Compare commits

..
Author SHA1 Message Date
Horizon agentandClaude Opus 5.5 60e38c57b5 crash::gpu instead of gfx::gpu: gfx.rs is over 3000 lines and may not grow
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:46:33 +01:00
Ludovic Marie 4ffac208e1 Merge branch 'split/telemetry-hooks' into split/telemetry-crash 2026-11-09 20:38:52 +01:00
Horizon agent 40f82d0e99 Merge remote-tracking branch 'origin/main' into split/telemetry-hooks
# Conflicts:
#	crates/horizon-telemetry-server/Cargo.lock
2026-11-09 20:38:46 +01:00
Horizon agent 2b3b2fe7e5 Merge branch 'split/telemetry-hooks' into split/telemetry-crash
# Conflicts:
#	crates/horizon-hooks/src/lib.rs
#	crates/horizon-platform/src/lib.rs
#	docs/layers.md
2026-11-09 20:06:14 +01:00
Horizon agent 7433b49bef Merge remote-tracking branch 'origin/main' into split/telemetry-hooks
# Conflicts:
#	crates/horizon-client/src/entry.rs
#	crates/horizon-hooks/src/lib.rs
#	crates/horizon-platform/src/lib.rs
#	docs/layers.md
2026-11-09 20:05:34 +01:00
Ludovic Marie 5176dc5a75 Merge branch 'split/telemetry-hooks' into split/telemetry-crash 2026-11-09 19:42:47 +01:00
Horizon agent 9f5ed29593 Merge remote-tracking branch 'origin/main' into split/telemetry-hooks
# Conflicts:
#	crates/horizon-client/src/entry.rs
2026-11-09 19:42:41 +01:00
Ludovic Marie 763bc981f0 Merge branch 'split/telemetry-hooks' into split/telemetry-crash 2026-11-09 19:26:18 +01:00
Horizon agentandClaude Opus 5.5 b7bf458117 horizon-telemetry-server's Cargo.lock: horizon-platform uses horizon-core (stale on main)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:26:15 +01:00
Horizon agentandClaude Opus 5.5 23f0abf4d2 horizon-client-render: one horizon-hooks dependency after main's settings store
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:11:56 +01:00
Ludovic Marie 9d70e670c8 Merge branch 'split/telemetry-hooks' into split/telemetry-crash 2026-11-09 19:11:12 +01:00
Horizon agent 5062adfb0c Merge remote-tracking branch 'origin/main' into split/telemetry-hooks
# Conflicts:
#	crates/horizon-hooks/src/lib.rs
2026-11-09 19:11:07 +01:00
Horizon agentandClaude Opus 5.5 63408fc7f0 rustfmt; Cargo.lock: horizon-client-render uses horizon-hooks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:58:17 +01:00
Horizon agent 4abfa15d97 Merge branch 'split/telemetry-hooks' into split/telemetry-crash 2026-11-09 18:39:06 +01:00
Horizon agentandClaude Opus 5.5 37bdbf9def spans::startup::since_start in the startup module; rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:39:04 +01:00
Horizon agentandClaude Opus 5.5 67d691b1e3 Telemetry hears crashes and the screen through the hooks (layer plan M5)
horizon-hooks gains crashed (the report's parts, the build and the GPU) and
display (the screen the window is on), and WorldLeft carries the build and
the GPU. crash.rs tells the hooks directly, replacing M3's on_report list
(telemetry was its only user); gfx::gpu() and crash::build() give the plain
data. telemetry.rs no longer reads the renderer, the crash module or a winit
window: everything it needs arrives through its hooks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:24:34 +01:00
Horizon agent 9a0d252abf Merge branch 'split/telemetry-display' into split/telemetry-crash 2026-11-09 18:22:36 +01:00
Horizon agentandClaude Opus 5.5 55b78015fe docs/layers.md: the hooks paragraph rewrapped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:59:57 +01:00
Horizon agentandClaude Opus 5.5 cb1198a38d Telemetry's hooks register only with horizon-extras
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:59:46 +01:00
Horizon agentandClaude Opus 5.5 17b50d7959 Telemetry's play session hears the game through the hooks (layer plan M5)
horizon-hooks gains the play session's hooks: startup (core-ready, rest-ready,
the title's first frame, once each), wants_frame_steps, world_shown, frame and
world_left, with plain data (Frame, WorldLeft, Milestone). The engine's
play_session::Session marks the startup trace and dispatches them; Game and
the startup menu hold it instead of telemetry's Session.

telemetry.rs implements them (HOOKS, registered by entry.rs like the ping):
the consent check for frame steps, the settings' encoding and the start's
timings move there, so gameplay no longer names horizon_telemetry for the
perf session.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:59:39 +01:00
217 changed files with 5483 additions and 3480 deletions

No files matched your search

@@ -1441,16 +1441,6 @@ pub enum Rumble {
},
Totem,
}
impl From<crate::input_source::Feedback> for Rumble {
fn from(event: crate::input_source::Feedback) -> Self {
use crate::input_source::Feedback;
match event {
Feedback::BlockBroken => Rumble::BlockBroken,
Feedback::Explosion { distance, radius } => Rumble::Explosion { distance, radius },
Feedback::Totem => Rumble::Totem,
}
}
}
/// A vibration: the heavy (low-frequency) and light motors, 0..1, and how
/// long it lasts.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -1,15 +0,0 @@
//! The engine's side of the input source (docs/layers.md, "Controllers, splitscreen, replays and
//! UI pages"): what gameplay tells a device beyond the keyboard and mouse. Gameplay names these
//! types, never a controller's; the controller code answers.
/// Something that happened to the player that a device may let them feel (a controller's
/// vibration). The device decides how, or whether.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Feedback {
/// The player broke a block.
BlockBroken,
/// An explosion this far away (blocks) with this power.
Explosion { distance: f64, radius: f32 },
/// A totem of undying saved the player.
Totem,
}
-1
View File
@@ -9,7 +9,6 @@ pub mod gamepad;
pub mod gameplay_guide;
pub mod held;
pub mod input;
pub mod input_source;
pub mod interaction_input;
pub mod key_names;
pub mod keybinds;
+2 -5
View File
@@ -7,7 +7,8 @@ rust-version.workspace = true
description = "The client's world data, rendering and screens: chunks, meshing, light, streaming, the renderer, the HUD, menus and settings; no gameplay"
[dependencies]
# The settings stores of the crates above the engine (docs/layers.md, "Platform registries").
# The crates above the engine: their settings stores (docs/layers.md, "Platform registries"),
# and the hooks that hear each crash (`crash.rs`).
horizon-hooks = { path = "../horizon-hooks" }
horizon-cosmetics = { path = "../horizon-cosmetics" }
# The GUI atlas's pixels, kept compressed once uploaded (hud.rs `pack_pixels`).
@@ -76,10 +77,6 @@ wgpu = { version = "30.0.1", default-features = false, features = ["gles"] }
audio = ["dep:cpal"]
# Helpers horizon-client's tests build their fixtures with.
test-support = []
# horizon-client's `horizon-extras`: asking the device for hardware ray tracing on request
# (`gfx/ray_query.rs`, `HORIZON_RAY_TRACING=1`). Without it the device is requested as without
# the variable.
horizon-extras = []
[lints]
workspace = true
@@ -1,158 +0,0 @@
//! Audio occlusion, attenuation and mixing benchmark.
//! Run with: `cargo run --profile fast -p horizon-client-render --example audio_bench`
use horizon_client_render::{
audio::Audio,
sound_engine::{MobSound, SoundInstance, Sounds, TickContext},
};
use std::{path::Path, time::Instant};
fn main() {
println!("=== Horizon Audio Attenuation & Mixing Benchmark ===");
let mut audio = Audio::silent(Path::new("/nonexistent"));
audio.engine.loaded = true;
audio.backend_live_for_bench();
audio.record_heard = false;
// Register a sound event with attenuation distance 16
audio.engine.registry.add_file(
"minecraft",
br#"{"bench.loop":{"attenuation_distance":16,"sounds":[{"name":"bench/loop","stream":false}]}}"#,
&|_, _| true,
);
// Insert 1 second of audio into cache (48000 mono samples)
let samples: Vec<f32> = (0..48_000)
.map(|i| ((i as f32) * 440.0 * 2.0 * std::f32::consts::PI / 48000.0).sin() * 0.5)
.collect();
audio.insert_cached_sound("minecraft:bench/loop", samples, 48_000, 1);
// 1. Benchmark set_listener (called every client render frame)
let listener_iterations = 200_000;
let start = Instant::now();
for i in 0..listener_iterations {
let angle = (i as f32) * 0.01;
audio.set_listener(
[
100.0 + (angle.cos() as f64) * 5.0,
64.0,
200.0 + (angle.sin() as f64) * 5.0,
],
angle,
0.0,
);
}
let listener_elapsed = start.elapsed();
println!(
"1. set_listener moving (render frame): {:?} for {} calls ({:.2} ns/call)",
listener_elapsed,
listener_iterations,
(listener_elapsed.as_nanos() as f64) / (listener_iterations as f64)
);
// 1b. Benchmark set_listener stationary (lock elimination early-out)
let stationary_iterations = 200_000;
let start = Instant::now();
for _ in 0..stationary_iterations {
audio.set_listener([100.0, 64.0, 200.0], 0.0, 0.0);
}
let stationary_elapsed = start.elapsed();
println!(
"1b. set_listener stationary (lock early-out): {:?} for {} calls ({:.2} ns/call)",
stationary_elapsed,
stationary_iterations,
(stationary_elapsed.as_nanos() as f64) / (stationary_iterations as f64)
);
// 2. Play 128 sounds in the world at various distances from listener at [100.0, 64.0, 200.0]
// 64 sounds within attenuation distance (<16 blocks)
// 64 sounds outside attenuation distance (>16 blocks)
for i in 0..128 {
let dist = if i < 64 {
(i as f64) * 0.24 // 0 to 15.1 blocks (audible)
} else {
17.0 + ((i - 64) as f64) * 1.5 // 17 to 111.5 blocks (out of attenuation range)
};
let pos = [100.0 + dist, 64.0, 200.0];
let instance = SoundInstance::new(
"minecraft:bench.loop",
crate_sound_source(i),
1.0,
1.0,
horizon_core::random::LegacyRandom::new(i as i64),
true, // looping
0,
horizon_client_render::sound_engine::Attenuation::Linear,
pos,
false,
);
audio.play_instance(instance, false);
}
// 3. Benchmark mix_buffer (5000 buffers of 1024 stereo frames @ 48kHz = ~106 seconds of audio mixing)
let mut buffer = vec![0.0f32; 1024 * 2];
let mix_iterations = 5_000;
let start = Instant::now();
for _ in 0..mix_iterations {
audio.mix_buffer(&mut buffer, 2, 48_000);
}
let mix_elapsed = start.elapsed();
println!(
"2. mix_buffer (128 active channels, 1024 stereo frames): {:?} for {} buffers ({:.2} µs/buffer)",
mix_elapsed,
mix_iterations,
(mix_elapsed.as_micros() as f64) / (mix_iterations as f64)
);
// 4. Benchmark SoundEngine::tick with ticking mob sounds
let mut mobs = Vec::new();
for i in 0..64 {
mobs.push(MobSound {
id: 2000 + i,
position: [100.0 + (i as f64) * 0.5, 64.0, 200.0 + (i as f64) * 0.5],
speed: 0.25,
baby: false,
angry: i % 2 == 0,
silent: false,
attack_scale: 0.5,
sniffer_digging: false,
});
}
let tick_ctx = TickContext {
player_underwater: false,
player_removed: false,
vehicle: None,
carts: Vec::new(),
mobs: mobs.clone(),
frozen: false,
player_position: [100.0, 64.0, 200.0],
player_speed_sqr: 0.1,
player_fall_flying: false,
ridden: None,
camera_position: [100.0, 64.0, 200.0],
};
let tick_iterations = 10_000;
let start = Instant::now();
for _ in 0..tick_iterations {
audio.tick(false, &tick_ctx);
}
let tick_elapsed = start.elapsed();
println!(
"3. SoundEngine::tick (64 channels + ticking): {:?} for {} ticks ({:.2} µs/tick)",
tick_elapsed,
tick_iterations,
(tick_elapsed.as_micros() as f64) / (tick_iterations as f64)
);
}
fn crate_sound_source(i: u32) -> usize {
match i % 6 {
0 => 0, // master
1 => 1, // music
2 => 2, // records
3 => 3, // weather
4 => 4, // blocks
_ => 5, // hostile
}
}
+2 -2
View File
@@ -382,8 +382,8 @@ impl RenderAssets {
};
// After the connected tiles: a tile identical to a block shares its layer, and the
// overlays skip shared layers.
if draws && let Some(suffix) = crate::pack_hooks::formats().emissive_suffix(root) {
emissive = crate::native_emissive::load_overlays(root, &suffix, &mut sprites);
if draws {
emissive = crate::native_emissive::load_optifine(root, &mut sprites);
}
sprites.save_disk_cache();
if draws {
@@ -233,11 +233,11 @@ pub fn texture_path(root: &Path, texture: &str, directory: &str) -> PathBuf {
}
let (namespace, path) = texture.split_once(':').unwrap_or(("minecraft", texture));
let rel = format!("assets/{namespace}/{directory}/{path}.png");
// No `.`, `..` or empty segment, and no `\` (a separator on Windows, where `..\..` climbs).
let stays = rel
.split('/')
.all(|segment| !matches!(segment, "" | "." | "..") && !segment.contains('\\'));
root.join(if stays { &rel } else { NOWHERE })
root.join(if horizon_optifine::paths::valid(&rel) {
&rel
} else {
NOWHERE
})
}
/// `SpriteSourceList.list`: every sprite id of the atlas and its origin.
+52 -166
View File
@@ -478,7 +478,6 @@ pub struct Audio {
pub record_heard: bool,
pub listener: [f64; 3],
pub listener_yaw: f32,
pub listener_pitch: f32,
pub master: f32,
/// Seeds of positional plays (the client level random's `nextLong`).
random: LegacyRandom,
@@ -723,29 +722,6 @@ impl Backend for MixerBackend {
fn set_unmuffled(&mut self, channel: ChannelId, unmuffled: bool) {
self.with(channel, |c| c.unmuffled = unmuffled);
}
fn update_channel(&mut self, channel: ChannelId, volume: f32, pitch: f32, position: [f64; 3]) {
if let Ok(mut m) = self.mixer.lock()
&& let Some(c) = m.channels.get_mut(&channel)
{
c.gain = volume;
c.pitch = pitch;
c.at = [position[0] as f32, position[1] as f32, position[2] as f32];
}
}
fn filter_stopped(&mut self, live: &[(u64, ChannelId)], stopped: &mut Vec<u64>) {
if let Ok(m) = self.mixer.lock() {
for &(h, c) in live {
if m.channels
.get(&c)
.is_none_or(|ch| ch.state == State::Stopped)
{
stopped.push(h);
}
}
} else {
stopped.extend(live.iter().map(|&(h, _)| h));
}
}
/// `getCompleteBuffer` (cached, else decoded on the decoder thread) or
/// `getStream` (decoded on a thread of its own), then attach and
/// `alSourcePlay`. A sound that cannot load leaves its source initial,
@@ -846,24 +822,18 @@ impl Backend for MixerBackend {
/// pinned client's) rendered through `ALC_SOFT_loopback` within 1e-5.
fn stereo_gains(right: f32, up: f32, forward: f32) -> [f32; 2] {
let length = (right * right + up * up + forward * forward).sqrt();
stereo_gains_with_length(right, up, forward, length)
}
#[inline]
fn stereo_gains_with_length(right: f32, up: f32, forward: f32, length: f32) -> [f32; 2] {
if length <= f32::EPSILON {
return stereo_gains_with_length(0.0, 0.0, 1.0, 1.0);
return stereo_gains(0.0, 0.0, 1.0);
}
let u = (up / length).clamp(-1.0, 1.0);
let cos_elev = (1.0 - u * u).max(0.0).sqrt();
let elevation = (up / length).clamp(-1.0, 1.0).asin();
let mut azimuth = right.atan2(forward);
if azimuth.abs() < std::f32::consts::FRAC_PI_2 {
azimuth = (azimuth.abs() * 1.5)
.min(std::f32::consts::FRAC_PI_2)
.copysign(azimuth);
}
let (sin_az, cos_az) = azimuth.sin_cos();
let side = sin_az * cos_elev;
let front = cos_az * cos_elev * 0.095_660_8;
let side = azimuth.sin() * elevation.cos();
let front = azimuth.cos() * elevation.cos() * 0.095_660_8;
[0.5 - 0.5 * side + front, 0.5 + 0.5 * side + front]
}
/// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference
@@ -883,10 +853,16 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
// and OpenAL's right = forward x up.
let basis = |yaw: f32, pitch: f32| {
let (yaw, pitch) = (f64::from(yaw.to_radians()), f64::from(pitch.to_radians()));
let (yaw_sin, yaw_cos) = yaw.sin_cos();
let (pitch_sin, pitch_cos) = pitch.sin_cos();
let forward = [-yaw_sin * pitch_cos, -pitch_sin, yaw_cos * pitch_cos];
let up = [-yaw_sin * pitch_sin, pitch_cos, yaw_cos * pitch_sin];
let forward = [
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
];
let up = [
-yaw.sin() * pitch.sin(),
pitch.cos(),
yaw.cos() * pitch.sin(),
];
let right = [
forward[1] * up[2] - forward[2] * up[1],
forward[2] * up[0] - forward[0] * up[2],
@@ -920,7 +896,7 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
// Gains and pans per source for this buffer.
let mut voices = std::mem::take(&mut mixer.voices);
voices.clear();
for (id, c) in &mut mixer.channels {
for (id, c) in &mixer.channels {
let Some((_, source_rate, source_channels)) = &c.samples else {
continue;
};
@@ -931,7 +907,6 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
if c.state != State::Playing {
continue;
}
let at = [f64::from(c.at[0]), f64::from(c.at[1]), f64::from(c.at[2])];
let away = |listener: [f64; 3]| {
[
@@ -940,56 +915,45 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
at[2] - listener[2],
]
};
let length_sq = |d: [f64; 3]| d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
let camera = if !shared {
let cam = &mixer.cameras[0];
if c.relative || cam.2 == c.world {
Some((cam.0, cam.1))
} else {
None
}
} else {
mixer
.cameras
.iter()
.filter(|camera| c.relative || camera.2 == c.world)
.min_by(|a, b| length_sq(away(a.0)).total_cmp(&length_sq(away(b.0))))
.map(|camera| (camera.0, camera.1))
};
let length = |d: [f64; 3]| d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
// The nearest camera hears it (one camera but in splitscreen).
let camera = mixer
.cameras
.iter()
.filter(|camera| c.relative || camera.2 == c.world)
.min_by(|a, b| length(away(a.0)).total_cmp(&length(away(b.0))))
.map(|camera| (camera.0, camera.1));
// Unheard sources still advance: returning to a world must not resume stale sounds.
let (listener, (forward, up, right)) = camera.unwrap_or(([0.0; 3], basis(0.0, 0.0)));
let d = if c.relative { at } else { away(listener) };
let d_sqr = length_sq(d);
let (gain, [left, right]) = if camera.is_none() {
(0.0, [0.0, 0.0])
} else if direct {
let gain = c.gain.clamp(0.0, 1.0);
(gain, [gain, gain])
} else {
let mut zero = false;
if let Some(max) = c.linear {
let max_d = max as f64;
if max <= 0.0 || (!c.relative && d_sqr >= max_d * max_d) {
zero = true;
}
}
if zero {
(0.0, [0.0, 0.0])
} else {
let distance = d_sqr.sqrt() as f32;
let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance);
let [mut left, mut right] = if c.relative {
stereo_gains_with_length(d[0] as f32, d[1] as f32, -d[2] as f32, distance)
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32;
let gain = if camera.is_some() {
c.gain.clamp(0.0, 1.0)
* if direct {
1.0
} else {
stereo_gains_with_length(dot(d, right), dot(d, up), dot(d, forward), distance)
};
if shared {
let middle = (left + right) * 0.5;
left = middle + (left - middle) * 0.5;
right = middle + (right - middle) * 0.5;
distance_gain(c.linear, distance)
}
(gain, [left * gain, right * gain])
} else {
0.0
};
let [left, right] = if direct {
[gain, gain]
} else {
// Relative sources are already in OpenAL's listener space (-Z ahead).
let [mut left, mut right] = if c.relative {
stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32)
} else {
stereo_gains(dot(d, right), dot(d, up), dot(d, forward))
};
if shared {
// Several players on the speakers: half the stereo width, as left and right are
// nobody's in particular.
let middle = (left + right) / 2.0;
left = middle + (left - middle) / 2.0;
right = middle + (right - middle) / 2.0;
}
[left * gain, right * gain]
};
let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0));
voices.push((*id, [left, right, gain], step));
@@ -1010,40 +974,6 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
};
let source_channels = source_channels as usize;
let frames = samples.len() / source_channels;
let inaudible = if channels >= 2 {
left == 0.0 && right == 0.0
} else {
gain == 0.0
};
if inaudible {
let buffer_frames = data.len() / channels;
// As the loop below: a sound of one frame or none stops, looping or not.
if !c.looping || frames <= 1 {
// `frames` may be 0: no `frames - 1` in usize. A step of 0 never
// reaches the end, as in the loop below.
let needed = frames as f64 - 1.0 - c.position;
if needed <= 0.0 {
c.state = State::Stopped;
} else if step > 0.0 {
let steps_to_stop = needed / step;
if (buffer_frames as f64) >= steps_to_stop {
c.state = State::Stopped;
} else {
c.position += step * (buffer_frames as f64);
}
}
} else {
for _ in 0..buffer_frames {
let i = c.position as usize;
if i + 1 >= frames {
c.position = 0.0;
}
c.position += step;
}
}
continue;
}
let out: &mut [f32] = if muffling && !c.unmuffled {
&mut bus
} else {
@@ -1062,8 +992,8 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
}
let t = (c.position - i as f64) as f32;
if source_channels > 1 {
let l = samples[i * 2] + (samples[(i + 1) * 2] - samples[i * 2]) * t;
let r = samples[i * 2 + 1] + (samples[(i + 1) * 2 + 1] - samples[i * 2 + 1]) * t;
let l = samples[i * 2] * (1.0 - t) + samples[(i + 1) * 2] * t;
let r = samples[i * 2 + 1] * (1.0 - t) + samples[(i + 1) * 2 + 1] * t;
if channels >= 2 {
frame[0] += l * left;
frame[1] += r * right;
@@ -1071,7 +1001,7 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
frame[0] += (l + r) * 0.5 * gain;
}
} else {
let s = samples[i] + (samples[i + 1] - samples[i]) * t;
let s = samples[i] * (1.0 - t) + samples[i + 1] * t;
if channels >= 2 {
frame[0] += s * left;
frame[1] += s * right;
@@ -1482,7 +1412,6 @@ impl Audio {
record_heard: false,
listener: [0.0; 3],
listener_yaw: 0.0,
listener_pitch: 0.0,
master: 1.0,
random: crate::random_source::create(),
source_override: None,
@@ -1606,12 +1535,8 @@ impl Audio {
/// `SoundManager.updateSource`: the camera position and rotation
/// (`Listener.setTransform` takes its forward and up vectors).
pub fn set_listener(&mut self, position: [f64; 3], yaw: f32, pitch: f32) {
if self.listener == position && self.listener_yaw == yaw && self.listener_pitch == pitch {
return;
}
self.listener = position;
self.listener_yaw = yaw;
self.listener_pitch = pitch;
if let Ok(mut m) = self.backend.mixer.lock() {
if self.backend.owner == 0 {
m.listener = position;
@@ -1651,7 +1576,6 @@ impl Audio {
record_heard: false,
listener: [0.0; 3],
listener_yaw: 0.0,
listener_pitch: 0.0,
master: self.master,
random: crate::random_source::create(),
source_override: None,
@@ -2185,25 +2109,6 @@ impl Audio {
})
.collect()
}
/// Mixes one buffer of audio into `data` (channels: 1 or 2, rate in Hz).
pub fn mix_buffer(&mut self, data: &mut [f32], channels: usize, rate: u32) {
if let Ok(mut m) = self.backend.mixer.lock() {
mix(&mut m, data, channels, rate);
}
}
#[doc(hidden)]
pub fn insert_cached_sound(&mut self, key: &str, samples: Vec<f32>, rate: u32, channels: u16) {
if let Ok(mut c) = self.backend.cache.lock() {
c.insert(
key.to_owned(),
Some((std::sync::Arc::new(samples), rate, channels)),
);
}
}
#[doc(hidden)]
pub fn backend_live_for_bench(&mut self) {
self.backend.live = true;
}
}
impl Sounds for Audio {
fn engine(&mut self) -> &mut SoundEngine {
@@ -2708,25 +2613,6 @@ mod tests {
assert_eq!(data, [0.0; 4], "returning must not resume the old one-shot");
}
/// A sound of one frame or none, heard or not, looping or not, stops at its first
/// buffer as the mixing loop stops it: none stays playing (and holds its channel).
#[test]
fn sounds_too_short_to_mix_stop_even_unheard() {
for (samples, looping) in [(vec![], false), (vec![1.0], false), (vec![1.0], true)] {
let mut mixer = Mixer::default();
let mut source = channel(samples.clone(), None, [0.0; 3], looping);
source.gain = 0.0;
mixer.channels.insert(1, source);
let mut data = [0.0; 4];
mix(&mut mixer, &mut data, 2, 48_000);
assert_eq!(
mixer.channels[&1].state,
State::Stopped,
"{samples:?} {looping}"
);
}
}
#[test]
fn variants_of_one_sound_are_the_same_sound() {
assert_eq!(
+32 -20
View File
@@ -204,6 +204,23 @@ impl Report {
}
}
/// The renderer's adapter ([`crate::gfx::adapter`]), for the hooks above the engine.
pub fn gpu() -> Option<horizon_hooks::Gpu> {
crate::gfx::adapter().map(|a| horizon_hooks::Gpu {
name: a.name,
vendor: a.vendor,
kind: a.kind,
driver: a.driver,
backend: a.backend,
})
}
/// The build, for what leaves the machine: the release (`v0.2.3`), or `dev <crate version>` for a
/// build from source.
pub fn build() -> String {
release_tag().unwrap_or_else(|| format!("dev {}", env!("CARGO_PKG_VERSION")))
}
/// The release this binary is (`v0.2.3`); a nightly's label (`Nightly 2026-10-28 · 0c02067`); for a
/// release from before 0.2, its tag and the client's crate version; for a build from source, that
/// version alone.
@@ -383,19 +400,20 @@ fn thread_name(side: &str) -> String {
/// promise to launchers (docs/api/launch.md), so it never changes within a line of that API.
pub const SAVED_LINE: &str = "Horizon: crash report saved to ";
/// What runs on each report before it is saved ([`on_report`]).
pub type ReportHook = fn(&Path, &Report);
static REPORT_HOOKS: std::sync::RwLock<Vec<ReportHook>> = std::sync::RwLock::new(Vec::new());
/// Runs `hook` with every crash report, before it is saved: the game folder and the report. An
/// extension point for what lives above the engine (Horizon's opt-in telemetry keeps the
/// report). A hook runs inside the crash handler: it must not panic or block.
pub fn on_report(hook: ReportHook) {
REPORT_HOOKS
.write()
.unwrap_or_else(|e| e.into_inner())
.push(hook);
/// The hooks above the engine hear the report before it is saved (`Hooks::crashed`; Horizon's
/// opt-in telemetry keeps it). They run inside the crash handler: they must not panic or block.
fn tell_hooks(home: &Path, report: &Report) {
let version = build();
let gpu = gpu();
horizon_hooks::engine::crashed(&horizon_hooks::Crash {
home,
version: &version,
error: &report.error,
stack: &report.stack,
thread: &report.thread,
details: &report.details,
gpu: gpu.as_ref(),
});
}
/// Writes the report and tells where it is; the log gets the error too.
@@ -418,13 +436,7 @@ fn deliver(home: &Path, report: Report) -> Option<PathBuf> {
),
);
crate::logging::flush();
for hook in REPORT_HOOKS
.read()
.unwrap_or_else(|e| e.into_inner())
.iter()
{
hook(home, &report);
}
tell_hooks(home, &report);
// A player of a shared game folder (`--player-dir`) finds the report beside its own log.
match report.save(crate::logging::player_dir_override().unwrap_or(home)) {
Ok(path) => {
@@ -569,25 +569,6 @@ pub(crate) fn polytone_noise() -> &'static horizon_core::noise::SimplexNoise {
}
impl horizon_polytone::expr::Host for BlockHost<'_> {
fn field(
&mut self,
root: horizon_polytone::expr::Root,
field: horizon_polytone::expr::Field,
) -> Option<horizon_polytone::expr::Value> {
use horizon_polytone::expr::Field as F;
if root != horizon_polytone::expr::Root::Object {
return None;
}
Some(horizon_polytone::expr::Value::Num(match field {
F::X => f64::from(self.at[0]),
F::Y => f64::from(self.at[1]),
F::Z => f64::from(self.at[2]),
F::Temperature => f64::from(self.biome.temperature),
F::Downfall => f64::from(self.biome.downfall),
_ => return None,
}))
}
fn root(&mut self, root: horizon_polytone::expr::Root) -> horizon_polytone::expr::Value {
use horizon_polytone::expr::Root;
horizon_polytone::expr::Value::Object(match root {
-53
View File
@@ -233,8 +233,6 @@ pub struct FogInputs<'a> {
pub night_vision: f32,
/// The packs' `environment` fog settings (Polytone's).
pub environment: crate::pack_palette::Environment,
/// The packs' fluid modifiers' fog.
pub fluid_fog: crate::pack_palette::FluidFogs,
}
/// `FogRenderer.setupFog` + `computeFogColor`.
@@ -399,24 +397,6 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog
}
}
}
// A pack's fluid modifier over its fluid's fog, after everything else (wiki "Custom Colors").
let fluid = match input.fog_type {
FogType::Lava => input.fluid_fog.lava,
FogType::Water if input.blindness.is_none() && input.darkness.is_none() => {
input.fluid_fog.water
}
_ => None,
};
if let Some(f) = fluid {
if let Some(rgb) = f.color {
let [r, g, b] = self::rgb(rgb);
fog.color = [r, g, b, 1.0];
}
let end = fog.environmental_end * f.radius;
let start = end - (end - fog.environmental_start * f.radius) * f.fade;
(fog.environmental_start, fog.environmental_end) = (start, end);
(fog.sky_end, fog.cloud_end) = (end, end);
}
let span = (rd / 10.0).clamp(4.0, 64.0);
fog.render_distance_start = rd - span;
fog.render_distance_end = rd;
@@ -515,7 +495,6 @@ mod tests {
full_water_vision: false,
night_vision: 0.0,
environment: Default::default(),
fluid_fog: Default::default(),
}
}
#[test]
@@ -632,38 +611,6 @@ mod tests {
let kept = setup_fog(&tables, &state, &input).color;
assert_eq!(&kept[..3], &[0.1, 0.2, 0.4]);
}
#[test]
fn a_fluid_modifier_scales_and_colours_its_fog_last() {
let sky = Sky {
fog_start: 10.0,
fog_end: 96.0,
..Sky::default()
};
let tables = FogTables {
water_fog_end: vec![1.0],
};
let mut input = inputs(&sky);
input.fog_type = FogType::Lava;
input.fire_resistance = true;
let vanilla = setup_fog(&tables, &FogState::default(), &input);
assert_eq!(
(vanilla.environmental_start, vanilla.environmental_end),
(0.0, 5.0)
);
input.fluid_fog.lava = Some(crate::pack_palette::FluidFog {
color: Some(0x00FF00),
radius: 2.0,
fade: 0.5,
});
let fog = setup_fog(&tables, &FogState::default(), &input);
assert_eq!(fog.color, [0.0, 1.0, 0.0, 1.0]);
// The end doubles; half the fade from 0 to 10 starts it at 5.
assert_eq!(
(fog.environmental_start, fog.environmental_end),
(5.0, 10.0)
);
assert_eq!((fog.sky_end, fog.cloud_end), (10.0, 10.0));
}
fn inputs_with<'a>(
input: &FogInputs<'a>,
environment: crate::pack_palette::Environment,
+5 -5
View File
@@ -7041,10 +7041,8 @@ impl Renderer {
}
}
/// This renderer's output as applied, with what its destination offers and reports.
pub fn output(&self) -> output::EffectiveOutput {
let native = self.native.as_ref().map(|n| n.frame.api);
self.output
.with_pack(self.shader_pack_kind() == Some("iris"), native)
pub fn output(&self) -> &output::EffectiveOutput {
&self.output
}
/// What this renderer's display last reported: a renderer made again for the window
/// starts from it (`Renderer::new`'s `display`).
@@ -8321,7 +8319,9 @@ impl Renderer {
let taa = !frame.title
&& self.pack_post.as_ref().is_none_or(|p| p.1.is_none())
&& self.native.as_ref().is_none_or(|n| n.post.is_none());
let hdr_lighting = self.shader_pack_kind().is_none();
let hdr_lighting = self.native.is_none()
&& self.pack_post.as_ref().is_none_or(|p| p.1.is_none())
&& std::env::var_os("HORIZON_HDR_LIGHTING").is_none_or(|v| v != "0");
if let Some(hdr) = &mut self.hdr {
hdr.lighting = hdr_lighting && hdr.look;
}
+1 -1
View File
@@ -191,7 +191,7 @@ pub struct Hdr {
pub masks: Masks,
/// HDR lighting, whether Horizon lifts this frame's world: off under a Horizon shader pack
/// that draws, while a `shaders/` pack's post or material stage runs (the pack's own),
/// and with HDR Lighting (`look`) off.
/// with HDR Lighting (`look`) off, and with `HORIZON_HDR_LIGHTING=0`, to compare.
pub lighting: bool,
/// The HDR Lighting setting: off, nothing in the world is lifted, light sources and the
/// sun included, so the picture is SDR's on the HDR canvas.
@@ -144,9 +144,6 @@ pub struct EffectiveOutput {
pub(crate) nits: [f32; 3],
/// The HUD and menus' brightness, as a share of paper white: their nits over its.
pub(crate) ui_brightness: f32,
/// The running shader pack lights the world itself: Horizon lifts none of it, so HDR
/// Lighting has nothing to switch (`with_pack`).
pub(crate) pack_lights: bool,
}
impl Default for EffectiveOutput {
fn default() -> Self {
@@ -169,22 +166,7 @@ impl EffectiveOutput {
},
nits: [203.0, 1000.0, 0.0],
ui_brightness: 1.0,
pack_lights: false,
};
/// This output under the running shader pack: a `shaders/` one (`shaders`), or one of
/// Horizon's own of API `native`. Under a 0.1 pack on the 8- or 16-bit frame the last pass
/// still lifts the light sources and the sun its marks hold (`lifts_world` in
/// `Renderer::render`); under the rest Horizon lifts nothing.
pub(crate) fn with_pack(self, shaders: bool, native: Option<horizon_shader_api::Api>) -> Self {
let pack_lights = shaders
|| native.is_some_and(|api| {
api != horizon_shader_api::Api::V0_1 || self.frame.format == super::LINEAR_FRAME
});
Self {
pack_lights,
..self
}
}
/// Whether the destination offers HDR output.
pub fn hdr_offered(&self) -> bool {
self.offered.is_some()
@@ -291,7 +273,6 @@ pub(crate) fn resolve_output(
],
ui_brightness: settings.ui_nits(reading.luminance) as f32
/ settings.paper_white_nits(reading.luminance) as f32,
pack_lights: false,
}
}
@@ -1,79 +0,0 @@
//! Hardware ray queries, only on request (#13780, after the #1180 spike): `HORIZON_RAY_TRACING=1`
//! at startup asks the device for wgpu's `EXPERIMENTAL_RAY_QUERY` when the GPU has it. Nothing
//! draws with it yet. Without the variable, and in a build without `horizon-extras` (a Horizon
//! extra, docs/layers.md), the device is opened exactly as before.
/// The ray query feature.
const RAY_QUERY: wgpu::Features = wgpu::Features::EXPERIMENTAL_RAY_QUERY;
/// Whether the player asked for ray tracing (the device needs the feature from its creation).
fn requested() -> bool {
asked(std::env::var("HORIZON_RAY_TRACING").ok().as_deref())
}
/// Whether `HORIZON_RAY_TRACING` set to `var` asks for ray tracing: only in a `horizon-extras`
/// build.
fn asked(var: Option<&str>) -> bool {
cfg!(feature = "horizon-extras") && var == Some("1")
}
/// The features to request on `adapter`: ray queries, when asked for and offered.
pub(super) fn features(adapter: &wgpu::Adapter) -> wgpu::Features {
let features = pick(requested(), adapter.features());
if requested() {
let info = adapter.get_info();
if features.is_empty() {
log::warn!(
"Horizon renderer: ray tracing asked for, but {} on {:?} has no hardware ray \
queries; it stays off",
info.name,
info.backend
);
} else {
log::info!(
"Horizon renderer: ray queries on ({} on {:?})",
info.name,
info.backend
);
}
}
features
}
fn pick(requested: bool, offered: wgpu::Features) -> wgpu::Features {
if requested {
offered & RAY_QUERY
} else {
wgpu::Features::empty()
}
}
/// The device's opt-in to `features`' experimental ones.
pub(super) fn experimental(features: wgpu::Features) -> wgpu::ExperimentalFeatures {
if features.contains(RAY_QUERY) {
horizon_hdr::experimental_features()
} else {
wgpu::ExperimentalFeatures::disabled()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_an_extras_build_asks_for_ray_tracing() {
assert_eq!(asked(Some("1")), cfg!(feature = "horizon-extras"));
assert!(!asked(None));
assert!(!asked(Some("0")));
}
#[test]
fn ray_queries_only_when_asked_and_offered() {
let all = wgpu::Features::all();
assert_eq!(pick(true, all), RAY_QUERY);
assert!(pick(false, all).is_empty());
assert!(pick(true, all - RAY_QUERY).is_empty());
assert!(!experimental(wgpu::Features::empty()).is_enabled());
}
}
@@ -5,9 +5,6 @@ use super::{
Renderer, check_layers, cull, describe_adapter, is_software, oit, startup_step, surface_format,
timing,
};
// Ray tracing on request, which the device needs from its creation (gfx.rs may not grow).
#[path = "ray_query.rs"]
mod ray_query;
use std::sync::Arc;
use winit::window::Window;
@@ -137,7 +134,6 @@ pub(super) async fn open_adapter(
let features = timing::GpuTimer::features(adapter)
| cull::Cull::features(adapter)
| oit::features(adapter)
| ray_query::features(adapter)
| (adapter.features()
& (wgpu::Features::INDIRECT_FIRST_INSTANCE
| wgpu::Features::MULTI_DRAW_INDIRECT_COUNT
@@ -170,7 +166,6 @@ pub(super) async fn open_adapter(
// with the larger blocks a few small buffers kept whole blocks the arena's pages had
// left, and over half the video memory reserved was unused (1,344 MiB for 500).
memory_hints: wgpu::MemoryHints::MemoryUsage,
experimental_features: ray_query::experimental(features),
..Default::default()
};
#[cfg(not(target_os = "macos"))]
@@ -1110,8 +1110,7 @@ impl Item {
/// active; saved values wait for it. Translucent Batching switches where the device can batch
/// (`graphics::translucent_batching_offered`), its saved value waiting for one that can,
/// Smooth Gradients only where it can draw the 16-bit frame, the same way, and GPU Culling
/// only where it is offered (`graphics::gpu_culling_offer`), with the reason it isn't. HDR
/// Lighting has nothing to switch where the running shader pack lights the world itself.
/// only where it is offered (`graphics::gpu_culling_offer`), with the reason it isn't.
fn blocked(self, s: &Settings, out: &EffectiveOutput) -> Option<&'static str> {
if !self.available() {
return Some("This feature is not yet available in Horizon.");
@@ -1142,9 +1141,6 @@ impl Item {
} else {
"Turn HDR on to use it."
}),
Item::Horizon(H::HdrLighting) if out.pack_lights => {
Some("The shader pack lights the world itself.")
}
Item::Horizon(H::TranslucentBatching)
if !crate::graphics::translucent_batching_offered() =>
{
@@ -31,49 +31,6 @@ fn smooth_gradients_wait_for_a_device_that_draws_the_16_bit_frame() {
assert_eq!(item.blocked(&s, &out), Some("Turn HDR on to use it."));
}
#[test]
fn hdr_lighting_is_greyed_only_where_the_running_pack_lights_the_world() {
use horizon_shader_api::Api;
let mut s = Settings::default();
s.horizon.hdr = HdrMode::On;
let item = Item::Horizon(H::HdrLighting);
let lights = Some("The shader pack lights the world itself.");
let out = offering(true, None);
// No pack running, as with one picked but refused, missing or its mod off: live.
assert_eq!(item.blocked(&s, &out.with_pack(false, None)), None);
// A 0.1 pack on the 16-bit frame: the light sources and the sun still shine.
assert_eq!(
item.blocked(&s, &out.with_pack(false, Some(Api::V0_1))),
None
);
assert_eq!(
item.blocked(&s, &out.with_pack(false, Some(Api::V0_2))),
lights
);
assert_eq!(item.blocked(&s, &out.with_pack(true, None)), lights);
let float = EffectiveOutput {
frame: crate::gfx::FrameConfiguration {
format: wgpu::TextureFormat::Rgba16Float,
..out.frame
},
..out
};
assert_eq!(
item.blocked(&s, &float.with_pack(false, Some(Api::V0_1))),
lights
);
// HDR's own reasons come first.
assert_eq!(
item.blocked(&s, &NONE.with_pack(true, None)),
Some("Your display or system doesn't offer HDR output.")
);
s.horizon.hdr = HdrMode::Off;
assert_eq!(
item.blocked(&s, &out.with_pack(true, None)),
Some("Turn HDR on to use it.")
);
}
#[test]
fn hdr_auto_can_be_selected_before_querying_and_brightness_waits_for_output() {
let mut s = Settings::default();
@@ -1,7 +1,6 @@
//! Optional, texture-matched overlays drawn full bright over their base texture in the same
//! terrain fragment: native mods' (`<ns>:emissive/...`) and a pack's emissive block textures
//! (OptiFine's `block/stone_e.png` beside `block/stone.png`, the suffix from the pack formats,
//! [`crate::pack_hooks`]). No extra draw calls or world light changes.
//! terrain fragment: native mods' (`<ns>:emissive/...`) and OptiFine's emissive block textures
//! (`block/stone_e.png` beside `block/stone.png`). No extra draw calls or world light changes.
use crate::sprites::Sprites;
use std::{collections::BTreeMap, path::Path};
@@ -36,12 +35,14 @@ fn tile_file(name: &str) -> Option<&str> {
name.strip_suffix(".png")
}
/// A pack's emissive overlays of the block sprites already loaded (what the terrain draws;
/// items draw from the HUD atlas): for each `<ns>:block/<name>`, or connected-texture tile
/// `assets/<ns>/.../<name>.png`, whose `<name><suffix>.png` sits beside it, the overlay is loaded
/// too and paired with it, blocks first, then tiles, each by name, at most [`MAX`] - [`NATIVE`]
/// (native mods keep their share of the table). A pack without such files adds nothing.
pub fn load_overlays(root: &Path, suffix: &str, sprites: &mut Sprites) -> Vec<(String, String)> {
/// OptiFine's emissive overlays of the block sprites already loaded (what the terrain draws;
/// items draw from the HUD atlas): for each
/// `<ns>:block/<name>`, or connected-texture tile `assets/<ns>/.../<name>.png`, whose
/// `<name><suffix>.png` sits beside it, the overlay is loaded too and paired with it, blocks
/// first, then tiles, each by name, at most [`MAX`] - [`NATIVE`] (native mods keep their share of
/// the table). A pack without such files adds nothing.
pub fn load_optifine(root: &Path, sprites: &mut Sprites) -> Vec<(String, String)> {
let suffix = horizon_optifine::emissive::suffix(root);
// Blocks with identical pixels share a layer (and the shader pairs by layer): a shared
// base would glow on every block that shares it, so it gets no overlay.
let mut sharing: BTreeMap<u32, usize> = BTreeMap::new();
@@ -55,8 +56,8 @@ pub fn load_overlays(root: &Path, suffix: &str, sprites: &mut Sprites) -> Vec<(S
sharing[layer] == 1
&& (name
.split_once(':')
.is_some_and(|(_, p)| p.starts_with("block/") && !p.ends_with(suffix))
|| tile_file(name).is_some_and(|stem| !stem.ends_with(suffix)))
.is_some_and(|(_, p)| p.starts_with("block/") && !p.ends_with(&suffix))
|| tile_file(name).is_some_and(|stem| !stem.ends_with(&suffix)))
})
.map(|(name, _)| name.clone())
.collect();
@@ -109,7 +110,7 @@ pub fn load_overlays(root: &Path, suffix: &str, sprites: &mut Sprites) -> Vec<(S
pub const CUTOUT: u32 = 1 << 31;
/// The frame's overlay table: native mods' pairs (at most [`NATIVE`] requested), then the packs'
/// OptiFine pairs flagged [`CUTOUT`] (at most [`MAX`] - [`NATIVE`], as [`load_overlays`] loads),
/// OptiFine pairs flagged [`CUTOUT`] (at most [`MAX`] - [`NATIVE`], as [`load_optifine`] loads),
/// one per base layer with native mods' first, sorted by base layer for the shader's early exit.
pub fn table<'a>(
layers: &BTreeMap<String, u32>,
@@ -203,7 +204,7 @@ mod tests {
// Items draw from the HUD atlas, not the terrain: no pair.
sprites.insert(&root, "minecraft:item/stick").unwrap();
// glowstone isn't loaded: its overlay pairs with nothing.
let pairs = load_overlays(&root, "_e", &mut sprites);
let pairs = load_optifine(&root, &mut sprites);
assert_eq!(
pairs,
[(
@@ -214,6 +215,9 @@ mod tests {
assert!(sprites.layers.contains_key("minecraft:block/stone_e"));
assert!(!sprites.layers.contains_key("minecraft:block/granite_e"));
// The pack's own suffix.
let props = root.join("assets/minecraft/optifine/emissive.properties");
std::fs::create_dir_all(props.parent().unwrap()).unwrap();
std::fs::write(&props, "suffix.emissive=_glow").unwrap();
// Connected-texture tiles pair with the overlay beside them.
let tiles = root.join("assets/minecraft/optifine/ctm/lamp");
png(&tiles.join("0.png"), 230);
@@ -230,7 +234,7 @@ mod tests {
.insert_file(&root, &format!("assets/minecraft/optifine/{tile}.png"))
.unwrap();
}
let pairs = load_overlays(&root, "_glow", &mut sprites);
let pairs = load_optifine(&root, &mut sprites);
assert_eq!(
pairs,
// Blocks first, then tiles.
@@ -7,14 +7,6 @@ use horizon_polytone::colors::PackColors;
use crate::block_entity_render::DYES;
use crate::pack_palette::{self, Environment};
fn fluid(fog: horizon_polytone::colors::FluidFog) -> pack_palette::FluidFog {
pack_palette::FluidFog {
color: fog.color,
radius: fog.radius,
fade: fog.fade,
}
}
/// The colours of every namespace's file under the pack overlay at `root`.
pub fn read(root: &Path) -> pack_palette::PackColors {
let colors = PackColors::read(root);
@@ -37,10 +29,6 @@ pub fn read(root: &Path) -> pack_palette::PackColors {
water_fog_brightening_time: env.water_fog_brightening_time,
horizon_height: env.horizon_height,
},
fluid_fog: pack_palette::FluidFogs {
water: colors.fluid_fog.water.map(fluid),
lava: colors.fluid_fog.lava.map(fluid),
},
}
}
@@ -20,10 +20,6 @@ impl PackFormats for Formats {
Some(colors::read(root))
}
fn emissive_suffix(&self, root: &Path) -> Option<String> {
Some(horizon_optifine::emissive::suffix(root))
}
fn custom_sky(&self, root: &Path) -> Option<Arc<dyn crate::custom_sky::SkyLayers>> {
let sky = custom_sky::CustomSky::load(root);
(!sky.is_empty()).then(|| Arc::new(sky) as _)
@@ -15,12 +15,6 @@ pub trait PackFormats: Send + Sync {
None
}
/// The name ending of the overlay's emissive textures (`stone_e.png` beside `stone.png`),
/// if its format has them.
fn emissive_suffix(&self, _root: &Path) -> Option<String> {
None
}
/// The sky layers the overlay draws over the vanilla sky, if it has any.
fn custom_sky(&self, _root: &Path) -> Option<Arc<dyn crate::custom_sky::SkyLayers>> {
None
@@ -59,24 +59,6 @@ pub struct PackColors {
pub xp_bar: [Option<u32>; 2],
/// The effect fogs' settings: the fog reads them every frame.
pub env: Environment,
/// The fog the packs' fluid modifiers give water and lava.
pub fluid_fog: FluidFogs,
}
/// A fluid modifier's fog: a flat colour (RGB), and the fog's radius and fade multipliers (1 is
/// vanilla's).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FluidFog {
pub color: Option<u32>,
pub radius: f32,
pub fade: f32,
}
/// The fog the packs' fluid modifiers give water and lava.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FluidFogs {
pub water: Option<FluidFog>,
pub lava: Option<FluidFog>,
}
impl Default for PackColors {
@@ -90,7 +72,6 @@ impl Default for PackColors {
entity_shadows: true,
xp_bar: [None; 2],
env: Environment::default(),
fluid_fog: FluidFogs::default(),
}
}
}
@@ -801,26 +801,6 @@ impl Host for Ctx<'_, '_> {
_ => Err(format!("{name} is not available here")),
}
}
/// A particle's own fields, as `particle_method` answers them.
fn field(&mut self, root: Root, field: horizon_polytone::expr::Field) -> Option<V> {
use horizon_polytone::expr::Field as F;
let Subject::Particle(p) = &self.subject else {
return None;
};
if root != Root::Object {
return None;
}
Some(V::Num(match field {
F::Age => f64::from(p.age),
F::Life => f64::from(p.lifetime),
F::Custom => *self.custom,
F::X => p.position[0],
F::Y => p.position[1],
F::Z => p.position[2],
F::Temperature | F::Downfall => return None,
}))
}
}
fn eval(program: &Program, ctx: &mut Ctx) -> Option<f64> {
@@ -337,13 +337,6 @@ impl Settings {
.and_then(|mode| self.video_modes.iter().position(|m| *m == mode))
.map_or(-1, |i| i as i32)
}
/// Loads only the crates' settings stores (`horizon_hooks::settings`) from the files next to
/// `path`, into the seat whose turn it is (`horizon_hooks::seat`): a splitscreen player whose
/// settings were made from P1's rather than loaded.
pub fn load_stores(path: &Path) {
let dir = path.parent();
horizon_hooks::settings::engine::load(&mut |file| fs::read_to_string(dir?.join(file)).ok());
}
pub fn load(path: &Path) -> Self {
let mut horizon = path
.parent()
@@ -913,20 +913,6 @@ pub trait Backend {
fn unpause(&mut self, channel: ChannelId);
/// `Channel.stopped`.
fn stopped(&mut self, channel: ChannelId) -> bool;
/// Update volume, pitch, and position in a single backend call.
fn update_channel(&mut self, channel: ChannelId, volume: f32, pitch: f32, position: [f64; 3]) {
self.set_volume(channel, volume);
self.set_pitch(channel, pitch);
self.set_position(channel, position);
}
/// Filter which handles have stopped playing in a single pass.
fn filter_stopped(&mut self, live: &[(u64, ChannelId)], stopped: &mut Vec<u64>) {
for &(h, c) in live {
if self.stopped(c) {
stopped.push(h);
}
}
}
/// Whether the channel plays clearly through a mod's muffle (`Audio::muffle`): its sound
/// event is one the mod exempted. A backend without a muffle ignores it.
fn set_unmuffled(&mut self, _channel: ChannelId, _unmuffled: bool) {}
@@ -1508,14 +1494,13 @@ impl SoundEngine {
.iter()
.filter_map(|(h, handle)| handle.channel.map(|c| (*h, c))),
);
let mut stopped = std::mem::take(&mut self.mapped_scratch);
stopped.clear();
backend.filter_stopped(&live, &mut stopped);
for h in stopped.drain(..) {
self.release_handle(h, backend);
for (h, c) in live.drain(..) {
if backend.stopped(c) {
self.release_handle(h, backend);
}
}
// Released handles nobody maps any more.
let mut mapped = stopped;
let mut mapped = std::mem::take(&mut self.mapped_scratch);
mapped.clear();
mapped.extend(self.instance_to_channel.iter().map(|(_, h)| *h));
self.handles
@@ -1565,7 +1550,9 @@ impl SoundEngine {
h.pitch_edited = pitch_edited;
}
if let Some(c) = self.handles.get(&handle).and_then(handle_channel) {
backend.update_channel(c, volume, pitch, position);
backend.set_volume(c, volume);
backend.set_pitch(c, pitch);
backend.set_position(c, position);
}
let instance = self.instances.get_mut(&id).expect("present");
if instance.looping
+7 -2
View File
@@ -51,7 +51,7 @@ pub fn enabled() -> bool {
}
/// Record this thread's spans even with spans off, their wall time only (no CPU clock read):
/// what the render thread's slow frames spent their time in, for the opt-in performance
/// statistics (`telemetry::Session::frame`). The thread takes them every frame ([`take`]).
/// statistics (`play_session::Session::frame`). The thread takes them every frame ([`take`]).
pub fn record_here(on: bool) {
HERE.with(|h| h.set(on));
}
@@ -466,7 +466,7 @@ pub mod startup {
Mutex, OnceLock,
atomic::{AtomicBool, AtomicU32, Ordering},
},
time::Instant,
time::{Duration, Instant},
};
static ON: AtomicBool = AtomicBool::new(false);
@@ -489,6 +489,11 @@ pub mod startup {
ON.store(sink.is_some(), Ordering::Relaxed);
}
/// The time since the process started ([`init`]'s origin; zero before it).
pub fn since_start() -> Duration {
ORIGIN.get().map_or(Duration::ZERO, Instant::elapsed)
}
/// Whether a trace is being written.
#[inline]
pub fn on() -> bool {
+1 -23
View File
@@ -1251,9 +1251,6 @@ pub struct EditBox {
/// `getMessage`: what the narrator calls the box ("<message> edit box:
/// <value>").
pub message: String,
/// `EditBox.setInvertHighlightedTextColor`: a selection draws its text
/// inverted (the default) or in the box's own colour (`AnvilScreen`).
pub invert_highlighted_text_color: bool,
/// Where a borderless box drawn in a frame of its own focuses: a controller's outline goes
/// round the frame, not over the text.
pub frame: Option<[f32; 4]>,
@@ -1546,7 +1543,6 @@ impl EditBox {
text_color_uneditable: rgba(112, 112, 112, 255),
editable: true,
message: String::new(),
invert_highlighted_text_color: true,
frame: None,
}
}
@@ -1922,11 +1918,7 @@ impl EditBox {
let right = self.x + self.width;
let (x0, x1) = (cursor_x.min(right), (hx - 1.0).min(right));
let (a, b) = (x0.min(x1), x0.max(x1));
batch.text_highlight(
atlas,
(a, ty - 1.0, b - a, 11.0),
self.invert_highlighted_text_color,
);
batch.text_highlight(atlas, (a, ty - 1.0, b - a, 11.0), true);
}
if show_cursor {
if insert {
@@ -2636,20 +2628,6 @@ mod tests {
);
}
/// `EditBox.setInvertHighlightedTextColor`: a selection inverts its text
/// unless the box asks it not to (the anvil's rename box).
#[test]
fn a_selection_inverts_its_text_unless_the_box_says_not_to() {
let mut edit = EditBox::new(0.0, 0.0, 100.0, 20.0);
assert!(edit.invert_highlighted_text_color);
edit.invert_highlighted_text_color = false;
edit.set_value("name");
edit.set_cursor(0, false);
edit.set_cursor(4, true);
assert_eq!(edit.selected_text(), "name");
assert!(!edit.invert_highlighted_text_color);
}
/// `EditBox.setEditable(false)`: the box keeps the focus, the caret keys
/// and copy, but `charTyped`/paste/Backspace/Delete do nothing, and Cut
/// copies without taking the text out. A value and the caret still show,
+2 -3
View File
@@ -119,11 +119,10 @@ audio = ["horizon-client-render/audio", "horizon-client-lib/audio"]
controllers = ["horizon-client-lib/controllers", "dep:gilrs", "dep:horizon-dualsense", "horizon-client-input/controllers"]
# Horizon's own extras over the vanilla game, for a fork that wants them out (docs/forking.md):
# cosmetics and emotes, the "Horizon player" presence, the official server added to
# the server list, the Horizon Settings and Mods pages, Discord and Play with Friends, and ray
# tracing on request (`HORIZON_RAY_TRACING=1`). Players always get them; there is no switch. `grep -rn horizon-extras crates/` lists
# the server list, the Horizon Settings and Mods pages, Discord and Play with Friends. Players always get them; there is no switch. `grep -rn horizon-extras crates/` lists
# every place it gates. Without it (`--no-default-features --features audio,controllers`) the
# client is best effort: CI builds only the default.
horizon-extras = ["horizon-client-lib/horizon-extras", "horizon-client-render/horizon-extras", "discord", "friends"]
horizon-extras = ["horizon-client-lib/horizon-extras", "discord", "friends"]
# Online extras a server or a port can leave out; the server build has none of them. "Playing Horizon"
# on Discord (game/discord.rs).
discord = ["horizon-client-lib/discord"]
@@ -287,7 +287,6 @@
"This feature is not yet available in Horizon.": "This feature is not yet available in Horizon.",
"Your display or system doesn't offer HDR output.": "Your display or system doesn't offer HDR output.",
"Turn HDR on to use it.": "Turn HDR on to use it.",
"The shader pack lights the world itself.": "The shader pack lights the world itself.",
"Your GPU or graphics API doesn't support it.": "Your GPU or graphics API doesn't support it.",
"Not with software rendering, which runs it on the CPU.": "Not with software rendering, which runs it on the CPU.",
"Out of video memory: off until the next start.": "Out of video memory: off until the next start.",
+1 -1
View File
@@ -110,6 +110,7 @@ pub mod osk;
pub mod patrol;
pub mod perf_overlay;
pub mod pick_item;
pub mod play_session;
pub mod player_sync;
pub mod portal_sections;
pub mod pose;
@@ -171,7 +172,6 @@ pub use horizon_client_input::gamepad;
pub use horizon_client_input::gameplay_guide;
pub use horizon_client_input::held;
pub use horizon_client_input::input;
pub use horizon_client_input::input_source;
pub use horizon_client_input::interaction_input;
pub use horizon_client_input::key_names;
pub use horizon_client_input::keybinds;
+8 -4
View File
@@ -20,13 +20,17 @@ pub fn main_with(mods: crate::mod_api::Mods) {
horizon_client::options_ui::HORIZON_EXTRAS
.store(false, std::sync::atomic::Ordering::Relaxed);
}
horizon_client::telemetry::mark_start();
// Opt-in telemetry keeps each crash report (docs/telemetry.md), whatever the mode.
crash::on_report(horizon_client::telemetry::keep_crash);
// The process's start, for the startup trace and the start's milestones.
horizon_client::spans::startup::init(std::time::Instant::now());
// Opt-in telemetry (the play session's summary, each crash report, whatever the mode) plugs
// in through the hooks until it moves to a Horizon crate in horizon-official's parts (layer
// plan M5). horizon-extras: telemetry is Horizon's (docs/layers.md); without it nothing is
// kept.
#[cfg(feature = "horizon-extras")]
let _ = horizon_hooks::register(&horizon_client::telemetry::HOOKS);
// Crates above the engine registered their hooks before this (horizon-official's `main`);
// none registers after this point.
horizon_hooks::engine::seal();
horizon_client::spans::startup::init(std::time::Instant::now());
horizon_client::spans::trace::start_from_env();
let args: Vec<String> = std::env::args().skip(1).collect();
let game_args = args.iter().take_while(|a| *a != "--dedicated");
+81 -61
View File
@@ -2801,7 +2801,7 @@ struct Game<'a> {
agent_last: Option<Instant>,
frame_stats: horizon_client::control::FrameStats,
/// This play session's frame and tick times, for opt-in performance statistics.
perf: horizon_client::telemetry::Session,
perf: horizon_client::play_session::Session,
/// Control replies waiting for a rendered frame or a benchmark deadline.
pending_screenshot: Option<std::sync::mpsc::Sender<String>>,
/// `screenshot-sequence` while it runs.
@@ -2882,8 +2882,19 @@ struct Game<'a> {
/// The open connection joined from Realms: `ServerData.isRealm` for the friends
/// service's presence status.
realm_session: bool,
/// Horizon Studio: replay playback, its free camera, timeline and top bar (game/studio.rs).
pub(super) studio: studio::Studio,
/// Active packet replay session (game/studio.rs).
pub(super) studio_replay: Option<horizon_client::studio::ReplayDriver>,
pub(super) studio_freecam: horizon_client::studio::StudioFreecam,
pub(super) studio_timeline: horizon_client::studio::TimelineUi,
pub(super) studio_topbar: horizon_client::studio::TopBarUi,
pub(super) studio_rmb_down: bool,
studio_camera_track_dirty: bool,
/// Camera perspective to restore after leaving replay playback.
studio_replay_previous_camera_type: Option<perspective::CameraType>,
/// Replay opened from the title screen owns the synthetic remote session.
studio_replay_standalone: bool,
last_replay_tick: Option<Instant>,
pub(super) studio_virtual_tick_ms: f32,
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
/// Single player's server thread, which `remote` is connected to.
@@ -5015,7 +5026,7 @@ impl Game<'_> {
if canceled {
return Ok(false);
}
self.input_feedback(horizon_client::input_source::Feedback::BlockBroken);
self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken);
let broken = state;
let facts = self.res.facts().get(state).clone();
let state = self.crack_mined_pot(pos, state);
@@ -5834,7 +5845,7 @@ impl Game<'_> {
batch
}
fn hud_layers(&mut self, size: [u32; 2]) -> HudBatch {
self.input_hud_begin();
self.pad.guide_shown.clear();
let mut batch = HudBatch::new(size);
batch.glint_colour = self.settings.extras.pvp.tweaks.glint_texel();
// GlobalSettingsUniform's GameTime, for a resource pack's text shader.
@@ -5931,7 +5942,7 @@ impl Game<'_> {
// the sleep overlay, debug screen and open screens still draw.
let spectator = self.spectator();
let (wi, hi) = (w as i32, h as i32);
let in_studio = self.studio.replay.is_some();
let in_studio = self.studio_replay.is_some();
let show_hud = !self.ui.hide_gui && !in_studio;
// Hud.extractRenderState asks `Screen.isInGameUi` twice: such a screen
// defers the subtitles over itself, and keeps them while F1 hides the
@@ -6273,19 +6284,19 @@ impl Game<'_> {
}
if !self.ui.hide_gui
&& self.screen == Screen::Playing
&& (self.studio.replay.is_some() || self.studio.freecam.active)
&& (self.studio_replay.is_some() || self.studio_freecam.active)
{
self.studio.topbar.render(
self.studio_topbar.render(
&mut batch,
&self.gui.atlas,
self.cursor,
self.studio.freecam.locked_to_path,
self.studio_freecam.locked_to_path,
);
self.studio.timeline.render(
self.studio_timeline.render(
&mut batch,
&self.gui.atlas,
self.cursor,
&self.studio.freecam,
&self.studio_freecam,
);
}
if show_hud {
@@ -6510,12 +6521,12 @@ impl Game<'_> {
/// `Camera.setRotation`: the camera's orientation, turned round in
/// third-person front view.
pub(super) fn camera_orientation(&self) -> glam::Quat {
if self.studio.freecam.active {
if self.studio_freecam.active {
return camera_rotation(
perspective::CameraType::FirstPerson,
self.studio.freecam.yaw,
self.studio.freecam.pitch,
) * glam::Quat::from_rotation_z(self.studio.freecam.roll.to_radians());
self.studio_freecam.yaw,
self.studio_freecam.pitch,
) * glam::Quat::from_rotation_z(self.studio_freecam.roll.to_radians());
}
match self.posed_rotation {
// The frame's camera, already turned round in front view.
@@ -6722,8 +6733,8 @@ impl Game<'_> {
self.mark_player(out.len(), !self.own_body_in_view());
let player_start = out.len();
self.mark_motion(player_start, Self::MOTION_OWN_PLAYER);
let player_alpha = if self.studio.replay.is_some() {
(self.studio.virtual_tick_ms as f64 / 50.0).clamp(0.0, 1.0)
let player_alpha = if self.studio_replay.is_some() {
(self.studio_virtual_tick_ms as f64 / 50.0).clamp(0.0, 1.0)
} else {
self.clock.camera_fraction()
};
@@ -9225,7 +9236,7 @@ impl Game<'_> {
let camera_alpha = self.clock.camera_fraction();
let vanilla = self.camera_view(camera_alpha as f32);
let view = vanilla.map(|view| {
if self.shows_panorama() || self.studio.freecam.active {
if self.shows_panorama() || self.studio_freecam.active {
view
} else {
self.native_camera_pose_now(camera_alpha as f32, view)
@@ -9403,9 +9414,9 @@ impl Game<'_> {
// hitboxes (F3+G, F3+B).
let mut lines = self.fishing_line(alpha, size);
let mut g = self.debug_gizmos(alpha as f32, camera.to_array());
if self.studio.freecam.active || self.studio.replay.is_some() {
if self.studio_freecam.active || self.studio_replay.is_some() {
horizon_client::studio::render_camera_path(
&self.studio.freecam.track,
&self.studio_freecam.track,
&mut g,
None,
100,
@@ -9432,7 +9443,7 @@ impl Game<'_> {
Vec::new()
};
pr.lap("pr_native_visuals");
let view = if self.studio.freecam.active {
let view = if self.studio_freecam.active {
glam::Mat4::from_quat(self.camera_orientation().conjugate())
} else {
horizon_client::camera::view_matrix(view_yaw, view_pitch)
@@ -9558,7 +9569,7 @@ impl Game<'_> {
} else {
self.fov_degrees(camera_alpha as f32, camera.to_array())
};
let camera_effects = fov::camera_effects_enabled(title, self.studio.freecam.active);
let camera_effects = fov::camera_effects_enabled(title, self.studio_freecam.active);
let bob = if !camera_effects {
glam::Mat4::IDENTITY
} else {
@@ -10063,7 +10074,7 @@ impl Game<'_> {
)
)
{
self.input_keyboard_used();
self.pad.keyboard_took_over = true;
}
if let WindowEvent::KeyboardInput { event, .. } = &event
&& event.state == ElementState::Pressed
@@ -10452,19 +10463,19 @@ impl Game<'_> {
let previous = self.cursor;
self.cursor = (position.x as f32 / b.scale, position.y as f32 / b.scale);
if self.screen == Screen::Playing
&& (self.studio.timeline.dragging_playhead
|| self.studio.timeline.dragging_keyframe.is_some())
&& (self.studio_timeline.dragging_playhead
|| self.studio_timeline.dragging_keyframe.is_some())
{
let action = self.studio.timeline.handle_mouse_drag(
let action = self.studio_timeline.handle_mouse_drag(
self.cursor,
b.width,
&mut self.studio.freecam,
&mut self.studio_freecam,
);
if matches!(
action,
horizon_client::studio::TimelineAction::KeyframeMoved
) {
self.studio.camera_track_dirty = true;
self.studio_camera_track_dirty = true;
}
return Ok(());
}
@@ -10516,7 +10527,7 @@ impl Game<'_> {
}
}
WindowEvent::MouseWheel { .. }
if self.screen == Screen::Playing && self.studio.replay.is_some() => {}
if self.screen == Screen::Playing && self.studio_replay.is_some() => {}
WindowEvent::MouseWheel { delta, .. } => {
let (raw_x, raw_y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (f64::from(x), f64::from(y)),
@@ -10794,44 +10805,44 @@ impl Game<'_> {
WindowEvent::MouseInput { state, button, .. } => {
let pressed = state == ElementState::Pressed;
if !pressed && button == MouseButton::Left {
let action = self.studio.timeline.handle_mouse_up();
let action = self.studio_timeline.handle_mouse_up();
if !matches!(action, horizon_client::studio::TimelineAction::None) {
self.handle_studio_timeline_action(action);
}
}
if (self.studio.freecam.active || self.studio.replay.is_some())
if (self.studio_freecam.active || self.studio_replay.is_some())
&& button == MouseButton::Right
{
if let Some(renderer) = &self.renderer {
let batch =
HudBatch::new([renderer.config.width, renderer.config.height]);
if self.studio.timeline.visible
&& self.cursor.1 >= batch.height - self.studio.timeline.height()
if self.studio_timeline.visible
&& self.cursor.1 >= batch.height - self.studio_timeline.height()
{
if pressed
&& let Some(index) = self.studio.timeline.keyframe_at_cursor(
&& let Some(index) = self.studio_timeline.keyframe_at_cursor(
self.cursor,
batch.width,
batch.height,
&self.studio.freecam,
&self.studio_freecam,
)
{
if index < self.studio.freecam.track.keyframes.len() {
self.studio.freecam.track.keyframes.remove(index);
self.studio.camera_track_dirty = true;
if index < self.studio_freecam.track.keyframes.len() {
self.studio_freecam.track.keyframes.remove(index);
self.studio_camera_track_dirty = true;
}
self.studio.timeline.selected_keyframe = None;
self.studio_timeline.selected_keyframe = None;
}
return Ok(());
}
}
if pressed {
self.studio.topbar.close_dropdown();
self.studio.rmb_down = true;
self.studio_topbar.close_dropdown();
self.studio_rmb_down = true;
self.capture(true);
return Ok(());
} else if self.studio.rmb_down {
self.studio.rmb_down = false;
} else if self.studio_rmb_down {
self.studio_rmb_down = false;
self.capture(false);
return Ok(());
}
@@ -10839,7 +10850,7 @@ impl Game<'_> {
if pressed
&& button == MouseButton::Left
&& self.screen == Screen::Playing
&& (self.studio.replay.is_some() || self.studio.freecam.active)
&& (self.studio_replay.is_some() || self.studio_freecam.active)
{
let size = self
.renderer
@@ -10847,8 +10858,8 @@ impl Game<'_> {
.map(|renderer| [renderer.config.width, renderer.config.height])
.unwrap_or([1, 1]);
let batch = HudBatch::new(size);
let had_open_menu = self.studio.topbar.open_menu.is_some();
let topbar_action = self.studio.topbar.handle_mouse_click(
let had_open_menu = self.studio_topbar.open_menu.is_some();
let topbar_action = self.studio_topbar.handle_mouse_click(
self.cursor,
batch.width,
batch.height,
@@ -10857,26 +10868,26 @@ impl Game<'_> {
self.handle_studio_topbar_action(topbar_action);
return Ok(());
}
if had_open_menu || self.cursor.1 <= self.studio.topbar.height {
if had_open_menu || self.cursor.1 <= self.studio_topbar.height {
return Ok(());
}
if self.studio.timeline.visible {
let action = self.studio.timeline.handle_mouse_down(
if self.studio_timeline.visible {
let action = self.studio_timeline.handle_mouse_down(
self.cursor,
batch.width,
batch.height,
&self.studio.freecam,
&self.studio_freecam,
);
if !matches!(action, horizon_client::studio::TimelineAction::None) {
self.handle_studio_timeline_action(action);
return Ok(());
}
if self.cursor.1 >= batch.height - self.studio.timeline.height() {
if self.cursor.1 >= batch.height - self.studio_timeline.height() {
return Ok(());
}
}
}
if self.screen == Screen::Playing && self.studio.replay.is_some() {
if self.screen == Screen::Playing && self.studio_replay.is_some() {
return Ok(());
}
if matches!(self.screen, Screen::Inventory | Screen::Creative)
@@ -11346,7 +11357,7 @@ impl Game<'_> {
let between = now.saturating_duration_since(self.frame_end);
self.frame_ticks = elapsed.as_secs_f32() * 20.0;
self.previous = now;
if self.studio.freecam.active
if self.studio_freecam.active
&& self.screen == Screen::Playing
&& !self.dialog_open()
{
@@ -11356,7 +11367,7 @@ impl Game<'_> {
let vertical =
held(KeyCode::KeyE) - held(KeyCode::KeyQ) + held(KeyCode::Space);
let fast = self.keys.raw(&KeyCode::ControlRight);
self.studio.freecam.update_flight_motion(
self.studio_freecam.update_flight_motion(
forward,
strafe,
vertical,
@@ -11436,7 +11447,7 @@ impl Game<'_> {
self.extras_frame(elapsed);
self.extras_retry()?;
self.apply_mouse_look();
self.input_look(elapsed.as_secs_f32());
self.pad_look(elapsed.as_secs_f32());
self.advance_flight();
self.tick_world_icon();
let ticked = Instant::now();
@@ -12146,7 +12157,16 @@ impl<'a> Game<'a> {
entity_attachments: Default::default(),
remote: None,
realm_session: false,
studio: Default::default(),
studio_replay: None,
studio_freecam: Default::default(),
studio_timeline: Default::default(),
studio_topbar: Default::default(),
studio_rmb_down: false,
studio_camera_track_dirty: false,
studio_replay_previous_camera_type: None,
studio_replay_standalone: false,
last_replay_tick: None,
studio_virtual_tick_ms: 0.0,
lan: None,
integrated: None,
level_shapes: Default::default(),
@@ -12615,11 +12635,11 @@ pub fn run_with() -> Result<()> {
options.spikes = Some(dedicated::SLOW_TICK_MS);
}
tick_profile::want_spans(tick_profile::SPANS_SPIKES, options.spikes.is_some());
// A player who allows performance statistics also says what their slow frames spent their
// time in: this thread, which draws the frames, times its steps (wall time only).
// A hook that wants to know what slow frames spent their time in (a player who allows
// performance statistics): this thread, which draws the frames, times its steps (wall time
// only).
if options.execution_role.is_client()
&& horizon_telemetry::Consent::load(&horizon_client::logging::game_home())
.allows(horizon_telemetry::Kind::Perf)
&& horizon_hooks::engine::wants_frame_steps(&horizon_client::logging::game_home())
{
horizon_client::spans::record_here(true);
}
@@ -12644,7 +12664,7 @@ pub fn run_with() -> Result<()> {
// for a server, a benchmark, a run that quits by itself, a harness's fixture or a run that
// horizon-ctl drives: those start in a source checkout and wrote the list there.
if !options.offscreen && !synchronous_startup(&options) {
let version = horizon_client::telemetry::version();
let version = horizon_client::crash::build();
horizon_hooks::engine::started(&horizon_hooks::Started::new(&version));
// horizon-extras: the official server is Horizon's (docs/forking.md).
#[cfg(feature = "horizon-extras")]
@@ -42,25 +42,12 @@ impl Game<'_> {
self.trial_spawner_tick_positions.clear();
self.item_columns = Some(Default::default());
self.pass_mobs = Some(Default::default());
let tickers = self.world.block_entity_tickers();
let mut last_chunk = (i32::MIN, i32::MIN);
let mut last_chunk_ticking = false;
for slot in tickers.iter().copied() {
for slot in self.world.block_entity_tickers().iter().copied() {
let pos = slot.0;
let chunk = (pos.0 >> 4, pos.2 >> 4);
let chunk_ticking = if chunk == last_chunk {
last_chunk_ticking
} else {
last_chunk = chunk;
last_chunk_ticking = ticking(pos.0, pos.2);
last_chunk_ticking
};
if !chunk_ticking {
continue;
}
// Ticks before this one can remove it (`TickingBlockEntity.isRemoved`).
if self.world.block_entities.is_asleep(&pos)
|| !self.world.block_entities.is_live(slot)
|| !ticking(pos.0, pos.2)
|| !self.border.contains(f64::from(pos.0), f64::from(pos.2))
{
continue;
@@ -223,14 +210,8 @@ impl Game<'_> {
/// (`ServerLevel.areEntitiesLoaded`).
pub(super) fn block_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> {
let levels = self.tickets.levels();
let has_pending = !self.world.entities_pending.is_empty();
let pending = has_pending.then(|| self.world.entities_pending.clone());
move |x, z| {
levels.block_ticking_at(x, z)
&& pending
.as_ref()
.is_none_or(|p| !p.contains(&(x >> 4, z >> 4)))
}
let pending = self.world.entities_pending.clone();
move |x, z| levels.block_ticking_at(x, z) && !pending.contains(&(x >> 4, z >> 4))
}
/// `DaylightDetectorBlock.tickEntity` of the detector at `pos`.
fn tick_daylight_detector(&mut self, pos: Pos) {
+6 -3
View File
@@ -3831,9 +3831,12 @@ impl Game<'_> {
return;
}
g.spawn = None;
g.respawn_config = Some(super::respawn_anchor::RespawnConfig::forced(
level, pos, yaw, pitch,
));
g.respawn_config = Some(super::respawn_anchor::RespawnConfig {
dim: level,
pos,
yaw,
forced: true,
});
});
}
let dim = Text::literal(self.dim.id());
+2 -2
View File
@@ -644,7 +644,7 @@ impl Game<'_> {
.into());
}
if arg(2)? != "up" {
self.input_keyboard_used();
self.pad.keyboard_took_over = true;
}
// The command confirmation takes the keys; none go past it.
if self.command_prompt.is_some() {
@@ -800,7 +800,7 @@ impl Game<'_> {
// controller still holding one keeps it.
let options = [self.settings.toggle_crouch, self.settings.toggle_sprint];
for (slot, name) in [(0, "key.sneak"), (1, "key.sprint")] {
if !self.input_holds(name) {
if !self.pad.holds_action(&self.settings.controller, name) {
self.toggles.key(
slot,
horizon_client::keymapping::KeyAction::Release,
@@ -9,7 +9,7 @@ impl Game<'_> {
pub(super) fn mapped_key_down(&self, mapping: &str) -> bool {
keybinds::key_code(self.settings.keys.get(mapping))
.is_some_and(|k| self.physical_keys.contains(&k))
|| self.input_holds(mapping)
|| self.pad.holds_action(&self.settings.controller, mapping)
}
/// `CreativeModeInventoryScreen.selectTab` on the HOTBAR tab: each saved
+2 -2
View File
@@ -2317,7 +2317,7 @@ impl Game<'_> {
a.spawn_velocity = Some(p.velocity);
a.spawn_rot = Some((p.pitch, p.yaw));
}
self.creatures.projectiles.put_back(p);
self.creatures.projectiles.push(p);
self.native_projectile_launch(player, &name, id, kind);
}
/// `MushroomCow.shear`'s `sendParticles(EXPLOSION, x, getY(0.5), z, 1, 0, 0, 0, 0)`:
@@ -6949,7 +6949,7 @@ impl Game<'_> {
{
m.heal(25.0);
consume = true;
eat = Some(("entity.iron_golem.repair", 1.0, m.golem_repair_pitch()));
sound = Some("entity.iron_golem.repair");
}
Species::Creeper if creeper_igniter => {
m.extra.flag = true;
@@ -353,7 +353,7 @@ impl Game<'_> {
let found =
self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?;
used.push(match found {
Some((p, yaw, _pitch)) => format!(
Some((p, yaw)) => format!(
"respawn {} {} {} {}",
num(p.x),
num(p.y),
@@ -579,7 +579,6 @@ impl Game<'_> {
dim: self.dim,
pos: [p(0), p(1), p(2)],
yaw: 0.0,
pitch: 0.0,
forced: false,
});
}
+1 -2
View File
@@ -739,8 +739,7 @@ impl Game<'_> {
// anchor puts the player, facing it; else onto the spawn column.
let mut target = target;
if let Some(c) = self.respawn_config.filter(|c| c.dim == self.dim) {
// This existing owner transition adapter carries yaw only; its pitch path remains open.
if let Some((at, yaw, _pitch)) = self.find_respawn_and_use(c, false)? {
if let Some((at, yaw)) = self.find_respawn_and_use(c, false)? {
return Ok(Some((at, Some(yaw))));
}
target = fallback_spawn(self.spawn, self.level.world_spawn);
+1 -4
View File
@@ -1008,10 +1008,7 @@ impl Game<'_> {
p.position.z - center[2],
];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
self.input_feedback(horizon_client::input_source::Feedback::Explosion {
distance,
radius,
});
self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius });
}
// Explosion.explode: the blast is heard.
let ctx = horizon_client::sculk::Context::default();
@@ -70,10 +70,9 @@ fn overworld_spawnpoint_is_validated_at_both_player_blocks() {
assert_eq!(actual.is_some(), allowed, "{block} at height {height}");
assert_eq!(game.respawn_config.is_some(), allowed);
assert_eq!(game.level.world_spawn, Some([0, 80, 0]));
if let Some((at, yaw, pitch)) = actual {
if let Some((at, yaw)) = actual {
assert_eq!(at, Vec3::new(5.5, 64.1, 5.5));
assert_eq!(yaw, 0.0);
assert_eq!(pitch.to_bits(), 0.0f32.to_bits());
}
}
}
+2 -2
View File
@@ -135,8 +135,8 @@ impl Game<'_> {
}
/// `Camera.calculateFov` with `modifyFovBasedOnDeathOrFluid`.
pub(super) fn fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 {
if self.studio.freecam.active {
return self.studio.freecam.fov.clamp(1.0, 179.0);
if self.studio_freecam.active {
return self.studio_freecam.fov.clamp(1.0, 179.0);
}
let fov = self.view.calculate_fov(
partial,
@@ -193,7 +193,7 @@ impl Game<'_> {
// replay player's hands remain visible in first person; freecam has
// no player-view hand.
if !fov::studio_draws_hand(
self.studio.freecam.active,
self.studio_freecam.active,
self.ui.hands_drawn(
self.spectator(),
self.sleeping.is_some(),
@@ -4190,8 +4190,8 @@ impl Game<'_> {
.map_or([0.5, 80.0, 0.5], |[x, y, z]| {
[f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]
});
let at = found.map_or(world, |(at, yaw, pitch)| {
(host.hub.guests[i].yaw, host.hub.guests[i].pitch) = (yaw, pitch);
let at = found.map_or(world, |(at, yaw)| {
host.hub.guests[i].yaw = yaw;
[at.x, at.y, at.z]
});
if found.is_none() {
@@ -123,7 +123,7 @@ impl Loading {
};
horizon_client::window::settle_created_fullscreen(&window, fullscreen);
drop(window_step);
horizon_client::telemetry::note_display(&window);
horizon_client::play_session::note_display(&window);
// The renderer takes seconds to build and winit's window sits white
// until the first frame presents, so paint the boot screen on it and
// keep repainting it as the console's lines arrive; the wgpu frames
+72 -171
View File
@@ -118,78 +118,34 @@ impl View {
}
None
}
/// `WorldlyContainer.getSlotsForFace` or every slot, zero-allocation iterator.
pub(super) fn slots_for_face_iter(&self, face: Option<Direction>) -> Slots<'_> {
/// `WorldlyContainer.getSlotsForFace` or every slot.
fn slots_for_face(&self, face: Option<Direction>) -> Vec<usize> {
match (self.kind, face) {
(Kind::Furnace, Some(Direction::Down)) => Slots::Slice(&[2, 1]),
(Kind::Furnace, Some(Direction::Up)) => Slots::Slice(&[0]),
(Kind::Furnace, Some(_)) => Slots::Slice(&[1]),
(Kind::Brewing, Some(Direction::Up)) => Slots::Slice(&[3]),
(Kind::Brewing, Some(Direction::Down)) => Slots::Slice(&[0, 1, 2, 3]),
(Kind::Brewing, Some(_)) => Slots::Slice(&[0, 1, 2, 4]),
(Kind::Composter(8), Some(Direction::Down)) => Slots::Slice(&[0]),
(Kind::Composter(level), Some(Direction::Up)) if level < 7 => Slots::Slice(&[0]),
(Kind::Composter(_), _) => Slots::Slice(&[]),
(Kind::Furnace, Some(Direction::Down)) => vec![2, 1],
(Kind::Furnace, Some(Direction::Up)) => vec![0],
(Kind::Furnace, Some(_)) => vec![1],
(Kind::Brewing, Some(Direction::Up)) => vec![3],
(Kind::Brewing, Some(Direction::Down)) => vec![0, 1, 2, 3],
(Kind::Brewing, Some(_)) => vec![0, 1, 2, 4],
(Kind::Composter(8), Some(Direction::Down)) => vec![0],
(Kind::Composter(level), Some(Direction::Up)) if level < 7 => vec![0],
(Kind::Composter(_), _) => vec![],
(Kind::Mod, Some(face)) => self
.container
.as_ref()
.map_or(Slots::Slice(&[]), |c| Slots::Mod(&c.faces[face as usize])),
_ => Slots::Range(0..self.len()),
.map_or_else(Vec::new, |c| c.faces[face as usize].clone()),
_ => (0..self.len()).collect(),
}
}
/// The slots `HopperBlockEntity.addItem` tries through `face`, zero-allocation iterator.
pub(super) fn slots_to_add_iter(&self, face: Option<Direction>) -> Slots<'_> {
if matches!(self.kind, Kind::Furnace | Kind::Brewing | Kind::Mod) && face.is_some() {
self.slots_for_face_iter(face)
} else {
Slots::Range(0..self.len())
}
}
/// `WorldlyContainer.getSlotsForFace` or every slot.
fn slots_for_face(&self, face: Option<Direction>) -> Vec<usize> {
self.slots_for_face_iter(face).collect()
}
/// The slots `HopperBlockEntity.addItem` tries through `face`.
fn slots_to_add(&self, face: Option<Direction>) -> Vec<usize> {
self.slots_to_add_iter(face).collect()
}
}
pub(super) enum Slots<'a> {
Range(std::ops::Range<usize>),
Slice(&'static [usize]),
Mod(&'a [usize]),
}
impl Iterator for Slots<'_> {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
match self {
Slots::Range(r) => r.next(),
Slots::Slice(s) => {
let (&first, rest) = s.split_first()?;
*s = rest;
Some(first)
}
Slots::Mod(s) => {
let (&first, rest) = s.split_first()?;
*s = rest;
Some(first)
}
if matches!(self.kind, Kind::Furnace | Kind::Brewing | Kind::Mod) && face.is_some() {
self.slots_for_face(face)
} else {
(0..self.len()).collect()
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = match self {
Slots::Range(r) => r.len(),
Slots::Slice(s) => s.len(),
Slots::Mod(s) => s.len(),
};
(len, Some(len))
}
}
impl ExactSizeIterator for Slots<'_> {}
pub(super) fn dir_from_name(name: &str) -> Option<Direction> {
Some(match name {
@@ -224,6 +180,8 @@ struct Containers<'a> {
registry: &'static horizon_world::registry::BlockRegistry,
/// Brewing recipes, for what a brewing stand accepts (not needed for signals).
brewing: Option<&'a horizon_client::brewing::Brewing>,
/// The stack of a full composter's `OutputContainer`.
bone_meal: ItemStack,
}
impl Containers<'_> {
fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> {
@@ -388,7 +346,7 @@ impl Containers<'_> {
fn get(&self, view: &View, slot: usize) -> Option<&ItemStack> {
if let Kind::Composter(level) = view.kind {
// OutputContainer holds one bone meal; InputContainer composts at once.
return (level == 8 && slot == 0).then_some(bone_meal_stack());
return (level == 8 && slot == 0).then_some(&self.bone_meal);
}
let (pos, i) = view.locate(slot)?;
self.world
@@ -494,7 +452,7 @@ impl Containers<'_> {
}
/// `HopperBlockEntity.isFullContainer`.
fn is_full(&self, view: &View, face: Direction) -> bool {
view.slots_for_face_iter(Some(face)).all(|i| {
view.slots_for_face(Some(face)).into_iter().all(|i| {
self.insertion_item(view, i)
.is_some_and(|s| s.count >= self.max_stack(&s))
})
@@ -540,9 +498,6 @@ impl ItemColumns {
x: i32,
z: i32,
) -> bool {
if items.is_empty() {
return false;
}
let (len, last) = (items.len(), items.last().map(|i| i.id));
let stale = self
.seen
@@ -601,14 +556,13 @@ impl StampedItemColumns {
}
}
fn bone_meal_stack() -> &'static ItemStack {
static STACK: std::sync::LazyLock<ItemStack> = std::sync::LazyLock::new(|| ItemStack {
fn bone_meal() -> ItemStack {
ItemStack {
item: "minecraft:bone_meal".into(),
count: 1,
damage: 0,
extra: None,
});
&STACK
}
}
/// Comparator input from a container block entity (0 when there is none).
@@ -625,6 +579,7 @@ pub(super) fn container_signal(
items,
registry,
brewing: None,
bone_meal: bone_meal(),
};
c.view((pos.x, pos.y, pos.z), true)
.filter(|v| !matches!(v.kind, Kind::Composter(_)))
@@ -680,6 +635,7 @@ impl Game<'_> {
items: self.items(),
registry: self.pack.assets.registry,
brewing: Some(&self.stations().brewing),
bone_meal: bone_meal(),
}
}
pub(super) fn block_can_place(&self, pos: [i32; 3], slot: usize, stack: &ItemStack) -> bool {
@@ -891,7 +847,7 @@ impl Game<'_> {
return self.composter_container_insert([x, y, z], stack, face == Some(Direction::Up));
}
let mut rest = Some(stack);
for slot in view.slots_to_add_iter(face) {
for slot in view.slots_to_add(face) {
let Some(stack) = rest.take() else { break };
rest = self.try_move_in_item(from_hopper, view, stack, slot, face);
}
@@ -924,31 +880,32 @@ impl Game<'_> {
/// is still a hopper (`BlockEntityType.isValid`).
pub(super) fn tick_hopper(&mut self, pos: Pos) {
let time = self.world.game_time;
// Every hopper keeps its cooldown and the tick it last ticked
// (`HopperBlockEntity.tickedGameTime`), idle ones too: a hopper that
// receives an item reads it for its cooldown (8, or 7 once it ticked).
let state = self.hoppers.entry(pos).or_default();
state.cooldown = state.cooldown.wrapping_sub(1);
state.ticked = time;
if state.cooldown > 0 {
let waiting = {
let state = self.hoppers.entry(pos).or_default();
state.cooldown = state.cooldown.wrapping_sub(1);
state.ticked = time;
state.cooldown > 0
};
if waiting {
return;
}
state.cooldown = 0;
// Most ticks only advance the cooldown: the block is checked when the
// hopper is about to move, not on every tick it waits.
let state = self.world.block(pos.0, pos.1, pos.2);
let Some(info) = self.pack.assets.registry.state(state) else {
self.hoppers.remove(&pos);
return;
};
if info.name != "minecraft:hopper" {
let hopper = self
.res
.facts()
.get(self.world.block(pos.0, pos.1, pos.2))
.name
.as_ref()
== "minecraft:hopper";
if !hopper {
self.hoppers.remove(&pos);
return;
}
if info.properties.get("enabled").is_some_and(|v| v == "false") {
return;
if let Some(state) = self.hoppers.get_mut(&pos) {
state.cooldown = 0;
}
self.hopper_try_move_items_with_state(pos, state);
self.hopper_try_move_items(pos);
}
/// Drops the cooldowns of hoppers whose block entity is gone.
pub(super) fn forget_gone_hoppers(&mut self) {
@@ -960,69 +917,23 @@ impl Game<'_> {
/// `HopperBlockEntity.tryMoveItems` with `suckInItems`.
pub(super) fn hopper_try_move_items(&mut self, pos: Pos) {
let state = self.world.block(pos.0, pos.1, pos.2);
self.hopper_try_move_items_with_state(pos, state);
}
fn hopper_try_move_items_with_state(&mut self, pos: Pos, state: BlockStateId) {
let Some(info) = self.pack.assets.registry.state(state) else {
let c = self.containers();
let enabled = c.prop(state, "enabled") != Some("false");
let Some(view) = c.view(pos, false) else {
return;
};
if info.properties.get("enabled").is_some_and(|v| v == "false") {
if self.hoppers.get(&pos).is_some_and(|h| h.cooldown > 0) || !enabled {
return;
}
if self.hoppers.get(&pos).is_some_and(|h| h.cooldown > 0) {
return;
}
let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&pos) else {
return;
};
if items.len() != HOPPER_SLOTS {
return;
}
let is_empty = items
.iter()
.all(|s| s.as_ref().is_none_or(|s| s.count == 0));
let has_empty_slot = items
.iter()
.any(|s| s.as_ref().is_none_or(|s| s.count == 0));
let above = (pos.0, pos.1 + 1, pos.2);
// Fast path for empty hopper with no source container and no item entities:
// if empty, cannot eject; if no container above, cannot suck container;
// if no dropped items nearby, cannot suck entities -> nothing can happen!
if is_empty
&& self.world.block_entities.get(&above).is_none()
&& self.carts.is_empty()
&& self.boats.is_empty()
&& (self.dropped.is_empty()
|| self
.item_columns
.as_mut()
.is_some_and(|c| !c.may_reach(&self.dropped, pos.0, pos.2)))
&& self
.pack
.assets
.registry
.state(self.world.block(above.0, above.1, above.2))
.is_none_or(|s| s.name != "minecraft:composter")
{
return;
}
self.native_prepare_hopper_transfer([pos.0, pos.1, pos.2]);
let view = View {
parts: vec![(pos, HOPPER_SLOTS)],
kind: Kind::Hopper,
container: None,
};
let mut changed = false;
if !is_empty {
changed = self.hopper_eject_with_state(pos, state, &view);
if !c.is_empty(&view) {
changed = self.hopper_eject(pos, &view);
}
let is_full = !changed && !has_empty_slot && {
let c = self.containers();
(0..HOPPER_SLOTS).all(|i| c.get(&view, i).is_some_and(|s| s.count >= c.max_stack(s)))
};
if !is_full {
let c = self.containers();
let full =
(0..view.len()).all(|i| c.get(&view, i).is_some_and(|s| s.count == c.max_stack(s)));
if !full {
changed |= self.hopper_suck(pos, &view);
}
if changed {
@@ -1084,20 +995,19 @@ impl Game<'_> {
/// `tryMoveItems(…, () -> addItem(hopper, itemEntity))`; true when the
/// item entity was taken whole.
fn hopper_take_item(&mut self, pos: Pos, i: usize) -> bool {
if self.hoppers.get(&pos).is_some_and(|h| h.cooldown > 0) {
return false;
}
let state = self.world.block(pos.0, pos.1, pos.2);
let c = self.containers();
if c.prop(state, "enabled") == Some("false") {
return false;
}
let Some(view) = c.view(pos, false) else {
return false;
};
if c.prop(state, "enabled") == Some("false")
|| self.hoppers.get(&pos).is_some_and(|h| h.cooldown > 0)
{
return false;
}
let mut changed = false;
if !c.is_empty(&view) {
changed = self.hopper_eject_with_state(pos, state, &view);
changed = self.hopper_eject(pos, &view);
}
let c = self.containers();
let full =
@@ -1133,7 +1043,8 @@ impl Game<'_> {
}
/// `HopperBlockEntity.ejectItems`: into the block container in front, else
/// a container entity there (`getContainerAt`).
fn hopper_eject_with_state(&mut self, pos: Pos, state: BlockStateId, hopper: &View) -> bool {
fn hopper_eject(&mut self, pos: Pos, hopper: &View) -> bool {
let state = self.world.block(pos.0, pos.1, pos.2);
let c = self.containers();
let Some(facing) = c.prop(state, "facing").and_then(dir_from_name) else {
return false;
@@ -1245,9 +1156,6 @@ impl Game<'_> {
if blocked {
return false;
}
if self.dropped.is_empty() {
return false;
}
// Hopper.SUCK_AABB: the hopper bowl and the block above.
let (min, max) = (
[
@@ -1306,7 +1214,7 @@ impl Game<'_> {
// second setChanged after the move or, when the hopper has no
// room, the setItem putting the bone meal back into the detached
// container (whose bone meal is lost with it).
let bone_meal = bone_meal_stack().clone();
let bone_meal = c.bone_meal.clone();
if !horizon_client::mod_api::mods().is_empty() {
let mut cancel = false;
self.native_inventory_move_item(
@@ -1336,15 +1244,13 @@ impl Game<'_> {
source: &View,
hopper: &View,
) -> bool {
for slot in source.slots_for_face_iter(Some(Direction::Down)) {
{
let c = self.containers();
let Some(stack) = c.get(source, slot) else {
continue;
};
if !c.can_take(source, slot, stack, Direction::Down) {
continue;
}
for slot in source.slots_for_face(Some(Direction::Down)) {
let c = self.containers();
let Some(stack) = c.get(source, slot) else {
continue;
};
if !c.can_take(source, slot, stack, Direction::Down) {
continue;
}
if self.hopper_move_canceled(source, slot, source, hopper) {
continue;
@@ -1363,9 +1269,7 @@ impl Game<'_> {
}
return true;
}
Some(rest) => {
self.put_back(source, slot, rest);
}
Some(rest) => self.put_back(source, slot, rest),
}
}
false
@@ -1375,9 +1279,6 @@ impl Game<'_> {
/// minecarts, chest boats) whose box meets the 1x1x1 box around `at`,
/// picked at random.
fn entity_container_at(&mut self, at: [f64; 3]) -> Option<u32> {
if self.carts.is_empty() && self.boats.is_empty() {
return None;
}
let meets = |b: horizon_core::geometry::Aabb| {
let (lo, hi) = (b.min_position(), b.max_position());
lo.x < at[0] + 0.5
+24 -27
View File
@@ -61,49 +61,46 @@ impl Game<'_> {
/// that are gone, and read what the instances follow.
pub(super) fn start_mob_sounds(&mut self) -> Vec<MobSound> {
let game_time = self.world.game_time;
let mut mobs = Vec::new();
let mut bee_indices = Vec::new();
for m in &self.mobs {
if m.removed {
continue;
}
let species = m.species();
if !matches!(
species,
Species::Bee | Species::Guardian | Species::ElderGuardian | Species::Sniffer
) {
continue;
}
let is_bee = species == Species::Bee;
let sound = MobSound {
let mobs: Vec<MobSound> = self
.mobs
.iter()
.filter(|m| {
!m.removed
&& matches!(
m.species(),
Species::Bee
| Species::Guardian
| Species::ElderGuardian
| Species::Sniffer
)
})
.map(|m| MobSound {
id: m.id,
position: [m.position.x, m.position.y, m.position.z],
// Vec3.horizontalDistance.
speed: m.velocity.x.hypot(m.velocity.z),
baby: m.is_baby(),
// NeutralMob.isAngry: the anger end time is ahead.
angry: is_bee
angry: m.species() == Species::Bee
&& bee::get(m).is_some_and(|b| b.anger_end > 0 && b.anger_end - game_time > 0),
silent: m.silent,
attack_scale: guardian::attack_scale(m),
// SnifferSoundInstance.tick.
sniffer_digging: species == Species::Sniffer
sniffer_digging: m.species() == Species::Sniffer
&& m.ai.target.is_none()
&& sniffer::can_play_digging_sound(m),
};
if is_bee {
bee_indices.push(mobs.len());
}
mobs.push(sound);
}
})
.collect();
self.guardian_sounds
.retain(|id| mobs.iter().any(|m| m.id == *id));
self.bee_sounds
.retain(|id, _| mobs.iter().any(|m| m.id == *id));
for &idx in &bee_indices {
let sound = &mobs[idx];
if self.bee_sounds.get(&sound.id) != Some(&sound.angry) {
for sound in &mobs {
let is_bee = self
.mobs
.iter()
.any(|m| m.id == sound.id && m.species() == Species::Bee);
if is_bee && self.bee_sounds.get(&sound.id) != Some(&sound.angry) {
self.bee_sounds.insert(sound.id, sound.angry);
let instance = SoundInstance::bee(sound, sound.angry, random_source::create());
self.audio.play_instance(instance, false);
@@ -471,7 +471,6 @@ pub(crate) mod tests {
dim: game.dim,
pos: [1, 2, 3],
yaw: 0.0,
pitch: 0.0,
forced: false,
};
let spawn = Vec3::new(1.0, 2.0, 3.0);
@@ -46,8 +46,6 @@ pub(super) struct SpawnScratch {
/// dx/dz order, that no earlier player's square holds.
segments: Vec<Vec<(i32, i32)>>,
stale: Vec<bool>,
/// Reusable buffer for spawn players across ticks to avoid heap allocation.
pub(super) spawn_players: Vec<SpawnPlayer>,
}
impl SpawnScratch {
fn chunk(p: &LevelPlayer) -> (i32, i32) {
@@ -130,20 +128,6 @@ impl SpawnScratch {
self.prepare(players);
self.candidates.clear();
let mut count = 0;
if players.len() == 1 {
let p = &players[0];
count = self.segments.first().map_or(0, |s| s.len());
if !p.spectator
&& let Some(segment) = self.segments.first()
{
for &c in segment {
if close_enough_for_spawning(p, c) && keep(c) {
self.candidates.push(c);
}
}
}
return count as i32;
}
for (i, segment) in self.segments.iter().enumerate() {
count += segment.len();
let near = &self.neighbours[i];
@@ -666,10 +650,8 @@ fn spawn_cost_types(biomes: &horizon_client::biome::Biomes) -> Vec<&str> {
types
}
impl<'a> Game<'a> {
pub(super) fn natural_level_with_players(
&self,
players: Vec<LevelPlayer>,
) -> GameLevel<'_, 'a> {
pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> {
let players = self.level_players();
let nearest = players
.iter()
.filter(|p| !p.spectator)
@@ -688,9 +670,6 @@ impl<'a> Game<'a> {
costed: spawn_cost_types(world_biomes!(self)),
}
}
pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> {
self.natural_level_with_players(self.level_players())
}
/// Creates a mob the spawner accepted, finalized the game's way; the
/// caller adds it with [`Game::add_spawned`].
fn finalize_spawned(&self, r: &SpawnRequest, pending: &mut Vec<Mob>) -> Option<Spawned> {
@@ -794,8 +773,6 @@ impl<'a> Game<'a> {
scratch: &mut SpawnScratch,
) -> i32 {
let levels = self.tickets.levels();
// Recomputed each pass: a chunk's ticket level and entity loading change without the
// players moving or the chunk count changing.
scratch.collect(players, |(cx, cz)| {
levels.loaded_ticking(cx, cz) && super::ticking_chunk(&self.world, cx, cz)
})
@@ -842,28 +819,31 @@ impl<'a> Game<'a> {
{
let level = self.natural_level();
laps.lap("sn_level");
let counted = self.mobs.iter().map(|m| Counted {
entity: &m.kind.id,
category: Category::from_name(&m.kind.category),
block: [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
],
is_mob: true,
persistent: m.persistent
|| horizon_client::mobs::ai::requires_custom_persistence(m),
});
scratch.spawn_players.clear();
scratch
.spawn_players
.extend(players.iter().map(|p| SpawnPlayer {
let counted: Vec<Counted> = self
.mobs
.iter()
.map(|m| Counted {
entity: &m.kind.id,
category: Category::from_name(&m.kind.category),
block: [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
],
is_mob: true,
persistent: m.persistent
|| horizon_client::mobs::ai::requires_custom_persistence(m),
})
.collect();
let players = players
.iter()
.map(|p| SpawnPlayer {
position: [p.position.x, p.position.y, p.position.z],
spectator: p.spectator,
}));
let spawn_players = std::mem::take(&mut scratch.spawn_players);
})
.collect();
laps.lap("sn_materialize");
let mut state = SpawnState::new(&level, spawnable, spawn_players, counted, |cx, cz| {
let mut state = SpawnState::new(&level, spawnable, players, &counted, |cx, cz| {
self.world.chunks.contains_key(&(cx, cz))
});
laps.lap("sn_state");
@@ -874,8 +854,7 @@ impl<'a> Game<'a> {
Vec::new()
};
laps.lap("sn_categories");
// Util.shuffle, every pass: it draws from the level's random even when no
// category may spawn.
// Util.shuffle.
for i in (1..scratch.candidates.len()).rev() {
let j = random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize;
scratch.candidates.swap(i, j);
@@ -906,7 +885,6 @@ impl<'a> Game<'a> {
);
}
}
scratch.spawn_players = state.into_players();
}
spawn_selection::attempt_counters(true);
laps.lap("sn_attempts");
+1 -1
View File
@@ -185,7 +185,7 @@ impl Game<'_> {
let output = self
.renderer
.as_ref()
.map_or(Default::default(), |r| r.output());
.map_or(Default::default(), |r| *r.output());
ui.draw(&self.settings, output, batch, &self.gui.atlas, self.cursor);
self.ui.options = ui;
self.show_calibration((batch.width, batch.height));
+20
View File
@@ -679,6 +679,26 @@ impl Game<'_> {
gamepad::move_vector(self.pad.state.left, settings.move_deadzone)
}
/// Whether `key` is held, a movement key by the left stick too: as the keys the stick holds
/// (`eight_direction_keys`), whatever moves the player. For readers of the keys that aren't
/// the movement itself.
pub(super) fn movement_key_held(&self, key: KeyCode) -> bool {
if self.keys.raw(&key) {
return true;
}
let Some(stick) = self.pad_move() else {
return false;
};
let [forward, backward, left, right] = gamepad::eight_direction_keys(stick);
match key {
KeyCode::KeyW => forward,
KeyCode::KeyS => backward,
KeyCode::KeyA => left,
KeyCode::KeyD => right,
_ => false,
}
}
/// The right stick turns the view, once per frame (`Entity.turn`).
pub(super) fn pad_look(&mut self, seconds: f32) {
let settings = &self.settings.controller;
@@ -280,11 +280,11 @@ impl Game<'_> {
/// front of) it, pulled in where visual shapes are in the way. Returns the
/// position, yaw and pitch to render from.
pub(super) fn camera_view(&mut self, partial: f32) -> Option<(glam::DVec3, f32, f32)> {
if self.studio.freecam.active {
if self.studio_freecam.active {
return Some((
self.studio.freecam.position,
self.studio.freecam.yaw,
self.studio.freecam.pitch,
self.studio_freecam.position,
self.studio_freecam.yaw,
self.studio_freecam.pitch,
));
}
// Minecraft.cameraEntity: a server's spectator camera on a mob or
@@ -643,9 +643,8 @@ impl Game<'_> {
/// The model's old pitch is the player's `xRotO`, which the turn moves
/// with `xRot` (`turn_rotation`).
pub(super) fn turn_player(&mut self, xo: f64, yo: f64) {
if self.studio.freecam.active {
self.studio
.freecam
if self.studio_freecam.active {
self.studio_freecam
.turn((xo * 0.15) as f32, (yo * 0.15) as f32);
return;
}
@@ -698,7 +697,7 @@ impl Game<'_> {
/// `LevelExtractor`'s skip of the camera entity: the player's own body
/// is drawn unless the camera is in first person, or while it sleeps.
pub(super) fn own_body_in_view(&self) -> bool {
!self.camera_type.first_person() || self.sleeping.is_some() || self.studio.freecam.active
!self.camera_type.first_person() || self.sleeping.is_some() || self.studio_freecam.active
}
/// Whether the player's own model shows in the world view (its body or,
/// while invisible, only its armour and held items).
+6 -77
View File
@@ -101,7 +101,7 @@ impl Game<'_> {
};
// A controller's stick click acts as the key without setting the modifier: it is held
// while the pad holds it (or its release waits for a tick), not when the keyboard says.
let pad = self.input_holds(mapping);
let pad = self.pad.holds_action(&self.settings.controller, mapping);
if !held && !pad {
self.toggles.0[slot].set_down(false, needs_toggle);
self.sync_toggle(slot);
@@ -180,7 +180,7 @@ impl Game<'_> {
raw: KeyCode,
source: Source,
) -> Result<()> {
if self.screen == Screen::Playing && self.studio.replay.is_some() {
if self.screen == Screen::Playing && self.studio_replay.is_some() {
if !pressed {
self.keys.release(&key, source);
return Ok(());
@@ -191,7 +191,7 @@ impl Game<'_> {
}
return Ok(());
}
if !studio_freecam_movement_key(key) || !self.studio.freecam.active {
if !studio_freecam_movement_key(key) || !self.studio_freecam.active {
return Ok(());
}
}
@@ -352,7 +352,9 @@ impl Game<'_> {
_ => return false,
};
match source {
Source::Keyboard | Source::Agent => self.input_holds(mapping),
Source::Keyboard | Source::Agent => {
self.pad.holds_action(&self.settings.controller, mapping)
}
Source::Pad => {
let keys = &self.settings.keys;
self.physical_buttons
@@ -448,79 +450,6 @@ impl Game<'_> {
}
}
/// The input source (docs/layers.md, "Controllers, splitscreen, replays and UI pages"): what
/// gameplay asks of a device beyond the keyboard and mouse, and tells it. Gameplay calls these,
/// never the controller modules; today `pad` answers.
impl Game<'_> {
/// The analog move vector (`[left, forward]`, -1..1) while a device moves the player.
pub(super) fn input_move(&self) -> Option<[f32; 2]> {
self.pad_move()
}
/// Whether a device holds the key mapping named `mapping` (`key.use`).
pub(super) fn input_holds(&self, mapping: &str) -> bool {
self.pad.holds_action(&self.settings.controller, mapping)
}
/// Turns the view by what the devices give this frame (`Entity.turn`).
pub(super) fn input_look(&mut self, seconds: f32) {
self.pad_look(seconds);
}
/// The keyboard or mouse acted in play (a key or button pressed): it has control again, though
/// only moving the mouse takes a pad out of use.
pub(super) fn input_keyboard_used(&mut self) {
self.pad.keyboard_took_over = true;
}
/// Whether the pointer event being handled is one a device made (a pad's menu cursor
/// clicking), not the mouse's.
pub(super) fn input_made_pointer_event(&self) -> bool {
self.pad.menu.synthetic
}
/// A new player entity took over (spawn, respawn, a server joined, a dimension change).
pub(super) fn input_player_replaced(&mut self) {
self.pad.player_replaced();
}
/// Whether the drop about to happen is a device's whole-stack drop (it has no Control key to
/// hold). Asking answers once.
pub(super) fn input_takes_stack_drop(&mut self) -> bool {
std::mem::take(&mut self.pad.drop_stack)
}
/// The HUD starts a frame: what a device drew on the last one is gone.
pub(super) fn input_hud_begin(&mut self) {
self.pad.guide_shown.clear();
}
/// Something happened to the player that a device may let them feel.
pub(super) fn input_feedback(&mut self, event: horizon_client::input_source::Feedback) {
self.pad_rumble(event.into());
}
/// Whether `key` is held, a movement key by the analog move vector too: as the keys it holds
/// (`eight_direction_keys`), whatever moves the player. For readers of the keys that aren't
/// the movement itself.
pub(super) fn movement_key_held(&self, key: KeyCode) -> bool {
if self.keys.raw(&key) {
return true;
}
let Some(stick) = self.input_move() else {
return false;
};
let [forward, backward, left, right] = horizon_client::gamepad::eight_direction_keys(stick);
match key {
KeyCode::KeyW => forward,
KeyCode::KeyS => backward,
KeyCode::KeyA => left,
KeyCode::KeyD => right,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::{studio_freecam_movement_key, studio_replay_shortcut};
+8 -7
View File
@@ -10,7 +10,7 @@ impl Game<'_> {
/// the container's hotbar keys are now (`checkHotbarKeyPressed`).
pub(super) fn key_pressed(&mut self, key: KeyCode, raw: KeyCode) -> Result<()> {
self.direct_craft_stop();
if self.screen == Screen::Playing && self.studio.replay.is_some() {
if self.screen == Screen::Playing && self.studio_replay.is_some() {
match key {
KeyCode::Escape => {
self.close_studio_replay();
@@ -25,19 +25,19 @@ impl Game<'_> {
KeyCode::KeyF => self.handle_studio_timeline_action(
horizon_client::studio::TimelineAction::ToggleFreecam,
),
KeyCode::KeyT => self.studio.timeline.visible = !self.studio.timeline.visible,
KeyCode::KeyT => self.studio_timeline.visible = !self.studio_timeline.visible,
KeyCode::KeyM => self.add_studio_marker(),
KeyCode::Home => self.handle_studio_topbar_action(
horizon_client::studio::TopBarAction::ResetCameraToPlayer,
),
KeyCode::KeyL => {
self.studio.freecam.locked_to_path = !self.studio.freecam.locked_to_path;
self.studio_freecam.locked_to_path = !self.studio_freecam.locked_to_path;
}
KeyCode::KeyK => self.handle_studio_timeline_action(
horizon_client::studio::TimelineAction::AddCameraKeyframe,
),
KeyCode::Delete => {
if let Some(index) = self.studio.timeline.selected_keyframe {
if let Some(index) = self.studio_timeline.selected_keyframe {
self.handle_studio_timeline_action(
horizon_client::studio::TimelineAction::RemoveCameraKeyframe(index),
);
@@ -78,7 +78,7 @@ impl Game<'_> {
KeyCode::Escape => match self.screen {
Screen::Options => self.options_key(KeyCode::Escape, None)?,
Screen::Playing => {
if self.studio.replay.is_some() && self.captured {
if self.studio_replay.is_some() && self.captured {
self.capture(false);
return Ok(());
}
@@ -213,7 +213,7 @@ impl Game<'_> {
// key.toggleGui is a KeyMapping: it clicks only with no screen open.
KeyCode::F1 if self.screen == Screen::Playing => self.toggle_hide_gui(),
KeyCode::F11 => self.toggle_fullscreen(),
KeyCode::F5 if self.screen == Screen::Playing && self.studio.replay.is_none() => {
KeyCode::F5 if self.screen == Screen::Playing && self.studio_replay.is_none() => {
self.cycle_camera()
}
KeyCode::KeyE
@@ -279,7 +279,8 @@ impl Game<'_> {
KeyCode::KeyQ if self.screen == Screen::Playing => {
// handleKeybinds: the number keys select before key.drop.
self.select_queued_hotbar();
let all = drop_whole_stack(self.modifiers) || self.input_takes_stack_drop();
let all =
drop_whole_stack(self.modifiers) || std::mem::take(&mut self.pad.drop_stack);
self.drop_held(all);
}
KeyCode::Digit1
@@ -111,7 +111,7 @@ impl Game<'_> {
self.stop_sounds_for_new_level();
}
self.player = Some(player);
self.input_player_replaced();
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
self.eye = 1.62;
@@ -26,7 +26,7 @@ impl Game<'_> {
let pointer = self.captured || self.agent_pointer;
let grabbed = pointer
&& self.screen == Screen::Playing
&& (self.player.is_some() || self.studio.freecam.active);
&& (self.player.is_some() || self.studio_freecam.active);
let active = self.focused || self.agent_pointer;
if let Some((xo, yo)) = self
.mouse
@@ -76,8 +76,8 @@ impl Game<'_> {
&& self.control.is_none()
&& self.screen == Screen::Playing
&& !studio_suppresses_focus_pause(
self.studio.replay.is_some(),
self.studio.freecam.active,
self.studio_replay.is_some(),
self.studio_freecam.active,
)
&& self.player.is_some()
&& !self.options.no_pause
@@ -149,7 +149,7 @@ impl Game<'_> {
self.reset_inventory_clicks();
if !capture {
self.stop_mining();
self.studio.rmb_down = false;
self.studio_rmb_down = false;
}
// The real pointer takes over from an agent's.
self.agent_pointer = false;
@@ -353,9 +353,9 @@ impl Game<'_> {
/// click. A screen that is open keeps it free, as releasing the pointer
/// for that screen did: it is the screen, not the focus, that shows it.
pub(super) fn regrab_on_refocus(&mut self) {
if self.studio.replay.is_some() || self.studio.freecam.active {
if self.studio_replay.is_some() || self.studio_freecam.active {
self.regrab_on_refocus = false;
self.studio.rmb_down = false;
self.studio_rmb_down = false;
self.capture(false);
return;
}
+38 -14
View File
@@ -2433,7 +2433,7 @@ impl Game<'_> {
/// view centre, `calculateStorageRange` (the server's radius, at least
/// two, plus three) chunks each way.
pub(super) fn remote_chunk_in_range(&self, x: i32, z: i32) -> bool {
if self.studio.replay.is_some() {
if self.studio_replay.is_some() {
return true;
}
self.remote
@@ -3110,6 +3110,33 @@ impl Game<'_> {
index.get(mobs, id as u32).map(mob_tracking_body)
});
}
fn remove_entity(&mut self, id: i32) {
self.detach_remote_tracking_entity(id);
self.audio.remove_sound_entity(id as u32);
// Entity.setRemoved detaches every passenger, even when no empty
// SetPassengers packet preceded the vehicle's removal. Otherwise
// mobs and other players keep their passenger pose after it is gone.
self.remote_set_passengers(id, &[]);
self.mobs.retain(|m| m.id != id as u32);
self.orbs.retain(|o| o.id != id as u32);
self.dropped.retain(|d| d.id != id as u32);
// Before the crystals go: the dragon's beam index follows them.
self.remove_remote_dragon(id);
self.remove_remote_object(id as u32);
self.remove_remote_projectile(id as u32);
self.persist.uuids.remove(&(id as u32));
if let Some(r) = self.remote.as_mut() {
r.glowing.remove(&id);
r.entities.remove(&id);
r.passenger_vehicles.remove(&(id as u32));
r.passenger_vehicles.retain(|_, v| *v != id as u32);
r.lerps.remove(&id);
r.cart_lerps.remove(&id);
r.stepped.remove(&id);
r.head_lerps.remove(&id);
r.pending_items.remove(&id);
}
}
/// Map a menu slot to Horizon's inventory screen slot ids.
pub(super) fn menu_slot(menu: &str, slot: i32) -> Option<usize> {
let s = usize::try_from(slot).ok()?;
@@ -3680,7 +3707,7 @@ impl Game<'_> {
self.move_remote_interaction(p.id, p.position);
}
C::RemoveEntities(p) => {
for &id in &p.ids {
for id in p.ids {
if let Some(r) = self.remote.as_mut() {
if let Some(uuid) = r.level_players.remove(&id) {
r.attachments.remove(&Holder::Player(uuid));
@@ -3689,8 +3716,8 @@ impl Game<'_> {
r.level_player_textures.remove(&id);
r.attachments.remove(&Holder::Entity(id as u32));
}
self.remove_entity(id);
}
self.remove_entities(&p.ids);
}
C::MoveEntityPos(play::MoveEntityPos(m))
| C::MoveEntityPosRot(play::MoveEntityPosRot(m))
@@ -6149,7 +6176,7 @@ impl Game<'_> {
player.spectator = self.spectator();
player.velocity = delta;
self.player = Some(player);
self.input_player_replaced();
self.pad.player_replaced();
self.sway = Default::default();
self.eye = 1.62;
self.previous_eye = 1.62;
@@ -6158,7 +6185,7 @@ impl Game<'_> {
self.apply_remote_abilities();
}
}
if self.studio.replay.is_none() {
if self.studio_replay.is_none() {
self.previous_position = position;
}
self.yaw = yaw;
@@ -6414,7 +6441,7 @@ impl Game<'_> {
}
return Ok(());
}
let stick = self.input_move();
let stick = self.pad_move();
if self.player.is_none() {
return Ok(());
}
@@ -6494,7 +6521,7 @@ impl Game<'_> {
return Ok(());
};
player.fluids.boat = boat;
if !riding && self.studio.replay.is_none() {
if !riding && self.studio_replay.is_none() {
self.previous_position = player.position;
}
let before = (
@@ -6701,7 +6728,7 @@ impl Game<'_> {
self.snap_player_model_pitch();
}
// The player's own model (third person, the inventory's preview).
if self.studio.replay.is_none() {
if self.studio_replay.is_none() {
self.tick_player_model();
}
self.tick_emotes();
@@ -9498,7 +9525,7 @@ impl Game<'_> {
KeyCode::KeyQ if !self.spectator() => {
// Minecraft.hasControlDown: the physical keys, so a toggled
// sprint on Left Control does not make Q drop the stack.
let all = self.has_control_down() || self.input_takes_stack_drop();
let all = self.has_control_down() || std::mem::take(&mut self.pad.drop_stack);
self.remote_drop(all);
}
KeyCode::KeyE
@@ -10501,7 +10528,7 @@ impl Game<'_> {
/// A connection's screen is over the world: connecting, reconfiguring, or
/// the level loading screen, a portal's included (`remote_overlay`).
pub(super) fn remote_screen_up(&self) -> bool {
self.studio.replay.is_none()
self.studio_replay.is_none()
&& self
.remote
.as_ref()
@@ -10585,7 +10612,7 @@ impl Game<'_> {
/// Connected or connecting with no player yet: `ConnectScreen`, then
/// `LevelLoadingScreen`, over the panorama with its blur.
pub(super) fn remote_loading(&self) -> bool {
if self.studio.replay.is_some() {
if self.studio_replay.is_some() {
return false;
}
use horizon_client::level_loading::Reason;
@@ -11615,9 +11642,6 @@ fn in_storage_range(view_distance: i32, center: (i32, i32), x: i32, z: i32) -> b
x.abs_diff(center.0) <= range && z.abs_diff(center.1) <= range
}
// A packet's removals (`RemoveEntities`), apart: this file may not grow.
#[path = "remote_removal.rs"]
mod removal;
#[cfg(test)]
mod tests {
#[test]
@@ -793,17 +793,13 @@ impl Game<'_> {
}
pub(super) fn remove_remote_projectile(&mut self, id: u32) {
self.fangs.list.retain(|f| f.id != id);
self.tnts.retain(|t| t.id != id);
self.falling.retain(|f| f.id != id);
self.crystals.retain(|c| c.id != id);
self.remove_remote_small_projectiles(id);
}
pub(super) fn remove_remote_small_projectiles(&mut self, id: u32) {
self.fangs.list.retain(|f| f.id != id);
self.creatures.projectiles.retain(|p| p.id != id);
self.tridents.retain(|t| t.id != id);
self.rockets.retain(|r| r.id != id);
self.crystals.retain(|c| c.id != id);
self.potions.remove_remote_thrown(id);
self.potions.clouds.retain(|c| c.id != id);
self.end.remove_remote_eye(id);
@@ -1,142 +0,0 @@
//! Removing entities a server dropped (`RemoveEntities`), out of remote.rs,
//! which may not grow.
use super::super::Game;
impl Game<'_> {
pub(super) fn remove_entity(&mut self, id: i32) {
self.remove_entities(&[id]);
}
/// `ClientboundRemoveEntitiesPacket`: a packet's ids go together, the big
/// entity lists filtered once (#13007), each id's own cleanup in order.
pub(super) fn remove_entities(&mut self, ids: &[i32]) {
for &id in ids {
self.detach_remote_tracking_entity(id);
self.audio.remove_sound_entity(id as u32);
// Entity.setRemoved detaches every passenger, even when no empty
// SetPassengers packet preceded the vehicle's removal. Otherwise
// mobs and other players keep their passenger pose after it is gone.
self.remote_set_passengers(id, &[]);
// Before the crystals go: the dragon's beam index follows them.
self.remove_remote_dragon(id);
self.crystals.retain(|c| c.id != id as u32);
self.remove_remote_object(id as u32);
self.remove_remote_small_projectiles(id as u32);
self.persist.uuids.remove(&(id as u32));
if let Some(r) = self.remote.as_mut() {
r.glowing.remove(&id);
r.entities.remove(&id);
r.passenger_vehicles.remove(&(id as u32));
r.lerps.remove(&id);
r.cart_lerps.remove(&id);
r.stepped.remove(&id);
r.head_lerps.remove(&id);
r.pending_items.remove(&id);
}
}
let removed: horizon_client::fast_hash::FxHashSet<u32> = if ids.len() > 1 {
ids.iter().map(|&id| id as u32).collect()
} else {
Default::default()
};
let keep = |id: u32| {
if ids.len() > 1 {
!removed.contains(&id)
} else {
ids.first().is_none_or(|&removed| id != removed as u32)
}
};
self.mobs.retain(|m| keep(m.id));
self.orbs.retain(|o| keep(o.id));
self.dropped.retain(|d| keep(d.id));
self.falling.retain(|f| keep(f.id));
self.tnts.retain(|t| keep(t.id));
if let Some(r) = self.remote.as_mut() {
r.passenger_vehicles.retain(|_, v| keep(*v));
}
}
}
#[cfg(test)]
mod tests {
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES and scratch homes/cwd"]
fn remove_entities_filters_mixed_entity_lists() {
use crate::game::{
Audio, Game, Options, Progress, Settings, execution_role::ExecutionRole, load_resources,
};
use horizon_protocol::packets::play::{self, Clientbound as C};
let root = std::path::PathBuf::from(std::env::var_os("HORIZON_TEST_RESOURCES").unwrap());
let settings = Settings::default();
let loaded = load_resources(
root.clone(),
None,
&root,
&settings,
std::time::Instant::now(),
false,
true,
&Progress::new(),
&mut |_, _| unreachable!(),
)
.unwrap();
let mut options = Options::parse(std::iter::empty()).unwrap().unwrap();
options.resources = root.clone();
options.execution_role = ExecutionRole::Client;
let mut game = Game::new(
&loaded.resources,
loaded.pack,
loaded.gui.unwrap(),
options,
settings,
Audio::silent(&root),
None,
)
.unwrap();
let (client, _server) = horizon_protocol::connection::Pipe::pair();
game.connect_local(client, "RemovalTest").unwrap();
for (id, kind) in [
(40, "minecraft:falling_block"),
(41, "minecraft:falling_block"),
(42, "minecraft:falling_block"),
(43, "minecraft:tnt"),
(44, "minecraft:tnt"),
(45, "minecraft:experience_orb"),
(46, "minecraft:experience_orb"),
(47, "minecraft:zombie"),
(48, "minecraft:zombie"),
] {
if matches!(kind, "minecraft:falling_block" | "minecraft:tnt") {
assert!(game.spawn_remote_projectile(
id,
kind,
[0.0, 64.0, 0.0],
(0.0, 0.0),
[0.0; 3],
0
));
} else {
game.spawn_entity(id, kind, [0.0, 64.0, 0.0], [0.0; 3]);
}
}
for id in [49, 50] {
game.dropped.push(horizon_client::entities::ItemEntity::new(
id,
horizon_client::items::ItemStack::new("minecraft:sand", 1),
horizon_core::geometry::Vec3::new(0.0, 64.0, 0.0),
horizon_core::geometry::Vec3::ZERO,
0.0,
));
}
game.handle_packet(C::RemoveEntities(play::RemoveEntities {
ids: vec![40, 42, 43, 45, 47, 49],
}))
.unwrap();
assert_eq!(game.falling.iter().map(|e| e.id).collect::<Vec<_>>(), [41]);
assert_eq!(game.tnts.iter().map(|e| e.id).collect::<Vec<_>>(), [44]);
assert_eq!(game.orbs.iter().map(|e| e.id).collect::<Vec<_>>(), [46]);
assert_eq!(game.mobs.iter().map(|e| e.id).collect::<Vec<_>>(), [48]);
assert_eq!(game.dropped.iter().map(|e| e.id).collect::<Vec<_>>(), [50]);
}
}
@@ -168,7 +168,6 @@ impl Game<'_> {
full_water_vision: self.settings.extras.pvp.tweaks.clear_water,
night_vision: self.fog_night_vision(),
environment: self.pack.polytone_colors.env,
fluid_fog: self.pack.polytone_colors.fluid_fog,
};
let mut fog = horizon_client::fog::setup_fog(tables, &self.fog, &input);
if !self.settings.horizon.fog {
@@ -487,7 +487,7 @@ pub(super) fn load_resources(
};
let resources = Arc::new(resources);
if menu {
horizon_client::telemetry::mark_core_ready();
horizon_client::play_session::core_ready();
log::info!(
"Horizon: core-ready after {} ms",
started.elapsed().as_millis()
@@ -526,7 +526,7 @@ pub(super) fn load_resources(
.set(rest)
.map_err(|_| "world resources already loaded".to_owned())?;
progress.set(9);
horizon_client::telemetry::mark_rest_ready();
horizon_client::play_session::rest_ready();
log::info!(
"Horizon: rest-ready after {} ms",
started.elapsed().as_millis()
@@ -29,13 +29,12 @@ pub(super) struct RespawnConfig {
pub dim: Dim,
pub pos: [i32; 3],
pub yaw: f32,
pub pitch: f32,
pub forced: bool,
}
/// A respawn point as a player's save keeps it (`respawn`): dimension,
/// block, yaw, pitch and whether it is forced.
pub(super) type SavedRespawn = (String, [i32; 3], f32, f32, bool);
/// block, yaw and whether it is forced.
pub(super) type SavedRespawn = (String, [i32; 3], f32, bool);
impl RespawnConfig {
/// `RespawnData.of`: the yaw wrapped to [-180, 180).
@@ -44,37 +43,19 @@ impl RespawnConfig {
dim,
pos,
yaw: wrap_degrees(f64::from(yaw)) as f32,
pitch: 0.0,
forced,
}
}
/// `SetSpawnCommand`: the forced literal, with its already parsed angles.
pub(super) fn forced(dim: Dim, pos: [i32; 3], yaw: f32, pitch: f32) -> Self {
Self {
dim,
pos,
yaw,
pitch,
forced: true,
}
}
pub(super) fn from_saved((dim, pos, yaw, pitch, forced): &SavedRespawn) -> Self {
pub(super) fn from_saved((dim, pos, yaw, forced): &SavedRespawn) -> Self {
Self {
dim: Dim::from_id(dim),
pos: *pos,
yaw: *yaw,
pitch: *pitch,
forced: *forced,
}
}
pub(super) fn saved(&self) -> SavedRespawn {
(
self.dim.id().to_owned(),
self.pos,
self.yaw,
self.pitch,
self.forced,
)
(self.dim.id().to_owned(), self.pos, self.yaw, self.forced)
}
}
@@ -199,7 +180,6 @@ impl Game<'_> {
dim: self.dim,
pos,
yaw: 0.0,
pitch: 0.0,
forced: false,
};
// RespawnConfig.isSamePosition: dimension and block.
@@ -498,14 +478,14 @@ impl Game<'_> {
rule.can_set_spawn.test(self.dark_outside())
}
/// `ServerPlayer.findRespawnAndUseSpawnBlock` for a config in the loaded
/// dimension: position and angles, using an anchor's charge; a bed's
/// dimension: the position and yaw, using an anchor's charge; a bed's
/// stand-up spot. A forced point (`spawnpoint`) that is no anchor or bed
/// holds if a player fits in it; anything else is gone.
pub(super) fn find_respawn_and_use(
&mut self,
c: RespawnConfig,
consume: bool,
) -> Result<Option<(Vec3, f32, f32)>> {
) -> Result<Option<(Vec3, f32)>> {
let state = self.world.block(c.pos[0], c.pos[1], c.pos[2]);
if !(self.is_anchor(state)
&& (c.forced || self.anchor_charges(state) > 0)
@@ -515,7 +495,7 @@ impl Game<'_> {
if self.is_bed(state) && self.bed_sets_spawn(state) {
let facing = self.bed_forward(state);
let stand = self.bed_stand_up(c.pos, facing, c.yaw);
return Ok(stand.map(|p| (p, look_at_yaw(p, c.pos), 0.0)));
return Ok(stand.map(|p| (p, look_at_yaw(p, c.pos))));
}
let [x, y, z] = c.pos;
let free = c.forced
@@ -523,7 +503,7 @@ impl Game<'_> {
&& self.possible_to_respawn_in(state)
&& self.possible_to_respawn_in(self.world.block(x, y + 1, z));
let at = Vec3::new(f64::from(x) + 0.5, f64::from(y) + 0.1, f64::from(z) + 0.5);
return Ok(free.then_some((at, c.yaw, c.pitch)));
return Ok(free.then_some((at, c.yaw)));
}
let stand = self.anchor_stand_up(c.pos);
if !c.forced
@@ -533,7 +513,7 @@ impl Game<'_> {
{
self.level_set(c.pos, next)?;
}
Ok(stand.map(|p| (p, look_at_yaw(p, c.pos), 0.0)))
Ok(stand.map(|p| (p, look_at_yaw(p, c.pos))))
}
}
@@ -580,354 +560,3 @@ mod tests {
assert!((look_at_yaw(east, head) - 90.0).abs() < 1.0e-4);
}
}
#[cfg(test)]
mod connected_spawnpoint_rotation_tests {
use crate::game::{Game, lan::LanSettings};
use horizon_client::{
chunk::Chunk,
lan::{Joined, NetConfig, Out, PlayerSender, guest::Guest, hub::HubConfig, playerdata},
};
use horizon_protocol::packets::{
configuration::ClientInformation,
play::{self, Clientbound as C, Serverbound as S},
};
use std::sync::{Arc, atomic::AtomicI32, mpsc};
fn command(game: &mut Game<'_>, text: &str) {
game.chat_capture = Some(Vec::new());
game.ui.registries.permission = 4;
let dispatcher = horizon_client::command::vanilla::build_for(false, true);
let parsed = dispatcher.parse(text, &game.ui.registries);
let (ctx, _) = parsed
.executable()
.expect("actual registered dedicated command");
let (root, ctx) = (parsed.context.clone(), ctx.clone());
assert_eq!(game.run_chain(&root, &ctx).unwrap(), 1, "{text}");
assert!(
!game.chat_capture.take().unwrap().is_empty(),
"actual command feedback {text}"
);
}
#[test]
#[ignore = "prepared resources and isolated scratch homes/cwd"]
fn command_forced_free_point_survives_real_guest_death_and_respawn_packet() {
let mut game = crate::game::native_machines::tests::server_game();
game.set_allow_commands(true);
let scratch = std::env::temp_dir().join(format!(
"horizon-forced-spawn-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&scratch).unwrap();
game.world_root = scratch.clone();
// Fixture setup through the existing column insertion API; admit every lit column below.
for x in -2..=2 {
for z in -2..=2 {
game.streaming
.insert_remote(&mut game.world, Chunk::empty(x, z));
assert!(game.streaming.is_lit(x, z));
}
}
let stone = game
.pack
.assets
.registry
.default_state("minecraft:stone")
.unwrap();
let air = game
.pack
.assets
.registry
.default_state("minecraft:air")
.unwrap();
game.world.set(12, 99, 12, stone).unwrap();
for y in [100, 101] {
game.world.set(12, y, 12, air).unwrap();
}
assert_eq!(game.world.block(12, 99, 12), stone);
assert!(game.world.loaded(12, 12));
game.level.world_spawn = Some([4, 100, 4]);
game.level.world_spawn_angle = [-30.0, -5.0];
game.lan_host(
LanSettings {
port: 0,
guest_commands: true,
force_game_mode: false,
},
NetConfig {
listen: false,
announce: false,
..NetConfig::loopback(0, String::new(), 2)
},
HubConfig {
default_game_mode: 0,
guest_commands: true,
force_game_mode: false,
hardcore: false,
view_distance: 2,
simulation_distance: 2,
dimension: "minecraft:overworld".into(),
allow_flight: false,
seed: 0,
max_players: 2,
integrated: false,
levels: Default::default(),
},
)
.unwrap();
let (tx, rx) = mpsc::channel();
let mut guest = Guest::new(
Joined {
conn: 7,
uuid: 77,
name: "Alice".into(),
properties: Vec::new(),
info: ClientInformation::new(2),
brand: "test".into(),
sender: PlayerSender::new(tx, Arc::default()),
latency: Arc::new(AtomicI32::new(0)),
address: "127.0.0.1:7".parse().unwrap(),
expected: false,
configured: Default::default(),
},
7,
[4.5, 100.0, 4.5],
2,
);
guest.dimension = "minecraft:overworld".into();
guest.placed = true;
guest.loaded = true;
guest.health = 20.0;
guest.game_mode = 0;
guest.yaw = 0.0;
guest.pitch = 0.0;
game.lan.as_mut().unwrap().hub.guests.push(guest);
let clock = game.world.game_time;
command(&mut game, "spawnpoint Alice 12 100 12 45 10");
let host = game.lan.as_ref().unwrap();
assert!(host.owner.is_none());
let guest = &host.hub.guests[0];
assert_eq!(
(guest.uuid, guest.health, guest.game_mode, guest.position),
(77, 20.0, 0, [4.5, 100.0, 4.5])
);
let tag = playerdata::player_tag(guest);
let respawn = tag
.get("respawn")
.expect("actual serialized personal configuration")
.clone();
assert_eq!(
respawn.get("yaw"),
Some(&horizon_world::nbt::Tag::Float(45f32.to_bits()))
);
assert_eq!(
respawn.get("pos"),
Some(&horizon_world::nbt::Tag::IntArray(vec![12, 100, 12]))
);
command(&mut game, "kill Alice");
game.tick_lan(false);
let mut host = game.lan.take().unwrap();
assert_eq!(host.hub.guests[0].uuid, 77);
assert_eq!(host.hub.guests[0].health, 0.0);
assert!(
host.hub.guests[0].dead,
"actual command death before request"
);
for _ in rx.try_iter() {}
game.lan_guest_packet(
&mut host,
7,
S::ClientCommand(play::ClientCommand { action: 0 }),
);
game.tick_server_travel(&mut host);
assert!(
!game.on_server_trip(7),
"admitted lit columns permit actual arrival"
);
let guest = &host.hub.guests[0];
assert_eq!(guest.uuid, 77);
assert_eq!(guest.health, 20.0);
assert!(!guest.dead);
assert_eq!(guest.position, [12.5, 100.1, 12.5]);
assert_eq!(game.level.world_spawn, Some([4, 100, 4]));
assert_eq!(game.level.world_spawn_angle, [-30.0, -5.0]);
assert_eq!(game.world.game_time, clock);
let physical = [guest.yaw.to_bits(), guest.pitch.to_bits()];
let awaiting_id = guest
.awaiting_teleport
.expect("actual final arrival awaits its acknowledgement")
.0;
let mut packets = Vec::new();
for out in rx.try_iter() {
match out {
Out::Packet(p) => packets.push(p),
Out::Packets(p) => packets.extend(p),
Out::Disconnect(_) => panic!("unexpected disconnect"),
}
}
let mut positions = Vec::new();
let mut respawns = 0;
for p in packets {
println!("complete actual Hub frame {p:?}");
let mut r = horizon_protocol::buf::Reader::new(&p);
let id = r.varint().unwrap();
match C::decode(id, r.rest()).unwrap() {
C::PlayerPosition(p) => positions.push(p),
C::Respawn(_) => respawns += 1,
_ => {}
}
}
assert_eq!(respawns, 1);
assert!(!positions.is_empty());
println!("all actual arrival positions {positions:?}");
let selected: Vec<_> = positions
.iter()
.filter(|p| p.teleport == awaiting_id)
.collect();
assert_eq!(
selected.len(),
1,
"select by actual authoritative pending id, never expected position/pitch"
);
let p = selected[0];
assert_eq!(p.position, [12.5, 100.1, 12.5]);
// All successful command/death/arrival/identity/world controls precede the intended regression.
assert_eq!(
(
respawn.get("pitch"),
physical,
[p.yaw.to_bits(), p.pitch.to_bits()]
),
(
Some(&horizon_world::nbt::Tag::Float(10f32.to_bits())),
[45f32.to_bits(), 10f32.to_bits()],
[45f32.to_bits(), 10f32.to_bits()]
)
);
drop(host);
drop(game);
std::fs::remove_dir_all(scratch).unwrap();
}
}
#[cfg(test)]
mod pitch_preservation_controls {
use super::*;
#[test]
fn wrapped_existing_callers_default_to_positive_zero_pitch() {
let c = RespawnConfig::wrapped(Dim::Overworld, [5, 100, 5], 45.0, false);
assert_eq!(c.yaw.to_bits(), 45f32.to_bits());
assert_eq!(c.pitch.to_bits(), 0.0f32.to_bits());
assert!(!c.forced);
}
/// Added source/model controls; these do not add a connected bed/anchor runtime claim.
#[test]
#[ignore = "prepared resources and isolated scratch homes/cwd"]
fn bed_anchor_facing_and_invalid_personal_fallback_ignore_stored_pitch() {
let mut game = crate::game::native_machines::tests::server_game();
let stone = game
.pack
.assets
.registry
.default_state("minecraft:stone")
.unwrap();
for x in 0..16 {
for z in 0..16 {
game.world.set(x, 99, z, stone).unwrap();
}
}
let state = |game: &Game<'_>, name: &str, properties: &[(&str, &str)]| {
let registry = game.pack.assets.registry;
let id = registry.default_state(name).unwrap();
let mut value = registry.state(id).unwrap().clone();
for (key, value_) in properties {
value.properties.insert((*key).into(), (*value_).into());
}
registry.resolve(&value).unwrap()
};
let head = state(
&game,
"minecraft:red_bed",
&[("facing", "north"), ("part", "head")],
);
let foot = state(
&game,
"minecraft:red_bed",
&[("facing", "north"), ("part", "foot")],
);
game.world.set(5, 100, 5, head).unwrap();
game.world.set(5, 100, 6, foot).unwrap();
assert!(game.is_bed(head) && game.bed_sets_spawn(head));
let bed = RespawnConfig {
dim: Dim::Overworld,
pos: [5, 100, 5],
yaw: 45.0,
pitch: 0.0,
forced: true,
};
let zero = game
.find_respawn_and_use(bed, false)
.unwrap()
.expect("valid bed geometry");
let stored = game
.find_respawn_and_use(RespawnConfig { pitch: 75.0, ..bed }, false)
.unwrap()
.unwrap();
assert_eq!(stored, zero);
assert_eq!(stored.2.to_bits(), 0.0f32.to_bits());
assert_eq!(stored.1.to_bits(), look_at_yaw(stored.0, bed.pos).to_bits());
// Existing built-in dimension facts select the anchor rule; no new world or actor API.
game.dim = Dim::Nether;
let anchor = state(&game, "minecraft:respawn_anchor", &[("charges", "2")]);
game.world.set(10, 100, 10, anchor).unwrap();
assert!(game.anchor_works() && game.is_anchor(anchor));
let c = RespawnConfig {
dim: Dim::Nether,
pos: [10, 100, 10],
yaw: 45.0,
pitch: 0.0,
forced: true,
};
let zero = game
.find_respawn_and_use(c, false)
.unwrap()
.expect("valid anchor geometry");
let stored = game
.find_respawn_and_use(RespawnConfig { pitch: 75.0, ..c }, true)
.unwrap()
.unwrap();
assert_eq!(stored, zero);
assert_eq!(stored.2.to_bits(), 0.0f32.to_bits());
assert_eq!(stored.1.to_bits(), look_at_yaw(stored.0, c.pos).to_bits());
assert_eq!(
game.world.block(10, 100, 10),
anchor,
"existing forced-charge behavior"
);
game.dim = Dim::Overworld;
game.level.world_spawn = Some([4, 100, 4]);
game.level.world_spawn_angle = [-30.0, -5.0];
game.world.set(12, 100, 12, stone).unwrap();
let invalid = RespawnConfig {
dim: Dim::Overworld,
pos: [12, 100, 12],
yaw: 45.0,
pitch: 10.0,
forced: true,
};
game.respawn_config = Some(invalid);
assert!(game.resolve_server_respawn(invalid).is_none());
assert!(game.respawn_config.is_none());
assert_eq!(game.level.world_spawn, Some([4, 100, 4]));
assert_eq!(game.level.world_spawn_angle, [-30.0, -5.0]);
}
}
@@ -644,14 +644,11 @@ impl Game<'_> {
/// in the level in place: where it stands up, facing the anchor (with
/// the deplete sound) or the bed; else the point is forgotten, and the
/// caller tells the player (`Hub::missing_respawn_block`).
pub(super) fn resolve_server_respawn(
&mut self,
config: RespawnConfig,
) -> Option<(Vec3, f32, f32)> {
pub(super) fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> {
let [x, y, z] = config.pos;
let anchor = self.is_anchor(self.world.block(x, y, z));
match self.find_respawn_and_use(config, true) {
Ok(Some((at, yaw, pitch))) => {
Ok(Some((at, yaw))) => {
if !config.forced && anchor {
let [x, y, z] = config.pos.map(f64::from);
self.audio.play(
@@ -661,7 +658,7 @@ impl Game<'_> {
1.0,
);
}
Some((at, yaw, pitch))
Some((at, yaw))
}
Ok(None) | Err(_) => {
let mut cancel = false;
@@ -799,10 +796,7 @@ impl Game<'_> {
let yaw = host.hub.guests[i].yaw;
let (position, yaw) = if let Some(config) = trip.respawn {
match self.as_guest(host, trip.conn, |g| g.resolve_server_respawn(config)) {
Some(Some((at, yaw, pitch))) => {
host.hub.guests[i].pitch = pitch;
(at, yaw)
}
Some(Some(found)) => found,
_ => {
host.hub.missing_respawn_block(trip.conn);
self.respawn_at_world_spawn(host, trip.conn);
-2
View File
@@ -261,8 +261,6 @@ impl<'a> Split<'a> {
.get(i.wrapping_sub(1))
.map(|g| g.options.clone()),
);
let seat = self.guests.get(i.wrapping_sub(1)).map_or(1, |g| g.seat);
horizon_hooks::engine::set_seat(seat - 1);
self.turn = i;
}
@@ -126,7 +126,6 @@ impl Split<'_> {
// Until it has a profile, a scratch options file: never P1's.
let options = Self::folder()?.join(".joining/options.txt");
OPTIONS.set(Some(options.clone()));
horizon_hooks::engine::set_seat(seat - 1);
let mut settings = self.host.settings.clone();
if pad.is_some() {
// The Controller setting is P1's own: a player who pressed a pad to join plays
@@ -136,7 +135,6 @@ impl Split<'_> {
}
let game = self.start_guest(seat, &options, settings);
OPTIONS.set(None);
horizon_hooks::engine::set_seat(0);
let mut game = game?;
if let Some(pad) = pad {
// The press that joined it doesn't act in its game.
@@ -301,31 +299,16 @@ impl Split<'_> {
}
let profile = profiles.join(&name);
let options = profile.join("options.txt");
let made = if options.exists() {
None
let mut settings = if options.exists() {
horizon_client::settings::Settings::load(&options)
} else {
std::fs::create_dir_all(&profile)?;
let mut new = self.host.settings.clone();
// The Controller setting is P1's, as on the profile page (`join`).
new.controller.enabled |= self.guests[i].pad.is_some();
// On P1's seat, so the crates' settings stores write P1's values too.
let turn = horizon_hooks::seat();
horizon_hooks::engine::set_seat(0);
new.save(&options);
horizon_hooks::engine::set_seat(turn);
Some(new)
new
};
// The crates' stores load into the guest's seat, before its turn starts below.
let turn = horizon_hooks::seat();
horizon_hooks::engine::set_seat(self.guests[i].seat - 1);
let mut settings = match made {
Some(new) => {
horizon_client::settings::Settings::load_stores(&options);
new
}
None => horizon_client::settings::Settings::load(&options),
};
horizon_hooks::engine::set_seat(turn);
// A profile an earlier join saved with P1's off, or the player's pad would be dead.
settings.controller.enabled |= self.guests[i].pad.is_some();
// P1's own world through memory (`Ok`), else P1's server over the network (`Err`).
@@ -53,7 +53,7 @@ pub(super) struct StartupMenu {
pub reload_packs: bool,
/// Browse mods' worker (`mod_browser`).
mod_jobs: super::mod_browser::Jobs,
pub perf: horizon_client::telemetry::Session,
pub perf: horizon_client::play_session::Session,
}
impl StartupMenu {
@@ -1268,7 +1268,7 @@ impl Loading {
let output = self
.renderer
.as_ref()
.map_or(Default::default(), |r| r.output());
.map_or(Default::default(), |r| *r.output());
self.menu
.options
.draw(&self.settings, output, batch, &gui.atlas, self.menu.cursor);
@@ -15,8 +15,6 @@ pub(super) fn rename_box() -> horizon_client::ui::EditBox {
edit.text_color = u32::MAX;
// AnvilScreen also sets `setTextColorUneditable(-1)`: white either way.
edit.text_color_uneditable = u32::MAX;
// AnvilScreen sets `setInvertHighlightedTextColor(false)`.
edit.invert_highlighted_text_color = false;
edit.focused = true;
edit.editable = false;
edit
@@ -42,7 +40,6 @@ mod tests {
// AnvilScreen.init: no input yet, so the box is read-only but focused.
let station_box = rename_box();
assert!(station_box.focused && !station_box.editable);
assert!(!station_box.invert_highlighted_text_color);
// slotChanged with an item: editable, and it shows the item's name.
let mut station = Station::new_kind(Kind::Anvil, [0; 3]);
+127 -162
View File
@@ -15,26 +15,6 @@ use std::{
time::{Duration, SystemTime, UNIX_EPOCH},
};
/// Studio's state in a `Game`: the replay playing, its free camera, timeline and top bar. Studio is
/// a Horizon extra (docs/layers.md: the replay editor); the engine only asks it whether a replay
/// plays or the free camera flies.
#[derive(Default)]
pub(super) struct Studio {
/// The packet replay playing, if any.
pub(super) replay: Option<ReplayDriver>,
pub(super) freecam: horizon_client::studio::StudioFreecam,
pub(super) timeline: horizon_client::studio::TimelineUi,
pub(super) topbar: horizon_client::studio::TopBarUi,
pub(super) rmb_down: bool,
pub(super) camera_track_dirty: bool,
/// Camera perspective to restore after leaving replay playback.
pub(super) replay_previous_camera_type: Option<super::perspective::CameraType>,
/// Replay opened from the title screen owns the synthetic remote session.
pub(super) replay_standalone: bool,
pub(super) last_replay_tick: Option<std::time::Instant>,
pub(super) virtual_tick_ms: f32,
}
pub const HELP: &[&str] = &[
"studio record start [NAME] start recording clientbound packets into .mcpr archive",
"studio record stop stop recording and finalize .mcpr archive",
@@ -129,13 +109,13 @@ impl Game<'_> {
match words[0] {
"freecam" => match words.get(1).copied() {
Some("on") => {
if self.studio.replay.is_none() {
if self.studio_replay.is_none() {
self.system_message(Text::translate(
"horizon.studio.freecam.replay_required",
&[],
));
} else if let Some((position, yaw, pitch)) = self.camera_view(1.0) {
self.studio.freecam.activate(
self.studio_freecam.activate(
position,
yaw,
pitch,
@@ -151,24 +131,24 @@ impl Game<'_> {
}
}
Some("off") => {
self.studio.freecam.deactivate();
self.studio_freecam.deactivate();
self.capture(false);
self.system_message(Text::translate("horizon.studio.freecam.disabled", &[]));
}
_ => self.system_message(Text::translate("horizon.studio.freecam.usage", &[])),
},
"keyframe" => {
let Some(driver) = self.studio.replay.as_ref() else {
let Some(driver) = self.studio_replay.as_ref() else {
self.system_message(Text::translate("horizon.studio.replay.inactive", &[]));
return true;
};
let time_ms = driver.position_ms();
match words.get(1).copied() {
Some("add") => {
if !self.studio.freecam.active
if !self.studio_freecam.active
&& let Some((position, yaw, pitch)) = self.camera_view(1.0)
{
self.studio.freecam.activate(
self.studio_freecam.activate(
position,
yaw,
pitch,
@@ -176,16 +156,16 @@ impl Game<'_> {
);
}
self.capture(true);
self.studio.freecam.add_keyframe_at_current(time_ms);
self.studio.camera_track_dirty = true;
self.studio_freecam.add_keyframe_at_current(time_ms);
self.studio_camera_track_dirty = true;
self.system_message(Text::tr(
"horizon.studio.keyframe.added",
&[&time_ms.to_string()],
));
}
Some("clear") => {
self.studio.freecam.track.clear();
self.studio.camera_track_dirty = true;
self.studio_freecam.track.clear();
self.studio_camera_track_dirty = true;
self.system_message(Text::translate(
"horizon.studio.keyframe.cleared",
&[],
@@ -201,15 +181,15 @@ impl Game<'_> {
));
return true;
};
if index >= self.studio.freecam.track.keyframes.len() {
if index >= self.studio_freecam.track.keyframes.len() {
self.system_message(Text::translate(
"horizon.studio.keyframe.index_invalid",
&[],
));
return true;
}
self.studio.freecam.track.keyframes.remove(index);
self.studio.camera_track_dirty = true;
self.studio_freecam.track.keyframes.remove(index);
self.studio_camera_track_dirty = true;
self.system_message(Text::tr(
"horizon.studio.keyframe.removed",
&[&index.to_string()],
@@ -219,14 +199,14 @@ impl Game<'_> {
}
}
"path" => match words.get(1).copied() {
Some("lock") if !self.studio.freecam.track.is_empty() => {
self.studio.freecam.active = true;
self.studio.freecam.locked_to_path = true;
Some("lock") if !self.studio_freecam.track.is_empty() => {
self.studio_freecam.active = true;
self.studio_freecam.locked_to_path = true;
self.capture(true);
self.system_message(Text::translate("horizon.studio.path.locked", &[]));
}
Some("unlock") => {
self.studio.freecam.locked_to_path = false;
self.studio_freecam.locked_to_path = false;
self.system_message(Text::translate("horizon.studio.path.unlocked", &[]));
}
_ => self.system_message(Text::translate("horizon.studio.path.usage", &[])),
@@ -319,7 +299,7 @@ impl Game<'_> {
}
}
Some("pause") => {
if let Some(r) = self.studio.replay.as_mut() {
if let Some(r) = self.studio_replay.as_mut() {
r.set_paused(true);
self.system_message(Text::translate("horizon.studio.replay.paused", &[]));
} else {
@@ -327,7 +307,7 @@ impl Game<'_> {
}
}
Some("resume") => {
if let Some(r) = self.studio.replay.as_mut() {
if let Some(r) = self.studio_replay.as_mut() {
r.set_paused(false);
self.system_message(Text::translate("horizon.studio.replay.resumed", &[]));
} else {
@@ -343,7 +323,7 @@ impl Game<'_> {
return true;
};
if let Ok(spd) = spd_str.parse::<f64>() {
let new_speed = if let Some(r) = self.studio.replay.as_mut() {
let new_speed = if let Some(r) = self.studio_replay.as_mut() {
r.set_speed(spd);
Some(r.speed())
} else {
@@ -377,12 +357,11 @@ impl Game<'_> {
return true;
};
if let Ok(ms) = ms_str.parse::<u32>() {
if self.studio.replay.is_some() {
if self.studio_replay.is_some() {
match self.seek_studio_replay(ms) {
Ok(()) => {
let actual_ms = self
.studio
.replay
.studio_replay
.as_ref()
.map_or(ms, |replay| ms.min(replay.duration_ms()));
let ms_text = actual_ms.to_string();
@@ -421,7 +400,7 @@ impl Game<'_> {
}
}
Some("status") => {
if let Some(r) = self.studio.replay.as_ref() {
if let Some(r) = self.studio_replay.as_ref() {
let position = r.position_ms().to_string();
let duration = r.duration_ms().to_string();
let progress = format!("{:.1}", r.progress() * 100.0);
@@ -456,7 +435,7 @@ impl Game<'_> {
/// Reset playback tick accumulator and align positions on seek.
pub(super) fn reset_studio_playback_ticks(&mut self) {
self.studio.virtual_tick_ms = 0.0;
self.studio_virtual_tick_ms = 0.0;
if let Some(player) = &self.player {
self.previous_position = player.position;
if let Some(m) = self.player_model.as_mut() {
@@ -473,14 +452,12 @@ impl Game<'_> {
/// forward because its pre-replay world must remain intact.
pub(super) fn seek_studio_replay(&mut self, target_ms: u32) -> std::io::Result<()> {
let current_ms = self
.studio
.replay
.studio_replay
.as_ref()
.map_or(0, ReplayDriver::position_ms);
let packets = if self.studio.replay_standalone {
let packets = if self.studio_replay_standalone {
let packets = self
.studio
.replay
.studio_replay
.as_mut()
.expect("replay checked by caller")
.seek_and_collect(target_ms)?;
@@ -494,8 +471,7 @@ impl Game<'_> {
"backward seek requires a standalone replay",
));
}
self.studio
.replay
self.studio_replay
.as_mut()
.expect("replay checked by caller")
.seek_forward(target_ms)?
@@ -503,7 +479,7 @@ impl Game<'_> {
self.dispatch_studio_replay_packets(packets);
self.reset_studio_playback_ticks();
self.studio.last_replay_tick = Some(std::time::Instant::now());
self.last_replay_tick = Some(std::time::Instant::now());
Ok(())
}
@@ -534,19 +510,19 @@ impl Game<'_> {
/// Advance active replay playback by elapsed frame time and dispatch ready packets.
pub(super) fn advance_studio_replay(&mut self) -> Result<()> {
let Some(driver) = self.studio.replay.as_mut() else {
self.studio.last_replay_tick = None;
let Some(driver) = self.studio_replay.as_mut() else {
self.last_replay_tick = None;
return Ok(());
};
let now = std::time::Instant::now();
let delta = match self.studio.last_replay_tick {
let delta = match self.last_replay_tick {
Some(last) => now
.saturating_duration_since(last)
.min(Duration::from_millis(250)),
None => Duration::from_millis(16),
};
self.studio.last_replay_tick = Some(now);
self.last_replay_tick = Some(now);
let ready_packets = match driver.advance(delta) {
Ok(pkts) => pkts,
@@ -557,18 +533,16 @@ impl Game<'_> {
};
self.dispatch_studio_replay_packets(ready_packets);
if self.studio.freecam.locked_to_path
if self.studio_freecam.locked_to_path
&& let Some(position) = self
.studio
.replay
.studio_replay
.as_ref()
.map(|replay| replay.position_ms())
{
self.studio.freecam.update_spline_playback(position);
self.studio_freecam.update_spline_playback(position);
}
let paused = self
.studio
.replay
.studio_replay
.as_ref()
.is_some_and(|replay| replay.is_paused());
if self.player_model.is_none() {
@@ -576,14 +550,13 @@ impl Game<'_> {
}
if !paused {
let speed = self
.studio
.replay
.studio_replay
.as_ref()
.map_or(1.0, |r| r.speed() as f32)
.max(0.1);
self.studio.virtual_tick_ms += delta.as_secs_f32() * 1000.0 * speed;
while self.studio.virtual_tick_ms >= 50.0 {
self.studio.virtual_tick_ms -= 50.0;
self.studio_virtual_tick_ms += delta.as_secs_f32() * 1000.0 * speed;
while self.studio_virtual_tick_ms >= 50.0 {
self.studio_virtual_tick_ms -= 50.0;
if let Some(player) = &self.player {
let current_pos = player.position;
let (dx, dz) = (
@@ -634,7 +607,7 @@ impl Game<'_> {
m.previous_limb_speed = m.limb_speed;
}
if let Some((position, duration, paused, markers)) =
self.studio.replay.as_ref().map(|replay| {
self.studio_replay.as_ref().map(|replay| {
(
replay.position_ms(),
replay.duration_ms(),
@@ -643,10 +616,10 @@ impl Game<'_> {
)
})
{
self.studio.timeline.current_time_ms = u64::from(position);
self.studio.timeline.duration_ms = u64::from(duration);
self.studio.timeline.playing = !paused;
self.studio.timeline.markers = markers;
self.studio_timeline.current_time_ms = u64::from(position);
self.studio_timeline.duration_ms = u64::from(duration);
self.studio_timeline.playing = !paused;
self.studio_timeline.markers = markers;
}
Ok(())
}
@@ -666,10 +639,10 @@ impl Game<'_> {
self.capture(false);
}
TopBarAction::ExitStudio => {
if self.studio.replay.is_some() {
if self.studio_replay.is_some() {
self.close_studio_replay();
} else {
self.studio.freecam.deactivate();
self.studio_freecam.deactivate();
self.capture(false);
}
}
@@ -695,46 +668,42 @@ impl Game<'_> {
} else {
(glam::DVec3::ZERO, 0.0, 0.0)
};
self.studio
.freecam
self.studio_freecam
.activate(position, yaw, pitch, self.settings.fov);
}
TopBarAction::ToggleLockToPath => {
self.studio.freecam.locked_to_path = !self.studio.freecam.locked_to_path;
self.studio_freecam.locked_to_path = !self.studio_freecam.locked_to_path;
}
TopBarAction::ToggleFreecam => {
if self.studio.freecam.active {
self.studio.freecam.deactivate();
if self.studio_freecam.active {
self.studio_freecam.deactivate();
self.capture(false);
} else {
let (position, yaw, pitch) =
self.camera_view(0.0)
.unwrap_or((glam::DVec3::ZERO, 0.0, 0.0));
self.studio
.freecam
self.studio_freecam
.activate(position, yaw, pitch, self.settings.fov);
self.capture(true);
}
}
TopBarAction::AddKeyframe => {
self.studio
.freecam
.add_keyframe_at_current(self.studio.timeline.current_time_ms as u32);
self.studio.camera_track_dirty = true;
self.studio_freecam
.add_keyframe_at_current(self.studio_timeline.current_time_ms as u32);
self.studio_camera_track_dirty = true;
}
TopBarAction::AddMarker => self.add_studio_marker(),
TopBarAction::ClearKeyframes => {
self.studio.freecam.track.keyframes.clear();
self.studio.timeline.selected_keyframe = None;
self.studio.camera_track_dirty = true;
self.studio_freecam.track.keyframes.clear();
self.studio_timeline.selected_keyframe = None;
self.studio_camera_track_dirty = true;
}
TopBarAction::ToggleTimeline => {
self.studio.timeline.visible = !self.studio.timeline.visible;
self.studio_timeline.visible = !self.studio_timeline.visible;
}
TopBarAction::SplitClip => {
self.studio
.timeline
.split_at(self.studio.timeline.current_time_ms);
self.studio_timeline
.split_at(self.studio_timeline.current_time_ms);
}
}
}
@@ -747,97 +716,93 @@ impl Game<'_> {
use horizon_client::studio::TimelineAction;
match action {
TimelineAction::PauseForSeek => {
self.studio.timeline.playing = false;
if let Some(replay) = self.studio.replay.as_mut() {
self.studio_timeline.playing = false;
if let Some(replay) = self.studio_replay.as_mut() {
replay.set_paused(true);
}
}
TimelineAction::Seek(time_ms) => {
let time_ms = if self.studio.replay_standalone {
let time_ms = if self.studio_replay_standalone {
time_ms
} else {
let current =
self.studio
.replay
self.studio_replay
.as_ref()
.map_or(0, ReplayDriver::position_ms) as u64;
time_ms.max(current)
};
self.studio.timeline.current_time_ms = time_ms;
self.studio_timeline.current_time_ms = time_ms;
if let Err(error) = self.seek_studio_replay(time_ms.min(u32::MAX as u64) as u32) {
log::warn!("Studio timeline seek failed: {error}");
}
}
TimelineAction::TogglePlay => {
self.studio.timeline.playing = !self.studio.timeline.playing;
if let Some(replay) = self.studio.replay.as_mut() {
replay.set_paused(!self.studio.timeline.playing);
self.studio_timeline.playing = !self.studio_timeline.playing;
if let Some(replay) = self.studio_replay.as_mut() {
replay.set_paused(!self.studio_timeline.playing);
}
}
TimelineAction::StepBack => {
let time_ms = self.studio.timeline.current_time_ms.saturating_sub(1000);
let time_ms = self.studio_timeline.current_time_ms.saturating_sub(1000);
self.handle_studio_timeline_action(TimelineAction::Seek(time_ms));
}
TimelineAction::StepForward => {
let time_ms = self
.studio
.timeline
.studio_timeline
.current_time_ms
.saturating_add(1000)
.min(self.studio.timeline.duration_ms);
.min(self.studio_timeline.duration_ms);
self.handle_studio_timeline_action(TimelineAction::Seek(time_ms));
}
TimelineAction::SeekStart => {
self.handle_studio_timeline_action(TimelineAction::Seek(0))
}
TimelineAction::SeekEnd => self.handle_studio_timeline_action(TimelineAction::Seek(
self.studio.timeline.duration_ms,
self.studio_timeline.duration_ms,
)),
TimelineAction::SetSpeed(speed) => {
self.studio.timeline.speed = speed;
if let Some(replay) = self.studio.replay.as_mut() {
self.studio_timeline.speed = speed;
if let Some(replay) = self.studio_replay.as_mut() {
replay.set_speed(speed);
}
}
TimelineAction::ToggleFreecam => {
if self.studio.freecam.active {
self.studio.freecam.deactivate();
if self.studio_freecam.active {
self.studio_freecam.deactivate();
} else {
let (position, yaw, pitch) =
self.camera_view(0.0)
.unwrap_or((glam::DVec3::ZERO, 0.0, 0.0));
self.studio
.freecam
self.studio_freecam
.activate(position, yaw, pitch, self.settings.fov);
}
}
TimelineAction::AddCameraKeyframe => {
self.studio
.freecam
.add_keyframe_at_current(self.studio.timeline.current_time_ms as u32);
self.studio.camera_track_dirty = true;
self.studio_freecam
.add_keyframe_at_current(self.studio_timeline.current_time_ms as u32);
self.studio_camera_track_dirty = true;
}
TimelineAction::RemoveCameraKeyframe(index) => {
if index < self.studio.freecam.track.keyframes.len() {
self.studio.freecam.track.keyframes.remove(index);
self.studio.camera_track_dirty = true;
if index < self.studio_freecam.track.keyframes.len() {
self.studio_freecam.track.keyframes.remove(index);
self.studio_camera_track_dirty = true;
}
self.studio.timeline.selected_keyframe = None;
self.studio_timeline.selected_keyframe = None;
}
TimelineAction::SelectKeyframe(index) => {
self.studio.timeline.selected_keyframe = Some(index);
self.studio_timeline.selected_keyframe = Some(index);
}
TimelineAction::KeyframeMoved => {
self.studio.camera_track_dirty = true;
self.studio_camera_track_dirty = true;
}
TimelineAction::SplitClip(time_ms) => self.studio.timeline.split_at(time_ms),
TimelineAction::SplitClip(time_ms) => self.studio_timeline.split_at(time_ms),
TimelineAction::None => {}
}
}
/// Add a bookmark at the replay playhead and save it in the `.mcpr` archive.
pub(super) fn add_studio_marker(&mut self) {
let Some(replay) = self.studio.replay.as_mut() else {
let Some(replay) = self.studio_replay.as_mut() else {
return;
};
let label = Text::translate(
@@ -846,7 +811,7 @@ impl Game<'_> {
)
.plain();
match replay.add_marker(label) {
Ok(_) => self.studio.timeline.markers = replay.markers().to_vec(),
Ok(_) => self.studio_timeline.markers = replay.markers().to_vec(),
Err(error) => log::warn!("Studio: could not save replay marker: {error}"),
}
}
@@ -880,7 +845,7 @@ impl Game<'_> {
Ok(Some(res))
}
Some("pause") => {
if let Some(r) = self.studio.replay.as_mut() {
if let Some(r) = self.studio_replay.as_mut() {
r.set_paused(true);
Ok(Some(json!({ "ok": true, "paused": true })))
} else {
@@ -888,7 +853,7 @@ impl Game<'_> {
}
}
Some("resume") => {
if let Some(r) = self.studio.replay.as_mut() {
if let Some(r) = self.studio_replay.as_mut() {
r.set_paused(false);
Ok(Some(json!({ "ok": true, "paused": false })))
} else {
@@ -898,7 +863,7 @@ impl Game<'_> {
Some("speed") => {
let spd_str = words.get(3).ok_or("missing speed value")?;
let spd: f64 = spd_str.parse().map_err(|_| "invalid speed")?;
if let Some(r) = self.studio.replay.as_mut() {
if let Some(r) = self.studio_replay.as_mut() {
r.set_speed(spd);
Ok(Some(json!({ "ok": true, "speed": r.speed() })))
} else {
@@ -908,7 +873,7 @@ impl Game<'_> {
Some("seek") => {
let ms_str = words.get(3).ok_or("missing seek timestamp")?;
let ms: u32 = ms_str.parse().map_err(|_| "invalid timestamp")?;
let pos = if let Some(r) = self.studio.replay.as_mut() {
let pos = if let Some(r) = self.studio_replay.as_mut() {
r.seek(ms).map_err(|e| format!("{e}"))?;
Some(r.position_ms())
} else {
@@ -922,7 +887,7 @@ impl Game<'_> {
}
}
Some("status") => {
if let Some(r) = self.studio.replay.as_ref() {
if let Some(r) = self.studio_replay.as_ref() {
Ok(Some(json!({
"ok": true,
"active": true,
@@ -1034,13 +999,13 @@ impl Game<'_> {
}
pub(super) fn open_studio_replay(&mut self, path: &str) -> Result<Value> {
if self.studio.camera_track_dirty
&& let Some(active) = self.studio.replay.as_mut()
if self.studio_camera_track_dirty
&& let Some(active) = self.studio_replay.as_mut()
{
if let Err(error) = active.save_camera_track(&self.studio.freecam.track) {
if let Err(error) = active.save_camera_track(&self.studio_freecam.track) {
return Ok(json!({ "ok": false, "error": error.to_string() }));
}
self.studio.camera_track_dirty = false;
self.studio_camera_track_dirty = false;
}
// The recordings browser can be opened while the title screen is
// available but the slower world tables are still loading. Replay
@@ -1063,7 +1028,7 @@ impl Game<'_> {
}
};
let standalone = self.studio.replay.is_none() && self.remote.is_none();
let standalone = self.studio_replay.is_none() && self.remote.is_none();
if self.remote.is_none()
&& let Err(error) = self.init_remote_for_replay()
{
@@ -1073,17 +1038,17 @@ impl Game<'_> {
let duration_ms = driver.duration_ms();
let packets = driver.packet_count();
self.studio.timeline.duration_ms = u64::from(duration_ms);
self.studio.timeline.current_time_ms = 0;
self.studio.timeline.playing = !driver.is_paused();
self.studio.timeline.markers = driver.markers().to_vec();
self.studio.freecam.track = driver.camera_track().cloned().unwrap_or_default();
self.studio.camera_track_dirty = false;
if self.studio.replay.is_none() {
self.studio.replay_previous_camera_type = Some(self.camera_type);
self.studio.replay_standalone = standalone;
self.studio_timeline.duration_ms = u64::from(duration_ms);
self.studio_timeline.current_time_ms = 0;
self.studio_timeline.playing = !driver.is_paused();
self.studio_timeline.markers = driver.markers().to_vec();
self.studio_freecam.track = driver.camera_track().cloned().unwrap_or_default();
self.studio_camera_track_dirty = false;
if self.studio_replay.is_none() {
self.studio_replay_previous_camera_type = Some(self.camera_type);
self.studio_replay_standalone = standalone;
}
self.studio.replay = Some(driver);
self.studio_replay = Some(driver);
self.camera_type = super::perspective::CameraType::FirstPerson;
self.title = None;
self.screen = Screen::Playing;
@@ -1101,14 +1066,14 @@ impl Game<'_> {
}))
}
pub(super) fn close_studio_replay(&mut self) -> bool {
if self.studio.camera_track_dirty
&& let Some(driver) = self.studio.replay.as_mut()
&& let Err(error) = driver.save_camera_track(&self.studio.freecam.track)
if self.studio_camera_track_dirty
&& let Some(driver) = self.studio_replay.as_mut()
&& let Err(error) = driver.save_camera_track(&self.studio_freecam.track)
{
log::warn!("Studio: could not save camera path: {error}");
}
self.studio.camera_track_dirty = false;
let closed = self.studio.replay.take().is_some();
self.studio_camera_track_dirty = false;
let closed = self.studio_replay.take().is_some();
if !closed {
return false;
}
@@ -1116,23 +1081,23 @@ impl Game<'_> {
// A standalone replay owns a synthetic Remote connection. Treat that
// connection as replay state even if the saved origin flag was lost;
// sending it through leave_server() opens the Multiplayer screen.
let standalone = self.studio.replay_standalone
let standalone = self.studio_replay_standalone
|| self
.remote
.as_ref()
.is_some_and(|remote| remote.brand == "horizon-studio");
self.studio.replay_standalone = false;
if let Some(camera_type) = self.studio.replay_previous_camera_type.take() {
self.studio_replay_standalone = false;
if let Some(camera_type) = self.studio_replay_previous_camera_type.take() {
self.camera_type = camera_type;
}
self.studio.last_replay_tick = None;
self.studio.timeline.current_time_ms = 0;
self.studio.timeline.playing = false;
self.studio.timeline.markers.clear();
self.studio.timeline.split_points.clear();
self.studio.timeline.selected_keyframe = None;
self.studio.freecam.deactivate();
self.studio.virtual_tick_ms = 0.0;
self.last_replay_tick = None;
self.studio_timeline.current_time_ms = 0;
self.studio_timeline.playing = false;
self.studio_timeline.markers.clear();
self.studio_timeline.split_points.clear();
self.studio_timeline.selected_keyframe = None;
self.studio_freecam.deactivate();
self.studio_virtual_tick_ms = 0.0;
self.capture(false);
if standalone {
if let Some(mut remote) = self.remote.take() {
+1 -1
View File
@@ -149,7 +149,7 @@ impl Game<'_> {
self.audio
.play_unshared("minecraft:item.totem.use", Some(body.bounds.feet), 1.0, 1.0);
if target == TrackingTarget::LocalPlayer {
self.input_feedback(horizon_client::input_source::Feedback::Totem);
self.pad_rumble(horizon_client::gamepad::Rumble::Totem);
// findTotem, then LocalPlayer.displayItemActivation. The offsets
// come from the player's own random in vanilla, not the level's:
// the client-only particle random stands in for it. The server
+1 -1
View File
@@ -298,7 +298,7 @@ impl super::Game<'_> {
.into_iter()
.any(|action| self.keys.held(action))
|| self
.input_move()
.pad_move()
.is_some_and(|[left, forward]| left.abs() > 0.3 || forward.abs() > 0.3))
{
self.tutorial.input();
@@ -107,9 +107,9 @@ impl Game<'_> {
state: ElementState::Pressed,
..
}
) && !self.input_made_pointer_event()
) && !self.pad.menu.synthetic
{
self.input_keyboard_used();
self.pad.keyboard_took_over = true;
}
if let WindowEvent::MouseInput { state, button, .. } = &event {
if *state == ElementState::Pressed {
@@ -304,7 +304,7 @@ impl ApplicationHandler for Game<'_> {
};
horizon_client::window::settle_created_fullscreen(&window, fullscreen);
drop(window_step);
horizon_client::telemetry::note_display(&window);
horizon_client::play_session::note_display(&window);
match self.new_renderer(window.clone()) {
Ok(r) => {
self.renderer = Some(r);
+20 -20
View File
@@ -169,33 +169,33 @@ impl Game<'_> {
/// Leaving the game with a world open (window closed, Quit, `quit`):
/// menu items go back (Player.closeContainer), then the world is saved,
/// once.
/// Keeps this play session's performance summary for the launcher to send, if the player
/// allows performance statistics (`horizon_client::telemetry`), and starts the next one.
/// Ends this play session for the hooks (`horizon_client::play_session`): opt-in telemetry
/// keeps its performance summary for the launcher to send, if the player allows it.
pub(super) fn finish_perf(&mut self) {
// One session per computer: P1's (a splitscreen player's would count it again).
if self.options.split_guest {
return;
}
let s = &self.settings;
let settings = horizon_telemetry::payload::Settings {
render_distance: s.render_distance.clamp(0, 255) as u8,
simulation_distance: s.simulation_distance.clamp(0, 255) as u8,
// 260 is the slider's "unlimited".
max_fps: if s.max_fps >= 260 {
0
} else {
s.max_fps.min(u32::from(u16::MAX)) as u16
},
vsync: s.vsync,
fullscreen: s.fullscreen,
graphics: s.graphics_preset.clone(),
};
// Again now: on Wayland the window is on a screen only once it has been shown.
if let Some(window) = &self.window {
horizon_client::telemetry::note_display(window);
horizon_client::play_session::note_display(window);
}
self.perf
.finish(&horizon_client::logging::game_home(), settings);
let s = &self.settings;
let home = horizon_client::logging::game_home();
let version = horizon_client::crash::build();
let gpu = horizon_client::crash::gpu();
self.perf.finish(&horizon_hooks::WorldLeft {
home: &home,
version: &version,
gpu: gpu.as_ref(),
render_distance: s.render_distance,
simulation_distance: s.simulation_distance,
// 260 is the slider's "unlimited".
max_fps: (s.max_fps < 260).then_some(s.max_fps),
vsync: s.vsync,
fullscreen: s.fullscreen,
graphics: &s.graphics_preset,
});
}
pub(super) fn save_for_exit(&mut self) -> Result<()> {
@@ -245,7 +245,7 @@ impl Game<'_> {
// Pause-menu and death-screen exits use the normal world-close action.
// A standalone replay owns a synthetic remote session, so it must go
// through replay cleanup instead of being treated like a server.
if self.studio.replay.is_some() {
if self.studio_replay.is_some() {
self.close_studio_replay();
return Ok(());
}
-43
View File
@@ -165,22 +165,6 @@ impl<T: Joined> JoinList<T> {
self.push(entity);
}
}
/// An entity that never left its level keeps its place in
/// `EntityTickList`: one a pass took out and puts back (an arrow bouncing
/// off) goes back before the first entity that joined after it. One that
/// has not joined yet is appended and numbered, as by `push`.
pub fn put_back(&mut self, entity: T) {
let seq = entity.join_seq();
let at = if seq.is_joined() {
self.list
.iter()
.position(|q| q.join_seq() > seq)
.unwrap_or(self.list.len())
} else {
self.list.len()
};
self.insert(at, entity);
}
}
impl<'a, T> IntoIterator for &'a JoinList<T> {
@@ -209,33 +193,6 @@ impl<T> IntoIterator for JoinList<T> {
mod tests {
use super::*;
#[derive(Debug)]
struct E {
join: JoinSeq,
}
crate::impl_joined!(E);
/// A numbered entity put back lands by its join number; a new one goes last.
#[test]
fn put_back_keeps_the_join_order() {
let mut list = JoinList::default();
for _ in 0..3 {
list.push(E {
join: JoinSeq::UNJOINED,
});
}
let first = list.remove(0);
let first_seq = first.join;
list.put_back(first);
assert_eq!(list[0].join, first_seq, "back before the later joins");
list.put_back(E {
join: JoinSeq::UNJOINED,
});
let seqs: Vec<_> = list.iter().map(|e| e.join).collect();
assert!(seqs.windows(2).all(|w| w[0] < w[1]), "{seqs:?}");
assert_eq!(seqs.len(), 4);
}
/// Whatever can change a list changes its stamp; only reading leaves it.
#[test]
fn a_stamp_holds_until_the_list_can_have_changed() {
+4 -4
View File
@@ -173,10 +173,10 @@ pub struct Guest {
/// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`),
/// None for the world spawn.
pub spawn: Option<[f64; 3]>,
/// A block-resolved personal respawn point: its dimension, block, yaw,
/// pitch and whether it is forced, as the player's save keeps it
/// (`respawn`).
pub respawn_elsewhere: Option<(String, [i32; 3], f32, f32, bool)>,
/// A respawn point outside the Overworld (a respawn anchor, or one
/// `spawnpoint` set there): its dimension, block, yaw and whether it is
/// forced, as the player's save keeps it (`respawn`).
pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>,
/// Pending ClientboundPlayerPositionPacket id; movement is ignored until
/// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient).
pub awaiting_teleport: Option<(i32, [f64; 3])>,
+1 -1
View File
@@ -343,7 +343,7 @@ struct Kept {
effects: Option<crate::effects::PlayerEffects>,
game_mode: Option<(i32, bool, f32)>,
position: Option<([f64; 3], [f64; 3], f32, f32, f32, bool, Option<[i32; 4]>)>,
spawn: Option<(Option<[f64; 3]>, Option<(String, [i32; 3], f32, f32, bool)>)>,
spawn: Option<(Option<[f64; 3]>, Option<(String, [i32; 3], f32, bool)>)>,
recipes: Option<crate::recipe_book::Settings>,
/// The body's values: its fall goes with the position, its air and fire with the
/// health.
+9 -111
View File
@@ -246,9 +246,7 @@ impl Goal for DefendVillage {
// wider, as the box test is strict).
let near = b.inflate(Vec3::new(1.0, 1.0, 1.0));
// Villager.getPlayerReputation of the player this golem sees: the
// villager's gossips about that player's own UUID. The villagers come
// through the same `attackTargeting` (`forCombat().range(64)`), so the
// golem must see them too.
// villager's gossips about that player's own UUID.
let bad = cx.w.others_near(near).any(|s| {
s.species == Species::Villager
&& s.alive
@@ -257,7 +255,6 @@ impl Goal for DefendVillage {
.is_some_and(|v| v.gossips.reputation(p.uuid) <= -100)
&& b.contains(s.position)
&& s.position.distance_squared(m.position) <= 64.0 * 64.0
&& m.sees(cx.w, Who::Mob(s.id))
});
bad && m.sees(cx.w, Who::Player)
}
@@ -325,39 +322,6 @@ impl Goal for MoveTowardsTarget {
m.nav_stop();
}
}
impl Mob {
/// `IronGolem.mobInteract`: the repair sound's pitch comes from the
/// golem's own random, not the level's.
pub fn golem_repair_pitch(&mut self) -> f32 {
1.0 + (self.random.next_float() - self.random.next_float()) * 0.2
}
}
/// `Level.isBrightOutside`: a fixed-time dimension (the End) is never bright.
fn bright_outside(w: &MobWorld) -> bool {
w.daylight && !w.dimension_type.has_fixed_time
}
/// `OfferFlowerGoal.getNearestEntity`: the nearest of
/// #candidate_for_iron_golem_gift (villagers and copper golems) in the golem's
/// box inflated by (6, 2, 6) that passes `forNonCombat().range(6.0)`: within
/// six blocks and in sight.
fn gift_candidate(m: &mut Mob, w: &MobWorld) -> Option<u32> {
let area = m.bounds().inflate(Vec3::new(6.0, 2.0, 6.0));
let mut best: Option<(f64, u32)> = None;
for s in w.others_near(area) {
if !matches!(s.species, Species::Villager | Species::CopperGolem)
|| !s.alive
|| !area.intersects(s.bounds)
{
continue;
}
let d = s.position.distance_squared(m.position);
if d > 36.0 || best.is_some_and(|(b, _)| d >= b) || !m.sees(w, Who::Mob(s.id)) {
continue;
}
best = Some((d, s.id));
}
best.map(|(_, id)| id)
}
/// `OfferFlowerGoal`: by day, now and then, hold out a poppy to a villager.
#[derive(Clone, Debug)]
struct OfferFlower {
@@ -370,10 +334,16 @@ impl Goal for OfferFlower {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !bright_outside(cx.w) || m.random.next_int_bound(8000).unwrap_or(1) != 0 {
if !cx.w.daylight || m.random.next_int_bound(8000).unwrap_or(1) != 0 {
return false;
}
self.villager = gift_candidate(m, cx.w);
// The nearest of #candidate_for_iron_golem_gift: villagers and copper golems.
self.villager =
cx.w.nearby(m.position, 6.0, |s| {
matches!(s.species, Species::Villager | Species::CopperGolem) && s.alive
})
.map(|s| s.id)
.next();
self.villager.is_some()
}
fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
@@ -642,78 +612,6 @@ mod tests {
Mob::new(id, Arc::new(kind), at, 0.0)
}
fn villager_at(id: u32, at: Vec3) -> crate::mobs::Seen {
mob(id, Species::Villager, at).seen(None)
}
fn pick(w: &MobWorld) -> Option<u32> {
let mut golem = mob(1, Species::IronGolem, Vec3::new(0.5, 64.0, 0.5));
gift_candidate(&mut golem, w)
}
fn with_chunks(world: &mut crate::world::World, _: &horizon_world::registry::BlockRegistry) {
for cx in -2..2 {
for cz in -2..2 {
world.chunks.insert(
(cx, cz),
std::sync::Arc::new(crate::chunk::Chunk::empty(cx, cz)),
);
}
}
}
/// `OfferFlowerGoal`: the search box is the golem's box inflated by
/// (6, 2, 6) and the candidate must be within six blocks (Euclidean).
#[test]
fn the_poppy_goes_to_a_villager_in_the_box_within_six_blocks() {
let cases = [
(Vec3::new(4.5, 64.0, 0.5), true),
// 6.5 blocks on one axis: outside the range.
(Vec3::new(7.0, 64.0, 0.5), false),
// About 8.5 blocks away, inside the per-axis box of six.
(Vec3::new(6.0, 64.0, 6.0), false),
// Five blocks above: outside the box's two-block rise.
(Vec3::new(0.5, 69.0, 0.5), false),
];
for (at, offered) in cases {
let villager = villager_at(2, at);
crate::mobs::world::with_built_test_world(&[villager], with_chunks, |w, _| {
assert_eq!(pick(w).is_some(), offered, "villager at {at:?}");
});
}
}
/// The candidate must also be in sight, and a fixed-time dimension is
/// never bright outside.
#[test]
fn the_poppy_needs_sight_and_a_dimension_with_a_day() {
let villager = villager_at(2, Vec3::new(4.5, 64.0, 0.5));
let wall = |world: &mut crate::world::World, r: &horizon_world::registry::BlockRegistry| {
with_chunks(world, r);
let stone = r.default_state("minecraft:stone").unwrap();
for y in 62..70 {
for z in -6..8 {
world.set(2, y, z, stone).unwrap();
}
}
};
crate::mobs::world::with_built_test_world(std::slice::from_ref(&villager), wall, |w, _| {
assert_eq!(pick(w), None, "a villager behind a wall");
});
crate::mobs::world::with_built_test_world(&[villager], with_chunks, |w, _| {
assert!(bright_outside(w));
assert_eq!(pick(w), Some(2));
let mut end = w.clone();
end.dimension_type =
horizon_world::dimension_type::DimensionFacts::vanilla("minecraft:the_end")
.unwrap();
assert!(!bright_outside(&end));
let mut night = w.clone();
night.daylight = false;
assert!(!bright_outside(&night));
});
}
#[test]
fn snow_trail_posts_block_place_with_golem_and_snow_state() {
let ran = crate::mobs::world::with_built_test_world(
@@ -21,12 +21,7 @@ use horizon_core::{
random::RandomSource,
};
use serde_json::Value;
use std::{
borrow::{Borrow, Cow},
collections::HashMap,
fs,
path::Path,
};
use std::{borrow::Cow, collections::HashMap, fs, path::Path};
pub use crate::biome::{SpawnCost, parse_costs, parse_entries};
@@ -884,17 +879,13 @@ impl SpawnState {
/// `NaturalSpawner.createState`: every non-persistent entity of a
/// spawning category in a loaded chunk adds its biome's spawn charge, its
/// category count and (for mobs) the local caps of the players near it.
pub fn new<'a, L: NaturalLevel, I>(
pub fn new<L: NaturalLevel>(
l: &L,
spawnable_chunks: i32,
players: Vec<SpawnPlayer>,
entities: I,
entities: &[Counted],
chunk_loaded: impl Fn(i32, i32) -> bool,
) -> Self
where
I: IntoIterator,
I::Item: std::borrow::Borrow<Counted<'a>>,
{
) -> Self {
let mut state = Self {
spawnable_chunks,
counts: [0; 8],
@@ -907,7 +898,6 @@ impl SpawnState {
last_checked: None,
};
for e in entities {
let e = e.borrow();
if e.is_mob && e.persistent || e.category == Category::Misc {
continue;
}
@@ -925,10 +915,6 @@ impl SpawnState {
}
state
}
/// Reclaims the player buffer for reuse across passes.
pub fn into_players(self) -> Vec<SpawnPlayer> {
self.players
}
fn add_charge(&mut self, pos: [i32; 3], charge: f64) {
if charge != 0.0 {
self.charges.push((pos, charge));
+81
View File
@@ -0,0 +1,81 @@
//! A play session as the hooks above the engine hear it (`horizon_hooks`): the title screen's
//! first frame, a world opening and its first frame, the frames played, and leaving the world.
//! It also marks those moments in the startup trace (`spans::startup`). Opt-in telemetry's
//! performance summary is built from these hooks (docs/telemetry.md).
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use horizon_hooks::{Frame, Milestone, WorldLeft, engine};
use crate::spans::{self, startup};
/// One window's session: moved from the startup menu to the game with the window.
#[derive(Default)]
pub struct Session {
/// When the world being opened started to, until its first frame.
opening: Option<Instant>,
}
impl Session {
/// The title screen drew a frame: the first time, how long the start took.
pub fn title_shown(&mut self) {
static SHOWN: AtomicBool = AtomicBool::new(false);
if !SHOWN.swap(true, Ordering::Relaxed) {
startup::mark("title.shown");
// The frame itself: the menu bundle can be ready seconds before the renderer that
// draws it (pipelines compiling on a slow driver).
engine::startup(Milestone::TitleShown, startup::since_start());
}
}
/// A world starts loading.
pub fn world_opening(&mut self) {
if self.opening.is_none() {
startup::arm("world.opening");
}
self.opening.get_or_insert_with(Instant::now);
}
/// An entry queued during startup was cancelled before opening a world.
pub fn cancel_world_opening(&mut self) {
self.opening = None;
}
/// A frame drawn while playing (not in menus or loading), with the spans the render thread
/// recorded in it ([`spans::take_raw`]): the step it spent most of its time in is
/// [`spans::culprit`].
pub fn frame(&mut self, ms: f32, frame_spans: &[spans::Span]) {
if let Some(opening) = self.opening.take() {
startup::mark("world.first_frame");
engine::world_shown(opening.elapsed());
}
engine::frame(&Frame::new(ms, &|| spans::culprit(frame_spans)));
}
/// The player left the world: the session ends.
pub fn finish(&mut self, left: &WorldLeft<'_>) {
engine::world_left(left);
}
}
/// Tells the hooks the screen `window` is on ([`crate::window::display`]).
pub fn note_display(window: &winit::window::Window) {
if let Some(d) = crate::window::display(window) {
engine::display(&horizon_hooks::Display {
width: d.width,
height: d.height,
refresh_hz: d.refresh_hz,
scale: d.scale,
});
}
}
/// The resources the menus need are loaded.
pub fn core_ready() {
engine::startup(Milestone::CoreReady, startup::since_start());
}
/// What a world needs is loaded too.
pub fn rest_ready() {
engine::startup(Milestone::RestReady, startup::since_start());
}
+29 -10
View File
@@ -13,8 +13,6 @@
//! game rules) is kept from the loaded files and written back unchanged.
//! Worlds saved by older Horizon builds (`region/`, `DIM-1/`, `Player` in
//! `level.dat`) are migrated on open.
mod respawn;
use crate::{
Result,
beehive::BeehiveExt,
@@ -3947,8 +3945,8 @@ pub struct Level {
pub spawn: Option<[f64; 3]>,
/// A respawn point resolved through its block when the player respawns
/// (a bed, a respawn anchor, a forced point in any dimension):
/// dimension, block, yaw, pitch and `forced`.
pub respawn_elsewhere: Option<(String, [i32; 3], f32, f32, bool)>,
/// dimension, block, yaw and `forced`.
pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>,
pub position: Option<[f64; 3]>,
pub rotation: [f32; 2],
pub health: f32,
@@ -4294,8 +4292,20 @@ impl Level {
if let Some(d) = text(p.get("Dimension")) {
self.dimension = d;
}
if let Some(respawn) = respawn::read(p) {
self.respawn_elsewhere = Some(respawn);
if let Some(respawn) = p.get("respawn")
&& let Some(Tag::IntArray(pos)) = respawn.get("pos")
&& pos.len() == 3
{
let dimension =
text(respawn.get("dimension")).unwrap_or_else(|| "minecraft:overworld".into());
let forced = number(respawn.get("forced")).is_some_and(|v| v != 0);
// Forced points, including Overworld ones, are validated through
// their blocks on death, just like beds and respawn anchors.
let yaw = match respawn.get("yaw") {
Some(Tag::Float(b)) => f32::from_bits(*b),
_ => 0.0,
};
self.respawn_elsewhere = Some((dimension, [pos[0], pos[1], pos[2]], yaw, forced));
}
let mut inventory = Vec::new();
let mut inventory_components = HashMap::new();
@@ -4526,8 +4536,17 @@ impl Level {
));
}
// A respawn point other than the world spawn: an anchor elsewhere, or a bed.
if let Some(saved) = &self.respawn_elsewhere {
entries.push(("respawn", respawn::write(saved)));
if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere {
let mut respawn = vec![
("dimension", string(dimension)),
("pos", Tag::IntArray(block.to_vec())),
("yaw", Tag::Float(yaw.to_bits())),
("pitch", Tag::Float(0f32.to_bits())),
];
if *forced {
respawn.push(("forced", Tag::Byte(1)));
}
entries.push(("respawn", Tag::compound(respawn)));
} else if let Some(s) = self.spawn {
let block = [
s[0].floor() as i32,
@@ -7679,7 +7698,7 @@ mod tests {
assert_eq!(back.spawn, Some([8.0, 64.0, 8.0]));
assert_eq!(
back.respawn_elsewhere,
Some(("minecraft:overworld".into(), [20, 70, 20], 0.0, 0.0, true))
Some(("minecraft:overworld".into(), [20, 70, 20], 0.0, true))
);
assert!(back.difficulty_locked);
assert!(back.weather.raining);
@@ -7950,7 +7969,7 @@ mod tests {
// A personal point coinciding with the world spawn must still keep
// its forced flag and yaw, rather than turning into a world fallback.
for pos in [[5, 64, 5], [0, 80, 0]] {
let point = ("minecraft:overworld".to_owned(), pos, 37.0, 0.0, true);
let point = ("minecraft:overworld".to_owned(), pos, 37.0, true);
let level = Level {
respawn_elsewhere: Some(point.clone()),
..Level::default()
-104
View File
@@ -1,104 +0,0 @@
//! Personal respawn record leaves from Level, using its existing typed NBT rules.
use super::{Tag, number, string, text};
pub(super) fn read(p: &Tag) -> Option<(String, [i32; 3], f32, f32, bool)> {
let mut value = None;
if let Some(respawn) = p.get("respawn")
&& let Some(Tag::IntArray(pos)) = respawn.get("pos")
&& pos.len() == 3
{
let dimension =
text(respawn.get("dimension")).unwrap_or_else(|| "minecraft:overworld".into());
let forced = number(respawn.get("forced")).is_some_and(|v| v != 0);
// Forced points, including Overworld ones, are validated through
// their blocks on death, just like beds and respawn anchors.
let yaw = match respawn.get("yaw") {
Some(Tag::Float(b)) => f32::from_bits(*b),
_ => 0.0,
};
let pitch = match respawn.get("pitch") {
Some(Tag::Float(b)) => f32::from_bits(*b),
_ => 0.0,
};
value = Some((dimension, [pos[0], pos[1], pos[2]], yaw, pitch, forced));
}
value
}
pub(super) fn write(
(dimension, block, yaw, pitch, forced): &(String, [i32; 3], f32, f32, bool),
) -> Tag {
let mut respawn = vec![
("dimension", string(dimension)),
("pos", Tag::IntArray(block.to_vec())),
("yaw", Tag::Float(yaw.to_bits())),
("pitch", Tag::Float(pitch.to_bits())),
];
if *forced {
respawn.push(("forced", Tag::Byte(1)));
}
Tag::compound(respawn)
}
#[cfg(test)]
mod tests {
use super::super::{Level, read_dat, write_dat};
use super::*;
/// Added model control: old records without pitch retain the existing positive-zero default.
#[test]
fn personal_respawn_missing_pitch_loads_positive_zero() {
let tag = Tag::compound(vec![(
"respawn",
Tag::compound(vec![
("dimension", string("minecraft:overworld")),
("pos", Tag::IntArray(vec![12, 100, 12])),
("yaw", Tag::Float(45f32.to_bits())),
("forced", Tag::Byte(1)),
]),
)]);
let mut level = Level::default();
level.read_player(&tag);
let (_, pos, yaw, pitch, forced) = level.respawn_elsewhere.unwrap();
assert_eq!(pos, [12, 100, 12]);
assert_eq!(yaw.to_bits(), 45f32.to_bits());
assert_eq!(pitch.to_bits(), 0.0f32.to_bits());
assert!(forced);
}
/// Added model/I/O control, separate from the connected runtime proof.
#[test]
fn personal_respawn_nonzero_pitch_survives_actual_player_file_write_and_read() {
let root = std::env::temp_dir().join(format!(
"horizon-personal-pitch-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&root).unwrap();
let file = root.join("player.dat");
let original = Level {
respawn_elsewhere: Some((
"minecraft:overworld".into(),
[12, 100, 12],
45.0,
10.0,
true,
)),
..Level::default()
};
write_dat(&file, original.player_tag()).unwrap();
let tag = read_dat(&file).expect("actual written NBT player file");
assert_eq!(
tag.get("respawn").unwrap().get("pitch"),
Some(&Tag::Float(10f32.to_bits()))
);
let mut loaded = Level::default();
loaded.read_player(&tag);
assert_eq!(loaded.respawn_elsewhere, original.respawn_elsewhere);
println!("actual saved personal respawn {:?}", tag.get("respawn"));
std::fs::remove_dir_all(root).unwrap();
}
}
+5 -36
View File
@@ -852,24 +852,14 @@ fn parse_recipe_sources<'a>(
"minecraft:stonecutting" => {
// A result count outside 1..=99 fails vanilla's codec: no recipe.
if let Some(count) = crate::crafting::template_count(&v["result"]) {
let result = if v["result"].get("components").is_some() {
match SmithingResult::parse(&v["result"], defaults)
.and_then(|result| result.create())
{
Some(result) => result,
None => continue,
}
} else {
ItemStack::new(
horizon_world::loot::recipe_result_id(&v["result"])
.unwrap_or("minecraft:air"),
count,
)
};
stonecutting.push(Stonecutting {
id,
input: ingredient(&v["ingredient"], items),
result,
result: ItemStack::new(
horizon_world::loot::recipe_result_id(&v["result"])
.unwrap_or("minecraft:air"),
count,
),
});
}
}
@@ -2226,27 +2216,6 @@ mod tests {
vec!["minecraft:diamond_sword", "minecraft:diamond_axe"]
);
}
#[test]
fn stonecutter_result_keeps_its_components() {
let root = std::env::temp_dir().join(format!(
"horizon-stonecutter-components-{}",
std::process::id()
));
let dir = root.join("data/minecraft/recipe");
fs::create_dir_all(&dir).unwrap();
fs::write(root.join("items.json"), r#"{"minecraft:stone":{}}"#).unwrap();
fs::write(
dir.join("cut.json"),
r#"{"type":"minecraft:stonecutting","ingredient":"minecraft:stone","result":{"id":"minecraft:stone","components":{"minecraft:custom_name":"Cut Stone"}}}"#,
)
.unwrap();
let recipes = StationRecipes::load(&root, &sample_items(), &PackOverlay::NONE);
let _ = fs::remove_dir_all(&root);
let listed = recipes.stonecutter(&ItemStack::new("minecraft:stone", 1));
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].result.custom_name().as_deref(), Some("Cut Stone"));
}
/// A world pack's stonecutting recipe takes its place in registration
/// order (path, then namespace), not a place after the game's own.
#[test]
+184 -133
View File
@@ -3,10 +3,15 @@
//! summary, in the outbox. It never sends those itself: the launcher does, at its next start (the
//! game's only sending is the anonymous "I'm playing" ping, `heartbeat.rs`).
//! Without the player's yes for that kind nothing is kept, and crash-reports/ stays local.
//!
//! It hears the game only through its hooks ([`HOOKS`], `horizon_hooks`), as a Horizon crate does:
//! it leaves the engine for the Horizon layer next (layer plan M5, docs/layers.md).
use std::path::Path;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Instant;
use std::sync::{LazyLock, Mutex};
use std::time::Duration;
use horizon_hooks::{self as hooks, Frame, Hooks, Milestone, WorldLeft};
use horizon_telemetry::payload::{Crash, Display, Perf, Settings, System, Timings};
use horizon_telemetry::scrub::Scrubber;
@@ -19,85 +24,115 @@ const MIN_SECONDS: f32 = 60.0;
/// world, the server or the resource packs.
const CRASH_DETAILS: [&str; 3] = ["Horizon Version", "Graphics Adapter", "Render Settings"];
static STARTED: OnceLock<Instant> = OnceLock::new();
static CORE_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX);
static REST_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX);
/// The screen the window opened on.
static DISPLAY: Mutex<Option<Display>> = Mutex::new(None);
/// When the game started, for the time to the title screen. Call first thing in `main`.
pub fn mark_start() {
STARTED.get_or_init(Instant::now);
/// The game's hooks, for `horizon_hooks::register`.
pub static HOOKS: Telemetry = Telemetry {
session: LazyLock::new(|| Mutex::new(Session::default())),
};
/// The play session's performance, as the game's hooks tell it.
pub struct Telemetry {
session: LazyLock<Mutex<Session>>,
}
pub fn mark_core_ready() {
mark_ready(&CORE_READY_MS);
}
pub fn mark_rest_ready() {
mark_ready(&REST_READY_MS);
}
fn mark_ready(mark: &AtomicU32) {
if let Some(started) = STARTED.get() {
let ms = started.elapsed().as_millis().min(u128::from(u32::MAX - 1)) as u32;
let _ = mark.compare_exchange(u32::MAX, ms, Ordering::Relaxed, Ordering::Relaxed);
impl Telemetry {
fn session(&self) -> std::sync::MutexGuard<'_, Session> {
self.session.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl Hooks for Telemetry {
fn startup(&self, milestone: Milestone, since_start: Duration) {
match milestone {
Milestone::CoreReady => mark_ready(&CORE_READY_MS, since_start),
Milestone::RestReady => mark_ready(&REST_READY_MS, since_start),
Milestone::TitleShown => self.session().title_shown(since_start),
}
}
/// A player who allows performance statistics also says what their slow frames spent their
/// time in.
fn wants_frame_steps(&self, home: &Path) -> bool {
horizon_telemetry::Consent::load(home).allows(horizon_telemetry::Kind::Perf)
}
fn world_shown(&self, since_opening: Duration) {
self.session().world_shown(since_opening);
}
fn frame(&self, frame: &Frame<'_>) {
self.session().frame(frame.ms, || frame.slowest_step());
}
fn world_left(&self, left: &WorldLeft<'_>) {
let settings = Settings {
render_distance: left.render_distance.clamp(0, 255) as u8,
simulation_distance: left.simulation_distance.clamp(0, 255) as u8,
max_fps: left
.max_fps
.map_or(0, |f| f.min(u32::from(u16::MAX)) as u16),
vsync: left.vsync,
fullscreen: left.fullscreen,
graphics: left.graphics.to_owned(),
};
self.session()
.finish(left.home, left.version, left.gpu, settings);
}
fn display(&self, display: &hooks::Display) {
*DISPLAY.lock().unwrap_or_else(|e| e.into_inner()) = Some(Display {
width: display.width,
height: display.height,
refresh_hz: display.refresh_hz.unwrap_or(0),
scale: display.scale as f32,
});
}
fn crashed(&self, crash: &hooks::Crash<'_>) {
keep_crash(crash);
}
}
fn mark_ready(mark: &AtomicU32, since_start: Duration) {
let ms = since_start.as_millis().min(u128::from(u32::MAX - 1)) as u32;
let _ = mark.compare_exchange(u32::MAX, ms, Ordering::Relaxed, Ordering::Relaxed);
}
fn readiness_ms(mark: &AtomicU32) -> Option<u32> {
let ms = mark.load(Ordering::Relaxed);
(ms != u32::MAX).then_some(ms)
}
/// The screen the window is on: size in physical pixels, refresh rate, scale.
pub fn set_display(width: u32, height: u32, refresh_hz: u32, scale: f64) {
*DISPLAY.lock().unwrap_or_else(|e| e.into_inner()) = Some(Display {
width,
height,
refresh_hz,
scale: scale as f32,
});
}
/// Keeps the screen `window` is on ([`crate::window::display`]) for the items' `system.display`.
pub fn note_display(window: &winit::window::Window) {
if let Some(d) = crate::window::display(window) {
set_display(d.width, d.height, d.refresh_hz.unwrap_or(0), d.scale);
}
}
/// This machine, with the GPU and the screen once the renderer knows them. The drive is the one
/// This machine, with the GPU once the renderer has one and the screen. The drive is the one
/// under the game folder (the current folder).
pub fn system() -> System {
pub fn system(gpu: Option<&hooks::Gpu>) -> System {
let home = std::env::current_dir().ok();
let mut system = System::detect_in(home.as_deref());
if let Some(gpu) = crate::gfx::adapter() {
if let Some(gpu) = gpu {
system.vram_mb = match gpu.kind.as_str() {
"discrete" => horizon_telemetry::system::vram_mb(&gpu.vendor).unwrap_or(0),
_ => 0,
};
system.gpu = gpu.name;
system.gpu_vendor = gpu.vendor;
system.gpu_kind = gpu.kind;
system.driver = gpu.driver;
system.backend = gpu.backend;
system.gpu = gpu.name.clone();
system.gpu_vendor = gpu.vendor.clone();
system.gpu_kind = gpu.kind.clone();
system.driver = gpu.driver.clone();
system.backend = gpu.backend.clone();
}
system.display = DISPLAY.lock().unwrap_or_else(|e| e.into_inner()).clone();
system
}
/// The release (`v0.2.3`), or the client's crate version for a build from source.
pub fn version() -> String {
crate::crash::release_tag().unwrap_or_else(|| format!("dev {}", env!("CARGO_PKG_VERSION")))
}
/// What a crash report becomes when it may leave: the error and stack, the thread, and the
/// details in [`CRASH_DETAILS`], with the world's name and folder and the server's address
/// scrubbed wherever they appear. No log lines.
pub fn crash_item(report: &crate::crash::Report) -> Item {
pub fn crash_item(report: &hooks::Crash<'_>) -> Item {
let mut scrubber = Scrubber::new();
for (key, value) in &report.details {
for (key, value) in report.details {
match key.as_str() {
// `Name (saves/folder)`, as game.rs sets it.
"World" => {
@@ -112,10 +147,10 @@ pub fn crash_item(report: &crate::crash::Report) -> Item {
}
}
let crash = Crash {
system: system(),
error: scrubber.scrub(&report.error),
stack: scrubber.scrub(&report.stack),
thread: report.thread.clone(),
system: system(report.gpu),
error: scrubber.scrub(report.error),
stack: scrubber.scrub(report.stack),
thread: report.thread.to_owned(),
details: report
.details
.iter()
@@ -123,7 +158,7 @@ pub fn crash_item(report: &crate::crash::Report) -> Item {
.map(|(k, v)| (k.clone(), scrubber.scrub(v)))
.collect(),
};
let mut item = Item::new(Source::Game, version(), Payload::Crash(crash));
let mut item = Item::new(Source::Game, report.version, Payload::Crash(crash));
// A huge stack keeps its top, where the error is.
while item.validate().is_err() {
let Payload::Crash(crash) = &mut item.payload else {
@@ -145,8 +180,8 @@ pub fn crash_item(report: &crate::crash::Report) -> Item {
}
/// Keeps the crash for the launcher to send, if the player allows crash reports.
pub fn keep_crash(home: &Path, report: &crate::crash::Report) {
if let Err(e) = outbox::push(home, &crash_item(report)) {
pub fn keep_crash(report: &hooks::Crash<'_>) {
if let Err(e) = outbox::push(report.home, &crash_item(report)) {
log::warn!("Horizon: could not keep the crash report to send: {e}");
}
}
@@ -159,7 +194,11 @@ pub fn keep_benchmark(home: &Path, report: &horizon_bench::Report) {
};
if let Err(e) = outbox::push(
home,
&Item::new(Source::Game, version(), Payload::Benchmark(data)),
&Item::new(
Source::Game,
crate::crash::build(),
Payload::Benchmark(data),
),
) {
log::warn!("Horizon: could not keep the benchmark report to send: {e}");
}
@@ -176,42 +215,33 @@ pub struct Session {
/// The start was measured: only the first session carries it.
title_measured: bool,
to_world_ms: Option<u32>,
opening: Option<Instant>,
slow_frames: Vec<horizon_telemetry::payload::SlowFrames>,
}
impl Session {
/// The title screen drew a frame: the first time, how long the start took.
pub fn title_shown(&mut self) {
/// The title screen drew its first frame, `since_start` after the game started.
pub fn title_shown(&mut self, since_start: Duration) {
if !self.title_measured {
self.title_measured = true;
crate::spans::startup::mark("title.shown");
// The frame itself: the menu bundle can be ready seconds before
// the renderer that draws it (pipelines compiling on a slow driver).
self.to_title_ms = STARTED.get().map(|s| s.elapsed().as_millis() as u32);
self.to_title_ms = Some(since_start.as_millis().min(u128::from(u32::MAX)) as u32);
}
}
/// A world starts loading.
pub fn world_opening(&mut self) {
if self.opening.is_none() {
crate::spans::startup::arm("world.opening");
/// A world's first frame, `since_opening` after it started opening: the session's first
/// world counts.
pub fn world_shown(&mut self, since_opening: Duration) {
if self.to_world_ms.is_none() {
self.to_world_ms = Some(since_opening.as_millis().min(u128::from(u32::MAX)) as u32);
}
self.opening.get_or_insert_with(Instant::now);
}
/// An entry queued during startup was cancelled before opening a world.
pub fn cancel_world_opening(&mut self) {
self.opening = None;
}
/// A frame drawn while playing (not in menus or loading), with the spans the render thread
/// recorded in it ([`crate::spans::take_raw`]): a frame of `SLOW_FRAME_MS` or more counts
/// under the step it spent most of its time in ([`crate::spans::culprit`]).
pub fn frame(&mut self, ms: f32, spans: &[crate::spans::Span]) {
/// A frame drawn while playing (not in menus or loading): a frame of `SLOW_FRAME_MS` or
/// more counts under the step it spent most of its time in (`slowest_step`, the game's
/// `spans::culprit`).
pub fn frame(&mut self, ms: f32, slowest_step: impl FnOnce() -> Option<(String, f32)>) {
use horizon_telemetry::payload::{SLOW_FRAME_MS, SlowFrames};
if ms >= SLOW_FRAME_MS {
let (mut path, span_ms) = crate::spans::culprit(spans).unwrap_or_default();
let (mut path, span_ms) = slowest_step().unwrap_or_default();
// A path too long for the item keeps its last steps.
while path.len() > SlowFrames::MAX_NAME
&& let Some((_, rest)) = path.split_once('/')
@@ -220,12 +250,6 @@ impl Session {
}
SlowFrames::record(&mut self.slow_frames, ms, &path, span_ms);
}
if let Some(opening) = self.opening.take() {
crate::spans::startup::mark("world.first_frame");
if self.to_world_ms.is_none() {
self.to_world_ms = Some(opening.elapsed().as_millis() as u32);
}
}
self.frames.record(ms);
self.played_ms += ms;
}
@@ -236,10 +260,10 @@ impl Session {
}
/// The session's summary, if it was long enough to say something.
pub fn summary(&self, settings: Settings) -> Option<Perf> {
pub fn summary(&self, gpu: Option<&hooks::Gpu>, settings: Settings) -> Option<Perf> {
let seconds = self.played_ms / 1000.0;
(seconds >= MIN_SECONDS).then(|| Perf {
system: system(),
system: system(gpu),
settings,
seconds: seconds as u32,
frames: self.frames.summary(),
@@ -255,11 +279,17 @@ impl Session {
/// Keeps the session's summary for the launcher to send, if the player allows performance
/// statistics, and starts the next session (the time to the title goes with the first).
pub fn finish(&mut self, home: &Path, settings: Settings) {
pub fn finish(
&mut self,
home: &Path,
version: &str,
gpu: Option<&hooks::Gpu>,
settings: Settings,
) {
if horizon_telemetry::Consent::load(home).allows(horizon_telemetry::Kind::Perf)
&& let Some(perf) = self.summary(settings)
&& let Some(perf) = self.summary(gpu, settings)
{
let item = Item::new(Source::Game, version(), Payload::Perf(perf));
let item = Item::new(Source::Game, version, Payload::Perf(perf));
if let Err(e) = outbox::push(home, &item) {
log::warn!("Horizon: could not keep the session's performance summary: {e}");
}
@@ -322,16 +352,33 @@ mod tests {
consent.save(home).unwrap();
}
fn report() -> crate::crash::Report {
crate::crash::Report {
time: chrono::Local::now(),
description: "Unexpected error".into(),
/// A crash report's parts, as `crash.rs` gives them to the hooks.
struct Report {
error: String,
stack: String,
details: Vec<(String, String)>,
}
impl Report {
fn crash<'a>(&'a self, home: &'a Path) -> hooks::Crash<'a> {
hooks::Crash {
home,
version: "v2026.10.15",
error: &self.error,
stack: &self.stack,
thread: "Render thread",
details: &self.details,
gpu: None,
}
}
}
fn report() -> Report {
Report {
error:
"panicked at src/save.rs:10:5:\nno level.dat in /Users/ana/horizon/saves/Ana's Base"
.into(),
stack: "horizon_client::save::load (crates/horizon-client/src/save.rs:10:5)\n".into(),
thread: "Render thread".into(),
side: "client",
details: vec![
(
"Horizon Version".into(),
@@ -345,13 +392,13 @@ mod tests {
("Server".into(), "play.example.net:25565".into()),
("Resource Packs".into(), "Ana's pack".into()),
],
log: vec!["[CHAT] <Ana> hi".into()],
}
}
#[test]
fn a_crash_keeps_only_what_says_what_happened() {
let item = crash_item(&report());
let report = report();
let item = crash_item(&report.crash(Path::new("home")));
let Payload::Crash(crash) = &item.payload else {
panic!("a crash item");
};
@@ -367,13 +414,7 @@ mod tests {
)]
);
let json = serde_json::to_string(&item).unwrap();
for private in [
"Castle Ana",
"Ana's Base",
"example.net",
"Ana's pack",
"CHAT",
] {
for private in ["Castle Ana", "Ana's Base", "example.net", "Ana's pack"] {
assert!(!json.contains(private), "{private} in {json}");
}
assert!(item.validate().is_ok());
@@ -384,7 +425,7 @@ mod tests {
let mut report = report();
report.stack =
"horizon_client::game::deep (crates/horizon-client/src/game.rs:1:1)\n".repeat(2000);
let item = crash_item(&report);
let item = crash_item(&report.crash(Path::new("home")));
assert!(item.validate().is_ok());
let Payload::Crash(crash) = item.payload else {
panic!("a crash item");
@@ -428,7 +469,8 @@ mod tests {
#[test]
fn crashes_stay_local_without_consent() {
let home = home("crash");
keep_crash(&home, &report());
let report = report();
keep_crash(&report.crash(&home));
assert!(outbox::pending(&home).is_empty());
allow(
&home,
@@ -437,7 +479,7 @@ mod tests {
..Choices::NONE
},
);
keep_crash(&home, &report());
keep_crash(&report.crash(&home));
assert!(outbox::pending(&home).is_empty());
allow(
&home,
@@ -446,33 +488,38 @@ mod tests {
..Choices::NONE
},
);
keep_crash(&home, &report());
keep_crash(&report.crash(&home));
let pending = outbox::pending(&home);
assert_eq!(pending.len(), 1);
assert_eq!(pending[0].1.kind(), Kind::Crash);
}
#[test]
fn cancelled_startup_entry_does_not_time_menu_browsing() {
fn the_time_to_a_world_is_the_sessions_first() {
let mut session = Session::default();
session.world_opening();
assert!(session.opening.is_some());
session.cancel_world_opening();
assert!(session.opening.is_none());
session.frame(16.0, &[]);
assert!(session.to_world_ms.is_none());
session.world_opening();
session.frame(16.0, &[]);
assert!(session.to_world_ms.is_some());
session.world_shown(Duration::from_millis(4200));
session.world_shown(Duration::from_millis(900));
assert_eq!(session.to_world_ms, Some(4200));
}
#[test]
fn the_time_to_the_title_goes_with_the_first_session_only() {
let home = home("title");
let mut session = Session::default();
session.title_shown(Duration::from_millis(3100));
assert_eq!(session.to_title_ms, Some(3100));
session.finish(&home, "dev", None, Settings::default());
session.title_shown(Duration::from_millis(9000));
assert_eq!(session.to_title_ms, None);
}
#[test]
fn a_session_is_kept_only_with_consent_and_once_long_enough() {
let home = home("session");
let mut session = Session::default();
session.world_opening();
(0..2000).for_each(|_| session.frame(16.6, &[]));
session.finish(&home, Settings::default());
session.world_shown(Duration::from_millis(1500));
(0..2000).for_each(|_| session.frame(16.6, || None));
session.finish(&home, "dev", None, Settings::default());
assert!(outbox::pending(&home).is_empty(), "33 s, and no consent");
allow(
&home,
@@ -481,14 +528,16 @@ mod tests {
..Choices::NONE
},
);
(0..2000).for_each(|_| session.frame(16.6, &[]));
session.finish(&home, Settings::default());
(0..2000).for_each(|_| session.frame(16.6, || None));
session.finish(&home, "dev", None, Settings::default());
assert!(outbox::pending(&home).is_empty(), "33 s is too short");
session.world_opening();
(0..4000).for_each(|_| session.frame(16.6, &[]));
session.world_shown(Duration::from_millis(1500));
(0..4000).for_each(|_| session.frame(16.6, || None));
(0..1200).for_each(|_| session.tick(4.0));
session.finish(
&home,
"dev",
None,
Settings {
render_distance: 12,
..Settings::default()
@@ -518,14 +567,16 @@ mod tests {
cpu_ms: ms,
depth,
};
let culprit = |spans: &[Span]| crate::spans::culprit(spans);
let mut session = Session::default();
(0..4000).for_each(|_| session.frame(16.6, &[span("tick", 10.0, 0)]));
let ticking = [span("tick", 10.0, 0)];
(0..4000).for_each(|_| session.frame(16.6, || culprit(&ticking)));
let frozen = [span("r_uploads", 280.0, 1), span("renderer", 300.0, 0)];
session.frame(320.0, &frozen);
session.frame(900.0, &frozen);
session.frame(260.0, &[]);
session.frame(249.0, &frozen);
let perf = session.summary(Settings::default()).unwrap();
session.frame(320.0, || culprit(&frozen));
session.frame(900.0, || culprit(&frozen));
session.frame(260.0, || culprit(&[]));
session.frame(249.0, || culprit(&frozen));
let perf = session.summary(None, Settings::default()).unwrap();
let seen: Vec<_> = perf
.slow_frames
.iter()
-9
View File
@@ -47,15 +47,6 @@ pub fn open_vulkan_device(
Some(unsafe { adapter.create_device_from_hal(open, desc) })
}
/// wgpu's opt-in to its `EXPERIMENTAL_*` features, which the crates that forbid unsafe code
/// can't give: hardware ray queries, asked for only when the player turns ray tracing on
/// (`gfx/ray_query.rs` in horizon-client-render).
pub fn experimental_features() -> wgpu::ExperimentalFeatures {
// Safety: wgpu warns that its experimental features may have bugs that reach undefined
// behaviour through safe calls. Horizon accepts that only on request, for ray queries.
unsafe { wgpu::ExperimentalFeatures::enabled() }
}
/// Tells the compositor, through `VK_EXT_hdr_metadata`, that the swapchain's
/// content is BT.709, peaks at `peak` nits and is no darker than `black`. Needs a
/// device from `open_vulkan_device` and a configured surface; does nothing otherwise.
+215 -20
View File
@@ -24,8 +24,9 @@ pub mod settings;
pub mod tunnel;
use registry::Registry;
use std::cell::Cell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::time::Duration;
/// What a crate above the engine hears from the game. Every method has an empty default:
/// implement only those you need. Hooks run on the game's thread (the render thread) unless a
@@ -43,6 +44,34 @@ pub trait Hooks: Sync {
/// The game is ending normally: its window closed and the world is saved. Not after a crash.
fn shutdown(&self) {}
/// A moment of the game's start, once each, with the time since the process started.
fn startup(&self, _milestone: Milestone, _since_start: Duration) {}
/// Whether this hook wants the render thread to time its steps in every frame, for
/// [`Frame::slowest_step`]. Asked once as the game starts (not on a dedicated server);
/// `home` is the game's home folder. Timing the steps costs microseconds a frame.
fn wants_frame_steps(&self, _home: &Path) -> bool {
false
}
/// A world's first frame was drawn: the time since it started opening (single player, a
/// server, LAN). Every time a world is entered.
fn world_shown(&self, _since_opening: Duration) {}
/// A frame drawn while playing: not in the menus or while a world loads. Every frame.
fn frame(&self, _frame: &Frame<'_>) {}
/// The player left a world (to the title screen, or by quitting): the end of a play
/// session, with the settings it was played with.
fn world_left(&self, _left: &WorldLeft<'_>) {}
/// The screen the window is on: when the window opens, and again as a session ends (on
/// Wayland a window is on a screen only once it has been shown).
fn display(&self, _display: &Display) {}
/// The game crashed, once, before its report is saved in `crash-reports/`. Called on the
/// thread that crashed, whatever the mode (a dedicated server too).
fn crashed(&self, _crash: &Crash<'_>) {}
/// The resolver of `friend:` addresses this crate offers ([`tunnel`]); the first hook that
/// offers one is used. Asked on the network thread when joining and on the game thread when
/// an address is shown, never per frame.
@@ -51,6 +80,106 @@ pub trait Hooks: Sync {
}
}
/// The graphics adapter the renderer runs on.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Gpu {
pub name: String,
pub vendor: String,
/// `integrated`, `discrete`, `virtual`, `cpu` or `other`.
pub kind: String,
pub driver: String,
/// `metal`, `vulkan`, `dx12` or `gl`.
pub backend: String,
}
/// The screen a window is on ([`Hooks::display`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Display {
/// Physical pixels.
pub width: u32,
pub height: u32,
/// `None` where the OS doesn't say.
pub refresh_hz: Option<u32>,
pub scale: f64,
}
/// What [`Hooks::crashed`] gets: the crash report's parts.
pub struct Crash<'a> {
/// The game's home folder.
pub home: &'a Path,
/// The build: the release (`v0.2.3`), or `dev <crate version>` for a build from source.
pub version: &'a str,
/// The error's message.
pub error: &'a str,
/// Where it happened and how it got there: one frame a line.
pub stack: &'a str,
pub thread: &'a str,
/// The report's details (`Horizon Version`, `World`, `Server`...), as written in it.
pub details: &'a [(String, String)],
/// The renderer's adapter, once it has one.
pub gpu: Option<&'a Gpu>,
}
/// A moment of the game's start ([`Hooks::startup`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Milestone {
/// The resources the menus need are loaded.
CoreReady,
/// The rest (what a world needs) too.
RestReady,
/// The title screen drew its first frame.
TitleShown,
}
impl Milestone {
fn bit(self) -> u8 {
match self {
Self::CoreReady => 1,
Self::RestReady => 2,
Self::TitleShown => 4,
}
}
}
/// What [`Hooks::frame`] gets.
pub struct Frame<'a> {
/// How long the frame took.
pub ms: f32,
slowest_step: &'a dyn Fn() -> Option<(String, f32)>,
}
impl<'a> Frame<'a> {
/// `slowest_step` gives [`Frame::slowest_step`], only when asked.
pub fn new(ms: f32, slowest_step: &'a dyn Fn() -> Option<(String, f32)>) -> Self {
Self { ms, slowest_step }
}
/// The step the frame spent the most time in (`render/terrain`) and its milliseconds, when
/// the steps were timed ([`Hooks::wants_frame_steps`]). Worked out on each call: ask only
/// for a slow frame.
pub fn slowest_step(&self) -> Option<(String, f32)> {
(self.slowest_step)()
}
}
/// What [`Hooks::world_left`] gets: the game's home folder, the build, the adapter and the
/// settings played with.
pub struct WorldLeft<'a> {
pub home: &'a Path,
/// As [`Crash::version`].
pub version: &'a str,
/// The renderer's adapter.
pub gpu: Option<&'a Gpu>,
pub render_distance: i32,
pub simulation_distance: i32,
/// `None`: unlimited.
pub max_fps: Option<u32>,
pub vsync: bool,
pub fullscreen: bool,
/// The graphics preset's name.
pub graphics: &'a str,
}
/// What [`Hooks::started`] gets.
#[non_exhaustive]
pub struct Started<'a> {
@@ -90,27 +219,10 @@ fn all() -> &'static [&'static dyn Hooks] {
HOOKS.all()
}
thread_local! {
static SEAT: Cell<usize> = const { Cell::new(0) };
}
/// The splitscreen player whose turn it is: 0 for P1 (and without splitscreen), 1 for P2...
/// Splitscreen players are one process, each `Game` in turn on the game's thread, so a crate's
/// statics are shared by them: a crate that keeps per-player state (settings, pages, HUD) indexes
/// it by this. A player keeps its seat while it plays. Other threads always see 0.
pub fn seat() -> usize {
SEAT.get()
}
/// The engine's side: where it calls the hooks. Only the engine calls these.
pub mod engine {
use super::*;
/// The player whose turn starts on this thread ([`seat`]).
pub fn set_seat(seat: usize) {
SEAT.set(seat);
}
/// Seals every list (hooks and the registries); their first use does it anyway. Call where
/// registration ends.
pub fn seal() {
@@ -148,6 +260,57 @@ pub mod engine {
}
}
/// The milestones already said.
static MILESTONES: AtomicU8 = AtomicU8::new(0);
/// [`Hooks::startup`], the first time `milestone` is reached; later calls do nothing.
pub fn startup(milestone: Milestone, since_start: Duration) {
if MILESTONES.fetch_or(milestone.bit(), Ordering::Relaxed) & milestone.bit() == 0 {
for hooks in all() {
hooks.startup(milestone, since_start);
}
}
}
/// [`Hooks::wants_frame_steps`]: whether any hook wants them.
pub fn wants_frame_steps(home: &Path) -> bool {
all().iter().any(|h| h.wants_frame_steps(home))
}
/// [`Hooks::world_shown`].
pub fn world_shown(since_opening: Duration) {
for hooks in all() {
hooks.world_shown(since_opening);
}
}
/// [`Hooks::frame`].
pub fn frame(frame: &Frame<'_>) {
for hooks in all() {
hooks.frame(frame);
}
}
/// [`Hooks::world_left`].
pub fn world_left(left: &WorldLeft<'_>) {
for hooks in all() {
hooks.world_left(left);
}
}
/// [`Hooks::display`].
pub fn display(display: &Display) {
for hooks in all() {
hooks.display(display);
}
}
/// [`Hooks::crashed`].
pub fn crashed(crash: &Crash<'_>) {
for hooks in all() {
hooks.crashed(crash);
}
}
/// [`Hooks::tunnel`]: the first registered hook's resolver.
pub fn tunnel() -> Option<&'static dyn tunnel::Resolver> {
all().iter().find_map(|hooks| hooks.tunnel())
@@ -173,6 +336,24 @@ mod tests {
fn published(&self, open: bool) {
self.0.lock().unwrap().push(format!("published {open}"));
}
fn startup(&self, milestone: Milestone, since_start: Duration) {
self.0
.lock()
.unwrap()
.push(format!("{milestone:?} {}", since_start.as_millis()));
}
fn wants_frame_steps(&self, _home: &Path) -> bool {
true
}
fn frame(&self, frame: &Frame<'_>) {
let step = frame
.slowest_step()
.map(|(name, ms)| format!(" {name} {ms}"));
self.0
.lock()
.unwrap()
.push(format!("frame {}{}", frame.ms, step.unwrap_or_default()));
}
}
/// Implements nothing: the defaults do nothing.
@@ -190,10 +371,24 @@ mod tests {
for open in [false, true, true, true, false, false] {
engine::published(open);
}
// Each milestone once: the first time it is reached.
engine::startup(Milestone::CoreReady, Duration::from_millis(900));
engine::startup(Milestone::TitleShown, Duration::from_millis(1500));
engine::startup(Milestone::CoreReady, Duration::from_millis(4000));
// Any hook that wants the steps timed has them.
assert!(engine::wants_frame_steps(Path::new("home")));
engine::frame(&Frame::new(70.0, &|| Some(("render/terrain".into(), 50.0))));
engine::shutdown();
assert_eq!(
*RECORDER.0.lock().unwrap(),
["started 0.2.31", "published true", "published false"]
[
"started 0.2.31",
"published true",
"published false",
"CoreReady 900",
"TitleShown 1500",
"frame 70 render/terrain 50",
]
);
assert_eq!(register(&Silent), Err(TooLate));
}
+3 -1
View File
@@ -46,7 +46,9 @@ pub use horizon_server_files as server_files;
/// [`hooks::register`] it before the game starts (docs/layers.md, "How a Horizon crate plugs
/// in"). The engine's dispatch side is not part of the API.
pub mod hooks {
pub use horizon_hooks::{Hooks, Started, TooLate, register, seat, tunnel};
pub use horizon_hooks::{
Crash, Display, Frame, Gpu, Hooks, Milestone, Started, TooLate, WorldLeft, register, tunnel,
};
}
/// The settings store (`horizon_hooks::settings`): a crate's own `key:value` lines in the game
-125
View File
@@ -50,111 +50,12 @@ pub enum BiomeColor {
Colormap(String),
}
/// A fluid modifier's fog (`fluid_modifiers`): `fog_colormap` as a flat colour (RGB), and the
/// `fog_radius` and `fog_fade` multipliers (1 is vanilla).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FluidFog {
pub color: Option<u32>,
pub radius: f32,
pub fade: f32,
}
/// The fog the packs' fluid modifiers give water and lava, read with the colours.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FluidFogs {
pub water: Option<FluidFog>,
pub lava: Option<FluidFog>,
}
impl FluidFogs {
/// Every `assets/<namespace>/polytone/fluid_modifiers/**.json` under a pack overlay root that
/// sets a fog field and targets `minecraft:water` or `minecraft:lava` (still or flowing). A
/// colormap id or an expression isn't read (a warning names it).
pub fn read(root: &Path) -> Self {
let mut fogs = Self::default();
for namespace in std::fs::read_dir(root.join("assets"))
.into_iter()
.flatten()
.flatten()
{
let mut stack = vec![namespace.path().join("polytone/fluid_modifiers")];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
} else if path.extension().is_some_and(|e| e == "json") {
fogs.add(root, &path);
}
}
}
}
fogs
}
fn add(&mut self, root: &Path, path: &Path) {
let Ok(text) = std::fs::read_to_string(path) else {
return;
};
let Ok(json) = serde_json::from_str::<Json>(&text) else {
return;
};
let relative = path.strip_prefix(root).unwrap_or(path).to_string_lossy();
let number = |key: &str| match json.get(key) {
None => Some(1.0),
Some(Json::Number(n)) => n.as_f64().map(|v| v as f32),
Some(Json::String(s)) => s.trim().parse().ok().or_else(|| {
log::warn!("{relative}: {key} expressions aren't read yet");
None
}),
_ => None,
};
let color = match json.get("fog_colormap") {
None => None,
Some(value) => match parse_color(value) {
Some(c) => Some(c & 0xFF_FFFF),
None => {
log::warn!("{relative}: only flat fog colours are read");
None
}
},
};
let fog = FluidFog {
color,
radius: number("fog_radius").unwrap_or(1.0),
fade: number("fog_fade").unwrap_or(1.0),
};
if fog
== (FluidFog {
color: None,
radius: 1.0,
fade: 1.0,
})
{
return;
}
let implicit = crate::implicit_id(&relative, "fluid_modifiers");
let Ok(targets) = crate::Targets::parse(json.get("targets"), implicit.as_deref()) else {
return;
};
let aims = |id: &str| targets.matches(id, |_| false);
if aims("minecraft:water") || aims("minecraft:flowing_water") {
self.water = Some(fog);
}
if aims("minecraft:lava") || aims("minecraft:flowing_lava") {
self.lava = Some(fog);
}
}
}
/// Every pack's custom colours, by dotted key.
#[derive(Clone, Debug, Default)]
pub struct PackColors {
entries: BTreeMap<String, Json>,
/// [`Self::environment`], read once with the packs: the fog reads it every frame.
pub env: Environment,
/// The packs' fluid modifiers' fog.
pub fluid_fog: FluidFogs,
}
impl PackColors {
@@ -182,7 +83,6 @@ impl PackColors {
}
}
colors.env = colors.environment();
colors.fluid_fog = FluidFogs::read(root);
colors
}
@@ -476,31 +376,6 @@ mod tests {
assert_eq!(c.biome_color("dry_foliage"), None);
}
#[test]
fn fluid_modifiers_give_water_and_lava_their_fog() {
let root = std::env::temp_dir().join(format!("fluid-fog-{}", std::process::id()));
let dir = root.join("assets/minecraft/polytone/fluid_modifiers");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("water.json"),
r#"{"targets": ["minecraft:water", "minecraft:flowing_water"], "fog_colormap": "ff0000", "fog_radius": 0.3}"#,
)
.unwrap();
std::fs::write(dir.join("lava.json"), r#"{"fog_fade": "0"}"#).unwrap();
std::fs::write(dir.join("honey.json"), r#"{"colormap": "foliage_color"}"#).unwrap();
let fogs = FluidFogs::read(&root);
let fog = |color, radius, fade| {
Some(FluidFog {
color,
radius,
fade,
})
};
assert_eq!(fogs.water, fog(Some(0xff0000), 0.3, 1.0));
assert_eq!(fogs.lava, fog(None, 1.0, 0.0));
std::fs::remove_dir_all(&root).unwrap();
}
#[test]
fn dyes_name_their_colour_kind() {
let mut c = PackColors::default();
-267
View File
@@ -1,267 +0,0 @@
//! The numeric fast path: a program of one expression whose every part is a number (constants,
//! arithmetic, comparisons of numbers, math functions, ternaries and `root.method(...)` calls) is
//! compiled again into a tree of `f64`s, which runs without the interpreter's `Value`s and
//! `Result`s. It answers exactly what the interpreter would: anything that could tell them apart
//! (strings, objects, `==` on a method's value, locals, game functions) keeps the interpreter.
use super::parse::{BinOp, Expr, Stmt};
use super::{Field, Host, MathFn, Root, Value};
use std::sync::Arc;
/// What a node gives: always a number, always a boolean, or whatever a host method answers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Num,
Bool,
Unknown,
}
/// A method argument, handed to the host as the interpreter would: a constant of any kind
/// (`o.custom('glow')`), another method's own value, or a number or boolean.
#[derive(Debug)]
pub(super) enum Arg {
Value(Value),
Method(Num),
Num(Num, bool),
}
#[derive(Debug)]
pub(super) enum Num {
Const(f64),
Neg(Box<Num>),
Not(Box<Num>),
Bin(BinOp, Box<Num>, Box<Num>),
And(Box<Num>, Box<Num>),
Or(Box<Num>, Box<Num>),
Cond(Box<Num>, Box<Num>, Box<Num>),
Call(MathFn, Vec<Num>),
Method(Root, Arc<str>, Vec<Arg>),
/// A method without arguments the host may answer by [`Field`] (its name otherwise).
Field(Root, Field, Arc<str>),
}
/// The fast form of a whole program, with the kind of value it gives.
#[derive(Debug)]
pub(super) struct Fast {
root: Num,
kind: Kind,
}
impl Fast {
/// The fast form of a program, when it is one expression the fast path covers.
pub(super) fn of(body: &[Stmt], locals: usize) -> Option<Self> {
let [Stmt::Expr(e)] = body else {
return None;
};
if locals != 0 {
return None;
}
let root = Num::of(e)?;
let kind = root.kind();
// A method at the top hands back its own value; elsewhere the kind must be known.
(kind != Kind::Unknown || matches!(root, Num::Method(..) | Num::Field(..)))
.then_some(Self { root, kind })
}
pub(super) fn eval(&self, host: &mut dyn Host) -> Result<Value, String> {
match &self.root {
Num::Method(root, name, args) => return call(host, *root, name, args),
Num::Field(root, field, name) => return field_value(host, *root, *field, name),
_ => {}
}
let n = self.root.eval(host)?;
Ok(match self.kind {
Kind::Bool => Value::Bool(n != 0.0),
_ => Value::Num(n),
})
}
}
fn field_value(host: &mut dyn Host, root: Root, field: Field, name: &str) -> Result<Value, String> {
match host.field(root, field) {
Some(value) => Ok(value),
None => call(host, root, name, &[]),
}
}
fn call(host: &mut dyn Host, root: Root, name: &str, args: &[Arg]) -> Result<Value, String> {
const FEW: usize = 4;
let target = host.root(root);
if args.is_empty() {
return host.method(&target, name, &[]);
}
let mut values: [Value; FEW] = std::array::from_fn(|_| Value::Null);
if args.len() > FEW {
let all = args
.iter()
.map(|a| a.value(host))
.collect::<Result<Vec<_>, _>>()?;
return host.method(&target, name, &all);
}
for (slot, arg) in values.iter_mut().zip(args) {
*slot = arg.value(host)?;
}
host.method(&target, name, &values[..args.len()])
}
impl Arg {
fn value(&self, host: &mut dyn Host) -> Result<Value, String> {
Ok(match self {
Self::Value(v) => v.clone(),
Self::Method(Num::Method(root, name, args)) => call(host, *root, name, args)?,
Self::Method(Num::Field(root, field, name)) => field_value(host, *root, *field, name)?,
Self::Method(n) | Self::Num(n, false) => Value::Num(n.eval(host)?),
Self::Num(n, true) => Value::Bool(n.eval(host)? != 0.0),
})
}
}
/// Whether a subtree calls the host, whose answer may be no number.
fn has_method(e: &Expr) -> bool {
match e {
Expr::Method(..) => true,
Expr::Neg(a) | Expr::Not(a) => has_method(a),
Expr::Binary(_, a, b) | Expr::And(a, b) | Expr::Or(a, b) => has_method(a) || has_method(b),
Expr::Cond(c, a, b) => has_method(c) || has_method(a) || has_method(b),
Expr::Call(_, args) | Expr::Host(_, args) => args.iter().any(has_method),
_ => false,
}
}
impl Num {
fn of(e: &Expr) -> Option<Self> {
let boxed = |e: &Expr| Self::of(e).map(Box::new);
Some(match e {
Expr::Const(Value::Num(n)) => Self::Const(*n),
Expr::Const(_) | Expr::Local(_) | Expr::Root(_) | Expr::Host(..) => return None,
Expr::Neg(a) => Self::Neg(boxed(a)?),
Expr::Not(a) => Self::Not(boxed(a)?),
Expr::Binary(op, a, b) => {
// `==` and `!=` also compare strings and objects: only between plain numbers.
if matches!(op, BinOp::Eq | BinOp::Ne) && (has_method(a) || has_method(b)) {
return None;
}
Self::Bin(*op, boxed(a)?, boxed(b)?)
}
Expr::And(a, b) => Self::And(boxed(a)?, boxed(b)?),
Expr::Or(a, b) => Self::Or(boxed(a)?, boxed(b)?),
Expr::Cond(c, a, b) => Self::Cond(boxed(c)?, boxed(a)?, boxed(b)?),
Expr::Call(f, args) => {
Self::Call(*f, args.iter().map(Self::of).collect::<Option<_>>()?)
}
Expr::Method(target, name, args) => {
let Expr::Root(root) = **target else {
return None;
};
if let (true, Some(field)) = (args.is_empty(), Field::of(name)) {
return Some(Self::Field(root, field, name.clone()));
}
let args = args
.iter()
.map(|a| match a {
Expr::Const(v) => Some(Arg::Value(v.clone())),
other => {
let n = Self::of(other)?;
match n.kind() {
Kind::Unknown
if matches!(n, Self::Method(..) | Self::Field(..)) =>
{
Some(Arg::Method(n))
}
// A ternary between method values: the interpreter's own value.
Kind::Unknown => None,
kind => Some(Arg::Num(n, kind == Kind::Bool)),
}
}
})
.collect::<Option<_>>()?;
Self::Method(root, name.clone(), args)
}
})
}
fn kind(&self) -> Kind {
match self {
Self::Const(_) | Self::Neg(_) | Self::Call(..) => Kind::Num,
Self::Bin(op, ..) => match op {
BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => Kind::Bool,
_ => Kind::Num,
},
Self::Not(_) | Self::And(..) | Self::Or(..) => Kind::Bool,
Self::Cond(_, a, b) => match (a.kind(), b.kind()) {
(x, y) if x == y => x,
_ => Kind::Unknown,
},
Self::Method(..) | Self::Field(..) => Kind::Unknown,
}
}
/// The value as a number, as the interpreter's `Value::num` reads it.
fn eval(&self, host: &mut dyn Host) -> Result<f64, String> {
Ok(match self {
Self::Const(n) => *n,
Self::Neg(a) => -a.eval(host)?,
Self::Not(a) => f64::from(u8::from(!a.truthy(host)?)),
Self::Bin(op, a, b) => {
let (x, y) = (a.eval(host)?, b.eval(host)?);
let t = |b: bool| f64::from(u8::from(b));
match op {
BinOp::Add => x + y,
BinOp::Sub => x - y,
BinOp::Mul => x * y,
BinOp::Div => x / y,
BinOp::Rem => x % y,
BinOp::Pow => x.powf(y),
BinOp::Eq => t(x == y),
BinOp::Ne => t(x != y),
BinOp::Lt => t(x < y),
BinOp::Le => t(x <= y),
BinOp::Gt => t(x > y),
BinOp::Ge => t(x >= y),
}
}
Self::And(a, b) => f64::from(u8::from(a.truthy(host)? && b.truthy(host)?)),
Self::Or(a, b) => f64::from(u8::from(a.truthy(host)? || b.truthy(host)?)),
Self::Cond(c, a, b) => {
if c.truthy(host)? {
a.eval(host)?
} else {
b.eval(host)?
}
}
Self::Call(f, args) if args.len() <= 4 => {
let mut nums = [0.0; 4];
for (slot, arg) in nums.iter_mut().zip(args) {
*slot = arg.eval(host)?;
}
f(&nums[..args.len()])
}
Self::Call(f, args) => {
let nums = args
.iter()
.map(|a| a.eval(host))
.collect::<Result<Vec<_>, _>>()?;
f(&nums)
}
Self::Method(root, name, args) => call(host, *root, name, args)?.num(),
Self::Field(root, field, name) => field_value(host, *root, *field, name)?.num(),
})
}
/// The value's truth, as the interpreter's `Value::truthy` reads it: a method's own answer
/// (a string or an object is true), else whether the number isn't 0.
fn truthy(&self, host: &mut dyn Host) -> Result<bool, String> {
match self {
Self::Method(root, name, args) => Ok(call(host, *root, name, args)?.truthy()),
Self::Field(root, field, name) => Ok(field_value(host, *root, *field, name)?.truthy()),
Self::Cond(c, a, b) => {
if c.truthy(host)? {
a.truthy(host)
} else {
b.truthy(host)
}
}
other => Ok(other.eval(host)? != 0.0),
}
}
}
+1 -50
View File
@@ -3,7 +3,6 @@
//! loads, with every name resolved, and then evaluated against a [`Host`], the game side that
//! answers context objects (`o`, `p`, `g`...) and their methods.
mod colors;
mod fast;
mod legacy;
mod lex;
mod parse;
@@ -69,36 +68,6 @@ impl Root {
}
}
/// A method without arguments that expressions read most, resolved when the program compiles so
/// a host can answer it without comparing names ([`Host::field`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Field {
Age,
Life,
Custom,
X,
Y,
Z,
Temperature,
Downfall,
}
impl Field {
pub(crate) fn of(name: &str) -> Option<Self> {
Some(match name {
"age" => Self::Age,
"life" => Self::Life,
"custom" => Self::Custom,
"x" => Self::X,
"y" => Self::Y,
"z" => Self::Z,
"temperature" => Self::Temperature,
"downfall" => Self::Downfall,
_ => return None,
})
}
}
/// What the game answers while an expression runs.
pub trait Host {
fn root(&mut self, root: Root) -> Value;
@@ -107,12 +76,6 @@ pub trait Host {
fn method(&mut self, target: &Value, name: &str, args: &[Value]) -> Result<Value, String>;
/// A global function of the game's (`config`, `colormap`, `modOn`, `date*`).
fn function(&mut self, name: &str, args: &[Value]) -> Result<Value, String>;
/// `root.field()` answered without its name, or `None` to answer it through [`Self::method`]:
/// a host that answers must give what `method` would.
fn field(&mut self, root: Root, field: Field) -> Option<Value> {
let _ = (root, field);
None
}
}
type MathFn = fn(&[f64]) -> f64;
@@ -176,16 +139,13 @@ pub(crate) const MATH: &[(&str, usize, usize, MathFn)] = &[
pub struct Program {
body: Vec<Stmt>,
locals: usize,
/// The same program on the numeric fast path, when it is one (`fast.rs`).
fast: Option<fast::Fast>,
}
impl Program {
/// Parses `src`; a syntax error or an unknown name fails here.
pub fn compile(src: &str) -> Result<Self, String> {
let (body, locals) = parse::parse(src)?;
let fast = fast::Fast::of(&body, locals);
Ok(Self { body, locals, fast })
Ok(Self { body, locals })
}
/// Whether the program reads nothing of its context but the `root.name()` methods `allowed`
@@ -225,15 +185,6 @@ impl Program {
/// Runs the statements; the result is the last statement's value (an assignment's is the
/// value it stored).
pub fn eval(&self, host: &mut dyn Host) -> Result<Value, String> {
if let Some(fast) = &self.fast {
return fast.eval(host);
}
self.interpret(host)
}
/// Runs the statements through the interpreter (what [`Self::eval`] does for a program the
/// fast path doesn't cover).
fn interpret(&self, host: &mut dyn Host) -> Result<Value, String> {
let mut run = Run {
host,
locals: vec![Value::Null; self.locals],
-111
View File
@@ -231,114 +231,3 @@ fn reads_only_names_what_a_program_may_read() {
assert!(!ok("r.noise(o.y, 0)"));
assert!(!ok("config('pack:option')"));
}
/// A host whose methods answer every kind of value, and record the arguments they get.
struct Kinds {
age: f64,
seen: Vec<String>,
/// Answers `o.age` and `o.life` by field too, as the particles' host does.
fields: bool,
}
impl Host for Kinds {
fn root(&mut self, root: Root) -> Value {
match root {
Root::Object => Value::Object(1),
Root::Random => Value::Object(2),
_ => Value::Object(3),
}
}
fn method(&mut self, _: &Value, name: &str, args: &[Value]) -> Result<Value, String> {
self.seen.push(format!("{name}{args:?}"));
Ok(match name {
"age" => Value::Num(self.age),
"life" => Value::Num(140.0),
"custom" => Value::Num(if args.is_empty() { 0.3 } else { 2.0 }),
"inWater" => Value::Bool(self.age > 50.0),
"biome" => Value::Str("minecraft:plains".into()),
"empty" => Value::Str("".into()),
"me" => Value::Object(7),
"noise" => Value::Num(args.iter().map(Value::num).sum::<f64>().sin()),
"fail" => return Err("no such thing".into()),
_ => Value::Null,
})
}
fn function(&mut self, _: &str, _: &[Value]) -> Result<Value, String> {
Ok(Value::Null)
}
fn field(&mut self, root: Root, field: Field) -> Option<Value> {
if !self.fields || root != Root::Object {
return None;
}
match field {
Field::Age => Some(Value::Num(self.age)),
Field::Life => Some(Value::Num(140.0)),
_ => None,
}
}
}
#[test]
fn the_fast_path_answers_what_the_interpreter_does() {
let corpus = [
"(0.7 + 0.3*sin(o.age*0.18 + o.custom*13000)) * min(o.age/(o.life*0.15),1)",
"0.5+(r.noise(o.age/60,5+o.age/60)*0.55)",
"o.age > 40",
"o.age >= 40 && o.age < 90",
"!(o.age > 3)",
"o.age > 10 || o.fail",
"o.age > 70 ? 1 : 0.25",
"o.age > 70 ? o.age : o.life",
"o.age > 70 ? o.biome : o.life",
"o.inWater",
"o.inWater ? 2 : 3",
"!o.inWater",
"o.biome ? 1 : 0",
"o.empty ? 1 : 0",
"o.me ? 1 : 0",
"o.biome + 1",
"-o.inWater",
"o.custom('glow') + 1",
"o.custom(o.age > 3)",
"r.noise(o.inWater, 2)",
"o.fail + 1",
"o.age % 7 - 2 ^ 3",
"clamp(o.age, 10, 20) / 0",
"o.age == 3",
"2 == 2",
"1 != 2 ? o.age : 0",
"max(o.age, o.life) - min(o.age, 1)",
"o.age > 3 ? o.age > 5 : o.inWater",
];
for src in corpus {
let program = Program::compile(src).unwrap();
let cases = [0.0, 3.0, 45.0, 75.0, 139.0]
.into_iter()
.flat_map(|a| [(a, false), (a, true)]);
for (age, fields) in cases {
let mut fast_host = Kinds {
age,
seen: Vec::new(),
fields,
};
let mut slow_host = Kinds {
age,
seen: Vec::new(),
fields,
};
let fast = program.eval(&mut fast_host);
let slow = program.interpret(&mut slow_host);
let same = match (&fast, &slow) {
(Ok(Value::Num(a)), Ok(Value::Num(b))) => a.to_bits() == b.to_bits(),
(a, b) => a == b,
};
assert!(same, "{src} at {age}: fast {fast:?}, interpreter {slow:?}");
// A field the host answers skips its call; the interpreter makes it by name.
if !fields {
assert_eq!(fast_host.seen, slow_host.seen, "{src} at {age}: the calls");
}
}
}
// The fast path covers the particles' and colormaps' plain arithmetic.
assert!(Program::compile(corpus[0]).unwrap().fast.is_some());
assert!(Program::compile(corpus[1]).unwrap().fast.is_some());
}
+1 -1
View File
@@ -49,7 +49,7 @@ Every setting applies at once, except worker threads, the graphics API and trans
With `HORIZON_HDR_FRAME=float`, HDR on and no shader pack or a 0.2 one, devices with independent blending draw the frame in layers ([hdr-linear-light.md](design/hdr-linear-light.md), The HUD and menus). The world's shaders write their own light into the frame instead of a mark (`hdr_written`, `hdr_light.wgsl`), a whole frame at a time, so glass, water, clouds and particles each lay their own light over the light behind them. Improved Transparency's layers write their own light too, before they are weighted and composited. No float frame holds marks: under a 0.2 pack Horizon's own draws keep their colour, alpha 1 where opaque and coverage where blended, HDR output lifts nothing, and the pack's `[tonemap]` takes the tone curve's place below (one or the other runs, never both); without the HUD layer (HDR off, or a device without independent blending) its float frame finishes on the swapchain's 8 bits before the camera overlays, which then draw with the HUD as in SDR, and HDR output stays off. The camera overlays (vignette, pumpkin, powder snow, portal, nausea), post effects and entity outlines draw on light. After the post effects and before the camera overlays, the tone curve eases that light into the peak (`Hdr::tonemap`) in place of HDR lighting's own easing and the light sources' cap at the peak: up to 60% of the peak light stays as it is, and above it ITU-R BT.2390's EETF in PQ rolls it off, on its brightest channel so it keeps its hue. The HUD and menus then draw on an 8-bit target of their own, the world clipped to white, as they found the frame before (each draw clips at white as there), and write how much of the world they hide into an R8 coverage target. The last pass lays the HUD over the world's light by that coverage, in gamma as the HUD blends: light behind see-through HUD shows as vanilla weights the HUD over it, and none shows through what covers it. The menu blur blurs that picture, light above white included, and the menu draws over the result. UI Brightness scales the HUD's own part, not the world under it. A screenshot maps the world's light into SDR, unchanged up to 0.6 of paper white in linear light and smoothly rolled towards white above it, with one scale for all RGB channels to keep their hue (where Horizon lifts nothing, with HDR Lighting off or under a 0.2 pack, the world is clipped at white as SDR draws it); the HUD's own part stays as drawn, whatever UI Brightness is, over the mapped world by its coverage. The world's icon uses the same mapping without the HUD; the `-hdr.png` beside a screenshot keeps the whole HDR picture. `HORIZON_HDR_DEBUG=coverage` tints the coverage magenta for inspection.
HDR also lights the world past paper white: surfaces at block or sky light levels 11 to 15 rise above it, up to 4 times for the strongest light, sky light by how a face meets the sun, easing into the peak from 60% of it so bright textures keep their detail. The frame's alpha between 0.76 and 1 carries it to the last pass, where it amounts to the lightmap going past 1. Darker light stays as in SDR. It's off while a shader pack runs. **HDR Lighting** (`hdrLighting`, on by default) is the whole of this lift: light sources, the sun and the lit surfaces above; off, HDR shows SDR's picture. Under a `shaders/` pack or a 0.2 one Horizon lifts nothing, so the row is greyed and says why; under a 0.1 pack it still lifts the light sources and the sun.
HDR also lights the world past paper white: surfaces at block or sky light levels 11 to 15 rise above it, up to 4 times for the strongest light, sky light by how a face meets the sun, easing into the peak from 60% of it so bright textures keep their detail. The frame's alpha between 0.76 and 1 carries it to the last pass, where it amounts to the lightmap going past 1. Darker light stays as in SDR. It's off while a shader pack's post or material stage runs, and `HORIZON_HDR_LIGHTING=0` turns it off to compare.
HDR's light sources shine by the kind of light rather than its level (`mesher::hdr_tier`): the sun most, then glowstone, campfires and the soul fires, then flames and lava, torch and candle flames among them (particles too), then faint glowers such as a redstone torch or magma; glow lichen stays as in SDR. Each tier has its share of the headroom and the brightness its lift starts and ends at, the texel's own before lighting, so a light source shines alike at any light level and on every face (`gfx/hdr.rs` `TIERS`); `HORIZON_HDR_DEBUG=1` greys what isn't lifted and tints what is magenta.
+1 -1
View File
@@ -20,7 +20,7 @@ plan are in [server.md](server.md).
takes the account's UUID when someone owns that name, as vanilla does, and that player is then refused.
- **An offline server** (`online_mode = false`) never checks accounts: anyone who reaches it can join under
any name. Keep it on your LAN or a tailnet (Tailscale, ZeroTier), or share it only with friends you trust.
A Horizon game started without a session (no network at Play) can join only such a server.
A Horizon player under an offline name can join only such a server.
- **Secure chat** works as on vanilla's server: in online mode, vanilla clients and Horizon's (Nightly
2026-11-01 and newer) sign their chat, and with `enforce-secure-profile=true` (the default) unsigned chat is
refused. On an offline server, or for a player without a chat session, chat stays unsigned and shows as not
+36 -1
View File
@@ -188,7 +188,7 @@ MCP: `account_sign_out`, needs `confirm: true`.
## `horizon-launcher account select`
Play as this account.
Play as this account, or as one of your offline names.
horizon-launcher account select <WHO>
@@ -196,6 +196,41 @@ Play as this account.
MCP: `account_select`.
## `horizon-launcher account offline`
Play offline (LAN, offline-mode servers) beside a signed-in account that owns the game: as NAME (kept to switch back to; 3 to 16 letters, digits or _), or as the name the game made up.
horizon-launcher account offline [NAME]
- `NAME`
MCP: `account_offline`.
## `horizon-launcher account forget-offline`
Forget one of your offline names; its skin and cape go with it.
horizon-launcher account forget-offline <NAME>
- `NAME`
MCP: `account_forget_offline`.
## `horizon-launcher account skin`
Show or set an offline name's skin and cape: a 64x64 (or 64x32) skin PNG, a 64x32 cape PNG, the model. Kept by the launcher and given to the game when that name plays.
horizon-launcher account skin <NAME> [FILE]
- `NAME`
- `FILE`: The skin's PNG
- `--model`: classic or slim arms
- `--cape`: The cape's PNG
- `--no-skin`: Back to the default skin
- `--no-cape`: Take the cape off
MCP: `account_skin`.
## `horizon-launcher settings`
Show the launcher's settings, or set one (the Settings page): selected-version TAG, game-architecture auto|x64|arm64, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, prune-old-versions on|off (delete old versions after an install, keeping the selected one, the ones instances use and the newest few), keep-versions N (how many of the newest to keep; "default" is 2), opening-animation on|off, proxy http://host:port|socks5://host:port ("default" removes it), while-playing stay|minimize|hide (what the window does while the game runs), language system|en|fr|ru|de|zh|es|uk|pl (the window's language; system follows the computer's), accent violet|blue|teal|green|amber|red|pink|#rrggbb|DEGREES (a named accent, any colour, or any hue), background PATH (a picture behind Home; "default" shows Horizon's landscape), native-cache-gib N (combined native compilation cache limit in GiB, default 30; 0 disables automatic cleanup), native-profile performance|dev|release (the profile native mods build with: performance is incremental, dev rebuilds a mod quickest for a slow game, release is slowest to build and slightly faster to play).
+11 -78
View File
@@ -288,12 +288,17 @@ build pays nothing.
The hooks today: `started` (once, when someone plays: not a dedicated server, a benchmark or an automated run),
`published` (the world opened to or closed from LAN or friends, on change), `shutdown` (the window closed, the
world saved) and `tunnel` (the resolver of `friend:` addresses, Play with Friends'). **A hook you need and don't find:** add a method with an empty default to `Hooks` and a function in
`horizon_hooks::engine` that the engine calls where vanilla does the matching thing; give it plain data or a type
the engine owns, never one from above. A hook that needs engine types the platform doesn't expose yet (a draw
context for HUD and chat overlays, a settings page) comes with that type's platform API (M6). An extension point
that belongs to one subsystem (an input source, the compositor) lives in the engine crate that owns it, with the
same shape: registered before the game runs, read-only after.
world saved), and the play session's: `startup` (core-ready, rest-ready, the title's first frame, once each),
`wants_frame_steps` (asked once: time the render thread's steps), `world_shown` (a world's first frame), `frame`
(every frame played), `world_left` (the session's end, with its settings), `display` (the screen the window is on)
and `crashed` (each crash, before its report is saved); and `tunnel` (the resolver of `friend:` addresses, Play
with Friends'). Opt-in telemetry (`telemetry.rs`) hears the game through these only. **A hook you need and don't
find:** add a method with an empty default to `Hooks` and a function in `horizon_hooks::engine` that the engine
calls where vanilla does the matching thing; give it plain data or a type the engine owns, never one from above. A
hook that needs engine types the platform doesn't expose yet (a draw context for HUD and chat overlays, a settings
page) comes with that type's platform API (M6). An extension point that belongs to one subsystem (an input source,
the compositor) lives in the engine crate that owns it, with the same shape: registered before the game runs,
read-only after.
**What players get.** The release builds (`game-build.yml`, so the nightly and the release; `tools/ci/build-musl.sh`)
build `horizon-official` and ship it as `horizon-client`, the name the launcher and players know. The launcher's
@@ -423,78 +428,6 @@ pub trait Layer: Sync {
- Sprites, items and the player's state come with their platform API (M6). They are not in this first
version.
### Look (`horizon_platform::look`)
What the engine draws differently for a crate above, as plain data: PvP & HUD's knobs today (#14217).
```rust
pub struct Look { // #[non_exhaustive]; Default is vanilla's
pub legacy_pose: bool, pub hide_attack_indicator: bool,
pub mute_attack_sounds: bool, pub hide_attack_particles: bool,
pub frame: Frame, // outline, hurt overlay and glint colours
pub shield_size: u8, pub totem_scale: f32, pub fire_lower: f32,
pub clear_lava: bool, pub clear_water: bool, pub chat: Chat,
pub hide_effect_icons: bool, pub time_of_day: Option<i64>, pub weather: Option<(f32, f32)>,
}
pub fn update(change: impl FnOnce(&mut Look)); // the player whose turn it is (`seat()`)
```
- Pushed, not asked: a crate changes its own fields when its settings load or change (several crates share the
look, each keeping to its fields), and the engine reads it where it draws (`game/look.rs`, the only reader).
Nothing is called per frame, and a seat nothing changed sees vanilla's.
- A knob is named by what it changes in the picture or the sound, never by the feature that uses it. A new knob
is a field added with vanilla's value as its default.
### Container screens (`horizon_platform::containers`)
Input and drawing on an open container screen (the inventory, chests, furnaces, crafting tables...), for the
extras that act on one: Mouse Tweaks and sorting (M5).
```rust
/// The open screen's menu, for the length of one call. The engine implements it.
pub trait Container {
fn menu(&self) -> &str; // "inventory", "minecraft:generic_9x3", "minecraft:furnace"...
fn slots(&self) -> Vec<Slot>; // every slot drawn, in the screen's order
fn stack(&mut self, slot: SlotId) -> Option<Stack>;
fn carried(&self) -> Option<Stack>; // the stack on the cursor
fn takes_one(&mut self, slot: SlotId, of: &Stack) -> bool; // the menu's rules: mayPlace, the slot's limit
fn landing(&mut self, slot: SlotId) -> Vec<SlotId>; // where quickMoveStack would put its items
fn click(&mut self, slot: SlotId, click: Click) -> bool; // one ordinary click, as vanilla sends it
fn spread(&self) -> usize; // the slots vanilla's quick craft drag covers now
fn cursor(&self) -> (f32, f32); // GUI pixels, from the panel's corner
fn shift(&self) -> bool;
fn order(&mut self, slot: SlotId) -> (u32, String); // the creative tabs' order and the shown name
}
pub struct SlotId(pub u32); // opaque, stable while the screen is open
pub struct Slot { pub id: SlotId, pub role: Role, pub x: f32, pub y: f32 } // top left, from the panel's corner
pub enum Role { Hotbar, Inventory, Storage, Input, Result, Equipment, Other } // a crafting grid is Input
pub struct Stack { pub item: String, pub count: u32, pub max: u32, pub kind: u64 } // kind: equal for the same item and components
pub enum Click { Pick { right: bool }, QuickMove, Put { one: bool } } // Put: a one-slot QUICK_CRAFT drag
// In `Hooks`, each `false` (or nothing) by default, so vanilla's handling runs:
fn container_press(&self, c: &mut dyn Container, slot: Option<SlotId>, right: bool) -> bool;
fn container_drag(&self, c: &mut dyn Container, slot: Option<SlotId>) -> bool; // the cursor moved, a button held
fn container_release(&self, c: &mut dyn Container);
fn container_wheel(&self, c: &mut dyn Container, slot: Option<SlotId>, steps: f32) -> bool;
fn container_key(&self, c: &mut dyn Container, slot: Option<SlotId>, key: &str) -> bool; // `key.keyboard.r`, `key.mouse.middle`
fn container_draw(&self, c: &dyn Container, canvas: &mut dyn hud::Canvas); // over the panel, from its corner
```
- `true` means the hook took the input: vanilla's press, drag or wheel doesn't run, and a press or drag taken
ends vanilla's quick craft drag, as Mouse Tweaks' right-drag replaces it. Every hook hears `release`. The
first hook that returns `true` wins.
- Each `click` is an ordinary slot click: the menu engine's on the player's own world, a `ContainerClick` on a
server. So an extra built on it works wherever vanilla's clicks do, and anticheats see vanilla's packets.
- The engine offers every menu screen's slots; the crate decides which menus it acts in, by `menu()` (Mouse
Tweaks stays out of those whose slots cost or trigger something: anvils, enchanting, merchants, beacons,
crafters). Creative's tabs are no container screen.
- The reads that ask the menu's rules take `&mut self`, as the engine's do; drawing gets `&dyn Container`,
so it reads the rest only.
- The engine builds a `Container` only when a hook is registered and a container screen gets input or draws.
Without one there is no cost, and vanilla's handling is unchanged.
- `order` is the only text: Sorting ranks by it. The rest is ids and numbers, so the API names no engine type
(`ItemStack` stays in the engine).
## Extras that may leave the game
Horizon's extras are Horizon-layer code. Each one is a candidate to become an optional native mod that players add
+8 -14
View File
@@ -2,9 +2,9 @@
Horizon signs players in with their Microsoft account in the launcher and joins online-mode
(authenticated) servers like vanilla 26.3 does. The launcher plays only with an account that owns
Minecraft: Java Edition ([the owner gate](#the-owner-gate)), as that account, on LAN and
offline-mode servers too. There are no offline names. This note is the design, the status of each
part and what Ludovic has to register.
Minecraft: Java Edition ([the owner gate](#the-owner-gate)); offline names, LAN and offline-mode
servers play behind it. This note is the design, the status of each part and what Ludovic has to
register.
## What Ludovic registers (needs his accounts)
@@ -87,7 +87,7 @@ possible; the launcher just doesn't offer it on its own.
says "Sign in with a Microsoft account that owns Minecraft: Java Edition to play", with Sign in.
- **The window says it once.** A player without an owner (one who played offline until now) sees
the gate's screen once when the launcher opens: why Horizon needs the account ("like other
launchers"), and Sign in, which shows
launchers"), that worlds, offline names and settings stay where they are, and Sign in, which shows
the device code on the same screen. It comes back whenever Play is refused; Not now closes it,
and Home keeps a Sign in row (`launcher/src/owner_page.rs`).
- **The answer lives with the tokens.** Each account's keychain item keeps the last answer
@@ -96,13 +96,8 @@ possible; the launcher just doesn't offer it on its own.
`secret-tool` or Keychain Access. With no network (or a sign-in that can't be renewed) the
last answer stands: being offline never blocks a player who passed before, and the game starts
without a session, offline. An answer of "doesn't own" (or no profile) blocks at once.
- **The account that plays owns the game.** The game plays as the selected account (else the
first), which must own the game itself: another account's ownership doesn't let it play
(`account::launch_for_game`). The project decided on 2026-11-09 that Horizon plays only with a
Microsoft account that owns Minecraft: Java Edition: the offline names, their skins and capes,
and 0.2.58's hidden developer option are gone. Files from older launchers still load; the next
save drops them (`offline`, `offline_selected`, `looks` and `skins/` in accounts.json's folder,
`dev_offline` in settings.json).
- **Offline names play behind an owner.** They can be added and played only while an owning
account is signed in. Signing the last one out keeps them, and they play again once one is back.
- **Who isn't affected:** the game binary itself (`horizon-client`, `horizon-ctl launch`, the
harnesses, CI), the dedicated server and `horizon-server`, the website. There is no bypass flag:
the launcher's tests use accounts in a memory store (`MemoryStore`, and `HORIZON_NO_KEYCHAIN`
@@ -235,7 +230,7 @@ Progress is public metadata and does not expose credentials through the UI or MC
name the expected player. Signing in to a different account is rejected before storing its
credentials or adding/selecting that identity. Retry keeps the same target; Cancel leaves the
saved account alone. Successful re-sign-in restores that account without changing the player
currently selected for Play. Adding a new account remains a separate action.
or offline name currently selected for Play. Adding a new account remains a separate action.
## Handing the session to the game
@@ -292,8 +287,7 @@ Code: `horizon-protocol` (`rsa.rs`, `crypto::server_hash`), `horizon-client` (`a
Horizon's dedicated server verifies players when `online-mode=true`. A LAN or Play with Friends world
verifies its guests when the host is signed in, as vanilla's `IntegratedServer` does
(`OnlineMode::lan`); started without a session (the services couldn't be reached at Play) it
stays offline-mode. The host's own player joins through
(`OnlineMode::lan`); under an offline name it stays offline-mode. The host's own player joins through
memory and is never asked to authenticate.
`HORIZON_API_DISCOVERY` overrides the discovery URL, the counterpart of authlib's
+2 -2
View File
@@ -115,8 +115,8 @@ run at once there, and each must finish within 10 seconds however slowly its byt
Like LAN, and like vanilla's `IntegratedServer`: a host signed in with a Microsoft account runs the world
in online mode, so each guest signs in through Mojang's session servers and arrives with their own
UUID, skin and cape. A host playing without a session (the services couldn't be reached at Play) runs it in
offline mode, where a guest joins with the name their game uses. Either way the host's own profile is reserved. Every tunnelled guest
UUID, skin and cape. A host playing under an offline name runs it in offline mode, where a guest joins
with the name their game uses. Either way the host's own profile is reserved. Every tunnelled guest
reaches the integrated server from `127.0.0.1`.
## Relays (optional)
+19 -7
View File
@@ -160,11 +160,15 @@ The opening, then Play ([clip](docs/opening.webm)):
(`horizon_launcher::shortcut`). **Remove shortcut** moves it to the trash; it is found by the
instance id inside it, so a rename doesn't lose it. `horizon-launcher instance shortcut
[instance] [--remove]`; `HORIZON_LAUNCHER_DESKTOP` points it at another folder.
- **Accounts and quick switch**: the top bar's account chip opens a menu of the signed-in
Microsoft accounts. Picking one plays as it from the next Play; that account must own the game
([Microsoft accounts](#microsoft-accounts)). There are no offline names: the project decided
that Horizon plays only with a Microsoft account that owns Minecraft: Java Edition. The
Console's Share log takes the account names out of the log. `horizon-launcher account select
- **Accounts and quick switch**: the top bar's account chip opens a menu of everyone who can play:
each signed-in Microsoft account, the offline names the player keeps, and the name the game
made up (`horizon-player.txt`). Picking one plays as it from the next Play. Offline names play
only while an account that owns the game is signed in ([Microsoft accounts](#microsoft-accounts));
signing the last one out keeps them, unplayable until one is back. Settings > Account
adds offline names (3 to 16 letters, digits or `_`; the game gets `--name`) and forgets them,
skin and cape files included, and rolls the game's made-up name for a new one; the Console's
Share log takes the names out of the log too. `horizon-launcher account offline
[NAME]`, `account select <name>` (an account or an offline name), `account forget-offline
<name>`.
- **Accent and Home background**: on top of Dark, Light or System, Settings > Launcher picks an
accent (Horizon's violet, blue, teal, green, amber, red or pink, any hue, or any colour typed as
@@ -181,6 +185,13 @@ The opening, then Play ([clip](docs/opening.webm)):
`launcher/lang/<code>.json`, English text to its translation, Horizon's own; a test fails when
the code asks `tr("…")` for a string a table lacks, or a table keeps one the code dropped.
`horizon-launcher settings language system|en|fr|ru|de|zh|es|uk|pl`.
- **Skin and cape**: each offline name's **Skin…** in Settings > Account shows the front of its
skin and cape, takes a skin PNG (64×64, or the older 64×32) and a cape PNG (64×32), and picks
classic or slim arms. The launcher keeps copies in its `skins/` folder and gives the game
`HORIZON_OFFLINE_SKIN`, `HORIZON_OFFLINE_SKIN_MODEL` and `HORIZON_OFFLINE_CAPE` when that name
plays; the game draws the default skins until it reads them. A Microsoft account's skin and
cape: coming soon, with sign-in. `horizon-launcher account skin <name> [FILE] [--model
classic|slim] [--cape FILE] [--no-skin] [--no-cape]`.
- **Console**: Home's Console shows the game's output of this run as it comes: a search (every
word, any case), Follow to keep the newest line in view, Copy, and Open logs folder. Warnings
and errors stand out. **Share log…** uploads the log to [mclo.gs](https://mclo.gs), a paste
@@ -388,6 +399,7 @@ and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code
horizon-launcher account sign-in sign in in your browser with a code
horizon-launcher account sign-out <name>
horizon-launcher account select <name> play as this account
horizon-launcher account offline play without an account
horizon-launcher instance [list] the instances and their game folders (* = Play starts it)
horizon-launcher instance create <name> [--copy <instance>] empty, or a copy of one's worlds, options and packs
horizon-launcher instance create <name> --minecraft <1.21.4|latest|latest-snapshot> a Minecraft: Java Edition instance
@@ -480,8 +492,8 @@ MCP's `play`) says "Sign in with a Microsoft account that owns Minecraft: Java E
and starts nothing. Settings → Accounts signs in: the launcher shows a code, you enter it at
microsoft.com/link, and the launcher checks that the account owns the game. It asks again at every
Play, with the token renewal; with no network the last answer stands, and a "doesn't own" blocks
at once. The account that plays must own the game itself, and it plays online-mode servers under
your own name and skin, LAN and offline-mode servers too. The game binary started directly (`horizon-client`,
at once. The account also plays online-mode servers under your own name and skin; offline names
play LAN and offline-mode servers beside it. The game binary started directly (`horizon-client`,
`horizon-ctl launch`), the harnesses and the servers don't go through this check. Tokens live in the system keychain (Keychain,
Credential Manager, or the Secret Service on Linux), never in a log or the command line;
`accounts.json` in the data folder keeps only names and UUIDs. On Linux without a keychain they go
+28
View File
@@ -37,6 +37,7 @@
"Building {name}'s post-build step": "Bou van {name} se na-bou-stap",
"In use": "In gebruik",
"Prepare": "Berei voor",
"Developer options": "Ontwikkelaar opsies",
"{online} of {max} players": "{online} van {max} spelers",
"Minecraft {version} (Java Edition). Play downloads it from Mojang for your account the first time, with the Java it needs.": "Minecraft {version} (Java-uitgawe). Play laai dit die eerste keer van Mojang af vir jou rekening, met die Java wat dit nodig het.",
"Close": "Maak toe",
@@ -97,6 +98,7 @@
"From my install": "Van my installasie",
"the update failed: {error}": "die opdatering het misluk: {error}",
"Mesa's DRI_PRIME=1, so Vulkan picks the other card.": "Mesa se DRI_PRIME=1, so Vulkan kies die ander kaart.",
"New name": "Nuwe naam",
"Dark": "Donker",
"Not now": "Nie nou nie",
"Use an access token…": "Gebruik 'n toegangtoken...",
@@ -113,6 +115,7 @@
"Partly": "Gedeeltelik",
"All": "Almal",
"Instance": "Instansie",
"Classic arms": "Klassieke arms",
"Versions": "Weergawes",
"Release build: slower to build, slightly faster game": "Vrystelling bou: stadiger om te bou, effens vinniger spel",
"Performance build": "Prestasiebou",
@@ -169,6 +172,7 @@
"about a minute left": "omtrent 'n minuut oor",
"Cancel": "Kanselleer",
"Add to {client}": "Voeg by {client}",
"Skin…": "Vel…",
"Environment": "Omgewing",
"They often still work together. If the build fails, install versions made for the same Nightly.": "Hulle werk dikwels nog saam. As die bou misluk, installeer weergawes wat vir dieselfde Nightly gemaak is.",
"Import an instance folder…": "Voer 'n instansievouer in …",
@@ -180,6 +184,7 @@
"newest stable version": "nuutste stabiele weergawe",
"Choose image…": "Kies prent …",
"No worlds yet: they appear here once you play one.": "Nog geen wêrelde nie: hulle verskyn hier sodra jy een speel.",
"Offline names play without a Microsoft account that owns the game. Minecraft still comes from your own install.": "Vanlyn name speel sonder 'n Microsoft-rekening wat die speletjie besit. Minecraft kom steeds van jou eie installasie af.",
"crash reports beside it": "ineenstortingsverslae langsaan",
"Install all": "Installeer alles",
"No group": "Geen groep nie",
@@ -197,6 +202,7 @@
"My instance": "My voorbeeld",
"Snapshot": "Momentopname",
"Gallery": "Galery",
"Offline name": "Vanlyn naam",
"Home": "Tuis",
"Stopping": "Besig om te stop",
"MSPT · tick time": "MSPT · tiktyd",
@@ -298,6 +304,8 @@
"Patch notes": "Patch notas",
"Your Minecraft server, {online}.": "Jou Minecraft-bediener, {online}.",
"Crash reports": "Ineenstortingsverslae",
"Offline name · the game's own · plays": "Vanlyn naam · die speletjie se eie · speel",
"Slim arms": "Skraal arms",
"Asking GitHub about {owner}/{repo}…": "Vra GitHub oor {owner}/{repo}...",
"Downloading Minecraft {version} from Mojang · {done} of {total} files": "Laai tans Minecraft {version} af vanaf Mojang · {done} van {total} lêers",
"Could not save your choice: {error}": "Kon nie jou keuse stoor nie: {error}",
@@ -346,6 +354,7 @@
"Horizon's landscape. Pick a PNG, JPEG or WebP picture of your own.": "Horizon se landskap. Kies 'n eie PNG-, JPEG- of WebP-prent.",
"Not needed": "Nie nodig nie",
"This build of the launcher has no Microsoft sign-in (HORIZON_MSA_CLIENT_ID), so it can't start the game.": "Hierdie bou van die lanseerder het geen Microsoft-aanmelding nie (HORIZON_MSA_CLIENT_ID), so dit kan nie die speletjie begin nie.",
"Offline name · plays": "Vanlyn naam · speel",
"Run the game through": "Begin die speletjie deur",
"needed by another pack": "benodig deur 'n ander pakkie",
"Older →": "Ouer →",
@@ -356,10 +365,13 @@
"Could not run {program}: {error}": "Kon nie {program}: {error} laat loop nie",
"Restart": "Herbegin",
"Copied to the clipboard.": "Gekopieer na die knipbord.",
"Your worlds, offline names and settings stay where they are.": "Jou wêrelde, vanlyn name en instellings bly waar hulle is.",
"Send nothing": "Stuur niks",
"Move to Trash": "Skuif na asblik",
"Start from": "Begin vanaf",
"Asking Mojang for its versions…": "Vra Mojang vir sy weergawes ...",
"A 64×64 (or 64×32) skin PNG and a 64×32 cape PNG, kept by the launcher and given to the game when this name plays. The game draws the default skins for now; it uses these once it can. A Microsoft account's skin and cape: coming soon.": "'n 64×64 (of 64×32) vel PNG en 'n 64×32 cape PNG, gehou deur die lanseerder en aan die speletjie gegee wanneer hierdie naam speel. Die speletjie teken die verstekvelle vir nou; dit gebruik dit sodra dit kan. 'n Microsoft-rekening se vel en mantel: binnekort.",
"Play offline under another name, and switch from the top bar. Online servers don't take offline names.": "Speel vanlyn onder 'n ander naam, en skakel van die boonste balk af. Aanlyn bedieners neem nie vanlyn name nie.",
"Report on Discord": "Verslag oor Discord",
"Export": "Uitvoer",
"Server": "Bediener",
@@ -372,6 +384,7 @@
"No version installed yet.": "Nog geen weergawe geïnstalleer nie.",
"Release": "Vrystelling",
"Verified": "Geverifieer",
"Choose a skin…": "Kies 'n vel...",
"{instance} doesn't play its native mods yet: build the game with them.": "{instance} speel nog nie sy oorspronklike mods nie: bou die speletjie daarmee.",
"Use jars from my instance…": "Gebruik potte uit my instansie...",
"Applications menu": "Toepassings-kieslys",
@@ -395,6 +408,7 @@
"Open backups": "Maak rugsteun oop",
"The game is running: change packs in its own menus, or here once it is closed.": "Die speletjie is aan die gang: verander pakke in sy eie spyskaarte, of hier sodra dit gesluit is.",
"Check now": "Kyk nou",
"Choose a cape…": "Kies 'n kaap...",
"Save": "Stoor",
"Folder": "Vouer",
"Searching…": "Soek tans …",
@@ -408,6 +422,7 @@
"MangoHud": "MangoHud",
"Sign out": "Meld af",
"When it starts": "Wanneer dit begin",
"{name}'s skin": "{name} se vel",
"Start": "Begin",
"No Minecraft install needed: Horizon downloads it from Mojang for your account.": "Geen Minecraft-installasie nodig nie: Horizon laai dit van Mojang af vir jou rekening.",
"Logs": "Logs",
@@ -431,6 +446,7 @@
"The wordmark, while the release list loads.": "Die woordmerk, terwyl die vrystellinglys laai.",
"Playing offline": "Speel tans vanlyn",
"Sign in to Tailscale": "Meld aan by Tailscale",
"Offline names without an account": "Vanlyn name sonder 'n rekening",
"Help make Horizon faster and steadier?": "Help om Horizon vinniger en bestendiger te maak?",
"Sign in to play": "Meld aan om te speel",
"Ported": "Geplaas",
@@ -472,12 +488,14 @@
"Update this launcher with your package manager.": "Dateer hierdie lanseerder op met jou pakketbestuurder.",
"Close this launcher, move it to {folder}, and open it there to enable updates.": "Maak hierdie lanseerder toe, skuif dit na {folder} en maak dit daar oop om opdaterings te aktiveer.",
"Any MCP client": "Enige MCP-kliënt",
"{name}'s cape is kept.": "{name} se kaap word gehou.",
"Not reviewed by the Horizon registry": "Nie hersien deur die Horizon-register nie",
"Proxy": "Volmag",
"Checking": "Kontroleer",
"Updates": "Opdaterings",
"Asking Microsoft…": "Vra Microsoft …",
"Prepared for Minecraft {version}, without its sounds: the game will be silent. Prepare again to copy them from your Minecraft install.": "Voorbereid vir Minecraft {version}, sonder sy klanke: die speletjie sal stil wees. Berei weer voor om dit vanaf jou Minecraft-installasie te kopieer.",
"Forget": "Vergeet",
"Import a modpack…": "Voer 'n modpack in...",
"Search versions": "Soek weergawes",
"failed": "misluk",
@@ -486,6 +504,7 @@
"Left off: {line}.": "Opgehou: {line}.",
"Resource packs": "Hulpbronpakke",
"yesterday": "gister",
"No cape": "Geen mantel nie",
"After each session: frame-time percentiles and a 14-bucket histogram, tick times, peak memory and startup times, with your machine (OS, CPU and its cores and clocks, memory size, GPU, its memory and driver, drive type, screen size and refresh rate, laptop or desktop, on battery or not) and the settings that change performance.": "Na elke sessie: raam-tyd persentiele en 'n 14-emmer histogram, regmerkie tye, piek geheue en opstart tye, met jou masjien (OS, SVE en sy kerns en horlosies, geheue grootte, GPU, sy geheue en drywer, tipe skyf, skerm grootte en herlaaitempo, skootrekenaar of rekenaar, op battery of nie) en die instellings wat werkverrigting verander.",
"Make a token": "Maak 'n teken",
"Added {names}: the game turns it on when the world opens.": "Bygevoeg {names}: die speletjie skakel dit aan wanneer die wêreld oopgaan.",
@@ -538,6 +557,7 @@
"Shared: {url}": "Gedeel: {url}",
"Friends on the same Wi-Fi: Multiplayer, Add Server, then paste this address.": "Vriende op dieselfde Wi-Fi: Multiplayer, Voeg bediener by, plak dan hierdie adres.",
"None yet: drop a .hshader or a shader pack .zip here.": "Nog geen: gooi 'n .hshader- of 'n shader-pak .zip hier.",
"Offline name · the game's own": "Vanlyn naam · die speletjie se eie",
"Native mods aren't sandboxed: they run with full access to your computer, like any program. Install only mods whose authors you trust. To play with one, build the game on the Mods page; the first build downloads Rust and takes 20 to 30 minutes.": "Inheemse mods is nie sandboxed nie: hulle loop met volle toegang tot jou rekenaar, soos enige program. Installeer slegs mods wie se skrywers jy vertrou. Om met een te speel, bou die speletjie op die Mods-bladsy; die eerste bou laai Rust af en neem 20 tot 30 minute.",
"Your selected version only changes if you were playing the newest one.": "Jou gekose weergawe verander net as jy die nuutste een gespeel het.",
"Multiplayer": "Multispeler",
@@ -567,6 +587,7 @@
"the port": "die hawe",
"The source of {source}. Its release ships {file}, a content mod: installing those from GitHub is not supported yet.": "Die bron van {source}. Die vrystelling daarvan stuur {file}, 'n inhoudmodi: installering van dié vanaf GitHub word nog nie ondersteun nie.",
"Build anyway": "Bou in elk geval",
"A name, 3 to 16 letters": "'n Naam, 3 tot 16 letters",
"Installed {mods} from GitHub ({source}). Build it on the Mods page.": "Geïnstalleer {mods} vanaf GitHub ({source}). Bou dit op die Mods-bladsy.",
"Settings, Keys, Generate access token. It's kept in this computer's keychain and only sent to Tailscale.": "Instellings, Sleutels, Genereer toegangtoken. Dit word in hierdie rekenaar se sleutelhouer gehou en net na Tailscale gestuur.",
"{id} is up to date.": "{id} is op datum.",
@@ -581,6 +602,7 @@
"I read it and trust it: install": "Ek lees dit en vertrou dit: installeer",
"Close export": "Maak uitvoer toe",
"Playing needs a prepared Horizon version (Play page).": "Speel benodig 'n voorbereide Horizon-weergawe (Speelbladsy).",
"Offline, the game's name": "Vanlyn, die speletjie se naam",
"From Horizon's registry": "Van Horizon se register",
"Sounds": "Klanke",
"Edit…": "Wysig …",
@@ -613,10 +635,12 @@
"up to date": "op datum",
"← Newer": "← Nuwer",
"Downloading from Mojang · {done} of {total} files": "Laai tans af vanaf Mojang · {done} van {total} lêers",
"{name}'s skin is kept.": "{name} se vel word behou.",
"Edit instance": "Wysig instansie",
"Remove shortcut": "Verwyder kortpad",
"{program} is not installed here (or not on the PATH): copy the config instead.": "{program} is nie hier geïnstalleer nie (of nie op die PATH): kopieer eerder die konfigurasie.",
"No worlds to put in.": "Geen wêrelde om in te plaas nie.",
"Default skin": "Standaard vel",
"A link to a repository (its latest release), a release, a branch or tag, or a commit. The launcher installs one exact release file or commit, never a branch that moves.": "'n Skakel na 'n bewaarplek (die jongste vrystelling daarvan), 'n vrystelling, 'n tak of merker, of 'n commit. Die lanseerder installeer een presiese vrystellinglêer of commit, nooit 'n tak wat beweeg nie.",
"Sign in with GitHub to rate": "Meld aan met GitHub om te gradeer",
"Star on GitHub": "Gee 'n ster op GitHub",
@@ -1029,6 +1053,10 @@
"played by {names}": "gespeel deur {names}",
"{day}, {time} UTC": "{day}, {time} UTC",
"Microsoft account · online servers too": "Microsoft-rekening · ook aanlyn bedieners",
"Offline · single player and LAN worlds": "Vanlyn · enkelspeler- en LAN-wêrelde",
"Offline names": "Vanlyn name",
"Add a name": "Voeg 'n naam by",
"3 to 16 letters, numbers or underscores. Switch names from the top bar too. Online servers don't take offline names.": "3 tot 16 letters, syfers of onderstrepe. Verander ook name vanaf die boonste balk. Aanlyn bedieners neem nie vanlyn name nie.",
"Play online with your Microsoft account": "Speel aanlyn met jou Microsoft-rekening",
"Sign in with the account that owns Minecraft: Java Edition. Your name and skin come along to online servers, like in other launchers.": "Meld aan met die rekening wat Minecraft: Java Edition besit. Jou naam en vel kom saam na aanlyn bedieners, soos in ander lanseerders.",
"Microsoft's own page opens in your browser. Horizon never sees your password.": "Microsoft se eie bladsy maak in jou blaaier oop. Horizon sien nooit jou wagwoord nie.",
+28
View File
@@ -37,6 +37,7 @@
"Building {name}'s post-build step": "خطوة ما بعد البناء لـ {name}",
"In use": "قيد الاستخدام",
"Prepare": "تحضير",
"Developer options": "خيارات المطور",
"{online} of {max} players": "{online} من {max} لاعبين",
"Minecraft {version} (Java Edition). Play downloads it from Mojang for your account the first time, with the Java it needs.": "ماين كرافت {version} (إصدار جافا). يقوم الزر \"تشغيل\" بتنزيلها من موجانج لحسابك في المرة الأولى، مع إصدار جافا الذي تحتاجه.",
"Close": "إغلاق",
@@ -97,6 +98,7 @@
"From my install": "من تثبيتي الخاص",
"the update failed: {error}": "فشل التحديث: {error}",
"Mesa's DRI_PRIME=1, so Vulkan picks the other card.": "خاصية DRI_PRIME=1 في Mesa، لكي يختار Vulkan البطاقة الأخرى.",
"New name": "اسم جديد",
"Dark": "داكن",
"Not now": "ليس الآن",
"Use an access token…": "استخدام رمز وصول…",
@@ -113,6 +115,7 @@
"Partly": "جزئيًا",
"All": "الكل",
"Instance": "نسخة (Instance)",
"Classic arms": "أذرع كلاسيكية",
"Versions": "الإصدارات",
"Release build: slower to build, slightly faster game": "إصدار رسمي: أبطأ في البناء، وأسرع قليلاً في اللعبة",
"Performance build": "إصدار الأداء",
@@ -169,6 +172,7 @@
"about a minute left": "متبقي حوالي دقيقة",
"Cancel": "إلغاء",
"Add to {client}": "إضافة إلى {client}",
"Skin…": "المظهر (Skin)…",
"Environment": "البيئة",
"They often still work together. If the build fails, install versions made for the same Nightly.": "غالبًا ما تستمر في العمل معًا. إذا فشل البناء، قم بتثبيت الإصدارات المصنوعة لنفس نسخة Nightly.",
"Import an instance folder…": "استيراد مجلد نسخة…",
@@ -180,6 +184,7 @@
"newest stable version": "أحدث إصدار مستقر",
"Choose image…": "اختر صورة…",
"No worlds yet: they appear here once you play one.": "لا توجد عوالم حتى الآن: ستظهر هنا بمجرد لعب أحدها.",
"Offline names play without a Microsoft account that owns the game. Minecraft still comes from your own install.": "تتيح الأسماء غير المتصلة اللعب بدون حساب مايكروسوفت يمتلك اللعبة. لا تزال ماين كرافت تأتي من تثبيتك الخاص.",
"crash reports beside it": "تقارير الأعطال بجانبها",
"Install all": "تثبيت الكل",
"No group": "بدون مجموعة",
@@ -197,6 +202,7 @@
"My instance": "نسختي",
"Snapshot": "نسخة تجريبية",
"Gallery": "المعرض",
"Offline name": "اسم غير متصل",
"Home": "الرئيسية",
"Stopping": "جاري الإيقاف",
"MSPT · tick time": "MSPT · وقت التكتكة",
@@ -299,6 +305,8 @@
"Patch notes": "ملاحظات الإصدار",
"Your Minecraft server, {online}.": "خادم ماين كرافت الخاص بك، {online}.",
"Crash reports": "تقارير الأعطال",
"Offline name · the game's own · plays": "اسم غير متصل · الخاص باللعبة · يلعب",
"Slim arms": "أذرع نحيفة",
"Asking GitHub about {owner}/{repo}…": "جاري الاستعلام من جيت هاب عن {owner}/{repo}…",
"Downloading Minecraft {version} from Mojang · {done} of {total} files": "جاري تنزيل ماين كرافت {version} من موجانج · {done} من {total} ملفات",
"Could not save your choice: {error}": "تعذر حفظ اختيارك: {error}",
@@ -347,6 +355,7 @@
"Horizon's landscape. Pick a PNG, JPEG or WebP picture of your own.": "خلفية هورايزون الأفقية. اختر صورة بصيغة PNG أو JPEG أو WebP خاصة بك.",
"Not needed": "غير مطلوب",
"This build of the launcher has no Microsoft sign-in (HORIZON_MSA_CLIENT_ID), so it can't start the game.": "هذا الإصدار من المشغل لا يحتوي على ميزة تسجيل دخول مايكروسوفت (HORIZON_MSA_CLIENT_ID)، لذا لا يمكنه بدء اللعبة.",
"Offline name · plays": "اسم غير متصل · يلعب",
"Run the game through": "تشغيل اللعبة عبر",
"needed by another pack": "مطلوب بواسطة حزمة أخرى",
"Older →": "الأقدم ←",
@@ -357,10 +366,13 @@
"Could not run {program}: {error}": "تعذر تشغيل {program}: {error}",
"Restart": "إعادة التشغيل",
"Copied to the clipboard.": "تم النسخ إلى الحافظة.",
"Your worlds, offline names and settings stay where they are.": "عوالمك وأسماؤك غير المتصلة وإعداداتك تبقى كما هي.",
"Send nothing": "لا تقم بإرسال أي شيء",
"Move to Trash": "نقل إلى سلة المهملات",
"Start from": "البدء من",
"Asking Mojang for its versions…": "جاري طلب الإصدارات من موجانج…",
"A 64×64 (or 64×32) skin PNG and a 64×32 cape PNG, kept by the launcher and given to the game when this name plays. The game draws the default skins for now; it uses these once it can. A Microsoft account's skin and cape: coming soon.": "صورة مظهر (Skin) بصيغة PNG بدقة 64×64 (أو 64×32) وصورة رداء (Cape) بدقة 64×32، يتم الاحتفاظ بهما بواسطة المشغل وتمريرهما للعبة عند اللعب بهذا الاسم. ترسم اللعبة المظاهر الافتراضية في الوقت الحالي؛ وستستخدم هذه المظاهر فور إمكانية ذلك. مظهر ورداء حساب مايكروسوفت: قريباً.",
"Play offline under another name, and switch from the top bar. Online servers don't take offline names.": "العب بلا اتصال تحت اسم آخر، وقم بالتبديل من الشريط العلوي. لا تقبل خوادم الإنترنت الأسماء غير المتصلة.",
"Report on Discord": "الإبلاغ على ديسكورد",
"Export": "تصدير",
"Server": "خادم",
@@ -373,6 +385,7 @@
"No version installed yet.": "لم يتم تثبيت أي إصدار بعد.",
"Release": "إصدار رسمي",
"Verified": "مُتحقق منه",
"Choose a skin…": "اختر مظهراً (Skin)…",
"{instance} doesn't play its native mods yet: build the game with them.": "{instance} لا يشغل تعديلاته الأصلية بعد: قم ببناء اللعبة معها.",
"Use jars from my instance…": "استخدام ملفات Jars من نسختي…",
"Applications menu": "قائمة التطبيقات",
@@ -396,6 +409,7 @@
"Open backups": "فتح النسخ الاحتياطية",
"The game is running: change packs in its own menus, or here once it is closed.": "اللعبة قيد التشغيل: قم بتغيير الحزم من قوائمها الداخلية، أو هنا بمجرد إغلاقها.",
"Check now": "تحقق الآن",
"Choose a cape…": "اختر رداءً (Cape)…",
"Save": "حفظ",
"Folder": "المجلد",
"Searching…": "جاري البحث…",
@@ -409,6 +423,7 @@
"MangoHud": "MangoHud",
"Sign out": "تسجيل الخروج",
"When it starts": "عند البدء",
"{name}'s skin": "مظهر {name}",
"Start": "بدء",
"No Minecraft install needed: Horizon downloads it from Mojang for your account.": "لا حاجة لتثبيت ماين كرافت: يقوم هورايزون بتنزيلها من موجانج لحسابك.",
"Logs": "السجلات",
@@ -432,6 +447,7 @@
"The wordmark, while the release list loads.": "شعار الاسم أثناء تحميل قائمة الإصدارات.",
"Playing offline": "اللعب بدون اتصال",
"Sign in to Tailscale": "تسجيل الدخول إلى Tailscale",
"Offline names without an account": "أسماء غير متصلة بدون حساب",
"Help make Horizon faster and steadier?": "هل تريد المساعدة في جعل هورايزون أسرع وأكثر استقرارًا؟",
"Sign in to play": "تسجيل الدخول للعب",
"Ported": "منقولة",
@@ -474,12 +490,14 @@
"Update this launcher with your package manager.": "حدّث هذا المشغّل باستخدام مدير الحزم.",
"Close this launcher, move it to {folder}, and open it there to enable updates.": "أغلق هذا المشغّل، وانقله إلى {folder}، ثم افتحه من هناك لتمكين التحديثات.",
"Any MCP client": "أي عميل MCP",
"{name}'s cape is kept.": "تم الاحتفاظ برداء {name}.",
"Not reviewed by the Horizon registry": "لم يتم مراجعته من قِبل سجل هورايزون",
"Proxy": "الوكيل (Proxy)",
"Checking": "جاري التحقق",
"Updates": "التحديثات",
"Asking Microsoft…": "جاري السؤال مايكروسوفت…",
"Prepared for Minecraft {version}, without its sounds: the game will be silent. Prepare again to copy them from your Minecraft install.": "تم التجهيز لماين كرافت {version} بدون أصوات: ستكون اللعبة صامتة. قم بالتجهيز مرة أخرى لنسخها من تثبيت ماين كرافت الخاص بك.",
"Forget": "نسيان",
"Import a modpack…": "استيراد حزمة تعديلات…",
"Search versions": "البحث في الإصدارات",
"failed": "فشل",
@@ -488,6 +506,7 @@
"Left off: {line}.": "التوقف عند السطر: {line}.",
"Resource packs": "حزم الموارد",
"yesterday": "أمس",
"No cape": "بدون رداء",
"After each session: frame-time percentiles and a 14-bucket histogram, tick times, peak memory and startup times, with your machine (OS, CPU and its cores and clocks, memory size, GPU, its memory and driver, drive type, screen size and refresh rate, laptop or desktop, on battery or not) and the settings that change performance.": "بعد كل جلسة: النسب المئوية لأوقات الإطارات ومخطط بياني بـ 14 فئة، وأوقات التكتكة، وذروة الذاكرة وأوقات البدء، مع مواصفات جهازك (نظام التشغيل، المعالج وأنويته وسرعاته، حجم الذاكرة، بطاقة الرسوميات وذاكرتها وتعريفها، نوع القرص، حجم الشاشة ومعدل التحديث، ما إذا كان لابتوب أو جهاز مكتبياً، ويعمل على البطارية أم لا) والإعدادات التي تغير الأداء.",
"Make a token": "إنشاء رمز وصول (Token)",
"Added {names}: the game turns it on when the world opens.": "تمت إضافة {names}: تفعل اللعبة ذلك تلقائيًا عند فتح العالم.",
@@ -540,6 +559,7 @@
"Shared: {url}": "تمت المشاركة: {url}",
"Friends on the same Wi-Fi: Multiplayer, Add Server, then paste this address.": "الأصدقاء على نفس شبكة الواي فاي: اللعب الجماعي > إضافة خادم، ثم الصق هذا العنوان.",
"None yet: drop a .hshader or a shader pack .zip here.": "لا شيء بعد: اسحب ملف .hshader أو حزمة تظليل بصيغة .zip وأفلتها هنا.",
"Offline name · the game's own": "اسم غير متصل · الخاص باللعبة",
"Native mods aren't sandboxed: they run with full access to your computer, like any program. Install only mods whose authors you trust. To play with one, build the game on the Mods page; the first build downloads Rust and takes 20 to 30 minutes.": "التعديلات الأصلية ليست معزولة في بيئة آمنة (Sandboxed): فهي تعمل بصلاحيات كاملة على جهازك، مثل أي برنامج. ثبت فقط التعديلات التي تثق بمؤلفيها. للعب بها، قم ببناء اللعبة من صفحة التعديلات؛ يتطلب البناء الأول تنزيل لغة Rust ويستغرق من 20 إلى 30 دقيقة.",
"Your selected version only changes if you were playing the newest one.": "يتغير إصدارك المحدد فقط إذا كنت تلعب بالأحدث.",
"Multiplayer": "اللعب الجماعي",
@@ -569,6 +589,7 @@
"the port": "المنفذ",
"The source of {source}. Its release ships {file}, a content mod: installing those from GitHub is not supported yet.": "مصدر {source}. يحتوي إصداره على {file}، وهو تعديل محتوى: تثبيت هذه التعديلات من جيت هاب غير مدعوم بعد.",
"Build anyway": "البناء على أي حال",
"A name, 3 to 16 letters": "اسم، من 3 إلى 16 حرفًا",
"Installed {mods} from GitHub ({source}). Build it on the Mods page.": "تم تثبيت {mods} من جيت هاب ({source}). قم ببنائه في صفحة التعديلات.",
"Settings, Keys, Generate access token. It's kept in this computer's keychain and only sent to Tailscale.": "الإعدادات (Settings) > المفاتيح (Keys) > إنشاء رمز وصول (Generate access token). يتم الاحتفاظ به في سلسلة مفاتيح هذا الكمبيوتر وإرساله إلى Tailscale فقط.",
"{id} is up to date.": "{id} محدث لأحدث نسخة.",
@@ -583,6 +604,7 @@
"I read it and trust it: install": "لقد قرأته وأثق به: تثبيت",
"Close export": "إغلاق التصدير",
"Playing needs a prepared Horizon version (Play page).": "يتطلب اللعب وجود إصدار مجهز من هورايزون (صفحة اللعب).",
"Offline, the game's name": "غير متصل، اسم اللعبة",
"From Horizon's registry": "من سجل هورايزون الخاص",
"Sounds": "الأصوات",
"Edit…": "تعديل…",
@@ -615,10 +637,12 @@
"up to date": "محدث",
"← Newer": "← الأحدث",
"Downloading from Mojang · {done} of {total} files": "جاري التنزيل من موجانج · {done} من {total} ملفات",
"{name}'s skin is kept.": "تم الاحتفاظ بمظهر {name}.",
"Edit instance": "تعديل النسخة",
"Remove shortcut": "إزالة الاختصار",
"{program} is not installed here (or not on the PATH): copy the config instead.": "{program} غير مثبت هنا (أو غير مدرج في المسار PATH): انسخ ملف التكوين بدلاً من ذلك.",
"No worlds to put in.": "لا توجد عوالم لإضافتها.",
"Default skin": "المظهر الافتراضي",
"A link to a repository (its latest release), a release, a branch or tag, or a commit. The launcher installs one exact release file or commit, never a branch that moves.": "رابط إلى مستودع (أحدث إصدار له)، أو إصدار، أو فرع (Branch)، أو علامة (Tag)، أو التزام (Commit). يقوم المشغل بتثبيت ملف إصدار أو التزام محدد تمامًا، ولا يثبت فرعًا متغيرًا.",
"Sign in with GitHub to rate": "سجل الدخول بواسطة جيت هاب للتقييم",
"Star on GitHub": "أضف نجمة على GitHub",
@@ -1031,6 +1055,10 @@
"played by {names}": "يلعبه {names}",
"{day}, {time} UTC": "{day}، {time} UTC",
"Microsoft account · online servers too": "حساب Microsoft · الخوادم عبر الإنترنت أيضًا",
"Offline · single player and LAN worlds": "دون اتصال · اللعب الفردي وعوالم الشبكة المحلية",
"Offline names": "أسماء دون اتصال",
"Add a name": "أضف اسمًا",
"3 to 16 letters, numbers or underscores. Switch names from the top bar too. Online servers don't take offline names.": "من 3 إلى 16 حرفًا أو رقمًا أو شرطة سفلية. يمكنك تبديل الأسماء من الشريط العلوي أيضًا. الخوادم عبر الإنترنت لا تقبل الأسماء دون اتصال.",
"Play online with your Microsoft account": "العب عبر الإنترنت بحساب Microsoft",
"Sign in with the account that owns Minecraft: Java Edition. Your name and skin come along to online servers, like in other launchers.": "سجّل الدخول بالحساب الذي يملك Minecraft: Java Edition. يرافقك اسمك ومظهرك إلى الخوادم عبر الإنترنت، كما في المشغلات الأخرى.",
"Microsoft's own page opens in your browser. Horizon never sees your password.": "تُفتح صفحة Microsoft نفسها في متصفحك. لا يرى Horizon كلمة مرورك أبدًا.",
+28
View File
@@ -37,6 +37,7 @@
"Building {name}'s post-build step": "{name}-nin tikintidən sonrakı addımının qurulması",
"In use": "İstifadədədir",
"Prepare": "Hazırlayın",
"Developer options": "Tərtibatçı seçimləri",
"{online} of {max} players": "{max} oyunçudan {online}",
"Minecraft {version} (Java Edition). Play downloads it from Mojang for your account the first time, with the Java it needs.": "Minecraft {version} (Java Edition). Play ehtiyac duyduğu Java ilə ilk dəfə hesabınız üçün onu Mojang-dan endirir.",
"Close": "Bağlayın",
@@ -97,6 +98,7 @@
"From my install": "Quraşdırdığımdan",
"the update failed: {error}": "yeniləmə uğursuz oldu: {error}",
"Mesa's DRI_PRIME=1, so Vulkan picks the other card.": "Mesanın DRI_PRIME=1, ona görə də Vulkan digər kartı seçir.",
"New name": "Yeni ad",
"Dark": "Qaranlıq",
"Not now": "İndi yox",
"Use an access token…": "Giriş nişanından istifadə edin...",
@@ -113,6 +115,7 @@
"Partly": "Qismən",
"All": "Hamısı",
"Instance": "Nüsxə",
"Classic arms": "Klassik qollar",
"Versions": "Versiyalar",
"Release build: slower to build, slightly faster game": "Buraxılış quruluşu: qurmaq daha yavaş, bir az daha sürətli oyun",
"Performance build": "Performans qurmaq",
@@ -169,6 +172,7 @@
"about a minute left": "təxminən bir dəqiqə qaldı",
"Cancel": "Ləğv et",
"Add to {client}": "Əlavə et {client}",
"Skin…": "Dəri…",
"Environment": "Ətraf mühit",
"They often still work together. If the build fails, install versions made for the same Nightly.": "Çox vaxt hələ də birlikdə işləyirlər. Quraşdırma uğursuz olarsa, eyni Nightly üçün hazırlanmış versiyaları quraşdırın.",
"Import an instance folder…": "Nümunə qovluğunu idxal edin...",
@@ -180,6 +184,7 @@
"newest stable version": "ən yeni stabil versiya",
"Choose image…": "Şəkil seçin...",
"No worlds yet: they appear here once you play one.": "Hələ dünya yoxdur: siz birini oynadığınız zaman onlar burada görünür.",
"Offline names play without a Microsoft account that owns the game. Minecraft still comes from your own install.": "Oflayn adlar oyunun sahibi olan Microsoft hesabı olmadan oynayır. Minecraft hələ də öz quraşdırmanızdan gəlir.",
"crash reports beside it": "yanında çökmə hesabatları",
"Install all": "Hamısını quraşdırın",
"No group": "Qrup yoxdur",
@@ -197,6 +202,7 @@
"My instance": "Mənim nümunəm",
"Snapshot": "Ani görüntü",
"Gallery": "Qalereya",
"Offline name": "Oflayn ad",
"Home": "Ev",
"Stopping": "Dayanır",
"MSPT · tick time": "MSPT · tik vaxtı",
@@ -298,6 +304,8 @@
"Patch notes": "Yamaq qeydləri",
"Your Minecraft server, {online}.": "Minecraft serveriniz, {online}.",
"Crash reports": "Çökmə hesabatları",
"Offline name · the game's own · plays": "Oflayn ad · oyunun öz · oynayır",
"Slim arms": "İncə qollar",
"Asking GitHub about {owner}/{repo}…": "GitHub-dan {owner}/{repo}... haqqında soruşulur",
"Downloading Minecraft {version} from Mojang · {done} of {total} files": "Mojang-dan Minecraft {version} endirilir · {done} fayldan {total} fayl",
"Could not save your choice: {error}": "Seçiminizi saxlamaq mümkün olmadı: {error}",
@@ -346,6 +354,7 @@
"Horizon's landscape. Pick a PNG, JPEG or WebP picture of your own.": "Horizon mənzərəsi. Özünüzə məxsus PNG, JPEG və ya WebP şəklini seçin.",
"Not needed": "Lazım deyil",
"This build of the launcher has no Microsoft sign-in (HORIZON_MSA_CLIENT_ID), so it can't start the game.": "Başlatıcının bu quruluşunda Microsoft girişi yoxdur (HORIZON_MSA_CLIENT_ID), ona görə də o, oyunu başlata bilmir.",
"Offline name · plays": "Oflayn ad · oynayır",
"Run the game through": "Oyunu keçin",
"needed by another pack": "başqa paketə lazımdır",
"Older →": "Köhnə →",
@@ -356,10 +365,13 @@
"Could not run {program}: {error}": "Çalıştırmaq mümkün olmadı {program}: {error}",
"Restart": "Yenidən başladın",
"Copied to the clipboard.": "Buferə kopyalandı.",
"Your worlds, offline names and settings stay where they are.": "Dünyalarınız, oflayn adlarınız və parametrləriniz olduğu yerdə qalır.",
"Send nothing": "Heç nə göndərmə",
"Move to Trash": "Zibil qutusuna köçürün",
"Start from": "-dən başlayın",
"Asking Mojang for its versions…": "Mojangdan versiyaları soruşulur...",
"A 64×64 (or 64×32) skin PNG and a 64×32 cape PNG, kept by the launcher and given to the game when this name plays. The game draws the default skins for now; it uses these once it can. A Microsoft account's skin and cape: coming soon.": "Başlatıcı tərəfindən saxlanılan və bu ad oynanılan zaman oyuna verilən 64×64 (və ya 64×32) dəri PNG və 64×32 baş PNG. Oyun hazırda standart dəriləri çəkir; bir dəfə bunlardan istifadə edir. Microsoft hesabının dərisi və örtüyü: tezliklə.",
"Play offline under another name, and switch from the top bar. Online servers don't take offline names.": "Başqa ad altında oflayn oynayın və yuxarı paneldən keçin. Onlayn serverlər oflayn adlar götürmür.",
"Report on Discord": "Discord haqqında hesabat",
"Export": "İxrac",
"Server": "Server",
@@ -372,6 +384,7 @@
"No version installed yet.": "Hələ heç bir versiya quraşdırılmayıb.",
"Release": "Buraxılış",
"Verified": "Doğrulanıb",
"Choose a skin…": "Dəri seçin...",
"{instance} doesn't play its native mods yet: build the game with them.": "{instance} hələ öz doğma modlarını oynamır: onlarla oyunu qurun.",
"Use jars from my instance…": "Mənim nümunəmdəki bankalardan istifadə edin...",
"Applications menu": "Proqramlar menyusu",
@@ -395,6 +408,7 @@
"Open backups": "Yedəkləri açın",
"The game is running: change packs in its own menus, or here once it is closed.": "Oyun işləyir: paketləri öz menyularında və ya burada bağlandıqdan sonra dəyişdirin.",
"Check now": "İndi yoxlayın",
"Choose a cape…": "Başlıq seçin...",
"Save": "Saxla",
"Folder": "Qovluq",
"Searching…": "Axtarılır...",
@@ -408,6 +422,7 @@
"MangoHud": "MangoHud",
"Sign out": "Çıxın",
"When it starts": "Başlayanda",
"{name}'s skin": "{name} dərisi",
"Start": "Başlayın",
"No Minecraft install needed: Horizon downloads it from Mojang for your account.": "Minecraft quraşdırmasına ehtiyac yoxdur: Horizon onu hesabınız üçün Mojang-dan endirir.",
"Logs": "Qeydlər",
@@ -431,6 +446,7 @@
"The wordmark, while the release list loads.": "Buraxılış siyahısı yüklənərkən söz nişanı.",
"Playing offline": "Oflayn oynayır",
"Sign in to Tailscale": "Tailscale-ə daxil olun",
"Offline names without an account": "Hesab olmadan oflayn adlar",
"Help make Horizon faster and steadier?": "Horizon daha sürətli və sabit olmağa kömək edin?",
"Sign in to play": "Oynamaq üçün daxil olun",
"Ported": "Köçürülüb",
@@ -472,12 +488,14 @@
"Update this launcher with your package manager.": "Bu başlatıcını paket menecerinizlə yeniləyin.",
"Close this launcher, move it to {folder}, and open it there to enable updates.": "Bu başlatıcını bağlayın, onu {folder} ünvanına köçürün və yeniləmələri aktivləşdirmək üçün orada açın.",
"Any MCP client": "İstənilən MCP müştəri",
"{name}'s cape is kept.": "{name} nin papağı saxlanılır.",
"Not reviewed by the Horizon registry": "Horizon reyestr tərəfindən nəzərdən keçirilməyib",
"Proxy": "Proksi",
"Checking": "Yoxlanılır",
"Updates": "Yeniləmələr",
"Asking Microsoft…": "Microsoft soruşulur...",
"Prepared for Minecraft {version}, without its sounds: the game will be silent. Prepare again to copy them from your Minecraft install.": "Minecraft {version} üçün hazırlanmışdır, onun səsləri olmadan: oyun səssiz olacaq. Onları Minecraft quraşdırmanızdan köçürmək üçün yenidən hazırlayın.",
"Forget": "Unut",
"Import a modpack…": "Mod paketini idxal edin...",
"Search versions": "Versiyaları axtarın",
"failed": "uğursuz oldu",
@@ -486,6 +504,7 @@
"Left off: {line}.": "Qaldı: {line}.",
"Resource packs": "Resurs paketləri",
"yesterday": "dünən",
"No cape": "Plaş yoxdur",
"After each session: frame-time percentiles and a 14-bucket histogram, tick times, peak memory and startup times, with your machine (OS, CPU and its cores and clocks, memory size, GPU, its memory and driver, drive type, screen size and refresh rate, laptop or desktop, on battery or not) and the settings that change performance.": "Hər seansdan sonra: kadr vaxtı faizləri və 14 kova histoqramı, işarələmə vaxtları, pik yaddaş və işə başlama vaxtları, maşınınız (ƏS, CPU və onun nüvələri və saatları, yaddaş ölçüsü, GPU, onun yaddaşı və sürücüsü, sürücünün növü, ekran ölçüsü və yeniləmə sürəti, noutbuk və ya iş masası, batareyada olub-olmaması) və performansı dəyişən parametrlər.",
"Make a token": "Bir nişan hazırlayın",
"Added {names}: the game turns it on when the world opens.": "{names} əlavə edildi: dünya açılanda oyun onu işə salır.",
@@ -538,6 +557,7 @@
"Shared: {url}": "Paylaşıldı: {url}",
"Friends on the same Wi-Fi: Multiplayer, Add Server, then paste this address.": "Eyni Wi-Fi-da olan dostlar: Multiplayer, Server əlavə edin, sonra bu ünvanı yapışdırın.",
"None yet: drop a .hshader or a shader pack .zip here.": "Hələ heç biri: bura .hshader və ya shader paketini .zip buraxın.",
"Offline name · the game's own": "Oflayn ad · oyunun özünə məxsusdur",
"Native mods aren't sandboxed: they run with full access to your computer, like any program. Install only mods whose authors you trust. To play with one, build the game on the Mods page; the first build downloads Rust and takes 20 to 30 minutes.": "Native mods sandboxed deyil: onlar hər hansı bir proqram kimi kompüterinizə tam giriş imkanı ilə işləyirlər. Yalnız müəlliflərinə etibar etdiyiniz modları quraşdırın. Biri ilə oynamaq üçün oyunu Modlar səhifəsində qurun; ilk quruluş Rust-u yükləyir və 20-30 dəqiqə çəkir.",
"Your selected version only changes if you were playing the newest one.": "Seçdiyiniz versiya yalnız ən yenisini ifa etsəniz dəyişir.",
"Multiplayer": "Multiplayer",
@@ -567,6 +587,7 @@
"the port": "liman",
"The source of {source}. Its release ships {file}, a content mod: installing those from GitHub is not supported yet.": "Mənbə {source}. Onun buraxılışı məzmun modu olan {file} göndərilir: GitHub-dan bunları quraşdırmaq hələ dəstəklənmir.",
"Build anyway": "Hər halda tikin",
"A name, 3 to 16 letters": "Ad, 3 ilə 16 hərf",
"Installed {mods} from GitHub ({source}). Build it on the Mods page.": "GitHub-dan {mods} quraşdırılıb ({source}). Onu Modlar səhifəsində qurun.",
"Settings, Keys, Generate access token. It's kept in this computer's keychain and only sent to Tailscale.": "Parametrlər, Açarlar, Giriş nişanı yaradın. O, bu kompüterin brelokunda saxlanılır və yalnız Tailscale-ə göndərilir.",
"{id} is up to date.": "{id} güncəldir.",
@@ -581,6 +602,7 @@
"I read it and trust it: install": "Mən onu oxudum və inanıram: quraşdırın",
"Close export": "İxracatı bağlayın",
"Playing needs a prepared Horizon version (Play page).": "Oynamaq üçün hazırlanmış Horizon versiya lazımdır (Oynatma səhifəsi).",
"Offline, the game's name": "Oflayn, oyunun adı",
"From Horizon's registry": "Horizon reyestrindən",
"Sounds": "Səslər",
"Edit…": "Redaktə et...",
@@ -613,10 +635,12 @@
"up to date": "bu günə qədər",
"← Newer": "← Daha yeni",
"Downloading from Mojang · {done} of {total} files": "Mojang-dan endirilir · {total} fayldan {done} fayl",
"{name}'s skin is kept.": "{name} dərisi saxlanılır.",
"Edit instance": "Nümunəni redaktə edin",
"Remove shortcut": "Qısayolu silin",
"{program} is not installed here (or not on the PATH): copy the config instead.": "{program} burada quraşdırılmayıb (və ya PATH-də deyil): yerinə konfiqurasiyanı kopyalayın.",
"No worlds to put in.": "Yerləşdirməyə dünyalar yoxdur.",
"Default skin": "Defolt dəri",
"A link to a repository (its latest release), a release, a branch or tag, or a commit. The launcher installs one exact release file or commit, never a branch that moves.": "Repozitoriyaya keçid (onun ən son buraxılışı), buraxılış, filial və ya etiket və ya öhdəlik. Başlatıcı bir dəqiq buraxılış faylı və ya öhdəliyi quraşdırır, heç vaxt hərəkət edən bir filial yoxdur.",
"Sign in with GitHub to rate": "Qiymətləndirmək üçün GitHub ilə daxil olun",
"Star on GitHub": "GitHub-da ulduz ver",
@@ -1029,6 +1053,10 @@
"played by {names}": "ifa etdi {names}",
"{day}, {time} UTC": "{day}, {time} UTC",
"Microsoft account · online servers too": "Microsoft hesabı · onlayn serverlər də",
"Offline · single player and LAN worlds": "Oflayn · tək oyunçu və LAN dünyaları",
"Offline names": "Offline adlar",
"Add a name": "Ad əlavə edin",
"3 to 16 letters, numbers or underscores. Switch names from the top bar too. Online servers don't take offline names.": "3-dən 16-a qədər hərf, rəqəm və ya alt xətt. Üst paneldən də adları dəyişin. Onlayn serverlər oflayn adlar götürmür.",
"Play online with your Microsoft account": "Microsoft hesabınızla onlayn oynayın",
"Sign in with the account that owns Minecraft: Java Edition. Your name and skin come along to online servers, like in other launchers.": "Minecraft: Java Edition-a sahib olan hesabla daxil olun. Adınız və dəriniz digər işəsalanlar kimi onlayn serverlərə gəlir.",
"Microsoft's own page opens in your browser. Horizon never sees your password.": "Brauzerinizdə Microsoftun öz səhifəsi açılır. Horizon parolunuzu heç vaxt görmür.",
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff. Show more