diff --git a/THIRD-PARTY.md b/THIRD-PARTY.md new file mode 100644 index 00000000..5a021ec2 --- /dev/null +++ b/THIRD-PARTY.md @@ -0,0 +1,38 @@ +# Third-party notices + +## ViceHook + +Parts of `crates/victory-loader/src/bench_route.rs` follow ViceHook's script +hook, native-call guard, thread election and spawn implementation +(, MIT). + +MIT License + +Copyright (c) 2026 Ethan Aldrich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## Native database + +The native ids, names and argument layouts in `bench_route.rs` follow the +GTA VI NativeDB from ScriptHook VI +(), licensed under CC BY 4.0 +(), as carried by ViceHook's +`sdk/inc/natives.h`. The MIT text above covers ViceHook's own code; the +database is attributed here separately. diff --git a/crates/victory-core/src/bench.rs b/crates/victory-core/src/bench.rs index 7be9d13e..fbdf00cc 100644 --- a/crates/victory-core/src/bench.rs +++ b/crates/victory-core/src/bench.rs @@ -5,12 +5,17 @@ //! //! `VICTORY_BENCH_ROUTE` adds a fixed route the player is taken along (see //! [`Route`]; driven by `victory_loader::bench_route`). In a benchmark run -//! with a route, the run's clock and its figures start when the route does. +//! with a route, the run's clock starts when the route does; the first +//! [`ROUTE_SKIPPED_SECONDS`] of route frames are left out of its figures. /// Minutes at the start left out of the figures (loading and menus), in /// runs of at least twice this. pub const SKIPPED_SECONDS: f64 = 60.0; +/// Seconds at the start of a route left out of its figures: streaming and +/// first-use work, kept out of cross-machine comparisons. +pub const ROUTE_SKIPPED_SECONDS: f64 = 30.0; + /// Whether this process is a benchmark run. pub fn running() -> bool { std::env::var("VICTORY_BENCH").is_ok_and(|v| v == "rt" || v == "nort") @@ -60,8 +65,9 @@ pub enum Route { /// `downtown`: a noclip flight around a 2400 m square over the city, at /// 30 m/s, 40 m above the ground, the camera sweeping side to side. Downtown, - /// `drive`: the game's AI drives the player's car around a fixed loop of - /// waypoints, with traffic. + /// `drive`: experimental. The game's AI drives the player's car to a fixed + /// road point and back, with traffic, but may choose different roads; its + /// measured scenes and lap times are not comparable between runs. Drive, } @@ -94,16 +100,55 @@ pub fn route() -> Option { }) } -static ROUTE_STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static ROUTE_STATE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(RouteState::Pending as u8); -/// The route is under way (or gave up): a benchmark run starts its clock. -pub fn set_route_started() { - ROUTE_STARTED.store(true, std::sync::atomic::Ordering::Relaxed); +/// How the route asked for stands in a benchmark run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum RouteState { + /// Asked for, not started yet. + Pending, + /// Under way at the end of the run. + Running, + /// Could not start: another build, a handler mismatch, or a fault before + /// the route began. A benchmark run then goes on as a normal one. + Failed, + /// Failed after setup had begun to change the world (time, weather, + /// invincibility, player position). The run is not a normal free-roam + /// benchmark and its figures are not comparable. + FailedAfterSetup, + /// Ran, then stopped early. + Stopped, } -/// Whether the route asked for has started (or gave up). -pub fn route_started() -> bool { - ROUTE_STARTED.load(std::sync::atomic::Ordering::Relaxed) +/// Sets how the route stands. +pub fn set_route_state(state: RouteState) { + ROUTE_STATE.store(state as u8, std::sync::atomic::Ordering::Relaxed); +} + +/// How the route asked for stands. +pub fn route_state() -> RouteState { + match ROUTE_STATE.load(std::sync::atomic::Ordering::Relaxed) { + x if x == RouteState::Running as u8 => RouteState::Running, + x if x == RouteState::Failed as u8 => RouteState::Failed, + x if x == RouteState::FailedAfterSetup as u8 => RouteState::FailedAfterSetup, + x if x == RouteState::Stopped as u8 => RouteState::Stopped, + _ => RouteState::Pending, + } +} + +/// Starts the route only if it is still pending. A concurrent failure (for +/// example the benchmark's wait timeout) wins; the caller must stop. +pub fn try_start_route() -> bool { + ROUTE_STATE + .compare_exchange( + RouteState::Pending as u8, + RouteState::Running as u8, + std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, + ) + .is_ok() } /// The `downtown` flight: the square's corner (x, y), the ground height the @@ -115,12 +160,11 @@ pub const DOWNTOWN_SIDE: f32 = 2400.0; pub const DOWNTOWN_SPEED: f32 = 30.0; pub const DOWNTOWN_UP: f32 = 40.0; -/// The `drive` loop's waypoints (absolute map x, y), driven in order and -/// around again; the car starts at the first, facing the second. Points the -/// game's AI was seen to reach on its roads (a dirt road in the hills): off -/// the road network its route finding stalls. -pub const DRIVE_WAYPOINTS: [(f32, f32); 3] = - [(-2556.0, 6948.0), (-2399.0, 7172.0), (-2566.0, 7202.0)]; +/// The `drive` route's two points (absolute map x, y), driven in order and +/// around again; the car starts at the first, facing the second. The second +/// is a vehicle-node point, but the AI may take different roads to it; the +/// route is experimental and its scenes are not comparable between runs. +pub const DRIVE_WAYPOINTS: [(f32, f32); 2] = [(-2556.0, 6948.0), (-2405.0, 6862.5)]; /// The game's heading (degrees, 0 north, counter-clockwise) of travel from /// `from` to `to`. @@ -202,12 +246,30 @@ impl Recorder { /// The figures, leaving out the first `skip` seconds of frames. pub fn summary_skipping(&self, skip: f64) -> Option { + self.summary_between(skip, None) + } + + /// The figures, leaving out the first `skip` seconds and any frame that + /// starts at or after `end` seconds. + pub fn summary_between(&self, skip: f64, end: Option) -> Option { let mut at = 0.0; - let first = self.frames.iter().position(|dt| { - at += dt; - at > skip - })?; - let frames = &self.frames[first..]; + let frames: Vec = self + .frames + .iter() + .copied() + .filter(|dt| { + let start = at; + at += dt; + at > skip && end.is_none_or(|end| start < end) + }) + .collect(); + Self::summarize(&frames) + } + + fn summarize(frames: &[f64]) -> Option { + if frames.is_empty() { + return None; + } let seconds: f64 = frames.iter().sum(); let average = frames.len() as f64 / seconds; let mut sorted = frames.to_vec(); @@ -278,6 +340,17 @@ mod tests { assert_eq!(Recorder::default().summary(), None); } + #[test] + fn a_stopped_run_ends_at_the_stop_time() { + let mut r = Recorder::default(); + (0..100).for_each(|_| r.add(0.1)); + let s = r.summary_between(1.0, Some(5.0)).unwrap(); + assert!((40..=41).contains(&s.frames)); + assert!((s.seconds - 4.0).abs() < 0.11); + let s = r.summary_between(0.0, Some(5.0)).unwrap(); + assert!((50..=51).contains(&s.frames)); + } + #[test] fn routes_are_named_as_documented() { assert_eq!(Route::parse("downtown"), Some(Route::Downtown)); @@ -308,5 +381,6 @@ mod tests { #[test] fn the_drive_starts_toward_the_first_leg() { assert!(heading(DRIVE_WAYPOINTS[0], DRIVE_WAYPOINTS[1]) < 0.0); + assert_eq!(DRIVE_WAYPOINTS.len(), 2); } } diff --git a/crates/victory-gpu/src/bench.rs b/crates/victory-gpu/src/bench.rs index db58c68f..4cab7064 100644 --- a/crates/victory-gpu/src/bench.rs +++ b/crates/victory-gpu/src/bench.rs @@ -4,15 +4,15 @@ //! (`bench_stats.txt`) in `VICTORY_BENCH_DIR`, and the game ends. //! //! With a route (`VICTORY_BENCH_ROUTE`) the frames are timed from the -//! route's start instead, and none are left out of the figures; a route that -//! has not started after [`ROUTE_WAIT`] of frames is given up on and the run -//! is timed from then. +//! route's start, after [`bench::ROUTE_SKIPPED_SECONDS`] of route warm-up; a +//! route that cannot start is not recorded as one and the run is timed and +//! skipped as a normal benchmark. use std::path::PathBuf; use std::sync::Mutex; use std::time::{Duration, Instant}; -use victory_core::bench::{self, Recorder}; +use victory_core::bench::{self, Recorder, Route, RouteState}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -29,6 +29,75 @@ struct Run { frames: Recorder, vram_peak: u64, ram_peak: u64, + /// Seconds from the route's start to the frame the route stopped on. + route_stopped_at: Option, +} + +/// How a run's route frames are summarized and labelled. +#[derive(Debug, PartialEq)] +struct RouteAccounting { + ran: bool, + failed: bool, + invalid: bool, + status: &'static str, + skip: f64, + end: Option, +} + +/// The accounting for a requested route and its final state. +fn route_accounting( + route: Option, + state: RouteState, + stopped_at: Option, +) -> RouteAccounting { + if route.is_none() { + return RouteAccounting { + ran: false, + failed: false, + invalid: false, + status: "none", + skip: 0.0, + end: None, + }; + } + match state { + RouteState::Pending | RouteState::Failed => RouteAccounting { + ran: false, + failed: true, + invalid: false, + status: "failed", + skip: 0.0, + end: None, + }, + RouteState::FailedAfterSetup => RouteAccounting { + ran: false, + failed: true, + invalid: true, + status: "failed_after_setup", + skip: 0.0, + end: None, + }, + RouteState::Running => RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "ran", + skip: bench::ROUTE_SKIPPED_SECONDS, + end: None, + }, + RouteState::Stopped => RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "stopped", + skip: if stopped_at.is_some_and(|stopped| stopped < bench::ROUTE_SKIPPED_SECONDS) { + 0.0 + } else { + bench::ROUTE_SKIPPED_SECONDS + }, + end: stopped_at, + }, + } } static RUN: Mutex> = Mutex::new(None); @@ -54,18 +123,34 @@ pub(crate) fn presented(memory: impl FnOnce() -> (u64, u64)) { return; } let now = Instant::now(); + let route = bench::route(); with(|r| { - if r.started.is_none() && bench::route().is_some() && !bench::route_started() { - if now.duration_since(*r.first.get_or_insert(now)) < ROUTE_WAIT { - return; + if r.started.is_none() { + if route.is_some() { + match bench::route_state() { + RouteState::Pending => { + if now.duration_since(*r.first.get_or_insert(now)) < ROUTE_WAIT { + return; + } + tracing::warn!( + "benchmark: the route did not start in {} s; timing a normal run from now", + ROUTE_WAIT.as_secs() + ); + bench::set_route_state(RouteState::Failed); + } + RouteState::Failed | RouteState::FailedAfterSetup => {} + RouteState::Running | RouteState::Stopped => {} + } } - tracing::warn!( - "benchmark: the route did not start in {} s; timing the run from now", - ROUTE_WAIT.as_secs() - ); - bench::set_route_started(); + r.started = Some(now); + } + if route.is_some() + && r.route_stopped_at.is_none() + && bench::route_state() == RouteState::Stopped + && let Some(started) = r.started + { + r.route_stopped_at = Some(now.duration_since(started).as_secs_f64()); } - r.started.get_or_insert(now); if let Some(last) = r.last.replace(now) { r.frames.add(now.duration_since(last).as_secs_f64()); } @@ -167,13 +252,34 @@ pub(crate) fn finish(shot: Option) -> ! { } } let route = bench::route(); - if let Some(route) = route { - text.push_str(&format!("route={}\n", route.name())); - } + let state = bench::route_state(); with(|r| { - let summary = match route { - Some(_) => r.frames.summary_skipping(0.0), - None => r.frames.summary(), + if state == RouteState::Stopped + && r.route_stopped_at.is_none() + && let Some(started) = r.started + { + r.route_stopped_at = Some(started.elapsed().as_secs_f64()); + } + let accounting = route_accounting(route, state, r.route_stopped_at); + if accounting.ran { + let route = route.expect("checked above"); + text.push_str(&format!("route={}\n", route.name())); + text.push_str(&format!("route_status={}\n", accounting.status)); + if let Some(stopped) = r.route_stopped_at { + text.push_str(&format!("route_stopped_at={stopped:.1}\n")); + } + text.push_str(&format!("route_skip={:.0}\n", accounting.skip)); + } else if accounting.failed { + text.push_str("route_failed=1\n"); + text.push_str(&format!("route_status={}\n", accounting.status)); + if accounting.invalid { + text.push_str("route_invalid=1\n"); + } + } + let summary = if accounting.ran { + r.frames.summary_between(accounting.skip, accounting.end) + } else { + r.frames.summary() }; if let Some(s) = summary { text.push_str(&format!( @@ -262,3 +368,76 @@ fn png(width: u32, height: u32, raw: &[u8]) -> Vec { chunk(&mut png, b"IEND", &[]); png } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn route_accounting_covers_every_state_and_stop_time() { + let none = RouteAccounting { + ran: false, + failed: false, + invalid: false, + status: "none", + skip: 0.0, + end: None, + }; + assert_eq!(route_accounting(None, RouteState::Pending, None), none); + assert_eq!( + route_accounting(Some(Route::Downtown), RouteState::Failed, None), + RouteAccounting { + ran: false, + failed: true, + invalid: false, + status: "failed", + skip: 0.0, + end: None, + } + ); + assert_eq!( + route_accounting(Some(Route::Downtown), RouteState::FailedAfterSetup, None), + RouteAccounting { + ran: false, + failed: true, + invalid: true, + status: "failed_after_setup", + skip: 0.0, + end: None, + } + ); + assert_eq!( + route_accounting(Some(Route::Downtown), RouteState::Running, None), + RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "ran", + skip: 30.0, + end: None, + } + ); + assert_eq!( + route_accounting(Some(Route::Drive), RouteState::Stopped, Some(42.5)), + RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "stopped", + skip: 30.0, + end: Some(42.5), + } + ); + assert_eq!( + route_accounting(Some(Route::Drive), RouteState::Stopped, Some(10.0)), + RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "stopped", + skip: 0.0, + end: Some(10.0), + } + ); + } +} diff --git a/crates/victory-loader/src/bench_route.rs b/crates/victory-loader/src/bench_route.rs index b0449680..8ca0da1f 100644 --- a/crates/victory-loader/src/bench_route.rs +++ b/crates/victory-loader/src/bench_route.rs @@ -1,7 +1,8 @@ //! The benchmark routes (`VICTORY_BENCH_ROUTE=downtown|drive`, see //! [`victory_core::bench::Route`]): the player is taken along a fixed route -//! by the game's own script natives, so every run sees the same places. -//! Off, and nothing hooked, without the variable. +//! by the game's own script natives. Downtown aims to show every run the same +//! places; drive is experimental and its AI may choose different roads. Off, +//! and nothing hooked, without the variable. //! //! The game's scripts call natives through handlers `void(NativeContext*)`, //! arguments and results in 8-byte cells (an entity or a vector takes two). @@ -9,7 +10,8 @@ //! each is checked to be the native expected: a handler opens with //! `cmp dword [rcx+10h], 0` (the argument count) and a `js` to a cold block //! that writes the native's 64-bit id with `mov r64, imm64`, which must be -//! the id asked for. As in ViceHook (MIT), whose approach this follows. +//! the id asked for. As in ViceHook (MIT), whose approach this follows; see +//! `THIRD-PARTY.md`. //! //! The route runs on the game's script update path: PLAYER_PED_ID's handler //! is hooked, as nearly every game script calls it every frame. Once per @@ -18,7 +20,7 @@ //! frames, as many entity flags belong to the script thread that set them), //! the route takes one step. Every native call goes through a guard with an //! exception handler of its own: a fault in the game's code stops the route -//! with a log line instead of the game. +//! with a log line; the game may already be left in an inconsistent state. //! //! Vehicles are made with the game's asynchronous create native, as //! ViceHook's `spawn.cpp` does: the calling script program's token for the @@ -29,7 +31,7 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; -use victory_core::bench::{self, Route}; +use victory_core::bench::{self, Route, RouteState}; use windows_sys::Win32::Foundation::GetLastError; use windows_sys::Win32::System::Diagnostics::Debug::{ CONTEXT, EXCEPTION_RECORD, FlushInstructionCache, RtlUnwindEx, @@ -64,7 +66,6 @@ natives! { GET_FRAME_COUNT = "GET_FRAME_COUNT", 0x030E_FF3E_8820_56A7, 0x3E8_5700; GET_ID_OF_THIS_THREAD = "GET_ID_OF_THIS_THREAD", 0x9410_969F_AAAD_A3CB, 0x446_8FF0; GET_ENTITY_COORDS = "GET_ENTITY_COORDS", 0x6C66_0BB2_5792_A0F9, 0x3C0_9D00; - SET_ENTITY_COORDS = "SET_ENTITY_COORDS", 0xF9F5_FD94_F97B_C258, 0x3C1_3760; SET_ENTITY_COORDS_NO_OFFSET = "SET_ENTITY_COORDS_NO_OFFSET", 0x53E2_5C7A_DC65_CCAE, 0x3C1_36D0; SET_ENTITY_HEADING = "SET_ENTITY_HEADING", 0xBA3B_9AE4_30D4_63F9, 0x3C1_3B80; SET_ENTITY_INVINCIBLE = "SET_ENTITY_INVINCIBLE", 0x3BD9_0347_5A3C_78C9, 0x3C1_4370; @@ -96,31 +97,43 @@ const PLAYER_PED_ID_PROLOGUE: [u8; 14] = [ /// Spawning (1.0.2.1): the strong handle helpers `(holder, object)` and /// `(holder)`, the vehicle create task type (its record hash), the model -/// key of the Dinka Blista, and how many frames a create may take. +/// key of the Dinka Blista, and how long a create may take. const PIN: usize = 0x381_A110; const UNPIN: usize = 0x205_D410; const VEHICLE_TASK: u64 = 0xB160_382E_3F59_FF92; const BLISTA: u64 = 0x2C2A_ED8C_DC20_8C27; -const SPAWN_FRAMES: u32 = 300; +const SPAWN_WAIT: Duration = Duration::from_secs(30); /// The script thread election (frames), as ViceHook's. const ELECT_FRAMES: i64 = 60; const LOST_FRAMES: i64 = 90; -/// How high the player is held over the drive's start while its ground -/// streams in. -const DRIVE_HOLD_Z: f32 = 300.0; +/// How high the player is held over a route's start while its ground streams +/// in. +const HOLD_Z: f32 = 300.0; +/// The time constant of the flight's ground-follow smoothing, in seconds. +const GROUND_SMOOTH: f32 = 0.33; /// From the player's first appearance to the route's start. const SETTLE: Duration = Duration::from_secs(15); /// The drive: a waypoint is reached within this many metres; a leg not -/// done in [`LEG_LIMIT`] is skipped. +/// done in [`LEG_LIMIT`] stops the route, so its figures are not reported +/// as a completed route. The limit is well above the 31-155 s legs seen in +/// the experimental route, so normal traffic does not stop a run. const REACHED_M: f32 = 40.0; -const LEG_LIMIT: Duration = Duration::from_secs(180); +const LEG_LIMIT: Duration = Duration::from_secs(600); /// The longest the drive's start waits for the ground to stream in. const GROUND_WAIT: Duration = Duration::from_secs(60); +/// Whether a drive leg has run past its limit without reaching its goal. +fn leg_stalled(taken: Duration, dist: f32) -> bool { + dist >= REACHED_M && taken > LEG_LIMIT +} + static BASE: AtomicUsize = AtomicUsize::new(0); static TRAMPOLINE: AtomicUsize = AtomicUsize::new(0); static TICKING: AtomicBool = AtomicBool::new(false); +/// Setup has begun to change the world (time, weather, invincibility, +/// position); a failure from here on is not a clean free-roam run. +static SETUP_BEGAN: AtomicBool = AtomicBool::new(false); /// The route ended (stopped after a fault): the hook only passes calls on. static DONE: AtomicBool = AtomicBool::new(false); static LAST_FRAME: AtomicI64 = AtomicI64::new(-1); @@ -128,6 +141,15 @@ static STATE: Mutex> = Mutex::new(None); /// Where the last fault caught by the guard was. static FAULT_AT: AtomicUsize = AtomicUsize::new(0); +/// Clears [`TICKING`] on every exit, including a Rust unwind out of the hook. +struct Ticking; + +impl Drop for Ticking { + fn drop(&mut self) { + TICKING.store(false, Ordering::Release); + } +} + // The guard: `victory_route_guard(f, a, b, out)` calls `f(a, b)`, stores its // rax in `*out` and returns 0; an exception in `f` that nothing below // handles reaches `victory_route_except`, which unwinds to the landing with @@ -235,9 +257,14 @@ struct NativeContext { /// usual shape. /// /// # Safety -/// `at` and the 0x50 bytes after it, and its cold block, are mapped code. -unsafe fn handler_id(at: usize) -> Option { - // SAFETY: as the caller promises. +/// `at` and the 0x50 bytes after it are mapped code in the image of `size` +/// bytes at `base`; its cold block is checked separately before it is read. +unsafe fn handler_id(base: usize, size: usize, at: usize) -> Option { + let image_end = base.checked_add(size)?; + if at < base || at.checked_add(0x50)? > image_end { + return None; + } + // SAFETY: as the caller promises, and checked above. let code = unsafe { std::slice::from_raw_parts(at as *const u8, 0x50) }; let o = code .windows(4) @@ -255,9 +282,13 @@ unsafe fn handler_id(at: usize) -> Option { } } let cold = cold? as usize; - // SAFETY: the cold block is code of the same function (checked by the - // caller to be in the image). - let block = unsafe { std::slice::from_raw_parts(cold as *const u8, 24) }; + if cold < base || cold.checked_add(24)? > image_end { + return None; + } + let mut block = [0u8; 24]; + if !read_bytes(cold as u64, &mut block) { + return None; + } (0..14) .find(|&k| matches!(block[k], 0x48 | 0x49) && (0xb8..=0xbf).contains(&block[k + 1])) .map(|k| { @@ -401,9 +432,11 @@ fn freeze(e: Entity, on: bool) -> Step<()> { fn teleport(e: Entity, x: f32, y: f32, z: f32) -> Step<()> { let v = vector(x, y, z); + // The no-offset form is the one the flight moves with; `SET_ENTITY_COORDS` + // left the player at its spawn point in the drive's start. call( - SET_ENTITY_COORDS, - &[e.0[0], e.0[1], v[0], v[1], 0, 0, 0, 0, f(-1.0)], + SET_ENTITY_COORDS_NO_OFFSET, + &cells_of(&[&e.0, &v, &[0, 0, 0, f(0.0)]]), ) .map(drop) } @@ -602,8 +635,24 @@ fn resolve_strong(handle: u32) -> Option { /// A vehicle being made: the create task, held strongly. struct Spawning { - holder: Box<[u64; 4]>, - frames: u32, + /// The strong handle, if it is still ours to release. + holder: Option>, + since: Instant, + /// The strong handle was released (or the task never got one). + released: bool, +} + +impl Drop for Spawning { + fn drop(&mut self) { + if !self.released { + // A task still running stays held: releasing it corrupts the + // heap, and the helper may still refer to the holder, so keep + // both alive (a small leak) rather than free the box. + if let Some(holder) = self.holder.take() { + std::mem::forget(holder); + } + } + } } /// Starts making a Blista at (x, y, z) facing `heading`. @@ -633,42 +682,59 @@ fn spawn_blista(x: f32, y: f32, z: f32, heading: f32) -> Step { } // SAFETY: the game's strong-handle helper, with a holder of ours and // the task the create native returned. - unsafe { guarded(base + PIN, holder.as_mut_ptr() as usize, task as usize) } - .map_err(|f| RouteError::Fault("holding the create task", f))?; + if let Err(f) = unsafe { guarded(base + PIN, holder.as_mut_ptr() as usize, task as usize) } { + // The helper may have written a handle before it faulted; keep the + // holder alive rather than free memory the game might still mean. + std::mem::forget(holder); + return Err(RouteError::Fault("holding the create task", f)); + } if holder[0] as u32 == 0 { return Err(RouteError::Failed( "the vehicle create task could not be held".into(), )); } - Ok(Spawning { holder, frames: 0 }) + Ok(Spawning { + holder: Some(holder), + since: Instant::now(), + released: false, + }) } impl Spawning { /// The vehicle, once made. Task layout: status byte +0x12 (5 done), /// +0x20 error (0 when none), +0x28 the entity reference. fn poll(&mut self) -> Step> { - self.frames += 1; let mut q = [0u64; 8]; - let done = resolve_strong(self.holder[0] as u32).is_some_and(|at| { - // SAFETY: plain bytes; the array is ours. - let bytes = unsafe { std::slice::from_raw_parts_mut(q.as_mut_ptr().cast::(), 64) }; - read_bytes(at, bytes) && (q[2] >> 16) & 0xff == 5 - }); + let done = self + .holder + .as_ref() + .and_then(|holder| resolve_strong(holder[0] as u32)) + .is_some_and(|at| { + // SAFETY: plain bytes; the array is ours. + let bytes = + unsafe { std::slice::from_raw_parts_mut(q.as_mut_ptr().cast::(), 64) }; + read_bytes(at, bytes) && (q[2] >> 16) & 0xff == 5 + }); if !done { - if self.frames > SPAWN_FRAMES { - // A task still running stays held (a small leak): releasing - // a running task corrupts the heap. + if self.since.elapsed() > SPAWN_WAIT { return Err(RouteError::Failed(format!( - "the vehicle was not made in {SPAWN_FRAMES} frames" + "the vehicle was not made in {} s", + SPAWN_WAIT.as_secs() ))); } return Ok(None); } let base = BASE.load(Ordering::Relaxed); + let Some(holder) = self.holder.as_mut() else { + return Err(RouteError::Failed( + "the vehicle create task lost its holder".into(), + )); + }; // SAFETY: the game's release helper, with our holder; only once the // task is done (an early release corrupted the heap). - unsafe { guarded(base + UNPIN, self.holder.as_mut_ptr() as usize, 0) } + unsafe { guarded(base + UNPIN, holder.as_mut_ptr() as usize, 0) } .map_err(|f| RouteError::Fault("releasing the create task", f))?; + self.released = true; if q[4] != 0 { return Err(RouteError::Failed("the game refused the vehicle".into())); } @@ -691,7 +757,9 @@ enum Phase { Settle(Instant), /// The route's first steps. Setup, - /// downtown: the Blista being made near the player. + /// downtown: the player held at the corner until the ground loads. + FlyGround(Instant), + /// downtown: the Blista being made at the corner. FlySpawn(Spawning), Fly(Flight), /// drive: the player held high over the start until the ground loads. @@ -705,6 +773,8 @@ enum Phase { struct Flight { mover: Entity, start: Instant, + /// The last frame's time, for time-based ground smoothing. + last: Instant, /// The smoothed ground height (none until first found). ground: Option, laps: u32, @@ -731,6 +801,10 @@ struct Driver { /// The elected game script thread, and the frame it was last seen. chosen: Option<(i64, i64)>, election: Option<(i64, Vec<(i64, i64, i64)>)>, + /// The route has started (the vehicle is ready and the route clock is on). + started: bool, + /// The elected thread ended after the route started. + thread_lost: bool, } impl Driver { @@ -740,6 +814,8 @@ impl Driver { phase: Phase::WaitPlayer, chosen: None, election: None, + started: false, + thread_lost: false, } } @@ -754,6 +830,10 @@ impl Driver { if frame - seen < LOST_FRAMES { return false; } + if self.started || SETUP_BEGAN.load(Ordering::Relaxed) { + self.thread_lost = true; + return false; + } tracing::info!( thread = id, "bench route: the game script thread stopped; electing another" @@ -800,7 +880,7 @@ impl Driver { if player()?.valid() { tracing::info!( route = self.route.name(), - "bench route: the player is in the world; the route starts in {} s", + "bench route: the player is in the world; setup starts in {} s", SETTLE.as_secs() ); Phase::Settle(Instant::now()) @@ -811,19 +891,37 @@ impl Driver { Phase::Settle(since) if since.elapsed() < SETTLE => Phase::Settle(since), Phase::Settle(_) => Phase::Setup, Phase::Setup => self.setup()?, + Phase::FlyGround(since) => { + let (x, y) = bench::DOWNTOWN_CORNER; + let v = vector(x, y, HOLD_Z - 200.0); + call(REQUEST_COLLISION_AT_COORD, &[v[0], v[1]])?; + match ground_z(x, y)? { + Some(z) => { + // The player beside the corner, the car on it. + let me = player()?; + teleport(me, x + 3.0, y, z + 1.0)?; + freeze(me, false)?; + Phase::FlySpawn(spawn_blista(x, y, z + 0.5, 0.0)?) + } + None if since.elapsed() > GROUND_WAIT => { + return Err(RouteError::Failed(format!( + "the ground at the corner did not load in {} s", + GROUND_WAIT.as_secs() + ))); + } + None => Phase::FlyGround(since), + } + } Phase::FlySpawn(mut spawning) => { let me = player()?; - match spawning.poll() { - Ok(None) => Phase::FlySpawn(spawning), - Ok(Some(car)) => { + match spawning.poll()? { + None => Phase::FlySpawn(spawning), + Some(car) => { seat(me, car)?; - Phase::Fly(start_flight(car)?) + let flight = start_flight(car)?; + self.started = true; + Phase::Fly(flight) } - Err(e @ RouteError::Failed(_)) => { - tracing::warn!("bench route: downtown: {e}; flying the player on foot"); - Phase::Fly(start_flight(me)?) - } - Err(e) => return Err(e), } } Phase::Fly(mut flight) => { @@ -832,7 +930,7 @@ impl Driver { } Phase::DriveGround(since) => { let (x, y) = bench::DRIVE_WAYPOINTS[0]; - let v = vector(x, y, DRIVE_HOLD_Z - 200.0); + let v = vector(x, y, HOLD_Z - 200.0); call(REQUEST_COLLISION_AT_COORD, &[v[0], v[1]])?; match ground_z(x, y)? { Some(z) => { @@ -865,7 +963,12 @@ impl Driver { "bench route: drive: start at ({x:.0}, {y:.0}), a loop of {} waypoints, the game's AI driving with traffic", bench::DRIVE_WAYPOINTS.len() ); - bench::set_route_started(); + if !bench::try_start_route() { + return Err(RouteError::Failed( + "the benchmark route state changed before start".into(), + )); + } + self.started = true; let now = Instant::now(); Phase::Drive(Drive { car, @@ -891,20 +994,26 @@ impl Driver { } fn setup(&mut self) -> Step { + if bench::route_state() != RouteState::Pending { + return Err(RouteError::Failed( + "the benchmark route state changed before setup".into(), + )); + } + SETUP_BEGAN.store(true, Ordering::Relaxed); fix_time_and_weather()?; let me = player()?; set_invincible(me)?; Ok(match self.route { Route::Downtown => { - let (x, y, z) = coords(me)?; - match spawn_blista(x + 5.0, y, z + 0.5, 0.0) { - Ok(spawning) => Phase::FlySpawn(spawning), - Err(e @ RouteError::Failed(_)) => { - tracing::warn!("bench route: downtown: {e}; flying the player on foot"); - Phase::Fly(start_flight(me)?) - } - Err(e) => return Err(e), - } + let (x, y) = bench::DOWNTOWN_CORNER; + // Held at the corner while the area streams in; the collision + // is asked for each frame until the ground is found. + freeze(me, true)?; + teleport(me, x, y, HOLD_Z)?; + tracing::info!( + "bench route: downtown: waiting for the ground at ({x:.0}, {y:.0}) to load" + ); + Phase::FlyGround(Instant::now()) } Route::Drive => { let (x, y) = bench::DRIVE_WAYPOINTS[0]; @@ -912,7 +1021,7 @@ impl Driver { // up its collision never loaded); the collision is asked for // each frame until the ground is found. freeze(me, true)?; - teleport(me, x, y, DRIVE_HOLD_Z)?; + teleport(me, x, y, HOLD_Z)?; tracing::info!( "bench route: drive: waiting for the ground at ({x:.0}, {y:.0}) to load" ); @@ -922,8 +1031,8 @@ impl Driver { } } -/// The downtown flight's start: `mover` (the car, or the player) made -/// invincible, without collision and frozen in place; then moved each frame. +/// The downtown flight's start: `mover` made invincible, without collision +/// and frozen in place; then moved each frame. fn start_flight(mover: Entity) -> Step { set_invincible(mover)?; call( @@ -937,6 +1046,11 @@ fn start_flight(mover: Entity) -> Step { ], )?; freeze(mover, true)?; + if !bench::try_start_route() { + return Err(RouteError::Failed( + "the benchmark route state changed before start".into(), + )); + } let (x, y) = bench::DOWNTOWN_CORNER; tracing::info!( "bench route: downtown: start (corner {x:.0} {y:.0}, {:.0} m square, {:.0} m up, {:.0} m/s)", @@ -944,10 +1058,11 @@ fn start_flight(mover: Entity) -> Step { bench::DOWNTOWN_UP, bench::DOWNTOWN_SPEED ); - bench::set_route_started(); + let now = Instant::now(); Ok(Flight { mover, - start: Instant::now(), + start: now, + last: now, ground: None, laps: 0, }) @@ -956,12 +1071,16 @@ fn start_flight(mover: Entity) -> Step { impl Flight { /// One frame of the flight, as ViceMenu's `flybench`. fn step(&mut self) -> Step<()> { + let now = Instant::now(); let t = self.start.elapsed().as_secs_f32(); + let dt = now.duration_since(self.last).as_secs_f32(); + self.last = now; let ((x, y), heading, laps) = bench::downtown_at(t); - // Follow the ground, smoothed; the last height where it has not - // streamed in yet. + // Follow the ground, smoothed over time; the last height where it + // has not streamed in yet. if let Some(g) = ground_z(x, y)? { - self.ground = Some(self.ground.map_or(g, |h| h + (g - h) * 0.05)); + let alpha = 1.0 - (-dt / GROUND_SMOOTH).exp(); + self.ground = Some(self.ground.map_or(g, |h| h + (g - h) * alpha)); } let z = bench::downtown_height(self.ground); let p = vector(x, y, z); @@ -1040,15 +1159,10 @@ impl Drive { let (x, y, _) = coords(car)?; let dist = ((x - gx).powi(2) + (y - gy).powi(2)).sqrt(); let taken = now.duration_since(self.leg_start); - if dist < REACHED_M || taken > LEG_LIMIT { + if dist < REACHED_M { tracing::info!( - "bench route: drive: leg {} to ({gx:.0}, {gy:.0}) {} in {:.0} s", + "bench route: drive: leg {} to ({gx:.0}, {gy:.0}) reached in {:.0} s", self.legs, - if dist < REACHED_M { - "reached" - } else { - "skipped" - }, taken.as_secs_f32() ); self.legs += 1; @@ -1064,6 +1178,12 @@ impl Drive { } self.leg_start = now; self.tasked = false; + } else if leg_stalled(taken, dist) { + return Err(RouteError::Failed(format!( + "the drive's leg {} to ({gx:.0}, {gy:.0}) was not reached in {} s", + self.legs, + LEG_LIMIT.as_secs() + ))); } if now.duration_since(self.logged) > Duration::from_secs(30) { let speed = f32::from_bits(call(GET_ENTITY_SPEED, &[car.0[0], car.0[1]])?[0] as u32); @@ -1087,6 +1207,10 @@ fn int_result(n: Native) -> Step { } /// Once per game frame, in the elected script thread: one step of the route. +/// +/// This runs on every PLAYER_ENTITY call, before the same-frame early-out, so +/// route runs include the two guarded frame/thread queries per call. Compare +/// route runs with route runs, not with free roam. fn tick() { let frame = match int_result(GET_FRAME_COUNT) { Ok(f) => f, @@ -1104,7 +1228,16 @@ fn tick() { let Some(driver) = state.as_mut() else { return; }; - if !driver.elected(frame, thread) { + let elected = driver.elected(frame, thread); + if driver.thread_lost { + driver.phase = Phase::Stopped; + drop(state); + stop(&RouteError::Failed( + "the game script thread ended after the route started".into(), + )); + return; + } + if !elected { return; } LAST_FRAME.store(frame, Ordering::Relaxed); @@ -1115,15 +1248,47 @@ fn tick() { } } -/// Ends the route after `e`; a benchmark run goes on, timed from now if -/// the route had not started. +/// Ends the route after `e`: a run that had started keeps its route label +/// and records a stop; a run that had not started is a failed route and the +/// benchmark continues as a normal one. fn stop(e: &RouteError) { if !DONE.swap(true, Ordering::Relaxed) { tracing::warn!("bench route: stopped: {e}"); - bench::set_route_started(); + let setup = SETUP_BEGAN.load(Ordering::Relaxed); + match bench::route_state() { + RouteState::Running => bench::set_route_state(RouteState::Stopped), + RouteState::Pending | RouteState::Failed if setup => { + bench::set_route_state(RouteState::FailedAfterSetup) + } + RouteState::Pending | RouteState::Failed => bench::set_route_state(RouteState::Failed), + RouteState::FailedAfterSetup | RouteState::Stopped => {} + } + // Best effort: put the player back under the game's control after any + // stop once setup began. It may still be in the route's car, or have + // been left in the air; the route may also have stopped on a fault. + if setup { + release_player(); + } } } +/// Undoes the player's freeze and collision changes, ignoring errors: the +/// route may already be in a bad state. The route's mover or car is not +/// restored here. +fn release_player() { + let Ok(me) = player() else { + return; + }; + if !me.valid() { + return; + } + let _ = call( + SET_ENTITY_COLLISION, + &[me.0[0], me.0[1], flag(true), flag(true), flag(true)], + ); + let _ = freeze(me, false); +} + /// In front of PLAYER_PED_ID's handler. unsafe extern "system" fn player_ped_id(ctx: *mut NativeContext) { // SAFETY: the game passes its native context. @@ -1134,10 +1299,10 @@ unsafe extern "system" fn player_ped_id(ctx: *mut NativeContext) { .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) .is_ok() { + let _ticking = Ticking; if std::panic::catch_unwind(tick).is_err() { stop(&RouteError::Failed("a step panicked".into())); } - TICKING.store(false, Ordering::Release); } let original = TRAMPOLINE.load(Ordering::Relaxed); // SAFETY: the trampoline runs the handler's displaced head, then the @@ -1173,7 +1338,7 @@ pub unsafe fn apply_asked(base: usize, size: usize) { }; let give_up = |why: &str| { tracing::warn!(route = %asked, "bench route: off: {why}"); - bench::set_route_started(); + bench::set_route_state(RouteState::Failed); }; let Some(route) = bench::route() else { return give_up("not a route (downtown or drive)"); @@ -1190,9 +1355,9 @@ pub unsafe fn apply_asked(base: usize, size: usize) { if n.rva + 0x100 > size { return give_up("a native handler is outside the image"); } - // SAFETY: inside the mapped image (checked above); the cold block a - // handler jumps to is near it, also in the image's code. - let id = unsafe { handler_id(base + n.rva) }; + // SAFETY: inside the mapped image (checked above); handler_id checks + // the cold block it follows is inside the image too. + let id = unsafe { handler_id(base, size, base + n.rva) }; if id != Some(n.id) { return give_up(&format!("{} is not where 1.0.2.1 has it", n.name)); } @@ -1270,4 +1435,104 @@ mod tests { assert_eq!(v[1], u64::from(3.0f32.to_bits())); assert_eq!(int(-1), 0xffff_ffff); } + + #[test] + fn a_handler_reads_the_id_in_its_cold_block() { + let mut code = vec![0u8; 0x60]; + code[..4].copy_from_slice(&[0x83, 0x79, 0x10, 0x00]); + code[4..6].copy_from_slice(&[0x0f, 0x88]); + // js rel32 from after the six-byte instruction to 0x40. + code[6..10].copy_from_slice(&(0x40i32 - 10).to_le_bytes()); + code[0x40..0x42].copy_from_slice(&[0x48, 0xb8]); + let id = 0x1122_3344_5566_7788u64; + code[0x42..0x4a].copy_from_slice(&id.to_le_bytes()); + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, Some(id)); + } + + #[test] + fn a_short_jump_and_a_second_register_encode_the_same_id() { + for (jump, opcode) in [ + (vec![0x78, (0x40i8 - 6) as u8], [0x48u8, 0xb8]), + (vec![0x0f, 0x88, 0x36, 0x00, 0x00, 0x00], [0x49, 0xba]), + ] { + let mut code = vec![0u8; 0x60]; + code[..4].copy_from_slice(&[0x83, 0x79, 0x10, 0x00]); + code[4..4 + jump.len()].copy_from_slice(&jump); + code[0x40..0x42].copy_from_slice(&opcode); + let id = 0x8877_6655_4433_2211u64; + code[0x42..0x4a].copy_from_slice(&id.to_le_bytes()); + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, Some(id)); + } + } + + #[test] + fn a_cold_block_outside_the_image_is_refused() { + let mut code = vec![0u8; 0x60]; + code[..4].copy_from_slice(&[0x83, 0x79, 0x10, 0x00]); + code[4..6].copy_from_slice(&[0x0f, 0x88]); + // js rel32 to 0x1000, well outside this 0x60-byte image. + code[6..10].copy_from_slice(&(0x1000i32 - 10).to_le_bytes()); + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, None); + } + + #[test] + fn a_handler_without_the_usual_head_is_refused() { + let code = vec![0u8; 0x60]; + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, None); + } + + #[test] + fn election_needs_sixty_frames_and_replaces_a_lost_thread() { + let mut driver = Driver::new(Route::Downtown); + for frame in 0..60 { + assert!(!driver.elected(frame, 7)); + } + assert!(driver.elected(60, 7)); + assert!(driver.elected(61, 7)); + assert!(!driver.elected(62, 8)); + assert!(!driver.elected(151, 8)); + for frame in 152..=210 { + assert!(!driver.elected(frame, 8)); + } + assert!(driver.elected(211, 8)); + } + + #[test] + fn losing_the_thread_after_start_is_reported() { + let mut driver = Driver::new(Route::Downtown); + for frame in 0..60 { + assert!(!driver.elected(frame, 7)); + } + assert!(driver.elected(60, 7)); + assert!(driver.elected(61, 7)); + driver.started = true; + assert!(!driver.elected(151, 8)); + assert!(driver.thread_lost); + } + + #[test] + fn a_fault_in_a_guarded_call_is_caught() { + unsafe extern "system" fn fault(_: usize, _: usize) -> u64 { + // SAFETY: deliberately unmapped; the guard is what is tested. + unsafe { std::ptr::read_volatile(1 as *const u64) } + } + // SAFETY: deliberately faults; the guard catches it. + let caught = unsafe { guarded(fault as *const () as usize, 0, 0) }; + assert!(matches!(caught, Err(Fault(_)))); + } + + #[test] + fn a_leg_is_stalled_only_after_the_limit_and_out_of_reach() { + assert!(!leg_stalled(Duration::from_secs(599), 100.0)); + assert!(leg_stalled(Duration::from_secs(601), 100.0)); + assert!(!leg_stalled(Duration::from_secs(601), REACHED_M - 1.0)); + } } diff --git a/run.sh b/run.sh index c6d20f67..97df3e01 100755 --- a/run.sh +++ b/run.sh @@ -137,6 +137,16 @@ if [ "${VICTORY_DSP_DUMP:-}" = 1 ]; then mkdir -p "$root/local/dsp"; export VICT # on the card and the picture flickers less (RESEARCH-FRAME-RATE-HOST.md (in the history, commit 71955de), # section 3.3). if [ "${NOSAM:-0}" = 1 ]; then export RADV_PERFTEST="${RADV_PERFTEST:+$RADV_PERFTEST,}nosam"; fi +if [ "$mode" = play ] && [ -n "${VICTORY_BENCH_ROUTE:-}" ]; then + route=${VICTORY_BENCH_ROUTE} + route=${route#"${route%%[![:space:]]*}"} + route=${route%"${route##*[![:space:]]}"} + route=${route,,} + case "$route" in + downtown|drive) ;; + *) echo "VICTORY_BENCH_ROUTE must be downtown or drive (got '$VICTORY_BENCH_ROUTE')"; exit 1;; + esac +fi # A benchmark run (VICTORY_BENCH=rt|nort): PortWatch's settings over the # user's for this run only. bench= @@ -146,6 +156,8 @@ if [ "$mode" = play ] && [[ ${VICTORY_BENCH:-} =~ ^(rt|nort)$ ]]; then VICTORY_LOD_SCALE VICTORY_SMALL_CULL VICTORY_VEHICLE_LOD_BIAS VICTORY_QUAD_GUARD VICTORY_BVH_HARDWARE \ VICTORY_PLACED_COPIED VICTORY_KEEP_GPU_WRITTEN VICTORY_WARM LSFGVK_PROFILE LSFG_PROCESS export CONSOLE=series-x VICTORY_FSR=quality VICTORY_OUTPUT=3840x2160 VICTORY_SKIP_BINK=1 VICTORY_PANEL=full + # A play cap (run.conf or the title's settings) must not limit a benchmark. + export VICTORY_FRAME_INTERVAL_MS=0 export VICTORY_BVH_BUILDER=$([ "$bench" = rt ] && echo 1 || echo 0) export VICTORY_BENCH_MINUTES=${VICTORY_BENCH_MINUTES:-5} benchdir=$root/local/benchmark/$(date +%Y%m%d-%H%M%S)-$bench diff --git a/tools/bench-results.sh b/tools/bench-results.sh index 144fb418..c327379b 100755 --- a/tools/bench-results.sh +++ b/tools/bench-results.sh @@ -28,9 +28,45 @@ ram=$(awk '/MemTotal/{printf "%.0f GB", $2/1048576}' /proc/meminfo) os=$(. /etc/os-release 2>/dev/null; echo "${PRETTY_NAME:-Linux}") version=$(git -C "$root" log -1 --format='%h (%cs)' 2>/dev/null) git -C "$root" diff --quiet HEAD 2>/dev/null || version="$version, with local changes" +if [ -n "${s[route]:-}" ]; then + route_skip=${s[route_skip]:-30} + if [ "$route_skip" = 0 ]; then + measured_note="no route warm-up is left out" + else + measured_note="the first ${route_skip} s of the route are left out" + fi + route_display=${s[route]} + if [ "${s[route_status]:-}" = stopped ]; then + banner="INCOMPLETE: route stopped at ${s[route_stopped_at]:-?} s after start; figures are cut at the stop." + else + banner="" + fi + # The drive route is experimental: its path and scenes vary between runs. + if [ "${s[route]}" = drive ]; then + if [ -n "$banner" ]; then + banner="$banner +EXPERIMENTAL: drive figures are not comparable; do not submit them." + else + banner="EXPERIMENTAL: drive figures are not comparable; do not submit them." + fi + fi +elif [ "${s[route_invalid]:-0}" = 1 ] || [ "${s[route_status]:-}" = failed_after_setup ]; then + measured_note="INVALID RUN: the route failed after setup; the run is not comparable and should not be submitted" + route_display="none (route failed after setup)" + banner="INVALID RUN: route failed after setup; do not submit these figures." +elif [ "${s[route_failed]:-0}" = 1 ]; then + measured_note="the route failed to start; the run is timed as a normal benchmark" + route_display="none (route failed to start)" + banner="" +else + measured_note="the first minute is left out of runs of 2 min or more" + route_display="none (free roam)" + banner="" +fi cat > "$dir/bench_results.txt" <