ferravex_play/gameplay/
charge.rs

1//! Hold/release actions with minimum commitment, capped power and recovery time.
2//!
3//! [`ChargeAction::step`] retains the original held-only behavior.
4//! [`ChargeAction::step_edges`] also preserves aggregate press/release flags,
5//! including release/repress with a final held level. These flags contain no
6//! sub-tick timestamps; the helper uses a documented duration attribution, not
7//! reconstructed physical timing. Call once per actually executed simulation
8//! tick, sharing one consumed input snapshot across systems. Charge releases are
9//! requests: the game must accept costs/actions before emitting feedback.
10use super::{LoopError, seconds};
11
12/// The single release resolution from an edge-aware step.
13///
14/// See [`ChargeAction::step_edges`] for a compiling example and ordering rules.
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub enum ChargeRelease {
17    /// No charge was released (including an ignored tap during recovery).
18    None,
19    /// A charge ended below the minimum, including its `1e-7` second tolerance.
20    /// No recovery starts and no action is requested.
21    CanceledTooShort,
22    /// A release request with normalized, capped power in `0.0..=1.0`.
23    /// This does not mean the game accepted an action or spent resources.
24    Emitted(f32),
25}
26
27/// A release resolution and the charge state **after** the same snapshot.
28///
29/// An old release can coexist with a new charge when recovery is zero or the
30/// old charge was too short. See [`ChargeAction::step_edges`].
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub struct ChargeStep {
33    /// At most one resolution, even if the snapshot aggregates many transitions.
34    pub release: ChargeRelease,
35    /// Whether a charge remains active after this step.
36    pub charging: bool,
37    /// Current charge power, not the power of an old emitted release.
38    pub power: f32,
39    /// Remaining recovery in simulation seconds after this step.
40    pub cooldown_seconds: f32,
41}
42
43/// A fixed-size charge state machine; stepping does not allocate or queue input.
44#[derive(Clone, Copy, Debug)]
45pub struct ChargeAction {
46    minimum: f64,
47    maximum: f64,
48    recovery: f64,
49    held: f64,
50    cooldown: f64,
51    charging: bool,
52}
53impl ChargeAction {
54    pub fn new(minimum: f32, maximum: f32, recovery: f32) -> Result<Self, LoopError> {
55        let minimum = seconds(minimum)?;
56        let maximum = seconds(maximum)?;
57        let recovery = seconds(recovery)?;
58        if maximum == 0. || minimum > maximum {
59            return Err(LoopError::Invalid);
60        }
61        Ok(Self {
62            minimum,
63            maximum,
64            recovery,
65            held: 0.,
66            cooldown: 0.,
67            charging: false,
68        })
69    }
70    pub fn power(&self) -> f32 {
71        (self.held / self.maximum) as f32
72    }
73    pub fn charging(&self) -> bool {
74        self.charging
75    }
76    /// Remaining recovery in simulation seconds. Reading does not advance time.
77    /// See [`Self::step_edges`] for an example.
78    pub fn cooldown_seconds(&self) -> f32 {
79        self.cooldown as f32
80    }
81    /// Discards charge progress without a release, preserving recovery.
82    /// A subsequent held sample may start charging again when recovery ends.
83    pub fn cancel(&mut self) {
84        self.held = 0.;
85        self.charging = false;
86    }
87    /// Discards charge and recovery, preserving constructor configuration.
88    ///
89    /// Also clear pending host input on restart; this helper owns no input map.
90    ///
91    /// ```
92    /// use ferravex_play::gameplay::charge::ChargeAction;
93    /// let mut charge = ChargeAction::new(0.25, 1.0, 0.5)?;
94    /// charge.step(1.0, true)?;
95    /// charge.step(0.0, false)?;
96    /// charge.cancel(); // Does not bypass recovery.
97    /// assert_eq!(charge.cooldown_seconds(), 0.5);
98    /// charge.reset();
99    /// assert_eq!(charge.cooldown_seconds(), 0.0);
100    /// assert!(!charge.charging());
101    /// assert_eq!(charge.power(), 0.0);
102    /// # Ok::<(), ferravex_play::gameplay::LoopError>(())
103    /// ```
104    pub fn reset(&mut self) {
105        self.cancel();
106        self.cooldown = 0.;
107    }
108    /// A release emits at most one normalized power value. Continued holds cap
109    /// at full charge. Hosts commit resource costs only for returned releases.
110    pub fn step(&mut self, dt: f32, held: bool) -> Result<Option<f32>, LoopError> {
111        let dt = seconds(dt)?;
112        let active_dt = (dt - self.cooldown).max(0.);
113        self.cooldown = (self.cooldown - dt).max(0.);
114        if held && self.cooldown == 0. {
115            self.charging = true;
116            self.held = (self.held + active_dt).min(self.maximum);
117            return Ok(None);
118        }
119        if !held && self.charging {
120            let output = (self.held + 1e-7 >= self.minimum).then(|| self.power());
121            self.cancel();
122            if output.is_some() {
123                self.cooldown = self.recovery;
124            }
125            return Ok(output);
126        }
127        Ok(None)
128    }
129
130    /// Steps one aggregate snapshot, retaining held, pressed and released
131    /// independently. All eight flag combinations are accepted. Invalid `dt`
132    /// (nonfinite or outside `0.0..=3600.0`) returns [`LoopError::Invalid`]
133    /// **before any mutation**.
134    ///
135    /// Deterministic processing order and duration attribution:
136    ///
137    /// 1. Age **preexisting** recovery by `dt`. Only its nonnegative remainder
138    ///    `max(dt - old_cooldown, 0)` is available for held charging.
139    /// 2. If already charging and `released || !held`, resolve that old charge
140    ///    using only previously accumulated duration, with no current `dt`.
141    ///    Meeting `minimum` within the legacy `1e-7` second tolerance emits its
142    ///    capped power and starts a **fresh**, unaged recovery. Otherwise report
143    ///    [`ChargeRelease::CanceledTooShort`] without starting recovery.
144    /// 3. If finally held and recovery is zero, start/continue charging with the
145    ///    available duration. Thus release/repress (`held && pressed && released`)
146    ///    may return an old release plus a new charge. Positive fresh recovery
147    ///    blocks that new charge for this entire snapshot, even for large `dt`.
148    /// 4. If finally unheld, `pressed` and no old charge was resolved, a ready
149    ///    action resolves a **zero-duration tap**. This includes both edges with
150    ///    `held == false`, and also pressed-only with final unheld. A positive
151    ///    minimum exceeding the tolerance cancels it; minimum zero emits zero
152    ///    power. No second tap is resolved after closing an old charge.
153    ///
154    /// A held level can start a charge without `pressed` (including when recovery
155    /// expires exactly at the end of `dt`, with zero progress). `pressed` alone
156    /// never resets an existing held charge. `released` with no existing charge
157    /// is ignored; a final held level can still start one. Zero `dt` still
158    /// processes edges and minimum/recovery rules. Preexisting recovery expiring
159    /// within `dt` admits a final hold with only the remainder, or a zero-duration
160    /// tap with no elapsed charge credit. Fresh recovery is never aged here.
161    ///
162    /// With `pressed == released == false`, emitted values and final state match
163    /// [`Self::step`] exactly. Extra transitions aggregated into the same flags
164    /// cannot be counted or timed. The caller must consume edges only once on an
165    /// actual tick; replaying the same edge snapshot is a new request.
166    /// [`Self::cancel`] drops progress but keeps recovery; [`Self::reset`] clears
167    /// both. Neither clears pending host input.
168    ///
169    /// ```
170    /// use ferravex_play::gameplay::charge::{ChargeAction, ChargeRelease};
171    /// let mut charge = ChargeAction::new(0.25, 1.0, 0.0)?;
172    /// charge.step_edges(0.75, true, true, false)?;
173    /// let report = charge.step_edges(0.25, true, true, true)?;
174    /// assert_eq!(report.release, ChargeRelease::Emitted(0.75));
175    /// assert!(report.charging); // A new charge, not the old released charge.
176    /// assert_eq!(report.power, 0.25);
177    /// assert_eq!(report.cooldown_seconds, charge.cooldown_seconds());
178    /// let report = charge.step_edges(0.0, false, false, true)?;
179    /// assert_eq!(report.release, ChargeRelease::Emitted(0.25));
180    /// assert!(!report.charging);
181    /// assert_eq!(report.power, 0.0);
182    /// # Ok::<(), ferravex_play::gameplay::LoopError>(())
183    /// ```
184    pub fn step_edges(
185        &mut self,
186        dt: f32,
187        held: bool,
188        pressed: bool,
189        released: bool,
190    ) -> Result<ChargeStep, LoopError> {
191        let dt = seconds(dt)?;
192        let active_dt = (dt - self.cooldown).max(0.);
193        self.cooldown = (self.cooldown - dt).max(0.);
194        let close_old = self.charging && (released || !held);
195        let tap = !held && pressed && !close_old && self.cooldown == 0.;
196        let release = if close_old || tap {
197            let output = (self.held + 1e-7 >= self.minimum).then(|| self.power());
198            self.cancel();
199            if let Some(power) = output {
200                self.cooldown = self.recovery;
201                ChargeRelease::Emitted(power)
202            } else {
203                ChargeRelease::CanceledTooShort
204            }
205        } else {
206            ChargeRelease::None
207        };
208        if held && self.cooldown == 0. {
209            self.charging = true;
210            self.held = (self.held + active_dt).min(self.maximum);
211        }
212        Ok(ChargeStep {
213            release,
214            charging: self.charging,
215            power: self.power(),
216            cooldown_seconds: self.cooldown_seconds(),
217        })
218    }
219}
220#[cfg(test)]
221mod tests {
222    use super::*;
223    #[test]
224    fn short_taps_cancel_full_charge_caps_and_release_is_single_use() {
225        let mut c = ChargeAction::new(0.2, 1., 0.5).unwrap();
226        c.step(0.1, true).unwrap();
227        assert_eq!(c.step(0., false).unwrap(), None);
228        c.step(2., true).unwrap();
229        assert_eq!(c.power(), 1.);
230        assert_eq!(c.step(0., false).unwrap(), Some(1.));
231        assert_eq!(c.step(0., false).unwrap(), None);
232        c.step(0.25, true).unwrap();
233        assert!(!c.charging());
234        c.step(0.5, true).unwrap();
235        assert!((c.power() - 0.25).abs() < 1e-6);
236        assert!(c.step(f32::NAN, false).is_err());
237        assert!(c.charging());
238        c.cancel();
239        assert_eq!(c.power(), 0.);
240    }
241}