gui_pb/replay.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
//! A utility for recording over time
use anyhow::{anyhow, Error};
use core_pb::grid::standard_grid::StandardGrid;
use core_pb::pacbot_rs::game_state::GameState;
use nalgebra::Isometry2;
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime};
/// The types of data that might be stored in a [`ReplayFrame`]
#[derive(Clone, Debug, Serialize, Deserialize)]
enum ReplayFrameData {
/// Pacbot's real physical location, as determined by the [`PacbotSimulation`], as well as the
/// particle filter's best guess
PacbotLocation(Isometry2<f32>, Isometry2<f32>),
// /// Information that changes frequently in Pacman, like ghost locations and pellets
// PacmanGameState(Box<GameEngine>),
// /// Pacbot's sensors
// PacbotSensors(PacbotSensors),
// /// The AI's desired path
// TargetPath(Vec<IntLocation>),
// /// The robot target velocity
// TargetVelocity(Vector2<f32>, f32),
}
/// The metadata included in one frame of a [`Replay`]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct ReplayFrame {
/// The data in the frame
pub data: ReplayFrameData,
/// When the data was created
pub timestamp: SystemTime,
}
/// A collection of frames representing a full replay, along with associated metadata
#[derive(Clone, Serialize, Deserialize)]
pub struct Replay {
/// The time when recording started
start_time: SystemTime,
/// The StandardGrid the recording uses
standard_grid: StandardGrid,
/// The name/label given to this replay (usually matches the file name)
pub label: String,
/// The data of the replay
frames: Vec<ReplayFrame>,
/// Index of the most recently recorded or played frame
current_frame: usize,
/// Index of the most recently recorded or played pacman state frame
pacman_state_frame: usize,
/// Index of the most recently recorded or played pacman location frame
location_frame: usize,
}
impl Default for Replay {
fn default() -> Self {
Self::new(
"replay".to_string(),
StandardGrid::Pacman,
GameState::default(),
StandardGrid::Pacman.get_default_pacbot_isometry(),
)
}
}
#[allow(dead_code)]
impl Replay {
/// Start a new Replay
///
/// Note: pacman_state is copied once
///
/// # Examples
///
/// ```
/// use pacbot_rs::game_engine::GameEngine;
/// use rapier2d::math::Isometry;
/// use rapier2d::na::Vector2;
/// use mdrc_pacbot_util::replay::Replay;
/// use mdrc_pacbot_util::grid::standard_grids::StandardGrid;
///
/// let mut replay = Replay::new(
/// "My First Replay".to_string(),
/// StandardGrid::Pacman,
/// GameEngine::default(),
/// StandardGrid::Pacman.get_default_pacbot_isometry()
/// );
///
/// assert_eq!(replay.frame_count(), 2);
/// assert_eq!(replay.current_frame(), 1);
/// ```
pub fn new(
label: String,
standard_grid: StandardGrid,
_pacman_state: GameState,
pacbot_location: Isometry2<f32>,
) -> Self {
let start_time = SystemTime::now();
let frames = vec![
// ReplayFrame {
// data: ReplayFrameData::PacmanGameState(Box::new(pacman_state)),
// timestamp: start_time,
// },
ReplayFrame {
data: ReplayFrameData::PacbotLocation(pacbot_location, pacbot_location),
timestamp: start_time,
},
];
Self {
start_time,
standard_grid,
label,
frames,
current_frame: 1,
pacman_state_frame: 0,
location_frame: 1,
}
}
/// Create a new Replay starting at the current frame in the given Replay
///
/// All frames are updated so that the most recent one matches the current time
///
/// May return Err if the given replay frame is in the future
///
/// # Examples
///
/// ```
/// use pacbot_rs::game_engine::GameEngine;
/// use rand::rngs::ThreadRng;
/// use rapier2d::math::Isometry;
/// use rapier2d::na::Vector2;
/// use mdrc_pacbot_util::replay::Replay;
/// use mdrc_pacbot_util::grid::standard_grids::StandardGrid;
///
/// let mut pacman_state = GameEngine::default();
/// let mut rng = ThreadRng::default();
///
/// let mut replay = Replay::new(
/// "My First Replay".to_string(),
/// StandardGrid::Pacman,
/// pacman_state.to_owned(),
/// StandardGrid::Pacman.get_default_pacbot_isometry()
/// );
///
/// assert_eq!(replay.frame_count(), 2);
/// assert_eq!(replay.current_frame(), 1);
///
/// for i in 0..3 {
/// pacman_state.step();
/// replay.record_pacman_state(pacman_state.to_owned()).unwrap();
/// }
///
/// replay.step_back();
/// replay.step_back();
///
/// assert!(!replay.is_at_end());
/// assert_eq!(replay.frame_count(), 5);
/// assert_eq!(replay.current_frame(), 2);
///
/// let replay = Replay::starting_at(&replay);
///
/// assert!(replay.is_at_end());
/// assert_eq!(replay.frame_count(), 3);
/// assert_eq!(replay.current_frame(), 2);
/// ```
pub fn starting_at(other: &Replay) -> Self {
let mut frames = Vec::new();
let now = SystemTime::now();
let offset = now
.duration_since(other.frames[other.current_frame].timestamp)
.expect("Other replay ended in the future!");
let pacman_state_frame = 0;
let mut location_frame = 0;
for frame in 0..=other.current_frame {
match other.frames[frame].data {
ReplayFrameData::PacbotLocation(_, _) => location_frame = frame,
// ReplayFrameData::PacmanGameState(_) => pacman_state_frame = frame,
// _ => {}
}
frames.push(ReplayFrame {
data: other.frames[frame].data.to_owned(),
timestamp: other.frames[frame].timestamp + offset,
})
}
Self {
start_time: frames[0].timestamp,
standard_grid: other.standard_grid,
label: other.label.to_owned(),
frames,
current_frame: other.current_frame,
pacman_state_frame,
location_frame,
}
}
/// Create a new Replay using bytes from a file
///
/// # Examples
///
/// ```
/// use mdrc_pacbot_util::replay::Replay;
///
/// let replay = Replay::default();
/// let replay_bytes = replay.to_bytes().expect("Failed to serialize replay!");
/// let replay2 = Replay::from_bytes(&replay_bytes).expect("Failed to deserialize replay!");
/// ```
pub fn from_bytes(bytes: &[u8]) -> Result<(Replay, usize), bincode::error::DecodeError> {
bincode::serde::decode_from_slice(bytes, bincode::config::standard())
}
/// Get the bytes associated with the Replay
///
/// # Examples
///
/// ```
/// use mdrc_pacbot_util::replay::Replay;
///
/// let replay = Replay::default();
/// let replay_bytes = replay.to_bytes().expect("Failed to serialize replay!");
/// let replay2 = Replay::from_bytes(&replay_bytes).expect("Failed to deserialize replay!");
/// ```
pub fn to_bytes(&self) -> Result<Vec<u8>, bincode::error::EncodeError> {
bincode::serde::encode_to_vec(self, bincode::config::standard())
}
/// Returns whether the replay has played its last frame
///
/// # Examples
///
/// ```
/// use pacbot_rs::game_engine::GameEngine;
/// use mdrc_pacbot_util::replay::Replay;
///
/// let mut replay = Replay::default();
/// assert!(replay.is_at_end());
/// replay.record_pacman_state(GameEngine::default()).unwrap();
/// assert!(replay.is_at_end());
/// replay.step_back();
/// assert!(!replay.is_at_end());
/// replay.step_forwards();
/// assert!(replay.is_at_end());
/// ```
pub fn is_at_end(&self) -> bool {
self.current_frame == self.frames.len() - 1
}
/// Returns whether the replay is at the beginning
///
/// # Examples
///
/// ```
/// use pacbot_rs::game_engine::GameEngine;
/// use mdrc_pacbot_util::replay::Replay;
///
/// let mut replay = Replay::default();
/// assert!(replay.is_at_beginning());
/// replay.record_pacman_state(GameEngine::default()).unwrap();
/// assert!(!replay.is_at_beginning());
/// replay.step_back();
/// assert!(replay.is_at_beginning());
/// replay.step_forwards();
/// assert!(!replay.is_at_beginning());
/// ```
pub fn is_at_beginning(&self) -> bool {
self.current_frame <= 1
}
//
// /// Returns the most recent PacmanState
// ///
// /// # Examples
// ///
// /// ```
// /// use pacbot_rs::game_engine::GameEngine;
// /// use rand::rngs::ThreadRng;
// /// use mdrc_pacbot_util::replay::Replay;
// ///
// /// let mut replay = Replay::default();
// /// let mut pacman_state = GameEngine::default();
// /// let mut rng = ThreadRng::default();
// ///
// /// pacman_state.step();
// /// replay.record_pacman_state(pacman_state.to_owned()).unwrap();
// /// let pacman_state_1 = pacman_state.to_owned();
// /// pacman_state.step();
// /// replay.record_pacman_state(pacman_state.to_owned()).unwrap();
// /// let pacman_state_2 = pacman_state.to_owned();
// ///
// /// let _ = replay.get_pacman_state();
// /// ```
// pub fn get_pacman_state(&self) -> GameEngine {
// if let ReplayFrameData::PacmanGameState(data) = &self.frames[self.pacman_state_frame].data {
// *data.to_owned()
// } else {
// panic!("Replay was corrupt - pacman_state_frame was wrong")
// }
// }
/// Returns the most recent PacbotLocation
///
/// # Examples
///
/// ```
/// use rapier2d::na::{Isometry2, Vector2};
/// use mdrc_pacbot_util::replay::Replay;
///
/// let mut replay = Replay::default();
///
/// let isometry_1 = Isometry2::new(Vector2::new(1.0, 1.0), 1.0);
/// replay.record_pacman_location(isometry_1.to_owned()).unwrap();
/// let isometry_2 = Isometry2::new(Vector2::new(2.0, 2.0), 2.0);
/// replay.record_pacman_location(isometry_2.to_owned()).unwrap();
///
/// assert_eq!(isometry_2, replay.get_pacbot_location());
/// replay.step_back();
/// assert_eq!(isometry_1, replay.get_pacbot_location());
/// ```
pub fn get_pacbot_location(&self) -> Isometry2<f32> {
// if let ReplayFrameData::PacbotLocation(data, _) = &self.frames[self.location_frame].data {
// data.to_owned()
// } else {
// panic!("Replay was corrupt - location_frame was wrong")
// }
Isometry2::identity()
}
fn update_current_frames(&mut self) {
match &self.frames[self.current_frame].data {
ReplayFrameData::PacbotLocation(_, _) => self.location_frame = self.current_frame,
// ReplayFrameData::PacmanGameState(_) => self.pacman_state_frame = self.current_frame,
// _ => {}
};
}
/// Moves to the next frame, if it exists
pub fn step_forwards(&mut self) {
if !self.is_at_end() {
self.current_frame += 1;
self.update_current_frames();
}
}
/// Moves to the previous frame, if it exists
pub fn step_back(&mut self) {
if self.current_frame >= 2 {
self.current_frame -= 1;
self.update_current_frames();
} else {
// play all the frames from the beginning
self.go_to_beginning();
}
}
/// Go back to the beginning of the recording
pub fn go_to_beginning(&mut self) {
self.current_frame = 0;
self.pacman_state_frame = 0;
self.location_frame = 1;
self.update_current_frames();
}
/// Go to the end of the recording
pub fn go_to_end(&mut self) {
for frame in 0..self.frames.len() {
match &self.frames[frame].data {
ReplayFrameData::PacbotLocation(_, _) => self.location_frame = frame,
// ReplayFrameData::PacmanGameState(_) => self.pacman_state_frame = frame,
// _ => {}
}
}
self.current_frame = self.frames.len() - 1;
}
/// Step forwards until a PacmanState frame is reached
///
/// # Examples
///
/// ```
/// use pacbot_rs::game_engine::GameEngine;
/// use rapier2d::na::{Isometry2, Vector2};
/// use mdrc_pacbot_util::replay::Replay;
///
/// let mut replay = Replay::default();
///
/// replay.record_pacman_state(GameEngine::default()).unwrap();
/// replay.record_pacman_location(Isometry2::new(Vector2::new(1.0, 1.0), 1.0)).unwrap();
/// replay.record_pacman_location(Isometry2::new(Vector2::new(2.0, 2.0), 2.0)).unwrap();
/// replay.record_pacman_location(Isometry2::new(Vector2::new(3.0, 3.0), 3.0)).unwrap();
/// replay.record_pacman_state(GameEngine::default()).unwrap();
/// replay.record_pacman_location(Isometry2::new(Vector2::new(4.0, 4.0), 4.0)).unwrap();
/// replay.record_pacman_location(Isometry2::new(Vector2::new(5.0, 5.0), 5.0)).unwrap();
/// replay.record_pacman_location(Isometry2::new(Vector2::new(6.0, 6.0), 6.0)).unwrap();
/// replay.record_pacman_state(GameEngine::default()).unwrap();
///
/// assert_eq!(replay.get_pacbot_location(), Isometry2::new(Vector2::new(6.0, 6.0), 6.0));
/// replay.step_backwards_until_pacman_state();
/// assert_eq!(replay.get_pacbot_location(), Isometry2::new(Vector2::new(4.0, 4.0), 4.0));
/// replay.step_backwards_until_pacman_state();
/// assert_eq!(replay.get_pacbot_location(), Isometry2::new(Vector2::new(1.0, 1.0), 1.0));
/// replay.step_forwards_until_pacman_state();
/// assert_eq!(replay.get_pacbot_location(), Isometry2::new(Vector2::new(3.0, 3.0), 3.0));
/// replay.step_forwards_until_pacman_state();
/// assert_eq!(replay.get_pacbot_location(), Isometry2::new(Vector2::new(6.0, 6.0), 6.0));
/// ```
pub fn step_forwards_until_pacman_state(&mut self) {
let previous_pacman_state_frame = self.pacman_state_frame;
while !self.is_at_end() {
self.step_forwards();
if previous_pacman_state_frame != self.pacman_state_frame {
return;
}
}
}
/// Step backwards until a PacmanState frame is reached
///
/// See [`Replay::step_forwards_until_pacman_state`] for example
pub fn step_backwards_until_pacman_state(&mut self) {
let previous_pacman_state_frame = self.pacman_state_frame;
while !self.is_at_beginning() {
self.step_back();
if previous_pacman_state_frame != self.pacman_state_frame {
return;
}
}
}
/// Add a pacman location to the end of the replay
///
/// Returns err if the current frame is not the last frame
///
/// # Examples
///
/// ```
///
/// use pacbot_rs::game_engine::GameEngine;
/// use mdrc_pacbot_util::replay::Replay;
///
/// let mut replay = Replay::default();
///
/// assert!(replay.record_pacman_state(GameEngine::default()).is_ok());
/// replay.step_back();
/// // Don't add frames to a replay that isn't at the end
/// assert!(replay.record_pacman_state(GameEngine::default()).is_err());
/// ```
pub fn record_pacman_location(&mut self, location: Isometry2<f32>) -> Result<(), Error> {
if !self.is_at_end() {
Err(anyhow!("Tried to record to replay that was mid-playback"))
} else {
self.frames.push(ReplayFrame {
timestamp: SystemTime::now(),
data: ReplayFrameData::PacbotLocation(location, location),
});
self.current_frame += 1;
self.location_frame = self.current_frame;
Ok(())
}
}
//
// /// Add a pacman game state to the end of the replay
// ///
// /// Returns err if the current frame is not the last frame
// ///
// /// # Examples
// ///
// /// ```
// ///
// /// use rapier2d::na::Isometry2;
// /// use mdrc_pacbot_util::replay::Replay;
// ///
// /// let mut replay = Replay::default();
// ///
// /// assert!(replay.record_pacman_location(Isometry2::default()).is_ok());
// /// replay.step_back();
// /// // Don't add frames to a replay that isn't at the end
// /// assert!(replay.record_pacman_location(Isometry2::default()).is_err());
// /// ```
// pub fn record_pacman_state(&mut self, state: &GameEngine) -> Result<(), Error> {
// let state = bincode::serde::encode_to_vec(state, bincode::config::standard()).unwrap();
// let state: GameEngine =
// bincode::serde::decode_from_slice(&state, bincode::config::standard())
// .unwrap()
// .0;
// if !self.is_at_end() {
// Err(anyhow!("Tried to record to replay that was mid-playback"))
// } else {
// self.frames.push(ReplayFrame {
// timestamp: SystemTime::now(),
// data: ReplayFrameData::PacmanGameState(Box::new(state)),
// });
// self.current_frame += 1;
// self.pacman_state_frame = self.current_frame;
// Ok(())
// }
// }
/// Get the index of the current frame
///
/// While this can be a good estimation of the progress through a replay, there is no guarantee
/// that step_forwards() or step_back(), or any other methods, will hit any specific frame
pub fn current_frame(&self) -> usize {
self.current_frame
}
/// Get the number of frames
///
/// While this can be used to get a good estimation of the progress through a replay, there
/// is no guarantee that step_forwards() or step_back(), or any other methods, will hit
/// any specific frame
pub fn frame_count(&self) -> usize {
self.frames.len()
}
/// Get the amount of time until the next frame
///
/// If at the end, returns Duration::MAX
pub fn time_to_next(&self) -> Duration {
if self.is_at_end() {
Duration::MAX
} else {
self.frames[self.current_frame + 1]
.timestamp
.duration_since(self.frames[self.current_frame].timestamp)
.expect("Frames are out of order!")
}
}
/// Get the amount of time between the current and previous frame
///
/// If at the end, returns Duration::MAX
pub fn time_to_previous(&self) -> Duration {
if self.is_at_beginning() {
Duration::MAX
} else {
self.frames[self.current_frame]
.timestamp
.duration_since(self.frames[self.current_frame - 1].timestamp)
.expect("Frames are out of order!")
}
}
}
// #[cfg(test)]
// mod test {
// use crate::replay::Replay;
// use pacbot_rs::game_engine::GameEngine;
// use rapier2d::na::Isometry2;
//
// #[test]
// fn test_replay_starting_at_end_of_other() {
// let mut replay = Replay::default();
//
// replay.record_pacman_location(Isometry2::default()).unwrap();
// replay.record_pacman_location(Isometry2::default()).unwrap();
// replay.record_pacman_state(&GameEngine::default()).unwrap();
// replay.record_pacman_location(Isometry2::default()).unwrap();
// replay.record_pacman_location(Isometry2::default()).unwrap();
//
// let replay = Replay::starting_at(&replay);
//
// replay.get_pacman_state();
// replay.get_pacbot_location();
// }
// }