diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d6577d49e..8966854c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,10 @@ concurrency: # A new push to a pull request replaces its running checks; main's runs all finish (releases follow them). group: checks-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: verify: runs-on: ubuntu-latest diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index de4127c67..02c61cdd1 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -3,8 +3,10 @@ name: launcher # push to main that changes the launcher or a crate it builds in (the paths below), # every 10 minutes (a release waiting for merges to settle goes out) and by hand, tools/release_train.py decides as # for the game. -# A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull -# request is labelled feature. The version is given to the build (HORIZON_LAUNCHER_VERSION): no bump commits. +# A release is launcher@X.Y.Z on the release line in .github/release-line.txt (docs/versioning.md); without it +# launcher-vX.Y.Z, the patch after the last launcher tag or the next minor when a merged pull request is labelled +# feature. The version and the tag are given to the build (HORIZON_LAUNCHER_VERSION, HORIZON_LAUNCHER_TAG): no bump +# commits. # Never marked latest. Pushes to launcher branches only build. RELEASES_PAUSED=1 stops releases. # macOS: with the repository variable MACOS_SIGN_IDENTITY set, Horizon.app and the .dmg are signed with # Developer ID, notarized and stapled, from the runner's signing keychain (packaging/macos/README.md); @@ -47,6 +49,10 @@ concurrency: group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }} cancel-in-progress: false +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: decide: runs-on: ubuntu-latest @@ -75,7 +81,8 @@ jobs: python3 tools/release_train.py decide --kind launcher ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY" tag=$(jq -r '.tag' decision.json) - echo "version=${tag#launcher-v}" >> "$GITHUB_OUTPUT" + version=${tag#launcher-v} + echo "version=${version#launcher@}" >> "$GITHUB_OUTPUT" # A dry run (and a launcher branch's push) builds whatever the decision. if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT" @@ -113,9 +120,13 @@ jobs: # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository # variable, not a secret. Unset, the launcher says sign-in is not configured. HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} - # The release's version, built in (launcher/src/backend.rs VERSION); a launcher branch's build keeps - # Cargo.toml's. + # The mod browser's CurseForge source (docs/mod-browser.md#curseforge): a repository secret. Unset, the + # launcher searches Modrinth only. + HORIZON_CURSEFORGE_API_KEY: ${{ secrets.HORIZON_CURSEFORGE_API_KEY }} + # The release's version and tag, built in (launcher/src/backend.rs VERSION and own_tag: the tag says which + # line it is on, docs/versioning.md); a launcher branch's build keeps Cargo.toml's. HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }} + HORIZON_LAUNCHER_TAG: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.tag || '' }} defaults: run: working-directory: launcher @@ -181,9 +192,6 @@ jobs: retry "$launcher" install latest "$launcher" versions --installed "$launcher" links --json - "$launcher" menu-style classic - grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt" - "$launcher" menu-style horizon clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*) client="${clients[0]}" echo "installed client: $client" diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 689cdae59..51f9e89cd 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -23,6 +23,10 @@ permissions: concurrency: group: nightly-audit cancel-in-progress: false +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: audit: runs-on: [self-hosted, horizon-game] diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index 7289fe4de..a18fc5019 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -15,6 +15,10 @@ on: required: true permissions: contents: read +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: parity: runs-on: [self-hosted, horizon-game] diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index b7ef0b38b..3966f571b 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -1,17 +1,20 @@ name: promote -# Beta game releases become stable (docs/release-flow.md, "Channels"): every 30 minutes tools/release_channels.py -# promotes the newest beta that has been out 6 hours, passed its release smoke test and isn't covered by an issue -# labelled release-blocker. By hand, from GitHub's app too (Actions > promote > Run workflow): -# gh workflow run promote -f tag=v2026.10.19.03 # that beta now, without the wait -# gh workflow run promote -f tag=v2026.10.19.03 -f force=true # even blocked or without its smoke test -# gh workflow run promote -f dry_run=true # say what would be promoted +# Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in +# winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then, +# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha +# channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are +# retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once. +# By hand, from GitHub's app too (Actions > promote > Run workflow): +# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00 +# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test +# gh workflow run promote -f dry_run=true # say what would be promoted # Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it # still holds the betas published before it closed. The issue's text is never read (its author could edit it). -# When the oldest waiting beta is 24 hours old, an issue "Promotion to stable has stalled" says so; it closes itself -# after the next promotion. +# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable +# has stalled" says so; it closes itself after the next promotion. on: schedule: - - cron: '13,43 * * * *' + - cron: '7,37 20-21 * * *' workflow_dispatch: inputs: tag: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2c4e13cf2..b19ba9ce5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,13 +1,14 @@ name: release # Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a # release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: -# a release when pull requests merged since the last one changed what players run and the newest merged 15 minutes -# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now. +# a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes +# ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now. # RELEASES_PAUSED=1 (repository variable) stops them. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then -# publishes vYYYY.MM.DD[.N] with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes -# stable after 6 hours. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with +# publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated +# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes +# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with # Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain # (packaging/macos/README.md); unset (forks), ad hoc. # gh workflow run release --ref # dry run: builds and notes, publishes nothing @@ -44,6 +45,7 @@ jobs: outputs: release: ${{ steps.decide.outputs.release }} tag: ${{ steps.decide.outputs.tag }} + version: ${{ steps.decide.outputs.version }} head: ${{ steps.decide.outputs.head }} dry_run: ${{ steps.mode.outputs.dry_run }} steps: @@ -64,6 +66,9 @@ jobs: run: | python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY" + # The version the programs are built with (docs/versioning.md): the tag without its v. + tag=$(jq -r '.tag' decision.json) + echo "version=${tag#v}" >> "$GITHUB_OUTPUT" # A dry run builds whatever the decision, to test the builds. if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi @@ -98,6 +103,9 @@ jobs: timeout-minutes: ${{ matrix.mac && 60 || 40 }} env: RUSTFLAGS: ${{ matrix.rustflags }} + # The release's version, built in (horizon_core::release): --version, user agents, crash reports and + # telemetry say it. No version-bump commits. + HORIZON_VERSION: ${{ needs.decide.outputs.version }} defaults: run: shell: bash @@ -161,9 +169,13 @@ jobs: bin=target/release "$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources' "$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null - "$bin/horizon-prepare${{ matrix.exe }}" --version "$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir' - "$bin/horizon-server${{ matrix.exe }}" --version + # The version is the release's. + for binary in horizon-prepare horizon-server; do + out=$("$bin/$binary${{ matrix.exe }}" --version | tr -d '\r') + echo "$out" + [[ "$out" == "$binary $HORIZON_VERSION" ]] || { echo "::error::expected $binary $HORIZON_VERSION"; exit 1; } + done - name: Tools from the runner if: runner.environment == 'self-hosted' run: bash tools/ci/runner-env.sh @@ -244,7 +256,7 @@ jobs: folder="dist/${{ matrix.server_dir }}" python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" "$folder/horizon-engine" --help | grep -q -- '--resources' - "$folder/horizon-server" --version + [[ "$("$folder/horizon-server" --version)" == "horizon-server $HORIZON_VERSION" ]] cd dist rm -f "${{ matrix.server_asset }}" tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}" @@ -337,7 +349,8 @@ jobs: run: | signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json) - # A beta (pre-release): promote.yml makes it stable and latest after 6 hours (docs/release-flow.md). + # A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion + # (docs/release-flow.md). gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ --notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \ dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \ diff --git a/.github/workflows/run-parity.yml b/.github/workflows/run-parity.yml index fd3cce6f8..a2b8e3291 100644 --- a/.github/workflows/run-parity.yml +++ b/.github/workflows/run-parity.yml @@ -11,6 +11,10 @@ permissions: concurrency: group: run-parity-${{ github.event.pull_request.number }} cancel-in-progress: true +env: + # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md). + HORIZON_TELEMETRY_URL: "off" + jobs: parity: if: github.event.label.name == 'run-parity' diff --git a/README.md b/README.md index 72b6a3496..4abb52b86 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these. - **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status). - **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings). - **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers. -- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). +- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). - **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods). Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders: @@ -56,8 +56,8 @@ Screenshots, captured in the Rust client itself with vanilla assets and no mods Sunset over a savanna river valley and a plains village - Horizon's title screen over a veiled snowy landscape - The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs + Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience + Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs A plains village among savanna hills, with farms, villagers and an iron golem diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 368813ecf..88d3197af 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -36,3 +36,15 @@ SOFTWARE. developers, with one upstream fix applied ([gfx-rs/wgpu#10124](https://github.com/gfx-rs/wgpu/pull/10124)). It is licensed under MIT or Apache-2.0; both licenses are in that folder (`LICENSE.MIT`, `LICENSE.APACHE`). + +## Pixelify Sans + +`crates/horizon-theme/fonts/PixelifySans-*.ttf` is [Pixelify Sans](https://github.com/eifetx/Pixelify-Sans) +by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1.1 +(`crates/horizon-theme/fonts/OFL-PixelifySans.txt`). + +## Pixelarticons + +`crates/horizon-theme/icons/pixel/*.svg` are icons from +[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT +license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). diff --git a/crates/horizon-assets/src/blockstate/choice.rs b/crates/horizon-assets/src/blockstate/choice.rs index 93e9a4118..d871b1c66 100644 --- a/crates/horizon-assets/src/blockstate/choice.rs +++ b/crates/horizon-assets/src/blockstate/choice.rs @@ -82,6 +82,19 @@ impl CompiledChoices { .collect::>()?, }) } + /// The variant `particleMaterial` comes from: the first entry of a weighted + /// list (`WeightedVariants`) and, for a multipart root, of its first + /// selector whether or not that selector applies (`MultiPartModel`). + pub fn particle_variant(&self, selected: &SelectedModels) -> Option<&Variant> { + let choice = match selected { + SelectedModels::Variant(index) => self.variants.get(*index)?, + SelectedModels::Multipart(_) => self.multipart.first()?, + }; + Some(match choice { + Choice::Single(value) => value, + Choice::Weighted { variants, .. } => variants.first()?, + }) + } /// Append selected variants without allocating intermediate part lists. A /// multipart root consumes nextLong even for an empty selected subset, then /// resets the same random source to that seed before each selected part. diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 1a7a4d25c..48e2e57d4 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -42,8 +42,9 @@ log = "0.4" chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } horizon-theme = { path = "../horizon-theme" } -# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md). -horizon-telemetry = { path = "../horizon-telemetry", default-features = false } +# Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md); `live` is +# the anonymous "I'm playing" ping the game sends itself (`heartbeat.rs`). +horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] } horizon-bench = { path = "../horizon-bench" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/breaking_fixture.rs index 2016fd613..da696b88e 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/breaking_fixture.rs @@ -14,6 +14,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; +/// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only). +const STAGE: [f32; 2] = [0.25, 0.5]; fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); @@ -47,7 +49,7 @@ fn main() -> Result<(), Box> { .iter() .any(|(_, m)| m.faces.iter().any(|f| f.translucent)); for (_, m) in models { - breaking::geometry(m, origin, translucent, &mut vertices); + breaking::geometry(m, origin, translucent, STAGE, &mut vertices); } } let quads: Vec<_> = vertices @@ -58,7 +60,7 @@ fn main() -> Result<(), Box> { q.iter() .map(|v| { assert_eq!(v.color, 0xffff_ffff); - assert_eq!(v.light, 240 | (240 << 8)); + assert_eq!(v.light, breaking::stage_light(STAGE)); assert_eq!(v.layer, if translucent { 12 } else { 11 }); [v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]] }) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 584425ced..6aa942d42 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -82,12 +82,19 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); // The inventory menu never reads banner patterns. let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/environment_fixture.rs index d92123a2c..7f331962a 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/environment_fixture.rs @@ -30,7 +30,11 @@ fn main() -> horizon_client::Result<()> { ), }; let info = biomes.get(biomes.id(&format!("minecraft:{}", f[4]))); - let mut sky = environment.sample(f[1].parse()?, info.sky, info.fog); + let mut sky = environment.sample( + f[1].parse()?, + info.sky.map(horizon_client::biome::rgb), + info.fog.map(horizon_client::biome::rgb), + ); if dimension == "overworld" { apply_weather(&mut sky, f[2].parse()?, f[3].parse()?); } diff --git a/crates/horizon-client/examples/firework_tooltip_fixture.rs b/crates/horizon-client/examples/firework_tooltip_fixture.rs index 196fa9955..7f10278b7 100644 --- a/crates/horizon-client/examples/firework_tooltip_fixture.rs +++ b/crates/horizon-client/examples/firework_tooltip_fixture.rs @@ -1,7 +1,7 @@ //! Firework tooltip companion for tools/test_firework_tooltip_parity.py: the //! lines `item_tooltip::firework_lines` gives each stack (SNBT, one per line; //! the `#resources` line names the prepared resources for en_us). -use horizon_client::{item_data::parse_stack, item_tooltip::firework_lines, lang::Language}; +use horizon_client::{enchant::Enchantments, item_data::parse_stack, item_tooltip::firework_lines}; use std::{error::Error, fmt::Write, path::PathBuf}; fn main() -> Result<(), Box> { @@ -12,8 +12,9 @@ fn main() -> Result<(), Box> { .find_map(|l| l.strip_prefix("#resources ")) .map(PathBuf::from) .ok_or("no #resources line")?; - let language = Language::load(&[&root], "en_us"); - let translate = |key: &str| language.get(key).map(str::to_owned); + // Use the inventory's filtered translations so missing tooltip keys are caught. + let enchantments = Enchantments::load(&root); + let translate = |key: &str| enchantments.translate(key).map(str::to_owned); let mut output = String::new(); for line in input.lines().filter(|l| !l.starts_with('#')) { let stack = parse_stack(line)?.ok_or("empty stack")?; diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/held_drop_fixture.rs index 87ca9870c..a0c5d92ba 100644 --- a/crates/horizon-client/examples/held_drop_fixture.rs +++ b/crates/horizon-client/examples/held_drop_fixture.rs @@ -14,13 +14,22 @@ fn main() { for count in [0, 1, 4, 64] { let mut slot = Some(ItemStack::new("minecraft:stone", count)); let mut dropped = 0; + let mut swings = 0; + let mut packets = 0; for _ in 0..2 { if let Some(stack) = take_held_drop(&mut slot, all, mode == GameMode::Spectator) { dropped += stack.count; + swings += 1; } - println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped); + if mode != GameMode::Spectator { + packets += 1; + } + println!( + "{} {dropped} {swings} {packets}", + slot.as_ref().map_or(0, |s| s.count), + ); } } } diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 53a4d62f7..f3dfea6b1 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -102,6 +102,7 @@ fn main() -> Result<(), Box> { equipment: Default::default(), health: 20.0, attributes: Vec::new(), + bed: None, living_flags: 0, }; loop { diff --git a/crates/horizon-client/examples/load_bench.rs b/crates/horizon-client/examples/load_bench.rs new file mode 100644 index 000000000..5c30a71ff --- /dev/null +++ b/crates/horizon-client/examples/load_bench.rs @@ -0,0 +1,153 @@ +//! Read-only saved chunk benchmark. All timings exclude resource/corpus setup. +//! +//! load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum] +//! Add --profile-worker when a sampling collector cannot sample the main thread. +//! Reports warm filesystem SaveDir::load (read, inflate, NBT, decode and light), +//! plus isolated inflate/NBT and native decode. No files in the save are changed. +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + save::{SaveDir, SaveTables, decode_with}, +}; +use horizon_world::{nbt::Limits, region::RegionFile}; +use sha2::{Digest, Sha256}; +use std::{hint::black_box, path::PathBuf, sync::Arc, time::Instant}; + +type Result = std::result::Result>; + +fn main() -> Result<()> { + if std::env::args().any(|a| a == "--profile-worker") { + std::thread::spawn(|| run().map_err(|e| e.to_string())) + .join() + .expect("benchmark worker") + .map_err(Into::into) + } else { + run() + } +} + +fn run() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let usage = "load_bench RESOURCES DIMENSION_DIR [--rounds N] [--limit N] [--checksum]"; + let root = PathBuf::from(args.first().ok_or(usage)?); + let dimension = PathBuf::from(args.get(1).ok_or(usage)?); + let flag = |name: &str, default: usize| -> Result { + Ok(match args.iter().position(|a| a == name) { + Some(i) => args.get(i + 1).ok_or(usage)?.parse()?, + None => default, + }) + }; + let rounds = flag("--rounds", 5)?; + let limit = flag("--limit", 256)?; + if rounds == 0 || limit == 0 { + return Err("rounds and limit must be positive".into()); + } + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Biomes::load(&root)?; + let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); + let source = SaveDir::new(dimension.clone()); + let _ = source.tables.set(tables.clone()); + let mut paths: Vec<_> = std::fs::read_dir(dimension.join("region"))? + .map(|e| e.map(|e| e.path())) + .collect::>()?; + paths.retain(|p| p.extension().is_some_and(|e| e == "mca")); + paths.sort(); + let mut corpus = Vec::new(); + 'regions: for path in paths { + let mut region = RegionFile::open(path)?; + let mut positions: Vec<_> = region.chunks().map(|(pos, _)| pos).collect(); + positions.sort_by_key(|p| (p.x, p.z)); + for pos in positions { + let record = region.read(pos)?.ok_or("missing record")?; + let tag = record.nbt(Limits::default())?; + if decode_with(&tag, assets.registry, &biomes, Some(&tables)).is_none() { + continue; + } + corpus.push((pos, record, tag)); + if corpus.len() == limit { + break 'regions; + } + } + } + if corpus.is_empty() { + return Err("no full chunks in corpus".into()); + } + let mut records_hash = Sha256::new(); + for (pos, record, _) in &corpus { + records_hash.update(pos.x.to_le_bytes()); + records_hash.update(pos.z.to_le_bytes()); + records_hash.update((record.compressed.len() as u64).to_le_bytes()); + records_hash.update(&record.compressed); + } + println!( + "{}", + serde_json::json!({"corpus": dimension, "chunks": corpus.len(), "rounds": rounds, + "compressed_records_sha256": format!("{:x}", records_hash.finalize()), + "compressed_bytes": corpus.iter().map(|(_, r, _)| r.compressed.len()).sum::()}) + ); + // Prime SaveDir's region handles and the filesystem cache before measurement. + for (pos, _, _) in &corpus { + black_box( + source + .load(pos.x, pos.z, assets.registry, &biomes) + .ok_or("load failed")?, + ); + } + for round in 0..rounds { + let started = Instant::now(); + for (pos, _, _) in &corpus { + black_box( + source + .load(pos.x, pos.z, assets.registry, &biomes) + .ok_or("load failed")?, + ); + } + let load_s = started.elapsed().as_secs_f64(); + let started = Instant::now(); + for (_, record, _) in &corpus { + black_box(record.nbt(Limits::default())?); + } + let nbt_s = started.elapsed().as_secs_f64(); + let started = Instant::now(); + for (_, _, tag) in &corpus { + black_box( + decode_with(tag, assets.registry, &biomes, Some(&tables)).ok_or("decode failed")?, + ); + } + let decode_s = started.elapsed().as_secs_f64(); + println!( + "{}", + serde_json::json!({"round": round, "load_s": load_s, + "inflate_nbt_s": nbt_s, "decode_s": decode_s}) + ); + } + if args.iter().any(|a| a == "--checksum") { + let mut hash = Sha256::new(); + let mut light_loaded = 0; + for (pos, _, _) in &corpus { + let chunk = source + .load(pos.x, pos.z, assets.registry, &biomes) + .ok_or("load failed")?; + hash.update(pos.x.to_le_bytes()); + hash.update(pos.z.to_le_bytes()); + light_loaded += usize::from(chunk.light_loaded); + for section in &chunk.sections { + for i in 0..4096 { + hash.update(section.get(i).to_le_bytes()); + hash.update([section.light(i)]); + } + for i in 0..64 { + hash.update(section.biomes.get(i).to_le_bytes()); + } + } + } + println!( + "{}", + serde_json::json!({"blocks_biomes_light_sha256": format!("{:x}", hash.finalize()), + "light_loaded": light_loaded}) + ); + } + Ok(()) +} diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 63a5351a3..1da4a0278 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -11,8 +11,41 @@ use horizon_client::{ items::Items, menu::{Env, Input, Kind, Menu}, }; +use horizon_protocol::registry::Ids; use serde_json::Value; -use std::{fs, path::Path}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + fs, + path::Path, +}; + +/// The case's maps: (locked, scale) by id, and the next free id. +#[derive(Default)] +struct CaseMaps { + maps: RefCell>, + next: Cell, +} + +impl horizon_client::menu::Maps for CaseMaps { + fn state(&self, id: i32) -> Option<(bool, u8)> { + self.maps.borrow().get(&id).copied() + } + + /// `MapItemSavedData.scaled` (unlocked, one scale up) or `locked`. + fn derive(&self, id: i32, scale: bool) -> Option { + let (_, s) = self.state(id)?; + let new = self.next.get(); + self.next.set(new + 1); + let made = if scale { + (false, (s + 1).min(4)) + } else { + (true, s) + }; + self.maps.borrow_mut().insert(new, made); + Some(new) + } +} fn state(menu: &Menu) -> String { let slots: Vec = (0..menu.slot_count()) @@ -24,13 +57,21 @@ fn state(menu: &Menu) -> String { .iter() .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) .collect(); - format!( + let line = format!( "{} | {} |{data} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), menu.drops.join(";"), equipped.join(";") - ) + ); + if menu.kind() != Kind::Lectern { + return line; + } + // No inventory slots: the inventory Take Book fills. + let items: String = (0..36) + .map(|i| format!(" {}", canon_stack(menu.player_item(i)))) + .collect(); + format!("{line} | inv{items}") } fn main() -> horizon_client::Result<()> { @@ -44,13 +85,28 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::load(root, &items); + let enchantments = horizon_client::enchant::Enchantments::load(root); + let names = horizon_client::creative::Names::load(root); + let case_maps = CaseMaps::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: Some(&case_maps), }; + // The mob effects' network ids (BeaconMenu.encodeEffect). + let builtin = horizon_protocol::registry::Builtin::find(root) + .and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok()); + let effects = builtin + .as_ref() + .and_then(|b| b.get("minecraft:mob_effect")) + .cloned(); let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; @@ -68,15 +124,41 @@ fn main() -> horizon_client::Result<()> { .unwrap_or(name), ) .ok_or("menu kind")?; + // [id, scale, locked] each; the level's new maps from 1000. + case_maps.next.set(1000); + *case_maps.maps.borrow_mut() = case["maps"] + .as_array() + .into_iter() + .flatten() + .map(|m| { + let id = m[0].as_i64().unwrap_or(0) as i32; + ( + id, + ( + m[2].as_bool().unwrap_or(false), + m[1].as_u64().unwrap_or(0) as u8, + ), + ) + }) + .collect(); let mut menu = Menu::new(kind); menu.creative = case["creative"].as_bool().unwrap_or(false); + menu.levels = case["levels"].as_i64().unwrap_or(0) as i32; for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); } menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?; + for (i, item) in case["inventory"] + .as_array() + .into_iter() + .flatten() + .enumerate() + { + menu.set_player_item(i, parse_stack(item.as_str().unwrap_or("-"))?); + } menu.settle(&env); for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { - menu.data[i] = v.as_i64().unwrap_or(0) as i32; + menu.set_data(i, v.as_i64().unwrap_or(0) as i32); } let mut furnace = furnace_kind.map(|kind| Furnace { kind, @@ -100,6 +182,26 @@ fn main() -> horizon_client::Result<()> { out += &format!("{}\n", state(&menu)); continue; } + // ServerboundRenameItemPacket: AnvilMenu.setItemName. + "RENAME" => { + menu.rename(&env, op[3].as_str().unwrap_or_default()); + out += &format!("{}\n", state(&menu)); + continue; + } + // ServerboundSetBeaconPacket: BeaconMenu.updateEffects. + "SET_BEACON" => { + fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> { + let name = v.as_str()?; + Some((ids?.id(name)?, name)) + } + let (primary, secondary) = ( + power(effects.as_ref(), &op[3]), + power(effects.as_ref(), &op[4]), + ); + menu.beacon_update(&env, primary, secondary); + out += &format!("{}\n", state(&menu)); + continue; + } // ServerboundContainerSlotStateChangedPacket. "SLOT_STATE" => { if (0..9).contains(&slot) { diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 2a4969221..a3abb54d9 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> { nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), others: $snapshot, others_grid: $grid, + others_index: None, daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, @@ -1132,7 +1133,7 @@ fn main() -> horizon_client::Result<()> { } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); - let mut pushes = Vec::new(); + let mut pushes = horizon_client::mobs::PendingPushes::default(); let mut born = Vec::new(); for i in 0..mobs.len() { if mobs[i].removed { diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/particle_providers_probe.rs index 989895c07..8b8bd1e0d 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/particle_providers_probe.rs @@ -112,21 +112,26 @@ fn state(s: &ParticleSnapshot) -> String { } out } -fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result { +fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Result { let mut world = World::new(facts.air, 0); - let stone = assets - .registry - .default_state("minecraft:stone") - .ok_or("missing stone")?; + let state = |name: &str| assets.registry.default_state(name).ok_or("missing block"); + let (stone, still) = (state("minecraft:stone")?, state("minecraft:water")?); for cz in -3..=2 { for cx in -3..=2 { world .chunks .insert((cx, cz), Arc::new(Chunk::empty(cx, cz))); - if floor { - for z in 0..16 { - for x in 0..16 { - world.set(cx * 16 + x, 63, cz * 16 + z, stone)?; + for z in 0..16 { + for x in 0..16 { + let (x, z) = (cx * 16 + x, cz * 16 + z); + if floor { + world.set(x, 63, z, stone)?; + } + // The oracle's water: still sources from y 64 to 67. + if water { + for y in 64..=67 { + world.set(x, y, z, still)?; + } } } } @@ -142,8 +147,10 @@ fn main() -> Result<()> { let facts = BlockFacts::load(root, assets.registry)?; let collision = collisions::load(root, assets.registry)?; let worlds = [ - world(&assets, &facts, false)?, - world(&assets, &facts, true)?, + world(&assets, &facts, false, false)?, + world(&assets, &facts, true, false)?, + world(&assets, &facts, false, true)?, + world(&assets, &facts, true, true)?, ]; let mut engine = ParticleEngine::new(root, &HashMap::new()); for (ty, item) in [ @@ -174,7 +181,8 @@ fn main() -> Result<()> { engine.requested = Some(Vec::new()); engine.sounds.clear(); let level = ParticleLevel { - world: &worlds[usize::from(case["floor"].as_bool() == Some(true))], + world: &worlds[usize::from(case["floor"].as_bool() == Some(true)) + + 2 * usize::from(case["water"].as_bool() == Some(true))], facts: &facts, collision: &collision, player: None, diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index 45d763980..1e2b66dbf 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -38,12 +38,19 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: None, + maps: None, }; let mut out = String::new(); for (line, order) in cases.lines().zip(orders.lines()) { diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs index 9f8e99899..b8c56b28c 100644 --- a/crates/horizon-client/examples/streaming_bench.rs +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -3,6 +3,7 @@ //! what the render thread pays for it in `Streaming::update`. //! //! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] +//! [--dimension overworld|the_nether|the_end] [--center-x X] [--center-z Z] //! //! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x //! at that speed for T seconds while frames run at F per second. Each phase reports @@ -72,14 +73,33 @@ static ALLOCATOR: CountingAllocator = CountingAllocator; type Result = std::result::Result>; +fn cpu_seconds() -> f64 { + std::fs::read_to_string("/proc/self/stat") + .ok() + .and_then(|stat| { + let fields = stat + .rsplit_once(')')? + .1 + .split_whitespace() + .collect::>(); + Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.0) + }) + .unwrap_or(0.0) +} + #[derive(Default)] struct Phase { updates: Vec, local: (u64, u64), uploads: usize, + stage_samples: [u64; 7], + cpu_start: f64, } impl Phase { fn update(&mut self, streaming: &mut Streaming, world: &mut World) { + if self.updates.is_empty() { + self.cpu_start = cpu_seconds(); + } let before = LOCAL.with(Cell::get); let started = Instant::now(); let (uploads, _) = streaming.update(world); @@ -89,6 +109,9 @@ impl Phase { self.local.1 += after.1 - before.1; self.uploads += uploads.len(); drop(uploads); + for (sum, (_, count)) in self.stage_samples.iter_mut().zip(streaming.stages()) { + *sum += count as u64; + } } fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { let mut sorted = self.updates.clone(); @@ -106,6 +129,16 @@ impl Phase { at(0.99), sorted.last().copied().unwrap_or(0.0), ); + println!( + "BENCH {}", + serde_json::json!({ + "phase": name, "wall_s": wall.as_secs_f64(), + "cpu_s": cpu_seconds() - self.cpu_start, + "chunks": streaming.generated_total - generated, "sections": self.uploads, + "updates": self.updates.len(), "update_ms": total, + "mean_stages": self.stage_samples.map(|n| n as f64 / self.updates.len() as f64), + }) + ); if TRACK { println!( " update allocations: {} ({:.1} MiB)", @@ -142,6 +175,22 @@ fn main() -> Result<()> { let fly = flag("--fly", 0.0); let seconds = flag("--seconds", 10.0); let hz = flag("--hz", 240.0); + let dimension = args + .iter() + .position(|a| a == "--dimension") + .and_then(|i| args.get(i + 1)) + .map(|d| { + if d.contains(':') { + d.clone() + } else { + format!("minecraft:{d}") + } + }) + .unwrap_or_else(|| "minecraft:overworld".into()); + let center = ( + flag("--center-x", 0.0) as i32, + flag("--center-z", 0.0) as i32, + ); let assets = Arc::new(Assets::load(&root)?); let render = Arc::new(assets.reload(&root)?); @@ -154,11 +203,12 @@ fn main() -> Result<()> { models::load_visibility(&root, assets.registry)?, )?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let terrain = Arc::new(VanillaTerrain::new( + let terrain = Arc::new(VanillaTerrain::for_dimension( &root.join("worldgen"), assets.registry, &biomes, seed, + &dimension, )?); let context = Arc::new(WorkerContext { assets, @@ -170,8 +220,12 @@ fn main() -> Result<()> { let mut world = World::new(facts.air, seed); let mut streaming = Streaming::new(terrain, context, threads); streaming.radius = radius; - streaming.center = (0, 0); - println!("{threads} workers, radius {radius}, seed {seed}"); + streaming.center = center; + streaming.nether_shading = dimension == "minecraft:the_nether"; + streaming.sky_light = dimension != "minecraft:the_nether"; + println!( + "{threads} workers, radius {radius}, seed {seed}, dimension {dimension}, center {center:?}" + ); let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); // Fill: update as often as the game would uncapped, until settled. @@ -198,12 +252,12 @@ fn main() -> Result<()> { let mut behind = Vec::new(); while started.elapsed().as_secs_f64() < seconds { let next = Instant::now() + frame; - let x = (started.elapsed().as_secs_f64() * fly) as i32; - streaming.center = (x, 0); + let x = center.0 + (started.elapsed().as_secs_f64() * fly) as i32; + streaming.center = (x, center.1); phase.update(&mut streaming, &mut world); // Columns within 2 chunks of the player still missing their meshes. let near = (-2..=2) - .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz))) + .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, center.1 + dz))) .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) .count(); behind.push(near); diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/trading_fixture.rs index a560b1c06..58824257c 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -239,10 +239,12 @@ fn main() -> horizon_client::Result<()> { let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?; let items = Items::catalog(root)?; let enchantments = Enchantments::load(root); + let names = horizon_client::creative::Names::default(); let trades = Trades::load(root); let recipes = horizon_client::crafting::Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::default(); let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)? .types .into_iter() @@ -378,7 +380,11 @@ fn main() -> horizon_client::Result<()> { recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, + enchantments: &enchantments, + names: &names, trade: Some(&env_trade), + maps: None, }; trade(&mut out, name, &kv, &mut world, &env, origin)?; } diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/weather_fixture.rs index 15aab6bdb..3cf6c31be 100644 --- a/crates/horizon-client/examples/weather_fixture.rs +++ b/crates/horizon-client/examples/weather_fixture.rs @@ -11,6 +11,7 @@ fn bits(value: f32) -> String { fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let mut output = String::new(); + let mut parameters = weather::ParameterCache::default(); for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { let p: Vec<&str> = line.split_whitespace().collect(); let int = |i: usize| p[i].parse::().unwrap(); @@ -38,6 +39,13 @@ fn main() -> Result<(), Box> { bits(column.v_offset), column.light_coords )?; + assert_eq!( + parameters + .get(x, z) + .column(kind != 0, ticks, x, bottom, top, z, light, partial), + column, + "cached parameters differ from original random source at case {case}" + ); let max_alpha = if kind == 0 { 1.0 } else { 0.8 }; for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) { write!( diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 16028e220..6706532b7 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -53,6 +53,10 @@ pub struct Tree { pub by_id: HashMap, /// trigger id -> (advancement index, criterion index). pub by_trigger: HashMap>, + /// `recipe_unlocked` criteria by the recipe they name (`index_recipes`); + /// those naming none in `recipes_any`. + by_recipe: HashMap>, + recipes_any: Vec<(usize, usize)>, } fn frame(v: &Value) -> Frame { match v.as_str() { @@ -93,12 +97,111 @@ impl Tree { tree.list.push(a); } } + tree.index_recipes(); tree } + /// Index the `recipe_unlocked` criteria by recipe: a grant that unlocks + /// twenty recipes tested every one of the ~1,300 recipe advancements' + /// criteria for each (several ms in one tick). + pub fn index_recipes(&mut self) { + self.by_recipe.clear(); + self.recipes_any.clear(); + for &(ai, ci) in self + .by_trigger + .get("minecraft:recipe_unlocked") + .into_iter() + .flatten() + { + match self.list[ai].criteria[ci].conditions["recipes"].as_str() { + Some(r) => self + .by_recipe + .entry(r.to_owned()) + .or_default() + .push((ai, ci)), + None => self.recipes_any.push((ai, ci)), + } + } + } + /// The `recipe_unlocked` criteria that could pass for `recipe`, in tree + /// order (the others name another recipe). + pub fn recipe_criteria(&self, recipe: &str) -> Vec<(usize, usize)> { + let mut out = self.recipes_any.clone(); + out.extend(self.by_recipe.get(recipe).into_iter().flatten()); + out.sort_unstable(); + out + } pub fn get(&self, id: &str) -> Option<&Advancement> { self.by_id.get(id).map(|&i| &self.list[i]) } } + +/// The `inventory_changed` criteria by the items they need. A criterion whose +/// item predicates include one limited to some items (an id, a `#tag`, a +/// list) can only pass with one of those in the inventory, so an inventory +/// change tests only the criteria of the items it holds, plus those that +/// need no particular item. The same answers as testing them all: the ~1,300 +/// recipe advancements each have one, and testing every one of them cost a +/// player 1–4 ms on every tick its inventory changed. +#[derive(Default)] +pub struct InventoryIndex { + by_item: HashMap>, + any: Vec<(usize, usize)>, +} +impl InventoryIndex { + /// `tag` gives a `#tag`'s item ids (none for a tag that doesn't exist, + /// which matches nothing). + pub fn build<'t>(tree: &Tree, tag: impl Fn(&str) -> Vec<&'t str>) -> Self { + fn ids<'t>(v: &Value, tag: &impl Fn(&str) -> Vec<&'t str>, out: &mut Vec) { + match v { + Value::String(s) => match s.strip_prefix('#') { + Some(t) => out.extend(tag(t).into_iter().map(str::to_owned)), + None => out.push(s.clone()), + }, + Value::Array(a) => a.iter().for_each(|x| ids(x, tag, out)), + _ => {} + } + } + let mut index = Self::default(); + let Some(list) = tree.by_trigger.get("minecraft:inventory_changed") else { + return index; + }; + for &(ai, ci) in list { + let items = &tree.list[ai].criteria[ci].conditions["items"]; + // `id_matches`: only a string or a list limits the items. + let limited = items.as_array().and_then(|a| { + a.iter() + .map(|p| &p["items"]) + .find(|v| v.is_string() || v.is_array()) + }); + match limited { + Some(v) => { + let mut out = Vec::new(); + ids(v, &tag, &mut out); + out.sort(); + out.dedup(); + for id in out { + index.by_item.entry(id).or_default().push((ai, ci)); + } + } + None => index.any.push((ai, ci)), + } + } + index + } + /// The criteria an inventory holding these item ids could pass, in + /// tree order. + pub fn candidates<'a>(&self, held: impl IntoIterator) -> Vec<(usize, usize)> { + let mut out = self.any.clone(); + for id in held { + if let Some(list) = self.by_item.get(id) { + out.extend_from_slice(list); + } + } + out.sort_unstable(); + out.dedup(); + out + } +} fn collect(root: &Path, dir: &Path, ns: &str, out: &mut Vec<(String, std::path::PathBuf)>) { let Ok(entries) = std::fs::read_dir(dir) else { return; @@ -992,6 +1095,77 @@ impl Tree { #[cfg(test)] mod tests { use super::*; + + /// The criteria an inventory change and a recipe unlock test, on vanilla's tree: + /// `cargo test -p horizon-client --lib -- --ignored --nocapture index_on_vanilla_tree` + /// with HORIZON_RESOURCES set to the prepared resources. + #[test] + #[ignore = "needs the prepared resources"] + fn index_on_vanilla_tree() { + let Some(root) = std::env::var_os("HORIZON_RESOURCES").map(std::path::PathBuf::from) else { + return; + }; + let data = root.join("data"); + let t = std::time::Instant::now(); + let tree = Tree::load(&data); + let load = t.elapsed(); + let tags = data.join("minecraft/tags/item"); + let tag_items: HashMap> = std::fs::read_dir(&tags) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let v: Value = + serde_json::from_str(&std::fs::read_to_string(e.path()).ok()?).ok()?; + let name = format!("minecraft:{}", e.path().file_stem()?.to_string_lossy()); + let values = v["values"] + .as_array()? + .iter() + .filter_map(|x| x.as_str().map(str::to_owned)); + Some((name, values.collect())) + }) + .collect(); + let t = std::time::Instant::now(); + let index = InventoryIndex::build(&tree, |tag| { + tag_items + .get(tag) + .map(|v| v.iter().map(String::as_str).collect()) + .unwrap_or_default() + }); + let build = t.elapsed(); + let all = tree + .by_trigger + .get("minecraft:inventory_changed") + .map_or(0, Vec::len); + let held = [ + "minecraft:iron_ingot", + "minecraft:oak_log", + "minecraft:cobblestone", + "minecraft:diamond_pickaxe", + "minecraft:bread", + "minecraft:torch", + "minecraft:oak_planks", + "minecraft:stick", + "minecraft:coal", + ]; + let t = std::time::Instant::now(); + let mut candidates = 0; + for _ in 0..1000 { + candidates = index.candidates(held).len(); + } + let per_change = t.elapsed() / 1000; + let recipes = tree + .by_trigger + .get("minecraft:recipe_unlocked") + .map_or(0, Vec::len); + let per_recipe = tree.recipe_criteria("minecraft:iron_pickaxe").len(); + eprintln!( + "tree {load:?}; inventory_changed: {all} criteria, index built in {build:?}, \ + a 9-stack inventory tests {candidates} (looked up in {per_change:?}); \ + recipe_unlocked: {recipes} criteria, iron_pickaxe tests {per_recipe}" + ); + assert!(candidates < all / 10); + } struct Flat; impl World for Flat { fn dimension(&self) -> &str { @@ -1090,6 +1264,94 @@ mod tests { stack.id = "minecraft:tnt".into(); } } + /// Only the criteria the held items could pass are tested; those that + /// need no particular item always are. + #[test] + fn inventory_index_keeps_the_criteria_the_items_could_pass() { + let criteria = [ + serde_json::json!({"items": [{"items": "minecraft:diamond"}]}), + serde_json::json!({"items": [{"items": "#minecraft:planks"}]}), + serde_json::json!({"items": [{"count": {"min": 2}}]}), + serde_json::json!({"items": [{"count": 1}, {"items": ["minecraft:stick", "minecraft:apple"]}]}), + serde_json::json!({"slots": {"empty": 0}}), + serde_json::json!({"items": [{"items": "#minecraft:no_such_tag"}]}), + ]; + let mut tree = Tree::default(); + for (i, conditions) in criteria.into_iter().enumerate() { + tree.list.push(Advancement { + id: format!("test:{i}"), + parent: None, + display: None, + criteria: vec![Criterion { + name: "c".into(), + trigger: "minecraft:inventory_changed".into(), + conditions, + }], + requirements: vec![vec!["c".into()]], + rewards: Rewards::default(), + }); + tree.by_trigger + .entry("minecraft:inventory_changed".into()) + .or_default() + .push((i, 0)); + } + let index = InventoryIndex::build(&tree, |tag| match tag { + "minecraft:planks" => vec!["minecraft:oak_planks", "minecraft:birch_planks"], + _ => Vec::new(), + }); + let found = |held: &[&str]| -> Vec { + index + .candidates(held.iter().copied()) + .into_iter() + .map(|(ai, _)| ai) + .collect() + }; + assert_eq!(found(&[]), [2, 4]); + assert_eq!(found(&["minecraft:dirt"]), [2, 4]); + assert_eq!( + found(&["minecraft:oak_planks", "minecraft:diamond"]), + [0, 1, 2, 4] + ); + assert_eq!(found(&["minecraft:apple", "minecraft:apple"]), [2, 3, 4]); + } + /// A recipe unlocked tests only the criteria that name it. + #[test] + fn recipe_index_keeps_the_criteria_of_the_recipe() { + let mut tree = Tree::default(); + for (i, conditions) in [ + serde_json::json!({"recipes": "minecraft:oak_planks"}), + serde_json::json!({"recipes": "minecraft:stick"}), + serde_json::json!({}), + serde_json::json!({"recipes": "minecraft:oak_planks"}), + ] + .into_iter() + .enumerate() + { + tree.list.push(Advancement { + id: format!("test:{i}"), + parent: None, + display: None, + criteria: vec![Criterion { + name: "c".into(), + trigger: "minecraft:recipe_unlocked".into(), + conditions, + }], + requirements: vec![vec!["c".into()]], + rewards: Rewards::default(), + }); + tree.by_trigger + .entry("minecraft:recipe_unlocked".into()) + .or_default() + .push((i, 0)); + } + tree.index_recipes(); + assert_eq!( + tree.recipe_criteria("minecraft:oak_planks"), + [(0, 0), (2, 0), (3, 0)] + ); + assert_eq!(tree.recipe_criteria("minecraft:stick"), [(1, 0), (2, 0)]); + assert_eq!(tree.recipe_criteria("minecraft:torch"), [(2, 0)]); + } #[test] fn bucket_axolotl_block_advancements_require_the_placed_block() { let ctx = Entities { diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index b391c0cbf..ce34df510 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -61,6 +61,8 @@ enum Animate { Fire, /// An active sculk sensor. SculkSensor, + /// Potent sulfur that is not dry. + PotentSulfur, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -128,6 +130,9 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { } } "respawn_anchor" if prop("charges").is_some_and(|c| c != "0") => Animate::RespawnAnchor, + "potent_sulfur" if prop("potent_sulfur_state").is_some_and(|s| s != "dry") => { + Animate::PotentSulfur + } "bubble_column" => Animate::BubbleColumn { drag: prop("drag").as_deref() == Some("true"), }, @@ -819,6 +824,26 @@ fn block_animate_tick( } } } + Animate::PotentSulfur => { + // PotentSulfurBlock.animateTick: under a water source, two + // bubbles and, one time in ten, the noxious gas. + let above = ctx.facts.get(ctx.state([pos[0], pos[1] + 1, pos[2]])); + if above.fluid == Fluid::Water && above.fluid_level == 8 && !above.fluid_falling { + for _ in 0..2 { + let r = engine.random(); + let p = [ + fx + f64::from(r.next_float()), + fy + 1.0 + f64::from(r.next_float()), + fz + f64::from(r.next_float()), + ]; + add(engine, T::SulfurBubbles, p, [0.0; 3]); + } + if next_int(engine.random(), 10) == 0 { + let name = "minecraft:block.potent_sulfur.noxious_gas"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + } + } Animate::Mycelium => { let r = engine.random(); if next_int(r, 10) == 0 { diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 62bdc041f..f101f53cd 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -2,7 +2,7 @@ //! small mixer standing in for OpenAL: one channel per source with its gain, //! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0, //! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding -//! (streams on a worker thread) and stereo panning. +//! (streams on a worker thread) and OpenAL Soft's stereo panning. use crate::Result; use crate::sound_engine::{ Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance, @@ -45,6 +45,7 @@ struct Mixer { channels: HashMap, listener: [f64; 3], listener_yaw: f32, + listener_pitch: f32, limiter_peak: f32, } /// A sound the player could have heard (`SoundEventListener.onPlaySound`): @@ -157,6 +158,9 @@ pub struct Audio { /// Positional sounds played since the last drain, kept while the world /// is open to the network so guests hear them too. pub capture: Option>, + /// How many times each positional sound played (the control socket's `status`), + /// with or without an audio device. + pub heard: std::collections::BTreeMap, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -331,6 +335,32 @@ impl Backend for MixerBackend { .unwrap_or(true) } } +/// OpenAL Soft's stereo gains `[left, right]` for a mono source in a +/// direction given in listener space (right, up, forward; any length). +/// Vanilla's context (`Library.createAttributes`: HRTF off) on a stereo +/// output renders pairwise: front azimuths are stretched by 1.5 +/// (`ScaleAzimuthFront`, so 60 degrees off-centre pans fully) and the +/// direction is decoded by the first-order stereo decoder, 0.5 W, 0.5 Y and +/// 0.0957 X in this scaling. A centred source gets 0.596 on each side, one +/// behind 0.404, one above or below 0.5, one at the source's own position +/// is panned to the front. Matches OpenAL Soft 1.25.2 (LWJGL 3.4.3, the +/// pinned client's) rendered through `ALC_SOFT_loopback` within 1e-5. +fn stereo_gains(right: f32, up: f32, forward: f32) -> [f32; 2] { + let length = (right * right + up * up + forward * forward).sqrt(); + if length <= f32::EPSILON { + return stereo_gains(0.0, 0.0, 1.0); + } + let elevation = (up / length).clamp(-1.0, 1.0).asin(); + let mut azimuth = right.atan2(forward); + if azimuth.abs() < std::f32::consts::FRAC_PI_2 { + azimuth = (azimuth.abs() * 1.5) + .min(std::f32::consts::FRAC_PI_2) + .copysign(azimuth); + } + let side = azimuth.sin() * elevation.cos(); + let front = azimuth.cos() * elevation.cos() * 0.095_660_8; + [0.5 - 0.5 * side + front, 0.5 + 0.5 * side + front] +} /// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference /// distance 0 and rolloff 1: the distance clamps to the max distance). fn distance_gain(linear: Option, distance: f32) -> f32 { @@ -345,9 +375,30 @@ fn distance_gain(linear: Option, distance: f32) -> f32 { fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { data.fill(0.0); let listener = mixer.listener; - let yaw = mixer.listener_yaw.to_radians(); + // The camera's forward and up vectors (`Camera.forwardVector`/`upVector`) + // and OpenAL's right = forward x up. + let (yaw, pitch) = ( + f64::from(mixer.listener_yaw.to_radians()), + f64::from(mixer.listener_pitch.to_radians()), + ); + let forward = [ + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ]; + let up = [ + -yaw.sin() * pitch.sin(), + pitch.cos(), + yaw.cos() * pitch.sin(), + ]; + let right = [ + forward[1] * up[2] - forward[2] * up[1], + forward[2] * up[0] - forward[0] * up[2], + forward[0] * up[1] - forward[1] * up[0], + ]; + let dot = |a: [f64; 3], b: [f64; 3]| (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) as f32; // Gains and pans per source for this buffer. - let mut voices: Vec<(ChannelId, f32, f32, f64)> = Vec::new(); + let mut voices: Vec<(ChannelId, [f32; 3], f64)> = Vec::new(); for (id, c) in &mixer.channels { let Some((_, source_rate)) = &c.samples else { continue; @@ -366,19 +417,17 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { }; let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance); - // The listener's right vector for a Minecraft yaw. - let side = if c.relative { - (d[0] as f32) / distance.max(0.001) + // Relative sources are already in OpenAL's listener space (-Z ahead). + let [left, right] = if c.relative { + stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32) } else { - (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001) - }; - let pan = side.clamp(-1.0, 1.0); - let left = gain * (1.0 - pan.max(0.0) * 0.6); - let right = gain * (1.0 + pan.min(0.0) * 0.6); + stereo_gains(dot(d, right), dot(d, up), dot(d, forward)) + } + .map(|pan| gain * pan); let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0)); - voices.push((*id, left, right, step)); + voices.push((*id, [left, right, gain], step)); } - for (id, left, right, step) in voices { + for (id, [left, right, gain], step) in voices { let Some(c) = mixer.channels.get_mut(&id) else { continue; }; @@ -402,16 +451,19 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { frame[0] += s * left; frame[1] += s * right; } else { - frame[0] += s * (left + right) / 2.0; + // A mono output has no panning: the source's own gain. + frame[0] += s * gain; } c.position += step; } } // Limit the whole buffer together, preserving waveform and stereo balance - // instead of flattening each overloaded sample; release over 50 ms. + // instead of flattening each overloaded sample; release over 200 ms + // (OpenAL Soft's output limiter, `ALC_OUTPUT_LIMITER_SOFT`, releases + // over 0.2 s). let peak = data.iter().fold(1.0f32, |peak, s| peak.max(s.abs())); mixer.limiter_peak = mixer.limiter_peak.max(peak); - let release = (-1.0 / (0.05 * rate as f32)).exp(); + let release = (-1.0 / (0.2 * rate as f32)).exp(); for frame in data.chunks_mut(channels) { let gain = mixer.limiter_peak.recip(); for s in frame { @@ -542,6 +594,7 @@ impl Audio { random: LegacyRandom::new(crate::sound_engine::unique_seed()), source_override: None, capture: None, + heard: Default::default(), } } #[cfg(not(feature = "audio"))] @@ -591,13 +644,15 @@ impl Audio { backend: &mut self.backend, } } - /// `SoundManager.updateSource`: the camera position and yaw. - pub fn set_listener(&mut self, position: [f64; 3], yaw: f32) { + /// `SoundManager.updateSource`: the camera position and rotation + /// (`Listener.setTransform` takes its forward and up vectors). + pub fn set_listener(&mut self, position: [f64; 3], yaw: f32, pitch: f32) { self.listener = position; self.listener_yaw = yaw; if let Ok(mut m) = self.backend.mixer.lock() { m.listener = position; m.listener_yaw = yaw; + m.listener_pitch = pitch; } } /// Sync the volume options, refreshing the categories that changed @@ -682,6 +737,9 @@ impl Audio { if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) { capture.push((event.to_owned(), at, volume, pitch)); } + if at.is_some() { + *self.heard.entry(event.to_owned()).or_default() += 1; + } self.sync_volumes(); let event = crate::sound_events::normalize(event); let source = self @@ -908,8 +966,9 @@ mod tests { } let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); + // West of a listener facing south: fully on the right. for (frame, sample) in data.as_chunks::<2>().0.iter().zip(wave) { - assert!((frame[0] - sample * 0.4).abs() < 1e-6, "{frame:?}"); + assert!(frame[0].abs() < 1e-6, "{frame:?}"); assert!((frame[1] - sample).abs() < 1e-6, "{frame:?}"); } assert!(data.iter().all(|s| s.abs() <= 1.0)); @@ -920,9 +979,10 @@ mod tests { let mut m = Mixer::default(); m.channels .insert(1, channel(vec![0.25; 2], None, [0.0; 3], true)); + let quiet = 0.25 * stereo_gains(0.0, 0.0, 1.0)[0]; let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); - assert_eq!(data, [0.25; 16]); + assert_eq!(data, [quiet; 16]); for id in 2..=5 { m.channels @@ -935,7 +995,7 @@ mod tests { mix(&mut m, &mut recovery, 2, 48_000); assert!(recovery[0] > 0.0 && recovery[0] < 0.1); assert!(recovery.windows(2).all(|w| w[1] >= w[0])); - assert_eq!(*recovery.last().unwrap(), 0.25); + assert_eq!(*recovery.last().unwrap(), quiet); } #[test] @@ -953,4 +1013,60 @@ mod tests { let first = data[0] + data[1]; assert!(first > 1.4 && first < 3.1, "{first}"); } + + #[test] + fn stereo_panning_matches_openal_soft() { + // OpenAL Soft 1.25.2 (LWJGL 3.4.3's macOS build), stereo loopback + // device with vanilla's attributes, 1 kHz sine 4 blocks away. + let cases = [ + ((0.0, 0.0, 1.0), [0.5957, 0.5957]), + ((-1.0, 0.0, 0.0), [1.0, 0.0]), + ((1.0, 0.0, 0.0), [0.0, 1.0]), + ((0.0, 0.0, -1.0), [0.4043, 0.4043]), + ((0.0, 1.0, 0.0), [0.5, 0.5]), + ((0.0, -1.0, 0.0), [0.5, 0.5]), + ((-1.0, 0.0, 1.0), [0.9985, 0.0747]), + ((-1.0, 0.0, -1.0), [0.7859, 0.0788]), + ((0.0, 0.0, 0.0), [0.5957, 0.5957]), + ]; + for ((right, up, forward), expected) in cases { + let gains = stereo_gains(right, up, forward); + for (g, e) in gains.into_iter().zip(expected) { + assert!((g - e).abs() < 1e-4, "{right} {up} {forward}: {gains:?}"); + } + } + } + + #[test] + fn panning_follows_the_camera_rotation() { + let gains = |yaw: f32, pitch: f32, at: [f32; 3]| { + let mut m = Mixer { + listener_yaw: yaw, + listener_pitch: pitch, + ..Mixer::default() + }; + m.channels.insert(1, channel(vec![1.0; 4], None, at, true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 2, 48_000); + data + }; + let close = + |a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4; + // Facing south (yaw 0), east is on the left; facing north, on the right. + assert!(close(gains(0.0, 0.0, [1.0, 0.0, 0.0]), [1.0, 0.0])); + assert!(close(gains(180.0, 0.0, [1.0, 0.0, 0.0]), [0.0, 1.0])); + // Looking straight down, a source below is ahead and one south is above. + assert!(close(gains(0.0, 90.0, [0.0, -1.0, 0.0]), [0.5957, 0.5957])); + assert!(close(gains(0.0, 90.0, [0.0, 0.0, 1.0]), [0.5, 0.5])); + } + + #[test] + fn a_mono_output_plays_sources_unpanned() { + let mut m = Mixer::default(); + m.channels + .insert(1, channel(vec![0.5; 4], None, [0.0, 0.0, -3.0], true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 1, 48_000); + assert_eq!(data, [0.5; 2]); + } } diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs index a6dfab1ee..b899ea5d5 100644 --- a/crates/horizon-client/src/auth.rs +++ b/crates/horizon-client/src/auth.rs @@ -174,7 +174,7 @@ pub fn discovery_url() -> String { fn agent() -> ureq::Agent { ureq::AgentBuilder::new() .timeout(Duration::from_secs(15)) - .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("Horizon/{}", horizon_core::release::VERSION)) .build() } diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs index 09989b8c9..483a68848 100644 --- a/crates/horizon-client/src/benchmark.rs +++ b/crates/horizon-client/src/benchmark.rs @@ -145,6 +145,8 @@ fn run(control: &Control, setup: Setup) -> Result { replace_world(&setup.game_dir)?; control.call(&format!("open {WORLD} {SEED} creative"))?; + // The world opens on a worker: its folder may not exist yet when `open` replies. + std::fs::create_dir_all(setup.game_dir.join("saves").join(WORLD)).map_err(|e| e.to_string())?; std::fs::write( setup.game_dir.join("saves").join(WORLD).join(MARKER), "Created by horizon-client --benchmark; replaced by the next run.\n", diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs index fa60b38f9..8d67953a5 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -130,7 +130,7 @@ impl Session { "initialize" => Ok(json!({ "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL), "capabilities": { "tools": {} }, - "serverInfo": { "name": "horizon-ctl", "version": env!("CARGO_PKG_VERSION") }, + "serverInfo": { "name": "horizon-ctl", "version": horizon_core::release::VERSION }, "instructions": "Play Horizon, a Rust reimplementation of Minecraft Java Edition. Start with launch (it finds the game installed by the Horizon launcher and opens or creates a world), then read the world with state, inventory, screen, entities and find_block, and act with goto, look_at_block, break, place, interact, click_slot and click_button. Actions block until they finish and report what happened. Coordinates are block coordinates; yaw 0 faces south (+Z).", })), "ping" => Ok(json!({})), diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index e0c6900cf..63ad004d4 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -182,3 +182,102 @@ impl Biomes { } } } + +/// A 24-bit colour as sRGB components in 0..1. +pub fn rgb(c: u32) -> [f32; 3] { + [16, 8, 0].map(|shift| (c >> shift & 255) as f32 / 255.0) +} + +/// `GaussianSampler.GAUSSIAN_SAMPLE_KERNEL`. +const GAUSSIAN_KERNEL: [f64; 7] = [0.0, 1.0, 4.0, 6.0, 4.0, 1.0, 0.0]; + +/// `EnvironmentAttributeProbe.tick`: `GaussianSampler.sample` over the noise +/// biomes (quart cells) around `position`, in blocks. Each biome comes once +/// with its summed weight, in the order it was first sampled, as +/// `SpatialAttributeInterpolator` keeps them (zero weights included). +pub fn gaussian_weights( + position: [f64; 3], + mut biome_at_quart: impl FnMut(i32, i32, i32) -> u16, +) -> Vec<(u16, f64)> { + let p = position.map(|c| c * 0.25 - 0.5); + let integral = p.map(|c| c.floor() as i32); + let relative: [f64; 3] = std::array::from_fn(|i| p[i] - f64::from(integral[i])); + let weight = |axis: usize, i: usize| { + let (start, end) = (GAUSSIAN_KERNEL[i + 1], GAUSSIAN_KERNEL[i]); + start + relative[axis] * (end - start) + }; + let mut weights: Vec<(u16, f64)> = Vec::new(); + for z in 0..6 { + let wz = weight(2, z); + for x in 0..6 { + let wx = weight(0, x); + for y in 0..6 { + let wy = weight(1, y); + let biome = biome_at_quart( + integral[0] - 2 + x as i32, + integral[1] - 2 + y as i32, + integral[2] - 2 + z as i32, + ); + let w = wx * wy * wz; + match weights.iter_mut().find(|(b, _)| *b == biome) { + Some((_, total)) => *total += w, + None => weights.push((biome, w)), + } + } + } + } + weights +} + +/// `SpatialAttributeInterpolator.applyAttributeLayer` for an RGB colour +/// (`ARGB.srgbLerp`: a component-wise lerp of the sRGB values). +pub fn blend_rgb(weights: &[(u16, f64)], mut value: impl FnMut(u16) -> [f32; 3]) -> [f32; 3] { + let mut result: Option<[f32; 3]> = None; + let mut accumulated = 0.0; + for &(biome, weight) in weights { + let v = value(biome); + accumulated += weight; + result = Some(match result { + None => v, + Some(r) => { + let t = (weight / accumulated) as f32; + std::array::from_fn(|i| r[i] + (v[i] - r[i]) * t) + } + }); + } + result.unwrap_or([0.0; 3]) +} + +#[cfg(test)] +mod blend_tests { + use super::*; + + #[test] + fn one_biome_keeps_its_colour() { + let weights = gaussian_weights([10.3, 64.0, -7.9], |_, _, _| 4); + assert_eq!(weights.len(), 1); + // The kernel sums to 16 per axis whatever the offset. + assert!((weights[0].1 - 16f64.powi(3)).abs() < 1e-9); + assert_eq!(blend_rgb(&weights, |_| [0.2, 0.4, 0.6]), [0.2, 0.4, 0.6]); + } + + #[test] + fn colour_changes_gradually_across_a_boundary() { + // Biome 1 for quart x >= 0 (block x >= 0), biome 0 below. + let at = |x: f64| { + let w = gaussian_weights([x, 40.0, 0.0], |qx, _, _| u16::from(qx >= 0)); + blend_rgb(&w, |b| if b == 1 { [1.0, 0.0, 0.0] } else { [0.0; 3] })[0] + }; + assert_eq!(at(-12.0), 0.0); + assert_eq!(at(12.0), 1.0); + // Halfway at the boundary, rising steadily through it. + assert!((at(0.0) - 0.5).abs() < 1e-5, "{}", at(0.0)); + let mut last = 0.0; + for i in -16..=16 { + let v = at(f64::from(i) * 0.5); + assert!(v >= last - 1e-6, "{v} < {last} at {i}"); + last = v; + } + assert!(at(-2.0) > 0.0 && at(-2.0) < 0.5); + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index db6bf7b79..21376d698 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -939,7 +939,14 @@ impl BlockEntityRenderer { !matches!(self.kind(state), Kind::None) } /// ChestRenderer and BannerRenderer submit their animated models for crumbling. - pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec) { + pub fn render_breaking( + &self, + scene: &Scene, + pos: [i32; 3], + state: u32, + stage: [f32; 2], + out: &mut Vec, + ) { if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) { return; } @@ -958,7 +965,7 @@ impl BlockEntityRenderer { false, out, ); - crate::breaking::entity_geometry(&mut out[start..], origin); + crate::breaking::entity_geometry(&mut out[start..], origin, stage); } /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) @@ -1942,7 +1949,7 @@ mod tests { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); let mut cracks = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut cracks); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut cracks); assert!(!cracks.is_empty()); assert_eq!( base.iter().map(|v| v.pos).collect::>(), @@ -1956,7 +1963,7 @@ mod tests { scene.lid = &|_| 1.0; } let mut animated = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut animated); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut animated); assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos)); scene.game_time = 0; scene.lid = &|_| 0.0; diff --git a/crates/horizon-client/src/breaking.rs b/crates/horizon-client/src/breaking.rs index c7ee19206..84eedae75 100644 --- a/crates/horizon-client/src/breaking.rs +++ b/crates/horizon-client/src/breaking.rs @@ -23,7 +23,21 @@ pub fn decal_uv([x, y, z]: [f32; 3], direction: Direction) -> [f32; 2] { [-p[0], -p[1]] } -pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: &mut Vec) { +/// The light bytes of a crack vertex: the pass is unlit, so they carry the origin of the +/// vertex's destroy stage sprite (each crack in `LevelRenderer.destroyingBlocks` has its own +/// stage; every stage sprite has the same size, `crumbling_sprite.zw`). +pub fn stage_light([u0, v0]: [f32; 2]) -> u32 { + let q = |x: f32| (x.clamp(0.0, 1.0) * 65535.0).round() as u32; + q(u0) | (q(v0) << 16) +} + +pub fn geometry( + model: &BakedModel, + origin: glam::Vec3, + translucent: bool, + stage: [f32; 2], + out: &mut Vec, +) { // Vanilla visits all six cull groups and then the unculled faces, even beside solid neighbours. for cull in Direction::ALL.map(Some).into_iter().chain([None]) { for face in model.faces.iter().filter(|face| face.quad.cull == cull) { @@ -33,7 +47,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: uv: decal_uv(pos, face.quad.facing), layer: if translucent { 12 } else { 11 }, color: 0xffff_ffff, - light: 240 | (240 << 8), + light: stage_light(stage), normal: [0; 4], }); } @@ -42,7 +56,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: } /// Project a block entity's transformed quads onto the same destroy-stage pass. -pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { +pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3, stage: [f32; 2]) { for quad in vertices.as_chunks_mut::<4>().0 { let positions = [0, 1, 2].map(|i| glam::Vec3::from(quad[i].pos)); let normal = (positions[1] - positions[0]).cross(positions[2] - positions[0]); @@ -65,7 +79,7 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { vertex.uv = decal_uv((glam::Vec3::from(vertex.pos) - origin).to_array(), facing); vertex.layer = 11; vertex.color = 0xffff_ffff; - vertex.light = 240 | (240 << 8); + vertex.light = stage_light(stage); } } } @@ -73,6 +87,24 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { #[cfg(test)] mod tests { use super::*; + + #[test] + fn stage_origin_survives_the_light_bytes() { + // entity.wgsl's `wrap`: the low and high 16 bits over 65535. + for origin in [[0.0, 0.0], [0.5, 0.25], [0.123_456, 0.987_654], [1.0, 1.0]] { + let light = stage_light(origin); + let back = [ + (light & 0xffff) as f32 / 65535.0, + (light >> 16) as f32 / 65535.0, + ]; + for k in 0..2 { + assert!( + (back[k] - origin[k]).abs() <= 0.5 / 65535.0, + "{origin:?} -> {back:?}" + ); + } + } + } use crate::models::catalog::BakedFace; use horizon_assets::{bake::ModelQuad, model::Material}; fn slab_top() -> BakedModel { @@ -109,7 +141,13 @@ mod tests { fn slab_overlay_follows_baked_top_not_unit_cube() { let model = slab_top(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::new(2.0, 3.0, 4.0), false, &mut vertices); + geometry( + &model, + glam::Vec3::new(2.0, 3.0, 4.0), + false, + [0.0; 2], + &mut vertices, + ); assert_eq!(vertices.len(), 4); for (v, p) in vertices.iter().zip(model.faces[0].quad.positions) { assert_eq!(v.pos, [p[0] + 2.0, p[1] + 3.0, p[2] + 4.0]); @@ -120,14 +158,14 @@ mod tests { fn entity_overlay_uses_block_local_projected_uvs() { let origin = glam::Vec3::new(12.0, -3.0, 8.0); let mut expected = Vec::new(); - geometry(&slab_top(), origin, false, &mut expected); + geometry(&slab_top(), origin, false, [0.0; 2], &mut expected); let mut actual = expected.clone(); for vertex in &mut actual { vertex.uv = [0.0; 2]; vertex.layer = 0; vertex.color = 0; } - entity_geometry(&mut actual, origin); + entity_geometry(&mut actual, origin, [0.0; 2]); assert_eq!( bytemuck::cast_slice::<_, u8>(&actual), bytemuck::cast_slice::<_, u8>(&expected) @@ -143,7 +181,7 @@ mod tests { #[test] fn translucent_overlay_has_its_own_pass() { let mut vertices = Vec::new(); - geometry(&slab_top(), glam::Vec3::ZERO, true, &mut vertices); + geometry(&slab_top(), glam::Vec3::ZERO, true, [0.0; 2], &mut vertices); assert!(vertices.iter().all(|v| v.layer == 12)); } #[test] @@ -151,7 +189,7 @@ mod tests { let mut model = slab_top(); model.faces.clear(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::ZERO, false, &mut vertices); + geometry(&model, glam::Vec3::ZERO, false, [0.0; 2], &mut vertices); assert!(vertices.is_empty()); } } diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index a52f25ce7..67f5d6027 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -15,8 +15,9 @@ use horizon_world::{ entity_obstruction::EntityIdentity, fluid::{FluidKind, FluidState}, liquid_collision::LiquidCollisionWorld, + piston_shape::PistonCollisionWorld, powder_snow_collision::{PowderSnowEntity, PowderSnowWorld}, - registry::{BlockRegistry, BlockTableFile}, + registry::{BlockRegistry, BlockStateId, BlockTableFile}, world_movement::{ CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision, resolve_world_movement, @@ -259,8 +260,30 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> { fn shulker_is_closed(&mut self, _: [i32; 3]) -> io::Result> { Ok(None) } - fn moving_piston_shape(&mut self, _: [i32; 3]) -> io::Result> { - Ok(None) + /// `MovingPistonBlock.getCollisionShape`: the block entity's moving shape + /// (`PistonMovingBlockEntity.getCollisionShape`), outside any push. + fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result> { + let Some(&(_, piston)) = self.world.moving_pistons.iter().find(|(q, _)| *q == p) else { + return Ok(None); + }; + let binding = self.binding; + let Some(pistons) = binding.pistons() else { + return Ok(None); + }; + pistons + .collision_shape(self, p, piston, None) + .map(Some) + .map_err(io::Error::other) + } +} +impl PistonCollisionWorld for SceneCollisions<'_, '_> { + type Error = io::Error; + /// `BlockState.getCollisionShape(level, pos)` of the moved state. + fn collision_shape(&mut self, state: BlockStateId, p: [i32; 3]) -> io::Result { + let binding = self.binding; + binding + .collision_shape(self, state, p) + .map_err(io::Error::other) } } impl DynamicCollisionWorld for SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6a135799c..854332815 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -528,7 +528,7 @@ impl Furnace { let has_fuel = self.items[1].is_some(); if lit || has_fuel && has_ingredient { if let Some(ingredient) = self.items[0].clone() { - if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient).cloned() { + if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient) { if self.cooking_timer == 0 { self.cooking_total = total_time(recipe.time, self.speed); } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index e96ca0067..d0b8906ee 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1102,7 +1102,11 @@ pub struct Recipes { facts: HashMap, Facts>, /// The `#minecraft:curse` enchantments. curses: HashSet, + /// The first cooking recipe of each kind taking each item, built at the + /// first lookup (furnaces look theirs up every tick). + cook_index: std::sync::OnceLock, } +type CookIndex = HashMap>; /// `MinMaxBounds.Ints` as (min, max) with the given defaults. fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) { match v { @@ -1421,6 +1425,7 @@ impl Recipes { meta, facts, curses, + cook_index: Default::default(), }) } /// Match a `size`x`size` grid (row-major) against the crafting recipes. @@ -1606,6 +1611,22 @@ impl Recipes { out } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { + let index = self.cook_index.get_or_init(|| { + let mut index = CookIndex::new(); + for (i, c) in self.cooking.iter().enumerate() { + let of_kind = index.entry(c.kind.clone()).or_default(); + for item in &c.ingredient.0 { + of_kind.entry(item.clone()).or_insert(i); + } + } + index + }); + let i = *index.get(kind)?.get(&*input.item)?; + self.cooking.get(i) + } + /// `cook` by scanning every recipe, as it was before the index. + #[cfg(test)] + fn cook_scan(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking .iter() .find(|c| c.kind == kind && c.ingredient.test(input)) @@ -1625,6 +1646,80 @@ mod tests { s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; s } + /// About vanilla's count of cooking recipes: four kinds, ingredients of + /// one to twelve items, overlapping (several recipes take some items). + fn cooking_book() -> Recipes { + let kinds = ["smelting", "blasting", "smoking", "campfire_cooking"]; + let cooking = (0..320usize) + .map(|i| Cooking { + id: format!("r{i}"), + category: "misc".into(), + group: String::new(), + kind: kinds[i % 4].into(), + ingredient: ingredient( + &(0..1 + i % 12) + .map(|k| format!("minecraft:item_{}", (i * 7 + k * 13) % 400)) + .collect::>() + .iter() + .map(String::as_str) + .collect::>(), + ), + result: ItemStack::new("minecraft:stone", 1), + experience: 0.1, + time: 200, + }) + .collect(); + Recipes { + crafting: Vec::new(), + cooking, + meta: HashMap::new(), + facts: HashMap::new(), + curses: HashSet::new(), + cook_index: Default::default(), + } + } + #[test] + fn cook_finds_the_first_recipe_the_scan_finds() { + let recipes = cooking_book(); + for kind in [ + "smelting", + "blasting", + "smoking", + "campfire_cooking", + "other", + ] { + for n in 0..420 { + let stack = ItemStack::new(&format!("minecraft:item_{n}"), 1); + let a = recipes.cook(kind, &stack).map(|c| &c.id); + let b = recipes.cook_scan(kind, &stack).map(|c| &c.id); + assert_eq!(a, b, "{kind} item_{n}"); + } + } + } + /// A furnace's recipe lookup, once per lit furnace per tick. + #[test] + #[ignore] + fn cook_cost() { + let recipes = cooking_book(); + let stacks: Vec = (0..1000) + .map(|n| ItemStack::new(&format!("minecraft:item_{}", n % 400), 1)) + .collect(); + let t = std::time::Instant::now(); + let a = stacks + .iter() + .filter(|s| recipes.cook_scan("smelting", s).cloned().is_some()) + .count(); + let before = t.elapsed().as_secs_f64() * 1e3; + recipes.cook("smelting", &stacks[0]); + let t = std::time::Instant::now(); + let b = stacks + .iter() + .filter(|s| recipes.cook("smelting", s).is_some()) + .count(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!("1000 furnace lookups (scan and clone -> index): {before:.3} ms -> {after:.3} ms"); + } fn run(special: &Special, cells: &[ItemStack]) -> Option { let recipes = Recipes { crafting: Vec::new(), @@ -1632,6 +1727,7 @@ mod tests { meta: HashMap::new(), facts: HashMap::new(), curses: HashSet::new(), + cook_index: Default::default(), }; let ctx = Context { recipes: &recipes, diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index 8ee5803b5..e147bfb4c 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -105,18 +105,23 @@ impl Report { } } -/// The release tag (the launcher installs each build in a folder named after it) and the client's -/// own version, or just the latter. +/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's +/// crate version; for a build from source, that version alone. pub fn version() -> String { let version = env!("CARGO_PKG_VERSION"); - match release_tag() { - Some(tag) => format!("{tag} (client {version})"), - None => version.to_owned(), + match (horizon_core::release::RELEASE, release_tag()) { + (Some(_), Some(tag)) => tag, + (None, Some(tag)) => format!("{tag} (client {version})"), + (_, None) => version.to_owned(), } } -/// The release this binary came with: launcher installs live in a folder named after the tag. +/// The release this binary came with: the version release.yml built in (docs/versioning.md), else +/// the folder the launcher installed it in, named after the tag (releases from before 0.2). pub fn release_tag() -> Option { + if let Some(version) = horizon_core::release::RELEASE { + return Some(format!("v{version}")); + } let exe = std::env::current_exe().ok()?; let folder = exe.parent()?.file_name()?.to_str()?; (folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit())) @@ -517,6 +522,18 @@ pub fn debug_crash_after() -> Option { mod tests { use super::*; + #[test] + fn a_release_reports_its_built_in_version() { + // release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed. + match horizon_core::release::RELEASE { + Some(version) => { + assert_eq!(release_tag(), Some(format!("v{version}"))); + assert_eq!(super::version(), format!("v{version}")); + } + None => assert!(release_tag().is_none() || super::version().contains("(client ")), + } + } + fn report() -> Report { Report { time: chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(), diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 80445d541..55e4eb28e 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -44,6 +44,7 @@ pub struct Creative { search_index: Vec, } /// Display names from the pinned en_us language file. +#[derive(Default)] pub struct Names { map: HashMap, } diff --git a/crates/horizon-client/src/dynamic_light.rs b/crates/horizon-client/src/dynamic_light.rs new file mode 100644 index 000000000..4502b3356 --- /dev/null +++ b/crates/horizon-client/src/dynamic_light.rs @@ -0,0 +1,133 @@ +//! Horizon Extras' dynamic lights (docs/extras.md): a torch, lantern or other light source held by +//! a player or mob, dropped as an item, or an entity on fire lights the blocks and entities +//! around it. Not in vanilla; off by default. +//! +//! Client-only and at render time: the light engine, chunk meshes and saves never see it. Each +//! frame the game picks the [`MAX`] sources nearest the camera; terrain.wgsl and entity.wgsl +//! raise a vertex's block light to `level - distance` (one level per block, as block light falls +//! off) when that is brighter. Off, the list is empty and the shaders skip the loop. +use crate::blocks::BlockFacts; +use glam::DVec3; +use horizon_world::registry::BlockRegistry; +use std::collections::HashMap; + +/// Lights the shaders read: `Globals.dynamic_lights` in gfx.rs, terrain.wgsl and entity.wgsl. +pub const MAX: usize = 16; +/// What an entity on fire gives off, as a lit campfire or fire block does. +pub const BURNING: u8 = 15; +/// Sources farther than this from the camera light nothing it can see well. +const REACH: f64 = 96.0; + +/// How brightly each item glows when held or dropped. +#[derive(Debug, Default)] +pub struct Luminance(HashMap); + +impl Luminance { + /// A block item glows like its block's default state (`getLightEmission`): torches 14, + /// lanterns and glowstone 15, a lit redstone torch 7; a furnace's item, unlit, not at all. + pub fn new(facts: &BlockFacts, registry: &BlockRegistry) -> Self { + let mut map = HashMap::new(); + for (id, state) in facts.states.iter().enumerate() { + if state.emission == 0 || *state.item != *state.name { + continue; + } + if registry.default_state(&state.name).map(|d| d.0 as usize) == Some(id) { + map.insert(state.item.to_string(), state.emission); + } + } + // A bucket of lava glows as lava does. + map.insert("minecraft:lava_bucket".into(), 15); + Self(map) + } + + pub fn of(&self, item: &str) -> u8 { + self.0.get(item).copied().unwrap_or(0) + } + + #[cfg(test)] + fn from_pairs(pairs: &[(&str, u8)]) -> Self { + Self(pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()) + } +} + +/// One light this frame: where it is (world space) and its level, 1 to 15. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Source { + pub at: DVec3, + pub level: u8, +} + +/// The [`MAX`] sources nearest `camera` within reach, as the shaders read them: camera-relative +/// position and level. Overwrites `out`. +pub fn select(sources: &[Source], camera: DVec3, out: &mut Vec<[f32; 4]>) { + out.clear(); + let key = |s: &Source| s.at.distance_squared(camera); + let mut near: Vec<&Source> = sources + .iter() + .filter(|s| s.level > 0 && key(s) <= REACH * REACH) + .collect(); + near.sort_by(|a, b| key(a).total_cmp(&key(b))); + out.extend(near.into_iter().take(MAX).map(|s| { + let p = (s.at - camera).as_vec3(); + [p.x, p.y, p.z, f32::from(s.level.min(15))] + })); +} + +/// The block light a vertex at `pos` (camera-relative) gets from `lights`, 0 to 15: the WGSL +/// `dynamic_block_light` in Rust, for tests. +pub fn level_at(pos: [f32; 3], lights: &[[f32; 4]]) -> f32 { + lights.iter().fold(0.0f32, |level, l| { + let d = + ((pos[0] - l[0]).powi(2) + (pos[1] - l[1]).powi(2) + (pos[2] - l[2]).powi(2)).sqrt(); + level.max(l[3] - d) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nearest_sources_win() { + let camera = DVec3::new(100.0, 64.0, 100.0); + let mut sources: Vec = (0..40) + .map(|i| Source { + at: camera + DVec3::new(f64::from(i), 0.0, 0.0), + level: 14, + }) + .collect(); + sources.push(Source { + at: camera + DVec3::new(0.5, 0.0, 0.0), + level: 0, + }); + sources.push(Source { + at: camera + DVec3::new(0.0, 0.0, 200.0), + level: 15, + }); + let mut out = Vec::new(); + select(&sources, camera, &mut out); + assert_eq!(out.len(), MAX); + assert_eq!(out[0], [0.0, 0.0, 0.0, 14.0]); + assert_eq!(out[MAX - 1][0], (MAX - 1) as f32); + select(&[], camera, &mut out); + assert!(out.is_empty()); + } + + #[test] + fn light_falls_off_a_level_per_block() { + let torch = [[0.0, 0.0, 0.0, 14.0]]; + assert_eq!(level_at([0.0, 0.0, 0.0], &torch), 14.0); + assert_eq!(level_at([3.0, 4.0, 0.0], &torch), 9.0); + assert_eq!(level_at([20.0, 0.0, 0.0], &torch), 0.0); + let two = [[0.0, 0.0, 0.0, 14.0], [10.0, 0.0, 0.0, 15.0]]; + assert_eq!(level_at([8.0, 0.0, 0.0], &two), 13.0); + assert_eq!(level_at([0.0; 3], &[]), 0.0); + } + + #[test] + fn item_luminance() { + let l = Luminance::from_pairs(&[("minecraft:torch", 14)]); + assert_eq!(l.of("minecraft:torch"), 14); + assert_eq!(l.of("minecraft:stone"), 0); + } +} diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index a988eeb55..ca2ea6f5c 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -60,6 +60,7 @@ pub struct ItemProps { /// `minecraft:brewing_fuel` present. pub brewing_fuel: bool, } +#[derive(Default)] pub struct Enchantments { pub list: Vec, index: HashMap, usize>, @@ -192,6 +193,8 @@ impl Enchantments { || k.starts_with("item.minecraft.splash_potion") || k.starts_with("item.minecraft.lingering_potion") || k.starts_with("item.minecraft.tipped_arrow") + || k.starts_with("item.minecraft.firework_rocket.") + || k.starts_with("item.minecraft.firework_star.") || k.starts_with("trim_") || k.starts_with("potion.") || k.starts_with("container.") diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index acb2203a4..cfbdb0636 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -24,6 +24,9 @@ pub struct ItemEntity { pub age: u32, pub pickup_delay: u32, pub bob_offset: f32, + /// `Entity.tickCount`: ticks since the item entered the level, which + /// paces `ItemEntity.mergeWithNeighbours`. + pub ticks: u32, } /// Environment results needed by the entity owner, including lethal lava damage. #[derive(Debug)] @@ -102,6 +105,7 @@ impl ItemEntity { facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, ) -> bool { + self.ticks += 1; self.previous = self.position; if self.pickup_delay > 0 && self.pickup_delay != u32::MAX { self.pickup_delay -= 1; @@ -175,6 +179,130 @@ impl ItemEntity { self.age += 1; self.age < 6000 && self.position.y > -128.0 } + /// `ItemEntity.isMergable` at `age`: a stack below its size whose pickup + /// delay isn't infinite, before its lifetime ends. + fn mergeable(&self, age: u32, max_stack: u32) -> bool { + self.pickup_delay != u32::MAX && age < 6000 && self.stack.count < max_stack + } +} +/// Dropped items by block cell, for `ItemEntity.mergeWithNeighbours`'s +/// search around an item. Holds indexes into the tick's item list. +#[derive(Default)] +pub struct ItemCells { + cells: crate::fast_hash::FxHashMap<(i32, i32, i32), Vec>, +} +impl ItemCells { + pub fn new(items: &[ItemEntity]) -> Self { + let mut cells = Self::default(); + for (i, item) in items.iter().enumerate() { + cells.add(i, item.position); + } + cells + } + fn cell(p: Vec3) -> (i32, i32, i32) { + (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32) + } + fn add(&mut self, i: usize, at: Vec3) { + self.cells.entry(Self::cell(at)).or_default().push(i as u32); + } + pub fn remove(&mut self, i: usize, at: Vec3) { + if let Some(list) = self.cells.get_mut(&Self::cell(at)) { + list.retain(|&j| j as usize != i); + } + } + pub fn moved(&mut self, i: usize, from: Vec3, to: Vec3) { + if Self::cell(from) != Self::cell(to) { + self.remove(i, from); + self.add(i, to); + } + } + /// The items whose cells could hold a box meeting `area`, in the order + /// they were added (vanilla lists a section's entities in the order they + /// entered it). + fn near(&self, area: Aabb, out: &mut Vec) { + out.clear(); + // An item's box reaches 0.125 sideways and 0.25 up from its position. + let (min, max) = (area.min_position(), area.max_position()); + let (lo, hi) = ( + Self::cell(Vec3::new(min.x - 0.125, min.y - 0.25, min.z - 0.125)), + Self::cell(Vec3::new(max.x + 0.125, max.y, max.z + 0.125)), + ); + for x in lo.0..=hi.0 { + for y in lo.1..=hi.1 { + for z in lo.2..=hi.2 { + if let Some(list) = self.cells.get(&(x, y, z)) { + out.extend_from_slice(list); + } + } + } + } + out.sort_unstable(); + } +} +/// `ItemEntity.mergeWithNeighbours` for `items[i]`, which has just moved in +/// its tick (its `age` already counts this tick; vanilla's doesn't yet): each +/// mergeable item whose box meets this one's grown by 0.5 sideways takes this +/// stack or gives it its own, the smaller into the larger +/// (`ItemEntity.tryToMerge`), until this item is used up. An emptied item is +/// marked in `removed`. +pub fn merge_with_neighbours( + items: &mut [ItemEntity], + removed: &mut [bool], + cells: &mut ItemCells, + i: usize, + max_stack: &dyn Fn(&ItemStack) -> u32, +) { + let age = |items: &[ItemEntity], j: usize| { + if j == i { + items[j].age - 1 + } else { + items[j].age + } + }; + if removed[i] || !items[i].mergeable(age(items, i), max_stack(&items[i].stack)) { + return; + } + let area = items[i].bounds().inflate(Vec3::new(0.5, 0.0, 0.5)); + let mut near = Vec::new(); + cells.near(area, &mut near); + for j in near { + let j = j as usize; + if j == i + || removed[j] + || !items[j].bounds().intersects(area) + || !items[j].mergeable(age(items, j), max_stack(&items[j].stack)) + { + continue; + } + // ItemEntity.areMergable: both fit one stack of the same item and components. + let (this, other) = (&items[i].stack, &items[j].stack); + if this.count + other.count > max_stack(other) || !this.same_item_same_components(other) { + continue; + } + let (to, from) = if other.count < this.count { + (i, j) + } else { + (j, i) + }; + // ItemEntity.merge(toStack, fromStack, 64). + let room = max_stack(&items[to].stack).min(64) - items[to].stack.count; + let moved = room.min(items[from].stack.count); + items[to].stack.count += moved; + items[from].stack.count -= moved; + let (delay, from_age, to_age) = + (items[from].pickup_delay, age(items, from), age(items, to)); + let to_item = &mut items[to]; + to_item.pickup_delay = to_item.pickup_delay.max(delay); + // This item's age goes up once its tick ends. + to_item.age = to_age.min(from_age) + u32::from(to == i); + if items[from].stack.count == 0 { + removed[from] = true; + cells.remove(from, items[from].position); + } + if removed[i] { + return; + } + } } /// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks. #[derive(Clone, Debug)] @@ -455,6 +583,10 @@ pub struct ArmorStand { pub no_base_plate: bool, pub invisible: bool, pub marker: bool, + /// `CustomName`: the text of a hologram. + pub custom_name: Option, + /// `CustomNameVisible`. + pub name_visible: bool, /// Game time of the last hit (the wobble and the second-hit window). pub last_hit: i64, } @@ -475,6 +607,8 @@ impl ArmorStand { no_base_plate: false, invisible: false, marker: false, + custom_name: None, + name_visible: false, last_hit: i64::MIN / 2, } } @@ -634,6 +768,7 @@ mod fire_environment_tests { age: 0, pickup_delay: 0, bob_offset: 0.0, + ticks: 0, }; let mut wood = make("minecraft:oak_planks"); let mut metal = make("minecraft:netherite_ingot"); @@ -705,3 +840,179 @@ mod fire_environment_tests { assert_eq!(stand.health, 20.0, "lava does not hurt armor stands"); } } +#[cfg(test)] +mod merge_tests { + use super::*; + + fn item(id: &str, count: u32, x: f64, age: u32) -> ItemEntity { + let at = Vec3::new(x, 64.0, 0.5); + ItemEntity { + id: 0, + thrower: None, + stack: ItemStack { + item: std::sync::Arc::from(id), + count, + damage: 0, + extra: None, + }, + health: 5, + fire_ticks: 0, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: true, + age, + pickup_delay: 0, + bob_offset: 0.0, + ticks: age, + } + } + fn max_stack(stack: &ItemStack) -> u32 { + if &*stack.item == "minecraft:ender_pearl" { + 16 + } else { + 64 + } + } + /// Merges around `items[i]` as its tick would; returns the counts left. + fn merge(items: &mut [ItemEntity], i: usize) -> Vec> { + let mut removed = vec![false; items.len()]; + let mut cells = ItemCells::new(items); + merge_with_neighbours(items, &mut removed, &mut cells, i, &max_stack); + items + .iter() + .zip(removed) + .map(|(item, gone)| (!gone).then_some(item.stack.count)) + .collect() + } + + #[test] + fn the_smaller_stack_goes_into_the_larger() { + let mut items = [ + item("minecraft:sand", 3, 0.5, 41), + item("minecraft:sand", 5, 1.2, 7), + ]; + assert_eq!(merge(&mut items, 0), [None, Some(8)]); + // ItemEntity.merge keeps the younger age; the ticking item's is + // still the one before its tick. + assert_eq!(items[1].age, 7); + let mut items = [ + item("minecraft:sand", 5, 0.5, 41), + item("minecraft:sand", 3, 1.2, 7), + ]; + assert_eq!(merge(&mut items, 0), [Some(8), None]); + assert_eq!(items[0].age, 8, "age 7, plus the rest of this tick"); + } + + #[test] + fn items_merge_only_within_half_a_block_sideways() { + // Boxes 0.25 wide grown by 0.5: centres closer than 0.75 meet. + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 1.24, 1), + ]; + assert_eq!(merge(&mut items, 0), [None, Some(2)]); + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 1.26, 1), + ]; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 0.5, 1), + ]; + items[1].position.y += 0.3; + assert_eq!( + merge(&mut items, 0), + [Some(1), Some(1)], + "no vertical growth" + ); + } + + #[test] + fn different_or_full_stacks_stay_apart() { + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:gravel", 1, 0.5, 1), + ]; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + let mut items = [ + item("minecraft:sand", 60, 0.5, 1), + item("minecraft:sand", 10, 0.5, 1), + ]; + assert_eq!( + merge(&mut items, 0), + [Some(60), Some(10)], + "70 is over a stack" + ); + let mut items = [ + item("minecraft:ender_pearl", 10, 0.5, 1), + item("minecraft:ender_pearl", 6, 0.5, 1), + ]; + assert_eq!(merge(&mut items, 0), [Some(16), None]); + let mut items = [ + item("minecraft:ender_pearl", 16, 0.5, 1), + item("minecraft:ender_pearl", 1, 0.5, 1), + ]; + assert_eq!( + merge(&mut items, 0), + [Some(16), Some(1)], + "a full stack doesn't merge" + ); + } + + #[test] + fn unmergeable_items_are_skipped() { + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 0.5, 1), + ]; + items[1].pickup_delay = u32::MAX; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + // At age 6000 the other item's lifetime is over; this one's tick + // started at 5999, so it may still merge into a live item. + let mut items = [ + item("minecraft:sand", 1, 0.5, 6000), + item("minecraft:sand", 1, 0.5, 6000), + ]; + assert_eq!(merge(&mut items, 0), [Some(1), Some(1)]); + items[1].age = 10; + assert_eq!(merge(&mut items, 0), [None, Some(2)]); + assert_eq!(items[1].age, 10); + } + + #[test] + fn a_stack_takes_its_neighbours_in_spawn_order_until_full() { + let mut items = [ + item("minecraft:sand", 40, 0.5, 1), + item("minecraft:sand", 20, 0.7, 1), + item("minecraft:sand", 10, 0.3, 1), + item("minecraft:sand", 3, 0.4, 1), + ]; + // 40 + 20 = 60; 60 + 10 is over 64; then 3 more. + assert_eq!(merge(&mut items, 0), [Some(63), None, Some(10), None]); + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 0.5, 1), + ]; + items[1].pickup_delay = 30; + assert_eq!(merge(&mut items, 0), [None, Some(2)]); + assert_eq!(items[1].pickup_delay, 30, "the longer pickup delay stays"); + } + + #[test] + fn the_cells_follow_moves() { + let mut items = [ + item("minecraft:sand", 1, 0.5, 1), + item("minecraft:sand", 1, 5.5, 1), + ]; + let mut removed = [false; 2]; + let mut cells = ItemCells::new(&items); + let from = items[1].position; + items[1].position.x = 0.9; + cells.moved(1, from, items[1].position); + merge_with_neighbours(&mut items, &mut removed, &mut cells, 0, &max_stack); + assert_eq!(removed, [true, false]); + assert_eq!(items[1].stack.count, 2); + } +} diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index c6305c697..2e865dfb1 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -14,11 +14,13 @@ struct Globals { // Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: array, 2>, // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) - // y: Nether cardinal lighting. + // y: Nether cardinal lighting, z: how many dynamic_lights are set. time: vec4, crumbling_sprite: vec4, // Selection outline parameters (read by terrain.wgsl). outline_params: vec4, + // Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs). + dynamic_lights: array, 16>, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var atlas: texture_2d; @@ -41,6 +43,7 @@ struct Out { @location(8) back_color: vec4, // entity.vsh's lightMapColor, multiplied in after the overlay. @location(9) light_color: vec4, + @location(10) @interpolate(flat) weather_rect: vec4, } // Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed. fn entity_light(normal: vec3, nether: bool) -> f32 { @@ -58,20 +61,33 @@ fn overlay_texel(overlay: u32) -> vec4 { if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); } return vec4(1.0); } +// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units +// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one +// level less per block. time.z of them are set: none when the extra is off, so no loop runs. +fn dynamic_block_light(pos: vec3) -> f32 { + let count = min(u32(globals.time.z), 16u); + var level = 0.0; + for (var i = 0u; i < count; i++) { + let l = globals.dynamic_lights[i]; + level = max(level, l.w - distance(pos, l.xyz)); + } + return level * 16.0; +} fn entity_vertex(position: vec3, uv: vec2, overlay: u32, color: vec4, light: vec4, normal: vec4) -> Out { var out: Out; out.clip = globals.view_proj * vec4(position, 1.0); out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw); out.uv = uv; - let l = vec2(f32(light.y), f32(light.x)); + let l = vec2(max(f32(light.y), dynamic_block_light(position)), f32(light.x)); let lm = textureSampleLevel(lightmap, lightmap_sampler, clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); // Celestial bodies, clouds, beacon beams, End portals and breaking cracks are unlit. let unlit = overlay == 2u || overlay == 4u || overlay == 6u || overlay == 9u || overlay == 10u || overlay == 11u || overlay == 12u; out.light_color = select(lm, vec4(1.0), unlit); - // Overlay 6 (beacon beams): the light bytes carry the sprite's v range. + // Overlay 6 (beacon beams): the light bytes carry the sprite's v range; 11 and 12 + // (cracks): the destroy stage sprite's origin. out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0; // minecraft_mix_light: the vertex colour times the cardinal light only. var c = color; @@ -94,6 +110,13 @@ fn entity_vertex(position: vec3, uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { return entity_vertex(position, uv, overlay, color, light, normal); } +// Retained bolt-local geometry, translated using the same f64 camera +// subtraction as the former CPU path before adding each local f32 position. +@vertex fn vs_lightning(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4, + @location(6) offset: vec3) -> Out { + return entity_vertex(offset + position, uv, overlay, color, light, normal); +} struct CloudInfo { offset: vec4, colors: array, 4>, @@ -147,7 +170,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } if in.overlay == 11u || in.overlay == 12u { - uv = globals.crumbling_sprite.xy + fract(in.uv) * globals.crumbling_sprite.zw; + // Each crack's stage sprite origin comes in its light bytes (breaking::stage_light). + uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw; } var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front); if in.overlay == 9u || in.overlay == 10u { @@ -188,3 +212,140 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; return color; } + +// RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). +@fragment fn fs_water_mask() -> @location(0) vec4 { + return vec4(0.0); +} + +// WEATHER_MATH_BEGIN +// Unsigned 64-bit helpers (low word first). Snow adds a random double to a +// float drift before casting to float. Retaining the 53-bit base avoids early +// rounding, including ties, without requiring optional GPU float64 support. +fn weather_shr_jam(v: vec2, n: u32) -> vec2 { + if n == 0u { return v; } + if n < 32u { + return vec2((v.x >> n) | (v.y << (32u - n)) | select(0u, 1u, (v.x << (32u - n)) != 0u), v.y >> n); + } + if n == 32u { return vec2(v.y | select(0u, 1u, v.x != 0u), 0u); } + if n < 64u { + return vec2((v.y >> (n - 32u)) | select(0u, 1u, v.x != 0u || (v.y << (64u - n)) != 0u), 0u); + } + return vec2(select(0u, 1u, any(v != vec2(0u))), 0u); +} +fn weather_add64(a: vec2, b: vec2) -> vec2 { + let lo = a.x + b.x; + return vec2(lo, a.y + b.y + select(0u, 1u, lo < a.x)); +} +fn weather_sub64(a: vec2, b: vec2) -> vec2 { + return vec2(a.x - b.x, a.y - b.y - select(0u, 1u, a.x < b.x)); +} +fn weather_double_plus_float(base: vec2, delta: f32) -> f32 { + // The random base is nonnegative and either zero or >= 2^-53. + if all(base == vec2(0u)) { return select(delta, 0.0, delta == 0.0); } + let db = bitcast(delta); + let mag = db & 0x7fffffffu; + let be = i32((base.y >> 20u) & 2047u) - 1023; + var de = i32(mag >> 23u) - 127; + var dm = (mag & 0x7fffffu) | 0x800000u; + if mag < 0x800000u { + dm = mag; + if dm == 0u { de = -200; } + else { + let shift = countLeadingZeros(dm) - 8u; + dm <<= shift; + de = -126 - i32(shift); + } + } + let e = max(be, de); + // Leading significand bit at 61, with room for addition and guard bits. + var a = vec2(base.x << 9u, ((base.y & 0xfffffu) | 0x100000u) << 9u | (base.x >> 23u)); + var b = vec2(0u, dm << 6u); + a = weather_shr_jam(a, u32(e - be)); + b = weather_shr_jam(b, u32(e - de)); + var sign = 0u; + var value: vec2; + if (db >> 31u) == 0u { value = weather_add64(a, b); } + else if a.y > b.y || (a.y == b.y && a.x >= b.x) { value = weather_sub64(a, b); } + else { value = weather_sub64(b, a); sign = 0x80000000u; } + if all(value == vec2(0u)) { return 0.0; } + let leading = select(31u - countLeadingZeros(value.x), 63u - countLeadingZeros(value.y), value.y != 0u); + var exponent = e + i32(leading) - 61; + // Normalize the leading bit to 62. After jamming, bit 38 is the guard + // bit and bits 0..37 distinguish a tie from a value above the midpoint. + let shift = 62u - leading; + if shift >= 32u { value = vec2(0u, value.x << (shift - 32u)); } + else if shift != 0u { value = vec2(value.x << shift, (value.y << shift) | (value.x >> (32u - shift))); } + // Vanilla first rounds the addition to double, then casts to float. + // Round at bit 10 (53 retained bits) before the 24-bit rounding below; + // otherwise a double-rounding midpoint can select the wrong float. + let double_guard = (value.x & 512u) != 0u; + let double_sticky = (value.x & 511u) != 0u; + let double_odd = (value.x & 1024u) != 0u; + value.x &= 0xfffffc00u; + if double_guard && (double_sticky || double_odd) { + value = weather_add64(value, vec2(1024u, 0u)); + } + if (value.y & 0x80000000u) != 0u { + value = weather_shr_jam(value, 1u); + exponent += 1; + } + var mantissa = value.y >> 7u; + let guard = (value.y & 64u) != 0u; + let sticky = (value.y & 63u) != 0u || value.x != 0u; + if guard && (sticky || (mantissa & 1u) != 0u) { mantissa += 1u; } + if mantissa >= 0x1000000u { mantissa >>= 1u; exponent += 1; } + return bitcast(sign | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu)); +} +fn weather_phase(animation: vec4, bases: vec4, snow: u32, time: vec4) -> vec2 { + if snow == 0u { + let ticks = time.x + animation.y; + let t = ticks + time.z; + let step = -t / 32.0; + let offset = step * animation.x; + return vec2(0.0, offset % 32.0); + } + let t = time.x + time.z; + let u_time = t * 0.01; + let du = u_time * animation.z; + let v_time = t * animation.w; + let dv = v_time * 0.001; + let u = weather_double_plus_float(bases.xy, du); + let v = weather_double_plus_float(bases.zw, dv); + let fall_time = time.y + time.z; + let fall = -fall_time / 512.0; + return vec2(u, fall + v); +} +// Atlas sampler is nearest with no mipmaps. Clamp the integer texel inside +// the sprite even when a fractional coordinate rounds up at its far edge. +fn weather_texel(uv: vec2, rect: vec4, dimensions: vec2) -> vec2 { + let size = vec2(dimensions); + let origin = vec2(round(rect.xy * size)); + let extent = max(vec2(round(rect.zw * size)), vec2(1)); + let local = min(vec2(floor(fract(uv) * vec2(extent))), extent - vec2(1)); + return origin + local; +} +// WEATHER_MATH_END + +struct WeatherTime { values: vec4 } +@group(1) @binding(1) var weather_time: WeatherTime; +@vertex fn vs_weather(@location(0) position: vec3, @location(1) uv: vec2, + @location(2) rect: vec4, @location(3) animation: vec4, + @location(4) bases: vec4, @location(5) color: vec4, + @location(6) light: vec4, @location(7) snow: u32) -> Out { + let phase = weather_phase(animation, bases, snow, weather_time.values); + var out = entity_vertex(position, uv + phase, 0u, color, light, vec4(0.0)); + out.weather_rect = rect; + return out; +} +@fragment fn fs_weather(in: Out) -> @location(0) vec4 { + // Repeat within this sprite, never across the atlas. The atlas uses nearest + // filtering and no mipmaps, so fractional UVs have no seam derivatives. + let texel = weather_texel(in.uv, in.weather_rect, textureDimensions(atlas)); + var color = textureLoad(atlas, texel, 0) * in.color; + if color.a < 0.1 { discard; } + color *= in.light_color; + let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), + linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); + return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index d1c3665ed..aaccdd844 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -13,6 +13,7 @@ use crate::{ doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, uuid_from_tag, }, + text::Text, }; use horizon_core::geometry::Vec3; use horizon_world::nbt::{Compound, Tag}; @@ -555,6 +556,14 @@ fn custom_name(tag: &Tag) -> Option { _ => None, } } +/// `CustomName` as text: a string keeps its legacy formatting codes, anything +/// else is a component (`ComponentSerialization`). +pub fn name_text(tag: &Tag) -> Text { + match tag { + Tag::String(s) => Text::legacy(&s.to_string_lossy()), + t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), + } +} pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option { let kind = types.get(&self::kind(tag)?)?.clone(); let position = position(tag)?; @@ -606,6 +615,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.persistent = flag(tag, "PersistenceRequired"); m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); + m.custom_name_text = tag.get("CustomName").map(name_text); if m.kind.category == "creature" { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; @@ -914,9 +924,47 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option, +) -> Tag { + let base = Base { + id: "minecraft:ominous_item_spawner", + uuid, + position, + motion: Vec3::ZERO, + rotation: [0.0, 0.0], + on_ground: false, + fall_distance: 0.0, + }; + let mut tag = base.tag(raw); + put(&mut tag, "item", item_to_nbt(item)); + put( + &mut tag, + "spawn_item_after_ticks", + Tag::Long(spawn_item_after), + ); + tag +} +/// `OminousItemSpawner.readAdditionalSaveData`: the item, where it floats +/// and `spawn_item_after_ticks` (0 when absent). None without an item: +/// such a spawner would spawn nothing. +pub fn ominous_item_spawner_from_nbt(tag: &Tag) -> Option<(crate::items::ItemStack, Vec3, i64)> { + let item = tag.get("item").and_then(item_from_nbt)?; + let after = number(tag.get("spawn_item_after_ticks")).unwrap_or(0); + Some((item, position(tag)?, after)) +} + /// `ExperienceOrb`: Health, Age, Value, Count. pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag { let base = Base { @@ -1228,6 +1276,21 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) -> } else if let Tag::Compound(map) = &mut tag { map.remove(&"Marker".into()); } + if a.name_visible { + put(&mut tag, "CustomNameVisible", Tag::Byte(1)); + } else if let Tag::Compound(map) = &mut tag { + map.remove(&"CustomNameVisible".into()); + } + // A name from the save keeps its own shape unless it changed. + if let Some(name) = &a.custom_name + && !tag.get("CustomName").is_some_and(|t| name_text(t) == *name) + { + put( + &mut tag, + "CustomName", + crate::scoreboard::json_to_tag(&name.component()), + ); + } put(&mut tag, "Health", Tag::Float(a.health.to_bits())); put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16)); // LivingEntity.addAdditionalSaveData and ArmorStand's own fields. @@ -1256,6 +1319,8 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { a.velocity = motion(tag); a.health = float(tag.get("Health")).unwrap_or(20.0) as f32; a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32; + a.custom_name = tag.get("CustomName").map(name_text); + a.name_visible = flag(tag, "CustomNameVisible"); if let Some(eq) = tag.get("equipment") { for (i, slot) in ArmorStand::SLOTS.iter().enumerate() { a.equipment[i] = eq.get(slot).and_then(item_from_nbt); @@ -1504,6 +1569,63 @@ mod tests { use super::*; use crate::items::ItemStack; + /// The item, the spawn delay and the fields Horizon doesn't model come + /// back; a compound without an item is no spawner. + #[test] + fn ominous_item_spawner_round_trip() { + let item = ItemStack { + item: Arc::from("minecraft:ominous_trial_key"), + count: 1, + damage: 0, + extra: None, + }; + let raw = Tag::compound([("CustomName", string("kept"))]); + let at = Vec3::new(10.5, 64.25, -3.5); + let tag = ominous_item_spawner_to_nbt(&item, at, 97, [1, 2, 3, 4], Some(&raw)); + assert_eq!( + kind(&tag).as_deref(), + Some("minecraft:ominous_item_spawner") + ); + assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); + assert!(matches!( + tag.get("spawn_item_after_ticks"), + Some(Tag::Long(97)) + )); + assert!(tag.get("CustomName").is_some()); + let (back, pos, after) = ominous_item_spawner_from_nbt(&tag).unwrap(); + assert_eq!( + (back.item.as_ref(), back.count), + ("minecraft:ominous_trial_key", 1) + ); + assert_eq!((pos, after), (at, 97)); + assert!(ominous_item_spawner_from_nbt(&raw).is_none()); + } + + #[test] + fn armor_stand_names_keep_their_formatting_across_a_save() { + let tag = Tag::compound([ + ( + "Pos", + Tag::List(vec![ + Tag::Double(0.0f64.to_bits()), + Tag::Double(64.0f64.to_bits()), + Tag::Double(0.0f64.to_bits()), + ]), + ), + ("CustomName", string("§6Hello")), + ("CustomNameVisible", Tag::Byte(1)), + ]); + let a = armor_stand_from_nbt(&tag, 7).unwrap(); + let name = a.custom_name.as_ref().unwrap(); + assert_eq!(name.plain(), "Hello"); + assert!(name.spans[0].style.color.is_some()); + assert!(a.name_visible); + let saved = armor_stand_to_nbt(&a, [0; 4], Some(&tag)); + let restored = armor_stand_from_nbt(&saved, 7).unwrap(); + assert_eq!(restored.custom_name, a.custom_name); + assert!(restored.name_visible); + } + #[test] fn falling_block_round_trip_keeps_impact_distance_and_settings() { let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); @@ -1553,6 +1675,7 @@ mod tests { on_ground: true, age: 120, pickup_delay: 10, + ticks: 0, bob_offset: 0.0, }; let tag = item_entity_to_nbt(&e, [1, 2, 3, 4], None); diff --git a/crates/horizon-client/src/environment.rs b/crates/horizon-client/src/environment.rs index ee2c921d0..20855b749 100644 --- a/crates/horizon-client/src/environment.rs +++ b/crates/horizon-client/src/environment.rs @@ -230,16 +230,20 @@ impl Environment { fn base(&self, name: &str) -> [f32; 4] { self.base.get(name).copied().unwrap_or([0.0, 0.0, 0.0, 1.0]) } - /// Sky state for a time of day, with the biome's sky and fog colours as base values. - pub fn sample(&self, ticks: i64, biome_sky: Option, biome_fog: Option) -> Sky { - let rgb = |c: u32| { - [ - (c >> 16 & 255) as f32 / 255.0, - (c >> 8 & 255) as f32 / 255.0, - (c & 255) as f32 / 255.0, - 1.0, - ] - }; + /// The dimension's value of an RGB attribute (what biomes without it keep). + pub fn base_rgb(&self, name: &str) -> [f32; 3] { + let b = self.base(name); + [b[0], b[1], b[2]] + } + /// Sky state for a time of day, with the biomes' (blended) sky and fog + /// colours as base values. + pub fn sample( + &self, + ticks: i64, + biome_sky: Option<[f32; 3]>, + biome_fog: Option<[f32; 3]>, + ) -> Sky { + let rgb = |c: [f32; 3]| [c[0], c[1], c[2], 1.0]; let v = |name: &str, base: [f32; 4]| self.value(name, base, ticks); let three = |a: [f32; 4]| [a[0], a[1], a[2]]; let scalar = |name: &str| { diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index ee142486c..c7be78019 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -69,6 +69,8 @@ impl Corner { #[derive(Clone, Debug, PartialEq)] pub struct Extras { pub fullbright: bool, + /// Held, dropped and burning light sources light their surroundings (`dynamic_light`). + pub dynamic_lights: bool, pub zoom: bool, /// A vanilla key name (`key.keyboard.z`). pub zoom_key: String, @@ -110,6 +112,7 @@ impl Default for Extras { fn default() -> Self { Self { fullbright: false, + dynamic_lights: false, zoom: false, zoom_key: "key.keyboard.z".into(), zoom_level: 4, @@ -158,6 +161,7 @@ impl Extras { }; match key.trim() { "fullbright" => e.fullbright = flag(e.fullbright), + "dynamicLights" => e.dynamic_lights = flag(e.dynamic_lights), "zoom" => e.zoom = flag(e.zoom), "zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(), "zoomLevel" => { @@ -201,8 +205,9 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "fullbright:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n", + "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n", bool_text(self.fullbright), + bool_text(self.dynamic_lights), bool_text(self.zoom), self.zoom_key, self.zoom_level, @@ -423,6 +428,7 @@ impl Cps { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Item { Fullbright, + DynamicLights, Zoom, ZoomKey, ZoomLevel, @@ -452,6 +458,7 @@ pub fn rows() -> Vec> { vec![ Err("Lighting"), Ok(Fullbright), + Ok(DynamicLights), Err("Zoom"), Ok(Zoom), Ok(ZoomKey), @@ -501,11 +508,12 @@ impl Item { pub fn caption(self) -> &'static str { match self { Item::Fullbright => "Fullbright", + Item::DynamicLights => "Dynamic lights", Item::Zoom => "Zoom", Item::ZoomKey => "Zoom key", Item::ZoomLevel => "Starting zoom", Item::ZoomSmooth => "Smooth zoom", - Item::ZoomSensitivity => "Lower sensitivity while zoomed", + Item::ZoomSensitivity => "Slower turning", Item::Fps => "FPS counter", Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => "Corner", Item::Minimap => "Minimap", @@ -523,10 +531,29 @@ impl Item { Item::KeystrokesCps => "Clicks per second", } } + /// The switch this setting belongs to: it does nothing while that is off. + pub fn parent(self) -> Option { + use Item::*; + Some(match self { + ZoomKey | ZoomLevel | ZoomSmooth | ZoomSensitivity => Zoom, + MinimapCorner | MinimapSize | MinimapShape | MinimapZoom | MinimapRotate => Minimap, + FpsCorner | FpsLows => Fps, + KeystrokesCorner | KeystrokesCps => Keystrokes, + MouseTweaksWheel => MouseTweaks, + SortKey => Sort, + Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort + | AutoReconnect => { + return None; + } + }) + } /// What the row says under its caption. pub fn description(self) -> &'static str { match self { Item::Fullbright => "Show blocks and entities at full light, even in dark areas.", + Item::DynamicLights => { + "Torches and other light sources held, dropped or on fire light the blocks around them." + } Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.", Item::ZoomKey => "Click, then press a key. Escape unbinds it.", Item::ZoomLevel => "The zoom the key starts at.", @@ -566,7 +593,7 @@ impl Item { use crate::graphics_style::Cost; match self { Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), - Item::Minimap => Some(Cost::Low), + Item::Minimap | Item::DynamicLights => Some(Cost::Low), Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None), _ => None, } @@ -575,6 +602,7 @@ impl Item { pub fn switch(self, e: &Extras) -> Option { Some(match self { Item::Fullbright => e.fullbright, + Item::DynamicLights => e.dynamic_lights, Item::Zoom => e.zoom, Item::ZoomSmooth => e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity, @@ -617,6 +645,7 @@ impl Item { pub fn cycle(self, e: &mut Extras, back: bool) { match self { Item::Fullbright => e.fullbright = !e.fullbright, + Item::DynamicLights => e.dynamic_lights = !e.dynamic_lights, Item::Zoom => e.zoom = !e.zoom, Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity, @@ -662,7 +691,7 @@ mod tests { #[test] fn everything_is_off_by_default_and_round_trips() { let d = Extras::default(); - assert!(!d.fullbright); + assert!(!d.fullbright && !d.dynamic_lights); assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect); assert!(!d.mouse_tweaks && !d.sort); assert_eq!(Extras::parse(""), d); @@ -670,6 +699,9 @@ mod tests { let mut e = d.clone(); Item::Fullbright.cycle(&mut e, false); assert_eq!(Item::Fullbright.switch(&e), Some(true)); + Item::DynamicLights.cycle(&mut e, false); + assert_eq!(Item::DynamicLights.switch(&e), Some(true)); + assert_eq!(Extras::parse(&e.serialize()), e); e.zoom = true; e.zoom_key = "key.keyboard.c".into(); e.zoom_level = 6; diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index a25d9f537..463d51437 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -21,6 +21,8 @@ pub enum ItemPose { Trident { ticks_used: f32, }, + /// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork. + SpinAttack, Bow { ticks_used: f32, }, @@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - if matches!(pose, ItemPose::Using) { return m; } + if matches!(pose, ItemPose::SpinAttack) { + return m + * Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3)) + * Mat4::from_rotation_y((invert * 65.0f32).to_radians()) + * Mat4::from_rotation_z((invert * -85.0f32).to_radians()); + } let charging = match pose { ItemPose::Bow { ticks_used } => { let power = ticks_used / 20.0; diff --git a/crates/horizon-client/src/friends_screen.rs b/crates/horizon-client/src/friends_screen.rs new file mode 100644 index 000000000..7577e2add --- /dev/null +++ b/crates/horizon-client/src/friends_screen.rs @@ -0,0 +1,303 @@ +//! Play with Friends: Horizon's own sharing of the open world behind an +//! invite code (`game/friends.rs`). The pause menu's Friends button, the icon +//! vanilla's PauseScreen already has, opens it. It is drawn the way a mod adds +//! a screen to vanilla: the menu background, a centred title and text, +//! vanilla's buttons and Done in the footer. +use crate::{ + hud::{HudAtlas, HudBatch, rgba}, + multiplayer::wrap, + text::Text, + ui, +}; + +pub const TITLE: &str = "Play with Friends"; +/// What the screen shows (game/friends.rs fills it). +#[derive(Clone, Debug, Default)] +pub struct FriendsView { + /// A singleplayer world (not a server): sharing is offered. + pub shown: bool, + pub sharing: bool, + pub code: Option, + /// Who can join and what to do when friends on the internet can't (or, + /// before the code, what the game is doing). + pub status: String, + /// Friends on the internet can reach the host. + pub reachable: bool, + /// Where the troubleshooting is, when they can't. + pub help: Option, + /// The players in the world besides the host. + pub guests: Vec, + pub notice: Option, + /// The code was just copied. + pub copied: bool, +} + +/// A button's action. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Share, + Copy, + Stop, + /// Open the troubleshooting page. + Help, + Done, +} + +fn grey() -> u32 { + rgba(160, 160, 160, 255) +} +const WHITE: u32 = u32::MAX; +const HINT: &str = "Friends paste the code after the title screen's Friends button, in Direct Connection, or on the launcher's Play page."; + +struct Button { + x: f32, + y: f32, + w: f32, + label: &'static str, + action: Action, + active: bool, +} + +/// The centred lines (text, colour, y) and the buttons. +fn layout( + atlas: &HudAtlas, + (w, h): (f32, f32), + view: &FriendsView, +) -> (Vec<(String, u32, f32)>, Vec - - -
The launcher's Play page: the version, Client and Server, the version picker and Play, the prepared resources and the Minecraft folder as a numbered list
-
Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, the last world played and the faint wordmark, over a veiled snowy landscape
-
The Singleplayer page: the worlds as a numbered list with their dates and game modes, and Create world and Play
-
The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs
-
The pause screen of a world, with Back to game, Open to LAN and Save and quit
+
Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs
-

The launcher, and Horizon's own menus in the game. The launcher opens them, or vanilla's.

+

The launcher, and Horizon's graphics settings in the game: vanilla's menus, with Horizon's pages added the way mods add theirs.

-
+
-

05Patch notes

-

What changed

+

05Releases

+

Recently added

+

Alpha builds come out many times a day, as changes land; about once a day the tested ones become Stable, the launcher's default. The newest, and what they added:

-
- {{NOTES}} +
+ {{RECENT}}
@@ -235,7 +238,7 @@ diff --git a/website/src/main.js b/website/src/main.js index 825de1f25..4298cf1fd 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -1,53 +1,26 @@ // The page's behaviour: the download buttons for this platform, the latest releases, the -// links and contributors, the navigation, the menus' tabs, the lightbox and the motion. +// links and contributors, how many play now, the navigation, the menus' tabs, the lightbox +// and the motion. // Everything degrades to the baked-in content when GitHub can't be reached. import { escape } from "./markdown.js"; -import { releasesHtml } from "./releases.js"; +import { recentHtml } from "./releases.js"; import { contributorsFrom, contributorsHtml } from "./contributors.js"; +import { isGame, isLauncher as isLauncherTag, launcherVersion, newestFirst } from "./versions.js"; +import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; const REPO = "ludovic111/horizon"; -const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher-v&expanded=true`; +const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher&expanded=true`; const baked = JSON.parse(document.getElementById("baked").textContent); const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; // --- GitHub -------------------------------------------------------------------------- -async function cached(key, load) { - try { - const hit = JSON.parse(sessionStorage.getItem(key) || "null"); - if (hit && Date.now() - hit.at < 10 * 60 * 1000) return hit.value; - } catch {} - const value = await load(); - try { - sessionStorage.setItem(key, JSON.stringify({ at: Date.now(), value })); - } catch {} - return value; -} - -async function get(url, as = "json") { - const res = await fetch(url, { headers: as === "json" ? { Accept: "application/vnd.github+json" } : {} }); - if (!res.ok) throw new Error(`${res.status}`); - return as === "json" ? res.json() : res.text(); -} - -const slim = (r) => ({ - tag_name: r.tag_name, - name: r.name, - published_at: r.published_at, - html_url: r.html_url, - prerelease: r.prerelease, - body: r.body || "", - assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), -}); -const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}/.test(tag); -const isLauncher = (r) => r.tag_name.startsWith("launcher-v") && !r.prerelease; -const versionKey = (tag) => tag.replace("launcher-v", "").split(".").map(Number); -const newer = (a, b) => versionKey(b).reduce((d, n, i) => d || n - (versionKey(a)[i] || 0), 0); +const isLauncher = (r) => isLauncherTag(r.tag_name) && !r.prerelease; // The newest 100 releases (GitHub's most per page). Game betas come out several times a day, so the stable game // release and the newest launcher release can both be older than all of them. The stable game release is then // GitHub's "latest" (betas and launcher releases are never marked latest); the launcher release is looked up by its -// tag (the newest launcher-v tag with a published release). +// tag (the newest launcher@ tag with a published release, or launcher-v before 0.2: docs/versioning.md). async function loadReleases() { const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=100`)).filter((r) => !r.draft).map(slim); if (!list.some((r) => isGame(r.tag_name) && !r.prerelease)) { @@ -55,8 +28,12 @@ async function loadReleases() { if (latest && !latest.draft) list.push(slim(latest)); } if (list.some(isLauncher)) return list; - const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/launcher-v`).catch(() => []); - const tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter((t) => /^launcher-v\d+\.\d+\.\d+$/.test(t)).sort(newer); + let tags = []; + for (const prefix of ["launcher@", "launcher-v"]) { + if (tags.length) break; + const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/${prefix}`).catch(() => []); + tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter(isLauncherTag).sort(newestFirst); + } for (const tag of tags.slice(0, 3)) { const release = await get(`https://api.github.com/repos/${REPO}/releases/tags/${tag}`).catch(() => null); if (release && !release.draft) return [...list, slim(release)]; @@ -91,9 +68,9 @@ function platform() { async function setUpDownload() { const os = platform(); const list = await releases; - const launcher = list.find((r) => r.tag_name.startsWith("launcher-v") && !r.prerelease); + const launcher = list.filter(isLauncher).sort((a, b) => newestFirst(a.tag_name, b.tag_name))[0]; if (!launcher) return; - const version = launcher.tag_name.replace("launcher-v", ""); + const version = launcherVersion(launcher.tag_name); const asset = os && launcher.assets.find((a) => a.name.includes(os.key)); const others = `Other platforms`; document.querySelectorAll("[data-download]").forEach((a) => (a.href = asset ? asset.browser_download_url : launcher.html_url || RELEASES_PAGE)); @@ -104,11 +81,12 @@ async function setUpDownload() { document.querySelectorAll("[data-download-meta]").forEach((p) => (p.innerHTML = meta)); } -// --- Patch notes and the links from main --------------------------------- +// --- Recently added and the links from main --------------------------------- -async function setUpNotes() { - const list = (await releases).filter((r) => isGame(r.tag_name) && !r.prerelease); - if (list.length) document.getElementById("releases").innerHTML = releasesHtml(list.slice(0, 3)); +// "Recently added": the newest game releases, Alpha and Stable. +async function setUpRecent() { + const html = recentHtml((await releases).filter((r) => isGame(r.tag_name))); + if (html) document.getElementById("recent-releases").innerHTML = html; } async function setUpLinks() { @@ -126,6 +104,34 @@ async function setUpLinks() { }); } +// --- Playing now --------------------------------------------------------------------- + +const TELEMETRY = "https://telemetry.playhorizon.dev"; + +// How many play right now, from the games' anonymous "I'm playing" pings (Privacy explains them). The +// server rounds it and makes it again at most every 15 seconds; the row stays hidden while nobody plays +// or the server doesn't answer. +async function setUpLive() { + const row = document.querySelector("[data-live]"); + if (!row) return; + const update = async () => { + try { + const res = await fetch(`${TELEMETRY}/v1/live`, { signal: AbortSignal.timeout(3000) }); + if (!res.ok) throw new Error(String(res.status)); + const { playing } = await res.json(); + if (!Number.isInteger(playing) || playing < 1) throw new Error("nobody"); + row.querySelector("[data-live-count]").textContent = playing.toLocaleString("en"); + row.hidden = false; + // It shows up after the others came in, so it skips their entrance. + row.classList.add("is-visible"); + } catch { + row.hidden = true; + } + }; + await update(); + setInterval(() => document.visibilityState === "visible" && update(), 60_000); +} + // --- Navigation ---------------------------------------------------------------------- function setUpNav() { @@ -149,40 +155,6 @@ function setUpNav() { }; onScroll(update); update(); - - // The phone menu: a full-screen sheet; the page behind it is inert while it is open. - const button = document.querySelector(".menu-button"); - const menu = document.getElementById("menu"); - const main = document.getElementById("main"); - const label = button.querySelector(".menu-label"); - const items = [...menu.querySelectorAll("nav a")]; - items.forEach((a, i) => a.style.setProperty("transition-delay", `${60 + i * 35}ms`)); - let closing; - const setOpen = (open) => { - clearTimeout(closing); - button.setAttribute("aria-expanded", String(open)); - label.textContent = open ? "Close" : "Menu"; - bar.classList.toggle("is-menu", open); - main.inert = open; - document.body.style.overflow = open ? "hidden" : ""; - if (open) { - menu.hidden = false; - requestAnimationFrame(() => requestAnimationFrame(() => menu.classList.add("is-open"))); - items[0].focus({ preventScroll: true }); - } else { - menu.classList.remove("is-open"); - closing = setTimeout(() => (menu.hidden = true), reducedMotion ? 0 : 320); - } - }; - button.addEventListener("click", () => setOpen(button.getAttribute("aria-expanded") !== "true")); - items.forEach((a) => a.addEventListener("click", () => setOpen(false))); - addEventListener("keydown", (e) => { - if (e.key === "Escape" && button.getAttribute("aria-expanded") === "true") { - setOpen(false); - button.focus(); - } - }); - matchMedia("(min-width: 1120px)").addEventListener("change", (e) => e.matches && setOpen(false)); } // One rAF-throttled scroll listener for everything that follows the scroll. @@ -252,27 +224,6 @@ function setUpLightbox() { }); } -// --- Light and dark ------------------------------------------------------------------ - -// The page follows the system; the toggle picks the other appearance and remembers it. -function setUpTheme() { - const root = document.documentElement; - const button = document.querySelector(".theme-toggle"); - const label = button.querySelector("[data-theme-label]"); - const system = matchMedia("(prefers-color-scheme: dark)"); - const dark = () => (root.dataset.theme ? root.dataset.theme === "dark" : system.matches); - const show = () => (label.textContent = dark() ? "Light" : "Dark"); - button.addEventListener("click", () => { - root.dataset.theme = dark() ? "light" : "dark"; - try { - localStorage.setItem("theme", root.dataset.theme); - } catch {} - show(); - }); - system.addEventListener("change", show); - show(); -} - // --- Motion --------------------------------------------------------------------------- function setUpReveal() { @@ -306,9 +257,11 @@ function setUpReveal() { setUpReveal(); setUpTheme(); setUpNav(); +setUpMenu(); setUpTabs(); setUpLightbox(); setUpDownload(); -setUpNotes(); +setUpRecent(); setUpLinks(); setUpContributors(); +setUpLive(); diff --git a/website/src/privacy.html b/website/src/privacy.html index d3593cb3c..6b562a4cf 100644 --- a/website/src/privacy.html +++ b/website/src/privacy.html @@ -5,8 +5,8 @@ Privacy · Horizon - - + + @@ -26,20 +26,25 @@
  • Performance statistics, after each play session of a minute or more. These are the frame-time and tick-time percentiles and a 14-bucket histogram (never a recording of each frame), the peak memory, how long the game took to start and to load the world, and the settings that change performance (render and simulation distance, frame limit, VSync, fullscreen, graphics mode).
  • Crash reports, when the game crashes. They hold the error, where it happened in Horizon's code, your graphics adapter and settings. They hold no log, no world, no server and no resource packs.
  • Bug reports that you write and send yourself. The end of the game's log goes with one only if you add it after reading it, and lines of chat are removed first.
  • -
  • Benchmark uploads of the benchmarks you run. These are shown publicly in the community results.
  • +
  • Benchmark uploads of the benchmarks you run. They are shown publicly on the Benchmarks page, only as medians of groups of at least 3 different installs with the same graphics card, processor and render distance; never one by one, and never with your install ID, the day, your OS version, driver, memory or screen.
  • Each one also carries the Horizon version, the day it was made (not the time), and a description of your machine: the operating system and version, the CPU model and thread count, the memory rounded to the gigabyte, and the GPU, its driver and the graphics backend. It also carries a random install ID. The launcher makes that ID the first time you allow something; it says nothing about you and exists only so that your data can be deleted.

    Never sent: your Microsoft or Minecraft account name or UUID, world names, server or LAN addresses, chat, and your user name or home folder in file paths. Before anything is kept, those are replaced with placeholders, along with e-mail and IP addresses. The server does not store the IP address requests come from.

    The launcher shows exactly what would be sent: Settings → Data collection → View what would be sent, or horizon-launcher data show. Every field is listed in docs/telemetry.md.

    +

    The "I'm playing" ping

    +

    The game sends an anonymous "I'm playing" ping, so the launcher can show how many people play Horizon right now. It is sent once a minute while you play, whatever the switches say.

    +

    It holds: a random number made when the game starts and forgotten when it closes, the Horizon version, your operating system (Linux, macOS or Windows), and whether you have a world open to LAN or to friends. It does not hold: your account, your install ID, world or server names, your hardware or settings, or anything you do in the game. The random number changes every time you start the game, so two of your sessions can't be linked to each other or to you.

    +

    The server keeps the pings in memory only, never on disk, and not with the address they came from (that is used only to stop abuse, as below). A session counts while it pinged in the last two minutes and is then forgotten. What it shows is the number playing now, per version and with a world open, rounded.

    +

    Why

    -

    To find what is slow or crashes on which machines, and fix it. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.

    +

    To find what is slow or crashes on which machines, and fix it. The ping shows players, and Horizon, how many people play right now. Benchmark uploads also show other players how Horizon runs on hardware like theirs. Nothing is sold, shared for advertising, or used to identify you.

    On what basis

    -

    Your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer.

    +

    For the switches: your consent (Article 6(1)(a) of the EU's General Data Protection Regulation). It is given kind by kind, recorded on your computer with the version of the question you answered and when, and withdrawn at any time with the same switches. Withdrawing deletes what was waiting to be sent. When what is collected changes, the launcher asks again, and nothing new is sent until you answer. The ping holds nothing that identifies you; the address it comes from is used only to limit how often one address may send, kept in memory for an hour at most and never stored.

    Where and how long

    -

    Items wait on your computer (telemetry/ in the game folder) and are sent compressed when the launcher starts or closes, to Horizon's own server at Railway. The server keeps them for 180 days, then deletes them. What stays after that are anonymous totals per day, Horizon version, operating system, GPU maker and render distance (for example "120 sessions on macOS with Apple GPUs at render distance 12"). They hold no install ID, and groups too small to be anonymous are never shown.

    +

    Items wait on your computer (telemetry/ in the game folder) and are sent compressed when the launcher starts or closes, to Horizon's own server, telemetry.playhorizon.dev, hosted by Railway in the European Union (Amsterdam, the Netherlands). The server keeps them for 180 days, then deletes them. What stays after that are anonymous totals per day, Horizon version, operating system, GPU maker and render distance (for example "120 sessions on macOS with Apple GPUs at render distance 12"). They hold no install ID, and groups too small to be anonymous are never shown.

    Deleting your data

    Settings → Data collection → Delete my data, or horizon-launcher data delete. The server deletes everything sent under your install ID, your share of the totals is recomputed, anything waiting on your computer is removed, and you get a new install ID. You can also turn everything off, or delete the telemetry/ folder.

    diff --git a/website/src/releases-page.js b/website/src/releases-page.js new file mode 100644 index 000000000..ace84f63d --- /dev/null +++ b/website/src/releases-page.js @@ -0,0 +1,78 @@ +// The Releases page: the list baked at build time, refreshed from GitHub when a newer release is out, and the +// channel filter. Without JavaScript the baked list reads as it is. +import { releasesPageHtml } from "./releases.js"; +import { isGame, isLauncher, newestFirst } from "./versions.js"; +import { cached, get, setUpMenu, setUpTheme, slim } from "./chrome.js"; + +const REPO = "ludovic111/horizon"; +const list = document.getElementById("release-list"); +const counter = document.querySelector("[data-release-count]"); +const buttons = [...document.querySelectorAll("[data-filter]")]; +let filter = "all"; + +const ours = (r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name)); + +// Every release, a page of 100 at a time (GitHub's most), up to 500. +async function loadAll() { + const all = []; + for (let page = 1; page <= 5; page++) { + const batch = await get(`https://api.github.com/repos/${REPO}/releases?per_page=100&page=${page}`); + all.push(...batch.filter(ours).map(slim)); + if (batch.length < 100) break; + } + return all; +} + +function apply() { + const entries = [...list.querySelectorAll(".release-entry")]; + let shown = 0; + for (const el of entries) { + const on = filter === "all" || el.dataset.channel === filter; + el.hidden = !on; + if (on) shown++; + } + counter.textContent = `${shown} release${shown === 1 ? "" : "s"}`; + buttons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.filter === filter))); +} + +async function refresh() { + // One small request first: the full list only when GitHub has something newer than the page. + const newest = await cached("horizon:releases-newest", () => get(`https://api.github.com/repos/${REPO}/releases?per_page=5`)).catch(() => null); + if (!newest) return; + const top = newest.filter(ours).map((r) => r.tag_name).sort(newestFirst)[0]; + if (!top || top === list.dataset.newest) return; + const all = await cached("horizon:releases-all", loadAll).catch(() => null); + if (!all || !all.length) return; + const open = new Set([...list.querySelectorAll(".release-entry[open]")].map((el) => el.id)); + list.innerHTML = releasesPageHtml(all); + list.dataset.newest = top; + // Keep what the reader opened open. + open.forEach((id) => document.getElementById(id)?.setAttribute("open", "")); + apply(); +} + +// A link to one release (/releases#release-v0.2.1) opens it. +function openTarget() { + const el = location.hash && document.getElementById(location.hash.slice(1)); + if (el && el.classList.contains("release-entry")) { + if (el.hidden) { + filter = "all"; + apply(); + } + el.open = true; + el.scrollIntoView(); + } +} + +buttons.forEach((b) => + b.addEventListener("click", () => { + filter = b.dataset.filter; + apply(); + }), +); +addEventListener("hashchange", openTarget); +setUpTheme(); +setUpMenu(); +apply(); +openTarget(); +refresh().then(openTarget); diff --git a/website/src/releases.html b/website/src/releases.html new file mode 100644 index 000000000..f0e4b2de4 --- /dev/null +++ b/website/src/releases.html @@ -0,0 +1,50 @@ + + + + + + Releases · Horizon + + + + + + + + + + + + + + + + + + + + + +{{SITE_NAV}} +
    +
    +

    ReleasesEvery version, newest first

    +

    What's new in Horizon

    +

    Each release lists what it adds and fixes, then its full notes and its downloads. Alpha builds come out many times a day as changes land and can break; about once a day the tested ones become Stable, what the launcher installs unless you pick Alpha in its Settings. The launcher has its own releases.

    +
    + + + + +
    +

    {{RELEASE_COUNT}}

    +
    +{{RELEASE_LIST}} +
    +

    The releases on GitHub

    +

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    +
    +
    +{{SITE_FOOTER}} + + diff --git a/website/src/releases.js b/website/src/releases.js index 38810f10b..2e6a2e524 100644 --- a/website/src/releases.js +++ b/website/src/releases.js @@ -1,42 +1,152 @@ -// The patch notes: the latest game release in full, the ones before it folded. Shared by -// build.mjs (baked into the page) and main.js (refreshed from GitHub). -import { markdown, escape } from "./markdown.js"; +// The release notes on the site: the home page's "Recently added" block and the Releases page (every release, +// newest first). Shared by build.mjs (baked into the pages) and the pages' scripts (refreshed from GitHub). +// Tags: the game's vX.Y.Z and the launcher's launcher@X.Y.Z from 0.2, vYYYY.MM.DD[.N] and launcher-vX.Y.Z before +// (src/versions.js). Alpha is a game pre-release, Stable a game release (docs/release-flow.md, "Channels"). +import { markdown, inline, escape } from "./markdown.js"; +import { isLauncher, launcherVersion, newestFirst } from "./versions.js"; const REPO = "ludovic111/horizon"; -// "Horizon 2026.10.13: 100% of harnessed vanilla parity" reads as the version and its line. -function parts(r) { - const version = r.tag_name.replace(/^v/, ""); - const name = r.name || ""; - const line = name.includes(": ") ? name.slice(name.indexOf(": ") + 2) : name.replace(/^Horizon\s*/, "").replace(version, "").trim(); +export const channel = (r) => (isLauncher(r.tag_name) ? "Launcher" : r.prerelease ? "Alpha" : "Stable"); +const anchor = (r) => `release-${r.tag_name.replace(/[^\w.-]/g, "-")}`; + +// "Horizon 0.2.3: Cave culling, weather" (before 0.2, "Horizon 2026.10.13: …") reads as the version and its line. +export function parts(r) { + const version = launcherVersion(r.tag_name) ?? r.tag_name.replace(/^v/, ""); + const name = (r.name || "").trim(); + let line = name.includes(": ") ? name.slice(name.indexOf(": ") + 2) : name.replace(/^Horizon( launcher)?\s*/i, "").replace(version, "").trim(); + if (junk(line)) line = fromNotes(r.body) || line; return { version, line: line.charAt(0).toUpperCase() + line.slice(1), date: (r.published_at || "").slice(0, 10) }; } -export function releasesHtml(list) { - if (!list.length) return ""; - const [latest, ...older] = list; - const l = parts(latest); - const head = `
    -
    -

    Latest release

    -

    ${escape(l.version)}

    - ${l.line ? `

    ${escape(l.line)}

    ` : ""} - Downloads and full notes -
    -
    ${markdown(latest.body || "")}
    -
    `; - const rest = older +// A title made of issue numbers and "fix" ("#1255, mob pushes, fix, #1222") says nothing. +const junk = (line) => { + const bits = line.split(",").map((b) => b.trim()).filter(Boolean); + return bits.length > 1 && bits.filter((b) => /^(#\d+|fix(es)?|fixed)$/i.test(b)).length * 2 >= bits.length; +}; + +// The first item that isn't a bare "Fix #123:" prefix, as the line: "Mob pushes: one list per mob… and 3 more fixes". +function fromNotes(body) { + const s = sections(body); + const items = [...s.filter((x) => /^new|what's new/i.test(x.title)), ...s.filter((x) => /^fixed/i.test(x.title))].flatMap((x) => x.items).map(plainItem); + const clean = items.map((i) => i.replace(/^(fix|fixes)\s+#\d+:\s*/i, "").replace(/^\w+\([^)]*\):\s*/, "")).filter(Boolean); + if (!clean.length) return ""; + const first = clean[0].replace(/[.]$/, ""); + return clean.length > 1 ? `${first} and ${clean.length - 1} more` : first; +} + +// The notes' "### Heading" sections and their top-level items, in order. +export function sections(body) { + const out = []; + let current = null; + for (const raw of (body || "").replace(/\r\n?/g, "\n").split("\n")) { + const heading = raw.match(/^#{2,3}\s+(.+?)\s*$/); + if (heading) out.push((current = { title: heading[1], items: [] })); + else if (current && /^[-*]\s+/.test(raw)) current.items.push(raw.replace(/^[-*]\s+/, "").trim()); + } + return out; +} + +// An item without its pull request references: "Riptide (#123, fixes #45)" -> "Riptide". +export const plainItem = (item) => item.replace(/\s*\((?:#\d+|fixes #\d+|[^()]*#\d+[^()]*)\)\s*/g, " ").replace(/\s+/g, " ").trim(); + +// The notes' first sentence, for a release with no title line and no sections ("Rebuilt from the latest main."). +const firstLine = (body) => ((body || "").split(/\r?\n/).find((l) => l.trim() && !/^#/.test(l)) || "").trim().replace(/[.:]$/, ""); + +const count = (n, one, many) => `${n} ${n === 1 ? one : many}`; + +// What a release changes, in a line: "12 new, 30 fixed, 2 known issues". +export function overview(r) { + const s = sections(r.body); + const by = (re) => s.filter((x) => re.test(x.title)).reduce((n, x) => n + x.items.length, 0); + const added = by(/^new|what's new/i); + const fixed = by(/^fixed/i); + const known = by(/^known/i); + const bits = []; + if (added) bits.push(count(added, "new feature", "new features")); + if (fixed) bits.push(count(fixed, "fix", "fixes")); + if (known) bits.push(count(known, "known issue", "known issues")); + return { added, fixed, known, text: bits.join(", ") }; +} + +export function highlights(r, n = 3) { + const added = sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items); + return added.slice(0, n).map(plainItem); +} + +const byTag = (a, b) => newestFirst(a.tag_name, b.tag_name); +const badge = (r) => `${channel(r)}`; + +// The home page: the newest releases on a line each, and what the newest ones added. +export function recentHtml(list, { rows = 5, picks = 3 } = {}) { + const sorted = [...list].sort(byTag); + const game = sorted.filter((r) => !isLauncher(r.tag_name)); + if (!game.length) return ""; + const lines = game + .slice(0, rows) .map((r) => { - const o = parts(r); - return `
    - ${escape(o.version)}${escape(o.line)} -
    ${markdown(r.body || "")}

    Downloads and full notes on GitHub

    -
    `; + const p = parts(r); + return `
  • ${escape(p.version)}${escape(p.line || overview(r).text || firstLine(r.body) || "Release notes")}${badge(r)}
  • `; }) .join(""); - return `${head} -
    - ${rest ? `

    Earlier releases

    ${rest}` : ""} -

    Every release on GitHub

    -
    `; + // What landed last: the "New" items of the newest releases with the highest pull request numbers (a release's + // notes list everything since the last Stable, oldest first). + const pr = (item) => Math.max(0, ...[...item.matchAll(/#(\d+)/g)].map((m) => Number(m[1]))); + const seen = new Set(); + const picked = game + .slice(0, rows) + .flatMap((r) => sections(r.body).filter((x) => /^new|what's new/i.test(x.title)).flatMap((x) => x.items).map((raw) => ({ raw, item: plainItem(raw), r }))) + .filter(({ item }) => !seen.has(item) && seen.add(item)) + .sort((a, b) => pr(b.raw) - pr(a.raw)) + .slice(0, picks); + const picks_ = picked + .map(({ item, r }) => `
  • ${inline(item)}

    ${escape(parts(r).version)}
  • `) + .join(""); + return `
      ${lines}
    + ${picks_ ? `

    New lately

      ${picks_}
    ` : ""} +

    Every release, with its full notes

    `; } + +const ASSET_LABELS = [ + [/linux-x86_64/, "Linux x86-64"], + [/macos-arm64/, "macOS, Apple Silicon"], + [/macos-x86_64/, "macOS, Intel"], + [/windows-x64/, "Windows x64"], +]; +function assetLabel(name) { + if (/^SHA256SUMS/.test(name)) return name.endsWith(".sig") ? "Checksums signature" : "Checksums"; + const os = ASSET_LABELS.find(([re]) => re.test(name)); + const what = /server/.test(name) ? "Server" : /launcher/.test(name) ? "Launcher" : /smoke-test/.test(name) ? "Smoke test" : "Game"; + return os ? `${what}, ${os[1]}` : name; +} +const size = (bytes) => (bytes >= 1e6 ? `${(bytes / 1e6).toFixed(0)} MB` : bytes >= 1e3 ? `${(bytes / 1e3).toFixed(0)} kB` : `${bytes} B`); + +function releaseHtml(r, open) { + const p = parts(r); + const o = overview(r); + const top = highlights(r, 4); + const downloads = (r.assets || []) + .map((a) => `
  • ${escape(assetLabel(a.name))}${escape(a.name)} · ${size(a.size || 0)}
  • `) + .join(""); + return `
    + ${escape(p.version)}${badge(r)}${escape(p.line)} +
    + ${o.text || top.length ? `
    + ${o.text ? `

    ${escape(o.text)}

    ` : ""} + ${top.length ? `
      ${top.map((t) => `
    • ${inline(t)}
    • `).join("")}
    ` : ""} +
    ` : ""} +
    ${markdown(r.body || "") || "

    No notes for this release.

    "}
    + ${downloads ? `

    Downloads

      ${downloads}
    ` : ""} +

    This release on GitHub

    +
    +
    `; +} + +// The Releases page: every release, newest first; the newest few open. +export function releasesPageHtml(list, { open = 3 } = {}) { + const sorted = [...list].sort(byTag); + if (!sorted.length) return ""; + return sorted.map((r, i) => releaseHtml(r, i < open)).join("\n"); +} + +export const releasesUrl = `https://github.com/${REPO}/releases`; diff --git a/website/src/style.css b/website/src/style.css index 03004464b..9ced17c69 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -1,8 +1,7 @@ /* Horizon's design language (docs/design-system.md), set as a page. The tokens come from crates/horizon-theme through src/tokens.css, which build.mjs puts before this file: the - same palette, type, spacing and motion as the launcher and the game's menus. Type is the - interface; content is numbered index lists with one-pixel rules; one violet accent for the - main action, links and focus; space instead of borders; quiet motion. */ + launcher's Blocks palettes, type, spacing and motion. The base below lays out the page; the + "Blocks" section at the end gives it the launcher's blocky, Minecraft-like look. */ @font-face { font-family: "Geist"; src: url("/fonts/Geist-Regular.woff2") format("woff2"); font-weight: 400; font-display: swap; } @font-face { font-family: "Geist"; src: url("/fonts/Geist-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } @@ -301,12 +300,7 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter .screen-caption { margin-top: 12px; font-size: var(--text-caption); color: var(--muted); } /* Patch notes. */ -.release-latest { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 48px; padding-top: 32px; border-top: 1px solid var(--rule); } -.release-head { position: sticky; top: calc(var(--nav) + 24px); align-self: start; display: flex; flex-direction: column; gap: 12px; } .eyebrow { text-transform: uppercase; } -.release-version { font-size: var(--text-display); line-height: var(--text-display-line); letter-spacing: var(--text-display-tracking); font-weight: 500; } -.release-line { color: var(--muted); max-width: 36ch; } -.release-body { font-size: var(--text-ui); } .prose h2, .prose h3, .prose h4 { font-size: var(--text-heading); line-height: var(--text-heading-line); color: var(--ink); margin-top: 28px; } .prose ul, .prose ol { padding-left: 18px; list-style: disc; } .prose li + li { margin-top: 6px; } @@ -314,8 +308,6 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter .prose strong { color: var(--ink); font-weight: 500; } .prose pre { padding: 16px; border-radius: var(--radius-plate); background: var(--plate-soft); overflow-x: auto; } .prose pre code { background: none; padding: 0; } -.release-older { margin-top: 64px; } -.release-older-title { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); text-transform: uppercase; margin-bottom: 12px; } .release { border-top: 1px solid var(--rule); } .release:last-of-type { border-bottom: 1px solid var(--rule); } .release summary { @@ -405,9 +397,9 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter /* --- Narrow screens ------------------------------------------------------------------------ */ @media (max-width: 900px) { - .section-head, .parity-hero, .launcher-grid, .release-latest { grid-template-columns: minmax(0, 1fr); } + .section-head, .parity-hero, .launcher-grid { grid-template-columns: minmax(0, 1fr); } .section-head { gap: 16px; } - .screens, .release-head { position: static; } + .screens { position: static; } .fact { grid-template-columns: var(--index) minmax(0, 1fr); row-gap: 6px; } .fact p { grid-column: 2; } .mosaic { grid-template-columns: minmax(0, 1fr); } @@ -499,3 +491,253 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter @media (pointer: coarse) { .docs-nav li a, .docs-toc a, .docs-bar-title, .docs-bar-link { display: flex; align-items: center; min-height: 44px; } } + +/* --- Blocks: the launcher's look on the page (docs/design-system.md, "Blocks") ------------- + Pixel type for headings and controls, square panels with a dark outline, a light bevel on top + and a darker lip below, the violet face for the main action, sunk wells, a stone texture + behind the page and Horizon's pixel landscape behind the hero. The art is drawn in code + (scripts/art.mjs, like launcher/src/art.rs); nothing in it comes from Minecraft. */ + +@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Medium.woff2") format("woff2"); font-weight: 500; font-display: swap; } +@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-SemiBold.woff2") format("woff2"); font-weight: 600; font-display: swap; } +@font-face { font-family: "Pixelify Sans"; src: url("/fonts/PixelifySans-Bold.woff2") format("woff2"); font-weight: 700; font-display: swap; } + +:root { + --stone: url("/media/stone-light.png"); + --scene: url("/media/scene-light.png"); + --sky: #8d7fd8; + --panel-edges: inset 0 var(--block-bevel) 0 var(--bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--lip); + --radius: 0px; --radius-plate: 0px; --radius-pill: 0px; +} +:root[data-theme="dark"] { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { --stone: url("/media/stone-dark.png"); --scene: url("/media/scene-dark.png"); --sky: #0a0f2c; } +} + +/* The stone: 64 texels of the page colour in close shades, each texel 4 px. */ +body { position: relative; isolation: isolate; } +body::before { + content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; + background: var(--stone) 0 0 / 256px 256px repeat; image-rendering: pixelated; +} + +/* Pixel type for what names and what you act on; paragraphs stay in Geist. */ +.display, .title, .statement, .row-name, .card-title, .release-tag, .count, +.fact h3, .features h3, .system h3, .contributors-title, .footer-disclaimer, .footer-word, +.nav-mark, .docs-prose h2, .docs-prose h3, .prose h2, .prose h3, .prose h4, .menu nav a { + font-family: var(--pixel); font-weight: 600; letter-spacing: 0; +} +.display, .count, .footer-word { font-weight: 700; } +.nav-mark { font-size: 18px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; } +code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--outline); } + +/* Buttons: blocks with an outline, a bevel and a lip; they sink a pixel when pressed. */ +.button { + border: var(--block-outline) solid var(--outline); border-radius: 0; + font: 500 var(--text-ui) / 1 var(--pixel); + box-shadow: inset 0 var(--block-bevel) 0 var(--button-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--lip); + padding-bottom: 2px; +} +.button.large { font-size: 18px; } +.button.primary { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } +.button.primary:hover { opacity: 1; filter: brightness(1.08); } +.button.secondary { background: var(--button); } +.button.secondary:hover { background: var(--button); filter: brightness(1.06); } +.button.ghost { border-color: transparent; box-shadow: none; } +.button:active { opacity: 1; transform: translateY(1px); box-shadow: inset 0 var(--block-bevel) 0 var(--lip); } +:focus-visible { border-radius: 0; } + +/* The top bar: the sidebar colour with an outline under it, tabs with an accent underline. */ +.nav.is-scrolled, .nav.is-menu { background: var(--side); -webkit-backdrop-filter: none; backdrop-filter: none; box-shadow: 0 var(--block-outline) 0 var(--outline); } +.nav-links a, .nav-github, .theme-toggle { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } +.nav-links a:hover, .nav-github:hover, .theme-toggle:hover { background: var(--raised); } +.nav-links a[aria-current] { background: var(--raised); box-shadow: inset 0 -3px 0 var(--accent); } +.theme-toggle { text-transform: none; letter-spacing: 0; } +.menu { background: var(--side); } +.menu nav a { border-bottom: 0; } + +/* Lists become stacks of panels. */ +.index, .systems, .contributors-list { border-top: 0; display: grid; gap: 8px; } +.row, .system, .release, .release:last-of-type, .contributor { border-bottom: 0; border-top: 0; } +.row > a, .row.card, .fact.row, .features li, .system, .release, .contributor, .docs-pager a { + background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); + border-radius: 0; +} +.row > a, .row.card, .fact.row, .features li, .system { padding-left: 20px; padding-right: 20px; } +.row > a::before, .row.card::before { display: none; } +.row > a:hover, .row.card:hover, .contributor:hover, .docs-pager a:hover { background: var(--raised); } +.row > a:hover .row-index { color: var(--accent); } +.row-name { font-size: clamp(20px, 2.2vw, 28px); } +.release { padding: 0 20px; } +.release + .release { margin-top: 8px; } +.release .prose { padding-left: 12rem; } +.contributor { padding: 12px 14px; } +.contributors-list { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 8px; } +.contributor-avatar { border-radius: 0; box-shadow: 0 0 0 2px var(--outline); image-rendering: pixelated; } +.system.is-full .system-state { color: var(--success); } + +/* Screenshots and the launcher's screens: square, outlined. */ +.zoom, .screen, .lightbox, .prose pre, .docs-prose figure img { border-radius: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.tabs { border-radius: 0; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.tabs button { border-radius: 0; font-family: var(--pixel); font-weight: 500; font-size: 15px; } +.tabs button[aria-selected="true"] { color: var(--on-face); } +.tab-pill { border-radius: 0; background: var(--face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-bevel)) 0 var(--face-lip); } + +/* The hero: Horizon's landscape under a veil of the page colour, the words on the left. */ +.hero { + position: relative; isolation: isolate; overflow: hidden; + background: var(--scene) 70% 100% / clamp(1200px, 135vw, 2400px) auto no-repeat, var(--sky); image-rendering: pixelated; + border-bottom: var(--block-outline) solid var(--outline); +} +.hero::before { + content: ""; position: absolute; inset: 0; z-index: -1; + background: + linear-gradient(90deg, color-mix(in srgb, var(--page) 92%, transparent) 0%, color-mix(in srgb, var(--page) 78%, transparent) 45%, color-mix(in srgb, var(--page) 0%, transparent) 78%), + linear-gradient(180deg, color-mix(in srgb, var(--page) 0%, transparent) 55%, color-mix(in srgb, var(--page) 70%, transparent) 100%); +} +.hero .kicker span, .hero .kicker { color: var(--ink-soft); } +.hero .lede { color: var(--ink-soft); } +.hero { padding-bottom: clamp(160px, 18vw, 280px); } +.hero-after { padding-top: 40px; } +.hero-after .hero-index { margin-top: 0; max-width: 860px; } +.hero-after .disclaimer { margin-top: 24px; } +@media (max-width: 900px) { + .hero::before { background: color-mix(in srgb, var(--page) 84%, transparent); } +} + +/* Documentation. */ +.docs-bar { background: var(--side); -webkit-backdrop-filter: none; backdrop-filter: none; box-shadow: 0 var(--block-outline) 0 var(--outline); } +.docs-nav li a { border-radius: 0; } +.docs-nav li a[aria-current] { background: var(--raised); box-shadow: inset 4px 0 0 var(--accent); } +.docs-toc a { border-radius: 0; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.docs-pager a { box-shadow: var(--panel-edges); } +.docs-prose h2 { border-top: var(--block-outline) solid var(--outline); } +.docs-prose blockquote { border-left: 4px solid var(--accent); background: var(--panel); padding: 10px 16px; box-shadow: 0 0 0 var(--block-outline) var(--outline); } + +/* The footer: the giant wordmark in pixels. */ +.footer { background: var(--side); border-top: var(--block-outline) solid var(--outline); margin-top: 48px; } +.footer-word { color: var(--raised); letter-spacing: 0.02em; } +:root[data-theme="dark"] .footer-word { color: var(--panel); } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .footer-word { color: var(--panel); } } + +/* --- Releases and Benchmarks pages, and the home page's "Recently added" ------------------ */ + +/* Pixelify Sans' "fi" ligature draws as "A" ("8 Axes"): no common ligatures anywhere. */ +:root { font-variant-ligatures: no-common-ligatures; } + +.page-main { padding-top: calc(var(--nav) + clamp(40px, 6vw, 80px)); } +.page-title { max-width: 18ch; margin-bottom: 20px; } +.page-main > .container > .lede { font-size: var(--text-body); } +.page-main .disclaimer { margin-top: 48px; } + +/* Channel and source badges: small square tags. */ +.badge { + display: inline-flex; align-items: center; height: 22px; padding: 0 8px; margin-right: 10px; vertical-align: 2px; + font: 500 12px / 1 var(--pixel); letter-spacing: 0.02em; text-transform: uppercase; white-space: nowrap; + border: var(--block-outline) solid var(--outline); background: var(--well); color: var(--ink-soft); +} +.badge-stable { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } +.badge-alpha { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); } +.badge-launcher { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } +.badge-us { background: color-mix(in srgb, var(--accent) 20%, var(--panel)); color: var(--ink); } +.badge-players { background: color-mix(in srgb, var(--success) 22%, var(--panel)); color: var(--ink); } +.badge-estimate { background: color-mix(in srgb, var(--warn) 24%, var(--panel)); color: var(--ink); } + +/* Home: the newest releases on a line each, then what they added. */ +.recent-list .row > a { grid-template-columns: 8.5rem minmax(0, 13rem) minmax(0, 1fr) auto; align-items: baseline; } +.recent-line { color: var(--muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.recent-list .row-name { font-size: clamp(18px, 1.8vw, 22px); } +.recent-list .badge { margin-right: 0; } +.recent-picks { margin-top: 32px; } +.recent-picks .eyebrow { margin-bottom: 12px; } +.highlights { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } +.highlight { + display: flex; flex-direction: column; justify-content: space-between; gap: 16px; padding: 18px 20px; + background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); +} +.highlight p { color: var(--ink); } +.highlight-from { font: var(--text-micro) / 1 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } +.highlight-from:hover { color: var(--accent); } + +/* Releases: a filter, then every release as a panel that opens. */ +.release-filter { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } +.release-filter .button[aria-pressed="true"] { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } +.release-count { margin: 16px 0 12px; } +.release-list { display: grid; gap: 8px; } +.release-list .release + .release { margin-top: 0; } +.release-entry summary { grid-template-columns: minmax(0, 11rem) minmax(0, 1fr) auto; } +.release-entry .release-sub { display: flex; align-items: baseline; flex-wrap: wrap; row-gap: 4px; } +.release-detail { padding: 0 0 24px 11rem; margin-left: 16px; display: grid; gap: 20px; max-width: calc(11rem + 16px + var(--measure) + 120px); } +.release-detail .prose { padding: 0; margin: 0; font-size: var(--text-ui); max-width: none; } +.release-overview { padding: 16px 18px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.release-counts { font-family: var(--pixel); font-weight: 600; color: var(--ink); margin-bottom: 8px; } +.release-overview ul { list-style: square; padding-left: 18px; color: var(--ink-soft); font-size: var(--text-ui); } +.release-overview li + li { margin-top: 4px; } +.release-downloads ul { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 8px; margin-top: 8px; } +.release-downloads li { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; background: var(--button); box-shadow: 0 0 0 var(--block-outline) var(--outline); } +.release-downloads li a { font-weight: 500; } +.release-downloads li span { font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); overflow-wrap: anywhere; } +.release-github { font-size: var(--text-caption); } +.release-entry:target { box-shadow: var(--panel-edges), 0 0 0 3px var(--accent); } + +/* Benchmarks. */ +.bench-section { margin-top: clamp(64px, 8vw, 112px); } +.bench-section > .title { margin-bottom: 16px; } +.bench-section > .lede { margin-bottom: 32px; } +.machines { display: grid; grid-template-columns: minmax(0, 1fr); gap: 24px; } +.machine { min-width: 0; padding: 24px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } +.machine-head { display: grid; gap: 10px; margin-bottom: 20px; } +.machine-name { font-family: var(--pixel); font-weight: 600; font-size: var(--text-title); line-height: var(--text-title-line); } +.machine-facts { display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 0; } +.machine-facts div { display: flex; gap: 8px; min-width: 0; } +.machine-facts dt { font: var(--text-micro) / 1.6 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } +.machine-facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; font-size: var(--text-caption); color: var(--ink-soft); } +.machine-note { font-size: var(--text-caption); color: var(--muted); max-width: 90ch; } +/* relative: the screen-reader-only labels inside are absolute and would escape the scroll box otherwise. */ +.table-wrap { position: relative; overflow-x: auto; } +.bench-table { width: 100%; border-collapse: collapse; font-size: var(--text-ui); } +.bench-table th, .bench-table td { padding: 9px 12px; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: baseline; } +.bench-table thead th { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); font-weight: 400; } +.bench-table thead tr:first-child th { color: var(--ink); } +.bench-table tbody th { font-weight: 500; color: var(--ink); } +.bench-table td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } +.bench-table td.wins { color: var(--ink); font-weight: 600; } +.bench-table td.vs { font-size: var(--text-caption); white-space: nowrap; } +.vs-horizon { color: var(--success); } +.vs-java { color: var(--danger); } +.vs-tie, .vs-none { color: var(--muted); } +.capped { font: var(--text-micro) / 1 var(--mono); color: var(--warn); cursor: help; } +.metric-hint { display: block; font: var(--text-micro) / 1.4 var(--mono); color: var(--muted); font-weight: 400; } +.java-wins { margin-top: 16px; font-size: var(--text-caption); color: var(--ink-soft); } +.picker { display: flex; flex-wrap: wrap; gap: 16px 24px; align-items: end; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } +.picker label { display: grid; gap: 6px; } +.picker label > span, .picker legend { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } +.picker select { + min-width: min(320px, 80vw); height: var(--control); padding: 0 10px; font: inherit; font-size: var(--text-ui); color: var(--ink); + background: var(--well); border: var(--block-outline) solid var(--outline); border-radius: 0; +} +.picker-rd { display: flex; gap: 16px; align-items: center; border: 0; padding: 0; margin: 0; } +.picker-rd legend { margin-bottom: 6px; } +.picker-rd label { display: inline-flex; align-items: center; gap: 6px; font-family: var(--pixel); font-weight: 500; height: var(--control); } +.picker-rd input { accent-color: var(--accent); width: 18px; height: 18px; } +.pick-result { margin-top: 16px; padding: 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } +.pick-head { margin-bottom: 12px; font-size: var(--text-caption); color: var(--ink-soft); line-height: 1.8; } +.pick-result .meta { margin-top: 12px; } +.empty { color: var(--muted); } +.prose-section .prose { max-width: 80ch; } +.spec-table { margin-top: 24px; } +.spec-table summary { cursor: pointer; font-family: var(--pixel); font-weight: 600; } +.spec-table .bench-table { margin-top: 16px; max-width: 760px; } + +@media (max-width: 900px) { + .recent-list .row > a { grid-template-columns: minmax(0, 1fr) auto; row-gap: 4px; } + .recent-list .row-index { grid-column: 1; grid-row: 1; } + .recent-list .row-name { grid-column: 1; grid-row: 2; } + .recent-line { grid-column: 1 / -1; grid-row: 3; white-space: normal; } + .recent-list .row-meta { grid-column: 2; grid-row: 1; } + .highlights { grid-template-columns: minmax(0, 1fr); } + .release-entry summary { grid-template-columns: minmax(0, 1fr) auto; } + .release-detail { padding-left: 0; margin-left: 0; } + .machine { padding: 16px; } +} +.older-runs { margin-top: 16px; max-width: 90ch; padding: 16px 20px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); font-size: var(--text-caption); } diff --git a/website/src/tokens.css b/website/src/tokens.css index d272865cc..816ad5b8e 100644 --- a/website/src/tokens.css +++ b/website/src/tokens.css @@ -2,21 +2,39 @@ docs/design-system.md describes the tokens. */ :root { - --page: #fafafc; - --plate-soft: #f3f3f8; - --plate: #ebecf4; - --surface: #ffffff; - --rule: #e2e3ea; - --ink: #16181f; - --ink-soft: #3b3e49; - --muted: #646875; - --accent: #5b3fd6; + --page: #ece7f7; + --plate-soft: #e9e3f8; + --plate: #ddd4f3; + --surface: #f8f6fd; + --rule: #e4ddf4; + --ink: #1b1530; + --ink-soft: #3b3354; + --muted: #585071; + --accent: #5333c9; --on-accent: #ffffff; - --danger: #b4372a; - --success: #1d7a48; + --danger: #a3301d; + --success: #136336; + --warn: #7a4f00; + --side: #e2dbf2; + --panel: #f8f6fd; + --raised: #e9e3f8; + --button: #ddd4f3; + --button-bevel: #f4f0fe; + --well: #f3f0fb; + --bevel: #ffffff; + --lip: #c3b8e2; + --outline: #2b2244; + --face: #5b3fd6; + --face-bevel: #8069ef; + --face-lip: #3a2694; + --on-face: #ffffff; color-scheme: light; --font: "Geist", ui-sans-serif, system-ui, sans-serif; --mono: "Geist Mono", ui-monospace, monospace; + --pixel: "Pixelify Sans", "Geist", ui-sans-serif, sans-serif; + --block-outline: 2px; + --block-bevel: 2px; + --block-lip: 4px; --text-micro: 11px; --text-micro-line: 1.5; --text-micro-tracking: 0.04em; @@ -88,34 +106,62 @@ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { - --page: #0d0e13; - --plate-soft: #181a22; - --plate: #20222c; - --surface: #16181f; - --rule: #24262f; + --page: #0f0d17; + --plate-soft: #221e34; + --plate: #2b2641; + --surface: #1a1727; + --rule: #120f1c; --ink: #ecedf3; --ink-soft: #c5c7d1; - --muted: #8b8f9c; + --muted: #a29cb8; --accent: #9a86ff; - --on-accent: #0d0e13; + --on-accent: #ffffff; --danger: #f07a68; --success: #45c27a; + --warn: #f0b84f; + --side: #0b0a11; + --panel: #1a1727; + --raised: #221e34; + --button: #2b2641; + --button-bevel: #3d3560; + --well: #0c0b12; + --bevel: #342d52; + --lip: #07060b; + --outline: #05040a; + --face: #5b3fd6; + --face-bevel: #8a74ff; + --face-lip: #3a2694; + --on-face: #ffffff; color-scheme: dark; } } :root[data-theme="dark"] { - --page: #0d0e13; - --plate-soft: #181a22; - --plate: #20222c; - --surface: #16181f; - --rule: #24262f; + --page: #0f0d17; + --plate-soft: #221e34; + --plate: #2b2641; + --surface: #1a1727; + --rule: #120f1c; --ink: #ecedf3; --ink-soft: #c5c7d1; - --muted: #8b8f9c; + --muted: #a29cb8; --accent: #9a86ff; - --on-accent: #0d0e13; + --on-accent: #ffffff; --danger: #f07a68; --success: #45c27a; + --warn: #f0b84f; + --side: #0b0a11; + --panel: #1a1727; + --raised: #221e34; + --button: #2b2641; + --button-bevel: #3d3560; + --well: #0c0b12; + --bevel: #342d52; + --lip: #07060b; + --outline: #05040a; + --face: #5b3fd6; + --face-bevel: #8a74ff; + --face-lip: #3a2694; + --on-face: #ffffff; color-scheme: dark; } diff --git a/website/src/versions.js b/website/src/versions.js new file mode 100644 index 000000000..b2483b4ed --- /dev/null +++ b/website/src/versions.js @@ -0,0 +1,59 @@ +// Horizon's release tags (docs/versioning.md). From 0.2 the game is vX.Y.Z and the launcher launcher@X.Y.Z; +// before, vYYYY.MM.DD[.N] and launcher-vX.Y.Z. Every 0.2 tag is newer than every tag from before. Shared by +// build.mjs and main.js, and the same order as the launcher's and tools/release_train.py's. + +const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; +// Semver's majors stay below this; a date tag's first number is a year. +const FIRST_YEAR = 1000; + +const semver = (version) => { + const m = SEMVER.exec(version); + return m && Number(m[1]) < FIRST_YEAR ? m : null; +}; + +export const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}(\.\d+)?$/.test(tag) || (tag.startsWith("v") && !!semver(tag.slice(1))); + +// The version in a launcher tag (launcher@0.2.0, launcher-v0.16.0), or null. +export function launcherVersion(tag) { + if (tag.startsWith("launcher@") && semver(tag.slice(9))) return tag.slice(9); + const old = /^launcher-v(\d+\.\d+\.\d+)$/.exec(tag); + return old ? old[1] : null; +} + +export const isLauncher = (tag) => launcherVersion(tag) !== null; + +// [line, numbers, pre-release]: tags from before 0.2 by their numbers, then 0.2 tags in semver's order. +function key(tag) { + const version = tag.startsWith("launcher@") ? tag.slice(9) : tag.startsWith("v") ? tag.slice(1) : null; + const m = version !== null && semver(version); + if (!m) return [0, (tag.match(/\d+/g) || []).map(Number), []]; + const pre = m[4] ? m[4].split(".").map((id) => (/^\d+$/.test(id) ? [0, Number(id)] : [1, id])) : null; + return [1, [m[1], m[2], m[3]].map(Number), pre]; +} + +const cmpList = (a, b, cmp) => { + for (let i = 0; i < Math.min(a.length, b.length); i++) { + const d = cmp(a[i], b[i]); + if (d) return d; + } + return a.length - b.length; +}; +const cmpNumbers = (a, b) => { + const strip = (l) => { const c = [...l]; while (c.length && c[c.length - 1] === 0) c.pop(); return c; }; + return cmpList(strip(a), strip(b), (x, y) => x - y); +}; +const cmpId = ([ka, va], [kb, vb]) => ka - kb || (ka ? (va < vb ? -1 : va > vb ? 1 : 0) : va - vb); + +// Negative when tag a is older than tag b. +export function compareTags(a, b) { + const [la, na, pa] = key(a); + const [lb, nb, pb] = key(b); + if (la !== lb) return la - lb; + const d = cmpNumbers(na, nb); + if (d || !la) return d; + // A release follows its pre-releases. + if (!pa || !pb) return (pa ? -1 : 0) - (pb ? -1 : 0); + return cmpList(pa, pb, cmpId); +} + +export const newestFirst = (a, b) => compareTags(b, a); diff --git a/website/src/versions.test.mjs b/website/src/versions.test.mjs new file mode 100644 index 000000000..eed334429 --- /dev/null +++ b/website/src/versions.test.mjs @@ -0,0 +1,21 @@ +// node --test website/src/ (npm test in website/) +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { compareTags, isGame, isLauncher, launcherVersion, newestFirst } from "./versions.js"; + +test("0.2 tags follow every tag from before", () => { + const order = ["v2026.10.19.15", "v2026.10.21", "v0.2.0-beta.1", "v0.2.0", "v0.2.1-beta", "v0.2.1-beta.2", + "v0.2.1-beta.11", "v0.2.1-rc.1", "v0.2.1", "v0.2.9", "v0.2.10", "v0.3.0-1", "v0.3.0-alpha", "v0.3.0", "v1.0.0"]; + assert.deepEqual([...order].reverse().sort(compareTags), order); + assert.deepEqual(["launcher-v0.16.0", "launcher@0.2.0", "launcher-v0.17.0", "launcher@0.2.1"].sort(newestFirst), + ["launcher@0.2.1", "launcher@0.2.0", "launcher-v0.17.0", "launcher-v0.16.0"]); + assert.equal(compareTags("v2026.10.19", "v2026.10.19.0"), 0); +}); + +test("game and launcher tags never mix", () => { + for (const tag of ["v0.2.0", "v0.3.0-rc.1", "v2026.10.21", "v2026.10.19.15"]) assert.ok(isGame(tag), tag); + for (const tag of ["launcher@0.2.0", "launcher-v0.16.0", "v0.2", "vnext", "v2026.10.21-x"]) assert.ok(!isGame(tag), tag); + assert.equal(launcherVersion("launcher@0.2.0"), "0.2.0"); + assert.equal(launcherVersion("launcher-v0.16.0"), "0.16.0"); + assert.ok(!isLauncher("v0.2.0") && !isLauncher("launcher-vnext")); +});