ferravex_play/gameplay/projectile.rs
1//! Per-projectile target deduplication, piercing and ricochet budgets.
2//!
3//! This helper admits **caller-confirmed** contacts; it performs no collision
4//! query, target lookup, damage or feedback. A `u64` is an opaque host-provided
5//! generation identity (for ECS entities, use the existing `Entity::to_bits()`).
6//! The host must reject stale identities and supply a different ID for a new
7//! generation. Equal IDs are admitted at most once over this budget's lifetime;
8//! distinct generations can both be admitted. Even rejected game-owned damage
9//! consumes an admitted contact: there is no retry or refund here.
10//!
11//! Create a fresh budget with [`ProjectileBudget::new`] for a new projectile or
12//! run. There is no in-place reset. Copying a budget forks its admission history;
13//! it does not coordinate two authoritative projectiles or provide a rollback
14//! ledger. Operations allocate nothing and inspect at most `N <= 256` slots.
15//!
16//! This runnable recipe uses the existing first-party sphere sweep in the XY
17//! plane, then budget admission, then actual health acceptance and feedback.
18//! The second generation is immune, so its nominal admission emits no feedback.
19//! This is a single-contact recipe, not a multi-contact traversal/solver.
20//!
21//! ```rust
22//! use ferravex_math::Vec3;
23//! use ferravex_play::{
24//! attributes::Vitals,
25//! camera::{Blocker, Sweep},
26//! feedback::{FeedbackConfig, FeedbackController, FeedbackEvent},
27//! gameplay::projectile::{ProjectileBudget, TargetOutcome},
28//! };
29//!
30//! fn main() {
31//! let mut budget = ProjectileBudget::<3>::new(2, 1).unwrap();
32//! let mut health = Vitals::new(20., 0., 0., [0.; 8]).unwrap();
33//! let mut immune = Vitals::new(20., 0., 0., [1.; 8]).unwrap();
34//! let mut feedback = FeedbackController::<4>::new(FeedbackConfig::default(), 7).unwrap();
35//! let sweep = Sweep::new(Vec3::ZERO, Vec3::X * 10., 0.25).unwrap();
36//! let target = [Blocker::Sphere { center: Vec3::X * 5., radius: 0.75 }];
37//! let miss = [Blocker::Sphere { center: Vec3::Y * 5., radius: 0.75 }];
38//! assert!(sweep.probe(&miss[..], 0.).unwrap().hit_fraction.is_none());
39//! assert_eq!(budget.state().accepted_targets, 0);
40//! let mut cues = 0;
41//! // IDs are supplied by the host, not inferred from geometric witnesses.
42//! for (event_id, id) in [(1, 0x1_0000_0007), (2, 0x1_0000_0007), (3, 0x2_0000_0007)] {
43//! let contact = sweep.probe(&target[..], 0.).unwrap();
44//! if let Some(fraction) = contact.hit_fraction {
45//! assert!((fraction - 0.4).abs() < 1e-6);
46//! let report = budget.target_report(id);
47//! let mut accepted_damage = false;
48//! if report.accepted() {
49//! let vitals = if event_id == 3 { &mut immune } else { &mut health };
50//! let damage = vitals.damage(5., 0).unwrap();
51//! accepted_damage = damage.health > 0. || damage.shield > 0.;
52//! } else {
53//! assert_eq!(report.outcome, TargetOutcome::DuplicateTarget);
54//! }
55//! let event = FeedbackEvent::hit(sweep.start.lerp(sweep.end, fraction), 1.).unwrap();
56//! cues += usize::from(feedback.emit_if_accepted(event_id, accepted_damage, event)
57//! .unwrap().is_some());
58//! }
59//! }
60//! assert_eq!((health.health(), immune.health(), cues), (15., 20., 1));
61//! assert_eq!(budget.state().accepted_targets, 2);
62//! assert!(budget.has_hit(0x2_0000_0007));
63//! }
64//! ```
65use super::LoopError;
66use ferravex_math::Vec2;
67/// Legacy admission result. `Stop` normally includes an accepted final hit.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum HitResult {
70 Ignored,
71 Continue,
72 Stop,
73}
74/// Read-only state **after** a reported contact. See the module's runnable recipe.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct ProjectileState {
77 /// Additional target contacts that may continue travel. Zero still permits
78 /// one final target admission if alive; duplicates never spend this count.
79 pub remaining_pierces: u8,
80 /// Remaining reflections. Zero stops only on an approaching wall contact.
81 pub remaining_bounces: u8,
82 /// Number of lifetime target identities retained, including the final hit.
83 pub accepted_targets: usize,
84 pub alive: bool,
85}
86
87/// Budget policy only; acceptance does not prove game-owned damage or validity.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum TargetOutcome {
90 /// Checked before duplicate identity, including a repeat of the final hit.
91 Inactive,
92 DuplicateTarget,
93 /// Admitted and consumed one pierce; travel can continue.
94 Accepted,
95 /// Admitted the final target with no pierce remaining; projectile stopped.
96 PierceExhausted,
97 /// Not admitted; projectile stopped. Unreachable through the public API:
98 /// `pierces < N` guarantees room for every admitted target plus the final hit.
99 /// Retained only to describe the legacy defensive storage guard honestly.
100 StorageExhausted,
101}
102
103/// Target admission and resulting budgets. See the module's runnable recipe.
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub struct TargetReport {
106 pub outcome: TargetOutcome,
107 pub state: ProjectileState,
108}
109impl TargetReport {
110 /// Whether this contact was nominally admitted, including the final hit.
111 /// Apply actual target/damage rules before emitting feedback.
112 pub fn accepted(self) -> bool {
113 matches!(
114 self.outcome,
115 TargetOutcome::Accepted | TargetOutcome::PierceExhausted
116 )
117 }
118
119 /// Exact legacy mapping, including the defensive storage stop.
120 pub fn hit_result(self) -> HitResult {
121 match self.outcome {
122 TargetOutcome::Inactive | TargetOutcome::DuplicateTarget => HitResult::Ignored,
123 TargetOutcome::Accepted => HitResult::Continue,
124 TargetOutcome::PierceExhausted | TargetOutcome::StorageExhausted => HitResult::Stop,
125 }
126 }
127}
128
129/// Wall budget policy after vector validation, not a collision/normal query.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub enum WallOutcome {
132 Inactive,
133 /// Positive dot product; unchanged velocity and no bounce consumed.
134 Separating,
135 /// Exactly zero dot product (including stationary velocity and signed zero).
136 /// Unchanged velocity and no bounce consumed; no tolerance is applied.
137 Tangent,
138 /// Approaching with no bounces; stopped without reflection.
139 BounceExhausted,
140 /// One bounce consumed using the legacy perfect-reflection arithmetic.
141 Bounced,
142}
143
144/// Wall outcome and resulting budgets. `velocity` is exactly the legacy wall
145/// return value: `None` only for inactive or exhausted bounce. Separating and
146/// tangent outcomes are not accepted impacts and must not trigger hit feedback.
147/// A bounced report is nominal budget admission; the host owns applying the
148/// response and accepting any game-owned impact/damage before feedback.
149/// See [`ProjectileBudget::wall_report`] for a runnable example.
150#[derive(Clone, Copy, Debug, PartialEq)]
151pub struct WallReport {
152 pub outcome: WallOutcome,
153 pub velocity: Option<Vec2>,
154 pub state: ProjectileState,
155}
156
157/// Bounded, allocation-free policy for one projectile lifetime. See module recipe.
158#[derive(Clone, Copy, Debug)]
159pub struct ProjectileBudget<const N: usize> {
160 targets: [Option<u64>; N],
161 pierces: u8,
162 bounces: u8,
163 alive: bool,
164}
165impl<const N: usize> ProjectileBudget<N> {
166 /// Requires `1 <= N <= 256` and `pierces < N`. No change to authored defaults.
167 pub fn new(pierces: u8, bounces: u8) -> Result<Self, LoopError> {
168 if N == 0 || N > 256 || usize::from(pierces) >= N {
169 return Err(LoopError::Invalid);
170 }
171 Ok(Self {
172 targets: [None; N],
173 pierces,
174 bounces,
175 alive: true,
176 })
177 }
178 pub fn alive(&self) -> bool {
179 self.alive
180 }
181
182 /// Observe budgets without granting contacts or changing lifetime history.
183 pub fn state(&self) -> ProjectileState {
184 ProjectileState {
185 remaining_pierces: self.pierces,
186 remaining_bounces: self.bounces,
187 accepted_targets: self.targets.iter().filter(|slot| slot.is_some()).count(),
188 alive: self.alive,
189 }
190 }
191
192 /// Whether this exact host generation identity has been admitted, even if
193 /// now inactive. This does not establish that the target is still valid.
194 pub fn has_hit(&self, id: u64) -> bool {
195 self.targets.contains(&Some(id))
196 }
197
198 /// Supply a unique generational target ID after confirmed collision. Legacy
199 /// result; use [`Self::target_report`] to distinguish admission/stop reasons.
200 pub fn target(&mut self, id: u64) -> HitResult {
201 self.target_report(id).hit_result()
202 }
203
204 /// Admit one caller-confirmed target with the legacy ordering and budgets.
205 /// An inactive projectile wins over a duplicate ID. The final accepted hit
206 /// stops travel without decrementing the already-zero pierce count.
207 /// See the module recipe for geometry, damage and feedback composition.
208 pub fn target_report(&mut self, id: u64) -> TargetReport {
209 let outcome = if !self.alive {
210 TargetOutcome::Inactive
211 } else if self.has_hit(id) {
212 TargetOutcome::DuplicateTarget
213 } else if let Some(slot) = self.targets.iter_mut().find(|s| s.is_none()) {
214 *slot = Some(id);
215 if self.pierces == 0 {
216 self.alive = false;
217 TargetOutcome::PierceExhausted
218 } else {
219 self.pierces -= 1;
220 TargetOutcome::Accepted
221 }
222 } else {
223 self.alive = false;
224 TargetOutcome::StorageExhausted
225 };
226 TargetReport {
227 outcome,
228 state: self.state(),
229 }
230 }
231 /// Separating contacts spend no bounce; invalid vectors leave state intact.
232 pub fn wall(&mut self, velocity: Vec2, normal: Vec2) -> Result<Option<Vec2>, LoopError> {
233 Ok(self.wall_report(velocity, normal)?.velocity)
234 }
235
236 /// Validate vectors, then admit a caller-confirmed wall contact. Velocity
237 /// must be finite with each component in `[-1e6, 1e6]`; normal must be finite
238 /// and nonzero. Normalization uses the existing `Vec2::try_normalize`, even
239 /// for huge finite or subnormal normals. Invalid input returns
240 /// `LoopError::Invalid` before any mutation, **including when inactive**.
241 /// There is no epsilon, restitution change, post-reflection speed clamp or
242 /// extra numerical rejection. `dot >= 0` preserves the supplied velocity.
243 ///
244 /// ```rust
245 /// use ferravex_math::Vec2;
246 /// use ferravex_play::gameplay::{LoopError, projectile::{ProjectileBudget, WallOutcome}};
247 /// fn main() {
248 /// let mut budget = ProjectileBudget::<1>::new(0, 1).unwrap();
249 /// let tangent = budget.wall_report(Vec2::Y, Vec2::X).unwrap();
250 /// assert_eq!(tangent.outcome, WallOutcome::Tangent);
251 /// assert_eq!(tangent.state.remaining_bounces, 1);
252 /// let bounce = budget.wall_report(-Vec2::X, Vec2::X * f32::MAX).unwrap();
253 /// assert_eq!((bounce.outcome, bounce.velocity), (WallOutcome::Bounced, Some(Vec2::X)));
254 /// let stop = budget.wall_report(-Vec2::X, Vec2::X).unwrap();
255 /// assert_eq!(stop.outcome, WallOutcome::BounceExhausted);
256 /// assert!(!stop.state.alive);
257 /// assert_eq!(budget.wall_report(Vec2::X, Vec2::ZERO), Err(LoopError::Invalid));
258 /// }
259 /// ```
260 pub fn wall_report(&mut self, velocity: Vec2, normal: Vec2) -> Result<WallReport, LoopError> {
261 if !velocity.is_finite() || velocity.abs().max_element() > 1e6 || !normal.is_finite() {
262 return Err(LoopError::Invalid);
263 }
264 let normal = normal.try_normalize().ok_or(LoopError::Invalid)?;
265 if !self.alive {
266 return Ok(WallReport {
267 outcome: WallOutcome::Inactive,
268 velocity: None,
269 state: self.state(),
270 });
271 }
272 let dot = velocity.dot(normal);
273 let (outcome, velocity) = if dot >= 0. {
274 (
275 if dot == 0. {
276 WallOutcome::Tangent
277 } else {
278 WallOutcome::Separating
279 },
280 Some(velocity),
281 )
282 } else if self.bounces == 0 {
283 self.alive = false;
284 (WallOutcome::BounceExhausted, None)
285 } else {
286 self.bounces -= 1;
287 (WallOutcome::Bounced, Some(velocity - normal * (2. * dot)))
288 };
289 Ok(WallReport {
290 outcome,
291 velocity,
292 state: self.state(),
293 })
294 }
295}
296#[cfg(test)]
297mod tests {
298 use super::*;
299 #[test]
300 fn repeated_targets_and_separating_contacts_cannot_spend_twice() {
301 let mut p = ProjectileBudget::<3>::new(1, 1).unwrap();
302 assert_eq!(p.target(8), HitResult::Continue);
303 assert_eq!(p.target(8), HitResult::Ignored);
304 assert_eq!(p.wall(Vec2::X, Vec2::X).unwrap(), Some(Vec2::X));
305 assert!(p.wall(-Vec2::X, Vec2::ZERO).is_err());
306 assert_eq!(p.wall(-Vec2::X, Vec2::X).unwrap(), Some(Vec2::X));
307 assert_eq!(p.target(9), HitResult::Stop);
308 assert!(!p.alive());
309 assert_eq!(p.target(10), HitResult::Ignored);
310 let mut p = ProjectileBudget::<1>::new(0, 0).unwrap();
311 assert_eq!(p.wall(-Vec2::X, Vec2::X).unwrap(), None);
312 }
313}