Skip to main content

subtr_actor/processor/
mod.rs

1use crate::*;
2use boxcars;
3use std::collections::HashMap;
4
5pub mod actor_state;
6mod boost_pad_resolution;
7mod replay_keys;
8pub mod view;
9pub use actor_state::*;
10pub(crate) use boost_pad_resolution::*;
11pub(crate) use replay_keys::*;
12pub use view::*;
13
14pub(crate) fn attribute_type_name(attribute: &boxcars::Attribute) -> &'static str {
15    match attribute {
16        boxcars::Attribute::Boolean(_) => "Boolean",
17        boxcars::Attribute::Byte(_) => "Byte",
18        boxcars::Attribute::AppliedDamage(_) => "AppliedDamage",
19        boxcars::Attribute::DamageState(_) => "DamageState",
20        boxcars::Attribute::CamSettings(_) => "CamSettings",
21        boxcars::Attribute::ClubColors(_) => "ClubColors",
22        boxcars::Attribute::Demolish(_) => "Demolish",
23        boxcars::Attribute::DemolishExtended(_) => "DemolishExtended",
24        boxcars::Attribute::DemolishFx(_) => "DemolishFx",
25        boxcars::Attribute::Enum(_) => "Enum",
26        boxcars::Attribute::Explosion(_) => "Explosion",
27        boxcars::Attribute::ExtendedExplosion(_) => "ExtendedExplosion",
28        boxcars::Attribute::FlaggedByte(_, _) => "FlaggedByte",
29        boxcars::Attribute::ActiveActor(_) => "ActiveActor",
30        boxcars::Attribute::Float(_) => "Float",
31        boxcars::Attribute::GameMode(_, _) => "GameMode",
32        boxcars::Attribute::Int(_) => "Int",
33        boxcars::Attribute::Int64(_) => "Int64",
34        boxcars::Attribute::Loadout(_) => "Loadout",
35        boxcars::Attribute::TeamLoadout(_) => "TeamLoadout",
36        boxcars::Attribute::Location(_) => "Location",
37        boxcars::Attribute::MusicStinger(_) => "MusicStinger",
38        boxcars::Attribute::PlayerHistoryKey(_) => "PlayerHistoryKey",
39        boxcars::Attribute::Pickup(_) => "Pickup",
40        boxcars::Attribute::PickupNew(_) => "PickupNew",
41        boxcars::Attribute::QWord(_) => "QWord",
42        boxcars::Attribute::Welded(_) => "Welded",
43        boxcars::Attribute::Title(_, _, _, _, _, _, _, _) => "Title",
44        boxcars::Attribute::TeamPaint(_) => "TeamPaint",
45        boxcars::Attribute::RigidBody(_) => "RigidBody",
46        boxcars::Attribute::String(_) => "String",
47        boxcars::Attribute::UniqueId(_) => "UniqueId",
48        boxcars::Attribute::Reservation(_) => "Reservation",
49        boxcars::Attribute::PartyLeader(_) => "PartyLeader",
50        boxcars::Attribute::PrivateMatch(_) => "PrivateMatch",
51        boxcars::Attribute::LoadoutOnline(_) => "LoadoutOnline",
52        boxcars::Attribute::LoadoutsOnline(_) => "LoadoutsOnline",
53        boxcars::Attribute::StatEvent(_) => "StatEvent",
54        boxcars::Attribute::Rotation(_) => "Rotation",
55        boxcars::Attribute::RepStatTitle(_) => "RepStatTitle",
56        boxcars::Attribute::PickupInfo(_) => "PickupInfo",
57        boxcars::Attribute::Impulse(_) => "Impulse",
58        boxcars::Attribute::ReplicatedBoost(_) => "ReplicatedBoost",
59        boxcars::Attribute::LogoData(_) => "LogoData",
60    }
61}
62
63/// Attempts to match an attribute value with the given type.
64///
65/// # Arguments
66///
67/// * `$value` - An expression that yields the attribute value.
68/// * `$type` - The expected enum path.
69///
70/// If the attribute matches the specified type, it is returned wrapped in an
71/// [`Ok`] variant of a [`Result`]. If the attribute doesn't match, it results in an
72/// [`Err`] variant with a [`SubtrActorError`], specifying the expected type and
73/// the actual type.
74#[macro_export]
75macro_rules! attribute_match {
76    ($value:expr, $type:path $(,)?) => {{
77        let attribute = $value;
78        if let $type(value) = attribute {
79            Ok(value)
80        } else {
81            SubtrActorError::new_result(SubtrActorErrorVariant::UnexpectedAttributeType {
82                expected_type: stringify!($type),
83                actual_type: attribute_type_name(&attribute),
84            })
85        }
86    }};
87}
88
89/// Obtains an attribute from a map and ensures it matches the expected type.
90///
91/// # Arguments
92///
93/// * `$self` - The struct or instance on which the function is invoked.
94/// * `$map` - The data map.
95/// * `$prop` - The attribute key.
96/// * `$type` - The expected enum path.
97#[macro_export]
98macro_rules! get_attribute_errors_expected {
99    ($self:ident, $map:expr, $prop:expr, $type:path) => {
100        $self
101            .get_attribute($map, $prop)
102            .and_then(|found| attribute_match!(found, $type))
103    };
104}
105
106/// Obtains an attribute and its updated status from a map and ensures the
107/// attribute matches the expected type.
108///
109/// # Arguments
110///
111/// * `$self` - The struct or instance on which the function is invoked.
112/// * `$map` - The data map.
113/// * `$prop` - The attribute key.
114/// * `$type` - The expected enum path.
115///
116/// It returns a [`Result`] with a tuple of the matched attribute and its updated
117/// status, after invoking [`attribute_match!`] on the found attribute.
118macro_rules! get_attribute_and_updated {
119    ($self:ident, $map:expr, $prop:expr, $type:path) => {
120        $self
121            .get_attribute_and_updated($map, $prop)
122            .and_then(|(found, updated)| attribute_match!(found, $type).map(|v| (v, updated)))
123    };
124}
125
126/// Obtains an actor attribute and ensures it matches the expected type.
127///
128/// # Arguments
129///
130/// * `$self` - The struct or instance on which the function is invoked.
131/// * `$actor` - The actor identifier.
132/// * `$prop` - The attribute key.
133/// * `$type` - The expected enum path.
134macro_rules! get_actor_attribute_matching {
135    ($self:ident, $actor:expr, $prop:expr, $type:path) => {
136        $self
137            .get_actor_attribute($actor, $prop)
138            .and_then(|found| attribute_match!(found, $type))
139    };
140}
141
142/// Obtains a derived attribute from a map and ensures it matches the expected
143/// type.
144///
145/// # Arguments
146///
147/// * `$map` - The data map.
148/// * `$key` - The attribute key.
149/// * `$type` - The expected enum path.
150macro_rules! get_derived_attribute {
151    ($map:expr, $key:expr, $type:path) => {
152        $map.get($key)
153            .ok_or_else(|| {
154                SubtrActorError::new(SubtrActorErrorVariant::DerivedKeyValueNotFound {
155                    name: $key.to_string(),
156                })
157            })
158            .and_then(|found| attribute_match!(&found.0, $type))
159    };
160}
161
162fn get_actor_id_from_active_actor<T>(
163    _: T,
164    active_actor: &boxcars::ActiveActor,
165) -> boxcars::ActorId {
166    active_actor.actor
167}
168
169fn use_update_actor<T>(id: boxcars::ActorId, _: T) -> boxcars::ActorId {
170    id
171}
172
173#[derive(Clone, Copy, Default)]
174struct CachedObjectIds {
175    player_type: Option<boxcars::ObjectId>,
176    car_type: Option<boxcars::ObjectId>,
177    boost_type: Option<boxcars::ObjectId>,
178    dodge_type: Option<boxcars::ObjectId>,
179    jump_type: Option<boxcars::ObjectId>,
180    double_jump_type: Option<boxcars::ObjectId>,
181    unique_id: Option<boxcars::ObjectId>,
182    team: Option<boxcars::ObjectId>,
183    bot: Option<boxcars::ObjectId>,
184    client_loadouts: Option<boxcars::ObjectId>,
185    player_replication: Option<boxcars::ObjectId>,
186    vehicle: Option<boxcars::ObjectId>,
187    boost_replicated: Option<boxcars::ObjectId>,
188    boost_amount: Option<boxcars::ObjectId>,
189    component_active: Option<boxcars::ObjectId>,
190    seconds_remaining: Option<boxcars::ObjectId>,
191    replicated_state_name: Option<boxcars::ObjectId>,
192    replicated_game_state_time_remaining: Option<boxcars::ObjectId>,
193    match_type_class: Option<boxcars::ObjectId>,
194    ball_has_been_hit: Option<boxcars::ObjectId>,
195    replicated_game_playlist: Option<boxcars::ObjectId>,
196    ball_hit_team_num: Option<boxcars::ObjectId>,
197    dodges_refreshed_counter: Option<boxcars::ObjectId>,
198}
199
200impl CachedObjectIds {
201    fn from_name_map(name_to_object_id: &HashMap<String, boxcars::ObjectId>) -> Self {
202        let cached = |name| name_to_object_id.get(name).copied();
203        Self {
204            player_type: cached(PLAYER_TYPE),
205            car_type: cached(CAR_TYPE),
206            boost_type: cached(BOOST_TYPE),
207            dodge_type: cached(DODGE_TYPE),
208            jump_type: cached(JUMP_TYPE),
209            double_jump_type: cached(DOUBLE_JUMP_TYPE),
210            unique_id: cached(UNIQUE_ID_KEY),
211            team: cached(TEAM_KEY),
212            bot: cached(BOT_KEY),
213            client_loadouts: cached(CLIENT_LOADOUTS_KEY),
214            player_replication: cached(PLAYER_REPLICATION_KEY),
215            vehicle: cached(VEHICLE_KEY),
216            boost_replicated: cached(BOOST_REPLICATED_KEY),
217            boost_amount: cached(BOOST_AMOUNT_KEY),
218            component_active: cached(COMPONENT_ACTIVE_KEY),
219            seconds_remaining: cached(SECONDS_REMAINING_KEY),
220            replicated_state_name: cached(REPLICATED_STATE_NAME_KEY),
221            replicated_game_state_time_remaining: cached(REPLICATED_GAME_STATE_TIME_REMAINING_KEY),
222            match_type_class: cached(MATCH_TYPE_CLASS_KEY),
223            ball_has_been_hit: cached(BALL_HAS_BEEN_HIT_KEY),
224            replicated_game_playlist: cached(REPLICATED_GAME_PLAYLIST_KEY),
225            ball_hit_team_num: cached(BALL_HIT_TEAM_NUM_KEY),
226            dodges_refreshed_counter: cached(DODGES_REFRESHED_COUNTER_KEY),
227        }
228    }
229}
230
231mod bootstrap;
232mod debug;
233mod player_queries;
234mod queries;
235mod updaters;
236
237/// The [`ReplayProcessor`] struct is a pivotal component in `subtr-actor`'s
238/// replay parsing pipeline. It is designed to process and traverse an actor
239/// graph of a Rocket League replay, and expose methods for collectors to gather
240/// specific data points as it progresses through the replay.
241///
242/// The processor pushes frames from a replay through an [`ActorStateModeler`],
243/// which models the state all actors in the replay at a given point in time.
244/// The [`ReplayProcessor`] also maintains various mappings to allow efficient
245/// lookup and traversal of the actor graph, thus assisting [`Collector`]
246/// instances in their data accumulation tasks.
247///
248/// The primary method of this struct is [`process`](ReplayProcessor::process),
249/// which takes a collector and processes the replay. As it traverses the
250/// replay, it calls the [`Collector::process_frame`] method of the passed
251/// collector, passing the current frame along with its contextual data. This
252/// allows the collector to extract specific data from each frame as needed.
253///
254/// The [`ReplayProcessor`] also provides a number of helper methods for
255/// navigating the actor graph and extracting information, such as
256/// [`get_ball_rigid_body`](ReplayProcessor::get_ball_rigid_body),
257/// [`get_player_name`](ReplayProcessor::get_player_name),
258/// [`get_player_team_key`](ReplayProcessor::get_player_team_key),
259/// [`get_player_is_team_0`](ReplayProcessor::get_player_is_team_0), and
260/// [`get_player_rigid_body`](ReplayProcessor::get_player_rigid_body).
261///
262/// # See Also
263///
264/// * [`ActorStateModeler`]: A struct used to model the states of multiple
265///   actors at a given point in time.
266/// * [`Collector`]: A trait implemented by objects that wish to collect data as
267///   the `ReplayProcessor` processes a replay.
268pub struct ReplayProcessor<'a> {
269    /// The replay currently being traversed.
270    pub replay: &'a boxcars::Replay,
271    spatial_normalization_factor: f32,
272    rigid_body_velocity_normalization_factor: f32,
273    uses_legacy_rigid_body_rotation: bool,
274    cached_object_ids: CachedObjectIds,
275    is_boost_pad_object: Vec<bool>,
276    /// Modeled actor state for the current replay frame.
277    pub actor_state: ActorStateModeler,
278    /// Mapping from object ids to their replay object names.
279    pub object_id_to_name: HashMap<boxcars::ObjectId, String>,
280    /// Reverse lookup from replay object names to object ids.
281    pub name_to_object_id: HashMap<String, boxcars::ObjectId>,
282    /// Cached actor id for the replay ball when known.
283    pub ball_actor_id: Option<boxcars::ActorId>,
284    /// Best known game-type metadata for this replay.
285    pub game_type_details: ReplayGameTypeDetails,
286    /// Stable ordering of team 0 players.
287    pub team_zero: Vec<PlayerId>,
288    /// Stable ordering of team 1 players.
289    pub team_one: Vec<PlayerId>,
290    /// Mapping from player ids to their player-controller actor ids.
291    pub player_to_actor_id: HashMap<PlayerId, boxcars::ActorId>,
292    /// Mapping from player-controller actors to their replicated loadouts.
293    pub player_actor_to_loadout: HashMap<boxcars::ActorId, boxcars::TeamLoadout>,
294    /// Mapping from player-controller actors to car actors.
295    pub player_to_car: HashMap<boxcars::ActorId, boxcars::ActorId>,
296    /// Mapping from player-controller actors to team actors.
297    pub player_to_team: HashMap<boxcars::ActorId, boxcars::ActorId>,
298    /// Reverse mapping from car actors to player-controller actors.
299    pub car_to_player: HashMap<boxcars::ActorId, boxcars::ActorId>,
300    /// Mapping from car actors to boost component actors.
301    pub car_to_boost: HashMap<boxcars::ActorId, boxcars::ActorId>,
302    /// Mapping from car actors to jump component actors.
303    pub car_to_jump: HashMap<boxcars::ActorId, boxcars::ActorId>,
304    /// Mapping from car actors to double-jump component actors.
305    pub car_to_double_jump: HashMap<boxcars::ActorId, boxcars::ActorId>,
306    /// Mapping from car actors to dodge component actors.
307    pub car_to_dodge: HashMap<boxcars::ActorId, boxcars::ActorId>,
308    /// All boost-pad events observed so far in the replay.
309    pub boost_pad_events: Vec<BoostPadEvent>,
310    current_frame_boost_pad_events: Vec<BoostPadEvent>,
311    boost_pad_pickup_sequence_times: HashMap<(String, u8), f32>,
312    boost_pad_resolution: BoostPadResolutionState,
313    /// All touch events observed so far in the replay.
314    pub touch_events: Vec<TouchEvent>,
315    current_frame_touch_events: Vec<TouchEvent>,
316    /// All dodge-refresh events observed so far in the replay.
317    pub dodge_refreshed_events: Vec<DodgeRefreshedEvent>,
318    current_frame_dodge_refreshed_events: Vec<DodgeRefreshedEvent>,
319    dodge_refreshed_counters: HashMap<PlayerId, i32>,
320    /// All goal events observed so far in the replay.
321    pub goal_events: Vec<GoalEvent>,
322    current_frame_goal_events: Vec<GoalEvent>,
323    /// All shot/save/assist-style stat events observed so far in the replay.
324    pub player_stat_events: Vec<PlayerStatEvent>,
325    current_frame_player_stat_events: Vec<PlayerStatEvent>,
326    player_stat_counters: HashMap<(PlayerId, PlayerStatEventKind), i32>,
327    /// All demolishes observed so far in the replay.
328    pub demolishes: Vec<DemolishInfo>,
329    known_demolishes: Vec<(DemolishAttribute, usize)>,
330    demolish_format: Option<DemolishFormat>,
331    kickoff_phase_active_last_frame: bool,
332}
333
334impl<'a> ReplayProcessor<'a> {
335    const LEGACY_RIGID_BODY_NET_VERSION_CUTOFF: i32 = 5;
336    const LEGACY_RIGID_BODY_ROTATION_NET_VERSION_CUTOFF: i32 = 7;
337    const LEGACY_RIGID_BODY_LOCATION_FACTOR: f32 = 100.0;
338    const LEGACY_RIGID_BODY_VELOCITY_FACTOR: f32 = 10.0;
339
340    fn uses_legacy_rigid_body_vector_scale(net_version: Option<i32>) -> bool {
341        net_version.is_none_or(|version| version < Self::LEGACY_RIGID_BODY_NET_VERSION_CUTOFF)
342    }
343
344    fn uses_legacy_rigid_body_rotation_for_net_version(net_version: Option<i32>) -> bool {
345        net_version
346            .is_none_or(|version| version < Self::LEGACY_RIGID_BODY_ROTATION_NET_VERSION_CUTOFF)
347    }
348
349    fn rigid_body_location_normalization_factor_for_net_version(net_version: Option<i32>) -> f32 {
350        if Self::uses_legacy_rigid_body_vector_scale(net_version) {
351            Self::LEGACY_RIGID_BODY_LOCATION_FACTOR
352        } else {
353            1.0
354        }
355    }
356
357    fn rigid_body_velocity_normalization_factor_for_net_version(net_version: Option<i32>) -> f32 {
358        if Self::uses_legacy_rigid_body_vector_scale(net_version) {
359            Self::LEGACY_RIGID_BODY_VELOCITY_FACTOR
360        } else {
361            1.0
362        }
363    }
364
365    /// Constructs a new [`ReplayProcessor`] instance with the provided replay.
366    ///
367    /// # Arguments
368    ///
369    /// * `replay` - A reference to the [`boxcars::Replay`] to be processed.
370    ///
371    /// # Returns
372    ///
373    /// Returns a [`SubtrActorResult`] of [`ReplayProcessor`]. In the process of
374    /// initialization, the [`ReplayProcessor`]: - Maps each object id in the
375    /// replay to its corresponding name. - Initializes empty state and
376    /// attribute maps. - Sets the player order from either replay headers or
377    /// frames, if available.
378    pub fn new(replay: &'a boxcars::Replay) -> SubtrActorResult<Self> {
379        let mut object_id_to_name = HashMap::new();
380        let mut name_to_object_id = HashMap::new();
381        let spatial_normalization_factor =
382            Self::rigid_body_location_normalization_factor_for_net_version(replay.net_version);
383        let rigid_body_velocity_normalization_factor =
384            Self::rigid_body_velocity_normalization_factor_for_net_version(replay.net_version);
385        let uses_legacy_rigid_body_rotation =
386            Self::uses_legacy_rigid_body_rotation_for_net_version(replay.net_version);
387        for (id, name) in replay.objects.iter().enumerate() {
388            let object_id = boxcars::ObjectId(id as i32);
389            object_id_to_name.insert(object_id, name.clone());
390            name_to_object_id.insert(name.clone(), object_id);
391        }
392        let cached_object_ids = CachedObjectIds::from_name_map(&name_to_object_id);
393        let game_type_details = ReplayGameTypeDetails::from_headers(&replay.properties);
394        let mut processor = Self {
395            actor_state: ActorStateModeler::new(),
396            replay,
397            spatial_normalization_factor,
398            rigid_body_velocity_normalization_factor,
399            uses_legacy_rigid_body_rotation,
400            cached_object_ids,
401            is_boost_pad_object: replay
402                .objects
403                .iter()
404                .map(|name| name.contains("VehiclePickup_Boost_TA"))
405                .collect(),
406            object_id_to_name,
407            name_to_object_id,
408            game_type_details,
409            team_zero: Vec::new(),
410            team_one: Vec::new(),
411            ball_actor_id: None,
412            player_to_car: HashMap::new(),
413            player_to_team: HashMap::new(),
414            player_to_actor_id: HashMap::new(),
415            player_actor_to_loadout: HashMap::new(),
416            car_to_player: HashMap::new(),
417            car_to_boost: HashMap::new(),
418            car_to_jump: HashMap::new(),
419            car_to_double_jump: HashMap::new(),
420            car_to_dodge: HashMap::new(),
421            boost_pad_events: Vec::new(),
422            current_frame_boost_pad_events: Vec::new(),
423            boost_pad_pickup_sequence_times: HashMap::new(),
424            boost_pad_resolution: BoostPadResolutionState::default(),
425            touch_events: Vec::new(),
426            current_frame_touch_events: Vec::new(),
427            dodge_refreshed_events: Vec::new(),
428            current_frame_dodge_refreshed_events: Vec::new(),
429            dodge_refreshed_counters: HashMap::new(),
430            goal_events: Vec::new(),
431            current_frame_goal_events: Vec::new(),
432            player_stat_events: Vec::new(),
433            current_frame_player_stat_events: Vec::new(),
434            player_stat_counters: HashMap::new(),
435            demolishes: Vec::new(),
436            known_demolishes: Vec::new(),
437            demolish_format: None,
438            kickoff_phase_active_last_frame: false,
439        };
440        processor
441            .set_player_order_from_headers()
442            .or_else(|_| processor.set_player_order_from_frames())?;
443
444        Ok(processor)
445    }
446
447    /// Returns the scale factor applied when normalizing replay spatial values.
448    pub fn spatial_normalization_factor(&self) -> f32 {
449        self.spatial_normalization_factor
450    }
451
452    /// Returns the scale factor applied when normalizing rigid-body linear and angular velocity.
453    pub fn rigid_body_velocity_normalization_factor(&self) -> f32 {
454        self.rigid_body_velocity_normalization_factor
455    }
456
457    fn sync_player_order_from_known_mappings(&mut self) {
458        let player_ids: Vec<_> = self.player_to_actor_id.keys().cloned().collect();
459        for player_id in player_ids {
460            let already_ordered =
461                self.team_zero.contains(&player_id) || self.team_one.contains(&player_id);
462            if already_ordered {
463                continue;
464            }
465
466            let Ok(is_team_0) = self.get_player_is_team_0(&player_id) else {
467                continue;
468            };
469            if is_team_0 {
470                self.team_zero.push(player_id);
471            } else {
472                self.team_one.push(player_id);
473            }
474        }
475    }
476
477    pub(crate) fn insert_player_actor_id(
478        &mut self,
479        player_id: PlayerId,
480        actor_id: boxcars::ActorId,
481    ) {
482        let stale_player_ids = self
483            .player_to_actor_id
484            .iter()
485            .filter(|(existing_player_id, existing_actor_id)| {
486                **existing_actor_id == actor_id && **existing_player_id != player_id
487            })
488            .map(|(existing_player_id, _existing_actor_id)| existing_player_id.clone())
489            .collect::<Vec<_>>();
490
491        for stale_player_id in stale_player_ids {
492            self.player_to_actor_id.remove(&stale_player_id);
493            self.team_zero
494                .retain(|ordered_player_id| ordered_player_id != &stale_player_id);
495            self.team_one
496                .retain(|ordered_player_id| ordered_player_id != &stale_player_id);
497        }
498
499        self.player_to_actor_id.insert(player_id, actor_id);
500    }
501
502    fn normalize_vector_by_factor(
503        &self,
504        vector: boxcars::Vector3f,
505        factor: f32,
506    ) -> boxcars::Vector3f {
507        if (factor - 1.0).abs() < f32::EPSILON {
508            vector
509        } else {
510            boxcars::Vector3f {
511                x: vector.x * factor,
512                y: vector.y * factor,
513                z: vector.z * factor,
514            }
515        }
516    }
517
518    fn normalize_vector(&self, vector: boxcars::Vector3f) -> boxcars::Vector3f {
519        self.normalize_vector_by_factor(vector, self.spatial_normalization_factor)
520    }
521
522    fn normalize_rigid_body_velocity(&self, vector: boxcars::Vector3f) -> boxcars::Vector3f {
523        self.normalize_vector_by_factor(vector, self.rigid_body_velocity_normalization_factor)
524    }
525
526    fn normalize_optional_rigid_body_velocity(
527        &self,
528        vector: Option<boxcars::Vector3f>,
529    ) -> Option<boxcars::Vector3f> {
530        vector.map(|value| self.normalize_rigid_body_velocity(value))
531    }
532
533    fn normalize_rigid_body_rotation(&self, rotation: boxcars::Quaternion) -> boxcars::Quaternion {
534        if !self.uses_legacy_rigid_body_rotation {
535            return rotation;
536        }
537
538        // Older replays store rigid-body rotation as fixed compressed
539        // (pitch, yaw, roll), not as the modern quaternion shape. The decoded
540        // legacy roll component is opposite the modern angular-velocity sign.
541        let normalized = glam::Quat::from_euler(
542            glam::EulerRot::ZYX,
543            rotation.y * std::f32::consts::PI,
544            rotation.x * std::f32::consts::PI,
545            -rotation.z * std::f32::consts::PI,
546        );
547        boxcars::Quaternion {
548            x: normalized.x,
549            y: normalized.y,
550            z: normalized.z,
551            w: normalized.w,
552        }
553    }
554
555    fn normalize_rigid_body(&self, rigid_body: &boxcars::RigidBody) -> boxcars::RigidBody {
556        if (self.spatial_normalization_factor - 1.0).abs() < f32::EPSILON
557            && (self.rigid_body_velocity_normalization_factor - 1.0).abs() < f32::EPSILON
558            && !self.uses_legacy_rigid_body_rotation
559        {
560            *rigid_body
561        } else {
562            boxcars::RigidBody {
563                sleeping: rigid_body.sleeping,
564                location: self.normalize_vector(rigid_body.location),
565                rotation: self.normalize_rigid_body_rotation(rigid_body.rotation),
566                linear_velocity: self
567                    .normalize_optional_rigid_body_velocity(rigid_body.linear_velocity),
568                angular_velocity: self
569                    .normalize_optional_rigid_body_velocity(rigid_body.angular_velocity),
570            }
571        }
572    }
573
574    fn required_cached_object_id(
575        &self,
576        object_id: Option<boxcars::ObjectId>,
577        name: &'static str,
578    ) -> SubtrActorResult<boxcars::ObjectId> {
579        object_id
580            .ok_or_else(|| SubtrActorError::new(SubtrActorErrorVariant::ObjectIdNotFound { name }))
581    }
582
583    /// [`Self::process`] takes a [`Collector`] as an argument and iterates over
584    /// each frame in the replay, updating the internal state of the processor
585    /// and other relevant mappings based on the current frame.
586    ///
587    /// After each a frame is processed, [`Collector::process_frame`] of the
588    /// collector is called. The [`TimeAdvance`] return value of this call into
589    /// [`Collector::process_frame`] is used to determine what happens next: in
590    /// the case of [`TimeAdvance::Time`], the notion of current time is
591    /// advanced by the provided amount, and only the timestamp of the frame is
592    /// exceeded, do we process the next frame. This mechanism allows fine
593    /// grained control of frame processing, and the frequency of invocations of
594    /// the [`Collector`]. If time is advanced by less than the delay between
595    /// frames, the collector will be called more than once per frame, and can
596    /// use functions like [`Self::get_interpolated_player_rigid_body`] to get
597    /// values that are interpolated between frames. Its also possible to skip
598    /// over frames by providing time advance values that are sufficiently
599    /// large.
600    ///
601    /// At the end of processing, it checks to make sure that no unknown players
602    /// were encountered during the replay. If any unknown players are found, an
603    /// error is returned.
604    pub fn process<H: Collector>(&mut self, handler: &mut H) -> SubtrActorResult<()> {
605        // Initially, we set target_time to NextFrame to ensure the collector
606        // will process the first frame.
607        let mut target_time = TimeAdvance::NextFrame;
608        for (index, frame) in self
609            .replay
610            .network_frames
611            .as_ref()
612            .ok_or_else(|| SubtrActorError::new(SubtrActorErrorVariant::NoNetworkFrames))?
613            .frames
614            .iter()
615            .enumerate()
616        {
617            // Update the internal state of the processor based on the current frame
618            self.actor_state.process_frame(frame, index)?;
619            self.update_game_type_details();
620            self.update_mappings(frame)?;
621            self.update_ball_id(frame)?;
622            self.update_boost_amounts(frame, index)?;
623            self.update_boost_pad_events(frame, index)?;
624            self.update_touch_events(frame, index)?;
625            self.update_dodge_refreshed_events(frame, index)?;
626            self.update_goal_events(frame, index)?;
627            self.update_player_stat_events(frame, index)?;
628            self.update_demolishes(frame, index)?;
629
630            // Get the time to process for this frame. If target_time is set to
631            // NextFrame, we use the time of the current frame.
632            let mut current_time = match &target_time {
633                TimeAdvance::Time(t) => *t,
634                TimeAdvance::NextFrame => frame.time,
635            };
636
637            while current_time <= frame.time {
638                // Call the handler to process the frame and get the time for
639                // the next frame the handler wants to process
640                target_time = handler.process_frame(self, frame, index, current_time)?;
641                // If the handler specified a specific time, update current_time
642                // to that time. If the handler specified NextFrame, we break
643                // out of the loop to move on to the next frame in the replay.
644                // This design allows the handler to have control over the frame
645                // rate, including the possibility of skipping frames.
646                if let TimeAdvance::Time(new_target) = target_time {
647                    current_time = new_target;
648                } else {
649                    break;
650                }
651            }
652        }
653        handler.finish_replay(self)?;
654        Ok(())
655    }
656
657    /// Process multiple collectors simultaneously over the same replay frames.
658    ///
659    /// All collectors receive the same frame data for each frame. This is useful
660    /// when you have multiple independent collectors that each gather different
661    /// aspects of replay data.
662    ///
663    /// Note: This method always advances frame-by-frame. If collectors return
664    /// [`TimeAdvance::Time`] values, those are ignored.
665    pub fn process_all(&mut self, collectors: &mut [&mut dyn Collector]) -> SubtrActorResult<()> {
666        for (index, frame) in self
667            .replay
668            .network_frames
669            .as_ref()
670            .ok_or_else(|| SubtrActorError::new(SubtrActorErrorVariant::NoNetworkFrames))?
671            .frames
672            .iter()
673            .enumerate()
674        {
675            self.actor_state.process_frame(frame, index)?;
676            self.update_game_type_details();
677            self.update_mappings(frame)?;
678            self.update_ball_id(frame)?;
679            self.update_boost_amounts(frame, index)?;
680            self.update_boost_pad_events(frame, index)?;
681            self.update_touch_events(frame, index)?;
682            self.update_dodge_refreshed_events(frame, index)?;
683            self.update_goal_events(frame, index)?;
684            self.update_player_stat_events(frame, index)?;
685            self.update_demolishes(frame, index)?;
686
687            for collector in collectors.iter_mut() {
688                collector.process_frame(self, frame, index, frame.time)?;
689            }
690        }
691        for collector in collectors.iter_mut() {
692            collector.finish_replay(self)?;
693        }
694        Ok(())
695    }
696
697    /// Reset the state of the [`ReplayProcessor`].
698    pub fn reset(&mut self) {
699        self.ball_actor_id = None;
700        // Keep bootstrapped player/car mappings. Some old replays expose
701        // player identity late during bootstrap, but the actor ids are already
702        // valid for earlier frames once frame processing restarts.
703        self.actor_state = ActorStateModeler::new();
704        self.boost_pad_events = Vec::new();
705        self.current_frame_boost_pad_events = Vec::new();
706        self.boost_pad_pickup_sequence_times = HashMap::new();
707        self.boost_pad_resolution = BoostPadResolutionState::default();
708        self.touch_events = Vec::new();
709        self.current_frame_touch_events = Vec::new();
710        self.dodge_refreshed_events = Vec::new();
711        self.current_frame_dodge_refreshed_events = Vec::new();
712        self.dodge_refreshed_counters = HashMap::new();
713        self.goal_events = Vec::new();
714        self.current_frame_goal_events = Vec::new();
715        self.player_stat_events = Vec::new();
716        self.current_frame_player_stat_events = Vec::new();
717        self.player_stat_counters = HashMap::new();
718        self.demolishes = Vec::new();
719        self.known_demolishes = Vec::new();
720        self.demolish_format = None;
721        self.kickoff_phase_active_last_frame = false;
722    }
723}
724
725#[cfg(test)]
726#[path = "mod_tests.rs"]
727mod tests;