Skip to main content

subtr_actor/stats/calculators/
one_timer.rs

1use super::*;
2
3const ONE_TIMER_MIN_BALL_SPEED: f32 = 1000.0;
4const ONE_TIMER_MIN_GOAL_ALIGNMENT_COSINE: f32 = 0.65;
5const GOAL_CENTER_Y: f32 = 5120.0;
6const GOAL_MOUTH_HEIGHT_Z: f32 = 642.775;
7const GOAL_MOUTH_TRAJECTORY_MARGIN: f32 = BALL_RADIUS_Z * 1.5;
8/// The post-touch trajectory must cross the opponent goal mouth within this many
9/// seconds for the touch to read as a one-timer (i.e. it must actually be on
10/// net, not merely aimed in the goal's general direction).
11const ONE_TIMER_MAX_TIME_TO_GOAL_SECONDS: f32 = 4.0;
12
13/// A first-touch shot taken off an incoming pass without trapping the ball.
14#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
15#[ts(export)]
16pub struct OneTimerEvent {
17    pub time: f32,
18    pub frame: usize,
19    #[ts(as = "crate::interop::ts_bindings::RemoteIdTs")]
20    pub player: PlayerId,
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub player_position: Option<[f32; 3]>,
23    #[ts(as = "crate::interop::ts_bindings::RemoteIdTs")]
24    pub passer: PlayerId,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub passer_position: Option<[f32; 3]>,
27    pub is_team_0: bool,
28    pub pass_start_time: f32,
29    pub pass_start_frame: usize,
30    pub pass_duration: f32,
31    pub pass_travel_distance: f32,
32    pub pass_advance_distance: f32,
33    pub ball_speed: f32,
34    pub goal_alignment: f32,
35}
36
37/// Detects one-timers from ball state and upstream pass detection.
38#[derive(Debug, Clone, Default)]
39pub struct OneTimerCalculator {
40    events: EventStream<OneTimerEvent>,
41    processed_pass_events: usize,
42}
43
44impl OneTimerCalculator {
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    pub fn events(&self) -> &[OneTimerEvent] {
50        self.events.all()
51    }
52
53    pub fn new_events(&self) -> &[OneTimerEvent] {
54        self.events.new_events()
55    }
56
57    fn one_timer_event_for_pass(pass: &PassEvent, ball: &BallFrameState) -> Option<OneTimerEvent> {
58        // A one-timer is a direct first-touch redirect of a pass. If the ball
59        // bounced off the backboard between the passer's touch and the
60        // receiver's finish, that is a double tap / backboard play, not a
61        // one-timer, so exclude the backboard pass kinds here.
62        if matches!(
63            pass.pass_kind,
64            PassKind::Backboard | PassKind::FiftyFiftyBackboard
65        ) {
66            return None;
67        }
68
69        let ball = ball.sample()?;
70        let ball_position = ball.position();
71        let ball_velocity = ball.velocity();
72        let ball_speed = ball_velocity.length();
73        if ball_speed < ONE_TIMER_MIN_BALL_SPEED {
74            return None;
75        }
76
77        let target_y = if pass.is_team_0 {
78            GOAL_CENTER_Y
79        } else {
80            -GOAL_CENTER_Y
81        };
82        let goal_direction = glam::Vec3::new(0.0, target_y, ball_position.z) - ball_position;
83        let goal_alignment = goal_direction
84            .normalize_or_zero()
85            .dot(ball_velocity.normalize_or_zero());
86        if goal_alignment < ONE_TIMER_MIN_GOAL_ALIGNMENT_COSINE {
87            return None;
88        }
89
90        if !Self::trajectory_on_net(ball_position, ball_velocity, target_y) {
91            return None;
92        }
93
94        Some(OneTimerEvent {
95            time: pass.time,
96            frame: pass.frame,
97            player: pass.receiver.clone(),
98            player_position: pass.receiver_position,
99            passer: pass.passer.clone(),
100            passer_position: pass.passer_position,
101            is_team_0: pass.is_team_0,
102            pass_start_time: pass.start_time,
103            pass_start_frame: pass.start_frame,
104            pass_duration: pass.duration,
105            pass_travel_distance: pass.ball_travel_distance,
106            pass_advance_distance: pass.ball_advance_distance,
107            ball_speed,
108            goal_alignment,
109        })
110    }
111
112    /// Whether the post-touch ball trajectory, extended in a straight line to
113    /// the opponent goal plane, actually crosses the goal mouth (the shot is "on
114    /// net"). This is stricter than the goal-direction alignment check, which
115    /// only requires the ball to be heading toward the goal's general area.
116    fn trajectory_on_net(position: glam::Vec3, velocity: glam::Vec3, target_goal_y: f32) -> bool {
117        if velocity.y.abs() <= f32::EPSILON {
118            return false;
119        }
120        let time_to_goal_line = (target_goal_y - position.y) / velocity.y;
121        if !time_to_goal_line.is_finite()
122            || !(0.0..=ONE_TIMER_MAX_TIME_TO_GOAL_SECONDS).contains(&time_to_goal_line)
123        {
124            return false;
125        }
126        let projected = position + velocity * time_to_goal_line;
127        projected.x.abs() <= BACK_WALL_GOAL_MOUTH_HALF_WIDTH_X + GOAL_MOUTH_TRAJECTORY_MARGIN
128            && projected.z >= BALL_RADIUS_Z - GOAL_MOUTH_TRAJECTORY_MARGIN
129            && projected.z <= GOAL_MOUTH_HEIGHT_Z + GOAL_MOUTH_TRAJECTORY_MARGIN
130    }
131
132    fn record_one_timer(&mut self, _frame: &FrameInfo, event: OneTimerEvent) {
133        self.events.push(event);
134    }
135
136    pub fn update(
137        &mut self,
138        frame: &FrameInfo,
139        ball: &BallFrameState,
140        pass_calculator: &PassCalculator,
141        live_play_state: &LivePlayState,
142    ) -> SubtrActorResult<()> {
143        self.events.begin_update();
144        if !live_play_state.is_live_play {
145            self.processed_pass_events = pass_calculator.events().len();
146            return Ok(());
147        }
148
149        for pass in &pass_calculator.events()[self.processed_pass_events..] {
150            if pass.frame != frame.frame_number {
151                continue;
152            }
153            if let Some(event) = Self::one_timer_event_for_pass(pass, ball) {
154                self.record_one_timer(frame, event);
155            }
156        }
157        self.processed_pass_events = pass_calculator.events().len();
158
159        Ok(())
160    }
161}
162
163#[cfg(test)]
164#[path = "one_timer_tests.rs"]
165mod tests;