diff --git a/crates/horizon-client/examples/frame_limiter_probe.rs b/crates/horizon-client/examples/frame_limiter_probe.rs new file mode 100644 index 000000000..a877d05f9 --- /dev/null +++ b/crates/horizon-client/examples/frame_limiter_probe.rs @@ -0,0 +1,96 @@ +#![forbid(unsafe_code)] +//! Runs the JSON-lines scenarios of tools/test_frame_limiter_parity.py through +//! the Rust `FramerateLimiter` with the same scripted virtual clock. +use horizon_client::{ + Result, + window::{FramerateLimiter, LimiterClock, end_frame}, +}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +/// The scripted clock of the case: every query costs `call` ns, parking +/// sleeps the request plus the next overshoot (at least 1 ns), spinning +/// costs `spin` ns and interruptions follow their script. +struct Script { + now: i64, + call: i64, + spin: i64, + overshoot: Vec, + next_overshoot: usize, + interrupts: Vec, + next_interrupt: usize, + parks: Vec, + spins: u64, + queries: u64, +} +impl LimiterClock for Script { + fn nanos(&mut self) -> i64 { + self.queries += 1; + let t = self.now; + self.now = self.now.wrapping_add(self.call); + t + } + fn park(&mut self, nanos: i64) { + self.parks.push(nanos); + let o = self.overshoot[self.next_overshoot % self.overshoot.len()]; + self.next_overshoot += 1; + self.now = self.now.wrapping_add(nanos.max(0).wrapping_add(o).max(1)); + } + fn spin(&mut self) { + self.spins += 1; + self.now = self.now.wrapping_add(self.spin); + } + fn interrupted(&mut self) -> bool { + let i = self.interrupts[self.next_interrupt % self.interrupts.len()]; + self.next_interrupt += 1; + i + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let i = |k: &str| c[k].as_i64().unwrap(); + let mut clock = Script { + now: i("now"), + call: i("call"), + spin: i("spin"), + overshoot: c["overshoot"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(), + next_overshoot: 0, + interrupts: c["interrupts"].as_array().unwrap().iter().map(|v| v.as_bool().unwrap()).collect(), + next_interrupt: 0, + parks: Vec::new(), + spins: 0, + queries: 0, + }; + let mut limiter = FramerateLimiter::with_state(i("last"), i("average"), i("last_limit") as i32); + for frame in c["frames"].as_array().unwrap() { + clock.now = clock.now.wrapping_add(frame[0].as_i64().unwrap()); + clock.parks.clear(); + clock.spins = 0; + clock.queries = 0; + end_frame(&mut limiter, frame[1].as_i64().unwrap() as i32, &mut clock); + let parks: Vec = clock.parks.iter().map(i64::to_string).collect(); + writeln!( + out, + "frame {} {} {} {} queries {} spins {} parks [{}]", + clock.now, + limiter.last_frame_time(), + limiter.average_overshoot_ns(), + limiter.last_framerate_limit(), + clock.queries, + clock.spins, + parks.join(",") + )?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 23162566b..6a1413d2c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -617,6 +617,9 @@ struct Game<'a> { /// Camera.oldFovModifier / fovModifier. /// `Camera` (eye height and field-of-view easing, view placement). view: horizon_client::camera::Camera, + /// `FramerateLimiter` and its clock. + limiter: horizon_client::window::FramerateLimiter, + frame_clock: horizon_client::window::SystemClock, /// Hud.scopeScale (spyglass overlay size). scope_scale: f32, /// Duration of the last frame in ticks (GUI easing). @@ -8196,6 +8199,7 @@ impl ApplicationHandler for Game<'_> { } self.apply_mouse_look(); let rendered = self.render()?; + self.limit_frame(); self.pause = self.pauses_game(); self.clock.end_frame(self.pause); let finished = self @@ -8261,10 +8265,6 @@ impl ApplicationHandler for Game<'_> { event_loop.exit(); return; } - if let Some(due) = self.next_frame_due() { - event_loop.set_control_flow(ControlFlow::WaitUntil(due)); - return; - } if let Some(w) = &self.window { w.request_redraw(); } @@ -8504,6 +8504,8 @@ pub fn run() -> Result<()> { chest_open: HashMap::new(), using: None, view: Default::default(), + limiter: horizon_client::window::FramerateLimiter::new(0), + frame_clock: Default::default(), scope_scale: 0.5, frame_ticks: 0.0, title: None, diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 07cb5ba88..666656df3 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -176,13 +176,9 @@ impl Game<'_> { self.settings.save(&Self::options_path()); self.apply_ui_settings(); } - /// Frame limiter for the Max Framerate option: when the next frame is due. - pub(super) fn next_frame_due(&self) -> Option { - if self.options.frames.is_some() { - return None; - } - // FramerateLimitTracker.getFramerateLimit: the option, throttled when - // minimised, idle, or in a menu without a world. + /// `FramerateLimitTracker.getFramerateLimit`: the Max Framerate option, + /// throttled when minimised, idle, or in a menu without a world. + pub(super) fn framerate_limit(&self) -> i32 { let context = FrameContext { inactivity: if self.settings.inactivity_fps_limit == "minimized" { InactivityFpsLimit::Minimized @@ -201,11 +197,16 @@ impl Game<'_> { has_screen: self.title.is_some() || self.screen != super::Screen::Playing, has_overlay: false, }; - let fps = framerate_limit(self.settings.max_fps as i32, context); - if fps >= 260 { - return None; + framerate_limit(self.settings.max_fps as i32, context) + } + /// `Minecraft.runTick`'s frame limiter: `FramerateLimiter.limitDisplayFPS` + /// below 260 frames per second, sleeping then spin-waiting until the + /// frame's slot ends (not in scripted frame-count runs). + pub(super) fn limit_frame(&mut self) { + if self.options.frames.is_some() { + return; } - let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps)); - (due > std::time::Instant::now()).then_some(due) + let limit = self.framerate_limit(); + horizon_client::window::end_frame(&mut self.limiter, limit, &mut self.frame_clock); } } diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs index 18c76e683..bfcb973dd 100644 --- a/crates/horizon-client/src/window.rs +++ b/crates/horizon-client/src/window.rs @@ -143,16 +143,64 @@ pub trait LimiterClock { fn park(&mut self, nanos: i64); /// `Thread.onSpinWait`. fn spin(&mut self); + /// `Thread.interrupted`: an interrupted limiter skips that sleep. + fn interrupted(&mut self) -> bool { + false + } +} + +/// The real clock: `System.nanoTime` from a fixed origin, sleeping for +/// `LockSupport.parkNanos` and a CPU spin hint for `Thread.onSpinWait`. +#[derive(Clone, Copy, Debug)] +pub struct SystemClock { + origin: std::time::Instant, +} +impl Default for SystemClock { + fn default() -> Self { + Self { + origin: std::time::Instant::now(), + } + } +} +impl LimiterClock for SystemClock { + fn nanos(&mut self) -> i64 { + i64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(i64::MAX) + } + fn park(&mut self, nanos: i64) { + std::thread::sleep(std::time::Duration::from_nanos(nanos.max(0) as u64)); + } + fn spin(&mut self) { + std::hint::spin_loop(); + } +} + +/// `Minecraft.runTick`'s frame-limiter step: only limits below 260 +/// (the "unlimited" setting) pace frames. +pub fn end_frame(limiter: &mut FramerateLimiter, framerate_limit: i32, clock: &mut impl LimiterClock) { + if framerate_limit < 260 { + limiter.limit_display_fps(framerate_limit, clock); + } } impl FramerateLimiter { pub fn new(now_ns: i64) -> Self { + Self::with_state(now_ns, 0, 0) + } + /// The limiter's static state: `lastFrameTime`, `averageOvershootNs` + /// and `lastFramerateLimit`. + pub fn with_state(last_frame_time: i64, average_overshoot_ns: i64, last_framerate_limit: i32) -> Self { Self { - last_frame_time: now_ns, - average_overshoot_ns: 0, - last_framerate_limit: 0, + last_frame_time, + average_overshoot_ns, + last_framerate_limit, } } + pub fn average_overshoot_ns(&self) -> i64 { + self.average_overshoot_ns + } + pub fn last_framerate_limit(&self) -> i32 { + self.last_framerate_limit + } pub fn limit_display_fps(&mut self, framerate_limit: i32, clock: &mut impl LimiterClock) { let target_time_per_frame = 1_000_000_000 / i64::from(framerate_limit); let target_time_ns = self.last_frame_time + target_time_per_frame; @@ -168,13 +216,16 @@ impl FramerateLimiter { if remaining > self.average_overshoot_ns + 500_000 { let sleep_start = clock.nanos(); let expected = remaining - self.average_overshoot_ns - 500_000; - clock.park(expected); - let duration = clock.nanos() - sleep_start; - let overshoot = duration - expected; - if overshoot > 0 && overshoot < 25_000_000 { - self.average_overshoot_ns = - (0.1 * overshoot as f64 + 0.9 * self.average_overshoot_ns as f64) as i64; - self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000); + if !clock.interrupted() { + clock.park(expected); + let duration = clock.nanos() - sleep_start; + let overshoot = duration - expected; + if overshoot > 0 && overshoot < 25_000_000 { + self.average_overshoot_ns = (0.1 * overshoot as f64 + + 0.9 * self.average_overshoot_ns as f64) + as i64; + self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000); + } } } else { clock.spin(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFrameLimiterOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFrameLimiterOracle.java new file mode 100644 index 000000000..d6e2fa119 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFrameLimiterOracle.java @@ -0,0 +1,171 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.*; +import java.lang.classfile.*; +import java.lang.classfile.instruction.InvokeInstruction; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; + +/** + * Runs the real FramerateLimiter.limitDisplayFPS from the client jar with its + * clock calls (System.nanoTime, LockSupport.parkNanos, Thread.interrupted, + * Thread.onSpinWait) redirected by a ClassFile rewrite to a scripted virtual + * clock, and the Minecraft.runTick condition (limits below 260), printing the + * limiter state and clock interaction of every frame. + */ +public final class VanillaFrameLimiterOracle { + /** The scripted clock the rewritten limiter calls. */ + public static final class Clock { + static long now, call, spin; + static long[] overshoot; + static int nextOvershoot; + static boolean[] interrupts; + static int nextInterrupt; + static List parks = new ArrayList<>(); + static long spins, queries; + + public static long nanoTime() { + queries++; + long t = now; + now += call; + return t; + } + + public static void parkNanos(long nanos) { + parks.add(nanos); + long o = overshoot[nextOvershoot++ % overshoot.length]; + now += Math.max(Math.max(nanos, 0) + o, 1); + } + + public static void onSpinWait() { + spins++; + now += spin; + } + + public static boolean interrupted() { + return interrupts[nextInterrupt++ % interrupts.length]; + } + } + + static final ClassDesc CLOCK = ClassDesc.of(Clock.class.getName()); + + /** Loads FramerateLimiter itself, rewritten; everything else from the parent. */ + static final class Rewriting extends ClassLoader { + Rewriting(ClassLoader parent) { + super(parent); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.equals("net.minecraft.client.FramerateLimiter")) { + return super.loadClass(name, resolve); + } + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + try (var in = getParent().getResourceAsStream("net/minecraft/client/FramerateLimiter.class")) { + byte[] bytes = rewrite(in.readAllBytes()); + loaded = defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + return loaded; + } + } + } + + static int rewrites; + + static byte[] rewrite(byte[] bytes) { + var cf = ClassFile.of(); + ClassModel model = cf.parse(bytes); + return cf.transformClass(model, ClassTransform.transformingMethodBodies((builder, element) -> { + if (element instanceof InvokeInstruction call && call.opcode() == Opcode.INVOKESTATIC) { + String owner = call.owner().asInternalName(); + String name = call.name().stringValue(); + String target = switch (owner + "." + name) { + case "java/lang/System.nanoTime" -> "nanoTime"; + case "java/util/concurrent/locks/LockSupport.parkNanos" -> "parkNanos"; + case "java/lang/Thread.interrupted" -> "interrupted"; + case "java/lang/Thread.onSpinWait" -> "onSpinWait"; + default -> null; + }; + if (target != null) { + rewrites++; + builder.invokestatic(CLOCK, target, MethodTypeDesc.ofDescriptor(call.type().stringValue())); + return; + } + } + builder.with(element); + })); + } + + public static void main(String[] args) throws Exception { + Clock.overshoot = new long[] {0}; + Clock.interrupts = new boolean[] {false}; + Class limiter = Class.forName("net.minecraft.client.FramerateLimiter", true, + new Rewriting(VanillaFrameLimiterOracle.class.getClassLoader())); + // System.nanoTime x4 (and once in the static initialiser), parkNanos, interrupted, onSpinWait. + if (rewrites != 8) { + throw new AssertionError("unexpected clock calls in FramerateLimiter: " + rewrites); + } + Method limit = limiter.getMethod("limitDisplayFPS", int.class); + Field last = limiter.getDeclaredField("lastFrameTime"); + Field average = limiter.getDeclaredField("averageOvershootNs"); + Field lastLimit = limiter.getDeclaredField("lastFramerateLimit"); + for (Field f : List.of(last, average, lastLimit)) { + f.setAccessible(true); + } + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + int n = 0; + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + out.println("== " + n++); + Clock.now = c.get("now").getAsLong(); + Clock.call = c.get("call").getAsLong(); + Clock.spin = c.get("spin").getAsLong(); + var o = c.getAsJsonArray("overshoot"); + Clock.overshoot = new long[o.size()]; + for (int i = 0; i < o.size(); i++) { + Clock.overshoot[i] = o.get(i).getAsLong(); + } + var in = c.getAsJsonArray("interrupts"); + Clock.interrupts = new boolean[in.size()]; + for (int i = 0; i < in.size(); i++) { + Clock.interrupts[i] = in.get(i).getAsBoolean(); + } + Clock.nextOvershoot = 0; + Clock.nextInterrupt = 0; + last.setLong(null, c.get("last").getAsLong()); + average.setLong(null, c.get("average").getAsLong()); + lastLimit.setInt(null, c.get("last_limit").getAsInt()); + for (var e : c.getAsJsonArray("frames")) { + var frame = e.getAsJsonArray(); + Clock.now += frame.get(0).getAsLong(); + Clock.parks.clear(); + Clock.spins = 0; + Clock.queries = 0; + int framerateLimit = frame.get(1).getAsInt(); + // Minecraft.runTick: "if (framerateLimit < 260) FramerateLimiter.limitDisplayFPS(framerateLimit)". + if (framerateLimit < 260) { + limit.invoke(null, framerateLimit); + } + var parks = new StringJoiner(","); + for (long p : Clock.parks) { + parks.add(Long.toString(p)); + } + out.println("frame " + Clock.now + " " + last.getLong(null) + " " + average.getLong(null) + " " + + lastLimit.getInt(null) + " queries " + Clock.queries + " spins " + Clock.spins + " parks [" + parks + "]"); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_frame_limiter_parity.py b/tools/test_frame_limiter_parity.py new file mode 100644 index 000000000..1ff2099be --- /dev/null +++ b/tools/test_frame_limiter_parity.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Compare the frame limiter with the pinned client: the real +FramerateLimiter.limitDisplayFPS bytecode, its clock calls rewritten to a +scripted virtual clock, against the Rust limiter with the same script, frame +by frame: sleep requests, spin-waits, overshoot averaging and its reset on a +limit change, interrupted sleeps, oversleep and early wake-ups, the "below +260" condition of Minecraft.runTick, and the limits FramerateLimitTracker +hands it (option values, 60 in menus, 10 when minimised or idle).""" +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + +LIMITS = [10, 30, 60, 60, 120, 144, 165, 240, 250, 259, 260, 1, 2, 7, 1000, 2**31 - 1] + + +def cases(rng): + for limit in LIMITS: + for overshoot in ([0], [50_000], [3_000_000], [30_000_000], [-200_000], [100_000, 2_500_000, 0, 24_999_999, 25_000_000]): + for spin in (1_000, 50_000, 7_919): + frames = [[rng.choice([0, 1_000_000, 4_000_000, 16_000_000]), limit] for _ in range(12)] + yield dict(now=10**12, call=rng.choice([0, 25]), spin=spin, overshoot=overshoot, interrupts=[False], + last=10**12, average=0, last_limit=0, frames=frames) + for n in range(5000): + frames = [] + limit = rng.choice(LIMITS) + for _ in range(rng.randrange(1, 40)): + if rng.random() < 0.15: + limit = rng.choice(LIMITS) + work = rng.choice([0, 100_000, 2_000_000, 5_000_000, 16_666_666, 30_000_000, 120_000_000, rng.randrange(0, 50_000_000)]) + frames.append([work, limit]) + start = rng.choice([0, 10**9, 10**15, rng.randrange(0, 10**16)]) + yield dict(now=start, call=rng.choice([1, 30, 400, 20_000]), spin=rng.choice([100, 1_000, 70_000, 600_000]), + overshoot=[rng.choice([0, 30_000, 80_000, 1_200_000, 2_100_000, 24_000_000, 26_000_000, -300_000, rng.randrange(-1_000_000, 4_000_000)]) + for _ in range(rng.randrange(1, 8))], + interrupts=[False] + [rng.random() < 0.3 for _ in range(rng.randrange(0, 5))], + last=start - rng.choice([0, 1, 5_000_000, 200_000_000]), + average=rng.choice([0, 0, 1, 500_000, 2_000_000]), last_limit=rng.choice([0, 60, limit]), frames=frames) + + +def make_cases(build): + rng = random.Random(0x46505331) + path = build / 'cases.jsonl' + count = 0 + with path.open('w') as out: + for case in cases(rng): + out.write(json.dumps(case, separators=(',', ':')) + '\n') + count += 1 + return path, count + + +def main(): + scope = ('The actual FramerateLimiter.limitDisplayFPS bytecode from the client jar, loaded through a ClassFile ' + 'rewrite that redirects System.nanoTime, LockSupport.parkNanos, Thread.interrupted and Thread.onSpinWait ' + 'to a scripted virtual clock (query cost, oversleep/early wake per park, spin cost, interrupt pattern), ' + 'with its static state seeded per case and the Minecraft.runTick "limit < 260" gate. Compares every ' + 'frame\'s park requests, spin count, clock queries, lastFrameTime, averageOvershootNs and ' + 'lastFramerateLimit. The limits themselves (FramerateLimitTracker) are compared by the game loop harness; ' + 'real OS sleep accuracy is outside the comparison.') + harness.differential( + 'rust-frame-limiter-parity', 'VanillaFrameLimiterOracle', 'frame_limiter_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/window.rs']) + + +if __name__ == '__main__': + main()