Merge worktree-agent-a3d290373639c1580
This commit is contained in:
@@ -0,0 +1,301 @@
|
||||
#![forbid(unsafe_code)]
|
||||
//! Runs the JSON-lines scenarios of tools/test_game_loop_parity.py through the
|
||||
//! Rust timer, tick-rate manager, window, mouse and key-mapping code.
|
||||
use horizon_client::{
|
||||
Result,
|
||||
clock::{ServerTickRateManager, Timer},
|
||||
keymapping::KeyState,
|
||||
mouse::{LookOptions, MouseLook, Rotation},
|
||||
options_file::{OptionsFile, V},
|
||||
window::{self, FrameContext, InactivityFpsLimit},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, BufWriter, Write},
|
||||
};
|
||||
|
||||
fn fl(v: &Value) -> f32 {
|
||||
f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap())
|
||||
}
|
||||
fn db(v: &Value) -> f64 {
|
||||
f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
|
||||
}
|
||||
fn fb(v: f32) -> String {
|
||||
format!("{:08x}", if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() })
|
||||
}
|
||||
fn dbs(v: f64) -> String {
|
||||
format!(
|
||||
"{:016x}",
|
||||
if v.is_nan() {
|
||||
0x7ff8_0000_0000_0000
|
||||
} else {
|
||||
v.to_bits()
|
||||
}
|
||||
)
|
||||
}
|
||||
fn b(v: &Value) -> bool {
|
||||
v.as_bool().unwrap()
|
||||
}
|
||||
|
||||
fn timer(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
let mut timer = Timer::new(fl(&c["tps"]), c["start"].as_i64().unwrap());
|
||||
writeln!(out, "timer")?;
|
||||
for op in c["ops"].as_array().unwrap() {
|
||||
let name = op[0].as_str().unwrap();
|
||||
let mut result = String::new();
|
||||
match name {
|
||||
"adv" => {
|
||||
let mspt = if op[2].is_null() { 0.0 } else { fl(&op[2]) };
|
||||
let ticks = timer.advance_game_time(op[1].as_i64().unwrap(), |d| {
|
||||
if mspt == 0.0 { d } else { java_max(d, mspt) }
|
||||
});
|
||||
result = format!(" {ticks}");
|
||||
}
|
||||
"real" => timer.advance_real_time(op[1].as_i64().unwrap()),
|
||||
"pause" => timer.update_pause_state(b(&op[1])),
|
||||
"frozen" => timer.update_frozen_state(b(&op[1])),
|
||||
_ => panic!("{name}"),
|
||||
}
|
||||
writeln!(
|
||||
out,
|
||||
"{name}{result} {} {} {} {}",
|
||||
fb(timer.game_time_delta_ticks()),
|
||||
fb(timer.game_time_delta_partial_tick(false)),
|
||||
fb(timer.game_time_delta_partial_tick(true)),
|
||||
fb(timer.realtime_delta_ticks())
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Math.max(float, float).
|
||||
fn java_max(a: f32, b: f32) -> f32 {
|
||||
if a.is_nan() || b.is_nan() {
|
||||
f32::NAN
|
||||
} else if a == 0.0 && b == 0.0 {
|
||||
f32::from_bits(a.to_bits() & b.to_bits())
|
||||
} else if a >= b {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
|
||||
fn rate(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
let mut m = ServerTickRateManager::default();
|
||||
writeln!(out, "rate")?;
|
||||
for op in c["ops"].as_array().unwrap() {
|
||||
let name = op[0].as_str().unwrap();
|
||||
let mut result = String::new();
|
||||
let mut report = None;
|
||||
match name {
|
||||
"rate" => m.set_tick_rate(fl(&op[1])),
|
||||
"freeze" => m.base.set_frozen(b(&op[1])),
|
||||
"step" => {
|
||||
result = format!(" {}", m.step_game_if_paused(op[1].as_i64().unwrap() as i32))
|
||||
}
|
||||
"stopstep" => result = format!(" {}", m.stop_stepping()),
|
||||
"sprint" => {
|
||||
result = format!(
|
||||
" {}",
|
||||
m.request_game_to_sprint(op[1].as_i64().unwrap() as i32)
|
||||
)
|
||||
}
|
||||
"check" => {
|
||||
let (run, r) = m.check_should_sprint_this_tick(op[1].as_i64().unwrap());
|
||||
result = format!(" {run}");
|
||||
report = r;
|
||||
}
|
||||
"end" => m.end_tick_work(op[1].as_i64().unwrap()),
|
||||
"stopsprint" => {
|
||||
report = m.stop_sprinting();
|
||||
result = format!(" {}", report.is_some());
|
||||
}
|
||||
"tick" => m.base.tick(),
|
||||
_ => panic!("{name}"),
|
||||
}
|
||||
let tail = report.map_or(String::new(), |r| {
|
||||
format!(" report {} {}", r.ticks_per_second, r.milliseconds_per_tick)
|
||||
});
|
||||
writeln!(
|
||||
out,
|
||||
"{name}{result} | {} {} {} {} {} {} {} {}{tail}",
|
||||
fb(m.base.tickrate()),
|
||||
m.base.nanoseconds_per_tick(),
|
||||
fb(m.base.milliseconds_per_tick()),
|
||||
m.base.runs_normally(),
|
||||
m.base.is_stepping_forward(),
|
||||
m.base.frozen_ticks_to_run(),
|
||||
m.base.is_frozen(),
|
||||
m.is_sprinting()
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scale(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
let i = |k: &str| c[k].as_i64().unwrap() as i32;
|
||||
let fbsize = [i("w"), i("h")];
|
||||
let scale = window::calculate_scale(fbsize, i("max"), b(&c["uni"]));
|
||||
let [gw, gh] = window::gui_scaled_size(fbsize, scale);
|
||||
writeln!(
|
||||
out,
|
||||
"scale {scale} {gw} {gh} {} {}",
|
||||
dbs(window::scaled_pos(db(&c["x"]), gw, i("sw"))),
|
||||
dbs(window::scaled_pos(db(&c["y"]), gh, i("sh")))
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn limit(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
let ctx = FrameContext {
|
||||
inactivity: if b(&c["afk"]) {
|
||||
InactivityFpsLimit::Afk
|
||||
} else {
|
||||
InactivityFpsLimit::Minimized
|
||||
},
|
||||
iconified: b(&c["iconified"]),
|
||||
focused: b(&c["focused"]),
|
||||
exclusive_fullscreen: false,
|
||||
now_ms: c["ago"].as_i64().unwrap(),
|
||||
latest_input_ms: 0,
|
||||
has_level: b(&c["level"]),
|
||||
has_screen: b(&c["screen"]),
|
||||
has_overlay: b(&c["overlay"]),
|
||||
};
|
||||
let reason = window::throttle_reason(ctx);
|
||||
let name = match reason {
|
||||
window::ThrottleReason::None => "NONE",
|
||||
window::ThrottleReason::WindowIconified => "WINDOW_ICONIFIED",
|
||||
window::ThrottleReason::LongAfk => "LONG_AFK",
|
||||
window::ThrottleReason::ShortAfk => "SHORT_AFK",
|
||||
window::ThrottleReason::OutOfLevelMenu => "OUT_OF_LEVEL_MENU",
|
||||
};
|
||||
writeln!(
|
||||
out,
|
||||
"limit {name} {} {}",
|
||||
window::framerate_limit(c["opt"].as_i64().unwrap() as i32, ctx),
|
||||
window::heavily_throttled(reason)
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mouse(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
let look = LookOptions {
|
||||
sensitivity: db(&c["sens"]),
|
||||
smooth_camera: b(&c["smooth"]),
|
||||
scoping: b(&c["scoping"]),
|
||||
invert_x: b(&c["ix"]),
|
||||
invert_y: b(&c["iy"]),
|
||||
};
|
||||
let (active, grabbed) = (b(&c["active"]), b(&c["grabbed"]));
|
||||
let mut handler = MouseLook::default();
|
||||
let mut rotation = Rotation {
|
||||
x_rot: 0.0,
|
||||
y_rot: 0.0,
|
||||
x_rot_o: 0.0,
|
||||
y_rot_o: 0.0,
|
||||
};
|
||||
writeln!(out, "mouse")?;
|
||||
for op in c["ops"].as_array().unwrap() {
|
||||
match op[0].as_str().unwrap() {
|
||||
"move" => handler.on_move(
|
||||
db(&op[1]),
|
||||
db(&op[2]),
|
||||
db(&op[3]),
|
||||
db(&op[4]),
|
||||
active,
|
||||
grabbed,
|
||||
),
|
||||
"ignore" => handler.set_ignore_first_move(),
|
||||
"frame" => {
|
||||
if let Some((xo, yo)) =
|
||||
handler.handle_accumulated_movement(db(&op[1]), active, grabbed, look)
|
||||
{
|
||||
rotation.turn(xo, yo);
|
||||
}
|
||||
writeln!(
|
||||
out,
|
||||
"frame {} {} {} {}",
|
||||
fb(rotation.x_rot),
|
||||
fb(rotation.y_rot),
|
||||
fb(rotation.x_rot_o),
|
||||
fb(rotation.y_rot_o)
|
||||
)?;
|
||||
}
|
||||
other => panic!("{other}"),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scroll(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
let mut handler = MouseLook::default();
|
||||
let mut slot = c["slot"].as_i64().unwrap() as i32;
|
||||
// OptionInstance.set quantises the wheel sensitivity.
|
||||
let mut file = OptionsFile::default();
|
||||
file.set("mouseWheelSensitivity", V::Double(db(&c["sens"])));
|
||||
let sensitivity = file.double("mouseWheelSensitivity");
|
||||
writeln!(out, "scroll")?;
|
||||
for op in c["ops"].as_array().unwrap() {
|
||||
if let Some((wheel, _)) =
|
||||
handler.on_scroll(db(&op[0]), db(&op[1]), b(&c["discrete"]), sensitivity)
|
||||
{
|
||||
slot = horizon_client::mouse::ScrollWheelHandler::next_selection(
|
||||
f64::from(wheel),
|
||||
slot,
|
||||
9,
|
||||
);
|
||||
}
|
||||
writeln!(out, "{slot}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
let mut state = if b(&c["toggle"]) {
|
||||
KeyState::toggle(b(&c["restore"]), b(&c["keyboard"]))
|
||||
} else {
|
||||
KeyState::plain()
|
||||
};
|
||||
let mut option = false;
|
||||
writeln!(out, "key")?;
|
||||
for op in c["ops"].as_array().unwrap() {
|
||||
let name = op[0].as_str().unwrap();
|
||||
let mut result = String::new();
|
||||
match name {
|
||||
"option" => option = b(&op[1]),
|
||||
"down" => state.set_down(b(&op[1]), option),
|
||||
"release" => state.release(option),
|
||||
"restore" => {
|
||||
result = format!(" {}", state.should_restore_state_on_screen_closed(option))
|
||||
}
|
||||
"click" => state.click(),
|
||||
"consume" => result = format!(" {}", state.consume_click()),
|
||||
"ingame" => result = format!(" {}", state.should_set_on_ingame_focus(option)),
|
||||
_ => panic!("{name}"),
|
||||
}
|
||||
writeln!(out, "{name}{result} {}", state.is_down)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let mut out = BufWriter::new(File::create(&args[1])?);
|
||||
for line in BufReader::new(File::open(&args[0])?).lines() {
|
||||
let c: Value = serde_json::from_str(&line?)?;
|
||||
match c["t"].as_str().unwrap() {
|
||||
"timer" => timer(&c, &mut out)?,
|
||||
"rate" => rate(&c, &mut out)?,
|
||||
"scale" => scale(&c, &mut out)?,
|
||||
"limit" => limit(&c, &mut out)?,
|
||||
"mouse" => mouse(&c, &mut out)?,
|
||||
"scroll" => scroll(&c, &mut out)?,
|
||||
"key" => key(&c, &mut out)?,
|
||||
other => panic!("{other}"),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#![forbid(unsafe_code)]
|
||||
//! Loads and saves option files like `Options.load`/`save`, for the
|
||||
//! differential harness (tools/test_options_parity.py).
|
||||
use horizon_client::{Result, keybinds, options_file::OptionsFile};
|
||||
use std::{fs, io::Write};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let mut names: Vec<_> = fs::read_dir(&args[0])?
|
||||
.map(|e| e.map(|e| e.path()))
|
||||
.collect::<std::io::Result<_>>()?;
|
||||
names.sort();
|
||||
let mut out = fs::File::create(&args[1])?;
|
||||
let mut first = true;
|
||||
for path in names {
|
||||
let name = path.file_name().unwrap().to_string_lossy().into_owned();
|
||||
let file = if name == "absent.txt" {
|
||||
OptionsFile::default()
|
||||
} else {
|
||||
OptionsFile::parse(&String::from_utf8_lossy(&fs::read(&path)?))
|
||||
};
|
||||
write!(out, "== {name}\n{}", file.serialize())?;
|
||||
if first {
|
||||
first = false;
|
||||
writeln!(out, "== keys")?;
|
||||
for (name, key, category) in keybinds::MAPPINGS {
|
||||
writeln!(out, "{name} {key} {category} {}", keybinds::is_toggle(name))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+422
-145
@@ -1,134 +1,445 @@
|
||||
//! Fixed-rate development simulation driver. Rendering consumes elapsed time;
|
||||
//! a per-frame work cap retains its backlog instead of dropping simulation time.
|
||||
//! The rate, freezing, stepping and sprinting are what `/tick` controls
|
||||
//! (`ServerTickRateManager`).
|
||||
use std::time::Duration;
|
||||
//! `DeltaTracker.Timer` and the tick-rate managers of 26.3: how real
|
||||
//! milliseconds turn into game ticks, partial ticks and real-time deltas, and
|
||||
//! the `/tick` freeze, step and sprint state.
|
||||
|
||||
pub const TICK: Duration = Duration::from_millis(50);
|
||||
/// Ticks one sprint frame may run.
|
||||
const SPRINT_PER_FRAME: u32 = 40;
|
||||
/// `DeltaTracker.Timer`: float arithmetic on integer milliseconds, exactly as
|
||||
/// the client does it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Timer {
|
||||
delta_ticks: f32,
|
||||
delta_tick_residual: f32,
|
||||
realtime_delta_ticks: f32,
|
||||
paused_delta_tick_residual: f32,
|
||||
last_ms: i64,
|
||||
last_ui_ms: i64,
|
||||
ms_per_tick: f32,
|
||||
paused: bool,
|
||||
frozen: bool,
|
||||
}
|
||||
|
||||
impl Timer {
|
||||
pub fn new(ticks_per_second: f32, current_ms: i64) -> Self {
|
||||
Self {
|
||||
delta_ticks: 0.0,
|
||||
delta_tick_residual: 0.0,
|
||||
realtime_delta_ticks: 0.0,
|
||||
paused_delta_tick_residual: 0.0,
|
||||
last_ms: current_ms,
|
||||
last_ui_ms: current_ms,
|
||||
ms_per_tick: 1000.0 / ticks_per_second,
|
||||
paused: false,
|
||||
frozen: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `advanceGameTime`: the whole ticks to run now. `target_mspt` maps the
|
||||
/// default milliseconds per tick to the target in force (the tick-rate
|
||||
/// manager's, when the level runs normally). The caller runs at most ten.
|
||||
pub fn advance_game_time(
|
||||
&mut self,
|
||||
current_ms: i64,
|
||||
target_mspt: impl FnOnce(f32) -> f32,
|
||||
) -> i32 {
|
||||
self.delta_ticks = (current_ms - self.last_ms) as f32 / target_mspt(self.ms_per_tick);
|
||||
self.last_ms = current_ms;
|
||||
self.delta_tick_residual += self.delta_ticks;
|
||||
let ticks = self.delta_tick_residual as i32;
|
||||
self.delta_tick_residual -= ticks as f32;
|
||||
ticks
|
||||
}
|
||||
|
||||
/// `advanceRealTime`.
|
||||
pub fn advance_real_time(&mut self, current_ms: i64) {
|
||||
self.realtime_delta_ticks = (current_ms - self.last_ui_ms) as f32 / self.ms_per_tick;
|
||||
self.last_ui_ms = current_ms;
|
||||
}
|
||||
|
||||
/// `updatePauseState`.
|
||||
pub fn update_pause_state(&mut self, pause: bool) {
|
||||
if pause {
|
||||
if !self.paused {
|
||||
self.paused_delta_tick_residual = self.delta_tick_residual;
|
||||
}
|
||||
self.paused = true;
|
||||
} else {
|
||||
if self.paused {
|
||||
self.delta_tick_residual = self.paused_delta_tick_residual;
|
||||
}
|
||||
self.paused = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// `updateFrozenState`.
|
||||
pub fn update_frozen_state(&mut self, frozen: bool) {
|
||||
self.frozen = frozen;
|
||||
}
|
||||
|
||||
pub fn game_time_delta_ticks(&self) -> f32 {
|
||||
self.delta_ticks
|
||||
}
|
||||
|
||||
/// `getGameTimeDeltaPartialTick`.
|
||||
pub fn game_time_delta_partial_tick(&self, ignore_frozen_game: bool) -> f32 {
|
||||
if !ignore_frozen_game && self.frozen {
|
||||
1.0
|
||||
} else if self.paused {
|
||||
self.paused_delta_tick_residual
|
||||
} else {
|
||||
self.delta_tick_residual
|
||||
}
|
||||
}
|
||||
|
||||
/// `getRealtimeDeltaTicks`.
|
||||
pub fn realtime_delta_ticks(&self) -> f32 {
|
||||
if self.realtime_delta_ticks > 7.0 {
|
||||
0.5
|
||||
} else {
|
||||
self.realtime_delta_ticks
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const NANOSECONDS_PER_SECOND: i64 = 1_000_000_000;
|
||||
const NANOSECONDS_PER_MILLISECOND: i64 = 1_000_000;
|
||||
|
||||
/// `TickRateManager`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TickRateManager {
|
||||
tickrate: f32,
|
||||
nanoseconds_per_tick: i64,
|
||||
frozen_ticks_to_run: i32,
|
||||
run_game_elements: bool,
|
||||
is_frozen: bool,
|
||||
}
|
||||
|
||||
impl Default for TickRateManager {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tickrate: 20.0,
|
||||
nanoseconds_per_tick: NANOSECONDS_PER_SECOND / 20,
|
||||
frozen_ticks_to_run: 0,
|
||||
run_game_elements: true,
|
||||
is_frozen: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TickRateManager {
|
||||
/// `setTickRate` (`Math.max(rate, 1.0F)`, NaN propagates).
|
||||
pub fn set_tick_rate(&mut self, rate: f32) {
|
||||
self.tickrate = if rate.is_nan() || rate > 1.0 {
|
||||
rate
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
self.nanoseconds_per_tick =
|
||||
(NANOSECONDS_PER_SECOND as f64 / f64::from(self.tickrate)) as i64;
|
||||
}
|
||||
pub fn tickrate(&self) -> f32 {
|
||||
self.tickrate
|
||||
}
|
||||
pub fn milliseconds_per_tick(&self) -> f32 {
|
||||
self.nanoseconds_per_tick as f32 / NANOSECONDS_PER_MILLISECOND as f32
|
||||
}
|
||||
pub fn nanoseconds_per_tick(&self) -> i64 {
|
||||
self.nanoseconds_per_tick
|
||||
}
|
||||
pub fn runs_normally(&self) -> bool {
|
||||
self.run_game_elements
|
||||
}
|
||||
pub fn is_stepping_forward(&self) -> bool {
|
||||
self.frozen_ticks_to_run > 0
|
||||
}
|
||||
pub fn set_frozen_ticks_to_run(&mut self, ticks: i32) {
|
||||
self.frozen_ticks_to_run = ticks;
|
||||
}
|
||||
pub fn frozen_ticks_to_run(&self) -> i32 {
|
||||
self.frozen_ticks_to_run
|
||||
}
|
||||
pub fn set_frozen(&mut self, frozen: bool) {
|
||||
self.is_frozen = frozen;
|
||||
}
|
||||
pub fn is_frozen(&self) -> bool {
|
||||
self.is_frozen
|
||||
}
|
||||
/// `tick`: decides whether game elements run this tick.
|
||||
pub fn tick(&mut self) {
|
||||
self.run_game_elements = !self.is_frozen || self.frozen_ticks_to_run > 0;
|
||||
if self.frozen_ticks_to_run > 0 {
|
||||
self.frozen_ticks_to_run -= 1;
|
||||
}
|
||||
}
|
||||
/// `isEntityFrozen` for an entity that is not (and does not carry) a player.
|
||||
pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool {
|
||||
!self.runs_normally() && !is_player_or_carries_player
|
||||
}
|
||||
}
|
||||
|
||||
/// What `/tick sprint` reports when it ends.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SprintReport {
|
||||
pub ticks_per_second: i32,
|
||||
pub milliseconds_per_tick: String,
|
||||
}
|
||||
|
||||
/// `ServerTickRateManager`: the freeze, step and sprint state kept by the
|
||||
/// server (the broadcasts to clients are the caller's concern).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ServerTickRateManager {
|
||||
pub base: TickRateManager,
|
||||
remaining_sprint_ticks: i64,
|
||||
sprint_tick_start_time: i64,
|
||||
sprint_time_spend: i64,
|
||||
scheduled_current_sprint_ticks: i64,
|
||||
previous_is_frozen: bool,
|
||||
}
|
||||
|
||||
impl ServerTickRateManager {
|
||||
pub fn is_sprinting(&self) -> bool {
|
||||
self.scheduled_current_sprint_ticks > 0
|
||||
}
|
||||
pub fn remaining_sprint_ticks(&self) -> i64 {
|
||||
self.remaining_sprint_ticks
|
||||
}
|
||||
/// `stepGameIfPaused`.
|
||||
pub fn step_game_if_paused(&mut self, ticks: i32) -> bool {
|
||||
if !self.base.is_frozen() {
|
||||
return false;
|
||||
}
|
||||
self.base.set_frozen_ticks_to_run(ticks);
|
||||
true
|
||||
}
|
||||
/// `stopStepping`.
|
||||
pub fn stop_stepping(&mut self) -> bool {
|
||||
if self.base.frozen_ticks_to_run() > 0 {
|
||||
self.base.set_frozen_ticks_to_run(0);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
/// `stopSprinting`.
|
||||
pub fn stop_sprinting(&mut self) -> Option<SprintReport> {
|
||||
if self.remaining_sprint_ticks > 0 {
|
||||
Some(self.finish_tick_sprint())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// `requestGameToSprint`: true when an earlier sprint was interrupted.
|
||||
pub fn request_game_to_sprint(&mut self, time: i32) -> bool {
|
||||
let interrupted = self.remaining_sprint_ticks > 0;
|
||||
self.sprint_time_spend = 0;
|
||||
self.scheduled_current_sprint_ticks = i64::from(time);
|
||||
self.remaining_sprint_ticks = i64::from(time);
|
||||
self.previous_is_frozen = self.base.is_frozen();
|
||||
self.base.set_frozen(false);
|
||||
interrupted
|
||||
}
|
||||
fn finish_tick_sprint(&mut self) -> SprintReport {
|
||||
let completed_ticks = self.scheduled_current_sprint_ticks - self.remaining_sprint_ticks;
|
||||
let milliseconds_to_complete =
|
||||
(self.sprint_time_spend.max(1)) as f64 / NANOSECONDS_PER_MILLISECOND as f64;
|
||||
let ticks_per_second = (1000.0 * completed_ticks as f64 / milliseconds_to_complete) as i32;
|
||||
let per_tick = if completed_ticks == 0 {
|
||||
f64::from(self.base.milliseconds_per_tick())
|
||||
} else {
|
||||
milliseconds_to_complete / completed_ticks as f64
|
||||
};
|
||||
self.scheduled_current_sprint_ticks = 0;
|
||||
self.sprint_time_spend = 0;
|
||||
self.remaining_sprint_ticks = 0;
|
||||
self.base.set_frozen(self.previous_is_frozen);
|
||||
SprintReport {
|
||||
ticks_per_second,
|
||||
milliseconds_per_tick: crate::java_text::format_fixed2(per_tick),
|
||||
}
|
||||
}
|
||||
/// `checkShouldSprintThisTick`: whether to run this tick without waiting,
|
||||
/// plus the report when the sprint just finished.
|
||||
pub fn check_should_sprint_this_tick(&mut self, now_ns: i64) -> (bool, Option<SprintReport>) {
|
||||
if !self.base.run_game_elements {
|
||||
(false, None)
|
||||
} else if self.remaining_sprint_ticks > 0 {
|
||||
self.sprint_tick_start_time = now_ns;
|
||||
self.remaining_sprint_ticks -= 1;
|
||||
(true, None)
|
||||
} else {
|
||||
(false, Some(self.finish_tick_sprint()))
|
||||
}
|
||||
}
|
||||
/// `endTickWork`.
|
||||
pub fn end_tick_work(&mut self, now_ns: i64) {
|
||||
self.sprint_time_spend += now_ns - self.sprint_tick_start_time;
|
||||
}
|
||||
/// `setTickRate`.
|
||||
pub fn set_tick_rate(&mut self, rate: f32) {
|
||||
self.base.set_tick_rate(rate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ticks one sprint frame may run (rendering carries on between frames).
|
||||
const SPRINT_PER_FRAME: i64 = 40;
|
||||
const SAMPLES: usize = 100;
|
||||
|
||||
/// The game's clock: `DeltaTracker.Timer` pacing driven by the
|
||||
/// `ServerTickRateManager` the `/tick` command controls, over a virtual
|
||||
/// millisecond clock built from the frame times it is fed. The integrated
|
||||
/// simulation is one loop, so the tick rate paces it directly (the vanilla
|
||||
/// client timer only ever slows down, because its server ticks separately).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FixedStep {
|
||||
pending: Duration,
|
||||
/// Ticks per second (`tickrate`).
|
||||
rate: f32,
|
||||
frozen: bool,
|
||||
/// Ticks the frozen world still runs (`/tick step`).
|
||||
step: u32,
|
||||
/// Ticks left in a sprint.
|
||||
sprint: u32,
|
||||
/// How long recent ticks took (nanoseconds), newest last.
|
||||
samples: Vec<u64>,
|
||||
timer: Timer,
|
||||
manager: ServerTickRateManager,
|
||||
now: std::time::Duration,
|
||||
pause: bool,
|
||||
sprint_checked: bool,
|
||||
sprint_report: Option<SprintReport>,
|
||||
tick_times: [i64; SAMPLES],
|
||||
aggregated: i64,
|
||||
tick_count: i64,
|
||||
}
|
||||
|
||||
impl Default for FixedStep {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pending: Duration::ZERO,
|
||||
rate: 20.0,
|
||||
frozen: false,
|
||||
step: 0,
|
||||
sprint: 0,
|
||||
samples: Vec::new(),
|
||||
timer: Timer::new(20.0, 0),
|
||||
manager: ServerTickRateManager::default(),
|
||||
now: std::time::Duration::ZERO,
|
||||
pause: false,
|
||||
sprint_checked: false,
|
||||
sprint_report: None,
|
||||
tick_times: [0; SAMPLES],
|
||||
aggregated: 0,
|
||||
tick_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FixedStep {
|
||||
fn now_ms(&self) -> i64 {
|
||||
self.now.as_millis() as i64
|
||||
}
|
||||
fn now_ns(&self) -> i64 {
|
||||
self.now.as_nanos() as i64
|
||||
}
|
||||
/// The length of one tick at the current rate.
|
||||
pub fn tick_duration(&self) -> Duration {
|
||||
Duration::from_secs_f64(1.0 / f64::from(self.rate.max(0.01)))
|
||||
pub fn tick_duration(&self) -> std::time::Duration {
|
||||
std::time::Duration::from_nanos(self.manager.base.nanoseconds_per_tick().max(1) as u64)
|
||||
}
|
||||
pub fn advance(&mut self, elapsed: Duration) -> u32 {
|
||||
if self.sprint > 0 {
|
||||
let n = self.sprint.min(SPRINT_PER_FRAME);
|
||||
self.sprint -= n;
|
||||
self.pending = Duration::ZERO;
|
||||
return n;
|
||||
/// Feed one frame's elapsed time; returns the ticks to run (at most ten,
|
||||
/// or a sprint frame's worth).
|
||||
pub fn advance(&mut self, elapsed: std::time::Duration) -> u32 {
|
||||
self.now += elapsed;
|
||||
let now_ms = self.now_ms();
|
||||
if self.manager.is_sprinting() {
|
||||
// Keep the timer current so leaving the sprint does not replay it.
|
||||
self.timer.advance_game_time(now_ms, |d| d);
|
||||
let remaining = self.manager.remaining_sprint_ticks();
|
||||
// One extra pass lets the sprint finish and report.
|
||||
return (remaining + 1).min(SPRINT_PER_FRAME) as u32;
|
||||
}
|
||||
self.pending += elapsed;
|
||||
let tick = self.tick_duration();
|
||||
let steps = (self.pending.as_nanos() / tick.as_nanos().max(1)).min(10) as u32;
|
||||
self.pending -= tick * steps;
|
||||
steps
|
||||
let runs = self.manager.base.runs_normally();
|
||||
let mspt = self.manager.base.milliseconds_per_tick();
|
||||
let ticks = self
|
||||
.timer
|
||||
.advance_game_time(now_ms, |default| if runs { mspt } else { default });
|
||||
ticks.clamp(0, 10) as u32
|
||||
}
|
||||
/// Restart pacing from now (after loading, so no backlog replays).
|
||||
pub fn reset(&mut self) {
|
||||
self.pending = Duration::ZERO;
|
||||
self.timer = Timer::new(20.0, self.now_ms());
|
||||
self.timer.update_pause_state(self.pause);
|
||||
}
|
||||
/// The partial tick for interpolation (`getGameTimeDeltaPartialTick(false)`).
|
||||
pub fn fraction(&self) -> f64 {
|
||||
(self.pending.as_secs_f64() / self.tick_duration().as_secs_f64()).min(1.0)
|
||||
f64::from(self.timer.game_time_delta_partial_tick(false))
|
||||
}
|
||||
/// Whether the world ticks this time (`ServerTickRateManager.runsNormally`
|
||||
/// or a pending step); called once per tick.
|
||||
/// After a frame: whether the game is paused by a screen (the residual
|
||||
/// stops accumulating) and whether the level is frozen.
|
||||
pub fn end_frame(&mut self, pause: bool) {
|
||||
self.pause = pause;
|
||||
self.timer.update_pause_state(pause);
|
||||
self.timer
|
||||
.update_frozen_state(!self.manager.base.runs_normally());
|
||||
}
|
||||
pub fn paused(&self) -> bool {
|
||||
self.pause
|
||||
}
|
||||
/// `TickRateManager.tick` for one tick, then whether the world runs
|
||||
/// (`runsNormally`). Also the sprint check that opens a sprint tick.
|
||||
pub fn world_runs(&mut self) -> bool {
|
||||
if !self.frozen {
|
||||
return true;
|
||||
self.manager.base.tick();
|
||||
self.sprint_checked = false;
|
||||
if self.manager.is_sprinting() {
|
||||
let (_, report) = self.manager.check_should_sprint_this_tick(self.now_ns());
|
||||
self.sprint_checked = report.is_none();
|
||||
if report.is_some() {
|
||||
self.sprint_report = report;
|
||||
}
|
||||
}
|
||||
if self.step > 0 {
|
||||
self.step -= 1;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
self.manager.base.runs_normally()
|
||||
}
|
||||
/// The report of a sprint that just finished, once.
|
||||
pub fn take_sprint_report(&mut self) -> Option<SprintReport> {
|
||||
self.sprint_report.take()
|
||||
}
|
||||
pub fn rate(&self) -> f32 {
|
||||
self.rate
|
||||
self.manager.base.tickrate()
|
||||
}
|
||||
pub fn set_rate(&mut self, rate: f32) {
|
||||
self.rate = rate.clamp(1.0, 10000.0);
|
||||
self.manager.set_tick_rate(rate);
|
||||
}
|
||||
pub fn frozen(&self) -> bool {
|
||||
self.frozen
|
||||
self.manager.base.is_frozen()
|
||||
}
|
||||
pub fn set_frozen(&mut self, frozen: bool) {
|
||||
self.frozen = frozen;
|
||||
if !frozen {
|
||||
self.step = 0;
|
||||
}
|
||||
self.manager.base.set_frozen(frozen);
|
||||
}
|
||||
pub fn sprinting(&self) -> bool {
|
||||
self.sprint > 0
|
||||
self.manager.is_sprinting()
|
||||
}
|
||||
/// `requestGameToSprint`: true when a sprint was already running.
|
||||
pub fn start_sprint(&mut self, ticks: u32) -> bool {
|
||||
let was = self.sprint > 0;
|
||||
self.sprint = ticks;
|
||||
was
|
||||
self.manager
|
||||
.request_game_to_sprint(ticks.min(i32::MAX as u32) as i32)
|
||||
}
|
||||
pub fn stop_sprint(&mut self) -> bool {
|
||||
let was = self.sprint > 0;
|
||||
self.sprint = 0;
|
||||
was
|
||||
/// `stopSprinting`: the report when a sprint was running.
|
||||
pub fn stop_sprint(&mut self) -> Option<SprintReport> {
|
||||
self.manager.stop_sprinting()
|
||||
}
|
||||
pub fn stepping(&self) -> bool {
|
||||
self.step > 0
|
||||
self.manager.base.is_stepping_forward()
|
||||
}
|
||||
/// `stepGameIfPaused`: only works while frozen.
|
||||
pub fn start_step(&mut self, ticks: u32) -> bool {
|
||||
if !self.frozen {
|
||||
return false;
|
||||
}
|
||||
self.step = ticks;
|
||||
true
|
||||
self.manager
|
||||
.step_game_if_paused(ticks.min(i32::MAX as u32) as i32)
|
||||
}
|
||||
pub fn stop_step(&mut self) -> bool {
|
||||
let was = self.step > 0;
|
||||
self.step = 0;
|
||||
was
|
||||
self.manager.stop_stepping()
|
||||
}
|
||||
pub fn record(&mut self, took: Duration) {
|
||||
if self.samples.len() == SAMPLES {
|
||||
self.samples.remove(0);
|
||||
/// Record how long a tick took (`MinecraftServer.tickServer` bookkeeping
|
||||
/// and `endTickWork`).
|
||||
pub fn record(&mut self, took: std::time::Duration) {
|
||||
let took = took.as_nanos() as i64;
|
||||
let index = (self.tick_count % SAMPLES as i64) as usize;
|
||||
self.aggregated -= self.tick_times[index];
|
||||
self.aggregated += took;
|
||||
self.tick_times[index] = took;
|
||||
self.tick_count += 1;
|
||||
if self.sprint_checked {
|
||||
let end = self.now_ns() + took;
|
||||
self.manager.end_tick_work(end);
|
||||
}
|
||||
self.samples.push(took.as_nanos() as u64);
|
||||
}
|
||||
/// `getAverageTickTimeNanos`.
|
||||
pub fn average_nanos(&self) -> u64 {
|
||||
if self.samples.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
self.samples.iter().sum::<u64>() / self.samples.len() as u64
|
||||
(self.aggregated / SAMPLES.min(self.tick_count.max(1) as usize) as i64).max(0) as u64
|
||||
}
|
||||
/// The sorted tick times (p50, p95, p99 inputs) and their count.
|
||||
/// The sorted `getTickTimesNanos` array (always 100 entries).
|
||||
pub fn sorted_samples(&self) -> Vec<u64> {
|
||||
let mut v = self.samples.clone();
|
||||
let mut v: Vec<u64> = self.tick_times.iter().map(|&t| t.max(0) as u64).collect();
|
||||
v.sort_unstable();
|
||||
v
|
||||
}
|
||||
@@ -137,70 +448,36 @@ impl FixedStep {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn render_schedules_preserve_ticks_and_stall_backlog() {
|
||||
for schedule in [&[7, 13, 18, 12][..], &[50][..], &[1, 999, 2700, 300][..]] {
|
||||
let mut clock = FixedStep::default();
|
||||
let mut elapsed = Duration::ZERO;
|
||||
let mut ticks = 0;
|
||||
for _ in 0..100 {
|
||||
for &ms in schedule {
|
||||
let frame = Duration::from_millis(ms);
|
||||
elapsed += frame;
|
||||
let count = clock.advance(frame);
|
||||
assert!(count <= 10);
|
||||
ticks += count;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let count = clock.advance(Duration::ZERO);
|
||||
ticks += count;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(u128::from(ticks), elapsed.as_nanos() / TICK.as_nanos());
|
||||
fn timer_carries_fractions_and_caps_nothing_itself() {
|
||||
let mut t = Timer::new(20.0, 0);
|
||||
assert_eq!(t.advance_game_time(49, |d| d), 0);
|
||||
assert_eq!(t.advance_game_time(50, |d| d), 1);
|
||||
assert_eq!(t.advance_game_time(1050, |d| d), 20);
|
||||
}
|
||||
#[test]
|
||||
fn pause_restores_the_residual() {
|
||||
let mut t = Timer::new(20.0, 0);
|
||||
t.advance_game_time(25, |d| d);
|
||||
t.update_pause_state(true);
|
||||
t.advance_game_time(1000, |d| d);
|
||||
assert_eq!(t.game_time_delta_partial_tick(false), 0.5);
|
||||
t.update_pause_state(false);
|
||||
assert_eq!(t.game_time_delta_partial_tick(false), 0.5);
|
||||
}
|
||||
#[test]
|
||||
fn frozen_step_runs_exactly_the_requested_ticks() {
|
||||
let mut m = ServerTickRateManager::default();
|
||||
m.base.set_frozen(true);
|
||||
m.base.tick();
|
||||
assert!(!m.base.runs_normally());
|
||||
assert!(m.step_game_if_paused(2));
|
||||
for _ in 0..2 {
|
||||
m.base.tick();
|
||||
assert!(m.base.runs_normally());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn pause_discards_only_explicitly_reset_time() {
|
||||
let mut clock = FixedStep::default();
|
||||
assert_eq!(clock.advance(Duration::from_millis(49)), 0);
|
||||
assert_eq!(clock.advance(Duration::from_millis(1)), 1);
|
||||
assert_eq!(clock.advance(Duration::from_millis(24)), 0);
|
||||
clock.reset();
|
||||
assert_eq!(clock.advance(Duration::from_millis(26)), 0);
|
||||
assert_eq!(clock.advance(Duration::from_millis(24)), 1);
|
||||
}
|
||||
#[test]
|
||||
fn rate_changes_the_tick_length() {
|
||||
let mut clock = FixedStep::default();
|
||||
clock.set_rate(40.0);
|
||||
assert_eq!(clock.advance(Duration::from_millis(100)), 4);
|
||||
clock.set_rate(5.0);
|
||||
assert_eq!(clock.advance(Duration::from_millis(400)), 2);
|
||||
clock.set_rate(1.0e9);
|
||||
assert_eq!(clock.rate(), 10000.0);
|
||||
}
|
||||
#[test]
|
||||
fn freeze_step_and_sprint() {
|
||||
let mut clock = FixedStep::default();
|
||||
assert!(clock.world_runs());
|
||||
assert!(!clock.start_step(3), "stepping needs a frozen game");
|
||||
clock.set_frozen(true);
|
||||
assert!(!clock.world_runs());
|
||||
assert!(clock.start_step(2));
|
||||
assert!(clock.world_runs() && clock.world_runs() && !clock.world_runs());
|
||||
assert!(clock.start_step(5) && clock.stop_step() && !clock.stop_step());
|
||||
clock.set_frozen(false);
|
||||
assert!(!clock.start_sprint(100));
|
||||
assert!(clock.sprinting());
|
||||
assert_eq!(clock.advance(Duration::ZERO), SPRINT_PER_FRAME);
|
||||
assert!(clock.stop_sprint() && !clock.sprinting());
|
||||
for ns in [3, 1, 2] {
|
||||
clock.record(Duration::from_nanos(ns));
|
||||
}
|
||||
assert_eq!(clock.average_nanos(), 2);
|
||||
assert_eq!(clock.sorted_samples(), vec![1, 2, 3]);
|
||||
m.base.tick();
|
||||
assert!(!m.base.runs_normally());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,11 +105,13 @@ use horizon_client::{
|
||||
gfx::{Frame, Renderer},
|
||||
hud::{HudAtlas, HudBatch, rgba},
|
||||
items::{ItemStack, Items},
|
||||
keymapping::KeyState,
|
||||
light::LightTables,
|
||||
mesher::{MeshTables, Vertex},
|
||||
mobs::{Mob, MobType, MobTypes},
|
||||
models,
|
||||
motion::{MotionEvent, MotionResources, MotionWorld, PlayerMotion},
|
||||
mouse::{LookOptions, MouseLook, Rotation},
|
||||
particles::Particle,
|
||||
save::{Level, Persistent, SaveDir},
|
||||
settings::Settings,
|
||||
@@ -534,12 +536,24 @@ struct Game<'a> {
|
||||
cursor: (f32, f32),
|
||||
captured: bool,
|
||||
focused: bool,
|
||||
/// MouseHandler's accumulated look and wheel state.
|
||||
mouse: MouseLook,
|
||||
/// `Options.smoothCamera` (cinematic camera), not persisted.
|
||||
smooth_camera: bool,
|
||||
/// Sneak, sprint, attack and use as ToggleKeyMappings.
|
||||
toggles: [KeyState; 4],
|
||||
/// A world screen with the pointer captured was open last frame.
|
||||
was_playing: bool,
|
||||
/// Minecraft.pause: a single-player screen that pauses the game is open.
|
||||
pause: bool,
|
||||
debug: bool,
|
||||
screen: Screen,
|
||||
window: Option<Arc<Window>>,
|
||||
renderer: Option<Renderer>,
|
||||
started: Instant,
|
||||
previous: Instant,
|
||||
/// FramerateLimitTracker.latestInputTime.
|
||||
last_input: Instant,
|
||||
frames: u64,
|
||||
fps: f32,
|
||||
fps_frames: u64,
|
||||
@@ -2631,16 +2645,92 @@ impl Game<'_> {
|
||||
});
|
||||
self.res.block_entity_render.tick(r.block_entities(), eye);
|
||||
}
|
||||
self.tick_particles();
|
||||
if running {
|
||||
self.tick_particles();
|
||||
}
|
||||
if self.right && self.use_delay == 0 && self.screen == Screen::Playing {
|
||||
self.use_item()?;
|
||||
self.use_delay = 4;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Keep the held-key state of toggled sneak and sprint in step with their mapping.
|
||||
fn sync_toggle(&mut self, slot: usize) {
|
||||
let key = [KeyCode::ShiftLeft, KeyCode::ControlLeft][slot];
|
||||
if self.toggles[slot].is_down {
|
||||
self.keys.insert(key);
|
||||
} else {
|
||||
self.keys.remove(&key);
|
||||
}
|
||||
}
|
||||
/// `KeyMapping.releaseAll` when a screen opens and
|
||||
/// `restoreToggleStatesOnScreenClosed` when it closes.
|
||||
fn track_toggle_screens(&mut self) {
|
||||
let playing = self.screen == Screen::Playing && self.title.is_none();
|
||||
if playing == self.was_playing {
|
||||
return;
|
||||
}
|
||||
self.was_playing = playing;
|
||||
let options = [
|
||||
self.settings.toggle_crouch,
|
||||
self.settings.toggle_sprint,
|
||||
self.settings.toggle_attack,
|
||||
self.settings.toggle_use,
|
||||
];
|
||||
for (slot, option) in options.into_iter().enumerate() {
|
||||
if playing {
|
||||
if self.toggles[slot].should_restore_state_on_screen_closed(option) {
|
||||
self.toggles[slot].set_down(true, option);
|
||||
}
|
||||
} else {
|
||||
self.toggles[slot].release(option);
|
||||
}
|
||||
match slot {
|
||||
0 | 1 => self.sync_toggle(slot),
|
||||
2 => self.left = self.toggles[2].is_down,
|
||||
_ => self.right = self.toggles[3].is_down,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `MouseHandler.handleAccumulatedMovement` and `Entity.turn`, once per frame.
|
||||
fn apply_mouse_look(&mut self) {
|
||||
let look = LookOptions {
|
||||
sensitivity: f64::from(self.settings.sensitivity),
|
||||
smooth_camera: self.smooth_camera,
|
||||
scoping: self.scoping(),
|
||||
invert_x: self.settings.invert_x,
|
||||
invert_y: self.settings.invert_y,
|
||||
};
|
||||
let time = self.started.elapsed().as_secs_f64();
|
||||
let grabbed = self.captured && self.screen == Screen::Playing && self.player.is_some();
|
||||
if let Some((xo, yo)) =
|
||||
self.mouse
|
||||
.handle_accumulated_movement(time, self.focused, grabbed, look)
|
||||
{
|
||||
let mut rotation = Rotation {
|
||||
x_rot: self.pitch,
|
||||
y_rot: self.yaw,
|
||||
x_rot_o: self.pitch,
|
||||
y_rot_o: self.yaw,
|
||||
};
|
||||
rotation.turn(xo, yo);
|
||||
self.yaw = rotation.y_rot;
|
||||
self.pitch = rotation.x_rot;
|
||||
}
|
||||
}
|
||||
/// `Minecraft.pause`: a single-player game with a pausing screen open.
|
||||
fn pauses_game(&self) -> bool {
|
||||
self.remote.is_none()
|
||||
&& self.title.is_none()
|
||||
&& (matches!(
|
||||
self.screen,
|
||||
Screen::Paused | Screen::Options | Screen::Stats | Screen::Advancements
|
||||
) || self.book.is_some())
|
||||
}
|
||||
fn capture(&mut self, capture: bool) {
|
||||
let Some(window) = &self.window else { return };
|
||||
if capture {
|
||||
self.mouse.set_ignore_first_move();
|
||||
self.captured = window
|
||||
.set_cursor_grab(CursorGrabMode::Locked)
|
||||
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined))
|
||||
@@ -7106,13 +7196,15 @@ impl Game<'_> {
|
||||
if pressed && self.attack() {
|
||||
return Ok(());
|
||||
}
|
||||
self.left = pressed;
|
||||
self.toggles[2].set_down(pressed, self.settings.toggle_attack);
|
||||
self.left = self.toggles[2].is_down;
|
||||
if pressed {
|
||||
self.destroy_delay = 0;
|
||||
}
|
||||
}
|
||||
MouseButton::Right => {
|
||||
self.right = pressed;
|
||||
self.toggles[3].set_down(pressed, self.settings.toggle_use);
|
||||
self.right = self.toggles[3].is_down;
|
||||
if pressed {
|
||||
self.use_item()?;
|
||||
self.use_delay = 4;
|
||||
@@ -7222,6 +7314,15 @@ impl ApplicationHandler for Game<'_> {
|
||||
if self.window.as_ref().is_none_or(|w| w.id() != id) {
|
||||
return;
|
||||
}
|
||||
if matches!(
|
||||
event,
|
||||
WindowEvent::KeyboardInput { .. }
|
||||
| WindowEvent::MouseInput { .. }
|
||||
| WindowEvent::MouseWheel { .. }
|
||||
| WindowEvent::CursorMoved { .. }
|
||||
) {
|
||||
self.last_input = Instant::now();
|
||||
}
|
||||
let result: Result<()> = (|| {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
@@ -7274,10 +7375,33 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
let d = match delta {
|
||||
MouseScrollDelta::LineDelta(_, y) => y,
|
||||
MouseScrollDelta::PixelDelta(p) => p.y as f32,
|
||||
let (raw_x, raw_y) = match delta {
|
||||
MouseScrollDelta::LineDelta(x, y) => (f64::from(x), f64::from(y)),
|
||||
MouseScrollDelta::PixelDelta(p) => (p.x / 30.0, p.y / 30.0),
|
||||
};
|
||||
// MouseHandler.onScroll: discrete scrolling and the wheel sensitivity.
|
||||
let discrete = self.settings.discrete_scroll;
|
||||
let wheel_sensitivity = f64::from(self.settings.mouse_wheel_sensitivity);
|
||||
let scaled = |v: f64| {
|
||||
(if discrete {
|
||||
horizon_client::mouse::java_signum(v)
|
||||
} else {
|
||||
v
|
||||
}) * wheel_sensitivity
|
||||
};
|
||||
let d = scaled(raw_y) as f32;
|
||||
if self.screen == Screen::Playing
|
||||
&& self.player.is_some()
|
||||
&& let Some((wheel, _)) =
|
||||
self.mouse
|
||||
.on_scroll(raw_x, raw_y, discrete, wheel_sensitivity)
|
||||
{
|
||||
self.selected = horizon_client::mouse::ScrollWheelHandler::next_selection(
|
||||
f64::from(wheel),
|
||||
self.selected as i32,
|
||||
9,
|
||||
) as usize;
|
||||
}
|
||||
if self.screen == Screen::Chat && d != 0.0 {
|
||||
self.chat_scroll(d);
|
||||
}
|
||||
@@ -7300,15 +7424,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.stats_scroll(d);
|
||||
}
|
||||
if self.screen == Screen::Advancements {
|
||||
let x = match delta {
|
||||
MouseScrollDelta::LineDelta(x, _) => x,
|
||||
MouseScrollDelta::PixelDelta(p) => p.x as f32,
|
||||
};
|
||||
self.advancements_scroll(x, d);
|
||||
}
|
||||
if self.screen == Screen::Playing && d != 0.0 {
|
||||
self.selected =
|
||||
(self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize;
|
||||
self.advancements_scroll(scaled(raw_x) as f32, d);
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => {
|
||||
@@ -7513,6 +7629,15 @@ impl ApplicationHandler for Game<'_> {
|
||||
let PhysicalKey::Code(key) = event.physical_key else {
|
||||
return Ok(());
|
||||
};
|
||||
// key.smoothCamera toggles the cinematic camera.
|
||||
if self.screen == Screen::Playing
|
||||
&& event.state == ElementState::Pressed
|
||||
&& !event.repeat
|
||||
&& horizon_client::keybinds::key_name(key)
|
||||
.is_some_and(|n| self.settings.keys.get("key.smoothCamera") == n)
|
||||
{
|
||||
self.smooth_camera = !self.smooth_camera;
|
||||
}
|
||||
// Key binds: act as the default key of the bound mapping.
|
||||
let key = match self.settings.keys.translate(key) {
|
||||
Some(Ok(k)) => k,
|
||||
@@ -7524,11 +7649,27 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
None => return Ok(()),
|
||||
};
|
||||
if event.state != ElementState::Pressed {
|
||||
// Sneak and sprint are ToggleKeyMappings: a press flips them when toggling.
|
||||
let toggle = match key {
|
||||
KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)),
|
||||
KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((slot, option)) = toggle {
|
||||
if !event.repeat {
|
||||
self.toggles[slot]
|
||||
.set_down(event.state == ElementState::Pressed, option);
|
||||
self.sync_toggle(slot);
|
||||
}
|
||||
if event.state != ElementState::Pressed {
|
||||
return Ok(());
|
||||
}
|
||||
} else if event.state != ElementState::Pressed {
|
||||
self.keys.remove(&key);
|
||||
return Ok(());
|
||||
} else {
|
||||
self.keys.insert(key);
|
||||
}
|
||||
self.keys.insert(key);
|
||||
if event.repeat {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -7551,18 +7692,25 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.update_world();
|
||||
self.spawn_player()?;
|
||||
}
|
||||
self.track_toggle_screens();
|
||||
let steps = self.clock.advance(elapsed);
|
||||
for _ in 0..steps {
|
||||
let started = Instant::now();
|
||||
if self.title.is_none() {
|
||||
if self.title.is_none() && !self.pause {
|
||||
self.tick()?;
|
||||
self.tick_ambience();
|
||||
self.tick_fov();
|
||||
}
|
||||
self.tick_music();
|
||||
self.clock.record(started.elapsed());
|
||||
if let Some(report) = self.clock.take_sprint_report() {
|
||||
self.sprint_report(&report);
|
||||
}
|
||||
}
|
||||
self.apply_mouse_look();
|
||||
let rendered = self.render()?;
|
||||
self.pause = self.pauses_game();
|
||||
self.clock.end_frame(self.pause);
|
||||
let finished = self
|
||||
.renderer
|
||||
.as_mut()
|
||||
@@ -7614,12 +7762,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
&& self.screen == Screen::Playing
|
||||
&& let DeviceEvent::MouseMotion { delta: (x, y) } = event
|
||||
{
|
||||
// MouseHandler.turnPlayer at default sensitivity 0.5: 0.15 degrees per count.
|
||||
let s = f64::from(self.settings.sensitivity) * 0.6 + 0.2;
|
||||
// Scoping drops MouseHandler's 8x factor.
|
||||
let f = s * s * s * if self.scoping() { 1.0 } else { 8.0 };
|
||||
self.yaw += (x * f * 0.15) as f32;
|
||||
self.pitch = (self.pitch + (y * f * 0.15) as f32).clamp(-90.0, 90.0);
|
||||
// MouseHandler.onMove with the pointer grabbed; applied once per frame.
|
||||
self.mouse.on_move(0.0, 0.0, x, y, true, true);
|
||||
self.last_input = Instant::now();
|
||||
}
|
||||
}
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
@@ -7820,12 +7965,23 @@ pub fn run() -> Result<()> {
|
||||
cursor: (0.0, 0.0),
|
||||
captured: false,
|
||||
focused: true,
|
||||
mouse: MouseLook::default(),
|
||||
smooth_camera: false,
|
||||
toggles: [
|
||||
KeyState::toggle(true, true),
|
||||
KeyState::toggle(true, true),
|
||||
KeyState::toggle(true, false),
|
||||
KeyState::toggle(false, false),
|
||||
],
|
||||
was_playing: false,
|
||||
pause: false,
|
||||
debug: false,
|
||||
screen: Screen::Playing,
|
||||
window: None,
|
||||
renderer: None,
|
||||
started: now,
|
||||
previous: now,
|
||||
last_input: now,
|
||||
frames: 0,
|
||||
fps: 0.0,
|
||||
fps_frames: 0,
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
//! `/random` (RandomCommand) and `/teammsg` (TeamMsgCommand).
|
||||
use super::{Arg, Context, Game, R, Target, err};
|
||||
use crate::game::chat::PLAYER_NAME;
|
||||
use horizon_client::text::{self, Text};
|
||||
use horizon_client::{
|
||||
clock::SprintReport,
|
||||
java_text::format_fixed,
|
||||
text::{self, Text},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
fn millis(nanos: u64) -> String {
|
||||
format!("{:.1}", nanos as f32 / 1_000_000.0)
|
||||
format_fixed(f64::from(nanos as f32 / 1_000_000.0), 1)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -79,14 +83,14 @@ impl Game<'_> {
|
||||
self.clock.set_rate(rate);
|
||||
self.feedback(t(
|
||||
"commands.tick.rate.success",
|
||||
&[lit(format!("{rate:.1}"))],
|
||||
&[lit(format_fixed(f64::from(rate), 1))],
|
||||
));
|
||||
Ok(rate as i32)
|
||||
}
|
||||
"tick.query" => {
|
||||
let rate = self.clock.rate();
|
||||
let busy = millis(self.clock.average_nanos());
|
||||
let rate_text = format!("{rate:.1}");
|
||||
let rate_text = format_fixed(f64::from(rate), 1);
|
||||
if self.clock.sprinting() {
|
||||
self.feedback(t("commands.tick.status.sprinting", &[]));
|
||||
self.feedback(t(
|
||||
@@ -137,16 +141,19 @@ impl Game<'_> {
|
||||
Ok(1)
|
||||
}
|
||||
"tick.sprint.stop" => {
|
||||
if !self.clock.stop_sprint() {
|
||||
let Some(report) = self.clock.stop_sprint() else {
|
||||
return Err(err("commands.tick.sprint.stop.fail", &[]));
|
||||
}
|
||||
};
|
||||
self.sprint_report(&report);
|
||||
self.feedback(t("commands.tick.sprint.stop.success", &[]));
|
||||
Ok(1)
|
||||
}
|
||||
"tick.freeze" | "tick.unfreeze" => {
|
||||
let freeze = id == "tick.freeze";
|
||||
if freeze {
|
||||
self.clock.stop_sprint();
|
||||
if let Some(report) = self.clock.stop_sprint() {
|
||||
self.sprint_report(&report);
|
||||
}
|
||||
self.clock.stop_step();
|
||||
}
|
||||
self.clock.set_frozen(freeze);
|
||||
@@ -176,6 +183,16 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The report `/tick sprint` prints when a sprint ends.
|
||||
pub(in crate::game) fn sprint_report(&mut self, report: &SprintReport) {
|
||||
self.feedback(Text::translate(
|
||||
"commands.tick.sprint.report",
|
||||
&[
|
||||
Text::literal(report.ticks_per_second.to_string()),
|
||||
Text::literal(report.milliseconds_per_tick.clone()),
|
||||
],
|
||||
));
|
||||
}
|
||||
pub(super) fn cmd_random(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let seed = self.level.seed;
|
||||
if id == "random.reset" {
|
||||
|
||||
@@ -6,6 +6,7 @@ use horizon_client::{
|
||||
hud::HudBatch,
|
||||
lang,
|
||||
options_ui::{Event, Page},
|
||||
window::{FrameContext, InactivityFpsLimit, framerate_limit},
|
||||
};
|
||||
use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen};
|
||||
|
||||
@@ -177,16 +178,33 @@ impl Game<'_> {
|
||||
}
|
||||
/// Frame limiter for the Max Framerate option: when the next frame is due.
|
||||
pub(super) fn next_frame_due(&self) -> Option<std::time::Instant> {
|
||||
let fps = self.settings.max_fps;
|
||||
if fps >= 260 || self.options.frames.is_some() {
|
||||
if self.options.frames.is_some() {
|
||||
return None;
|
||||
}
|
||||
// Menus without a world run at 60 fps like vanilla's title screen.
|
||||
let fps = if self.title.is_some() {
|
||||
fps.min(60)
|
||||
} else {
|
||||
fps
|
||||
// FramerateLimitTracker.getFramerateLimit: the option, throttled when
|
||||
// minimised, idle, or in a menu without a world.
|
||||
let context = FrameContext {
|
||||
inactivity: if self.settings.inactivity_fps_limit == "minimized" {
|
||||
InactivityFpsLimit::Minimized
|
||||
} else {
|
||||
InactivityFpsLimit::Afk
|
||||
},
|
||||
iconified: self
|
||||
.window
|
||||
.as_ref()
|
||||
.is_some_and(|w| w.is_minimized().unwrap_or(false)),
|
||||
focused: self.focused,
|
||||
exclusive_fullscreen: false,
|
||||
now_ms: self.started.elapsed().as_millis() as i64,
|
||||
latest_input_ms: self.last_input.duration_since(self.started).as_millis() as i64,
|
||||
has_level: self.title.is_none(),
|
||||
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;
|
||||
}
|
||||
let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps));
|
||||
(due > std::time::Instant::now()).then_some(due)
|
||||
}
|
||||
|
||||
@@ -919,16 +919,21 @@ impl Renderer {
|
||||
}
|
||||
/// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available.
|
||||
pub fn set_vsync(&mut self, vsync: bool) {
|
||||
let has = |m| self.present_modes.contains(&m);
|
||||
let mode = match (
|
||||
vsync,
|
||||
has(wgpu::PresentMode::Mailbox),
|
||||
has(wgpu::PresentMode::Immediate),
|
||||
) {
|
||||
(true, true, _) => wgpu::PresentMode::Mailbox,
|
||||
(true, false, _) => wgpu::PresentMode::Fifo,
|
||||
(false, _, true) => wgpu::PresentMode::Immediate,
|
||||
(false, true, false) => wgpu::PresentMode::Mailbox,
|
||||
use crate::window::{PresentMode, vsync_present_mode};
|
||||
let supported: Vec<PresentMode> = self
|
||||
.present_modes
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
wgpu::PresentMode::Fifo => Some(PresentMode::Fifo),
|
||||
wgpu::PresentMode::Mailbox => Some(PresentMode::Mailbox),
|
||||
wgpu::PresentMode::Immediate => Some(PresentMode::Immediate),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
// GpuSurface.PresentMode.getSupportedVsyncMode.
|
||||
let mode = match vsync_present_mode(&supported, vsync) {
|
||||
Some(PresentMode::Mailbox) => wgpu::PresentMode::Mailbox,
|
||||
Some(PresentMode::Immediate) => wgpu::PresentMode::Immediate,
|
||||
_ => wgpu::PresentMode::Fifo,
|
||||
};
|
||||
if self.config.present_mode != mode {
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
//! Java text conventions the vanilla option files depend on: shortest-digit
|
||||
//! `Double.toString`/`Float.toString`, Gson's HTML-safe string escaping and a
|
||||
//! reader for Gson's lenient JSON (`JsonParser.parseString`).
|
||||
|
||||
/// Digits and decimal exponent of the shortest round-trip form.
|
||||
fn shortest(text: &str) -> (String, i32) {
|
||||
// `{:e}` yields "d.ddde-5" or "de5".
|
||||
let (mantissa, exponent) = text.split_once('e').unwrap_or((text, "0"));
|
||||
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
|
||||
(digits, exponent.parse().unwrap_or(0))
|
||||
}
|
||||
|
||||
fn render(negative: bool, digits: &str, exponent: i32) -> String {
|
||||
let mut out = String::new();
|
||||
if negative {
|
||||
out.push('-');
|
||||
}
|
||||
let digits = if digits.is_empty() { "0" } else { digits };
|
||||
if (-3..7).contains(&exponent) {
|
||||
if exponent >= 0 {
|
||||
let int_len = exponent as usize + 1;
|
||||
if digits.len() <= int_len {
|
||||
out.push_str(digits);
|
||||
out.extend(std::iter::repeat_n('0', int_len - digits.len()));
|
||||
out.push_str(".0");
|
||||
} else {
|
||||
out.push_str(&digits[..int_len]);
|
||||
out.push('.');
|
||||
out.push_str(&digits[int_len..]);
|
||||
}
|
||||
} else {
|
||||
out.push_str("0.");
|
||||
out.extend(std::iter::repeat_n('0', (-exponent - 1) as usize));
|
||||
out.push_str(digits);
|
||||
}
|
||||
} else {
|
||||
out.push_str(&digits[..1]);
|
||||
out.push('.');
|
||||
if digits.len() > 1 {
|
||||
out.push_str(&digits[1..]);
|
||||
} else {
|
||||
out.push('0');
|
||||
}
|
||||
out.push('E');
|
||||
out.push_str(&exponent.to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `Double.toString`.
|
||||
pub fn double_to_string(value: f64) -> String {
|
||||
if value.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if value.is_infinite() {
|
||||
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
|
||||
}
|
||||
if value == 0.0 {
|
||||
return if value.is_sign_negative() {
|
||||
"-0.0"
|
||||
} else {
|
||||
"0.0"
|
||||
}
|
||||
.into();
|
||||
}
|
||||
let (digits, exponent) = shortest(&format!("{:e}", value.abs()));
|
||||
render(value < 0.0, &digits, exponent)
|
||||
}
|
||||
|
||||
/// `Float.toString`.
|
||||
pub fn float_to_string(value: f32) -> String {
|
||||
if value.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if value.is_infinite() {
|
||||
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
|
||||
}
|
||||
if value == 0.0 {
|
||||
return if value.is_sign_negative() {
|
||||
"-0.0"
|
||||
} else {
|
||||
"0.0"
|
||||
}
|
||||
.into();
|
||||
}
|
||||
let (digits, exponent) = shortest(&format!("{:e}", value.abs()));
|
||||
render(value < 0.0, &digits, exponent)
|
||||
}
|
||||
|
||||
/// Gson's default (HTML-safe) JSON string literal.
|
||||
pub fn gson_string(value: &str) -> String {
|
||||
let mut out = String::from("\"");
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
'\u{8}' => out.push_str("\\b"),
|
||||
'\u{c}' => out.push_str("\\f"),
|
||||
'<' | '>' | '&' | '=' | '\'' | '\u{2028}' | '\u{2029}' => {
|
||||
out.push_str(&format!("\\u{:04x}", c as u32));
|
||||
}
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
/// A parsed JSON element as Gson models it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Json {
|
||||
Null,
|
||||
Bool(bool),
|
||||
/// The number's source text (`LazilyParsedNumber`).
|
||||
Number(String),
|
||||
String(String),
|
||||
Array(Vec<Json>),
|
||||
Object,
|
||||
}
|
||||
|
||||
impl Json {
|
||||
/// `Number.intValue()` of a `LazilyParsedNumber`: `Integer.parseInt`, else
|
||||
/// `BigDecimal.intValue()` (truncate, keep the low 32 bits).
|
||||
pub fn int_value(text: &str) -> i32 {
|
||||
let (negative, body) = match text.strip_prefix('-') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, text),
|
||||
};
|
||||
let (mantissa, exponent) = match body.split_once(['e', 'E']) {
|
||||
Some((m, e)) => (
|
||||
m,
|
||||
e.strip_prefix('+').unwrap_or(e).parse::<i64>().unwrap_or(0),
|
||||
),
|
||||
None => (body, 0),
|
||||
};
|
||||
let (int_part, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
|
||||
let digits: Vec<u32> = int_part
|
||||
.chars()
|
||||
.chain(fraction.chars())
|
||||
.filter_map(|c| c.to_digit(10))
|
||||
.collect();
|
||||
// value = digits * 10^scale; truncating drops digits below the point.
|
||||
let scale = exponent - fraction.len() as i64;
|
||||
let keep = if scale >= 0 {
|
||||
digits.len()
|
||||
} else {
|
||||
digits
|
||||
.len()
|
||||
.saturating_sub(scale.unsigned_abs().min(usize::MAX as u64) as usize)
|
||||
};
|
||||
let mut v: u32 = 0;
|
||||
for d in &digits[..keep] {
|
||||
v = v.wrapping_mul(10).wrapping_add(*d);
|
||||
}
|
||||
if scale > 0 {
|
||||
// v * 10^scale modulo 2^32 by repeated squaring.
|
||||
let (mut base, mut power, mut e) = (10u32, 1u32, scale as u64);
|
||||
while e > 0 {
|
||||
if e & 1 == 1 {
|
||||
power = power.wrapping_mul(base);
|
||||
}
|
||||
base = base.wrapping_mul(base);
|
||||
e >>= 1;
|
||||
}
|
||||
v = v.wrapping_mul(power);
|
||||
}
|
||||
let v = v as i32;
|
||||
if negative { v.wrapping_neg() } else { v }
|
||||
}
|
||||
/// `Number.doubleValue()`.
|
||||
pub fn double_value(text: &str) -> f64 {
|
||||
text.parse::<f64>().unwrap_or(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A syntax error aborts the whole options load, as in vanilla.
|
||||
#[derive(Debug)]
|
||||
pub struct SyntaxError;
|
||||
|
||||
struct Reader {
|
||||
chars: Vec<char>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
fn is_literal(c: char) -> bool {
|
||||
!matches!(
|
||||
c,
|
||||
'/' | '\\'
|
||||
| ';'
|
||||
| '#'
|
||||
| '='
|
||||
| '{'
|
||||
| '}'
|
||||
| '['
|
||||
| ']'
|
||||
| ':'
|
||||
| ','
|
||||
| ' '
|
||||
| '\t'
|
||||
| '\u{c}'
|
||||
| '\r'
|
||||
| '\n'
|
||||
)
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
fn peek_char(&self) -> Option<char> {
|
||||
self.chars.get(self.pos).copied()
|
||||
}
|
||||
/// `nextNonWhitespace` with lenient comments; `None` at the end.
|
||||
fn skip(&mut self) -> Result<Option<char>, SyntaxError> {
|
||||
loop {
|
||||
match self.peek_char() {
|
||||
None => return Ok(None),
|
||||
Some(' ' | '\t' | '\r' | '\n') => self.pos += 1,
|
||||
Some('#') => self.line_comment(),
|
||||
Some('/') => match self.chars.get(self.pos + 1) {
|
||||
Some('/') => self.line_comment(),
|
||||
Some('*') => {
|
||||
self.pos += 2;
|
||||
loop {
|
||||
match (self.peek_char(), self.chars.get(self.pos + 1)) {
|
||||
(Some('*'), Some('/')) => {
|
||||
self.pos += 2;
|
||||
break;
|
||||
}
|
||||
(Some(_), _) => self.pos += 1,
|
||||
(None, _) => return Err(SyntaxError),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Ok(Some('/')),
|
||||
},
|
||||
Some(c) => return Ok(Some(c)),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn line_comment(&mut self) {
|
||||
while let Some(c) = self.peek_char() {
|
||||
self.pos += 1;
|
||||
if c == '\n' || c == '\r' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn quoted(&mut self, quote: char) -> Result<String, SyntaxError> {
|
||||
self.pos += 1;
|
||||
let mut out = String::new();
|
||||
loop {
|
||||
let c = self.peek_char().ok_or(SyntaxError)?;
|
||||
self.pos += 1;
|
||||
if c == quote {
|
||||
return Ok(out);
|
||||
}
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
let e = self.peek_char().ok_or(SyntaxError)?;
|
||||
self.pos += 1;
|
||||
match e {
|
||||
'u' => {
|
||||
let mut v = 0u32;
|
||||
for _ in 0..4 {
|
||||
let d = self.peek_char().ok_or(SyntaxError)?;
|
||||
self.pos += 1;
|
||||
v = v * 16 + d.to_digit(16).ok_or(SyntaxError)?;
|
||||
}
|
||||
// Lone surrogates cannot be represented; keep the replacement.
|
||||
out.push(char::from_u32(v).unwrap_or('\u{fffd}'));
|
||||
}
|
||||
't' => out.push('\t'),
|
||||
'b' => out.push('\u{8}'),
|
||||
'n' => out.push('\n'),
|
||||
'r' => out.push('\r'),
|
||||
'f' => out.push('\u{c}'),
|
||||
'\n' | '\'' | '"' | '\\' | '/' => out.push(e),
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn literal(&mut self) -> String {
|
||||
let start = self.pos;
|
||||
while self.peek_char().is_some_and(is_literal) {
|
||||
self.pos += 1;
|
||||
}
|
||||
self.chars[start..self.pos].iter().collect()
|
||||
}
|
||||
/// JSON number grammar with Gson's leading-zero rule.
|
||||
fn is_number(text: &str) -> bool {
|
||||
let b: Vec<char> = text.chars().collect();
|
||||
let mut i = 0;
|
||||
if b.first() == Some(&'-') {
|
||||
i += 1;
|
||||
}
|
||||
match b.get(i) {
|
||||
Some('0') => {
|
||||
i += 1;
|
||||
}
|
||||
Some(c) if c.is_ascii_digit() => {
|
||||
while b.get(i).is_some_and(char::is_ascii_digit) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
if b.get(i) == Some(&'.') {
|
||||
i += 1;
|
||||
if !b.get(i).is_some_and(char::is_ascii_digit) {
|
||||
return false;
|
||||
}
|
||||
while b.get(i).is_some_and(char::is_ascii_digit) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if matches!(b.get(i), Some('e' | 'E')) {
|
||||
i += 1;
|
||||
if matches!(b.get(i), Some('+' | '-')) {
|
||||
i += 1;
|
||||
}
|
||||
if !b.get(i).is_some_and(char::is_ascii_digit) {
|
||||
return false;
|
||||
}
|
||||
while b.get(i).is_some_and(char::is_ascii_digit) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
i == b.len()
|
||||
}
|
||||
fn keyword(text: &str, word: &str) -> bool {
|
||||
text.len() == word.len() && text.eq_ignore_ascii_case(word)
|
||||
}
|
||||
fn value(&mut self) -> Result<Json, SyntaxError> {
|
||||
let c = self.skip()?.ok_or(SyntaxError)?;
|
||||
match c {
|
||||
'"' | '\'' => Ok(Json::String(self.quoted(c)?)),
|
||||
'[' => {
|
||||
self.pos += 1;
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
match self.skip()?.ok_or(SyntaxError)? {
|
||||
']' => {
|
||||
self.pos += 1;
|
||||
// A trailing separator leaves an implicit null.
|
||||
return Ok(Json::Array(items));
|
||||
}
|
||||
',' | ';' => {
|
||||
self.pos += 1;
|
||||
items.push(Json::Null);
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
items.push(self.value()?);
|
||||
match self.skip()?.ok_or(SyntaxError)? {
|
||||
']' => {
|
||||
self.pos += 1;
|
||||
return Ok(Json::Array(items));
|
||||
}
|
||||
',' | ';' => self.pos += 1,
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
}
|
||||
}
|
||||
'{' => {
|
||||
self.pos += 1;
|
||||
loop {
|
||||
match self.skip()?.ok_or(SyntaxError)? {
|
||||
'}' => {
|
||||
self.pos += 1;
|
||||
return Ok(Json::Object);
|
||||
}
|
||||
'"' | '\'' => {
|
||||
let q = self.skip()?.ok_or(SyntaxError)?;
|
||||
self.quoted(q)?;
|
||||
}
|
||||
c if is_literal(c) => {
|
||||
self.literal();
|
||||
}
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
match self.skip()?.ok_or(SyntaxError)? {
|
||||
':' => self.pos += 1,
|
||||
'=' => {
|
||||
self.pos += 1;
|
||||
if self.peek_char() == Some('>') {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
self.value()?;
|
||||
match self.skip()?.ok_or(SyntaxError)? {
|
||||
'}' => {
|
||||
self.pos += 1;
|
||||
return Ok(Json::Object);
|
||||
}
|
||||
',' | ';' => self.pos += 1,
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
}
|
||||
}
|
||||
']' | '}' | ',' | ';' | ':' | '=' | '\\' | '/' => Err(SyntaxError),
|
||||
_ => {
|
||||
let text = self.literal();
|
||||
if text.is_empty() {
|
||||
return Err(SyntaxError);
|
||||
}
|
||||
if Self::keyword(&text, "true") {
|
||||
Ok(Json::Bool(true))
|
||||
} else if Self::keyword(&text, "false") {
|
||||
Ok(Json::Bool(false))
|
||||
} else if Self::keyword(&text, "null") {
|
||||
Ok(Json::Null)
|
||||
} else if Self::is_number(&text) {
|
||||
Ok(Json::Number(text))
|
||||
} else {
|
||||
Ok(Json::String(text))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `JsonParser.parseString`: one lenient value and nothing after it.
|
||||
pub fn parse_lenient(text: &str) -> Result<Json, SyntaxError> {
|
||||
let text = text.strip_prefix(")]}'\n").unwrap_or(text);
|
||||
let mut reader = Reader {
|
||||
chars: text.chars().collect(),
|
||||
pos: 0,
|
||||
};
|
||||
if reader.skip()?.is_none() {
|
||||
return Ok(Json::Null);
|
||||
}
|
||||
let value = reader.value()?;
|
||||
// The trailing check runs after Gson restored its legacy-strict mode:
|
||||
// only whitespace may follow the value.
|
||||
if value != Json::Null
|
||||
&& reader.chars[reader.pos..]
|
||||
.iter()
|
||||
.any(|c| !matches!(c, ' ' | '\t' | '\r' | '\n'))
|
||||
{
|
||||
return Err(SyntaxError);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
/// Next non-whitespace char in strict mode (comments are errors).
|
||||
fn strict_skip(&mut self) -> Option<char> {
|
||||
while matches!(self.peek_char(), Some(' ' | '\t' | '\r' | '\n')) {
|
||||
self.pos += 1;
|
||||
}
|
||||
self.peek_char()
|
||||
}
|
||||
}
|
||||
|
||||
/// `Gson.getAdapter(List<String>).read` on a strict `JsonReader`
|
||||
/// (`GsonHelper.fromNullableJson`): `Ok(None)` for `null`, an error for
|
||||
/// anything Gson rejects, including an empty document.
|
||||
pub fn parse_strict_string_list(text: &str) -> Result<Option<Vec<String>>, SyntaxError> {
|
||||
let mut r = Reader {
|
||||
chars: text.chars().collect(),
|
||||
pos: 0,
|
||||
};
|
||||
match r.strict_skip().ok_or(SyntaxError)? {
|
||||
'n' => {
|
||||
let word = r.literal();
|
||||
if word == "null" {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(SyntaxError)
|
||||
}
|
||||
}
|
||||
'[' => {
|
||||
r.pos += 1;
|
||||
let mut items = Vec::new();
|
||||
if r.strict_skip().ok_or(SyntaxError)? == ']' {
|
||||
return Ok(Some(items));
|
||||
}
|
||||
loop {
|
||||
let c = r.strict_skip().ok_or(SyntaxError)?;
|
||||
match c {
|
||||
'"' => items.push(r.quoted('"')?),
|
||||
'-' | '0'..='9' => {
|
||||
let word = r.literal();
|
||||
if !Reader::is_number(&word) {
|
||||
return Err(SyntaxError);
|
||||
}
|
||||
items.push(word);
|
||||
}
|
||||
't' | 'f' | 'n' => {
|
||||
let word = r.literal();
|
||||
match word.as_str() {
|
||||
"true" | "false" => items.push(word),
|
||||
"null" => {}
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
}
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
match r.strict_skip().ok_or(SyntaxError)? {
|
||||
',' => r.pos += 1,
|
||||
']' => return Ok(Some(items)),
|
||||
_ => return Err(SyntaxError),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err(SyntaxError),
|
||||
}
|
||||
}
|
||||
|
||||
/// `String.format(Locale.ROOT, "%.<n>f", value)`: Java rounds the shortest
|
||||
/// round-trip decimal expansion half-up (so 1.005 gives 1.01).
|
||||
pub fn format_fixed(value: f64, decimals: usize) -> String {
|
||||
if value.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if value.is_infinite() {
|
||||
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
|
||||
}
|
||||
let negative = value.is_sign_negative();
|
||||
let (digits, exponent) = if value == 0.0 {
|
||||
("0".to_owned(), 0)
|
||||
} else {
|
||||
shortest(&format!("{:e}", value.abs()))
|
||||
};
|
||||
let mut int_part: Vec<u8> = Vec::new();
|
||||
let mut frac: Vec<u8> = Vec::new();
|
||||
let d: Vec<u8> = digits.bytes().map(|b| b - b'0').collect();
|
||||
let point = exponent + 1; // digits before the decimal point
|
||||
if point <= 0 {
|
||||
int_part.push(0);
|
||||
frac.extend(std::iter::repeat_n(0, (-point) as usize));
|
||||
frac.extend(&d);
|
||||
} else {
|
||||
let point = point as usize;
|
||||
for i in 0..point {
|
||||
int_part.push(d.get(i).copied().unwrap_or(0));
|
||||
}
|
||||
if d.len() > point {
|
||||
frac.extend(&d[point..]);
|
||||
}
|
||||
}
|
||||
let round_up = frac.get(decimals).is_some_and(|&x| x >= 5);
|
||||
frac.truncate(decimals);
|
||||
frac.resize(decimals, 0);
|
||||
if round_up {
|
||||
let mut carry = true;
|
||||
for x in frac.iter_mut().rev().chain(int_part.iter_mut().rev()) {
|
||||
if !carry {
|
||||
break;
|
||||
}
|
||||
if *x == 9 {
|
||||
*x = 0;
|
||||
} else {
|
||||
*x += 1;
|
||||
carry = false;
|
||||
}
|
||||
}
|
||||
if carry {
|
||||
int_part.insert(0, 1);
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
if negative {
|
||||
out.push('-');
|
||||
}
|
||||
out.extend(int_part.iter().map(|&x| (b'0' + x) as char));
|
||||
if decimals > 0 {
|
||||
out.push('.');
|
||||
out.extend(frac.iter().map(|&x| (b'0' + x) as char));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `%.2f`.
|
||||
pub fn format_fixed2(value: f64) -> String {
|
||||
format_fixed(value, 2)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn java_number_text() {
|
||||
assert_eq!(double_to_string(1.0), "1.0");
|
||||
assert_eq!(double_to_string(0.5), "0.5");
|
||||
assert_eq!(double_to_string(0.0001), "1.0E-4");
|
||||
assert_eq!(double_to_string(0.001), "0.001");
|
||||
assert_eq!(double_to_string(1234567.0), "1234567.0");
|
||||
assert_eq!(double_to_string(12345678.0), "1.2345678E7");
|
||||
assert_eq!(double_to_string(100.0), "100.0");
|
||||
assert_eq!(float_to_string(0.15), "0.15");
|
||||
assert_eq!(float_to_string(1.0e10), "1.0E10");
|
||||
assert_eq!(double_to_string(-2.5), "-2.5");
|
||||
}
|
||||
#[test]
|
||||
fn lenient_json() {
|
||||
assert_eq!(parse_lenient("0.5").unwrap(), Json::Number("0.5".into()));
|
||||
assert_eq!(parse_lenient("fast").unwrap(), Json::String("fast".into()));
|
||||
assert_eq!(parse_lenient("TRUE").unwrap(), Json::Bool(true));
|
||||
assert_eq!(parse_lenient("007").unwrap(), Json::String("007".into()));
|
||||
assert!(parse_lenient("1 2").is_err());
|
||||
assert!(parse_lenient("\"abc").is_err());
|
||||
assert_eq!(parse_lenient(" ").unwrap(), Json::Null);
|
||||
assert_eq!(gson_string("a=b"), "\"a\\u003db\"");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! InputConstants key tables of 26.3 (SDL scancodes), generated from the
|
||||
//! pinned client by `VanillaOptionsTableExporter`.
|
||||
|
||||
/// Keyboard keys: (SDL scancode, key name).
|
||||
pub const KEYBOARD: &[(i32, &str)] = &[
|
||||
(0, "key.keyboard.unknown"),
|
||||
(4, "key.keyboard.a"),
|
||||
(5, "key.keyboard.b"),
|
||||
(6, "key.keyboard.c"),
|
||||
(7, "key.keyboard.d"),
|
||||
(8, "key.keyboard.e"),
|
||||
(9, "key.keyboard.f"),
|
||||
(10, "key.keyboard.g"),
|
||||
(11, "key.keyboard.h"),
|
||||
(12, "key.keyboard.i"),
|
||||
(13, "key.keyboard.j"),
|
||||
(14, "key.keyboard.k"),
|
||||
(15, "key.keyboard.l"),
|
||||
(16, "key.keyboard.m"),
|
||||
(17, "key.keyboard.n"),
|
||||
(18, "key.keyboard.o"),
|
||||
(19, "key.keyboard.p"),
|
||||
(20, "key.keyboard.q"),
|
||||
(21, "key.keyboard.r"),
|
||||
(22, "key.keyboard.s"),
|
||||
(23, "key.keyboard.t"),
|
||||
(24, "key.keyboard.u"),
|
||||
(25, "key.keyboard.v"),
|
||||
(26, "key.keyboard.w"),
|
||||
(27, "key.keyboard.x"),
|
||||
(28, "key.keyboard.y"),
|
||||
(29, "key.keyboard.z"),
|
||||
(30, "key.keyboard.1"),
|
||||
(31, "key.keyboard.2"),
|
||||
(32, "key.keyboard.3"),
|
||||
(33, "key.keyboard.4"),
|
||||
(34, "key.keyboard.5"),
|
||||
(35, "key.keyboard.6"),
|
||||
(36, "key.keyboard.7"),
|
||||
(37, "key.keyboard.8"),
|
||||
(38, "key.keyboard.9"),
|
||||
(39, "key.keyboard.0"),
|
||||
(40, "key.keyboard.enter"),
|
||||
(41, "key.keyboard.escape"),
|
||||
(42, "key.keyboard.backspace"),
|
||||
(43, "key.keyboard.tab"),
|
||||
(44, "key.keyboard.space"),
|
||||
(45, "key.keyboard.minus"),
|
||||
(46, "key.keyboard.equal"),
|
||||
(47, "key.keyboard.left.bracket"),
|
||||
(48, "key.keyboard.right.bracket"),
|
||||
(49, "key.keyboard.backslash"),
|
||||
(50, "key.keyboard.world.2"),
|
||||
(51, "key.keyboard.semicolon"),
|
||||
(52, "key.keyboard.apostrophe"),
|
||||
(53, "key.keyboard.grave.accent"),
|
||||
(54, "key.keyboard.comma"),
|
||||
(55, "key.keyboard.period"),
|
||||
(56, "key.keyboard.slash"),
|
||||
(57, "key.keyboard.caps.lock"),
|
||||
(58, "key.keyboard.f1"),
|
||||
(59, "key.keyboard.f2"),
|
||||
(60, "key.keyboard.f3"),
|
||||
(61, "key.keyboard.f4"),
|
||||
(62, "key.keyboard.f5"),
|
||||
(63, "key.keyboard.f6"),
|
||||
(64, "key.keyboard.f7"),
|
||||
(65, "key.keyboard.f8"),
|
||||
(66, "key.keyboard.f9"),
|
||||
(67, "key.keyboard.f10"),
|
||||
(68, "key.keyboard.f11"),
|
||||
(69, "key.keyboard.f12"),
|
||||
(70, "key.keyboard.print.screen"),
|
||||
(71, "key.keyboard.scroll.lock"),
|
||||
(72, "key.keyboard.pause"),
|
||||
(73, "key.keyboard.insert"),
|
||||
(74, "key.keyboard.home"),
|
||||
(75, "key.keyboard.page.up"),
|
||||
(76, "key.keyboard.delete"),
|
||||
(77, "key.keyboard.end"),
|
||||
(78, "key.keyboard.page.down"),
|
||||
(79, "key.keyboard.right"),
|
||||
(80, "key.keyboard.left"),
|
||||
(81, "key.keyboard.down"),
|
||||
(82, "key.keyboard.up"),
|
||||
(83, "key.keyboard.num.lock"),
|
||||
(84, "key.keyboard.keypad.divide"),
|
||||
(85, "key.keyboard.keypad.multiply"),
|
||||
(86, "key.keyboard.keypad.subtract"),
|
||||
(87, "key.keyboard.keypad.add"),
|
||||
(88, "key.keyboard.keypad.enter"),
|
||||
(89, "key.keyboard.keypad.1"),
|
||||
(90, "key.keyboard.keypad.2"),
|
||||
(91, "key.keyboard.keypad.3"),
|
||||
(92, "key.keyboard.keypad.4"),
|
||||
(93, "key.keyboard.keypad.5"),
|
||||
(94, "key.keyboard.keypad.6"),
|
||||
(95, "key.keyboard.keypad.7"),
|
||||
(96, "key.keyboard.keypad.8"),
|
||||
(97, "key.keyboard.keypad.9"),
|
||||
(98, "key.keyboard.keypad.0"),
|
||||
(99, "key.keyboard.keypad.period"),
|
||||
(100, "key.keyboard.world.1"),
|
||||
(101, "key.keyboard.application"),
|
||||
(102, "key.keyboard.power"),
|
||||
(103, "key.keyboard.keypad.equal"),
|
||||
(104, "key.keyboard.f13"),
|
||||
(105, "key.keyboard.f14"),
|
||||
(106, "key.keyboard.f15"),
|
||||
(107, "key.keyboard.f16"),
|
||||
(108, "key.keyboard.f17"),
|
||||
(109, "key.keyboard.f18"),
|
||||
(110, "key.keyboard.f19"),
|
||||
(111, "key.keyboard.f20"),
|
||||
(112, "key.keyboard.f21"),
|
||||
(113, "key.keyboard.f22"),
|
||||
(114, "key.keyboard.f23"),
|
||||
(115, "key.keyboard.f24"),
|
||||
(116, "key.keyboard.execute"),
|
||||
(117, "key.keyboard.help"),
|
||||
(118, "key.keyboard.menu"),
|
||||
(119, "key.keyboard.select"),
|
||||
(120, "key.keyboard.stop"),
|
||||
(121, "key.keyboard.again"),
|
||||
(122, "key.keyboard.undo"),
|
||||
(123, "key.keyboard.cut"),
|
||||
(124, "key.keyboard.copy"),
|
||||
(125, "key.keyboard.paste"),
|
||||
(126, "key.keyboard.find"),
|
||||
(127, "key.keyboard.mute"),
|
||||
(128, "key.keyboard.volume.up"),
|
||||
(129, "key.keyboard.volume.down"),
|
||||
(133, "key.keyboard.keypad.comma"),
|
||||
(134, "key.keyboard.keypad.equals.as400"),
|
||||
(135, "key.keyboard.international1"),
|
||||
(136, "key.keyboard.international2"),
|
||||
(137, "key.keyboard.international3"),
|
||||
(138, "key.keyboard.international4"),
|
||||
(139, "key.keyboard.international5"),
|
||||
(140, "key.keyboard.international6"),
|
||||
(141, "key.keyboard.international7"),
|
||||
(142, "key.keyboard.international8"),
|
||||
(143, "key.keyboard.international9"),
|
||||
(144, "key.keyboard.lang1"),
|
||||
(145, "key.keyboard.lang2"),
|
||||
(146, "key.keyboard.lang3"),
|
||||
(147, "key.keyboard.lang4"),
|
||||
(148, "key.keyboard.lang5"),
|
||||
(149, "key.keyboard.lang6"),
|
||||
(150, "key.keyboard.lang7"),
|
||||
(151, "key.keyboard.lang8"),
|
||||
(152, "key.keyboard.lang9"),
|
||||
(153, "key.keyboard.alternate.erase"),
|
||||
(154, "key.keyboard.sys.req"),
|
||||
(155, "key.keyboard.cancel"),
|
||||
(156, "key.keyboard.clear"),
|
||||
(157, "key.keyboard.prior"),
|
||||
(158, "key.keyboard.enter2"),
|
||||
(159, "key.keyboard.separator"),
|
||||
(160, "key.keyboard.out"),
|
||||
(161, "key.keyboard.oper"),
|
||||
(162, "key.keyboard.clear.again"),
|
||||
(163, "key.keyboard.crsel"),
|
||||
(164, "key.keyboard.exsel"),
|
||||
(176, "key.keyboard.keypad.00"),
|
||||
(177, "key.keyboard.keypad.000"),
|
||||
(178, "key.keyboard.thousands.separator"),
|
||||
(179, "key.keyboard.decimal.separator"),
|
||||
(180, "key.keyboard.currency.unit"),
|
||||
(181, "key.keyboard.currency.subunit"),
|
||||
(182, "key.keyboard.keypad.left.parenthesis"),
|
||||
(183, "key.keyboard.keypad.right.parenthesis"),
|
||||
(184, "key.keyboard.keypad.left.brace"),
|
||||
(185, "key.keyboard.keypad.right.brace"),
|
||||
(186, "key.keyboard.keypad.tab"),
|
||||
(187, "key.keyboard.keypad.backspace"),
|
||||
(188, "key.keyboard.keypad.a"),
|
||||
(189, "key.keyboard.keypad.b"),
|
||||
(190, "key.keyboard.keypad.c"),
|
||||
(191, "key.keyboard.keypad.d"),
|
||||
(192, "key.keyboard.keypad.e"),
|
||||
(193, "key.keyboard.keypad.f"),
|
||||
(194, "key.keyboard.keypad.xor"),
|
||||
(195, "key.keyboard.keypad.power"),
|
||||
(196, "key.keyboard.keypad.percent"),
|
||||
(197, "key.keyboard.keypad.less"),
|
||||
(198, "key.keyboard.keypad.greater"),
|
||||
(199, "key.keyboard.keypad.ampersand"),
|
||||
(200, "key.keyboard.keypad.double.ampersand"),
|
||||
(201, "key.keyboard.keypad.vertical.bar"),
|
||||
(202, "key.keyboard.keypad.double.vertical.bar"),
|
||||
(203, "key.keyboard.keypad.colon"),
|
||||
(204, "key.keyboard.keypad.hash"),
|
||||
(205, "key.keyboard.keypad.space"),
|
||||
(206, "key.keyboard.keypad.at"),
|
||||
(207, "key.keyboard.keypad.exclamation"),
|
||||
(208, "key.keyboard.keypad.memory.store"),
|
||||
(209, "key.keyboard.keypad.memory.recall"),
|
||||
(210, "key.keyboard.keypad.memory.clear"),
|
||||
(211, "key.keyboard.keypad.memory.add"),
|
||||
(212, "key.keyboard.keypad.memory.subtract"),
|
||||
(213, "key.keyboard.keypad.memory.multiply"),
|
||||
(214, "key.keyboard.keypad.memory.divide"),
|
||||
(215, "key.keyboard.keypad.plus.minus"),
|
||||
(216, "key.keyboard.keypad.clear"),
|
||||
(217, "key.keyboard.keypad.clear.entry"),
|
||||
(218, "key.keyboard.keypad.binary"),
|
||||
(219, "key.keyboard.keypad.octal"),
|
||||
(220, "key.keyboard.keypad.decimal"),
|
||||
(221, "key.keyboard.keypad.hexadecimal"),
|
||||
(224, "key.keyboard.left.control"),
|
||||
(225, "key.keyboard.left.shift"),
|
||||
(226, "key.keyboard.left.alt"),
|
||||
(227, "key.keyboard.left.win"),
|
||||
(228, "key.keyboard.right.control"),
|
||||
(229, "key.keyboard.right.shift"),
|
||||
(230, "key.keyboard.right.alt"),
|
||||
(231, "key.keyboard.right.win"),
|
||||
(257, "key.keyboard.mode"),
|
||||
(258, "key.keyboard.sleep"),
|
||||
(259, "key.keyboard.wake"),
|
||||
(260, "key.keyboard.channel.up"),
|
||||
(261, "key.keyboard.channel.down"),
|
||||
(262, "key.keyboard.media.play"),
|
||||
(263, "key.keyboard.media.pause"),
|
||||
(264, "key.keyboard.media.record"),
|
||||
(265, "key.keyboard.media.fast.forward"),
|
||||
(266, "key.keyboard.media.rewind"),
|
||||
(267, "key.keyboard.media.next.track"),
|
||||
(268, "key.keyboard.media.previous.track"),
|
||||
(269, "key.keyboard.media.stop"),
|
||||
(270, "key.keyboard.media.eject"),
|
||||
(271, "key.keyboard.media.play.pause"),
|
||||
(272, "key.keyboard.media.select"),
|
||||
(273, "key.keyboard.ac.new"),
|
||||
(274, "key.keyboard.ac.open"),
|
||||
(275, "key.keyboard.ac.close"),
|
||||
(276, "key.keyboard.ac.exit"),
|
||||
(277, "key.keyboard.ac.save"),
|
||||
(278, "key.keyboard.ac.print"),
|
||||
(279, "key.keyboard.ac.properties"),
|
||||
(280, "key.keyboard.ac.search"),
|
||||
(281, "key.keyboard.ac.home"),
|
||||
(282, "key.keyboard.ac.back"),
|
||||
(283, "key.keyboard.ac.forward"),
|
||||
(284, "key.keyboard.ac.stop"),
|
||||
(285, "key.keyboard.ac.refresh"),
|
||||
(286, "key.keyboard.ac.bookmarks"),
|
||||
(287, "key.keyboard.soft.left"),
|
||||
(288, "key.keyboard.soft.right"),
|
||||
(289, "key.keyboard.call"),
|
||||
(290, "key.keyboard.end.call"),
|
||||
];
|
||||
|
||||
/// Mouse buttons: (button number, key name).
|
||||
pub const MOUSE: &[(i32, &str)] = &[
|
||||
(1, "key.mouse.left"),
|
||||
(2, "key.mouse.middle"),
|
||||
(3, "key.mouse.right"),
|
||||
(4, "key.mouse.4"),
|
||||
(5, "key.mouse.5"),
|
||||
(6, "key.mouse.6"),
|
||||
(7, "key.mouse.7"),
|
||||
(8, "key.mouse.8"),
|
||||
];
|
||||
@@ -43,6 +43,7 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[
|
||||
("key.advancements", "key.keyboard.l", "misc"),
|
||||
("key.quickActions", "key.keyboard.g", "misc"),
|
||||
("key.debug.overlay", "key.keyboard.f3", "debug"),
|
||||
("key.debug.modifier", "key.keyboard.f3", "debug"),
|
||||
("key.hotbar.1", "key.keyboard.1", "inventory"),
|
||||
("key.hotbar.2", "key.keyboard.2", "inventory"),
|
||||
("key.hotbar.3", "key.keyboard.3", "inventory"),
|
||||
@@ -52,7 +53,32 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[
|
||||
("key.hotbar.7", "key.keyboard.7", "inventory"),
|
||||
("key.hotbar.8", "key.keyboard.8", "inventory"),
|
||||
("key.hotbar.9", "key.keyboard.9", "inventory"),
|
||||
("key.debug.reloadChunk", "key.keyboard.a", "debug"),
|
||||
("key.debug.showHitboxes", "key.keyboard.b", "debug"),
|
||||
("key.debug.clearChat", "key.keyboard.d", "debug"),
|
||||
("key.debug.crash", "key.keyboard.c", "debug"),
|
||||
("key.debug.showChunkBorders", "key.keyboard.g", "debug"),
|
||||
("key.debug.showAdvancedTooltips", "key.keyboard.h", "debug"),
|
||||
("key.debug.copyRecreateCommand", "key.keyboard.i", "debug"),
|
||||
("key.debug.spectate", "key.keyboard.n", "debug"),
|
||||
("key.debug.switchGameMode", "key.keyboard.f4", "debug"),
|
||||
("key.debug.debugOptions", "key.keyboard.f6", "debug"),
|
||||
("key.debug.focusPause", "key.keyboard.p", "debug"),
|
||||
("key.debug.dumpDynamicTextures", "key.keyboard.s", "debug"),
|
||||
("key.debug.reloadResourcePacks", "key.keyboard.t", "debug"),
|
||||
("key.debug.profiling", "key.keyboard.l", "debug"),
|
||||
("key.debug.copyLocation", "key.keyboard.c", "debug"),
|
||||
("key.debug.dumpVersion", "key.keyboard.v", "debug"),
|
||||
("key.debug.profilingChart", "key.keyboard.1", "debug"),
|
||||
("key.debug.fpsCharts", "key.keyboard.2", "debug"),
|
||||
("key.debug.networkCharts", "key.keyboard.3", "debug"),
|
||||
("key.debug.lightmapTexture", "key.keyboard.4", "debug"),
|
||||
("key.debug.improvedTransparency", "key.keyboard.x", "debug"),
|
||||
];
|
||||
/// Mappings Options builds as `ToggleKeyMapping` (hold or toggle by option).
|
||||
pub fn is_toggle(name: &str) -> bool {
|
||||
matches!(name, "key.sneak" | "key.sprint" | "key.use" | "key.attack")
|
||||
}
|
||||
/// KeyMapping.Category sort order.
|
||||
pub const CATEGORIES: [&str; 8] = [
|
||||
"movement",
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! The down/click state of `KeyMapping` and `ToggleKeyMapping` (sneak,
|
||||
//! sprint, attack and use can be toggled instead of held).
|
||||
|
||||
/// One mapping's runtime state. `toggle` is `Some(restore)` for a
|
||||
/// `ToggleKeyMapping` (with its `shouldRestore` flag), `None` for a plain one.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct KeyState {
|
||||
pub is_down: bool,
|
||||
click_count: i32,
|
||||
released_by_screen_when_down: bool,
|
||||
toggle: Option<bool>,
|
||||
keyboard: bool,
|
||||
}
|
||||
|
||||
impl KeyState {
|
||||
pub fn plain() -> Self {
|
||||
Self {
|
||||
is_down: false,
|
||||
click_count: 0,
|
||||
released_by_screen_when_down: false,
|
||||
toggle: None,
|
||||
keyboard: true,
|
||||
}
|
||||
}
|
||||
/// A `ToggleKeyMapping`; `keyboard` is whether the bound key is a keyboard key.
|
||||
pub fn toggle(should_restore: bool, keyboard: bool) -> Self {
|
||||
Self {
|
||||
toggle: Some(should_restore),
|
||||
keyboard,
|
||||
..Self::plain()
|
||||
}
|
||||
}
|
||||
/// `KeyMapping.click`: one more pending click.
|
||||
pub fn click(&mut self) {
|
||||
self.click_count += 1;
|
||||
}
|
||||
/// `consumeClick`.
|
||||
pub fn consume_click(&mut self) -> bool {
|
||||
if self.click_count == 0 {
|
||||
false
|
||||
} else {
|
||||
self.click_count -= 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
/// `setDown`; `needs_toggle` is the mapping's option value.
|
||||
pub fn set_down(&mut self, down: bool, needs_toggle: bool) {
|
||||
if self.toggle.is_some() && needs_toggle {
|
||||
if down {
|
||||
self.is_down = !self.is_down;
|
||||
}
|
||||
} else {
|
||||
self.is_down = down;
|
||||
}
|
||||
}
|
||||
/// `shouldSetOnIngameFocus` for a keyboard-bound, bound key.
|
||||
pub fn should_set_on_ingame_focus(&self, needs_toggle: bool) -> bool {
|
||||
self.keyboard && (self.toggle.is_none() || !needs_toggle)
|
||||
}
|
||||
/// `release` (a screen opened): drops pending clicks and the held state.
|
||||
pub fn release(&mut self, needs_toggle: bool) {
|
||||
if self.toggle.is_some() {
|
||||
// ToggleKeyMapping.release does not clear pending clicks.
|
||||
if needs_toggle && self.is_down || self.released_by_screen_when_down {
|
||||
self.released_by_screen_when_down = true;
|
||||
}
|
||||
self.reset();
|
||||
} else {
|
||||
self.click_count = 0;
|
||||
self.set_down(false, needs_toggle);
|
||||
}
|
||||
}
|
||||
/// `ToggleKeyMapping.reset`.
|
||||
pub fn reset(&mut self) {
|
||||
self.is_down = false;
|
||||
}
|
||||
/// `shouldRestoreStateOnScreenClosed` (clears the remembered release).
|
||||
pub fn should_restore_state_on_screen_closed(&mut self, needs_toggle: bool) -> bool {
|
||||
let Some(restore) = self.toggle else {
|
||||
return false;
|
||||
};
|
||||
let result = restore && needs_toggle && self.keyboard && self.released_by_screen_when_down;
|
||||
self.released_by_screen_when_down = false;
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn toggle_flips_on_press_and_ignores_release() {
|
||||
let mut k = KeyState::toggle(true, true);
|
||||
k.set_down(true, true);
|
||||
assert!(k.is_down);
|
||||
k.set_down(false, true);
|
||||
assert!(k.is_down);
|
||||
k.set_down(true, true);
|
||||
assert!(!k.is_down);
|
||||
}
|
||||
#[test]
|
||||
fn screen_release_restores_toggled_state() {
|
||||
let mut k = KeyState::toggle(true, true);
|
||||
k.set_down(true, true);
|
||||
k.release(true);
|
||||
assert!(!k.is_down);
|
||||
assert!(k.should_restore_state_on_screen_closed(true));
|
||||
assert!(!k.should_restore_state_on_screen_closed(true));
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,10 @@ pub mod hunger;
|
||||
pub mod input;
|
||||
pub mod item_data;
|
||||
pub mod items;
|
||||
pub mod java_text;
|
||||
pub mod key_names;
|
||||
pub mod keybinds;
|
||||
pub mod keymapping;
|
||||
pub mod lan;
|
||||
pub mod landing;
|
||||
pub mod lang;
|
||||
@@ -53,10 +56,13 @@ pub mod mesher;
|
||||
pub mod mobs;
|
||||
pub mod models;
|
||||
pub mod motion;
|
||||
pub mod mouse;
|
||||
pub mod multiplayer;
|
||||
pub mod music;
|
||||
pub mod nbt_path;
|
||||
pub mod net;
|
||||
pub mod options_file;
|
||||
pub mod options_fixes;
|
||||
pub mod options_ui;
|
||||
pub mod packs;
|
||||
pub mod particles;
|
||||
@@ -86,6 +92,7 @@ pub mod text;
|
||||
pub mod title;
|
||||
pub mod ui;
|
||||
pub mod vanillagen;
|
||||
pub mod window;
|
||||
pub mod world;
|
||||
pub mod worldborder;
|
||||
pub mod zip;
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
//! Mouse look and scrolling of 26.3: `MouseHandler` (accumulated movement,
|
||||
//! sensitivity curve, cinematic smoothing, inversion), `SmoothDouble`,
|
||||
//! `ScrollWheelHandler` and `Entity.turn`.
|
||||
|
||||
/// `SmoothDouble`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SmoothDouble {
|
||||
target_value: f64,
|
||||
remaining_value: f64,
|
||||
last_amount: f64,
|
||||
}
|
||||
|
||||
impl SmoothDouble {
|
||||
pub fn get_new_delta_value(&mut self, target_delta: f64, time: f64) -> f64 {
|
||||
self.target_value += target_delta;
|
||||
let mut delta = self.target_value - self.remaining_value;
|
||||
let new_last_amount = self.last_amount + 0.5 * (delta - self.last_amount);
|
||||
let delta_sign = java_signum(delta);
|
||||
if delta_sign * delta > delta_sign * self.last_amount {
|
||||
delta = new_last_amount;
|
||||
}
|
||||
self.last_amount = new_last_amount;
|
||||
self.remaining_value += delta * time;
|
||||
delta * time
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// `Math.signum(double)`.
|
||||
pub fn java_signum(v: f64) -> f64 {
|
||||
if v == 0.0 || v.is_nan() {
|
||||
v
|
||||
} else {
|
||||
v.signum()
|
||||
}
|
||||
}
|
||||
|
||||
/// `ScrollWheelHandler`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ScrollWheelHandler {
|
||||
accumulated_x: f64,
|
||||
accumulated_y: f64,
|
||||
}
|
||||
|
||||
impl ScrollWheelHandler {
|
||||
/// `onMouseScroll`: whole wheel steps `(x, y)` once enough has accumulated.
|
||||
pub fn on_mouse_scroll(&mut self, x: f64, y: f64) -> (i32, i32) {
|
||||
if self.accumulated_x != 0.0 && java_signum(x) != java_signum(self.accumulated_x) {
|
||||
self.accumulated_x = 0.0;
|
||||
}
|
||||
if self.accumulated_y != 0.0 && java_signum(y) != java_signum(self.accumulated_y) {
|
||||
self.accumulated_y = 0.0;
|
||||
}
|
||||
self.accumulated_x += x;
|
||||
self.accumulated_y += y;
|
||||
// Java's double-to-int cast saturates and maps NaN to zero, like Rust's.
|
||||
let wheel_x = self.accumulated_x as i32;
|
||||
let wheel_y = self.accumulated_y as i32;
|
||||
if wheel_x == 0 && wheel_y == 0 {
|
||||
return (0, 0);
|
||||
}
|
||||
self.accumulated_x -= f64::from(wheel_x);
|
||||
self.accumulated_y -= f64::from(wheel_y);
|
||||
(wheel_x, wheel_y)
|
||||
}
|
||||
|
||||
/// `getNextScrollWheelSelection`.
|
||||
pub fn next_selection(wheel: f64, current_selected: i32, limit: i32) -> i32 {
|
||||
let step = java_signum(wheel) as i32;
|
||||
let mut current = (current_selected - step).max(-1);
|
||||
while current < 0 {
|
||||
current += limit;
|
||||
}
|
||||
while current >= limit {
|
||||
current -= limit;
|
||||
}
|
||||
current
|
||||
}
|
||||
}
|
||||
|
||||
/// Entity rotation as `Entity.turn` keeps it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Rotation {
|
||||
pub x_rot: f32,
|
||||
pub y_rot: f32,
|
||||
pub x_rot_o: f32,
|
||||
pub y_rot_o: f32,
|
||||
}
|
||||
|
||||
impl Rotation {
|
||||
fn set_x_rot(&mut self, x_rot: f32) {
|
||||
if x_rot.is_finite() {
|
||||
self.x_rot = (x_rot % 360.0).clamp(-90.0, 90.0);
|
||||
}
|
||||
}
|
||||
fn set_y_rot(&mut self, y_rot: f32) {
|
||||
if y_rot.is_finite() {
|
||||
self.y_rot = y_rot;
|
||||
}
|
||||
}
|
||||
/// `Entity.turn(xo, yo)`: mouse deltas in, 0.15 degrees per unit, pitch clamped.
|
||||
pub fn turn(&mut self, xo: f64, yo: f64) {
|
||||
let x_delta = (yo as f32) * 0.15;
|
||||
let y_delta = (xo as f32) * 0.15;
|
||||
self.set_x_rot(self.x_rot + x_delta);
|
||||
self.set_y_rot(self.y_rot + y_delta);
|
||||
self.set_x_rot(mth_clamp(self.x_rot, -90.0, 90.0));
|
||||
self.x_rot_o += x_delta;
|
||||
self.y_rot_o += y_delta;
|
||||
self.x_rot_o = mth_clamp(self.x_rot_o, -90.0, 90.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `Mth.clamp(float, float, float)`.
|
||||
pub fn mth_clamp(value: f32, min: f32, max: f32) -> f32 {
|
||||
if value < min {
|
||||
min
|
||||
} else if value.is_nan() || max.is_nan() {
|
||||
f32::NAN
|
||||
} else {
|
||||
value.min(max)
|
||||
}
|
||||
}
|
||||
|
||||
/// The options `turnPlayer` reads.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct LookOptions {
|
||||
pub sensitivity: f64,
|
||||
pub smooth_camera: bool,
|
||||
/// First-person camera and the player is scoping (spyglass).
|
||||
pub scoping: bool,
|
||||
pub invert_x: bool,
|
||||
pub invert_y: bool,
|
||||
}
|
||||
|
||||
/// The input state of `MouseHandler` that drives the camera and the hotbar.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MouseLook {
|
||||
xpos: f64,
|
||||
ypos: f64,
|
||||
ignore_first_move: bool,
|
||||
smooth_turn_x: SmoothDouble,
|
||||
smooth_turn_y: SmoothDouble,
|
||||
accumulated_dx: f64,
|
||||
accumulated_dy: f64,
|
||||
pub scroll: ScrollWheelHandler,
|
||||
last_handle_movement_time: f64,
|
||||
}
|
||||
|
||||
impl Default for MouseLook {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
xpos: 0.0,
|
||||
ypos: 0.0,
|
||||
ignore_first_move: true,
|
||||
smooth_turn_x: SmoothDouble::default(),
|
||||
smooth_turn_y: SmoothDouble::default(),
|
||||
accumulated_dx: 0.0,
|
||||
accumulated_dy: 0.0,
|
||||
scroll: ScrollWheelHandler::default(),
|
||||
// Double.MIN_VALUE
|
||||
last_handle_movement_time: 4.9e-324,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MouseLook {
|
||||
/// `setIgnoreFirstMove`.
|
||||
pub fn set_ignore_first_move(&mut self) {
|
||||
self.ignore_first_move = true;
|
||||
}
|
||||
|
||||
/// `onMove`: relative motion counts while the pointer is grabbed, absolute
|
||||
/// motion otherwise.
|
||||
pub fn on_move(
|
||||
&mut self,
|
||||
xpos: f64,
|
||||
ypos: f64,
|
||||
xrel: f64,
|
||||
yrel: f64,
|
||||
window_active: bool,
|
||||
grabbed: bool,
|
||||
) {
|
||||
if self.ignore_first_move {
|
||||
self.xpos = xpos;
|
||||
self.ypos = ypos;
|
||||
self.ignore_first_move = false;
|
||||
} else {
|
||||
if window_active {
|
||||
if grabbed {
|
||||
self.accumulated_dx += xrel;
|
||||
self.accumulated_dy += yrel;
|
||||
} else {
|
||||
self.accumulated_dx += xpos - self.xpos;
|
||||
self.accumulated_dy += ypos - self.ypos;
|
||||
}
|
||||
}
|
||||
self.xpos = xpos;
|
||||
self.ypos = ypos;
|
||||
}
|
||||
}
|
||||
|
||||
/// Movement accumulated since the last frame (for screens' mouse-moved events).
|
||||
pub fn accumulated(&self) -> (f64, f64) {
|
||||
(self.accumulated_dx, self.accumulated_dy)
|
||||
}
|
||||
|
||||
/// `handleAccumulatedMovement` for a frame at `time` seconds: the
|
||||
/// `(xo, yo)` passed to `Entity.turn` when the pointer is grabbed and the
|
||||
/// window is active. The accumulators are cleared either way.
|
||||
pub fn handle_accumulated_movement(
|
||||
&mut self,
|
||||
time: f64,
|
||||
window_active: bool,
|
||||
grabbed_with_player: bool,
|
||||
look: LookOptions,
|
||||
) -> Option<(f64, f64)> {
|
||||
let mousea = time - self.last_handle_movement_time;
|
||||
self.last_handle_movement_time = time;
|
||||
let turn = (window_active && grabbed_with_player).then(|| self.turn_player(mousea, look));
|
||||
self.accumulated_dx = 0.0;
|
||||
self.accumulated_dy = 0.0;
|
||||
turn
|
||||
}
|
||||
|
||||
fn turn_player(&mut self, mousea: f64, look: LookOptions) -> (f64, f64) {
|
||||
let ss = look.sensitivity * f64::from(0.6f32) + f64::from(0.2f32);
|
||||
let sensitivity_mod = ss * ss * ss;
|
||||
let sens = sensitivity_mod * 8.0;
|
||||
let (xo, yo) = if look.smooth_camera {
|
||||
(
|
||||
self.smooth_turn_x
|
||||
.get_new_delta_value(self.accumulated_dx * sens, mousea * sens),
|
||||
self.smooth_turn_y
|
||||
.get_new_delta_value(self.accumulated_dy * sens, mousea * sens),
|
||||
)
|
||||
} else if look.scoping {
|
||||
self.smooth_turn_x.reset();
|
||||
self.smooth_turn_y.reset();
|
||||
(
|
||||
self.accumulated_dx * sensitivity_mod,
|
||||
self.accumulated_dy * sensitivity_mod,
|
||||
)
|
||||
} else {
|
||||
self.smooth_turn_x.reset();
|
||||
self.smooth_turn_y.reset();
|
||||
(self.accumulated_dx * sens, self.accumulated_dy * sens)
|
||||
};
|
||||
(
|
||||
if look.invert_x { -xo } else { xo },
|
||||
if look.invert_y { -yo } else { yo },
|
||||
)
|
||||
}
|
||||
|
||||
/// `onScroll` for the in-game case (no screen, player present): the wheel
|
||||
/// value `wheel` the hotbar or spectator speed reacts to, and the raw
|
||||
/// wheel steps. `None` when no whole step has accumulated.
|
||||
pub fn on_scroll(
|
||||
&mut self,
|
||||
xoffset: f64,
|
||||
yoffset: f64,
|
||||
discrete: bool,
|
||||
wheel_sensitivity: f64,
|
||||
) -> Option<(i32, (i32, i32))> {
|
||||
let scale = |v: f64| (if discrete { java_signum(v) } else { v }) * wheel_sensitivity;
|
||||
let (x, y) = self.scroll.on_mouse_scroll(scale(xoffset), scale(yoffset));
|
||||
if x == 0 && y == 0 {
|
||||
return None;
|
||||
}
|
||||
let wheel = if y == 0 { -x } else { y };
|
||||
Some((wheel, (x, y)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn default_sensitivity_turns_point_fifteen_degrees_per_count_at_one() {
|
||||
let mut look = MouseLook::default();
|
||||
look.on_move(0.0, 0.0, 0.0, 0.0, true, true);
|
||||
look.on_move(1.0, 0.0, 1.0, 0.0, true, true);
|
||||
let (xo, _) = look
|
||||
.handle_accumulated_movement(
|
||||
1.0,
|
||||
true,
|
||||
true,
|
||||
LookOptions {
|
||||
sensitivity: 0.5,
|
||||
smooth_camera: false,
|
||||
scoping: false,
|
||||
invert_x: false,
|
||||
invert_y: false,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let mut rot = Rotation {
|
||||
x_rot: 0.0,
|
||||
y_rot: 0.0,
|
||||
x_rot_o: 0.0,
|
||||
y_rot_o: 0.0,
|
||||
};
|
||||
rot.turn(xo, 0.0);
|
||||
assert!((rot.y_rot - 0.15 * 1.0).abs() < 1e-6, "{}", rot.y_rot);
|
||||
}
|
||||
#[test]
|
||||
fn scroll_accumulates_fractions() {
|
||||
let mut look = MouseLook::default();
|
||||
assert_eq!(look.on_scroll(0.0, 0.4, false, 1.0), None);
|
||||
assert_eq!(look.on_scroll(0.0, 0.7, false, 1.0), Some((1, (0, 1))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,719 @@
|
||||
//! `options.txt` exactly as `Options.load`/`Options.save` handle it in 26.3:
|
||||
//! the processing order, per-option codecs and validation (`OptionInstance`),
|
||||
//! plain fields, key mappings, sound volumes and model parts. Typed access for
|
||||
//! the game lives in `settings`.
|
||||
use crate::{
|
||||
java_text::{self, Json},
|
||||
key_names,
|
||||
};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// A stored option value.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum V {
|
||||
Bool(bool),
|
||||
Int(i32),
|
||||
Double(f64),
|
||||
Str(String),
|
||||
List(Vec<String>),
|
||||
}
|
||||
|
||||
/// How an `OptionInstance` decodes, validates and encodes its value.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Spec {
|
||||
/// `Codec.BOOL`.
|
||||
Bool,
|
||||
/// `IntRange(min, max)`: codec `intRange(min, max + 1)`, validated to `max`.
|
||||
Int(i32, i32),
|
||||
/// `ClampingLazyMaxIntRange(min, ..)` while the game is not running.
|
||||
LazyInt(i32),
|
||||
/// `IntRange(imin, imax).xmap(i / k, (int)(v * k))` with `doubleRange(lo, hi)`.
|
||||
Scaled(i32, i32, f64, f64, f64),
|
||||
/// The frame rate limit: `IntRange(1, 26).xmap(i * 10, v / 10)`, codec 10..=260.
|
||||
FrameLimit,
|
||||
/// Field of view degrees stored as `(fov - 70) / 40`.
|
||||
Fov,
|
||||
/// `IntRange(-200, 100).xmap(10^(i/100), floor(log10(v) * 100))`.
|
||||
WheelSensitivity,
|
||||
/// `UnitDouble`.
|
||||
Unit,
|
||||
/// `UnitDouble.xmap(square, sqrt)` with an explicit `doubleRange(0, 1)` codec.
|
||||
UnitSquare,
|
||||
/// `UnitDouble.xmap(square, sqrt)` using the value set's own codec.
|
||||
UnitSquareImplicit,
|
||||
/// String-represented enum.
|
||||
Named(&'static [&'static str]),
|
||||
/// Enum stored as its id, wrapping out-of-range ids.
|
||||
Id(i32),
|
||||
/// `CloudStatus` with the boolean alternative.
|
||||
Clouds,
|
||||
/// Any string (`LazyEnum` while the game is not running).
|
||||
AnyStr,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Kind {
|
||||
Option(Spec),
|
||||
PlainBool,
|
||||
PlainInt,
|
||||
PlainStr,
|
||||
List,
|
||||
Tutorial,
|
||||
Key,
|
||||
}
|
||||
|
||||
struct Def {
|
||||
key: String,
|
||||
kind: Kind,
|
||||
default: V,
|
||||
}
|
||||
|
||||
const TUTORIAL_STEPS: [&str; 6] = [
|
||||
"movement",
|
||||
"find_tree",
|
||||
"punch_tree",
|
||||
"open_inventory",
|
||||
"craft_planks",
|
||||
"none",
|
||||
];
|
||||
const MODEL_PARTS: [&str; 7] = [
|
||||
"cape",
|
||||
"jacket",
|
||||
"left_sleeve",
|
||||
"right_sleeve",
|
||||
"left_pants_leg",
|
||||
"right_pants_leg",
|
||||
"hat",
|
||||
];
|
||||
const GRAPHICS_BACKEND: &[&str] = &["default", "opengl", "vulkan"];
|
||||
const GRAPHICS_PRESET: &[&str] = &["fast", "fancy", "fabulous", "custom"];
|
||||
const INACTIVITY: &[&str] = &["minimized", "afk"];
|
||||
const CLOUDS: &[&str] = &["false", "fast", "true"];
|
||||
const MAIN_HAND: &[&str] = &["left", "right"];
|
||||
const PRESENCE: &[&str] = &["none", "limited", "all"];
|
||||
const MUSIC_TOAST: &[&str] = &["never", "pause", "pause_and_toast"];
|
||||
const MUSIC_FREQUENCY: &[&str] = &["DEFAULT", "FREQUENT", "CONSTANT"];
|
||||
|
||||
fn def(key: &str, kind: Kind, default: V) -> Def {
|
||||
Def {
|
||||
key: key.to_owned(),
|
||||
kind,
|
||||
default,
|
||||
}
|
||||
}
|
||||
|
||||
/// The processing order of `Options.processOptions`.
|
||||
static TABLE: LazyLock<Vec<Def>> = LazyLock::new(|| {
|
||||
use Kind::{List, Option as O, PlainBool as PB, PlainInt as PI, PlainStr as PS, Tutorial};
|
||||
use Spec::{
|
||||
AnyStr, Bool, Clouds, Fov, FrameLimit, Id, Int, LazyInt, Named, Scaled, Unit, UnitSquare,
|
||||
UnitSquareImplicit, WheelSensitivity,
|
||||
};
|
||||
let b = |key: &str, d: bool| def(key, O(Bool), V::Bool(d));
|
||||
let i = |key: &str, lo, hi, d: i32| def(key, O(Int(lo, hi)), V::Int(d));
|
||||
let u = |key: &str, d: f64| def(key, O(Unit), V::Double(d));
|
||||
let n =
|
||||
|key: &str, names: &'static [&'static str], d: i32| def(key, O(Named(names)), V::Int(d));
|
||||
let id = |key: &str, count: i32, d: i32| def(key, O(Id(count)), V::Int(d));
|
||||
let pb = |key: &str, d: bool| def(key, PB, V::Bool(d));
|
||||
let mut t = vec![
|
||||
b("ao", true),
|
||||
i("biomeBlendRadius", 0, 7, 2),
|
||||
def(
|
||||
"chunkSectionFadeInTime",
|
||||
O(Scaled(0, 40, 20.0, 0.0, 2.0)),
|
||||
V::Double(0.75),
|
||||
),
|
||||
b("cutoutLeaves", true),
|
||||
b("enableVsync", true),
|
||||
def(
|
||||
"entityDistanceScaling",
|
||||
O(Scaled(2, 20, 4.0, 0.5, 5.0)),
|
||||
V::Double(1.0),
|
||||
),
|
||||
b("entityShadows", true),
|
||||
b("forceUnicodeFont", false),
|
||||
b("japaneseGlyphVariants", false),
|
||||
def("fov", O(Fov), V::Int(70)),
|
||||
def("fovEffectScale", O(UnitSquare), V::Double(1.0)),
|
||||
def("darknessEffectScale", O(UnitSquareImplicit), V::Double(1.0)),
|
||||
u("glintSpeed", 0.5),
|
||||
u("glintStrength", 0.75),
|
||||
n("preferredGraphicsBackend", GRAPHICS_BACKEND, 0),
|
||||
n("graphicsPreset", GRAPHICS_PRESET, 1),
|
||||
id("prioritizeChunkUpdates", 3, 0),
|
||||
b("fullscreen", false),
|
||||
b("exclusiveFullscreen", false),
|
||||
b("macFullscreenMenuVisibility", false),
|
||||
u("gamma", 0.5),
|
||||
def("guiScale", O(LazyInt(0)), V::Int(0)),
|
||||
def("debugGuiScale", O(LazyInt(-1)), V::Int(0)),
|
||||
i("maxAnisotropyBit", 1, 3, 2),
|
||||
id("textureFiltering", 3, 0),
|
||||
def("maxFps", O(FrameLimit), V::Int(120)),
|
||||
b("improvedTransparency", false),
|
||||
n("inactivityFpsLimit", INACTIVITY, 1),
|
||||
i("mipmapLevels", 0, 4, 4),
|
||||
id("narrator", 4, 0),
|
||||
id("particles", 3, 0),
|
||||
b("reducedDebugInfo", false),
|
||||
def("renderClouds", O(Clouds), V::Int(2)),
|
||||
i("cloudRange", 2, 128, 128),
|
||||
i("renderDistance", 2, 32, 12),
|
||||
i("simulationDistance", 5, 32, 12),
|
||||
u("screenEffectScale", 1.0),
|
||||
def("soundDevice", O(AnyStr), V::Str(String::new())),
|
||||
b("vignette", true),
|
||||
i("weatherRadius", 3, 10, 10),
|
||||
b("autoJump", false),
|
||||
b("rotateWithMinecart", false),
|
||||
b("operatorItemsTab", false),
|
||||
b("autoSuggestions", true),
|
||||
b("chatColors", true),
|
||||
b("chatLinks", true),
|
||||
b("chatLinksPrompt", true),
|
||||
b("discrete_mouse_scroll", false),
|
||||
b("invertXMouse", false),
|
||||
b("invertYMouse", false),
|
||||
b("realmsNotifications", true),
|
||||
b("showSubtitles", false),
|
||||
b("directionalAudio", false),
|
||||
b("bobView", true),
|
||||
b("toggleCrouch", false),
|
||||
b("toggleSprint", false),
|
||||
b("toggleAttack", false),
|
||||
b("toggleUse", false),
|
||||
i("sprintWindow", 0, 10, 7),
|
||||
b("darkMojangStudiosBackground", false),
|
||||
b("hideLightningFlashes", false),
|
||||
b("hideSplashTexts", false),
|
||||
u("mouseSensitivity", 0.5),
|
||||
u("damageTiltStrength", 1.0),
|
||||
b("highContrast", false),
|
||||
b("highContrastBlockOutline", false),
|
||||
b("narratorHotkey", true),
|
||||
def("resourcePacks", List, V::List(Vec::new())),
|
||||
def("incompatibleResourcePacks", List, V::List(Vec::new())),
|
||||
def("lastServer", PS, V::Str(String::new())),
|
||||
def("lang", PS, V::Str("en_us".into())),
|
||||
id("chatVisibility", 3, 0),
|
||||
u("chatOpacity", 1.0),
|
||||
u("chatLineSpacing", 0.0),
|
||||
u("textBackgroundOpacity", 0.5),
|
||||
b("backgroundForChatOnly", true),
|
||||
pb("hideServerAddress", false),
|
||||
pb("advancedItemTooltips", false),
|
||||
pb("pauseOnLostFocus", true),
|
||||
def("overrideWidth", PI, V::Int(0)),
|
||||
def("overrideHeight", PI, V::Int(0)),
|
||||
u("chatHeightFocused", 1.0),
|
||||
def(
|
||||
"chatDelay",
|
||||
O(Scaled(0, 60, 10.0, 0.0, 6.0)),
|
||||
V::Double(0.0),
|
||||
),
|
||||
u("chatHeightUnfocused", 0.4375),
|
||||
u("chatScale", 1.0),
|
||||
u("chatWidth", 1.0),
|
||||
def(
|
||||
"notificationDisplayTime",
|
||||
O(Scaled(5, 100, 10.0, 0.5, 10.0)),
|
||||
V::Double(1.0),
|
||||
),
|
||||
pb("useNativeTransport", true),
|
||||
n("mainHand", MAIN_HAND, 1),
|
||||
id("attackIndicator", 3, 1),
|
||||
def("tutorialStep", Tutorial, V::Int(0)),
|
||||
def("mouseWheelSensitivity", O(WheelSensitivity), V::Double(1.0)),
|
||||
b("allowCursorChanges", true),
|
||||
b("quitShortcuts", true),
|
||||
b("ctrlClickEmulatesRightClick", false),
|
||||
def("glDebugVerbosity", PI, V::Int(1)),
|
||||
pb("skipMultiplayerWarning", false),
|
||||
b("hideMatchedNames", true),
|
||||
pb("joinedFirstServer", false),
|
||||
pb("syncChunkWrites", false),
|
||||
b("showAutosaveIndicator", true),
|
||||
b("allowServerListing", true),
|
||||
b("inGameNotification", false),
|
||||
n("sharePresence", PRESENCE, 2),
|
||||
b("onlyShowSecureChat", false),
|
||||
b("saveChatDrafts", false),
|
||||
u("panoramaScrollSpeed", 1.0),
|
||||
b("telemetryOptInExtra", false),
|
||||
pb("onboardAccessibility", true),
|
||||
i("menuBackgroundBlurriness", 0, 10, 5),
|
||||
pb("startedCleanly", true),
|
||||
n("musicToast", MUSIC_TOAST, 0),
|
||||
n("musicFrequency", MUSIC_FREQUENCY, 0),
|
||||
];
|
||||
for (name, key, _) in crate::keybinds::MAPPINGS {
|
||||
t.push(def(
|
||||
&format!("key_{name}"),
|
||||
Kind::Key,
|
||||
V::Str((*key).to_owned()),
|
||||
));
|
||||
}
|
||||
for source in crate::settings::SOUND_SOURCES {
|
||||
t.push(u(&format!("soundCategory_{source}"), 1.0));
|
||||
}
|
||||
for part in MODEL_PARTS {
|
||||
t.push(pb(&format!("modelPart_{part}"), true));
|
||||
}
|
||||
t
|
||||
});
|
||||
|
||||
/// Mth.floor for doubles.
|
||||
fn floor_int(v: f64) -> i32 {
|
||||
let i = v as i32;
|
||||
if v < f64::from(i) { i - 1 } else { i }
|
||||
}
|
||||
|
||||
fn number(json: &Json) -> Option<&str> {
|
||||
match json {
|
||||
Json::Number(n) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn codec_int(json: &Json) -> Option<i32> {
|
||||
number(json).map(Json::int_value)
|
||||
}
|
||||
fn codec_double(json: &Json) -> Option<f64> {
|
||||
number(json).map(Json::double_value)
|
||||
}
|
||||
fn codec_bool(json: &Json) -> Option<bool> {
|
||||
match json {
|
||||
Json::Bool(b) => Some(*b),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn codec_string(json: &Json) -> Option<&str> {
|
||||
match json {
|
||||
Json::String(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn double_range(v: f64, lo: f64, hi: f64) -> Option<f64> {
|
||||
// Double.compareTo: -0.0 sorts below 0.0 and NaN above everything.
|
||||
(v.total_cmp(&lo).is_ge() && v.total_cmp(&hi).is_le() && !v.is_nan()).then_some(v)
|
||||
}
|
||||
fn log_mouse(value: i32) -> f64 {
|
||||
10f64.powf(f64::from(value) / 100.0)
|
||||
}
|
||||
fn unit_alt(json: &Json) -> Option<f64> {
|
||||
codec_double(json)
|
||||
.and_then(|v| double_range(v, 0.0, 1.0))
|
||||
.or_else(|| codec_bool(json).map(|b| if b { 1.0 } else { 0.0 }))
|
||||
}
|
||||
|
||||
impl Spec {
|
||||
/// `codec.parse(JsonOps.INSTANCE, element)`.
|
||||
fn decode(self, json: &Json) -> Option<V> {
|
||||
match self {
|
||||
Spec::Bool => codec_bool(json).map(V::Bool),
|
||||
Spec::Int(lo, hi) => {
|
||||
let v = codec_int(json)?;
|
||||
(v >= lo && i64::from(v) <= i64::from(hi) + 1).then_some(V::Int(v))
|
||||
}
|
||||
Spec::LazyInt(lo) => {
|
||||
let v = codec_int(json)?;
|
||||
(v >= lo).then_some(V::Int(v))
|
||||
}
|
||||
Spec::Scaled(.., lo, hi) => double_range(codec_double(json)?, lo, hi).map(V::Double),
|
||||
Spec::FrameLimit => {
|
||||
let v = codec_int(json)?;
|
||||
(10..=260).contains(&v).then_some(V::Int(v))
|
||||
}
|
||||
Spec::Fov => Some(V::Int((codec_double(json)? * 40.0 + 70.0) as i32)),
|
||||
Spec::WheelSensitivity => {
|
||||
double_range(codec_double(json)?, log_mouse(-200), log_mouse(100)).map(V::Double)
|
||||
}
|
||||
Spec::Unit => unit_alt(json).map(V::Double),
|
||||
Spec::UnitSquare => double_range(codec_double(json)?, 0.0, 1.0).map(V::Double),
|
||||
Spec::UnitSquareImplicit => unit_alt(json).map(|v| V::Double(v * v)),
|
||||
Spec::Named(names) => {
|
||||
let s = codec_string(json)?;
|
||||
names.iter().position(|n| *n == s).map(|i| V::Int(i as i32))
|
||||
}
|
||||
Spec::Id(count) => codec_int(json).map(|v| V::Int(v.rem_euclid(count))),
|
||||
Spec::Clouds => {
|
||||
if let Some(s) = codec_string(json) {
|
||||
return CLOUDS
|
||||
.iter()
|
||||
.position(|n| *n == s)
|
||||
.map(|i| V::Int(i as i32));
|
||||
}
|
||||
codec_bool(json).map(|b| V::Int(if b { 2 } else { 0 }))
|
||||
}
|
||||
Spec::AnyStr => codec_string(json).map(|s| V::Str(s.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ValueSet.validateValue`; `None` makes `OptionInstance.set` fall back
|
||||
/// to the option's initial value.
|
||||
fn validate(self, v: &V) -> Option<V> {
|
||||
match (self, v) {
|
||||
(Spec::Bool, V::Bool(_)) => Some(v.clone()),
|
||||
(Spec::Int(lo, hi), V::Int(x)) => (*x >= lo && *x <= hi).then(|| v.clone()),
|
||||
(Spec::LazyInt(lo), V::Int(x)) => Some(V::Int((*x).clamp(lo, 2_147_483_646))),
|
||||
(Spec::Scaled(imin, imax, k, ..), V::Double(x)) => {
|
||||
let i = (x * k) as i32;
|
||||
(i >= imin && i <= imax).then(|| V::Double(f64::from(i) / k))
|
||||
}
|
||||
(Spec::FrameLimit, V::Int(x)) => {
|
||||
let i = x / 10;
|
||||
(1..=26).contains(&i).then(|| V::Int(i * 10))
|
||||
}
|
||||
(Spec::Fov, V::Int(x)) => (30..=110).contains(x).then(|| v.clone()),
|
||||
(Spec::WheelSensitivity, V::Double(x)) => {
|
||||
let i = floor_int(x.log10() * 100.0);
|
||||
(-200..=100).contains(&i).then(|| V::Double(log_mouse(i)))
|
||||
}
|
||||
(Spec::Unit, V::Double(x)) => (*x >= 0.0 && *x <= 1.0).then(|| v.clone()),
|
||||
(Spec::UnitSquare | Spec::UnitSquareImplicit, V::Double(x)) => {
|
||||
let root = x.sqrt();
|
||||
(0.0..=1.0)
|
||||
.contains(&root)
|
||||
.then_some(V::Double(root * root))
|
||||
}
|
||||
(Spec::Named(names), V::Int(x)) => {
|
||||
(*x >= 0 && (*x as usize) < names.len()).then(|| v.clone())
|
||||
}
|
||||
(Spec::Id(count), V::Int(x)) => (*x >= 0 && *x < count).then(|| v.clone()),
|
||||
(Spec::Clouds, V::Int(x)) => (0..3).contains(x).then(|| v.clone()),
|
||||
(Spec::AnyStr, V::Str(_)) => Some(v.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `codec.encodeStart(JsonOps.INSTANCE, value)` rendered by Gson.
|
||||
fn encode(self, v: &V) -> Option<String> {
|
||||
let double = |x: f64| java_text::double_to_string(x);
|
||||
Some(match (self, v) {
|
||||
(Spec::Bool, V::Bool(b)) => b.to_string(),
|
||||
(Spec::Int(lo, hi), V::Int(x)) => {
|
||||
if *x < lo || i64::from(*x) > i64::from(hi) + 1 {
|
||||
return None;
|
||||
}
|
||||
x.to_string()
|
||||
}
|
||||
(Spec::LazyInt(lo), V::Int(x)) => {
|
||||
if *x < lo {
|
||||
return None;
|
||||
}
|
||||
x.to_string()
|
||||
}
|
||||
(Spec::Scaled(.., lo, hi), V::Double(x)) => {
|
||||
double_range(*x, lo, hi)?;
|
||||
double(*x)
|
||||
}
|
||||
(Spec::FrameLimit, V::Int(x)) => {
|
||||
if !(10..=260).contains(x) {
|
||||
return None;
|
||||
}
|
||||
x.to_string()
|
||||
}
|
||||
(Spec::Fov, V::Int(x)) => double((f64::from(*x) - 70.0) / 40.0),
|
||||
(Spec::WheelSensitivity, V::Double(x)) => {
|
||||
double_range(*x, log_mouse(-200), log_mouse(100))?;
|
||||
double(*x)
|
||||
}
|
||||
(Spec::Unit, V::Double(x)) => {
|
||||
double_range(*x, 0.0, 1.0)?;
|
||||
double(*x)
|
||||
}
|
||||
(Spec::UnitSquare, V::Double(x)) => {
|
||||
double_range(*x, 0.0, 1.0)?;
|
||||
double(*x)
|
||||
}
|
||||
(Spec::UnitSquareImplicit, V::Double(x)) => {
|
||||
let root = x.sqrt();
|
||||
double_range(root, 0.0, 1.0)?;
|
||||
double(root)
|
||||
}
|
||||
(Spec::Named(names), V::Int(x)) => {
|
||||
java_text::gson_string(names.get(usize::try_from(*x).ok()?)?)
|
||||
}
|
||||
(Spec::Id(_), V::Int(x)) => x.to_string(),
|
||||
(Spec::Clouds, V::Int(x)) => {
|
||||
java_text::gson_string(CLOUDS.get(usize::try_from(*x).ok()?)?)
|
||||
}
|
||||
(Spec::AnyStr, V::Str(s)) => java_text::gson_string(s),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `InputConstants.getKey(name)`: the canonical name of a key, or the
|
||||
/// unbound key when `name` is invalid.
|
||||
pub fn canonical_key(name: &str) -> Result<String, java_text::SyntaxError> {
|
||||
for (_, n) in key_names::KEYBOARD.iter().chain(key_names::MOUSE) {
|
||||
if *n == name {
|
||||
return Ok(name.to_owned());
|
||||
}
|
||||
}
|
||||
for (prefix, table) in [
|
||||
("key.keyboard", key_names::KEYBOARD),
|
||||
("key.mouse", key_names::MOUSE),
|
||||
] {
|
||||
if let Some(rest) = name.strip_prefix(prefix) {
|
||||
// substring(prefix.length() + 1): the separator is skipped blindly.
|
||||
let mut chars = rest.chars();
|
||||
if chars.next().is_none() {
|
||||
// StringIndexOutOfBoundsException is not an IllegalArgumentException.
|
||||
return Err(java_text::SyntaxError);
|
||||
}
|
||||
let Some(value) = crate::options_fixes::java_parse_int(chars.as_str()) else {
|
||||
return Ok("key.keyboard.unknown".into());
|
||||
};
|
||||
return Ok(table
|
||||
.iter()
|
||||
.find(|(v, _)| *v == value)
|
||||
.map_or_else(|| format!("{prefix}.{value}"), |(_, n)| (*n).to_owned()));
|
||||
}
|
||||
}
|
||||
Ok("key.keyboard.unknown".into())
|
||||
}
|
||||
|
||||
fn read_list(text: &str) -> Result<Vec<String>, java_text::SyntaxError> {
|
||||
// GsonHelper.fromNullableJson with a List<String> type token.
|
||||
Ok(java_text::parse_strict_string_list(text)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// All option values in `processOptions` order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OptionsFile {
|
||||
values: Vec<V>,
|
||||
/// `fullscreenResolution`, kept verbatim.
|
||||
pub fullscreen_resolution: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for OptionsFile {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
values: TABLE.iter().map(|d| d.default.clone()).collect(),
|
||||
fullscreen_resolution: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OptionsFile {
|
||||
fn index(key: &str) -> Option<usize> {
|
||||
TABLE.iter().position(|d| d.key == key)
|
||||
}
|
||||
pub fn get(&self, key: &str) -> Option<&V> {
|
||||
Self::index(key).map(|i| &self.values[i])
|
||||
}
|
||||
pub fn bool(&self, key: &str) -> bool {
|
||||
matches!(self.get(key), Some(V::Bool(true)))
|
||||
}
|
||||
pub fn int(&self, key: &str) -> i32 {
|
||||
match self.get(key) {
|
||||
Some(V::Int(i)) => *i,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
pub fn double(&self, key: &str) -> f64 {
|
||||
match self.get(key) {
|
||||
Some(V::Double(d)) => *d,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
pub fn string(&self, key: &str) -> String {
|
||||
match self.get(key) {
|
||||
Some(V::Str(s)) => s.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
pub fn list(&self, key: &str) -> Vec<String> {
|
||||
match self.get(key) {
|
||||
Some(V::List(l)) => l.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
/// The serialized name of an enum-valued option.
|
||||
pub fn name(&self, key: &str) -> String {
|
||||
let Some(i) = Self::index(key) else {
|
||||
return String::new();
|
||||
};
|
||||
match (TABLE[i].kind, &self.values[i]) {
|
||||
(Kind::Option(Spec::Named(names)), V::Int(x)) => {
|
||||
names.get(*x as usize).copied().unwrap_or("").to_owned()
|
||||
}
|
||||
(Kind::Option(Spec::Clouds), V::Int(x)) => {
|
||||
CLOUDS.get(*x as usize).copied().unwrap_or("").to_owned()
|
||||
}
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
/// `OptionInstance.set` with a candidate value (invalid values revert to
|
||||
/// the initial value).
|
||||
pub fn set(&mut self, key: &str, value: V) {
|
||||
let Some(i) = Self::index(key) else { return };
|
||||
let Kind::Option(spec) = TABLE[i].kind else {
|
||||
self.values[i] = value;
|
||||
return;
|
||||
};
|
||||
self.values[i] = spec
|
||||
.validate(&value)
|
||||
.unwrap_or_else(|| TABLE[i].default.clone());
|
||||
}
|
||||
/// Select an enum option by serialized name.
|
||||
pub fn set_name(&mut self, key: &str, name: &str) {
|
||||
let Some(i) = Self::index(key) else { return };
|
||||
let names: &[&str] = match TABLE[i].kind {
|
||||
Kind::Option(Spec::Named(names)) => names,
|
||||
Kind::Option(Spec::Clouds) => CLOUDS,
|
||||
_ => return,
|
||||
};
|
||||
if let Some(p) = names.iter().position(|n| *n == name) {
|
||||
self.values[i] = V::Int(p as i32);
|
||||
}
|
||||
}
|
||||
/// Key mapping value by mapping name.
|
||||
pub fn key_binding(&self, name: &str) -> String {
|
||||
self.string(&format!("key_{name}"))
|
||||
}
|
||||
|
||||
/// `Options.load` on the text of an options file.
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let mut file = Self::default();
|
||||
let mut raw: std::collections::HashMap<String, String> = std::collections::HashMap::new();
|
||||
for line in split_lines(text) {
|
||||
if let Some((k, v)) = line.split_once(':') {
|
||||
raw.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
}
|
||||
let version = raw
|
||||
.get("version")
|
||||
.and_then(|v| crate::options_fixes::java_parse_int(v))
|
||||
.unwrap_or(0);
|
||||
// A fixer failure abandons the whole file, leaving the defaults.
|
||||
if crate::options_fixes::update(&mut raw, version).is_ok() {
|
||||
file.apply(&raw);
|
||||
}
|
||||
file
|
||||
}
|
||||
|
||||
fn apply(&mut self, raw: &std::collections::HashMap<String, String>) {
|
||||
// A syntax error aborts the rest of the load, fullscreenResolution included.
|
||||
if self.try_apply(raw).is_ok()
|
||||
&& let Some(r) = raw.get("fullscreenResolution")
|
||||
{
|
||||
self.fullscreen_resolution = Some(r.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn try_apply(
|
||||
&mut self,
|
||||
raw: &std::collections::HashMap<String, String>,
|
||||
) -> Result<(), java_text::SyntaxError> {
|
||||
for (i, d) in TABLE.iter().enumerate() {
|
||||
let Some(text) = raw.get(&d.key) else {
|
||||
continue;
|
||||
};
|
||||
match d.kind {
|
||||
Kind::Option(spec) => {
|
||||
let json =
|
||||
java_text::parse_lenient(if text.is_empty() { "\"\"" } else { text })?;
|
||||
if let Some(decoded) = spec.decode(&json) {
|
||||
self.values[i] =
|
||||
spec.validate(&decoded).unwrap_or_else(|| d.default.clone());
|
||||
}
|
||||
}
|
||||
Kind::PlainBool => self.values[i] = V::Bool(text == "true"),
|
||||
Kind::PlainInt => {
|
||||
if let Some(v) = crate::options_fixes::java_parse_int(text) {
|
||||
self.values[i] = V::Int(v);
|
||||
}
|
||||
}
|
||||
Kind::PlainStr => self.values[i] = V::Str(text.clone()),
|
||||
Kind::List => self.values[i] = V::List(read_list(text)?),
|
||||
Kind::Tutorial => {
|
||||
let step = TUTORIAL_STEPS.iter().position(|n| n == text).unwrap_or(5);
|
||||
self.values[i] = V::Int(step as i32);
|
||||
}
|
||||
Kind::Key => {
|
||||
let V::Str(current) = &self.values[i] else {
|
||||
continue;
|
||||
};
|
||||
if current != text {
|
||||
self.values[i] = V::Str(canonical_key(text)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `Options.save`.
|
||||
pub fn serialize(&self) -> String {
|
||||
let mut out = format!("version:{}\n", horizon_world::DATA_VERSION);
|
||||
for (d, v) in TABLE.iter().zip(&self.values) {
|
||||
let rendered = match (d.kind, v) {
|
||||
(Kind::Option(spec), v) => match spec.encode(v) {
|
||||
Some(s) => s,
|
||||
None => continue,
|
||||
},
|
||||
(Kind::PlainBool, V::Bool(b)) => b.to_string(),
|
||||
(Kind::PlainInt, V::Int(x)) => x.to_string(),
|
||||
(Kind::PlainStr | Kind::Key, V::Str(s)) => s.clone(),
|
||||
(Kind::List, V::List(items)) => {
|
||||
let parts: Vec<String> =
|
||||
items.iter().map(|s| java_text::gson_string(s)).collect();
|
||||
format!("[{}]", parts.join(","))
|
||||
}
|
||||
(Kind::Tutorial, V::Int(x)) => TUTORIAL_STEPS
|
||||
.get(*x as usize)
|
||||
.copied()
|
||||
.unwrap_or("none")
|
||||
.to_owned(),
|
||||
_ => continue,
|
||||
};
|
||||
out.push_str(&d.key);
|
||||
out.push(':');
|
||||
out.push_str(&rendered);
|
||||
out.push('\n');
|
||||
}
|
||||
if let Some(r) = &self.fullscreen_resolution {
|
||||
out.push_str("fullscreenResolution:");
|
||||
out.push_str(r);
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// `BufferedReader.lines()`: \n, \r\n and \r terminate lines.
|
||||
fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let bytes = text.as_bytes();
|
||||
let mut start = 0;
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'\n' => {
|
||||
lines.push(&text[start..i]);
|
||||
start = i + 1;
|
||||
}
|
||||
b'\r' => {
|
||||
lines.push(&text[start..i]);
|
||||
if bytes.get(i + 1) == Some(&b'\n') {
|
||||
i += 1;
|
||||
}
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if start < bytes.len() {
|
||||
lines.push(&text[start..]);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Option names in processing order (for tests and tooling).
|
||||
pub fn keys() -> Vec<&'static str> {
|
||||
TABLE.iter().map(|d| d.key.as_str()).collect()
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
//! The `OPTIONS` data fixers of 26.3 (`DataFixTypes.OPTIONS`), applied to the
|
||||
//! raw key/value strings of an `options.txt` older than the current version.
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A fixer threw an exception; vanilla abandons loading the file.
|
||||
#[derive(Debug)]
|
||||
pub struct FixFailed;
|
||||
|
||||
pub type Raw = HashMap<String, String>;
|
||||
|
||||
/// OptionsKeyLwjgl3Fix.MAP: GLFW 2 key codes to key names.
|
||||
const LWJGL3: &[(i32, &str)] = &[
|
||||
(0, "key.unknown"),
|
||||
(11, "key.0"),
|
||||
(2, "key.1"),
|
||||
(3, "key.2"),
|
||||
(4, "key.3"),
|
||||
(5, "key.4"),
|
||||
(6, "key.5"),
|
||||
(7, "key.6"),
|
||||
(8, "key.7"),
|
||||
(9, "key.8"),
|
||||
(10, "key.9"),
|
||||
(30, "key.a"),
|
||||
(40, "key.apostrophe"),
|
||||
(48, "key.b"),
|
||||
(43, "key.backslash"),
|
||||
(14, "key.backspace"),
|
||||
(46, "key.c"),
|
||||
(58, "key.caps.lock"),
|
||||
(51, "key.comma"),
|
||||
(32, "key.d"),
|
||||
(211, "key.delete"),
|
||||
(208, "key.down"),
|
||||
(18, "key.e"),
|
||||
(207, "key.end"),
|
||||
(28, "key.enter"),
|
||||
(13, "key.equal"),
|
||||
(1, "key.escape"),
|
||||
(33, "key.f"),
|
||||
(59, "key.f1"),
|
||||
(68, "key.f10"),
|
||||
(87, "key.f11"),
|
||||
(88, "key.f12"),
|
||||
(100, "key.f13"),
|
||||
(101, "key.f14"),
|
||||
(102, "key.f15"),
|
||||
(103, "key.f16"),
|
||||
(104, "key.f17"),
|
||||
(105, "key.f18"),
|
||||
(113, "key.f19"),
|
||||
(60, "key.f2"),
|
||||
(61, "key.f3"),
|
||||
(62, "key.f4"),
|
||||
(63, "key.f5"),
|
||||
(64, "key.f6"),
|
||||
(65, "key.f7"),
|
||||
(66, "key.f8"),
|
||||
(67, "key.f9"),
|
||||
(34, "key.g"),
|
||||
(41, "key.grave.accent"),
|
||||
(35, "key.h"),
|
||||
(199, "key.home"),
|
||||
(23, "key.i"),
|
||||
(210, "key.insert"),
|
||||
(36, "key.j"),
|
||||
(37, "key.k"),
|
||||
(82, "key.keypad.0"),
|
||||
(79, "key.keypad.1"),
|
||||
(80, "key.keypad.2"),
|
||||
(81, "key.keypad.3"),
|
||||
(75, "key.keypad.4"),
|
||||
(76, "key.keypad.5"),
|
||||
(77, "key.keypad.6"),
|
||||
(71, "key.keypad.7"),
|
||||
(72, "key.keypad.8"),
|
||||
(73, "key.keypad.9"),
|
||||
(78, "key.keypad.add"),
|
||||
(83, "key.keypad.decimal"),
|
||||
(181, "key.keypad.divide"),
|
||||
(156, "key.keypad.enter"),
|
||||
(141, "key.keypad.equal"),
|
||||
(55, "key.keypad.multiply"),
|
||||
(74, "key.keypad.subtract"),
|
||||
(38, "key.l"),
|
||||
(203, "key.left"),
|
||||
(56, "key.left.alt"),
|
||||
(26, "key.left.bracket"),
|
||||
(29, "key.left.control"),
|
||||
(42, "key.left.shift"),
|
||||
(219, "key.left.win"),
|
||||
(50, "key.m"),
|
||||
(12, "key.minus"),
|
||||
(49, "key.n"),
|
||||
(69, "key.num.lock"),
|
||||
(24, "key.o"),
|
||||
(25, "key.p"),
|
||||
(209, "key.page.down"),
|
||||
(201, "key.page.up"),
|
||||
(197, "key.pause"),
|
||||
(52, "key.period"),
|
||||
(183, "key.print.screen"),
|
||||
(16, "key.q"),
|
||||
(19, "key.r"),
|
||||
(205, "key.right"),
|
||||
(184, "key.right.alt"),
|
||||
(27, "key.right.bracket"),
|
||||
(157, "key.right.control"),
|
||||
(54, "key.right.shift"),
|
||||
(220, "key.right.win"),
|
||||
(31, "key.s"),
|
||||
(70, "key.scroll.lock"),
|
||||
(39, "key.semicolon"),
|
||||
(53, "key.slash"),
|
||||
(57, "key.space"),
|
||||
(20, "key.t"),
|
||||
(15, "key.tab"),
|
||||
(22, "key.u"),
|
||||
(200, "key.up"),
|
||||
(47, "key.v"),
|
||||
(17, "key.w"),
|
||||
(45, "key.x"),
|
||||
(21, "key.y"),
|
||||
(44, "key.z"),
|
||||
];
|
||||
|
||||
/// `Integer.parseInt(String)`.
|
||||
pub fn java_parse_int(text: &str) -> Option<i32> {
|
||||
let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
|
||||
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
text.parse::<i32>().ok()
|
||||
}
|
||||
|
||||
enum Number<'a> {
|
||||
Special(f64),
|
||||
Decimal(bool, &'a str),
|
||||
}
|
||||
|
||||
fn java_number(text: &str) -> Option<Number<'_>> {
|
||||
let t = text.trim_matches(|c: char| c <= ' ');
|
||||
let (negative, body) = match t.strip_prefix('-') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, t.strip_prefix('+').unwrap_or(t)),
|
||||
};
|
||||
match body {
|
||||
"NaN" => return Some(Number::Special(f64::NAN)),
|
||||
"Infinity" => {
|
||||
return Some(Number::Special(if negative {
|
||||
f64::NEG_INFINITY
|
||||
} else {
|
||||
f64::INFINITY
|
||||
}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let body = body.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(body);
|
||||
if body.is_empty()
|
||||
|| !body
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-'))
|
||||
|| !body.chars().any(|c| c.is_ascii_digit())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Number::Decimal(negative, body))
|
||||
}
|
||||
|
||||
/// `Double.parseDouble(String)` for decimal and special forms.
|
||||
pub fn java_parse_double(text: &str) -> Option<f64> {
|
||||
match java_number(text)? {
|
||||
Number::Special(v) => Some(v),
|
||||
Number::Decimal(negative, body) => body
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.map(|v| if negative { -v } else { v }),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Float.parseFloat(String)`.
|
||||
pub fn java_parse_float(text: &str) -> Option<f32> {
|
||||
match java_number(text)? {
|
||||
Number::Special(v) => Some(v as f32),
|
||||
Number::Decimal(negative, body) => body
|
||||
.parse::<f32>()
|
||||
.ok()
|
||||
.map(|v| if negative { -v } else { v }),
|
||||
}
|
||||
}
|
||||
|
||||
fn rename(raw: &mut Raw, from: &str, to: &str, fix: impl FnOnce(&str) -> String) {
|
||||
if let Some(old) = raw.remove(from) {
|
||||
let value = fix(&old);
|
||||
raw.insert(to.to_owned(), value);
|
||||
}
|
||||
}
|
||||
|
||||
/// `OPTIONS` fixers from `version` up to the current data version.
|
||||
pub fn update(raw: &mut Raw, version: i32) -> Result<(), FixFailed> {
|
||||
if version < 816
|
||||
&& let Some(lang) = raw.get_mut("lang")
|
||||
{
|
||||
*lang = lang.to_lowercase();
|
||||
}
|
||||
if version < 1344 {
|
||||
let keys: Vec<String> = raw
|
||||
.keys()
|
||||
.filter(|k| k.starts_with("key_"))
|
||||
.cloned()
|
||||
.collect();
|
||||
for key in keys {
|
||||
let old = java_parse_int(&raw[&key]).ok_or(FixFailed)?;
|
||||
let name = if old < 0 {
|
||||
match old + 100 {
|
||||
0 => "key.mouse.left".to_owned(),
|
||||
1 => "key.mouse.right".to_owned(),
|
||||
2 => "key.mouse.middle".to_owned(),
|
||||
button => format!("key.mouse.{}", button + 1),
|
||||
}
|
||||
} else {
|
||||
LWJGL3
|
||||
.iter()
|
||||
.find(|(v, _)| *v == old)
|
||||
.map_or("key.unknown", |(_, n)| n)
|
||||
.to_owned()
|
||||
};
|
||||
raw.insert(key, name);
|
||||
}
|
||||
}
|
||||
if version < 1446 {
|
||||
let keys: Vec<String> = raw
|
||||
.keys()
|
||||
.filter(|k| k.starts_with("key_"))
|
||||
.cloned()
|
||||
.collect();
|
||||
for key in keys {
|
||||
let old = raw[&key].clone();
|
||||
if !old.starts_with("key.mouse") && !old.starts_with("scancode.") {
|
||||
// substring(4) on a shorter value throws.
|
||||
let rest: String = old.chars().skip(4).collect();
|
||||
if old.chars().count() < 4 {
|
||||
return Err(FixFailed);
|
||||
}
|
||||
raw.insert(key, format!("key.keyboard.{rest}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if version < 1936
|
||||
&& let Some(opacity) = raw.get("chatOpacity")
|
||||
{
|
||||
let background = java_parse_double(opacity).map_or(0.5, |v| (0.9 * v + 0.1) / 2.0);
|
||||
raw.insert(
|
||||
"textBackgroundOpacity".into(),
|
||||
crate::java_text::double_to_string(background),
|
||||
);
|
||||
}
|
||||
if version < 2556 {
|
||||
rename(raw, "fancyGraphics", "graphicsMode", |v| {
|
||||
if v == "true" { "1" } else { "0" }.to_owned()
|
||||
});
|
||||
}
|
||||
if version < 2558
|
||||
&& let Some(v) = raw.remove("key_key.swapHands")
|
||||
{
|
||||
raw.insert("key_key.swapOffhand".into(), v);
|
||||
}
|
||||
if version < 3201 {
|
||||
for key in ["resourcePacks", "incompatibleResourcePacks"] {
|
||||
if let Some(v) = raw.get_mut(key) {
|
||||
*v = v.replace("\"programer_art\"", "\"programmer_art\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
if version < 3214
|
||||
&& let Some(ao) = raw.get_mut("ao")
|
||||
{
|
||||
match ao.as_str() {
|
||||
"0" => *ao = "false".into(),
|
||||
"1" | "2" => *ao = "true".into(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if version < 3319 {
|
||||
raw.insert("onboardAccessibility".into(), "false".into());
|
||||
}
|
||||
if version < 3943
|
||||
&& let Some(v) = raw.get_mut("menuBackgroundBlurriness")
|
||||
{
|
||||
let value = java_parse_float(v).map_or(5, |d| ((d * 10.0) + 0.5).floor() as i32);
|
||||
*v = value.to_string();
|
||||
}
|
||||
if version < 4651 {
|
||||
let mode = raw.get("graphicsMode").cloned();
|
||||
for (name, fast, fancy, fabulous) in [
|
||||
("cutoutLeaves", "false", "true", "true"),
|
||||
("weatherRadius", "5", "10", "10"),
|
||||
("vignette", "false", "true", "true"),
|
||||
("improvedTransparency", "false", "false", "true"),
|
||||
] {
|
||||
let value = match mode.as_deref() {
|
||||
Some("2") => fabulous,
|
||||
Some("0") => fast,
|
||||
_ => fancy,
|
||||
};
|
||||
raw.insert(name.into(), value.into());
|
||||
}
|
||||
raw.insert("graphicsPreset".into(), "custom".into());
|
||||
}
|
||||
if version < 4661 {
|
||||
rename(raw, "showNowPlayingToast", "musicToast", |v| {
|
||||
if v == "false" {
|
||||
"never"
|
||||
} else {
|
||||
"pause_and_toast"
|
||||
}
|
||||
.to_owned()
|
||||
});
|
||||
}
|
||||
if version < 4892 {
|
||||
raw.insert("preferredGraphicsBackend".into(), "default".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
//! encodings (Options.processOptions); lines Horizon does not know are kept.
|
||||
//! The option screens live in `options_ui`.
|
||||
use crate::keybinds::KeyBinds;
|
||||
use std::{collections::BTreeMap, fs, path::Path};
|
||||
use crate::options_file::{OptionsFile, V};
|
||||
use std::{fs, path::Path};
|
||||
|
||||
/// SoundSource names in vanilla order.
|
||||
pub const SOUND_SOURCES: [&str; 11] = [
|
||||
@@ -166,8 +167,13 @@ pub struct Settings {
|
||||
/// Enabled resource packs, bottom first (resourcePacks).
|
||||
pub resource_packs: Vec<String>,
|
||||
pub keys: KeyBinds,
|
||||
/// Lines Horizon does not interpret, kept verbatim.
|
||||
pub extra: BTreeMap<String, String>,
|
||||
/// Every option in its stored form (the typed fields above mirror it).
|
||||
pub file: OptionsFile,
|
||||
pub invert_x: bool,
|
||||
pub toggle_attack: bool,
|
||||
pub toggle_use: bool,
|
||||
/// Taps of the sprint key counted as double taps (sprintWindow).
|
||||
pub sprint_window: i32,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
@@ -229,267 +235,228 @@ impl Default for Settings {
|
||||
show_subtitles: false,
|
||||
notification_display_time: 1.0,
|
||||
main_hand_left: false,
|
||||
resource_packs: vec!["vanilla".into()],
|
||||
resource_packs: Vec::new(),
|
||||
keys: KeyBinds::default(),
|
||||
extra: BTreeMap::new(),
|
||||
file: OptionsFile::default(),
|
||||
invert_x: false,
|
||||
toggle_attack: false,
|
||||
toggle_use: false,
|
||||
sprint_window: 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn unquote(v: &str) -> &str {
|
||||
v.strip_prefix('"')
|
||||
.and_then(|v| v.strip_suffix('"'))
|
||||
.unwrap_or(v)
|
||||
fn put_f(f: &mut OptionsFile, key: &str, v: f32) {
|
||||
if v != f.double(key) as f32 {
|
||||
f.set(key, V::Double(f64::from(v)));
|
||||
}
|
||||
}
|
||||
fn parse_list(v: &str) -> Vec<String> {
|
||||
serde_json::from_str::<Vec<String>>(v).unwrap_or_default()
|
||||
fn put_i(f: &mut OptionsFile, key: &str, v: i32) {
|
||||
if v != f.int(key) {
|
||||
f.set(key, V::Int(v));
|
||||
}
|
||||
}
|
||||
fn put_b(f: &mut OptionsFile, key: &str, v: bool) {
|
||||
if v != f.bool(key) {
|
||||
f.set(key, V::Bool(v));
|
||||
}
|
||||
}
|
||||
fn put_name(f: &mut OptionsFile, key: &str, v: &str) {
|
||||
if v != f.name(key) {
|
||||
f.set_name(key, v);
|
||||
}
|
||||
}
|
||||
fn put_s(f: &mut OptionsFile, key: &str, v: &str) {
|
||||
if v != f.string(key) {
|
||||
f.set(key, V::Str(v.to_owned()));
|
||||
}
|
||||
}
|
||||
impl Settings {
|
||||
pub fn load(path: &Path) -> Self {
|
||||
let Ok(text) = fs::read_to_string(path) else {
|
||||
let Ok(bytes) = fs::read(path) else {
|
||||
return Self::default();
|
||||
};
|
||||
Self::parse(&text)
|
||||
Self::parse(&String::from_utf8_lossy(&bytes))
|
||||
}
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let mut s = Self::default();
|
||||
for line in text.lines() {
|
||||
let Some((k, v)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let f = |d: f32| v.parse::<f32>().unwrap_or(d);
|
||||
let b = |d: bool| match v {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => d,
|
||||
};
|
||||
let i = |d: i32| v.parse::<i32>().unwrap_or(d);
|
||||
match k {
|
||||
"version" => {}
|
||||
"fov" => {
|
||||
s.fov = v
|
||||
.parse::<f32>()
|
||||
.map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0))
|
||||
}
|
||||
"renderDistance" => s.render_distance = i(12).clamp(2, 32),
|
||||
"simulationDistance" => s.simulation_distance = i(12).clamp(5, 32),
|
||||
"mouseSensitivity" => s.sensitivity = f(0.5).clamp(0.0, 1.0),
|
||||
"guiScale" => s.gui_scale = v.parse().unwrap_or(0),
|
||||
"bobView" => s.view_bobbing = b(true),
|
||||
"gamma" => s.gamma = f(0.5).clamp(0.0, 1.0),
|
||||
"maxFps" => s.max_fps = v.parse::<u32>().unwrap_or(260).clamp(10, 260),
|
||||
"enableVsync" => s.vsync = b(true),
|
||||
"fullscreen" => s.fullscreen = b(false),
|
||||
"ao" => s.smooth_lighting = b(true),
|
||||
"renderClouds" => s.clouds = unquote(v).to_owned(),
|
||||
"cloudRange" => s.cloud_range = i(128).clamp(2, 128),
|
||||
"particles" => s.particles = v.parse::<u8>().unwrap_or(0).min(2),
|
||||
"entityDistanceScaling" => s.entity_distance = f(1.0).clamp(0.5, 5.0),
|
||||
"entityShadows" => s.entity_shadows = b(true),
|
||||
"biomeBlendRadius" => s.biome_blend = i(2).clamp(0, 7),
|
||||
"graphicsPreset" => s.graphics_preset = unquote(v).to_owned(),
|
||||
"mipmapLevels" => s.mipmap_levels = i(4).clamp(0, 4),
|
||||
"weatherRadius" => s.weather_radius = i(10).clamp(3, 10),
|
||||
"chunkSectionFadeInTime" => s.chunk_fade = f(0.75).clamp(0.0, 2.0),
|
||||
"vignette" => s.vignette = b(true),
|
||||
"showAutosaveIndicator" => s.autosave_indicator = b(true),
|
||||
"cutoutLeaves" => s.cutout_leaves = b(true),
|
||||
"improvedTransparency" => s.improved_transparency = b(false),
|
||||
"attackIndicator" => s.attack_indicator = v.parse::<u8>().unwrap_or(1).min(2),
|
||||
"inactivityFpsLimit" => s.inactivity_fps_limit = unquote(v).to_owned(),
|
||||
"prioritizeChunkUpdates" => {
|
||||
s.prioritize_chunk_updates = v.parse::<u8>().unwrap_or(0).min(2)
|
||||
}
|
||||
"menuBackgroundBlurriness" => s.menu_blur = i(5).clamp(0, 10),
|
||||
"invertYMouse" => s.invert_y = b(false),
|
||||
"mouseWheelSensitivity" => s.mouse_wheel_sensitivity = f(1.0).clamp(0.01, 10.0),
|
||||
"discrete_mouse_scroll" => s.discrete_scroll = b(false),
|
||||
"toggleCrouch" => s.toggle_crouch = b(false),
|
||||
"toggleSprint" => s.toggle_sprint = b(false),
|
||||
"autoJump" => s.auto_jump = b(false),
|
||||
"lang" => s.language = v.to_owned(),
|
||||
"forceUnicodeFont" => s.force_unicode = b(false),
|
||||
"japaneseGlyphVariants" => s.japanese_glyphs = b(false),
|
||||
"chatVisibility" => s.chat_visibility = v.parse::<u8>().unwrap_or(0).min(2),
|
||||
"chatColors" => s.chat_colors = b(true),
|
||||
"chatLinks" => s.chat_links = b(true),
|
||||
"chatOpacity" => s.chat_opacity = f(1.0).clamp(0.0, 1.0),
|
||||
"textBackgroundOpacity" => s.text_background_opacity = f(0.5).clamp(0.0, 1.0),
|
||||
"chatScale" => s.chat_scale = f(1.0).clamp(0.0, 1.0),
|
||||
"chatWidth" => s.chat_width = f(1.0).clamp(0.0, 1.0),
|
||||
"chatHeightFocused" => s.chat_height_focused = f(1.0).clamp(0.0, 1.0),
|
||||
"chatHeightUnfocused" => s.chat_height_unfocused = f(0.4375).clamp(0.0, 1.0),
|
||||
"chatLineSpacing" => s.chat_line_spacing = f(0.0).clamp(0.0, 1.0),
|
||||
"autoSuggestions" => s.auto_suggestions = b(true),
|
||||
"reducedDebugInfo" => s.reduced_debug_info = b(false),
|
||||
"highContrast" => s.high_contrast = b(false),
|
||||
"showSubtitles" => s.show_subtitles = b(false),
|
||||
"notificationDisplayTime" => {
|
||||
s.notification_display_time = f(1.0).clamp(0.5, 10.0);
|
||||
}
|
||||
"mainHand" => s.main_hand_left = unquote(v) == "left",
|
||||
"resourcePacks" => s.resource_packs = parse_list(v),
|
||||
_ if k.starts_with("key_") => {
|
||||
if !s.keys.set_saved(&k[4..], v) {
|
||||
s.extra.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
}
|
||||
_ if k.starts_with("soundCategory_") => {
|
||||
let name = &k["soundCategory_".len()..];
|
||||
match SOUND_SOURCES.iter().position(|n| *n == name) {
|
||||
Some(0) => s.master_volume = f(1.0).clamp(0.0, 1.0),
|
||||
Some(i) => s.volumes[i] = f(1.0).clamp(0.0, 1.0),
|
||||
None => {
|
||||
s.extra.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
s.extra.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
Self::from_file(OptionsFile::parse(text))
|
||||
}
|
||||
/// The `options.txt` text (Options.save: `version` first, then key:value).
|
||||
pub fn serialize(&self) -> String {
|
||||
let mut lines: Vec<(String, String)> = vec![
|
||||
("ao".into(), self.smooth_lighting.to_string()),
|
||||
("biomeBlendRadius".into(), self.biome_blend.to_string()),
|
||||
("chunkSectionFadeInTime".into(), self.chunk_fade.to_string()),
|
||||
("cutoutLeaves".into(), self.cutout_leaves.to_string()),
|
||||
("enableVsync".into(), self.vsync.to_string()),
|
||||
(
|
||||
"entityDistanceScaling".into(),
|
||||
self.entity_distance.to_string(),
|
||||
),
|
||||
("entityShadows".into(), self.entity_shadows.to_string()),
|
||||
("forceUnicodeFont".into(), self.force_unicode.to_string()),
|
||||
(
|
||||
"japaneseGlyphVariants".into(),
|
||||
self.japanese_glyphs.to_string(),
|
||||
),
|
||||
("fov".into(), ((self.fov - 70.0) / 40.0).to_string()),
|
||||
(
|
||||
"graphicsPreset".into(),
|
||||
format!("\"{}\"", self.graphics_preset),
|
||||
),
|
||||
(
|
||||
"prioritizeChunkUpdates".into(),
|
||||
self.prioritize_chunk_updates.to_string(),
|
||||
),
|
||||
("fullscreen".into(), self.fullscreen.to_string()),
|
||||
("gamma".into(), self.gamma.to_string()),
|
||||
("guiScale".into(), self.gui_scale.to_string()),
|
||||
("maxFps".into(), self.max_fps.to_string()),
|
||||
(
|
||||
"improvedTransparency".into(),
|
||||
self.improved_transparency.to_string(),
|
||||
),
|
||||
(
|
||||
"inactivityFpsLimit".into(),
|
||||
format!("\"{}\"", self.inactivity_fps_limit),
|
||||
),
|
||||
("mipmapLevels".into(), self.mipmap_levels.to_string()),
|
||||
("particles".into(), self.particles.to_string()),
|
||||
(
|
||||
"reducedDebugInfo".into(),
|
||||
self.reduced_debug_info.to_string(),
|
||||
),
|
||||
("renderClouds".into(), format!("\"{}\"", self.clouds)),
|
||||
("cloudRange".into(), self.cloud_range.to_string()),
|
||||
("renderDistance".into(), self.render_distance.to_string()),
|
||||
(
|
||||
"simulationDistance".into(),
|
||||
self.simulation_distance.to_string(),
|
||||
),
|
||||
("vignette".into(), self.vignette.to_string()),
|
||||
("weatherRadius".into(), self.weather_radius.to_string()),
|
||||
("autoJump".into(), self.auto_jump.to_string()),
|
||||
("autoSuggestions".into(), self.auto_suggestions.to_string()),
|
||||
("chatColors".into(), self.chat_colors.to_string()),
|
||||
("chatLinks".into(), self.chat_links.to_string()),
|
||||
(
|
||||
"discrete_mouse_scroll".into(),
|
||||
self.discrete_scroll.to_string(),
|
||||
),
|
||||
("invertYMouse".into(), self.invert_y.to_string()),
|
||||
("bobView".into(), self.view_bobbing.to_string()),
|
||||
("toggleCrouch".into(), self.toggle_crouch.to_string()),
|
||||
("toggleSprint".into(), self.toggle_sprint.to_string()),
|
||||
("mouseSensitivity".into(), self.sensitivity.to_string()),
|
||||
("highContrast".into(), self.high_contrast.to_string()),
|
||||
("showSubtitles".into(), self.show_subtitles.to_string()),
|
||||
(
|
||||
"notificationDisplayTime".into(),
|
||||
self.notification_display_time.to_string(),
|
||||
),
|
||||
(
|
||||
"resourcePacks".into(),
|
||||
serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into()),
|
||||
),
|
||||
("lang".into(), self.language.clone()),
|
||||
("chatVisibility".into(), self.chat_visibility.to_string()),
|
||||
("chatOpacity".into(), self.chat_opacity.to_string()),
|
||||
("chatLineSpacing".into(), self.chat_line_spacing.to_string()),
|
||||
(
|
||||
"textBackgroundOpacity".into(),
|
||||
self.text_background_opacity.to_string(),
|
||||
),
|
||||
(
|
||||
"chatHeightFocused".into(),
|
||||
self.chat_height_focused.to_string(),
|
||||
),
|
||||
(
|
||||
"chatHeightUnfocused".into(),
|
||||
self.chat_height_unfocused.to_string(),
|
||||
),
|
||||
("chatScale".into(), self.chat_scale.to_string()),
|
||||
("chatWidth".into(), self.chat_width.to_string()),
|
||||
(
|
||||
"mainHand".into(),
|
||||
if self.main_hand_left {
|
||||
"\"left\"".into()
|
||||
} else {
|
||||
"\"right\"".into()
|
||||
},
|
||||
),
|
||||
("attackIndicator".into(), self.attack_indicator.to_string()),
|
||||
(
|
||||
"mouseWheelSensitivity".into(),
|
||||
self.mouse_wheel_sensitivity.to_string(),
|
||||
),
|
||||
(
|
||||
"showAutosaveIndicator".into(),
|
||||
self.autosave_indicator.to_string(),
|
||||
),
|
||||
(
|
||||
"menuBackgroundBlurriness".into(),
|
||||
self.menu_blur.to_string(),
|
||||
),
|
||||
];
|
||||
for (name, key) in self.keys.saved() {
|
||||
lines.push((format!("key_{name}"), key));
|
||||
/// Typed view of an options file.
|
||||
pub fn from_file(f: OptionsFile) -> Self {
|
||||
let mut keys = KeyBinds::default();
|
||||
for (name, _, _) in crate::keybinds::MAPPINGS {
|
||||
keys.set(name, &f.key_binding(name));
|
||||
}
|
||||
let mut volumes = [1.0; 11];
|
||||
for (i, source) in SOUND_SOURCES.iter().enumerate() {
|
||||
volumes[i] = f.double(&format!("soundCategory_{source}")) as f32;
|
||||
}
|
||||
Self {
|
||||
fov: f.int("fov") as f32,
|
||||
render_distance: f.int("renderDistance"),
|
||||
simulation_distance: f.int("simulationDistance"),
|
||||
sensitivity: f.double("mouseSensitivity") as f32,
|
||||
master_volume: volumes[0],
|
||||
volumes,
|
||||
gui_scale: f.int("guiScale").max(0) as u32,
|
||||
view_bobbing: f.bool("bobView"),
|
||||
gamma: f.double("gamma") as f32,
|
||||
max_fps: f.int("maxFps") as u32,
|
||||
vsync: f.bool("enableVsync"),
|
||||
fullscreen: f.bool("fullscreen"),
|
||||
smooth_lighting: f.bool("ao"),
|
||||
clouds: f.name("renderClouds"),
|
||||
cloud_range: f.int("cloudRange"),
|
||||
particles: f.int("particles") as u8,
|
||||
entity_distance: f.double("entityDistanceScaling") as f32,
|
||||
entity_shadows: f.bool("entityShadows"),
|
||||
biome_blend: f.int("biomeBlendRadius"),
|
||||
graphics_preset: f.name("graphicsPreset"),
|
||||
mipmap_levels: f.int("mipmapLevels"),
|
||||
weather_radius: f.int("weatherRadius"),
|
||||
chunk_fade: f.double("chunkSectionFadeInTime") as f32,
|
||||
vignette: f.bool("vignette"),
|
||||
autosave_indicator: f.bool("showAutosaveIndicator"),
|
||||
cutout_leaves: f.bool("cutoutLeaves"),
|
||||
improved_transparency: f.bool("improvedTransparency"),
|
||||
attack_indicator: f.int("attackIndicator") as u8,
|
||||
inactivity_fps_limit: f.name("inactivityFpsLimit"),
|
||||
prioritize_chunk_updates: f.int("prioritizeChunkUpdates") as u8,
|
||||
menu_blur: f.int("menuBackgroundBlurriness"),
|
||||
invert_x: f.bool("invertXMouse"),
|
||||
invert_y: f.bool("invertYMouse"),
|
||||
mouse_wheel_sensitivity: f.double("mouseWheelSensitivity") as f32,
|
||||
discrete_scroll: f.bool("discrete_mouse_scroll"),
|
||||
toggle_crouch: f.bool("toggleCrouch"),
|
||||
toggle_sprint: f.bool("toggleSprint"),
|
||||
toggle_attack: f.bool("toggleAttack"),
|
||||
toggle_use: f.bool("toggleUse"),
|
||||
sprint_window: f.int("sprintWindow"),
|
||||
auto_jump: f.bool("autoJump"),
|
||||
language: f.string("lang"),
|
||||
force_unicode: f.bool("forceUnicodeFont"),
|
||||
japanese_glyphs: f.bool("japaneseGlyphVariants"),
|
||||
chat_visibility: f.int("chatVisibility") as u8,
|
||||
chat_colors: f.bool("chatColors"),
|
||||
chat_links: f.bool("chatLinks"),
|
||||
chat_opacity: f.double("chatOpacity") as f32,
|
||||
text_background_opacity: f.double("textBackgroundOpacity") as f32,
|
||||
chat_scale: f.double("chatScale") as f32,
|
||||
chat_width: f.double("chatWidth") as f32,
|
||||
chat_height_focused: f.double("chatHeightFocused") as f32,
|
||||
chat_height_unfocused: f.double("chatHeightUnfocused") as f32,
|
||||
chat_line_spacing: f.double("chatLineSpacing") as f32,
|
||||
auto_suggestions: f.bool("autoSuggestions"),
|
||||
reduced_debug_info: f.bool("reducedDebugInfo"),
|
||||
high_contrast: f.bool("highContrast"),
|
||||
show_subtitles: f.bool("showSubtitles"),
|
||||
notification_display_time: f.double("notificationDisplayTime") as f32,
|
||||
main_hand_left: f.name("mainHand") == "left",
|
||||
resource_packs: f.list("resourcePacks"),
|
||||
keys,
|
||||
file: f,
|
||||
}
|
||||
}
|
||||
/// The options file reflecting the typed fields; values the game did not
|
||||
/// change keep their stored form.
|
||||
pub fn to_file(&self) -> OptionsFile {
|
||||
let mut f = self.file.clone();
|
||||
put_i(&mut f, "fov", self.fov as i32);
|
||||
put_i(&mut f, "renderDistance", self.render_distance);
|
||||
put_i(&mut f, "simulationDistance", self.simulation_distance);
|
||||
put_f(&mut f, "mouseSensitivity", self.sensitivity);
|
||||
for (i, source) in SOUND_SOURCES.iter().enumerate() {
|
||||
let v = if i == 0 {
|
||||
self.master_volume
|
||||
} else {
|
||||
self.volumes[i]
|
||||
};
|
||||
lines.push((format!("soundCategory_{source}"), v.to_string()));
|
||||
put_f(&mut f, &format!("soundCategory_{source}"), v);
|
||||
}
|
||||
let known: std::collections::BTreeSet<String> =
|
||||
lines.iter().map(|(k, _)| k.clone()).collect();
|
||||
for (k, v) in &self.extra {
|
||||
if !known.contains(k) {
|
||||
lines.push((k.clone(), v.clone()));
|
||||
}
|
||||
put_i(&mut f, "guiScale", self.gui_scale as i32);
|
||||
put_b(&mut f, "bobView", self.view_bobbing);
|
||||
put_f(&mut f, "gamma", self.gamma);
|
||||
put_i(&mut f, "maxFps", self.max_fps as i32);
|
||||
put_b(&mut f, "enableVsync", self.vsync);
|
||||
put_b(&mut f, "fullscreen", self.fullscreen);
|
||||
put_b(&mut f, "ao", self.smooth_lighting);
|
||||
put_name(&mut f, "renderClouds", &self.clouds);
|
||||
put_i(&mut f, "cloudRange", self.cloud_range);
|
||||
put_i(&mut f, "particles", i32::from(self.particles));
|
||||
put_f(&mut f, "entityDistanceScaling", self.entity_distance);
|
||||
put_b(&mut f, "entityShadows", self.entity_shadows);
|
||||
put_i(&mut f, "biomeBlendRadius", self.biome_blend);
|
||||
put_name(&mut f, "graphicsPreset", &self.graphics_preset);
|
||||
put_i(&mut f, "mipmapLevels", self.mipmap_levels);
|
||||
put_i(&mut f, "weatherRadius", self.weather_radius);
|
||||
put_f(&mut f, "chunkSectionFadeInTime", self.chunk_fade);
|
||||
put_b(&mut f, "vignette", self.vignette);
|
||||
put_b(&mut f, "showAutosaveIndicator", self.autosave_indicator);
|
||||
put_b(&mut f, "cutoutLeaves", self.cutout_leaves);
|
||||
put_b(&mut f, "improvedTransparency", self.improved_transparency);
|
||||
put_i(&mut f, "attackIndicator", i32::from(self.attack_indicator));
|
||||
put_name(&mut f, "inactivityFpsLimit", &self.inactivity_fps_limit);
|
||||
put_i(
|
||||
&mut f,
|
||||
"prioritizeChunkUpdates",
|
||||
i32::from(self.prioritize_chunk_updates),
|
||||
);
|
||||
put_i(&mut f, "menuBackgroundBlurriness", self.menu_blur);
|
||||
put_b(&mut f, "invertXMouse", self.invert_x);
|
||||
put_b(&mut f, "invertYMouse", self.invert_y);
|
||||
put_f(
|
||||
&mut f,
|
||||
"mouseWheelSensitivity",
|
||||
self.mouse_wheel_sensitivity,
|
||||
);
|
||||
put_b(&mut f, "discrete_mouse_scroll", self.discrete_scroll);
|
||||
put_b(&mut f, "toggleCrouch", self.toggle_crouch);
|
||||
put_b(&mut f, "toggleSprint", self.toggle_sprint);
|
||||
put_b(&mut f, "toggleAttack", self.toggle_attack);
|
||||
put_b(&mut f, "toggleUse", self.toggle_use);
|
||||
put_i(&mut f, "sprintWindow", self.sprint_window);
|
||||
put_b(&mut f, "autoJump", self.auto_jump);
|
||||
put_s(&mut f, "lang", &self.language);
|
||||
put_b(&mut f, "forceUnicodeFont", self.force_unicode);
|
||||
put_b(&mut f, "japaneseGlyphVariants", self.japanese_glyphs);
|
||||
put_i(&mut f, "chatVisibility", i32::from(self.chat_visibility));
|
||||
put_b(&mut f, "chatColors", self.chat_colors);
|
||||
put_b(&mut f, "chatLinks", self.chat_links);
|
||||
put_f(&mut f, "chatOpacity", self.chat_opacity);
|
||||
put_f(
|
||||
&mut f,
|
||||
"textBackgroundOpacity",
|
||||
self.text_background_opacity,
|
||||
);
|
||||
put_f(&mut f, "chatScale", self.chat_scale);
|
||||
put_f(&mut f, "chatWidth", self.chat_width);
|
||||
put_f(&mut f, "chatHeightFocused", self.chat_height_focused);
|
||||
put_f(&mut f, "chatHeightUnfocused", self.chat_height_unfocused);
|
||||
put_f(&mut f, "chatLineSpacing", self.chat_line_spacing);
|
||||
put_b(&mut f, "autoSuggestions", self.auto_suggestions);
|
||||
put_b(&mut f, "reducedDebugInfo", self.reduced_debug_info);
|
||||
put_b(&mut f, "highContrast", self.high_contrast);
|
||||
put_b(&mut f, "showSubtitles", self.show_subtitles);
|
||||
put_f(
|
||||
&mut f,
|
||||
"notificationDisplayTime",
|
||||
self.notification_display_time,
|
||||
);
|
||||
put_name(
|
||||
&mut f,
|
||||
"mainHand",
|
||||
if self.main_hand_left { "left" } else { "right" },
|
||||
);
|
||||
if self.resource_packs != f.list("resourcePacks") {
|
||||
f.set("resourcePacks", V::List(self.resource_packs.clone()));
|
||||
}
|
||||
let mut out = format!("version:{}\n", horizon_world::DATA_VERSION);
|
||||
for (k, v) in lines {
|
||||
out.push_str(&format!("{k}:{v}\n"));
|
||||
for (name, key) in self.keys.saved() {
|
||||
put_s(&mut f, &format!("key_{name}"), &key);
|
||||
}
|
||||
out
|
||||
f
|
||||
}
|
||||
/// The `options.txt` text (Options.save).
|
||||
pub fn serialize(&self) -> String {
|
||||
self.to_file().serialize()
|
||||
}
|
||||
pub fn save(&self, path: &Path) {
|
||||
let _ = fs::write(path, self.serialize());
|
||||
@@ -538,7 +505,8 @@ mod tests {
|
||||
let out = s.serialize();
|
||||
assert!(out.starts_with("version:"));
|
||||
assert!(out.contains("\nkey_key.jump:key.keyboard.j\n"));
|
||||
assert!(out.contains("\nsomeFutureOption:42\n"));
|
||||
// Options.save writes only the options it knows.
|
||||
assert!(!out.contains("someFutureOption"));
|
||||
assert!(out.contains("\nrenderClouds:\"fast\"\n"));
|
||||
let again = Settings::parse(&out);
|
||||
assert_eq!(again.fov, 90.0);
|
||||
@@ -555,10 +523,10 @@ mod tests {
|
||||
let d = Settings::parse("");
|
||||
assert!(!d.show_subtitles);
|
||||
assert_eq!(d.notification_display_time, 1.0);
|
||||
// The multiplier stays within the slider's range.
|
||||
// Codec.doubleRange(0.5, 10.0) rejects other values; the default stays.
|
||||
assert_eq!(
|
||||
Settings::parse("notificationDisplayTime:50\n").notification_display_time,
|
||||
10.0
|
||||
1.0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Window sizing and frame pacing of 26.3: `Window.calculateScale` and
|
||||
//! `setGuiScale`, `MouseHandler`'s scaled positions, `FramerateLimitTracker`,
|
||||
//! `FramerateLimiter` and the vsync present-mode choice.
|
||||
|
||||
/// `Window.calculateScale`: the largest scale that leaves at least 320x240
|
||||
/// GUI pixels, capped by `max_scale` (0 = automatic); an odd result is bumped
|
||||
/// to even when unicode is enforced.
|
||||
pub fn calculate_scale(framebuffer: [i32; 2], max_scale: i32, enforce_unicode: bool) -> i32 {
|
||||
let [width, height] = framebuffer;
|
||||
let mut scale = 1;
|
||||
while scale != max_scale
|
||||
&& scale < width
|
||||
&& scale < height
|
||||
&& width / (scale + 1) >= 320
|
||||
&& height / (scale + 1) >= 240
|
||||
{
|
||||
scale += 1;
|
||||
}
|
||||
if enforce_unicode && scale % 2 != 0 {
|
||||
scale += 1;
|
||||
}
|
||||
scale
|
||||
}
|
||||
|
||||
/// `Window.setGuiScale`: the GUI-scaled size of a framebuffer.
|
||||
pub fn gui_scaled_size(framebuffer: [i32; 2], gui_scale: i32) -> [i32; 2] {
|
||||
let scaled = |v: i32| (f64::from(v) / f64::from(gui_scale)).ceil() as i32;
|
||||
[scaled(framebuffer[0]), scaled(framebuffer[1])]
|
||||
}
|
||||
|
||||
/// `MouseHandler.getScaledXPos`/`getScaledYPos`.
|
||||
pub fn scaled_pos(pos: f64, gui_scaled: i32, screen: i32) -> f64 {
|
||||
pos * f64::from(gui_scaled) / f64::from(screen)
|
||||
}
|
||||
|
||||
/// `InactivityFpsLimit`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum InactivityFpsLimit {
|
||||
Minimized,
|
||||
Afk,
|
||||
}
|
||||
|
||||
/// `FramerateLimitTracker.FramerateThrottleReason`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ThrottleReason {
|
||||
None,
|
||||
WindowIconified,
|
||||
LongAfk,
|
||||
ShortAfk,
|
||||
OutOfLevelMenu,
|
||||
}
|
||||
|
||||
/// What `FramerateLimitTracker` looks at.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct FrameContext {
|
||||
pub inactivity: InactivityFpsLimit,
|
||||
pub iconified: bool,
|
||||
pub focused: bool,
|
||||
pub exclusive_fullscreen: bool,
|
||||
pub now_ms: i64,
|
||||
pub latest_input_ms: i64,
|
||||
pub has_level: bool,
|
||||
pub has_screen: bool,
|
||||
pub has_overlay: bool,
|
||||
}
|
||||
|
||||
/// `getThrottleReason`.
|
||||
pub fn throttle_reason(c: FrameContext) -> ThrottleReason {
|
||||
if !c.iconified && (c.focused || !c.exclusive_fullscreen) {
|
||||
if c.inactivity == InactivityFpsLimit::Afk {
|
||||
let afk = c.now_ms - c.latest_input_ms;
|
||||
if afk > 600_000 {
|
||||
return ThrottleReason::LongAfk;
|
||||
}
|
||||
if afk > 60_000 {
|
||||
return ThrottleReason::ShortAfk;
|
||||
}
|
||||
}
|
||||
if c.has_level || (!c.has_screen && !c.has_overlay) {
|
||||
ThrottleReason::None
|
||||
} else {
|
||||
ThrottleReason::OutOfLevelMenu
|
||||
}
|
||||
} else {
|
||||
ThrottleReason::WindowIconified
|
||||
}
|
||||
}
|
||||
|
||||
/// `getFramerateLimit`.
|
||||
pub fn framerate_limit(option_limit: i32, c: FrameContext) -> i32 {
|
||||
match throttle_reason(c) {
|
||||
ThrottleReason::None => option_limit,
|
||||
ThrottleReason::WindowIconified | ThrottleReason::LongAfk => 10,
|
||||
ThrottleReason::ShortAfk => option_limit.min(30),
|
||||
ThrottleReason::OutOfLevelMenu => 60,
|
||||
}
|
||||
}
|
||||
|
||||
/// `isHeavilyThrottled`.
|
||||
pub fn heavily_throttled(reason: ThrottleReason) -> bool {
|
||||
matches!(
|
||||
reason,
|
||||
ThrottleReason::WindowIconified | ThrottleReason::LongAfk
|
||||
)
|
||||
}
|
||||
|
||||
/// Present modes the renderer can choose between.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PresentMode {
|
||||
Fifo,
|
||||
Mailbox,
|
||||
Immediate,
|
||||
}
|
||||
|
||||
/// `GpuSurface.PresentMode.getSupportedVsyncMode`: vsync means Fifo only,
|
||||
/// otherwise the first of Immediate, Mailbox, Fifo that is supported.
|
||||
pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option<PresentMode> {
|
||||
let preferred: &[PresentMode] = if vsync {
|
||||
&[PresentMode::Fifo]
|
||||
} else {
|
||||
&[
|
||||
PresentMode::Immediate,
|
||||
PresentMode::Mailbox,
|
||||
PresentMode::Fifo,
|
||||
]
|
||||
};
|
||||
preferred.iter().copied().find(|m| supported.contains(m))
|
||||
}
|
||||
|
||||
/// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep
|
||||
/// and spin decisions are testable.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FramerateLimiter {
|
||||
last_frame_time: i64,
|
||||
average_overshoot_ns: i64,
|
||||
last_framerate_limit: i32,
|
||||
}
|
||||
|
||||
/// Time source of the limiter.
|
||||
pub trait LimiterClock {
|
||||
fn nanos(&mut self) -> i64;
|
||||
/// `LockSupport.parkNanos`.
|
||||
fn park(&mut self, nanos: i64);
|
||||
/// `Thread.onSpinWait`.
|
||||
fn spin(&mut self);
|
||||
}
|
||||
|
||||
impl FramerateLimiter {
|
||||
pub fn new(now_ns: i64) -> Self {
|
||||
Self {
|
||||
last_frame_time: now_ns,
|
||||
average_overshoot_ns: 0,
|
||||
last_framerate_limit: 0,
|
||||
}
|
||||
}
|
||||
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;
|
||||
if framerate_limit != self.last_framerate_limit {
|
||||
self.average_overshoot_ns = 0;
|
||||
self.last_framerate_limit = framerate_limit;
|
||||
}
|
||||
loop {
|
||||
let remaining = target_time_ns - clock.nanos();
|
||||
if remaining <= 0 {
|
||||
break;
|
||||
}
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
clock.spin();
|
||||
}
|
||||
}
|
||||
self.last_frame_time = clock.nanos();
|
||||
}
|
||||
pub fn last_frame_time(&self) -> i64 {
|
||||
self.last_frame_time
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Virtual {
|
||||
now: i64,
|
||||
oversleep: i64,
|
||||
}
|
||||
impl LimiterClock for Virtual {
|
||||
fn nanos(&mut self) -> i64 {
|
||||
self.now
|
||||
}
|
||||
fn park(&mut self, nanos: i64) {
|
||||
self.now += nanos + self.oversleep;
|
||||
}
|
||||
fn spin(&mut self) {
|
||||
self.now += 1000;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_matches_the_320_by_240_rule() {
|
||||
assert_eq!(calculate_scale([854, 480], 0, false), 2);
|
||||
assert_eq!(calculate_scale([1920, 1080], 0, false), 4);
|
||||
assert_eq!(calculate_scale([1920, 1080], 3, false), 3);
|
||||
assert_eq!(calculate_scale([1920, 1080], 3, true), 4);
|
||||
assert_eq!(gui_scaled_size([1921, 1081], 4), [481, 271]);
|
||||
}
|
||||
#[test]
|
||||
fn limiter_paces_frames_at_the_target() {
|
||||
let mut limiter = FramerateLimiter::new(0);
|
||||
let mut clock = Virtual {
|
||||
now: 1_000_000,
|
||||
oversleep: 200_000,
|
||||
};
|
||||
limiter.limit_display_fps(100, &mut clock);
|
||||
assert!(clock.now >= 10_000_000);
|
||||
assert!(clock.now < 10_000_000 + 1_000_000);
|
||||
}
|
||||
#[test]
|
||||
fn vsync_only_uses_fifo() {
|
||||
let all = [
|
||||
PresentMode::Mailbox,
|
||||
PresentMode::Fifo,
|
||||
PresentMode::Immediate,
|
||||
];
|
||||
assert_eq!(vsync_present_mode(&all, true), Some(PresentMode::Fifo));
|
||||
assert_eq!(
|
||||
vsync_present_mode(&all, false),
|
||||
Some(PresentMode::Immediate)
|
||||
);
|
||||
assert_eq!(
|
||||
vsync_present_mode(&[PresentMode::Fifo], false),
|
||||
Some(PresentMode::Fifo)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.platform.FramerateLimitTracker;
|
||||
import com.mojang.blaze3d.platform.InputConstants;
|
||||
import com.mojang.blaze3d.platform.Window;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.tutorial.Tutorial;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.contents.TranslatableContents;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.ServerTickRateManager;
|
||||
import net.minecraft.server.players.PlayerList;
|
||||
import net.minecraft.world.entity.player.Input;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
|
||||
/**
|
||||
* Drives the real DeltaTracker.Timer, ServerTickRateManager, Window.calculateScale,
|
||||
* FramerateLimitTracker, MouseHandler (move, scroll, turnPlayer), Entity.turn and
|
||||
* ToggleKeyMapping with the input sequences in a JSON-lines file and prints
|
||||
* every observable bit-exactly. Hosts are uninitialised shells (Unsafe) that
|
||||
* carry only the fields the exercised code reads.
|
||||
*/
|
||||
public final class VanillaGameLoopOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
return (T) allocate.invoke(unsafe, type);
|
||||
}
|
||||
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
Field f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
static float f(JsonElement v) {
|
||||
return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static double d(JsonElement v) {
|
||||
return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(), 16));
|
||||
}
|
||||
|
||||
static String fb(float v) {
|
||||
return String.format("%08x", Float.floatToRawIntBits(v) == 0x7fc00000 || Float.isNaN(v) ? 0x7fc00000 : Float.floatToRawIntBits(v));
|
||||
}
|
||||
|
||||
static String db(double v) {
|
||||
return String.format("%016x", Double.isNaN(v) ? 0x7ff8000000000000L : Double.doubleToRawLongBits(v));
|
||||
}
|
||||
|
||||
// ---- stubs for the server tick manager -------------------------------------------------
|
||||
static final List<String> reports = new ArrayList<>();
|
||||
|
||||
static final class StubStack extends CommandSourceStack {
|
||||
StubStack() {
|
||||
super(null, null, null, null, null, (Component) null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendSuccess(Supplier<Component> message, boolean broadcast) {
|
||||
var contents = (TranslatableContents) message.get().getContents();
|
||||
reports.add(contents.getArgs()[0] + " " + contents.getArgs()[1]);
|
||||
}
|
||||
}
|
||||
|
||||
static final class StubPlayers extends PlayerList {
|
||||
StubPlayers() {
|
||||
super(null, null, null, (net.minecraft.server.notifications.NotificationService) null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void broadcastAll(net.minecraft.network.protocol.Packet<?> packet) {
|
||||
}
|
||||
}
|
||||
|
||||
static StubStack stubStack;
|
||||
static StubPlayers stubPlayers;
|
||||
|
||||
static final class StubServer extends MinecraftServer {
|
||||
StubServer() {
|
||||
super(null, null, null, null, null, null, null, null, null, false, null);
|
||||
}
|
||||
|
||||
@Override public PlayerList getPlayerList() { return stubPlayers; }
|
||||
@Override public CommandSourceStack createCommandSourceStack() { return stubStack; }
|
||||
@Override public void onTickRateChanged() { }
|
||||
@Override protected boolean initServer() { return false; }
|
||||
@Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; }
|
||||
@Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; }
|
||||
@Override public boolean shouldRconBroadcast() { return false; }
|
||||
@Override protected net.minecraft.util.debugchart.SampleLogger getTickTimeLogger() { return null; }
|
||||
@Override public boolean isTickTimeLoggingEnabled() { return false; }
|
||||
@Override public net.minecraft.SystemReport fillServerSystemReport(net.minecraft.SystemReport r) { return r; }
|
||||
@Override public boolean isDedicatedServer() { return false; }
|
||||
@Override public int getRateLimitPacketsPerSecond() { return 0; }
|
||||
@Override public int getCommandSpamThresholdSeconds() { return 0; }
|
||||
@Override public int getChatSpamThresholdSeconds() { return 0; }
|
||||
@Override public boolean useNativeTransport() { return false; }
|
||||
@Override public boolean isPublished() { return false; }
|
||||
@Override public int getMaxPlayers() { return 0; }
|
||||
@Override public boolean shouldInformAdmins() { return false; }
|
||||
@Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; }
|
||||
}
|
||||
|
||||
static final class StubPlayer extends LocalPlayer {
|
||||
boolean scoping;
|
||||
|
||||
StubPlayer() {
|
||||
super(null, null, null, null, null, Input.EMPTY, false, null, null);
|
||||
}
|
||||
|
||||
@Override public boolean isScoping() { return scoping; }
|
||||
@Override public boolean isSpectator() { return false; }
|
||||
}
|
||||
|
||||
static Minecraft shell;
|
||||
static Options options;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
shell = make(Minecraft.class);
|
||||
field(Minecraft.class, "fixerUpper").set(shell, net.minecraft.util.datafix.DataFixers.getDataFixer());
|
||||
field(Minecraft.class, "instance").set(null, shell);
|
||||
options = new Options(shell, Files.createTempDirectory("opts").toFile());
|
||||
stubStack = make(StubStack.class);
|
||||
stubPlayers = make(StubPlayers.class);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
switch (c.get("t").getAsString()) {
|
||||
case "timer" -> timer(c, out);
|
||||
case "rate" -> rate(c, out);
|
||||
case "scale" -> scale(c, out);
|
||||
case "limit" -> limit(c, out);
|
||||
case "mouse" -> mouse(c, out);
|
||||
case "scroll" -> scroll(c, out);
|
||||
case "key" -> key(c, out);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static void timer(JsonObject c, PrintWriter out) {
|
||||
float[] mspt = {0};
|
||||
var timer = new DeltaTracker.Timer(f(c.get("tps")), c.get("start").getAsLong(),
|
||||
d -> mspt[0] == 0 ? d : Math.max(d, mspt[0]));
|
||||
out.println("timer");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String name = op.get(0).getAsString();
|
||||
String result = "";
|
||||
switch (name) {
|
||||
case "adv" -> {
|
||||
mspt[0] = op.get(2).isJsonNull() ? 0 : f(op.get(2));
|
||||
result = " " + timer.advanceGameTime(op.get(1).getAsLong());
|
||||
}
|
||||
case "real" -> timer.advanceRealTime(op.get(1).getAsLong());
|
||||
case "pause" -> timer.updatePauseState(op.get(1).getAsBoolean());
|
||||
case "frozen" -> timer.updateFrozenState(op.get(1).getAsBoolean());
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
}
|
||||
out.println(name + result + " " + fb(timer.getGameTimeDeltaTicks()) + " " + fb(timer.getGameTimeDeltaPartialTick(false))
|
||||
+ " " + fb(timer.getGameTimeDeltaPartialTick(true)) + " " + fb(timer.getRealtimeDeltaTicks()));
|
||||
}
|
||||
}
|
||||
|
||||
static void rate(JsonObject c, PrintWriter out) throws Exception {
|
||||
var m = make(ServerTickRateManager.class);
|
||||
field(ServerTickRateManager.class, "server").set(m, make(StubServer.class));
|
||||
// Field initialisers do not run on a shell.
|
||||
field(net.minecraft.world.TickRateManager.class, "tickrate").setFloat(m, 20.0F);
|
||||
field(net.minecraft.world.TickRateManager.class, "nanosecondsPerTick").setLong(m, 50_000_000L);
|
||||
field(net.minecraft.world.TickRateManager.class, "runGameElements").setBoolean(m, true);
|
||||
var startTime = field(ServerTickRateManager.class, "sprintTickStartTime");
|
||||
var spend = field(ServerTickRateManager.class, "sprintTimeSpend");
|
||||
out.println("rate");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String name = op.get(0).getAsString();
|
||||
reports.clear();
|
||||
String result = "";
|
||||
switch (name) {
|
||||
case "rate" -> m.setTickRate(f(op.get(1)));
|
||||
case "freeze" -> m.setFrozen(op.get(1).getAsBoolean());
|
||||
case "step" -> result = " " + m.stepGameIfPaused(op.get(1).getAsInt());
|
||||
case "stopstep" -> result = " " + m.stopStepping();
|
||||
case "sprint" -> result = " " + m.requestGameToSprint(op.get(1).getAsInt());
|
||||
case "check" -> {
|
||||
result = " " + m.checkShouldSprintThisTick();
|
||||
if (m.runsNormally() && result.equals(" true")) {
|
||||
startTime.setLong(m, op.get(1).getAsLong());
|
||||
} else if (m.runsNormally() && reports.isEmpty()) {
|
||||
// unreachable: the else branch always reports
|
||||
}
|
||||
}
|
||||
case "end" -> {
|
||||
long before = spend.getLong(m);
|
||||
m.endTickWork();
|
||||
spend.setLong(m, before + (op.get(1).getAsLong() - startTime.getLong(m)));
|
||||
}
|
||||
case "stopsprint" -> result = " " + m.stopSprinting();
|
||||
case "tick" -> m.tick();
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
}
|
||||
out.println(name + result + " | " + fb(m.tickrate()) + " " + m.nanosecondsPerTick() + " " + fb(m.millisecondsPerTick())
|
||||
+ " " + m.runsNormally() + " " + m.isSteppingForward() + " " + m.frozenTicksToRun() + " " + m.isFrozen()
|
||||
+ " " + m.isSprinting() + (reports.isEmpty() ? "" : " report " + reports.get(0)));
|
||||
}
|
||||
}
|
||||
|
||||
static Window window(int w, int h, int sw, int sh) throws Exception {
|
||||
Window window = make(Window.class);
|
||||
field(Window.class, "framebufferWidth").setInt(window, w);
|
||||
field(Window.class, "framebufferHeight").setInt(window, h);
|
||||
field(Window.class, "width").setInt(window, sw);
|
||||
field(Window.class, "height").setInt(window, sh);
|
||||
return window;
|
||||
}
|
||||
|
||||
static void scale(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(c.get("w").getAsInt(), c.get("h").getAsInt(), c.get("sw").getAsInt(), c.get("sh").getAsInt());
|
||||
int scale = window.calculateScale(c.get("max").getAsInt(), c.get("uni").getAsBoolean());
|
||||
window.setGuiScale(scale);
|
||||
out.println("scale " + scale + " " + window.getGuiScaledWidth() + " " + window.getGuiScaledHeight() + " "
|
||||
+ db(MouseHandler.getScaledXPos(window, d(c.get("x")))) + " " + db(MouseHandler.getScaledYPos(window, d(c.get("y")))));
|
||||
}
|
||||
|
||||
static void limit(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(1, 1, 1, 1);
|
||||
field(Window.class, "iconified").setBoolean(window, c.get("iconified").getAsBoolean());
|
||||
field(Window.class, "focused").setBoolean(window, c.get("focused").getAsBoolean());
|
||||
Minecraft mc = make(Minecraft.class);
|
||||
field(Minecraft.class, "window").set(mc, window);
|
||||
Gui gui = make(Gui.class);
|
||||
field(Gui.class, "screen").set(gui, c.get("screen").getAsBoolean() ? make(net.minecraft.client.gui.screens.PauseScreen.class) : null);
|
||||
field(Gui.class, "overlay").set(gui, c.get("overlay").getAsBoolean() ? make(net.minecraft.client.gui.screens.LoadingOverlay.class) : null);
|
||||
field(Minecraft.class, "gui").set(mc, gui);
|
||||
field(Minecraft.class, "level").set(mc, c.get("level").getAsBoolean() ? make(net.minecraft.client.multiplayer.ClientLevel.class) : null);
|
||||
options.framerateLimit().set(c.get("opt").getAsInt());
|
||||
options.inactivityFpsLimit().set(c.get("afk").getAsBoolean() ? InactivityFpsLimit.AFK : InactivityFpsLimit.MINIMIZED);
|
||||
var tracker = new FramerateLimitTracker(options, mc);
|
||||
field(FramerateLimitTracker.class, "latestInputTime").setLong(tracker, net.minecraft.util.Util.getMillis() - c.get("ago").getAsLong());
|
||||
out.println("limit " + tracker.getThrottleReason() + " " + tracker.getFramerateLimit() + " " + tracker.isHeavilyThrottled());
|
||||
}
|
||||
|
||||
static MouseHandler handler(Minecraft mc) throws Exception {
|
||||
MouseHandler h = new MouseHandler(mc);
|
||||
return h;
|
||||
}
|
||||
|
||||
static void mouse(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(1, 1, 1, 1);
|
||||
field(Window.class, "handle").setLong(window, 1L);
|
||||
field(Window.class, "focused").setBoolean(window, c.get("active").getAsBoolean());
|
||||
Minecraft mc = make(Minecraft.class);
|
||||
field(Minecraft.class, "window").set(mc, window);
|
||||
field(Minecraft.class, "options").set(mc, options);
|
||||
field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class));
|
||||
field(Minecraft.class, "tutorial").set(mc, make(Tutorial.class));
|
||||
StubPlayer player = make(StubPlayer.class);
|
||||
player.scoping = c.get("scoping").getAsBoolean();
|
||||
mc.player = player;
|
||||
options.sensitivity().set(d(c.get("sens")));
|
||||
options.smoothCamera = c.get("smooth").getAsBoolean();
|
||||
options.invertMouseX().set(c.get("ix").getAsBoolean());
|
||||
options.invertMouseY().set(c.get("iy").getAsBoolean());
|
||||
MouseHandler h = handler(mc);
|
||||
field(MouseHandler.class, "mouseGrabbed").setBoolean(h, c.get("grabbed").getAsBoolean());
|
||||
var turn = MouseHandler.class.getDeclaredMethod("turnPlayer", double.class);
|
||||
turn.setAccessible(true);
|
||||
var dx = field(MouseHandler.class, "accumulatedDX");
|
||||
var dy = field(MouseHandler.class, "accumulatedDY");
|
||||
double last = Double.MIN_VALUE;
|
||||
out.println("mouse");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "move" -> h.onMove(1L, d(op.get(1)), d(op.get(2)), d(op.get(3)), d(op.get(4)));
|
||||
case "ignore" -> h.setIgnoreFirstMove();
|
||||
case "frame" -> {
|
||||
double time = d(op.get(1));
|
||||
double mousea = time - last;
|
||||
last = time;
|
||||
// MouseHandler.handleAccumulatedMovement without the SDL clock and screens.
|
||||
if (mc.isWindowActive() && h.isMouseGrabbed() && mc.player != null) {
|
||||
turn.invoke(h, mousea);
|
||||
}
|
||||
dx.setDouble(h, 0.0);
|
||||
dy.setDouble(h, 0.0);
|
||||
out.println("frame " + fb(player.getXRot()) + " " + fb(player.getYRot()) + " "
|
||||
+ fb(player.xRotO) + " " + fb(player.yRotO));
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void scroll(JsonObject c, PrintWriter out) throws Exception {
|
||||
Window window = window(1, 1, 1, 1);
|
||||
field(Window.class, "handle").setLong(window, 1L);
|
||||
Minecraft mc = make(Minecraft.class);
|
||||
field(Minecraft.class, "window").set(mc, window);
|
||||
field(Minecraft.class, "options").set(mc, options);
|
||||
field(Minecraft.class, "framerateLimitTracker").set(mc, make(FramerateLimitTracker.class));
|
||||
field(Minecraft.class, "gui").set(mc, make(Gui.class));
|
||||
StubPlayer player = make(StubPlayer.class);
|
||||
Inventory inventory = make(Inventory.class);
|
||||
inventory.setSelectedSlot(c.get("slot").getAsInt());
|
||||
field(net.minecraft.world.entity.player.Player.class, "inventory").set(player, inventory);
|
||||
mc.player = player;
|
||||
options.discreteMouseScroll().set(c.get("discrete").getAsBoolean());
|
||||
options.mouseWheelSensitivity().set(d(c.get("sens")));
|
||||
MouseHandler h = handler(mc);
|
||||
out.println("scroll");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
h.onScroll(1L, d(op.get(0)), d(op.get(1)));
|
||||
out.println(inventory.getSelectedSlot());
|
||||
}
|
||||
}
|
||||
|
||||
static int keys = 0;
|
||||
|
||||
static void key(JsonObject c, PrintWriter out) throws Exception {
|
||||
AtomicBoolean option = new AtomicBoolean();
|
||||
int value = 10000 + keys++;
|
||||
KeyMapping mapping = c.get("toggle").getAsBoolean()
|
||||
? new ToggleKeyMapping("key.test" + value, c.get("keyboard").getAsBoolean() ? InputConstants.Type.KEYBOARD : InputConstants.Type.MOUSE,
|
||||
value, KeyMapping.Category.MISC, option::get, c.get("restore").getAsBoolean())
|
||||
: new KeyMapping("key.test" + value, InputConstants.Type.KEYBOARD, value, KeyMapping.Category.MISC);
|
||||
var release = KeyMapping.class.getDeclaredMethod("release");
|
||||
release.setAccessible(true);
|
||||
var key = c.get("toggle").getAsBoolean() && !c.get("keyboard").getAsBoolean()
|
||||
? InputConstants.Type.MOUSE.getOrCreate(value) : InputConstants.Type.KEYBOARD.getOrCreate(value);
|
||||
out.println("key");
|
||||
for (var e : c.getAsJsonArray("ops")) {
|
||||
var op = e.getAsJsonArray();
|
||||
String result = "";
|
||||
switch (op.get(0).getAsString()) {
|
||||
case "option" -> option.set(op.get(1).getAsBoolean());
|
||||
case "down" -> mapping.setDown(op.get(1).getAsBoolean());
|
||||
case "release" -> release.invoke(mapping);
|
||||
case "restore" -> result = mapping instanceof ToggleKeyMapping t ? " " + t.shouldRestoreStateOnScreenClosed() : " false";
|
||||
case "click" -> KeyMapping.click(key);
|
||||
case "consume" -> result = " " + mapping.consumeClick();
|
||||
case "ingame" -> {
|
||||
var m = KeyMapping.class.getDeclaredMethod("shouldSetOnIngameFocus");
|
||||
m.setAccessible(true);
|
||||
result = " " + m.invoke(mapping);
|
||||
}
|
||||
default -> throw new IllegalArgumentException(op.toString());
|
||||
}
|
||||
out.println(op.get(0).getAsString() + result + " " + mapping.isDown());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.util.datafix.DataFixers;
|
||||
|
||||
/**
|
||||
* Loads each options.txt case through the real Options.load and writes it back
|
||||
* with Options.save, then dumps the key mapping table (order, defaults,
|
||||
* categories). The Minecraft instance is an uninitialised shell that only
|
||||
* supplies the data fixer.
|
||||
*/
|
||||
public final class VanillaOptionsOracle {
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = u.getDeclaredField("theUnsafe");
|
||||
uf.setAccessible(true);
|
||||
Object unsafe = uf.get(null);
|
||||
var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class);
|
||||
Field fixer = Minecraft.class.getDeclaredField("fixerUpper");
|
||||
fixer.setAccessible(true);
|
||||
fixer.set(shell, DataFixers.getDataFixer());
|
||||
Field instance = Minecraft.class.getDeclaredField("instance");
|
||||
instance.setAccessible(true);
|
||||
instance.set(null, shell);
|
||||
Path cases = Path.of(args[0]);
|
||||
Path work = Files.createTempDirectory("opts");
|
||||
List<Path> files = new ArrayList<>();
|
||||
try (var s = Files.list(cases)) {
|
||||
s.sorted().forEach(files::add);
|
||||
}
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
boolean first = true;
|
||||
for (Path file : files) {
|
||||
Path target = work.resolve("options.txt");
|
||||
Files.deleteIfExists(target);
|
||||
if (!file.getFileName().toString().equals("absent.txt")) {
|
||||
Files.copy(file, target);
|
||||
}
|
||||
Options options = new Options(shell, work.toFile());
|
||||
options.save();
|
||||
out.print("== " + file.getFileName() + "\n");
|
||||
out.print(Files.readString(target, StandardCharsets.UTF_8));
|
||||
if (first) {
|
||||
first = false;
|
||||
out.print("== keys\n");
|
||||
for (KeyMapping k : options.keyMappings) {
|
||||
out.print(k.getName() + " " + k.getDefaultKey().getName() + " " + k.getCategory().id().getPath() + " "
|
||||
+ (k instanceof ToggleKeyMapping) + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.util.datafix.DataFixers;
|
||||
|
||||
/**
|
||||
* Dumps Options.processOptions as a table: key, kind and default in processing
|
||||
* order. Used to (re)generate the Rust options table; the differential harness
|
||||
* then proves the Rust port agrees on loading and saving.
|
||||
*/
|
||||
public final class VanillaOptionsTableExporter {
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = u.getDeclaredField("theUnsafe");
|
||||
uf.setAccessible(true);
|
||||
Object unsafe = uf.get(null);
|
||||
var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
Minecraft shell = (Minecraft) allocate.invoke(unsafe, Minecraft.class);
|
||||
Field instance = Minecraft.class.getDeclaredField("instance");
|
||||
instance.setAccessible(true);
|
||||
instance.set(null, shell);
|
||||
Path work = Files.createTempDirectory("opts");
|
||||
Options options = new Options(shell, work.toFile());
|
||||
Method process = Options.class.getDeclaredMethod("processOptions", Class.forName("net.minecraft.client.Options$FieldAccess"));
|
||||
process.setAccessible(true);
|
||||
Field valuesField = OptionInstance.class.getDeclaredField("values");
|
||||
valuesField.setAccessible(true);
|
||||
Gson gson = new Gson();
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0]), StandardCharsets.UTF_8))) {
|
||||
Class<?> fa = Class.forName("net.minecraft.client.Options$FieldAccess");
|
||||
Object access = Proxy.newProxyInstance(fa.getClassLoader(), new Class<?>[]{fa}, (proxy, method, a) -> {
|
||||
String name = (String) a[0];
|
||||
Class<?> rt = method.getReturnType();
|
||||
if (a.length == 2 && a[1] instanceof OptionInstance<?> oi) {
|
||||
Object vs = valuesField.get(oi);
|
||||
var encoded = ((OptionInstance<Object>) oi).codec().encodeStart(JsonOps.INSTANCE, oi.get()).result().orElse(null);
|
||||
if (vs instanceof OptionInstance.Enum<?> en) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object v : en.values()) {
|
||||
sb.append(gson.toJson(((com.mojang.serialization.Codec<Object>) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(',');
|
||||
}
|
||||
out.println("enum " + name + " " + sb);
|
||||
}
|
||||
if (vs instanceof OptionInstance.SliderableEnum<?> en) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object v : en.values()) {
|
||||
sb.append(gson.toJson(((com.mojang.serialization.Codec<Object>) en.codec()).encodeStart(JsonOps.INSTANCE, v).result().orElse(null))).append(',');
|
||||
}
|
||||
out.println("enum " + name + " " + sb);
|
||||
}
|
||||
out.println("option " + name + " " + vs.getClass().getSimpleName() + " " + describe(vs) + " => " + gson.toJson(encoded));
|
||||
return null;
|
||||
}
|
||||
if (a.length == 2) {
|
||||
out.println("plain " + name + " " + rt.getSimpleName() + " => " + a[1]);
|
||||
return a[1];
|
||||
}
|
||||
if (a.length == 4) {
|
||||
Object conv = ((Function<Object, String>) a[3]).apply(a[1]);
|
||||
out.println("custom " + name + " => " + conv);
|
||||
return a[1];
|
||||
}
|
||||
return null;
|
||||
});
|
||||
process.invoke(options, access);
|
||||
}
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
|
||||
Field map = com.mojang.blaze3d.platform.InputConstants.Type.class.getDeclaredField("map");
|
||||
map.setAccessible(true);
|
||||
for (var type : com.mojang.blaze3d.platform.InputConstants.Type.values()) {
|
||||
var m = (it.unimi.dsi.fastutil.ints.Int2ObjectMap<com.mojang.blaze3d.platform.InputConstants.Key>) map.get(type);
|
||||
var entries = new TreeMap<Integer, String>();
|
||||
for (var e : m.int2ObjectEntrySet()) {
|
||||
entries.put(e.getIntKey(), e.getValue().getName());
|
||||
}
|
||||
for (var e : entries.entrySet()) {
|
||||
out.println(type.name().toLowerCase() + " " + e.getKey() + " " + e.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static String describe(Object vs) throws Exception {
|
||||
if (vs instanceof Record r) {
|
||||
StringBuilder sb = new StringBuilder("{");
|
||||
for (var c : r.getClass().getRecordComponents()) {
|
||||
Object v = c.getAccessor().invoke(r);
|
||||
String s = String.valueOf(v);
|
||||
if (v instanceof List<?> l) {
|
||||
s = l.toString();
|
||||
} else if (v != null && s.contains("$$Lambda")) {
|
||||
s = "<fn>";
|
||||
}
|
||||
if (c.getName().equals("codec") || c.getName().equals("valueSetter") || c.getName().equals("altCondition")
|
||||
|| c.getName().equals("validateValue") || c.getName().equals("maxSupplier") || c.getName().equals("values") && !(v instanceof List)) {
|
||||
if (c.getName().equals("maxSupplier")) {
|
||||
s = "<supplier " + ((java.util.function.IntSupplier) v).getAsInt() + ">";
|
||||
} else if (!c.getName().equals("values")) {
|
||||
s = "<fn>";
|
||||
}
|
||||
}
|
||||
sb.append(c.getName()).append('=').append(s).append(' ');
|
||||
}
|
||||
return sb.append('}').toString();
|
||||
}
|
||||
return vs.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Shared plumbing for single-oracle differential harnesses.
|
||||
|
||||
A harness supplies a Java oracle (compiled against the pinned client jar and its
|
||||
libraries), a Rust example probe, and a text input; both programs write one
|
||||
result line per input line and the outputs must be byte-identical."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
|
||||
def run_logged(command, build, name, timeout=900, **kwargs):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
subprocess.run([str(c) for c in command], cwd=lab.ROOT, check=True, timeout=timeout,
|
||||
stdout=log, stderr=subprocess.STDOUT, **kwargs)
|
||||
|
||||
|
||||
def compile_oracle(build, oracle_name, jars, libraries, java_major):
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle_name + '.java')
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(parents=True, exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
run_logged(['javac', '--release', java_major, '-proc:none', '-sourcepath',
|
||||
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
|
||||
build, 'compile-java-' + oracle_name)
|
||||
return classes, dependencies, oracle
|
||||
|
||||
|
||||
def build_probe(build, example):
|
||||
run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example],
|
||||
build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3'))
|
||||
import json
|
||||
metadata = json.loads(subprocess.check_output(
|
||||
['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
|
||||
return Path(metadata['target_directory']) / 'debug/examples' / example
|
||||
|
||||
|
||||
def java_run(build, classes, dependencies, main_class, args, name, jvm=()):
|
||||
run_logged(['java', '-Xmx2g', '-Djava.awt.headless=true', *jvm, '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.' + main_class, *args], build, name)
|
||||
|
||||
|
||||
def compare(client_out, rust_out, expected_lines):
|
||||
matched = base.compare(client_out, rust_out)
|
||||
if matched != expected_lines:
|
||||
raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines')
|
||||
return matched
|
||||
|
||||
|
||||
def differential(name, oracle, probe, make_input, scope, sources=(), expected_lines=None):
|
||||
"""Compile the oracle and probe, run both on one input and require identical output."""
|
||||
import platform
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
libraries = baking.client_libraries()
|
||||
build = lab.LOCAL / name
|
||||
build.mkdir(exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
oracle_path = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle + '.java')
|
||||
all_sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/test_rust_parity.py',
|
||||
lab.ROOT / 'tools/lab.py', oracle_path, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock',
|
||||
lab.ROOT / 'crates/horizon-client/Cargo.toml', lab.ROOT / 'crates/horizon-client/src/lib.rs',
|
||||
lab.ROOT / f'crates/horizon-client/examples/{probe}.rs', *map(Path, sources)]
|
||||
tested = base.source_hashes(all_sources)
|
||||
input_path, units = make_input(build)
|
||||
input_hash = lab.digest(input_path, 'sha256') if input_path.is_file() else None
|
||||
classes, dependencies, _ = compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major'])
|
||||
binary = build_probe(build, probe)
|
||||
run_logged([binary, input_path, build / 'rust.txt'], build, 'rust')
|
||||
java_run(build, classes, dependencies, oracle, [input_path, build / 'client.txt'], 'client')
|
||||
try:
|
||||
matched = base.compare(build / 'client.txt', build / 'rust.txt')
|
||||
except AssertionError as error:
|
||||
raise AssertionError(str(error) + explain(build, str(error))) from None
|
||||
if expected_lines is not None and matched != expected_lines:
|
||||
raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines')
|
||||
base.ensure_sources_unchanged(all_sources, tested)
|
||||
if input_hash is not None and input_hash != lab.digest(input_path, 'sha256'):
|
||||
raise AssertionError('Input fixtures changed')
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'],
|
||||
platform=platform.platform(), rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], units=units,
|
||||
sources_sha256=tested, input_sha256=input_hash, client_jar_sha256=lab.digest(jars['client'], 'sha256'),
|
||||
matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), scope=scope))
|
||||
print(f'{units:,} {name} cases match the pinned client ({matched:,} output lines): {report}', flush=True)
|
||||
return matched
|
||||
|
||||
|
||||
def explain(build, message):
|
||||
"""Summarise differing sections ("== name" blocks) of multi-case outputs."""
|
||||
def sections(path):
|
||||
out, name = {}, None
|
||||
for line in path.read_text(encoding='utf-8', errors='replace').splitlines():
|
||||
if line.startswith('== '):
|
||||
name = line[3:]
|
||||
out[name] = []
|
||||
elif name is not None:
|
||||
out[name].append(line)
|
||||
return out
|
||||
left, right = sections(build / 'client.txt'), sections(build / 'rust.txt')
|
||||
report, count = '', 0
|
||||
for name in left:
|
||||
if left[name] != right.get(name):
|
||||
count += 1
|
||||
if count <= 25:
|
||||
case = build / 'cases' / name
|
||||
text = case.read_text(encoding='utf-8', errors='replace') if case.is_file() else ''
|
||||
a, b = left[name], right.get(name, [])
|
||||
diffs = [(x, y) for x, y in zip(a, b) if x != y][:4]
|
||||
if len(a) != len(b):
|
||||
diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>'))
|
||||
report += f"\n case {name}: {text[:300]!r}\n differences (vanilla, rust): {diffs}"
|
||||
return f'\n{count} differing cases.' + report
|
||||
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the game loop and input handling with the pinned client: the
|
||||
DeltaTracker.Timer, ServerTickRateManager (freeze, step, sprint), Window
|
||||
scale computation, FramerateLimitTracker decisions, MouseHandler (relative
|
||||
and absolute motion, sensitivity curve, cinematic smoothing, inversion,
|
||||
scroll accumulation and discrete scrolling), Entity.turn and ToggleKeyMapping,
|
||||
all driven with identical synthetic input and time sequences."""
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import struct
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def fbits(v):
|
||||
return struct.pack('>f', v).hex()
|
||||
|
||||
|
||||
def dbits(v):
|
||||
return struct.pack('>d', v).hex()
|
||||
|
||||
|
||||
def timer_cases(rng):
|
||||
for n in range(700):
|
||||
tps = rng.choice([20.0, 20.0, 10.0, 60.0, 1.0, 144.0])
|
||||
start = rng.choice([0, 0, 1234, 10**9])
|
||||
now = start
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
kind = rng.choice(['adv', 'adv', 'adv', 'real', 'pause', 'frozen'])
|
||||
if kind in ('adv', 'real'):
|
||||
now += rng.choice([0, 1, 2, 7, 16, 17, 33, 49, 50, 51, 99, 100, 101, 250, 999, 5000, 70000])
|
||||
if rng.random() < 0.03:
|
||||
now -= rng.randrange(0, 30)
|
||||
if kind == 'adv':
|
||||
mspt = rng.choice([None, None, None, 50.0, 25.0, 100.0, 500.0, 1000.0, 0.5, 5.0, 0.1])
|
||||
ops.append(['adv', now, None if mspt is None else fbits(mspt)])
|
||||
elif kind == 'real':
|
||||
ops.append(['real', now])
|
||||
else:
|
||||
ops.append([kind, rng.random() < 0.5])
|
||||
yield dict(t='timer', tps=fbits(tps), start=start, ops=ops)
|
||||
|
||||
|
||||
def rate_cases(rng):
|
||||
rates = [20.0, 1.0, 0.5, 0.0, -3.0, 100.0, 10000.0, 3.3, 1e-3, 33.333, 7.0, float('nan'), float('inf'), 59.99]
|
||||
for n in range(500):
|
||||
ops = []
|
||||
clock = 0
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
kind = rng.choice(['rate', 'freeze', 'step', 'stopstep', 'sprint', 'check', 'check', 'check', 'end', 'stopsprint',
|
||||
'tick', 'tick', 'tick'])
|
||||
if kind == 'rate':
|
||||
ops.append(['rate', fbits(rng.choice(rates))])
|
||||
elif kind == 'freeze':
|
||||
ops.append(['freeze', rng.random() < 0.5])
|
||||
elif kind == 'step':
|
||||
ops.append(['step', rng.choice([1, 2, 5, 20, 0, -1])])
|
||||
elif kind == 'sprint':
|
||||
ops.append(['sprint', rng.choice([1, 2, 3, 10, 100, 0])])
|
||||
elif kind in ('check', 'end'):
|
||||
clock += rng.choice([0, 1, 1000, 50_000_000, 123_456_789, 3_000_000_000])
|
||||
ops.append([kind, clock])
|
||||
else:
|
||||
ops.append([kind])
|
||||
yield dict(t='rate', ops=ops)
|
||||
|
||||
|
||||
def scale_cases(rng):
|
||||
sizes = [(1, 1), (2, 2), (319, 239), (320, 240), (321, 241), (640, 480), (854, 480), (1280, 720), (1920, 1080),
|
||||
(2560, 1440), (3840, 2160), (7680, 4320), (0, 0), (1000, 100), (100, 1000), (641, 481), (333, 777)]
|
||||
for w, h in sizes:
|
||||
for maxs in [0, 1, 2, 3, 4, 5, 6, 8, 100, -1, 7]:
|
||||
for uni in (False, True):
|
||||
sw, sh = rng.choice([(w, h), (max(w // 2, 1), max(h // 2, 1)), (w + 1, h + 3)])
|
||||
yield dict(t='scale', w=w, h=h, max=maxs, uni=uni, sw=sw, sh=sh,
|
||||
x=dbits(rng.uniform(0, w)), y=dbits(rng.uniform(0, h)))
|
||||
|
||||
|
||||
def limit_cases(rng):
|
||||
for iconified, focused in [(True, False), (True, True), (False, True)]:
|
||||
for opt in (10, 30, 60, 120, 140, 260):
|
||||
for afk in (False, True):
|
||||
for ago in (0, 1000, 59000, 61000, 599000, 601000, 5_000_000):
|
||||
for level in (False, True):
|
||||
for screen in (False, True):
|
||||
for overlay in (False, True):
|
||||
yield dict(t='limit', iconified=iconified, focused=focused, opt=opt, afk=afk, ago=ago,
|
||||
level=level, screen=screen, overlay=overlay)
|
||||
|
||||
|
||||
def mouse_cases(rng):
|
||||
for n in range(900):
|
||||
sens = rng.choice([0.0, 0.5, 1.0, 0.25, 0.1, 0.75, 0.3333, rng.random()])
|
||||
time = rng.choice([0.0, 10.0, 12345.678])
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
kind = rng.choice(['move', 'move', 'move', 'frame', 'frame', 'ignore'])
|
||||
if kind == 'move':
|
||||
x, y = rng.uniform(0, 1920), rng.uniform(0, 1080)
|
||||
big = rng.choice([1, 1, 1, 50, 5000])
|
||||
ops.append(['move', dbits(x), dbits(y), dbits(rng.uniform(-30, 30) * big), dbits(rng.uniform(-30, 30) * big)])
|
||||
elif kind == 'frame':
|
||||
time += rng.choice([0.0, 0.001, 0.0069, 0.016, 0.0167, 0.05, 0.5, 2.0])
|
||||
ops.append(['frame', dbits(time)])
|
||||
else:
|
||||
ops.append(['ignore'])
|
||||
yield dict(t='mouse', sens=dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3,
|
||||
ix=rng.random() < 0.3, iy=rng.random() < 0.3, grabbed=rng.random() < 0.85, active=rng.random() < 0.9, ops=ops)
|
||||
|
||||
|
||||
def scroll_cases(rng):
|
||||
for n in range(700):
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)])
|
||||
y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)])
|
||||
ops.append([dbits(x), dbits(y)])
|
||||
yield dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])),
|
||||
slot=rng.randrange(9), ops=ops)
|
||||
|
||||
|
||||
def key_cases(rng):
|
||||
for n in range(900):
|
||||
toggle = rng.random() < 0.8
|
||||
ops = []
|
||||
for _ in range(rng.randrange(1, 50)):
|
||||
ops.append(rng.choice([['option', rng.random() < 0.5], ['down', True], ['down', False], ['down', True], ['release'],
|
||||
['restore'], ['click'], ['consume'], ['consume'], ['ingame']]))
|
||||
yield dict(t='key', toggle=toggle, keyboard=rng.random() < 0.7, restore=rng.random() < 0.6, ops=ops)
|
||||
|
||||
|
||||
def make_cases(build):
|
||||
rng = random.Random(0x4c4f4f50)
|
||||
path = build / 'cases.jsonl'
|
||||
count = 0
|
||||
with path.open('w') as out:
|
||||
for generator in (timer_cases, rate_cases, scale_cases, limit_cases, mouse_cases, scroll_cases, key_cases):
|
||||
for case in generator(rng):
|
||||
out.write(json.dumps(case, separators=(',', ':')) + '\n')
|
||||
count += 1
|
||||
return path, count
|
||||
|
||||
|
||||
def main():
|
||||
scope = ('Real DeltaTracker.Timer (float partial ticks from integer milliseconds, pause residual, frozen partial tick, '
|
||||
'real-time delta cap), ServerTickRateManager (set rate, freeze, step, sprint including the sprint report text), '
|
||||
'Window.calculateScale/setGuiScale and MouseHandler scaled positions, FramerateLimitTracker throttle reasons and '
|
||||
'limits (not the focus-lost exclusive-fullscreen branch, which reads SDL), MouseHandler.onMove/turnPlayer with '
|
||||
'sensitivity, cinematic smoothing, scoping and inversion, Entity.turn clamps, onScroll with ScrollWheelHandler '
|
||||
'accumulation, discrete scrolling and hotbar selection, and ToggleKeyMapping/KeyMapping down, click and '
|
||||
'screen-release state. The frame clock source (Blaze3D.getTime, System.nanoTime) is injected, so sleeping in '
|
||||
'FramerateLimiter and vsync present-mode selection are covered by Rust unit tests only.')
|
||||
harness.differential(
|
||||
'rust-game-loop-parity', 'VanillaGameLoopOracle', 'game_loop_probe', make_cases, scope,
|
||||
sources=[lab.ROOT / f'crates/horizon-client/src/{name}.rs' for name in ('clock', 'mouse', 'window', 'keymapping')])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare options.txt loading and saving, and the key mapping table, with the
|
||||
pinned client: every file is loaded through the real Options.load and written
|
||||
back with Options.save, and the Rust port must produce identical text."""
|
||||
from pathlib import Path
|
||||
import random
|
||||
import shutil
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
VERSION = 5023
|
||||
|
||||
# Raw JSON-ish value texts: valid, boundary, wrong-typed, lenient-parser and
|
||||
# syntax-error forms. Syntax errors abort the rest of a load, as in vanilla.
|
||||
TOKENS = [
|
||||
'true', 'false', 'TRUE', 'False', '"true"', '0', '1', '2', '3', '4', '5', '-1', '-3', '7', '10', '11', '12', '13',
|
||||
'16', '27', '29', '30', '31', '32', '33', '60', '65', '69', '70', '71', '100', '109', '110', '111', '120', '128',
|
||||
'129', '130', '255', '256', '260', '261', '1000', '2147483646', '2147483647', '2147483648', '-2147483648',
|
||||
'0.0', '0.1', '0.25', '0.3', '0.5', '0.75', '0.77', '0.99', '1.0', '1.5', '2.0', '2.5', '5.0', '5.5', '6.0',
|
||||
'10.0', '10.5', '-0.5', '-0.0', '1e0', '1e1', '1E-2', '1e2', '2.5e-1', '0.0001', '1e30', '12.7', '4.99',
|
||||
'"fast"', '"fancy"', '"fabulous"', '"custom"', '"afk"', '"minimized"', '"left"', '"right"', '"default"',
|
||||
'"opengl"', '"all"', '"none"', '"limited"', '"never"', '"pause"', '"pause_and_toast"', '"DEFAULT"', '"FREQUENT"',
|
||||
'"CONSTANT"', '"false"', '"movement"', '"Fast"', "'fast'", 'fast', 'afk', 'left', 'abc', '', ' ', '""', 'null',
|
||||
'[]', '[1,2]', '["vanilla"]', '["vanilla","file/x.zip"]', '{}', '[vanilla,a]', '["a<b>&=\'"]', '0.5f', '.5',
|
||||
'007', '+1', 'NaN', 'Infinity', '-Infinity', '0x10', '1 2', '"unterminated', '{', ']', '1,2', '0.5 # note',
|
||||
'0.5 // note', '/* c */ 0.5', '0.5;', ')]}\'\n0.5', 'tRuE', 'nul', 'true false',
|
||||
]
|
||||
KEY_TOKENS = [
|
||||
'key.keyboard.w', 'key.keyboard.unknown', 'key.mouse.left', 'key.mouse.9', 'key.mouse.99', 'key.keyboard.200',
|
||||
'key.keyboard.007', 'key.keyboard.-5', 'key.keyboard.+4', 'key.keyboard.', 'key.keyboard', 'key.mouse', 'key.mousefoo',
|
||||
'key.keyboardX5', 'key.keyboard.abc', 'key.keyboard.f13', 'key.keyboard.keypad.0', 'key.keyboard.right.shift',
|
||||
'', 'w', 'key.w', 'scancode.17', 'key.keyboard.4294967296', 'key.keyboard.2147483647', 'key.keyboard.2147483648',
|
||||
'KEY.KEYBOARD.W', 'key.keyboard.menu', 'key.keyboard.f24',
|
||||
]
|
||||
PLAIN_TOKENS = ['true', 'false', 'True', '1', '0', 'yes', '', ' true', 'abc', '5', '-1', '2147483648', '+3', '007', '1.0']
|
||||
STRING_TOKENS = ['en_us', 'FR_fr', '', ' a:b ', 'a:b:c', 'Ünïcode', '"quoted"', 'x' * 300]
|
||||
TAIL = 'musicFrequency:"FREQUENT"\nmodelPart_hat:false\n' # shows whether a load was aborted
|
||||
|
||||
|
||||
def option_keys():
|
||||
"""Option-instance keys, read from the Rust table through the probe-independent
|
||||
list below (generated from VanillaOptionsTableExporter output)."""
|
||||
return ALL_KEYS
|
||||
|
||||
|
||||
# Every key the 26.3 Options writes, in processing order (verified by the
|
||||
# defaults case: a mismatch in either name or order fails the comparison).
|
||||
ALL_KEYS = [
|
||||
'ao', 'biomeBlendRadius', 'chunkSectionFadeInTime', 'cutoutLeaves', 'enableVsync', 'entityDistanceScaling',
|
||||
'entityShadows', 'forceUnicodeFont', 'japaneseGlyphVariants', 'fov', 'fovEffectScale', 'darknessEffectScale',
|
||||
'glintSpeed', 'glintStrength', 'preferredGraphicsBackend', 'graphicsPreset', 'prioritizeChunkUpdates',
|
||||
'fullscreen', 'exclusiveFullscreen', 'macFullscreenMenuVisibility', 'gamma', 'guiScale', 'debugGuiScale',
|
||||
'maxAnisotropyBit', 'textureFiltering', 'maxFps', 'improvedTransparency', 'inactivityFpsLimit', 'mipmapLevels',
|
||||
'narrator', 'particles', 'reducedDebugInfo', 'renderClouds', 'cloudRange', 'renderDistance',
|
||||
'simulationDistance', 'screenEffectScale', 'soundDevice', 'vignette', 'weatherRadius', 'autoJump',
|
||||
'rotateWithMinecart', 'operatorItemsTab', 'autoSuggestions', 'chatColors', 'chatLinks', 'chatLinksPrompt',
|
||||
'discrete_mouse_scroll', 'invertXMouse', 'invertYMouse', 'realmsNotifications', 'showSubtitles',
|
||||
'directionalAudio', 'bobView', 'toggleCrouch', 'toggleSprint', 'toggleAttack', 'toggleUse', 'sprintWindow',
|
||||
'darkMojangStudiosBackground', 'hideLightningFlashes', 'hideSplashTexts', 'mouseSensitivity',
|
||||
'damageTiltStrength', 'highContrast', 'highContrastBlockOutline', 'narratorHotkey', 'resourcePacks',
|
||||
'incompatibleResourcePacks', 'lastServer', 'lang', 'chatVisibility', 'chatOpacity', 'chatLineSpacing',
|
||||
'textBackgroundOpacity', 'backgroundForChatOnly', 'hideServerAddress', 'advancedItemTooltips',
|
||||
'pauseOnLostFocus', 'overrideWidth', 'overrideHeight', 'chatHeightFocused', 'chatDelay', 'chatHeightUnfocused',
|
||||
'chatScale', 'chatWidth', 'notificationDisplayTime', 'useNativeTransport', 'mainHand', 'attackIndicator',
|
||||
'tutorialStep', 'mouseWheelSensitivity', 'allowCursorChanges', 'quitShortcuts', 'ctrlClickEmulatesRightClick',
|
||||
'glDebugVerbosity', 'skipMultiplayerWarning', 'hideMatchedNames', 'joinedFirstServer', 'syncChunkWrites',
|
||||
'showAutosaveIndicator', 'allowServerListing', 'inGameNotification', 'sharePresence', 'onlyShowSecureChat',
|
||||
'saveChatDrafts', 'panoramaScrollSpeed', 'telemetryOptInExtra', 'onboardAccessibility',
|
||||
'menuBackgroundBlurriness', 'startedCleanly', 'musicToast', 'musicFrequency',
|
||||
]
|
||||
PLAIN = {'lastServer', 'lang', 'hideServerAddress', 'advancedItemTooltips', 'pauseOnLostFocus', 'overrideWidth',
|
||||
'overrideHeight', 'useNativeTransport', 'glDebugVerbosity', 'skipMultiplayerWarning', 'joinedFirstServer',
|
||||
'syncChunkWrites', 'onboardAccessibility', 'startedCleanly'}
|
||||
PLAIN_STRINGS = {'lastServer', 'lang'}
|
||||
MAPPINGS = None
|
||||
SOUNDS = ['master', 'music', 'record', 'weather', 'block', 'hostile', 'neutral', 'player', 'ambient', 'voice', 'ui']
|
||||
PARTS = ['cape', 'jacket', 'left_sleeve', 'right_sleeve', 'left_pants_leg', 'right_pants_leg', 'hat']
|
||||
|
||||
|
||||
def write(directory, index, text, newline='\n'):
|
||||
(directory / f'{index:05d}.txt').write_bytes(text.replace('\n', newline).encode('utf-8'))
|
||||
|
||||
|
||||
def make_cases(build):
|
||||
directory = build / 'cases'
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir()
|
||||
rng = random.Random(0x4f5054)
|
||||
n = 0
|
||||
# The no-file case is named absent.txt so the oracle skips the copy.
|
||||
(directory / 'absent.txt').write_text('')
|
||||
n += 1
|
||||
header = f'version:{VERSION}\n'
|
||||
# One option per file with each token: isolates every codec path.
|
||||
for key in ALL_KEYS:
|
||||
tokens = PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else (
|
||||
STRING_TOKENS if key in PLAIN_STRINGS else TOKENS)
|
||||
for token in tokens:
|
||||
write(directory, n, f'{header}{key}:{token}\n{TAIL}')
|
||||
n += 1
|
||||
# Round trips of values the game itself would save.
|
||||
for key in ALL_KEYS:
|
||||
write(directory, n, f'{header}{key}:{rng.choice(TOKENS)}\n{key}:{rng.choice(TOKENS)}\n')
|
||||
n += 1
|
||||
# Key mappings, sound volumes and model parts.
|
||||
keys = ['key.attack', 'key.use', 'key.forward', 'key.sneak', 'key.sprint', 'key.hotbar.1', 'key.swapOffhand',
|
||||
'key.debug.modifier', 'key.debug.profilingChart', 'key.spectatorHotbar', 'key.nonexistent']
|
||||
for key in keys:
|
||||
for token in KEY_TOKENS:
|
||||
write(directory, n, f'{header}key_{key}:{token}\n{TAIL}')
|
||||
n += 1
|
||||
for source in SOUNDS + ['nonexistent']:
|
||||
for token in TOKENS[:60]:
|
||||
write(directory, n, f'{header}soundCategory_{source}:{token}\n{TAIL}')
|
||||
n += 1
|
||||
for part in PARTS + ['nonexistent']:
|
||||
for token in PLAIN_TOKENS:
|
||||
write(directory, n, f'{header}modelPart_{part}:{token}\n')
|
||||
n += 1
|
||||
# Random multi-option files, some with CRLF/CR line ends, noise and duplicates.
|
||||
syntax_errors = {'1 2', '"unterminated', '{', ']', '1,2', 'true false', '0.5 // note'}
|
||||
safe = [t for t in TOKENS if t not in syntax_errors]
|
||||
for _ in range(1500):
|
||||
lines = [] if rng.random() < 0.1 else [f'version:{VERSION}']
|
||||
for _ in range(rng.randrange(1, 40)):
|
||||
key = rng.choice(ALL_KEYS)
|
||||
pool = safe if rng.random() < 0.9 else TOKENS
|
||||
lines.append(f'{key}:{rng.choice(PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else pool)}')
|
||||
if rng.random() < 0.05:
|
||||
lines.append(rng.choice(['', 'garbage', ':', 'novalue:', ':novalue', 'a:b:c', 'fullscreenResolution:1920x1080@60:24']))
|
||||
newline = rng.choice(['\n', '\n', '\r\n', '\r'])
|
||||
write(directory, n, '\n'.join(lines) + rng.choice(['', '\n']), newline)
|
||||
n += 1
|
||||
# Older files exercise the data fixers; each version boundary of the OPTIONS fixers.
|
||||
legacy = [
|
||||
'fancyGraphics:true\nao:2\nlang:EN_US\nchatOpacity:0.4\nmenuBackgroundBlurriness:0.5\nkey_key.forward:17\n'
|
||||
'key_key.attack:-100\nkey_key.use:-99\nkey_key.pickItem:-98\nkey_key.jump:-95\nresourcePacks:["programer_art"]\n'
|
||||
'showNowPlayingToast:true\n',
|
||||
'fancyGraphics:false\nao:0\nkey_key.forward:key.w\nkey_key.swapHands:key.f\nmouseSensitivity:0.5\n',
|
||||
'graphicsMode:2\nao:1\nmenuBackgroundBlurriness:abc\nchatOpacity:abc\nshowNowPlayingToast:false\n',
|
||||
'graphicsMode:0\nmenuBackgroundBlurriness:0.35\nchatOpacity:1e-3\n',
|
||||
'graphicsMode:1\nlang:Fr_Ca\nresourcePacks:["a","programer_art"]\nincompatibleResourcePacks:["programer_art"]\n',
|
||||
'key_key.forward:abc\n', 'key_key.forward:\n', 'key_key.attack:k\n', 'chatOpacity:Infinity\n',
|
||||
'chatOpacity: 0.5d\n', 'menuBackgroundBlurriness:0.25\n', 'menuBackgroundBlurriness:1.04999\n',
|
||||
]
|
||||
versions = [-1, 0, 100, 504, 505, 815, 816, 1343, 1344, 1445, 1446, 1935, 1936, 2555, 2556, 2557, 2558, 3200, 3201,
|
||||
3213, 3214, 3318, 3319, 3942, 3943, 4650, 4651, 4660, 4661, 4891, 4892, 5022, 5023, 5024, 9999]
|
||||
for version in versions:
|
||||
for body in legacy:
|
||||
write(directory, n, f'version:{version}\n{body}')
|
||||
n += 1
|
||||
for body in legacy:
|
||||
write(directory, n, body)
|
||||
n += 1
|
||||
write(directory, n, f'version:abc\n{body}')
|
||||
n += 1
|
||||
write(directory, n, f'version: 5023\n{body}')
|
||||
n += 1
|
||||
for text in ['fullscreenResolution:1920x1080@60:24\n', 'fullscreenResolution:\n', 'fov:abc\nfullscreenResolution:x\n',
|
||||
'fov:1 2\nfullscreenResolution:x\n', 'version:5023\nfov:0.5\n', 'FOV:0.5\n', ' fov:0.5\n', 'fov :0.5\n']:
|
||||
write(directory, n, f'version:{VERSION}\n{text}')
|
||||
n += 1
|
||||
return directory, n
|
||||
|
||||
|
||||
def main():
|
||||
scope = ('Real Options.load and Options.save (26.3) on generated options.txt files: the full option table in '
|
||||
'processing order with defaults, every codec/validator path (int ranges, quantised doubles, unit doubles with '
|
||||
'boolean alternative, string and id enums with wrapping, clouds, fov, frame limit, scroll sensitivity), plain '
|
||||
'fields, lenient Gson parsing and syntax-error aborts, key mappings (names, scancode-number forms, unbinding), '
|
||||
'sound volumes, model parts, line endings, the OPTIONS data fixers across version boundaries, and the '
|
||||
'KeyMapping table (order, defaults, categories, toggle mappings). Does not cover option screens or '
|
||||
'runtime side effects of setting an option.')
|
||||
harness.differential(
|
||||
'rust-options-parity', 'VanillaOptionsOracle', 'options_probe', make_cases, scope,
|
||||
sources=[lab.ROOT / 'crates/horizon-client/src/options_file.rs', lab.ROOT / 'crates/horizon-client/src/options_fixes.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/java_text.rs', lab.ROOT / 'crates/horizon-client/src/key_names.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/keybinds.rs'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user