1use crate::*;
2use boxcars;
3use std::collections::HashMap;
4
5pub mod actor_state;
6pub use actor_state::*;
7
8pub(crate) fn attribute_type_name(attribute: &boxcars::Attribute) -> &'static str {
9 match attribute {
10 boxcars::Attribute::Boolean(_) => "Boolean",
11 boxcars::Attribute::Byte(_) => "Byte",
12 boxcars::Attribute::AppliedDamage(_) => "AppliedDamage",
13 boxcars::Attribute::DamageState(_) => "DamageState",
14 boxcars::Attribute::CamSettings(_) => "CamSettings",
15 boxcars::Attribute::ClubColors(_) => "ClubColors",
16 boxcars::Attribute::Demolish(_) => "Demolish",
17 boxcars::Attribute::DemolishExtended(_) => "DemolishExtended",
18 boxcars::Attribute::DemolishFx(_) => "DemolishFx",
19 boxcars::Attribute::Enum(_) => "Enum",
20 boxcars::Attribute::Explosion(_) => "Explosion",
21 boxcars::Attribute::ExtendedExplosion(_) => "ExtendedExplosion",
22 boxcars::Attribute::FlaggedByte(_, _) => "FlaggedByte",
23 boxcars::Attribute::ActiveActor(_) => "ActiveActor",
24 boxcars::Attribute::Float(_) => "Float",
25 boxcars::Attribute::GameMode(_, _) => "GameMode",
26 boxcars::Attribute::Int(_) => "Int",
27 boxcars::Attribute::Int64(_) => "Int64",
28 boxcars::Attribute::Loadout(_) => "Loadout",
29 boxcars::Attribute::TeamLoadout(_) => "TeamLoadout",
30 boxcars::Attribute::Location(_) => "Location",
31 boxcars::Attribute::MusicStinger(_) => "MusicStinger",
32 boxcars::Attribute::PlayerHistoryKey(_) => "PlayerHistoryKey",
33 boxcars::Attribute::Pickup(_) => "Pickup",
34 boxcars::Attribute::PickupNew(_) => "PickupNew",
35 boxcars::Attribute::QWord(_) => "QWord",
36 boxcars::Attribute::Welded(_) => "Welded",
37 boxcars::Attribute::Title(_, _, _, _, _, _, _, _) => "Title",
38 boxcars::Attribute::TeamPaint(_) => "TeamPaint",
39 boxcars::Attribute::RigidBody(_) => "RigidBody",
40 boxcars::Attribute::String(_) => "String",
41 boxcars::Attribute::UniqueId(_) => "UniqueId",
42 boxcars::Attribute::Reservation(_) => "Reservation",
43 boxcars::Attribute::PartyLeader(_) => "PartyLeader",
44 boxcars::Attribute::PrivateMatch(_) => "PrivateMatch",
45 boxcars::Attribute::LoadoutOnline(_) => "LoadoutOnline",
46 boxcars::Attribute::LoadoutsOnline(_) => "LoadoutsOnline",
47 boxcars::Attribute::StatEvent(_) => "StatEvent",
48 boxcars::Attribute::Rotation(_) => "Rotation",
49 boxcars::Attribute::RepStatTitle(_) => "RepStatTitle",
50 boxcars::Attribute::PickupInfo(_) => "PickupInfo",
51 boxcars::Attribute::Impulse(_) => "Impulse",
52 boxcars::Attribute::ReplicatedBoost(_) => "ReplicatedBoost",
53 boxcars::Attribute::LogoData(_) => "LogoData",
54 }
55}
56
57#[macro_export]
69macro_rules! attribute_match {
70 ($value:expr, $type:path $(,)?) => {{
71 let attribute = $value;
72 if let $type(value) = attribute {
73 Ok(value)
74 } else {
75 SubtrActorError::new_result(SubtrActorErrorVariant::UnexpectedAttributeType {
76 expected_type: stringify!($type),
77 actual_type: attribute_type_name(&attribute),
78 })
79 }
80 }};
81}
82
83#[macro_export]
92macro_rules! get_attribute_errors_expected {
93 ($self:ident, $map:expr, $prop:expr, $type:path) => {
94 $self
95 .get_attribute($map, $prop)
96 .and_then(|found| attribute_match!(found, $type))
97 };
98}
99
100macro_rules! get_attribute_and_updated {
113 ($self:ident, $map:expr, $prop:expr, $type:path) => {
114 $self
115 .get_attribute_and_updated($map, $prop)
116 .and_then(|(found, updated)| attribute_match!(found, $type).map(|v| (v, updated)))
117 };
118}
119
120macro_rules! get_actor_attribute_matching {
129 ($self:ident, $actor:expr, $prop:expr, $type:path) => {
130 $self
131 .get_actor_attribute($actor, $prop)
132 .and_then(|found| attribute_match!(found, $type))
133 };
134}
135
136macro_rules! get_derived_attribute {
145 ($map:expr, $key:expr, $type:path) => {
146 $map.get($key)
147 .ok_or_else(|| {
148 SubtrActorError::new(SubtrActorErrorVariant::DerivedKeyValueNotFound {
149 name: $key.to_string(),
150 })
151 })
152 .and_then(|found| attribute_match!(&found.0, $type))
153 };
154}
155
156fn get_actor_id_from_active_actor<T>(
157 _: T,
158 active_actor: &boxcars::ActiveActor,
159) -> boxcars::ActorId {
160 active_actor.actor
161}
162
163fn use_update_actor<T>(id: boxcars::ActorId, _: T) -> boxcars::ActorId {
164 id
165}
166
167#[derive(Clone, Copy, Default)]
168struct CachedObjectIds {
169 player_type: Option<boxcars::ObjectId>,
170 car_type: Option<boxcars::ObjectId>,
171 boost_type: Option<boxcars::ObjectId>,
172 dodge_type: Option<boxcars::ObjectId>,
173 jump_type: Option<boxcars::ObjectId>,
174 double_jump_type: Option<boxcars::ObjectId>,
175 unique_id: Option<boxcars::ObjectId>,
176 team: Option<boxcars::ObjectId>,
177 bot: Option<boxcars::ObjectId>,
178 player_replication: Option<boxcars::ObjectId>,
179 vehicle: Option<boxcars::ObjectId>,
180 boost_replicated: Option<boxcars::ObjectId>,
181 boost_amount: Option<boxcars::ObjectId>,
182 component_active: Option<boxcars::ObjectId>,
183 seconds_remaining: Option<boxcars::ObjectId>,
184 replicated_state_name: Option<boxcars::ObjectId>,
185 replicated_game_state_time_remaining: Option<boxcars::ObjectId>,
186 ball_has_been_hit: Option<boxcars::ObjectId>,
187 ball_hit_team_num: Option<boxcars::ObjectId>,
188 dodges_refreshed_counter: Option<boxcars::ObjectId>,
189}
190
191impl CachedObjectIds {
192 fn from_name_map(name_to_object_id: &HashMap<String, boxcars::ObjectId>) -> Self {
193 let cached = |name| name_to_object_id.get(name).copied();
194 Self {
195 player_type: cached(PLAYER_TYPE),
196 car_type: cached(CAR_TYPE),
197 boost_type: cached(BOOST_TYPE),
198 dodge_type: cached(DODGE_TYPE),
199 jump_type: cached(JUMP_TYPE),
200 double_jump_type: cached(DOUBLE_JUMP_TYPE),
201 unique_id: cached(UNIQUE_ID_KEY),
202 team: cached(TEAM_KEY),
203 bot: cached(BOT_KEY),
204 player_replication: cached(PLAYER_REPLICATION_KEY),
205 vehicle: cached(VEHICLE_KEY),
206 boost_replicated: cached(BOOST_REPLICATED_KEY),
207 boost_amount: cached(BOOST_AMOUNT_KEY),
208 component_active: cached(COMPONENT_ACTIVE_KEY),
209 seconds_remaining: cached(SECONDS_REMAINING_KEY),
210 replicated_state_name: cached(REPLICATED_STATE_NAME_KEY),
211 replicated_game_state_time_remaining: cached(REPLICATED_GAME_STATE_TIME_REMAINING_KEY),
212 ball_has_been_hit: cached(BALL_HAS_BEEN_HIT_KEY),
213 ball_hit_team_num: cached(BALL_HIT_TEAM_NUM_KEY),
214 dodges_refreshed_counter: cached(DODGES_REFRESHED_COUNTER_KEY),
215 }
216 }
217}
218
219mod bootstrap;
220mod debug;
221mod queries;
222mod updaters;
223
224pub struct ReplayProcessor<'a> {
256 pub replay: &'a boxcars::Replay,
258 spatial_normalization_factor: f32,
259 rigid_body_velocity_normalization_factor: f32,
260 uses_legacy_rigid_body_rotation: bool,
261 cached_object_ids: CachedObjectIds,
262 is_boost_pad_object: Vec<bool>,
263 pub actor_state: ActorStateModeler,
265 pub object_id_to_name: HashMap<boxcars::ObjectId, String>,
267 pub name_to_object_id: HashMap<String, boxcars::ObjectId>,
269 pub ball_actor_id: Option<boxcars::ActorId>,
271 pub team_zero: Vec<PlayerId>,
273 pub team_one: Vec<PlayerId>,
275 pub player_to_actor_id: HashMap<PlayerId, boxcars::ActorId>,
277 pub player_to_car: HashMap<boxcars::ActorId, boxcars::ActorId>,
279 pub player_to_team: HashMap<boxcars::ActorId, boxcars::ActorId>,
281 pub car_to_player: HashMap<boxcars::ActorId, boxcars::ActorId>,
283 pub car_to_boost: HashMap<boxcars::ActorId, boxcars::ActorId>,
285 pub car_to_jump: HashMap<boxcars::ActorId, boxcars::ActorId>,
287 pub car_to_double_jump: HashMap<boxcars::ActorId, boxcars::ActorId>,
289 pub car_to_dodge: HashMap<boxcars::ActorId, boxcars::ActorId>,
291 pub boost_pad_events: Vec<BoostPadEvent>,
293 current_frame_boost_pad_events: Vec<BoostPadEvent>,
294 boost_pad_pickup_sequence_times: HashMap<(String, u8), f32>,
295 pub touch_events: Vec<TouchEvent>,
297 current_frame_touch_events: Vec<TouchEvent>,
298 pub dodge_refreshed_events: Vec<DodgeRefreshedEvent>,
300 current_frame_dodge_refreshed_events: Vec<DodgeRefreshedEvent>,
301 dodge_refreshed_counters: HashMap<PlayerId, i32>,
302 pub goal_events: Vec<GoalEvent>,
304 current_frame_goal_events: Vec<GoalEvent>,
305 pub player_stat_events: Vec<PlayerStatEvent>,
307 current_frame_player_stat_events: Vec<PlayerStatEvent>,
308 player_stat_counters: HashMap<(PlayerId, PlayerStatEventKind), i32>,
309 pub demolishes: Vec<DemolishInfo>,
311 known_demolishes: Vec<(DemolishAttribute, usize)>,
312 demolish_format: Option<DemolishFormat>,
313 kickoff_phase_active_last_frame: bool,
314}
315
316impl<'a> ReplayProcessor<'a> {
317 const LEGACY_RIGID_BODY_NET_VERSION_CUTOFF: i32 = 5;
318 const LEGACY_RIGID_BODY_ROTATION_NET_VERSION_CUTOFF: i32 = 7;
319 const LEGACY_RIGID_BODY_LOCATION_FACTOR: f32 = 100.0;
320 const LEGACY_RIGID_BODY_VELOCITY_FACTOR: f32 = 10.0;
321
322 fn uses_legacy_rigid_body_vector_scale(net_version: Option<i32>) -> bool {
323 net_version.is_none_or(|version| version < Self::LEGACY_RIGID_BODY_NET_VERSION_CUTOFF)
324 }
325
326 fn uses_legacy_rigid_body_rotation_for_net_version(net_version: Option<i32>) -> bool {
327 net_version
328 .is_none_or(|version| version < Self::LEGACY_RIGID_BODY_ROTATION_NET_VERSION_CUTOFF)
329 }
330
331 fn rigid_body_location_normalization_factor_for_net_version(net_version: Option<i32>) -> f32 {
332 if Self::uses_legacy_rigid_body_vector_scale(net_version) {
333 Self::LEGACY_RIGID_BODY_LOCATION_FACTOR
334 } else {
335 1.0
336 }
337 }
338
339 fn rigid_body_velocity_normalization_factor_for_net_version(net_version: Option<i32>) -> f32 {
340 if Self::uses_legacy_rigid_body_vector_scale(net_version) {
341 Self::LEGACY_RIGID_BODY_VELOCITY_FACTOR
342 } else {
343 1.0
344 }
345 }
346
347 pub fn new(replay: &'a boxcars::Replay) -> SubtrActorResult<Self> {
361 let mut object_id_to_name = HashMap::new();
362 let mut name_to_object_id = HashMap::new();
363 let spatial_normalization_factor =
364 Self::rigid_body_location_normalization_factor_for_net_version(replay.net_version);
365 let rigid_body_velocity_normalization_factor =
366 Self::rigid_body_velocity_normalization_factor_for_net_version(replay.net_version);
367 let uses_legacy_rigid_body_rotation =
368 Self::uses_legacy_rigid_body_rotation_for_net_version(replay.net_version);
369 for (id, name) in replay.objects.iter().enumerate() {
370 let object_id = boxcars::ObjectId(id as i32);
371 object_id_to_name.insert(object_id, name.clone());
372 name_to_object_id.insert(name.clone(), object_id);
373 }
374 let cached_object_ids = CachedObjectIds::from_name_map(&name_to_object_id);
375 let mut processor = Self {
376 actor_state: ActorStateModeler::new(),
377 replay,
378 spatial_normalization_factor,
379 rigid_body_velocity_normalization_factor,
380 uses_legacy_rigid_body_rotation,
381 cached_object_ids,
382 is_boost_pad_object: replay
383 .objects
384 .iter()
385 .map(|name| name.contains("VehiclePickup_Boost_TA"))
386 .collect(),
387 object_id_to_name,
388 name_to_object_id,
389 team_zero: Vec::new(),
390 team_one: Vec::new(),
391 ball_actor_id: None,
392 player_to_car: HashMap::new(),
393 player_to_team: HashMap::new(),
394 player_to_actor_id: HashMap::new(),
395 car_to_player: HashMap::new(),
396 car_to_boost: HashMap::new(),
397 car_to_jump: HashMap::new(),
398 car_to_double_jump: HashMap::new(),
399 car_to_dodge: HashMap::new(),
400 boost_pad_events: Vec::new(),
401 current_frame_boost_pad_events: Vec::new(),
402 boost_pad_pickup_sequence_times: HashMap::new(),
403 touch_events: Vec::new(),
404 current_frame_touch_events: Vec::new(),
405 dodge_refreshed_events: Vec::new(),
406 current_frame_dodge_refreshed_events: Vec::new(),
407 dodge_refreshed_counters: HashMap::new(),
408 goal_events: Vec::new(),
409 current_frame_goal_events: Vec::new(),
410 player_stat_events: Vec::new(),
411 current_frame_player_stat_events: Vec::new(),
412 player_stat_counters: HashMap::new(),
413 demolishes: Vec::new(),
414 known_demolishes: Vec::new(),
415 demolish_format: None,
416 kickoff_phase_active_last_frame: false,
417 };
418 processor
419 .set_player_order_from_headers()
420 .or_else(|_| processor.set_player_order_from_frames())?;
421
422 Ok(processor)
423 }
424
425 pub fn spatial_normalization_factor(&self) -> f32 {
427 self.spatial_normalization_factor
428 }
429
430 pub fn rigid_body_velocity_normalization_factor(&self) -> f32 {
432 self.rigid_body_velocity_normalization_factor
433 }
434
435 fn sync_player_order_from_known_mappings(&mut self) {
436 let player_ids: Vec<_> = self.player_to_actor_id.keys().cloned().collect();
437 for player_id in player_ids {
438 let already_ordered =
439 self.team_zero.contains(&player_id) || self.team_one.contains(&player_id);
440 if already_ordered {
441 continue;
442 }
443
444 let Ok(is_team_0) = self.get_player_is_team_0(&player_id) else {
445 continue;
446 };
447 if is_team_0 {
448 self.team_zero.push(player_id);
449 } else {
450 self.team_one.push(player_id);
451 }
452 }
453 }
454
455 pub(crate) fn insert_player_actor_id(
456 &mut self,
457 player_id: PlayerId,
458 actor_id: boxcars::ActorId,
459 ) {
460 let stale_player_ids = self
461 .player_to_actor_id
462 .iter()
463 .filter(|(existing_player_id, existing_actor_id)| {
464 **existing_actor_id == actor_id && **existing_player_id != player_id
465 })
466 .map(|(existing_player_id, _existing_actor_id)| existing_player_id.clone())
467 .collect::<Vec<_>>();
468
469 for stale_player_id in stale_player_ids {
470 self.player_to_actor_id.remove(&stale_player_id);
471 self.team_zero
472 .retain(|ordered_player_id| ordered_player_id != &stale_player_id);
473 self.team_one
474 .retain(|ordered_player_id| ordered_player_id != &stale_player_id);
475 }
476
477 self.player_to_actor_id.insert(player_id, actor_id);
478 }
479
480 fn normalize_vector_by_factor(
481 &self,
482 vector: boxcars::Vector3f,
483 factor: f32,
484 ) -> boxcars::Vector3f {
485 if (factor - 1.0).abs() < f32::EPSILON {
486 vector
487 } else {
488 boxcars::Vector3f {
489 x: vector.x * factor,
490 y: vector.y * factor,
491 z: vector.z * factor,
492 }
493 }
494 }
495
496 fn normalize_vector(&self, vector: boxcars::Vector3f) -> boxcars::Vector3f {
497 self.normalize_vector_by_factor(vector, self.spatial_normalization_factor)
498 }
499
500 fn normalize_rigid_body_velocity(&self, vector: boxcars::Vector3f) -> boxcars::Vector3f {
501 self.normalize_vector_by_factor(vector, self.rigid_body_velocity_normalization_factor)
502 }
503
504 fn normalize_optional_rigid_body_velocity(
505 &self,
506 vector: Option<boxcars::Vector3f>,
507 ) -> Option<boxcars::Vector3f> {
508 vector.map(|value| self.normalize_rigid_body_velocity(value))
509 }
510
511 fn normalize_rigid_body_rotation(&self, rotation: boxcars::Quaternion) -> boxcars::Quaternion {
512 if !self.uses_legacy_rigid_body_rotation {
513 return rotation;
514 }
515
516 let normalized = glam::Quat::from_euler(
520 glam::EulerRot::ZYX,
521 rotation.y * std::f32::consts::PI,
522 rotation.x * std::f32::consts::PI,
523 -rotation.z * std::f32::consts::PI,
524 );
525 boxcars::Quaternion {
526 x: normalized.x,
527 y: normalized.y,
528 z: normalized.z,
529 w: normalized.w,
530 }
531 }
532
533 fn normalize_rigid_body(&self, rigid_body: &boxcars::RigidBody) -> boxcars::RigidBody {
534 if (self.spatial_normalization_factor - 1.0).abs() < f32::EPSILON
535 && (self.rigid_body_velocity_normalization_factor - 1.0).abs() < f32::EPSILON
536 && !self.uses_legacy_rigid_body_rotation
537 {
538 *rigid_body
539 } else {
540 boxcars::RigidBody {
541 sleeping: rigid_body.sleeping,
542 location: self.normalize_vector(rigid_body.location),
543 rotation: self.normalize_rigid_body_rotation(rigid_body.rotation),
544 linear_velocity: self
545 .normalize_optional_rigid_body_velocity(rigid_body.linear_velocity),
546 angular_velocity: self
547 .normalize_optional_rigid_body_velocity(rigid_body.angular_velocity),
548 }
549 }
550 }
551
552 fn required_cached_object_id(
553 &self,
554 object_id: Option<boxcars::ObjectId>,
555 name: &'static str,
556 ) -> SubtrActorResult<boxcars::ObjectId> {
557 object_id
558 .ok_or_else(|| SubtrActorError::new(SubtrActorErrorVariant::ObjectIdNotFound { name }))
559 }
560
561 pub fn process<H: Collector>(&mut self, handler: &mut H) -> SubtrActorResult<()> {
583 let mut target_time = TimeAdvance::NextFrame;
586 for (index, frame) in self
587 .replay
588 .network_frames
589 .as_ref()
590 .ok_or(SubtrActorError::new(
591 SubtrActorErrorVariant::NoNetworkFrames,
592 ))?
593 .frames
594 .iter()
595 .enumerate()
596 {
597 self.actor_state.process_frame(frame, index)?;
599 self.update_mappings(frame)?;
600 self.update_ball_id(frame)?;
601 self.update_boost_amounts(frame, index)?;
602 self.update_boost_pad_events(frame, index)?;
603 self.update_touch_events(frame, index)?;
604 self.update_dodge_refreshed_events(frame, index)?;
605 self.update_goal_events(frame, index)?;
606 self.update_player_stat_events(frame, index)?;
607 self.update_demolishes(frame, index)?;
608
609 let mut current_time = match &target_time {
612 TimeAdvance::Time(t) => *t,
613 TimeAdvance::NextFrame => frame.time,
614 };
615
616 while current_time <= frame.time {
617 target_time = handler.process_frame(self, frame, index, current_time)?;
620 if let TimeAdvance::Time(new_target) = target_time {
626 current_time = new_target;
627 } else {
628 break;
629 }
630 }
631 }
632 handler.finish_replay(self)?;
633 Ok(())
634 }
635
636 pub fn process_all(&mut self, collectors: &mut [&mut dyn Collector]) -> SubtrActorResult<()> {
645 for (index, frame) in self
646 .replay
647 .network_frames
648 .as_ref()
649 .ok_or(SubtrActorError::new(
650 SubtrActorErrorVariant::NoNetworkFrames,
651 ))?
652 .frames
653 .iter()
654 .enumerate()
655 {
656 self.actor_state.process_frame(frame, index)?;
657 self.update_mappings(frame)?;
658 self.update_ball_id(frame)?;
659 self.update_boost_amounts(frame, index)?;
660 self.update_boost_pad_events(frame, index)?;
661 self.update_touch_events(frame, index)?;
662 self.update_dodge_refreshed_events(frame, index)?;
663 self.update_goal_events(frame, index)?;
664 self.update_player_stat_events(frame, index)?;
665 self.update_demolishes(frame, index)?;
666
667 for collector in collectors.iter_mut() {
668 collector.process_frame(self, frame, index, frame.time)?;
669 }
670 }
671 for collector in collectors.iter_mut() {
672 collector.finish_replay(self)?;
673 }
674 Ok(())
675 }
676
677 pub fn reset(&mut self) {
679 self.ball_actor_id = None;
680 self.actor_state = ActorStateModeler::new();
684 self.boost_pad_events = Vec::new();
685 self.current_frame_boost_pad_events = Vec::new();
686 self.boost_pad_pickup_sequence_times = HashMap::new();
687 self.touch_events = Vec::new();
688 self.current_frame_touch_events = Vec::new();
689 self.dodge_refreshed_events = Vec::new();
690 self.current_frame_dodge_refreshed_events = Vec::new();
691 self.dodge_refreshed_counters = HashMap::new();
692 self.goal_events = Vec::new();
693 self.current_frame_goal_events = Vec::new();
694 self.player_stat_events = Vec::new();
695 self.current_frame_player_stat_events = Vec::new();
696 self.player_stat_counters = HashMap::new();
697 self.demolishes = Vec::new();
698 self.known_demolishes = Vec::new();
699 self.demolish_format = None;
700 self.kickoff_phase_active_last_frame = false;
701 }
702}
703
704#[cfg(test)]
705#[path = "mod_tests.rs"]
706mod tests;