mirror of
https://github.com/horizon-rust/horizon-mods.git
synced 2026-11-07 11:05:58 -10:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83ace618de | ||
|
|
e53ad8220b | ||
|
|
43fb2513a2 | ||
|
|
dfd2102274 | ||
|
|
35ce93db53 | ||
|
|
3f3103d070 | ||
|
|
ed4aa85442 | ||
|
|
43010d3eb2 | ||
|
|
546deac561 | ||
|
|
2eca4bc2ec | ||
|
|
a2ae910123 | ||
|
|
88b20af247 | ||
|
|
ceb5b2275d | ||
|
|
e980583b96 | ||
|
|
5c094254e5 | ||
|
|
d8a3327ee3 | ||
|
|
239ce420fa | ||
|
|
ee1620f438 | ||
|
|
a0dba26666 | ||
|
|
82e29462a9 | ||
|
|
725ff7a410 | ||
|
|
64b5237f7c | ||
|
|
7d17c4d63a | ||
|
|
aab9aa4c22 | ||
|
|
6d9a7492e2 | ||
|
|
96c7c46e41 | ||
|
|
09f69374d9 | ||
|
|
4e8a65e584 | ||
|
|
bba4bda2d7 | ||
|
|
6263473f81 | ||
|
|
1fc4bd47d5 | ||
|
|
7558c0945c | ||
|
|
467b17bf38 | ||
|
|
3d113f473a | ||
|
|
792fa822f4 | ||
|
|
7b65e9b10f | ||
|
|
cd1f1c3970 | ||
|
|
be266234cb | ||
|
|
cf1f608745 | ||
|
|
f1f5aba33a | ||
|
|
0062a1e27a | ||
|
|
e79b92ff2c | ||
|
|
ce14e90beb | ||
|
|
93b3f04390 | ||
|
|
bc40e7bafe | ||
|
|
5628be3e6b | ||
|
|
58fbad4a85 | ||
|
|
7645804495 |
No files matched your search
@@ -78,7 +78,9 @@ jobs:
|
||||
names = zipfile.ZipFile(path).namelist()
|
||||
manifest = json.loads(zipfile.ZipFile(path).read("horizon-native.json"))
|
||||
assert manifest["hooks"] >= 1, manifest
|
||||
assert all(n == "horizon-native.json" or (n.startswith(f"mixins/{manifest['id']}/") and n.endswith((".rs", ".toml"))) for n in names), names
|
||||
bundle = f"mixins/{manifest['id']}/"
|
||||
assert all(n == "horizon-native.json" or n == bundle + "LICENSE" or (n.startswith(bundle) and n.endswith((".rs", ".toml"))) for n in names), names
|
||||
assert bundle + "LICENSE" in names, "the mod's LICENSE travels in its package"
|
||||
print(path, manifest)
|
||||
PY
|
||||
- uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -83,7 +83,8 @@ The index: `https://horizon-rust.github.io/horizon-mods/index.json`.
|
||||
[horizon-mixins](https://github.com/horizon-rust/horizon-mixins) bundles on Horizon's native hook points
|
||||
([docs/native-mods.md](https://github.com/horizon-rust/horizon/blob/main/docs/native-mods.md)). Each folder keeps the
|
||||
history of the repository it came from. A mod builds on any Horizon whose hook points are at least the version its
|
||||
`compatibility.json` names; `horizon_revision` is the commit it was last tested on.
|
||||
`compatibility.json` names; `horizon_revision` is the commit it was last tested on. `smp` and `voicechat-server`
|
||||
are server mods, built into the official server's engine (see their READMEs).
|
||||
|
||||
```sh
|
||||
python3 native/tools/native.py check zoom # apply on the tested Horizon and cargo check the game
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 990 B |
Binary file not shown.
|
After Width: | Height: | Size: 660 B |
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 8.7 KiB |
@@ -0,0 +1,31 @@
|
||||
id = "accurate_block_placement"
|
||||
kind = "native-mod"
|
||||
name = "Accurate Block Placement"
|
||||
summary = "Hold right click with a block and every new spot you look at gets one, however fast you move."
|
||||
description = """
|
||||
Placing blocks fast is all about timing: vanilla places a block every four ticks while you hold right click, so moving fast skips spots and moving slowly stacks extra blocks. **Accurate Block Placement** times it for you: hold right click and every *new* spot you look at gets a block at once.
|
||||
|
||||
- **A new spot, a block**: bridging, building walls and floors, or sweeping along a row; no spot skipped, however fast you move.
|
||||
- **No extra blocks**: staring at one spot places nothing more.
|
||||
- **A single click stays a single block**: right after the click it waits as vanilla does, unless you turn the view.
|
||||
- **Building backwards**: walking backwards while placing toward yourself places one block per step.
|
||||
- Doors, chests, buttons and other blocks you click still work as usual.
|
||||
|
||||
**Settings** (Options > Mods > Accurate Block Placement): turn it on or off, bind a key to toggle it (unbound by default), and choose whether it works on servers.
|
||||
|
||||
Some servers see fast, accurate placing as a cheat: check their rules, or turn "Allowed on servers" off.
|
||||
|
||||
A port of [Accurate Block Placement: Reborn](https://modrinth.com/mod/accurate-block-placement-reborn) (MIT) by Clayborn, Flourick, schwar and KadTheHunter, rewritten in Rust for Horizon."""
|
||||
authors = ["Lutziano888"]
|
||||
owners = ["Lutziano888"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Lutziano888/horizon-accurate-block-placement"
|
||||
icon = "https://raw.githubusercontent.com/Lutziano888/horizon-accurate-block-placement/main/icon.png"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "accurate_block_placement-1.0.0.hnmod"
|
||||
sha256 = "e631745f6d267360de6eb51995ee995bf1ab3d64393d287b7b93c332b85939ce"
|
||||
changelog = "First release."
|
||||
+14
-1
@@ -13,9 +13,22 @@ authors = ["soufi"]
|
||||
owners = ["soufied"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/soufied/AppleSkin-Horizon"
|
||||
icon = "icons/appleskin.png"
|
||||
icon = "https://raw.githubusercontent.com/soufied/AppleSkin-Horizon/refs/heads/main/icons/appleskin.png"
|
||||
key = "RWT6eNq4e5WfVDA2lzOOi6XCm/+jJgilqT1+HUUM33ie5MCjcRfSg760"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.2"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "appleskin-0.1.2.hnmod"
|
||||
sha256 = "627d1e7c4b4fa3dd191a4ff5887fe38b20ceb7d7d7f1197c1e03d1f25b6b6b92"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RUT6eNq4e5WfVJqiP4tt8vQGW6sVLSxiLXLeVunyGuyfS9aZWqPilg77biu/2B+HUDS1FlBE31F/HOhBR2YWy0GSmdwhUO7xNAs=
|
||||
trusted comment: timestamp:1793633868\tfile:appleskin-0.1.2.hnmod\thashed
|
||||
IW9M2qJIktmQDlARS6ZTJ1IA9BoGCfMZvatnjIlSpVPkpeG/Qpr5QKRRRPFhnZa93a5KcUG34ok+cgFxipRjBg=="""
|
||||
changelog = "animation fix"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.1"
|
||||
published = "2026-10-31"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
id = "armorhud"
|
||||
kind = "native-mod"
|
||||
name = "Armor HUD"
|
||||
summary = "Armor HUD mod"
|
||||
description = "A mod that adds 4 armor durability viewing slots to the hotbar."
|
||||
authors = ["Thomas9950"]
|
||||
owners = ["Thomas-Slot"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Thomas-Slot/horizon-armor-hud"
|
||||
icon = "https://github.com/Thomas-Slot/horizon-armor-hud/blob/main/icon.png"
|
||||
key = "RWQNLUB+Hf9pa54kEx/ItgJHmDivzpAZxK9lqvv9wnecj34yzNVQHQur"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "armorhud-1.0.0.hnmod"
|
||||
sha256 = "8bd85e1584f307201bce5de2e60466d603b61d4807803d4ebc02772b4f6b704b"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RUQNLUB+Hf9pa0KnzbNFmdhyi6xpMr56two0l9g3QlnoBYyrHFtJt5luXXEl9FnJQpP6GH7Y9KDqYUSAac7QZEQDejqrM2gA7A4=
|
||||
trusted comment: timestamp:1793750475\tfile:armorhud-1.0.0.hnmod\thashed
|
||||
q840egwiCqF5Ptn8MCP/0VqaPUQQgaWzyXwhnFhD47GLeblsZWdvPyaTnEUbsGxHCgHGT5FFrqJ54Mu1OSz/DQ=="""
|
||||
changelog = "First upload."
|
||||
+57
-13
@@ -1,29 +1,73 @@
|
||||
id = "basic_hud"
|
||||
kind = "native-mod"
|
||||
name = "The Basic HUD"
|
||||
summary = "Effect timers, potions, golden apples and totems carried, totems used by each player, and armour, elytra and shield durability."
|
||||
summary = "A visual HUD editor with 14 customizable widgets, recent pickups, effect timers, durability, coordinates, FPS and a customizable Tab list."
|
||||
description = """
|
||||
A small HUD box in a corner of the screen.
|
||||
A client-side visual HUD for Horizon. Move, resize and style fourteen independent widgets directly over the game.
|
||||
|
||||
## What it shows
|
||||
Includes effects and timers, consumable counts, durability, observed totem uses, available player health, item cooldowns, coordinates, FPS, ping, speed, CPS, world clock, mini armour and recent item pickups.
|
||||
|
||||
- Active effects with their time left. Potion effects are pinned by default; any other effect can be pinned on the mod's settings page, or all of them shown at once.
|
||||
- Potions of each kind, golden apples, enchanted golden apples and totems in your inventory.
|
||||
- Totems each player has used, above that player's name. Your own count is in the box.
|
||||
- Durability of worn armour, elytra and a held shield.
|
||||
Recent pickups aggregates matching items and refreshes their expiry: 4 torches + 2 torches becomes x6. Five seconds by default, adjustable from 1 to 60 seconds. Includes icon + count mode.
|
||||
|
||||
The count of a player's totems resets when they die or when you leave the world.
|
||||
Customize each widget's position, scale, colours, opacity, padding and shadows. Includes a customizable Tab list and ten interface languages. A short tutorial appears on the first settings visit and can be replayed with ?. Reset requires confirmation; leaving with edits offers Save / Discard / Stay.
|
||||
|
||||
## What it does not do
|
||||
Controls: Right Shift, or Options > Mods > The Basic HUD > Settings > Edit HUD.
|
||||
|
||||
- It builds on one Horizon commit only, 68ac6f6 (Minecraft 26.3). Counting totems and writing above a player have no hook point, so it hooks two of the game's own functions (totem_event, name_tag_geometry). The rest uses hook points but reads the game's internal data.
|
||||
- It knows only what the client is told: a totem used out of your sight is not counted.
|
||||
- Its own texts are in English. Effect and item names follow the game's language.
|
||||
- Tested on Windows in single player and over LAN with two clients, not on a dedicated server."""
|
||||
Install the .hnmod through Horizon and choose Performance. Minecraft 26.3; pinned Horizon 68ac6f647e7022b2c696e81863d7cface28c9416. Compatibility with other Nightlies is not claimed.
|
||||
|
||||
Client-side only: unknown health stays unknown, unobserved totem uses cannot be counted, and server-plugin-only cooldowns are unavailable. No FPS improvement is claimed.
|
||||
|
||||
Release notes and verification: https://github.com/repositorykreml1n/the-basic-hud/releases/tag/v0.5.0"""
|
||||
authors = ["repositorykreml1n"]
|
||||
owners = ["repositorykreml1n"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/repositorykreml1n/the-basic-hud"
|
||||
icon = "https://raw.githubusercontent.com/repositorykreml1n/the-basic-hud/v0.5.0/icon.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.5.0"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "basic_hud-0.5.0.hnmod"
|
||||
sha256 = "97011cc7374354c6293678c7ab593240d0512bffde1d7b642dad521e1df3f8ac"
|
||||
changelog = """
|
||||
## 0.5.0 — Recent pickups
|
||||
- New movable widget for recently collected items: pick up 4 torches, then 2 more before expiry, and it shows x6. Each repeat pickup refreshes that item's timer.
|
||||
- Default display time: 5 seconds; adjustable from 1 to 60 seconds.
|
||||
- Supports icon + count mode, dragging, scale, colours and opacity.
|
||||
- Partial pickups count only the amount that fits. Giving, crafting and inventory rearrangement do not by themselves create entries.
|
||||
- New pixel-art totem icon; new labels translated into all ten interface languages. Existing layouts and settings are preserved.
|
||||
|
||||
Verified: 75 strict Rust test executions, warning-free pinned native build, real in-game aggregation/expiry/partial-pickup checks, editor persistence and ordinary startup without a controller.
|
||||
|
||||
Русский: добавлен блок недавнего подбора с суммированием количества, обновлением таймера и настройкой 1–60 секунд (по умолчанию 5). Новая иконка — тотем.
|
||||
Deutsch: Neues Widget für aufgehobene Gegenstände mit addierten Mengen und einstellbarer Dauer von 1–60 Sekunden.
|
||||
Français : nouveau widget des objets ramassés, quantités cumulées et durée réglable de 1 à 60 secondes.
|
||||
Español: nuevo widget de objetos recogidos, cantidades acumuladas y duración ajustable de 1 a 60 segundos."""
|
||||
|
||||
[[versions]]
|
||||
version = "0.4.1"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "basic_hud-0.4.1.hnmod"
|
||||
sha256 = "36431d3a2d810e2aefbd8611767a80f9184e3df032e4cc2b9b9fd9398f794560"
|
||||
changelog = """
|
||||
Major update from 0.1.0 to 0.4.1.
|
||||
|
||||
- Visual in-game editor: drag, individual scale, colours, opacity, shadows, padding and snap.
|
||||
- 13 widgets, including FPS, coordinates, available player health and actual item cooldowns.
|
||||
- Icons + values: ×16, 1:45 and durability without long labels.
|
||||
- Mini armour beside the hotbar, including elytra.
|
||||
- Custom Tab list: numeric ping, bars, player counts, sorting and scale.
|
||||
- Smoothed optional speed; single-player ping labelled Local.
|
||||
- Ten UI languages plus Auto; first-visit tutorial, replay through ?.
|
||||
- Reset confirmation; Save / Discard changes / Stay on leaving with edits; failed-save recovery.
|
||||
|
||||
Pinned to Minecraft 26.3 / Horizon 68ac6f6. Use the Performance build profile on Windows; Dev can overflow the startup stack on this baseline. No compatibility with other Nightlies or FPS gain is claimed.
|
||||
|
||||
Validated: 67 Rust test executions, native build, isolated gameplay/editor tests, restart persistence and ordinary asynchronous startup.
|
||||
|
||||
Full notes (English + Russian, Ukrainian, German, French and Spanish summaries): https://github.com/repositorykreml1n/the-basic-hud/blob/main/CHANGELOG.md"""
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.0"
|
||||
|
||||
+10
-2
@@ -1,14 +1,22 @@
|
||||
id = "blockscope"
|
||||
kind = "native-mod"
|
||||
name = "Blockscope"
|
||||
summary = "The block under your crosshair: its name, id, distance and icon, with reach, placement and opacity on its own settings page. A Jade-style tooltip for Horizon."
|
||||
description = "Jade-style block info for Horizon: the block under your crosshair, its name in your language, its block id, how far it is and its icon."
|
||||
summary = "The block under your crosshair: its name, id, distance and icon, plus hardness, states and a container's slots."
|
||||
description = "A Jade-style tooltip for Horizon: the block under your crosshair with its name in your language, block id, distance and icon, plus its hardness and the tool it wants, its state properties, a crop's growth and, for a container, its slots. Ten switches on its own settings page."
|
||||
authors = ["Domanffe"]
|
||||
owners = ["Domanffe"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Domanffe/blockscope"
|
||||
icon = "https://horizon-rust.github.io/horizon-mods/icons/blockscope.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.3.1"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "blockscope-0.3.1.hnmod"
|
||||
sha256 = "4fea94e5337aa82df3d981fc6231fecc80161262add577b596bb6661e0e303d1"
|
||||
changelog = "Rebuilt on the 2026-11-01 Nightly (Horizon `4aa6854`). All five hook points are named now — `mods`, `settings`, `settings_click`, `hud`, `tick` — so the bundle still applies when the game moves them."
|
||||
|
||||
[[versions]]
|
||||
version = "0.3.0"
|
||||
published = "2026-10-30"
|
||||
|
||||
+9
-6
@@ -2,18 +2,21 @@ id = "chatheads"
|
||||
kind = "native-mod"
|
||||
name = "ChatHeads"
|
||||
summary = "A player's head left of every chat line they wrote."
|
||||
description = """
|
||||
Each chat line from a player gets their 8x8 skin face in the strip to its left, like the Chat Heads Java mod. Lines without a player (system messages, /me, wrapped continuations) stay as they are; the face fades with its line.
|
||||
|
||||
Settings: Options > Mods > ChatHeads > Settings (on or off).
|
||||
|
||||
Known limit: the chat's hit-test does not know about the 10 px indent, so clicking a link in chat lands 10 px left of its pixels."""
|
||||
description = "Each chat line from a player gets their 8x8 skin face in the strip to its left; lines without a player stay as they are, and the face fades with its line. The switch lives in Options > Mods."
|
||||
authors = ["Domanffe"]
|
||||
owners = ["Domanffe"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Domanffe/chatheads"
|
||||
icon = "https://horizon-rust.github.io/horizon-mods/icons/chatheads.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.1"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "chatheads-0.1.1.hnmod"
|
||||
sha256 = "16f5e1db33255c550c087fcf3ed982a4be9abf61b547b470a08f471d309ad1fe"
|
||||
changelog = "Rebuilt on the 2026-11-01 Nightly (Horizon `4aa6854`). The three hook points it shares — `mods`, `settings`, `settings_click` — are named now instead of pinned to raw source targets, so a Horizon update that moves them no longer breaks the bundle."
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.0"
|
||||
published = "2026-10-30"
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
id = "chop"
|
||||
kind = "native-mod"
|
||||
name = "Chop!"
|
||||
summary = "Cut one log and the whole tree tips over, crashes down and breaks apart, with soft vanilla sounds and particles."
|
||||
description = """
|
||||
Cut one log with an axe: the whole tree tips over like a real falling tree, crashes to the ground, and breaks apart from the base to the top in little pops. Everything is made of vanilla sounds and particles: no resource pack.
|
||||
|
||||
- **The log shakes while you cut it**, then pops when it gives way.
|
||||
- **A physical fall**: the trunk drops onto the stump, creaks, tips over with gravity and stops where it meets the ground. Leaves in the way are crushed.
|
||||
- **Falls in front of you**, within an adjustable angle, toward the clearest side.
|
||||
- **A cute break-up** from the base to the top, with clouds, sparkles and hearts.
|
||||
- **Replants a sapling** of the tree's kind (from its loot, or always).
|
||||
- **Chain reactions**: a falling trunk can knock over the next tree.
|
||||
- **Adjustable damage**: hurts monsters by default; animals, allies and players are spared unless you turn them on.
|
||||
- Vanilla loot (Fortune, Silk Touch), honest axe wear, fall preview, shaking trees with an empty hand, giant mushrooms and Nether fungi, angry bees, birds, apples, biome-tinted leaves, optional loot into your inventory.
|
||||
- **Everything is configurable in game**, with commands or by clicking in the chat: `/chop config` (operators), `/chop perso` (each player's sounds, particles and preview), `/chop stats`, `/chop aide`. The menus are in French.
|
||||
|
||||
**What it does and doesn't do.** It runs server-side, where the world runs: players who join install nothing. No network access, no telemetry, never runs a program. It reads and writes one file, `<world>/data/chop.txt` (settings, stats, player-placed logs). It only touches trees, the sapling it replants, its own `block_display` entities and what a falling tree hits. Besides the game's functions, it runs a few vanilla commands as the server: `kill` on its own tagged displays, `item modify` for the axe's wear, `damage` on a player the tree hits (off by default), and `summon item` / `setblock … keep` for loot and replanting when the tree is in another dimension.
|
||||
|
||||
Native source mod: install it on the launcher's Mods page, press Build there, and confirm the native-code warning. The launcher builds a separate game with it, and it runs with your account's permissions. Each version is pinned to one Horizon Nightly and Horizon Mixins revision, named in its changelog; the launcher builds those exact revisions.
|
||||
|
||||
Original mod by Mayonesu0. All rights reserved, except the grants in its [LICENSE](https://github.com/Mayonesu0/chop/blob/main/LICENSE): players may use it unchanged, Horizon's registry may distribute it, and Horizon's reviewers may read it to review it."""
|
||||
authors = ["Mayonesu0", "Claude"]
|
||||
owners = ["Mayonesu0"]
|
||||
license = "LicenseRef-Chop-1.0"
|
||||
source = "https://github.com/Mayonesu0/chop"
|
||||
icon = "https://raw.githubusercontent.com/Mayonesu0/chop/main/registry/icon.png"
|
||||
key = "RWSwx1v4zUCUjQ8rssfZCXvXkvgVc9TbA60RJyCtVCeMx4lSTanIleIs"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.1"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "chop-1.0.1.hnmod"
|
||||
sha256 = "5abac195c54da7716f35f641489c0dba780444c91b0b3e4f3387ecd4cb2b260b"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key\r
|
||||
RUSwx1v4zUCUjfR+WYS97be0UecaBcKGyNXNsCQAPVG0j2U2yeMfnNPkWMEU9CMOobMI6nKaPj/Kqv0EPAuw2xiPnRaduNgI8wA=\r
|
||||
trusted comment: timestamp:1793711491\tfile:chop-1.0.1.hnmod\thashed\r
|
||||
eOi2t+LMQ4LOM/nsJqmpvAraWsLcgdRZA4OJotjBkgxcANkG3MeZ9tbAKbEaidIy1kBSZyc4Dri+3MtOsd+xBA=="""
|
||||
changelog = "First release (1.0.0 was never published: its package carried a LICENSE file the registry's checker refuses; the code is the same). Pinned to Horizon Nightly 2026-11-01 (c9d474d) and Horizon Mixins ddd9700; the launcher builds those exact revisions."
|
||||
@@ -0,0 +1,41 @@
|
||||
id = "crossversion"
|
||||
kind = "native-mod"
|
||||
name = "Cross Version"
|
||||
summary = "Allows version hopping offline."
|
||||
description = """
|
||||
Hop versions, offline.
|
||||
Uses ViaProxy as an inbetween for now."""
|
||||
authors = ["JustKarkat"]
|
||||
owners = ["JustKarkat"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/JustKarkat/horizon-crossversion/"
|
||||
icon = "https://github.com/JustKarkat/horizon-crossversion/blob/master/icon.png?raw=true"
|
||||
key = "RWTcPJHJYjPW0pV3lPwr45crCu0wJxW5HbDLc3fr3Eom1TzxO++kHOo4"
|
||||
|
||||
[[versions]]
|
||||
version = "0.8.0"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "crossversion-0.8.0.hnmod"
|
||||
sha256 = "5b371f1b7b3582e0c92aa1dc22b491b50c024fe95833aa2bd9457189631caafd"
|
||||
signature = """
|
||||
untrusted comment: signature from rsign secret key
|
||||
RUTcPJHJYjPW0vc8h9pG+LC/9EkYg60UM28gNkxJ31iDOXapyV80qqnB9H12OuOtzBmPkbB33fkh0IKE5O8zcCzat0jyj6Tpqw8=
|
||||
trusted comment: timestamp:1793679858\tfile:crossversion-0.8.0.hnmod\thashed
|
||||
3hY5NK517bzva/2q54Pmj9QXO3z6WF0WWMfuA8T9H8qCuOe6TYnmYB5eEagRMpZUNK/ICcrfPEx+DE303XIOAQ=="""
|
||||
changelog = "Offline mode only. "
|
||||
|
||||
[[versions]]
|
||||
version = "0.7.1"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "crossversion-0.7.1.hnmod"
|
||||
sha256 = "deb9cf8a84838e6c48999f70fbd3c81db90992c456d6e85a0e0746b088c5b8fa"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RUTcPJHJYjPW0nmeON4u6rxOS7AxK+s/e3kPaLkJ3lm618iPPc8oP8nWdJQ8k9yYriSZSu091TZ5m7qX56nNovAjeZyTcOdrUAk=
|
||||
trusted comment: timestamp:1793657606\tfile:crossversion-0.7.1.hnmod\thashed
|
||||
q2Oy6yVv5T+GHc2iM+HxNDImfPcaKGV/XPToNCTQFHSTKJ8+rz5IV4LfJnOBwBp1rZQZoGkExopDrXfZyQybCQ=="""
|
||||
changelog = """
|
||||
Version: 0.7.1
|
||||
Changelog: The MIT notice now ships inside the .hnmod (it is the header of the bundled engine source). The settings page's 'Delete the downloaded ViaProxy' deletes the jars only, so the account added to ViaProxy and its refresh token in saves.json stay. Also: a version switch on Edit Server and Direct Connect: choose what version ViaProxy tells that server it is (auto, 1.8, 1.9, 1.12.2, 1.16.5, 1.20.1, 1.21.1, 1.21.4, 26.3), kept per address, for servers whose status reports the wrong version."""
|
||||
@@ -0,0 +1,28 @@
|
||||
id = "customhud"
|
||||
kind = "native-mod"
|
||||
name = "Beautiful Day Counter"
|
||||
summary = "A lightweight day counter, clock and day/night cycle bar for the HUD, with an in-game settings screen."
|
||||
description = """
|
||||
Beautiful Day Counter for Horizon, a native mod.
|
||||
|
||||
Shows the current survival day, an in-game clock and a color-shifting bar that follows the day/night cycle, without changing gameplay. It is a port of the author's own Fabric/NeoForge mod [CustomHUD](https://github.com/sonoFrangu/CustomHUD), with the same HUD and the same settings screen.
|
||||
|
||||
- Day counter with the game mode icon; a golden apple or totem, a rainbow counter and a sound on milestone days (50, 100, 365, every 100).
|
||||
- 12-hour or 24-hour clock; the clock icon turns into a bed when you can sleep.
|
||||
- Day/night bar with four color themes (Classic, Pastel, Colorblind, Mono), night marks, countdown to night or day, moon phase.
|
||||
- Top or bottom placement, size, opacity, offsets, optional background; vanilla boss bars move below the HUD when it is at the top.
|
||||
- Settings screen opened with H (or from Options > Mods): Elements, Look and Behavior, with tooltips.
|
||||
- English, Italian, German, Spanish, French and Portuguese."""
|
||||
authors = ["SCARABOCCHIO100"]
|
||||
owners = ["sonoFrangu"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/sonoFrangu/CustomHUD-Horizon"
|
||||
icon = "icons/customhud.png"
|
||||
|
||||
[[versions]]
|
||||
version = "1.6.0"
|
||||
published = "2026-10-31"
|
||||
game = "26.3"
|
||||
file = "customhud-1.6.0.hnmod"
|
||||
sha256 = "ab255d3c722b40f4d068a762857d6c027c11381308bfe23196e2974307814a7f"
|
||||
changelog = "First release for Horizon: the CustomHUD 1.6.0 HUD and settings screen as a native mod."
|
||||
@@ -0,0 +1,35 @@
|
||||
id = "fast_items"
|
||||
kind = "native-mod"
|
||||
name = "Fast Items for Horizon"
|
||||
summary = "Optimize item rendering by transforming item entities to 2D"
|
||||
description = """
|
||||
Fast Items (2D Items)
|
||||
Optimizes item rendering by transforming items to 2D forms.
|
||||
|
||||
For 2D items(such as potions), this mod avoids rendering their sides, so they are completely flat
|
||||
|
||||
For 3D items(such as cube blocks), this mod makes them always face to camera, just as the same behaviour in Lunar Client/BLC."""
|
||||
authors = ["Lyvt (dc: _.lyvt)"]
|
||||
owners = ["Lyvt-Dev"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Lyvt-Dev/FastItems-for-Horizon"
|
||||
icon = "https://github.com/Lyvt-Dev/FastItems-for-Horizon/tree/main/logo/fastitems.png"
|
||||
key = "RWQ84d8BvD1EaarVDgHgXyz+MDiL7ONsCZc0BUrJqTmqzXBItnJy918A"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.0"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "fast_items-0.1.0.hnmod"
|
||||
sha256 = "c3acd8adfeac6450c3a13b5172c8abb298cb3ceb355dfc539b4bdd653ef15502"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key\r
|
||||
RUQ84d8BvD1EaR6fPq1+iCBwAhUosfQDHMjVQLYQkIRcmU7I9Ls7Z3nC8wFUF4BOzgB4DaP5UonvlkAG4wqNMZH6EnRLmwaGqgw=\r
|
||||
trusted comment: Fast Items for Horizon 0.1.0; fast-items-0.1.0.hnmod\r
|
||||
iqcDMYeA2LekavHGy7yMhtCtH6kCyjq7x76cVPD994O+CYj0lfW4tZL1HSgtXQJFM+3Gw3h2xr55DndjcqFiAA=="""
|
||||
changelog = """
|
||||
Optimizes item rendering by transforming items to 2D forms.
|
||||
|
||||
For 2D items(such as potions), this mod avoids rendering their sides, so they are completely flat
|
||||
|
||||
For 3D items(such as cube blocks), this mod makes them always face to camera, just as the same behaviour in Lunar Client/BLC."""
|
||||
@@ -0,0 +1,24 @@
|
||||
id = "flair"
|
||||
kind = "native-mod"
|
||||
name = "flair"
|
||||
summary = "Custom accessory mod"
|
||||
description = "A cosmetics catalog for Horizon. Open it from the title screen or the pause menu and wear HD capes that move like cloth, animated bandanas with Japanese script, hats, wings, shoulder pets and auras with colour themes. Turn your player in a live preview, hide your armor, and add your own capes and Blockbench cosmetics with animations. Only you see them."
|
||||
authors = ["_idom_"]
|
||||
owners = ["umbx-dot"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/umbx-dot/horizon-flair"
|
||||
icon = "https://raw.githubusercontent.com/umbx-dot/horizon-flair/main/icon.png"
|
||||
key = "RWT9Ujo/oCprPGHHiSLHFNOJV1ZzoJdAU6EdZyiQcBwT2iMXfiYms4hD"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "flair-1.0.0.hnmod"
|
||||
sha256 = "64e4d645d5bda3c363603d483af2095d6d3673d91803954f338d54265bf4fab5"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key\r
|
||||
RUT9Ujo/oCprPBIbqV9rmrjRgpF9gnCIL+4FlZXSTq0Qi4kkklSKfjNDx9YFIw1DuufGVSL3+lOieSX4Fx0nRl7j/CCUNjiWIQs=\r
|
||||
trusted comment: timestamp:1793723044\tfile:flair-1.0.0.hnmod\thashed\r
|
||||
QPCGNEAWFCaZLdZLgkUVY9v+hRP4/gJe4H2hCMh7YT7k/V4tynkQ0AM3hZqEdrBoPn4q5SFHDVIcloGkqCTzDw=="""
|
||||
changelog = "Initial Release."
|
||||
@@ -0,0 +1,25 @@
|
||||
id = "fullbright_nofog"
|
||||
kind = "native-mod"
|
||||
name = "Fullbright & NoFog"
|
||||
summary = "Toggle full brightness and the world's fog with a key (G / N), /fullbright or /nofog."
|
||||
description = """
|
||||
A native Horizon mod: the launcher builds it into the game (install it on the launcher's Mods page, then press Build there). Native mods are not sandboxed and run with your account's rights, so read the source before you build it. Uses only Horizon's native hook points (hooks 80, for `render_fog`); tested on Nightly 2026-11-01 (c9d474d) and horizon-mixins 0d6b103.
|
||||
|
||||
- **Fullbright**: press G (or `/fullbright`, `/fb`) to toggle full brightness (gamma 1500%). Your brightness slider and `options.txt` are never changed; turning it off gives your own brightness back.
|
||||
- **NoFog**: press N (or `/nofog`) to remove the world's fog. `/nofog fluids` also clears water, lava and powder snow fog.
|
||||
- `/fullbright on|off` and `/nofog on|off` set them directly.
|
||||
- Options → Mods → Fullbright & NoFog: a button for each toggle and both keys, rebindable.
|
||||
|
||||
Toggling is silent (no chat messages). Client-side: works in single player, on LAN and on servers. Settings are remembered between sessions."""
|
||||
authors = ["Nirokx"]
|
||||
owners = ["Nirokx"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Nirokx/horizon-fullbright-nofog"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "fullbright_nofog-1.0.0.hnmod"
|
||||
sha256 = "07a13abd8af2405343241f8985db7595a03bfb8ced2f1dfab8a105848eb1b7d7"
|
||||
changelog = "First release."
|
||||
@@ -0,0 +1,17 @@
|
||||
id = "held_item_info"
|
||||
kind = "native-mod"
|
||||
name = "Held Item Info"
|
||||
summary = "Selected-item durability, count and enchantment names above the hotbar."
|
||||
description = "Minimal client-only selected-item text HUD for Horizon 26.3. Displays remaining/maximum durability, stack count and up to six translated enchantment names; long strings are shortened to GUI width. Original MIT implementation inspired by A5b84/held-item-info; no LGPL source was read or included. Potion details, layout options and fading are not implemented. Existing Armor Status covers equipped-item icons/durability; this mod focuses on selected-item text and enchantment names. See the source for validation and exact engine/mixin pins."
|
||||
authors = ["AltMugen"]
|
||||
owners = ["AltMugen"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/AltMugen/horizon-held-item-info"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.0"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "held_item_info-0.1.0.hnmod"
|
||||
sha256 = "37a11d98f0afabe37f8ffa9982dc710ad2985817db6b5e094d807c24d30a6a6a"
|
||||
changelog = "Initial reviewed native release."
|
||||
@@ -0,0 +1,38 @@
|
||||
id = "hitbox_plus"
|
||||
kind = "native-mod"
|
||||
name = "Hitbox+"
|
||||
summary = "Customizable entity hitboxes with exact weapon & spear in-reach colors, thickness, eye rays, and sprint HUD."
|
||||
description = """
|
||||
Hitbox+ for Horizon
|
||||
|
||||
Hitbox+ is a high-performance native mod ported to Horizon that revamps vanilla F3+B debug hitboxes with full customization and PvP reach indicators.
|
||||
|
||||
Key Features:
|
||||
Dynamic In-Reach Detection: Hitboxes automatically change to your chosen reach color when your crosshair is within hitting distance.
|
||||
Spear Reach: Accurately extends reach to 4.5 blocks (survival) and 6.5 blocks (creative).
|
||||
Melee Reach: Standard 3.0 blocks for swords, axes, maces, and fists.
|
||||
11 Selectable Reach Colors: Choose between Bright Green, Neon Cyan, Aqua Mint, Gold Yellow, Sunset Orange, Hot Pink, Neon Purple, Electric Blue, Crimson Red, Pure White, or smooth dynamic Rainbow.
|
||||
Hitbox Styles & Thickness: Custom styles (White, Cyan, Yellow, Red, Rainbow) and 3 thickness modes (1.5px Thin, 2.5px Default, 4.0px Thick).
|
||||
Eye-Ray & Looking Direction: Toggle looking direction lines and forehead level markers.
|
||||
Always-On Sprint HUD: Built-in sprint status indicator with customizable screen corner placement (Top-Left, Top-Right, Bottom-Left, Bottom-Right).
|
||||
Zero FPS Cost: Pure lock-free atomic architecture.
|
||||
Controls:
|
||||
Press H to toggle hitboxes on/off.
|
||||
Access Options > Mods > Hitbox+ to customize all colors, thickness, and HUD positions."""
|
||||
authors = ["taxtii", "itzglecni"]
|
||||
owners = ["taxtii"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/taxtii/hitbox_plus.git"
|
||||
|
||||
[[versions]]
|
||||
version = "1.3.0"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "hitbox_plus-1.3.0.hnmod"
|
||||
sha256 = "8d1b95e7461e38fc40994b35a82c1f753a58e9751ce27af1dc101a4717dba8a4"
|
||||
changelog = """
|
||||
- Added dynamic spear attack reach support (4.5 blocks in survival, 6.5 blocks in creative with 0.125 hitbox margin).
|
||||
- Standard melee weapons (swords, axes, fists) use exact 3.0-block in-reach detection.
|
||||
- Added 11 selectable reach color options (Bright Green, Neon Cyan, Aqua Mint, Gold Yellow, Sunset Orange, Hot Pink, Neon Purple, Electric Blue, Crimson Red, Pure White, Rainbow).
|
||||
- Removed red hit flashing when attacking entities.
|
||||
- Zero-overhead lock-free atomic rendering with configurable line thickness, eye rays, and always-on toggle sprint HUD."""
|
||||
@@ -0,0 +1,31 @@
|
||||
id = "horizon_physics"
|
||||
kind = "native-mod"
|
||||
name = "Horizon Physics"
|
||||
summary = "Physics for blocks, mobs, items, snow, water, smoke, capes and more, with its own settings screen."
|
||||
description = """
|
||||
By tariksabanuz. Physics for Horizon in the spirit of PhysicsMod: broken blocks fall apart into pieces, mobs die as
|
||||
ragdolls, snow gives way under your feet, water waves, smoke rises and plants sway in the wind.
|
||||
|
||||
- Broken blocks crumble into pieces (blocky, particles, crumbled voxel or fractured). Mobs die as ragdolls or come apart.
|
||||
- Structures and trees fall when what holds them up is broken. Dropped items tumble and settle.
|
||||
- Snow layers are pressed down by you and the mobs, water has waves that boats (and you in them) ride, and leaves, plants and vines sway.
|
||||
- Hit a ragdoll or a piece and it flies off; grass and flowers bend away as you walk through them.
|
||||
- Fire, campfires and lava give off smoke and embers that gather and darken under ceilings, capes and banners are cloth, doors swing open and shut, leads and fishing lines are ropes.
|
||||
- Rain splashes and rings the water, snow falls, and the wind blows harder with the weather.
|
||||
- A Physics Settings button in Options opens a screen with a page for every part, and a Quick Setup the first time you start.
|
||||
|
||||
Needs the Performance build in the launcher. Inspired by PhysicsMod by Haubna; this is a clean-room version for
|
||||
Horizon and contains none of its code or assets. It uses your own game's textures at runtime, and the icon is my own."""
|
||||
authors = ["tariksabanuz"]
|
||||
owners = ["tariksabanuz"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/tariksabanuz/PhysicsModHorizon"
|
||||
icon = "icons/horizon_physics.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.15.1"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "horizon_physics-0.15.1.hnmod"
|
||||
sha256 = "d7cf1201f0a47a852aa1a4c9684ef9e658ec3c86852104d44716d05f11281ca3"
|
||||
changelog = "First release: block, mob, item, snow, water, smoke, cloth, weather and collapse physics, with a Physics Settings screen."
|
||||
@@ -0,0 +1,64 @@
|
||||
id = "horizonmatica"
|
||||
kind = "native-mod"
|
||||
name = "Horizonmatica"
|
||||
summary = "Litematica for Horizon: schematics as ghost blocks, a verifier, material lists and a printer that builds the missing blocks for you."
|
||||
description = """
|
||||
Horizonmatica is a re-creation of **Litematica** (with its **printer**) for Horizon. Load a schematic, see it as ghost blocks in your world, check your build against it, get a material list, and let the printer place the missing blocks.
|
||||
|
||||
## Features
|
||||
- **Formats:** `.litematic` (versions 1–7, several regions), `.schem` (Sponge v1–v3: WorldEdit, FAWE, Amulet, Axiom), `.schematic` (MCEdit / WorldEdit up to 1.12) and vanilla structure `.nbt`. Older files are upgraded with Horizon's data fixer, the same way old worlds are.
|
||||
- **Overlay:** missing blocks as translucent real block models (chests, banners, heads and other block entities included), optionally visible through walls.
|
||||
- **Verifier:** wrong block (red), wrong state (orange), extra block (pink), plus a progress HUD.
|
||||
- **Layers:** all / one layer / above / below / range.
|
||||
- **Placement:** move, rotate, mirror; a move mode for mouse wheel and arrow keys. Each placement is remembered per world and dimension and restored when you join again.
|
||||
- **Material list:** missing, total and carried, with item icons, in the HUD, in chat or in the menu.
|
||||
- **Menu (M):** a screen of its own, drawn with the game's widgets.
|
||||
- **Printer:** places one missing block within reach every few ticks, from the bottom up. It only clicks when Horizon's own placement logic says the click produces exactly the wanted state (stairs, slabs, logs, furnaces…). Redstone-aware order, repeater, comparator and note block setup after placing, double slabs and stacks, chests, falling blocks. The camera never moves.
|
||||
|
||||
Usage: put schematics into `schematics/` next to `options.txt` of your instance (`/hm folder` shows the path), then `/hm load <name>` or press **M**. All commands and keys are in the [README](https://github.com/keksi2k/horizonmatica#usage).
|
||||
|
||||
## What it does and doesn't do
|
||||
- **Reads** only files in the instance's `schematics/` folder, and creates that folder if it's missing.
|
||||
- **Writes** nothing itself: settings and remembered placements go through Horizon's mod settings.
|
||||
- **Network:** no connections of its own. The only thing sent to a server is what the printer does: the same block-placing clicks a player would make (with the matching look direction), and hotbar slot changes.
|
||||
- **"Open folder"** in the menu opens the schematics folder in your file manager through Horizon's own function.
|
||||
- No telemetry, no downloads, no code run from schematic files. Schematics are parsed as data only.
|
||||
|
||||
⚠️ On other people's servers, automatic placing may break the rules or trip anti-cheat. The printer is off until you turn it on (`K` or `/hm printer on`). Its *air place* option (on by default) is noticed by anti-cheat plugins such as Grim.
|
||||
|
||||
**Version:** native mods use game internals, so Horizonmatica is pinned to one Horizon commit (currently Nightly 2026-11-01, `4aa6854`). A new Nightly needs a new release.
|
||||
|
||||
## Credits
|
||||
The idea, the way it's used, the file format and the behaviour come from **[Litematica](https://github.com/maruohon/litematica)** by masa (maruohon), maintained by **[Sakura-Ryoko](https://github.com/sakura-ryoko/litematica)**, and from **[Litematica Printer](https://github.com/aleksilassila/litematica-printer)** by aleksilassila. Horizonmatica is not an official project of these authors, isn't made or endorsed by them, and contains none of their code. Only the file format and the behaviour are re-created. If you like it, go and support the originals.
|
||||
|
||||
Menus built with [horizon-menus](https://github.com/keksi2k/horizon-menus). MIT licensed."""
|
||||
authors = ["keksi2k"]
|
||||
owners = ["keksi2k"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/keksi2k/horizonmatica"
|
||||
icon = "https://raw.githubusercontent.com/keksi2k/horizonmatica/main/icon.png"
|
||||
key = "RWS+BRoCJslNCFapck3cbG2VFQcjlr1MUH5m3+CWA8zhJecoBoja7X94"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.1"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "horizonmatica-0.1.1.hnmod"
|
||||
sha256 = "2ddc562dd2ea0f9a76a47eb761c64c803def68a8c81b92cb5d15ec26c5d432aa"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key\r
|
||||
RUS+BRoCJslNCOkWo88+wHXYmMr1C6TzXpxZIGwzFuUN+K4lbd9RT6tLC8sIQQ5uD3QZQZx2rawTHRJvUvRhCgUNDoqhIek18w4=\r
|
||||
trusted comment: timestamp:1793599192\tfile:horizonmatica-0.1.1.hnmod\thashed\r
|
||||
BmryY+OjbG0qZnnFappBEO2tR8zx+a5BmqBFA4AVytjqvLnuvDWYE0PUwZLLodqbN218NM0JluVGpstnI3DvBQ=="""
|
||||
changelog = """
|
||||
First release in the registry.
|
||||
|
||||
- Loads .litematic, .schem (Sponge v1–v3), .schematic (MCEdit, 1.12 ids) and structure .nbt; older files are upgraded with Horizon's data fixer
|
||||
- Ghost overlay with real block models, see-through mode, verifier colours and layer modes
|
||||
- Placements remembered per world and dimension; move mode, rotate, mirror
|
||||
- Own menu screen (M) and a material list with item icons
|
||||
- Printer: places missing blocks within reach, checked against the game's own placement logic; the camera never moves
|
||||
|
||||
Since 0.1.0 on GitHub: loading another schematic no longer shows the previous one's blocks.
|
||||
|
||||
Built for Horizon Nightly 2026-11-01 (c9d474d, hook API 80)."""
|
||||
@@ -0,0 +1,39 @@
|
||||
id = "inventory_wizard"
|
||||
kind = "native-mod"
|
||||
name = "InventoryWizard"
|
||||
summary = "InventoryWizard's one-click sorting as a native mod for Horizon"
|
||||
description = """
|
||||
## Features
|
||||
|
||||
- **Smart sorting** by category (stone, earth, wood, ores, blocks, tools, weapons, armor, food, redstone,
|
||||
transportation, decoration), from item tags and components, so other mods' items are sorted too
|
||||
- **Survival-friendly hotbar**: weapons, tools, food, building blocks, utility items, then the rest
|
||||
- **Stacks merged**, but enchanted or named items are never combined
|
||||
- **Three modes**: Default, Alphabetical and Stack-based
|
||||
- **Sort buttons** by the inventory and container titles, plus a mode button (it shows the mode's letter)
|
||||
- **Locked slots**: **Alt+Click** a hotbar or inventory slot to lock it, and sorting leaves it alone
|
||||
- **Keys**: **R** (or **Shift+Right Click**) sorts the part under the cursor: the hotbar sorts everything, the
|
||||
inventory the inventory, a container the container. Outside a screen, R sorts the whole inventory.
|
||||
**Shift+Right Click** on the middle hotbar slot cycles the mode. The mode also has its own key, unbound by default.
|
||||
- **Commands**: `/iwiz [hotbar|inventory|all|mode]` (also `/inventorywizard`)
|
||||
- **Works on** the inventory, hotbar, chests, barrels, shulker boxes and ender chests, **in singleplayer and on any
|
||||
server**: every sort is made of ordinary left clicks, as a player could click them, so a vanilla server accepts it"""
|
||||
authors = ["VanishingTacos"]
|
||||
owners = ["VanishingTacos"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/VanishingTacos/InventoryWizard-Horizon"
|
||||
icon = "https://cdn.modrinth.com/data/cU0ynk3p/21b58402405493964af438e3e3b9551676b68433.png"
|
||||
key = "RWTos7ZtiqwDTrtjtHk3WhMJJc1+sSTTyTu9CaDtIYWSQvww2D9WrAN1"
|
||||
|
||||
[[versions]]
|
||||
version = "2.3.3"
|
||||
published = "2026-11-01"
|
||||
game = "26.3"
|
||||
file = "inventory_wizard-2.3.3.hnmod"
|
||||
sha256 = "03a7c8a528148611e5f309f3d05294a97b6766ca5e3bda9b3f1f79458fe65a42"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key\r
|
||||
RUTos7ZtiqwDTmRp04qx/n5ZXozvaeOig3nJZFeNqmfmZ1PjB/2JUcfiF0JLZZJBkqpwm6sZQAvrt4HNce0juB5KaxJUOQJtAAo=\r
|
||||
trusted comment: timestamp:1793498930\tfile:inventory_wizard-2.3.3.hnmod\thashed\r
|
||||
Q0SE4CMnaFQHCmizFD0JcIPkUfiYQVs3KyGCCpS99m3OfFNhnS0gQt20ul0QlyYDAC8bAPJRjyrSIgcD1KzPAQ=="""
|
||||
changelog = "Full native port of InventoryWizard for Horizon "
|
||||
@@ -0,0 +1,17 @@
|
||||
id = "invisible_frames"
|
||||
kind = "native-mod"
|
||||
name = "Invisible Frames"
|
||||
summary = "Sneak-right-click a filled frame to hide and lock it, or restore it."
|
||||
description = "Server-side frame visibility toggling for Horizon 26.3. Ordinary and glowing frames are supported. Empty visible frames remain visible. Original MIT implementation inspired by ADHDMC/InvisibleFrames; no Java source or assets included. See the source repository for tested engine/mixin pins, build instructions and validation scope."
|
||||
authors = ["AltMugen"]
|
||||
owners = ["AltMugen"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/AltMugen/horizon-invisible-frames"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.1"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "invisible_frames-0.1.1.hnmod"
|
||||
sha256 = "76128b48ce5c826007379c85634b934ae6bad51c134fbaead7c46b36fecd9274"
|
||||
changelog = "Use the acting player's authoritative server sneak input instead of physical keyboard state."
|
||||
@@ -0,0 +1,34 @@
|
||||
id = "jade"
|
||||
kind = "native-mod"
|
||||
name = "Jade"
|
||||
summary = "The look-at tooltip: what you're pointing at, its mod, its details and its state."
|
||||
description = """
|
||||
An unofficial port of [Jade](https://github.com/Snownee/Jade) 26.3.5 by Snownee to Horizon: the look-at overlay for blocks and entities, with its providers, its settings under Options > Mods, its keys, and the `/jade` and `/jadec` commands.
|
||||
|
||||
Rewritten in Rust for Horizon's hooks, so no original code runs. Not made or endorsed by Snownee, so please report problems to this project, not to them.
|
||||
|
||||
**Ported:** themes, opacity, text background, profiles, ignore lists, boss bar overlap, TTS, perspective mode, reach, icon positions, the item mod name and the plugin sub-options.
|
||||
|
||||
**What differs from Jade:**
|
||||
- Themes are drawn with solid fills in the theme's colours, not Jade's sprites.
|
||||
- The position adjust screen is a setting you cycle through, not a screen you drag on.
|
||||
- The sniffer's dig cooldown isn't shown.
|
||||
- Energy Storage has nothing to show, because Horizon has no shared energy API for other mods.
|
||||
- Access variant and NPC details are approximate.
|
||||
|
||||
Tested on Windows, in single player and on LAN with one guest. Dedicated servers don't build native mods, so "server" here means a LAN host.
|
||||
|
||||
Licence: CC BY-NC-SA 4.0, noncommercial use only, the same licence as Jade."""
|
||||
authors = ["Snownee", "Joeypc6"]
|
||||
owners = ["Joeypc6"]
|
||||
license = "CC-BY-NC-SA-4.0"
|
||||
source = "https://github.com/Joeypc6/Jade-Horizon"
|
||||
icon = "https://media.forgecdn.net/avatars/thumbnails/207/323/256/256/636965628804677340.png"
|
||||
|
||||
[[versions]]
|
||||
version = "26.3.5"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "jade-26.3.5.hnmod"
|
||||
sha256 = "676a129f55db075284313a39ff4387674c426ebd9be04a8830ffb8955281c7ec"
|
||||
changelog = "First Horizon release, a port of Jade 26.3.5. Built and tested on Horizon commit c9d474d."
|
||||
@@ -0,0 +1,34 @@
|
||||
id = "killc"
|
||||
kind = "native-mod"
|
||||
owners = ["Vakarux12"]
|
||||
key = "RWS5u/7lEyKbzVHC6uMJRlhM/N7vzKp5fZe2LCDUlHsDK4lvPupxJbqQ"
|
||||
name = "KillC"
|
||||
summary = "/killc, /killc <player> and /suicide, with an optional random respawn near (0, 0)."
|
||||
description = """
|
||||
A Horizon port of [adasjusk's KillC](https://github.com/adasjusk/KillC), the kill command plugin for Paper, Folia, Velocity and Fabric.
|
||||
|
||||
- `/killc` and `/suicide` kill you.
|
||||
- `/killc <player>` kills another player (operator level 2).
|
||||
- After a death in the Overworld, players respawn at a random surface spot within `randomSpawnRadius` of (0, 0).
|
||||
- Config: `config/killc.json` (`enabled`, `useRandomSpawn`, `randomSpawnRadius`), the same file as the Fabric build.
|
||||
|
||||
Vanilla keeps `/kill`. Runs where the world is hosted: single player and worlds opened to LAN (Horizon's dedicated server cannot build native mods yet). Native mods run with the player's account permissions and are not sandboxed.
|
||||
|
||||
Source: `horizon/` in https://github.com/Vakarux12/KillC, a fork of the original. CC-BY-SA-4.0, the original's licence, with a grant for Horizon's reviewers in `horizon/REVIEW-GRANT.md`.
|
||||
"""
|
||||
authors = ["adasjusk", "Vakarux12"]
|
||||
license = "CC-BY-SA-4.0"
|
||||
source = "https://github.com/Vakarux12/KillC/tree/main/horizon"
|
||||
|
||||
[[versions]]
|
||||
version = "5.1.0"
|
||||
published = "2026-11-01"
|
||||
game = "26.3"
|
||||
file = "killc-5.1.0.hnmod"
|
||||
sha256 = "6c44d0a5e93aef42f2a33df8286980d9957a04526ff2c1884dfe7aa83f837086"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RUS5u/7lEyKbzbHxeuREFeXgBYM6FjB/wiwBtmdu5na35k0DXINdt3FILWvtW7yDekrFYjn4Xrl5pv9ttijPbocgpNbqZpPqLgY=
|
||||
trusted comment: timestamp:1793694719 file:killc-5.1.0.hnmod hashed
|
||||
vC2AGwA5JYAw1yjFLScjYyy+ef03gA5lxE3mwpD/D6CqKRblrpIKtHacgjYViC714ob5w1fgXFPya8AobYmVBg=="""
|
||||
changelog = "First Horizon release, ported from adasjusk's KillC."
|
||||
@@ -0,0 +1,22 @@
|
||||
id = "mod_menu"
|
||||
kind = "native-mod"
|
||||
name = "Mod Menu"
|
||||
summary = "ModMenu For Horizon"
|
||||
description = """
|
||||
Adds a Mods button next to Accessibility on the title screen. It opens a Mod Menu style screen that lists every mod you have installed, with its icon, name, version and description.
|
||||
|
||||
- Search by name, id or description, and filter by on, off, native or content mods.
|
||||
- Pick a mod to see its details, turn it on or off, or open its own settings page.
|
||||
- Open Mods Folder and Done at the bottom, as in the Java mod."""
|
||||
authors = ["tariksabanuz"]
|
||||
owners = ["tariksabanuz"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/tariksabanuz/ModMenuHorizon"
|
||||
icon = "https://raw.githubusercontent.com/tariksabanuz/ModMenuHorizon/main/icon.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.3.0"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "mod_menu-0.3.0.hnmod"
|
||||
sha256 = "7896b3b5ad727ef6e2bc56039796713809483fb157daa385f78ebd3353d653bd"
|
||||
@@ -0,0 +1,4 @@
|
||||
id = "radiant"
|
||||
kind = "shader"
|
||||
repo = "expensiverest/radiant"
|
||||
owners = ["expensiverest"]
|
||||
@@ -0,0 +1,38 @@
|
||||
id = "resourcify"
|
||||
kind = "native-mod"
|
||||
name = "ResourcifyHorizon"
|
||||
summary = "Resourcify for Horizon"
|
||||
description = """
|
||||
Find and install resource packs from Modrinth without leaving the game. By tariksabanuz.
|
||||
|
||||
A **+** button appears in the top right of the Resource Packs screen. It opens a browser with:
|
||||
|
||||
- a search box that searches while you type, a sort button (Relevance, Downloads, Newest, Updated) and a switch between "for this game version" and "all versions";
|
||||
- a list of packs with pictures, authors and download counts, loaded as you scroll;
|
||||
- a detail pane with the versions of the selected pack and an **Install** button.
|
||||
|
||||
Installing downloads the file from Modrinth's own server (`cdn.modrinth.com` only), checks it against the SHA-1 hash Modrinth provides, and saves it in `resourcepacks/`. Nothing is turned on for you.
|
||||
|
||||
Source code: https://github.com/tariksabanuz/ResourcifyHorizon"""
|
||||
authors = ["tariksabanuz"]
|
||||
owners = ["tariksabanuz"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/tariksabanuz/ResourcifyHorizon"
|
||||
icon = "https://github.com/tariksabanuz/ResourcifyHorizon/blob/364648324ac0e67489a3f06faa716d96d24668ed/icon.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.1"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "resourcify-0.1.1.hnmod"
|
||||
sha256 = "a6611819c9401dc7370dece7453cdda2356747f2a34c32940bf82ccd6abdcf53"
|
||||
changelog = """
|
||||
- Version 0.1.1.
|
||||
- Rebuilt and re-checked against the current Horizon revision."""
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.0"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "resourcify-0.1.0.hnmod"
|
||||
sha256 = "789447fb454864af2a711ad8204f395331248d70dba570016b248766b959a2a2"
|
||||
@@ -0,0 +1,50 @@
|
||||
id = "right_click_crops"
|
||||
kind = "native-mod"
|
||||
name = "Right-Click Crops"
|
||||
summary = "Right-click harvest for 16 plant families, with replanting and individual settings."
|
||||
description = """
|
||||
Harvest mature plants with a right-click, replant crops, and keep your garden growing.
|
||||
|
||||
### Features
|
||||
- Supports 16 plant families.
|
||||
- Replants crops using one planting item from the harvest, or from your inventory.
|
||||
- Keeps the base of tall plants and the stems of pumpkins and melons.
|
||||
- Lets you enable or disable each plant separately in **Options > Mods > Right-Click Crops > Settings**.
|
||||
|
||||
### Supported plants
|
||||
Wheat, carrots, potatoes, beetroot, nether wart, cocoa, torchflower, pitcher crop, sugar cane, cactus, bamboo, kelp, twisting vines, weeping vines, pumpkin and melon.
|
||||
|
||||
### Good to know
|
||||
- Harvesting works in survival, one targeted plant at a time.
|
||||
- Without a suitable planting item, the crop is harvested but not replanted.
|
||||
- Torchflower needs spare seeds; pitcher crop needs spare pitcher pods.
|
||||
- Twisting and weeping vines can drop nothing when harvested by hand. Use shears for guaranteed drops.
|
||||
- Bone meal, ordinary breaking and planting, sweet berries and glow berries keep their normal behaviour.
|
||||
|
||||
### Compatibility
|
||||
Last checked on **November 1, 2026**, for Minecraft 26.3. The release is pinned to Horizon Nightly 2026-10-31 (`9d979ca`), where single-player and LAN were tested. A compilation-only check also passed on the newest Nightly available on that date (`d91cab6`); gameplay on that newer revision was not tested.
|
||||
|
||||
This is a native mod: install only if you trust its source and accept the launcher's native-code warning.
|
||||
|
||||
[Watch the demo](https://youtu.be/kll-qvj5s54) · [Harvesting guide](https://github.com/AyanoKaito/horizon-right-click-crops/blob/main/docs/harvesting.md)
|
||||
"""
|
||||
authors = ["AyanoKaito"]
|
||||
owners = ["AyanoKaito"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/AyanoKaito/horizon-right-click-crops"
|
||||
icon = "icons/right_click_crops.png"
|
||||
key = "RWRwbuaByP5mM4VUm4kZEQVPiuw+3IEVJ7CZcEHIjY5fPKf9lhQKUZRy"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-01"
|
||||
game = "26.3"
|
||||
file = "right_click_crops-1.0.0.hnmod"
|
||||
sha256 = "681ce896c50dd041132900e7bbab71167f133b3f3862f86e8b1a0cac52754b97"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RURwbuaByP5mM4x8HGWHv/S/WlHPsmamRwsi70PTq7E5u4uJ7wyNzNT4rwpR/vGA9V2H6w9yLhmF1CPtS1grEfWorPixnk6efAw=
|
||||
trusted comment: timestamp:1793523764\tfile:right_click_crops-1.0.0.hnmod\thashed
|
||||
seiWz0D/X34FIKhiE1yfZc2uAkkSGuwAnTHbGrK63sHg+HdL+EgqEkzaxNgJTiMOdnf/iIdSkDVVwuF+Od/SCQ==
|
||||
"""
|
||||
changelog = "First public release: right-click harvesting for 16 plant families, ordinary Horizon loot, paid replanting, retained bases and stems, and individual plant settings. Validated in single-player and for LAN host and guest."
|
||||
@@ -2,16 +2,21 @@ id = "rightharvest"
|
||||
kind = "native-mod"
|
||||
name = "RightClickHarvest"
|
||||
summary = "Right-click a ripe crop to pick it and sow it again."
|
||||
description = """
|
||||
With an empty hand, right-click a ripe wheat, carrot, potato, beetroot or nether wart: the crop is harvested with the game's own drops, sound and statistics, and sown again from a seed in your inventory.
|
||||
|
||||
No settings: turn it off in Options > Mods."""
|
||||
description = "With an empty hand, right-click a ripe wheat, carrot, potato, beetroot or nether wart: the crop is harvested with the game's own drops, sound and statistics, and sown again from a seed in your inventory."
|
||||
authors = ["Domanffe"]
|
||||
owners = ["Domanffe"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Domanffe/rightharvest"
|
||||
icon = "https://horizon-rust.github.io/horizon-mods/icons/rightharvest.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.1"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "rightharvest-0.1.1.hnmod"
|
||||
sha256 = "2f70f3a5abaca35f1ff8df7b198f0fd616eacaa5229f5113f75935e16f50255b"
|
||||
changelog = "Rebuilt on the 2026-11-01 Nightly (Horizon `4aa6854`); the `mods` hook is named instead of pinned to a source target, so it survives an update that moves that point."
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.0"
|
||||
published = "2026-10-30"
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
id = "rmotd"
|
||||
kind = "native-mod"
|
||||
owners = ["Vakarux12"]
|
||||
key = "RWS5u/7lEyKbzVHC6uMJRlhM/N7vzKp5fZe2LCDUlHsDK4lvPupxJbqQ"
|
||||
name = "RMotd"
|
||||
summary = "Rotating server list MOTDs, managed in game with /randommotd and /motd."
|
||||
description = """
|
||||
A Horizon port of [adasjusk's RMotd](https://github.com/adasjusk/RMotd), the rotating MOTD plugin.
|
||||
|
||||
- The MOTD in the server list changes every 10 seconds, through the list in `config/rmotd.json` (the Fabric build's file).
|
||||
- `/randommotd` turns rotation on and off.
|
||||
- `/motd create <name> <motd>` adds an MOTD, `/motd reload` reads the file again (operator level 2).
|
||||
- MOTDs take `&` colour codes.
|
||||
|
||||
It sets the MOTD of a world opened to LAN. The server list ping shows the rotation, the LAN broadcast keeps the first one. Horizon has no MOTD hook point, so a support module in `horizon_client::lan` writes the private MOTD field of the LAN server. Its injections are all hook points, but that field is not a stable API, so a later Nightly can break the build. Runs where the world is hosted: single player and worlds opened to LAN (Horizon's dedicated server cannot build native mods yet). Native mods run with the player's account permissions and are not sandboxed.
|
||||
|
||||
Source: `horizon/` in https://github.com/Vakarux12/RMotd, a fork of the original. CC-BY-SA-4.0, the original's licence, with a grant for Horizon's reviewers in `horizon/REVIEW-GRANT.md`.
|
||||
"""
|
||||
authors = ["adasjusk", "Vakarux12"]
|
||||
license = "CC-BY-SA-4.0"
|
||||
source = "https://github.com/Vakarux12/RMotd/tree/main/horizon"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-01"
|
||||
game = "26.3"
|
||||
file = "rmotd-1.0.0.hnmod"
|
||||
sha256 = "68d43b760e95178a67bc1c7d54fbde004eee4bb764d9891d83bd4e4fa4bd8ce5"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RUS5u/7lEyKbzSnV+LLOgmX/1ryZ/5d3asf4KyfdUUOJKALk9isprehFuFIDN5X+GZy0C7jzHAImFnq9FRt2yc1J3N5lbA1oUgM=
|
||||
trusted comment: timestamp:1793694734 file:rmotd-1.0.0.hnmod hashed
|
||||
x+Ecd8KV0OFBcUEONAvAHxw87IG2MnjWZzcrIiMLjRNtl7KcuZQXvakrAm6slC1qADzj+n+HpwYoGT1QmQ07Bg=="""
|
||||
changelog = "First Horizon release, ported from adasjusk's RMotd."
|
||||
@@ -0,0 +1,32 @@
|
||||
id = "server_browser"
|
||||
kind = "native-mod"
|
||||
name = "Server Atlas"
|
||||
summary = "Discover and organize Minecraft servers with filters, favorites and local notes."
|
||||
description = """
|
||||
Server Atlas is an independent, MIT-licensed native Rust multiplayer browser for Horizon and Minecraft Java 26.3, with familiar Minecraft buttons and translucent server rows.
|
||||
|
||||
Features: My Servers, Discover, Favorites, Recent and LAN tabs; search names, addresses, MOTDs, tags and notes; combined status, version, ping and player-count filters; local notes and groups; custom ordering; saved filter profiles; JSON/NBT import/export preserving unknown vanilla fields. English and German are included.
|
||||
|
||||
Public discovery combines Modrinth and minecraftserve.rs with a bundled catalog of 2,835 public addresses. It is enabled by default and can be switched off. Personal server lists, notes and search text are not submitted to directory providers. Normal status pings contact the servers being checked. Feedback and server suggestions save local drafts; automatic email delivery is not configured. Joining and authentication use Horizon's existing implementation.
|
||||
|
||||
Install the .hnmod in the desired Horizon instance, enable it, build through the official launcher and open Multiplayer in that built instance. Native code runs with the player's permissions. No separate host patch or companion executable is required.
|
||||
|
||||
Version 2.2.0 was built and tested on Nightly 2026-11-04: Horizon 6475f62f3c834b7489e1816bf47f47ea5eb2b879 and horizon-mixins a2af5c0dd4117d51ecd70066ba7a00b4a2c10dab. The official package checker, native build, 44 Rust tests and isolated game checks pass. Runtime coverage includes 10,000 saved entries, CRUD/filter/undo, Mods on/off, controller keyboard, GUI scales/4K, both live directories and real local-server Join/Direct Connect. Future Nightlies and combined native mod sets need separate validation. This bundle is unsigned.
|
||||
|
||||
Real game captures and installation: https://musti3214.github.io/Horizon-Server-Browser/
|
||||
Validation: https://github.com/Musti3214/Horizon-Server-Browser/blob/v2.2.0/mod/VALIDATION.md
|
||||
|
||||
Developed with Codex assistance at the owner's request. Separate Fabric and Forge public betas are different files from this native Horizon bundle."""
|
||||
authors = ["shuab"]
|
||||
owners = ["Musti3214"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Musti3214/Horizon-Server-Browser/tree/v2.2.0/mod"
|
||||
icon = "https://raw.githubusercontent.com/Musti3214/Horizon-Server-Browser/v2.2.0/docs/horizon-registry/icons/server_browser.png"
|
||||
|
||||
[[versions]]
|
||||
version = "2.2.0"
|
||||
published = "2026-11-05"
|
||||
game = "26.3"
|
||||
file = "server_browser-2.2.0.hnmod"
|
||||
sha256 = "e65411ec3ed57c2ef288b627d0337cb1592762c24a869024a301b4c57bdfa94e"
|
||||
changelog = "Initial registry submission of Server Atlas 2.2.0. Updated for Horizon Nightly 2026-11-04 (6475f62): client library, rendering, scrolling, keyboard actions, LAN connection flags and DNS resolution. Official package checker, native build, 44 Rust tests and isolated game checks pass, including Join/Direct Connect against a real local dedicated server."
|
||||
@@ -0,0 +1,21 @@
|
||||
id = "smoothie_capes"
|
||||
kind = "native-mod"
|
||||
name = "Smoothie Capes"
|
||||
summary = "An Wavey Capes inspired mod for Horizon"
|
||||
authors = ["Nully"]
|
||||
owners = ["dumbnully"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/dumbnully/smoothie-capes"
|
||||
key = "RWRJPBl24rTE23dFezewHWl465FAcgTsmeJnDkANtUPT19YfVmQ1gYCu"
|
||||
|
||||
[[versions]]
|
||||
version = "0.2.0"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "smoothie_capes-0.2.0.hnmod"
|
||||
sha256 = "303b88bf5dd2c518ed9f5186252813b5a98716289c42e60838d0cb9846fc6429"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RURJPBl24rTE247uqvyB1Bh5PIfR4C2XUVWvCx4/lt5jAO8sgDBEgtfs9adTKkv+L89ENRyYUVCLG1c8yptts8AYfcmPEI7bcQs=
|
||||
trusted comment: timestamp:1793663973\tfile:smoothie_capes.hnmod\thashed
|
||||
f+QyN8EVz5M41RHayEZGX7Fk1Z+FZnhUTv7MwH5Y3GTBYXiNMAHAIMdox4i62RDTx3wQhVUuIOBa3GqJ2H7KAQ=="""
|
||||
@@ -0,0 +1,35 @@
|
||||
id = "stuck"
|
||||
kind = "native-mod"
|
||||
owners = ["Vakarux12"]
|
||||
key = "RWS5u/7lEyKbzVHC6uMJRlhM/N7vzKp5fZe2LCDUlHsDK4lvPupxJbqQ"
|
||||
name = "Stuck?"
|
||||
summary = "/stuck and /escape move you to a safe spot nearby, off the Nether roof too."
|
||||
description = """
|
||||
A Horizon port of [adasjusk's Stuck?](https://github.com/adasjusk/Stuck), the unstuck plugin for Spigot, Paper, Folia and Fabric.
|
||||
|
||||
- `/stuck` and `/escape` search random columns near you for solid ground with two blocks of air above, and teleport you there.
|
||||
- Skips lava, fire, magma, cactus and other hazards, and leaves and snow.
|
||||
- A player on the Nether's bedrock roof is brought back under it.
|
||||
- Cooldown between uses, 30 seconds by default.
|
||||
- Config: `config/stuck.properties`, the same keys as the Fabric build.
|
||||
|
||||
Only loaded chunks are searched. Runs where the world is hosted: single player and worlds opened to LAN (Horizon's dedicated server cannot build native mods yet). Native mods run with the player's account permissions and are not sandboxed.
|
||||
|
||||
Source: `horizon/` in https://github.com/Vakarux12/Stuck, a fork of the original. CC-BY-SA-4.0, the original's licence, with a grant for Horizon's reviewers in `horizon/REVIEW-GRANT.md`.
|
||||
"""
|
||||
authors = ["adasjusk", "Vakarux12"]
|
||||
license = "CC-BY-SA-4.0"
|
||||
source = "https://github.com/Vakarux12/Stuck/tree/main/horizon"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-01"
|
||||
game = "26.3"
|
||||
file = "stuck-1.0.0.hnmod"
|
||||
sha256 = "8e6292d9c89f660e72f01e54be4103b5273017955c7bd8034dd5ae8ec2e98630"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RUS5u/7lEyKbzf0/fn5Is2b8jJq55073yA8Sl7hSeLN1jAg9itcMlCO2kcEMVJaGyYrxFZIwPYfQJMCb61o/0g8XD8iYIUCeswU=
|
||||
trusted comment: timestamp:1793694727 file:stuck-1.0.0.hnmod hashed
|
||||
/JDVcy8eoaPHppahV7p+f+3LTx0CtfE34jqqZq7bU4TNvnSOx7ISCgp6Eg3+X1xYMRJRwTYM2aJwgbytRGzOCA=="""
|
||||
changelog = "First Horizon release, ported from adasjusk's Stuck."
|
||||
@@ -0,0 +1,30 @@
|
||||
id = "tectonic_horizon"
|
||||
kind = "native-mod"
|
||||
name = "Tectonic-Horizon"
|
||||
summary = "Unofficial native port of Tectonic: mountain ranges, underground rivers and configurable terrain."
|
||||
description = """
|
||||
Unofficial native Rust port of Tectonic 3.0.1 by Apollo (Apollounknowndev), revision 0761b561062de01b701d2571401f625c31059a9a under CC0-1.0. Not made or endorsed by Apollo or the Horizon project.
|
||||
|
||||
Mountain ranges, terrain density recipes, underground rivers and configurable terrain for Horizon 26.3. Source-only native mod: install in the launcher, then Build; runs with the game's account permissions. No Minecraft code or assets are included.
|
||||
|
||||
Enable under Options > Mods before opening a world. The mod's Settings page edits terrain and biome configuration. Config: config/tectonic-horizon.json in the game home. Invalid configuration logs a diagnostic and uses defaults. Restart after editing; new chunks only. Select increased height before world creation.
|
||||
|
||||
Pins upstream Horizon 8dbbde43501924d16497d251e6e9d08f812eafcd and Mixins e8cd0aa38cffef49cb2e088ef716baa107148c02. See docs/REVIEW-0.3.4.md for current validation and docs/VALIDATION.md for historical checks with their original revisions.
|
||||
|
||||
No block-for-block Java parity claim. Native river-decoration placement differs from Lithostitched. Java config UI and Terralith/CliffTree overlays are omitted. Other biome mods need their own Horizon ports.
|
||||
|
||||

|
||||
|
||||
Author-supplied screenshot captured November 1 in our Horizon fork; illustrative, not evidence of current upstream validation. Minimap is a separate mod. Original Tectonic by Apollo; Horizon adaptation by eltanschauung with Codex assistance. Source licenses, notices and provenance hashes retained."""
|
||||
authors = ["eltanschauung", "Apollo (original Tectonic)"]
|
||||
owners = ["eltanschauung"]
|
||||
license = "CC0-1.0"
|
||||
source = "https://github.com/eltanschauung/tectonic-horizon"
|
||||
|
||||
[[versions]]
|
||||
version = "0.3.4"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "tectonic_horizon-0.3.4.hnmod"
|
||||
sha256 = "590198d7df43b5c9474c41648db89a15bd4d388be0fe860a2f84a84b59285cec"
|
||||
changelog = "Revision of PR #160: removes unsupported runtime-toggle.json, falls back to defaults with a diagnostic for invalid/unreadable/oversized configuration, and fixes the GitHub formatting failure. Includes the 0.3.2 in-game settings editor and 0.3.3 upstream height adapter. Pins Horizon 8dbbde43501924d16497d251e6e9d08f812eafcd and Mixins e8cd0aa38cffef49cb2e088ef716baa107148c02. All 13 Rust tests, Clippy, formatting, native-package checking, reproducible packaging, mixin plan/apply, and the patched horizon-world compile check pass. No new interactive game test is claimed. Source: https://github.com/eltanschauung/tectonic-horizon/tree/6f69f2b64a41f0cad09f87840cbdb104138c54c3"
|
||||
@@ -0,0 +1,29 @@
|
||||
id = "visuality_horizon"
|
||||
kind = "native-mod"
|
||||
name = "Visuality"
|
||||
summary = "Small pixel particles: hit fragments, slime blobs, creeper sparks, glints, soul wisps and rain ripples."
|
||||
description = """
|
||||
An original client-side Rust implementation of the effects of PinkGoosik's Visuality (MIT), with its own art made in Blender.
|
||||
|
||||
Effects
|
||||
Hit fragments: bone chips from skeletons, strays and skeleton horses, dark chips from wither skeletons, feathers in each chicken variant's colours, emerald chips from villagers.
|
||||
Slime blobs: chunky blobs in three sizes when a slime lands, in a colour you choose (magma cubes are left alone).
|
||||
Charged creeper sparks, amethyst sparkles on full clusters, armor glints on gold and diamond armor, ore glints on uncovered faces only, soul wisps over soul sand and soil and when sprinting on them, and flat rain ripples on open water.
|
||||
|
||||
Low preset by default, for integrated GPUs; Balanced and High add density. Settings in Options > Mods > Visuality, lists in config/visuality_horizon.toml.
|
||||
Client only: it sends nothing to the server and needs nothing installed there. Tested in single player on Windows; LAN, servers, Linux and macOS are not tested yet (see docs/VALIDATION.md).
|
||||
Pinned to Horizon c9d474d (Nightly 2026-11-01): it hooks private client functions, so it builds on that commit only.
|
||||
Not made or endorsed by Visuality's author."""
|
||||
authors = ["BenjiSyS"]
|
||||
owners = ["BenjiSyS"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/BenjiSyS/visuality-horizon"
|
||||
icon = "icons/visuality_horizon.png"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.2"
|
||||
published = "2026-11-03"
|
||||
game = "26.3"
|
||||
file = "visuality_horizon-1.0.2.hnmod"
|
||||
sha256 = "b764f15a062e44b27c55f478b2d02e163bfb01c3d8e222fcd6d83bcc66f19a0d"
|
||||
changelog = "First release, for Horizon Nightly 2026-11-01 (c9d474d). 1.0.1: entity pass skips entities out of reach (client tick 20-31 us instead of 71-157 us); package entries stored, so the file is byte-identical whatever Python builds it. 1.0.2: atlas and notices carried as Rust source, so the bundle holds only .rs and .toml files."
|
||||
@@ -0,0 +1,42 @@
|
||||
id = "voicechat"
|
||||
kind = "native-mod"
|
||||
name = "Horizon Voice Chat"
|
||||
summary = "Talk with Simple Voice Chat players: proximity voice, groups, push to talk and a menu (V)."
|
||||
description = """
|
||||
An unofficial client for the [Simple Voice Chat](https://github.com/henkelmax/simple-voice-chat) protocol. On a server with the Simple Voice Chat mod or plugin, you can talk with players who use the Java mod on the regular launcher.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Menu (V):** connection status, microphone and voice chat on/off, push to talk or voice activation, voice volume, microphone gain and activation level with a live meter, and every hotkey as it is bound now. The right side lists the server's groups with their members: join (with a password if needed), leave, or create a group.
|
||||
- **Talking:** hold Caps Lock (push to talk) or use voice activation. Voices come from where players stand, getting quieter with distance and panned left or right.
|
||||
- **Groups:** each player's group shows above their head. `/vc join <group> [password]`, `/vc leave`, `/vc create <name> [password] [normal|open|isolated]` and `/vc groups` work too.
|
||||
- **Keys** (Options > Mods > Horizon Voice Chat): menu (V), push to talk (Caps Lock), whisper (unbound), mute (J), voice chat off/on (K).
|
||||
- **Protocols:** Simple Voice Chat 2.6.x (compatibility 20) and 2.7 (21).
|
||||
|
||||
## What it touches
|
||||
|
||||
- It reads the server's `voicechat:*` custom payloads and other players' positions inside `game::remote`, so it is pinned to Horizon `c9d474d`.
|
||||
- It opens one UDP connection to the server's voice chat port, encrypted with AES-128-GCM using the secret the server sends.
|
||||
- It uses the default microphone and speakers through cpal, and loads the system **libopus** at run time (the `opus` package must be installed).
|
||||
- It keeps its settings in Horizon's own mod settings. It contacts no host other than the Minecraft server you are on (and DNS, for the server's SRV record).
|
||||
|
||||
## Not affiliated
|
||||
|
||||
This project is not made, endorsed or supported by Max Henkel or the Simple Voice Chat project. It contains none of Simple Voice Chat's code: everything is written from scratch in Rust.
|
||||
|
||||
## Tested
|
||||
|
||||
The engine's unit tests pass, and the modded client type-checks. Live, against Paper 26.3 with the Simple Voice Chat 2.6.27 plugin, it authenticated and connected, a test tone was heard through the server, and groups and labels came from the server. Not tested yet: the menu in the real game, a real microphone, 2.7 servers, and talking with the Java mod itself.
|
||||
"""
|
||||
authors = ["Nirokx"]
|
||||
owners = ["Nirokx"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Nirokx/horizon-voice-chat"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "voicechat-1.0.0.hnmod"
|
||||
sha256 = "7a12ef9e691d10128ea081906a313d597c67f22897380618871477f9dd8eabf1"
|
||||
changelog = "First release."
|
||||
@@ -0,0 +1,23 @@
|
||||
id = "wayfarer_stones"
|
||||
kind = "mod"
|
||||
name = "Wayfarer Stones (assets)"
|
||||
summary = "The textures, text, recipes and villages of Wayfarer Stones. Needs the Wayfarer Stones mod."
|
||||
description = """
|
||||
**This is one of the two parts of [Wayfarer Stones](https://playhorizon.dev/mods/wayfarer_stones_native), and does nothing alone.** Install both.
|
||||
|
||||
It holds the mod's models and textures, its English and Russian text, its recipes and drops, and the stones villages build. It has no code. The code, and the description of what the mod does, are in Wayfarer Stones.
|
||||
|
||||
All the art is original. No Minecraft assets are included. MIT licensed."""
|
||||
authors = ["bioneisme"]
|
||||
owners = ["Bioneisme"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Bioneisme/wayfarer-stones"
|
||||
icon = "https://raw.githubusercontent.com/Bioneisme/wayfarer-stones/main/content/assets/wayfarer_stones/textures/item/wayfarer_stone.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.6.0"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "wayfarer_stones-0.6.0.hmod"
|
||||
sha256 = "87bec46b6bbe05d95563a4bf7b8a3b92340ca1dd54c2d5709b6a0a41989d7176"
|
||||
changelog = "First release."
|
||||
@@ -0,0 +1,33 @@
|
||||
id = "wayfarer_stones_native"
|
||||
kind = "native-mod"
|
||||
name = "Wayfarer Stones"
|
||||
summary = "Place stones around your world, activate them, and travel between the ones you know."
|
||||
description = """
|
||||
**This mod has two parts, and you need both.** Install this one and [Wayfarer Stones (assets)](https://playhorizon.dev/mods/wayfarer_stones), then press Build.
|
||||
|
||||
- **Place** a stone, or find one in a village. Right-click it once to add it to your list.
|
||||
- **Travel** from any stone you know: pick a destination on the screen, or search for it. You land beside the stone, on solid ground.
|
||||
- **Pay** in experience levels: 1, plus 1 for each 500 blocks, up to 5. Travel between dimensions costs 3.
|
||||
- **Carry** a Wayfarer's Scroll to travel from anywhere. Each travel uses one up.
|
||||
- **Stones are safe:** only the owner or an operator can break one, and pistons won't move it.
|
||||
|
||||
Every world has its own settings: cost, cooldown, warmup and more. English and Russian.
|
||||
|
||||
**Commands:** `/wayfarer`, `/wayfarer list`, `/wayfarer to <name>`, `/wayfarer name <name>`, `/wayfarer forget <name>`. Operators also have `/wayfarer global <name>` and `/wayfarer remove <name>`.
|
||||
|
||||
Native source mod: install it on the launcher's Mods page, press Build there, and confirm the native-code warning. It runs with your account's permissions. It is pinned to one Horizon Nightly and Horizon Mixins revision, named in each version's changelog.
|
||||
|
||||
No Minecraft code or assets are included. MIT licensed."""
|
||||
authors = ["bioneisme"]
|
||||
owners = ["Bioneisme"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Bioneisme/wayfarer-stones"
|
||||
icon = "https://raw.githubusercontent.com/Bioneisme/wayfarer-stones/main/content/assets/wayfarer_stones/textures/item/wayfarer_stone.png"
|
||||
|
||||
[[versions]]
|
||||
version = "0.6.0"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "wayfarer_stones_native-0.6.0.hnmod"
|
||||
sha256 = "0c5929425bea6c570ad455229b519fc411ea2b769ef08be8a91bb8b7793d9dba"
|
||||
changelog = "First release. Pinned to Nightly 2026-11-04 (67dad0d) and Horizon Mixins e8cd0aa."
|
||||
@@ -0,0 +1,31 @@
|
||||
id = "waymap"
|
||||
kind = "native-mod"
|
||||
name = "Waymap"
|
||||
summary = "Native Horizon waypoint mod with per-context storage, minimap dots, world markers, and full command suite."
|
||||
description = """
|
||||
Waymap — Native client-side waypoints for Horizon.
|
||||
Features:
|
||||
- World markers (3D, camera-projected)
|
||||
- Minimap dots (rotation-aware)
|
||||
- Waypoint list panel (bottom-left, 6 nearest)
|
||||
- Per-context storage (per server server_<host:port>.txt / world world_<folder>.txt)
|
||||
- Atomic saves (temp + atomic rename), legacy migration
|
||||
- Commands: /wp add|del|list|rename|color|clear|edit|help
|
||||
- Keys: N = add, B = toggle list"""
|
||||
authors = ["Aron"]
|
||||
owners = ["Lauch2"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Lauch2/horizon-waymap-mod"
|
||||
key = "RWS1B1QZPeYaSNKJr9rffnfHDSvB0AZj/Ul1B2pKrJ2XFBgKXL0FC96u"
|
||||
|
||||
[[versions]]
|
||||
version = "0.1.4"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "waymap-0.1.4.hnmod"
|
||||
sha256 = "61bf573af5b2711453ca37a41b4ac2abc78ab827863bcafb9bfabe7dbf19ccd5"
|
||||
signature = """
|
||||
untrusted comment: signature from minisign secret key
|
||||
RUS1B1QZPeYaSBV67KshMqdN7e9tTtnd0aJ2j2hE0IOvZNQpo896FjvOETBrxu0OhB738CE44moftY8pvDMvF8o+dxXsfxQduAU=
|
||||
trusted comment: timestamp:1793662341\tfile:waymap-0.1.4.hnmod\thashed
|
||||
j0dStr7Yhq33q3uA+wVGhfiEfjdNx0XBCUIHiZ5AfD7vPhcCqtVnrnYx8KKcliC2UOMNBP0Kl3gOz2MyiqJSAQ=="""
|
||||
@@ -0,0 +1,27 @@
|
||||
id = "waypoints"
|
||||
kind = "native-mod"
|
||||
name = "Waypoints"
|
||||
summary = "Place waypoints with N, manage them with M, and see their name and distance in the world."
|
||||
description = """
|
||||
Waypoints for Horizon.
|
||||
|
||||
- **N**: create a waypoint where you stand: name, X/Y/Z, dimension, colour, visible or hidden. Enter saves, Tab moves between fields, Esc cancels.
|
||||
- **M**: the waypoint list, filtered by All / Overworld / Nether / End. Each row shows its colour, name, coordinates, dimension and distance, with Hide/Show, Edit and Delete buttons.
|
||||
- **In the world**: each visible waypoint in your current dimension shows its name, its distance and a marker in its colour.
|
||||
- **Options > Mods > Waypoints**: rebind both keys and turn the in-world labels on or off.
|
||||
|
||||
**What it does and doesn't do:** it only reads the game's own state (player position, dimension, camera, world folder name, server address) and draws on the HUD and its own screen. It stores waypoints as a text file per world and per server in `horizon-mods/.horizon-mod-data/waypoints/` inside the game folder. It uses only the Rust standard library, opens no network connections, and reads or writes no other files.
|
||||
|
||||
Pinned to Horizon `c9d474d`, because it reads the world folder, server address and last frame's camera from the game itself."""
|
||||
authors = ["Nirokx"]
|
||||
owners = ["Nirokx"]
|
||||
license = "MIT"
|
||||
source = "https://github.com/Nirokx/horizon-waypoints"
|
||||
|
||||
[[versions]]
|
||||
version = "1.0.0"
|
||||
published = "2026-11-02"
|
||||
game = "26.3"
|
||||
file = "waypoints-1.0.0.hnmod"
|
||||
sha256 = "9c0e670f1205c23fed0fe0b0eaf8f0b90a01f3cbb883a8eee445ebc03f4d90a4"
|
||||
changelog = "First release for Horizon 26.3 (Nightly c9d474d)."
|
||||
@@ -0,0 +1,32 @@
|
||||
id = "wisdom_horizon"
|
||||
kind = "shader"
|
||||
name = "Wisdom Shaders V3 (Horizon port)"
|
||||
summary = "bobcao3's Wisdom Shaders V3, ported to Horizon's own WGSL shader format."
|
||||
description = """
|
||||
An unofficial port of **Wisdom Shaders V3 (Build 3300)** by bobcao3 (https://github.com/bobcao3/Wisdom-Shaders) to Horizon's shader API (schema 1, API 0.1), translated from GLSL to WGSL. Wisdom Shaders is licensed under the Apache License 2.0, and so is this port. It is not an official Wisdom Shaders release.
|
||||
|
||||
## Ported
|
||||
- Wisdom's sun, ambient and torch colours by time of day, and its exposure curve.
|
||||
- Oren-Nayar diffuse and GGX specular lighting, light through thin plants, and soft shadows from a jittered 3x3 kernel.
|
||||
- The atmosphere, 2D clouds and their shadows, the sun and moon discs, and height fog.
|
||||
- The AgX tonemap with its lookup table (ACES as an option), plus bloom, the vignette and waving foliage.
|
||||
|
||||
## Changed for Horizon
|
||||
- Lighting runs per surface in the material stage, since Horizon has no G-buffers.
|
||||
- Shadows use Horizon's shadow map with PCF, and water and stained glass tint the light passing through them.
|
||||
- There is no SSAO, SSR, volumetric clouds, god rays, caustics or TAA. FXAA replaces TAA.
|
||||
- The water is rewritten for Horizon's translucent pass.
|
||||
|
||||
The full list of changes is in the README. For integrated graphics there is a Lite version (`wisdom_horizon_lite`) based on Wisdom's LITE profile."""
|
||||
authors = ["bobcao3", "tomasmendes01"]
|
||||
owners = ["tomasmendes01"]
|
||||
license = "Apache-2.0"
|
||||
source = "https://github.com/tomasmendes01/wisdom-horizon"
|
||||
|
||||
[[versions]]
|
||||
version = "1.1.0"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "wisdom_horizon-1.1.0.hshader"
|
||||
sha256 = "2b7b4e11e3506b65e8c4162ed56fbf3c33bc51bbc56038a4b1297219d917dd1e"
|
||||
changelog = "First release: a port of Wisdom Shaders V3 (Build 3300) to Horizon's shader API."
|
||||
@@ -0,0 +1,25 @@
|
||||
id = "wisdom_horizon_lite"
|
||||
kind = "shader"
|
||||
name = "Wisdom Shaders V3 Lite (Horizon port)"
|
||||
summary = "The LITE profile of bobcao3's Wisdom Shaders V3 for Horizon, made for integrated graphics."
|
||||
description = """
|
||||
The LITE profile of the unofficial Horizon port of **Wisdom Shaders V3 (Build 3300)** by bobcao3 (https://github.com/bobcao3/Wisdom-Shaders). Like the original, it is licensed under the Apache License 2.0. It is not an official Wisdom Shaders release.
|
||||
|
||||
It has the same lighting, sky, clouds, fog and AgX tonemap as the full version (`wisdom_horizon`), tuned to Wisdom's LITE profile for integrated graphics:
|
||||
- a 1024 shadow map over 64 blocks, with single-tap shadows
|
||||
- no cloud shadows and no water mirror
|
||||
- no bloom and no FXAA
|
||||
|
||||
The README in the repository lists everything that was ported and what changed."""
|
||||
authors = ["bobcao3", "tomasmendes01"]
|
||||
owners = ["tomasmendes01"]
|
||||
license = "Apache-2.0"
|
||||
source = "https://github.com/tomasmendes01/wisdom-horizon"
|
||||
|
||||
[[versions]]
|
||||
version = "1.1.0"
|
||||
published = "2026-11-04"
|
||||
game = "26.3"
|
||||
file = "wisdom_horizon_lite-1.1.0.hshader"
|
||||
sha256 = "662570653111bd34fec37a7482791b8b1d0bdcee1bcba5351c4137acababb818"
|
||||
changelog = "First release: the LITE profile of Wisdom Shaders V3 (Build 3300), ported to Horizon's shader API."
|
||||
@@ -4,5 +4,5 @@
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "4baa571566e39bfd6594988d3bb2bc85440c30e7",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "0d6b103c70633d8fd9443d8d0acd3aadaacedb06"
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
@@ -4,5 +4,5 @@
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "6f8c7a0e5d531d3834c4d0be4659a1db8e7e5c2a",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "0d6b103c70633d8fd9443d8d0acd3aadaacedb06"
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
@@ -4,5 +4,5 @@
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "6f8c7a0e5d531d3834c4d0be4659a1db8e7e5c2a",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "0d6b103c70633d8fd9443d8d0acd3aadaacedb06"
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
@@ -4,5 +4,5 @@
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "6f8c7a0e5d531d3834c4d0be4659a1db8e7e5c2a",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "0d6b103c70633d8fd9443d8d0acd3aadaacedb06"
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
@@ -4,5 +4,5 @@
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "4baa571566e39bfd6594988d3bb2bc85440c30e7",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "0d6b103c70633d8fd9443d8d0acd3aadaacedb06"
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
Generated
+1
-1
@@ -4,7 +4,7 @@ version = 4
|
||||
|
||||
[[package]]
|
||||
name = "horizon-mod-smp"
|
||||
version = "0.30.1"
|
||||
version = "0.33.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "horizon-mod-smp"
|
||||
version = "0.30.1"
|
||||
version = "0.33.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
|
||||
+80
-33
@@ -9,7 +9,7 @@ lines, vanilla chest menus the server fills with ordinary items (the trade menu)
|
||||
bar, boss bars and the sidebar).
|
||||
|
||||
This version: the economy, the auction house, the server market and its `/shop` menu, player trades, the coinflip, the lottery, places (spawn, homes, warps,
|
||||
teleport requests, the rules), land claims, and the scoreboard (a sidebar with your balance, playtime and the richest players, the Tab list's
|
||||
teleport requests, the rules), land claims, and the scoreboard (a sidebar with your balance and playtime, the Tab list's
|
||||
header and footer).
|
||||
|
||||
| Command | Does |
|
||||
@@ -21,13 +21,13 @@ header and footer).
|
||||
| `/eco take <player> <amount> [reason]`, `/money take ...` | operators of level 3: takes a cheat's gains out of the game, logged with the reason |
|
||||
| `/eco stats` | the money supply and where it sits, what the server made and destroyed today, how evenly money is spread |
|
||||
| `/ah` | the auction house: a chest menu of listings by category, cheapest a unit first; click one to buy it or bid; your listings (click to take one back) and your mail |
|
||||
| `/ah sell <price> [count]` | lists the stack in your hand (or part of it) at a fixed price, for `listing_hours` (48); listing is free |
|
||||
| `/ah sell <price> [count]` | lists the stack in your hand (or part of it), whole (enchantments, name, contents...), at a fixed price, for `listing_hours` (48); listing is free |
|
||||
| `/ah auction <start> [hours]` | auctions the stack in your hand from a starting bid, for 1 to 24 hours (12) |
|
||||
| `/ah bid <listing> <amount>`, `/ah buy <listing>` | bids (the money is held until someone bids more or it ends), buys a fixed-price listing |
|
||||
| `/ah cancel <listing>`, `/ah claim`, `/ah search <words>`, `/ah mine`, `/ah mail` | takes back a listing nobody bid on; gives you your mail; the menu on a search, your listings, your mail |
|
||||
| `/shop` | the market as a chest menu: categories, a click buys one, a shift-click 64, a click on a stack of yours sells it, "Sell all" |
|
||||
| `/market [item]` | the moving market as a chest menu: categories, each item's price, its move over 1 h and 24 h and its volume; an item's page buys or sells 1, 16 or 64, sells all you carry, and gives its price chart as a map |
|
||||
| `/worth [item]` | an item's price, the same to buy and to sell (the one in your hand without a name), and what you may still sell today |
|
||||
| `/worth [item]` | an item's price, the same to buy and to sell (the one in your hand without a name) |
|
||||
| `/sell hand [count]`, `/sell <item> [count]`, `/sell all` | sells to the market: the stack in your hand, an item, or everything it buys |
|
||||
| `/buy <item> [count]` | buys from the market, only what fits in your inventory |
|
||||
| `/trade <player>` | asks a player to trade (60 s to answer) |
|
||||
@@ -39,10 +39,11 @@ header and footer).
|
||||
| `/casino`, `/casino roulette\|slots\|crash\|blackjack` | the casino's lobby menu, or a game's table (needs `gambling.enabled` and `casino.enabled`) |
|
||||
| `/casino help`, `/casino top`, `/casino stats` | every game's odds and house edge and the limits; today's biggest wins; what you bet, won and may still lose today |
|
||||
| `/coinflip accept <player>`, `/coinflip cancel`, `/coinflip list` | takes an offer (a fair coin decides, the winner gets both stakes), withdraws yours, lists those waiting |
|
||||
| `/spawn` | to the server's spawn; `/setspawn` (operators of level 3) sets it where you stand |
|
||||
| `/spawn` | to a safe spot within `places.spawn_radius` of the server's spawn; `/setspawn` (operators of level 3) sets it where you stand |
|
||||
| `/home [name]`, `/sethome [name]`, `/delhome [name]`, `/homes` | your homes (`home` when unnamed): go, set or move one where you stand, delete, list |
|
||||
| `/warp <name>`, `/warps` | to a warp, the list; `/setwarp <name>`, `/delwarp <name>` for operators of level 3 |
|
||||
| `/tpa <player>`, `/tpaccept [player]`, `/tpdeny [player]` | asks to go to a player (60 s to answer); answers a request |
|
||||
| `/rtp`, `/wild` | to a random safe spot 500 to 5,000 blocks from the spawn, in the Overworld only; once every 30 minutes |
|
||||
| `/rules` | the server's rules |
|
||||
| `/back` | back to where you died, or where your last teleport took you from (warmup and cooldown as any teleport) |
|
||||
| `/afk` | marks you away from the keyboard until you move, turn or run a command |
|
||||
@@ -54,14 +55,16 @@ header and footer).
|
||||
| `/nick <name>`, `/nick off`, `/nick` | operators of level 3 (with `ops_only`, the default): another name for you in chat and the Tab list, shown as `~name` (hovering it gives your real one); `/nick off` (anyone with a nickname) takes it off; `/nick` alone says how |
|
||||
| `/nick <player> <name\|off>` | operators of level 3: sets or takes off a player's nickname |
|
||||
| `/realname <nick>` | who goes by that nickname |
|
||||
| `/vanish`, `/vanish list` | operators of level 3: hides you from the other players, or shows you again; who is vanished |
|
||||
| `/invsee <player>`, `/endersee <player>` | operators of level 3: the player's inventory (main, hotbar, armour, off hand) or ender chest in a chest menu, on or off the server; click one of theirs to take it, one of yours to give it; every move in `audit.log`, a summary in `staff.log` |
|
||||
| `/sidebar off`, `/sidebar on`, `/sidebar` | hides the scoreboard sidebar for you (remembered), shows it again |
|
||||
| `/smp status`, `/smp off [part\|all] [reason]`, `/smp on [part\|all]` | operators of level 3: the emergency switches (below) |
|
||||
|
||||
The market trades only plain items (not worn, named or enchanted), and only with players in survival or adventure
|
||||
mode. Items move first, then money, both logged; a sale the log refuses gives the items back, and a purchase checks the
|
||||
money and the room before anything moves.
|
||||
|
||||
**No way to get rich from the market.** The market makes money only from what players gather, and only so much a day:
|
||||
**No way to get rich from the market.** The market makes money only from what players gather:
|
||||
- One price per item, to buy and to sell (since 0.29): a config that still has two (`buy` 400, `sell` 100) gets
|
||||
their geometric mean (200) at load, logged ("one price now"); `buy` or `sell` 0 still closes that side. A trade
|
||||
of N items is priced along the curve it moves the price on (below), so buying N and selling them back gives back
|
||||
@@ -74,12 +77,10 @@ money and the room before anything moves.
|
||||
copper, diamond, emerald, coal, redstone, lapis, wheat, wood and food chains at each start.
|
||||
- Items a recipe links (an ingot and its block, wheat and hay...) share one moving price, the block moving it as
|
||||
its 9 ingots do, so crafting never beats the market however prices move; the vanilla-recipe test checks every item
|
||||
at the worst drift (what makes it at 0.6 times its price, it at 1.6) too.
|
||||
- Each player sells at most `daily_sell_coins` (2,000 coins) and `daily_sell_items` (640 of each item) a UTC day,
|
||||
`/worth` and the shop show what is left, and `market.json` keeps the day's count across restarts.
|
||||
- Money received with `/pay` counts toward the receiver's same `daily_sell_coins`: selling up to the limit on alts
|
||||
and paying it all to a main is refused once the main's limit is reached ("can only receive N more today").
|
||||
Trades (`/trade`) and auction house sales are not counted.
|
||||
at the worst drift (what makes it at 0.2 times its price, it at 1.6) too.
|
||||
- There are no daily coin or per-item limits on market sales, or daily limits on `/pay` receipts.
|
||||
The former `daily_sell_coins` and `daily_sell_items` settings and `market.json` counts are ignored,
|
||||
including in existing server files.
|
||||
- Amounts are checked: no price above 1,000,000,000,000, no sum that overflows.
|
||||
- The coinflip and the lottery give the winner all the stakes: they move money between players and never make any.
|
||||
|
||||
@@ -110,6 +111,14 @@ before it is made (`invsee_take`, `invsee_put`: operator, player, inventory, ite
|
||||
its reason); closing the menu writes one line to the server log (`[smp] staff: ...`), `staff.log`, and the chat of
|
||||
the other operators on. Needs horizon#6106 (`native_inventory`, `native_move_stack`).
|
||||
|
||||
**Vanish.** `/vanish` takes an operator of level 3 out of the Tab list and the world of every player below level 3,
|
||||
whatever the game mode (survival and creative too), and those players don't read them joining or leaving; operators of
|
||||
level 3 or more still see them, and are told who vanished. A vanished operator reads a subtitle the whole time
|
||||
(*Vanished: only operators see you*), isn't counted online (the sidebar, the Tab list's footer), doesn't hold the night up, isn't
|
||||
announced as AFK or on a first join, and can't be reached by name by those who don't see them (`/tpa`, `/trade`,
|
||||
`/coinflip`, `/playtime`). It lasts over a relog and a restart (`vanish.json`) until `/vanish` again. Needs
|
||||
horizon#7003 (`native_hide_player`).
|
||||
|
||||
**Nicknames.** With `ops_only` (the default since 0.22) only operators of level 3 set nicknames: their own, or a
|
||||
player's with `/nick <player> <name>`; a player may take off the one given to them (`/nick off`). At each start, a
|
||||
nickname a player who isn't an operator picked themselves is taken off and logged (`for operators only`). 3 to 16 letters, digits or `_`, shown with a `~` in front (`~Rocky`) so a nickname never passes for
|
||||
@@ -130,15 +139,19 @@ names), `reserved` (the words above).
|
||||
**Moving prices** (`market.dynamic`, on by default since 0.26). Each item has one price: its base price (`items`)
|
||||
times a factor that supply and demand move as each trade happens. Every item bought raises the log of the factor by
|
||||
`1% / depth`, every item sold lowers it as much, where the depth follows the item's rarity (400 / its price, between
|
||||
2 and 400: a diamond moves 50 times faster per item than cobblestone; `depth` overrides it per item). A trade of N is
|
||||
2 and 50: a diamond moves 25 times faster per item than cobblestone, and any item reaches the floor within 10,000
|
||||
sold; `depth` overrides it per item). A trade of N is
|
||||
worth the area under that curve (`price / step × (e^(N × step) - 1)`), rounded up to whole coins when buying and down
|
||||
when selling: one diamond at 200 costs 201 and sells for 199, 64 cobblestone at 1 cost 65, and a sale walks back the
|
||||
exact path of the purchase. All trades together move an item at most `max_minute_move_percent` (5%) a minute from
|
||||
where it started that minute: past that, a purchase is cut short and a sale keeps the rest ("sell them in a
|
||||
minute"). The factor goes back to 1 with a half-life of `half_life_hours` (6) and stays within `min_factor` (0.6)
|
||||
and `max_factor` (1.6), where the rest of a trade goes at that price. There is no tax on trades (an older config's
|
||||
`tax_percent` is ignored): the receipt is the price ("Sold 3 diamond at 198 coins each: 595 coins."). Items a player bought from the market in the last `round_trip_hours` (24) can't be
|
||||
sold back to it. (`max_trade_impact_percent` and `max_player_impact_percent` are no longer used: the curve and the
|
||||
minute"). The factor goes back to 1 with a half-life of `half_life_hours` (6) and stays within `min_factor` (0.2)
|
||||
and `max_factor` (1.6), where the rest of a trade goes at that price. With no daily sale caps (since 0.33), the floor
|
||||
is what bounds a farm: selling one item without end takes its price down to a fifth of its base, where it stays while
|
||||
the selling goes on; a config with the old floor (0.6) gets 0.2 when it loads. There is no tax on trades (an older config's
|
||||
`tax_percent` is ignored): the receipt is the price ("Sold 3 diamond at 198 coins each: 595 coins."). Market purchases can be sold back immediately;
|
||||
the former `round_trip_hours` setting and saved purchase receipts are ignored. (`max_trade_impact_percent` and
|
||||
`max_player_impact_percent` are no longer used: the curve and the
|
||||
minute's band do their work.) History: one point a minute for 24 hours and one an hour for 30 days (the mid price, the
|
||||
items traded and those sold), in `market_prices.json`, written by a thread every 5 minutes and when the world closes.
|
||||
At the first minute of each UTC day, the day's three biggest risers and fallers (at least 1%) and news from real
|
||||
@@ -148,7 +161,7 @@ fixed prices of 0.23. For other mods: `Market::spot`, `volume(id, now, hours)`,
|
||||
|
||||
**`/market`.** A 6-row chest menu: the shop's categories and the day's movers; a category's items, each with its
|
||||
price, its change over 1 h and 24 h (green ▲, red ▼) and what was traded in 24 h; an item's page with its
|
||||
base price and what you may still sell today, buttons to buy or sell 1, 16 and 64 (what they come to
|
||||
base price , buttons to buy or sell 1, 16 and 64 (what they come to
|
||||
along the curve), sell all of it you carry, and the price chart over 24 hours or 7 days, given as a filled map (128 × 128,
|
||||
drawn by the server: the curve green when it rose, red when it fell, the price, the change, the low and high). A
|
||||
chart map is drawn again each minute for whoever carries it, and once a minute the open menus follow the prices.
|
||||
@@ -157,8 +170,8 @@ chart map is drawn again each minute for whoever carries it, and once a minute t
|
||||
**The shop.** `/shop` opens a 6-row chest menu on the market's prices: the categories of `config.json`'s `shop` (an
|
||||
item in none goes under "Other"), each item named with its prices. A click buys one, a shift-click 64; a click on a
|
||||
stack in your own inventory, below the menu, sells it; "Sell all" sells everything the market buys. The bottom row
|
||||
shows your balance and today's selling limit. It goes through the market's own rules (survival or adventure only,
|
||||
items then money, logged, the daily limits); the items move by the console's `clear` and `give`, measured on the
|
||||
shows your balance. It goes through the market's own rules (survival or adventure only,
|
||||
items then money, logged); the items move by the console's `clear` and `give`, measured on the
|
||||
inventory before and after, so the money follows what really moved.
|
||||
|
||||
**Trades.** Once accepted, both players see a 6-row chest menu: their own offer on the left (16 stacks), the other's
|
||||
@@ -213,9 +226,23 @@ stays where they are, and `cooldown_seconds` (10) passes between two of one play
|
||||
`places.fees` is ignored). `/tpa` takes the
|
||||
asker to where the other player is when the warmup ends. Homes grow with the time played on the server since the mod
|
||||
was on (`homes`: `[hours, homes]`, by default 1 home, 2 from 5 hours, 3 from 20, 5 from 100). `rules` holds `/rules`'
|
||||
lines. Teleports are vanilla's `tp`, run as the server (`execute in <level> run tp`), so they cross levels and land
|
||||
lines. `/spawn` lands on a random safe column within `spawn_radius` (250) blocks of the spawn point, like vanilla's `respawn_radius` for a first join or a respawn: after the `tp`, vanilla's `spreadplayers` moves the player off fluid, fire and magma onto solid ground (0: exactly the spawn point; if no column is found the player stays at the spawn point). Teleports are vanilla's `tp`, run as the server (`execute in <level> run tp`), so they cross levels and land
|
||||
as any teleport does.
|
||||
|
||||
`/rtp` (or `/wild`) draws `rtp_attempts` (6) chunks at random between `rtp_min_distance` (500) and `rtp_max_distance`
|
||||
(5000) blocks from the spawn (`/setspawn`'s point, 0 0 without one), uniform over the ring's area and at least 16 blocks
|
||||
inside the world border (as last saved in `world_border.dat`), then holds them loaded one after another with vanilla's
|
||||
`forceload` while the warmup runs: the game generates them on its worker threads, never on the server tick. Once a
|
||||
chunk is loaded, the Overworld's tick reads its 256 columns (`native_read_columns`, the top block below the
|
||||
`MOTION_BLOCKING_NO_LEAVES` height and the two above it) and the player lands, still standing still, on a random one
|
||||
whose top block is solid ground (no fluid, fire, cactus, magma, powder snow, berry bush or dripstone) with air or grass
|
||||
above it, outside another player's claim and still in the ring and the border; with none the next chunk is tried. With
|
||||
no spot after the six, or no land loaded `rtp_search_seconds` (30) after the warmup, it says so and nothing is spent.
|
||||
A teleport made starts `rtp_cooldown_seconds` (1800) for that player, kept in `places.json` over restarts ("Wait 12 min
|
||||
before your next /rtp."); a teleport called off (a move, a hit, the game failing it) doesn't. Elsewhere than the
|
||||
Overworld it refuses. The chunks it forced are let go 10 s after the landing, or at the next start if the server
|
||||
stopped first; a chunk an operator forced already is used and left forced. `/back` returns from it as from any teleport.
|
||||
|
||||
**Claims.** In a claimed chunk, only its owner, the players they trust and operators of level 3 break blocks or right
|
||||
click blocks: doors, chests, levers, buttons, placing a block, a bucket or flint on a block. Anyone else's click does
|
||||
nothing, and the action bar says whose land it is. The chunks a player may hold grow with the time played here
|
||||
@@ -230,14 +257,14 @@ items, shearing, leads), which waits for Horizon's hook (#4648). The server's `s
|
||||
the spawn.
|
||||
|
||||
**The scoreboard.** A sidebar on the right, titled `board.title` ("Horizon SMP"): your own block first (your name, or
|
||||
your nickname; your balance, `125.4k`, `3.2M`; your playtime, `2h 05m`; the players online), then the `board.top` (3)
|
||||
richest players with their balance, then `board.footer` (`play.playhorizon.dev`, empty for none). The ranking is
|
||||
built once for everyone, only when a balance changed (at most every `board.min_seconds`, 5) or every
|
||||
`board.refresh_seconds` (60); each player's own lines are looked at on the same `board.refresh_seconds`, and a
|
||||
your nickname; your balance, `125.4k`, `3.2M`; your playtime, `2h 05m`; the players online), then `board.footer`
|
||||
(`play.playhorizon.dev`, empty for none). It lists no ranking: `/baltop` does (`board.top`, of 0.14 to 0.29, is
|
||||
ignored). The balances are read once for everyone, only when one changed (at most every `board.min_seconds`, 5) or
|
||||
every `board.refresh_seconds` (60); each player's own lines are looked at on the same `board.refresh_seconds`, and a
|
||||
sidebar is sent only to the players whose lines changed and to newcomers: nothing runs per tick per player. The Tab
|
||||
list shows `board.tab_header` and `board.tab_footer` (`{server}`, `{tps}`, `{players}` filled in, every
|
||||
`board.tab_refresh_seconds`, 5). `board.sidebar` and `board.tab` turn either off; `board.server_name` names the Tab
|
||||
list. A server that kept 0.13's defaults (`Richest players`, the top 10) gets these at its first start of 0.14. The
|
||||
list. A server that kept 0.13's title (`Richest players`) gets `Horizon SMP` at its first start. The
|
||||
sidebar uses one scoreboard objective of its own (`horizon:native_sidebar`) and leaves the world's scoreboard alone.
|
||||
|
||||
**Presence.** A player's first join is announced to everyone (`presence.first_join`, empty for none) and they read
|
||||
@@ -261,8 +288,14 @@ raising one's own only holds the difference, and a bid in the last `snipe_second
|
||||
60 seconds away. When an auction ends, the seller is paid the winning bid and the items go to the winner's mail. Sellers
|
||||
and outbid players who are offline find a note when they come back. Everything (listings, bids, mail, notes) is
|
||||
written in `economy.json` with the balances, in one step: a crash can't keep the money and lose the items, or the
|
||||
reverse. Only plain items for now (not worn, named or enchanted); whole stacks with their enchantments wait for
|
||||
Horizon's `native_give_stack` to be stamped. Survival and adventure players only. `config.json`'s `auction`:
|
||||
reverse. A listing carries the whole stack (since 0.31): its enchantments, name, damage, lore, a shulker box's
|
||||
or a bundle's contents and every other component, written as the game writes it in player files, and given back
|
||||
exactly so (Horizon's `native_give_stack`) to the buyer, the winner, or the seller when it comes back. `/ah sell
|
||||
<price> <count>` lists part of the stack in hand; the rest stays in the hand, the same. The menu shows the stack
|
||||
itself (its tooltip), with the listing's price, seller and time under it. A stack is taken only if it would come
|
||||
back the same (its data written and read back equal); not market charts (free at `/market`), nor a stack holding
|
||||
more than 32 KiB of data (a box of books). Listings and mail from before 0.31 hold plain items and are given back as
|
||||
before. Survival and adventure players only. `config.json`'s `auction`:
|
||||
`enabled`, `max_listings` (8 a player), `listing_hours` (48), `auction_hours` (12),
|
||||
`auction_hours_max` (24), `bid_step_percent` (5: the smallest raise), `snipe_seconds` (60). Ended listings are
|
||||
looked at once a second (a pass over the open listings).
|
||||
@@ -291,6 +324,19 @@ pool: the stake goes in, the payout comes out, never more than the pool holds),
|
||||
|
||||
The currency is earned in game only: it can't be bought with real money or cashed out (Mojang's usage guidelines).
|
||||
|
||||
**Emergency switches.** An operator of level 3 turns parts of the SMP off while the server runs: `/smp off`
|
||||
(everything but land protection), `/smp off <part> [reason]`, `/smp on [part]`, `/smp status` (what is off, by whom,
|
||||
when and why). Parts: `economy` (balances, `/pay`, `/eco`, the daily
|
||||
reward), `market` (`/worth`, `/sell`, `/buy`, `/shop`, `/market`), `auction`, `trades`, `gambling` (coinflips, the
|
||||
lottery, the casino), `places` (spawn, homes, warps, `/tpa`, `/back`), `claims` (land protection and
|
||||
`/claim`: only by name, `/smp off claims`), `board` (the sidebar and the Tab list's header and footer), `presence`
|
||||
(welcomes, AFK, the commands' rate limit), `nicks`, `invsee`. A part that is off answers its commands with "... is
|
||||
turned off for now by the server's staff", and its menus close at the next click. Turning one off ends open trades
|
||||
with nothing moved, closes the shop, market and auction menus, calls off teleports waiting, takes the
|
||||
sidebars and nicknames away. Its timed work waits (the lottery's draw, auctions ending, the daily reward); nothing held is lost: coinflips not taken still go back and a casino
|
||||
round under way still ends and is paid. The other operators on are told, and each change is in the server's log and
|
||||
`audit.log` (`switch_off`, `switch_on`). What is off is kept in `switches.json`, so a restart keeps it off.
|
||||
|
||||
## Data
|
||||
|
||||
Everything is in the world's folder, `world/horizon-smp/`, so a backup of the world carries it. A world without that
|
||||
@@ -298,16 +344,17 @@ folder is untouched until the mod first runs on it; it changes no block and no p
|
||||
|
||||
| File | Holds |
|
||||
|---|---|
|
||||
| `config.json` | `currency` (default `coins`), `starting_balance` (default 0), `market`: `enabled`, `items` (each item's `buy`, what the market asks, and `sell`, what it pays, 0 closing that side), `daily_sell_coins` (2000) and `daily_sell_items` (640), 0 for no limit; `shop`: `enabled`, `title`, `categories` (`name`, `icon`, `items`); `web`: `url` (Kira's `/smp/ingest`) and `token` (empty: nothing is sent), where the pages of `web/` go; written with the defaults the first time, and again when a newer version adds keys (your values kept) |
|
||||
| `config.json` | `currency` (default `coins`), `starting_balance` (default 0), `market`: `enabled`, `items` (each item's `buy`, what the market asks, and `sell`, what it pays, 0 closing that side), `shop`: `enabled`, `title`, `categories` (`name`, `icon`, `items`); `web`: `url` (Kira's `/smp/ingest`) and `token` (empty: nothing is sent), where the pages of `web/` go; written with the defaults the first time, and again when a newer version adds keys (your values kept) |
|
||||
| `economy.json` | balances by player UUID, with the name last seen; `held`: coinflip stakes and lottery tickets being decided; `pools`: the casino's pot and the auction house's bids; `ext`: other parts' state written in the same step as the money (`auction`: the listings, bids, mail and notes) |
|
||||
| `places.json` | the spawn, the warps, each player's homes, and the seconds each player has played (written once a minute) |
|
||||
| `nicks.json` | each player's nickname and when they last changed it |
|
||||
| `vanish.json` | the vanished operators by UUID, with their name |
|
||||
| `staff.log` | one line per `/invsee` or `/endersee` menu in which something moved: who, whose, what was taken and put |
|
||||
| `market.json` | what each player sold today (coins and items), for the daily limits |
|
||||
| `market_prices.json` | each item's price factor and history (minutes for 24 h, hours for 30 days: `[time, mid, traded, sold]`), what each player bought in the last day (no selling it back), the day's summary |
|
||||
| `market_prices.json` | each item's price factor and history (minutes for 24 h, hours for 30 days: `[time, mid, traded, sold]`), the day's summary |
|
||||
| `web/market.json` | for the website (`/hub/market`, through Kira), written by a thread each minute prices move: `schema` 1, `generated`, `currency`, `tax_percent` (always 0, for older readers), `daily_summary` (`day`, `lines`), `items` (`id`, `name`, `category`, `price` (the one price; `buy` and `sell` repeat it on the sides the market trades, for older readers), `mid`, `base`, `change_1h`, `change_24h`, `volume_24h`, `day`: 5-minute points, `month`: hours, each `{step, t, price, volume}`). When `web.token` is set, the same thread POSTs each page of `web/` that changed (gzipped, `Authorization: Bearer <token>`) to `<web.url>/<name>`: Kira keeps the last one and serves it to the site; the server needs no inbound access and Kira no key to it |
|
||||
| `presence.json` | the players who have joined (no welcome again), and the day each last got the daily reward |
|
||||
| `board.json` | the players who hid the sidebar (`/sidebar off`) |
|
||||
| `switches.json` | the parts operators turned off (`/smp off`): by whom, when and why |
|
||||
| `casino.json` | the day's ledger: each player's bets, wins and rounds today (the daily loss cap), the day's biggest wins, each game's totals, the pot's last sweep |
|
||||
| `claims.json` | each claimed chunk (`<dimension> <chunk x> <chunk z>`) with its owner, and whom each owner trusts |
|
||||
| `audit.log` | one JSON line per change, written before the change: `time` (ms), `kind` (`open`, `pay`, `grant`, `ah_listing_fee`...), `amount`, `from`/`to` with their balance before, `by` for an operator, `to_pool`/`from_pool` with `pool_before` and `reason` for a pool's movement; a trade's line (`trade`: both players, their items and money) comes before its swap, `trade_failed` after one that didn't go through |
|
||||
@@ -323,13 +370,13 @@ acting player's items (API 9), the server menus and `native_exchange_items` (API
|
||||
`native_run_command` (API 21), `native_destroy_block` (API 14), `native_right_click_block`, the acting player and the
|
||||
action bar (API 21), `native_block_spread`, `native_piston_move`, `native_explosion_detonate`, `native_fill_bucket` and
|
||||
`native_attack_entity` (API 22), `native_sidebar`, `native_tab_list` and `native_tick_stats` (API 49),
|
||||
`native_set_nickname` and `native_text_allowed` (API 62), the server tick and the world lifecycle.
|
||||
`native_set_nickname` and `native_text_allowed` (API 62), `native_hide_player` (API 314, horizon#7003), the server tick and the world lifecycle.
|
||||
`compatibility.json` names `"hooks": 58`.
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `mixins/smp/horizon-mixin.toml` | The bundle: twenty-seven modules and the HEAD hooks |
|
||||
| `mixins/smp/smp_store.rs`, `smp_economy.rs`, `smp_market.rs`, `smp_recipes.rs`, `smp_shop.rs`, `smp_nick.rs`, `smp_trade.rs`, `smp_games.rs`, `smp_lottery.rs`, `smp_places.rs`, `smp_claims.rs`, `smp_board.rs`, `smp_presence.rs`, `smp_auction.rs`, `smp_report.rs`, `smp_market_prices.rs`, `smp_market_menu.rs`, `smp_market_chart.rs`, `smp_invsee.rs` | The rules, no game types (a trade's stacks are a type parameter): added to the game as `game::smp_store`, `game::smp_economy`, `game::smp_market`, `game::smp_recipes`, `game::smp_shop`, `game::smp_nick`, `game::smp_trade`, `game::smp_games`, `game::smp_lottery`, `game::smp_places`, `game::smp_claims`, `game::smp_board`, `game::smp_presence`, `game::smp_auction`, `game::smp_report`, `game::smp_market_prices`, `game::smp_market_menu`, `game::smp_market_chart`, `game::smp_invsee`; also this crate's modules (`src/lib.rs`), for their tests |
|
||||
| `mixins/smp/horizon-mixin.toml` | The bundle: twenty-nine modules and the HEAD hooks |
|
||||
| `mixins/smp/smp_store.rs`, `smp_economy.rs`, `smp_market.rs`, `smp_recipes.rs`, `smp_shop.rs`, `smp_nick.rs`, `smp_trade.rs`, `smp_games.rs`, `smp_lottery.rs`, `smp_places.rs`, `smp_claims.rs`, `smp_board.rs`, `smp_presence.rs`, `smp_auction.rs`, `smp_report.rs`, `smp_market_prices.rs`, `smp_market_menu.rs`, `smp_market_chart.rs`, `smp_invsee.rs`, `smp_switch.rs`, `smp_vanish.rs` | The rules, no game types (a trade's stacks are a type parameter): added to the game as `game::smp_store`, `game::smp_economy`, `game::smp_market`, `game::smp_recipes`, `game::smp_shop`, `game::smp_nick`, `game::smp_trade`, `game::smp_games`, `game::smp_lottery`, `game::smp_places`, `game::smp_claims`, `game::smp_board`, `game::smp_presence`, `game::smp_auction`, `game::smp_report`, `game::smp_market_prices`, `game::smp_market_menu`, `game::smp_market_chart`, `game::smp_invsee`, `game::smp_switch`, `game::smp_vanish`; also this crate's modules (`src/lib.rs`), for their tests |
|
||||
| `mixins/smp/glue.rs` | The state for the open world and the edges to the game's types (`game::smp_glue`) |
|
||||
| `mixins/smp/{register,command,tick,lifecycle,menu_clicked,menu_closed,destroy_block,right_click_block,block_spread,piston_move,explosion_detonate,fill_bucket,attack_entity}.rs` | One small helper per hook |
|
||||
| `mixins/smp/smp_casino.rs`, `smp_casino_roulette.rs`, `smp_casino_slots.rs`, `smp_casino_crash.rs`, `smp_casino_blackjack.rs` | The casino's rules, menus and effects (`game::smp_casino*`) |
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"game": "26.3",
|
||||
"hooks": 62,
|
||||
"hooks": 314,
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "975c07d9151847e6af13afc4b5ab37b6bbe78ef5",
|
||||
"horizon_revision": "48c63bc09d9acc82f2074e75ae59720514796a9d",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "0d6b103c70633d8fd9443d8d0acd3aadaacedb06"
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
+566
-70
@@ -2,7 +2,7 @@
|
||||
// between the game's types and the rules (smp_economy, smp_market, smp_shop,
|
||||
// smp_trade, smp_games, smp_lottery, smp_places, smp_claims). Added to
|
||||
// the game as `game::smp_glue`; the helpers (register.rs, command.rs,
|
||||
// tick.rs, lifecycle.rs, menu_clicked.rs, menu_closed.rs, destroy_block.rs,
|
||||
// tick.rs, level_tick.rs, lifecycle.rs, menu_clicked.rs, menu_closed.rs, destroy_block.rs,
|
||||
// right_click_block.rs, block_spread.rs, piston_move.rs,
|
||||
// explosion_detonate.rs, fill_bucket.rs, attack_entity.rs) call it from the
|
||||
// hook points.
|
||||
@@ -27,7 +27,9 @@ use crate::game::{
|
||||
smp_nick::{self, Names as _, Nicks},
|
||||
smp_shop::{self, Shop},
|
||||
smp_store,
|
||||
smp_switch::{self, Part, Switches},
|
||||
smp_trade::{self, Act, Cell, Trades},
|
||||
smp_vanish::{self, Vanish},
|
||||
};
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
@@ -39,7 +41,7 @@ use std::{path::PathBuf, sync::Mutex};
|
||||
/// The mod's id, name and version.
|
||||
pub const ID: &str = "smp";
|
||||
pub const NAME: &str = "SMP";
|
||||
pub const VERSION: &str = "0.30.1";
|
||||
pub const VERSION: &str = "0.33.0";
|
||||
|
||||
/// `config.json` in `world/horizon-smp/`, written with its defaults the
|
||||
/// first time, and again with the keys a newer version adds (values kept).
|
||||
@@ -123,6 +125,14 @@ pub struct Smp {
|
||||
/// `/claim show`: whose chunk border is drawn (level, chunk x, chunk z)
|
||||
/// until when.
|
||||
shows: std::collections::HashMap<u128, (String, i32, i32, i64)>,
|
||||
/// `/vanish`: an error when `vanish.json` can't be read (nobody is
|
||||
/// hidden then, and the command says so).
|
||||
vanish: Result<Vanish, String>,
|
||||
/// The vanished players on who were sent the subtitle: cleared and
|
||||
/// counted for sleeping again once they show themselves or leave.
|
||||
vanish_titled: std::collections::HashSet<u128>,
|
||||
/// The parts operators turned off (`/smp off`).
|
||||
switches: Switches,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<Smp>> = Mutex::new(None);
|
||||
@@ -133,6 +143,11 @@ static BUSY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(
|
||||
/// Sleep-count changes decided inside a player's command, for the next
|
||||
/// second's tick.
|
||||
static PENDING_SLEEP: Mutex<Vec<smp_presence::Act>> = Mutex::new(Vec::new());
|
||||
/// Whether an `/rtp` waits for its land: the Overworld's tick reads it then.
|
||||
static RTP: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
/// What each `/rtp`'s reads cost the Overworld's tick, by player: reads,
|
||||
/// total and longest (µs), for the line logged when they land.
|
||||
static RTP_COST: Mutex<Vec<(u128, u32, u64, u64)>> = Mutex::new(Vec::new());
|
||||
|
||||
fn open(dir: PathBuf) -> Smp {
|
||||
let config_path = dir.join("config.json");
|
||||
@@ -164,7 +179,7 @@ fn open(dir: PathBuf) -> Smp {
|
||||
let mut config = config;
|
||||
// Prices never edited: today's defaults (the balances are untouched).
|
||||
let write = smp_market::migrate(&mut config.market) | write;
|
||||
// 0.13's sidebar (the richest ten), never edited: 0.14's scoreboard.
|
||||
// 0.13's sidebar title, never edited: today's.
|
||||
let write = smp_board::migrate(&mut config.board) | write;
|
||||
if write && let Err(e) = smp_store::write_json(&config_path, &config) {
|
||||
log::error!("[smp] {e}");
|
||||
@@ -194,6 +209,10 @@ fn open(dir: PathBuf) -> Smp {
|
||||
Err(e) => log::error!("[smp] claims are off: {e}"),
|
||||
}
|
||||
let board = Board::open(&dir, config.board);
|
||||
let vanish = Vanish::open(&dir);
|
||||
if let Err(e) = &vanish {
|
||||
log::error!("[smp] /vanish is off: {e}");
|
||||
}
|
||||
if let Err(e) = &board {
|
||||
log::error!("[smp] the sidebar is off: {e}");
|
||||
}
|
||||
@@ -218,6 +237,13 @@ fn open(dir: PathBuf) -> Smp {
|
||||
if let Err(e) = &presence {
|
||||
log::error!("[smp] welcomes, daily rewards and AFK are off: {e}");
|
||||
}
|
||||
let (switches, problem) = Switches::open(&dir);
|
||||
if let Some(e) = problem {
|
||||
log::error!("[smp] {e}: every part is on");
|
||||
}
|
||||
for p in Part::ALL.into_iter().filter(|&p| !switches.on(p)) {
|
||||
log::warn!("[smp] {} is turned off (/smp on {} turns it on)", p.name(), p.name());
|
||||
}
|
||||
let (casino, problem) = Casino::open(&dir, config.casino, config.gambling.enabled);
|
||||
if let Some(e) = problem {
|
||||
log::error!("[smp] casino.json can't be read, the day's ledger starts again (kept apart): {e}");
|
||||
@@ -244,6 +270,9 @@ fn open(dir: PathBuf) -> Smp {
|
||||
nicks,
|
||||
nicks_shown: Default::default(),
|
||||
shows: Default::default(),
|
||||
vanish,
|
||||
vanish_titled: Default::default(),
|
||||
switches,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,9 +310,6 @@ fn save(smp: &mut Smp) {
|
||||
{
|
||||
log::error!("[smp] {err}");
|
||||
}
|
||||
if let Err(err) = smp.market.save() {
|
||||
log::error!("[smp] {err}");
|
||||
}
|
||||
if let Ok(p) = &mut smp.places
|
||||
&& let Err(err) = p.save(chrono::Utc::now().timestamp_millis())
|
||||
{
|
||||
@@ -312,6 +338,14 @@ fn save(smp: &mut Smp) {
|
||||
if let Err(err) = smp.casino.save() {
|
||||
log::error!("[smp] {err}");
|
||||
}
|
||||
if let Ok(v) = &mut smp.vanish
|
||||
&& let Err(err) = v.save()
|
||||
{
|
||||
log::error!("[smp] {err}");
|
||||
}
|
||||
if let Err(err) = smp.switches.save() {
|
||||
log::error!("[smp] {err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands, for every player's command tree.
|
||||
@@ -360,6 +394,8 @@ pub fn commands(commands: &mut Vec<NativeCommand>) {
|
||||
"tpdeny [player:word]",
|
||||
"rules",
|
||||
"back",
|
||||
"rtp",
|
||||
"wild",
|
||||
"playtime [player:word]",
|
||||
"claim",
|
||||
"claim info",
|
||||
@@ -394,9 +430,14 @@ pub fn commands(commands: &mut Vec<NativeCommand>) {
|
||||
"setwarp <name:word>",
|
||||
"delwarp <name:word>",
|
||||
"nick <name:word> <nick:word>",
|
||||
"vanish",
|
||||
"vanish list",
|
||||
] {
|
||||
commands.push(NativeCommand::op(usage, 3));
|
||||
}
|
||||
for usage in ["smp", "smp status", "smp on [part:word]", "smp off [part:word] [reason:text]"] {
|
||||
commands.push(NativeCommand::op(usage, smp_switch::LEVEL));
|
||||
}
|
||||
// Operators make money (an event prize, a bug refund: with a reason
|
||||
// everyone reads) and take a cheat's gains away.
|
||||
for name in ["eco", "money"] {
|
||||
@@ -429,23 +470,217 @@ impl Bag for GameBag<'_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most encoded data one listed stack may carry (a shulker box of
|
||||
/// written books can hold megabytes; economy.json is written whole).
|
||||
const MAX_STACK_DATA: usize = 32 * 1024;
|
||||
|
||||
/// A stack as the auction house keeps it: `ItemStack.CODEC`'s NBT (id,
|
||||
/// count, components), as the game saves it in player files, in hex.
|
||||
fn encode_stack(stack: &ItemStack) -> Option<String> {
|
||||
let tag = horizon_items::item_nbt::item_to_nbt(stack);
|
||||
let bytes = horizon_world::nbt::write_network(&tag, horizon_world::nbt::Limits::saved()).ok()?;
|
||||
Some(bytes.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
fn decode_stack(data: &str) -> Option<ItemStack> {
|
||||
if data.len() % 2 != 0 || data.len() > 2 * MAX_STACK_DATA {
|
||||
return None;
|
||||
}
|
||||
let bytes: Vec<u8> = (0..data.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(data.get(i..i + 2)?, 16).ok())
|
||||
.collect::<Option<_>>()?;
|
||||
let (tag, _) = horizon_world::nbt::read_network(&bytes, horizon_world::nbt::Limits::default()).ok()?;
|
||||
horizon_items::item_nbt::item_from_nbt(&tag)
|
||||
}
|
||||
|
||||
fn whole_of(stack: &ItemStack) -> Option<smp_auction::Whole> {
|
||||
Some(smp_auction::Whole { item: stack.item.to_string(), count: stack.count, data: encode_stack(stack)? })
|
||||
}
|
||||
|
||||
/// Why `stack` can't be listed whole, if it can't: only what comes back
|
||||
/// exactly as it went (every component read back the same) is taken.
|
||||
fn unsellable(stack: &ItemStack) -> Option<String> {
|
||||
if &*stack.item == "minecraft:filled_map" && stack.data().and_then(|d| d.map_id).is_some_and(|m| m >= CHART_MAPS) {
|
||||
return Some("Market charts are free at /market: they can't be sold.".into());
|
||||
}
|
||||
let Some(data) = encode_stack(stack) else {
|
||||
return Some("That stack can't be listed: its data can't be written.".into());
|
||||
};
|
||||
if data.len() > 2 * MAX_STACK_DATA {
|
||||
return Some("That stack holds too much (books, contents...) to be listed.".into());
|
||||
}
|
||||
if decode_stack(&data).as_ref() != Some(stack) {
|
||||
return Some("That stack can't be listed whole: some of its data wouldn't come back the same.".into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The same stack but for the count.
|
||||
fn same_kind(a: &ItemStack, b: &ItemStack) -> bool {
|
||||
a.item == b.item && a.damage == b.damage && a.extra == b.extra
|
||||
}
|
||||
|
||||
/// Whether `stack` fits whole in `slots` (the 36 main slots), as
|
||||
/// `Inventory.add` places it: onto equal stacks, then into empty slots.
|
||||
fn fits_in(slots: &[Option<ItemStack>], stack: &ItemStack, max: u32) -> bool {
|
||||
let room: u32 = slots
|
||||
.iter()
|
||||
.take(36)
|
||||
.map(|s| match s {
|
||||
None => max,
|
||||
Some(s) if same_kind(s, stack) => max.saturating_sub(s.count),
|
||||
Some(_) => 0,
|
||||
})
|
||||
.sum();
|
||||
room >= stack.count
|
||||
}
|
||||
|
||||
/// `native_give_stack` for the auction house: what didn't fit, encoded
|
||||
/// again (all of it when the data can't be read: it waits in the mail).
|
||||
fn give_whole_to(game: &mut Game<'_>, uuid: u128, w: &smp_auction::Whole) -> Option<smp_auction::Whole> {
|
||||
let Some(stack) = decode_stack(&w.data) else {
|
||||
log::error!("[smp] auction house: a stack's data can't be read; it stays in the mail");
|
||||
return Some(w.clone());
|
||||
};
|
||||
let rest = game.native_give_stack(uuid, stack)?;
|
||||
Some(whole_of(&rest).unwrap_or_else(|| w.clone()))
|
||||
}
|
||||
|
||||
impl smp_auction::Hand for GameBag<'_, '_> {
|
||||
/// The acting player's state is swapped into the game inside their
|
||||
/// command, so the hand is the game's selected slot (no helper hands out
|
||||
/// a whole stack yet).
|
||||
fn held_whole(&self) -> Option<Result<smp_auction::Whole, String>> {
|
||||
let s = self.0.inventory.get(self.0.selected)?.as_ref()?;
|
||||
if let Some(why) = unsellable(s) {
|
||||
return Some(Err(why));
|
||||
}
|
||||
whole_of(s).map(Ok)
|
||||
}
|
||||
fn take_held(&mut self, held: &smp_auction::Whole, count: u32) -> Option<smp_auction::Whole> {
|
||||
self.0.player.as_ref()?;
|
||||
let selected = self.0.selected;
|
||||
let slot = self.0.inventory.get_mut(selected)?;
|
||||
let s = slot.as_ref()?;
|
||||
if count == 0 || count > s.count || encode_stack(s).as_deref() != Some(held.data.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let mut taken = s.clone();
|
||||
taken.count = count;
|
||||
let encoded = whole_of(&taken)?;
|
||||
if count == s.count {
|
||||
*slot = None;
|
||||
} else if let Some(s) = slot.as_mut() {
|
||||
s.count -= count;
|
||||
}
|
||||
Some(encoded)
|
||||
}
|
||||
fn fits(&mut self, w: &smp_auction::Whole) -> bool {
|
||||
let Some(stack) = decode_stack(&w.data) else {
|
||||
return false;
|
||||
};
|
||||
let max = self.0.native_max_stack_size(&stack.item).unwrap_or(64).max(1);
|
||||
fits_in(&self.0.inventory, &stack, max)
|
||||
}
|
||||
fn give_whole(&mut self, w: &smp_auction::Whole) -> Option<smp_auction::Whole> {
|
||||
let Some(me) = self.0.native_acting_player() else {
|
||||
return Some(w.clone());
|
||||
};
|
||||
give_whole_to(self.0, me.uuid, w)
|
||||
}
|
||||
}
|
||||
|
||||
const COMMANDS: [&str; 16] = [
|
||||
"balance", "bal", "pay", "baltop", "eco", "money", "worth", "sell", "buy", "shop", "market", "trade", "coinflip",
|
||||
"lottery", "ah", "casino",
|
||||
];
|
||||
|
||||
/// `/pay <player> <amount>`'s receiver (account, name) and amount, as
|
||||
/// `Economy::pay` reads them; None for another command.
|
||||
fn pay_target(e: &Economy, line: &str) -> Option<(u128, String, i64)> {
|
||||
let [cmd, who, amount] = line.split_whitespace().collect::<Vec<_>>()[..] else {
|
||||
return None;
|
||||
/// The world border, from the Overworld's `world_border.dat` (the root's in
|
||||
/// older worlds), as the game last saved it; None without one (the default
|
||||
/// border, 60 million blocks wide).
|
||||
fn world_border(world: &std::path::Path) -> Option<smp_places::Bounds> {
|
||||
let files = [
|
||||
world.join("dimensions/minecraft/overworld/data/minecraft/world_border.dat"),
|
||||
world.join("data/minecraft/world_border.dat"),
|
||||
];
|
||||
let root = files
|
||||
.iter()
|
||||
.find_map(|f| horizon_world::datafix::files::read_saved_dat(f).ok().flatten())?;
|
||||
let border = horizon_client::worldborder::WorldBorder::unpack(root.get("data")?);
|
||||
Some(border.bounds())
|
||||
}
|
||||
|
||||
/// After a level's tick: in the Overworld, each `/rtp` that waits reads the
|
||||
/// chunk it loads (the game reads only the level it ticks), five times a
|
||||
/// second. Columns in another player's claim are never a spot.
|
||||
pub(in crate::game) fn level_ticked(game: &mut Game<'_>, dimension: &str) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
if dimension != smp_places::OVERWORLD
|
||||
|| !RTP.load(Relaxed)
|
||||
|| TICKS.load(Relaxed) % 4 != 0
|
||||
|| !game.native_on(ID)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(dir) = game.native_world_dir() else {
|
||||
return;
|
||||
};
|
||||
if cmd != "pay" {
|
||||
let mut guard = state(dir.join(smp_store::DIR));
|
||||
let Some(smp) = guard.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let (Ok(places), claims) = (&mut smp.places, &smp.claims) else {
|
||||
return;
|
||||
};
|
||||
let game = &*game;
|
||||
let mut cost = RTP_COST.lock().unwrap_or_else(|e| e.into_inner());
|
||||
places.rtp_look(&mut |uuid, (cx, cz)| {
|
||||
let started = std::time::Instant::now();
|
||||
let ground = read_chunk(game, claims, uuid, (cx, cz));
|
||||
let us = started.elapsed().as_micros() as u64;
|
||||
match cost.iter_mut().find(|c| c.0 == uuid) {
|
||||
Some(c) => *c = (uuid, c.1 + 1, c.2 + us, c.3.max(us)),
|
||||
None => cost.push((uuid, 1, us, us)),
|
||||
}
|
||||
ground
|
||||
});
|
||||
RTP.store(places.rtp_searching(), Relaxed);
|
||||
}
|
||||
|
||||
/// Chunk `(cx, cz)` of the Overworld as `/rtp` reads it, None while it isn't
|
||||
/// loaded; no columns when another player claimed it.
|
||||
fn read_chunk(
|
||||
game: &Game<'_>,
|
||||
claims: &Result<Claims, String>,
|
||||
uuid: u128,
|
||||
(cx, cz): (i32, i32),
|
||||
) -> Option<smp_places::Ground> {
|
||||
let columns: Vec<(i32, i32)> = (0..256).map(|i| (cx * 16 + i / 16, cz * 16 + i % 16)).collect();
|
||||
let read = game
|
||||
.native_read_columns(
|
||||
smp_places::OVERWORLD,
|
||||
&columns,
|
||||
crate::game::native_world_edit::NativeHeightmap::MotionBlockingNoLeaves,
|
||||
(1, 2),
|
||||
)
|
||||
.ok()?;
|
||||
if read.bases.iter().any(Option::is_none) {
|
||||
return None;
|
||||
}
|
||||
let amount = smp_economy::parse_amount(amount)?;
|
||||
let (to, account) = e.find(who)?;
|
||||
Some((to, account.name.clone(), amount))
|
||||
let mut ground = smp_places::Ground { palette: read.palette, columns: Vec::new() };
|
||||
let claimed = claims
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|c| c.owner(smp_places::OVERWORLD, cx * 16, cz * 16))
|
||||
.is_some_and(|owner| owner != uuid);
|
||||
if !claimed {
|
||||
for (i, (&(x, z), base)) in columns.iter().zip(&read.bases).enumerate() {
|
||||
let b = &read.blocks[i * 3..i * 3 + 3];
|
||||
ground.columns.push((x, z, base.unwrap_or_default(), [b[0], b[1], b[2]]));
|
||||
}
|
||||
}
|
||||
Some(ground)
|
||||
}
|
||||
|
||||
/// The players on, as the places see them.
|
||||
@@ -497,6 +732,8 @@ pub(in crate::game) fn perform(
|
||||
&smp_board::COMMANDS,
|
||||
&smp_presence::COMMANDS,
|
||||
&smp_nick::COMMANDS,
|
||||
&smp_vanish::COMMANDS,
|
||||
&smp_switch::COMMANDS,
|
||||
];
|
||||
if !game.native_on(ID) || !ours.iter().any(|c| c.contains(&word)) {
|
||||
return;
|
||||
@@ -513,20 +750,44 @@ pub(in crate::game) fn perform(
|
||||
// Survival and adventure: a creative player could sell what they made.
|
||||
let trades = matches!(player.game_mode, 0 | 2);
|
||||
let players = game.native_server_players();
|
||||
let online = |name: &str| {
|
||||
players
|
||||
.iter()
|
||||
.find(|p| p.name.eq_ignore_ascii_case(name))
|
||||
.map(|p| (p.uuid, p.name.clone(), matches!(p.game_mode, 0 | 2)))
|
||||
};
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
let mut guard = state(dir.join(smp_store::DIR));
|
||||
let smp = guard.as_mut().expect("opened");
|
||||
// A vanished player is out of reach (trades, teleports, bets) of those
|
||||
// who don't see them.
|
||||
let hidden: Vec<u128> = smp.vanish.as_ref().map_or_else(
|
||||
|_| Vec::new(),
|
||||
|v| players.iter().filter(|p| !v.sees(me.level, p.uuid)).map(|p| p.uuid).collect(),
|
||||
);
|
||||
let online = |name: &str| {
|
||||
players
|
||||
.iter()
|
||||
.filter(|p| !hidden.contains(&p.uuid))
|
||||
.find(|p| p.name.eq_ignore_ascii_case(name))
|
||||
.map(|p| (p.uuid, p.name.clone(), matches!(p.game_mode, 0 | 2)))
|
||||
};
|
||||
// The switches: `/smp` itself, then a part turned off answers alone.
|
||||
if let Some((out, changed)) = smp.switches.command(&me, now, line) {
|
||||
let out = switched(game, smp, &me, &players, changed, now, out);
|
||||
drop(guard);
|
||||
*ran = true;
|
||||
show(game, out);
|
||||
return;
|
||||
}
|
||||
if let Some(part) = smp_switch::Part::of_command(word).filter(|&p| !smp.switches.on(p)) {
|
||||
let refusal = smp_switch::refusal(part);
|
||||
drop(guard);
|
||||
*ran = true;
|
||||
show(game, vec![refusal]);
|
||||
return;
|
||||
}
|
||||
let mut acts = Vec::new();
|
||||
// Any SMP command is activity (no longer AFK), and past the limit waits.
|
||||
let mut sleeps = Vec::new();
|
||||
let mut before = Vec::new();
|
||||
if let Ok(p) = &mut smp.presence {
|
||||
if let Ok(p) = &mut smp.presence
|
||||
&& smp.switches.on(Part::Presence)
|
||||
{
|
||||
match p.allow(&me, now) {
|
||||
Ok((o, a)) => (before, sleeps) = (o, a),
|
||||
Err(o) => {
|
||||
@@ -548,7 +809,24 @@ pub(in crate::game) fn perform(
|
||||
n.resolve(line, &is_name, &name_of)
|
||||
});
|
||||
let line = resolved.as_deref().unwrap_or(line);
|
||||
let out = if smp_nick::COMMANDS.contains(&word) {
|
||||
let out = if smp_vanish::COMMANDS.contains(&word) {
|
||||
let ops: Vec<u128> = players.iter().filter(|p| p.permission >= smp_vanish::LEVEL).map(|p| p.uuid).collect();
|
||||
match &mut smp.vanish {
|
||||
Ok(v) => {
|
||||
let out = v.command(&me, &ops, line).unwrap_or_default();
|
||||
// Hidden or shown at once; the subtitle comes with the next
|
||||
// second (commands can't run inside a player's).
|
||||
for (uuid, hidden) in v.changes() {
|
||||
game.native_hide_player(uuid, hidden.then_some(smp_vanish::LEVEL));
|
||||
}
|
||||
if let Ok(p) = &mut smp.presence {
|
||||
p.quiet = v.quiet();
|
||||
}
|
||||
out
|
||||
}
|
||||
Err(_) => vec![Out::Error("/vanish is off: vanish.json can't be read (see the server log).".into())],
|
||||
}
|
||||
} else if smp_nick::COMMANDS.contains(&word) {
|
||||
let names = ServerNames::read(&dir, smp.economy.as_ref().ok());
|
||||
match &mut smp.nicks {
|
||||
Ok(n) => {
|
||||
@@ -618,7 +896,15 @@ pub(in crate::game) fn perform(
|
||||
}
|
||||
} else if smp_places::COMMANDS.contains(&word) {
|
||||
match &mut smp.places {
|
||||
Ok(p) => p.command(&me, &bodies(&players), now, line).unwrap_or_default(),
|
||||
Ok(p) => {
|
||||
if matches!(word, "rtp" | "wild") {
|
||||
p.border = world_border(&dir);
|
||||
RTP_COST.lock().unwrap_or_else(|e| e.into_inner()).retain(|c| c.0 != me.uuid);
|
||||
BUSY.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
let seen: Vec<NativeServerPlayer> = players.iter().filter(|p| !hidden.contains(&p.uuid)).cloned().collect();
|
||||
p.command(&me, &bodies(&seen), now, line).unwrap_or_default()
|
||||
}
|
||||
Err(_) => vec![Out::Error(
|
||||
"Homes and warps are off: their file can't be read (see the server log).".into(),
|
||||
)],
|
||||
@@ -646,27 +932,7 @@ pub(in crate::game) fn perform(
|
||||
let report = smp.report.as_ref();
|
||||
report
|
||||
.and_then(|r| r.command(e, line))
|
||||
.or_else(|| {
|
||||
// A payment counts toward the receiver's daily selling
|
||||
// limit (alts can't sell for a main past it).
|
||||
let paid = pay_target(e, line);
|
||||
if let Some((to, name, amount)) = &paid
|
||||
&& let Err(left) = smp.market.may_receive(*to, *amount, now)
|
||||
{
|
||||
return Some(vec![Out::Error(format!(
|
||||
"{name} can only receive {} more today: payments count toward the same daily limit as selling to the market.",
|
||||
e.money(left)
|
||||
))]);
|
||||
}
|
||||
let before = paid.as_ref().map(|(to, ..)| e.balance(*to));
|
||||
let out = e.command(&me, &on, line);
|
||||
if let (Some((to, _, amount)), Some(b)) = (paid, before)
|
||||
&& e.balance(to) == b + amount
|
||||
{
|
||||
smp.market.count_received(to, now, amount);
|
||||
}
|
||||
out
|
||||
})
|
||||
.or_else(|| e.command(&me, &on, line))
|
||||
.or_else(|| smp.market.command(e, &me, trades, &mut bag, line))
|
||||
.or_else(|| {
|
||||
let (out, a) = smp.trades.command(e, &me, trades, &online, now, line)?;
|
||||
@@ -709,6 +975,9 @@ pub(in crate::game) fn guard(game: &mut Game<'_>, pos: [i32; 3], canceled: &mut
|
||||
};
|
||||
let mut guard = state(dir.join(smp_store::DIR));
|
||||
let smp = guard.as_mut().expect("opened");
|
||||
if !smp.switches.on(Part::Claims) {
|
||||
return;
|
||||
}
|
||||
let Ok(claims) = &mut smp.claims else {
|
||||
return;
|
||||
};
|
||||
@@ -743,7 +1012,7 @@ pub(in crate::game) fn attack(game: &mut Game<'_>, kind: &str, pos: [f64; 3], ca
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.claims.as_ref().is_ok_and(|c| c.protects(kind)));
|
||||
.is_some_and(|s| s.switches.on(Part::Claims) && s.claims.as_ref().is_ok_and(|c| c.protects(kind)));
|
||||
if protected {
|
||||
guard(game, pos.map(|v| v.floor() as i32), canceled);
|
||||
}
|
||||
@@ -766,7 +1035,7 @@ pub(in crate::game) fn world_allows(dimension: &str, from: [i32; 3], to: &[[i32;
|
||||
let Ok(state) = STATE.try_lock() else {
|
||||
return true;
|
||||
};
|
||||
match state.as_ref().map(|s| &s.claims) {
|
||||
match state.as_ref().filter(|s| s.switches.on(Part::Claims)).map(|s| &s.claims) {
|
||||
Some(Ok(c)) => to.iter().all(|&t| c.spread_allowed(dimension, from, t)),
|
||||
_ => true,
|
||||
}
|
||||
@@ -781,7 +1050,7 @@ pub(in crate::game) fn explosion(game: &Game<'_>, dimension: &str, blocks: &mut
|
||||
let Ok(state) = STATE.try_lock() else {
|
||||
return;
|
||||
};
|
||||
if let Some(Ok(c)) = state.as_ref().map(|s| &s.claims) {
|
||||
if let Some(Ok(c)) = state.as_ref().filter(|s| s.switches.on(Part::Claims)).map(|s| &s.claims) {
|
||||
c.spare(dimension, blocks);
|
||||
}
|
||||
}
|
||||
@@ -959,6 +1228,14 @@ pub(in crate::game) fn menu_clicked(game: &mut Game<'_>, uuid: u128, window: i32
|
||||
};
|
||||
let mut guard = state(dir.join(smp_store::DIR));
|
||||
let smp = guard.as_mut().expect("opened");
|
||||
// A menu of a part turned off since it opened: closed, nothing done.
|
||||
if let Some(part) = menu_part(smp, uuid, window).filter(|&p| !smp.switches.on(p)) {
|
||||
let refusal = smp_switch::refusal(part);
|
||||
drop(guard);
|
||||
game.native_close_menu(uuid);
|
||||
tell(game, uuid, vec![refusal]);
|
||||
return;
|
||||
}
|
||||
if smp.shop.views.get(&uuid).is_some_and(|v| v.0 == Some(window)) {
|
||||
shop_clicked(game, smp, uuid, slot, mode == 1);
|
||||
return;
|
||||
@@ -1007,6 +1284,133 @@ pub(in crate::game) fn menu_clicked(game: &mut Game<'_>, uuid: u128, window: i32
|
||||
show(game, out);
|
||||
}
|
||||
|
||||
/// The part whose menu `window` is, open for that player.
|
||||
fn menu_part(smp: &Smp, uuid: u128, window: i32) -> Option<Part> {
|
||||
let open = |v: Option<i32>| v == Some(window);
|
||||
if smp.shop.views.get(&uuid).is_some_and(|v| open(v.0)) || smp.market_menus.views.get(&uuid).is_some_and(|v| open(v.0)) {
|
||||
return Some(Part::Market);
|
||||
}
|
||||
if smp.auction.as_ref().is_some_and(|a| a.views.get(&uuid).is_some_and(|v| open(v.0))) {
|
||||
return Some(Part::Auction);
|
||||
}
|
||||
if smp.casino.owns(uuid, window) {
|
||||
return Some(Part::Gambling);
|
||||
}
|
||||
let trade = smp.trades.trade_of(uuid);
|
||||
trade.and_then(|t| t.side_of(uuid).map(|me| t.sides[me].window)).filter(|&w| open(w)).map(|_| Part::Trades)
|
||||
}
|
||||
|
||||
/// Parts turned off or on by `/smp`: what was under way in those turned off
|
||||
/// stops (trades end with nothing moved, menus close, teleports waiting are
|
||||
/// called off, sidebars and nicknames are taken away), the other operators
|
||||
/// on are told, and the change is in the server's log and `audit.log`.
|
||||
fn switched(
|
||||
game: &mut Game<'_>,
|
||||
smp: &mut Smp,
|
||||
me: &Player,
|
||||
players: &[NativeServerPlayer],
|
||||
changed: smp_switch::Changed,
|
||||
now: i64,
|
||||
mut out: Vec<Out>,
|
||||
) -> Vec<Out> {
|
||||
let names = |ps: &[Part]| ps.iter().map(|p| p.name()).collect::<Vec<_>>().join(", ");
|
||||
let reason = line_reason(&smp.switches, &changed);
|
||||
for (verb, parts) in [("off", &changed.off), ("on", &changed.on)] {
|
||||
if parts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
log::warn!("[smp] {} turned {verb}: {}{reason}", me.name, names(parts));
|
||||
if let Ok(e) = &mut smp.economy
|
||||
&& let Err(err) = e.record(serde_json::json!({
|
||||
"time": now, "kind": format!("switch_{verb}"), "by": smp_store::uuid_string(me.uuid),
|
||||
"parts": parts.iter().map(|p| p.name()).collect::<Vec<_>>(), "reason": reason.trim_start_matches(": "),
|
||||
}))
|
||||
{
|
||||
log::error!("[smp] {err}");
|
||||
}
|
||||
for p in players.iter().filter(|p| p.permission >= smp_switch::LEVEL && p.uuid != me.uuid) {
|
||||
out.push(Out::Tell(p.uuid, format!("[SMP] {} turned {verb}: {}{reason}", me.name, names(parts))));
|
||||
}
|
||||
}
|
||||
for part in changed.off {
|
||||
match part {
|
||||
Part::Trades => {
|
||||
let sides: Vec<u128> = smp.trades.open.iter().map(|t| t.sides[0].uuid).collect();
|
||||
for uuid in sides {
|
||||
let (o, acts) = smp.trades.end(uuid, "trading was turned off");
|
||||
out.extend(o);
|
||||
act(game, smp, acts);
|
||||
}
|
||||
}
|
||||
Part::Market => {
|
||||
let open: Vec<u128> = smp.shop.views.keys().chain(smp.market_menus.views.keys()).copied().collect();
|
||||
open.into_iter().for_each(|u| game.native_close_menu(u));
|
||||
}
|
||||
Part::Auction => {
|
||||
let open: Vec<u128> = smp.auction.as_ref().map(|a| a.views.keys().copied().collect()).unwrap_or_default();
|
||||
open.into_iter().for_each(|u| game.native_close_menu(u));
|
||||
}
|
||||
// A round under way still ends and is paid when its menu closes
|
||||
// (`menu_clicked` closes it at the next click).
|
||||
Part::Gambling => {}
|
||||
Part::Places => {
|
||||
if let Ok(p) = &mut smp.places {
|
||||
for t in std::mem::take(&mut p.pending) {
|
||||
out.push(Out::Tell(t.uuid, "Teleport called off: teleporting was turned off.".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Part::Claims => smp.shows.clear(),
|
||||
Part::Board => {
|
||||
if let Ok(b) = &mut smp.board {
|
||||
b.forget();
|
||||
}
|
||||
let blank = Text::literal("");
|
||||
for p in players {
|
||||
game.native_sidebar(p.uuid, None);
|
||||
game.native_tab_list(p.uuid, &blank, &blank);
|
||||
}
|
||||
}
|
||||
Part::Nicks => {
|
||||
for uuid in std::mem::take(&mut smp.nicks_shown) {
|
||||
game.native_set_nickname(uuid, None);
|
||||
}
|
||||
}
|
||||
// `/invsee` refuses and its open menus take no click.
|
||||
Part::Invsee | Part::Economy | Part::Presence => {}
|
||||
}
|
||||
}
|
||||
BUSY.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
out
|
||||
}
|
||||
|
||||
/// `: why` of the parts just turned off (as `switches.json` has it), or "".
|
||||
fn line_reason(switches: &Switches, changed: &smp_switch::Changed) -> String {
|
||||
changed
|
||||
.off
|
||||
.first()
|
||||
.and_then(|&p| switches.why(p))
|
||||
.filter(|r| !r.is_empty())
|
||||
.map(|r| format!(": {r}"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a command of a part turned off answers.
|
||||
pub(in crate::game) fn refusal(part: Part) -> String {
|
||||
match smp_switch::refusal(part) {
|
||||
Out::Error(s) | Out::Reply(s) | Out::Tell(_, s) | Out::All(s) => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a part of the SMP is on (`/smp off` turns them off), for the
|
||||
/// SMP's other glue (`/invsee`).
|
||||
pub(in crate::game) fn part_on(game: &Game<'_>, part: Part) -> bool {
|
||||
let Some(dir) = game.native_world_dir() else {
|
||||
return true;
|
||||
};
|
||||
state(dir.join(smp_store::DIR)).as_ref().is_none_or(|s| s.switches.on(part))
|
||||
}
|
||||
|
||||
/// A native menu closed: a trade's ends, nothing moved.
|
||||
pub(in crate::game) fn menu_closed(game: &mut Game<'_>, uuid: u128, window: i32) {
|
||||
if !game.native_on(ID) {
|
||||
@@ -1125,6 +1529,25 @@ impl Bag for MenuBag<'_, '_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl smp_auction::Hand for MenuBag<'_, '_> {
|
||||
fn held_whole(&self) -> Option<Result<smp_auction::Whole, String>> {
|
||||
None
|
||||
}
|
||||
fn take_held(&mut self, _held: &smp_auction::Whole, _count: u32) -> Option<smp_auction::Whole> {
|
||||
None
|
||||
}
|
||||
fn fits(&mut self, w: &smp_auction::Whole) -> bool {
|
||||
let Some(stack) = decode_stack(&w.data) else {
|
||||
return false;
|
||||
};
|
||||
let max = self.game.native_max_stack_size(&stack.item).unwrap_or(64).max(1);
|
||||
fits_in(&self.stacks(), &stack, max)
|
||||
}
|
||||
fn give_whole(&mut self, w: &smp_auction::Whole) -> Option<smp_auction::Whole> {
|
||||
give_whole_to(self.game, self.uuid, w)
|
||||
}
|
||||
}
|
||||
|
||||
/// The shop menu's cells as items.
|
||||
fn shop_items(smp: &Smp, uuid: u128) -> Vec<Option<ItemStack>> {
|
||||
let economy = smp.economy.as_ref().ok();
|
||||
@@ -1148,10 +1571,6 @@ fn shop_items(smp: &Smp, uuid: u128) -> Vec<Option<ItemStack>> {
|
||||
button("minecraft:gold_ingot", &format!("Balance: {}", money(b)), "gold")
|
||||
}
|
||||
C::SellAll => button("minecraft:hopper", "Sell everything the market buys", "green"),
|
||||
C::Limits => {
|
||||
let line = economy.and_then(|e| smp.market.limits_line(e, uuid));
|
||||
button("minecraft:clock", &line.unwrap_or_else(|| "No selling limit".into()), "aqua")
|
||||
}
|
||||
C::Help => button("minecraft:book", smp_shop::HELP_TEXT, "white"),
|
||||
C::Close => button("minecraft:barrier", "Close", "red"),
|
||||
})
|
||||
@@ -1332,9 +1751,6 @@ fn market_items(smp: &Smp, uuid: u128, now: i64) -> Vec<Option<ItemStack>> {
|
||||
let mut lines = price_lines(smp, &id, now);
|
||||
let base = smp.market.base(&id);
|
||||
lines.push((format!("Base price: {}", money(base.buy.max(base.sell))), "gray"));
|
||||
if let Some(left) = smp.market.items_left(uuid, now, &id) {
|
||||
lines.push((format!("You may still sell {left} today"), "gray"));
|
||||
}
|
||||
with_lore(button(&id, &name(&id), "white"), &lines)
|
||||
}
|
||||
C::Buy(id, n) => {
|
||||
@@ -1717,12 +2133,24 @@ fn ah_items(smp: &Smp, uuid: u128) -> Vec<Option<ItemStack>> {
|
||||
C::Listing(id) => {
|
||||
let l = a.listing(id)?;
|
||||
let color = if l.auction { "gold" } else { "white" };
|
||||
named_stack(&l.item, l.count, &a.label(l, now, &money), color)
|
||||
let label = a.label(l, now, &money);
|
||||
match l.stack.as_deref().and_then(decode_stack) {
|
||||
// The stack itself (its name, enchantments, contents
|
||||
// in the tooltip), the listing's facts under it.
|
||||
Some(stack) => {
|
||||
let lines: Vec<(String, &str)> = label.split(" · ").map(|p| (p.to_owned(), color)).collect();
|
||||
with_lore(stack, &lines)
|
||||
}
|
||||
None => named_stack(&l.item, l.count, &label, color),
|
||||
}
|
||||
}
|
||||
C::Parcel(i) => {
|
||||
let p = a.parcel(uuid, i)?;
|
||||
let name = format!("Claim {} {} ({})", p.count, smp_shop::title(&p.item), p.why);
|
||||
named_stack(&p.item, p.count, &name, "green")
|
||||
match p.stack.as_deref().and_then(decode_stack) {
|
||||
Some(stack) => with_lore(stack, &[(name, "green")]),
|
||||
None => named_stack(&p.item, p.count, &name, "green"),
|
||||
}
|
||||
}
|
||||
C::Confirm(id) => {
|
||||
let l = a.listing(id)?;
|
||||
@@ -1867,7 +2295,31 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
};
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
let mut out = Vec::new();
|
||||
// `/vanish`, once a second: the game told who is hidden (after a
|
||||
// restart), and the subtitle sent to each vanished player on.
|
||||
let vanished = smp.vanish.as_ref().map(|v| v.quiet()).unwrap_or_default();
|
||||
let (mut subtitles, mut unvanished) = (Vec::new(), Vec::new());
|
||||
if n % 20 == 0
|
||||
&& let Ok(v) = &mut smp.vanish
|
||||
{
|
||||
for (uuid, hidden) in v.changes() {
|
||||
game.native_hide_player(uuid, hidden.then_some(smp_vanish::LEVEL));
|
||||
}
|
||||
for p in &players {
|
||||
if vanished.contains(&p.uuid) {
|
||||
subtitles.push((p.uuid, p.name.clone()));
|
||||
} else if smp.vanish_titled.contains(&p.uuid) {
|
||||
unvanished.push((p.uuid, p.name.clone()));
|
||||
}
|
||||
}
|
||||
smp.vanish_titled = subtitles.iter().map(|s| s.0).collect();
|
||||
if let Ok(p) = &mut smp.presence {
|
||||
p.quiet = vanished.clone();
|
||||
}
|
||||
}
|
||||
// Teleports: each tick while one warms up; requests expire once a second.
|
||||
// With places off only the playtime counts.
|
||||
let places_on = smp.switches.on(Part::Places);
|
||||
if let Ok(p) = &mut smp.places
|
||||
&& (n % 20 == 0 || warming)
|
||||
{
|
||||
@@ -1875,7 +2327,7 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
let on: Vec<u128> = players.iter().map(|p| p.uuid).collect();
|
||||
p.played(&on, now);
|
||||
}
|
||||
let (o, go) = p.tick(&bodies(&players), now);
|
||||
let (o, go) = if places_on { p.tick(&bodies(&players), now) } else { Default::default() };
|
||||
out.extend(o);
|
||||
for t in go {
|
||||
// `.3`: a whole number would be a block's centre to `tp`.
|
||||
@@ -1889,8 +2341,27 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
out.push(Out::Tell(t.uuid, "The teleport failed.".into()));
|
||||
continue;
|
||||
}
|
||||
// `/spawn`: on to a safe column within the radius, as vanilla's
|
||||
// respawn does. If none is found the player stays at the spawn.
|
||||
if let Some(spread) = t.spread_line()
|
||||
&& !game.native_run_command(&spread)
|
||||
{
|
||||
log::warn!("[smp] no safe spot near the spawn: {spread}");
|
||||
}
|
||||
if t.what == "a random spot" {
|
||||
let mut cost = RTP_COST.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (_, n, total, max) = cost.iter().find(|c| c.0 == t.uuid).copied().unwrap_or_default();
|
||||
cost.retain(|c| c.0 != t.uuid);
|
||||
log::info!(
|
||||
"[smp] /rtp: {} to {:.1} {:.1} {:.1} ({n} chunk reads on the tick: {total} µs, longest {max} µs)",
|
||||
t.name, t.to.x, t.to.y, t.to.z
|
||||
);
|
||||
}
|
||||
out.push(Out::Tell(t.uuid, t.done.clone()));
|
||||
}
|
||||
// `/rtp`'s chunks: held loaded while it looks, let go after.
|
||||
p.force(now, &mut |line| game.native_run_command(line));
|
||||
RTP.store(p.rtp_searching(), Relaxed);
|
||||
}
|
||||
if let Ok(e) = &mut smp.economy
|
||||
&& n % 20 == 0
|
||||
@@ -1910,9 +2381,16 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
for uuid in gone {
|
||||
smp.games.left(e, uuid);
|
||||
}
|
||||
out.extend(smp.lottery.tick(&smp.games.config, e, now, &mut below));
|
||||
// A part turned off waits: its draws, endings, markings and payments
|
||||
// happen once it is on again (coinflips not taken still go back).
|
||||
let on = |p| smp.switches.on(p);
|
||||
if on(Part::Gambling) {
|
||||
out.extend(smp.lottery.tick(&smp.games.config, e, now, &mut below));
|
||||
}
|
||||
// The auction house: notes for who came on, listings that ended.
|
||||
if let Some(a) = &mut smp.auction {
|
||||
if let Some(a) = &mut smp.auction
|
||||
&& on(Part::Auction)
|
||||
{
|
||||
let on: Vec<u128> = players.iter().map(|p| p.uuid).collect();
|
||||
out.extend(a.tick(e, &on, now));
|
||||
}
|
||||
@@ -1987,7 +2465,9 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
}
|
||||
// Welcomes, daily rewards and AFK, once a second.
|
||||
let mut sleeps = std::mem::take(&mut *PENDING_SLEEP.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let economy_on = smp.switches.on(Part::Economy);
|
||||
if n % 20 == 0
|
||||
&& smp.switches.on(Part::Presence)
|
||||
&& let Ok(pr) = &mut smp.presence
|
||||
{
|
||||
let seen: Vec<smp_presence::Seen> = players
|
||||
@@ -2006,7 +2486,9 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
for a in acts {
|
||||
match a {
|
||||
smp_presence::Act::Reward(uuid) => {
|
||||
if let Ok(e) = &mut smp.economy {
|
||||
if let Ok(e) = &mut smp.economy
|
||||
&& economy_on
|
||||
{
|
||||
match e.adjust("daily_reward", uuid, reward, "") {
|
||||
Ok(_) => out.push(Out::Tell(uuid, format!("Daily reward: {}.", e.money(reward)))),
|
||||
Err(err) => log::warn!("[smp] daily reward: {err}"),
|
||||
@@ -2045,6 +2527,7 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
let mut tab = None;
|
||||
let (nicks, places) = (&smp.nicks, &smp.places);
|
||||
if n % 20 == 0
|
||||
&& smp.switches.on(Part::Board)
|
||||
&& let Ok(b) = &mut smp.board
|
||||
{
|
||||
let on: Vec<u128> = players.iter().map(|p| p.uuid).collect();
|
||||
@@ -2064,16 +2547,20 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
.unwrap_or_default(),
|
||||
played_seconds: places.as_ref().map_or(0, |p| p.played_seconds(uuid)),
|
||||
};
|
||||
b.quiet = vanished.clone();
|
||||
sidebars = b.updates(now, &on, me);
|
||||
let to = b.tab_due(now, &on);
|
||||
if !to.is_empty() {
|
||||
let (rate, mspt) = game.native_tick_stats();
|
||||
let tps = f64::from(rate).min(1000.0 / mspt.max(0.001));
|
||||
tab = Some((to, b.tab_lines(tps, mspt, on.len())));
|
||||
// Vanished players aren't counted: the footer is everyone's.
|
||||
let shown = on.iter().filter(|u| !b.quiet.contains(u)).count();
|
||||
tab = Some((to, b.tab_lines(tps, mspt, shown)));
|
||||
}
|
||||
}
|
||||
// Nicknames: the changes asked for, then those of players who came on.
|
||||
if n % 20 == 0
|
||||
&& smp.switches.on(Part::Nicks)
|
||||
&& let Ok(nicks) = &mut smp.nicks
|
||||
{
|
||||
let pending = std::mem::take(&mut nicks.pending);
|
||||
@@ -2129,6 +2616,23 @@ pub(in crate::game) fn tick(game: &mut Game<'_>) {
|
||||
game.native_sleep_ignored(uuid, ignored);
|
||||
}
|
||||
}
|
||||
// A vanished player doesn't hold the night up; the subtitle lasts a
|
||||
// little past the next second's (1.5 s), so it never blinks.
|
||||
for (uuid, name) in subtitles {
|
||||
game.native_sleep_ignored(uuid, true);
|
||||
let subtitle = serde_json::json!({"text": smp_vanish::SUBTITLE, "color": "aqua"});
|
||||
for line in [
|
||||
format!("title {name} times 0 30 5"),
|
||||
format!("title {name} subtitle {subtitle}"),
|
||||
format!("title {name} title \"\""),
|
||||
] {
|
||||
game.native_run_command(&line);
|
||||
}
|
||||
}
|
||||
for (uuid, name) in unvanished {
|
||||
game.native_sleep_ignored(uuid, false);
|
||||
game.native_run_command(&format!("title {name} clear"));
|
||||
}
|
||||
for line in particles.into_iter().chain(casino) {
|
||||
game.native_run_command(&line);
|
||||
}
|
||||
@@ -2243,14 +2747,6 @@ fn sidebar(title: &str, lines: &[Line]) -> NativeSidebar {
|
||||
)
|
||||
}
|
||||
Line::Gap => (Text::literal(""), None),
|
||||
Line::Heading => (Text::literal("Richest").with_color(text::YELLOW), None),
|
||||
Line::Top { rank, name, amount, me } => {
|
||||
let color = if *me { text::GREEN } else { text::WHITE };
|
||||
(
|
||||
Text::literal(format!("{rank}. ")).with_color(text::GRAY).append(Text::literal(name.clone()).with_color(color)),
|
||||
Some(Text::literal(amount.clone()).with_color(text::GOLD)),
|
||||
)
|
||||
}
|
||||
Line::Footer(address) => (Text::literal(address.clone()).with_color(text::AQUA), None),
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
[mod]
|
||||
id = "smp"
|
||||
version = "0.30.1"
|
||||
version = "0.33.0"
|
||||
priority = 100
|
||||
|
||||
# The commit of horizon it was tested on: it needs horizon#6106 (merged at 975c07d): native_inventory,
|
||||
# native_move_stack, native_send_map, lore on the wire.
|
||||
# The commit of horizon it was tested on: it needs native_hide_player (horizon#7003, API 314, stamped at 48c63bc),
|
||||
# on top of horizon#6106's native_inventory, native_move_stack, native_send_map and lore on the wire.
|
||||
[compatibility]
|
||||
horizon_revision = "975c07d9151847e6af13afc4b5ab37b6bbe78ef5"
|
||||
horizon_revision = "48c63bc09d9acc82f2074e75ae59720514796a9d"
|
||||
|
||||
[[module]]
|
||||
id = "store"
|
||||
@@ -74,6 +74,12 @@ file = "crates/horizon-client/src/game.rs"
|
||||
name = "smp_trade"
|
||||
source = "smp_trade.rs"
|
||||
|
||||
[[module]]
|
||||
id = "vanish"
|
||||
file = "crates/horizon-client/src/game.rs"
|
||||
name = "smp_vanish"
|
||||
source = "smp_vanish.rs"
|
||||
|
||||
[[module]]
|
||||
id = "games"
|
||||
file = "crates/horizon-client/src/game.rs"
|
||||
@@ -164,6 +170,12 @@ file = "crates/horizon-client/src/game.rs"
|
||||
name = "smp_invsee_glue"
|
||||
source = "invsee_glue.rs"
|
||||
|
||||
[[module]]
|
||||
id = "switch"
|
||||
file = "crates/horizon-client/src/game.rs"
|
||||
name = "smp_switch"
|
||||
source = "smp_switch.rs"
|
||||
|
||||
[[module]]
|
||||
id = "glue"
|
||||
file = "crates/horizon-client/src/game.rs"
|
||||
@@ -201,6 +213,16 @@ bindings = [
|
||||
{ name = "phase", ty = "crate::game::native_lifecycle::ServerTickPhase", value = "phase" },
|
||||
]
|
||||
|
||||
[[injection]]
|
||||
id = "level_tick"
|
||||
kind = "HEAD"
|
||||
target = "horizon_client::game::native_hooks::Game<'_>::native_level_tick_post"
|
||||
helper = "level_tick.rs"
|
||||
bindings = [
|
||||
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
|
||||
{ name = "dimension", ty = "&str", value = "dimension" },
|
||||
]
|
||||
|
||||
[[injection]]
|
||||
id = "lifecycle"
|
||||
kind = "HEAD"
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::game::{
|
||||
smp_economy::{Out, Player},
|
||||
smp_glue,
|
||||
smp_invsee::{self, Cell, Invsee, Kind, Move},
|
||||
smp_store,
|
||||
smp_store, smp_switch,
|
||||
};
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
@@ -88,6 +88,11 @@ pub(in crate::game) fn perform(game: &mut Game<'_>, player: &NativeServerPlayer,
|
||||
return;
|
||||
}
|
||||
*ran = true;
|
||||
if !smp_glue::part_on(game, smp_switch::Part::Invsee) {
|
||||
let refusal = smp_glue::refusal(smp_switch::Part::Invsee);
|
||||
game.native_feedback(Text::literal(refusal).with_color(text::RED));
|
||||
return;
|
||||
}
|
||||
let me = Player {
|
||||
uuid: player.uuid,
|
||||
name: player.name.clone(),
|
||||
@@ -251,6 +256,12 @@ pub(in crate::game) fn menu_clicked(game: &mut Game<'_>, uuid: u128, window: i32
|
||||
if !matches!(mode, 0 | 1) {
|
||||
return true;
|
||||
}
|
||||
// Turned off since it opened: closed, nothing moves.
|
||||
if !smp_glue::part_on(game, smp_switch::Part::Invsee) {
|
||||
drop(guard);
|
||||
game.native_close_menu(uuid);
|
||||
return true;
|
||||
}
|
||||
let mut asked: Option<Move> = None;
|
||||
// Each move is in the audit log before it is made; one the log
|
||||
// refuses isn't made.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
// After a level's tick: in the Overworld, the `/rtp`s waiting for their land
|
||||
// read it (the game reads only the level it ticks).
|
||||
fn smp_level_tick_post(game: &mut crate::game::Game<'_>, dimension: &str) {
|
||||
crate::game::smp_glue::level_ticked(game, dimension);
|
||||
}
|
||||
@@ -13,11 +13,14 @@
|
||||
// action on its one server thread, under the SMP's lock: of two players who
|
||||
// buy the same listing at once, the second finds it gone.
|
||||
//
|
||||
// Plain items only for now (not worn, named or enchanted): the hook point
|
||||
// that gives a whole stack with its components (`native_give_stack`) isn't
|
||||
// stamped yet. No game types: the glue lends the items (`Bag`) and draws the
|
||||
// menu from `Cell`s. Added to the game as `game::smp_auction`; also a module
|
||||
// of this crate, for its tests.
|
||||
// A listing carries the whole stack: its enchantments, name, damage,
|
||||
// contents (a shulker box's, a bundle's) and every other component, kept as
|
||||
// the glue encodes it (`Whole::data`) and given back exactly so
|
||||
// (`native_give_stack`). Listings and mail from before 0.31 hold plain items
|
||||
// by id and count (no `stack`) and are given back as they were. No game
|
||||
// types: the glue lends the items (`Hand`) and draws the menu from `Cell`s.
|
||||
// Added to the game as `game::smp_auction`; also a module of this crate, for
|
||||
// its tests.
|
||||
|
||||
use super::smp_economy::{DAY_MS, Economy, MAX_AMOUNT, Out, Player, parse_amount};
|
||||
use super::smp_market::{Bag, item_name, valid_id};
|
||||
@@ -98,6 +101,10 @@ pub struct Listing {
|
||||
pub seller_name: String,
|
||||
pub item: String,
|
||||
pub count: u32,
|
||||
/// The whole stack as the glue encodes it; None: `count` plain `item`
|
||||
/// (a listing from before 0.31).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub stack: Option<String>,
|
||||
/// The price (fixed), or the starting bid (auction).
|
||||
pub price: i64,
|
||||
pub auction: bool,
|
||||
@@ -119,6 +126,9 @@ impl Listing {
|
||||
pub struct Parcel {
|
||||
pub item: String,
|
||||
pub count: u32,
|
||||
/// The whole stack, as `Listing::stack`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub stack: Option<String>,
|
||||
/// `expired`, `won`, `cancelled`...
|
||||
pub why: String,
|
||||
}
|
||||
@@ -154,6 +164,91 @@ pub struct Data {
|
||||
pub today: Today,
|
||||
}
|
||||
|
||||
/// A whole stack as the glue lends it: its id and count (what lines and
|
||||
/// menus show) and the stack itself in the glue's encoding, every component
|
||||
/// kept. The glue's encoding is the truth; `item` and `count` repeat it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Whole {
|
||||
pub item: String,
|
||||
pub count: u32,
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
/// The acting player's items, whole stacks too.
|
||||
pub trait Hand: Bag {
|
||||
/// The main hand's stack (None: empty hand), or why it can't be sold.
|
||||
fn held_whole(&self) -> Option<Result<Whole, String>>;
|
||||
/// Takes `count` of the main hand's stack while it is still exactly
|
||||
/// `held`: the part taken (the rest stays in the hand), or None and
|
||||
/// nothing moved.
|
||||
fn take_held(&mut self, held: &Whole, count: u32) -> Option<Whole>;
|
||||
/// Whether `stack` fits whole in the inventory.
|
||||
fn fits(&mut self, stack: &Whole) -> bool;
|
||||
/// Gives `stack` where it fits: what didn't fit (None: all of it given).
|
||||
fn give_whole(&mut self, stack: &Whole) -> Option<Whole>;
|
||||
}
|
||||
|
||||
/// Items on their way: plain (`stack` None) or one whole stack.
|
||||
struct Goods {
|
||||
item: String,
|
||||
count: u32,
|
||||
stack: Option<String>,
|
||||
}
|
||||
|
||||
impl Goods {
|
||||
fn of(l: &Listing) -> Self {
|
||||
Self {
|
||||
item: l.item.clone(),
|
||||
count: l.count,
|
||||
stack: l.stack.clone(),
|
||||
}
|
||||
}
|
||||
fn whole(&self) -> Option<Whole> {
|
||||
self.stack.as_ref().map(|data| Whole {
|
||||
item: self.item.clone(),
|
||||
count: self.count,
|
||||
data: data.clone(),
|
||||
})
|
||||
}
|
||||
/// Whether they fit in `bag` now.
|
||||
fn fit(&self, bag: &mut dyn Hand) -> bool {
|
||||
match self.whole() {
|
||||
Some(w) => bag.fits(&w),
|
||||
None => bag.room(&self.item) >= self.count,
|
||||
}
|
||||
}
|
||||
/// Gives them: how many went, and what is left (None: all went).
|
||||
fn give(&self, bag: &mut dyn Hand) -> (u32, Option<Goods>) {
|
||||
match self.whole() {
|
||||
Some(w) => match bag.give_whole(&w) {
|
||||
None => (self.count, None),
|
||||
Some(rest) => (
|
||||
self.count.saturating_sub(rest.count),
|
||||
Some(Goods {
|
||||
item: rest.item,
|
||||
count: rest.count,
|
||||
stack: Some(rest.data),
|
||||
}),
|
||||
),
|
||||
},
|
||||
None => {
|
||||
let given = if self.count > 0 {
|
||||
bag.give(&self.item, self.count)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let left = self.count - given.min(self.count);
|
||||
let rest = (left > 0).then(|| Goods {
|
||||
item: self.item.clone(),
|
||||
count: left,
|
||||
stack: None,
|
||||
});
|
||||
(given, rest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which listings a list page shows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Filter {
|
||||
@@ -342,8 +437,8 @@ impl AuctionHouse {
|
||||
}
|
||||
|
||||
/// Items to `uuid`'s mail.
|
||||
fn post(&mut self, uuid: &str, item: &str, count: u32, why: &str) {
|
||||
if count == 0 {
|
||||
fn post(&mut self, uuid: &str, goods: Goods, why: &str) {
|
||||
if goods.count == 0 {
|
||||
return;
|
||||
}
|
||||
self.data
|
||||
@@ -351,8 +446,9 @@ impl AuctionHouse {
|
||||
.entry(uuid.to_owned())
|
||||
.or_default()
|
||||
.push(Parcel {
|
||||
item: item.to_owned(),
|
||||
count,
|
||||
item: goods.item,
|
||||
count: goods.count,
|
||||
stack: goods.stack,
|
||||
why: why.to_owned(),
|
||||
});
|
||||
self.dirty = true;
|
||||
@@ -426,7 +522,7 @@ impl AuctionHouse {
|
||||
economy: &mut Economy,
|
||||
me: &Player,
|
||||
trades: bool,
|
||||
bag: &mut dyn Bag,
|
||||
bag: &mut dyn Hand,
|
||||
now: i64,
|
||||
line: &str,
|
||||
) -> Option<Reply> {
|
||||
@@ -510,7 +606,7 @@ impl AuctionHouse {
|
||||
&mut self,
|
||||
economy: &mut Economy,
|
||||
me: &Player,
|
||||
bag: &mut dyn Bag,
|
||||
bag: &mut dyn Hand,
|
||||
price: &str,
|
||||
count: Option<u32>,
|
||||
hours: Option<i64>,
|
||||
@@ -534,41 +630,55 @@ impl AuctionHouse {
|
||||
self.config.max_listings
|
||||
));
|
||||
}
|
||||
let Some((item, held, plain)) = bag.held() else {
|
||||
return err("Hold the items you want to sell.".into());
|
||||
let held = match bag.held_whole() {
|
||||
None => return err("Hold the items you want to sell.".into()),
|
||||
Some(Err(why)) => return err(why),
|
||||
Some(Ok(h)) => h,
|
||||
};
|
||||
if !plain || !valid_id(&item) {
|
||||
return err(
|
||||
"The auction house takes only plain items for now (not worn, named or enchanted)."
|
||||
.into(),
|
||||
);
|
||||
if !valid_id(&held.item) {
|
||||
return err("That item can't be sold here.".into());
|
||||
}
|
||||
let count = count.unwrap_or(held);
|
||||
if count == 0 || count > held {
|
||||
return err(format!("You hold {held} {}.", item_name(&item)));
|
||||
let count = count.unwrap_or(held.count);
|
||||
if count == 0 || count > held.count {
|
||||
return err(format!(
|
||||
"You hold {} {}.",
|
||||
held.count,
|
||||
item_name(&held.item)
|
||||
));
|
||||
}
|
||||
let taken = bag.take(&item, count);
|
||||
if taken != count {
|
||||
bag.give(&item, taken);
|
||||
// The stack leaves the hand before anything is written: from here
|
||||
// on it is either listed or given back, never both.
|
||||
let Some(taken) = bag.take_held(&held, count) else {
|
||||
return err("Those items couldn't be taken.".into());
|
||||
}
|
||||
};
|
||||
self.data.next_id += 1;
|
||||
let id = self.data.next_id;
|
||||
let ends = now + hours.unwrap_or(self.config.listing_hours).max(1) * 3_600_000;
|
||||
let entry = serde_json::json!({
|
||||
"kind": "ah_list", "id": id, "seller": mine, "item": &item, "count": count,
|
||||
"price": price, "auction": hours.is_some(), "ends": ends,
|
||||
"kind": "ah_list", "id": id, "seller": mine, "item": &taken.item, "count": taken.count,
|
||||
"stack": &taken.data, "price": price, "auction": hours.is_some(), "ends": ends,
|
||||
});
|
||||
if let Err(e) = economy.record(entry) {
|
||||
bag.give(&item, taken);
|
||||
self.data.next_id -= 1;
|
||||
// Back whole; what doesn't fit (it came from the hand: nothing,
|
||||
// unless the hand filled meanwhile) waits in the mail.
|
||||
if let Some(rest) = bag.give_whole(&taken) {
|
||||
let goods = Goods {
|
||||
item: rest.item,
|
||||
count: rest.count,
|
||||
stack: Some(rest.data),
|
||||
};
|
||||
self.post(&mine, goods, "not listed");
|
||||
}
|
||||
return err(e);
|
||||
}
|
||||
let l = Listing {
|
||||
id,
|
||||
seller: mine,
|
||||
seller_name: me.name.clone(),
|
||||
item,
|
||||
count,
|
||||
item: taken.item,
|
||||
count: taken.count,
|
||||
stack: Some(taken.data),
|
||||
price,
|
||||
auction: hours.is_some(),
|
||||
bid: None,
|
||||
@@ -580,7 +690,7 @@ impl AuctionHouse {
|
||||
"Listed #{id}: {} for {} ({:.2} each), {}h.",
|
||||
Self::what(&l),
|
||||
economy.money(price),
|
||||
price as f64 / f64::from(count),
|
||||
price as f64 / f64::from(l.count.max(1)),
|
||||
self.config.listing_hours
|
||||
),
|
||||
Some(h) => format!(
|
||||
@@ -609,7 +719,7 @@ impl AuctionHouse {
|
||||
&mut self,
|
||||
economy: &mut Economy,
|
||||
me: &Player,
|
||||
bag: &mut dyn Bag,
|
||||
bag: &mut dyn Hand,
|
||||
id: u64,
|
||||
now: i64,
|
||||
) -> Vec<Out> {
|
||||
@@ -638,12 +748,12 @@ impl AuctionHouse {
|
||||
let Some(seller) = parse_uuid(&l.seller) else {
|
||||
return err("That listing is damaged.".into());
|
||||
};
|
||||
if bag.room(&l.item) < l.count {
|
||||
if !Goods::of(&l).fit(bag) {
|
||||
return err(format!("Make room for {} first.", Self::what(&l)));
|
||||
}
|
||||
let entry = serde_json::json!({
|
||||
"kind": "ah_buy", "id": id, "buyer": uuid_string(me.uuid), "seller": &l.seller,
|
||||
"item": &l.item, "count": l.count, "price": l.price,
|
||||
"item": &l.item, "count": l.count, "stack": &l.stack, "price": l.price,
|
||||
});
|
||||
if let Err(e) = economy.record(entry) {
|
||||
return err(e);
|
||||
@@ -651,12 +761,14 @@ impl AuctionHouse {
|
||||
// The listing leaves first: nothing can sell it twice.
|
||||
self.data.listings.remove(i);
|
||||
self.dirty = true;
|
||||
let given = bag.give(&l.item, l.count);
|
||||
let (given, rest) = Goods::of(&l).give(bag);
|
||||
if given == 0 {
|
||||
self.data.listings.insert(i, l);
|
||||
return err("The items couldn't be given: nothing was bought.".into());
|
||||
}
|
||||
self.post(&uuid_string(me.uuid), &l.item, l.count - given, "bought");
|
||||
if let Some(rest) = rest {
|
||||
self.post(&uuid_string(me.uuid), rest, "bought");
|
||||
}
|
||||
if let Err(e) = Self::pay_seller(economy, Ok(me.uuid), seller, l.price) {
|
||||
self.problems.push(format!("auction house sale #{id}: {e}"));
|
||||
}
|
||||
@@ -785,13 +897,13 @@ impl AuctionHouse {
|
||||
return vec![Out::Error("Someone bid on it: it runs to its end.".into())];
|
||||
}
|
||||
let l = self.data.listings.remove(i);
|
||||
self.post(&l.seller, &l.item, l.count, "withdrawn");
|
||||
self.post(&l.seller, Goods::of(&l), "withdrawn");
|
||||
vec![Out::Reply(format!("Took #{id} ({}) back.", Self::what(&l)))]
|
||||
}
|
||||
|
||||
/// Gives `uuid` their mail (one parcel, or all of it), as much as fits;
|
||||
/// the rest stays.
|
||||
pub fn claim(&mut self, uuid: u128, bag: &mut dyn Bag, only: Option<usize>) -> Vec<Out> {
|
||||
pub fn claim(&mut self, uuid: u128, bag: &mut dyn Hand, only: Option<usize>) -> Vec<Out> {
|
||||
let key = uuid_string(uuid);
|
||||
let Some(mut parcels) = self.data.mail.remove(&key) else {
|
||||
return vec![Out::Reply("Your mail is empty.".into())];
|
||||
@@ -802,9 +914,33 @@ impl AuctionHouse {
|
||||
if only.is_some_and(|o| o != i) {
|
||||
continue;
|
||||
}
|
||||
let n = p.count.min(bag.room(&p.item));
|
||||
let given = if n > 0 { bag.give(&p.item, n) } else { 0 };
|
||||
p.count -= given.min(p.count);
|
||||
let goods = Goods {
|
||||
item: p.item.clone(),
|
||||
count: p.count,
|
||||
stack: p.stack.clone(),
|
||||
};
|
||||
let given = match &goods.stack {
|
||||
// Plain: as much as there is room for.
|
||||
None => {
|
||||
let n = p.count.min(bag.room(&p.item));
|
||||
let given = if n > 0 { bag.give(&p.item, n) } else { 0 };
|
||||
p.count -= given.min(p.count);
|
||||
given
|
||||
}
|
||||
// A whole stack: once it fits whole; what didn't go stays.
|
||||
Some(_) if !goods.fit(bag) => 0,
|
||||
Some(_) => {
|
||||
let (given, rest) = goods.give(bag);
|
||||
match rest {
|
||||
None => p.count = 0,
|
||||
Some(r) => {
|
||||
p.count = r.count;
|
||||
p.stack = r.stack;
|
||||
}
|
||||
}
|
||||
given
|
||||
}
|
||||
};
|
||||
full |= p.count > 0;
|
||||
if given > 0 {
|
||||
given_all.push(format!("{given} {}", item_name(&p.item)));
|
||||
@@ -858,7 +994,7 @@ impl AuctionHouse {
|
||||
for l in ended {
|
||||
let Some(b) = l.bid.clone() else {
|
||||
let why = if l.auction { "no bids" } else { "expired" };
|
||||
self.post(&l.seller, &l.item, l.count, why);
|
||||
self.post(&l.seller, Goods::of(&l), why);
|
||||
let line = format!(
|
||||
"#{} ({}) ended with {why}: the items are in your mail (/ah claim).",
|
||||
l.id,
|
||||
@@ -872,7 +1008,7 @@ impl AuctionHouse {
|
||||
self.problems
|
||||
.push(format!("auction #{} payment: {e}", l.id));
|
||||
}
|
||||
self.post(&b.uuid, &l.item, l.count, "won");
|
||||
self.post(&b.uuid, Goods::of(&l), "won");
|
||||
self.record_sale(&l, b.amount, now);
|
||||
let line = format!(
|
||||
"You won #{} ({}) for {}: the items are in your mail (/ah claim).",
|
||||
@@ -1132,15 +1268,89 @@ mod tests {
|
||||
const NOTCH: u128 = 3;
|
||||
const T0: i64 = 1_793_577_600_000;
|
||||
|
||||
/// A player's inventory: plain stacks by id, 36 slots of 64.
|
||||
/// A player's inventory: plain stacks by id, 36 slots of 64, and whole
|
||||
/// stacks (`id|count|components`, the glue's encoding stands in), one a
|
||||
/// slot.
|
||||
#[derive(Default)]
|
||||
struct Inv {
|
||||
hand: Option<(String, u32)>,
|
||||
/// A whole stack in the hand (instead of `hand`).
|
||||
hand_whole: Option<String>,
|
||||
items: BTreeMap<String, u32>,
|
||||
wholes: Vec<String>,
|
||||
slots_free: u32,
|
||||
fail_give: bool,
|
||||
}
|
||||
|
||||
/// `id|count|components` as a `Whole`.
|
||||
fn whole(data: &str) -> Whole {
|
||||
let mut parts = data.splitn(3, '|');
|
||||
let item = parts.next().unwrap().to_owned();
|
||||
let count = parts.next().unwrap().parse().unwrap();
|
||||
Whole {
|
||||
item,
|
||||
count,
|
||||
data: data.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_count(data: &str, n: u32) -> String {
|
||||
let p: Vec<&str> = data.splitn(3, '|').collect();
|
||||
format!("{}|{n}|{}", p[0], p[2])
|
||||
}
|
||||
|
||||
fn is_plain(data: &str) -> bool {
|
||||
data.ends_with('|')
|
||||
}
|
||||
|
||||
impl Hand for Inv {
|
||||
fn held_whole(&self) -> Option<Result<Whole, String>> {
|
||||
if let Some(d) = &self.hand_whole {
|
||||
return Some(Ok(whole(d)));
|
||||
}
|
||||
self.held()
|
||||
.map(|(item, n, _)| Ok(whole(&format!("{item}|{n}|"))))
|
||||
}
|
||||
fn take_held(&mut self, held: &Whole, count: u32) -> Option<Whole> {
|
||||
if let Some(d) = self.hand_whole.clone() {
|
||||
if d != held.data || count > held.count {
|
||||
return None;
|
||||
}
|
||||
let left = held.count - count;
|
||||
self.hand_whole = (left > 0).then(|| with_count(&d, left));
|
||||
return Some(whole(&with_count(&d, count)));
|
||||
}
|
||||
let taken = self.take(&held.item, count);
|
||||
if taken != count {
|
||||
self.give(&held.item, taken);
|
||||
return None;
|
||||
}
|
||||
Some(whole(&with_count(&held.data, count)))
|
||||
}
|
||||
fn fits(&mut self, stack: &Whole) -> bool {
|
||||
if is_plain(&stack.data) {
|
||||
self.room(&stack.item) >= stack.count
|
||||
} else {
|
||||
self.slots_free > 0
|
||||
}
|
||||
}
|
||||
fn give_whole(&mut self, stack: &Whole) -> Option<Whole> {
|
||||
if self.fail_give {
|
||||
return Some(stack.clone());
|
||||
}
|
||||
if is_plain(&stack.data) {
|
||||
let n = self.give(&stack.item, stack.count);
|
||||
return (n < stack.count).then(|| whole(&with_count(&stack.data, stack.count - n)));
|
||||
}
|
||||
if self.slots_free == 0 {
|
||||
return Some(stack.clone());
|
||||
}
|
||||
self.slots_free -= 1;
|
||||
self.wholes.push(stack.data.clone());
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Bag for Inv {
|
||||
fn held(&self) -> Option<(String, u32, bool)> {
|
||||
self.hand
|
||||
@@ -1183,10 +1393,63 @@ mod tests {
|
||||
hand: Some((format!("minecraft:{item}"), n)),
|
||||
items: BTreeMap::from([(format!("minecraft:{item}"), n)]),
|
||||
slots_free: 30,
|
||||
fail_give: false,
|
||||
..Inv::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn holding_whole(data: &str) -> Inv {
|
||||
Inv {
|
||||
hand_whole: Some(data.into()),
|
||||
slots_free: 30,
|
||||
..Inv::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// An enchanted, named, worn sword (one stack).
|
||||
const SWORD: &str = "minecraft:diamond_sword|1|custom_name=Excalibur;enchantments={sharpness:5,unbreaking:3};damage=12";
|
||||
/// A shulker box with its contents.
|
||||
const SHULKER: &str = "minecraft:shulker_box|1|container=[{slot:0,id:diamond,count:64},{slot:1,id:bundle,count:1,bundle_contents=[{id:emerald,count:8}]}]";
|
||||
|
||||
/// Where the copies of `data` are: in bags, listings and mail.
|
||||
fn copies(ah: &AuctionHouse, bags: &[&Inv], data: &str) -> usize {
|
||||
let listed = ah
|
||||
.data
|
||||
.listings
|
||||
.iter()
|
||||
.filter(|l| l.stack.as_deref() == Some(data))
|
||||
.count();
|
||||
let mailed = ah
|
||||
.data
|
||||
.mail
|
||||
.values()
|
||||
.flatten()
|
||||
.filter(|p| p.stack.as_deref() == Some(data))
|
||||
.count();
|
||||
let held = bags
|
||||
.iter()
|
||||
.map(|b| {
|
||||
b.wholes.iter().filter(|w| *w == data).count()
|
||||
+ usize::from(b.hand_whole.as_deref() == Some(data))
|
||||
})
|
||||
.sum::<usize>();
|
||||
listed + mailed + held
|
||||
}
|
||||
|
||||
/// Saves everything and opens it again from disk, as a restart (or a
|
||||
/// crash right after the save) does.
|
||||
fn reopen(
|
||||
ah: &mut AuctionHouse,
|
||||
e: &mut Economy,
|
||||
dir: &std::path::Path,
|
||||
) -> (Economy, AuctionHouse) {
|
||||
ah.store(e);
|
||||
e.save().unwrap();
|
||||
let mut e = Economy::open(dir, EcoConfig::default()).unwrap();
|
||||
e.now = T0;
|
||||
let ah = AuctionHouse::open(&e, Config::default());
|
||||
(e, ah)
|
||||
}
|
||||
|
||||
fn empty() -> Inv {
|
||||
Inv {
|
||||
slots_free: 30,
|
||||
@@ -1567,4 +1830,191 @@ mod tests {
|
||||
.starts_with("#4 32 Oak Log · 16 coins (0.50 each) · Alex · 2d 0h left")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_enchanted_named_sword_comes_back_identical_after_a_purchase_an_expiry_an_auction_and_a_claim()
|
||||
{
|
||||
let (mut e, mut ah, dir) = setup("whole");
|
||||
let (alex, steve, notch) = (p(ALEX, "Alex"), p(STEVE, "Steve"), p(NOTCH, "Notch"));
|
||||
ah.online = [ALEX, STEVE, NOTCH].into();
|
||||
// Listed whole: the stack leaves the hand, the listing keeps it all.
|
||||
let mut a = holding_whole(SWORD);
|
||||
let out = run(&mut ah, &mut e, &alex, &mut a, T0, "ah sell 500");
|
||||
assert!(
|
||||
matches!(&out[0], Out::Reply(s) if s.starts_with("Listed #1: 1 diamond sword")),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_eq!(a.hand_whole, None);
|
||||
assert_eq!(ah.listing(1).unwrap().stack.as_deref(), Some(SWORD));
|
||||
// Bought: Steve gets the very stack.
|
||||
let mut s = empty();
|
||||
ah.buy(&mut e, &steve, &mut s, 1, T0 + 1);
|
||||
assert_eq!(s.wholes, [SWORD]);
|
||||
assert_eq!((e.balance(ALEX), e.balance(STEVE)), (1500, 500));
|
||||
// Steve lists it; nobody buys; a restart; it comes back by mail.
|
||||
let mut s = holding_whole(SWORD);
|
||||
run(&mut ah, &mut e, &steve, &mut s, T0, "ah sell 900");
|
||||
ah.tick(&mut e, &[STEVE], T0 + 48 * 3_600_000);
|
||||
let (mut e, mut ah) = reopen(&mut ah, &mut e, &dir);
|
||||
assert_eq!(ah.mail_of(STEVE)[0].stack.as_deref(), Some(SWORD));
|
||||
let mut s = empty();
|
||||
assert_eq!(
|
||||
ah.claim(STEVE, &mut s, None),
|
||||
[Out::Reply("From your mail: 1 diamond sword.".into())]
|
||||
);
|
||||
assert_eq!(s.wholes, [SWORD]);
|
||||
// Auctioned: Notch wins it, claims it after a restart.
|
||||
let mut s = holding_whole(SWORD);
|
||||
run(&mut ah, &mut e, &steve, &mut s, T0, "ah auction 100 1");
|
||||
ah.bid(&mut e, ¬ch, 3, None, T0);
|
||||
ah.tick(&mut e, &[STEVE, NOTCH], T0 + 3_600_000);
|
||||
let (_e, mut ah) = reopen(&mut ah, &mut e, &dir);
|
||||
let mut n = empty();
|
||||
ah.claim(NOTCH, &mut n, None);
|
||||
assert_eq!(n.wholes, [SWORD]);
|
||||
assert_eq!(copies(&ah, &[&a, &s, &n], SWORD), 1);
|
||||
// A shulker box keeps its contents (a bundle inside, with its own).
|
||||
let (mut e, mut ah, _dir) = setup("shulker");
|
||||
let mut a = holding_whole(SHULKER);
|
||||
run(&mut ah, &mut e, &alex, &mut a, T0, "ah sell 10");
|
||||
let mut s = empty();
|
||||
ah.buy(&mut e, &steve, &mut s, 1, T0);
|
||||
assert_eq!(s.wholes, [SHULKER]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part_of_a_named_stack_is_listed_and_the_rest_stays_in_the_hand() {
|
||||
let (mut e, mut ah, _dir) = setup("part");
|
||||
let pearls = "minecraft:ender_pearl|16|custom_name=Warp";
|
||||
let mut a = holding_whole(pearls);
|
||||
run(
|
||||
&mut ah,
|
||||
&mut e,
|
||||
&p(ALEX, "Alex"),
|
||||
&mut a,
|
||||
T0,
|
||||
"ah sell 60 6",
|
||||
);
|
||||
assert_eq!(
|
||||
a.hand_whole.as_deref(),
|
||||
Some("minecraft:ender_pearl|10|custom_name=Warp")
|
||||
);
|
||||
let l = ah.listing(1).unwrap();
|
||||
assert_eq!(
|
||||
(l.count, l.stack.as_deref()),
|
||||
(6, Some("minecraft:ender_pearl|6|custom_name=Warp"))
|
||||
);
|
||||
assert_eq!(
|
||||
run(
|
||||
&mut ah,
|
||||
&mut e,
|
||||
&p(ALEX, "Alex"),
|
||||
&mut a,
|
||||
T0,
|
||||
"ah sell 60 11"
|
||||
),
|
||||
[Out::Error("You hold 10 ender pearl.".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failure_or_a_crash_between_steps_never_dupes_or_loses_the_stack() {
|
||||
// The audit log can't be written: the listing isn't made and the
|
||||
// sword is back in the inventory, once.
|
||||
let dir = std::env::temp_dir().join(format!("smp-ah-crash-log-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(dir.join("audit.log")).unwrap();
|
||||
let mut e = Economy::open(&dir, EcoConfig::default()).unwrap();
|
||||
let mut ah = AuctionHouse::open(&e, Config::default());
|
||||
let mut a = holding_whole(SWORD);
|
||||
let out = run(&mut ah, &mut e, &p(ALEX, "Alex"), &mut a, T0, "ah sell 500");
|
||||
assert!(matches!(&out[0], Out::Error(_)), "{out:?}");
|
||||
assert!(ah.data.listings.is_empty() && ah.data.mail.is_empty());
|
||||
assert_eq!(
|
||||
(a.hand_whole, &a.wholes[..]),
|
||||
(None, &[SWORD.to_owned()][..])
|
||||
);
|
||||
|
||||
// Each step saved and read back (a restart or a crash after the
|
||||
// save): the sword is in exactly one place each time.
|
||||
let (mut e, mut ah, dir) = setup("crash");
|
||||
let (alex, steve) = (p(ALEX, "Alex"), p(STEVE, "Steve"));
|
||||
let mut a = holding_whole(SWORD);
|
||||
let mut s = empty();
|
||||
run(&mut ah, &mut e, &alex, &mut a, T0, "ah sell 500");
|
||||
let (mut e, mut ah) = reopen(&mut ah, &mut e, &dir);
|
||||
assert_eq!(copies(&ah, &[&a, &s], SWORD), 1, "listed");
|
||||
// A give that fails: nothing bought, nothing moved.
|
||||
let mut broken = Inv {
|
||||
slots_free: 5,
|
||||
fail_give: true,
|
||||
..Inv::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
&ah.buy(&mut e, &steve, &mut broken, 1, T0)[0],
|
||||
Out::Error(_)
|
||||
));
|
||||
assert_eq!((ah.listing(1).is_some(), e.balance(STEVE)), (true, 1000));
|
||||
// No room: refused before anything moves.
|
||||
let mut full = Inv::default();
|
||||
assert!(
|
||||
matches!(&ah.buy(&mut e, &steve, &mut full, 1, T0)[0], Out::Error(s) if s.starts_with("Make room"))
|
||||
);
|
||||
ah.buy(&mut e, &steve, &mut s, 1, T0);
|
||||
let (mut e, mut ah) = reopen(&mut ah, &mut e, &dir);
|
||||
assert_eq!(copies(&ah, &[&a, &s], SWORD), 1, "bought");
|
||||
let mut s = holding_whole(SWORD);
|
||||
run(&mut ah, &mut e, &steve, &mut s, T0, "ah sell 500");
|
||||
ah.tick(&mut e, &[STEVE], T0 + 48 * 3_600_000);
|
||||
let (mut e, mut ah) = reopen(&mut ah, &mut e, &dir);
|
||||
assert_eq!(copies(&ah, &[&a, &s], SWORD), 1, "expired to the mail");
|
||||
// A full inventory: the parcel waits, whole.
|
||||
let mut full = Inv::default();
|
||||
ah.claim(STEVE, &mut full, None);
|
||||
let (_e, mut ah) = reopen(&mut ah, &mut e, &dir);
|
||||
assert_eq!(copies(&ah, &[&a, &s, &full], SWORD), 1, "claim refused");
|
||||
ah.claim(STEVE, &mut s, None);
|
||||
assert_eq!(
|
||||
ah.claim(STEVE, &mut s, None),
|
||||
[Out::Reply("Your mail is empty.".into())]
|
||||
);
|
||||
assert_eq!(
|
||||
(copies(&ah, &[&a, &s], SWORD), &s.wholes[..]),
|
||||
(1, &[SWORD.to_owned()][..])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listings_and_mail_from_0_30_load_unchanged_and_give_plain_items() {
|
||||
let (mut e, _ah, dir) = setup("old");
|
||||
let old = serde_json::json!({
|
||||
"next_id": 7,
|
||||
"listings": [{"id": 7, "seller": uuid_string(ALEX), "seller_name": "Alex", "item": "minecraft:wheat",
|
||||
"count": 64, "price": 100, "auction": false, "created": T0, "ends": T0 + 3_600_000}],
|
||||
"mail": {uuid_string(STEVE): [{"item": "minecraft:diamond", "count": 3, "why": "won"}]},
|
||||
"notes": {}, "sales": [], "today": {"day": 0, "sales": 0, "volume": 0},
|
||||
});
|
||||
e.set_ext("auction", old.clone());
|
||||
e.save().unwrap();
|
||||
let e2 = Economy::open(&dir, EcoConfig::default()).unwrap();
|
||||
let mut ah = AuctionHouse::open(&e2, Config::default());
|
||||
assert_eq!(
|
||||
serde_json::to_value(&ah.data).unwrap(),
|
||||
old,
|
||||
"read and written back the same"
|
||||
);
|
||||
let mut e = e2;
|
||||
e.now = T0;
|
||||
let mut s = empty();
|
||||
assert_eq!(
|
||||
ah.claim(STEVE, &mut s, None),
|
||||
[Out::Reply("From your mail: 3 diamond.".into())]
|
||||
);
|
||||
ah.buy(&mut e, &p(STEVE, "Steve"), &mut s, 7, T0);
|
||||
assert_eq!(
|
||||
(s.items["minecraft:diamond"], s.items["minecraft:wheat"]),
|
||||
(3, 64)
|
||||
);
|
||||
assert!(s.wholes.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
// The SMP's screens: a scoreboard sidebar, the player's own block first (their
|
||||
// name or nickname, balance, playtime, the players on), then the three
|
||||
// richest and the server's address, which a player hides with `/sidebar off`
|
||||
// (kept in `board.json`); and the Tab list's header and footer (the server's
|
||||
// name, its TPS and the players on). Nothing happens per tick: the ranking is
|
||||
// built once for everyone when a balance changed (at most once each
|
||||
// `min_seconds`) or every `refresh_seconds`; the players' own lines are looked
|
||||
// name or nickname, balance, playtime, the players on), then the server's
|
||||
// address, which a player hides with `/sidebar off` (kept in `board.json`);
|
||||
// and the Tab list's header and footer (the server's name, its TPS and the
|
||||
// players on). Nothing happens per tick: the balances are read once for
|
||||
// everyone when one changed (at most once each `min_seconds`) or every
|
||||
// `refresh_seconds`; the players' own lines are looked
|
||||
// at on the same `refresh_seconds`, and a sidebar is sent only to the players
|
||||
// whose lines changed and to newcomers. The Tab list goes out every
|
||||
// `tab_refresh_seconds`, and to a player who just joined. No game types. Added to the game as `game::smp_board`;
|
||||
@@ -16,10 +16,6 @@ use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The most of the richest a sidebar lists: vanilla's 15 lines, less the
|
||||
/// player's four, the two gaps, the heading and the address.
|
||||
const MAX_TOP: usize = 7;
|
||||
|
||||
/// `config.json`'s `board` section.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -27,11 +23,9 @@ pub struct Config {
|
||||
/// The sidebar (each player may hide it).
|
||||
pub sidebar: bool,
|
||||
pub title: String,
|
||||
/// How many of the richest players it lists (at most 7; 0: none).
|
||||
pub top: usize,
|
||||
/// Its last line, the server's address ("": none).
|
||||
pub footer: String,
|
||||
/// The ranking is built again, and the players' own lines looked at,
|
||||
/// The balances are read again, and the players' own lines looked at,
|
||||
/// at least this often.
|
||||
pub refresh_seconds: i64,
|
||||
/// After a balance changed, at most this often.
|
||||
@@ -50,7 +44,6 @@ impl Default for Config {
|
||||
Self {
|
||||
sidebar: true,
|
||||
title: "Horizon SMP".into(),
|
||||
top: 3,
|
||||
footer: "play.playhorizon.dev".into(),
|
||||
refresh_seconds: 60,
|
||||
min_seconds: 5,
|
||||
@@ -63,19 +56,14 @@ impl Default for Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// SMP 0.13's sidebar defaults (the richest ten), moved to 0.14's when a
|
||||
/// server never changed them. True when something changed.
|
||||
/// SMP 0.13's sidebar title (`Richest players`), moved to today's when a
|
||||
/// server never changed it. True when something changed.
|
||||
pub fn migrate(config: &mut Config) -> bool {
|
||||
let mut changed = false;
|
||||
if config.title == "Richest players" {
|
||||
config.title = Config::default().title;
|
||||
changed = true;
|
||||
return true;
|
||||
}
|
||||
if config.top == 10 {
|
||||
config.top = Config::default().top;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
false
|
||||
}
|
||||
|
||||
/// `board.json`.
|
||||
@@ -95,16 +83,6 @@ pub enum Line {
|
||||
Stat { label: &'static str, value: String },
|
||||
/// An empty line.
|
||||
Gap,
|
||||
/// The heading over the richest.
|
||||
Heading,
|
||||
/// One of the richest: their rank, name and balance; `me` on the
|
||||
/// player's own line.
|
||||
Top {
|
||||
rank: usize,
|
||||
name: String,
|
||||
amount: String,
|
||||
me: bool,
|
||||
},
|
||||
/// The server's address.
|
||||
Footer(String),
|
||||
}
|
||||
@@ -131,10 +109,9 @@ pub struct Board {
|
||||
path: PathBuf,
|
||||
data: Data,
|
||||
changed: bool,
|
||||
/// Every account by balance, richest first: UUID, name, balance.
|
||||
ranked: Vec<(u128, String, i64)>,
|
||||
rank_of: HashMap<u128, usize>,
|
||||
/// When the ranking was built, and over which economy revision.
|
||||
/// Every account's balance.
|
||||
balances: HashMap<u128, i64>,
|
||||
/// When the balances were read, and at which economy revision.
|
||||
built_at: Option<i64>,
|
||||
built_revision: u64,
|
||||
/// What each player on was last sent.
|
||||
@@ -145,6 +122,8 @@ pub struct Board {
|
||||
personal_at: Option<i64>,
|
||||
tab_at: Option<i64>,
|
||||
tab_sent: HashSet<u128>,
|
||||
/// The vanished players (the glue sets it): on, but not counted online.
|
||||
pub quiet: HashSet<u128>,
|
||||
}
|
||||
|
||||
/// `1,250`, `125.4k`, `3.2M`: short enough for the sidebar's right side.
|
||||
@@ -180,8 +159,7 @@ impl Board {
|
||||
path,
|
||||
data,
|
||||
changed: false,
|
||||
ranked: Vec::new(),
|
||||
rank_of: HashMap::new(),
|
||||
balances: HashMap::new(),
|
||||
built_at: None,
|
||||
built_revision: 0,
|
||||
sent: HashMap::new(),
|
||||
@@ -189,6 +167,7 @@ impl Board {
|
||||
personal_at: None,
|
||||
tab_at: None,
|
||||
tab_sent: HashSet::new(),
|
||||
quiet: HashSet::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -200,11 +179,19 @@ impl Board {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forgets what each player was sent: everyone gets theirs again at the
|
||||
/// next update (the sidebars were taken away).
|
||||
pub fn forget(&mut self) {
|
||||
self.sent.clear();
|
||||
self.tab_sent.clear();
|
||||
self.stale = true;
|
||||
}
|
||||
|
||||
pub fn hidden(&self, uuid: u128) -> bool {
|
||||
self.data.hidden.contains(&smp_store::uuid_string(uuid))
|
||||
}
|
||||
|
||||
/// Whether the ranking should be built again: the economy changed
|
||||
/// Whether the balances should be read again: the economy changed
|
||||
/// (`revision`) and `min_seconds` passed, or `refresh_seconds` passed.
|
||||
pub fn due(&self, now: i64, revision: u64) -> bool {
|
||||
if !self.config.sidebar {
|
||||
@@ -218,27 +205,17 @@ impl Board {
|
||||
|| since >= self.config.refresh_seconds * 1000
|
||||
}
|
||||
|
||||
/// The ranking from the accounts (UUID, name, balance, any order).
|
||||
pub fn rebuild(&mut self, mut accounts: Vec<(u128, String, i64)>, now: i64, revision: u64) {
|
||||
accounts.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.1.cmp(&b.1)));
|
||||
self.rank_of = accounts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, a)| (a.0, i + 1))
|
||||
.collect();
|
||||
self.ranked = accounts;
|
||||
/// The balances from the accounts (UUID, name, balance).
|
||||
pub fn rebuild(&mut self, accounts: Vec<(u128, String, i64)>, now: i64, revision: u64) {
|
||||
self.balances = accounts.into_iter().map(|(u, _, b)| (u, b)).collect();
|
||||
self.built_at = Some(now);
|
||||
self.built_revision = revision;
|
||||
self.stale = true;
|
||||
}
|
||||
|
||||
/// `uuid`'s sidebar: their own block, the richest from the ranking, the
|
||||
/// address.
|
||||
/// `uuid`'s sidebar: their own block, then the address.
|
||||
pub fn lines(&self, uuid: u128, me: &Me, online: usize) -> Vec<Line> {
|
||||
let balance = self
|
||||
.rank_of
|
||||
.get(&uuid)
|
||||
.map_or(0, |&rank| self.ranked[rank - 1].2);
|
||||
let balance = self.balances.get(&uuid).copied().unwrap_or(0);
|
||||
let mut lines = vec![
|
||||
Line::Name(me.name.clone()),
|
||||
Line::Stat {
|
||||
@@ -254,19 +231,6 @@ impl Board {
|
||||
value: online.to_string(),
|
||||
},
|
||||
];
|
||||
let top = self.config.top.min(MAX_TOP);
|
||||
if top > 0 && !self.ranked.is_empty() {
|
||||
lines.push(Line::Gap);
|
||||
lines.push(Line::Heading);
|
||||
lines.extend(self.ranked.iter().take(top).enumerate().map(
|
||||
|(i, (u, name, balance))| Line::Top {
|
||||
rank: i + 1,
|
||||
name: name.clone(),
|
||||
amount: compact(*balance),
|
||||
me: *u == uuid,
|
||||
},
|
||||
));
|
||||
}
|
||||
if !self.config.footer.is_empty() {
|
||||
lines.push(Line::Gap);
|
||||
lines.push(Line::Footer(self.config.footer.clone()));
|
||||
@@ -297,11 +261,12 @@ impl Board {
|
||||
}
|
||||
let all = std::mem::take(&mut self.stale) || personal;
|
||||
let mut out = Vec::new();
|
||||
let online = on.iter().filter(|u| !self.quiet.contains(u)).count();
|
||||
for &uuid in on {
|
||||
if self.hidden(uuid) || (!all && self.sent.contains_key(&uuid)) {
|
||||
continue;
|
||||
}
|
||||
let lines = self.lines(uuid, &me(uuid), on.len());
|
||||
let lines = self.lines(uuid, &me(uuid), online);
|
||||
if self.sent.get(&uuid) != Some(&lines) {
|
||||
self.sent.insert(uuid, lines.clone());
|
||||
out.push((uuid, lines));
|
||||
@@ -429,7 +394,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sidebar_shows_the_player_then_the_three_richest_then_the_address() {
|
||||
fn the_sidebar_shows_the_player_then_the_address_and_no_ranking() {
|
||||
let d = dir();
|
||||
let mut b = Board::open(&d, Config::default()).unwrap();
|
||||
assert!(b.due(0, 0));
|
||||
@@ -442,12 +407,6 @@ mod tests {
|
||||
label,
|
||||
value: value.into(),
|
||||
};
|
||||
let top = |rank, name: &str, amount: &str, me| Line::Top {
|
||||
rank,
|
||||
name: name.into(),
|
||||
amount: amount.into(),
|
||||
me,
|
||||
};
|
||||
assert_eq!(
|
||||
b.lines(11, &rocky, 42),
|
||||
vec![
|
||||
@@ -456,27 +415,20 @@ mod tests {
|
||||
stat("Playtime", "2h 05m"),
|
||||
stat("Online", "42"),
|
||||
Line::Gap,
|
||||
Line::Heading,
|
||||
top(1, "P12", "1,200", false),
|
||||
top(2, "P11", "1,100", true),
|
||||
top(3, "P10", "1,000", false),
|
||||
Line::Gap,
|
||||
Line::Footer("play.playhorizon.dev".into()),
|
||||
]
|
||||
);
|
||||
// A player with no account yet; a server with no address and no top.
|
||||
// A player with no account yet; a server with no address.
|
||||
assert_eq!(b.lines(99, &rocky, 1)[1], stat("Balance", "0"));
|
||||
b.config.footer.clear();
|
||||
b.config.top = 0;
|
||||
assert_eq!(b.lines(99, &rocky, 1).len(), 4);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_old_defaults_move_to_the_new_ones_and_set_ones_stay() {
|
||||
fn the_old_title_moves_to_the_new_one_and_a_set_one_stays() {
|
||||
let mut old = Config {
|
||||
title: "Richest players".into(),
|
||||
top: 10,
|
||||
..Config::default()
|
||||
};
|
||||
assert!(migrate(&mut old));
|
||||
@@ -484,15 +436,21 @@ mod tests {
|
||||
assert!(!migrate(&mut old));
|
||||
let mut own = Config {
|
||||
title: "My server".into(),
|
||||
top: 5,
|
||||
..Config::default()
|
||||
};
|
||||
assert!(!migrate(&mut own));
|
||||
assert_eq!((own.title.as_str(), own.top), ("My server", 5));
|
||||
assert_eq!(own.title, "My server");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidebars_go_out_on_join_on_a_new_ranking_and_on_the_refresh() {
|
||||
fn an_old_config_with_a_top_still_reads() {
|
||||
let old = serde_json::json!({ "title": "Horizon SMP", "top": 3 });
|
||||
let c: Config = serde_json::from_value(old).unwrap();
|
||||
assert_eq!(c, Config::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidebars_go_out_on_join_on_a_balance_change_and_on_the_refresh() {
|
||||
let d = dir();
|
||||
let mut b = Board::open(&d, Config::default()).unwrap();
|
||||
b.rebuild(accounts(3), 0, 1);
|
||||
@@ -511,11 +469,12 @@ mod tests {
|
||||
assert!(b.due(5_000, 2));
|
||||
b.rebuild(accounts(3), 5_000, 2);
|
||||
assert!(b.updates(5_000, &[1, 2], me).is_empty(), "same lines");
|
||||
// Player 1 gets richer: everyone's top changes.
|
||||
// Player 1 gets richer: only their own sidebar changes.
|
||||
let mut a = accounts(3);
|
||||
a[0].2 = 1_000;
|
||||
b.rebuild(a, 10_000, 3);
|
||||
assert_eq!(b.updates(10_000, &[1, 2], me).len(), 2);
|
||||
let sent = b.updates(10_000, &[1, 2], me);
|
||||
assert_eq!(sent.iter().map(|s| s.0).collect::<Vec<_>>(), vec![1]);
|
||||
// A newcomer gets theirs at once, and only they are looked at.
|
||||
asked.set(0);
|
||||
assert_eq!(b.updates(11_000, &[1, 2, 3], me).len(), 1);
|
||||
@@ -529,6 +488,15 @@ mod tests {
|
||||
let sent = b.updates(60_000, &[1, 2, 3], me);
|
||||
assert_eq!(sent.iter().map(|s| s.0).collect::<Vec<_>>(), vec![2]);
|
||||
assert!(b.due(70_000, 3), "a minute passed");
|
||||
// A vanished player isn't counted, at the next refresh.
|
||||
b.quiet.insert(3);
|
||||
let sent = b.updates(120_000, &[1, 2, 3], me);
|
||||
assert_eq!(sent.len(), 3, "everyone's count changed");
|
||||
let online = Line::Stat {
|
||||
label: "Online",
|
||||
value: "2".into(),
|
||||
};
|
||||
assert!(sent[0].1.contains(&online), "{:?}", sent[0].1);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
|
||||
+255
-372
@@ -7,16 +7,16 @@
|
||||
// log refuses gives the items back. Nobody gets rich from it: buying always
|
||||
// costs more than selling (an item priced otherwise isn't bought), no chain
|
||||
// of recipes turns bought items into dearer ones (smp_recipes; such an item
|
||||
// isn't bought either), and what a player sells is capped each UTC day, in
|
||||
// coins and per item (`market.json` counts it). No game types: the glue
|
||||
// isn't bought either). No daily sale caps. No game types: the glue
|
||||
// lends the player's items as a `Bag`. Added to the game as
|
||||
// `game::smp_market`; also a module of this crate, for its tests.
|
||||
|
||||
use super::smp_economy::{Economy, MAX_AMOUNT, Out, Player, parse_amount};
|
||||
use super::smp_market_prices::{
|
||||
Book, Dynamic, MINUTE_MS, Point, Quote, Span, arrow, base_mid, one_price, to_get, to_pay,
|
||||
Book, Dynamic, MIN_FACTOR, MINUTE_MS, OLD_MIN_FACTOR, Point, Quote, Span, arrow, base_mid,
|
||||
one_price, to_get, to_pay,
|
||||
};
|
||||
use super::smp_store::{read_json, uuid_string, write_json};
|
||||
use super::smp_store::read_json;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, path::PathBuf};
|
||||
|
||||
@@ -39,12 +39,6 @@ pub struct Config {
|
||||
pub enabled: bool,
|
||||
/// By item id, `minecraft:diamond`. Items that stack to 64.
|
||||
pub items: BTreeMap<String, Price>,
|
||||
/// The most a player earns selling to the market in a UTC day (0: no
|
||||
/// limit).
|
||||
pub daily_sell_coins: i64,
|
||||
/// The most of one item a player sells to the market in a UTC day (0:
|
||||
/// no limit).
|
||||
pub daily_sell_items: u32,
|
||||
/// Prices that move with supply and demand (smp_market_prices); the
|
||||
/// item prices above are then the base ones.
|
||||
pub dynamic: Dynamic,
|
||||
@@ -119,8 +113,7 @@ pub const PRICES: &[(&str, i64, i64)] = &[
|
||||
];
|
||||
|
||||
impl Default for Config {
|
||||
/// `PRICES` (one price where the market trades both ways), and the
|
||||
/// daily limits.
|
||||
/// `PRICES` (one price where the market trades both ways).
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
@@ -137,8 +130,6 @@ impl Default for Config {
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
daily_sell_coins: 2000,
|
||||
daily_sell_items: 640,
|
||||
dynamic: Dynamic::default(),
|
||||
}
|
||||
}
|
||||
@@ -167,9 +158,20 @@ const OLD_PRICES: [(&str, i64, i64); 18] = [
|
||||
("torch", 1, 0),
|
||||
];
|
||||
|
||||
/// A config whose prices are still the old defaults, untouched: today's
|
||||
/// defaults instead. Whether it changed (the file is written again).
|
||||
/// A config whose prices, or price floor, are still the old defaults,
|
||||
/// untouched: today's defaults instead. Whether it changed (the file is
|
||||
/// written again).
|
||||
pub fn migrate(config: &mut Config) -> bool {
|
||||
// 0.33 dropped the daily sale caps: the floor (60% of the base before)
|
||||
// goes down to 20%, so selling without end pays less and less.
|
||||
let floor = (config.dynamic.min_factor - OLD_MIN_FACTOR).abs() < 1e-9;
|
||||
if floor {
|
||||
config.dynamic.min_factor = MIN_FACTOR;
|
||||
}
|
||||
migrate_prices(config) || floor
|
||||
}
|
||||
|
||||
fn migrate_prices(config: &mut Config) -> bool {
|
||||
let old: BTreeMap<String, Price> = OLD_PRICES
|
||||
.iter()
|
||||
.map(|(id, buy, sell)| {
|
||||
@@ -189,29 +191,11 @@ pub fn migrate(config: &mut Config) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// What one player sold today.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Sold {
|
||||
/// The UTC day (days since 1970) the counts are for.
|
||||
pub day: i64,
|
||||
pub coins: i64,
|
||||
pub items: BTreeMap<String, u32>,
|
||||
}
|
||||
|
||||
/// `market.json`: what each player sold today, by UUID.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Ledger {
|
||||
pub sold: BTreeMap<String, Sold>,
|
||||
}
|
||||
|
||||
/// A config's prices made safe: an amount out of range closes that side; an
|
||||
/// item traded both ways gets one price; an item a chain of recipes makes
|
||||
/// for less than it sells for is no longer bought. What changed, to log.
|
||||
pub fn validate(config: &mut Config) -> Vec<String> {
|
||||
let mut closed = Vec::new();
|
||||
config.daily_sell_coins = config.daily_sell_coins.clamp(0, MAX_AMOUNT);
|
||||
config.dynamic.validate();
|
||||
for (id, p) in config.items.iter_mut() {
|
||||
if !valid_id(id) {
|
||||
@@ -315,10 +299,8 @@ pub fn item_name(id: &str) -> String {
|
||||
|
||||
pub struct Market {
|
||||
pub config: Config,
|
||||
ledger: Ledger,
|
||||
/// `market.json`; None in tests that keep nothing.
|
||||
path: Option<PathBuf>,
|
||||
dirty: bool,
|
||||
/// The SMP data directory; None in tests that keep nothing.
|
||||
dir: Option<PathBuf>,
|
||||
/// The moving prices and their history (`market_prices.json`, written
|
||||
/// by the glue off the tick thread: `book_to_write`).
|
||||
pub book: Book,
|
||||
@@ -368,9 +350,7 @@ const BOOK_EVERY_MS: i64 = 5 * MINUTE_MS;
|
||||
|
||||
impl Market {
|
||||
/// The market of `dir` (`world/horizon-smp/`), its config made safe
|
||||
/// (`validate`), with what to log. A `market.json` that can't be read
|
||||
/// starts the day's counts from nothing (they only limit, never hold
|
||||
/// money).
|
||||
/// (`validate`), with what to log.
|
||||
pub fn open(dir: &std::path::Path, mut config: Config) -> (Self, Vec<String>) {
|
||||
let mids = |c: &Config| -> BTreeMap<String, f64> {
|
||||
c.items
|
||||
@@ -383,11 +363,6 @@ impl Market {
|
||||
.into_iter()
|
||||
.map(|l| format!("market: {l}"))
|
||||
.collect();
|
||||
let path = dir.join("market.json");
|
||||
let ledger = read_json(&path).unwrap_or_else(|e| {
|
||||
problems.push(format!("{e}: today's sale limits start again"));
|
||||
Ledger::default()
|
||||
});
|
||||
let mut book: Book = read_json(&dir.join("market_prices.json")).unwrap_or_else(|e| {
|
||||
problems.push(format!("{e}: prices start again from their base"));
|
||||
Book::default()
|
||||
@@ -401,9 +376,7 @@ impl Market {
|
||||
}
|
||||
let mut market = Self {
|
||||
config,
|
||||
ledger,
|
||||
path: Some(path),
|
||||
dirty: false,
|
||||
dir: Some(dir.to_owned()),
|
||||
book,
|
||||
book_written: 0,
|
||||
book_dirty: !rebased.is_empty(),
|
||||
@@ -419,9 +392,7 @@ impl Market {
|
||||
pub fn new(config: Config) -> Self {
|
||||
let mut m = Self {
|
||||
config,
|
||||
ledger: Ledger::default(),
|
||||
path: None,
|
||||
dirty: false,
|
||||
dir: None,
|
||||
book: Book::default(),
|
||||
book_written: 0,
|
||||
book_dirty: false,
|
||||
@@ -446,18 +417,21 @@ impl Market {
|
||||
}
|
||||
|
||||
/// How far one `id` moves the log of its factor: in a family, by value
|
||||
/// (a block of 9 moves it as 9 ingots do), so crafting can't beat it.
|
||||
/// (a block of 9 moves it as 9 ingots do), so crafting can't beat it,
|
||||
/// from its cheapest member's depth (so that every member, not only
|
||||
/// the cheapest, reaches the floor within `MAX_DEPTH` items a 1%).
|
||||
fn unit_move(&self, id: &str) -> f64 {
|
||||
let d = &self.config.dynamic;
|
||||
let mid = |id: &str| {
|
||||
let b = self.base(id);
|
||||
base_mid(b.buy, b.sell)
|
||||
};
|
||||
match self
|
||||
.family
|
||||
.get(id)
|
||||
.and_then(|f| f.iter().chain([&id.to_owned()]).min().cloned())
|
||||
{
|
||||
match self.family.get(id).and_then(|f| {
|
||||
f.iter()
|
||||
.chain([&id.to_owned()])
|
||||
.min_by(|a, b| mid(a).total_cmp(&mid(b)).then_with(|| a.cmp(b)))
|
||||
.cloned()
|
||||
}) {
|
||||
Some(first) if mid(&first) > 0.0 => {
|
||||
Book::unit_move(d, &first, mid(&first)) / mid(&first) * mid(id)
|
||||
}
|
||||
@@ -485,82 +459,6 @@ impl Market {
|
||||
self.spot(id).map_or(0.0, |q| q.mid)
|
||||
}
|
||||
|
||||
pub fn save(&mut self) -> Result<(), String> {
|
||||
if !self.dirty {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(path) = &self.path {
|
||||
write_json(path, &self.ledger)?;
|
||||
}
|
||||
self.dirty = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What `uuid` sold today (`now`: milliseconds since 1970).
|
||||
fn sold(&self, uuid: u128, now: i64) -> Sold {
|
||||
match self.ledger.sold.get(&uuid_string(uuid)) {
|
||||
Some(s) if s.day == now.div_euclid(DAY_MS) => s.clone(),
|
||||
_ => Sold::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The coins `uuid` may still earn selling today (None: no limit).
|
||||
pub fn coins_left(&self, uuid: u128, now: i64) -> Option<i64> {
|
||||
let cap = self.config.daily_sell_coins;
|
||||
(cap > 0).then(|| (cap - self.sold(uuid, now).coins).max(0))
|
||||
}
|
||||
|
||||
/// How many of `id` `uuid` may still sell today (None: no limit).
|
||||
pub fn items_left(&self, uuid: u128, now: i64, id: &str) -> Option<u32> {
|
||||
let cap = self.config.daily_sell_items;
|
||||
(cap > 0)
|
||||
.then(|| cap.saturating_sub(self.sold(uuid, now).items.get(id).copied().unwrap_or(0)))
|
||||
}
|
||||
|
||||
/// Whether `uuid` may be paid `amount` by another player now (`/pay`):
|
||||
/// money received counts toward the same daily limit as selling to the
|
||||
/// market, so selling on alts and paying it all to a main doesn't get
|
||||
/// past it. Err: what they may still receive today.
|
||||
pub fn may_receive(&self, uuid: u128, amount: i64, now: i64) -> Result<(), i64> {
|
||||
match self.coins_left(uuid, now) {
|
||||
Some(left) if amount > left => Err(left),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts `coins` paid to `uuid` (`/pay`) against today's limit.
|
||||
pub fn count_received(&mut self, uuid: u128, now: i64, coins: i64) {
|
||||
let day = now.div_euclid(DAY_MS);
|
||||
let s = self.ledger.sold.entry(uuid_string(uuid)).or_default();
|
||||
if s.day != day {
|
||||
*s = Sold {
|
||||
day,
|
||||
..Sold::default()
|
||||
};
|
||||
}
|
||||
s.coins = s.coins.saturating_add(coins.max(0));
|
||||
self.ledger.sold.retain(|_, s| s.day == day);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// Counts a sale against today's limits.
|
||||
fn count_sale(&mut self, uuid: u128, now: i64, id: &str, n: u32, coins: i64) {
|
||||
let day = now.div_euclid(DAY_MS);
|
||||
let s = self.ledger.sold.entry(uuid_string(uuid)).or_default();
|
||||
if s.day != day {
|
||||
*s = Sold {
|
||||
day,
|
||||
..Sold::default()
|
||||
};
|
||||
}
|
||||
s.coins = s.coins.saturating_add(coins);
|
||||
let c = s.items.entry(id.to_owned()).or_default();
|
||||
*c = c.saturating_add(n);
|
||||
// Yesterday's counts go.
|
||||
self.ledger.sold.retain(|_, s| s.day == day);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// The price of `id` now (nothing on either side when it isn't
|
||||
/// traded): the base one moved by supply and demand.
|
||||
pub fn price(&self, id: &str) -> Price {
|
||||
@@ -642,7 +540,7 @@ impl Market {
|
||||
if !self.book_dirty || (!force && now - self.book_written < BOOK_EVERY_MS) {
|
||||
return None;
|
||||
}
|
||||
let path = self.path.as_ref()?.with_file_name("market_prices.json");
|
||||
let path = self.dir.as_ref()?.join("market_prices.json");
|
||||
self.book_dirty = false;
|
||||
self.book_written = now;
|
||||
Some((path, self.book.clone()))
|
||||
@@ -696,26 +594,6 @@ impl Market {
|
||||
}
|
||||
}
|
||||
|
||||
/// Today's limits for `uuid`, as a line (None when there are none).
|
||||
pub fn limits_line(&self, economy: &Economy, uuid: u128) -> Option<String> {
|
||||
let now = economy.now;
|
||||
let coins = self.coins_left(uuid, now).map(|left| {
|
||||
format!(
|
||||
"{} left of your {} a day",
|
||||
economy.money(left),
|
||||
economy.money(self.config.daily_sell_coins)
|
||||
)
|
||||
});
|
||||
let items = (self.config.daily_sell_items > 0).then(|| {
|
||||
format!(
|
||||
"at most {} of each item a day",
|
||||
self.config.daily_sell_items
|
||||
)
|
||||
});
|
||||
let parts: Vec<String> = coins.into_iter().chain(items).collect();
|
||||
(!parts.is_empty()).then(|| format!("Selling today: {}.", parts.join(", ")))
|
||||
}
|
||||
|
||||
/// Runs `/worth`, `/sell` or `/buy`; None for another command. `trades`
|
||||
/// is false for a player in creative or spectator mode.
|
||||
pub fn command(
|
||||
@@ -735,7 +613,7 @@ impl Market {
|
||||
return Some(vec![Out::Error("The market is closed.".into())]);
|
||||
}
|
||||
if name == "worth" {
|
||||
return Some(self.worth(economy, me, bag, args));
|
||||
return Some(self.worth(economy, bag, args));
|
||||
}
|
||||
if !trades {
|
||||
return Some(vec![Out::Error(
|
||||
@@ -748,7 +626,7 @@ impl Market {
|
||||
})
|
||||
}
|
||||
|
||||
fn worth(&self, economy: &Economy, me: &Player, bag: &mut dyn Bag, args: &[&str]) -> Vec<Out> {
|
||||
fn worth(&self, economy: &Economy, bag: &mut dyn Bag, args: &[&str]) -> Vec<Out> {
|
||||
let id = match args {
|
||||
[] => match bag.held() {
|
||||
Some((id, ..)) => id,
|
||||
@@ -781,19 +659,10 @@ impl Market {
|
||||
id.trim_start_matches("minecraft:")
|
||||
)));
|
||||
}
|
||||
if p.sell > 0 {
|
||||
if let Some(left) = self.items_left(me.uuid, economy.now, &id) {
|
||||
out.push(Out::Reply(format!(
|
||||
"You may sell {left} more {name} today."
|
||||
)));
|
||||
}
|
||||
out.extend(self.limits_line(economy, me.uuid).map(Out::Reply));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Sells what `args` names (`hand [n]`, `all`, `<item> [n]`), within
|
||||
/// today's limits.
|
||||
/// Sells what `args` names (`hand [n]`, `all`, `<item> [n]`).
|
||||
pub fn sell(
|
||||
&mut self,
|
||||
economy: &mut Economy,
|
||||
@@ -846,39 +715,15 @@ impl Market {
|
||||
continue;
|
||||
}
|
||||
let price = self.each(&id).max(0.01);
|
||||
// Never more than the account can be paid for at once, nor
|
||||
// than today's limits leave.
|
||||
let now = economy.now;
|
||||
let mut cap = (MAX_AMOUNT as f64 / price).min(f64::from(u32::MAX)) as u32;
|
||||
if let Some(left) = self.items_left(me.uuid, now, &id) {
|
||||
cap = cap.min(left);
|
||||
}
|
||||
// What they bought here lately can't come back yet.
|
||||
let back = self.recently_bought(me.uuid, &id, now);
|
||||
if let Some(left) = self.coins_left(me.uuid, now) {
|
||||
cap = cap.min((left as f64 / price).min(f64::from(u32::MAX)) as u32);
|
||||
}
|
||||
// Never more than the account can be paid for at once.
|
||||
let cap = (MAX_AMOUNT as f64 / price).min(f64::from(u32::MAX)) as u32;
|
||||
let carried = bag.count(&id).min(at_most);
|
||||
if carried == 0 {
|
||||
out.push(Out::Error(format!("You have no plain {name}.")));
|
||||
continue;
|
||||
}
|
||||
let limited = carried.min(cap);
|
||||
if limited == 0 {
|
||||
out.push(Out::Error(format!(
|
||||
"You reached today's selling limit for {name}; it starts again at midnight UTC."
|
||||
)));
|
||||
continue;
|
||||
}
|
||||
let have = limited.min(carried.saturating_sub(back));
|
||||
if have == 0 {
|
||||
let hours = self.config.dynamic.round_trip_hours;
|
||||
out.push(Out::Error(format!(
|
||||
"You bought {back} {name} from the market in the last {hours} h: those can't be sold back yet."
|
||||
)));
|
||||
continue;
|
||||
}
|
||||
let taken = bag.take(&id, have);
|
||||
let taken = bag.take(&id, limited);
|
||||
if taken == 0 {
|
||||
continue;
|
||||
}
|
||||
@@ -905,7 +750,6 @@ impl Market {
|
||||
let kind = format!("sell {taken} {id}");
|
||||
match economy.adjust(&kind, me.uuid, pay, "") {
|
||||
Ok(_) => {
|
||||
self.count_sale(me.uuid, now, &id, taken, pay);
|
||||
self.moved(&id, taken, false);
|
||||
total = total.saturating_add(pay);
|
||||
let each = each_money(economy, pay as f64 / f64::from(taken));
|
||||
@@ -913,19 +757,6 @@ impl Market {
|
||||
"Sold {taken} {name} at {each} each: {}.",
|
||||
economy.money(pay)
|
||||
)));
|
||||
if taken < limited {
|
||||
let hours = self.config.dynamic.round_trip_hours;
|
||||
out.push(Out::Reply(format!(
|
||||
"{} {name} kept: bought from the market in the last {hours} h.",
|
||||
limited - taken
|
||||
)));
|
||||
}
|
||||
if limited < carried {
|
||||
out.push(Out::Reply(format!(
|
||||
"{} {name} kept: today's selling limit.",
|
||||
carried - limited
|
||||
)));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let back = bag.give(&id, taken);
|
||||
@@ -1008,9 +839,6 @@ impl Market {
|
||||
};
|
||||
if given > 0 {
|
||||
self.moved(&id, given, true);
|
||||
let now = economy.now;
|
||||
self.book.bought(&uuid_string(me.uuid), &id, given, now);
|
||||
self.book_dirty = true;
|
||||
}
|
||||
let each = each_money(economy, paid as f64 / f64::from(given.max(1)));
|
||||
let mut out = vec![Out::Reply(format!(
|
||||
@@ -1069,15 +897,6 @@ impl Market {
|
||||
);
|
||||
self.book_dirty = true;
|
||||
}
|
||||
|
||||
/// How many of `id` `uuid` bought within the round-trip window.
|
||||
pub fn recently_bought(&self, uuid: u128, id: &str, now: i64) -> u32 {
|
||||
if !self.config.dynamic.enabled {
|
||||
return 0;
|
||||
}
|
||||
self.book
|
||||
.recently_bought(&self.config.dynamic, &uuid_string(uuid), id, now)
|
||||
}
|
||||
}
|
||||
|
||||
/// `minecraft:iron_ingot` as `Iron Ingot`.
|
||||
@@ -1207,6 +1026,7 @@ impl WebView {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::smp_economy::Config as EconomyConfig;
|
||||
use super::super::smp_store::{uuid_string, write_json};
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
@@ -1279,31 +1099,58 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn money_received_by_pay_counts_toward_the_daily_selling_limit() {
|
||||
let config = Config {
|
||||
daily_sell_coins: 250,
|
||||
..Config::default()
|
||||
fn legacy_daily_caps_do_not_limit_sales_or_payments() {
|
||||
// Existing configs and today's saved ledger may still contain the
|
||||
// removed daily caps and receipts from before the upgrade.
|
||||
let config: Config = serde_json::from_value(serde_json::json!({
|
||||
"daily_sell_coins": 2000,
|
||||
"daily_sell_items": 640,
|
||||
"dynamic": {"enabled": false}
|
||||
}))
|
||||
.unwrap();
|
||||
let (mut e, mut m, me, dir) = setup_with("no-coin-cap", config);
|
||||
e.now = 5 * 86_400_000;
|
||||
fs::write(
|
||||
dir.join("market.json"),
|
||||
serde_json::json!({
|
||||
"sold": { uuid_string(ALEX): {
|
||||
"day": 5, "coins": 2000, "items": {"minecraft:diamond": 640}
|
||||
}}
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, problems) = Market::open(&dir, m.config.clone());
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
m = loaded;
|
||||
let mut b = bag(&[("minecraft:diamond", 700)], 0);
|
||||
m.command(&mut e, &me, true, &mut b, "sell diamond")
|
||||
.unwrap();
|
||||
assert_eq!(b.count("minecraft:diamond"), 0);
|
||||
assert_eq!(e.balance(ALEX), 140_000);
|
||||
let earned = e.balance(ALEX);
|
||||
e.seen(2, "Steve");
|
||||
e.adjust("test", 2, 10_000, "").unwrap();
|
||||
let sender = Player {
|
||||
uuid: 2,
|
||||
name: "Steve".into(),
|
||||
level: 0,
|
||||
};
|
||||
let (_e, mut m, _me, _dir) = setup_with("received", config);
|
||||
let now = 1_793_577_600_000;
|
||||
// An alt pays the main 200: fine, and it counts.
|
||||
assert_eq!(m.may_receive(ALEX, 200, now), Ok(()));
|
||||
m.count_received(ALEX, now, 200);
|
||||
assert_eq!(m.coins_left(ALEX, now), Some(50));
|
||||
// A second alt's 100 is refused: 50 left today, for sales or payments.
|
||||
assert_eq!(m.may_receive(ALEX, 100, now), Err(50));
|
||||
assert_eq!(m.may_receive(ALEX, 50, now), Ok(()));
|
||||
// The next day the limit is whole again.
|
||||
assert_eq!(m.may_receive(ALEX, 250, now + DAY_MS), Ok(()));
|
||||
// No limit configured: anything goes.
|
||||
let (_e, m, _me, _dir) = setup_with(
|
||||
"unlimited",
|
||||
Config {
|
||||
daily_sell_coins: 0,
|
||||
..Config::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(m.may_receive(ALEX, 1_000_000, now), Ok(()));
|
||||
// Repeated receipts over the former cap, on the same day as sales.
|
||||
for _ in 0..2 {
|
||||
let out = e.command(&sender, &[], "pay Alex 3000").unwrap();
|
||||
assert!(matches!(&out[0], Out::Reply(_)), "{out:?}");
|
||||
}
|
||||
assert_eq!(e.balance(ALEX), earned + 6000);
|
||||
assert_eq!(e.balance(2), 4000);
|
||||
// Reopening on the same day ignores the old full daily ledger too.
|
||||
let (mut m, problems) = Market::open(&dir, m.config.clone());
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
b.items.insert("minecraft:diamond".into(), 700);
|
||||
m.command(&mut e, &me, true, &mut b, "sell all").unwrap();
|
||||
assert_eq!(b.count("minecraft:diamond"), 0);
|
||||
assert_eq!(e.balance(ALEX), 286_000);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1433,95 +1280,6 @@ mod tests {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sales_stop_at_the_daily_limits_and_start_again_the_next_day() {
|
||||
let config = Config {
|
||||
daily_sell_coins: 250,
|
||||
daily_sell_items: 30,
|
||||
..fixed()
|
||||
};
|
||||
let (mut e, mut m, me, dir) = setup_with("limits", config);
|
||||
e.now = 5 * DAY_MS + 1000;
|
||||
let mut b = bag(&[("minecraft:diamond", 5), ("minecraft:wheat", 64)], 0);
|
||||
// 250 coins a day: one diamond (200), then 25 wheat (50 coins), the
|
||||
// coins' limit before the 30 items of one kind.
|
||||
let out = m
|
||||
.command(&mut e, &me, true, &mut b, "sell diamond")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out[0],
|
||||
Out::Reply("Sold 1 diamond at 200 coins each: 200 coins.".into()),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
out[1],
|
||||
Out::Reply("4 diamond kept: today's selling limit.".into())
|
||||
);
|
||||
let out = m
|
||||
.command(&mut e, &me, true, &mut b, "sell wheat 5")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out[0],
|
||||
Out::Reply("Sold 5 wheat at 2 coins each: 10 coins.".into()),
|
||||
"{out:?}"
|
||||
);
|
||||
// 40 coins left, but 25 more wheat would pass the 30 items.
|
||||
e.adjust("test", ALEX, 0, "").ok();
|
||||
m.config.daily_sell_coins = 1000;
|
||||
let out = m.command(&mut e, &me, true, &mut b, "sell wheat").unwrap();
|
||||
assert_eq!(
|
||||
out[0],
|
||||
Out::Reply("Sold 25 wheat at 2 coins each: 50 coins.".into()),
|
||||
"{out:?}"
|
||||
);
|
||||
m.config.daily_sell_coins = 250;
|
||||
let out = m.command(&mut e, &me, true, &mut b, "sell wheat").unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
[Out::Error(
|
||||
"You reached today's selling limit for wheat; it starts again at midnight UTC."
|
||||
.into()
|
||||
)]
|
||||
);
|
||||
let worth = m
|
||||
.command(&mut e, &me, true, &mut b, "worth diamond")
|
||||
.unwrap();
|
||||
assert!(
|
||||
worth.contains(&Out::Reply("You may sell 29 more diamond today.".into())),
|
||||
"{worth:?}"
|
||||
);
|
||||
assert!(
|
||||
worth.contains(&Out::Reply(
|
||||
"Selling today: 0 coins left of your 250 coins a day, at most 30 of each item a day.".into()
|
||||
)),
|
||||
"{worth:?}"
|
||||
);
|
||||
assert_eq!((e.balance(ALEX), b.items["minecraft:diamond"]), (260, 4));
|
||||
// Kept across a restart, in market.json.
|
||||
m.path = Some(dir.join("market.json"));
|
||||
m.dirty = true;
|
||||
m.save().unwrap();
|
||||
let (mut m, _) = Market::open(&dir, m.config.clone());
|
||||
let out = m
|
||||
.command(&mut e, &me, true, &mut b, "sell diamond")
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(&out[0], Out::Error(s) if s.contains("limit")),
|
||||
"{out:?}"
|
||||
);
|
||||
// A new UTC day.
|
||||
e.now = 6 * DAY_MS;
|
||||
let out = m
|
||||
.command(&mut e, &me, true, &mut b, "sell diamond")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
out[0],
|
||||
Out::Reply("Sold 1 diamond at 200 coins each: 200 coins.".into()),
|
||||
"{out:?}"
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prices_that_would_make_money_are_closed() {
|
||||
let mut config = fixed();
|
||||
@@ -1556,13 +1314,7 @@ mod tests {
|
||||
);
|
||||
assert!(config.items.keys().all(|k| valid_id(k)));
|
||||
// At the largest price: one at a time, without overflow.
|
||||
let (mut e, mut m, me, dir) = setup_with(
|
||||
"validate",
|
||||
Config {
|
||||
daily_sell_coins: 0,
|
||||
..config
|
||||
},
|
||||
);
|
||||
let (mut e, mut m, me, dir) = setup_with("validate", Config { ..config });
|
||||
let mut b = bag(&[("minecraft:rotten_flesh", 64)], 0);
|
||||
let out = m
|
||||
.command(&mut e, &me, true, &mut b, "sell rotten_flesh")
|
||||
@@ -1630,15 +1382,9 @@ mod tests {
|
||||
assert_eq!(edited, before);
|
||||
}
|
||||
|
||||
/// Moving prices, validated, with no daily caps and no round-trip
|
||||
/// window: only the prices themselves stand between a trader and money.
|
||||
/// Moving prices, validated: only the prices stand between a trader and money.
|
||||
fn moving() -> Config {
|
||||
let mut c = Config {
|
||||
daily_sell_coins: 0,
|
||||
daily_sell_items: 0,
|
||||
..Config::default()
|
||||
};
|
||||
c.dynamic.round_trip_hours = 0;
|
||||
let mut c = Config::default();
|
||||
let _ = validate(&mut c);
|
||||
c
|
||||
}
|
||||
@@ -1797,11 +1543,157 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_prices_pay_the_whole_receipt_and_keep_bought_items_from_coming_back() {
|
||||
fn the_old_price_floor_becomes_the_new_one_and_an_edited_one_stays() {
|
||||
let mut c = Config::default();
|
||||
let _ = validate(&mut c);
|
||||
c.dynamic.min_factor = 0.6;
|
||||
assert!(migrate(&mut c));
|
||||
assert_eq!(c.dynamic.min_factor, 0.2);
|
||||
assert!(!migrate(&mut c), "once");
|
||||
c.dynamic.min_factor = 0.5;
|
||||
assert!(!migrate(&mut c));
|
||||
assert_eq!(c.dynamic.min_factor, 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selling_ten_thousand_of_any_item_drives_its_price_to_the_floor() {
|
||||
// No daily cap: an AFK farm sells 10,000 of one item, a minute at a
|
||||
// time as the band allows. The price falls to a fifth of its base
|
||||
// and the farm gets far less than 10,000 at the base price.
|
||||
let c = moving();
|
||||
let ids: Vec<String> = c
|
||||
.items
|
||||
.iter()
|
||||
.filter(|(_, p)| p.sell > 0)
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
assert!(ids.len() > 30, "{ids:?}");
|
||||
let t0 = 1_800_000_000_000i64;
|
||||
for id in ids {
|
||||
let (mut e, _, me, dir) = setup(&format!("farm-{id}"));
|
||||
let mut m = Market::new(c.clone());
|
||||
let base = m.base(&id).sell;
|
||||
// Room for what a minute's band keeps.
|
||||
let mut b = bag(&[(id.as_str(), 10_000)], u32::MAX);
|
||||
let mut now = t0;
|
||||
e.now = now;
|
||||
m.tick(now);
|
||||
let mut minutes = 0;
|
||||
while b.count(&id) > 0 && minutes < 600 {
|
||||
m.sell(&mut e, &me, &mut b, &[&id]);
|
||||
minutes += 1;
|
||||
now += MINUTE_MS;
|
||||
e.now = now;
|
||||
m.tick(now);
|
||||
}
|
||||
// A few left worth less than a coin at the floor: kept.
|
||||
assert!(b.count(&id) < 5, "{id}: {} unsold", b.count(&id));
|
||||
let got = e.balance(ALEX);
|
||||
let at_base = 10_000 * base;
|
||||
assert!(
|
||||
got * 2 < at_base,
|
||||
"{id}: 10,000 sold for {got}, {at_base} at the base price"
|
||||
);
|
||||
let f = m.book.factor(&id);
|
||||
assert!(f < c.dynamic.min_factor * 1.01, "{id}: factor {f}");
|
||||
if std::env::var_os("SMP_MARKET_REPORT").is_some() {
|
||||
eprintln!("{id}: 10,000 sold for {got} ({at_base} at the base) in {minutes} min");
|
||||
}
|
||||
// The price comes back once the selling stops: in a day, to
|
||||
// within 10% of the base.
|
||||
m.tick(now + 24 * 60 * MINUTE_MS);
|
||||
assert!(m.book.factor(&id) > 0.9, "{id}: {}", m.book.factor(&id));
|
||||
fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buying_and_selling_straight_back_never_earns_without_a_resale_delay() {
|
||||
// Every item the market trades both ways, bought and sold back the
|
||||
// same moment, from a fresh price, from the floor (after another
|
||||
// player's dump) and from the top (after another's pumping): the
|
||||
// trader never ends with more coins than they started with.
|
||||
let c = moving();
|
||||
let ids: Vec<String> = c
|
||||
.items
|
||||
.iter()
|
||||
.filter(|(_, p)| p.buy > 0 && p.sell > 0)
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
assert!(ids.len() > 10, "{ids:?}");
|
||||
let t0 = 1_800_000_000_000i64;
|
||||
let mut cases = 0;
|
||||
let mut worst = (0i64, String::new());
|
||||
for id in &ids {
|
||||
for start in ["fresh", "floor", "top"] {
|
||||
for n in [1u32, 7, 64, 640, 64 * 36] {
|
||||
let (mut e, _, me, dir) = setup("loop");
|
||||
let mut m = Market::new(c.clone());
|
||||
let mut now = t0;
|
||||
m.tick(now);
|
||||
// Others push the price to a bound, a minute at a time.
|
||||
let to_bound = |m: &mut Market, now: &mut i64, buy: bool| {
|
||||
for _ in 0..200 {
|
||||
m.moved(id, 100_000, buy);
|
||||
*now += MINUTE_MS;
|
||||
m.tick(*now);
|
||||
}
|
||||
};
|
||||
match start {
|
||||
"floor" => to_bound(&mut m, &mut now, false),
|
||||
"top" => to_bound(&mut m, &mut now, true),
|
||||
_ => {}
|
||||
}
|
||||
match start {
|
||||
"floor" => assert!(m.book.factor(id) < c.dynamic.min_factor * 1.01),
|
||||
"top" => assert!(m.book.factor(id) > c.dynamic.max_factor * 0.99),
|
||||
_ => {}
|
||||
}
|
||||
e.now = now;
|
||||
e.adjust("test_funds", me.uuid, 100_000_000, "").unwrap();
|
||||
let start_coins = e.balance(me.uuid);
|
||||
let mut b = bag(&[], u32::MAX);
|
||||
m.buy(&mut e, &me, &mut b, &[id, &n.to_string()]);
|
||||
let bought = b.count(id);
|
||||
assert!(bought > 0, "{id} {start} {n}: nothing bought");
|
||||
// At once; what the minute's band keeps, in the next
|
||||
// minutes (the price only drifts back down meanwhile).
|
||||
m.sell(&mut e, &me, &mut b, &[id]);
|
||||
let mut minutes = 0;
|
||||
while b.count(id) >= 5 && minutes < 2_000 {
|
||||
now += MINUTE_MS;
|
||||
e.now = now;
|
||||
m.tick(now);
|
||||
m.sell(&mut e, &me, &mut b, &[id]);
|
||||
minutes += 1;
|
||||
}
|
||||
assert!(b.count(id) < 5, "{id} {start} {n}: {} kept", b.count(id));
|
||||
let end = e.balance(me.uuid);
|
||||
assert!(
|
||||
end <= start_coins,
|
||||
"{id} from {start}: bought {bought} and sold back, {} coins earned",
|
||||
end - start_coins
|
||||
);
|
||||
worst = worst.max((end - start_coins, format!("{id} {start} {n}")));
|
||||
cases += 1;
|
||||
fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(cases, ids.len() * 15);
|
||||
if std::env::var_os("SMP_MARKET_REPORT").is_some() {
|
||||
eprintln!("round trips: {cases}, best for the trader {worst:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_prices_allow_immediate_resale_with_legacy_purchase_history() {
|
||||
let c: Config = serde_json::from_value(serde_json::json!({
|
||||
"dynamic": {"round_trip_hours": 24}
|
||||
}))
|
||||
.unwrap();
|
||||
let (mut e, _, me, dir) = setup("dyn");
|
||||
let mut m = Market::new(c);
|
||||
let (mut m, problems) = Market::open(&dir, c);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let t0 = 1_800_000_000_000i64;
|
||||
e.now = t0;
|
||||
e.adjust("test_funds", me.uuid, 10_000, "").unwrap();
|
||||
@@ -1819,31 +1711,22 @@ mod tests {
|
||||
Out::Reply("Bought 10 iron ingot at 15 coins each: 151 coins.".into())
|
||||
);
|
||||
assert_eq!(e.balance(me.uuid), 10_000 + 595 - 151);
|
||||
// Old files can still contain a purchase within the former 24 h
|
||||
// window. Preserve the moving price history and ignore that receipt.
|
||||
let mut old_book = serde_json::to_value(&m.book).unwrap();
|
||||
old_book["bought"] = serde_json::json!({
|
||||
uuid_string(me.uuid): [["minecraft:iron_ingot", t0, 10]]
|
||||
});
|
||||
write_json(&dir.join("market_prices.json"), &old_book).unwrap();
|
||||
let (mut m, problems) = Market::open(&dir, m.config.clone());
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let out = m.sell(&mut e, &me, &mut b, &["iron_ingot"]);
|
||||
assert_eq!(
|
||||
out[0],
|
||||
Out::Error("You bought 10 iron ingot from the market in the last 24 h: those can't be sold back yet.".into())
|
||||
);
|
||||
// Five more found in a mine: those sell, the bought ones stay.
|
||||
b.items.insert("minecraft:iron_ingot".into(), 15);
|
||||
let out = m.sell(&mut e, &me, &mut b, &["iron_ingot"]);
|
||||
assert!(
|
||||
matches!(&out[0], Out::Reply(r) if r.starts_with("Sold 5 iron ingot")),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
out[1],
|
||||
Out::Reply("10 iron ingot kept: bought from the market in the last 24 h.".into())
|
||||
);
|
||||
b.items.insert("minecraft:iron_ingot".into(), 10);
|
||||
// A day later they may.
|
||||
e.now = t0 + 25 * 3_600_000;
|
||||
m.tick(e.now);
|
||||
let out = m.sell(&mut e, &me, &mut b, &["iron_ingot"]);
|
||||
assert!(
|
||||
matches!(&out[0], Out::Reply(r) if r.starts_with("Sold 10 iron ingot")),
|
||||
"{out:?}"
|
||||
Out::Reply("Sold 10 iron ingot at 15 coins each: 150 coins.".into())
|
||||
);
|
||||
assert_eq!(b.count("minecraft:iron_ingot"), 0);
|
||||
assert_eq!(e.balance(me.uuid), 10_000 + 595 - 151 + 150);
|
||||
fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,17 @@ pub const HOUR_MS: i64 = 3_600_000;
|
||||
pub const MINUTES: usize = 1440;
|
||||
pub const HOURS: usize = 720;
|
||||
|
||||
/// The least share of its base price the market pays (since 0.33, with no
|
||||
/// daily sale caps: an item sold without end falls to it and stays there
|
||||
/// while the selling goes on).
|
||||
pub const MIN_FACTOR: f64 = 0.2;
|
||||
/// The default floor before 0.33: a config that still has it gets
|
||||
/// `MIN_FACTOR` (`smp_market::migrate`).
|
||||
pub const OLD_MIN_FACTOR: f64 = 0.6;
|
||||
/// The most items that move a price 1% (unless `depth` says otherwise): the
|
||||
/// cheap items farms make reach the floor within 10,000 sold.
|
||||
pub const MAX_DEPTH: f64 = 50.0;
|
||||
|
||||
/// `config.json`'s `market.dynamic`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
@@ -43,9 +54,6 @@ pub struct Dynamic {
|
||||
pub max_player_impact_percent: f64,
|
||||
/// How far the price may move within one minute (either way).
|
||||
pub max_minute_move_percent: f64,
|
||||
/// What a player bought from the market can't be sold back to it for
|
||||
/// this long (that many of that item).
|
||||
pub round_trip_hours: i64,
|
||||
/// Items that move the price 1%, by item (else from its price: dear
|
||||
/// items move faster).
|
||||
pub depth: BTreeMap<String, f64>,
|
||||
@@ -58,13 +66,12 @@ impl Default for Dynamic {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
min_factor: 0.6,
|
||||
min_factor: MIN_FACTOR,
|
||||
max_factor: 1.6,
|
||||
half_life_hours: 6.0,
|
||||
max_trade_impact_percent: 2.0,
|
||||
max_player_impact_percent: 2.0,
|
||||
max_minute_move_percent: 5.0,
|
||||
round_trip_hours: 24,
|
||||
depth: BTreeMap::new(),
|
||||
news_percent: 30.0,
|
||||
news_min_volume: 64,
|
||||
@@ -98,7 +105,6 @@ impl Dynamic {
|
||||
50.0,
|
||||
d.max_minute_move_percent,
|
||||
);
|
||||
self.round_trip_hours = self.round_trip_hours.clamp(0, 24 * 30);
|
||||
self.depth.retain(|_, v| v.is_finite() && *v > 0.0);
|
||||
}
|
||||
}
|
||||
@@ -175,9 +181,6 @@ pub struct Book {
|
||||
pub minute: i64,
|
||||
/// The UTC day the last summary was for.
|
||||
pub summary_day: i64,
|
||||
/// What each player bought (item, when, how many), for the round-trip
|
||||
/// rule.
|
||||
pub bought: BTreeMap<String, Vec<(String, i64, u32)>>,
|
||||
/// The last daily summary's lines (for the web page and Kira).
|
||||
pub last_summary: Vec<String>,
|
||||
/// The base price each item's history is quoted in (since 0.29).
|
||||
@@ -262,7 +265,7 @@ impl Book {
|
||||
.depth
|
||||
.get(id)
|
||||
.copied()
|
||||
.unwrap_or_else(|| (400.0 / mid.max(0.01)).clamp(2.0, 400.0))
|
||||
.unwrap_or_else(|| (400.0 / mid.max(0.01)).clamp(2.0, MAX_DEPTH))
|
||||
}
|
||||
|
||||
/// How far one of `id` (based at `mid`) moves the log of its factor.
|
||||
@@ -448,34 +451,9 @@ impl Book {
|
||||
// Items no longer traded go.
|
||||
self.items.retain(|id, _| mids.contains_key(id));
|
||||
self.minute = minute;
|
||||
// Purchases past the round-trip window go.
|
||||
let since = now - config.round_trip_hours * HOUR_MS;
|
||||
for v in self.bought.values_mut() {
|
||||
v.retain(|(_, t, _)| *t > since);
|
||||
}
|
||||
self.bought.retain(|_, v| !v.is_empty());
|
||||
true
|
||||
}
|
||||
|
||||
/// `uuid` bought `n` of `id` at `now`.
|
||||
pub fn bought(&mut self, uuid: &str, id: &str, n: u32, now: i64) {
|
||||
self.bought
|
||||
.entry(uuid.to_owned())
|
||||
.or_default()
|
||||
.push((id.to_owned(), now, n));
|
||||
}
|
||||
|
||||
/// How many of `id` `uuid` bought within the round-trip window.
|
||||
pub fn recently_bought(&self, config: &Dynamic, uuid: &str, id: &str, now: i64) -> u32 {
|
||||
let since = now - config.round_trip_hours * HOUR_MS;
|
||||
self.bought.get(uuid).map_or(0, |v| {
|
||||
v.iter()
|
||||
.filter(|(i, t, _)| i == id && *t > since)
|
||||
.map(|e| e.2)
|
||||
.sum()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn history(&self, id: &str, span: Span) -> &[Point] {
|
||||
match self.items.get(id) {
|
||||
Some(t) => match span {
|
||||
@@ -667,10 +645,10 @@ mod tests {
|
||||
assert!((b.factor(D) - (-0.005f64).exp()).abs() < 1e-12, "at once");
|
||||
assert_eq!(deal(&mut b, 1, true), (-250, 1));
|
||||
assert!((b.factor(D) - 1.0).abs() < 1e-12, "and back");
|
||||
// Wheat is deep: 64 move it far less than one diamond.
|
||||
// Wheat is deep: a whole stack moves it under 1.5%.
|
||||
let w = Book::unit_move(&c, "minecraft:wheat", 2.0);
|
||||
b.trade(&c, "minecraft:wheat", &[], 2.0, w, 64, false);
|
||||
assert!(1.0 - b.factor("minecraft:wheat") < 0.004);
|
||||
assert!(1.0 - b.factor("minecraft:wheat") < 0.015);
|
||||
// Its family moves with it.
|
||||
let fam = vec!["minecraft:hay_block".to_string()];
|
||||
b.trade(&c, "minecraft:wheat", &fam, 2.0, w, 64, true);
|
||||
@@ -843,20 +821,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_round_trip_window_and_one_price() {
|
||||
let c = Dynamic::default();
|
||||
let mut b = book();
|
||||
b.bought("u", "minecraft:diamond", 5, T0);
|
||||
assert_eq!(
|
||||
b.recently_bought(&c, "u", "minecraft:diamond", T0 + HOUR_MS),
|
||||
5
|
||||
);
|
||||
b.tick(&c, &mids(), T0 + 25 * HOUR_MS);
|
||||
assert_eq!(
|
||||
b.recently_bought(&c, "u", "minecraft:diamond", T0 + 25 * HOUR_MS),
|
||||
0
|
||||
);
|
||||
assert!(b.bought.is_empty());
|
||||
fn one_price_and_whole_coin_rounding() {
|
||||
// One price from the old two: their geometric mean, whole.
|
||||
assert_eq!(one_price(400, 100), 200);
|
||||
assert_eq!(one_price(30, 8), 15);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -98,6 +98,9 @@ pub struct Presence {
|
||||
/// Seconds each player was active today (UTC day), toward the reward;
|
||||
/// not kept over a restart.
|
||||
played_today: HashMap<u128, (String, i64)>,
|
||||
/// The vanished players (the glue sets it): their first join and AFK
|
||||
/// are told to them only, never announced.
|
||||
pub quiet: HashSet<u128>,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
@@ -123,6 +126,7 @@ impl Presence {
|
||||
afk: HashSet::new(),
|
||||
recent: HashMap::new(),
|
||||
played_today: HashMap::new(),
|
||||
quiet: HashSet::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -165,7 +169,7 @@ impl Presence {
|
||||
if self.data.known.insert(key.clone()) {
|
||||
self.dirty = true;
|
||||
let fill = |l: &str| l.replace("{player}", &p.name);
|
||||
if !self.config.first_join.is_empty() {
|
||||
if !self.config.first_join.is_empty() && !self.quiet.contains(&p.uuid) {
|
||||
out.push(Out::All(fill(&self.config.first_join)));
|
||||
}
|
||||
out.extend(
|
||||
@@ -235,7 +239,7 @@ impl Presence {
|
||||
|
||||
fn away(&mut self, uuid: u128, name: &str, acts: &mut Vec<Act>) -> Out {
|
||||
acts.push(Act::Sleep(uuid, true));
|
||||
if self.config.afk_announce {
|
||||
if self.config.afk_announce && !self.quiet.contains(&uuid) {
|
||||
Out::All(format!("{name} is AFK."))
|
||||
} else {
|
||||
Out::Tell(
|
||||
@@ -247,7 +251,7 @@ impl Presence {
|
||||
|
||||
fn back(&mut self, uuid: u128, name: &str, acts: &mut Vec<Act>) -> Vec<Out> {
|
||||
acts.push(Act::Sleep(uuid, false));
|
||||
vec![if self.config.afk_announce {
|
||||
vec![if self.config.afk_announce && !self.quiet.contains(&uuid) {
|
||||
Out::All(format!("{name} is back."))
|
||||
} else {
|
||||
Out::Tell(uuid, "You are back.".into())
|
||||
@@ -331,6 +335,30 @@ mod tests {
|
||||
(Presence::open(&dir, Config::default(), known).unwrap(), dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vanished_player_is_never_announced() {
|
||||
let (mut p, _dir) = open(vec![]);
|
||||
p.config.afk_announce = true;
|
||||
p.quiet.insert(A);
|
||||
let (out, _) = p.tick(&[seen(A, 0.0)], "2026-10-31", 0, &[]);
|
||||
assert!(
|
||||
!out.iter().any(|o| matches!(o, Out::All(_))),
|
||||
"no first join: {out:?}"
|
||||
);
|
||||
let afk = p.config.afk_minutes * 60_000;
|
||||
let (out, acts) = p.tick(&[seen(A, 0.0)], "2026-10-31", afk, &[]);
|
||||
assert!(
|
||||
matches!(&out[..], [Out::Tell(A, _)]),
|
||||
"AFK told to them only: {out:?}"
|
||||
);
|
||||
assert!(acts.contains(&Act::Sleep(A, true)));
|
||||
let (out, _) = p.tick(&[seen(A, 5.0)], "2026-10-31", afk + 1_000, &[]);
|
||||
assert!(
|
||||
matches!(&out[..], [Out::Tell(A, _)]),
|
||||
"back told to them only: {out:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_join_is_welcomed_once_and_known_players_are_not() {
|
||||
let (mut p, dir) = open(vec![B]);
|
||||
|
||||
@@ -447,7 +447,7 @@ mod tests {
|
||||
assert!(recipes.len() > 1000, "{} recipes", recipes.len());
|
||||
let config = Config::default();
|
||||
assert_eq!(loops(&config.items, &recipes), []);
|
||||
// Nor once prices have moved as far as they may (0.6 to 1.6 times
|
||||
// Nor once prices have moved as far as they may (0.2 to 1.6 times
|
||||
// their base): an item sold at the top while what makes it is
|
||||
// bought at the bottom, unless both share one price (a family).
|
||||
let families = super::super::smp_market::families(&config.items);
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
// categories; a category's page its items, with what the market asks and
|
||||
// pays (in its name). A click buys one, a shift-click a stack of 64; a click on a stack in
|
||||
// your own inventory sells it; "Sell all" sells everything the market buys.
|
||||
// Buying and selling go through the market's own rules (its prices, today's
|
||||
// limits, items first then money, logged). This file only lays the pages out
|
||||
// Buying and selling go through the market's own rules (its prices,
|
||||
// items first then money, logged). This file only lays the pages out
|
||||
// and says what a click means; the glue opens the menu and moves the items.
|
||||
// No game types. Added to the game as `game::smp_shop`; also a module of this
|
||||
// crate, for its tests.
|
||||
@@ -26,7 +26,6 @@ const HELP: usize = 46;
|
||||
const PREV: usize = 47;
|
||||
const BALANCE: usize = 48;
|
||||
const SELL_ALL: usize = 49;
|
||||
const LIMITS: usize = 50;
|
||||
const NEXT: usize = 51;
|
||||
const CLOSE: usize = 53;
|
||||
/// Where the first page puts the categories: the middle of rows 2 to 4.
|
||||
@@ -183,7 +182,6 @@ pub enum Cell {
|
||||
Next,
|
||||
Balance,
|
||||
SellAll,
|
||||
Limits,
|
||||
Help,
|
||||
Close,
|
||||
}
|
||||
@@ -254,7 +252,6 @@ impl Shop {
|
||||
cells[HELP] = Cell::Help;
|
||||
cells[BALANCE] = Cell::Balance;
|
||||
cells[SELL_ALL] = Cell::SellAll;
|
||||
cells[LIMITS] = Cell::Limits;
|
||||
cells[CLOSE] = Cell::Close;
|
||||
match page {
|
||||
Page::Main => {
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
// The SMP's emergency switches: an operator of level 3 turns parts of the SMP
|
||||
// off (`/smp off [part] [reason]`) and on again (`/smp on [part]`) while the
|
||||
// server runs, kept in `switches.json` so a restart keeps them off. A part
|
||||
// that is off takes no command and no menu click, and its timed work (daily
|
||||
// rewards, auctions ending, the lottery's draw) waits; nothing held is lost: it goes on when the part is on
|
||||
// again. `/smp off` alone turns off every part but land protection, which an
|
||||
// operator turns off by name (`/smp off claims`). No game types. Added to the
|
||||
// game as `game::smp_switch`; also a module of this crate, for its tests.
|
||||
|
||||
use super::smp_economy::{Out, Player};
|
||||
use super::smp_store;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The operator level that turns parts off and on.
|
||||
pub const LEVEL: u8 = 3;
|
||||
|
||||
pub const COMMANDS: [&str; 1] = ["smp"];
|
||||
|
||||
/// A part of the SMP that can be turned off.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Part {
|
||||
/// Balances, `/pay`, `/eco` and the daily reward.
|
||||
Economy,
|
||||
/// `/worth`, `/sell`, `/buy`, `/shop`, `/market`.
|
||||
Market,
|
||||
/// `/ah`.
|
||||
Auction,
|
||||
/// `/trade`.
|
||||
Trades,
|
||||
/// `/coinflip`, `/lottery`, `/casino`.
|
||||
Gambling,
|
||||
/// Spawn, homes, warps, `/tpa`, `/back`.
|
||||
Places,
|
||||
/// Land protection and `/claim`.
|
||||
Claims,
|
||||
/// The sidebar and the Tab list's header and footer.
|
||||
Board,
|
||||
/// Welcomes, AFK and the commands' rate limit.
|
||||
Presence,
|
||||
/// Nicknames.
|
||||
Nicks,
|
||||
/// `/invsee`, `/endersee`.
|
||||
Invsee,
|
||||
}
|
||||
|
||||
impl Part {
|
||||
pub const ALL: [Part; 11] = [
|
||||
Part::Economy,
|
||||
Part::Market,
|
||||
Part::Auction,
|
||||
Part::Trades,
|
||||
Part::Gambling,
|
||||
Part::Places,
|
||||
Part::Claims,
|
||||
Part::Board,
|
||||
Part::Presence,
|
||||
Part::Nicks,
|
||||
Part::Invsee,
|
||||
];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Part::Economy => "economy",
|
||||
Part::Market => "market",
|
||||
Part::Auction => "auction",
|
||||
Part::Trades => "trades",
|
||||
Part::Gambling => "gambling",
|
||||
Part::Places => "places",
|
||||
Part::Claims => "claims",
|
||||
Part::Board => "board",
|
||||
Part::Presence => "presence",
|
||||
Part::Nicks => "nicks",
|
||||
Part::Invsee => "invsee",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn named(name: &str) -> Option<Part> {
|
||||
Part::ALL
|
||||
.into_iter()
|
||||
.find(|p| p.name().eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The part a command belongs to (its first word); None for `/smp` and
|
||||
/// what isn't the SMP's.
|
||||
pub fn of_command(word: &str) -> Option<Part> {
|
||||
Some(match word {
|
||||
"balance" | "bal" | "pay" | "baltop" | "eco" | "money" => Part::Economy,
|
||||
"worth" | "sell" | "buy" | "shop" | "market" => Part::Market,
|
||||
"ah" => Part::Auction,
|
||||
"trade" => Part::Trades,
|
||||
"coinflip" | "lottery" | "casino" => Part::Gambling,
|
||||
"claim" | "unclaim" | "claims" | "trust" | "untrust" => Part::Claims,
|
||||
"sidebar" => Part::Board,
|
||||
"afk" => Part::Presence,
|
||||
"nick" | "realname" => Part::Nicks,
|
||||
"invsee" | "endersee" => Part::Invsee,
|
||||
"spawn" | "setspawn" | "home" | "sethome" | "delhome" | "homes" | "warp" | "warps"
|
||||
| "setwarp" | "delwarp" | "tpa" | "tpaccept" | "tpdeny" | "rules" | "back"
|
||||
| "playtime" | "rtp" | "wild" => Part::Places,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Why and by whom a part is off.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Off {
|
||||
pub by: String,
|
||||
/// When (ms).
|
||||
pub at: i64,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// `switches.json`: the parts that are off, by name.
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Data {
|
||||
off: BTreeMap<String, Off>,
|
||||
}
|
||||
|
||||
pub struct Switches {
|
||||
path: PathBuf,
|
||||
data: Data,
|
||||
changed: bool,
|
||||
}
|
||||
|
||||
/// What a `/smp` command changed, for the glue to carry out.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Changed {
|
||||
pub off: Vec<Part>,
|
||||
pub on: Vec<Part>,
|
||||
}
|
||||
|
||||
impl Switches {
|
||||
/// `switches.json` in `dir`. A file that can't be read turns nothing off
|
||||
/// (and is logged by the caller): the switches are for emergencies, not a
|
||||
/// reason for the SMP to stop.
|
||||
pub fn open(dir: &Path) -> (Self, Option<String>) {
|
||||
let path = dir.join("switches.json");
|
||||
let (data, problem) = match smp_store::read_json(&path) {
|
||||
Ok(d) => (d, None),
|
||||
Err(e) => (Data::default(), Some(e)),
|
||||
};
|
||||
let mut s = Self {
|
||||
path,
|
||||
data,
|
||||
changed: false,
|
||||
};
|
||||
// Names of parts this version doesn't know are dropped.
|
||||
let before = s.data.off.len();
|
||||
s.data.off.retain(|name, _| Part::named(name).is_some());
|
||||
s.changed = s.data.off.len() != before;
|
||||
(s, problem)
|
||||
}
|
||||
|
||||
pub fn save(&mut self) -> Result<(), String> {
|
||||
if self.changed {
|
||||
smp_store::write_json(&self.path, &self.data)?;
|
||||
self.changed = false;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn on(&self, part: Part) -> bool {
|
||||
!self.data.off.contains_key(part.name())
|
||||
}
|
||||
|
||||
/// Why a part is off, as the operator said.
|
||||
pub fn why(&self, part: Part) -> Option<&str> {
|
||||
self.data.off.get(part.name()).map(|o| o.reason.as_str())
|
||||
}
|
||||
|
||||
/// `/smp`, `/smp status`, `/smp off [part|all] [reason]`,
|
||||
/// `/smp on [part|all]`: the answer and what changed. None for another
|
||||
/// command.
|
||||
pub fn command(&mut self, me: &Player, now: i64, line: &str) -> Option<(Vec<Out>, Changed)> {
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
if words.first() != Some(&"smp") {
|
||||
return None;
|
||||
}
|
||||
let none = Changed::default();
|
||||
if me.level < LEVEL {
|
||||
return Some((
|
||||
vec![Out::Error(
|
||||
"Only operators turn the SMP's parts off and on.".into(),
|
||||
)],
|
||||
none,
|
||||
));
|
||||
}
|
||||
let usage = || {
|
||||
Out::Error(format!(
|
||||
"Usage: /smp status, /smp off [part|all] [reason], /smp on [part|all]. Parts: {}.",
|
||||
Part::ALL.map(Part::name).join(", ")
|
||||
))
|
||||
};
|
||||
let (turn_off, rest) = match words[1..] {
|
||||
[] | ["status"] => return Some((self.status(), none)),
|
||||
["off", ref rest @ ..] => (true, rest),
|
||||
["on", ref rest @ ..] => (false, rest),
|
||||
_ => return Some((vec![usage()], none)),
|
||||
};
|
||||
// The part, or every one: `all`, or none named.
|
||||
let (parts, reason): (Vec<Part>, &[&str]) = match rest.first() {
|
||||
None => (everything(turn_off), &[]),
|
||||
Some(w) if w.eq_ignore_ascii_case("all") => (everything(turn_off), &rest[1..]),
|
||||
Some(w) => match Part::named(w) {
|
||||
Some(p) => (vec![p], &rest[1..]),
|
||||
// `/smp off <reason>` turns off everything (but claims).
|
||||
None if turn_off => (everything(true), rest),
|
||||
None => return Some((vec![usage()], none)),
|
||||
},
|
||||
};
|
||||
let mut changed = Changed::default();
|
||||
for p in parts {
|
||||
if turn_off && self.on(p) {
|
||||
let off = Off {
|
||||
by: me.name.clone(),
|
||||
at: now,
|
||||
reason: reason.join(" "),
|
||||
};
|
||||
self.data.off.insert(p.name().into(), off);
|
||||
changed.off.push(p);
|
||||
} else if !turn_off && self.data.off.remove(p.name()).is_some() {
|
||||
changed.on.push(p);
|
||||
}
|
||||
}
|
||||
self.changed |= !changed.off.is_empty() || !changed.on.is_empty();
|
||||
let names = |ps: &[Part]| ps.iter().map(|p| p.name()).collect::<Vec<_>>().join(", ");
|
||||
let out = match (turn_off, changed.off.is_empty() && changed.on.is_empty()) {
|
||||
(true, true) => vec![Out::Reply("Already off.".into())],
|
||||
(false, true) => vec![Out::Reply("Already on.".into())],
|
||||
(true, false) => {
|
||||
let why = if reason.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" ({})", reason.join(" "))
|
||||
};
|
||||
let mut out = vec![Out::Reply(format!(
|
||||
"Turned off: {}{why}. /smp on turns them on again.",
|
||||
names(&changed.off)
|
||||
))];
|
||||
if !self.on(Part::Claims) || changed.off.contains(&Part::Claims) {
|
||||
out.push(Out::Reply(
|
||||
"Land is not protected while claims are off.".into(),
|
||||
));
|
||||
} else {
|
||||
out.push(Out::Reply(
|
||||
"Land protection stays on (/smp off claims turns it off too).".into(),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
(false, false) => vec![Out::Reply(format!(
|
||||
"Turned on again: {}.",
|
||||
names(&changed.on)
|
||||
))],
|
||||
};
|
||||
Some((out, changed))
|
||||
}
|
||||
|
||||
/// What is off, by whom, since when and why.
|
||||
pub fn status(&self) -> Vec<Out> {
|
||||
if self.data.off.is_empty() {
|
||||
return vec![Out::Reply("Every part of the SMP is on.".into())];
|
||||
}
|
||||
let mut out = vec![Out::Reply(format!(
|
||||
"Off: {} of {} parts.",
|
||||
self.data.off.len(),
|
||||
Part::ALL.len()
|
||||
))];
|
||||
for (name, off) in &self.data.off {
|
||||
let when = utc_minute(off.at);
|
||||
let why = if off.reason.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(": {}", off.reason)
|
||||
};
|
||||
out.push(Out::Reply(format!(
|
||||
"- {name}, by {} at {when} UTC{why}",
|
||||
off.by
|
||||
)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer to a command of a part that is off.
|
||||
pub fn refusal(part: Part) -> Out {
|
||||
Out::Error(format!(
|
||||
"{} is turned off for now by the server's staff.",
|
||||
match part {
|
||||
Part::Economy => "The economy",
|
||||
Part::Market => "The market",
|
||||
Part::Auction => "The auction house",
|
||||
Part::Trades => "Trading",
|
||||
Part::Gambling => "Gambling",
|
||||
Part::Places => "Teleporting",
|
||||
Part::Claims => "Claiming",
|
||||
Part::Board => "The sidebar",
|
||||
Part::Presence => "AFK",
|
||||
Part::Nicks => "Nicknames",
|
||||
Part::Invsee => "Inventory viewing",
|
||||
}
|
||||
))
|
||||
}
|
||||
|
||||
/// Every part, but land protection when turning off.
|
||||
fn everything(turn_off: bool) -> Vec<Part> {
|
||||
Part::ALL
|
||||
.into_iter()
|
||||
.filter(|&p| !turn_off || p != Part::Claims)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `2026-11-02 14:05` from ms since the epoch (UTC).
|
||||
fn utc_minute(ms: i64) -> String {
|
||||
let secs = ms.div_euclid(1000);
|
||||
let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
|
||||
// Howard Hinnant's civil_from_days.
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||
format!(
|
||||
"{y:04}-{m:02}-{d:02} {:02}:{:02}",
|
||||
rem / 3600,
|
||||
rem % 3600 / 60
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
fn dir() -> PathBuf {
|
||||
static N: AtomicU32 = AtomicU32::new(0);
|
||||
let n = N.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!("smp-switch-{}-{n}", std::process::id()))
|
||||
}
|
||||
fn op() -> Player {
|
||||
Player {
|
||||
uuid: 1,
|
||||
name: "luzW".into(),
|
||||
level: 3,
|
||||
}
|
||||
}
|
||||
fn texts(out: &[Out]) -> String {
|
||||
out.iter()
|
||||
.map(|o| match o {
|
||||
Out::Reply(s) | Out::Error(s) | Out::Tell(_, s) | Out::All(s) => s.as_str(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_command_of_the_smp_belongs_to_a_part() {
|
||||
// The glue's own (its `COMMANDS`), then each part's.
|
||||
let glue = [
|
||||
"balance", "bal", "pay", "baltop", "eco", "money", "worth", "sell", "buy", "shop",
|
||||
"market", "trade", "coinflip", "lottery", "ah", "casino",
|
||||
];
|
||||
let parts = [
|
||||
&super::super::smp_places::COMMANDS[..],
|
||||
&super::super::smp_claims::COMMANDS,
|
||||
&super::super::smp_board::COMMANDS,
|
||||
&super::super::smp_presence::COMMANDS,
|
||||
&super::super::smp_nick::COMMANDS,
|
||||
&super::super::smp_invsee::COMMANDS,
|
||||
];
|
||||
for word in glue.into_iter().chain(parts.into_iter().flatten().copied()) {
|
||||
assert!(Part::of_command(word).is_some(), "{word}");
|
||||
}
|
||||
assert_eq!(
|
||||
Part::of_command("smp"),
|
||||
None,
|
||||
"the switch itself is never off"
|
||||
);
|
||||
assert_eq!(
|
||||
Part::of_command("tp"),
|
||||
None,
|
||||
"vanilla's commands are not the SMP's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_alone_turns_off_everything_but_claims_and_survives_a_restart() {
|
||||
let d = dir();
|
||||
let (mut s, problem) = Switches::open(&d);
|
||||
assert!(problem.is_none());
|
||||
let (out, changed) = s
|
||||
.command(&op(), 1_762_092_300_000, "smp off market exploit")
|
||||
.unwrap();
|
||||
assert_eq!(changed.off, vec![Part::Market], "a named part alone");
|
||||
assert!(
|
||||
texts(&out).contains("Turned off: market (exploit)"),
|
||||
"{}",
|
||||
texts(&out)
|
||||
);
|
||||
let (out, changed) = s
|
||||
.command(&op(), 1_762_092_300_000, "smp off duping bug")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
changed.off.len(),
|
||||
Part::ALL.len() - 2,
|
||||
"all but claims and the market already off"
|
||||
);
|
||||
assert!(!changed.off.contains(&Part::Claims));
|
||||
assert!(
|
||||
texts(&out).contains("Land protection stays on"),
|
||||
"{}",
|
||||
texts(&out)
|
||||
);
|
||||
assert!(s.on(Part::Claims) && !s.on(Part::Economy) && !s.on(Part::Invsee));
|
||||
s.save().unwrap();
|
||||
let (s, _) = Switches::open(&d);
|
||||
assert!(!s.on(Part::Market) && !s.on(Part::Gambling) && s.on(Part::Claims));
|
||||
let status = texts(&s.status());
|
||||
assert!(
|
||||
status.contains("- market, by luzW at 2025-11-02 14:05 UTC: exploit"),
|
||||
"{status}"
|
||||
);
|
||||
assert!(
|
||||
status.contains("- economy, by luzW at 2025-11-02 14:05 UTC: duping bug"),
|
||||
"{status}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claims_go_off_only_by_name_and_on_with_the_rest() {
|
||||
let d = dir();
|
||||
let (mut s, _) = Switches::open(&d);
|
||||
s.command(&op(), 0, "smp off all");
|
||||
assert!(s.on(Part::Claims));
|
||||
let (out, changed) = s.command(&op(), 0, "smp off claims grief").unwrap();
|
||||
assert_eq!(changed.off, vec![Part::Claims]);
|
||||
assert!(
|
||||
texts(&out).contains("Land is not protected"),
|
||||
"{}",
|
||||
texts(&out)
|
||||
);
|
||||
let (_, changed) = s.command(&op(), 0, "smp on").unwrap();
|
||||
assert_eq!(changed.on.len(), Part::ALL.len());
|
||||
assert!(Part::ALL.iter().all(|&p| s.on(p)));
|
||||
let (out, changed) = s.command(&op(), 0, "smp on market").unwrap();
|
||||
assert_eq!(changed, Changed::default());
|
||||
assert_eq!(texts(&out), "Already on.");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn players_below_level_three_change_nothing() {
|
||||
let d = dir();
|
||||
let (mut s, _) = Switches::open(&d);
|
||||
let player = Player {
|
||||
uuid: 2,
|
||||
name: "Steve".into(),
|
||||
level: 2,
|
||||
};
|
||||
let (out, changed) = s.command(&player, 0, "smp off").unwrap();
|
||||
assert_eq!(changed, Changed::default());
|
||||
assert!(matches!(&out[0], Out::Error(_)));
|
||||
assert!(Part::ALL.iter().all(|&p| s.on(p)));
|
||||
assert!(s.command(&player, 0, "balance").is_none());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_file_turns_nothing_off_and_is_reported() {
|
||||
let d = dir();
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
std::fs::write(d.join("switches.json"), "{ not json").unwrap();
|
||||
let (s, problem) = Switches::open(&d);
|
||||
assert!(problem.is_some());
|
||||
assert!(Part::ALL.iter().all(|&p| s.on(p)));
|
||||
// A part this version doesn't know is dropped.
|
||||
std::fs::write(
|
||||
d.join("switches.json"),
|
||||
r#"{"off": {"rockets": {}, "market": {"by": "x"}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (s, _) = Switches::open(&d);
|
||||
assert!(!s.on(Part::Market));
|
||||
assert_eq!(s.data.off.len(), 1);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// `/vanish` for operators: a vanished operator is out of the other players'
|
||||
// Tab list and world (whatever their game mode), and nobody reads them
|
||||
// joining or leaving; operators of `LEVEL` or more still see them. The game
|
||||
// hides them (`native_hide_player`); this keeps who is vanished in
|
||||
// `vanish.json`, so it lasts over a restart and a relog, and says what the
|
||||
// game must be told. The vanished operator reads a subtitle the whole time.
|
||||
// No game types. Added to the game as `game::smp_vanish`; also a module of
|
||||
// this crate, for its tests.
|
||||
|
||||
use super::smp_economy::{Out, Player};
|
||||
use super::smp_store;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Who may vanish, and who still sees a vanished player.
|
||||
pub const LEVEL: u8 = 3;
|
||||
|
||||
pub const COMMANDS: [&str; 1] = ["vanish"];
|
||||
|
||||
/// The subtitle a vanished operator reads the whole time.
|
||||
pub const SUBTITLE: &str = "Vanished: only operators see you";
|
||||
|
||||
/// `vanish.json`: the vanished players by UUID, with the name last seen.
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct Data {
|
||||
vanished: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
pub struct Vanish {
|
||||
path: PathBuf,
|
||||
data: Data,
|
||||
changed: bool,
|
||||
/// What the game was told this run (hidden or not), by UUID: a player
|
||||
/// whose entry differs from `data` is told again.
|
||||
told: HashMap<u128, bool>,
|
||||
}
|
||||
|
||||
impl Vanish {
|
||||
/// `vanish.json` in `dir`; an error when it exists but can't be read.
|
||||
pub fn open(dir: &Path) -> Result<Self, String> {
|
||||
let path = dir.join("vanish.json");
|
||||
let data = smp_store::read_json(&path)?;
|
||||
Ok(Self {
|
||||
path,
|
||||
data,
|
||||
changed: false,
|
||||
told: HashMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn save(&mut self) -> Result<(), String> {
|
||||
if self.changed {
|
||||
smp_store::write_json(&self.path, &self.data)?;
|
||||
self.changed = false;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is(&self, uuid: u128) -> bool {
|
||||
self.data
|
||||
.vanished
|
||||
.contains_key(&smp_store::uuid_string(uuid))
|
||||
}
|
||||
|
||||
/// The vanished players, by UUID.
|
||||
pub fn quiet(&self) -> HashSet<u128> {
|
||||
self.data
|
||||
.vanished
|
||||
.keys()
|
||||
.filter_map(|k| smp_store::parse_uuid(k))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a player of `level` sees the player `uuid`.
|
||||
pub fn sees(&self, level: u8, uuid: u128) -> bool {
|
||||
level >= LEVEL || !self.is(uuid)
|
||||
}
|
||||
|
||||
/// What the game must be told now: (UUID, hidden) for each vanished
|
||||
/// player not yet hidden this run, and each one shown again.
|
||||
pub fn changes(&mut self) -> Vec<(u128, bool)> {
|
||||
let mut out = Vec::new();
|
||||
for key in self.data.vanished.keys() {
|
||||
if let Some(u) = smp_store::parse_uuid(key)
|
||||
&& self.told.get(&u) != Some(&true)
|
||||
{
|
||||
out.push((u, true));
|
||||
}
|
||||
}
|
||||
for (&u, &hidden) in &self.told {
|
||||
if hidden && !self.is(u) {
|
||||
out.push((u, false));
|
||||
}
|
||||
}
|
||||
for &(u, hidden) in &out {
|
||||
self.told.insert(u, hidden);
|
||||
}
|
||||
self.told.retain(|_, hidden| *hidden);
|
||||
out
|
||||
}
|
||||
|
||||
/// `/vanish` (toggles), `/vanish list`: the answer, and the lines for the
|
||||
/// other operators on (`ops`). None for another command.
|
||||
pub fn command(&mut self, me: &Player, ops: &[u128], line: &str) -> Option<Vec<Out>> {
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
if words.first() != Some(&"vanish") {
|
||||
return None;
|
||||
}
|
||||
if me.level < LEVEL {
|
||||
return Some(vec![Out::Error("Only operators can vanish.".into())]);
|
||||
}
|
||||
let key = smp_store::uuid_string(me.uuid);
|
||||
match words[1..] {
|
||||
[] => {}
|
||||
["list"] => {
|
||||
if self.data.vanished.is_empty() {
|
||||
return Some(vec![Out::Reply("Nobody is vanished.".into())]);
|
||||
}
|
||||
let names: Vec<&str> = self.data.vanished.values().map(String::as_str).collect();
|
||||
return Some(vec![Out::Reply(format!("Vanished: {}.", names.join(", ")))]);
|
||||
}
|
||||
_ => return Some(vec![Out::Error("Usage: /vanish, /vanish list".into())]),
|
||||
}
|
||||
self.changed = true;
|
||||
let (reply, staff) = if self.data.vanished.remove(&key).is_some() {
|
||||
(
|
||||
"You are visible again.",
|
||||
format!("[Staff] {} is visible again.", me.name),
|
||||
)
|
||||
} else {
|
||||
self.data.vanished.insert(key, me.name.clone());
|
||||
(
|
||||
"You vanished: other players can't see you, in the Tab list or the world; operators still can.",
|
||||
format!("[Staff] {} vanished.", me.name),
|
||||
)
|
||||
};
|
||||
let mut out = vec![Out::Reply(reply.into())];
|
||||
out.extend(
|
||||
ops.iter()
|
||||
.filter(|&&u| u != me.uuid)
|
||||
.map(|&u| Out::Tell(u, staff.clone())),
|
||||
);
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
fn dir() -> PathBuf {
|
||||
static N: AtomicU32 = AtomicU32::new(0);
|
||||
let n = N.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!("smp-vanish-{}-{n}", std::process::id()))
|
||||
}
|
||||
fn player(uuid: u128, level: u8) -> Player {
|
||||
Player {
|
||||
uuid,
|
||||
name: format!("P{uuid}"),
|
||||
level,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_operator_vanishes_and_comes_back_and_the_game_is_told_once_each() {
|
||||
let d = dir();
|
||||
let mut v = Vanish::open(&d).unwrap();
|
||||
let out = v.command(&player(1, 3), &[1, 2], "vanish").unwrap();
|
||||
assert!(
|
||||
matches!(&out[0], Out::Reply(s) if s.starts_with("You vanished")),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
out[1],
|
||||
Out::Tell(2, "[Staff] P1 vanished.".into()),
|
||||
"the other operators are told"
|
||||
);
|
||||
assert!(v.is(1));
|
||||
assert!(
|
||||
!v.sees(0, 1) && !v.sees(2, 1),
|
||||
"players below level 3 don't see them"
|
||||
);
|
||||
assert!(v.sees(3, 1) && v.sees(4, 1), "operators do");
|
||||
assert!(v.sees(0, 2), "nobody else is hidden");
|
||||
assert_eq!(v.changes(), vec![(1, true)]);
|
||||
assert!(v.changes().is_empty(), "told once");
|
||||
v.command(&player(1, 4), &[], "vanish").unwrap();
|
||||
assert!(!v.is(1));
|
||||
assert_eq!(v.changes(), vec![(1, false)]);
|
||||
assert!(v.changes().is_empty());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vanish_lasts_over_a_restart_and_the_game_is_told_again() {
|
||||
let d = dir();
|
||||
let mut v = Vanish::open(&d).unwrap();
|
||||
v.command(&player(1, 3), &[], "vanish").unwrap();
|
||||
v.changes();
|
||||
v.save().unwrap();
|
||||
let mut v = Vanish::open(&d).unwrap();
|
||||
assert!(v.is(1));
|
||||
assert_eq!(
|
||||
v.changes(),
|
||||
vec![(1, true)],
|
||||
"a new run hides them again, on or off"
|
||||
);
|
||||
let out = v.command(&player(5, 3), &[], "vanish list").unwrap();
|
||||
assert_eq!(out, vec![Out::Reply("Vanished: P1.".into())]);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn players_below_level_three_cant_vanish() {
|
||||
let d = dir();
|
||||
let mut v = Vanish::open(&d).unwrap();
|
||||
let out = v.command(&player(1, 2), &[], "vanish").unwrap();
|
||||
assert!(matches!(&out[0], Out::Error(_)));
|
||||
assert!(!v.is(1) && v.changes().is_empty());
|
||||
assert!(v.command(&player(1, 3), &[], "balance").is_none());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
}
|
||||
+291
-41
@@ -19,18 +19,26 @@ Steve, `horizon-ctl --offscreen`) join it. Checked from the clients' own chat an
|
||||
the pot;
|
||||
- after the server stops cleanly and starts again, the balances are the same, and audit.log holds every change;
|
||||
- an operator's /eco give, then the /shop menu: a category, one item bought by a click and a stack by
|
||||
a shift-click, a stack of the player's own sold by clicking it, "Sell all" stopped by the daily limit (the rest
|
||||
kept, the limit shown in the menu and in /worth, the day's sales in market.json), the close button;
|
||||
- after the restart, prices moving: a purchase and a sale with no tax (receipts), an item bought can't be sold
|
||||
back while one found can, one price for diamond, moved down by a sale and up by a purchase as they go, /market's item
|
||||
a shift-click, a stack of the player's own sold by clicking it, "Sell all", the close button;
|
||||
- after the restart, prices moving: a purchase and a sale with no tax (receipts), bought items can be sold
|
||||
back immediately, one price for diamond, moved down by a sale and up by a purchase as they go, /market's item
|
||||
page buying, the 24 h chart given as a map and drawn in the player's hand (market-chart.png), web/market.json, and
|
||||
market_prices.json written when the world closes;
|
||||
- a farm's dump with no daily cap: 1,000 wheat (more than the old 640 a day) sold over four minutes, each minute's
|
||||
sale stopped by the 5% band, the price lower after each, and /worth showing no daily limit;
|
||||
- the web pages (web/market.json, web/economy.json) sent gzipped with the token to a stand-in for Kira;
|
||||
- /invsee: an operator takes a stack from an offline player's saved inventory, logged before the move and summed up in
|
||||
staff.log;
|
||||
- the emergency switches: an operator turns the market off (its commands refuse), then everything but land
|
||||
protection (the economy refuses, the sidebar goes), then everything on again, each in audit.log;
|
||||
- nicknames, for operators only: a player can't pick one; an operator's refused ones (a player's name, too short, a
|
||||
bad character), the one given in the other's chat and Tab list, /realname, someone else's taken, the player taking
|
||||
it off.
|
||||
it off;
|
||||
- /rtp: refused in the Nether; in the Overworld the player lands 500 to 5,000 blocks from the spawn on solid ground
|
||||
(and stays there), a second /rtp is refused with the time left, and the chunk it held loaded is let go.
|
||||
|
||||
`SMP_PROOF=rtp` runs one /rtp alone on a normal (not flat) world's fresh land instead, and what it cost the server's
|
||||
ticks: a performance report (`horizon-report`) over the search and landing against one over the same time before it.
|
||||
|
||||
The casino has its own proof (proof_casino.py): `SMP_PROOF=casino` runs it instead of this one.
|
||||
|
||||
@@ -98,10 +106,10 @@ def scratch_env(root):
|
||||
class Server:
|
||||
"""`horizon-client --dedicated --nogui` in a scratch server folder, its console on stdin."""
|
||||
|
||||
def __init__(self, game, resources, folder, port):
|
||||
def __init__(self, game, resources, folder, port, properties=None):
|
||||
self.folder, self.lines, self.game, self.resources, self.port = folder, [], game, resources, port
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
props = dict(PROPERTIES, **{"server-port": str(port)})
|
||||
props = dict(PROPERTIES, **(properties or {}), **{"server-port": str(port)})
|
||||
(folder / "server.properties").write_text("".join(f"{k}={v}\n" for k, v in props.items()))
|
||||
(folder / "eula.txt").write_text("eula=true\n")
|
||||
self.env = scratch_env(folder.parent / "server-env")
|
||||
@@ -340,6 +348,135 @@ def places(server, alex, steve):
|
||||
return r
|
||||
|
||||
|
||||
def landed(c, text, timeout=120):
|
||||
"""Waits for a chat line with `text` (an /rtp's end), up to `timeout` s; the line."""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
hit = [l for l in c.chat()[-6:] if text in l or "/rtp couldn't" in l or "No safe spot" in l]
|
||||
if hit:
|
||||
return hit[-1]
|
||||
time.sleep(1)
|
||||
raise AssertionError(f"{c.name}: no {text!r} in {timeout} s: {c.chat()[-8:]}")
|
||||
|
||||
|
||||
FLAT_GROUND = "if block ~ ~-1 ~ minecraft:grass_block if block ~ ~ ~ minecraft:air if block ~ ~1 ~ minecraft:air"
|
||||
SOLID_GROUND = ("unless block ~ ~-1 ~ minecraft:air unless block ~ ~-1 ~ minecraft:water "
|
||||
"unless block ~ ~-1 ~ minecraft:lava")
|
||||
|
||||
|
||||
def standing(server, c, at, tests=FLAT_GROUND):
|
||||
"""Whether the blocks round `at` pass `tests` (execute's conditions), as the server sees them: it says so."""
|
||||
x, y, z = (math.floor(v) for v in at)
|
||||
before = len(server.lines)
|
||||
server.console(f"execute in minecraft:overworld positioned {x} {y} {z} {tests} run say rtp-ground-ok")
|
||||
time.sleep(3)
|
||||
seen = server.lines[before:] + c.chat()[-4:]
|
||||
return any("rtp-ground-ok" in l for l in seen), seen
|
||||
|
||||
|
||||
def rtp(server, steve, data):
|
||||
"""/rtp: refused in the Nether; to a random spot 500..5000 blocks from the spawn, on the ground; then its cooldown."""
|
||||
r = {}
|
||||
spawn = json.loads((data / "places.json").read_text())["spawn"]
|
||||
_, home, _ = where(steve)
|
||||
server.console("execute in minecraft:the_nether run tp Steve 0.5 128 0.5")
|
||||
time.sleep(5)
|
||||
r["nether"] = steve.say("/rtp")
|
||||
assert any("/rtp only works in the Overworld." in l for l in r["nether"]), r
|
||||
server.console(f"execute in minecraft:overworld run tp Steve {home[0]:.2f} {home[1]:.2f} {home[2]:.2f}")
|
||||
time.sleep(5)
|
||||
start = len(server.lines)
|
||||
r["asked"] = steve.say("/wild")
|
||||
assert any("Teleporting in 2 s: don't move." in l for l in r["asked"]), r
|
||||
r["landed"] = landed(steve, "Teleported to a random spot")
|
||||
assert "Teleported to a random spot" in r["landed"], r
|
||||
time.sleep(3)
|
||||
dim, at, health = where(steve)
|
||||
r["at"], r["distance"] = at, math.hypot(at[0] - spawn["x"], at[2] - spawn["z"])
|
||||
assert dim == "minecraft:overworld" and 499 <= r["distance"] <= 5001, r
|
||||
# On the ground, not falling: the same place a few seconds later, unhurt.
|
||||
time.sleep(4)
|
||||
_, still, health2 = where(steve)
|
||||
assert near(at, still) and health2 >= health, (r, still, health2)
|
||||
r["ground"], lines = standing(server, steve, at)
|
||||
assert r["ground"], (r, lines)
|
||||
log = [l for l in server.lines[start:] if "[smp] /rtp: Steve" in l]
|
||||
assert log, server.lines[start:][-20:]
|
||||
r["log"] = log[-1]
|
||||
r["slow_ticks"] = [l for l in server.lines[start:] if "slow tick" in l or "Can't keep up" in l]
|
||||
r["again"] = steve.say("/rtp")
|
||||
assert any("Wait 30 min before your next /rtp." in l for l in r["again"]), r
|
||||
# The chunk it held loaded is let go 10 s after the landing.
|
||||
time.sleep(12)
|
||||
saved = json.loads((data / "places.json").read_text())
|
||||
assert not saved.get("forced") and len(saved.get("rtp", {})) == 1, saved
|
||||
server.console(f"execute in minecraft:overworld run tp Steve {home[0]:.2f} {home[1]:.2f} {home[2]:.2f}")
|
||||
time.sleep(3)
|
||||
return r
|
||||
|
||||
|
||||
def report(server, seconds):
|
||||
"""A performance report over the next `seconds`: its ticks (`mspt`, `over_50_ms`...)."""
|
||||
folder = server.folder / "reports"
|
||||
before = set(folder.glob("perf-*.json")) if folder.exists() else set()
|
||||
server.console(f"horizon-report {seconds}")
|
||||
end = time.time() + seconds + 60
|
||||
while time.time() < end:
|
||||
made = set(folder.glob("perf-*.json")) - before if folder.exists() else set()
|
||||
if made:
|
||||
time.sleep(1)
|
||||
return json.loads(made.pop().read_text())["ticks"]
|
||||
time.sleep(1)
|
||||
raise AssertionError(f"no report after {seconds} s: {server.lines[-20:]}")
|
||||
|
||||
|
||||
def rtp_alone(ctl, resources, out):
|
||||
"""SMP_PROOF=rtp: one /rtp on a normal world's fresh land (view distance 8, as the official server), with the
|
||||
ticks' cost: a 30 s report from the /rtp on, against a 30 s report just before it."""
|
||||
out = Path(out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
game = Path(ctl).with_name("horizon-client")
|
||||
root = Path(tempfile.mkdtemp(prefix="smp-rtp-"))
|
||||
port = free_port()
|
||||
server = Server(game, resources, root / "server", port, {"level-type": "minecraft\\:normal", "view-distance": "8",
|
||||
"generate-structures": "true"})
|
||||
server.env["HORIZON_SPIKES"] = "50"
|
||||
steve = Client(ctl, resources, "Steve", root)
|
||||
r = {}
|
||||
try:
|
||||
server.start()
|
||||
steve.join(port)
|
||||
# The spawn's land settles first.
|
||||
time.sleep(30)
|
||||
r["before"] = report(server, 30)
|
||||
start = len(server.lines)
|
||||
r["asked"] = steve.say("/rtp")
|
||||
assert any("Teleporting in 3 s: don't move." in l for l in r["asked"]), r
|
||||
server.console("horizon-report 30")
|
||||
r["landed"] = landed(steve, "Teleported to a random spot", 90)
|
||||
assert "Teleported to a random spot" in r["landed"], r
|
||||
folder = server.folder / "reports"
|
||||
end = time.time() + 120
|
||||
while len(list(folder.glob("perf-*.json"))) < 2 and time.time() < end:
|
||||
time.sleep(1)
|
||||
r["during"] = json.loads(max(folder.glob("perf-*.json"), key=lambda f: f.stat().st_mtime).read_text())["ticks"]
|
||||
time.sleep(5)
|
||||
dim, at, _ = where(steve)
|
||||
r["at"], r["distance"] = at, math.hypot(at[0], at[2])
|
||||
assert dim == "minecraft:overworld" and 499 <= r["distance"] <= 5001, r
|
||||
r["ground"], _ = standing(server, steve, at, SOLID_GROUND)
|
||||
r["log"] = [l for l in server.lines[start:] if "[smp] /rtp: Steve" in l]
|
||||
r["slow_ticks"] = [l for l in server.lines[start:] if "slow tick" in l or "Can't keep up" in l]
|
||||
print(json.dumps({"proof": "rtp", "ok": True, **r}, indent=2))
|
||||
finally:
|
||||
(out / "server.log").write_text("\n".join(server.lines))
|
||||
steve.quit()
|
||||
server.stop()
|
||||
if server.__dict__.get("process") and server.process.poll() is None:
|
||||
server.process.kill()
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
|
||||
|
||||
def claims(server, alex, steve):
|
||||
"""Alex claims a chunk: Steve can't break, use or place there until trusted."""
|
||||
r = {}
|
||||
@@ -452,7 +589,7 @@ def world_guard(server, alex, steve):
|
||||
|
||||
|
||||
def board(alex, steve, out):
|
||||
"""The scoreboard sidebar (the player's own block, the richest, the address) and the Tab list; /sidebar off
|
||||
"""The scoreboard sidebar (the player's own block, then the address) and the Tab list; /sidebar off
|
||||
hides it, on shows it again."""
|
||||
r = {}
|
||||
side = lambda c: c.run("status").get("sidebar")
|
||||
@@ -462,9 +599,8 @@ def board(alex, steve, out):
|
||||
break
|
||||
time.sleep(0.5)
|
||||
assert r["sidebar"]["objective"] == "horizon:native_sidebar" and r["sidebar"]["title"] == "Horizon SMP", r
|
||||
# Steve's name, balance, playtime and the players on; a gap, "Richest", Alex and Steve (the two accounts); a gap,
|
||||
# the address.
|
||||
assert len(r["sidebar"]["scores"]) == 10, r
|
||||
# Steve's name, balance, playtime and the players on; a gap, the address. No ranking of the richest.
|
||||
assert len(r["sidebar"]["scores"]) == 6, r
|
||||
# Holders starting with '#' would be hidden from the sidebar (only the title would show).
|
||||
assert not any(o.startswith("#") for o in r["sidebar"]["scores"]), r
|
||||
steve.run("key", "tab", "down")
|
||||
@@ -513,6 +649,37 @@ def polish(server, alex, steve, out):
|
||||
return r
|
||||
|
||||
|
||||
def switches(alex, data):
|
||||
"""/smp off and on (Alex is an operator): a part turned off refuses its commands, everything (but land
|
||||
protection) off takes the sidebar away, and on again brings it all back; switches.json keeps what is off."""
|
||||
r = {}
|
||||
side = lambda: alex.run("status").get("sidebar")
|
||||
r["off_market"] = alex.say("/smp off market proof")
|
||||
assert any("Turned off: market (proof)" in l for l in r["off_market"]), r
|
||||
r["worth"] = alex.say("/worth diamond")
|
||||
assert any("The market is turned off for now" in l for l in r["worth"]), r
|
||||
r["balance"] = alex.say("/balance")
|
||||
assert any("Balance:" in l for l in r["balance"]), r
|
||||
r["status"] = alex.say("/smp status")
|
||||
assert any("- market, by Alex" in l and ": proof" in l for l in r["status"]), r
|
||||
r["off_all"] = alex.say("/smp off")
|
||||
assert any("Land protection stays on" in l for l in r["off_all"]), r
|
||||
r["balance_off"] = alex.say("/balance")
|
||||
assert any("The economy is turned off for now" in l for l in r["balance_off"]), r
|
||||
time.sleep(1.5)
|
||||
assert not side(), "the sidebar is taken away"
|
||||
r["on"] = alex.say("/smp on")
|
||||
assert any("Turned on again:" in l and "claims" not in l for l in r["on"]), r
|
||||
r["balance_on"] = alex.say("/balance")
|
||||
assert any("Balance:" in l for l in r["balance_on"]), r
|
||||
for _ in range(10):
|
||||
if side():
|
||||
break
|
||||
time.sleep(0.5)
|
||||
assert side(), "the sidebar is back"
|
||||
return r
|
||||
|
||||
|
||||
def presence(server, alex, steve):
|
||||
"""/afk keeps Steve out of the sleep count (Alex alone in bed passes the night); moving brings him back; too many
|
||||
commands at once wait."""
|
||||
@@ -603,7 +770,7 @@ def nicks(server, alex, steve, out):
|
||||
|
||||
def shop(server, alex):
|
||||
"""Alex alone, op, in survival: given money (/eco give), then the /shop menu: a category, buying one and a stack,
|
||||
selling a stack of hers, "Sell all" up to the daily limit, closing. Returns the coins it added, and the lines."""
|
||||
selling a stack of hers, "Sell all" without a daily limit, closing. Returns the coins it added, and the lines."""
|
||||
results = {}
|
||||
# Only what the step gives her: "Sell all" would sell the rest too.
|
||||
server.console("clear Alex")
|
||||
@@ -628,42 +795,40 @@ def shop(server, alex):
|
||||
alex.run("click-slot", 300 + 0, "shift") # a stack of cobblestone
|
||||
time.sleep(1)
|
||||
assert alex.count("minecraft:cobblestone") == 64, alex.run("inventory")
|
||||
# Along the price as the stack moves it: 64 at 1 coin come to 64.05, 65 whole coins.
|
||||
# Along the price as the stack moves it (50 a 1%): 64 at 1 coin come to 64.41, 65 whole coins.
|
||||
results["stack"] = alex.chat()[-4:] # an advancement may come after
|
||||
assert any("Bought 64 cobblestone at 1.02 coins each: 65 coins." in l for l in results["stack"]), results
|
||||
assert not any("Tax" in l for l in results["stack"]), results
|
||||
# Her own stack of iron, clicked: the ingot she just bought stays (no buying to sell back), one she found sells.
|
||||
# Clear the cobblestone so the later Sell all step only tests diamonds.
|
||||
server.console("clear Alex minecraft:cobblestone 64")
|
||||
time.sleep(1)
|
||||
# The iron she just bought can be sold back immediately.
|
||||
alex.click(alex.slot_of("minecraft:iron_ingot"))
|
||||
results["round_trip"] = alex.chat()[-1:]
|
||||
assert any("You bought 1 iron ingot from the market in the last 24 h" in l for l in results["round_trip"]), results
|
||||
results["round_trip"] = alex.chat()[-3:]
|
||||
assert any("Sold 1 iron ingot at 15 coins each: 15 coins." in l for l in results["round_trip"]), results
|
||||
assert alex.count("minecraft:iron_ingot") == 0
|
||||
server.console("give Alex minecraft:iron_ingot 1")
|
||||
time.sleep(2)
|
||||
alex.click(alex.slot_of("minecraft:iron_ingot"))
|
||||
results["sold"] = alex.chat()[-4:]
|
||||
# Sold at the price she bought at: one price.
|
||||
assert any("Sold 1 iron ingot at 15 coins each: 15 coins." in l for l in results["sold"]), results
|
||||
assert any("1 iron ingot kept: bought from the market in the last 24 h." in l for l in results["sold"]), results
|
||||
assert alex.count("minecraft:iron_ingot") == 1
|
||||
# Sell all, up to the 2,000 coins a day: 1,984 left (1 from Steve's /pay in the nickname step: money received
|
||||
# counts too; 15 for the iron), 9 diamonds at 200. Each one sold lowers the price: 40,000 * (1 - e^-0.045)
|
||||
# = 1,760.1 for the 9.
|
||||
server.console("give Alex minecraft:diamond 30")
|
||||
assert alex.count("minecraft:iron_ingot") == 0
|
||||
# Sell all nine diamonds, with no daily cap. Along the curve they earn
|
||||
# 40,000 * (1 - e^-0.045) = 1,760.1, rounded down to 1,760 coins.
|
||||
server.console("give Alex minecraft:diamond 9")
|
||||
time.sleep(2)
|
||||
alex.click(300 + 49)
|
||||
results["sell_all"] = alex.chat()[-8:]
|
||||
assert any("Sold 9 diamond at 196 coins each: 1,760 coins." in l for l in results["sell_all"]), results
|
||||
assert not any("Tax" in l for l in results["sell_all"]), results
|
||||
assert any("21 diamond kept: today's selling limit." in l for l in results["sell_all"]), results
|
||||
assert alex.count("minecraft:diamond") == 21, alex.run("inventory")
|
||||
limits = alex.menu()[50]
|
||||
results["limits"] = limits
|
||||
# 1,984 - 1,760.
|
||||
assert "224 coins left of your 2,000 coins a day" in json.dumps(limits), limits
|
||||
assert alex.count("minecraft:diamond") == 0, alex.run("inventory")
|
||||
assert alex.menu()[50]["item"] == "minecraft:gray_stained_glass_pane", alex.menu()
|
||||
alex.click(300 + 53) # close
|
||||
assert not alex.menu()
|
||||
results["worth"] = alex.say("/worth diamond")
|
||||
assert any("You may sell 631 more diamond today." in l for l in results["worth"]), results
|
||||
return 2000 + 10 - 15 - 65 + 15 + 1760, results
|
||||
assert any("diamond:" in l for l in results["worth"]), results
|
||||
return 2000 + 10 - 15 - 65 + 15 + 15 + 1760, results
|
||||
|
||||
|
||||
def invsee(alex, data):
|
||||
@@ -749,6 +914,47 @@ def market(server, alex, out, data):
|
||||
return paid, results
|
||||
|
||||
|
||||
def farm(server, alex):
|
||||
"""No daily sale cap: Alex sells 1,000 wheat, more than the old 640 a day, a minute at a time. Each minute's
|
||||
sale stops at the 5% band (250 wheat at 50 a 1%), and the price is lower after each. Returns the coins and lines."""
|
||||
results = {}
|
||||
|
||||
def worth():
|
||||
lines = alex.say("/worth wheat")
|
||||
line = next(l for l in lines if "wheat: " in l and "each, to buy or sell." in l)
|
||||
return float(re.search(r"wheat: ([\d.,]+) coins? each", line)[1].replace(",", "")), lines
|
||||
|
||||
server.console("give Alex minecraft:wheat 1000")
|
||||
time.sleep(2)
|
||||
assert alex.count("minecraft:wheat") == 1000, alex.run("inventory")
|
||||
price, lines = worth()
|
||||
results["worth_before"] = lines
|
||||
assert not any("today" in l for l in lines), lines
|
||||
got, prices, sales = 0, [price], []
|
||||
for minute in range(4):
|
||||
if minute:
|
||||
time.sleep(61) # the next minute's band
|
||||
lines = alex.say("/sell wheat")
|
||||
sold = [re.search(r"Sold (\d+) wheat at [\d.,]+ coins? each: ([\d,]+) coins?\.", l) for l in lines]
|
||||
sold = [m for m in sold if m]
|
||||
assert len(sold) == 1, lines
|
||||
n, coins = int(sold[0][1]), int(sold[0][2].replace(",", ""))
|
||||
sales.append(n)
|
||||
got += coins
|
||||
# 250 a minute; what the band keeps stays in her inventory.
|
||||
assert n == 250, lines
|
||||
assert minute == 3 or any("kept: its price moved 5% this minute" in l for l in lines), lines
|
||||
assert not any("limit" in l for l in lines), lines
|
||||
price, wl = worth()
|
||||
assert price < prices[-1], (prices, wl)
|
||||
prices.append(price)
|
||||
assert alex.count("minecraft:wheat") == 0, alex.run("inventory")
|
||||
results["sales"], results["prices"], results["coins"] = sales, prices, got
|
||||
# Four 5% steps down from 2 (a little drift back between): about 2 * e^-0.2 = 1.64.
|
||||
assert 1.6 < prices[-1] < 1.7 and 1500 < got < 2000, results
|
||||
return got, results
|
||||
|
||||
|
||||
def trades(server, alex, steve, port, ctl, resources, root):
|
||||
"""Every way out of a trade, then one that goes through. Alex: 10 diamonds; Steve: 5 emeralds, 5 torches."""
|
||||
results = {}
|
||||
@@ -827,6 +1033,46 @@ def trades(server, alex, steve, port, ctl, resources, root):
|
||||
return results, steve
|
||||
|
||||
|
||||
def vanish(server, alex, steve, out):
|
||||
"""/vanish: Alex (an operator) leaves Steve's world and Tab list, and reads a subtitle the whole time; Steve can't
|
||||
reach her by name; /vanish again brings her back. Steve can't vanish."""
|
||||
r = {}
|
||||
players = lambda c: [e for e in c.run("entities", 64, "player")["entities"]]
|
||||
subtitle = lambda c: c.run("messages", 1).get("subtitle") or ""
|
||||
r["seen_before"] = len(players(steve))
|
||||
r["refused"] = steve.say("/vanish")
|
||||
assert any("Unknown" in l or "Only operators" in l or "permission" in l for l in r["refused"]), r
|
||||
r["vanish"] = alex.say("/vanish")
|
||||
assert any("You vanished" in l for l in r["vanish"]), r
|
||||
time.sleep(2.5)
|
||||
# Over a few seconds, not just once: the subtitle never lapses.
|
||||
r["subtitles"] = []
|
||||
for _ in range(4):
|
||||
r["subtitles"].append(subtitle(alex))
|
||||
time.sleep(1)
|
||||
assert all(s == "Vanished: only operators see you" for s in r["subtitles"]), r
|
||||
assert "Vanished" not in subtitle(steve), r
|
||||
if r["seen_before"]:
|
||||
assert not players(steve), "Steve no longer sees Alex"
|
||||
alex.run("screenshot", str(Path(out).resolve() / "vanish-subtitle.png"))
|
||||
steve.run("key", "tab", "down")
|
||||
time.sleep(1)
|
||||
steve.run("screenshot", str(Path(out).resolve() / "vanish-tab.png"))
|
||||
steve.run("key", "tab", "up")
|
||||
r["tpa"] = steve.say("/tpa Alex")
|
||||
assert any("Alex is not on." in l or "Alex isn't on." in l for l in r["tpa"]), r
|
||||
r["list"] = alex.say("/vanish list")
|
||||
assert any("Vanished: Alex." in l for l in r["list"]), r
|
||||
r["back"] = alex.say("/vanish")
|
||||
assert any("You are visible again." in l for l in r["back"]), r
|
||||
time.sleep(3)
|
||||
assert "Vanished" not in subtitle(alex), r
|
||||
if r["seen_before"]:
|
||||
assert players(steve), "Steve sees Alex again"
|
||||
time.sleep(6) # the spam guard's window, for the steps after
|
||||
return r
|
||||
|
||||
|
||||
def run(ctl, resources, out):
|
||||
if os.environ.get("SMP_PROOF") == "casino":
|
||||
# The casino's own proof (proof_casino.py), apart: it plays its games for a few minutes.
|
||||
@@ -835,6 +1081,8 @@ def run(ctl, resources, out):
|
||||
casino = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(casino)
|
||||
return casino.run(ctl, resources, out)
|
||||
if os.environ.get("SMP_PROOF") == "rtp":
|
||||
return rtp_alone(ctl, resources, out)
|
||||
out = Path(out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
game = Path(ctl).with_name("horizon-client")
|
||||
@@ -898,12 +1146,10 @@ def run(ctl, resources, out):
|
||||
assert any("You paid 120 coins to Steve. Balance: 380 coins" in l for l in results["pay"]), results
|
||||
results["paid"] = steve.chat()[-3:]
|
||||
assert any("Alex paid you 120 coins." in l for l in results["paid"]), results
|
||||
# 9999 is past what Steve may still receive today (2,000 a day, 120 received): money paid counts toward the
|
||||
# same daily limit as selling, so alts can't sell for a main past it.
|
||||
results["refused"] = [alex.say(l) for l in ("/pay Steve 1500", "/pay Steve 9999", "/pay Alex 1",
|
||||
"/pay Nobody 1")]
|
||||
for lines, error in zip(results["refused"], ("You only have 380 coins.",
|
||||
"Steve can only receive 1,880 coins more today",
|
||||
"You only have 380 coins.",
|
||||
"You can't pay yourself.",
|
||||
"No player named Nobody has an account.")):
|
||||
assert any(error in l for l in lines), results["refused"]
|
||||
@@ -944,12 +1190,14 @@ def run(ctl, resources, out):
|
||||
results["trades"], steve = trades(server, alex, steve, port, ctl, resources, root)
|
||||
# Before the coinflips: their last offer must still wait when the server stops.
|
||||
results["places"] = places(server, alex, steve)
|
||||
results["rtp"] = rtp(server, steve, data)
|
||||
results["claims"] = claims(server, alex, steve)
|
||||
results["world_guard"] = world_guard(server, alex, steve)
|
||||
results["board"] = board(alex, steve, out)
|
||||
results["polish"] = polish(server, alex, steve, out)
|
||||
results["presence"] = presence(server, alex, steve)
|
||||
results["nicks"] = nicks(server, alex, steve, out)
|
||||
results["vanish"] = vanish(server, alex, steve, out)
|
||||
results["coinflip"], alex_wins = coinflips(alex, steve)
|
||||
results["lottery"], alex_lotto = lottery(alex, steve, alex_wins)
|
||||
alex_after = 415 + (100 if alex_wins else -100) + (20 if alex_lotto else -30)
|
||||
@@ -998,7 +1246,10 @@ def run(ctl, resources, out):
|
||||
assert not any("joined for the first time" in l for l in alex.chat()), alex.chat()
|
||||
added, results["shop"] = shop(server, alex)
|
||||
spent, results["market"] = market(server, alex, out, data)
|
||||
farmed, results["farm"] = farm(server, alex)
|
||||
added += farmed
|
||||
results["invsee"] = invsee(alex, data)
|
||||
results["switches"] = switches(alex, data)
|
||||
sent = {path: (auth, doc) for path, auth, doc in receiver.got}
|
||||
results["pushed"] = sorted(sent)
|
||||
assert {"/smp/ingest/market.json", "/smp/ingest/economy.json"} <= set(sent), receiver.got[:2]
|
||||
@@ -1018,19 +1269,18 @@ def run(ctl, resources, out):
|
||||
audit = [json.loads(l) for l in (data / "audit.log").read_text().splitlines()]
|
||||
took = [a for a in audit if a["kind"] == "invsee_take"]
|
||||
assert [(a["item"], a["count"], a["inventory"]) for a in took] == [("minecraft:torch", 5, "inventory")], took
|
||||
kinds = [a["kind"] for a in audit if not a["kind"].startswith("invsee_")]
|
||||
switched = [(a["kind"], a["parts"]) for a in audit if a["kind"].startswith("switch_")]
|
||||
assert [k for k, _ in switched] == ["switch_off", "switch_off", "switch_on"], switched
|
||||
assert switched[0][1] == ["market"] and "claims" not in switched[1][1], switched
|
||||
assert not json.loads((data / "switches.json").read_text())["off"], "everything on again"
|
||||
kinds = [a["kind"] for a in audit if not a["kind"].startswith(("invsee_", "switch_"))]
|
||||
shop_kinds = ["eco_give", "buy 1 minecraft:iron_ingot", "buy 64 minecraft:cobblestone",
|
||||
"sell 1 minecraft:iron_ingot", "sell 9 minecraft:diamond", "buy 1 minecraft:diamond"]
|
||||
"sell 1 minecraft:iron_ingot", "sell 1 minecraft:iron_ingot", "sell 9 minecraft:diamond", "buy 1 minecraft:diamond",
|
||||
*["sell 250 minecraft:wheat"] * 4]
|
||||
assert kinds[-len(shop_kinds):] == shop_kinds, kinds[-8:]
|
||||
kinds = kinds[:-len(shop_kinds)]
|
||||
assert kinds[-2] in ("held_returned", "coinflip_cancel") and kinds[-1] == "daily_reward", kinds[-3:]
|
||||
results["stake_back"] = kinds[-2]
|
||||
sold = json.loads((data / "market.json").read_text())["sold"]
|
||||
# Steve's sales of the first run's day, and Alex's; coins received by /pay count too (#139): Steve got 120 + 1
|
||||
# from Alex, Alex 1 from Steve.
|
||||
assert sorted((s["coins"], s["items"]) for s in sold.values()) == [
|
||||
(441, {"minecraft:diamond": 1, "minecraft:wheat": 60}),
|
||||
(1776, {"minecraft:diamond": 9, "minecraft:iron_ingot": 1})], sold
|
||||
print(json.dumps({"proof": "smp", "ok": True, **results}, indent=2))
|
||||
finally:
|
||||
(out / "server.log").write_text("\n".join(server.lines))
|
||||
|
||||
@@ -47,5 +47,9 @@ pub mod smp_report;
|
||||
pub mod smp_shop;
|
||||
#[path = "../mixins/smp/smp_store.rs"]
|
||||
pub mod smp_store;
|
||||
#[path = "../mixins/smp/smp_switch.rs"]
|
||||
pub mod smp_switch;
|
||||
#[path = "../mixins/smp/smp_trade.rs"]
|
||||
pub mod smp_trade;
|
||||
#[path = "../mixins/smp/smp_vanish.rs"]
|
||||
pub mod smp_vanish;
|
||||
+10
-4
@@ -170,7 +170,9 @@ def cargo(stage_dir, action):
|
||||
|
||||
|
||||
def package(m):
|
||||
"""A deterministic .hnmod: horizon-native.json and the bundle's .rs and .toml files."""
|
||||
"""A deterministic .hnmod: horizon-native.json, the bundle's .rs and .toml files (its crates' too) and the mod's
|
||||
LICENSE as mixins/<id>/LICENSE, so the licence's notice travels with the sources (Horizon's bundle reader
|
||||
accepts LICENSE* files there)."""
|
||||
manifest = {"schema": 1, "id": m.id, "version": m.version, "game": m.compat["game"],
|
||||
"horizon": m.compat["horizon_revision"], "mixins": m.compat["horizon_mixins_revision"],
|
||||
"hooks": m.compat["hooks"]}
|
||||
@@ -178,9 +180,13 @@ def package(m):
|
||||
if pinned != m.compat["horizon_revision"]:
|
||||
sys.exit(f"{m.id}: horizon-mixin.toml pins {pinned}, compatibility.json {m.compat['horizon_revision']}")
|
||||
files = {"horizon-native.json": (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()}
|
||||
for path in sorted(m.bundle.iterdir()):
|
||||
if path.suffix in (".rs", ".toml"):
|
||||
files[f"mixins/{m.id}/{path.name}"] = path.read_bytes()
|
||||
# The helpers and modules, and the sources of the bundle's own crates (horizon-mixins 0.6.0).
|
||||
for path in sorted(m.bundle.rglob("*")):
|
||||
if path.is_file() and path.suffix in (".rs", ".toml"):
|
||||
files[f"mixins/{m.id}/{path.relative_to(m.bundle).as_posix()}"] = path.read_bytes()
|
||||
licence = m.root / "LICENSE"
|
||||
if licence.is_file():
|
||||
files.setdefault(f"mixins/{m.id}/LICENSE", licence.read_bytes())
|
||||
out = TARGET / f"{m.id}-{m.version}.hnmod"
|
||||
TARGET.mkdir(exist_ok=True)
|
||||
with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
|
||||
Generated
+252
@@ -0,0 +1,252 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "voicechat_server_relay"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,4 @@
|
||||
# The relay crate the bundle adds to the game (mixins/voicechat_server/relay), with its tests.
|
||||
[workspace]
|
||||
members = ["mixins/voicechat_server/relay"]
|
||||
resolver = "3"
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Ludovic Marie and the Horizon contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Voice chat server (Horizon native mod)
|
||||
|
||||
The server half of proximity voice chat on a Horizon dedicated server. Players who have a voice chat client mod
|
||||
(azetech's Complex Voice Chat, any client that speaks Simple Voice Chat 2.6.x's protocol over Horizon's mod
|
||||
messages) talk to the players near them, or to their group from anywhere. Players without one join and play as on
|
||||
any server: the server sends them nothing.
|
||||
|
||||
- **The handshake** goes over Horizon's mod messages (`native_net_from_client` / `native_net_send_to_player`, the
|
||||
`horizon:mod_net` channel) on `voicechat:` channel names, the same messages and layouts as Simple Voice Chat 2.6.x
|
||||
(compatibility version 20). A client gets a fresh 16-byte secret when it asks; nothing is sent to anyone before.
|
||||
- **Voices** go over UDP, through the server, never from player to player: no player learns another's address.
|
||||
Each player's packets are sealed with their own secret (AES-128-GCM). The server relays a voice to the players
|
||||
in the same dimension within `distance` blocks (`whisper_distance` for a whisper), and to the speaker's group
|
||||
wherever they are. Groups: normal (members aren't heard outside but hear who is near), open (heard and hearing
|
||||
nearby), isolated (members only).
|
||||
- **Limits:** 75 voice packets a second a player (burst 30), Opus frames up to 1275 bytes, 128 groups, names and
|
||||
passwords up to 24 characters, group and state changes 2 a second a player (burst 10), one secret a second a
|
||||
player (more requests meanwhile get one answer), 24 messages a player a tick and at most 512 waiting.
|
||||
- **Replays:** a packet that doesn't open with the player's key is dropped without an answer. A secret belongs to
|
||||
the first address that authenticates with it: a handshake copied and sent from elsewhere moves nothing. Exact
|
||||
copies are dropped too (the last 64 control packets' nonces, and voice packets' sequence numbers). A client the
|
||||
server stops hearing for 10 keep-alives (its NAT rebound, say) gets a fresh secret over the game connection and
|
||||
comes back from its new address with it; the old key then opens nothing.
|
||||
- **No port is opened** until the first voice chat client asks. Then the relay binds `bind:port` (UDP).
|
||||
|
||||
## Config
|
||||
|
||||
`config/voicechat-server.json`, beside `server.properties`, written with its defaults the first time a client asks:
|
||||
|
||||
| Key | Default | |
|
||||
|---|---|---|
|
||||
| `enabled` | `true` | `false`: no port, no answer to clients |
|
||||
| `port` | `24454` | the UDP port. A host that gives one port for the game usually forwards UDP on it too: use the game's port |
|
||||
| `bind` | `0.0.0.0` | |
|
||||
| `voice_host` | `""` | where clients send UDP if not the game server's address: a port, a host, or host:port |
|
||||
| `distance` | `48.0` | blocks a voice carries |
|
||||
| `whisper_distance` | `24.0` | |
|
||||
| `groups` | `true` | players may make and join groups |
|
||||
| `keep_alive_ms` | `1000` | a client silent 10 times this long shows as disconnected |
|
||||
| `mtu` | `1024` | |
|
||||
|
||||
## Files
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `mixins/voicechat_server/horizon-mixin.toml` | The bundle: the relay crate, the glue module and four HEAD hooks (mod messages, server tick, player logged out, world closing) |
|
||||
| `mixins/voicechat_server/relay/` | The relay crate (`voicechat_server_relay`): the wire format (`proto.rs`), the handshake, groups and UDP relay (`lib.rs`) and its tests over real UDP sockets (`tests.rs`). Depends on `ring` (AES-GCM) and `serde`, both in Horizon's `Cargo.lock` |
|
||||
| `mixins/voicechat_server/glue.rs` | Added to the game as `game::voicechat_server`: the config, starting the relay, the players each tick |
|
||||
|
||||
It needs horizon-mixins 0.6.0 (bundle crates) and hook points API 57. Tests: `cargo test` here.
|
||||
|
||||
Not made with or endorsed by Simple Voice Chat or its author: it speaks the same protocol, written from its packet
|
||||
layouts, with none of its code.
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"game": "26.3",
|
||||
"hooks": 57,
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "f4833621f9037e08c487b1779e8c030487e65cc2",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// Voice chat's server half in the game (`game::voicechat_server`): the relay
|
||||
// (crate voicechat_server_relay) opens its UDP port when the first voice chat
|
||||
// client asks for a secret, hears the clients' messages through Horizon's mod
|
||||
// messages, and learns each tick where every player is. A player without a
|
||||
// voice chat client is never sent anything.
|
||||
|
||||
use crate::game::Game;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use voicechat_server_relay::{Config, Player, Server, proto};
|
||||
|
||||
/// Messages to one player a tick at most (mod messages allow 32, shared with other mods).
|
||||
const PER_TICK: usize = 24;
|
||||
/// The config file in the server's `config/` folder.
|
||||
const FILE: &str = "voicechat-server.json";
|
||||
/// After the port failed to open, wait this long before trying again.
|
||||
const RETRY: Duration = Duration::from_secs(60);
|
||||
|
||||
enum Relay {
|
||||
Off,
|
||||
Running(Server),
|
||||
Failed(Instant),
|
||||
}
|
||||
|
||||
static RELAY: Mutex<Relay> = Mutex::new(Relay::Off);
|
||||
|
||||
fn relay() -> std::sync::MutexGuard<'static, Relay> {
|
||||
RELAY.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn players(game: &Game<'_>) -> Vec<Player> {
|
||||
game.native_server_players()
|
||||
.into_iter()
|
||||
.map(|p| Player {
|
||||
uuid: p.uuid,
|
||||
name: p.name,
|
||||
dimension: p.dimension,
|
||||
position: p.position,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `config/voicechat-server.json`, written with its defaults the first time
|
||||
/// and again with the keys a newer version adds (values kept). A file that
|
||||
/// doesn't read is left alone and the defaults apply.
|
||||
fn config() -> Config {
|
||||
let Ok(dir) = Game::native_config_dir() else {
|
||||
return Config::default();
|
||||
};
|
||||
let path = dir.join(FILE);
|
||||
let config = match std::fs::read_to_string(&path) {
|
||||
Ok(text) => match serde_json::from_str::<Config>(&text) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"Voice chat: {} doesn't read ({e}); using the defaults",
|
||||
path.display()
|
||||
);
|
||||
return Config::default();
|
||||
}
|
||||
},
|
||||
Err(_) => Config::default(),
|
||||
};
|
||||
if let Ok(text) = serde_json::to_string_pretty(&config) {
|
||||
let _ = std::fs::write(&path, text + "\n");
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// A message from a player's client: only `voicechat:` channels are ours.
|
||||
pub(super) fn message(game: &mut Game<'_>, player: u128, channel: &str, data: &[u8]) {
|
||||
if !channel.starts_with("voicechat:") {
|
||||
return;
|
||||
}
|
||||
let mut relay = relay();
|
||||
if !matches!(*relay, Relay::Running(_)) {
|
||||
if channel != proto::REQUEST_SECRET {
|
||||
return;
|
||||
}
|
||||
if let Relay::Failed(at) = *relay
|
||||
&& at.elapsed() < RETRY
|
||||
{
|
||||
return;
|
||||
}
|
||||
let config = config();
|
||||
match Server::start(config.clone()) {
|
||||
Ok(server) => {
|
||||
let at = server
|
||||
.local_addr()
|
||||
.map(|a| a.to_string())
|
||||
.unwrap_or_default();
|
||||
log::info!("Voice chat: relaying voices on UDP {at}");
|
||||
*relay = Relay::Running(server);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"Voice chat: not started on UDP {}:{}: {e}",
|
||||
config.bind,
|
||||
config.port
|
||||
);
|
||||
*relay = Relay::Failed(Instant::now());
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Relay::Running(server) = &*relay else {
|
||||
return;
|
||||
};
|
||||
// A player who joined since the last tick (or a relay that just started):
|
||||
// learn who is on first. Not for every message: it lists every player.
|
||||
if !server.knows(player) {
|
||||
server.tick(players(game));
|
||||
}
|
||||
server.message(player, channel, data);
|
||||
}
|
||||
|
||||
/// Each server tick, once the relay runs.
|
||||
pub(super) fn tick(game: &mut Game<'_>) {
|
||||
let out = {
|
||||
let relay = relay();
|
||||
let Relay::Running(server) = &*relay else {
|
||||
return;
|
||||
};
|
||||
server.tick(players(game));
|
||||
server.outgoing(PER_TICK)
|
||||
};
|
||||
for (player, channel, data) in out {
|
||||
if let Err(e) = game.native_net_send_to_player(player, &channel, &data) {
|
||||
log::debug!("Voice chat: {channel} not sent: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn left(player: u128) {
|
||||
if let Relay::Running(server) = &*relay() {
|
||||
server.left(player);
|
||||
}
|
||||
}
|
||||
|
||||
/// The world closed: the port closes too (it opens again on the next request).
|
||||
pub(super) fn stop() {
|
||||
*relay() = Relay::Off;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
[mod]
|
||||
id = "voicechat_server"
|
||||
version = "1.0.0"
|
||||
priority = 100
|
||||
|
||||
# The commit it was tested on (the official server's engine).
|
||||
[compatibility]
|
||||
horizon_revision = "f4833621f9037e08c487b1779e8c030487e65cc2"
|
||||
|
||||
# The handshake, the groups and the UDP relay: plain Rust with its tests.
|
||||
[[crate]]
|
||||
id = "relay"
|
||||
path = "relay"
|
||||
|
||||
# The edges between the game and the relay.
|
||||
[[module]]
|
||||
id = "glue"
|
||||
file = "crates/horizon-client/src/game.rs"
|
||||
name = "voicechat_server"
|
||||
source = "glue.rs"
|
||||
|
||||
[[injection]]
|
||||
id = "net"
|
||||
kind = "HEAD"
|
||||
target = "horizon_client::game::native_hooks::Game<'_>::native_net_from_client"
|
||||
helper = "net.rs"
|
||||
bindings = [
|
||||
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
|
||||
{ name = "player", ty = "u128", value = "player" },
|
||||
{ name = "channel", ty = "&str", value = "channel" },
|
||||
{ name = "data", ty = "&[u8]", value = "data" },
|
||||
]
|
||||
|
||||
[[injection]]
|
||||
id = "tick"
|
||||
kind = "HEAD"
|
||||
target = "horizon_client::game::native_hooks::Game<'_>::native_server_tick"
|
||||
helper = "tick.rs"
|
||||
bindings = [
|
||||
{ name = "game", ty = "&mut crate::game::Game<'_>", value = "&mut *self" },
|
||||
{ name = "phase", ty = "crate::game::native_lifecycle::ServerTickPhase", value = "phase" },
|
||||
]
|
||||
|
||||
[[injection]]
|
||||
id = "logged_out"
|
||||
kind = "HEAD"
|
||||
target = "horizon_client::game::native_hooks::Game<'_>::native_player_logged_out"
|
||||
helper = "logged_out.rs"
|
||||
bindings = [
|
||||
{ name = "player", ty = "u128", value = "player" },
|
||||
]
|
||||
|
||||
[[injection]]
|
||||
id = "lifecycle"
|
||||
kind = "HEAD"
|
||||
target = "horizon_client::game::native_hooks::Game<'_>::native_world_lifecycle"
|
||||
helper = "lifecycle.rs"
|
||||
bindings = [
|
||||
{ name = "phase", ty = "crate::game::native_lifecycle::WorldPhase", value = "phase" },
|
||||
]
|
||||
@@ -0,0 +1,10 @@
|
||||
// The world closing: the relay closes its UDP port.
|
||||
fn voicechat_server_lifecycle(phase: crate::game::native_lifecycle::WorldPhase) {
|
||||
use crate::game::native_lifecycle::WorldPhase;
|
||||
if matches!(
|
||||
phase,
|
||||
WorldPhase::WorldCloseFinal | WorldPhase::WorldCloseFailed
|
||||
) {
|
||||
crate::game::voicechat_server::stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// A player left: the relay forgets them and tells the others.
|
||||
fn voicechat_server_logged_out(player: u128) {
|
||||
crate::game::voicechat_server::left(player);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// A voice chat client's message (`voicechat:` channels) to the relay.
|
||||
fn voicechat_server_net(
|
||||
game: &mut crate::game::Game<'_>,
|
||||
player: u128,
|
||||
channel: &str,
|
||||
data: &[u8],
|
||||
) {
|
||||
crate::game::voicechat_server::message(game, player, channel, data);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "voicechat_server_relay"
|
||||
version = "1.0.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
publish = false
|
||||
description = "Horizon's voice chat server: the handshake for voice chat clients and the UDP relay of their voices."
|
||||
|
||||
[dependencies]
|
||||
ring = "0.17"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,788 @@
|
||||
//! The server half of proximity voice chat on Horizon: it answers the voice
|
||||
//! chat clients' handshake (sent over Horizon's mod messages) and relays their
|
||||
//! voices over UDP to the players who should hear them, by distance and
|
||||
//! group. Players without a voice chat client never hear of it: nothing is
|
||||
//! sent to a player until their client asks.
|
||||
//!
|
||||
//! Voices go through the server, never player to player, so nobody learns
|
||||
//! another player's address. Each player's packets are sealed with their own
|
||||
//! key (AES-128-GCM), which they get over the game connection.
|
||||
pub mod proto;
|
||||
|
||||
use proto::{FromClient, GroupKind, PlayerState, Request, ToClient};
|
||||
use ring::rand::{SecureRandom, SystemRandom};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::io;
|
||||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `config/voicechat-server.json`.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Config {
|
||||
/// Off: no port is opened and clients get no answer.
|
||||
pub enabled: bool,
|
||||
/// The UDP port voices use. A host that gives one port for the game
|
||||
/// (TCP) usually forwards UDP on it too: use the game's port then.
|
||||
pub port: u16,
|
||||
/// The address the UDP socket binds.
|
||||
pub bind: String,
|
||||
/// Where clients send UDP, when not the game server's own address:
|
||||
/// a port, a host, or host:port.
|
||||
pub voice_host: String,
|
||||
/// How far a voice carries, in blocks.
|
||||
pub distance: f64,
|
||||
/// How far a whisper carries.
|
||||
pub whisper_distance: f64,
|
||||
/// Players may make and join groups.
|
||||
pub groups: bool,
|
||||
pub keep_alive_ms: u32,
|
||||
pub mtu: u32,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
port: 24454,
|
||||
bind: "0.0.0.0".into(),
|
||||
voice_host: String::new(),
|
||||
distance: 48.0,
|
||||
whisper_distance: 24.0,
|
||||
groups: true,
|
||||
keep_alive_ms: 1000,
|
||||
mtu: 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A player on the game server, as the last tick saw them.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Player {
|
||||
pub uuid: u128,
|
||||
pub name: String,
|
||||
pub dimension: String,
|
||||
pub position: [f64; 3],
|
||||
}
|
||||
|
||||
/// A message for a player's client: (player, channel, data).
|
||||
pub type Message = (u128, String, Vec<u8>);
|
||||
|
||||
/// Groups at most, and voice packets a second a player may send.
|
||||
const MAX_GROUPS: usize = 128;
|
||||
const MIC_PER_SECOND: f64 = 75.0;
|
||||
const MIC_BURST: f64 = 30.0;
|
||||
/// Group and voice state changes a second a player may make.
|
||||
const OPS_PER_SECOND: f64 = 2.0;
|
||||
const OPS_BURST: f64 = 10.0;
|
||||
/// Secrets a player's own requests get at most this often; more requests
|
||||
/// meanwhile are answered once, when the time is up.
|
||||
const SECRET_EVERY: Duration = Duration::from_secs(1);
|
||||
/// Messages waiting for one player at most; more are dropped.
|
||||
const MAX_QUEUED: usize = 512;
|
||||
/// The nonces of a player's last control packets remembered, to drop exact
|
||||
/// replays; and how far behind the newest a voice packet's sequence may be.
|
||||
const SEEN_NONCES: usize = 64;
|
||||
const MIC_WINDOW: i128 = 64;
|
||||
|
||||
/// A player's voice connection, for the life of one secret.
|
||||
///
|
||||
/// The first address that authenticates holds the secret: no other address
|
||||
/// can use it, so a handshake captured and sent again from elsewhere moves
|
||||
/// nothing. A client that moves (a NAT that rebinds) gets a fresh secret
|
||||
/// over the game connection, which the game session authenticates: when the
|
||||
/// server stops hearing it, or when it asks again. The old key then opens
|
||||
/// nothing.
|
||||
struct Client {
|
||||
secret: [u8; 16],
|
||||
cipher: proto::Cipher,
|
||||
addr: Option<SocketAddr>,
|
||||
/// Answered the connection check: its voice connection works.
|
||||
connected: bool,
|
||||
last_keep_alive: Instant,
|
||||
disabled: bool,
|
||||
group: Option<u128>,
|
||||
tokens: f64,
|
||||
refilled: Instant,
|
||||
ops: f64,
|
||||
ops_refilled: Instant,
|
||||
/// When this secret was given, and whether a request for another waits.
|
||||
issued: Instant,
|
||||
asked_again: bool,
|
||||
/// Nonces of the control packets already taken (the newest last).
|
||||
seen: VecDeque<[u8; 12]>,
|
||||
/// The newest voice sequence, and which of the 64 before it arrived.
|
||||
mic_top: Option<i64>,
|
||||
mic_seen: u64,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn new(secret: [u8; 16], now: Instant) -> Self {
|
||||
Self {
|
||||
secret,
|
||||
cipher: proto::Cipher::new(&secret),
|
||||
addr: None,
|
||||
connected: false,
|
||||
last_keep_alive: now,
|
||||
disabled: false,
|
||||
group: None,
|
||||
tokens: MIC_BURST,
|
||||
refilled: now,
|
||||
ops: OPS_BURST,
|
||||
ops_refilled: now,
|
||||
issued: now,
|
||||
asked_again: false,
|
||||
seen: VecDeque::new(),
|
||||
mic_top: None,
|
||||
mic_seen: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A control packet's nonce: false if it was already taken.
|
||||
fn fresh_nonce(&mut self, nonce: [u8; 12]) -> bool {
|
||||
if self.seen.contains(&nonce) {
|
||||
return false;
|
||||
}
|
||||
if self.seen.len() >= SEEN_NONCES {
|
||||
self.seen.pop_front();
|
||||
}
|
||||
self.seen.push_back(nonce);
|
||||
true
|
||||
}
|
||||
|
||||
/// A voice packet's sequence: false if it was already relayed or is too
|
||||
/// old (a replay). A client counts up from 0 for each secret.
|
||||
fn fresh_sequence(&mut self, sequence: i64) -> bool {
|
||||
let Some(top) = self.mic_top else {
|
||||
self.mic_top = Some(sequence);
|
||||
self.mic_seen = 1;
|
||||
return true;
|
||||
};
|
||||
let ahead = i128::from(sequence) - i128::from(top);
|
||||
if ahead > 0 {
|
||||
self.mic_seen = if ahead >= MIC_WINDOW {
|
||||
1
|
||||
} else {
|
||||
(self.mic_seen << ahead) | 1
|
||||
};
|
||||
self.mic_top = Some(sequence);
|
||||
return true;
|
||||
}
|
||||
let back = -ahead;
|
||||
if back >= MIC_WINDOW {
|
||||
return false;
|
||||
}
|
||||
let bit = 1u64 << back;
|
||||
if self.mic_seen & bit != 0 {
|
||||
return false;
|
||||
}
|
||||
self.mic_seen |= bit;
|
||||
true
|
||||
}
|
||||
|
||||
/// One group or state change, if the player has one left.
|
||||
fn spend_op(&mut self, now: Instant) -> bool {
|
||||
self.ops = (self.ops
|
||||
+ now.duration_since(self.ops_refilled).as_secs_f64() * OPS_PER_SECOND)
|
||||
.min(OPS_BURST);
|
||||
self.ops_refilled = now;
|
||||
if self.ops < 1.0 {
|
||||
return false;
|
||||
}
|
||||
self.ops -= 1.0;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
struct Group {
|
||||
name: String,
|
||||
password: Option<String>,
|
||||
kind: GroupKind,
|
||||
}
|
||||
|
||||
struct State {
|
||||
config: Config,
|
||||
/// The UDP port the socket got.
|
||||
port: u16,
|
||||
clients: HashMap<u128, Client>,
|
||||
players: HashMap<u128, Player>,
|
||||
groups: HashMap<u128, Group>,
|
||||
/// Players whose state changed since the last tick, to tell everyone.
|
||||
changed: HashSet<u128>,
|
||||
outbox: HashMap<u128, VecDeque<(String, Vec<u8>)>>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
socket: UdpSocket,
|
||||
rng: SystemRandom,
|
||||
running: AtomicBool,
|
||||
}
|
||||
|
||||
/// The running voice server: its UDP socket and thread. Dropping it stops them.
|
||||
pub struct Server {
|
||||
shared: Arc<Shared>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
fn lock(m: &Mutex<State>) -> MutexGuard<'_, State> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Opens the UDP port and starts relaying.
|
||||
pub fn start(config: Config) -> io::Result<Self> {
|
||||
if !config.enabled {
|
||||
return Err(io::Error::other("voice chat is turned off in its config"));
|
||||
}
|
||||
let socket = UdpSocket::bind((config.bind.as_str(), config.port))?;
|
||||
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
|
||||
let port = socket.local_addr()?.port();
|
||||
let shared = Arc::new(Shared {
|
||||
state: Mutex::new(State {
|
||||
config,
|
||||
port,
|
||||
clients: HashMap::new(),
|
||||
players: HashMap::new(),
|
||||
groups: HashMap::new(),
|
||||
changed: HashSet::new(),
|
||||
outbox: HashMap::new(),
|
||||
}),
|
||||
socket,
|
||||
rng: SystemRandom::new(),
|
||||
running: AtomicBool::new(true),
|
||||
});
|
||||
let worker = shared.clone();
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("voicechat-relay".into())
|
||||
.spawn(move || relay(&worker))?;
|
||||
Ok(Self {
|
||||
shared,
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
|
||||
/// The UDP address voices arrive on.
|
||||
pub fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
self.shared.socket.local_addr()
|
||||
}
|
||||
|
||||
/// Each server tick: the players on the server now. Voice chat forgets
|
||||
/// the ones who left, and tells everyone what changed.
|
||||
pub fn tick(&self, players: Vec<Player>) {
|
||||
let mut st = lock(&self.shared.state);
|
||||
st.players = players.into_iter().map(|p| (p.uuid, p)).collect();
|
||||
let gone: Vec<u128> = st
|
||||
.clients
|
||||
.keys()
|
||||
.filter(|u| !st.players.contains_key(u))
|
||||
.copied()
|
||||
.collect();
|
||||
for uuid in gone {
|
||||
st.forget(uuid);
|
||||
}
|
||||
// Requests that came too soon after a secret get one now.
|
||||
let due: Vec<u128> = st
|
||||
.clients
|
||||
.iter()
|
||||
.filter(|(_, c)| c.asked_again && c.issued.elapsed() >= SECRET_EVERY)
|
||||
.map(|(u, _)| *u)
|
||||
.collect();
|
||||
for uuid in due {
|
||||
st.give_secret(&self.shared.rng, uuid, false);
|
||||
}
|
||||
let changed: Vec<u128> = st.changed.drain().collect();
|
||||
for uuid in changed {
|
||||
if let Some(s) = st.player_state(uuid) {
|
||||
st.tell_all(proto::STATE, proto::state(&s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `player` was on the server at the last tick.
|
||||
pub fn knows(&self, player: u128) -> bool {
|
||||
lock(&self.shared.state).players.contains_key(&player)
|
||||
}
|
||||
|
||||
/// A player left the game.
|
||||
pub fn left(&self, player: u128) {
|
||||
lock(&self.shared.state).forget(player);
|
||||
}
|
||||
|
||||
/// A message from `player`'s client on a `voicechat:` channel.
|
||||
pub fn message(&self, player: u128, channel: &str, data: &[u8]) {
|
||||
let Some(Ok(request)) = Request::read(channel, data) else {
|
||||
return;
|
||||
};
|
||||
let mut st = lock(&self.shared.state);
|
||||
if !st.players.contains_key(&player) {
|
||||
return;
|
||||
}
|
||||
match request {
|
||||
Request::Secret { version } => {
|
||||
if version != proto::COMPATIBILITY_VERSION {
|
||||
return;
|
||||
}
|
||||
if let Some(c) = st.clients.get_mut(&player)
|
||||
&& c.issued.elapsed() < SECRET_EVERY
|
||||
{
|
||||
c.asked_again = true;
|
||||
return;
|
||||
}
|
||||
st.give_secret(&self.shared.rng, player, false);
|
||||
}
|
||||
Request::State { disabled } => {
|
||||
if let Some(c) = st.clients.get_mut(&player)
|
||||
&& c.spend_op(Instant::now())
|
||||
&& c.disabled != disabled
|
||||
{
|
||||
c.disabled = disabled;
|
||||
st.changed.insert(player);
|
||||
}
|
||||
}
|
||||
Request::CreateGroup {
|
||||
name,
|
||||
password,
|
||||
kind,
|
||||
} => {
|
||||
let name = name.trim().to_owned();
|
||||
if !st.config.groups
|
||||
|| name.is_empty()
|
||||
|| st.groups.len() >= MAX_GROUPS
|
||||
|| !st.spend_op(player)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut id = [0u8; 16];
|
||||
if self.shared.rng.fill(&mut id).is_err() {
|
||||
return;
|
||||
}
|
||||
let id = u128::from_be_bytes(id);
|
||||
let password = password
|
||||
.map(|p| p.trim().to_owned())
|
||||
.filter(|p| !p.is_empty());
|
||||
let add = proto::add_group(id, &name, password.is_some(), kind);
|
||||
st.groups.insert(
|
||||
id,
|
||||
Group {
|
||||
name,
|
||||
password,
|
||||
kind,
|
||||
},
|
||||
);
|
||||
st.tell_all(proto::ADD_GROUP, add);
|
||||
st.join(player, id);
|
||||
}
|
||||
Request::JoinGroup { group, password } => {
|
||||
if !st.config.groups || !st.groups.contains_key(&group) || !st.spend_op(player) {
|
||||
return;
|
||||
}
|
||||
let Some(g) = st.groups.get(&group) else {
|
||||
return;
|
||||
};
|
||||
let ok = g.password.is_none()
|
||||
|| g.password.as_deref() == password.as_deref().map(str::trim);
|
||||
if ok {
|
||||
st.join(player, group);
|
||||
} else {
|
||||
let current = st.clients.get(&player).and_then(|c| c.group);
|
||||
st.tell(
|
||||
player,
|
||||
proto::JOINED_GROUP,
|
||||
proto::joined_group(current, true),
|
||||
);
|
||||
}
|
||||
}
|
||||
Request::LeaveGroup => {
|
||||
let Some(c) = st.clients.get_mut(&player) else {
|
||||
return;
|
||||
};
|
||||
if c.group.is_none() || !c.spend_op(Instant::now()) {
|
||||
return;
|
||||
}
|
||||
let Some(g) = c.group.take() else { return };
|
||||
st.tell(
|
||||
player,
|
||||
proto::JOINED_GROUP,
|
||||
proto::joined_group(None, false),
|
||||
);
|
||||
st.changed.insert(player);
|
||||
st.leave_group_cleanup(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What to send to the players' clients now, at most `per_player` messages each (the rest wait for the
|
||||
/// next call).
|
||||
pub fn outgoing(&self, per_player: usize) -> Vec<Message> {
|
||||
let mut st = lock(&self.shared.state);
|
||||
let mut out = Vec::new();
|
||||
st.outbox.retain(|player, queue| {
|
||||
for _ in 0..per_player {
|
||||
let Some((channel, data)) = queue.pop_front() else {
|
||||
break;
|
||||
};
|
||||
out.push((*player, channel, data));
|
||||
}
|
||||
!queue.is_empty()
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
self.shared.running.store(false, Ordering::Relaxed);
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Queues a message for `player`'s client (dropped when MAX_QUEUED wait).
|
||||
fn tell(&mut self, player: u128, channel: &str, data: Vec<u8>) {
|
||||
let queue = self.outbox.entry(player).or_default();
|
||||
if queue.len() < MAX_QUEUED {
|
||||
queue.push_back((channel.to_owned(), data));
|
||||
}
|
||||
}
|
||||
|
||||
fn spend_op(&mut self, player: u128) -> bool {
|
||||
self.clients
|
||||
.get_mut(&player)
|
||||
.is_some_and(|c| c.spend_op(Instant::now()))
|
||||
}
|
||||
|
||||
/// A fresh secret for `player`: the old one opens nothing any more.
|
||||
/// `rekey`: the server's own, for a client it stopped hearing (it keeps its
|
||||
/// group and state, and gets only the secret). Otherwise the client asked:
|
||||
/// it starts over and gets everyone's state and the groups, instead of
|
||||
/// whatever still waited for it.
|
||||
fn give_secret(&mut self, rng: &SystemRandom, player: u128, rekey: bool) {
|
||||
let mut secret = [0u8; 16];
|
||||
if rng.fill(&mut secret).is_err() {
|
||||
return;
|
||||
}
|
||||
let mut client = Client::new(secret, Instant::now());
|
||||
let old = self.clients.remove(&player);
|
||||
if rekey && let Some(old) = &old {
|
||||
client.group = old.group;
|
||||
client.disabled = old.disabled;
|
||||
client.ops = old.ops;
|
||||
client.ops_refilled = old.ops_refilled;
|
||||
}
|
||||
self.clients.insert(player, client);
|
||||
if !rekey && let Some(g) = old.and_then(|o| o.group) {
|
||||
self.leave_group_cleanup(g);
|
||||
}
|
||||
let c = &self.config;
|
||||
let body = proto::secret(&proto::SecretInfo {
|
||||
secret: &secret,
|
||||
port: self.port,
|
||||
player,
|
||||
mtu: c.mtu.min(i32::MAX as u32) as i32,
|
||||
distance: c.distance,
|
||||
keep_alive_ms: c.keep_alive_ms.clamp(100, 60_000) as i32,
|
||||
groups: c.groups,
|
||||
voice_host: &c.voice_host,
|
||||
});
|
||||
self.changed.insert(player);
|
||||
if rekey {
|
||||
// Past the cap: the secret is what gets the client back.
|
||||
self.outbox
|
||||
.entry(player)
|
||||
.or_default()
|
||||
.push_back((proto::SECRET.to_owned(), body));
|
||||
return;
|
||||
}
|
||||
self.outbox.remove(&player);
|
||||
self.tell(player, proto::SECRET, body);
|
||||
let all: Vec<PlayerState> = self
|
||||
.clients
|
||||
.keys()
|
||||
.filter_map(|u| self.player_state(*u))
|
||||
.collect();
|
||||
self.tell(player, proto::STATES, proto::states(&all));
|
||||
let groups: Vec<Vec<u8>> = self
|
||||
.groups
|
||||
.iter()
|
||||
.map(|(id, g)| proto::add_group(*id, &g.name, g.password.is_some(), g.kind))
|
||||
.collect();
|
||||
for g in groups {
|
||||
self.tell(player, proto::ADD_GROUP, g);
|
||||
}
|
||||
}
|
||||
|
||||
/// To every player with a voice chat client.
|
||||
fn tell_all(&mut self, channel: &str, data: Vec<u8>) {
|
||||
let all: Vec<u128> = self.clients.keys().copied().collect();
|
||||
for p in all {
|
||||
self.tell(p, channel, data.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn player_state(&self, uuid: u128) -> Option<PlayerState> {
|
||||
let c = self.clients.get(&uuid)?;
|
||||
Some(PlayerState {
|
||||
uuid,
|
||||
name: self
|
||||
.players
|
||||
.get(&uuid)
|
||||
.map(|p| p.name.clone())
|
||||
.unwrap_or_default(),
|
||||
disabled: c.disabled,
|
||||
disconnected: !c.connected,
|
||||
group: c.group,
|
||||
})
|
||||
}
|
||||
|
||||
fn join(&mut self, player: u128, group: u128) {
|
||||
let Some(c) = self.clients.get_mut(&player) else {
|
||||
return;
|
||||
};
|
||||
let old = c.group.replace(group);
|
||||
self.tell(
|
||||
player,
|
||||
proto::JOINED_GROUP,
|
||||
proto::joined_group(Some(group), false),
|
||||
);
|
||||
self.changed.insert(player);
|
||||
if let Some(old) = old
|
||||
&& old != group
|
||||
{
|
||||
self.leave_group_cleanup(old);
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty group goes away.
|
||||
fn leave_group_cleanup(&mut self, group: u128) {
|
||||
if self.clients.values().any(|c| c.group == Some(group)) {
|
||||
return;
|
||||
}
|
||||
if self.groups.remove(&group).is_some() {
|
||||
self.tell_all(proto::REMOVE_GROUP, proto::remove_group(group));
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&mut self, uuid: u128) {
|
||||
self.outbox.remove(&uuid);
|
||||
self.changed.remove(&uuid);
|
||||
let Some(c) = self.clients.remove(&uuid) else {
|
||||
return;
|
||||
};
|
||||
self.tell_all(proto::REMOVE_STATE, proto::remove_state(uuid));
|
||||
if let Some(g) = c.group {
|
||||
self.leave_group_cleanup(g);
|
||||
}
|
||||
}
|
||||
|
||||
/// Who hears `sender`, and how: (listener, address, positional range or None for the group's voice).
|
||||
fn listeners(&self, sender: u128, whispering: bool) -> Vec<(u128, SocketAddr, Option<f64>)> {
|
||||
let Some(from) = self.clients.get(&sender) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let from_kind = from.group.and_then(|g| self.groups.get(&g)).map(|g| g.kind);
|
||||
let at = self.players.get(&sender);
|
||||
let range = if whispering {
|
||||
self.config.whisper_distance
|
||||
} else {
|
||||
self.config.distance
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (uuid, c) in &self.clients {
|
||||
if *uuid == sender || c.disabled || !c.connected {
|
||||
continue;
|
||||
}
|
||||
let Some(addr) = c.addr else { continue };
|
||||
if from.group.is_some() && from.group == c.group {
|
||||
out.push((*uuid, addr, None));
|
||||
continue;
|
||||
}
|
||||
let to_kind = c.group.and_then(|g| self.groups.get(&g)).map(|g| g.kind);
|
||||
// Normal and isolated groups aren't heard outside; isolated ones hear nobody outside.
|
||||
if matches!(from_kind, Some(GroupKind::Normal | GroupKind::Isolated))
|
||||
|| to_kind == Some(GroupKind::Isolated)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (Some(a), Some(b)) = (at, self.players.get(uuid)) else {
|
||||
continue;
|
||||
};
|
||||
if a.dimension != b.dimension {
|
||||
continue;
|
||||
}
|
||||
let d = (0..3)
|
||||
.map(|i| (a.position[i] - b.position[i]).powi(2))
|
||||
.sum::<f64>()
|
||||
.sqrt();
|
||||
if d <= range {
|
||||
out.push((*uuid, addr, Some(range)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The UDP side: handshakes, keep-alives and voices.
|
||||
fn relay(shared: &Shared) {
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let mut last_keep_alive = Instant::now();
|
||||
while shared.running.load(Ordering::Relaxed) {
|
||||
match shared.socket.recv_from(&mut buf) {
|
||||
Ok((n, from)) => datagram(shared, &buf[..n], from),
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
|
||||
) => {}
|
||||
// Never spin on an error that comes back at once.
|
||||
Err(_) => std::thread::sleep(Duration::from_millis(10)),
|
||||
}
|
||||
let every = Duration::from_millis(u64::from(
|
||||
lock(&shared.state).config.keep_alive_ms.clamp(100, 60_000),
|
||||
));
|
||||
if last_keep_alive.elapsed() >= every {
|
||||
last_keep_alive = Instant::now();
|
||||
keep_alive(shared, every);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send(shared: &Shared, cipher: &proto::Cipher, to: SocketAddr, packet: &ToClient) {
|
||||
if let Some(sealed) = cipher.seal(&shared.rng, &packet.write()) {
|
||||
let _ = shared.socket.send_to(&proto::server_datagram(&sealed), to);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep-alives to every authenticated client. One that stopped answering
|
||||
/// gets a fresh secret over the game connection: if it moved (its NAT
|
||||
/// rebound), it comes back from its new address with that secret.
|
||||
fn keep_alive(shared: &Shared, every: Duration) {
|
||||
let mut st = lock(&shared.state);
|
||||
let mut lost = Vec::new();
|
||||
for (uuid, c) in st.clients.iter_mut() {
|
||||
let Some(addr) = c.addr else { continue };
|
||||
if c.connected && c.last_keep_alive.elapsed() > every * 10 {
|
||||
c.connected = false;
|
||||
lost.push(*uuid);
|
||||
continue;
|
||||
}
|
||||
send(shared, &c.cipher, addr, &ToClient::KeepAlive);
|
||||
}
|
||||
for uuid in lost {
|
||||
st.give_secret(&shared.rng, uuid, true);
|
||||
}
|
||||
}
|
||||
|
||||
fn datagram(shared: &Shared, datagram: &[u8], from: SocketAddr) {
|
||||
let Ok((player, sealed)) = proto::client_datagram(datagram) else {
|
||||
return;
|
||||
};
|
||||
let mut st = lock(&shared.state);
|
||||
let Some(c) = st.clients.get_mut(&player) else {
|
||||
return;
|
||||
};
|
||||
let Some(plain) = c.cipher.open(sealed) else {
|
||||
return;
|
||||
};
|
||||
let Ok(packet) = FromClient::read(&plain) else {
|
||||
return;
|
||||
};
|
||||
// It opened, so it holds at least a nonce and a tag.
|
||||
let mut nonce = [0u8; 12];
|
||||
nonce.copy_from_slice(&sealed[..12]);
|
||||
let now = Instant::now();
|
||||
if let FromClient::Authenticate {
|
||||
player: who,
|
||||
secret,
|
||||
} = packet
|
||||
{
|
||||
if who != player || !constant_eq(&secret, &c.secret) {
|
||||
return;
|
||||
}
|
||||
// The secret belongs to the first address that authenticated with it.
|
||||
if c.addr.is_some_and(|a| a != from) || !c.fresh_nonce(nonce) {
|
||||
return;
|
||||
}
|
||||
c.addr = Some(from);
|
||||
send(shared, &c.cipher, from, &ToClient::AuthenticateAck);
|
||||
return;
|
||||
}
|
||||
// Everything else only from the address that authenticated.
|
||||
if c.addr != Some(from) {
|
||||
return;
|
||||
}
|
||||
if let FromClient::Mic { sequence, .. } = packet {
|
||||
if !c.fresh_sequence(sequence) {
|
||||
return;
|
||||
}
|
||||
} else if !c.fresh_nonce(nonce) {
|
||||
return;
|
||||
}
|
||||
match packet {
|
||||
FromClient::ConnectionCheck => {
|
||||
c.last_keep_alive = now;
|
||||
if !c.connected {
|
||||
c.connected = true;
|
||||
st.changed.insert(player);
|
||||
}
|
||||
let c = &st.clients[&player];
|
||||
send(shared, &c.cipher, from, &ToClient::ConnectionCheckAck);
|
||||
}
|
||||
FromClient::KeepAlive => {
|
||||
c.last_keep_alive = now;
|
||||
if !c.connected {
|
||||
c.connected = true;
|
||||
st.changed.insert(player);
|
||||
}
|
||||
}
|
||||
// The server never pings, so this isn't an answer: not echoed (a
|
||||
// client that echoes pings would otherwise bounce it forever).
|
||||
FromClient::Ping { .. } => {}
|
||||
FromClient::Mic {
|
||||
data,
|
||||
sequence,
|
||||
whispering,
|
||||
} => {
|
||||
if c.disabled || !c.connected {
|
||||
return;
|
||||
}
|
||||
c.tokens = (c.tokens + now.duration_since(c.refilled).as_secs_f64() * MIC_PER_SECOND)
|
||||
.min(MIC_BURST);
|
||||
c.refilled = now;
|
||||
if c.tokens < 1.0 {
|
||||
return;
|
||||
}
|
||||
c.tokens -= 1.0;
|
||||
for (listener, addr, range) in st.listeners(player, whispering) {
|
||||
let packet = match range {
|
||||
Some(r) => ToClient::Positional {
|
||||
sender: player,
|
||||
data: &data,
|
||||
sequence,
|
||||
distance: r as f32,
|
||||
whispering,
|
||||
},
|
||||
None => ToClient::Group {
|
||||
sender: player,
|
||||
data: &data,
|
||||
sequence,
|
||||
},
|
||||
};
|
||||
send(shared, &st.clients[&listener].cipher, addr, &packet);
|
||||
}
|
||||
}
|
||||
FromClient::Authenticate { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn constant_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,734 @@
|
||||
//! The voice chat wire format Simple Voice Chat 2.6.x clients speak
|
||||
//! (compatibility version 20), from the server's side: control messages on
|
||||
//! `voicechat:` channels over the game connection, and AES-128-GCM UDP
|
||||
//! datagrams for the voice itself.
|
||||
//!
|
||||
//! Numbers are big-endian, a UUID is 16 bytes (most significant half first),
|
||||
//! strings and byte arrays are a VarInt length then the bytes.
|
||||
|
||||
/// The only version this server speaks.
|
||||
pub const COMPATIBILITY_VERSION: i32 = 20;
|
||||
/// Every UDP datagram starts with it.
|
||||
pub const MAGIC: u8 = 0xFF;
|
||||
/// The largest Opus frame relayed.
|
||||
pub const MAX_OPUS: usize = 1275;
|
||||
/// The largest encrypted body read from a datagram.
|
||||
pub const MAX_BODY: usize = 2048;
|
||||
/// Group names and passwords, in characters.
|
||||
pub const MAX_GROUP_TEXT: usize = 24;
|
||||
|
||||
pub const REQUEST_SECRET: &str = "voicechat:request_secret";
|
||||
pub const SECRET: &str = "voicechat:secret";
|
||||
pub const UPDATE_STATE: &str = "voicechat:update_state";
|
||||
pub const STATE: &str = "voicechat:state";
|
||||
pub const STATES: &str = "voicechat:states";
|
||||
pub const REMOVE_STATE: &str = "voicechat:remove_state";
|
||||
pub const CREATE_GROUP: &str = "voicechat:create_group";
|
||||
pub const SET_GROUP: &str = "voicechat:set_group";
|
||||
pub const LEAVE_GROUP: &str = "voicechat:leave_group";
|
||||
pub const JOINED_GROUP: &str = "voicechat:joined_group";
|
||||
pub const ADD_GROUP: &str = "voicechat:add_group";
|
||||
pub const REMOVE_GROUP: &str = "voicechat:remove_group";
|
||||
|
||||
/// A message that can't be read.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Malformed;
|
||||
|
||||
type Read<T> = Result<T, Malformed>;
|
||||
|
||||
pub struct In<'a> {
|
||||
rest: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> In<'a> {
|
||||
pub fn new(data: &'a [u8]) -> Self {
|
||||
Self { rest: data }
|
||||
}
|
||||
pub fn take(&mut self, n: usize) -> Read<&'a [u8]> {
|
||||
if self.rest.len() < n {
|
||||
return Err(Malformed);
|
||||
}
|
||||
let (head, tail) = self.rest.split_at(n);
|
||||
self.rest = tail;
|
||||
Ok(head)
|
||||
}
|
||||
fn fixed<const N: usize>(&mut self) -> Read<[u8; N]> {
|
||||
let mut out = [0; N];
|
||||
out.copy_from_slice(self.take(N)?);
|
||||
Ok(out)
|
||||
}
|
||||
pub fn byte(&mut self) -> Read<u8> {
|
||||
Ok(self.take(1)?[0])
|
||||
}
|
||||
pub fn flag(&mut self) -> Read<bool> {
|
||||
Ok(self.byte()? != 0)
|
||||
}
|
||||
pub fn short(&mut self) -> Read<i16> {
|
||||
Ok(i16::from_be_bytes(self.fixed()?))
|
||||
}
|
||||
pub fn int(&mut self) -> Read<i32> {
|
||||
Ok(i32::from_be_bytes(self.fixed()?))
|
||||
}
|
||||
pub fn long(&mut self) -> Read<i64> {
|
||||
Ok(i64::from_be_bytes(self.fixed()?))
|
||||
}
|
||||
pub fn uuid(&mut self) -> Read<u128> {
|
||||
Ok(u128::from_be_bytes(self.fixed()?))
|
||||
}
|
||||
pub fn varint(&mut self) -> Read<i32> {
|
||||
let mut value = 0u32;
|
||||
for shift in 0..5 {
|
||||
let b = self.byte()?;
|
||||
value |= u32::from(b & 0x7F) << (shift * 7);
|
||||
if b & 0x80 == 0 {
|
||||
return Ok(value as i32);
|
||||
}
|
||||
}
|
||||
Err(Malformed)
|
||||
}
|
||||
/// A VarInt length of at most `max`, then that many bytes.
|
||||
pub fn bytes(&mut self, max: usize) -> Read<&'a [u8]> {
|
||||
let n = usize::try_from(self.varint()?).map_err(|_| Malformed)?;
|
||||
if n > max {
|
||||
return Err(Malformed);
|
||||
}
|
||||
self.take(n)
|
||||
}
|
||||
/// A string of at most `max` characters.
|
||||
pub fn text(&mut self, max: usize) -> Read<String> {
|
||||
let raw = self.bytes(max.saturating_mul(4))?;
|
||||
let s = std::str::from_utf8(raw).map_err(|_| Malformed)?;
|
||||
if s.chars().count() > max {
|
||||
return Err(Malformed);
|
||||
}
|
||||
Ok(s.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Out(pub Vec<u8>);
|
||||
|
||||
impl Out {
|
||||
pub fn byte(&mut self, v: u8) -> &mut Self {
|
||||
self.0.push(v);
|
||||
self
|
||||
}
|
||||
pub fn flag(&mut self, v: bool) -> &mut Self {
|
||||
self.byte(u8::from(v))
|
||||
}
|
||||
pub fn short(&mut self, v: i16) -> &mut Self {
|
||||
self.0.extend(v.to_be_bytes());
|
||||
self
|
||||
}
|
||||
pub fn int(&mut self, v: i32) -> &mut Self {
|
||||
self.0.extend(v.to_be_bytes());
|
||||
self
|
||||
}
|
||||
pub fn long(&mut self, v: i64) -> &mut Self {
|
||||
self.0.extend(v.to_be_bytes());
|
||||
self
|
||||
}
|
||||
pub fn float(&mut self, v: f32) -> &mut Self {
|
||||
self.0.extend(v.to_be_bytes());
|
||||
self
|
||||
}
|
||||
pub fn double(&mut self, v: f64) -> &mut Self {
|
||||
self.0.extend(v.to_be_bytes());
|
||||
self
|
||||
}
|
||||
pub fn uuid(&mut self, v: u128) -> &mut Self {
|
||||
self.0.extend(v.to_be_bytes());
|
||||
self
|
||||
}
|
||||
pub fn varint(&mut self, v: i32) -> &mut Self {
|
||||
let mut v = v as u32;
|
||||
while v >= 0x80 {
|
||||
self.0.push((v as u8) | 0x80);
|
||||
v >>= 7;
|
||||
}
|
||||
self.0.push(v as u8);
|
||||
self
|
||||
}
|
||||
pub fn bytes(&mut self, b: &[u8]) -> &mut Self {
|
||||
self.varint(b.len() as i32);
|
||||
self.0.extend_from_slice(b);
|
||||
self
|
||||
}
|
||||
pub fn text(&mut self, s: &str) -> &mut Self {
|
||||
self.bytes(s.as_bytes())
|
||||
}
|
||||
pub fn done(&mut self) -> Vec<u8> {
|
||||
std::mem::take(&mut self.0)
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the game connection
|
||||
|
||||
/// How a group hears the world.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GroupKind {
|
||||
/// Members hear each other anywhere and players nearby; nobody outside hears them.
|
||||
Normal,
|
||||
/// Members hear each other anywhere; players nearby hear them and are heard.
|
||||
Open,
|
||||
/// Members hear only each other.
|
||||
Isolated,
|
||||
}
|
||||
|
||||
impl GroupKind {
|
||||
pub fn from_wire(v: i16) -> Self {
|
||||
match v {
|
||||
1 => Self::Open,
|
||||
2 => Self::Isolated,
|
||||
_ => Self::Normal,
|
||||
}
|
||||
}
|
||||
pub fn wire(self) -> i16 {
|
||||
match self {
|
||||
Self::Normal => 0,
|
||||
Self::Open => 1,
|
||||
Self::Isolated => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a client asks on a `voicechat:` channel.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Request {
|
||||
Secret {
|
||||
version: i32,
|
||||
},
|
||||
State {
|
||||
disabled: bool,
|
||||
},
|
||||
CreateGroup {
|
||||
name: String,
|
||||
password: Option<String>,
|
||||
kind: GroupKind,
|
||||
},
|
||||
JoinGroup {
|
||||
group: u128,
|
||||
password: Option<String>,
|
||||
},
|
||||
LeaveGroup,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
/// None: not a channel a client sends on.
|
||||
pub fn read(channel: &str, data: &[u8]) -> Option<Read<Self>> {
|
||||
let mut r = In::new(data);
|
||||
let parsed = match channel {
|
||||
REQUEST_SECRET => r.int().map(|version| Self::Secret { version }),
|
||||
UPDATE_STATE => r.flag().map(|disabled| Self::State { disabled }),
|
||||
CREATE_GROUP => (|| {
|
||||
let name = r.text(MAX_GROUP_TEXT)?;
|
||||
let password = if r.flag()? {
|
||||
Some(r.text(MAX_GROUP_TEXT)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let kind = GroupKind::from_wire(r.short()?);
|
||||
Ok(Self::CreateGroup {
|
||||
name,
|
||||
password,
|
||||
kind,
|
||||
})
|
||||
})(),
|
||||
SET_GROUP => (|| {
|
||||
let group = r.uuid()?;
|
||||
let password = if r.flag()? {
|
||||
Some(r.text(MAX_GROUP_TEXT)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Self::JoinGroup { group, password })
|
||||
})(),
|
||||
LEAVE_GROUP => Ok(Self::LeaveGroup),
|
||||
_ => return None,
|
||||
};
|
||||
Some(parsed)
|
||||
}
|
||||
}
|
||||
|
||||
/// `voicechat:secret`: what the client needs to open its voice connection.
|
||||
pub struct SecretInfo<'a> {
|
||||
pub secret: &'a [u8; 16],
|
||||
pub port: u16,
|
||||
pub player: u128,
|
||||
pub mtu: i32,
|
||||
pub distance: f64,
|
||||
pub keep_alive_ms: i32,
|
||||
pub groups: bool,
|
||||
/// Empty: the game server's own address.
|
||||
pub voice_host: &'a str,
|
||||
}
|
||||
|
||||
pub fn secret(s: &SecretInfo) -> Vec<u8> {
|
||||
let mut o = Out::default();
|
||||
o.0.extend_from_slice(s.secret);
|
||||
o.int(i32::from(s.port))
|
||||
.uuid(s.player)
|
||||
.byte(0) // the Opus application: VoIP
|
||||
.int(s.mtu)
|
||||
.double(s.distance)
|
||||
.int(s.keep_alive_ms)
|
||||
.flag(s.groups)
|
||||
.text(s.voice_host)
|
||||
.flag(false) // recording not allowed
|
||||
.done()
|
||||
}
|
||||
|
||||
/// A player's voice chat state, as `voicechat:state` and each of `voicechat:states` carry it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PlayerState {
|
||||
pub uuid: u128,
|
||||
pub name: String,
|
||||
pub disabled: bool,
|
||||
pub disconnected: bool,
|
||||
pub group: Option<u128>,
|
||||
}
|
||||
|
||||
fn put_state(o: &mut Out, s: &PlayerState) {
|
||||
o.flag(s.disabled)
|
||||
.flag(s.disconnected)
|
||||
.uuid(s.uuid)
|
||||
.text(&s.name)
|
||||
.flag(s.group.is_some());
|
||||
if let Some(g) = s.group {
|
||||
o.uuid(g);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state(s: &PlayerState) -> Vec<u8> {
|
||||
let mut o = Out::default();
|
||||
put_state(&mut o, s);
|
||||
o.done()
|
||||
}
|
||||
|
||||
pub fn states(all: &[PlayerState]) -> Vec<u8> {
|
||||
let mut o = Out::default();
|
||||
o.int(all.len() as i32);
|
||||
for s in all {
|
||||
put_state(&mut o, s);
|
||||
}
|
||||
o.done()
|
||||
}
|
||||
|
||||
pub fn remove_state(uuid: u128) -> Vec<u8> {
|
||||
Out::default().uuid(uuid).done()
|
||||
}
|
||||
|
||||
pub fn add_group(id: u128, name: &str, has_password: bool, kind: GroupKind) -> Vec<u8> {
|
||||
Out::default()
|
||||
.uuid(id)
|
||||
.text(name)
|
||||
.flag(has_password)
|
||||
.flag(false) // persistent
|
||||
.flag(false) // hidden
|
||||
.short(kind.wire())
|
||||
.done()
|
||||
}
|
||||
|
||||
pub fn remove_group(id: u128) -> Vec<u8> {
|
||||
Out::default().uuid(id).done()
|
||||
}
|
||||
|
||||
pub fn joined_group(group: Option<u128>, wrong_password: bool) -> Vec<u8> {
|
||||
let mut o = Out::default();
|
||||
o.flag(group.is_some());
|
||||
if let Some(g) = group {
|
||||
o.uuid(g);
|
||||
}
|
||||
o.flag(wrong_password).done()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ UDP
|
||||
|
||||
/// A voice packet a client sends.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum FromClient {
|
||||
/// The microphone: an Opus frame (empty: stopped talking).
|
||||
Mic {
|
||||
data: Vec<u8>,
|
||||
sequence: i64,
|
||||
whispering: bool,
|
||||
},
|
||||
Authenticate {
|
||||
player: u128,
|
||||
secret: [u8; 16],
|
||||
},
|
||||
Ping {
|
||||
id: u128,
|
||||
timestamp: i64,
|
||||
},
|
||||
KeepAlive,
|
||||
ConnectionCheck,
|
||||
}
|
||||
|
||||
impl FromClient {
|
||||
pub fn read(plain: &[u8]) -> Read<Self> {
|
||||
let mut r = In::new(plain);
|
||||
Ok(match r.byte()? {
|
||||
1 => Self::Mic {
|
||||
data: r.bytes(MAX_OPUS)?.to_vec(),
|
||||
sequence: r.long()?,
|
||||
whispering: r.flag()?,
|
||||
},
|
||||
5 => Self::Authenticate {
|
||||
player: r.uuid()?,
|
||||
secret: r.fixed()?,
|
||||
},
|
||||
7 => Self::Ping {
|
||||
id: r.uuid()?,
|
||||
timestamp: r.long()?,
|
||||
},
|
||||
8 => Self::KeepAlive,
|
||||
9 => Self::ConnectionCheck,
|
||||
_ => return Err(Malformed),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A voice packet this server sends.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ToClient<'a> {
|
||||
/// A voice heard where `sender` stands.
|
||||
Positional {
|
||||
sender: u128,
|
||||
data: &'a [u8],
|
||||
sequence: i64,
|
||||
distance: f32,
|
||||
whispering: bool,
|
||||
},
|
||||
/// A group member's voice, heard everywhere.
|
||||
Group {
|
||||
sender: u128,
|
||||
data: &'a [u8],
|
||||
sequence: i64,
|
||||
},
|
||||
AuthenticateAck,
|
||||
Ping {
|
||||
id: u128,
|
||||
timestamp: i64,
|
||||
},
|
||||
KeepAlive,
|
||||
ConnectionCheckAck,
|
||||
}
|
||||
|
||||
impl ToClient<'_> {
|
||||
pub fn write(&self) -> Vec<u8> {
|
||||
let mut o = Out::default();
|
||||
match self {
|
||||
// The channel is the sender: the client places a positional voice at that entity.
|
||||
Self::Positional {
|
||||
sender,
|
||||
data,
|
||||
sequence,
|
||||
distance,
|
||||
whispering,
|
||||
} => o
|
||||
.byte(2)
|
||||
.uuid(*sender)
|
||||
.uuid(*sender)
|
||||
.bytes(data)
|
||||
.long(*sequence)
|
||||
.float(*distance)
|
||||
.flag(*whispering),
|
||||
Self::Group {
|
||||
sender,
|
||||
data,
|
||||
sequence,
|
||||
} => o
|
||||
.byte(3)
|
||||
.uuid(*sender)
|
||||
.uuid(*sender)
|
||||
.bytes(data)
|
||||
.long(*sequence)
|
||||
.byte(0),
|
||||
Self::AuthenticateAck => o.byte(6),
|
||||
Self::Ping { id, timestamp } => o.byte(7).uuid(*id).long(*timestamp),
|
||||
Self::KeepAlive => o.byte(8),
|
||||
Self::ConnectionCheckAck => o.byte(10),
|
||||
};
|
||||
o.done()
|
||||
}
|
||||
}
|
||||
|
||||
/// AES-128-GCM keyed by a player's secret: a random 12-byte nonce, then the
|
||||
/// ciphertext and its 16-byte tag.
|
||||
pub struct Cipher {
|
||||
key: ring::aead::LessSafeKey,
|
||||
}
|
||||
|
||||
impl Cipher {
|
||||
pub fn new(secret: &[u8; 16]) -> Self {
|
||||
let key =
|
||||
ring::aead::UnboundKey::new(&ring::aead::AES_128_GCM, secret).expect("a 16-byte key");
|
||||
Self {
|
||||
key: ring::aead::LessSafeKey::new(key),
|
||||
}
|
||||
}
|
||||
pub fn seal(&self, rng: &dyn ring::rand::SecureRandom, plain: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut nonce = [0u8; 12];
|
||||
rng.fill(&mut nonce).ok()?;
|
||||
let mut body = plain.to_vec();
|
||||
self.key
|
||||
.seal_in_place_append_tag(
|
||||
ring::aead::Nonce::assume_unique_for_key(nonce),
|
||||
ring::aead::Aad::empty(),
|
||||
&mut body,
|
||||
)
|
||||
.ok()?;
|
||||
let mut out = nonce.to_vec();
|
||||
out.extend(body);
|
||||
Some(out)
|
||||
}
|
||||
pub fn open(&self, sealed: &[u8]) -> Option<Vec<u8>> {
|
||||
if sealed.len() < 12 + 16 {
|
||||
return None;
|
||||
}
|
||||
let (nonce, body) = sealed.split_at(12);
|
||||
let nonce = ring::aead::Nonce::try_assume_unique_for_key(nonce).ok()?;
|
||||
let mut body = body.to_vec();
|
||||
let plain = self
|
||||
.key
|
||||
.open_in_place(nonce, ring::aead::Aad::empty(), &mut body)
|
||||
.ok()?;
|
||||
Some(plain.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
/// A client's datagram: magic, the player's UUID (in clear, to find their key), the sealed packet.
|
||||
pub fn client_datagram(datagram: &[u8]) -> Read<(u128, &[u8])> {
|
||||
let mut r = In::new(datagram);
|
||||
if r.byte()? != MAGIC {
|
||||
return Err(Malformed);
|
||||
}
|
||||
let player = r.uuid()?;
|
||||
Ok((player, r.bytes(MAX_BODY)?))
|
||||
}
|
||||
|
||||
/// A server datagram: magic, then the sealed packet.
|
||||
pub fn server_datagram(sealed: &[u8]) -> Vec<u8> {
|
||||
Out::default().byte(MAGIC).bytes(sealed).done()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn varints_match_minecraft() {
|
||||
for (v, bytes) in [
|
||||
(0, vec![0]),
|
||||
(127, vec![0x7F]),
|
||||
(128, vec![0x80, 1]),
|
||||
(300, vec![0xAC, 2]),
|
||||
(-1, vec![0xFF, 0xFF, 0xFF, 0xFF, 0x0F]),
|
||||
] {
|
||||
assert_eq!(Out::default().varint(v).done(), bytes, "{v}");
|
||||
assert_eq!(In::new(&bytes).varint().unwrap(), v);
|
||||
}
|
||||
assert_eq!(In::new(&[0x80; 6]).varint(), Err(Malformed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_read_their_layouts() {
|
||||
assert_eq!(
|
||||
Request::read(REQUEST_SECRET, &[0, 0, 0, 20]),
|
||||
Some(Ok(Request::Secret { version: 20 }))
|
||||
);
|
||||
assert_eq!(
|
||||
Request::read(UPDATE_STATE, &[1]),
|
||||
Some(Ok(Request::State { disabled: true }))
|
||||
);
|
||||
// name "ab", a password "x", kind open.
|
||||
assert_eq!(
|
||||
Request::read(CREATE_GROUP, &[2, b'a', b'b', 1, 1, b'x', 0, 1]),
|
||||
Some(Ok(Request::CreateGroup {
|
||||
name: "ab".into(),
|
||||
password: Some("x".into()),
|
||||
kind: GroupKind::Open
|
||||
}))
|
||||
);
|
||||
let mut join = 7u128.to_be_bytes().to_vec();
|
||||
join.push(0);
|
||||
assert_eq!(
|
||||
Request::read(SET_GROUP, &join),
|
||||
Some(Ok(Request::JoinGroup {
|
||||
group: 7,
|
||||
password: None
|
||||
}))
|
||||
);
|
||||
assert_eq!(
|
||||
Request::read(LEAVE_GROUP, &[]),
|
||||
Some(Ok(Request::LeaveGroup))
|
||||
);
|
||||
assert_eq!(
|
||||
Request::read("voicechat:secret", &[]),
|
||||
None,
|
||||
"a server's channel"
|
||||
);
|
||||
let long = [&[30u8][..], &[b'n'; 30]].concat();
|
||||
assert_eq!(
|
||||
Request::read(CREATE_GROUP, &[&long[..], &[0, 0, 0]].concat()),
|
||||
Some(Err(Malformed))
|
||||
);
|
||||
assert_eq!(Request::read(REQUEST_SECRET, &[0, 0]), Some(Err(Malformed)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_layout() {
|
||||
let key = [9u8; 16];
|
||||
let bytes = secret(&SecretInfo {
|
||||
secret: &key,
|
||||
port: 24454,
|
||||
player: 0xAB,
|
||||
mtu: 1024,
|
||||
distance: 48.0,
|
||||
keep_alive_ms: 1000,
|
||||
groups: true,
|
||||
voice_host: "",
|
||||
});
|
||||
// key, port, uuid, codec, mtu, distance, keep-alive, groups, "" , recording
|
||||
assert_eq!(bytes.len(), 16 + 4 + 16 + 1 + 4 + 8 + 4 + 1 + 1 + 1);
|
||||
assert_eq!(&bytes[..16], &key);
|
||||
assert_eq!(&bytes[16..20], &24454i32.to_be_bytes());
|
||||
assert_eq!(&bytes[20..36], &0xABu128.to_be_bytes());
|
||||
assert_eq!(&bytes[41..49], &48.0f64.to_be_bytes());
|
||||
assert_eq!(bytes[53], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_and_groups_layouts() {
|
||||
let a = PlayerState {
|
||||
uuid: 1,
|
||||
name: "a".into(),
|
||||
disabled: true,
|
||||
disconnected: false,
|
||||
group: Some(2),
|
||||
};
|
||||
assert_eq!(
|
||||
state(&a),
|
||||
[
|
||||
&[1u8, 0][..],
|
||||
&1u128.to_be_bytes(),
|
||||
&[1, b'a', 1],
|
||||
&2u128.to_be_bytes()
|
||||
]
|
||||
.concat()
|
||||
);
|
||||
let both = states(&[
|
||||
a.clone(),
|
||||
PlayerState {
|
||||
group: None,
|
||||
..a.clone()
|
||||
},
|
||||
]);
|
||||
assert_eq!(&both[..4], &2i32.to_be_bytes());
|
||||
assert_eq!(both.len(), 4 + 37 + 21);
|
||||
let g = add_group(5, "Base", true, GroupKind::Isolated);
|
||||
assert_eq!(
|
||||
g,
|
||||
[
|
||||
&5u128.to_be_bytes()[..],
|
||||
&[4, b'B', b'a', b's', b'e', 1, 0, 0, 0, 2]
|
||||
]
|
||||
.concat()
|
||||
);
|
||||
assert_eq!(joined_group(None, true), vec![0, 1]);
|
||||
assert_eq!(
|
||||
joined_group(Some(3), false),
|
||||
[&[1u8][..], &3u128.to_be_bytes(), &[0]].concat()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voice_packets() {
|
||||
let mic = [&[1u8, 2, 0xAA, 0xBB][..], &5i64.to_be_bytes(), &[1]].concat();
|
||||
assert_eq!(
|
||||
FromClient::read(&mic),
|
||||
Ok(FromClient::Mic {
|
||||
data: vec![0xAA, 0xBB],
|
||||
sequence: 5,
|
||||
whispering: true
|
||||
})
|
||||
);
|
||||
let auth = [&[5u8][..], &7u128.to_be_bytes(), &[3; 16]].concat();
|
||||
assert_eq!(
|
||||
FromClient::read(&auth),
|
||||
Ok(FromClient::Authenticate {
|
||||
player: 7,
|
||||
secret: [3; 16]
|
||||
})
|
||||
);
|
||||
assert_eq!(FromClient::read(&[8]), Ok(FromClient::KeepAlive));
|
||||
assert_eq!(FromClient::read(&[9]), Ok(FromClient::ConnectionCheck));
|
||||
assert_eq!(FromClient::read(&[2]), Err(Malformed), "a server's packet");
|
||||
let big = [
|
||||
&[1u8][..],
|
||||
&Out::default().varint(1276).done(),
|
||||
&[0; 1276],
|
||||
&[0; 9],
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(FromClient::read(&big), Err(Malformed));
|
||||
|
||||
let sound = ToClient::Positional {
|
||||
sender: 4,
|
||||
data: &[1, 2],
|
||||
sequence: 9,
|
||||
distance: 48.0,
|
||||
whispering: false,
|
||||
}
|
||||
.write();
|
||||
assert_eq!(sound[0], 2);
|
||||
assert_eq!(&sound[1..17], &4u128.to_be_bytes());
|
||||
assert_eq!(&sound[17..33], &4u128.to_be_bytes());
|
||||
assert_eq!(&sound[33..36], &[2, 1, 2]);
|
||||
assert_eq!(&sound[36..44], &9i64.to_be_bytes());
|
||||
assert_eq!(&sound[44..48], &48.0f32.to_be_bytes());
|
||||
assert_eq!(sound[48], 0);
|
||||
assert_eq!(sound.len(), 49);
|
||||
let group = ToClient::Group {
|
||||
sender: 4,
|
||||
data: &[1],
|
||||
sequence: 2,
|
||||
}
|
||||
.write();
|
||||
assert_eq!(
|
||||
(group[0], group.len(), group[group.len() - 1]),
|
||||
(3, 1 + 32 + 2 + 8 + 1, 0)
|
||||
);
|
||||
assert_eq!(ToClient::AuthenticateAck.write(), vec![6]);
|
||||
assert_eq!(ToClient::ConnectionCheckAck.write(), vec![10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sealed_bodies_round_trip_and_reject_tampering() {
|
||||
let rng = ring::rand::SystemRandom::new();
|
||||
let c = Cipher::new(&[1; 16]);
|
||||
let sealed = c.seal(&rng, b"hello").unwrap();
|
||||
assert_eq!(sealed.len(), 12 + 5 + 16);
|
||||
assert_eq!(c.open(&sealed).unwrap(), b"hello");
|
||||
let mut bad = sealed.clone();
|
||||
bad[14] ^= 1;
|
||||
assert_eq!(c.open(&bad), None);
|
||||
assert_eq!(Cipher::new(&[2; 16]).open(&sealed), None);
|
||||
assert_ne!(
|
||||
c.seal(&rng, b"hello").unwrap(),
|
||||
sealed,
|
||||
"fresh nonce each time"
|
||||
);
|
||||
|
||||
let datagram = [
|
||||
&[MAGIC][..],
|
||||
&9u128.to_be_bytes(),
|
||||
&Out::default().bytes(&sealed).done(),
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(client_datagram(&datagram), Ok((9, &sealed[..])));
|
||||
assert_eq!(client_datagram(&datagram[1..]), Err(Malformed));
|
||||
assert_eq!(server_datagram(&[1, 2])[..], [MAGIC, 2, 1, 2]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
//! The relay with real UDP sockets on localhost: clients that speak the
|
||||
//! wire format the way a voice chat client does, written from the layouts.
|
||||
use super::*;
|
||||
use proto::{In, Out};
|
||||
|
||||
const A: u128 = 0xA;
|
||||
const B: u128 = 0xB;
|
||||
const FAR: u128 = 0xC;
|
||||
const NETHER: u128 = 0xD;
|
||||
const PLAIN: u128 = 0xE;
|
||||
|
||||
fn player(uuid: u128, name: &str, dimension: &str, x: f64) -> Player {
|
||||
Player {
|
||||
uuid,
|
||||
name: name.into(),
|
||||
dimension: dimension.into(),
|
||||
position: [x, 64.0, 0.0],
|
||||
}
|
||||
}
|
||||
|
||||
fn world() -> Vec<Player> {
|
||||
vec![
|
||||
player(A, "alice", "minecraft:overworld", 0.0),
|
||||
player(B, "bob", "minecraft:overworld", 10.0),
|
||||
player(FAR, "carol", "minecraft:overworld", 500.0),
|
||||
player(NETHER, "dave", "minecraft:the_nether", 0.0),
|
||||
// Joined without a voice chat client: never asks, never told.
|
||||
player(PLAIN, "erin", "minecraft:overworld", 5.0),
|
||||
]
|
||||
}
|
||||
|
||||
fn server() -> Server {
|
||||
server_with(Config::default())
|
||||
}
|
||||
|
||||
fn server_with(config: Config) -> Server {
|
||||
let s = Server::start(Config {
|
||||
bind: "127.0.0.1".into(),
|
||||
port: 0,
|
||||
..config
|
||||
})
|
||||
.unwrap();
|
||||
s.tick(world());
|
||||
s
|
||||
}
|
||||
|
||||
/// The messages for `who` among `all`.
|
||||
fn for_player(all: &[Message], who: u128) -> Vec<(String, Vec<u8>)> {
|
||||
all.iter()
|
||||
.filter(|m| m.0 == who)
|
||||
.map(|m| (m.1.clone(), m.2.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Voice {
|
||||
uuid: u128,
|
||||
secret: [u8; 16],
|
||||
cipher: proto::Cipher,
|
||||
socket: UdpSocket,
|
||||
server: SocketAddr,
|
||||
rng: SystemRandom,
|
||||
/// The datagrams of its handshake: authenticate, connection check.
|
||||
handshake: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Voice {
|
||||
/// Reads the secret the server gave, then authenticates and checks the connection.
|
||||
fn connect(uuid: u128, secret_message: &[u8]) -> Self {
|
||||
let mut r = In::new(secret_message);
|
||||
let secret: [u8; 16] = r.take(16).unwrap().try_into().unwrap();
|
||||
let port = r.int().unwrap() as u16;
|
||||
assert_eq!(r.uuid().unwrap(), uuid);
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_millis(300)))
|
||||
.unwrap();
|
||||
let mut v = Self {
|
||||
uuid,
|
||||
secret,
|
||||
cipher: proto::Cipher::new(&secret),
|
||||
socket,
|
||||
server: SocketAddr::from(([127, 0, 0, 1], port)),
|
||||
rng: SystemRandom::new(),
|
||||
handshake: Vec::new(),
|
||||
};
|
||||
let auth = v.send(
|
||||
&Out::default()
|
||||
.byte(5)
|
||||
.uuid(uuid)
|
||||
.done()
|
||||
.into_iter()
|
||||
.chain(secret)
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
assert_eq!(v.next(|p| p == [6]), Some(vec![6]), "authenticated");
|
||||
let check = v.send(&[9]);
|
||||
assert_eq!(v.next(|p| p == [10]), Some(vec![10]), "connection checked");
|
||||
v.handshake = vec![auth, check];
|
||||
v
|
||||
}
|
||||
/// Sends a sealed packet; returns the datagram.
|
||||
fn send(&self, plain: &[u8]) -> Vec<u8> {
|
||||
let sealed = self.cipher.seal(&self.rng, plain).unwrap();
|
||||
let datagram = Out::default()
|
||||
.byte(proto::MAGIC)
|
||||
.uuid(self.uuid)
|
||||
.bytes(&sealed)
|
||||
.done();
|
||||
self.socket.send_to(&datagram, self.server).unwrap();
|
||||
datagram
|
||||
}
|
||||
/// Answers keep-alives for a while, as a live client does.
|
||||
fn idle(&self, for_ms: u64) {
|
||||
let until = Instant::now() + Duration::from_millis(for_ms);
|
||||
while Instant::now() < until {
|
||||
self.next(|_| false);
|
||||
}
|
||||
}
|
||||
fn talk(&self, sequence: i64, whispering: bool) -> Vec<u8> {
|
||||
self.send(
|
||||
&Out::default()
|
||||
.byte(1)
|
||||
.bytes(&[0xAB; 40])
|
||||
.long(sequence)
|
||||
.flag(whispering)
|
||||
.done(),
|
||||
)
|
||||
}
|
||||
/// The next packet `wanted` accepts, skipping keep-alives (answered) and others; None after a quiet while.
|
||||
fn next(&self, wanted: impl Fn(&[u8]) -> bool) -> Option<Vec<u8>> {
|
||||
let mut buf = [0u8; 4096];
|
||||
let until = Instant::now() + Duration::from_millis(900);
|
||||
while Instant::now() < until {
|
||||
let Ok((n, _)) = self.socket.recv_from(&mut buf) else {
|
||||
continue;
|
||||
};
|
||||
let mut r = In::new(&buf[..n]);
|
||||
assert_eq!(r.byte().unwrap(), proto::MAGIC);
|
||||
let plain = self
|
||||
.cipher
|
||||
.open(r.bytes(4096).unwrap())
|
||||
.expect("sealed with my key");
|
||||
if plain == [8] {
|
||||
self.send(&[8]);
|
||||
}
|
||||
if wanted(&plain) {
|
||||
return Some(plain);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn hears(&self) -> Option<Vec<u8>> {
|
||||
self.next(|p| p[0] == 2 || p[0] == 3)
|
||||
}
|
||||
}
|
||||
|
||||
fn ask_secret(s: &Server, who: u128) -> Vec<u8> {
|
||||
s.message(who, proto::REQUEST_SECRET, &20i32.to_be_bytes());
|
||||
let out = s.outgoing(64);
|
||||
for_player(&out, who)
|
||||
.into_iter()
|
||||
.find(|(c, _)| c == proto::SECRET)
|
||||
.expect("a secret")
|
||||
.1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_asking_clients_hear_of_voice_chat() {
|
||||
let s = server();
|
||||
assert!(s.outgoing(64).is_empty(), "nothing before anyone asks");
|
||||
// Wrong version: no answer.
|
||||
s.message(A, proto::REQUEST_SECRET, &21i32.to_be_bytes());
|
||||
assert!(s.outgoing(64).is_empty());
|
||||
s.message(A, proto::REQUEST_SECRET, &20i32.to_be_bytes());
|
||||
s.tick(world());
|
||||
let out = s.outgoing(64);
|
||||
assert!(out.iter().all(|m| m.0 == A), "{out:?}");
|
||||
let channels: Vec<String> = for_player(&out, A).into_iter().map(|m| m.0).collect();
|
||||
assert_eq!(channels, [proto::SECRET, proto::STATES, proto::STATE]);
|
||||
// A message from someone not on the server, or garbage, is ignored.
|
||||
s.message(0xF, proto::REQUEST_SECRET, &20i32.to_be_bytes());
|
||||
s.message(B, proto::CREATE_GROUP, &[200]);
|
||||
s.tick(world());
|
||||
assert!(s.outgoing(64).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn voices_reach_who_is_near_in_the_same_dimension() {
|
||||
let s = server();
|
||||
let voices: Vec<Voice> = [A, B, FAR, NETHER]
|
||||
.iter()
|
||||
.map(|&u| Voice::connect(u, &ask_secret(&s, u)))
|
||||
.collect();
|
||||
let [a, b, far, nether] = &voices[..] else {
|
||||
unreachable!()
|
||||
};
|
||||
s.tick(world());
|
||||
let states = s.outgoing(64);
|
||||
assert!(
|
||||
for_player(&states, PLAIN).is_empty(),
|
||||
"the player without voice chat gets nothing"
|
||||
);
|
||||
|
||||
a.talk(0, false);
|
||||
let heard = b.hears().expect("bob, 10 blocks away, hears alice");
|
||||
assert_eq!(heard[0], 2, "positional");
|
||||
assert_eq!(&heard[1..17], &A.to_be_bytes(), "at alice");
|
||||
assert_eq!(&heard[33..34], &[40]);
|
||||
assert_eq!(
|
||||
&heard[heard.len() - 13..heard.len() - 5],
|
||||
&0i64.to_be_bytes()
|
||||
);
|
||||
assert_eq!(far.hears(), None, "500 blocks away");
|
||||
assert_eq!(nether.hears(), None, "another dimension");
|
||||
assert_eq!(a.hears(), None, "not your own voice");
|
||||
|
||||
// A whisper carries 24 blocks: bob at 10 still hears it; at 30 he doesn't.
|
||||
a.talk(1, true);
|
||||
assert_eq!(
|
||||
b.hears().map(|p| p[p.len() - 1]),
|
||||
Some(1),
|
||||
"whispering flag"
|
||||
);
|
||||
let mut moved = world();
|
||||
moved[1].position[0] = 30.0;
|
||||
s.tick(moved);
|
||||
a.talk(2, true);
|
||||
assert_eq!(b.hears(), None);
|
||||
a.talk(3, false);
|
||||
assert!(b.hears().is_some());
|
||||
s.tick(world());
|
||||
|
||||
// Voice chat off: bob neither hears nor is heard.
|
||||
s.message(B, proto::UPDATE_STATE, &[1]);
|
||||
a.talk(4, false);
|
||||
assert_eq!(b.hears(), None);
|
||||
b.talk(0, false);
|
||||
assert_eq!(a.hears(), None);
|
||||
s.message(B, proto::UPDATE_STATE, &[0]);
|
||||
a.talk(5, false);
|
||||
assert!(b.hears().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_follow_their_kind() {
|
||||
let s = server();
|
||||
let a = Voice::connect(A, &ask_secret(&s, A));
|
||||
let b = Voice::connect(B, &ask_secret(&s, B));
|
||||
let far = Voice::connect(FAR, &ask_secret(&s, FAR));
|
||||
s.tick(world());
|
||||
s.outgoing(64);
|
||||
|
||||
// Alice makes an isolated group with a password; carol joins it from 500 blocks.
|
||||
s.message(
|
||||
A,
|
||||
proto::CREATE_GROUP,
|
||||
&Out::default()
|
||||
.text("Base")
|
||||
.flag(true)
|
||||
.text("pw")
|
||||
.short(2)
|
||||
.done(),
|
||||
);
|
||||
let out = s.outgoing(64);
|
||||
let add = for_player(&out, FAR)
|
||||
.into_iter()
|
||||
.find(|m| m.0 == proto::ADD_GROUP)
|
||||
.expect("everyone sees the group")
|
||||
.1;
|
||||
let id = In::new(&add).uuid().unwrap();
|
||||
let joined = for_player(&out, A)
|
||||
.into_iter()
|
||||
.find(|m| m.0 == proto::JOINED_GROUP)
|
||||
.unwrap()
|
||||
.1;
|
||||
assert_eq!(joined, proto::joined_group(Some(id), false));
|
||||
|
||||
s.message(
|
||||
FAR,
|
||||
proto::SET_GROUP,
|
||||
&Out::default().uuid(id).flag(true).text("nope").done(),
|
||||
);
|
||||
let out = s.outgoing(64);
|
||||
assert_eq!(
|
||||
for_player(&out, FAR),
|
||||
vec![(
|
||||
proto::JOINED_GROUP.to_owned(),
|
||||
proto::joined_group(None, true)
|
||||
)]
|
||||
);
|
||||
s.message(
|
||||
FAR,
|
||||
proto::SET_GROUP,
|
||||
&Out::default().uuid(id).flag(true).text("pw").done(),
|
||||
);
|
||||
s.tick(world());
|
||||
s.outgoing(64);
|
||||
|
||||
a.talk(0, false);
|
||||
assert_eq!(
|
||||
far.hears().map(|p| p[0]),
|
||||
Some(3),
|
||||
"a group voice, from anywhere"
|
||||
);
|
||||
assert_eq!(b.hears(), None, "isolated: bob nearby doesn't hear alice");
|
||||
b.talk(0, false);
|
||||
assert_eq!(a.hears(), None, "isolated: alice doesn't hear bob");
|
||||
|
||||
// Both leave: the empty group goes away for everyone.
|
||||
s.message(A, proto::LEAVE_GROUP, &[]);
|
||||
s.message(FAR, proto::LEAVE_GROUP, &[]);
|
||||
let out = s.outgoing(64);
|
||||
assert!(
|
||||
for_player(&out, B).contains(&(proto::REMOVE_GROUP.to_owned(), proto::remove_group(id)))
|
||||
);
|
||||
a.talk(1, false);
|
||||
assert_eq!(b.hears().map(|p| p[0]), Some(2), "back to proximity");
|
||||
|
||||
// An open group: members are heard nearby, and hear who is nearby.
|
||||
s.message(
|
||||
A,
|
||||
proto::CREATE_GROUP,
|
||||
&Out::default().text("Open").flag(false).short(1).done(),
|
||||
);
|
||||
s.tick(world());
|
||||
s.outgoing(64);
|
||||
a.talk(2, false);
|
||||
assert_eq!(b.hears().map(|p| p[0]), Some(2));
|
||||
b.talk(1, false);
|
||||
assert_eq!(a.hears().map(|p| p[0]), Some(2));
|
||||
// A normal one: members aren't heard outside, but hear who is nearby.
|
||||
s.message(
|
||||
A,
|
||||
proto::CREATE_GROUP,
|
||||
&Out::default().text("Normal").flag(false).short(0).done(),
|
||||
);
|
||||
s.tick(world());
|
||||
s.outgoing(64);
|
||||
a.talk(3, false);
|
||||
assert_eq!(b.hears(), None);
|
||||
b.talk(2, false);
|
||||
assert_eq!(a.hears().map(|p| p[0]), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_and_strangers() {
|
||||
let s = server();
|
||||
let a = Voice::connect(A, &ask_secret(&s, A));
|
||||
let b = Voice::connect(B, &ask_secret(&s, B));
|
||||
s.tick(world());
|
||||
s.outgoing(64);
|
||||
|
||||
// Someone without the key can't speak as alice, nor take her address.
|
||||
let stranger = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let fake = proto::Cipher::new(&[0; 16])
|
||||
.seal(&SystemRandom::new(), &[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0])
|
||||
.unwrap();
|
||||
stranger
|
||||
.send_to(
|
||||
&Out::default()
|
||||
.byte(proto::MAGIC)
|
||||
.uuid(A)
|
||||
.bytes(&fake)
|
||||
.done(),
|
||||
b.server,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(b.hears(), None);
|
||||
// A copy of alice's own handshake from elsewhere, while she's active, is refused.
|
||||
let replay = a
|
||||
.cipher
|
||||
.seal(
|
||||
&a.rng,
|
||||
&Out::default()
|
||||
.byte(5)
|
||||
.uuid(A)
|
||||
.done()
|
||||
.into_iter()
|
||||
.chain(a.secret)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap();
|
||||
stranger
|
||||
.set_read_timeout(Some(Duration::from_millis(300)))
|
||||
.unwrap();
|
||||
stranger
|
||||
.send_to(
|
||||
&Out::default()
|
||||
.byte(proto::MAGIC)
|
||||
.uuid(A)
|
||||
.bytes(&replay)
|
||||
.done(),
|
||||
b.server,
|
||||
)
|
||||
.unwrap();
|
||||
let mut buf = [0u8; 64];
|
||||
assert!(
|
||||
stranger.recv_from(&mut buf).is_err(),
|
||||
"no answer to a stranger"
|
||||
);
|
||||
a.talk(0, false);
|
||||
assert!(
|
||||
b.hears().is_some(),
|
||||
"alice still talks from her own address"
|
||||
);
|
||||
|
||||
// Bob leaves the game: alice is told, and his voice is gone.
|
||||
let mut without_bob = world();
|
||||
without_bob.retain(|p| p.uuid != B);
|
||||
s.tick(without_bob);
|
||||
let out = s.outgoing(64);
|
||||
assert_eq!(
|
||||
for_player(&out, A),
|
||||
vec![(proto::REMOVE_STATE.to_owned(), proto::remove_state(B))]
|
||||
);
|
||||
b.talk(5, false);
|
||||
assert_eq!(a.hears(), None);
|
||||
s.left(A);
|
||||
assert!(s.outgoing(64).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_is_paced_per_player() {
|
||||
let s = server();
|
||||
ask_secret(&s, A);
|
||||
for i in 0..10 {
|
||||
s.message(
|
||||
A,
|
||||
proto::CREATE_GROUP,
|
||||
&Out::default()
|
||||
.text(&format!("g{i}"))
|
||||
.flag(false)
|
||||
.short(0)
|
||||
.done(),
|
||||
);
|
||||
}
|
||||
let first = s.outgoing(4);
|
||||
assert_eq!(first.len(), 4);
|
||||
let mut rest = 0;
|
||||
loop {
|
||||
let more = s.outgoing(4);
|
||||
if more.is_empty() {
|
||||
break;
|
||||
}
|
||||
assert!(more.len() <= 4);
|
||||
rest += more.len();
|
||||
}
|
||||
// Each group: its add and alice's joined (the old one, emptied, is removed).
|
||||
assert_eq!(4 + rest, 10 * 2 + 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_defaults_fill_in() {
|
||||
let c: Config = serde_json::from_str(r#"{"port": 25565}"#).unwrap();
|
||||
assert_eq!((c.port, c.distance, c.enabled), (25565, 48.0, true));
|
||||
assert!(
|
||||
Server::start(Config {
|
||||
enabled: false,
|
||||
..Config::default()
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// A socket elsewhere that copies datagrams it saw and sends them as its own.
|
||||
fn stranger() -> UdpSocket {
|
||||
let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_millis(300)))
|
||||
.unwrap();
|
||||
socket
|
||||
}
|
||||
|
||||
fn answered(socket: &UdpSocket) -> bool {
|
||||
let mut buf = [0u8; 4096];
|
||||
socket.recv_from(&mut buf).is_ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replayed_handshake_after_a_silence_moves_nothing() {
|
||||
let s = server();
|
||||
let a = Voice::connect(A, &ask_secret(&s, A));
|
||||
let b = Voice::connect(B, &ask_secret(&s, B));
|
||||
s.tick(world());
|
||||
s.outgoing(64);
|
||||
|
||||
// Alice says nothing for longer than the old 5 s move rule (but less than
|
||||
// the 10 s after which she counts as lost).
|
||||
std::thread::sleep(Duration::from_millis(5300));
|
||||
let eve = stranger();
|
||||
for datagram in &a.handshake {
|
||||
eve.send_to(datagram, a.server).unwrap();
|
||||
assert!(!answered(&eve), "no answer to a copied handshake");
|
||||
}
|
||||
b.talk(0, false);
|
||||
assert!(a.hears().is_some(), "bob's voice still goes to alice");
|
||||
assert!(!answered(&eve), "and not to the copier");
|
||||
|
||||
// Exact copies from alice's own address are dropped too.
|
||||
a.socket.send_to(&a.handshake[1], a.server).unwrap();
|
||||
assert_eq!(a.next(|p| p == [10]), None, "a copied check isn't answered");
|
||||
let said = a.talk(0, false);
|
||||
assert!(b.hears().is_some());
|
||||
a.socket.send_to(&said, a.server).unwrap();
|
||||
assert_eq!(b.hears(), None, "a copied voice packet isn't relayed twice");
|
||||
a.talk(1, false);
|
||||
assert!(b.hears().is_some(), "the next one is");
|
||||
|
||||
// Once her handshake has left the nonces remembered, the secret still
|
||||
// belongs to her address alone.
|
||||
for _ in 0..SEEN_NONCES + 4 {
|
||||
a.send(&[8]);
|
||||
}
|
||||
a.idle(200);
|
||||
for datagram in &a.handshake {
|
||||
eve.send_to(datagram, a.server).unwrap();
|
||||
assert!(!answered(&eve), "no answer to an old copy either");
|
||||
}
|
||||
b.talk(1, false);
|
||||
assert!(a.hears().is_some());
|
||||
assert!(!answered(&eve));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_the_server_stops_hearing_gets_a_fresh_secret() {
|
||||
let s = server_with(Config {
|
||||
// Lost after 3 s: bob, who answers keep-alives only while a test
|
||||
// reads his socket, must not count as lost too.
|
||||
keep_alive_ms: 300,
|
||||
..Config::default()
|
||||
});
|
||||
let a = Voice::connect(A, &ask_secret(&s, A));
|
||||
let b = Voice::connect(B, &ask_secret(&s, B));
|
||||
s.message(
|
||||
A,
|
||||
proto::CREATE_GROUP,
|
||||
&Out::default().text("Open").flag(false).short(1).done(),
|
||||
);
|
||||
s.tick(world());
|
||||
let out = s.outgoing(64);
|
||||
let group = for_player(&out, A)
|
||||
.into_iter()
|
||||
.find(|m| m.0 == proto::ADD_GROUP)
|
||||
.map(|m| In::new(&m.1).uuid().unwrap())
|
||||
.unwrap();
|
||||
|
||||
// Alice's NAT rebinds: the server hears nothing from her for 10 keep-alives.
|
||||
b.idle(3500);
|
||||
let out = s.outgoing(64);
|
||||
let to_alice = for_player(&out, A);
|
||||
assert_eq!(
|
||||
to_alice.iter().map(|m| m.0.as_str()).collect::<Vec<_>>(),
|
||||
[proto::SECRET],
|
||||
"only a new secret, over the game connection"
|
||||
);
|
||||
let fresh = &to_alice[0].1;
|
||||
assert_ne!(&fresh[..16], &a.secret, "a new key");
|
||||
|
||||
// The old key opens nothing now, from anywhere.
|
||||
let eve = stranger();
|
||||
eve.send_to(&a.handshake[0], a.server).unwrap();
|
||||
assert!(!answered(&eve));
|
||||
a.send(&[9]);
|
||||
assert_eq!(a.next(|p| p == [10]), None);
|
||||
|
||||
// From her new address with the new secret, she is back, in her group.
|
||||
let moved = Voice::connect(A, fresh);
|
||||
s.tick(world());
|
||||
let out = s.outgoing(64);
|
||||
let alice = proto::state(&PlayerState {
|
||||
uuid: A,
|
||||
name: "alice".into(),
|
||||
disabled: false,
|
||||
disconnected: false,
|
||||
group: Some(group),
|
||||
});
|
||||
assert!(
|
||||
for_player(&out, B).contains(&(proto::STATE.to_owned(), alice)),
|
||||
"{out:?}"
|
||||
);
|
||||
b.talk(0, false);
|
||||
assert!(
|
||||
moved.hears().is_some(),
|
||||
"bob's voice reaches her new address"
|
||||
);
|
||||
assert_eq!(a.hears(), None, "and not the old one");
|
||||
moved.talk(0, false);
|
||||
assert!(b.hears().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_secret_requests_and_group_changes_stay_bounded() {
|
||||
let s = server();
|
||||
// 40 players, each in a group of their own.
|
||||
let many: Vec<Player> = (0..40u128)
|
||||
.map(|i| player(0x100 + i, &format!("p{i}"), "minecraft:overworld", 0.0))
|
||||
.collect();
|
||||
s.tick(many.clone());
|
||||
for p in &many {
|
||||
ask_secret(&s, p.uuid);
|
||||
s.message(
|
||||
p.uuid,
|
||||
proto::CREATE_GROUP,
|
||||
&Out::default().text(&p.name).flag(false).short(0).done(),
|
||||
);
|
||||
}
|
||||
s.tick(many.clone());
|
||||
s.outgoing(usize::MAX);
|
||||
|
||||
// A thousand requests in a row: answered once now, once more a second later.
|
||||
let first = many[0].uuid;
|
||||
for _ in 0..1000 {
|
||||
s.message(first, proto::REQUEST_SECRET, &20i32.to_be_bytes());
|
||||
}
|
||||
let count = |out: &[Message], channel: &str| {
|
||||
out.iter()
|
||||
.filter(|m| m.0 == first && m.1 == channel)
|
||||
.count()
|
||||
};
|
||||
let out = s.outgoing(usize::MAX);
|
||||
assert_eq!(count(&out, proto::SECRET), 0, "too soon after the last one");
|
||||
std::thread::sleep(SECRET_EVERY + Duration::from_millis(50));
|
||||
s.tick(many.clone());
|
||||
let out = s.outgoing(usize::MAX);
|
||||
assert_eq!(count(&out, proto::SECRET), 1);
|
||||
// Starting over, it left its own group, which went away.
|
||||
assert_eq!(count(&out, proto::ADD_GROUP), 39, "the groups once");
|
||||
let mine: Vec<String> = for_player(&out, first).into_iter().map(|m| m.0).collect();
|
||||
assert!(mine.len() <= 1 + 1 + 39 + 1, "{mine:?}");
|
||||
s.tick(many.clone());
|
||||
assert_eq!(count(&s.outgoing(usize::MAX), proto::SECRET), 0);
|
||||
|
||||
// Group changes: a burst of 10, then 2 a second.
|
||||
let second = many[1].uuid;
|
||||
for i in 0..100 {
|
||||
s.message(
|
||||
second,
|
||||
proto::CREATE_GROUP,
|
||||
&Out::default()
|
||||
.text(&format!("g{i}"))
|
||||
.flag(false)
|
||||
.short(0)
|
||||
.done(),
|
||||
);
|
||||
}
|
||||
let out = s.outgoing(usize::MAX);
|
||||
let joined = out
|
||||
.iter()
|
||||
.filter(|m| m.0 == second && m.1 == proto::JOINED_GROUP)
|
||||
.count();
|
||||
// Its bucket refilled during the wait: 10 of the 100.
|
||||
assert_eq!(joined, OPS_BURST as usize);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// The end of each server tick: the relay learns where everyone is, and its
|
||||
// messages leave for the players' clients.
|
||||
fn voicechat_server_tick(
|
||||
game: &mut crate::game::Game<'_>,
|
||||
phase: crate::game::native_lifecycle::ServerTickPhase,
|
||||
) {
|
||||
if matches!(
|
||||
phase,
|
||||
crate::game::native_lifecycle::ServerTickPhase::ServerTickEnd { .. }
|
||||
) {
|
||||
crate::game::voicechat_server::tick(game);
|
||||
}
|
||||
}
|
||||
@@ -4,5 +4,5 @@
|
||||
"horizon_repository": "https://github.com/horizon-rust/horizon",
|
||||
"horizon_revision": "6f8c7a0e5d531d3834c4d0be4659a1db8e7e5c2a",
|
||||
"horizon_mixins_repository": "https://github.com/horizon-rust/horizon-mixins",
|
||||
"horizon_mixins_revision": "0d6b103c70633d8fd9443d8d0acd3aadaacedb06"
|
||||
"horizon_mixins_revision": "d9c83d7096b7ea5b83678da2efdfd6161f74997e"
|
||||
}
|
||||
@@ -6,3 +6,9 @@
|
||||
# sha256 = "..."
|
||||
# reason = "What it did, in one sentence players will read."
|
||||
# date = "2026-10-24"
|
||||
|
||||
[[revoked]]
|
||||
id = "crossversion"
|
||||
sha256 = "deb9cf8a84838e6c48999f70fbd3c81db90992c456d6e85a0e0746b088c5b8fa"
|
||||
reason = "Paused while its Microsoft sign-in for online-mode servers is reviewed with its author; a reviewed version will replace it."
|
||||
date = "2026-11-03"
|
||||
Reference in new issue
Block a user