From 15e46114a6ae71986aac13052c724526130bca93 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 11:04:38 +0100 Subject: [PATCH 1/3] Discord Rich Presence: show what the player does, with a switch in Horizon Settings Each frame the game hands the presence thread its status (menus; single player, multiplayer or hosting a world with its party size; the dimension; the game mode), and only a change wakes it. The switch "Discord Rich Presence" (on by default, discordPresence in horizon-extras.txt) sits beside Controller Settings. Dedicated servers never start it. tools/discord_presence_e2e.py runs real games against a fake Discord: title, world, Nether and quit on the server thread and in-frame, a LAN host (both paths) and guest, the switch, and a Discord started after the game. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/extras.rs | 22 +- crates/horizon-client/src/game.rs | 12 + crates/horizon-client/src/game/discord.rs | 43 ++++ crates/horizon-client/src/game/remote.rs | 4 + crates/horizon-client/src/options_ui.rs | 5 +- docs/native-client.md | 21 ++ tools/discord_presence_e2e.py | 287 ++++++++++++++++++++++ 7 files changed, 390 insertions(+), 4 deletions(-) create mode 100644 crates/horizon-client/src/game/discord.rs create mode 100644 tools/discord_presence_e2e.py diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index 698741846..40e87214e 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -1,7 +1,8 @@ //! Horizon's optional extras (zoom, FPS counter, keystroke overlay): their //! settings, kept in `horizon-extras.txt` next to `options.txt` so that file //! stays exactly vanilla's, and the logic behind them. Every extra is off by -//! default; see `docs/extras.md`. +//! default; see `docs/extras.md`. Horizon's own switches outside the Extras page +//! (No AI, Agent Control, Discord Rich Presence) are kept here too. use std::{collections::VecDeque, fs, path::Path}; pub const FILE: &str = "horizon-extras.txt"; @@ -112,6 +113,8 @@ pub struct Extras { /// Agents may control the game the player starts: it opens its control socket for /// horizon-ctl and MCP clients (off by default; an agent's own launch always opens it). pub agent_control: bool, + /// "Playing Horizon" on the player's Discord profile (`discord_presence`; on by default). + pub discord_presence: bool, } impl Default for Extras { fn default() -> Self { @@ -142,6 +145,7 @@ impl Default for Extras { sort_key: "key.keyboard.unknown".into(), no_ai: false, agent_control: false, + discord_presence: true, } } } @@ -207,6 +211,7 @@ impl Extras { "sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(), horizon_core::no_ai::KEY => e.no_ai = flag(e.no_ai), "agentControl" => e.agent_control = flag(e.agent_control), + "discordPresence" => e.discord_presence = flag(e.discord_presence), _ => {} } } @@ -214,7 +219,7 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\n", + "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\ndiscordPresence:{}\n", bool_text(self.fullbright), bool_text(self.dynamic_lights), bool_text(self.zoom), @@ -246,6 +251,7 @@ impl Extras { horizon_core::no_ai::KEY, bool_text(self.no_ai), bool_text(self.agent_control), + bool_text(self.discord_presence), ) } /// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for @@ -466,6 +472,8 @@ pub enum Item { /// Not on the Extras page: Horizon Settings shows No AI, its AI Agent page Agent Control. NoAi, AgentControl, + /// On the Horizon Settings page. + DiscordPresence, } /// The Extras page: headers and items. pub fn rows() -> Vec> { @@ -546,6 +554,7 @@ impl Item { Item::KeystrokesCps => "Clicks per second", Item::NoAi => "No AI", Item::AgentControl => "Agent Control", + Item::DiscordPresence => "Discord Rich Presence", } } /// The switch this setting belongs to: it does nothing while that is off. @@ -559,7 +568,7 @@ impl Item { MouseTweaksWheel => MouseTweaks, SortKey => Sort, Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort - | AutoReconnect | NoAi | AgentControl => { + | AutoReconnect | NoAi | AgentControl | DiscordPresence => { return None; } }) @@ -606,6 +615,9 @@ impl Item { Item::NoAi => { "Hides and turns off every AI feature: agent control, horizon-ctl and the MCP servers. The launcher's switch too." } + Item::DiscordPresence => { + "Shows Playing Horizon on your Discord profile while Discord runs: menus, single player or multiplayer, the dimension and the time played. Never a world's name or a server's address." + } Item::AgentControl => { "Your own AI agent can play this game through horizon-ctl or an MCP client, on this computer only." } @@ -641,6 +653,7 @@ impl Item { Item::Sort => e.sort, Item::NoAi => e.no_ai, Item::AgentControl => e.agent_control, + Item::DiscordPresence => e.discord_presence, _ => return None, }) } @@ -698,6 +711,7 @@ impl Item { Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back), Item::NoAi => e.no_ai = !e.no_ai, Item::AgentControl => e.agent_control = !e.agent_control, + Item::DiscordPresence => e.discord_presence = !e.discord_presence, Item::ZoomKey | Item::SortKey => {} } } @@ -721,6 +735,7 @@ mod tests { assert!(!d.fullbright && !d.dynamic_lights); assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect); assert!(!d.mouse_tweaks && !d.sort); + assert!(d.discord_presence); assert_eq!(Extras::parse(""), d); assert_eq!(Extras::parse(&d.serialize()), d); let mut e = d.clone(); @@ -746,6 +761,7 @@ mod tests { e.mouse_tweaks_wheel = false; e.sort = true; e.sort_key = "key.keyboard.r".into(); + e.discord_presence = false; assert_eq!(Extras::parse(&e.serialize()), e); } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2bc5512b7..90811b39b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -36,6 +36,7 @@ mod debug_keys; mod decorated_pot; mod dedicated; mod deflect; +mod discord; mod dispense_fixture; mod dispenser; mod dragon; @@ -11396,6 +11397,7 @@ impl ApplicationHandler for Game<'_> { self.track_toggle_screens(); // For the "I'm playing" ping: an atomic, sent on when it changes. horizon_client::heartbeat::set_lan(self.is_published()); + self.update_discord_presence(); let steps = self.clock.advance(elapsed); // The world ticking in the frame: once its ticks took a // tick's length, the rest are dropped (`FixedStep::tick_fits`). @@ -12864,6 +12866,7 @@ fn write_report(game: &Game<'_>) -> Result<()> { fn run_event_loop(mut game: Game<'_>) -> Result<()> { EventLoop::new()?.run_app(&mut game)?; + horizon_client::discord_presence::stop(); write_report(&game)?; if let Some(e) = game.error.take() { return Err(e); @@ -13221,6 +13224,7 @@ fn run_loading( }; let mut app = App::Loading(Box::new(loading)); EventLoop::new()?.run_app(&mut app)?; + horizon_client::discord_presence::stop(); match app { App::Ready(mut game) => { write_report(&game)?; @@ -13269,6 +13273,14 @@ pub fn run() -> Result<()> { horizon_client::spans::enable(options.spikes.is_some()); let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); + // "Playing Horizon" on Discord: never for a server; an automated run only talks to a test's fake Discord. + if options.dedicated.is_none() { + let automated = options.benchmark.is_some() + || options.offscreen + || options.frames.is_some() + || options.world_frames.is_some(); + horizon_client::discord_presence::start(early_settings.extras.discord_presence, automated); + } // Snapshots of derived tables live in the game folder, never beside the // shared resources. Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache")); diff --git a/crates/horizon-client/src/game/discord.rs b/crates/horizon-client/src/game/discord.rs new file mode 100644 index 000000000..23fd3edda --- /dev/null +++ b/crates/horizon-client/src/game/discord.rs @@ -0,0 +1,43 @@ +//! What the player is doing, for Discord Rich Presence (`horizon_client::discord_presence`). +use super::*; +use horizon_client::discord_presence::{self as presence, Dimension, Play, Status}; + +impl Game<'_> { + /// Each frame: only a change reaches the presence thread. + pub(super) fn update_discord_presence(&self) { + presence::set(self.discord_status()); + } + fn discord_status(&self) -> Status { + if !self.settings.extras.discord_presence { + return Status::Off; + } + if self.title.is_some() { + return Status::Menus; + } + let play = if let Some(host) = &self.lan { + Play::Hosting { + players: 1 + host.hub.guests.len(), + } + } else if let Some(server) = &self.integrated { + match (server.published(), &self.remote) { + (Some(_), Some(remote)) => Play::Hosting { + players: remote.player_count(), + }, + _ => Play::Singleplayer, + } + } else if self.remote.is_some() { + Play::Multiplayer + } else { + Play::Singleplayer + }; + Status::World { + play, + dimension: match self.dim { + Dim::Overworld => Dimension::Overworld, + Dim::Nether => Dimension::Nether, + Dim::End => Dimension::End, + }, + mode: self.mode, + } + } +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 2f59acabc..f8ddf7c44 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -5406,6 +5406,10 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_ } impl Remote { + /// Players in the server's player list, this one included. + pub(super) fn player_count(&self) -> usize { + self.players.len() + } /// The local player's profile UUID. pub(super) fn profile(&self) -> u128 { self.profile diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 99a83072f..5a0cb9e41 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -1291,7 +1291,10 @@ impl OptionsUi { open("Graphics...", Page::Graphics), Some(open("Advanced Graphics...", Page::GraphicsAdvanced)), ), - Row::Buttons(open("Controller Settings...", Page::Controller), None), + Row::Buttons( + open("Controller Settings...", Page::Controller), + Some(self.extra_button(s, crate::extras::Item::DiscordPresence)), + ), Row::Buttons( open("Extras...", Page::Extras), Some(open("Mods...", Page::Mods)), diff --git a/docs/native-client.md b/docs/native-client.md index f6251592d..0e8a6ac67 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -208,6 +208,27 @@ p50/p95/p99/max frame times), plus CPU and GPU time per frame; [the graphics benchmark](graphics.md#benchmark) is built on it. Frame times include waits for presentation, so `bench` reports what is on screen. +### Discord Rich Presence + +While Discord runs on the same computer, the player's Discord profile shows +"Playing Horizon" and what they are doing: "In the menus", "Singleplayer", +"Multiplayer" or "Hosting a world" (with the party size, of 8), the dimension +("In the Nether") and the time since they entered the world. It never shows a +world's name or a server's address. Horizon Settings has the switch +(**Discord Rich Presence**, on by default; `discordPresence` in +`horizon-extras.txt`), and `HORIZON_NO_DISCORD=1` turns it off for one run. + +`crates/horizon-client/src/discord_presence.rs` speaks Discord's local IPC +itself (the `discord-ipc-N` socket or named pipe, no SDK) from a thread of its +own: the frame only hands it a status when it changes. It retries every 15 s +while Discord isn't running and stays within Discord's 5 updates per 20 s. +Dedicated servers never start it, and automated runs (offscreen, benchmarks) +only talk to a fake Discord: `lab.game_env` sets `HORIZON_NO_DISCORD=1`, and +`tools/discord_presence_e2e.py` points games at a fake server with +`HORIZON_DISCORD_IPC_DIR` (title, world, Nether and quit on both single-player +paths; a LAN host and guest). It stays inert until `DISCORD_APP_ID` holds the +Horizon application's id. + ### Play on another of your machines Horizon targets Linux on x86-64 with an NVIDIA GPU (Vulkan); macOS and Windows diff --git a/tools/discord_presence_e2e.py b/tools/discord_presence_e2e.py new file mode 100644 index 000000000..512c6530f --- /dev/null +++ b/tools/discord_presence_e2e.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +"""End-to-end check of Discord Rich Presence: real games talk to a fake Discord. + +Each game gets its own fake Discord IPC server (a Unix socket in a scratch folder, pointed to by +HORIZON_DISCORD_IPC_DIR) that answers the handshake with READY and records every SET_ACTIVITY. +The game goes title -> world -> Nether -> quit through horizon-ctl, and the activities must say +"In the menus", "Singleplayer" in the Overworld, then the Nether, and be cleared on quit: + + single single player on its server thread (the default) + in-frame single player ticked in the window's frame (--in-frame) + lan a host opens its world to LAN and a guest joins: the guest shows "Multiplayer", + the host "Hosting a world" with a party of 2 of 8 (lan-in-frame: the host in-frame) + setting off in horizon-extras.txt: nothing reaches Discord; the Horizon Settings switch + turns it on (the activity appears) and off (it is cleared) + late Discord starts after the game: found within the 15 s retry + + python3 tools/discord_presence_e2e.py # all of them + python3 tools/discord_presence_e2e.py --check lan --bin-dir target/fast + +macOS and Linux (Discord's Windows pipes aren't faked here). Games render offscreen, have no audio +and use scratch homes (lab.game_env). Needs the prepared resources in .local/horizon-client. +""" +import argparse +import json +import os +import shutil +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +try: + from . import lab +except ImportError: + import lab + +ROOT = Path(__file__).resolve().parents[1] +HANDSHAKE, FRAME, CLOSE = 0, 1, 2 + + +class FakeDiscord: + """discord-ipc-0 in a scratch folder: READY on handshake, a reply to each command.""" + + def __init__(self): + # Short: Unix socket paths are limited to ~100 bytes. + self.dir = Path(tempfile.mkdtemp(prefix='hzdc-', dir='/tmp')) + self.server = None + self.activities = [] # (seconds since start, activity or None) + self.handshakes = [] + self.started = time.time() + self.lock = threading.Lock() + + def start(self): + """Discord starts: its socket appears.""" + self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.server.bind(str(self.dir / 'discord-ipc-0')) + self.server.listen() + threading.Thread(target=self.accept, daemon=True).start() + + def accept(self): + while True: + try: + conn, _ = self.server.accept() + except OSError: + return + threading.Thread(target=self.serve, args=(conn,), daemon=True).start() + + def serve(self, conn): + def read(): + header = conn.recv(8, socket.MSG_WAITALL) + if len(header) < 8: + raise EOFError + op, length = struct.unpack(' Date: Sun, 25 Oct 2026 11:49:53 +0100 Subject: [PATCH 2/3] docs: Discord Rich Presence is live with the Horizon application Co-Authored-By: Claude Opus 5.5 --- docs/native-client.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/native-client.md b/docs/native-client.md index 0e8a6ac67..2c123bac4 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -226,8 +226,9 @@ Dedicated servers never start it, and automated runs (offscreen, benchmarks) only talk to a fake Discord: `lab.game_env` sets `HORIZON_NO_DISCORD=1`, and `tools/discord_presence_e2e.py` points games at a fake server with `HORIZON_DISCORD_IPC_DIR` (title, world, Nether and quit on both single-player -paths; a LAN host and guest). It stays inert until `DISCORD_APP_ID` holds the -Horizon application's id. +paths; a LAN host and guest; the switch; a Discord started after the game). +`DISCORD_APP_ID` is Discord's "Horizon" application, whose `horizon` image is +the large one; there are no game-mode images yet. ### Play on another of your machines From 47d1b060b24af9e816f42893c695fa5705c1e92f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:57:19 +0100 Subject: [PATCH 3/3] Discord presence: test where the game looks for Discord on macOS, Linux, Flatpak and Snap sockets() reads the environment through a function, so a unit test can check the paths a real Discord listens on for each platform ($TMPDIR on macOS, $XDG_RUNTIME_DIR and its Flatpak and Snap subfolders on Linux, named pipes on Windows). Offscreen e2e runs can't cover this: an automated run only talks to a fake Discord named by HORIZON_DISCORD_IPC_DIR. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/discord_presence.rs | 61 ++++++++++++++++++- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/discord_presence.rs b/crates/horizon-client/src/discord_presence.rs index 5c25960fb..5f8cc5837 100644 --- a/crates/horizon-client/src/discord_presence.rs +++ b/crates/horizon-client/src/discord_presence.rs @@ -393,16 +393,20 @@ impl Client { /// Where Discord listens: `discord-ipc-0..9` in the temporary folders (and Flatpak's and /// Snap's subfolders) on Linux and macOS, named pipes on Windows. fn sockets() -> Vec { + sockets_with(|key| std::env::var_os(key), cfg!(windows)) +} + +fn sockets_with(var: impl Fn(&str) -> Option, windows: bool) -> Vec { let names = (0..10).map(|n| format!("discord-ipc-{n}")); - if let Some(dir) = std::env::var_os(IPC_DIR_ENV) { + if let Some(dir) = var(IPC_DIR_ENV) { return names.map(|n| PathBuf::from(&dir).join(n)).collect(); } - if cfg!(windows) { + if windows { return names.map(|n| PathBuf::from(r"\\?\pipe\").join(n)).collect(); } let mut dirs: Vec = ["XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"] .into_iter() - .filter_map(std::env::var_os) + .filter_map(&var) .map(PathBuf::from) .collect(); dirs.push("/tmp".into()); @@ -445,6 +449,57 @@ mod tests { } } + /// The folders a real Discord listens in: `$TMPDIR` on macOS, `$XDG_RUNTIME_DIR` on Linux (and its + /// Flatpak and Snap subfolders), named pipes on Windows. + #[test] + fn sockets_cover_where_discord_listens() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |key: &str| { + pairs + .iter() + .find(|(k, _)| *k == key) + .map(|(_, v)| std::ffi::OsString::from(v)) + } + }; + let macos = sockets_with(env(&[("TMPDIR", "/var/folders/xy/abc/T/")]), false); + assert_eq!( + macos[0], + PathBuf::from("/var/folders/xy/abc/T/discord-ipc-0") + ); + assert!(macos.contains(&PathBuf::from("/var/folders/xy/abc/T/discord-ipc-9"))); + assert!(macos.contains(&PathBuf::from("/tmp/discord-ipc-0"))); + + let linux = sockets_with( + env(&[("XDG_RUNTIME_DIR", "/run/user/1000"), ("TMPDIR", "/tmp")]), + false, + ); + assert_eq!(linux[0], PathBuf::from("/run/user/1000/discord-ipc-0")); + for path in [ + "/run/user/1000/app/com.discordapp.Discord/discord-ipc-0", + "/run/user/1000/snap.discord/discord-ipc-0", + "/tmp/discord-ipc-0", + ] { + assert!(linux.contains(&PathBuf::from(path)), "{path}"); + } + assert_eq!(linux.len(), 2 * 3 * 10, "/tmp is listed once"); + + let bare = sockets_with(env(&[]), false); + assert_eq!(bare[0], PathBuf::from("/tmp/discord-ipc-0")); + + let windows = sockets_with(env(&[("TEMP", r"C:\Temp")]), true); + assert_eq!(windows.len(), 10); + // `Path::join` only uses `\` as the separator on Windows itself. + #[cfg(windows)] + assert_eq!(windows[0], PathBuf::from(r"\\?\pipe\discord-ipc-0")); + + let fake = sockets_with( + env(&[("HORIZON_DISCORD_IPC_DIR", "/tmp/hz"), ("TMPDIR", "/x")]), + false, + ); + assert_eq!(fake.len(), 10); + assert_eq!(fake[0], PathBuf::from("/tmp/hz/discord-ipc-0")); + } + #[test] fn frames_round_trip() { let frame = encode(FRAME, &json!({"cmd": "SET_ACTIVITY"}));