Add a control socket and horizon-ctl to drive the client from scripts
`--control` opens a local Unix socket; horizon-ctl sends text commands and prints JSON replies. Scripts can read status, press keys and mouse buttons, look, teleport, give items, change render distance, take PNG screenshots of the presented frame, and benchmark frame times without a person at the keyboard. Under control, losing focus no longer pauses the game. Key presses and play-screen mouse buttons move into shared methods so the window and the socket take the same paths. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
[package]
|
||||
name = "horizon-client"
|
||||
default-run = "horizon-client"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
//! horizon-ctl: drive a running Horizon client through its control socket.
|
||||
#![forbid(unsafe_code)]
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Write},
|
||||
os::unix::net::UnixStream,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, ExitCode, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const USAGE: &str = "usage: horizon-ctl [--socket PATH] COMMAND [ARGS...]
|
||||
|
||||
Local commands:
|
||||
launch [GAME ARGS...] start horizon-client with a control socket and wait for it
|
||||
hold KEY SECONDS press KEY, wait, release it
|
||||
wait-ready [SECONDS] wait until the player has spawned and no chunks are pending
|
||||
- run commands from stdin, one per line (\"sleep S\" waits locally)
|
||||
|
||||
Game commands (run \"horizon-ctl help\" against a running game for the full list):
|
||||
status, key, mouse, look, turn, tp, hotbar, give, render-distance, time,
|
||||
screenshot PATH, stats, bench SECONDS, open, save, quit
|
||||
|
||||
Replies are JSON lines; the exit status is 1 when the reply has an \"error\".
|
||||
The socket defaults to $HORIZON_CONTROL or $XDG_RUNTIME_DIR/horizon-control.sock.";
|
||||
|
||||
struct Client {
|
||||
writer: UnixStream,
|
||||
reader: BufReader<UnixStream>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn connect(path: &Path) -> Result<Self, String> {
|
||||
let stream = UnixStream::connect(path).map_err(|e| {
|
||||
format!(
|
||||
"cannot connect to {} ({e}); is the game running with --control?",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
let reader = BufReader::new(stream.try_clone().map_err(|e| e.to_string())?);
|
||||
Ok(Self {
|
||||
writer: stream,
|
||||
reader,
|
||||
})
|
||||
}
|
||||
fn send(&mut self, line: &str) -> Result<String, String> {
|
||||
writeln!(self.writer, "{line}").map_err(|e| e.to_string())?;
|
||||
let mut reply = String::new();
|
||||
if self
|
||||
.reader
|
||||
.read_line(&mut reply)
|
||||
.map_err(|e| e.to_string())?
|
||||
== 0
|
||||
{
|
||||
return Err("the game closed the connection".into());
|
||||
}
|
||||
Ok(reply.trim_end().to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_error(reply: &str) -> bool {
|
||||
serde_json::from_str::<serde_json::Value>(reply).map_or(true, |v| v.get("error").is_some())
|
||||
}
|
||||
|
||||
/// Screenshot paths are written by the game process: make them absolute here.
|
||||
fn absolute_paths(words: &mut [String]) {
|
||||
if words.first().map(String::as_str) == Some("screenshot")
|
||||
&& let Some(path) = words.get_mut(1)
|
||||
&& let Ok(cwd) = std::env::current_dir()
|
||||
{
|
||||
*path = cwd.join(&*path).display().to_string();
|
||||
}
|
||||
}
|
||||
|
||||
fn run_line(client: &mut Client, words: &mut [String]) -> Result<bool, String> {
|
||||
match words.first().map(String::as_str) {
|
||||
Some("sleep") => {
|
||||
let seconds: f64 = words
|
||||
.get(1)
|
||||
.ok_or("sleep SECONDS")?
|
||||
.parse()
|
||||
.map_err(|_| "sleep SECONDS")?;
|
||||
thread::sleep(Duration::from_secs_f64(seconds));
|
||||
Ok(true)
|
||||
}
|
||||
Some("hold") => {
|
||||
let (key, seconds) = match words {
|
||||
[_, key, seconds] => (
|
||||
key.clone(),
|
||||
seconds.parse::<f64>().map_err(|_| "hold KEY SECONDS")?,
|
||||
),
|
||||
_ => return Err("hold KEY SECONDS".into()),
|
||||
};
|
||||
let down = client.send(&format!("key {key} down"))?;
|
||||
if is_error(&down) {
|
||||
println!("{down}");
|
||||
return Ok(false);
|
||||
}
|
||||
thread::sleep(Duration::from_secs_f64(seconds));
|
||||
let up = client.send(&format!("key {key} up"))?;
|
||||
println!("{up}");
|
||||
Ok(!is_error(&up))
|
||||
}
|
||||
Some("wait-ready") => {
|
||||
let limit = words
|
||||
.get(1)
|
||||
.map_or(Ok(120.0), |s| s.parse::<f64>())
|
||||
.map_err(|_| "wait-ready [SECONDS]")?;
|
||||
let deadline = Instant::now() + Duration::from_secs_f64(limit);
|
||||
loop {
|
||||
let reply = client.send("status")?;
|
||||
let status: serde_json::Value =
|
||||
serde_json::from_str(&reply).map_err(|e| e.to_string())?;
|
||||
if !status["player"].is_null() && status["pending_chunks"] == 0 {
|
||||
println!("{reply}");
|
||||
return Ok(true);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
println!(
|
||||
"{{\"error\":\"not ready after {limit} seconds\",\"status\":{reply}}}"
|
||||
);
|
||||
return Ok(false);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
absolute_paths(words);
|
||||
let reply = client.send(&words.join(" "))?;
|
||||
println!("{reply}");
|
||||
Ok(!is_error(&reply))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn launch(socket: &Path, args: &[String]) -> Result<bool, String> {
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let game = exe.with_file_name("horizon-client");
|
||||
let log = socket.with_extension("log");
|
||||
let file = std::fs::File::create(&log).map_err(|e| format!("{}: {e}", log.display()))?;
|
||||
let child = Command::new(&game)
|
||||
.args(args)
|
||||
.arg("--control-socket")
|
||||
.arg(socket)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(file.try_clone().map_err(|e| e.to_string())?)
|
||||
.stderr(file)
|
||||
.spawn()
|
||||
.map_err(|e| format!("{}: {e}", game.display()))?;
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
while Instant::now() < deadline {
|
||||
if UnixStream::connect(socket).is_ok() {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({ "ok": true, "pid": child.id(), "socket": socket, "log": log })
|
||||
);
|
||||
return Ok(true);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({ "error": "control socket did not open within 60 seconds", "log": log })
|
||||
);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut socket = horizon_client::control::default_path();
|
||||
if args.first().map(String::as_str) == Some("--socket") && args.len() >= 2 {
|
||||
socket = PathBuf::from(args.remove(1));
|
||||
args.remove(0);
|
||||
}
|
||||
let result = match args.first().map(String::as_str) {
|
||||
None | Some("-h" | "--help") => {
|
||||
println!("{USAGE}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
Some("launch") => launch(&socket, &args[1..]),
|
||||
Some("-") => Client::connect(&socket).and_then(|mut client| {
|
||||
let mut all_ok = true;
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let line = line.map_err(|e| e.to_string())?;
|
||||
let mut words: Vec<String> = line.split_whitespace().map(str::to_owned).collect();
|
||||
if words.is_empty() || words[0].starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
all_ok &= run_line(&mut client, &mut words)?;
|
||||
}
|
||||
Ok(all_ok)
|
||||
}),
|
||||
Some(_) => Client::connect(&socket).and_then(|mut client| run_line(&mut client, &mut args)),
|
||||
};
|
||||
match result {
|
||||
Ok(true) => ExitCode::SUCCESS,
|
||||
Ok(false) => ExitCode::from(1),
|
||||
Err(e) => {
|
||||
eprintln!("horizon-ctl: {e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Local control socket: lets a script or `horizon-ctl` drive a running game.
|
||||
//!
|
||||
//! Each connection sends commands as text lines and receives one JSON line per
|
||||
//! command. Commands are executed on the game thread between frames; replies
|
||||
//! that depend on a later frame (screenshots, benchmarks) arrive when ready.
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Write},
|
||||
os::unix::net::{UnixListener, UnixStream},
|
||||
path::{Path, PathBuf},
|
||||
sync::mpsc,
|
||||
thread,
|
||||
};
|
||||
|
||||
/// One command line from a client, with the channel for its JSON reply.
|
||||
pub struct Request {
|
||||
pub line: String,
|
||||
pub reply: mpsc::Sender<String>,
|
||||
}
|
||||
|
||||
pub struct Server {
|
||||
path: PathBuf,
|
||||
requests: mpsc::Receiver<Request>,
|
||||
}
|
||||
|
||||
/// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime directory.
|
||||
pub fn default_path() -> PathBuf {
|
||||
if let Some(path) = std::env::var_os("HORIZON_CONTROL") {
|
||||
return path.into();
|
||||
}
|
||||
let dir = std::env::var_os("XDG_RUNTIME_DIR").map_or_else(std::env::temp_dir, PathBuf::from);
|
||||
dir.join("horizon-control.sock")
|
||||
}
|
||||
|
||||
impl Server {
|
||||
pub fn start(path: &Path) -> std::io::Result<Self> {
|
||||
// A socket left by a crashed game refuses connections; replace it.
|
||||
if path.exists() && UnixStream::connect(path).is_err() {
|
||||
std::fs::remove_file(path)?;
|
||||
}
|
||||
let listener = UnixListener::bind(path)?;
|
||||
let (sender, requests) = mpsc::channel();
|
||||
thread::Builder::new()
|
||||
.name("horizon-control".into())
|
||||
.spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let sender = sender.clone();
|
||||
let _ = thread::Builder::new()
|
||||
.name("horizon-control-client".into())
|
||||
.spawn(move || serve(stream, &sender));
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
path: path.to_owned(),
|
||||
requests,
|
||||
})
|
||||
}
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
pub fn try_recv(&self) -> Option<Request> {
|
||||
self.requests.try_recv().ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn serve(stream: UnixStream, sender: &mpsc::Sender<Request>) {
|
||||
let Ok(mut writer) = stream.try_clone() else {
|
||||
return;
|
||||
};
|
||||
for line in BufReader::new(stream).lines() {
|
||||
let Ok(line) = line else { return };
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (reply, response) = mpsc::channel();
|
||||
if sender.send(Request { line, reply }).is_err() {
|
||||
return;
|
||||
}
|
||||
// The game dropping the reply sender means it exited mid-command.
|
||||
let text = response
|
||||
.recv()
|
||||
.unwrap_or_else(|_| r#"{"error":"game exited"}"#.to_owned());
|
||||
if writeln!(writer, "{text}").is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Frame durations since the last reset, summarized like the Java recorder.
|
||||
#[derive(Default)]
|
||||
pub struct FrameStats {
|
||||
millis: Vec<f32>,
|
||||
}
|
||||
|
||||
impl FrameStats {
|
||||
const LIMIT: usize = 1 << 20;
|
||||
pub fn record(&mut self, millis: f32) {
|
||||
if self.millis.len() < Self::LIMIT {
|
||||
self.millis.push(millis);
|
||||
}
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.millis.clear();
|
||||
}
|
||||
pub fn summary(&self) -> serde_json::Value {
|
||||
let mut sorted = self.millis.clone();
|
||||
sorted.sort_by(f32::total_cmp);
|
||||
let n = sorted.len();
|
||||
if n == 0 {
|
||||
return serde_json::json!({ "frames": 0 });
|
||||
}
|
||||
let total: f64 = sorted.iter().map(|&m| f64::from(m)).sum();
|
||||
let percentile = |p: f64| sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1];
|
||||
// Average frame time of the slowest 1% of frames, as frames per second.
|
||||
let slowest = n.div_ceil(100);
|
||||
let slow: f64 = sorted[n - slowest..]
|
||||
.iter()
|
||||
.map(|&m| f64::from(m))
|
||||
.sum::<f64>()
|
||||
/ slowest as f64;
|
||||
serde_json::json!({
|
||||
"frames": n,
|
||||
"seconds": total / 1000.0,
|
||||
"avg_fps": n as f64 * 1000.0 / total,
|
||||
"low_1pct_fps": 1000.0 / slow,
|
||||
"p50_ms": percentile(0.5),
|
||||
"p95_ms": percentile(0.95),
|
||||
"p99_ms": percentile(0.99),
|
||||
"max_ms": sorted[n - 1],
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The playable game loop: streaming world, player simulation at 20 ticks/s,
|
||||
//! block interaction, inventory and HUD.
|
||||
mod control;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -71,6 +72,8 @@ struct Options {
|
||||
time: Option<i64>,
|
||||
weather: Option<String>,
|
||||
dimension: Option<String>,
|
||||
/// Control socket path (`--control`), for `horizon-ctl`.
|
||||
control: Option<PathBuf>,
|
||||
}
|
||||
impl Options {
|
||||
fn read() -> Result<Option<Self>> {
|
||||
@@ -98,18 +101,20 @@ impl Options {
|
||||
time: None,
|
||||
weather: None,
|
||||
dimension: None,
|
||||
control: None,
|
||||
};
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
|
||||
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
"--creative" => o.creative = true,
|
||||
"--test-terrain" => o.test_terrain = true,
|
||||
"--control" => o.control = Some(horizon_client::control::default_path()),
|
||||
_ => {
|
||||
let value = args.next().ok_or_else(|| format!("missing value after {arg}"))?;
|
||||
match arg.as_str() {
|
||||
@@ -135,6 +140,7 @@ impl Options {
|
||||
"--smoke-report" => o.report = Some(value.into()),
|
||||
"--screenshot-after" => o.screenshot_after = Some(value.parse()?),
|
||||
"--world" => o.world = Some(value),
|
||||
"--control-socket" => o.control = Some(value.into()),
|
||||
"--time" => o.time = Some(value.parse()?),
|
||||
"--weather" => o.weather = Some(value),
|
||||
"--dimension" => o.dimension = Some(if value.contains(':') { value } else { format!("minecraft:{value}") }),
|
||||
@@ -368,6 +374,11 @@ struct Game<'a> {
|
||||
tick_chunks: HashSet<(i32, i32)>,
|
||||
level_events: Vec<LevelEvent>,
|
||||
falling: Vec<FallingBlock>,
|
||||
control: Option<horizon_client::control::Server>,
|
||||
frame_stats: horizon_client::control::FrameStats,
|
||||
/// Control replies waiting for a rendered frame or a benchmark deadline.
|
||||
pending_screenshot: Option<std::sync::mpsc::Sender<String>>,
|
||||
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Dim {
|
||||
@@ -4010,6 +4021,91 @@ impl Game<'_> {
|
||||
};
|
||||
self.renderer.as_mut().ok_or("renderer")?.render(&frame)
|
||||
}
|
||||
/// A key press while a world is open (keyboard or control socket).
|
||||
fn key_pressed(&mut self, key: KeyCode) -> Result<()> {
|
||||
match key {
|
||||
KeyCode::Escape => match self.screen {
|
||||
Screen::Options => {
|
||||
self.settings.save(&std::env::current_dir()?.join("options.txt"));
|
||||
self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused };
|
||||
}
|
||||
Screen::Playing => {
|
||||
self.screen = Screen::Paused;
|
||||
self.capture(false);
|
||||
}
|
||||
Screen::Paused | Screen::Inventory => {
|
||||
self.close_container();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
Screen::Dead => {}
|
||||
},
|
||||
KeyCode::KeyE => match self.screen {
|
||||
Screen::Playing => {
|
||||
self.screen = Screen::Inventory;
|
||||
self.capture(false);
|
||||
}
|
||||
Screen::Inventory => {
|
||||
self.close_container();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
KeyCode::F3 => self.debug = !self.debug,
|
||||
KeyCode::KeyQ if self.screen == Screen::Playing => {
|
||||
let all = self.keys.contains(&KeyCode::ControlLeft);
|
||||
self.drop_held(all);
|
||||
}
|
||||
KeyCode::Digit1 | KeyCode::Digit2 | KeyCode::Digit3 | KeyCode::Digit4 | KeyCode::Digit5 | KeyCode::Digit6 | KeyCode::Digit7 | KeyCode::Digit8 | KeyCode::Digit9 => {
|
||||
self.selected = match key {
|
||||
KeyCode::Digit1 => 0,
|
||||
KeyCode::Digit2 => 1,
|
||||
KeyCode::Digit3 => 2,
|
||||
KeyCode::Digit4 => 3,
|
||||
KeyCode::Digit5 => 4,
|
||||
KeyCode::Digit6 => 5,
|
||||
KeyCode::Digit7 => 6,
|
||||
KeyCode::Digit8 => 7,
|
||||
_ => 8,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// A mouse button while playing (window or control socket).
|
||||
fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
|
||||
match button {
|
||||
MouseButton::Left => {
|
||||
if pressed && self.attack() {
|
||||
return Ok(());
|
||||
}
|
||||
self.left = pressed;
|
||||
if pressed {
|
||||
self.destroy_delay = 0;
|
||||
}
|
||||
}
|
||||
MouseButton::Right => {
|
||||
self.right = pressed;
|
||||
if pressed {
|
||||
self.use_item()?;
|
||||
self.use_delay = 4;
|
||||
}
|
||||
}
|
||||
MouseButton::Middle if pressed && self.creative => {
|
||||
if let Some(hit) = self.pick() {
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let item = self.res.facts.get(state).item.clone();
|
||||
if &*item != "minecraft:air" {
|
||||
self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn update_world(&mut self) {
|
||||
if let Some(p) = &self.player {
|
||||
self.streaming.center = ((p.position.x.floor() as i32) >> 4, (p.position.z.floor() as i32) >> 4);
|
||||
@@ -4096,7 +4192,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
WindowEvent::Focused(focused) => {
|
||||
self.focused = focused;
|
||||
if !focused {
|
||||
if !focused && self.control.is_none() {
|
||||
self.keys.clear();
|
||||
self.left = false;
|
||||
self.right = false;
|
||||
@@ -4164,34 +4260,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.capture(true);
|
||||
return Ok(());
|
||||
}
|
||||
match button {
|
||||
MouseButton::Left => {
|
||||
if pressed && self.attack() {
|
||||
return Ok(());
|
||||
}
|
||||
self.left = pressed;
|
||||
if pressed {
|
||||
self.destroy_delay = 0;
|
||||
}
|
||||
}
|
||||
MouseButton::Right => {
|
||||
self.right = pressed;
|
||||
if pressed {
|
||||
self.use_item()?;
|
||||
self.use_delay = 4;
|
||||
}
|
||||
}
|
||||
MouseButton::Middle if pressed && self.creative => {
|
||||
if let Some(hit) = self.pick() {
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let item = self.res.facts.get(state).item.clone();
|
||||
if &*item != "minecraft:air" {
|
||||
self.inventory[self.selected] = Some(ItemStack { item, count: 1, damage: 0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.play_mouse(button, pressed)?;
|
||||
}
|
||||
Screen::Inventory if pressed => {
|
||||
self.click_inventory(button == MouseButton::Right);
|
||||
@@ -4249,55 +4318,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
if event.repeat {
|
||||
return Ok(());
|
||||
}
|
||||
match key {
|
||||
KeyCode::Escape => match self.screen {
|
||||
Screen::Options => {
|
||||
self.settings.save(&std::env::current_dir()?.join("options.txt"));
|
||||
self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused };
|
||||
}
|
||||
Screen::Playing => {
|
||||
self.screen = Screen::Paused;
|
||||
self.capture(false);
|
||||
}
|
||||
Screen::Paused | Screen::Inventory => {
|
||||
self.close_container();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
Screen::Dead => {}
|
||||
},
|
||||
KeyCode::KeyE => match self.screen {
|
||||
Screen::Playing => {
|
||||
self.screen = Screen::Inventory;
|
||||
self.capture(false);
|
||||
}
|
||||
Screen::Inventory => {
|
||||
self.close_container();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
KeyCode::F3 => self.debug = !self.debug,
|
||||
KeyCode::KeyQ if self.screen == Screen::Playing => {
|
||||
let all = self.keys.contains(&KeyCode::ControlLeft);
|
||||
self.drop_held(all);
|
||||
}
|
||||
KeyCode::Digit1 | KeyCode::Digit2 | KeyCode::Digit3 | KeyCode::Digit4 | KeyCode::Digit5 | KeyCode::Digit6 | KeyCode::Digit7 | KeyCode::Digit8 | KeyCode::Digit9 => {
|
||||
self.selected = match key {
|
||||
KeyCode::Digit1 => 0,
|
||||
KeyCode::Digit2 => 1,
|
||||
KeyCode::Digit3 => 2,
|
||||
KeyCode::Digit4 => 3,
|
||||
KeyCode::Digit5 => 4,
|
||||
KeyCode::Digit6 => 5,
|
||||
KeyCode::Digit7 => 6,
|
||||
KeyCode::Digit8 => 7,
|
||||
_ => 8,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.key_pressed(key)?;
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
let now = Instant::now();
|
||||
@@ -4318,7 +4339,17 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.tick()?;
|
||||
}
|
||||
}
|
||||
if self.render()? {
|
||||
let rendered = self.render()?;
|
||||
if let Some(result) = self.renderer.as_mut().and_then(|r| r.screenshot_result.take())
|
||||
&& let Some(reply) = self.pending_screenshot.take()
|
||||
{
|
||||
let _ = reply.send(match result {
|
||||
Ok([w, h]) => serde_json::json!({ "ok": true, "width": w, "height": h }),
|
||||
Err(e) => serde_json::json!({ "error": e }),
|
||||
}.to_string());
|
||||
}
|
||||
if rendered {
|
||||
self.frame_stats.record(elapsed.as_secs_f32() * 1000.0);
|
||||
self.frames += 1;
|
||||
self.fps_frames += 1;
|
||||
if self.fps_at.elapsed() >= Duration::from_secs(1) {
|
||||
@@ -4354,6 +4385,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
self.poll_control(event_loop);
|
||||
if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout {
|
||||
self.error = Some("frame-limited run timed out".into());
|
||||
event_loop.exit();
|
||||
@@ -4540,7 +4572,17 @@ pub fn run() -> Result<()> {
|
||||
tick_chunks: HashSet::new(),
|
||||
level_events: Vec::new(),
|
||||
falling: Vec::new(),
|
||||
control: None,
|
||||
frame_stats: Default::default(),
|
||||
pending_screenshot: None,
|
||||
pending_bench: None,
|
||||
};
|
||||
if let Some(path) = &game.options.control {
|
||||
let server = horizon_client::control::Server::start(path)
|
||||
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
|
||||
eprintln!("Horizon: control socket {}", server.path().display());
|
||||
game.control = Some(server);
|
||||
}
|
||||
match game.options.world.clone() {
|
||||
Some(folder) => {
|
||||
let (seed, creative) = (game.options.seed, game.options.creative);
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Commands from the control socket (`horizon-ctl`), run on the game thread.
|
||||
use super::{Game, Screen};
|
||||
use horizon_client::{Result, items::ItemStack};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
sync::mpsc::Sender,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use winit::{event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode};
|
||||
|
||||
const HELP: &[&str] = &[
|
||||
"status game, player, streaming and renderer state",
|
||||
"key KEY down|up|tap press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
|
||||
"release release every key and mouse button",
|
||||
"mouse left|right|middle down|up|click",
|
||||
"look YAW PITCH set the view direction in degrees",
|
||||
"turn DYAW DPITCH rotate the view",
|
||||
"tp X Y Z teleport the player",
|
||||
"hotbar 1-9 select a hotbar slot",
|
||||
"give ITEM [COUNT] add items to the inventory",
|
||||
"render-distance N chunks, 2..64",
|
||||
"time TICKS set the time of day",
|
||||
"resume leave the pause menu",
|
||||
"screenshot PATH write the next frame as PNG",
|
||||
"stats [reset] frame-time summary since the last reset",
|
||||
"bench SECONDS reset stats, wait, then reply with the summary",
|
||||
"open WORLD [SEED] [creative] open or create a world from the title screen",
|
||||
"save save the world",
|
||||
"quit save and exit",
|
||||
];
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn poll_control(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if let Some((deadline, reply)) = self.pending_bench.take() {
|
||||
if Instant::now() >= deadline {
|
||||
let _ = reply.send(self.frame_stats.summary().to_string());
|
||||
} else {
|
||||
self.pending_bench = Some((deadline, reply));
|
||||
}
|
||||
}
|
||||
while let Some(request) = self.control.as_ref().and_then(|c| c.try_recv()) {
|
||||
let reply = match self.control_command(&request.line, &request.reply, event_loop) {
|
||||
Ok(Some(value)) => value,
|
||||
// Deferred: the command keeps its own reply channel.
|
||||
Ok(None) => continue,
|
||||
Err(e) => json!({ "error": e.to_string() }),
|
||||
};
|
||||
let _ = request.reply.send(reply.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn control_command(
|
||||
&mut self,
|
||||
line: &str,
|
||||
reply: &Sender<String>,
|
||||
event_loop: &ActiveEventLoop,
|
||||
) -> Result<Option<Value>> {
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
let arg = |i: usize| {
|
||||
words
|
||||
.get(i)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("missing argument {i} for {}", words[0]))
|
||||
};
|
||||
let ok = || Ok(Some(json!({ "ok": true })));
|
||||
match words[0] {
|
||||
"help" => Ok(Some(json!({ "commands": HELP }))),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
self.require_world()?;
|
||||
match arg(2)? {
|
||||
"down" => self.control_key_down(key)?,
|
||||
"up" => {
|
||||
self.keys.remove(&key);
|
||||
}
|
||||
"tap" => {
|
||||
self.control_key_down(key)?;
|
||||
self.keys.remove(&key);
|
||||
}
|
||||
other => {
|
||||
return Err(
|
||||
format!("key action must be down, up or tap, not {other}").into()
|
||||
);
|
||||
}
|
||||
}
|
||||
ok()
|
||||
}
|
||||
"release" => {
|
||||
self.keys.clear();
|
||||
self.left = false;
|
||||
self.right = false;
|
||||
ok()
|
||||
}
|
||||
"mouse" => {
|
||||
let button = match arg(1)? {
|
||||
"left" => MouseButton::Left,
|
||||
"right" => MouseButton::Right,
|
||||
"middle" => MouseButton::Middle,
|
||||
other => return Err(format!("unknown mouse button {other}").into()),
|
||||
};
|
||||
self.require_world()?;
|
||||
if self.screen != Screen::Playing {
|
||||
return Err(format!(
|
||||
"mouse needs the playing screen, not {}",
|
||||
self.screen_name()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
match arg(2)? {
|
||||
"down" => self.play_mouse(button, true)?,
|
||||
"up" => self.play_mouse(button, false)?,
|
||||
"click" => {
|
||||
self.play_mouse(button, true)?;
|
||||
self.play_mouse(button, false)?;
|
||||
}
|
||||
other => {
|
||||
return Err(
|
||||
format!("mouse action must be down, up or click, not {other}").into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
ok()
|
||||
}
|
||||
"look" => {
|
||||
self.yaw = arg(1)?.parse()?;
|
||||
self.pitch = arg(2)?.parse::<f32>()?.clamp(-90.0, 90.0);
|
||||
ok()
|
||||
}
|
||||
"turn" => {
|
||||
self.yaw += arg(1)?.parse::<f32>()?;
|
||||
self.pitch = (self.pitch + arg(2)?.parse::<f32>()?).clamp(-90.0, 90.0);
|
||||
ok()
|
||||
}
|
||||
"tp" => {
|
||||
let to = Vec3::new(arg(1)?.parse()?, arg(2)?.parse()?, arg(3)?.parse()?);
|
||||
let player = self.player.as_mut().ok_or("no player yet")?;
|
||||
player.position = to;
|
||||
player.velocity = Vec3::new(0.0, 0.0, 0.0);
|
||||
player.fall_distance = 0.0;
|
||||
self.previous_position = to;
|
||||
ok()
|
||||
}
|
||||
"hotbar" => {
|
||||
let slot: usize = arg(1)?.parse()?;
|
||||
if !(1..=9).contains(&slot) {
|
||||
return Err("hotbar slot must be 1..9".into());
|
||||
}
|
||||
self.selected = slot - 1;
|
||||
ok()
|
||||
}
|
||||
"give" => {
|
||||
self.require_world()?;
|
||||
let name = arg(1)?;
|
||||
let item = if name.contains(':') {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{name}")
|
||||
};
|
||||
let info = self
|
||||
.res
|
||||
.items
|
||||
.get(&item)
|
||||
.ok_or_else(|| format!("unknown item {item}"))?;
|
||||
let count: u32 = words.get(2).map_or(Ok(1), |c| c.parse())?;
|
||||
let max = info.max_stack;
|
||||
let mut given = 0;
|
||||
// Stop once the inventory is full.
|
||||
while given < count {
|
||||
let n = (count - given).min(max);
|
||||
let rest = self
|
||||
.give(ItemStack {
|
||||
item: item.as_str().into(),
|
||||
count: n,
|
||||
damage: 0,
|
||||
})
|
||||
.map_or(0, |r| r.count);
|
||||
given += n - rest;
|
||||
if rest > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Some(json!({ "ok": true, "given": given })))
|
||||
}
|
||||
"render-distance" => {
|
||||
let n: i32 = arg(1)?.parse()?;
|
||||
if !(2..=64).contains(&n) {
|
||||
return Err("render distance must be 2..64".into());
|
||||
}
|
||||
self.settings.render_distance = n;
|
||||
self.apply_settings();
|
||||
ok()
|
||||
}
|
||||
"time" => {
|
||||
self.world.day_time = arg(1)?.parse()?;
|
||||
ok()
|
||||
}
|
||||
"resume" => {
|
||||
if self.screen == Screen::Paused {
|
||||
self.screen = Screen::Playing;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
"screenshot" => {
|
||||
let renderer = self.renderer.as_mut().ok_or("no renderer yet")?;
|
||||
if self.pending_screenshot.is_some() {
|
||||
return Err("a screenshot is already pending".into());
|
||||
}
|
||||
renderer.screenshot = Some(arg(1)?.into());
|
||||
self.pending_screenshot = Some(reply.clone());
|
||||
Ok(None)
|
||||
}
|
||||
"stats" => {
|
||||
let summary = self.frame_stats.summary();
|
||||
if words.get(1) == Some(&"reset") {
|
||||
self.frame_stats.reset();
|
||||
}
|
||||
Ok(Some(summary))
|
||||
}
|
||||
"bench" => {
|
||||
let seconds: f64 = arg(1)?.parse()?;
|
||||
if self.pending_bench.is_some() {
|
||||
return Err("a benchmark is already running".into());
|
||||
}
|
||||
self.frame_stats.reset();
|
||||
self.pending_bench = Some((
|
||||
Instant::now() + Duration::from_secs_f64(seconds),
|
||||
reply.clone(),
|
||||
));
|
||||
Ok(None)
|
||||
}
|
||||
"open" => {
|
||||
if self.title.is_none() {
|
||||
return Err("a world is already open".into());
|
||||
}
|
||||
let folder = arg(1)?;
|
||||
let seed = words.get(2).map(|s| s.parse::<i64>()).transpose()?;
|
||||
let creative = words.get(3) == Some(&"creative");
|
||||
self.open_world(folder, Some(folder), seed, creative)?;
|
||||
ok()
|
||||
}
|
||||
"save" => {
|
||||
self.require_world()?;
|
||||
self.save_game()?;
|
||||
ok()
|
||||
}
|
||||
"quit" => {
|
||||
if self.title.is_none() {
|
||||
self.save_game()?;
|
||||
}
|
||||
event_loop.exit();
|
||||
ok()
|
||||
}
|
||||
other => Err(format!("unknown command {other}; try help").into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_world(&self) -> Result<()> {
|
||||
if self.title.is_some() {
|
||||
return Err("no world open; use: open WORLD [SEED] [creative]".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn control_key_down(&mut self, key: KeyCode) -> Result<()> {
|
||||
if self.keys.insert(key) {
|
||||
self.key_pressed(key)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn screen_name(&self) -> &'static str {
|
||||
if self.title.is_some() {
|
||||
return "title";
|
||||
}
|
||||
match self.screen {
|
||||
Screen::Playing => "playing",
|
||||
Screen::Paused => "paused",
|
||||
Screen::Options => "options",
|
||||
Screen::Inventory => "inventory",
|
||||
Screen::Dead => "dead",
|
||||
}
|
||||
}
|
||||
|
||||
fn control_status(&self) -> Value {
|
||||
let player = self.player.as_ref().map(|p| {
|
||||
json!({
|
||||
"position": [p.position.x, p.position.y, p.position.z],
|
||||
"velocity": [p.velocity.x, p.velocity.y, p.velocity.z],
|
||||
"on_ground": p.ground.on_ground,
|
||||
"health": p.health.health(),
|
||||
"food": p.health.food.food,
|
||||
})
|
||||
});
|
||||
let target = self.pick().map(|hit| {
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name })
|
||||
});
|
||||
let renderer = self.renderer.as_ref().map(|r| {
|
||||
json!({
|
||||
"gpu": r.info.name,
|
||||
"backend": format!("{:?}", r.info.backend),
|
||||
"size": [r.config.width, r.config.height],
|
||||
"present_mode": format!("{:?}", r.config.present_mode),
|
||||
"drawn_sections": r.drawn_sections,
|
||||
"uploaded_bytes": r.uploaded_bytes,
|
||||
})
|
||||
});
|
||||
json!({
|
||||
"screen": self.screen_name(),
|
||||
"dimension": self.dim.id(),
|
||||
"creative": self.creative,
|
||||
"player": player,
|
||||
"yaw": self.yaw,
|
||||
"pitch": self.pitch,
|
||||
"target": target,
|
||||
"selected": self.selected + 1,
|
||||
"held": self.held().map(|s| json!({ "item": &*s.item, "count": s.count })),
|
||||
"keys": self.keys.iter().map(|k| format!("{k:?}")).collect::<Vec<_>>(),
|
||||
"fps": self.fps,
|
||||
"frames": self.frames,
|
||||
"ticks": self.ticks,
|
||||
"day_time": self.world.day_time,
|
||||
"render_distance": self.streaming.radius,
|
||||
"chunks": self.world.chunks.len(),
|
||||
"pending_chunks": self.streaming.pending(),
|
||||
"generated_chunks": self.streaming.generated_total,
|
||||
"meshed_sections": self.streaming.meshed_total,
|
||||
"renderer": renderer,
|
||||
"uptime_seconds": self.started.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn key_code(name: &str) -> Option<KeyCode> {
|
||||
let name = name.to_ascii_lowercase();
|
||||
let letters = [
|
||||
KeyCode::KeyA,
|
||||
KeyCode::KeyB,
|
||||
KeyCode::KeyC,
|
||||
KeyCode::KeyD,
|
||||
KeyCode::KeyE,
|
||||
KeyCode::KeyF,
|
||||
KeyCode::KeyG,
|
||||
KeyCode::KeyH,
|
||||
KeyCode::KeyI,
|
||||
KeyCode::KeyJ,
|
||||
KeyCode::KeyK,
|
||||
KeyCode::KeyL,
|
||||
KeyCode::KeyM,
|
||||
KeyCode::KeyN,
|
||||
KeyCode::KeyO,
|
||||
KeyCode::KeyP,
|
||||
KeyCode::KeyQ,
|
||||
KeyCode::KeyR,
|
||||
KeyCode::KeyS,
|
||||
KeyCode::KeyT,
|
||||
KeyCode::KeyU,
|
||||
KeyCode::KeyV,
|
||||
KeyCode::KeyW,
|
||||
KeyCode::KeyX,
|
||||
KeyCode::KeyY,
|
||||
KeyCode::KeyZ,
|
||||
];
|
||||
let digits = [
|
||||
KeyCode::Digit0,
|
||||
KeyCode::Digit1,
|
||||
KeyCode::Digit2,
|
||||
KeyCode::Digit3,
|
||||
KeyCode::Digit4,
|
||||
KeyCode::Digit5,
|
||||
KeyCode::Digit6,
|
||||
KeyCode::Digit7,
|
||||
KeyCode::Digit8,
|
||||
KeyCode::Digit9,
|
||||
];
|
||||
if let [c] = name.as_bytes() {
|
||||
return match c {
|
||||
b'a'..=b'z' => Some(letters[usize::from(c - b'a')]),
|
||||
b'0'..=b'9' => Some(digits[usize::from(c - b'0')]),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
Some(match name.as_str() {
|
||||
"space" => KeyCode::Space,
|
||||
"shift" | "lshift" => KeyCode::ShiftLeft,
|
||||
"ctrl" | "control" | "lctrl" => KeyCode::ControlLeft,
|
||||
"esc" | "escape" => KeyCode::Escape,
|
||||
"tab" => KeyCode::Tab,
|
||||
"enter" | "return" => KeyCode::Enter,
|
||||
"f3" => KeyCode::F3,
|
||||
"left" => KeyCode::ArrowLeft,
|
||||
"right" => KeyCode::ArrowRight,
|
||||
"up" => KeyCode::ArrowUp,
|
||||
"down" => KeyCode::ArrowDown,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use crate::{
|
||||
sprites::SpriteAnimation,
|
||||
};
|
||||
use glam::{DVec3, Mat4, Vec3, Vec4};
|
||||
use std::{collections::HashMap, sync::Arc, time::Instant};
|
||||
use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Instant};
|
||||
use wgpu::util::DeviceExt;
|
||||
use winit::window::Window;
|
||||
|
||||
@@ -104,6 +104,10 @@ pub struct Renderer {
|
||||
pub drawn_sections: usize,
|
||||
pub uploaded_bytes: u64,
|
||||
started: Instant,
|
||||
/// Write the next presented frame to this PNG path (control socket).
|
||||
pub screenshot: Option<PathBuf>,
|
||||
/// Outcome of the last screenshot: frame size, or the error.
|
||||
pub screenshot_result: Option<std::result::Result<[u32; 2], String>>,
|
||||
}
|
||||
fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec<u8>, u32) {
|
||||
let levels = size.trailing_zeros() + 1;
|
||||
@@ -196,6 +200,10 @@ impl Renderer {
|
||||
.find(|f| !f.is_srgb())
|
||||
.unwrap_or(config.format);
|
||||
config.view_formats = vec![config.format.remove_srgb_suffix()];
|
||||
// Screenshots copy the presented frame back from the swapchain.
|
||||
if caps.usages.contains(wgpu::TextureUsages::COPY_SRC) {
|
||||
config.usage |= wgpu::TextureUsages::COPY_SRC;
|
||||
}
|
||||
config.present_mode = if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) {
|
||||
wgpu::PresentMode::Mailbox
|
||||
} else {
|
||||
@@ -688,6 +696,8 @@ impl Renderer {
|
||||
drawn_sections: 0,
|
||||
uploaded_bytes: 0,
|
||||
started: Instant::now(),
|
||||
screenshot: None,
|
||||
screenshot_result: None,
|
||||
})
|
||||
}
|
||||
fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer {
|
||||
@@ -1243,7 +1253,11 @@ impl Renderer {
|
||||
frame.hud,
|
||||
[self.config.width, self.config.height],
|
||||
);
|
||||
let readback = self.screenshot.take().map(|path| (path, self.copy_frame(&mut encoder, &surface_frame.texture)));
|
||||
self.queue.submit([encoder.finish()]);
|
||||
if let Some((path, buffer)) = readback {
|
||||
self.screenshot_result = Some(self.write_screenshot(&path, &buffer).map_err(|e| e.to_string()));
|
||||
}
|
||||
self.window.pre_present_notify();
|
||||
self.queue.present(surface_frame);
|
||||
if reconfigure {
|
||||
@@ -1253,6 +1267,61 @@ impl Renderer {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
impl Renderer {
|
||||
fn padded_row(&self) -> u32 {
|
||||
(self.config.width * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
|
||||
}
|
||||
fn copy_frame(&self, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> wgpu::Buffer {
|
||||
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Horizon screenshot"),
|
||||
size: u64::from(self.padded_row()) * u64::from(self.config.height),
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
texture.as_image_copy(),
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(self.padded_row()),
|
||||
rows_per_image: None,
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d { width: self.config.width, height: self.config.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
buffer
|
||||
}
|
||||
fn write_screenshot(&self, path: &std::path::Path, buffer: &wgpu::Buffer) -> Result<[u32; 2]> {
|
||||
if !self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) {
|
||||
return Err("this surface does not support frame readback".into());
|
||||
}
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
buffer.map_async(wgpu::MapMode::Read, .., move |r| {
|
||||
let _ = sender.send(r);
|
||||
});
|
||||
self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(|e| e.to_string())?;
|
||||
receiver.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?;
|
||||
let (width, height, row) = (self.config.width, self.config.height, self.padded_row() as usize);
|
||||
let bgra = matches!(self.config.format.remove_srgb_suffix(), wgpu::TextureFormat::Bgra8Unorm);
|
||||
let mut pixels = Vec::with_capacity((width * height * 4) as usize);
|
||||
{
|
||||
let data = buffer.get_mapped_range(..).map_err(|e| e.to_string())?;
|
||||
for y in 0..height as usize {
|
||||
for px in data[y * row..y * row + width as usize * 4].as_chunks::<4>().0 {
|
||||
let (r, b) = if bgra { (px[2], px[0]) } else { (px[0], px[2]) };
|
||||
pixels.extend_from_slice(&[r, px[1], b, 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
buffer.unmap();
|
||||
let mut encoder = png::Encoder::new(std::io::BufWriter::new(std::fs::File::create(path)?), width, height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header()?.write_image_data(&pixels)?;
|
||||
Ok([width, height])
|
||||
}
|
||||
}
|
||||
fn frustum(m: Mat4) -> [Vec4; 6] {
|
||||
let r = |i| m.row(i);
|
||||
let planes = [
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod blocks;
|
||||
pub mod chunk;
|
||||
pub mod clock;
|
||||
pub mod containers;
|
||||
pub mod control;
|
||||
pub mod crafting;
|
||||
pub mod collisions;
|
||||
pub mod entities;
|
||||
|
||||
@@ -54,6 +54,32 @@ Worlds autosave every 6000 ticks (5 minutes), when chunks unload and on quit.
|
||||
On headless Linux use `vscreen start ./target/release/horizon-client` and
|
||||
`vscreen shot`.
|
||||
|
||||
### Drive the game from scripts (`horizon-ctl`)
|
||||
|
||||
`--control` opens a local Unix socket (`$XDG_RUNTIME_DIR/horizon-control.sock`,
|
||||
or `--control-socket PATH`). `horizon-ctl` sends it one command per line and
|
||||
prints one JSON reply per command; the exit status is 1 when the reply holds an
|
||||
`error`. Under control, losing window focus does not pause the game or release
|
||||
held keys, so a script can play while you use other windows.
|
||||
|
||||
```sh
|
||||
cargo build --release -p horizon-client --bins
|
||||
C=target/release/horizon-ctl
|
||||
$C launch --world Bench --seed 12345 --render-distance 32 # starts the game, waits for the socket
|
||||
$C wait-ready # player spawned, no chunks pending
|
||||
$C look 90 10; $C hold w 2 # face west, walk for two seconds
|
||||
$C screenshot /tmp/view.png # PNG of the next presented frame
|
||||
$C bench 10 # avg/1%-low FPS and p50/p95/p99/max frame times
|
||||
$C quit # save and exit
|
||||
```
|
||||
|
||||
Other commands: `status`, `key KEY down|up|tap`, `mouse left|right|middle
|
||||
down|up|click`, `turn`, `tp X Y Z`, `hotbar N`, `give ITEM [COUNT]`,
|
||||
`render-distance N`, `time TICKS`, `resume`, `stats [reset]`, `open WORLD [SEED]
|
||||
[creative]` and `save`; `horizon-ctl help` lists them from the running game.
|
||||
`horizon-ctl -` reads a script from standard input, where `sleep S` waits locally.
|
||||
Frame times include waits for presentation, so `bench` reports what is on screen.
|
||||
|
||||
### Play on another of your machines
|
||||
|
||||
Horizon targets Linux on ludodesktop (Ubuntu 26.04, RTX 4080); macOS and Windows
|
||||
|
||||
Reference in New Issue
Block a user