upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com>2026-12-02 14:05:38 -0500
committerubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com>2026-12-02 14:05:38 -0500
commitab3bf6eceeb3f87807f71a0fd42872d503a0a208 (patch)
tree12e11a0f52b51159d7bdbe678e3c56065d3840fe
parentb41763227aeed2d23c98af84bcbc1bddc7acdc90 (diff)
Uncap D3D12 rendering and use measured simulation stepscodex/d3d12-uncapped-simulation
-rw-r--r--d3d12/README.md10
-rw-r--r--d3d12/crates/leonida-gpu/src/frame.rs71
-rw-r--r--d3d12/crates/leonida-loader/src/hooks.rs132
-rw-r--r--d3d12/crates/leonida-loader/src/windows.rs5
-rw-r--r--docs/vi_patch.md22
5 files changed, 190 insertions, 50 deletions
diff --git a/d3d12/README.md b/d3d12/README.md
index 98c58609b..c3aad14a2 100644
--- a/d3d12/README.md
+++ b/d3d12/README.md
@@ -348,12 +348,12 @@ still reaches.
348- **DLSS frame generation** (NVIDIA Streamline), 2x to 6x, from the menu. The 348- **DLSS frame generation** (NVIDIA Streamline), 2x to 6x, from the menu. The
349 amount changes while playing. Frames are only generated while the game's 349 amount changes while playing. Frames are only generated while the game's
350 window has the focus. 350 window has the focus.
351- **Frame rate cap**: the title asks for 30 frames a second on its own; the 351- **Frame rate cap** lets you choose the title's 60 FPS interval, 30, 60,
352 loader's frame-rate patch, always on, makes that 60 352 120 or `NONE` in F1. On 1.0.2.1 the runtime handles pacing and the game
353 ([docs/vi_patch.md](../docs/vi_patch.md)), and the menu's FRAME RATE CAP 353 and camera clocks use the measured frame duration.
354 changes it (30, 60, 120 or none). 354 [Frame timing details](../docs/vi_patch.md#uncapped-rendering-and-simulation-time)
355- **Game patches after VI-Patch** ([docs/vi_patch.md](../docs/vi_patch.md)): 355- **Game patches after VI-Patch** ([docs/vi_patch.md](../docs/vi_patch.md)):
356 60 frames a second always; no vignette by `LEONIDA_VIPATCH_NO_VIGNETTE=1` 356 60 FPS title-requested interval, and no vignette by `LEONIDA_VIPATCH_NO_VIGNETTE=1`
357 or the menu. 357 or the menu.
358- **Real ray tracing**, off by default: `-RayTracing` or the menu. On this 358- **Real ray tracing**, off by default: `-RayTracing` or the menu. On this
359 renderer the title's structure builder runs on NVIDIA (53 programs), and 359 renderer the title's structure builder runs on NVIDIA (53 programs), and
diff --git a/d3d12/crates/leonida-gpu/src/frame.rs b/d3d12/crates/leonida-gpu/src/frame.rs
index 43749f627..a24f9a181 100644
--- a/d3d12/crates/leonida-gpu/src/frame.rs
+++ b/d3d12/crates/leonida-gpu/src/frame.rs
@@ -5,6 +5,7 @@
5//! kind never end on the same tick: the title polls the origin 5//! kind never end on the same tick: the title polls the origin
6//! with "token on time-out" (starting its next frame at once) and is paced 6//! with "token on time-out" (starting its next frame at once) and is paced
7//! by a blocking wait for the flip before each present. 7//! by a blocking wait for the flip before each present.
8//! With the cap off, each event completes without waiting for a tick.
8//! 9//!
9//! shortcut: event offsets are ignored (every event is at the tick); tie 10//! shortcut: event offsets are ignored (every event is at the tick); tie
10//! the clock to presentation if a title paces by them. 11//! the clock to presentation if a title paces by them.
@@ -24,17 +25,17 @@ const ORIGIN: u32 = 0;
24/// frame early). 25/// frame early).
25const TOKEN_ON_TIMEOUT: u32 = 2; 26const TOKEN_ON_TIMEOUT: u32 = 2;
26const SIXTIETH: Duration = Duration::from_micros(16_667); 27const SIXTIETH: Duration = Duration::from_micros(16_667);
28const CAP_UNREAD: i64 = -2;
29const CAP_NONE: i64 = -1;
27 30
28/// LOCAL (11/26): `LEONIDA_FPS_CAP`. Unset: the title's own interval (60 frames a second with the 31/// `LEONIDA_FPS_CAP` is live. Unset uses the title's interval, `0` skips pacing, and a positive rate has
29/// loader's frame-rate patch, `leonida-loader`'s `vipatch.rs`, which is always on; 30 without it); 32/// a frame interval in microseconds. Internally, zero means the title's interval.
30/// `0`: none (ticks half a millisecond apart); `n`: n frames a second. The F1 menu 33static CAP_US: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(CAP_UNREAD);
31/// changes it while running ([`set_cap`]). -1: not read yet; 0: the title's; else microseconds.
32static CAP_US: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1);
33 34
34fn parse_cap(value: Option<&str>) -> i64 { 35fn parse_cap(value: Option<&str>) -> i64 {
35 match value.map(str::trim).and_then(|v| v.parse::<u32>().ok()) { 36 match value.map(str::trim).and_then(|v| v.parse::<u32>().ok()) {
36 None => 0, 37 None => 0,
37 Some(0) => 500, 38 Some(0) => CAP_NONE,
38 Some(n) => (1_000_000 / i64::from(n)).max(500), 39 Some(n) => (1_000_000 / i64::from(n)).max(500),
39 } 40 }
40} 41}
@@ -42,21 +43,25 @@ fn parse_cap(value: Option<&str>) -> i64 {
42/// The interval ticks are apart: the title's, or the cap's when one is set. 43/// The interval ticks are apart: the title's, or the cap's when one is set.
43fn capped(asked: Duration) -> Duration { 44fn capped(asked: Duration) -> Duration {
44 let mut us = CAP_US.load(Ordering::Relaxed); 45 let mut us = CAP_US.load(Ordering::Relaxed);
45 if us < 0 { 46 if us == CAP_UNREAD {
46 us = parse_cap(std::env::var("LEONIDA_FPS_CAP").ok().as_deref()); 47 us = parse_cap(std::env::var("LEONIDA_FPS_CAP").ok().as_deref());
47 CAP_US.store(us, Ordering::Relaxed); 48 CAP_US.store(us, Ordering::Relaxed);
48 } 49 }
49 if us == 0 { asked } else { Duration::from_micros(us as u64) } 50 match us {
51 CAP_NONE => Duration::ZERO,
52 0 => asked,
53 us => Duration::from_micros(us as u64),
54 }
50} 55}
51 56
52/// The cap changed (the F1 menu): the clock goes on from now with the new interval. 57/// The cap changed (the F1 menu): the clock goes on from now with the new interval.
53#[allow(dead_code)] 58#[allow(dead_code)]
54pub(crate) fn set_cap(value: &str) { 59pub(crate) fn set_cap(value: &str) {
60 let mut clock = clock();
55 CAP_US.store(parse_cap(Some(value).filter(|v| !v.is_empty())), Ordering::Relaxed); 61 CAP_US.store(parse_cap(Some(value).filter(|v| !v.is_empty())), Ordering::Relaxed);
56 let first = LAST.iter().map(|t| t.load(Ordering::Relaxed)).max().unwrap_or(0); 62 if let Some(c) = clock.as_mut() {
57 if let Some(c) = clock().as_mut() {
58 c.start = Instant::now(); 63 c.start = Instant::now();
59 c.first = first; 64 c.first = last_tick();
60 c.interval = capped(c.asked); 65 c.interval = capped(c.asked);
61 tracing::info!(asked = ?c.asked, interval = ?c.interval, "frame interval: the cap changed"); 66 tracing::info!(asked = ?c.asked, interval = ?c.interval, "frame interval: the cap changed");
62 } 67 }
@@ -66,7 +71,7 @@ struct Clock {
66 start: Instant, 71 start: Instant,
67 /// What the title asked for. 72 /// What the title asked for.
68 asked: Duration, 73 asked: Duration,
69 /// What ticks are apart ([`capped`]). 74 /// What ticks are apart ([`capped`]), or zero when there's no cap.
70 interval: Duration, 75 interval: Duration,
71 /// The tick number at `start` (ticks go on across interval changes). 76 /// The tick number at `start` (ticks go on across interval changes).
72 first: u64, 77 first: u64,
@@ -89,24 +94,19 @@ pub(crate) extern "system" fn set_interval(
89 _period: u32, 94 _period: u32,
90 _flags: u32, 95 _flags: u32,
91) -> HRESULT { 96) -> HRESULT {
92 let interval = match length { 97 let asked = match length {
93 0 => SIXTIETH, 98 0 => SIXTIETH,
94 us => Duration::from_micros(u64::from(us)), 99 us => Duration::from_micros(u64::from(us)),
95 }; 100 };
96 let asked = interval; 101 let mut clock = clock();
97 let interval = capped(asked); 102 let interval = capped(asked);
98 tracing::info!(?asked, ?interval, "frame interval (LEONIDA_FPS_CAP: unset the title's, 0 none, n frames a second)"); 103 tracing::info!(?asked, ?interval, "frame interval (LEONIDA_FPS_CAP: unset the title's, 0 none, n frames a second)");
99 // A new interval starts from now, after the last tick handed out. 104 // A new interval starts from now, after the last tick handed out.
100 let first = LAST 105 *clock = Some(Clock {
101 .iter()
102 .map(|t| t.load(Ordering::Relaxed))
103 .max()
104 .unwrap_or(0);
105 *clock() = Some(Clock {
106 start: Instant::now(), 106 start: Instant::now(),
107 asked, 107 asked,
108 interval, 108 interval,
109 first, 109 first: last_tick(),
110 }); 110 });
111 S_OK 111 S_OK
112} 112}
@@ -137,6 +137,10 @@ pub(crate) fn test_advance() {
137/// wait for it ended on. 137/// wait for it ended on.
138static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; 138static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
139 139
140fn last_tick() -> u64 {
141 LAST.iter().map(|t| t.load(Ordering::Relaxed)).max().unwrap_or(0)
142}
143
140fn last(kind: u32) -> &'static AtomicU64 { 144fn last(kind: u32) -> &'static AtomicU64 {
141 &LAST[(kind as usize).min(LAST.len() - 1)] 145 &LAST[(kind as usize).min(LAST.len() - 1)]
142} 146}
@@ -152,8 +156,11 @@ fn next_tick(kind: u32) -> (u64, Duration) {
152 interval: capped(SIXTIETH), 156 interval: capped(SIXTIETH),
153 first: 0, 157 first: 0,
154 }); 158 });
159 if c.interval.is_zero() {
160 return (last(kind).fetch_add(1, Ordering::Relaxed) + 1, Duration::ZERO);
161 }
155 let elapsed = c.start.elapsed().as_nanos(); 162 let elapsed = c.start.elapsed().as_nanos();
156 let interval = c.interval.as_nanos().max(1); 163 let interval = c.interval.as_nanos();
157 let tick = 164 let tick =
158 (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); 165 (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1);
159 let at = u128::from(tick - c.first) * interval; 166 let at = u128::from(tick - c.first) * interval;
@@ -197,7 +204,9 @@ pub(crate) extern "system" fn wait(
197 std::thread::sleep(limit); 204 std::thread::sleep(limit);
198 TIMEOUT 205 TIMEOUT
199 } else { 206 } else {
200 std::thread::sleep(wait); 207 if !wait.is_zero() {
208 std::thread::sleep(wait);
209 }
201 last(kind).fetch_max(tick, Ordering::Relaxed); 210 last(kind).fetch_max(tick, Ordering::Relaxed);
202 S_OK 211 S_OK
203 }; 212 };
@@ -256,6 +265,7 @@ mod tests {
256 #[test] 265 #[test]
257 fn waits_end_on_ticks_and_count_frames() { 266 fn waits_end_on_ticks_and_count_frames() {
258 let null = std::ptr::null(); 267 let null = std::ptr::null();
268 set_cap("");
259 assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK); 269 assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK);
260 let mut first = 0; 270 let mut first = 0;
261 assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK); 271 assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK);
@@ -309,5 +319,20 @@ mod tests {
309 // Even when a flip wait begins on the tick another just ended on. 319 // Even when a flip wait begins on the tick another just ended on.
310 let (tick, _) = next_tick(FLIP); 320 let (tick, _) = next_tick(FLIP);
311 assert!(tick > flips[3]); 321 assert!(tick > flips[3]);
322
323 // None makes the event immediately available even for a poll. Each origin wait still gives a new token.
324 set_cap("0");
325 let list = std::ptr::null();
326 assert_eq!(wait(null, ORIGIN, 0, list, 0, &mut token), S_OK);
327 let first_uncapped = token;
328 assert_eq!(wait(null, FLIP, 0, list, 0, &mut token), S_OK);
329 assert_eq!(token, first_uncapped);
330 assert_eq!(wait(null, ORIGIN, 0, list, 0, &mut token), S_OK);
331 assert_eq!(token, first_uncapped + 1);
332
333 // Changing back to the title's cap resumes waits from the most recent event.
334 set_cap("");
335 assert_eq!(wait(null, FLIP, 0, list, 0, &mut token), TIMEOUT);
336 assert!(next_tick(FLIP).0 > flips[3]);
312 } 337 }
313} 338}
diff --git a/d3d12/crates/leonida-loader/src/hooks.rs b/d3d12/crates/leonida-loader/src/hooks.rs
index 1c8639f3d..5dccc2370 100644
--- a/d3d12/crates/leonida-loader/src/hooks.rs
+++ b/d3d12/crates/leonida-loader/src/hooks.rs
@@ -342,7 +342,7 @@ fn render_scale_patches(base: usize, scale: f32, fsr: bool, max_scaled: bool) ->
342/// (`100`, `125`, `200` or `250`; unset, `0` or `67`: the title's own 1/15 s). 342/// (`100`, `125`, `200` or `250`; unset, `0` or `67`: the title's own 1/15 s).
343pub(crate) const MAX_STEP_ENV: &str = "LEONIDA_SIM_MAX_STEP_MS"; 343pub(crate) const MAX_STEP_ENV: &str = "LEONIDA_SIM_MAX_STEP_MS";
344 344
345/// The title's game timers step `clamp(real time, 1 / rate, 1/15 s)` a frame (+0x2226040, which the frame's own 345/// The stock game timers step `clamp(real time, 1 / rate, 1/15 s)` a frame (+0x2226040, which the frame's own
346/// timer at +0x22264d0 runs): a frame longer than 66.7 ms moves game time 66.7 ms, so below 15 frames a second, 346/// timer at +0x22264d0 runs): a frame longer than 66.7 ms moves game time 66.7 ms, so below 15 frames a second,
347/// and at every hitch longer than that, the world runs slower than the wall clock and the sound. The ceiling is 347/// and at every hitch longer than that, the world runs slower than the wall clock and the sound. The ceiling is
348/// the constant at [`MAX_STEP_TITLE`], loaded in these two places (`vmovss xmm, [rip + disp32]`, the displacement 348/// the constant at [`MAX_STEP_TITLE`], loaded in these two places (`vmovss xmm, [rip + disp32]`, the displacement
@@ -359,6 +359,59 @@ const MAX_STEP_TITLE: (f32, usize) = (1.0 / 15.0, 0x6159ec0);
359const MAX_STEPS: [(u32, f32, usize); 4] = 359const MAX_STEPS: [(u32, f32, usize); 4] =
360 [(100, 0.1, 0x6159dfc), (125, 0.125, 0x615a6b8), (200, 0.2, 0x6159f8c), (250, 0.25, 0x6159ca4)]; 360 [(100, 0.1, 0x6159dfc), (125, 0.125, 0x615a6b8), (200, 0.2, 0x6159f8c), (250, 0.25, 0x6159ca4)];
361 361
362/// `vmovss xmm, [rip + disp32]` reads from the end of the eight-byte instruction.
363fn step_load(at: usize, op: [u8; 4], target: usize) -> Vec<u8> {
364 let disp = (target as i64 - (at as i64 + 8)) as i32;
365 [&op[..], &disp.to_le_bytes()].concat()
366}
367
368/// The engine initializes its minimum step to 1/3000 s before the first tick. In the image file it is 1/30 s.
369const MIN_STEP: usize = 0x6847660;
370const NOMINAL_STEP: usize = 0x6849844;
371const NOMINAL_STEP_LOADS: [(usize, [u8; 4]); 2] = [(0x222605a, [0xC5, 0xFA, 0x10, 0x25]), (0x2226854, [0xC5, 0xFA, 0x10, 0x0D])];
372
373fn measured_frame_timing_patches() -> Vec<OwnedPatch> {
374 let initial_min = (1.0f32 / 30.0).to_le_bytes().to_vec();
375 let mut patches = vec![OwnedPatch {
376 what: "game step: the timer's minimum before initialization",
377 rva: MIN_STEP,
378 expect: initial_min.clone(),
379 new: initial_min,
380 }];
381 for (at, op) in NOMINAL_STEP_LOADS {
382 patches.push(OwnedPatch {
383 what: "game step: use the timer's minimum instead of the nominal step",
384 rva: at,
385 expect: step_load(at, op, NOMINAL_STEP),
386 new: step_load(at, op, MIN_STEP),
387 });
388 }
389 // The title's frame limiter compares the elapsed interval with its deadline. Fall through to the existing
390 // completion path even if the frame is early, keeping its timestamps and return value. The device's frame
391 // events still enforce the cap selected by the player, including changes made during play.
392 patches.push(OwnedPatch {
393 what: "frame pacing: leave the wait to the runtime's frame events",
394 rva: 0x12062c,
395 expect: vec![0x0F, 0x86, 0x85, 0x00, 0x00, 0x00],
396 new: vec![0x90; 6],
397 });
398 patches
399}
400
401/// Let the runtime pace rendering and make the game and camera clocks use measured steps. The existing
402/// maximum step still bounds hitches, and the separate script counter patch still guards its 60 FPS branch.
403/// The measured floor comes from the repository's earlier `runtime/src/frame_step.h` at 2694497e8.
404///
405/// # Safety
406/// As `disarm_watchdog`.
407pub(crate) unsafe fn measured_frame_timing(base: usize, hash: &blake3::Hash) -> usize {
408 if !is_build_1_0_2_1(hash) {
409 return 0;
410 }
411 // SAFETY: forwarded from this function's contract.
412 unsafe { apply_all(base, &measured_frame_timing_patches()) }
413}
414
362/// The ceiling `LEONIDA_SIM_MAX_STEP_MS` asks for: `Some(None)` for the title's own, `None` if not one of them. 415/// The ceiling `LEONIDA_SIM_MAX_STEP_MS` asks for: `Some(None)` for the title's own, `None` if not one of them.
363fn parse_max_step(text: &str) -> Option<Option<(u32, f32, usize)>> { 416fn parse_max_step(text: &str) -> Option<Option<(u32, f32, usize)>> {
364 match text.trim() { 417 match text.trim() {
@@ -374,10 +427,6 @@ fn parse_max_step(text: &str) -> Option<Option<(u32, f32, usize)>> {
374/// ceiling and the new one checked to hold their values (the same bytes put back), then the two loads pointed at 427/// ceiling and the new one checked to hold their values (the same bytes put back), then the two loads pointed at
375/// the new one. Applied all or none ([`apply_all`]). 428/// the new one. Applied all or none ([`apply_all`]).
376fn max_step_patches(value: f32, constant: usize) -> Vec<OwnedPatch> { 429fn max_step_patches(value: f32, constant: usize) -> Vec<OwnedPatch> {
377 let load = |at: usize, op: [u8; 4], target: usize| {
378 let disp = (target as i64 - (at as i64 + 8)) as i32;
379 [&op[..], &disp.to_le_bytes()].concat()
380 };
381 let mut patches = vec![ 430 let mut patches = vec![
382 OwnedPatch { 431 OwnedPatch {
383 what: "game step: the title's longest step is 1/15 s", 432 what: "game step: the title's longest step is 1/15 s",
@@ -396,8 +445,8 @@ fn max_step_patches(value: f32, constant: usize) -> Vec<OwnedPatch> {
396 patches.push(OwnedPatch { 445 patches.push(OwnedPatch {
397 what: "game step: a load of the longest step a frame", 446 what: "game step: a load of the longest step a frame",
398 rva: at, 447 rva: at,
399 expect: load(at, op, MAX_STEP_TITLE.1), 448 expect: step_load(at, op, MAX_STEP_TITLE.1),
400 new: load(at, op, constant), 449 new: step_load(at, op, constant),
401 }); 450 });
402 } 451 }
403 patches 452 patches
@@ -583,11 +632,37 @@ unsafe fn apply_all(base: usize, patches: &[OwnedPatch]) -> usize {
583 tracing::warn!(what = missing.what, "hooks skipped, all that go with it too: the bytes are not the expected ones"); 632 tracing::warn!(what = missing.what, "hooks skipped, all that go with it too: the bytes are not the expected ones");
584 return 0; 633 return 0;
585 } 634 }
586 patches 635 let mut writable = Vec::with_capacity(patches.len());
587 .iter() 636 for p in patches {
588 // SAFETY: forwarded from this function's contract. 637 let at = (base + p.rva) as *mut u8;
589 .filter(|p| unsafe { apply(base, &p.borrowed()) }) 638 let mut old = 0;
590 .count() 639 // SAFETY: the bytes were checked above and the image is mapped for the duration of the call.
640 if unsafe { VirtualProtect(at as _, p.new.len(), PAGE_EXECUTE_READWRITE, &mut old) } == 0 {
641 tracing::warn!(what = p.what, "hooks skipped: could not make every patch writable");
642 break;
643 }
644 writable.push((at, p.new.len(), old));
645 }
646 let ready = writable.len() == patches.len();
647 if ready {
648 for (p, &(at, len, _)) in patches.iter().zip(&writable) {
649 // SAFETY: each destination is validated and writable and the source is owned by the patch.
650 unsafe { std::ptr::copy_nonoverlapping(p.new.as_ptr(), at, len) };
651 tracing::info!(what = p.what, "hook applied");
652 }
653 }
654 // Several patches can share a page. Undo protection changes in reverse order.
655 for (at, len, old) in writable.into_iter().rev() {
656 let mut ignored = 0;
657 // SAFETY: these are the ranges just made writable.
658 unsafe {
659 VirtualProtect(at as _, len, old, &mut ignored);
660 if ready {
661 FlushInstructionCache(GetCurrentProcess(), at as _, len);
662 }
663 }
664 }
665 if ready { patches.len() } else { 0 }
591} 666}
592 667
593/// Leonida: applies the game patches of `vipatch.rs` (after VI-Patch, `docs/vi_patch.md`) to the title's 668/// Leonida: applies the game patches of `vipatch.rs` (after VI-Patch, `docs/vi_patch.md`) to the title's
@@ -791,7 +866,13 @@ mod tests {
791 for (value, rva) in FSR_SCALES { 866 for (value, rva) in FSR_SCALES {
792 assert_eq!(at(rva, 4), value.to_le_bytes(), "{value} at {rva:#x}"); 867 assert_eq!(at(rva, 4), value.to_le_bytes(), "{value} at {rva:#x}");
793 } 868 }
794 // The game step's places and its constants (`LEONIDA_SIM_MAX_STEP_MS`). 869 for p in measured_frame_timing_patches() {
870 assert_eq!(at(p.rva, p.expect.len()), p.expect, "{} at {:#x}", p.what, p.rva);
871 }
872 // The engine initializes the floor's destination before using it as a step.
873 assert_eq!(at(0x2226196, 4), (1.0f32 / 3000.0).to_le_bytes());
874
875 // The optional ceiling is still applied independently of the measured step.
795 for (_, value, constant) in MAX_STEPS { 876 for (_, value, constant) in MAX_STEPS {
796 for p in max_step_patches(value, constant) { 877 for p in max_step_patches(value, constant) {
797 assert_eq!(at(p.rva, p.expect.len()), p.expect, "{} at {:#x}", p.what, p.rva); 878 assert_eq!(at(p.rva, p.expect.len()), p.expect, "{} at {:#x}", p.what, p.rva);
@@ -961,6 +1042,31 @@ mod tests {
961 } 1042 }
962 1043
963 #[test] 1044 #[test]
1045 fn measured_steps_and_the_title_wait_are_patched_together() {
1046 let patches = measured_frame_timing_patches();
1047 let mut image = vec![0u8; 0x6847664];
1048 for p in &patches {
1049 image[p.rva..p.rva + p.expect.len()].copy_from_slice(&p.expect);
1050 }
1051 let read_i32 = |bytes: &[u8], at: usize| i32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
1052 assert_eq!(0x2226062 + read_i32(&image, 0x222605e), 0x6849844);
1053 assert_eq!(0x222685c + read_i32(&image, 0x2226858), 0x6849844);
1054
1055 let base = image.as_mut_ptr() as usize;
1056 let last = image[0x12062c];
1057 image[0x12062c] = 0;
1058 // SAFETY: the synthetic image holds every patch range.
1059 assert_eq!(unsafe { apply_all(base, &patches) }, 0);
1060 assert_eq!(0x2226062 + read_i32(&image, 0x222605e), 0x6849844);
1061 image[0x12062c] = last;
1062 // SAFETY: as above.
1063 assert_eq!(unsafe { apply_all(base, &patches) }, patches.len());
1064 assert_eq!(0x2226062 + read_i32(&image, 0x222605e), 0x6847660);
1065 assert_eq!(0x222685c + read_i32(&image, 0x2226858), 0x6847660);
1066 assert_eq!(&image[0x12062c..0x120632], &[0x90; 6]);
1067 }
1068
1069 #[test]
964 fn scales_outside_the_floor_are_refused() { 1070 fn scales_outside_the_floor_are_refused() {
965 assert_eq!(parse_scale("0.5"), Some(0.5)); 1071 assert_eq!(parse_scale("0.5"), Some(0.5));
966 assert_eq!(parse_scale(" 1 "), Some(1.0)); 1072 assert_eq!(parse_scale(" 1 "), Some(1.0));
diff --git a/d3d12/crates/leonida-loader/src/windows.rs b/d3d12/crates/leonida-loader/src/windows.rs
index d1ee577a8..91edcfb7d 100644
--- a/d3d12/crates/leonida-loader/src/windows.rs
+++ b/d3d12/crates/leonida-loader/src/windows.rs
@@ -106,6 +106,11 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result<LoadedImage> {
106 crate::hooks::OUTPUT_ENV 106 crate::hooks::OUTPUT_ENV
107 ); 107 );
108 } 108 }
109 // SAFETY: just mapped, and no title code has run.
110 let timing = unsafe { crate::hooks::measured_frame_timing(loaded.base(), &prepared.original_hash) };
111 if timing > 0 {
112 tracing::info!(places = timing, "frame pacing and measured simulation steps");
113 }
109 // Leonida: the longest step the title's game time takes a frame (`LEONIDA_SIM_MAX_STEP_MS`), so that frames 114 // Leonida: the longest step the title's game time takes a frame (`LEONIDA_SIM_MAX_STEP_MS`), so that frames
110 // under 15 a second do not run in slow motion. 115 // under 15 a second do not run in slow motion.
111 // SAFETY: just mapped, and no title code has run. 116 // SAFETY: just mapped, and no title code has run.
diff --git a/docs/vi_patch.md b/docs/vi_patch.md
index a6ccffa3e..2eac5ca01 100644
--- a/docs/vi_patch.md
+++ b/docs/vi_patch.md
@@ -13,8 +13,8 @@ written are Leonida's own. The idea of each patch is ZiZc3's.
13 13
14None of the eight is a protection, licence or online patch: they change the frame rate, the picture and the game. 14None of the eight is a protection, licence or online patch: they change the frame rate, the picture and the game.
15 15
16**Not run in the game.** The places were checked offline only (below). Nothing here has been seen working in a 16The original VI-Patch port was checked offline. The measured simulation step is described in
17run yet. 17[Uncapped rendering and simulation time](#uncapped-rendering-and-simulation-time).
18 18
19## The list 19## The list
20 20
@@ -69,14 +69,18 @@ Untouched, the title asks for 33 333 microseconds: 30 frames a second. The patch
69executable twice, these two places; the interval global has one more writer, a start-up initialiser that stores 69executable twice, these two places; the interval global has one more writer, a start-up initialiser that stores
701000 (no limit) before the settings are applied. 701000 (no limit) before the settings are applied.
71 71
72What can still hold the rate under 60: 72## Uncapped rendering and simulation time
73 73
74- `LEONIDA_FPS_CAP` (the F1 menu's FRAME RATE CAP, the F4 menu's frame-rate cap): unset, the frame clock of 74On 1.0.2.1 the loader skips the title's own deadline wait and lets that function finish its normal timestamp
75 `leonida-gpu/src/frame.rs` ticks at the title's interval, now 60 a second (the menu's `GAME (60)`); a value 75update. The runtime's frame events then do the pacing. The F1 and F4 frame-rate cap settings take effect live.
76 saved there replaces it, and `30` is how to have the old pace back. The play scripts do not set it. 76`GAME (60)` uses the title's requested interval, a numeric `LEONIDA_FPS_CAP` uses that rate, and `NONE`
77- The present itself does not wait: `Present(0, 0)` on a flip-discard swap chain, no vertical sync. 77(`LEONIDA_FPS_CAP=0`) lets frame events complete immediately. Frame generation has independent pacing.
78- The PC: the title waits for a tick before each present, and a frame that takes longer than 16.7 ms is simply 78
79 late. 79The game and camera timers use the measured frame duration. The loader redirects both reads of the nominal
80frame duration to the timer's own minimum, initialized to 1/3000 s. The existing upper bound still limits a
81step during a hitch to 1/15 s by default, or the value selected by `LEONIDA_SIM_MAX_STEP_MS`. This fixes the
82clock's speedup at high frame rates. Systems that count rendered frames directly can still vary with FPS.
83See the earlier timing measurements in [port_status.md](port_status.md#leonida-on-this-machine).
80 84
81## No Vignette 85## No Vignette
82 86