Compare commits

...
Author SHA1 Message Date
Ludovic Marie 8b792957f7 Merge pull request #2286 from ludovic111/chore/site-repo-split
🤖 Agent: merging. playhorizon.dev already deploys from ludovic111/horizon-site (verified page by page); this drops website/ and moves tokens.css, roadmap.json, the benchmark fixtures and the web icons where the site's build and the tests read them. verify passed; pr_ready --quick and the telemetry server's tests pass locally.
2026-10-26 17:00:07 +01:00
Ludovic Marie 2c6b60f3fb Merge pull request #2105 from socksprox/fix/fire-smoke-no-break-particles
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `BaseFireBlock.animateTick` (three large smoke above, or two per burnable side when the block below neither burns nor is sturdy up, in that order and with the `* 0.1F` float edge), `SoulFireBlock.canBurn` always true, and `Level.destroyBlock` → `spawnDestroyParticles` → `BaseFireBlock`'s empty `spawnDestroyByEntityParticles`. `fire.igniteOdds` is in block-behaviours.json at the top level, as read. I added one rule: `FireBlock.getIgniteOdds` is 0 for a waterlogged state, so such a neighbour no longer counts as burnable. This and #2082 (the player's predicted break) cover different paths, so both stay; #2092 was already closed in favour of this one. In game, fire and soul fire show their large smoke above them. Thanks @socksprox, and @kacpherek for #2092! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:59:27 +01:00
Ludovic Marie 8f827db52d Merge pull request #2102 from kacpherek/fix/1516-vehicles-in-nether-portals
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `NetherPortalBlock.entityInside` takes any entity that `canUsePortal(false)`, and boats and minecarts travel through `teleportCrossDimension` with their data, as items and mobs already did here. A ridden vehicle stays out of this PR's scope (the player-and-vehicle case is #1486). `lan_e2e.py --check vehicles`, `boats` and `minecarts` pass in both modes. Fixes #1516. Thanks @kacpherek! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:56:54 +01:00
Ludovic Marie 0e0b0c947f Merge pull request #2100 from kacpherek/fix/1436-item-frame-light
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `ItemFrameRenderer.getBlockLightLevel` gives a glow frame's model at least block light 5 (the item and map inside stay full bright), and the frame model takes the entity shader's directional shading from its face normals. My screenshot run couldn't place a frame, so this rests on the code and on `lan_e2e.py --check frames`, which passes in both modes. Fixes #1436. Thanks @kacpherek! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:54:21 +01:00
Ludovic Marie e065f2af6f Merge pull request #2097 from kacpherek/fix/1507-server-end-credits
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `EndPortalBlock.entityInside` calls `showEndCredits` on a player in the End without `seenCredits`. That sends `WIN_GAME` with 0.0 once (`wonGame`), and `handleClientCommand(PERFORM_RESPAWN)` while `wonGame` respawns the player in the Overworld keeping its data. `seenCredits` round-trips through playerdata. One difference is left for later: vanilla takes the player out of the End level (`removePlayerImmediately`) while the poem rolls, and here it stays in the level. `lan_e2e.py --check portals` passes with the host on its server thread (I pushed one fix to the check: it closes the credits on the host's first End exit). Fixes #1507. Thanks @kacpherek! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:51:57 +01:00
Ludovic Marie 8ccf20d909 Merge pull request #2077 from RoyalPixelsDE/fix/structure-starts-3-legacy
🤖 Agent: Gate check by Ludovic's AI agent (Claude). The remaining legacy structure pieces now save their vanilla fields. Checked with a vanilla save of a generated world (overworld, Nether, End) taken through Horizon and back to vanilla 26.3 on the server thread and in-frame. On an integration tree with the whole stack, `save_roundtrip`, `world_reopen`, `chunk_generation`, `structure_start_nbt`, `structure_blocks`, `structure_layout`, `trial_spawner` and `vault` all pass. Thanks @FusselTV!
2026-10-26 16:51:18 +01:00
Ludovic Marie 7ace1e9e8f Merge pull request #2076 from RoyalPixelsDE/fix/structure-starts-2-templates
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Template pieces now save as vanilla's TemplateStructurePiece does. Checked with a vanilla save of a generated world (overworld, Nether, End) taken through Horizon and back to vanilla 26.3 on the server thread and in-frame. On an integration tree with the whole stack, `save_roundtrip`, `world_reopen`, `chunk_generation`, `structure_start_nbt`, `structure_blocks`, `structure_layout`, `trial_spawner` and `vault` all pass. Thanks @FusselTV!
2026-10-26 16:48:38 +01:00
Ludovic Marie ebf2132885 Merge pull request #2103 from rdbtCVS/fix/1948-merchant-cost-components
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `ItemCost.STREAM_CODEC` is item, count, then `DataComponentExactPredicate.STREAM_CODEC`, a list of typed components with no removal count, as now written and read. Its verify failed only on rustfmt (item_sync.rs), which I pushed. Main conflicted in item_sync.rs's tests (the new bundle test), so I merged it, keeping both tests. I also took the codec round trip back out of the trading probe: the probe's output is what the harness compares with vanilla, the round trip is already covered by your two unit tests, and its `unwrap` would abort the probe on any cost whose components name an entry the stub registry lacks. `lan_e2e.py --check hero-trading` passes in both modes. Fixes #1948. Thanks @rdbtCVS! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:44:53 +01:00
Ludovic MarieandClaude Opus 5.5 4fe648b674 Move the website to its own repository (ludovic111/horizon-site)
playhorizon.dev now deploys from the private ludovic111/horizon-site, which holds website/'s history. The files
its build still reads from here move out of website/:

- the design tokens to crates/horizon-theme/tokens.css (xtask tokens writes them, tokens_css_is_up_to_date checks them);
- the roadmap's JSON to roadmap/roadmap.json (tools/roadmap.py build);
- the benchmark fixtures to crates/horizon-telemetry-server/tests/fixtures/benchmarks/ (the site keeps a copy);
- the web icons to docs/media/brand/web/ (xtask icons).

pr_ready loses its website area and the tokens special case; rust_changes, the roadmap's links and every doc
that pointed into website/ follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:43:32 +01:00
Ludovic Marie 747c22a5c2 Merge pull request #2088 from rdbtCVS/rdbt/fix-1491-guardian-beams-20261026
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `Guardian.DATA_ID_MOVING` (16) and `DATA_ID_ATTACK_TARGET` (17, the target's entity id, 0 for none) are synced, `onSyncedDataUpdated` zeroes `clientSideAttackTime`, and the client's `aiStep` advances it up to `getAttackDuration` (80, elder 60), which drives the beam. The in-frame tick now shares `client_tick`. Main conflicted (the bat flags from #2003, the sonic and cushion checks), so I merged it into the branch, keeping both sides. `lan_e2e.py --check guardian-beams` passes with the host in-frame and on its server thread (I pushed one fix to the check: the host reads the guardian from the level that ticks it). Fixes #1491. Thanks @rdbtCVS! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:41:53 +01:00
Ludovic Marie cab57a158f Merge pull request #2072 from RoyalPixelsDE/fix/proto-block-entity-id
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Block entities placed in proto chunks now save with their id, as vanilla's ProtoChunk does, so vanilla loads them. Checked with a vanilla save of a generated world (overworld, Nether, End) taken through Horizon and back to vanilla 26.3 on the server thread and in-frame. On an integration tree with the whole stack, `save_roundtrip`, `world_reopen`, `chunk_generation`, `structure_start_nbt`, `structure_blocks`, `structure_layout`, `trial_spawner` and `vault` all pass. Thanks @FusselTV!
2026-10-26 16:41:09 +01:00
Ludovic Marie 9cbf93a193 Merge pull request #2070 from RoyalPixelsDE/fix/dimension-height
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Nether and End chunks now save with their own min_y/height and sky light, as ChunkSerializer does per dimension: vanilla reads them back with every section in place. Checked with a vanilla save of a generated world (overworld, Nether, End) taken through Horizon and back to vanilla 26.3 on the server thread and in-frame. On an integration tree with the whole stack, `save_roundtrip`, `world_reopen`, `chunk_generation`, `structure_start_nbt`, `structure_blocks`, `structure_layout`, `trial_spawner` and `vault` all pass. Thanks @FusselTV!
2026-10-26 16:38:29 +01:00
Ludovic Marie b1afe112a4 Merge pull request #2281 from ludovic111/fix/launcher-proxy-redact
🤖 Agent: Merged by Ludovic's AI agent (Claude). This keeps proxy credentials out of the launcher's messages and fixes the launcher build that broke on main (download::agent call in browser/horizon.rs). Launcher lib tests 137/137, horizon-port-pack 68/68. Thanks again to @zhykowo for the proxy support in #2059.
2026-10-26 16:36:08 +01:00
Ludovic Marie b107b8539d Merge pull request #2101 from kacpherek/fix/server-thread-chest-minecart
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `ContainerEntity.isChestVehicleStillValid` is `!isRemoved() && player.isWithinEntityInteractionRange(getBoundingBox(), 4.0)`, which is entity interaction range (3, creative 5) plus 4 measured from the eye to the box, as here. The menu had closed on the tick it opened because the placeholder key was checked as a block. This is also the Discord report of a chest minecart that plays its sound but opens no screen. `lan_e2e.py --check minecarts` passes in both modes, and through horizon-ctl a chest minecart's screen is still open 60 ticks after it opens. Thanks @kacpherek! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:35:45 +01:00
Ludovic Marie df518c1683 Merge pull request #2071 from RoyalPixelsDE/fix/trial-spawner-spawn-data
🤖 Agent: Gate check by Ludovic's AI agent (Claude). A trial spawner with nothing to spawn no longer writes an empty spawn_data, matching TrialSpawnerStateData's codec. Checked with a vanilla save of a generated world (overworld, Nether, End) taken through Horizon and back to vanilla 26.3 on the server thread and in-frame. On an integration tree with the whole stack, `save_roundtrip`, `world_reopen`, `chunk_generation`, `structure_start_nbt`, `structure_blocks`, `structure_layout`, `trial_spawner` and `vault` all pass. Thanks @FusselTV!
2026-10-26 16:35:11 +01:00
Ludovic Marie 2aa41f867e Merge pull request #2068 from lazy-importer/fix/2039-custom-item-name-tooltip
🤖 Agent: Gate check by Ludovic's AI agent (Claude). The item_name component now sits on items and tooltips as vanilla's Item.getName/getStyledHoverName read it (custom_name first, then item_name, then the translation key). I pushed d983ef89b so item_name stays a component and is not folded into custom_name. `tooltip_display`, `lore_tooltip` and `firework_tooltip` pass on an integration tree with the other open contributor PRs. Fixes #2039 is right. Thanks @lazy-importer!
2026-10-26 16:32:32 +01:00
Ludovic Marie 8741f4d590 Merge pull request #2015 from vlesmentie/feat/campfire-cooking
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Campfire cooking (CampfireBlockEntity.cookTick/cooldownTick, placing food, dropping the result, the arm swing) matches 26.3, and food cooks in game on the server thread and in-frame. Since campfires now tick, the save round trip saw the fixture's lit campfire advance its CookingTimes between load and save, as the lit furnace already did. I added that one ignore rule (ba797f60a); `save_roundtrip` then passes with 0 unexplained differences. Thanks @vlesmentie!
2026-10-26 16:29:52 +01:00
Ludovic Marie d880b23fec Merge pull request #2278 from ludovic111/feat/sculk-banner-launcher
🤖 Agent: Sculk partner banner in the launcher (Servers and Home), as Ludovic asked. Launcher fmt, clippy -D warnings and tests pass; checked in dark and light on the Mac mini; verify passed on this head.
2026-10-26 16:26:53 +01:00
Ludovic Marie c97be88ae5 Merge pull request #2094 from rdbtCVS/rdbt/fix-1478-firework-bursts-20261026
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `FireworkRocketEntity.explode` broadcasts entity event 17 before damage and `discard`, and `handleEntityEvent(17)` calls `createFireworks` with the rocket's movement and its item's explosions, so sending the event before the tracker drops the rocket is the right order. Main conflicted (fireworks.rs, lan_e2e.py), so I merged it, keeping main's rocket damage and your `remote_firework_explosion`. `lan_e2e.py --check fireworks` passes in both modes. Fixes #1478. Thanks @rdbtCVS! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:26:25 +01:00
Ludovic MarieandClaude Opus 5.5 600b2a1dda Launcher proxy: keep a proxy's credentials out of messages; build again
An address the launcher can't use as a proxy is printed to stderr by
horizon-port-pack and shown under the Settings field or by `settings set`:
a user name and password in it now read `***`.

The registry's star ratings called download::agent() without the address
it now takes (#2059 and the ratings landed side by side), so the launcher
didn't build.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:25:16 +01:00
Ludovic Marie 03b52db24e Merge pull request #2096 from kacpherek/fix/2091-recipe-book-tabs
🤖 Agent: Gate check by Ludovic's AI agent (Claude). Checked against 26.3: `AbstractRecipeBookScreen.mouseClicked` offers the click to `recipeBookComponent` before anything else, and the tabs sit left of the book, outside the strip `hasClickedOutside` counts, so the outside branch has to ask the book first. `lan_e2e.py --check recipes` passes in both modes. Fixes #2091. Thanks @kacpherek! Gate: this batch merged with wave 1 in one tree: clippy `-D warnings` clean, 1164 horizon-client lib tests pass, and of the 88 harnesses `parity.py --changed-files` picked, 87 pass (`block_entity_render` fails from #2099, which is held).
2026-10-26 16:23:43 +01:00
Ludovic Marie 27f9120510 Merge pull request #2021 from senjinthedragon/hdr-output
🤖 Agent: Gate check by Ludovic's AI agent (Claude). I merged main and added `crates/horizon-hdr` to the workspace, and pushed caae02641 so that native material packs keep a light-emitting translucent face (nether portal) at its own alpha. HDR stays off by default. With it off, screenshots match main within noise, and the frame time does too (A/B, two runs each: p50 0.326 to 0.329 ms vs 0.317 to 0.345 ms). `section_mesh` passes. HDR on was not tested here (no HDR display on the Mac mini). Thanks @senjinthedragon!
2026-10-26 16:23:13 +01:00
Ludovic Marie 0a699d34f5 Merge pull request #2049 from vlesmentie/fix/remote-ender-dragon
🤖 Agent: Gate check by Ludovic's AI agent (Claude). With the default server thread, the End's dragon is now drawn (screenshots in the End: invisible on main, visible with this PR), and attacks on its parts reach the server. `server_dragon` passes on an integration tree with the other open contributor PRs. Fixes #1530 is right. Thanks @vlesmentie!
2026-10-26 16:22:28 +01:00
Ludovic MarieandClaude Opus 5.5 96afc48ce2 Merge main into fix/1948-merchant-cost-components
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:18:40 +01:00
Ludovic MarieandClaude Opus 5.5 804a288214 Merge main into rdbt/fix-1491-guardian-beams-20261026
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:18:38 +01:00
Ludovic Marie 1851dc87a7 Merge pull request #2086 from kacpherek/fix/thrown-eye-and-pearl
🤖 Agent: Gate check by Ludovic's AI agent (Claude). rdbt's approval counts as the first review (trusted reviewer). In the integration tree with the other open PRs, `lan_e2e --check thrown` and `--check projectiles` pass in-frame and on the server thread, and the `pearl_death` harness passes. Fixes #1826 is right. Thanks @kacpherek!
2026-10-26 16:17:59 +01:00
Ludovic MarieandClaude Opus 5.5 ba797f60a1 save_roundtrip: the lit campfire keeps cooking while Horizon runs
Campfires now tick, so the fixture's campfire advances its CookingTimes
between load and save, as the lit furnace does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:17:25 +01:00
Ludovic Marie 95f9ad56b2 Merge pull request #2270 from ludovic111/fix/mob-ai-oracle-heap
🤖 Agent: verify passed; this only raises the mob_ai oracle's heap (tools only). The oracle passed alone at 4g.
2026-10-26 16:17:23 +01:00
Ludovic MarieandClaude Opus 5.5 528d65ab12 launcher: Sculk partner banner on Servers and Home
Sculk, a server host, sponsors Horizon. Its banner (a 50 KB WebP,
1200x441, bundled with include_bytes) sits under a muted "Partner"
label at the end of the Servers page and of Home, below Play. A click
opens https://my.sculkhosting.com/ref/horizon; hovering lifts it 2 px
and turns the label to ink; it is reachable with Tab.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:15:57 +01:00
Ludovic Marie f8eb2f086e Merge pull request #1990 from Joansitoh/fix/server-text-caret
🤖 Agent: Gate check by Ludovic's AI agent (Claude). This needs no decision from Ludovic: every field now edits at the caret, as vanilla's EditBox does. rdbt's line-break review: the book page is a MultiLineEditBox in 26.3 (javap), so I pushed MultilineTextField's own word rule. getPreviousWord/getNextWord split words at any Character.isWhitespace and start from the cursor clamped to the last character. The single-line EditBox.getWordPosition keeps counting spaces only. I also merged main in twice (multiplayer.rs labels, stations.rs). Integration tree: `lan_e2e --check books`, `signs` and `anvil` pass in-frame and on the server thread, the `creative` and `container_screen` harnesses pass, and the ui/creative/title/clipboard unit tests pass. Thanks @Joansitoh!
2026-10-26 16:15:00 +01:00
Ludovic Marie 26a2aa2fdc Merge pull request #2047 from ESHAYAT102/fix/cushion-placement
🤖 Agent: Gate check by Ludovic's AI agent (Claude). I checked CushionItem.useOn and Cushion.interact against the 26.3 bytecode with rea_vanilla and pushed three leftovers. (1) An occupied cushion now returns PASS, as Cushion.interact does. (2) A cushion placed in fire burns at once (destroyIfInFire). (3) Placing always posts the entity_place game event before consuming the item. I also merged main into the branch (lan_e2e.py). The suffocation check matches vanilla's block definitions except closed shulker boxes, which are approximated as always suffocating (noted in a comment). Integration tree: `lan_e2e --check cushions` passes in-frame and on the server thread, and the `cushion_placement` and suffocation harnesses pass. Thanks @ESHAYAT102!
2026-10-26 16:14:15 +01:00
Ludovic Marie 006006f1d5 Merge pull request #2059 from zhykowo/feat/launcher-proxy
🤖 Agent: Gate check by Ludovic's AI agent (Claude). The launcher contacts no new host: the existing requests (releases, Mojang files, Modrinth, CurseForge, the mod registry, pictures, Microsoft sign-in, Tailscale's API, modpack jars) now go through the player's HTTP proxy, or HTTPS_PROXY/HTTP_PROXY/ALL_PROXY when unset. Loopback and NO_PROXY hosts stay direct, and the Servers page's local API never uses the proxy. Tokens (Microsoft, Tailscale) only cross the proxy inside TLS (CONNECT), so the proxy can't read them, and none are logged. rdbt's NO_PROXY review is addressed: `horizon-port-pack`'s agents apply the same rules (`no_proxy_lists_hosts_and_their_subdomains`). On Linux at da54f988d: launcher lib tests 132 passed, `cargo clippy --all-targets -D warnings` clean, `horizon-port-pack` 68 tests passed and clippy clean. Labelled feature. One small note for later: an unusable proxy address is printed to stderr as typed, so a `user:pass@` in it would show in the log. Thanks @zhykowo!
2026-10-26 16:10:03 +01:00
Ludovic MarieandClaude Opus 5.5 453ee22376 Merge main into fix/server-text-caret
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 16:01:24 +01:00
Ludovic Marie db4ea8a200 Merge pull request #2038 from levzzz5154/fix/bundle-tooltip
🤖 Agent: Gate check by Ludovic's AI agent (Claude). `tools/bundle_tooltip_e2e.py` passes in-frame. On the server thread (what players run) it showed every bundle full, holding more bundles, so I pushed two commits: (1) BundleContents' stream codec (component 52, a list of ItemStackTemplate, checked with javap) plus sending it to clients in `network_stack`; (2) `Hub::stack` gave every stack inside an item the outer item's id, which also turned a crossbow's charged projectiles into crossbows on clients. It is fixed now: each inner stack looks up its own id. With both commits the e2e passes on the server thread and in-frame (306 px tooltip frame; main shows 117 px and fails). The screenshot shows 32 stone with a half-full bar, as in vanilla. Unit tests: `bundle_contents_are_item_stack_templates` and `a_bundle_keeps_its_contents_across_the_wire`. Thanks @levzzz5154!
2026-10-26 15:58:10 +01:00
Ludovic Marie d48e56778e Merge pull request #2037 from levzzz5154/fix/loot-enchant-functions
🤖 Agent: Gate check by Ludovic's AI agent (Claude). I checked the loot functions against vanilla 26.3 directly. A vanilla server placed 48 chests with fixed LootTableSeed values: 16 tables (end city, stronghold library, ancient city, mansion, dungeon, trial chamber rewards and more) times 3 seeds, then rolled them. Horizon then opened the same world. Every chest got the same items, counts, slots and enchantments as vanilla, enchant_randomly and enchant_with_levels included: 48/48 on the server thread and 48/48 in-frame. The only difference is the order of keys inside the enchantments map, which vanilla doesn't read. EnchantRandomly and EnchantWithLevels match the bytecode, and rdbt's single-level review point is covered by `a_single_level_enchantment_draws_no_level`. It is also built and run in an integration tree with the other open PRs. Thanks @levzzz5154!
2026-10-26 15:51:13 +01:00
Ludovic MarieandClaude Opus 5.5 17e4d547c7 parity: give the mob_ai oracle a 4g heap
VanillaMobAiOracle ran out of its 3g heap in PoiManager.tick on a busy CI
runner. Each scenario forces 9x9 chunks at a new origin; the live heap after
GC swings between 0.3 and 1 GB over a run, with peaks near 2 GB before GC.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:45:13 +01:00
Ludovic MarieandClaude Opus 5.5 b242a5ac15 Give the stacks inside a sent item their own ids
Hub::stack resolved every item id of a stack to the outer item's, so a
bundle's contents and a crossbow's charged projectiles reached a server's
clients as more bundles and crossbows. The tooltip then drew a bundle of
bundles, full. Each stack inside now looks its own id up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:40:50 +01:00
Ludovic Marie 8975e2370b Merge pull request #2217 from ludovic111/ci/linux-runner-ubuntu
CI: Linux runner on Ubuntu (playhorizon), tokens without gh, CPU and memory knobs
2026-10-26 15:40:06 +01:00
Ludovic Marie 9a7f75b75d Merge pull request #1894 from ludovic111/feat/server-mods-game
🤖 Agent: merged main (aec52c85e). pr_ready --quick passes (1308 horizon-client tests, clippy, 507 LOC). The welcome server mod e2e passes 35/35 in every mode: in-frame, server thread, LAN host in-frame and on its thread with a guest, dedicated with a guest. Verify is green; parity now runs on main (parity-scope). Queued.
2026-10-26 15:30:36 +01:00
Ludovic MarieandClaude Opus 5.5 a4839d322b CI: Linux runner on Ubuntu (playhorizon), tokens without gh, CPU and memory knobs
linux-runner.sh takes its packages from apt where there is no Nix, the
registration token from RUNNER_TOKEN (a machine where gh must not be logged
in), and RUNNER_CPUS / RUNNER_MEMORY for a machine that does nothing else.
playhorizon, a partner's 8-thread server, joins parity_hosts.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:28:21 +01:00
Ludovic Marie c5a2259d92 Merge pull request #2022 from mc070309/cursor/sprint-jump-impulse-68db
🤖 Agent: Gate check by Ludovic's AI agent (Claude). The server fix in this PR landed first in #1779 (levzzz's PR, same change to `hub.rs` and `agent.rs`, with the same `lan_bot` test). I merged main into the branch and kept main's side, so what this PR now adds is its two unit tests: `sprint::tests::sprint_survives_releasing_the_key_through_a_jump` (the client sprint state survives the key coming up on the jump tick) and `living_motion::tests::sprint_jump_adds_look_direction_impulse` (LivingEntity.jumpFromGround's 0.2 impulse along the look, and none for a walk). Both pass, and `lan_e2e --check sprint-fov` passes in-frame and on the server thread in the integration tree. Labelled skip-release, because players see no change. Thanks @mc070309 for tracking the cause down and for the tests.
2026-10-26 15:25:12 +01:00
Ludovic Marie 7ec3fd2b4c Merge pull request #2212 from ludovic111/fix/furnace-recipes-used-namespace
🤖 Agent: Merging. verify and parity passed; the new unit test covers the merge of both key forms, and save_roundtrip no longer sees duplicate RecipesUsed keys.
2026-10-26 15:20:16 +01:00
Ludovic MarieandClaude Opus 5.5 be73f4ac6a Keep a furnace's RecipesUsed keys namespaced, so vanilla reads Horizon's furnaces
bf81ae635 started saving recipes_used, but Horizon's recipe ids lack the
minecraft: namespace, so a furnace could hold both forms of one id and
vanilla refused it with "Duplicate entry for key" (save_roundtrip).
recipe_used_key gives the full id; loading merges the two forms from saves
written in between.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 15:10:58 +01:00
Ludovic Marie 8027cb4176 Merge pull request #2177 from ludovic111/feat/launcher-mod-ratings
🤖 Agent: Merging. verify passed, along with launcher tests (11 registry tests), the horizon-theme icon test and clippy -D warnings. #2173, which it was stacked on, is merged.
2026-10-26 15:05:13 +01:00
Ludovic Marie 91400aac5b Merge pull request #2173 from ludovic111/feat/mod-index-downloads
🤖 Agent: Merging. verify and mod-registry passed, and pr_ready --quick passed (clippy, horizon-mods and launcher tests). The index's downloads field is optional, so the schema doesn't change.
2026-10-26 15:02:11 +01:00
Ludovic Marie 26894ab3fd Merge pull request #2170 from ludovic111/feat/mods-site-stats
🤖 Agent: Merging. verify passed and the website tests (44) pass. Ratings appear once #2167's service is live; until then the pages show downloads only.
2026-10-26 14:59:28 +01:00
Ludovic Marie ae17e26009 Merge pull request #2140 from ludovic111/feat/quiet-commands-server
🤖 Agent: verify and parity pass (109 harnesses affected; parity green). The dedicated-server e2e (tools/quiet_commands_e2e.py) passes 7/7. Queued. #2171 (the mod API, stacked on it) follows once this lands.
2026-10-26 14:57:05 +01:00
Ludovic MarieandClaude Opus 5.5 ae3b844d74 Merge main into fix/server-text-caret
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:56:10 +01:00
Ludovic Marie 03c8594494 Merge pull request #2061 from lazy-importer/fix/2034-bossbar-vanish-reconfigure
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @lazy-importer!
2026-10-26 14:53:47 +01:00
Ludovic MarieandClaude Opus 5.5 9540734e29 Merge main into fix/cushion-placement
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:50:57 +01:00
Ludovic Marie 601df6c22d Merge pull request #2052 from levzzz5154/fix/chest-shift-click
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @levzzz5154!
2026-10-26 14:50:55 +01:00
Ludovic MarieandClaude Opus 5.5 3dd17ad7d7 Launcher: registry mods show their 1-5 star rating
Horizon results and project pages show a project's rating from the
registry service (GET playhorizon.dev/api/mods/ratings, fetched with the
results, kept ten minutes): five pixel stars, the mean and how many, or
"No ratings yet". Nothing shows when the service doesn't answer.

The launcher has no GitHub account, so a project's page offers "Sign in
with GitHub to rate": it opens the site's sign-in, which comes back to the
project's page and its stars (one rating per GitHub account).

HORIZON_MOD_RATINGS (a file or https:// address) points a test registry at
its own ratings. The star icon is drawn for Horizon on the icons' grid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:50:40 +01:00
Ludovic Marie 394ce4928c Merge pull request #2044 from Domanffe/docs/roadmap-help-wanted-links
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:47:47 +01:00
Ludovic MarieandClaude Opus 5.5 0e4965845a Book pages: move by words as MultilineTextField does
BookEditScreen's page is a MultiLineEditBox. Its getPreviousWord and
getNextWord split words at any whitespace (Character.isWhitespace, line breaks
included) and start from the cursor clamped to the last character. The
single-line EditBox.getWordPosition keeps looking at spaces only, so the line
break rule moves to the multiline box alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:47:17 +01:00
Ludovic Marie 8fa967ac07 Merge remote-tracking branch 'origin/main' into feat/server-mods-game 2026-10-26 14:45:29 +01:00
Ludovic Marie aec52c85e9 Merge pull request #2041 from Domanffe/perf/uniform-values-reuse
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:44:52 +01:00
Ludovic MarieandClaude Opus 5.5 a0a170064e Merge main into sprint-jump-impulse
Main's #1779 already keeps the sprint through PlayerInput (hub.rs, agent.rs)
and has the same lan_bot test, so this keeps main's side: what the branch adds
is the two unit tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:44:08 +01:00
Ludovic MarieandClaude Opus 5.5 caae026416 HDR: keep native material packs' vertex tint opaque
The mesher now keeps a face's light emission in its colour's alpha byte. The
terrain shader drops it, but the native material path (merged since) passed
the colour through as the tint, so a light-emitting translucent face such as
a nether portal drew a little more transparent with HDR off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:42:00 +01:00
Ludovic MarieandClaude Opus 5.5 92ed365a19 Merge main into hdr-output
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:41:59 +01:00
Ludovic Marie c65338b3cb Merge pull request #2029 from Domanffe/perf/subtitle-width-once
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:41:27 +01:00
Ludovic MarieandClaude Opus 5.5 590ca775c2 Mod registry: download counts in the index and the launcher's browser
The registry's publish job (ludovic111/horizon-mods#7) writes each
project's `downloads` into index.json, summed from GitHub's counts of its
release assets every hour. `index::Project` reads it (absent: 0, never
written when 0, so older readers and the schema are unchanged).

The launcher's Horizon results show "12.3k downloads" like Modrinth's, and
list the most downloaded first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:37:12 +01:00
Ludovic Marie 38bea19137 Merge pull request #2167 from ludovic111/feat/mod-ratings-api
🤖 Agent: Merging. The verify and mod-registry checks (fmt, clippy -D warnings, tests) passed. The registry-data volume is already mounted at /data.
2026-10-26 14:36:12 +01:00
Ludovic MarieandClaude Opus 5.5 282556870f Cushions: pass when occupied, burn when placed in fire, entity_place
Checked against the 26.3 bytecode (tools/rea_vanilla.py):
- Cushion.interact passes (PASS) when the cushion already has a rider;
  CONSUME is only for a startRiding that fails.
- CushionItem.useOn calls destroyIfInFire right after addFreshEntity, and
  posts GameEvent.ENTITY_PLACE from the player.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:34:55 +01:00
Ludovic Marie a03940e0a8 Merge pull request #2166 from ludovic111/ci/parity-main-flake-green
🤖 Agent: parity-main counts a failure that passes again at HEAD as a pass; tests assert each exit code, YAML parses.
2026-10-26 14:33:41 +01:00
Ludovic Marie 4f70efcfa9 Merge pull request #2027 from Domanffe/perf/sign-first-line
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:33:10 +01:00
Ludovic MarieandClaude Opus 5.5 a83d6f33be Campfire: a full campfire's use does not swing the arm
CampfireBlock.useItemOn returns SUCCESS_SERVER (a swing) only when
placeFood took the item, and CONSUME (no swing) when all four slots are
taken.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:31:50 +01:00
Ludovic Marie 9c26db87e6 Merge pull request #2024 from levzzz5154/fix/remote-cooldown-tick
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @levzzz5154!
2026-10-26 14:30:19 +01:00
Ludovic MarieandClaude Opus 5.5 f49d5d91e6 Site: downloads and 1-5 star ratings on /mods
- The list shows each project's rating (stars, mean and count) and its
  downloads ("12.3k downloads"), ordered by downloads by default; an Order
  menu also sorts by rating or name (?sort= too).
- A project's page shows the same, then a rating control: five stars when
  signed in (the account's own rating lit), "Sign in with GitHub to rate"
  (coming back to the page) when not, a note for its owners.
- Ratings come from the registry service's GET /api/mods/ratings; a rating
  is POSTed with the session's CSRF token. Until the service answers, the
  pages show downloads only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:29:31 +01:00
Ludovic Marie ec7a2e22a7 Merge pull request #2012 from Domanffe/perf/poses-layer-reuse
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:27:29 +01:00
Ludovic MarieandClaude Opus 5.5 3caf8f7014 lan_e2e portals: close the credits on the host's first End exit
The first exit from the End now rolls the poem and credits, and the host
goes home once they close (PERFORM_RESPAWN); the check asserts they show.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:24:09 +01:00
Ludovic MarieandClaude Opus 5.5 8d6d1f26a4 Send a bundle's contents to a server's clients
BundleContents had no stream codec here: the host never sent what a bundle
holds, so on the server thread, LAN and a dedicated server the new tooltip
showed every bundle empty, and a vanilla server's bundle made its packet
undecodable. Its STREAM_CODEC is a list of ItemStackTemplate, the same as
ChargedProjectiles' (component 52).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:20:25 +01:00
Ludovic Marie b78daab11c Merge pull request #2081 from kacpherek/fix/performance-keeps-animated-textures
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @kacpherek!
2026-10-26 14:18:21 +01:00
zhykowoandWorkBuddy AI da54f988d4 Proxy: one copy of the rules, none of it per request
Co-Authored-By: WorkBuddy AI (DeepSeek-V4.1-Flash) <[email protected]>
2026-10-26 21:17:28 +08:00
Ludovic MarieandClaude Opus 5.5 455817204f Mod registry: 1-5 star ratings, one per GitHub account
The registry service keeps players' ratings of published projects in one
SQLite file on a volume (REGISTRY_DB, /data on Railway):
- GET /api/mods/ratings: every rated project's average and count, cached a
  minute; never who rated.
- GET /api/mods/{id}/rating: the signed-in account's own rating.
- POST /api/mods/{id}/rating: sets or changes it, checked like a submission
  (origin, session, CSRF token), 30 per account and 600 in all per hour, only
  for projects on the registry's main, never by their owners.
- The sign-in takes ?back=/mods/<id> to come back to a project's page.

The image hands the volume to nobody before running as nobody.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:15:46 +01:00
Ludovic Marie aadb8b6727 Merge pull request #2079 from nirajkhetre/fix/enderman-death-message
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @nirajkhetre!
2026-10-26 14:14:44 +01:00
Ludovic Marie 7b94de404e Merge pull request #2010 from Domanffe/perf/skip-lookup-once
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:13:29 +01:00
Ludovic MarieandClaude Opus 5.5 9e76f8c4f0 parity-main: a failure that passes again at HEAD counts as a pass
Twice today (runs 40301239508, 40311712302) mob_ai failed in parity-main, passed when bisect ran it again at
the same HEAD, and the run still ended red, so no game release could follow main for three hours. The
harness step now continues on error and the bisect step gives the verdict: 0 when every failed harness
passes again at HEAD, 1 when they fail at the base too or a merge is named.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:12:04 +01:00
Ludovic Marie 8087d8bf58 Merge pull request #2009 from vlesmentie/fix/villager-new-profession-trades
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @vlesmentie!
2026-10-26 14:10:43 +01:00
Ludovic Marie 659e6d7896 Merge pull request #1993 from Domanffe/perf/no-double-cracks-and-ticker-copy
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:09:57 +01:00
Ludovic MarieandClaude Opus 5.5 ae63b23dd6 lan_e2e guardian-beams: the host reads the guardian's own level
horizon-ctl's mobs answers from the server's level when the host runs on
its server thread, where the targeted player is Player, as in-frame.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:08:15 +01:00
Ludovic Marie a3f5615ec7 Merge pull request #2108 from ludovic111/perf/worldgen-data-parallel-load
🤖 Agent: pr_ready passed (horizon-world and client tests, affected harnesses), lan_e2e passed in-frame and on the server thread. GeneratorData::load on the ThinkPad 0.64 → 0.45 s warm. Queued for merge.
2026-10-26 14:07:33 +01:00
Ludovic Marie b244c5d26e Merge pull request #2042 from Domanffe/perf/tooltip-component-compare
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 14:06:20 +01:00
Ludovic MarieandClaude Opus 5.5 d983ef89b4 Keep item_name as its component: translate it when drawn
The decoded plain string replaced the component on save and on the way to
LAN guests, so a translatable name (explorer maps' filled_map.*, the
ominous banner in tests without a language) came back as its key, and
spill's ominous banner test failed. The component now stays in the patch
as loaded and is resolved in the current language when a name is drawn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 14:05:17 +01:00
Ludovic Marie 9af6d0be5c Merge pull request #2118 from ludovic111/fix/localize-server-screens
🤖 Agent: contrib-gate-17 verified this head (integration tree build, clippy, tests, parity; details in the PR comment). Re-opened from kohad1ck's PR; thanks to kohad1ck.
2026-10-26 14:03:06 +01:00
Ludovic Marie 034c0f0228 Merge pull request #2117 from ludovic111/fix/font-glyphs-atlas-rebuild
🤖 Agent: contrib-gate-17 verified this head (integration tree build, clippy, tests, parity; details in the PR comment). Re-opened from kohad1ck's PR; thanks to kohad1ck.
2026-10-26 14:00:01 +01:00
Ludovic Marie dec94b6c61 Merge pull request #2053 from rdbtCVS/rdbtcvs/fix-2019-recipe-screen-cleanup
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @rdbtCVS!
2026-10-26 13:59:13 +01:00
Ludovic Marie c1e7a86622 Merge pull request #2020 from levzzz5154/fix/guest-chat-visibility
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @levzzz5154!
2026-10-26 13:58:21 +01:00
Ludovic Marie 6ee319c607 Merge pull request #2018 from rdbtCVS/fix/peaceful-mob-despawn-1942
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @rdbtCVS!
2026-10-26 13:55:47 +01:00
Ludovic Marie fc5cd8060d Merge pull request #2007 from rdbtCVS/fix/1962-passenger-animation
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @rdbtCVS!
2026-10-26 13:55:12 +01:00
Ludovic Marie 0555120244 Merge pull request #2048 from rdbtCVS/fix/1490-sonic-boom-delivery
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @rdbtCVS!
2026-10-26 13:52:47 +01:00
Ludovic Marie 9feb4da17c Merge pull request #2003 from rdbtCVS/fix/bat-wing-animation-2000
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @rdbtCVS!
2026-10-26 13:51:59 +01:00
Ludovic Marie f8f49a033f Merge pull request #1992 from DanielGodriNeto/fix/benchmark-wait-loaded
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @DanielGodriNeto!
2026-10-26 13:51:04 +01:00
Ludovic Marie 245206203d Merge pull request #1999 from rdbtCVS/t3/fix-critical-hit-particles
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @rdbtCVS!
2026-10-26 13:48:23 +01:00
Ludovic Marie 1da8c57e72 Merge pull request #1987 from socksprox/fix/world-text-parity
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @socksprox!
2026-10-26 13:47:04 +01:00
Ludovic Marie 11635c3bdf Merge pull request #2085 from kacpherek/fix/2084-enderman-teleport
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @kacpherek!
2026-10-26 13:44:44 +01:00
Ludovic Marie ba6ca28577 Merge pull request #2082 from kacpherek/fix/fire-extinguish-no-break-particles
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @kacpherek!
2026-10-26 13:44:08 +01:00
Ludovic Marie 612d5f33ea Merge pull request #2031 from Domanffe/perf/debug-line-width-once
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 13:43:34 +01:00
Ludovic Marie f6b3e9935d Merge pull request #2011 from Domanffe/perf/vehicle-set-once
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @Domanffe!
2026-10-26 13:42:53 +01:00
Ludovic Marie 749a8a2a64 Merge pull request #1986 from some-du6e/fix/prepare-atlauncher
🤖 Agent: contrib-gate-17 verified this head (26.3 sources, integration tree build, clippy, tests, parity; details in the PR comment). Thanks @some-du6e!
2026-10-26 13:42:23 +01:00
Ludovic Marie 175419c6e7 Merge pull request #2139 from ludovic111/fix/registry-dockerfile-shader-api
🤖 Agent: the registry image copies horizon-shader-api (every Railway build failed without it); the same context builds locally with --locked.
2026-10-26 13:42:01 +01:00
Ludovic Marie aea0df9770 Merge pull request #2122 from ludovic111/feat/native-material-stage
🤖 Agent: verified: pr_ready --quick green at this head, 33/33 affected harnesses pass locally, CI verify green, A/B shows no frame cost without a pack. A Horizon shader pack's material stage now colours terrain in the game.
2026-10-26 13:38:03 +01:00
Ludovic MarieandClaude Opus 5.5 145c4c877b Quiet commands: the server runs a mod's batch of commands with no chat
A Horizon client sends a client mod's batch of command lines as one
`horizon:quiet_commands` payload, which Horizon's server announces only to
Horizon clients. Each line runs exactly as the player typing it would
(the same checks, their own permission level), with vanilla's suppressed
output: no feedback and no failure in anyone's chat. Batches wait in a
queue: at most 64 lines run per player per tick, and at most 4096 wait.
Each finished batch is one line in the server's log.

tools/quiet_commands_e2e.py checks it on the dedicated server: a non-op's
quiet setblock is refused, an op's runs, and nothing reaches the chat.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 13:37:04 +01:00
Ludovic MarieandClaude Opus 5.5 4b3af580d9 mob_ai: drop the Peaceful type scenarios that diverge for other reasons
A slime made without finalizeSpawn keeps 20 health where the probe's has 1,
the probe doesn't report a piglin's brain, and a NoAI bee's flower cooldown
runs one tick apart; none of that is the Peaceful despawn rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 13:34:52 +01:00
Ludovic MarieandClaude Opus 5.5 a34cad379f mod registry image: copy horizon-shader-api, which horizon-mods now depends on
Every Railway build of the registry has failed since horizon-mods gained the optional horizon-shader-api
dependency ("no matching package named horizon-shader-api"). Built the same context locally: OK.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 13:32:27 +01:00
Ludovic Marie a27579dd72 Merge remote-tracking branch 'origin/main' into feat/server-mods-game
# Conflicts:
#	crates/horizon-client/src/game/mods.rs
2026-10-26 13:29:17 +01:00
Ludovic Marie 23c748b2f3 Merge pull request #2127 from ludovic111/fix/ops-feedback-clock
🤖 Agent: server_ops_feedback on the server clock (stall-injector proof by ci-flakes-1); CI parity runs the harness.
2026-10-26 13:17:23 +01:00
Ludovic MarieandClaude Opus 5.5 ddbf2ce211 Trading probe: compare generated offers only
The probe's output is what the harness compares with vanilla; the codec
round trip lives in the unit tests, and its unwrap on a cost whose
components name an unmapped registry entry could abort the probe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 13:16:22 +01:00
Ludovic Marie 5a9e07301b Merge pull request #2113 from ludovic111/feat/mod-raycast
🤖 Agent: game.raycast, mod API level 2. CI is green on c23b4e8e4. In game, in-frame and on the server thread, the ui guest's /raycast passes all four checks: glass at 2 blocks, nothing at 1, gold after /setblock, the sky is no hit. The ported Orbital Laser aims with it and fires in both modes. Queued.
2026-10-26 13:13:29 +01:00
Ludovic MarieandClaude Opus 5.5 e2e591858e Fire smoke: a waterlogged neighbour doesn't burn
FireBlock.getIgniteOdds returns 0 for a waterlogged state, so canBurn is
false there and the smoke takes the other branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 13:11:49 +01:00
Ludovic MarieandClaude Opus 5.5 6a7951e150 mob_ai oracle: create a Peaceful scenario's hostile mobs past canSpawn
EntityType.create returns null for a type that isn't allowedInPeaceful once
the difficulty is Peaceful, so the peaceful_* scenarios threw in the oracle.
Their mobs stand for ones already in the world when the difficulty changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 13:09:28 +01:00
Ludovic MarieandClaude Opus 5.5 e944bd2a0e Merge main (#2114 merged)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 13:09:24 +01:00
Alexander Krylov 51425c9c22 Merge remote-tracking branch 'origin/main' into docs/roadmap-help-wanted-links 2026-10-26 15:07:19 +03:00
Alexander Krylov dfefb6d46a Merge remote-tracking branch 'origin/main' into perf/tooltip-component-compare 2026-10-26 15:07:16 +03:00
Alexander Krylov 02f147f137 Merge remote-tracking branch 'origin/main' into perf/uniform-values-reuse 2026-10-26 15:07:14 +03:00
Alexander Krylov 54e4274b87 Merge remote-tracking branch 'origin/main' into perf/debug-line-width-once 2026-10-26 15:07:11 +03:00
Alexander Krylov c2d137ed06 Merge remote-tracking branch 'origin/main' into perf/subtitle-width-once 2026-10-26 15:07:08 +03:00
Alexander Krylov 81e4272126 Merge remote-tracking branch 'origin/main' into perf/sign-first-line 2026-10-26 15:07:05 +03:00
Alexander Krylov 7e047c409c Merge remote-tracking branch 'origin/main' into perf/poses-layer-reuse 2026-10-26 15:07:01 +03:00
Alexander Krylov d3a1ce1d7a Merge remote-tracking branch 'origin/main' into perf/vehicle-set-once 2026-10-26 15:06:56 +03:00
Alexander Krylov 11eb74b0b6 Merge remote-tracking branch 'origin/main' into perf/skip-lookup-once 2026-10-26 15:06:45 +03:00
Alexander Krylov 68f23b9916 Merge remote-tracking branch 'origin/main' into perf/no-double-cracks-and-ticker-copy 2026-10-26 15:06:38 +03:00
Ludovic Marie 43929f3ff8 Merge pull request #2090 from ludovic111/perf/teleport-drop-off-frame
🤖 Agent: pr_ready passed (79 harnesses, 1299 client tests), lan_e2e passed in-frame and on the server thread (portals, levels, distance). Mass-drop frame at RD 32: 26-40 → 7-8.5 ms. Queued for merge.
2026-10-26 13:02:03 +01:00
Ludovic Marie f362f15212 Merge pull request #2114 from ludovic111/fix/harness-await-flakes
🤖 Agent: harness-only change (skip-release). The old harnesses fail under server stalls, the new ones pass; 20 affected harnesses pass locally, and the two changed ones rerun after merging main.
2026-10-26 12:53:58 +01:00
Ludovic Marie 68fa7714bb Merge remote-tracking branch 'origin/main' into feat/native-material-stage
# Conflicts:
#	docs/shaders.md
2026-10-26 12:48:15 +01:00
Ludovic MarieandClaude Sonnet 5.5 f0649da024 parity: server_ops_feedback ends steps on the server's clock, not a 2 s sleep
Built on the Client of the harness-await branch (#2114). Under 2.5 s server stalls the old harness fails (a command's
feedback filed under the next step) and the new one passes 3 of 3.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 12:46:11 +01:00
Ludovic Marie 4fbb0cde70 Merge pull request #1837 from ludovic111/feat/server-mod-test-scripts
🤖 Agent: The test scripts for server mods. CI is green on d64bd7c52, and the PR is now based on main after #1833 merged. I ran pr_ready --quick on this head merged with main (b8027d4b1): fmt, clippy, the horizon-mods and welcome tests (48) and the launcher tests (132) all pass. The only affected harness is lan_integration, which runs in CI. Queued.
2026-10-26 12:43:44 +01:00
Ludovic MarieandClaude Opus 5.5 fcbadbaa30 Merge main into rdbt/fix-1478-firework-bursts-20261026
fireworks.rs keeps main's rocket blast damage next to the client burst;
lan_e2e.py takes main's CHECKS and server-thread default plus 'fireworks'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 12:37:15 +01:00
kohad1ck b279758c7c Localization: server screens and the new world name follow the language
The Add/Edit Server, Direct Connection and Friends screens and Create New\nWorld built their titles, field labels, defaults and buttons from English\nliterals, so every non-English language showed English there. Route them\nthrough the current language with vanilla's keys:\n\n- ManageServerScreen: manageServer.add.title/edit.title, enterName, enterIp,\n  selectServer.defaultName, gui.done and gui.cancel.\n- DirectJoinServerScreen: manageServer.enterIp (the addServer.enterIp key is\n  not in 26.3), selectServer.select and gui.cancel.\n- WorldCreationUiState: selectWorld.newWorld.\n- Select World: selectWorld.title and selectWorld.versionUnknown.\n- DisconnectedScreen: disconnect.lost and gui.toMenu.\n\nA language missing a key keeps the English fallback, so en_us is unchanged.\n\nCo-Authored-By: ZCode Agent <[email protected]>
2026-10-26 12:35:25 +01:00
kohad1ck 5ec21ff5f1 Font: menus keep their run-time glyphs when the renderer rebuilds its atlas
Menu text drawn with characters the bitmap sheets lack (Chinese, Japanese,
Korean) is rasterized into a reserve of the shared atlas at run time, and the
font caches the atlas rect it got. The loading screen hands over to the game
about two seconds after the title shows by building a new renderer, whose
atlas texture is made from HudAtlas.pixels alone: those never hold a
run-time glyph, while the cache still answers with the old rects, so every
such character already drawn went blank. Latin text, straight from the
sheets, stayed. build_renderer and loading_renderer now forget the cache
before the new texture exists, so the characters that are drawn again are
placed into it, as ui_theme clears its own cache when the atlas changes.

Fixes #1824, fixes #2040.
2026-10-26 12:35:21 +01:00
Ludovic MarieandClaude Opus 5.5 db5c10ba20 Merchant offers: rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 12:35:09 +01:00
Ludovic MarieandClaude Opus 5.5 f4b4f944e3 Capture test: the fixture's Game resets its inventory clicks too
capture(true) now calls reset_inventory_clicks; the fixture compiles the
method body against a stub Game.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 12:33:08 +01:00
Ludovic Marie 6ff335eacf Merge pull request #2112 from ludovic111/feat/native-material-plumbing
🤖 Agent: verified: pr_ready --quick green, 30/30 affected harnesses pass locally, CI verify green. Internal: one WGSL prefixer for the shader-pack stages (no visible change).
2026-10-26 12:32:07 +01:00
c23b4e8e41 Mod API: game.raycast, the block the player looks at (level 2)
`game.raycast(distance)` returns the first block along the player's view
(fluids pass), up to 1024 blocks: through the loaded chunks as the
crosshair's ray goes, then across the distant terrain's ground heights
(`Lod::ground`, from Stink-O's fork). The game casts it only while a running
mod imports the function. It is API level 2, so older Horizons refuse a mod
that calls it with "update Horizon".

Co-authored-by: Stink-O <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 12:27:06 +01:00
Ludovic Marie b8027d4b19 Merge pull request #1765 from ludovic111/feat/lithostitched-processors
Lithostitched's processors as the game's own types; replace the old Lithostitched conversion
2026-10-26 12:24:09 +01:00
Ludovic Marie 4d98e545eb Merge pull request #2098 from ludovic111/feat/launcher-mod-api-level
🤖 Agent: The launcher half of the mod API levels. CI is green on c8464c6bf, and the PR is now based on main after #2080 merged. Launcher tests pass, the new browser test included. The level mark is read from a real fast build of the game. Queued.
2026-10-26 12:22:55 +01:00
zhykowoandWorkBuddy AI a9453b7c93 Modpack downloads honour NO_PROXY too
The jars an import fetches went through the proxy whatever the host, so a host
that only answers directly failed there while the launcher's own requests to it
went direct. net::agent now takes the URL and applies the same NO_PROXY and
loopback rules the launcher's own traffic gets.

Co-Authored-By: WorkBuddy AI (DeepSeek-V4.1-Flash) <[email protected]>
2026-10-26 19:21:09 +08:00
Ludovic MarieandClaude Opus 5.5 fe19efb917 Predicted break: test BaseFireBlock by its class, as the server does
The world side checks Class::BaseFire; the tag is a data-pack list that can
differ from the class.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 12:14:59 +01:00
Ludovic Marie e34cb7c021 Merge pull request #2080 from ludovic111/feat/mod-api-level
🤖 Agent: Mod API levels. CI is green on b12c89650. Locally: horizon-mods lib 31, api_reference 4 and sandbox 26 pass. A dummy component that calls a function from a newer level is refused with "update Horizon". Level 1 is render.set-minimap and the players.* functions; level 0 matches 0.2.67 to 0.2.69. Queued.
2026-10-26 12:06:13 +01:00
Ludovic Marie 5d04a5bee8 Merge remote-tracking branch 'origin/main' into fix/harness-await-flakes 2026-10-26 12:04:32 +01:00
Ludovic Marie b66861c721 Merge pull request #2106 from ludovic111/ci/nightly-schedule-guard
🤖 Agent: nightly schedule guard by Paris offset, lan_integration timeout; YAML checked.
2026-10-26 11:59:55 +01:00
Ludovic Marie 27f63ce50c Merge pull request #1975 from kacpherek/fix/1523-tp-during-arrival
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:55:20 +01:00
Ludovic Marie 8682fb845d Merge pull request #1971 from kacpherek/fix/1477-firework-player-damage
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:52:34 +01:00
Ludovic MarieandClaude Opus 5.5 189b2c6b3c nightly: pick the 03:07 Paris schedule by offset, not by the clock at start; room for lan_integration
GitHub started both 10-26 schedules over an hour late, so the hour check skipped both and no audit ran.
lan_integration takes ~2,400 s under load, past the 1,800 s per-harness limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:52:09 +01:00
Ludovic Marie c048292f3f Merge pull request #1909 from rdbtCVS/t3/server-thread-integration-clean
🤖 Agent: gate verified on e3e08911b (main merged). fmt, clippy -D warnings and horizon-client tests pass. lan_e2e with the server-thread host: 131/133, and cursor/falling pass on rerun in both modes. 14 in-frame checks pass. agent_control_e2e: only manage fails, and it fails the same way on main. 82 of the 83 affected harnesses pass. lan_integration flakes under load and is now named-only (nightly). Queued.
2026-10-26 11:47:59 +01:00
Ludovic MarieandClaude Opus 5.5 ee83d8f247 Chat test: set the abilities through set_abilities (clippy)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:47:27 +01:00
Ludovic Marie c8464c6bff Merge branch 'feat/mod-api-level' into feat/launcher-mod-api-level 2026-10-26 11:46:43 +01:00
Ludovic MarieandClaude Opus 5.5 b12c89650e Mod API levels: server mods' players functions are level 1; the registry's lockfile
Main gained players.online, tell and broadcast (#1833) after 0.2.69, so
they take level 1 with render.set-minimap. horizon-mod-registry's own
Cargo.lock picks up wasmparser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:46:27 +01:00
Kacpherek 990786901a Let empty boats and minecarts enter Nether portals 2026-10-26 11:46:16 +01:00
Kacpherek 1f51e3d18c Server players: chest minecart and chest boat menus stay open
A vehicle's items are kept under a placeholder key far outside the world, and the guest container tick checked the player's reach to that key as a block, so the menu closed the tick it opened. Vanilla checks reach to the vehicle (ContainerEntity.isChestVehicleStillValid).
2026-10-26 11:46:10 +01:00
Kacpherek 49b167ce22 Item frames: shade the frame model by face and light glow frames from 5 2026-10-26 11:45:56 +01:00
Ludovic Marie 0a9a7c0d06 Merge remote-tracking branch 'origin/main' into feat/mod-api-level 2026-10-26 11:45:15 +01:00
Ludovic Marie d104a350cd Merge pull request #1980 from kacpherek/fix/place-sound-refused
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:45:09 +01:00
Kacpherek 1e6884c591 Show the poem and credits on a player's first End exit in server-thread mode 2026-10-26 11:43:37 +01:00
Ludovic MarieandClaude Opus 5.5 cdbe1edcda Text displays: keep the background at vanilla's -1..width, -1..height
TextDisplayRenderer.submitInner calls submitTextBackground(-1, -1, width,
height), and Font.prepareBackground's effect glyph spans x0..x1, y0..y1, so the
fill is width + 1 by height + 1 from (-1, -1), as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:42:48 +01:00
Ludovic MarieandClaude Opus 5.5 2bfa7f57ba Merge main into fix/world-text-parity
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:42:48 +01:00
Ludovic Marie 6cd4238930 Merge pull request #1979 from kacpherek/fix/1899-swim-ceiling
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:42:32 +01:00
Kacpherek 76e2c84103 Recipe book: a click on a category tab reaches the book before the outside test 2026-10-26 11:41:21 +01:00
Ludovic MarieandClaude Opus 5.5 7abae79d41 Merge main into fix/prepare-atlauncher
sounds.rs: main's Assets::load reads the launcher's files through game_files.
The rewritten-manifest test takes main's message; main's new test passes
GameFiles. ATLauncher is also looked for where the Horizon launcher looks
(~/Library/Application Support/ATLauncher, the Flatpak's data/atlauncher).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:41:03 +01:00
Ludovic Marie 3c1ab736d5 Merge pull request #1978 from kacpherek/fix/1881-death-camera-tilt
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:39:58 +01:00
socksproxandDevin 0a2de159fd Fire: ambient smoke particles and no mob-break crumbs
BaseFireBlock.animateTick adds large smoke above a fire (three puffs in
its top half), or two puffs at each burnable neighbour's face when the
fire sits on nothing burnable or sturdy. SoulFireBlock.canBurn is
always true, so soul fire always takes the top-half branch. The
burnable table mirrors FireBlock.canBurn (fire.igniteOdds above zero)
from block-behaviours.json.

Mobs breaking blocks (MobEvent::BreakBlock) map to Level.destroyBlock,
whose Block.spawnDestroyParticles BaseFireBlock overrides to nothing:
a wither or another mob destroying fire no longer emits break
particles. Player breaks already route through player_destroy (1009);
the client-side predict_break particles are PR #2082's.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 11:39:08 +01:00
Ludovic MarieandClaude Opus 5.5 f19390bae1 Sonic boom: take the LAN host in the same let-else as the particle
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:39:07 +01:00
Ludovic MarieandClaude Opus 5.5 78bfe74465 Container clicks: the stuck-drag test joins the module's tests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:38:39 +01:00
rdbtCVSandOpenAI Codex GPT-6.1 Sol d25d0f025b Merchant offers: preserve required potion components
Co-Authored-By: OpenAI Codex GPT-6.1 Sol <[email protected]>
2026-10-26 10:38:26 +00:00
Ludovic MarieandClaude Opus 5.5 fb74b6038f Chat: system and player lines share the window's chat code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:38:17 +01:00
Ludovic MarieandClaude Opus 5.5 bde76794ee Mobs: no rain or thunder outside the overworld
Level.canHaveWeather is false in the Nether and the End, so their rain and
thunder levels stay at 0. Set that once in the mob world instead of checking
the End at two of the rain sites: bees, dolphins, wolves and happy ghasts read
the same flag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:37:43 +01:00
Ludovic Marie a31a435525 Merge pull request #1976 from kacpherek/fix/1526-gateway-cooldown
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:37:21 +01:00
Ludovic MarieandClaude Opus 5.5 2918f31811 Poses::reset clears the scratch pose too
A missing part's writes land in `dummy`; a fresh Poses started it at zero,
so a reused one must too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:36:50 +01:00
rdbtCVSandOpenAI Codex GPT-6.1 Sol 52a0a5a89c Fix firework bursts on server clients
Send the rocket explosion event before tracked removal and render it with the synchronized firework item. Cover colored bursts and later trail frames in both hosting paths.

Co-Authored-By: OpenAI Codex GPT-6.1 Sol <[email protected]>
2026-10-26 10:35:33 +00:00
Ludovic MarieandClaude Opus 5.5 c813261574 Horizon shader packs: the material stage runs in the game
A pack's `fn material(input: MaterialInput) -> Surface` now gives the lit
colour of every terrain surface: sections and distant tiles, solid,
cutout and translucent, in both the instanced and the flat draws. Terrain
keeps Horizon's meshes, culling and draw lists; only its pipelines change.
Their shader is the pack's stage, a prefixed copy of terrain.wgsl's
terrain section, and entries that hand the pack the texture, the vertex
tint, the light levels and the lightmap's colour apart, then apply the
alpha test and fog as `fs_solid` and `fs_translucent` do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:35:15 +01:00
Ludovic Marie 7650451b4f Merge pull request #1974 from kacpherek/fix/1500-vehicle-storage
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:34:26 +01:00
Ludovic MarieandClaude Opus 5.5 3c22ff0849 Launcher: don't install a mod version the game can't run
The game program carries its mod API level in a mark
(horizon-mod-api-level:NNNN;), which the launcher reads once per
installed version; a program from before the mark (0.2.68 and older)
serves level 0. The Horizon browser marks versions above the level of the
game the player runs (the selected version, else the newest installed)
"needs a newer Horizon than the game you play", and installs the newest
version that game can run, or says to update it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:33:30 +01:00
Ludovic Marie c0171fa6bc Merge pull request #1973 from kacpherek/fix/1497-machine-menu-changes
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:31:24 +01:00
Ludovic Marie 707348fcd5 Merge pull request #1972 from kacpherek/fix/1493-shulker-guest-homing
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:28:33 +01:00
Ludovic Marie 8a458496c7 Merge pull request #1984 from rdbtCVS/fix/1956-item-fluid-current
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:23:24 +01:00
Ludovic Marie 3144276935 Merge pull request #1970 from kacpherek/fix/1328-respawn-after-trip-death
🤖 Agent: Merged after the contrib-gate-16 review: checked against 26.3, the in-game checks and lan_e2e in both modes, and the 79 affected harnesses on the integration tree (see the gate comment). Thanks!
2026-10-26 11:22:15 +01:00
rdbtCVSandOpenAI Codex GPT-6.1 Sol 8c6ec16c99 Fix guardian charging beams on server clients
Sync guardian moving and active attack-target metadata, resolve the actual targeted player, and tick the client's visual charge clock. Cover charge completion and target loss for guardians and elders. Fixes #1491.

Co-Authored-By: OpenAI Codex GPT-6.1 Sol <[email protected]>
2026-10-26 10:21:50 +00:00
socksproxandDevin 6b8fde092f Keep 26.3's name-tag and text-display values
Review caught three regressions against the pinned client jar: submitInner
lines stay lineHeight+1 (10 px), submitNameTag fades discrete and
see-through names with the same 0x7F, and lightCoordsWithEmission floors
both light channels at 2.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 11:20:39 +01:00
levzzzandHermes Agent 7a2de4e328 Render bundle contents in station inventory tooltips
Keep hovered item stacks through draw_station and use draw_stack_tooltip, while retaining text-only station hints. Covers anvil and brewing-stand player inventory slots and stonecutter result previews.\n\nAdd an offscreen render regression which fails on the old binary for both reported screens and passes on the fix in server-thread and in-frame modes.

Co-Authored-By: Hermes Agent (OpenAI) <[email protected]>
2026-10-26 15:18:17 +05:00
Ludovic MarieandClaude Opus 5.5 08f4fd5c8e Teleports free their dropped columns off the frame and in batches
A teleport far away (or a storage that moves by more than its size) drops
every column in one frame: 3,725 at RD 32. That frame freed every column's
sections, then removed each section from the renderer one at a time, with
a few hash lookups per section and a free-list tree update per mesh range.

- The dropped columns, and a left dimension's whole chunk map, are freed on
  a short-lived thread of their own ("Chunk freeing").
- Renderer::remove_columns removes whole columns: one lookup per column for
  the tables kept by column, and the meshes' ranges go back to the arena in
  one sorted merge per page (FreeList::give_all) instead of a tree update
  each. Per-section Renderer::remove and Occlusion::remove had no other
  callers and are gone.
- The renderer's block-entity and detail-column tables use FxHashMap.

Mac mini (M4 Pro), RD 32, explored world, server thread, 3 alternated runs,
two long teleports each: the drop took 26.1-39.7 ms, now 6.9-8.5 ms.
Entering the Nether: 9.7-13.4 ms, now 4.0 ms or under 6 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:10:25 +01:00
Ludovic Marie 6c995bfa15 Merge remote-tracking branch 'origin/main' into feat/mod-api-level
# Conflicts:
#	crates/horizon-mods/Cargo.toml
#	crates/horizon-mods/src/index/tests.rs
#	launcher/Cargo.lock
2026-10-26 11:09:19 +01:00
Kacpherek 6b60056637 Thrown projectiles: fly on the client between server updates, eye shatter particles, potion motion order
On a server, arrows, snowballs, eggs, ender pearls, potions and eyes of ender only eased towards the tracker's position, which comes every 10 to 20 ticks, so they moved in jerks. Like vanilla (Entity's NO_OP InterpolationHandler) the server's position now replaces theirs at once and they fly on by themselves each tick.

A shattered eye of ender now sends level event 2003 with its item crumbs and portal rings.

Thrown potions applied gravity and drag after the move; ThrowableProjectile applies them before.
2026-10-26 11:07:37 +01:00
Ludovic Marie 88b7bfafc0 Merge pull request #1833 from ludovic111/feat/server-mods-0.3
🤖 Agent: merged main (12 files conflicted with ui, render and input). The runtime now keeps the server/client Hooks split beside the ui-events export, and the Snapshot carries both the GUI fields and the server's players. Locally: the horizon-mods sandbox and unit tests, cargo-horizon-mod tests, and clippy on the client with mods all pass. CI verify and parity pass at b90ab85f4. Bottom of the server-mods stack (#1837, #1894, #1895, #1901 follow).
2026-10-26 11:07:35 +01:00
Ludovic MarieandClaude Sonnet 5.5 34d8d94022 parity: server harnesses wait on the server's clock and replies, not on sleeps
server_knockback, locator_bar, server_dimension_players and their one-player users now end a step by the server's
game clock (a sync round trip, N ticks, a last sync) the way server_player_targets does, so a server that stalls
under load still gets all its ticks inside the step. server_knockback's frozen section waits for the stepped tick,
the stopped clock and the landed hit; dedicated_server waits for the player's leaving before /list.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 11:06:02 +01:00
Kacpherek 311c0f7392 Stop endermen teleporting nonstop in the End
The End has a fixed time and no precipitation, so endermen there must not
flee daylight or take rain damage.
2026-10-26 11:05:49 +01:00
Ludovic MarieandClaude Opus 5.5 83f0d5bf58 Worldgen data loads its three biggest parts in parallel
GeneratorData::load read everything on the server thread while the chunk
workers waited: the block tables, the structure templates and the block
behaviours now load on threads of their own, and BlockBehavior::load reads
its cached-support table beside the other two. The behaviour exports
(gameplay-facts.json is 55 MB) parse from bytes in memory instead of
through a reader.

ThinkPad (2 cores), 3 alternated runs: 0.63 -> 0.45 s with the behaviour
snapshot cached, 2.40 -> 2.07 s on a first start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:04:57 +01:00
SenjinandClaude Opus 5.5 728c6a62b3 HDR: the emission mark in the vertex colour's alpha, not a layer bit
EMISSIVE_LAYER took bit 14 of TerrainVertex::layer, halving the sprite
layers terrain vertices can index (32768 to 16384) and leaving no flag
bit free. The colour's alpha byte was always 0xFF: its low four bits now
hold 15 minus the light level the face emits (EMISSION_BITS), so 0xFF
still means none and the other four bits stay free. terrain.wgsl takes
only the colour's rgb and passes the level on; Java shader packs get
alpha 1; the section mesh fixture restores vanilla's 0xFF.

The HDR pass still lifts any emitting face the same way; the level is
there for scaling the lift by it later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:03:16 +01:00
SenjinandClaude Opus 5.5 9b863d6093 HDR output: scRGB swapchain, HDR metadata and emissive highlights
HDR (Graphics > Display, off by default) presents to an scRGB swapchain
where the surface offers it. The frame is drawn as in SDR, in vanilla's
gamma space; a last pass decodes it at the Paper White and lifts light
sources (blocks that emit light, lava, the sun and the moon) evenly
towards the Peak Brightness.

The mesher marks emitting faces with EMISSIVE_LAYER (bit 14 of the
layer); the frame's alpha carries the mark to the HDR pass, which lifts
only pixels that still show the world before the hand and HUD.

horizon-hdr sends HDR metadata through VK_EXT_hdr_metadata, which wgpu
doesn't: without it KWin clips scRGB content above 1.0 (80 nits).

Part of #1441.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 11:03:16 +01:00
Kacpherek c80b3b4950 Multiplayer: no break particles or sound when a player puts out fire
The predicted break played the block's break sound (wool for fire) and its destroy particles. BaseFireBlock skips both (spawnDestroyByEntityParticles does nothing); players only hear the server's extinguish sound.
2026-10-26 10:58:41 +01:00
Ludovic Marie 2a0f4e39a8 Merge pull request #2036 from ludovic111/feat/launcher-shader-packs
🤖 Agent: I looked at the launcher's Shader packs tab in dark and light (Mac mini, mktemp homes, a local registry with the sample pack): Soft Glow is listed from Horizon with Works, Page and Install, and the look matches the other tabs. pr_ready --quick is green, with the launcher's 130 tests.
2026-10-26 10:57:13 +01:00
Ludovic MarieandClaude Opus 5.5 acbcaad743 Horizon shader packs: one WGSL prefixer for copies of the renderer's shaders
The sky stage runs a copy of terrain.wgsl's sky beside the pack's code
with every name prefixed `horizon_sky_`. The prefixer moves to
`gfx/wgsl_prefix.rs` and now also renames module variables (bindings)
and overrides, so the material stage can copy the terrain section the
same way. The sky's shader is unchanged apart from where `globals` is
declared.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 10:56:39 +01:00
Kacpherek e7f41e7d13 Performance preset: keep animated textures on
The preset turned them off, which froze fire, water, lava and portals. Players reported fire with no animation (#2064). The option stays in Advanced Graphics for anyone who wants it off.
2026-10-26 10:51:26 +01:00
Ludovic MarieandClaude Opus 5.5 e3e08911ba parity: run lan_integration only when named and in the nightly audit
The harness runs the whole lan_e2e suite: ~40 minutes on a loaded runner,
and single checks flake under load (barter, riding, shulker_bullets in one
run; cursor, falling in another, all passing on rerun). Selected by
--changed it would run on most gameplay pull requests and on parity-main.
tools/parity_hosts.json gains a named_only table that every automatic
selection (--changed, --failed, the default, --flake-check) leaves out;
naming the harness or --all (the nightly audit) still runs it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 10:48:58 +01:00
Niraj Khetre 290e2e1ac7 The ender dragon's hits and breath name it in the death message
The dragon's wing and head hits and its breath clouds hurt the player
without recording the dragon as the causing entity, and the dragon is
not one of the mobs note_attacker looks up. death.attack.mob and
death.attack.indirectMagic then got only the victim's name, so the
template showed through: "%1$s was killed by %2$s using magic".

Record the dragon before its damage lands (EnderDragon.hurt and
knockBack use mobAttack(dragon); its breath clouds apply
indirectMagic(cloud, dragon)).

Fixes #2062

Assisted-by: Claude Opus 5.5
2026-10-26 15:14:37 +05:30
Ludovic Marie 87ff54e702 Merge remote-tracking branch 'origin/main' into feat/launcher-shader-packs
# Conflicts:
#	docs/shaders.md
2026-10-26 10:40:12 +01:00
Ludovic MarieandClaude Opus 5.5 8cc8c6180d Mod API levels: refuse a mod made for a newer Horizon, list each version's level
Every function the game offers mods has the API level it arrived at
(crates/horizon-mods/src/api_level.rs): level 0 is the contract of
Horizon 0.2.67 and 0.2.68, level 1 adds render.set-minimap. A mod needs
the level of the newest function it imports, read from its component.

- The game refuses a mod that calls a function it doesn't have with
  "made for a newer Horizon (it uses ...): update Horizon to run it"
  instead of wasmtime's linking error.
- The registry index lists each mod version's level (api_level, read
  from the file by CI); check_file compares it when the entry has one,
  and the moved extras' installer takes the newest version this game
  can run.
- cargo horizon-mod check prints the level.
- The api_reference test fails until a new WIT function has a level.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 10:39:47 +01:00
Ludovic Marie 852e7cd524 Merge pull request #1855 from ludovic111/feat/native-shaders-registry
🤖 Agent: verified: pr_ready --quick green (launcher and horizon-mods tests), CI verify and check green, merges cleanly with main. The registry takes Horizon shader packs, checked by the game's own shader check.
2026-10-26 10:39:24 +01:00
Ludovic Marie 28ef79ed66 Merge pull request #1863 from ludovic111/feat/native-shaders-sky
🤖 Agent: verified: pr_ready --quick green, 80/80 affected harnesses pass locally, CI verify green, A/B shows no frame cost without a pack. A Horizon shader pack's sky stage now draws in the game.
2026-10-26 10:36:58 +01:00
Ludovic Marie f52d053817 Merge pull request #2063 from ludovic111/feat/moved-minimap
🤖 Agent: verify passed. Checked against the real registry now that Minimap 1.0.0 is published: the migration e2e passes 34/34 on the server thread and 34/34 in-frame. The minimap case starts at bottom left, 128, round, 0.5 blocks per pixel, turning: the mod is installed and on, its settings carried, the map shows, and the Extras page has no minimap rows. pr_ready --quick passes (clippy, 1295 horizon-client tests).
2026-10-26 10:30:49 +01:00
levzzzand[CC] <deepseek-v4.1-flash> 941f148957 Loot: a single-level enchantment draws no level
Review of #2037 (rdbtCVS): `EnchantRandomlyFunction.enchantItem` calls
`Mth.nextInt(random, minLevel, maxLevel)`, which returns `min` without
drawing when `min >= max`. The arm here drew unconditionally, so choosing
Mending (or any one-level enchantment) shifted every roll after it.

`horizon_world::loot`'s copy and `merchant.rs`'s already guard this; only the
loot dispatcher in `items.rs` did not.

Vanilla with `LegacyRandom(11)`: a Mending book followed by
`set_count` uniform 1..64 is 46; the extra draw made it 28.
`a_single_level_enchantment_draws_no_level` pins that (and the stored
Mending level).

Co-Authored-By: [CC] <deepseek-v4.1-flash> <[email protected]>
2026-10-26 14:30:45 +05:00
lazy-importerandClaude Opus 5.5 ad7203fc8a Model item_name component on items and tooltips
In vanilla 1.20.5+, servers and datapacks customize base item names using
the `minecraft:item_name` data component rather than `minecraft:custom_name`.
Vanilla's `ItemStack.getHoverName()` checks `custom_name` first, then
falls back to `getItemName()`, which retrieves `DataComponents.ITEM_NAME`.

Previously, Horizon did not model `item_name` in `StackData`, causing items
with custom base names from servers or resource packs to fall back to
their default translation keys instead of the server-provided name.

This adds `item_name` to `StackData`, decodes and encodes it across
network item sync, and prioritizes it in `name_line` and hover tooltips.

Fixes #2039.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 10:21:00 +01:00
JoansitohandClaude Sonnet 5.5 fa8291fc97 Treat a line break as a word boundary in text fields.
Ctrl+Backspace on a book page with the caret after `two` in `one\ntwo` removed both lines because the word helper only knew spaces.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 10:06:48 +01:00
Ludovic Marie 593b99a68b Merge branch 'feat/server-mod-test-scripts' into feat/server-mods-game
# Conflicts:
#	crates/horizon-client/src/game/mods.rs
2026-10-26 10:01:50 +01:00
Ludovic Marie d64bd7c528 Merge branch 'feat/server-mods-0.3' into feat/server-mod-test-scripts
# Conflicts:
#	crates/horizon-mods/src/testing.rs
2026-10-26 09:56:41 +01:00
Ludovic Marie 45bc45b396 Merge pull request #2057 from ludovic111/perf/remote-chunks-off-render
🤖 Agent: pr_ready passed (78 harnesses), lan_e2e in-frame and server-thread passed; frame p99 4.96→3.95 ms during a RD 32 flight. Queued for merge.
2026-10-26 09:56:18 +01:00
Ludovic Marie 6f0c0c13b6 Merge pull request #2051 from ludovic111/feat/native-shader-frame
🤖 Agent: verified: pr_ready --quick green, 38/38 affected harnesses pass locally, CI verify green, A/B shows no frame cost. Internal: a Horizon shader pack's frame uniform is shared by its stages (no visible change).
2026-10-26 09:54:11 +01:00
Ludovic Marie b90ab85f44 Merge remote-tracking branch 'origin/main' into feat/server-mods-0.3
# Conflicts:
#	Cargo.toml
#	crates/cargo-horizon-mod/src/check.rs
#	crates/horizon-client/src/game/mods.rs
#	crates/horizon-mod-sdk/src/lib.rs
#	crates/horizon-mod-sdk/wit/horizon.wit
#	crates/horizon-mods/src/manifest.rs
#	crates/horizon-mods/src/runtime.rs
#	crates/horizon-mods/src/testing.rs
#	crates/horizon-mods/tests/sandbox.rs
#	docs/api/mods-reference.md
#	docs/api/mods.md
#	docs/mods.md
2026-10-26 09:51:00 +01:00
Ludovic Marie b110608a93 Merge remote-tracking branch 'origin/main' into feat/moved-minimap 2026-10-26 09:43:44 +01:00
lazy-importerandClaude Opus 5.5 c675329208 Reset boss overlay on server reconfiguration
When switching sub-servers on a proxy network (Velocity/BungeeCord), the
network thread enters configuration mode and emits Event::Reconfigured.
Vanilla's ClientPacketListener.handleConfigurationStart clears the client
level, which calls Hud.onDisconnected() and resets BossHealthOverlay.
Without this reset, bossbars from previous servers remained visible on
screen.

Fixes #2034.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:42:35 +01:00
Ludovic MarieandClaude Opus 5.5 382380fc8b Minimap moved to the mod browser: remove the built-in minimap
The official Minimap mod (mods/official/minimap) shows the extra's map
through render.set-minimap. The extra's switch and its five Extras rows
go; the game still draws a mod's map from the same tiles. A player who
had the minimap on gets the mod installed and turned on at the first
start, with the corner, size, shape, zoom and turning carried into its
storage, and one chat line. horizon-extras.txt keeps the old keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:38:52 +01:00
Ludovic Marie 9e447a7e92 Merge pull request #2058 from ludovic111/feat/official-minimap-mod
🤖 Agent: The official Minimap mod (mods/official/minimap): the minimap extra as a mod with its five options. Pixel-identical to the extra in the map region (0.000 to 0.002) with default and other settings, at the same frame cost. Verified: pr_ready (2179 workspace tests, clippy), the settings page in game, and the published mods loading beside it in both modes.
2026-10-26 09:34:51 +01:00
FusselTVandClaude Opus 5.5 ad50996f7c Structures: save the remaining legacy pieces as vanilla does
Desert and jungle temples, swamp huts, buried treasure, ocean
monuments, mineshafts, fortresses and strongholds save the tag their
StructurePiece subclass writes, with the state placement leaves: the
height a scattered feature settled on, the buried treasure chest,
placed chests, traps and spawners, and the swamp hut's witch and cat.
With these every StructurePieceType is saved.

test_structure_start_nbt_parity gets one site of each of these kinds,
and a badlands mineshaft.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:33:34 +01:00
FusselTVandClaude Opus 5.5 b7b36836af Structures: save template pieces as vanilla does
Igloo, shipwreck, ocean ruin, ruined portal, nether fossil, End City
and mansion pieces save the tag TemplateStructurePiece and its
subclasses write, with the state placement leaves: the height a
shipwreck or ocean ruin settled on and the igloo's moved box. Ruined
portals save all six properties, End City pieces their genDepth tag.

test_structure_start_nbt_parity gets one site of each of these kinds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:33:34 +01:00
FusselTVandClaude Opus 5.5 9a0fcda3a9 Proto chunks: save placed block entities with their id
Block entity data a structure places can lack its type: a brushable
block's is only its loot table. Finished chunks get the id from the block,
saved proto chunks did not. Vanilla and Paper skip a pending block entity
without one when they finish the chunk ("Skipping block entity with
invalid type"), so suspicious sand and gravel at the edge of a
pre-generated area lost their archaeology loot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:33:34 +01:00
FusselTVandClaude Opus 5.5 df3ac51447 Trial spawners: no empty spawn_data on save
The block entity canonicaliser added spawn_data {entity: {}} to every
trial spawner that had none. Vanilla only writes spawn_data once the
spawner has picked its next mob (TrialSpawnerStateData.Packed reads it as
Optional.empty). A spawner saved while mob spawning was off, as worlds
pre-generated in peaceful or with spawner_blocks_work false are, kept the
empty entity for good: getOrCreateNextSpawnData returns it, it names no
mob, and the spawner never spawns, in Horizon and in vanilla or Paper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:33:34 +01:00
FusselTVandClaude Opus 5.5 c776d6586e Structures: save jigsaw starts as StructureStart.createTag does
Horizon kept no saveable form of its structure starts, so its saves carry
an empty structures.starts and every structure it generates is invisible
to vanilla and Paper (locate, structure spawns, location predicates,
advancements) and cannot be continued past the generated area.

StructureStart::save and Piece::save write the tag vanilla writes. This
covers the pieces of jigsaw pools (villages, pillager outposts, ancient
cities, trail ruins, trial chambers, abandoned camps, bastions) with
their pool element, junctions and liquid settings. Junctions keep
delta_y and dest_proj, pool elements their processors as written.
LegacyPiece::save defaults to None; a start with such a piece is not
saved, as before.

test_structure_start_nbt_parity compares the tags with the pinned
server's own for one site of every jigsaw structure kind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:33:34 +01:00
FusselTVandClaude Opus 5.5 1bbe64265c Saves: Nether and End chunks keep their own height
Chunk holds the Overworld's 24 sections in every dimension, and the save
wrote them as they are: yPos -4, sections -4 to 19 and heightmaps counted
from y=-64. Vanilla and Paper trust those heightmaps, so a Horizon-made
Nether reads its surface at y=192, above the bedrock roof, and the End 64
blocks too high. Re-saving a vanilla Nether chunk rewrote its yPos too.

LevelShape (skylight, min_y, height per dimension folder) replaces the
save path's sky_light flag. yPos, the saved sections, the PostProcessing
lists and the heightmaps follow it, as SerializableChunkData.write does.

LAN clients in the Nether and End now get the chunk's heightmaps; the
heightmap check failed there and they were sent empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:33:33 +01:00
zhykowoandWorkBuddy AI 3e79b22c43 Launcher downloads go through the proxy the player sets
Everything the launcher fetches now goes through one HTTP proxy when there is
one: Horizon's releases and the launcher's own update, Minecraft's files and
Java from Mojang, Modrinth, CurseForge, the mod registry, pictures, Microsoft
sign-in, Tailscale's API, and the jars a modpack import downloads. It is
Settings' Proxy row (`proxy` in settings.json), or `horizon-launcher settings
proxy http://host:port`; without one, HTTPS_PROXY, HTTP_PROXY and ALL_PROXY
apply, with NO_PROXY naming the hosts to reach directly.

A local address never goes through it, and the Servers page's calls to a game
server's API stay direct: they are on loopback and asked every second.

horizon-port-pack builds its own agents, so the launcher hands it the address
(net.rs); run on its own, it reads the same variables.

Co-Authored-By: WorkBuddy AI (DeepSeek-V4.1-Flash) <[email protected]>
2026-10-26 16:28:24 +08:00
Ludovic MarieandClaude Opus 5.5 4498df8be5 Merge feat/official-minimap-mod into feat/moved-minimap
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:24:17 +01:00
levzzz d1c1af598b Bundles show what they hold
Hovering a bundle showed only its name and `BundleItem.appendHoverText`'s
"Can hold a mixed stack of items": nothing drew the contents, so a player
could not see what was inside or how full it was (#2001).

`ClientBundleTooltip` is ported to `bundle::tooltip_layout`: the 96 pixel
column, the four-wide grid filled bottom-up and right-to-left from
`getNumberOfItemsToShow` (eleven stacks and a `+N` when it overflows), the
progress bar at `Mth.mulAndTruncate(weight, 94)` with the full sprite and the
`item.minecraft.bundle.empty`/`.full` labels, and an empty bundle's wrapped
description. The game draws it under the stack's own tooltip
(`Game::draw_stack_tooltip`), which the inventory, creative, container,
beacon and trading hovers now use.

Verified in game: a bundle with 64 stone shows one slot and a full red bar
labelled "Full!"; one with 32 stone and 8 dirt shows two slots (32 stone
first, as the next out) over a half-filled blue bar; an empty one shows the
description and "Empty".
2026-10-26 13:22:31 +05:00
Ludovic Marie 57c5f81299 Merge pull request #2028 from ludovic111/feat/shader-packs-page
🤖 Agent: verified: pr_ready --quick green, 38/38 affected harnesses pass locally, CI verify green, paired A/B shows no frame cost. Options > Horizon Settings > Shader Packs lists and picks packs of either kind.
2026-10-26 09:22:21 +01:00
Ludovic Marie ce46917121 Merge pull request #2056 from ludovic111/feat/mod-minimap-api
🤖 Agent: Mod API render.set-minimap: a mod picks the corner, size, scale, shape and turning, and the game draws the map from the minimap extra's tiles. It is a new function, so published mods keep loading. Verified: pr_ready (1353 tests, clippy, launcher), the sandbox test, and in game beside the published mods in both modes.
2026-10-26 09:12:15 +01:00
Ludovic Marie 09d61ec866 Merge pull request #2030 from ludovic111/feat/moved-zoom
🤖 Agent: Zoom moved to the mod browser. The built-in zoom is removed, and a player who had it on gets the published Zoom mod with their settings and key. Verified against the real registry, in both modes (54/54), plus clippy and the client tests.
2026-10-26 09:09:19 +01:00
Ludovic MarieandClaude Opus 5.5 427b48aa42 Server chunk packets decode on their own thread, not in the frame
A server's chunk columns (single player on its server thread, LAN,
servers) were decoded on the render thread: sections, palettes, biomes
and light, about 0.1 ms each on an M4 Pro. Once the backlog was overdue,
a frame decoded every waiting column at once. Now each chunk packet goes
to a decoder thread as soon as it arrives, and the frame that reaches it
in order only inserts the column. A column still decoding holds back what
follows it, overdue or not, so a frame never waits for the decoder. A
dimension or registry change since a column was decoded makes the frame
decode it again with the new format.

Forgetting a column removed its pending sections with a pass over all of
them. A moved or shrunk storage forgets thousands of columns in one frame,
so it now removes them by key and drops their block entities in one pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:05:47 +01:00
Ludovic Marie 2b54c8a4ab Merge pull request #1812 from ludovic111/fix/trapped-chest-signal-barrel-open
🤖 Agent: main merged into the branch (merge commit). fmt, clippy -D warnings and the horizon-client tests pass; the 30 harnesses parity.py --changed picks for the game-binary files pass (30/30 on an integration of #1896 #1809 #1812); verify passed on this head. The earlier parity failure was the stale-head runner setup (.local/horizon-client link).
2026-10-26 08:57:39 +01:00
Ludovic Marie ff26716cd1 Merge pull request #1809 from ludovic111/fix/portal-effect-on-server-clients
🤖 Agent: main merged into the branch (merge commit). fmt, clippy -D warnings and the horizon-client tests pass; the 30 harnesses parity.py --changed picks for the game-binary files pass (30/30 on an integration of #1896 #1809 #1812); verify passed on this head. The earlier parity failure was the stale-head runner setup (.local/horizon-client link).
2026-10-26 08:55:30 +01:00
Ludovic MarieandClaude Opus 5.5 71126d3e13 Merge feat/mod-minimap-api (with main) into feat/official-minimap-mod
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:55:08 +01:00
Ludovic MarieandClaude Opus 5.5 641ff51089 Merge main into feat/mod-minimap-api
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:55:02 +01:00
Ludovic Marie 45bd296f14 Merge pull request #1896 from ludovic111/fix/creative-drop-on-server
🤖 Agent: main merged into the branch (merge commit). fmt, clippy -D warnings and the horizon-client tests pass; the 30 harnesses parity.py --changed picks for the game-binary files pass (30/30 on an integration of #1896 #1809 #1812); verify passed on this head. The earlier parity failure was the stale-head runner setup (.local/horizon-client link).
2026-10-26 08:53:22 +01:00
levzzzand[CC] <deepseek-v4.1-flash> 87e3df5331 Container clicks: a closed screen drops its press state
`AbstractContainerScreen` keeps `isQuickCrafting` and the drag it belongs
to on the screen. Horizon keeps both on `Game` (`inv_clicks`, `inv_drag`,
`last_inv_click`), and nothing cleared them when a screen closed: a press
whose release never reached the screen — the pointer left the window, or the
screen closed between the press and the release — left a quick-craft drag
running, and `Clicks::press` answers `None` for every later press, so clicks
went dead on every screen after it.

`Game::reset_inventory_clicks` now runs when a container closes and when the
pointer is grabbed again (the inventory's screens are behind us), which is the
lifetime vanilla gives that state.

Refs #1737

Co-Authored-By: [CC] <deepseek-v4.1-flash> <[email protected]>
2026-10-26 12:52:42 +05:00
rdbtCVSandCodex GPT-6.1 Sol cd7b6e025e Fix recipe book overlays surviving remote screen changes
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-10-26 07:49:37 +00:00
vlesmentieandClaude Opus 5.5 955b6c2134 The server thread's client draws the Ender Dragon
On a server's client (single player on its server thread, LAN guests,
dedicated servers) the dragon was tracked but never built: spawn_entity
only makes mobs from mob_types(), which has no dragon, and
dragon_geometry draws Game::dragon. The crystals had their own remote
constructor; the dragon had none.

The client now keeps the server's dragon in Game:🐉
handleAddEntity builds it (full health, hovering, as its constructor
does), SetEntityData applies DATA_HEALTH_ID and DATA_PHASE,
SetEntityMotion its velocity, and its moves interpolate like other
living entities. tick_remote_dragon is the client side of
EnderDragon.aiStep: wing flaps and their sound, the growl,
checkCrystals' nearest-crystal search for the healing beam, the flight
history and the parts; a dead dragon rises and bursts as in tickDeath.
Hurt animations flash it, removal and level changes drop it, and the
player's attacks pick its parts and send the server their ids.

The in-frame fight is unchanged; its nearest-crystal search moved into
nearest_crystal_to, shared with the client.

Fixes #1530.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 04:45:47 -03:00
Ludovic MarieandClaude Opus 5.5 cad817c82d Horizon shader packs: the sky stage runs in the game
A pack's `sky` function gets vanilla's colour along each view ray and draws
where the vanilla sky dome draws, under the sun, moon, stars and clouds. The
pipeline's shader is the pack's checked stage (`CheckedStage::source`, new)
followed by a copy of terrain.wgsl's sky with every name prefixed
`horizon_sky_`, so none can meet a pack's; terrain.wgsl's `fs_sky` now calls
`sky_along_ray`, the same code as before.

A running pack is one `NativePack`: the frame every stage reads (written once
a frame), its sky and post stages and its pass timer. In a frame F3 times, the
sky draws in a pass of its own so the overlay can show its time; otherwise it
stays in the world's pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:42:57 +01:00
Ludovic MarieandClaude Opus 5.5 a68c2f587d Horizon shader packs: one frame uniform per pack, apart from its post passes
`NativePack` holds what a running pack needs: the `frame` every stage
reads (`NativeFrame`, written once a frame before the world draws), its
post passes and the timer of its passes. `NativePost` no longer owns the
frame buffer or the timer, so the sky stage can read the same frame and
be timed by the same timer. No change in what draws.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:42:46 +01:00
Ludovic Marie d31832eaf4 Merge pull request #1996 from ludovic111/perf/reach-planning
🤖 Agent: merged main in. The old head's parity failure was server_dimension_players, which passes on main's parity-main. tests/test_parity_reach.py OK.
2026-10-26 08:40:52 +01:00
Ludovic MarieandClaude Opus 5.5 6c3473c6e0 Official mod: Minimap
The minimap extra as a mod (mods/official/minimap): the extra's five
options on its settings page, kept in its storage with the extra's values
(corner, size, shape, zoom, rotate), and the map drawn by the game
through render.set-minimap, so it looks and costs the same.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:40:03 +01:00
Ludovic MarieandClaude Opus 5.5 e52f0fdcc2 Merge main into feat/moved-zoom
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:39:51 +01:00
Ludovic Marie 3f5a323fd9 Merge pull request #2026 from ludovic111/feat/shader-pass-times
🤖 Agent: verified: pr_ready --quick green, 32/32 affected harnesses pass locally, CI verify green, paired A/B shows no frame cost without a pack. F3 now shows a shader pack's GPU time per pass, for both pack kinds.
2026-10-26 08:33:05 +01:00
rdbtCVSandCodex b6af258465 Fix warden sonic boom particle delivery to connected players
Send each sonic ray point through the existing particle packet path with vanilla recipient filtering. Cover nearby and distant clients, damage, and local rendering in the LAN harness. Fixes #1490.

Co-Authored-By: Codex (GPT-6.1 Sol) <[email protected]>
2026-10-26 07:29:40 +00:00
Eshayat Al-WasiuandOpenAI GPT-6.1 Sol f4b04218f1 Implement cushion placement and synchronize placed cushions
Add cushion entities, shape-based placement and support checks, colored rendering, server tracking, sitting, destruction and save/load support. Compare placement rules against vanilla and exercise host/guest interactions.

Co-Authored-By: OpenAI GPT-6.1 Sol <[email protected]>
2026-10-26 13:29:16 +06:00
Ludovic MarieandClaude Opus 5.5 24ab642e7b Mod API: render.set-minimap, a map the game keeps in a corner
What the official Minimap mod needs: a mod picks the corner, side, scale,
shape and turning, and the game draws the map as the minimap extra does,
from the same tiles (vanilla's map colours, the floor under roofs) within
its own frame budget. One map at a time, the first loaded mod's. A new
function and type, so mods built before it keep loading.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:20:30 +01:00
Ludovic Marie c58af30ca6 Merge pull request #2043 from ludovic111/ci/parity-main-runner-comment
🤖 Agent: comment only; the runner labels were moved via the API.
2026-10-26 08:20:07 +01:00
Alexander KrylovandHermes Agent 4a7173918b Roadmap: finished help-wanted items link the pull requests that did them
check still found five Help wanted items whose only links were closed
issues. Each was finished by a merged pull request, so the item now links
that pull request and waits in Now until a release carries it.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 10:12:08 +03:00
Ludovic MarieandClaude Opus 5.5 6ace65fc18 ci: parity-main's runner comment says where it runs now
ludovics-mac-mini-2 holds only the horizon-parity-main label; the release
runner no longer has it, since a release waited behind each new
parity-main run there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 08:11:46 +01:00
Ludovic Marie 301b006ef4 Merge pull request #1816 from ludovic111/feat/mod-test-runner
🤖 Agent: cargo horizon-mod test runs a mod's test scripts with no game. Main is merged in, and the runner fills the new snapshot fields (input, render, frame stats) with the trial run's screen size. Verified: clippy, the cargo-horizon-mod, coords-hud and horizon-mods tests (57), launcher, and cargo horizon-mod test on coords-hud (2 scripts).
2026-10-26 08:07:39 +01:00
Ludovic Marie 2d57f97869 Merge pull request #2033 from ludovic111/perf/mob-ai-tick
🤖 Agent: verified: parity for the 75 harnesses parity.py picks passes locally, pr_ready --quick passes on the final head, lan_e2e mobs/hazards pass in-frame and on the server thread. Same results; −1.3% of the dedicated server's tick-thread cycles at 10 bots.
2026-10-26 08:00:18 +01:00
Ludovic MarieandClaude Opus 5.5 8e71cb4754 Test runner: fill the snapshot's new fields, with the trial run's screen size
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:57:49 +01:00
Ludovic Marie c3b29a2652 Merge pull request #2023 from ludovic111/feat/official-zoom-mod
🤖 Agent: The official Zoom mod (mods/official/zoom): the zoom extra as a mod, pixel-identical and at the same frame cost. Verified with main merged: clippy, cargo horizon-mod check, and in game in both modes. Publishing follows in horizon-mods.
2026-10-26 07:57:29 +01:00
Alexander KrylovandHermes Agent 73bbbd3ee8 Tooltips: compare the hidden component id without a UTF-16 copy
TooltipDisplay.shows built a JavaString from the id on every call just to
test membership in the NBT list. A hovered tooltip asks this a dozen times
per frame, so the hover allocated a dozen short vectors per frame for a read.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 09:55:58 +03:00
Ludovic Marie 3163c7867d Merge pull request #1995 from ludovic111/feat/moved-hud-extras
🤖 Agent: The FPS counter and Keystrokes moved to the mod browser. A player who had one on gets the published official mod installed on the first start, with their settings and a chat line. Verified against the real registry, in both modes (34/34), plus clippy and the client tests.
2026-10-26 07:55:07 +01:00
Alexander KrylovandHermes Agent b59d9ada27 Shaders: the frame uniforms keep their buffer between frames
update rebuilt the values vector every frame for a fixed-length list: one
allocation and one free per frame for nothing. eval_custom already treats
the same vector as a buffer to truncate and extend.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 09:49:41 +03:00
Ludovic MarieandClaude Opus 5.5 f7d7c7c70a Merge main into feat/mod-test-runner
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:47:58 +01:00
vlesmentieandClaude Opus 5.5 fdba6b4153 Campfire timers mark their chunk for saving
CampfireBlockEntity.cookTick and cooldownTick call setChanged whenever
a timer moves (cookTick while any slot holds food, cooldownTick while
any progress is above zero). tick_campfire only marked the chunk when
an item finished, so after a save partway through cooking, an unload
saved nothing and the progress since went back to the saved value.
The chunk is now marked modified on those ticks, with no update to the
clients, who don't see the timers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:43:02 -03:00
Ludovic MarieandClaude Opus 5.5 108ced5793 launcher: a Shader packs tab that installs Horizon's own shader packs
The Mods page gets a fourth kind, Shader packs, which searches Horizon's
registry and installs a `.hshader` into `shaderpacks/` once
`index::check_file` has run the game's own `horizon_shader_api::check`.
Modrinth and CurseForge answer that tab with a pointer to the registry:
their shader packs are the shaders/ format and are not offered.

The sample index lists a shader pack (`glow`, made with
`horizon-shader new` and `pack`), so the registry build, check_file and
the launcher's install are tested on a real file. A file of the same
name the registry didn't put in place is no longer called a mod.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:41:24 +01:00
Ludovic Marie 7cb390fbff Merge pull request #2032 from ludovic111/fix/ctl-options-set-mods
🤖 Agent: horizon-ctl options-set no longer turns every mod off: Settings::with_option keeps the mod list with Horizon's other files. Verified: unit test, clippy, client tests, and in game in both modes (10/10).
2026-10-26 07:29:59 +01:00
Ludovic MarieandClaude Opus 5.5 c8d75a7892 Merge main into feat/official-zoom-mod
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:24:16 +01:00
Ludovic MarieandClaude Opus 5.5 828a2519e1 Merge main into feat/moved-hud-extras
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:23:36 +01:00
Ludovic MarieandClaude Opus 5.5 053291e339 Mob scans skip sections that can't hold what they look for
A mob's fluid state and its supporting block each read every cell around
its box, every tick. World::may_hold answers from the palettes of the
sections the box reaches: with no fluid listed there the fluid scan stops
before reading a cell, and with no block that reaches out of its cell
(large collision shapes, moving pistons) the supporting block search
reads only the cells meeting its area, as BlockCollisions' cursor does.
Results are the same.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:22:42 +01:00
Ludovic MarieandClaude Opus 5.5 130f1dc6a5 horizon-ctl options-set keeps the mod list
options-set rebuilt Settings from options.txt and carried over Horizon's
graphics, controller and extras files, but not the mod list: every mod
read as off afterwards, and the next save wrote an empty
horizon-mods.txt. Settings::with_option now does the rebuild and keeps
all four.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:13:21 +01:00
Ludovic MarieandClaude Opus 5.5 a1f1501305 launcher: Cargo.lock follows horizon-mods' shader check
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 07:11:30 +01:00
Alexander KrylovandHermes Agent dd45bf7740 F3: measure each line once per frame
The overlay measured every line to place it and measured it again for its
background box, about thirty extra glyph walks per frame on a full screen.
The width that placed the line is carried to the background pass.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 09:08:18 +03:00
Ludovic Marie cbdbf068bf Merge main into feat/native-shaders-registry 2026-10-26 06:59:07 +01:00
Alexander KrylovandHermes Agent 9dc72bf3ac Subtitles: measure each line once per frame
The max-width pass built a Text for every audible subtitle and dropped the
width it measured, then the draw loop built the same Text again to measure
it a second time. The row loop uses the number the first pass already had.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 08:58:50 +03:00
Alexander KrylovandHermes Agent 1e9644cc15 Signs: cut the first line on byte offsets, not through a char copy
first_line collected the whole line into a Vec<char> and then re-collected
a prefix of it, eight times per sign per frame, front and back. Every cut
point it needs is already a byte offset in the input.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 08:51:52 +03:00
Ludovic Marie ee6dfd2b6c Merge pull request #2016 from ludovic111/feat/mod-ui-key
🤖 Agent: Players rebind a mod's keys on its Options > Mods page (the game's own key rows, saved in horizon-mods.txt), with no WIT type change, so the published mods keep loading. Verified with main merged: clippy, the client, mods and SDK tests, and the in-game check in both modes (24/24).
2026-10-26 06:50:11 +01:00
Ludovic MarieandClaude Opus 5.5 70b832d658 Options > Horizon Settings > Shader Packs: pick a pack of either kind
The page lists the packs in shaderpacks/: Horizon's own, marked (Horizon) and
named by their manifest, then packs in the shaders/ format. One runs at a
time: clicking a pack picks it, clicking the picked one turns it off, and
Open Pack Folder opens the folder. The pick is saved in horizon-graphics.txt
under a new key (pickedShaderPack), so the shaderPack value older versions
saved stays ignored. A new pick drops the running pack and loads the new one
in the next frame; HORIZON_SHADER_PACK still wins, for development.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:49:41 +01:00
Ludovic MarieandClaude Sonnet 5.5 c1814283e0 Merge origin/main into fix/creative-drop-on-server
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 06:49:26 +01:00
Ludovic MarieandClaude Sonnet 5.5 4512105e85 Merge origin/main into fix/trapped-chest-signal-barrel-open
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 06:48:57 +01:00
Ludovic MarieandClaude Opus 5.5 c3763ff1b3 F3 shows the shader pack's GPU time per pass, for either kind of pack
While the F3 overlay is open, the running pack's passes are timed on the GPU,
a shaders/ pack's or a native pack's, and the overlay lists the pack's total
and its costliest passes (the median of the last 15 timed frames). The timer
never waits: a timed frame's stamps are resolved once the GPU has finished it
and read back once mapped, then the next frame is timed. A native pack's first
pass counts from a mark that ends with the world's draws, so it does not carry
the time it waited for them. HORIZON_SHADER_PACK_TIMING still logs the medians.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:48:57 +01:00
Ludovic MarieandClaude Sonnet 5.5 0958cb297a Merge origin/main into fix/portal-effect-on-server-clients
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 06:48:55 +01:00
Ludovic Marie 5bcc87983e Merge pull request #1861 from ludovic111/feat/native-shaders-post
🤖 Agent: native shader packs' post stage in the game with hot reload; pr_ready, 66 affected harnesses and a paired A/B (no cost without a pack) passed.
2026-10-26 06:45:33 +01:00
Ludovic MarieandClaude Opus 5.5 a6c8e9070a Zoom moved to the mod browser: remove the built-in zoom
The official Zoom mod (mods/official/zoom) does what the extra did. The
extra's zoom, its key and wheel hooks and its Extras rows go; the camera
keeps a mod's zoom (render.set-zoom). A player who had zoom on gets the
mod installed and turned on at the first start, with the starting zoom,
smooth zoom and slower turning carried into its storage and a changed
key into horizon-mods.txt, and one chat line. horizon-extras.txt keeps
the old keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:42:14 +01:00
Alexander KrylovandHermes Agent 77def1f2dd Mob models: a skipped part still draws its children
The early return skipped the child loop as well, while skipDraw only hides
the part's own cubes. A rolled armadillo skips its body and still renders
the parts below it.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 08:40:00 +03:00
levzzz c68e55438f Loot: the enchantment functions reach every table that rolls
`/loot give @s loot minecraft:chests/end_city_treasure` handed out bare gear: the
loot dispatcher in `items.rs` (the path `/loot`, bartering, raids, dispenser
tables, advancements and mob drops use) knew no `minecraft:enchant_with_levels`
or `minecraft:enchant_randomly`, so both fell through its arm untouched. Only the
chunk-generation path, which uses `horizon_world::loot`, enchanted anything —
which is why #1911 and #1437 looked fixed.

The dispatcher now runs both, as vanilla does: `EnchantWithLevelsFunction` picks
from `EnchantmentHelper.enchantItem`'s results (a book becomes one enchanted
book), `EnchantRandomlyFunction` picks one compatible enchantment at a level
between its min and max, and both resolve `options` as a tag, a list or one id,
else the whole registry. `Items` carries that registry now
(`Items::enchantments`), and `StationData` shares the same copy instead of
loading a second one.

Verified in game: six `/loot give … end_city_treasure` rolls gave 10 pieces of
gear, all 10 enchanted (unbreaking 3, mending 1 + protection 4, …), where all 10
were bare before.

Refs #1660
2026-10-26 10:34:21 +05:00
Ludovic Marie 344ef96894 Merge pull request #2025 from ludovic111/ci/parity-main-bisect-confirm
🤖 Agent: bisect fix; tests/test_parity_main.py passes (4 tests).
2026-10-26 06:20:14 +01:00
Ludovic Marie 2f46365df1 Merge remote-tracking branch 'origin/main' into feat/mod-ui-key 2026-10-26 06:15:25 +01:00
Ludovic Marie 886ecd9b20 Merge remote-tracking branch 'origin/main' into perf/reach-planning 2026-10-26 06:13:02 +01:00
Ludovic MarieandClaude Opus 5.5 2c5dac354e parity-main: name a merge only when HEAD fails again and the base passes
The bisect ended on the newest merge when the failed harnesses pass
everywhere now (a flake, or a runner that was missing the sounds), and
on the oldest when they fail everywhere (the runner), and commented on
that pull request either way. It now reruns them at HEAD and at the base
first and names nobody unless HEAD fails and the base passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:11:01 +01:00
Ludovic MarieandClaude Opus 5.5 bea3165267 Merge main into feat/mod-test-runner
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:03:11 +01:00
levzzzand[CC] <deepseek-v4.1-flash> 276f8d49c1 Chat: a LAN guest's line follows the host's Chat option
Review of #1932 (rdbtCVS): with `--in-frame`, opening a world to LAN and
setting Commands Only still showed a guest's ordinary chat on the host. The
hub's `HostEvent::Chat` went through `system_message`, which asks for
`receive_system_messages` — true at Commands Only — so the line passed.

`Game::player_message` shows a chat line as `ChatSource::Player`, which is
the permission `ChatListener` checks for player chat; `lan_log_event`
routes `HostEvent::Chat` there. `/say` and `/me` arrive as chat messages
too (say_command, emote_command), so they follow the same permission as they
do for the guests' own packets; command feedback such as `/list` is a system
message and keeps the system-message permission.

Reproduced on the pre-fix build: host at Commands Only, guest sends
`baseline-visible` → the host shows `<Guest9> baseline-visible`. With this
change the same line stays hidden at Commands Only and shows at Shown.

Co-Authored-By: [CC] <deepseek-v4.1-flash> <[email protected]>
2026-10-26 10:03:06 +05:00
Ludovic MarieandClaude Opus 5.5 90a9d9c612 Merge main into feat/moved-hud-extras
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 06:02:48 +01:00
Ludovic Marie 7ecb43ccc8 Merge pull request #1982 from ludovic111/feat/official-hud-mods
🤖 Agent: Horizon's official FPS Counter and Keystrokes as mods in mods/official/, same options and look as the extras (pixel-identical, frame cost within noise). Main merged in (wasmtime 48). Verified: pr_ready, clippy and tests of both mods, horizon-mods tests, both mods' settings pages in game.
2026-10-26 06:02:08 +01:00
Ludovic MarieandClaude Opus 5.5 d113131f7e Merge feat/official-zoom-mod into feat/moved-zoom
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:55:10 +01:00
Ludovic MarieandClaude Opus 5.5 82deb28954 Merge main into feat/mod-ui-key
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:54:27 +01:00
levzzzand[CC] <deepseek-v4.1-flash> bf2961834b Item cooldowns: tick them on the server client's path too
Review of #1933 (rdbtCVS): `Game::tick` returns through `tick_remote` whenever
`remote` is set — every multiplayer session and the default single player — so
the `tick_world` call that advanced the entries never ran there. A thrown
pearl's slot stayed at full shade until the server's duration-0 packet arrived
instead of fading over the second.

`tick_remote_level` advances them now (Player.tick's ItemCooldowns.tick); the
groups that end are dropped silently, as the client's plain ItemCooldowns
does.

Co-Authored-By: [CC] <deepseek-v4.1-flash> <[email protected]>
2026-10-26 09:52:00 +05:00
Ludovic MarieandClaude Opus 5.5 8fdb27f949 Zoom: the game lists its key on the settings page, as "Zoom key: Z"
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:47:15 +01:00
Ludovic Marie e372fce7ab Merge branch 'feat/mod-ui-key' into feat/official-zoom-mod 2026-10-26 05:35:16 +01:00
Ludovic MarieandClaude Opus 5.5 1aa6f21620 Horizon shader packs: the post stage runs in the game, with hot reload
A native pack named by HORIZON_SHADER_PACK (a folder with horizon-shaders.toml
or a .hshader in shaderpacks/) is checked, then its post passes run over the
world's own target, the one a shaders/ pack reads: no second target and no
extra pass, and without a pack the frame only tests one Option. The pack is
looked at twice a second; a saved file is checked and rebuilt in place, and a
version that fails is refused in the chat while the last good one keeps
drawing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:35:00 +01:00
Ludovic MarieandClaude Opus 5.5 3e3c0cebb5 Mod keys: rows the game adds to the settings page, not a WIT widget
A new case in ui's widget variant stops every ui mod built before it from
loading: the runtime links a component only when each imported
function's types match exactly ("expected variant of 5 cases, found
4"), so the published FPS Counter and Keystrokes would break. Instead,
the game lists a mod's keys first on its page in Options > Mods, as Key
Binds rows, and a mod with keys gets a page even without ui. No WIT
type changes. docs/api/stability.md said a new case the mod sends isn't
breaking; it is, and now says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:34:49 +01:00
Ludovic MarieandClaude Opus 5.5 3df60c21c2 tests: compare resolved paths in the prepared-report fallback test
macOS temp dirs live under /var, a symlink to /private/var, so the
resolved report path never equalled the unresolved fallback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:28:30 +01:00
Ludovic Marie 8cf51888c6 Merge pull request #1757 from ludovic111/feat/structure-saved-starts
🤖 Agent: structures stack brought up to date with main (merge commits); queued with verify passed, the merger waits for parity on this head.
2026-10-26 05:22:52 +01:00
rdbtCVSandOpenAI Codex 03a3c48a71 Fix Peaceful removal of existing hostile mobs
Apply the vanilla Mob.checkDespawn Peaceful gate before persistence and player distance checks. Extend the mob AI parity harness with difficulty, persistence, name-tag and NoAI regressions and allowed-type controls.

Fixes #1942

Co-Authored-By: OpenAI Codex (GPT-6.1 Sol) <[email protected]>
2026-10-26 04:18:54 +00:00
Ludovic Marie b485c43928 Merge pull request #2017 from ludovic111/ci/vanilla-data-new-shared-entries
🤖 Agent: CI script fix, tested on scratch folders. The release runner had no sounds, so parity-main's audio harnesses failed.
2026-10-26 05:18:40 +01:00
rdbtCVSandOpenCode f70b39290d Merge origin/main into t3/fix-critical-hit-particles
Include main's latest mod-input changes before validation.

Co-Authored-By: OpenCode (agentrouter/gpt-6.1-sol) <[email protected]>
2026-10-26 04:14:52 +00:00
rdbtCVSandOpenCode 70f1b71de1 Merge origin/main into t3/fix-critical-hit-particles
Keep both critical-hit and sculk container regressions.

Co-Authored-By: OpenCode (agentrouter/gpt-6.1-sol) <[email protected]>
2026-10-26 04:14:11 +00:00
Ludovic Marie d8aaf367eb Merge pull request #2013 from ludovic111/feat/mod-api-zoom
🤖 Agent: Mod API (experimental): render.set-zoom and input.claim-wheel, held mod keys let go when a screen opens, mod keys on mouse buttons. The consume choice is in stability.md. Verified: pr_ready (1300 tests), sandbox tests, in game 22/22 in-frame and on the server thread.
2026-10-26 05:12:07 +01:00
vlesmentieandClaude Opus 5.5 3d401e55f4 Merge origin/main into feat/campfire-cooking
Keeps both new block entities: BlockEntity::Campfire (this branch) and
BlockEntity::Skull (main), in containers.rs's enum, id() and the menu
lists in game.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:10:29 -03:00
Ludovic MarieandClaude Opus 5.5 5335354658 CI: runners clone what the shared source gained after their first copy
The release runner, now parity-main's, cloned the shared source before
the sounds were added to it; vanilla-data.sh only copied on the first
run, so ambient_sound, audio_attributes and music failed there with
"Sound assets missing". Each run now clones any entry the runner's copy
lacks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:10:19 +01:00
Ludovic MarieandClaude Opus 5.5 0cb1d46393 Merge main into feat/official-hud-mods
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:09:45 +01:00
Ludovic MarieandClaude Opus 5.5 53289d3565 Official mod: Zoom, the zoom extra as a mod
mods/official/zoom: hold the key (Z) to zoom in at the starting zoom,
the wheel changes it while held (x1.25 a step, 1.25 to 10), smooth
easing and slower turning as options. Same settings page as the extra,
with the key widget for the key. Built on render.set-zoom,
input.claim-wheel and ui's key widget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 05:08:36 +01:00
Ludovic Marie ab92ab346c Merge remote-tracking branch 'origin/main' into cg15/1909 2026-10-26 05:06:59 +01:00
Ludovic Marie 88d061ec9b Merge pull request #1955 from rdbtCVS/t3/migrate-parity-server-thread
🤖 Agent: Thanks rdbt! The command, dispenser and sculk fixtures now run on a server Game. Checked:
2026-10-26 05:06:41 +01:00
Ludovic Marie 4231905b1e Merge pull request #1967 from socksprox/fix/mannequin-npcs
🤖 Agent: Thanks socksprox! Mannequins render as the player model with their profile skin. I pushed d3af1e04e: a mannequin is a LivingEntity, not a Mob, so it runs no goals and never despawns. Checked in game: a summoned mannequin stays put for 400 ticks on the server thread and falls to the ground in-frame (it wandered 14 blocks before). Tested together with the other wave 2 contributor PRs: fmt, clippy -D warnings, and the horizon-client, horizon-world and horizon-protocol tests pass. Of the 127 harnesses the batch affects, 124 pass; the other three are a player-head mismatch fixed in #1934 and two worldgen timeouts on a loaded machine with no chunk differing. lan_e2e chat, fireball, cursor, looks, thrown, eat, shield, lava, contacts, projectiles and mobs pass with the host in-frame and on its server thread.
2026-10-26 05:00:59 +01:00
Ludovic Marie 1114b4d734 Merge pull request #1933 from levzzz5154/fix/item-cooldowns
🤖 Agent: Thanks levzzz5154! Matches ItemCooldowns and the slot sweep in Gui.renderSlot; thrown, eat and shield pass on both hosts. I merged main and dropped orphaned doc comments. Tested together with the other wave 2 contributor PRs: fmt, clippy -D warnings, and the horizon-client, horizon-world and horizon-protocol tests pass. Of the 127 harnesses the batch affects, 124 pass; the other three are a player-head mismatch fixed in #1934 and two worldgen timeouts on a loaded machine with no chunk differing. lan_e2e chat, fireball, cursor, looks, thrown, eat, shield, lava, contacts, projectiles and mobs pass with the host in-frame and on its server thread.
2026-10-26 04:58:42 +01:00
Ludovic Marie c31e8b2381 Merge pull request #1932 from levzzz5154/fix/chat-visibility
🤖 Agent: Thanks levzzz5154! Matches ChatComponent's ChatVisiblity filter for the Full, Commands only and Hidden options. I pushed 1e6f05ed5 earlier: every line keeps its source, so changing the option refilters the history both ways (new test). Verify had failed because main's mod output (#1875) calls Chat::add without a source. I merged main, and 2256941af marks a mod's lines as the client's own, which the Chat option keeps. Clippy and the chat tests pass after the merge. Before it, the wave 2 batch passed its 127 affected harnesses, and lan_e2e chat passed with the host in-frame and on its server thread.
2026-10-26 04:54:32 +01:00
Ludovic Marie 2e05b11a4d Merge remote-tracking branch 'origin/feat/official-hud-mods' into feat/official-zoom-mod 2026-10-26 04:53:36 +01:00
Ludovic Marie 23d4bc0a69 Merge pull request #1905 from rdbtCVS/fix/server-player-sculk-events
🤖 Agent: Thanks rdbt! Every server player now emits its own movement game events, with per-player sculk history; the new server_player_sculk harness passes. I merged main (the guest swap code). Tested together with the other wave 2 contributor PRs: fmt, clippy -D warnings, and the horizon-client, horizon-world and horizon-protocol tests pass. Of the 127 harnesses the batch affects, 124 pass; the other three are a player-head mismatch fixed in #1934 and two worldgen timeouts on a loaded machine with no chunk differing. lan_e2e chat, fireball, cursor, looks, thrown, eat, shield, lava, contacts, projectiles and mobs pass with the host in-frame and on its server thread.
2026-10-26 04:52:23 +01:00
Ludovic Marie f1ab726503 Merge pull request #1897 from vlesmentie/fix/pointing-hand-cursor
🤖 Agent: Thanks vlesmentie! Matches vanilla 26.3's AbstractWidget.handleCursor: buttons show the pointing hand. lan_e2e's cursor check passes. Tested together with the other wave 2 contributor PRs: fmt, clippy -D warnings, and the horizon-client, horizon-world and horizon-protocol tests pass. Of the 127 harnesses the batch affects, 124 pass; the other three are a player-head mismatch fixed in #1934 and two worldgen timeouts on a loaded machine with no chunk differing. lan_e2e chat, fireball, cursor, looks, thrown, eat, shield, lava, contacts, projectiles and mobs pass with the host in-frame and on its server thread.
2026-10-26 04:49:09 +01:00
Ludovic Marie 061ae61465 Merge pull request #1963 from ludovic111/feat/mod-api-extras
🤖 Agent: Mod API calls the official HUD mods use: render corner panels, text width and frame stats; input mappings and clicks per second; a ui button widget. Main merged in (after #1914's widget refactor). Verified: horizon-mods tests, clippy with and without mods, horizon-client tests (1121 lib), Keystrokes' settings page in game.
2026-10-26 04:45:01 +01:00
Ludovic Marie 5320391ff6 Merge pull request #1904 from rdbtCVS/fix/remote-fireball-motion
🤖 Agent: Thanks rdbt! Matches the client's LargeFireball tick between tracker updates; the new remote_fireball harness passes and lan_e2e's fireball check sees it on both sides. Tested together with the other wave 2 contributor PRs: fmt, clippy -D warnings, and the horizon-client, horizon-world and horizon-protocol tests pass. Of the 127 harnesses the batch affects, 124 pass; the other three are a player-head mismatch fixed in #1934 and two worldgen timeouts on a loaded machine with no chunk differing. lan_e2e chat, fireball, cursor, looks, thrown, eat, shield, lava, contacts, projectiles and mobs pass with the host in-frame and on its server thread.
2026-10-26 04:42:27 +01:00
Ludovic MarieandClaude Opus 5.5 7e4012c83e Mod API: a key widget, so players bind a mod's keys (ui, input)
A ui page's key widget shows one of the mod's keys as Key Binds does
("Zoom: Z"). A click waits for the next key or mouse button, which
becomes the key; Esc binds none. The game keeps the choice in
horizon-mods.txt (key.<mod>.<name>:key.keyboard.z), applies it when
the mods load and to keys registered later, and lets a held key go when
it is rebound. register-key's key is now the default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 04:41:12 +01:00
Ludovic Marie c94c4e140f Merge pull request #1915 from vlesmentie/fix/big-dripleaf-tilt
🤖 Agent: Thanks vlesmentie! Matches BigDripleafBlock.entityInside and canEntityTilt (the 0.6875 height check): a big dripleaf tilts under a player standing on it. Tested with the wave 2 batch: fmt, clippy and the horizon-client and horizon-world tests pass, and all 127 affected harnesses pass. The chunk_generation and decorated_region reruns took 8 minutes with no chunk differing. lan_e2e contacts and the rest of wave 2's checks pass with the host in-frame and on its server thread.
2026-10-26 04:39:41 +01:00
Ludovic Marie 3d8cf1f53a Merge pull request #1710 from ludovic111/fix/remote-tnt
🤖 Agent: main merged into the branch (merge commit); verify passed on this head, the merger waits for parity.
2026-10-26 04:36:46 +01:00
Ludovic Marie 5a79c8dede Merge pull request #1997 from ludovic111/fix/server-ops-feedback-save-wait
🤖 Agent: ready. server_ops_feedback waits for vanilla's and Horizon's 'Saved the game' before the save step's 2 s, so a loaded runner (the desktop's full trial) no longer cuts the transcript. Harness only. verify passed; parity ran server_ops_feedback on the Mac: PASS 120 s.
2026-10-26 04:34:33 +01:00
Ludovic Marie 2979303263 Merge pull request #1977 from ludovic111/perf/collision-scan-edges
🤖 Agent: requeued after a runner-setup parity failure (subtitle: missing sounds.json on the runner); 30/31 harnesses passed, the 56 selected passed locally. Queued by perf-next-2.
2026-10-26 04:33:56 +01:00
Ludovic Marie ce266e60be Merge pull request #1741 from ludovic111/feat/styled-menu-titles
🤖 Agent: server dialogs stack brought up to date with main (merge commits); verify passed on this head.
2026-10-26 04:31:44 +01:00
Ludovic Marie e410a3977b Merge pull request #1735 from ludovic111/feat/server-dialog-inputs
🤖 Agent: server dialogs stack brought up to date with main (merge commits); verify passed on this head.
2026-10-26 04:29:32 +01:00
Ludovic Marie d177a96be6 Merge pull request #1916 from ludovic111/feat/shader-packs-shadow-casters
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 04:27:16 +01:00
Ludovic Marie 452c444933 Merge pull request #1918 from vlesmentie/fix/water-cauldron-extinguish
🤖 Agent: Thanks vlesmentie! Matches LayeredCauldronBlock.entityInside / handleEntityOnFireInside: a burning player is put out and the cauldron loses a level. The cauldron harness passes, and lava and contacts pass on both hosts. Tested together with the other wave 2 contributor PRs: fmt, clippy -D warnings, and the horizon-client, horizon-world and horizon-protocol tests pass. Of the 127 harnesses the batch affects, 124 pass; the other three are a player-head mismatch fixed in #1934 and two worldgen timeouts on a loaded machine with no chunk differing. lan_e2e chat, fireball, cursor, looks, thrown, eat, shield, lava, contacts, projectiles and mobs pass with the host in-frame and on its server thread.
2026-10-26 04:24:50 +01:00
Ludovic Marie a4eefb0730 Merge remote-tracking branch 'origin/main' into cg15/1955
# Conflicts:
#	tools/lan_e2e.py
2026-10-26 04:24:12 +01:00
Ludovic Marie f72a63ca01 Merge pull request #1869 from ludovic111/fix/prepare-rewritten-version-file
🤖 Agent: verified: the fix for #1772 plus #1947 merged in. Its parity job prepares with this preparer and checks that the output is still OUTPUT_VERSION 1, so with #1946 players keep their prepared resources. Merging.
2026-10-26 04:24:12 +01:00
vlesmentieandClaude Opus 5.5 5febf0d957 Campfires cook food
Horizon had no CampfireBlockEntity, so right-clicking a campfire with raw
food did nothing. Now:

- BlockEntity::Campfire keeps four slots with their cookingProgress and
  cookingTime, saved as Items, CookingTimes and CookingTotalTimes; both
  campfires share the minecraft:campfire block entity type. It is not a
  Container (only Clearable), so hoppers don't reach in.
- CampfireBlock.useItemOn: a campfire_cooking input goes into the first
  free slot (placeFood) with its recipe's time; the use is consumed
  whether or not there was room, the item is used up outside creative,
  interact_with_campfire is awarded and a block_change goes out. A client
  of a server leaves it to the server.
- cookTick (lit): each item's progress rises; a finished item's result
  drops at the block (Containers.dropItemStack), the slot empties and a
  block_change goes out. cooldownTick (unlit): progress falls by 2.
- Breaking the campfire drops its items (preRemoveSideEffects).
- The update tag (Items) reaches a server's clients, and CampfireRenderer
  draws the items on the fire.

Fixes #1988.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:24:10 -03:00
Ludovic MarieandClaude Opus 5.5 2256941af7 Chat: mod output lines are the client's own
Main's mod output calls Chat::add without the new source; a mod's line is
written by this client, so the Chat option keeps it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 04:23:25 +01:00
Ludovic Marie 6e15257873 Merge remote-tracking branch 'origin/main' into cg15/1932
# Conflicts:
#	crates/horizon-client/src/game.rs
2026-10-26 04:23:24 +01:00
Ludovic Marie 1d83584da4 Merge pull request #1900 from ludovic111/feat/shader-packs-shadow-entities
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 04:22:09 +01:00
Ludovic Marie 8d6754226e Merge pull request #1934 from socksprox/feat/player-head-skins
🤖 Agent: Thanks socksprox! Player heads now show their owner's skin, fetched like vanilla's SkullBlockRenderer from the profile's textures property; TEXTURE_URIS limits it to textures.minecraft.net, so there's no new host.
2026-10-26 04:19:47 +01:00
Ludovic Marie 2ae2e57c66 Merge pull request #1449 from ludovic111/chore/wasmtime-48
🤖 Agent: main merged into the branch (merge commit); verify passed on this head.
2026-10-26 04:19:14 +01:00
Ludovic MarieandClaude Opus 5.5 de294e34bb rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 04:19:07 +01:00
Ludovic Marie fed2bdb304 Merge pull request #1892 from vlesmentie/fix/chicken-flap-remote
🤖 Agent: Thanks vlesmentie! Matches Chicken.aiStep's flap on the client of a server. I merged main and slimmed the test to reuse an existing mob kind. Tested together with the other wave 2 contributor PRs: fmt, clippy -D warnings, and the horizon-client, horizon-world and horizon-protocol tests pass. Of the 127 harnesses the batch affects, 124 pass; the other three are a player-head mismatch fixed in #1934 and two worldgen timeouts on a loaded machine with no chunk differing. lan_e2e chat, fireball, cursor, looks, thrown, eat, shield, lava, contacts, projectiles and mobs pass with the host in-frame and on its server thread.
2026-10-26 04:17:55 +01:00
Ludovic Marie 4aca4e151a Merge pull request #1734 from ludovic111/feat/server-dialog-screen
🤖 Agent: server dialogs stack brought up to date with main (merge commits); verify passed on this head.
2026-10-26 04:17:30 +01:00
Ludovic Marie 1faafb9f90 Merge pull request #1888 from ludovic111/feat/shader-packs-shadow-terrain
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 04:16:44 +01:00
Ludovic Marie 6bbf40e345 Merge pull request #1753 from ludovic111/feat/structure-blocks-harness
🤖 Agent: structures stack brought up to date with main (merge commits), verify and parity passed on this head.
2026-10-26 04:13:52 +01:00
Ludovic Marie 4d460bfb3a Merge pull request #1887 from ludovic111/feat/shader-packs-shadow-buffers
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 04:10:49 +01:00
Ludovic MarieandClaude Opus 5.5 c89434557b Player heads without a skin show slim steve, as vanilla
SkullBlockRenderer's SKIN_BY_TYPE is DefaultPlayerSkin.getDefaultTexture(),
DEFAULT_SKINS[6] = entity/player/slim/steve; the block_entity_render harness
found Horizon drawing nothing for heads without a profile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 04:09:25 +01:00
Ludovic Marie d208121c8e Merge pull request #1886 from ludovic111/feat/shader-packs-shadow-programs
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 04:08:13 +01:00
Ludovic MarieandClaude Sonnet 5.5 55c961b889 Merge origin/main into fix/remote-tnt
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 04:07:18 +01:00
Ludovic Marie 1880e12f2b Merge pull request #1885 from ludovic111/feat/shader-packs-shadow-camera
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 04:05:36 +01:00
Alexander KrylovandHermes Agent d41aa95dbd Mob models: one Poses per mob per frame, not one per equipment layer
Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 06:04:06 +03:00
Ludovic MarieandClaude Sonnet 5.5 7d4792fb31 Mods API reference test: follow wit-parser 0.254 (FixedLengthList, Param)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 04:03:03 +01:00
Alexander KrylovandHermes Agent dcc5899692 Name tags: collect the ridden mobs once, not per tag
Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 06:00:36 +03:00
Alexander KrylovandHermes Agent 51911080f0 Mob models: one skip lookup per part, not one per polygon
Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 05:58:53 +03:00
Alexander KrylovandHermes Agent 1dcb33f111 Merge main into perf/no-double-cracks-and-ticker-copy
The profiling marks that landed in main (mark_entity, mark_stage) collide with
the cached cracks scan; both are kept.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 05:55:32 +03:00
Ludovic Marie 163f099ecb Merge pull request #2006 from ludovic111/perf/behaviour-cache-hash-once
🤖 Agent: pr_ready and 91 harnesses pass (shared run, body); the duplicate 70 MB hash at world entry removed. Queued by perf-next-2.
2026-10-26 03:41:58 +01:00
Ludovic Marie 6d92727d9d Merge pull request #2004 from ludovic111/perf/sculk-ticking-chunks
🤖 Agent: pr_ready and 91 harnesses pass (shared run, body); tick_sculk_blocks halved at 10 bots, −75% at 25. Queued by perf-next-2.
2026-10-26 03:38:40 +01:00
Ludovic MarieandClaude Sonnet 5.5 0bfb011ee2 Merge feat/structure-saved-starts into feat/lithostitched-processors
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:38:00 +01:00
Ludovic MarieandClaude Sonnet 5.5 b4700c0a9d Merge feat/structure-blocks-harness into feat/structure-saved-starts
Both branches changed how the harness finds the mod jars: resolve every jar
through jar_path (jars, then pack-jars) and keep the profile packs check.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:36:24 +01:00
Ludovic Marie 2b4e1fd03b Merge pull request #1944 from ludovic111/feat/mod-input
🤖 Agent: Mod API capability input (experimental): claimed items' use and the mod's keys. Main merged in beside command and render (9 capabilities). Verified: horizon-mods tests (sandbox, API reference), clippy with and without mods, horizon-client tests (1121 lib), earlier pr_ready and in-game runs in both modes.
2026-10-26 03:35:25 +01:00
Ludovic MarieandClaude Opus 5.5 2631eca00b Drop the migration's validation ledger from the docs
It records an agent's runs and diagnoses, which the pull request and its
branch history already keep; docs/ is for how the project works.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:32:44 +01:00
Ludovic MarieandClaude Sonnet 5.5 355df65240 Merge feat/yung-port-as-written into feat/structure-blocks-harness
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:31:39 +01:00
Ludovic Marie c7c4cfe996 Merge pull request #1801 from ludovic111/feat/shader-packs-hand
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 03:30:48 +01:00
Ludovic Marie ef4018805e Merge pull request #2008 from ludovic111/ci/parity-main-vanilla-data
🤖 Agent: verify passed at 0c84eb307. Merged by hand: the PR parity job is queued behind the same runners, and this changes only how that job prepares its data. The next PR parity job on ludovics-mac-mini is the real test.
2026-10-26 03:27:46 +01:00
Ludovic Marie 905464e2b3 Merge pull request #2005 from ludovic111/perf/rings-out-of-reach
🤖 Agent: pr_ready and 91 harnesses pass (shared run, body, incl. decorated_region's stronghold site and world_spawn); first chunk 8.7 → 6.0 s on 4 threads. Queued by perf-next-2.
2026-10-26 03:27:25 +01:00
Ludovic Marie 6c2effae82 Merge pull request #1931 from levzzz5154/fix/draggable-scrollbars
🤖 Agent: Thanks levzzz5154! The Game Rules and Statistics scroll bars can be pressed, dragged and released like vanilla's; I merged main and pushed a41381236 (Statistics uses the GUI height; #1913's drag test is folded in). Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 03:24:52 +01:00
vlesmentieandClaude Opus 5.5 9572330ee4 A villager's new profession rolls its trades
Villager.setVillagerData sets offers to null when the profession changes,
and getOffers rolls the new profession's trades on the next look.
set_profession cleared the offers but left unset false, so ensure_offers
never rolled new ones: a villager that took a placed workstation after
losing its first wore the new profession but only shook its head.
It now marks the offers unset, as vanilla's null.

Fixes #1998.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:24:25 -03:00
Ludovic MarieandClaude Sonnet 5.5 d322c4b870 Merge feat/server-dialog-screen into feat/styled-menu-titles
Both branches changed the machine screens' title drawing: keep the styled server
title from this branch and the translated container title and inventory label
from feat/server-dialog-screen.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:22:13 +01:00
Ludovic Marie 4bfb7f6506 Merge pull request #1965 from rdbtCVS/t3/optimize-launcher-resource-prepare
🤖 Agent: Thanks rdbt, preparation needs only a Java runtime now and runs 5 JVMs instead of 18! Verified on the Mac mini:
2026-10-26 03:21:56 +01:00
Ludovic Marie ba105e0784 Merge branch 'feat/official-hud-mods' into feat/moved-hud-extras 2026-10-26 03:20:09 +01:00
Ludovic MarieandClaude Opus 5.5 980c619b81 Merge feat/mod-api-extras (with main) into feat/official-hud-mods
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:20:09 +01:00
Ludovic Marie 9f42b39aca Merge pull request #2002 from ludovic111/ci/parity-main-own-runner
🤖 Agent: verify passed at 2c612fd79. The PR parity job is still queued behind the same runners, and it can't test a runs-on change, so I merge by hand.
2026-10-26 03:19:47 +01:00
Ludovic Marie 1e317cff5e Merge branch 'feat/mod-api-extras' into feat/mod-api-zoom 2026-10-26 03:19:44 +01:00
Ludovic Marie 0f47d2a028 Merge pull request #1800 from ludovic111/feat/shader-packs-held-items
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 03:19:36 +01:00
Ludovic MarieandClaude Sonnet 5.5 0c73bb3c90 Merge feat/server-dialog-screen into feat/server-dialog-inputs
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:18:45 +01:00
Ludovic MarieandClaude Opus 5.5 0c84eb3079 ci: PR parity jobs prepare vanilla data with main's script
A PR head older than the fix in vanilla-data.sh left a real
.local/horizon-client without sounds.json on runner ludovics-mac-mini;
every later job there failed subtitle. Like the harness selection, the
job now runs main's script unless the branch changes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:18:39 +01:00
Ludovic Marie 666a1ba6f7 Merge pull request #1786 from ludovic111/feat/shader-packs-weather
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 03:16:38 +01:00
Ludovic MarieandClaude Sonnet 5.5 a1ffa1ac11 Merge feat/server-dialogs into feat/server-dialog-screen
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:14:19 +01:00
Ludovic MarieandClaude Opus 5.5 50c54098ef Merge feat/mod-input (with main) into feat/mod-api-extras
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:13:27 +01:00
rdbtCVSandCodex GPT-6.1 Sol 4cc134d08a Fix passenger walk animation in shared render state
Zero passenger walk position and speed like vanilla LivingEntityRenderer, covering local and remote riders. Extend entity model parity with moving passenger and on-foot render-state cases.

Fixes #1962

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-10-26 02:13:12 +00:00
Ludovic Marie 9bf96bcea5 Merge pull request #1785 from ludovic111/feat/shader-packs-clouds
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 03:12:49 +01:00
Ludovic Marie 4457d4e0ca Merge remote-tracking branch 'origin/main' into perf/behaviour-cache-hash-once 2026-10-26 03:12:43 +01:00
Ludovic Marie 96290f4b94 Merge remote-tracking branch 'origin/main' into perf/rings-out-of-reach 2026-10-26 03:12:31 +01:00
Ludovic Marie facc1d4d08 Merge remote-tracking branch 'origin/main' into perf/sculk-ticking-chunks 2026-10-26 03:12:20 +01:00
rdbtCVSandOpenCode GPT-6.1 Sol 15d99a6856 Start bat animation clocks on server clients
Fixes #2000.

Co-Authored-By: OpenCode GPT-6.1 Sol <[email protected]>
2026-10-26 02:11:48 +00:00
Ludovic Marie 8dfe518b60 Merge pull request #1911 from vlesmentie/fix/structure-chest-enchantments
🤖 Agent: Thanks vlesmentie! Structure chests keep the enchantments their loot table rolled. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 03:11:16 +01:00
Ludovic MarieandClaude Opus 5.5 2c612fd791 ci: parity-main on the release runner, not behind PR parity jobs
The queued parity-main run waited 2 h behind PR parity jobs on the two
horizon-game runners, each merge replacing the pending one, and releases
need it green. The release runner gets a horizon-parity-main label; a
release only starts after parity-main passed, so the two never compete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:10:55 +01:00
Ludovic MarieandClaude Opus 5.5 48db367d4a Mod API: zoom the camera, take the mouse wheel (render, input)
render.set-zoom divides the field of view by up to 10, eased through the
game's FOV easing or at once, with a turning scale (at least 0.05); only
while playing, and the spyglass's own view wins. The strongest of several
mods' zooms counts, and the built-in zoom keeps working beside it.

input.claim-wheel takes the wheel from the hotbar while playing: its steps
are the mod's wheel events. That is the one input a mod consumes; its keys
never do (docs/api/stability.md). A screen opening now lets the mod's held
keys up, and mod keys bound to mouse buttons (key.mouse.4) are heard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:09:29 +01:00
Ludovic MarieandClaude Opus 5.5 b7b7cd6c50 Merge main into feat/mod-input: input beside command and render
Capability::ALL is 9 with Input; the SDK re-exports command and input;
the API reference is regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 03:09:13 +01:00
Ludovic Marie 74b08e6310 Merge pull request #1928 from levzzz5154/fix/end-city-banner-patterns
🤖 Agent: Thanks levzzz5154! End city banners keep their template patterns; I pushed 401ac1322 so the structure code and the save loader share one banner decoder. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 03:08:48 +01:00
Ludovic MarieandClaude Sonnet 5.5 1dff593ac3 Merge feat/shader-packs-shadow-entities into feat/shader-packs-shadow-casters
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:05:49 +01:00
Ludovic Marie 68d1a8a388 Merge pull request #1769 from ludovic111/feat/shader-packs-entity-spans
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 03:04:53 +01:00
Ludovic MarieandClaude Sonnet 5.5 4292806437 Merge feat/shader-packs-shadow-terrain into feat/shader-packs-shadow-entities
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:04:24 +01:00
Ludovic MarieandClaude Sonnet 5.5 c841ab6d56 Merge feat/shader-packs-shadow-buffers into feat/shader-packs-shadow-terrain
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:02:40 +01:00
Ludovic MarieandClaude Sonnet 5.5 8b7315a6ff Merge feat/shader-packs-shadow-programs into feat/shader-packs-shadow-buffers
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:01:43 +01:00
Ludovic Marie 76be4d0e73 Merge pull request #1756 from ludovic111/feat/shader-packs-sildurs
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 03:01:05 +01:00
Ludovic MarieandClaude Sonnet 5.5 b2a7e77036 Merge feat/shader-packs-shadow-camera into feat/shader-packs-shadow-programs
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 03:00:08 +01:00
Ludovic MarieandClaude Sonnet 5.5 86a2f8e470 Merge feat/shader-packs-hand into feat/shader-packs-shadow-camera
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:58:53 +01:00
Ludovic Marie 9d07d5a3e2 Merge pull request #1755 from ludovic111/feat/shader-packs-mip-current
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 02:58:43 +01:00
Ludovic Marie 298a9778a7 Merge pull request #1754 from ludovic111/feat/shader-packs-biomes
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 02:58:14 +01:00
Ludovic MarieandClaude Sonnet 5.5 ffda62db09 Merge feat/shader-packs-held-items into feat/shader-packs-hand
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:53:39 +01:00
Ludovic Marie d4526191ce Merge pull request #1744 from ludovic111/feat/shader-packs-normals
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 02:52:49 +01:00
Ludovic MarieandClaude Sonnet 5.5 ae3bbe6bb4 Merge feat/shader-packs-weather into feat/shader-packs-held-items
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:52:31 +01:00
Ludovic Marie b3fabc1743 Merge pull request #1699 from ludovic111/feat/shader-packs-run-globals
🤖 Agent: shader packs clean room: main merged into the stack (merge commits), verify passed on this head, parity skipped by parity-scope.
2026-10-26 02:51:12 +01:00
Ludovic MarieandClaude Sonnet 5.5 34397fe09d Merge feat/shader-packs-clouds into feat/shader-packs-weather
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:50:35 +01:00
Ludovic Marie c56102125b Merge pull request #1799 from cristibctr/codex/fix-1649-resource-pack-cache
🤖 Agent: Thanks cristibctr! Windows pack cache recovery; it bumps the cache version, so every platform rebuilds that cache once. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:50:17 +01:00
Ludovic MarieandClaude Sonnet 5.5 94c1b5bfaa Merge feat/shader-packs-translucent-entities into feat/shader-packs-clouds
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:49:32 +01:00
Ludovic MarieandClaude Sonnet 5.5 eab457d0ae Merge feat/shader-packs-entities into feat/shader-packs-translucent-entities
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:48:31 +01:00
Ludovic Marie b3bc8e807e Merge pull request #1946 from ludovic111/feat/prepare-output-version
🤖 Agent: verified: the launcher keeps prepared resources while the preparer's OUTPUT_VERSION (or a legacy fingerprint for v0.2.49 to v0.2.64) is the same. Unit tests and clippy pass. End to end with the real v0.2.64 release: an update to a build with OUTPUT_VERSION 1 reused its resources, and a build with the number bumped to 2 did not. Merging.
2026-10-26 02:47:48 +01:00
rdbtCVSandOpenCode be42e67e9d Merge origin/main into t3/fix-critical-hit-particles
Keep both critical-hit and replant regressions.

Co-Authored-By: OpenCode (agentrouter/gpt-6.1-sol) <[email protected]>
2026-10-26 01:45:16 +00:00
Ludovic MarieandClaude Sonnet 5.5 02248f4314 Merge feat/shader-packs-alpha-test into feat/shader-packs-entities
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:45:08 +01:00
Ludovic Marie dd1581c062 Merge remote-tracking branch 'origin/main' into cg15/1965
# Conflicts:
#	crates/horizon-prepare/src/lib.rs
2026-10-26 02:44:23 +01:00
Ludovic Marie 5450f5e872 Merge pull request #1698 from ludovic111/feat/shader-packs-terrain-draw
🤖 Agent: shader packs clean room 14 brought up to date with main (merge commit); verify passed on this head; parity skipped by parity-scope.
2026-10-26 02:44:07 +01:00
Ludovic MarieandClaude Sonnet 5.5 b0fd6e660e Merge feat/shader-packs-entity-spans into feat/shader-packs-alpha-test
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:41:50 +01:00
Ludovic Marie 5ba4793d35 Merge pull request #1960 from rdbtCVS/t3/optimize-launcher-resource-prepare-1
🤖 Agent: Thanks rdbt! Verified on the Mac mini:
2026-10-26 02:41:36 +01:00
rdbtCVSandOpenCode 5e2871dbfd Show critical-hit particles on server clients
Queue successful mob and player crit animations until the hub can send them to the attacker and tracking clients. Cover falling, grounded and refused attacks in both host modes. Fixes #1898.

Co-Authored-By: OpenCode (agentrouter/gpt-6.1-sol) <[email protected]>
2026-10-26 01:39:30 +00:00
Ludovic Marie f565f67ee5 Merge pull request #1958 from rdbtCVS/t3/item-frame-name-display
🤖 Agent: Thanks rdbt! Matches ItemFrameRenderer: a targeted frame shows its item's custom name. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:39:17 +01:00
Ludovic MarieandClaude Sonnet 5.5 91b0db48e7 Merge feat/shader-packs-sildurs into feat/shader-packs-entity-spans
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:38:42 +01:00
Ludovic MarieandClaude Sonnet 5.5 01ef17a258 Merge feat/shader-packs-mip-current into feat/shader-packs-sildurs
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:37:36 +01:00
Ludovic Marie 559ea59fcb Merge pull request #1952 from ludovic111/ci/linux-runner
🤖 Agent: ready. Linux runner support (runner-env/vanilla-data Linux paths, linux-runner.sh, runner_pause.py with Ludovic's lock/idle-15-min rule, heat, game, GPU and pause-file checks), desktop parity host, nightly and parity-main pinned to the Mac. verify and parity passed at this head. The desktop runner stays without the horizon-game label until its trial is identical: that is a runner setting, not in this PR. Desktop full run: 342/343 in 39.3 min (the 1 is a harness timing flake, fixed by #1997).
2026-10-26 02:36:59 +01:00
Ludovic Marie 09b3057610 Merge pull request #1926 from Domanffe/fix/enchantment-names-language
🤖 Agent: Thanks Domanffe! Enchantment names and levels follow the selected language; the server thread shares the client's language, and with none loaded (dedicated server, probes) the English names stay. I pushed a doc tweak (b7629cf65). Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:36:25 +01:00
Ludovic MarieandClaude Sonnet 5.5 2203c1777a Merge feat/shader-packs-biomes into feat/shader-packs-mip-current
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:36:22 +01:00
Ludovic MarieandClaude Sonnet 5.5 04000cb4db Merge feat/shader-packs-normals into feat/shader-packs-biomes
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:35:21 +01:00
Ludovic MarieandClaude Sonnet 5.5 3f10f57178 Merge feat/shader-packs-block-ids into feat/shader-packs-normals
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:34:28 +01:00
Ludovic Marie 894576e1e9 Merge pull request #1914 from socksprox/fix/mod-ui-screen-capture
🤖 Agent: Thanks socksprox! Refactor of the mod screen widgets plus a mouse recapture when a mod's screen goes away. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:34:15 +01:00
Ludovic MarieandClaude Sonnet 5.5 2b05e2809b Merge feat/shader-packs-arena-storage into feat/shader-packs-block-ids
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:32:06 +01:00
Ludovic Marie a83cf01169 Merge pull request #1943 from socksprox/fix/particle-atlas-reload
🤖 Agent: Thanks socksprox! Particles keep their sprites across a resource reload (content root set again on reload). Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:31:57 +01:00
Ludovic MarieandClaude Sonnet 5.5 b023ab934a Merge feat/shader-packs-sun-moon into feat/shader-packs-arena-storage
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:30:35 +01:00
Ludovic Marie 834a84f198 Merge pull request #1945 from rdbtCVS/t3/fix-anvil-combining-sound
🤖 Agent: Thanks rdbt! Matches AnvilMenu, which sends the level event with a null player so every player hears it once; lan_e2e's anvil check heard it exactly once on the host and once on the guest. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:29:05 +01:00
Ludovic MarieandClaude Sonnet 5.5 181d188324 Merge feat/shader-packs-sky into feat/shader-packs-sun-moon
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:28:17 +01:00
Ludovic MarieandClaude Opus 5.5 d3af1e04e0 Mannequins run no mob goals and never despawn
A mannequin is an Avatar (a LivingEntity), not a Mob: its serverAiStep has
no goals and LivingEntity has no checkDespawn. With the passive brain a
summoned mannequin wandered off (14 blocks in 400 ticks on the server
thread) and could despawn far from players.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 02:27:37 +01:00
Ludovic Marie 93d58b7024 Merge pull request #1954 from rdbtCVS/rdbt/fix-1949-leash-death
🤖 Agent: Thanks rdbt! Matches Leashable.tickLeash / dropLeash: a leashed mob that dies drops its lead; the new mob_ai scenarios run against the vanilla oracle. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:26:53 +01:00
Ludovic Marie d4e1b3c773 Merge pull request #1922 from rdbtCVS/t3/fix-crop-planting-harvesting
🤖 Agent: Thanks rdbt! Matches ServerPlayerGameMode.handleBlockBreakAction: an instant survival START never leaves a block being destroyed, so no repeated hit sounds and a replanted crop isn't broken again. It now includes #1966's sound regression. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:25:58 +01:00
Ludovic MarieandClaude Sonnet 5.5 f299e18fc6 Merge feat/shader-packs-draw-uniforms into feat/shader-packs-sky
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:25:46 +01:00
Ludovic Marie 1da949efbd Merge pull request #1919 from sl4ppleware/fix/heart-blink-on-set-health
🤖 Agent: Thanks sl4ppleware! Matches LocalPlayer.hurtTo: the hearts blink again when hurt, and the remote client ticks the blink through its controlled simulation tick. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:25:31 +01:00
Ludovic MarieandClaude Sonnet 5.5 0f1ab46921 Merge feat/shader-packs-mipmaps into feat/shader-packs-draw-uniforms
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:24:37 +01:00
Ludovic MarieandClaude Sonnet 5.5 f1fc01ffcf Merge feat/shader-packs-timing into feat/shader-packs-mipmaps
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:23:46 +01:00
Ludovic Marie 80e1eb20cc Merge pull request #1883 from ludovic111/fix/copper-golem-statue-poses
🤖 Agent: merged after verify (bugs-dezerx-1's fix for a player's bug list, self-checked with pr_ready); harnesses run on main by parity-main, which gates releases.
2026-10-26 02:22:56 +01:00
Ludovic MarieandClaude Sonnet 5.5 4ee54d84a8 Merge feat/shader-packs-water into feat/shader-packs-timing
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:22:48 +01:00
Ludovic Marie e93aba600b Merge pull request #1941 from rdbtCVS/t3/preserve-gui-scale-setting
🤖 Agent: Thanks rdbt! Matches vanilla: the saved GUI scale isn't clamped while a temporary small surface is up, the HUD caps the scale it draws with. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:20:26 +01:00
Ludovic MarieandClaude Opus 5.5 24b26da5d6 server_ops_feedback: wait for the save's reply before the next step
On the desktop runner (8 harnesses at a time) vanilla's save-all took 2 s,
the whole step: the transcript ended before "Saved the game" and the
harness failed with Horizon right. The save step now waits for that console
line, on both sides, before its usual 2 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 02:19:17 +01:00
Ludovic Marie 3bea1cd023 Merge pull request #1937 from rdbtCVS/fix/android-helper-scheduling
🤖 Agent: Thanks rdbt! Android-only cfg change to helper thread priorities; the desktop targets compile the same code as before. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:17:46 +01:00
Ludovic MarieandClaude Sonnet 5.5 e5f4d02549 Merge feat/shader-packs-real-buffers into feat/shader-packs-water
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:16:49 +01:00
Ludovic Marie a7d1d17ac9 Merge pull request #1991 from ludovic111/fix/pr-ready-affected-once
🤖 Agent: merged on verify: tooling only, it changes how fast harnesses are chosen, not which game code runs. Fixes pr_ready's 14+ min planning (affected_harnesses was called once per harness) and bounds the selection.
2026-10-26 02:15:09 +01:00
Ludovic Marie 3093f22a8a Merge pull request #1903 from rdbtCVS/fix/clear-offhand-slot-order
🤖 Agent: Thanks rdbt! Checked against vanilla's Inventory order (armour FEET to HEAD, then the off hand) when items are cleared. Tested together with the other wave 1 contributor PRs on current main: fmt, clippy -D warnings and the horizon-client tests (1,120 lib tests and the rest) pass; the 114 harnesses the batch affects pass; lan_e2e anvil, grindstone, replant, instant_digging, digging, frames and leads pass with the host in-frame and on its server thread.
2026-10-26 02:14:29 +01:00
Ludovic MarieandClaude Sonnet 5.5 f1a3409721 Merge feat/shader-packs-custom-uniforms into feat/shader-packs-real-buffers
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:14:28 +01:00
Ludovic MarieandClaude Opus 5.5 7b0192118e parity: choose harnesses faster (shared parse cache, early stop, time budget)
- The reach parse cache lives in the shared parity folder, keyed by content,
  so a new worktree starts warm (written atomically, other worktrees'
  entries kept within bounds).
- A harness's reach search stops as soon as it reaches a changed file that
  differs in more than its `mod` declarations; partial searches are not
  memoized. Declaration diffs are memoized (one git show per file).
- A harness whose changed dependency is outside crates/ is picked without a
  search (narrowing always keeps those).
- After PARITY_REACH_BUDGET seconds (default 180) the remaining harnesses
  count every source their probes link.
- crate_of is cached; no pathlib in the hot paths.

Same 79 harnesses on the 19-file diff from contrib-gate-16; CPU 19.9 s cold /
16.6 s warm before, 13.1 s cold / 9.9 s warm after (Mac mini under load).

parity.yml: skip the prepare_output check for heads made before #1947 (no
OUTPUT_VERSION, no tool): the job runs main's workflow on the head's files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 02:13:09 +01:00
Ludovic MarieandClaude Sonnet 5.5 ff3d57ea9c Merge feat/shader-packs-run-globals into feat/shader-packs-custom-uniforms
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:12:44 +01:00
Ludovic Marie f10a7cd880 Merge pull request #1994 from ludovic111/fix/vanilla-data-failed-prepare
🤖 Agent: ready. A failed horizon-prepare now leaves nothing in .local, and stale real .local/horizon-client* folders and preparations lacking horizon-client are cleaned at job start. Tested on a fake checkout (fail, stale, cached). verify passed; parity skipped (scope). No overlap with #1965.
2026-10-26 02:12:07 +01:00
Ludovic MarieandClaude Sonnet 5.5 b73ca494a8 Merge feat/shader-packs-terrain-draw into feat/shader-packs-run-globals
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 02:11:28 +01:00
Ludovic Marie b10d927e5e Merge pull request #1929 from ludovic111/feat/mod-render
🤖 Agent: Mod API capability render (experimental): HUD shapes and camera shake. Main merged in beside command (8 capabilities). Verified: horizon-mods tests, clippy with and without mods, earlier pr_ready, harnesses and in-game runs.
2026-10-26 02:10:10 +01:00
Ludovic MarieandClaude Opus 5.5 a9b5ca3936 Merge main: test beside main's new templates
The usage line, the docs and the website list `test` with main's
`new --template code|content`; the code template keeps tests/hello.toml.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 02:08:41 +01:00
Ludovic MarieandClaude Opus 5.5 07f1bcff68 Merge main: render beside main's command capability
Both add a Capability variant: the list holds 8 now. The SDK re-exports
both interfaces; the API reference is regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 02:02:00 +01:00
Ludovic MarieandClaude Sonnet 5.5 2a85b6a432 Merge origin/main into fix/remote-tnt
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 01:59:53 +01:00
Ludovic MarieandClaude Sonnet 5.5 48121cb109 Merge origin/main into chore/wasmtime-48
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 01:59:44 +01:00
Ludovic MarieandClaude Sonnet 5.5 b222dd9194 Merge origin/main into feat/server-dialogs
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 01:59:19 +01:00
Ludovic MarieandClaude Sonnet 5.5 35e047fb8e Merge origin/main into feat/yung-port-as-written
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 01:59:00 +01:00
Ludovic MarieandClaude Opus 5.5 d782e455a4 docs: the desktop's CI slice gets half the threads
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:55:57 +01:00
Ludovic Marie ee403545ce Merge pull request #1805 from kacpherek/pr/pregen
🤖 Agent: thank you kacpherek! /pregen is in, off by default: a server turns it on with horizon-pregen=true in server.properties (server.toml [properties]), single player and LAN with --pregen. With it off, the command tree and /help match vanilla. Tested on a dedicated server through horizon-server (on: 1,369 chunks generated and saved), single player on the server thread and in-frame, and 11 harnesses including command_exec.
2026-10-26 01:54:20 +01:00
Ludovic MarieandClaude Opus 5.5 160c1e8b7a CI: a failed preparation leaves nothing in .local
When horizon-prepare failed, vanilla-data.sh deleted the preparation folder but kept what it had
already written to .local/ (horizon-client, horizon-client-motion, ...). The next job then saw those
real folders as already there: its preparation listed only horizon-client-structures in .entries,
and the checkout kept using the stale resources outside the per-key cache.

Now a failed preparation removes the .local/ entries it created; a job first removes real folders
named like preparation outputs, and makes again a preparation whose .entries lacks horizon-client.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:54:02 +01:00
Ludovic Marie 98f5a811cc Merge pull request #1829 from ludovic111/fix/global-level-events
🤖 Agent: merged after verify (bugs-dezerx-1's fix for a player's bug list, self-checked with pr_ready); harnesses run on main by parity-main, which gates releases.
2026-10-26 01:50:29 +01:00
Ludovic MarieandClaude Sonnet 5.5 7bbd715c8c Merge origin/main into feat/shader-packs-terrain-draw
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-26 01:48:29 +01:00
Ludovic MarieandClaude Opus 5.5 22980fc8cc Extras: the FPS counter and keystrokes move to the mod browser
They are official mods now (#1982). The Extras page loses their rows and
the HUD its built-in drawing. A player who had one on gets the mod on the
first start: installed from Horizon's registry, checked as the launcher
checks it (size, SHA-256, signature, manifest), turned on, with the
corner and options carried into the mod's storage. One chat line says so
("FPS counter moved to the mod browser: installed for you"). If it can't
be installed (offline), a line says Horizon tries again at the next
start. horizon-extras.txt keeps the old keys and lists what was done in
movedToMods.

The client's horizon-mods dependency gains the `index` feature for the
check. The frame and click counters now run only for mods.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:41:18 +01:00
Ludovic MarieandClaude Opus 5.5 49bbdf8954 CI: the desktop's CI slice gets half the threads
On all 24, a cargo build held ludodesktop's CPU at 92 °C and the watcher kept pausing; at half,
harnesses run at a median of 80 °C.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:38:23 +01:00
Alexander KrylovandHermes Agent 258dd8561d Frames: one scan for breaking progress, and no name formatting per crack
`entity_geometry` ran `cracks()` twice per frame: once for the block-entity
pass that draws `render_breaking`, once for the overlay near the end of the
same function. Each run walked `mining` and the `destroying` map, and formatted
`block/destroy_stage_<n>` for every crack it found before looking that string up
in the atlas.

The list is computed once, at the top of the function, and the passes read it.
The ten stage names are a const table, so a crack costs one lookup and no
allocation. Nothing between the two passes touches `mining` or `destroying`,
which are only read there, so the list the second pass used to rebuild was
always identical to the first one.

No behaviour change: the same ten sprite names, and a stage above 9 still finds
no sprite and skips the crack.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-26 03:34:33 +03:00
Ludovic MarieandClaude Opus 5.5 bdbf67ef93 pr_ready: work out the affected harnesses once, not once per harness
affected_here called parity.affected_harnesses inside the filter, once for
each of the 343 harnesses. Since the selection reads the Rust items each
probe reaches (#1964) one call takes about a minute and a half, so
pr_ready sat for hours before its first step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:31:38 +01:00
Joansitoh 060a37dc85 Edit the remaining text fields at the caret.
Those fields only appended, so the cursor, selection and arrow keys did nothing. A sign paste strips formatting first, matching TextFieldHelper.getClipboardContents.
2026-10-26 01:29:07 +01:00
Ludovic MarieandClaude Opus 5.5 9db6a0ee48 CI: parity-main stays on the Mac; heat check on a median, boot as the first sign; nix roots fixed
nix-build names a dev output's GC root <name>-dev, so the runner's PKG_CONFIG_PATH pointed at links
that didn't exist and every client build failed on libudev; it now uses the store path nix-build
prints. The package temperature spikes for a second under load, so the heat check takes the median
of 5 readings. Restarting the watcher no longer throttles a running job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:23:27 +01:00
Ludovic MarieandClaude Opus 5.5 4c78d1b4f8 Merge origin/main into ci/linux-runner
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:23:12 +01:00
Ludovic MarieandClaude Opus 5.5 045bda8bfc release: give the exporters job an hour, as the Mac builds
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:21:20 +01:00
Ludovic MarieandClaude Opus 5.5 8b26c4cf34 Ring search thread: start once generation pauses
In the idle class the thread still slowed a fresh world's first 600 chunks
by about 3 s on a 4-thread laptop (it shares a physical core with a worker).
It now waits until no proto chunk was generated for 2 s, or a minute after
the world opened, and gives up if the world closes first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:14:39 +01:00
DanielGodriNetoandClaude 467413df5b fix(benchmark): wait for the post-teleport load before measuring
wait_loaded declared a scene loaded during the idle second right after a teleport, so village and mountain were measured with 0 chunks. Port the guard from tools/perf_bench.py: counts must change once (or stay full for 5 s) and resident chunks must reach 80% of the view circle.

Co-Authored-By: Claude <[email protected]>
2026-10-25 21:13:23 -03:00
Ludovic MarieandClaude Opus 5.5 bb3a289caa Read the click's changed slots for the machine's setChanged
The menu op already lists the slots the click changed; a container slot
among them is the Slot.setChanged that saves the block entity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:07:48 +01:00
Ludovic MarieandClaude Opus 5.5 7dfd4c6280 Share the player's water and lava tags with dropped items
The item's fluid world had its own copy of the FluidTags.WATER/LAVA
membership the player's immersion uses; motion now exports that one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:04:20 +01:00
Ludovic MarieandClaude Opus 5.5 31eecdc271 Compute a firework's blast distance in floats, as Entity.distanceTo does
Entity.distanceTo casts each offset to float and sums the squares in
floats; taking the double distance and rounding it gave a slightly
different damage at the edge of rounding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 01:03:25 +01:00
Ludovic MarieandClaude Opus 5.5 1dd47581de Ring search thread: the idle class, not behind the server
On a 4-thread laptop the background search at nice +10 took a share of the
cores from the chunk workers: 600 chunks arrived 3-4 s later. The thread now
runs only on cores nothing else wants (Linux SCHED_IDLE, macOS background
QoS, Windows idle priority): horizon_threads::idle_current.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:59:15 +01:00
socksproxandDevin 920a728989 World text parity: same-frame glyph uploads, display lines, name-tag colours
Atlas patches rasterized while building world text (display text, name
tags, sign glyphs, map items) drained into the HUD batch before
entity_geometry ran, uploading a frame late: for that frame the quads
sampled unwritten atlas cells, so text flickered or showed the wrong
glyphs whenever content changed or new text entered view.

Display text also lined up 10 px apart where vanilla's lineHeight is 9,
its background quad stopped a pixel short of vanilla's -1..width+1 fill,
and name tags used 0x7F where renderNameTag's colours are 0x20FFFFFF
(discrete) and 0x80FFFFFF (see-through). lightCoordsWithEmission floors
only the block channel at 2 and leaves the sky alone, and a discrete
name's background draws lit in the normal pass rather than unlit.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 00:56:00 +01:00
Ludovic MarieandClaude Opus 5.5 40f79354d6 release: build the preparer and compile the exporters fresh in the exporters job
The clean checkout removes target/, and vanilla-data.sh builds horizon-prepare only when it
prepares afresh, so compile-exporters had no binary on a cached preparation. The bundle is
also compiled in the job instead of reused from .local/exporters, which vanilla-data.sh links
to preparations that pull requests' parity jobs write, and the job fails if anything but our
classes and the manifest would leave the runner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:40:43 +01:00
rdbtCVSandCodex gpt-6.1-sol 2d088739e5 Fix dropped items following fluid currents
Sample item immersion and apply shared entity currents before and after movement, matching vanilla tick order. Cover item-sized fluid scans and flowing-water movement.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-10-25 23:40:17 +00:00
Ludovic MarieandClaude Opus 5.5 0a8af38ac4 Rings: search them on a thread behind the server, as the world opens
The previous commit decides chunks far from the rings without them. The
128 biome searches now start on a helper thread as an overworld with
structures opens, behind the server and render threads, so an eye of ender
or a chunk near a ring finds them done or shares what is left, instead of
running them all on the thread that asked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:39:18 +01:00
rdbtCVSandCodex 0b970c0c9a Cover instant-break sounds alongside replanting
Move the instant_digging regression from redundant PR #1966 into the existing stale-dig fix for #1880 and #1908.

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
2026-10-25 23:35:22 +00:00
Ludovic Marie da66056bd5 Merge remote-tracking branch 'origin/main' into perf/behaviour-cache-hash-once 2026-10-26 00:33:29 +01:00
Ludovic Marie d5699d5f90 Merge remote-tracking branch 'origin/main' into perf/sculk-ticking-chunks 2026-10-26 00:33:28 +01:00
Ludovic Marie 7092d5f4d7 Merge remote-tracking branch 'origin/main' into perf/rings-out-of-reach 2026-10-26 00:33:28 +01:00
Ludovic MarieandClaude Opus 5.5 e5403c0224 Merge origin/main into fix/item-cooldowns
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:33:20 +01:00
Ludovic Marie 1fd42f311f Merge remote-tracking branch 'origin/main' into perf/collision-scan-edges 2026-10-26 00:31:46 +01:00
Ludovic MarieandClaude Opus 5.5 0baf6cbd62 CI: the desktop runner works while its screen is locked or untouched for 15 min
Ludovic's rule (2026-10-26): runner_pause.py pauses at once on keyboard, mouse or gamepad input
(read from /dev/input, only whether bytes came), on an unlocked session touched in the last
15 min, at 90 °C, on a game or the GPU. Fixes the service start: the link loop's last test
failed the script under set -e.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:27:22 +01:00
Ludovic MarieandClaude Opus 5.5 ef5361e4c2 Creatures: drop the doc comments the removed cooldown fields left behind
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:26:17 +01:00
some-du6eandClaude Opus 5.5 97e78e0f11 horizon-prepare: find 26.3 in ATLauncher's and the CurseForge app's folders
ATLauncher saves Mojang's version JSON as is in configs/json/minecraft and
the client jar as the library net.minecraft:client:<version>, with the
libraries at their version JSON paths and the assets and Java runtimes in
Mojang's layouts. horizon-prepare now reads that layout, in the chosen
folder, the launcher above a chosen instances/<name> folder, or, with no
folder chosen, ATLauncher's default folder on each system after the
official launcher's, then the CurseForge app's Install folder. The lock's
pins gate it as before, and nothing is downloaded. The error names every
folder looked in and the launchers Horizon reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:22:32 -06:00
Kacpherek a6548089c4 Count the death roll in ticks so the dead camera eases instead of shaking
The camera's death roll and zoom (GameRenderer.bobHurt, Camera.modifyFovBasedOnDeathOrFluid) read deathTime + partialTick. Horizon derived deathTime from the wall clock since the death message, which the server thread path never set: there deathTime stayed 0, so every frame used 0 + partialTick and the view rolled from 0 to 0.2 degrees and snapped back twenty times a second (with a matching zoom pulse) instead of settling at vanilla's 3.6 degrees. In frame, the wall-clock ticks were not in step with the frame's partial tick either.

deathTime is now the tick counter LivingEntity.tickDeath keeps: the in-frame tick already counted it, and the server thread path now resets it when the death screen opens and counts it once per client tick. horizon-ctl state reports it as player.death_time.
2026-10-26 00:20:39 +01:00
Kacpherek bbc57aa838 Save furnace, brewing stand and crafter edits made through a server menu
A server player's clicks in a furnace, brewing stand or crafter menu wrote
the block entity's slots but never marked it changed, so the chunk was
not saved: an idle furnace (nothing burning, so its own tick changes
nothing) given or emptied through its menu rolled back on reopen or
chunk unload, losing or duplicating the items. Comparators kept the old
reading too.

When the click changed the container's slots, call container_changed
(BlockEntity.setChanged, reached through Slot.setChanged in vanilla's
AbstractContainerMenu.doClick and quickMoveStack), as chest-like menus
already do.
2026-10-26 00:20:26 +01:00
Kacpherek d143666e46 Mark a server's player dead while its arrival in a level is loading
A server's player on a trip into another level was skipped by
tick_guests before its zero-health body was marked dead, so a death
during the arrival (a /kill, damage) only counted once the destination
had loaded. The client already showed the death screen, and a Respawn
press in between was refused (guest_respawn wants a dead player) and
then lost, leaving the player on the death screen until a second press.

LivingEntity.hurt calls die at once, loaded or not: the death half of
the guest tick is now its own guest_die, which also runs for a player
on a trip.
2026-10-26 00:19:55 +01:00
socksproxandDevin ea1c0a4490 Render mannequin entities (server NPCs)
Servers on 26.3 spawn NPCs as minecraft:mannequin — the avatar entity
vanilla added for exactly this — instead of fake players (gommehd.net's
"Gommunity" lobby NPCs are invisible today). The client never registered
the type: MobTypes.load only builds species::ALL, so AddEntity produced a
tracked entity but nothing to draw.

- EntityDataSerializers.RESOLVABLE_PROFILE (41) decodes into
  Value::Profile. Before, the entry list ended at it and the mannequin's
  DATA_IMMOVABLE and DATA_DESCRIPTION after it never decoded.
- species::ALL gains mannequin (player#main model, Humanoid anim), and
  the player-only render paths — skin texture, sleep pose,
  AvatarRenderer's 0.9375 scale — take an avatar() check instead of the
  id string.
- SetEntityData's apply stores DATA_PROFILE on the mob, and
  update_remote_skins resolves its textures property through
  PlayerSkinRenderCache's rules (unsigned allowed, SkinManager's
  insecure path) the way a tab player's skin resolves.
- Mannequins get the shared-flags crouch and sleeping-position handling
  other players already had.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 00:19:44 +01:00
Kacpherek c7432c21e1 Check a server player's moves with the box of its pose
A player sprint-swimming up under a ceiling was sent back every tick on the server thread (and for LAN guests): the server never updated the player's pose, and handlePlayerPositionChange's collision check always used a standing 1.8-block box, so the 0.6-block swimming box the client moved with looked like it entered the ceiling. Player.tick ends with updatePlayerPose, and the check uses getBoundingBox, so run updatePlayerPose in the server player's tick and check moves with the pose's dimensions. Fixes #1899.
2026-10-26 00:17:03 +01:00
Kacpherek 2c0d9cc30e Tick End gateways' server copies on a server without a window
A used End gateway never worked again on the server thread or on a
dedicated server. TheEndGatewayBlockEntity's server ticker (portalTick)
ran only inside the client block-entity pass, which returns at once when
there is no renderer, so the 40 tick cooldown that
EndGatewayBlock.entityInside starts (triggerCooldown) never ran out.

A Game without a renderer now runs portalTick on the gateways it keeps a
server copy of, in block-ticking chunks as Level.tickBlockEntities does,
and sends triggerCooldown's block event every 2400 ticks of age.
2026-10-26 00:16:50 +01:00
Kacpherek f988ed417a Drop a pending server trip when its player is teleported within the level
A server's player sent into another level waits on a trip until the
chunks around its target load, and the server leaves its body alone and
skips its portal checks until then. A /tp within the level while the
arrival was still loading left that trip behind: its target lost its
loading tickets and never finished, so Nether, End and gateway portals
stopped taking the player until they went back to the abandoned spot.

ServerPlayer.teleport within a level places the player at once, so the
pending arrival is now abandoned. server-dimension-players gains the
case: sent far into the Nether, teleported back near the origin before
the far chunks load, then an End portal there.
2026-10-26 00:15:54 +01:00
rdbtCVSandCodex 3adff150cf Record preparation validation timings and measurement limits
Co-Authored-By: Codex <[email protected]>
2026-10-25 23:15:40 +00:00
Ludovic MarieandClaude Opus 5.5 1e6f05ed5a Chat option: filter the chat's lines both ways, as setVisibleMessageFilter
The chat keeps where each message came from and the Chat option's
abilities. A message the option hides is still dropped on arrival, but a
change of the option now also hides the lines already in the chat that
it no longer shows, and brings them back when it shows them again
(ChatComponent.setVisibleMessageFilter -> refreshTrimmedMessages), on
apply_settings. Every Chat::add names its source. The Restrictions
screen reads its two flags from ChatAbilities instead of its own copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:15:37 +01:00
Kacpherek 21019afc2b Vehicle storage menus edit the vehicle's own items
A chest minecart, hopper minecart or chest boat's menu edits a stand-in
container, which is meant to be copied back to the vehicle when the menu
closes. close_container took the open container before calling
close_cart_container, which then found nothing open and copied nothing:
items taken out came back on the next open, and items put in vanished.

Copy the stand-in back from the key close_container took. A server
player's clicks in such a menu copy it back at once, since the menu is
the vehicle's own inventory (ContainerEntity, AbstractMinecartContainer
and ChestBoat implement the container the menu reads and writes).
2026-10-26 00:14:27 +01:00
Kacpherek 785e83feeb Firework explosions hurt nearby players, not only the boosted one
FireworkRocketEntity.dealExplosionDamage hurts every LivingEntity within 5
blocks that the rocket can see (its feet or its middle, ClipContext
COLLIDER with no fluids), besides the entity it is attached to. Horizon only
hurt the attached player and the nearby mobs, so a rocket bursting next to a
player on foot did nothing to them, in both single player modes.

The player (unless it is the attached one) and every guest in the level now
take damageAmount * sqrt((5 - distanceTo) / 5) as fireworks damage, with the
armor wear of hurtServer. distanceTo is a float, as vanilla computes it, for
the mobs too.
2026-10-26 00:14:19 +01:00
rdbtCVSandCodex 03190ec724 Update the runtime download fixture for runtime-only discovery
Co-Authored-By: Codex <[email protected]>
2026-10-25 23:13:02 +00:00
Ludovic MarieandClaude Opus 5.5 5e9d45bc9a /pregen: off unless the server turns it on
Vanilla has no /pregen, so with it always registered /help and the command
tree differed from vanilla's (the command_exec harness failed on /help).
Horizon's own commands are now added to the game's tree only when the owner
asks: `horizon-pregen=true` in server.properties (`horizon-pregen = true`
under [properties] in server.toml) for a dedicated server, `--pregen` for
the game (single player, LAN). Off, the trees are vanilla's own, unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:11:39 +01:00
rdbtCVSandCodex f45e3f1237 Optimize launcher preparation with precompiled, batched exporters
Compile and validate original exporter bundles during release builds, cache development compilation, and reuse initialized JVMs and collision data during preparation. Keep legacy preparers compatible while current releases need only a Java runtime.

Co-Authored-By: Codex <[email protected]>
2026-10-25 23:11:23 +00:00
Kacpherek 9aa6d7723f Shulker bullets home on the guest the shulker targets
A mob that sees a guest (a LAN guest, or the player of the server thread)
holds Who::Player as its target, and what it does to that player runs with
the guest swapped in. A shulker's bullet, though, keeps the target it was
fired with until it lands, and the projectiles tick outside that swap:
there Who::Player is the host's own player, so on a server thread the
bullet found no target, stopped homing and fell onto the blocks.

The bullet now carries the guest's entity id, as ShulkerBullet.finalTarget
holds the targeted entity in vanilla (ShulkerAttackGoal.tick passes
Shulker.getTarget()), so it homes on the guest among the projectiles'
targets and its hit runs as that guest: 4 damage and Levitation.
2026-10-26 00:10:54 +01:00
Ludovic MarieandClaude Opus 5.5 fbd6bee3e3 Official mods: FPS Counter and Keystrokes, the first extras as mods
The FPS counter and keystrokes extras rewritten as mods on the public API
(render, input, ui, storage), in mods/official/, with the extras' options
on their settings pages and the extras' look: the same boxes, colours and
text positions, pixel for pixel. They are workspace members, so clippy and
pr_ready cover them; a maintainer publishes them in horizon-mods. The
built-in extras stay until the removal PR, which installs these for the
players who had them on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:08:55 +01:00
Kacpherek e50a4c6443 Play no place sound when a block item placement is refused
Clicking with a torch or flower into a space that is already taken (or where the block cannot stand) made the server-thread client play the block's place sound when the server resent the refused target. BlockItem.place returns FAIL before playSound when canPlace() is false, and the client only hears its own predicted placement, so clear the pending place sound when no placement was predicted.
2026-10-26 00:06:53 +01:00
Ludovic MarieandClaude Opus 5.5 6824224a33 Player heads: read the profile's skin once, and no skull on a piston head
- Skull keeps what its profile draws (the skin URL, its skins/<sha1>
  sprite and the default skin), computed when the block entity loads,
  instead of decoding base64 JSON and hashing it for every head every
  frame; skull_skin_at no longer scans the chunk's saved block entities.
- BlockEntity::for_block gave minecraft:piston_head a skull block entity
  (it ends in _head), which would have been saved as minecraft:skull.
- AGENTS.md is left as it is on main: the workflow note is not part of
  this fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:06:22 +01:00
Ludovic MarieandClaude Opus 5.5 c28bea8e96 Mod API: input's permission line says it sees keys and clicks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:06:16 +01:00
Ludovic MarieandClaude Opus 5.5 2a576b5886 Merge origin/main into fix/water-cauldron-extinguish
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 00:01:15 +01:00
Ludovic MarieandClaude Opus 5.5 eb443cdacc Merge origin/main into fix/server-player-sculk-events
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:59:04 +01:00
rdbtCVSandCodex 4be53ee28a Reduce resource preparation filesystem work
Share the asset index and verification state, stage checked imports while hashing, preserve indexed replacements, and clone independent resource copies where supported.

Co-Authored-By: Codex (GPT-6.1) <[email protected]>
2026-10-25 22:58:00 +00:00
Ludovic MarieandClaude Opus 5.5 9d5301627b Chickens: the flap test uses the shared test mob type
chicken_flap reads only the ground flag, so the test builds its mob from
mobs::sensor_scan_tests::kind() instead of a 50-line copy of a MobType.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:55:43 +01:00
Ludovic MarieandClaude Opus 5.5 d5b88ff130 Merge origin/main into fix/chicken-flap-remote
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:55:43 +01:00
Ludovic MarieandClaude Opus 5.5 b7629cf656 Enchantments: say which callers have no language
full_name reads the process's language, which the server thread shares
with its window; only a process with no language loaded (a dedicated
server, the probes) keeps the English names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:46:36 +01:00
Ludovic MarieandClaude Opus 5.5 a413812363 Scroll bars: the screen's GUI size, and a test of the drag
stats_scroll and stats_drag take the GUI height from gui_size() instead
of a copy of it. The Game Rules list's press, drag and release get the
test from #1913 (vlesmentie's take on the same fix).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:46:15 +01:00
Ludovic MarieandClaude Opus 5.5 dd73faccbc Merge origin/main into fix/draggable-scrollbars
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:43:27 +01:00
rdbtCVSandCodex 072f5ce2ee Fix custom item names above targeted item frames
Show the framed item's custom name through the existing world name-label renderer, matching vanilla's HUD and crosshair conditions. Extend the LAN frame check for normal and glow frames.

Co-Authored-By: Codex <[email protected]>
2026-10-25 22:43:07 +00:00
Ludovic MarieandClaude Opus 5.5 401ac1322f Banners: one loader for saved and generated banners
The generated banner reuses save.rs's BannerBlockEntity.loadAdditional
(now decode_banner) instead of a copy of it, and the generated block
entity clones its NBT only for the kinds that read it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:43:03 +01:00
rdbtCVSandOpenAI Codex 28206976d8 Move parity fixtures onto server execution
Co-Authored-By: OpenAI Codex (GPT-6.1) <[email protected]>
2026-10-25 22:36:21 +00:00
Ludovic MarieandClaude Opus 5.5 d81aa97e84 CI: the desktop runner works only while nobody is at the screen; desktop as a parity host
runner_pause.py pauses on any seat0 session (locked too), games, GPU use or a pause file, and is
the only thing that starts the runner; a job under way is throttled, then the runner stops. The
desktop host in parity_hosts.json refuses work while paused and its workers stop on a pause. The
nightly audit stays on the Mac mini. Docs and a unit test of the watcher.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:12:09 +01:00
Ludovic MarieandClaude Opus 5.5 8463325648 CI: Linux runners for the parity job (desktop, ThinkPad), paused while a game runs
runner-env.sh and vanilla-data.sh find Python 3.13, the pinned JDK and sccache on NixOS;
linux-runner.sh installs a runner as a systemd user service with its own screen; runner-pause.py
stops it from taking jobs while a game runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:12:09 +01:00
Ludovic MarieandClaude Opus 5.5 e3bd626688 Mod API: what the extras need as mods: corner panels, frame stats, mappings, buttons
The built-in extras become official mods; these are the calls the FPS
counter and keystrokes overlay need to look and behave the same:

- render.set-corner(corner, w, h, shapes): a box the game places with
  its own corner stacking (under the status effects, with the overlays
  and hud panels), clear-corner; text-width(text) in the HUD font
  (advances for U+0000..U+024F, 6 otherwise); frame-stats(): the game's
  FPS counter (fps, min, 1% low).
- input.mapping(name): a movement or click mapping's key label and
  whether it is held; clicks-per-second() for attack and use.
- ui: a button widget (200 x 20, select(id, 0)) for settings pages.
- The game keeps its FPS and click counters running while a mod runs,
  and refreshes the snapshot every frame for mods with a frame hook.
- The ui test guest gains /corner and /readings, with a sandbox test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:08:15 +01:00
rdbtCVSandCodex 0b49da2466 Fix lead drops when leashed mobs die
Follow Leashable.tickLeash for dying mobs and cover trader/player-held llama leads through the death animation.

Co-Authored-By: Codex <[email protected]>
2026-10-25 22:07:58 +00:00
Ludovic Marie 1a857b285d Merge branch 'feat/prepare-output-check' into fix/prepare-rewritten-version-file 2026-10-25 22:50:36 +01:00
Ludovic MarieandClaude Opus 5.5 acb68ed163 launcher: reuse prepared resources while the preparer's OUTPUT_VERSION is the same
A version's resources were reused only when the preparer's sources and the exporters were
byte for byte the same, so any change to crates/horizon-prepare (even one that prepares the
same files) made every player prepare again. The launcher now compares the number the preparer
declares for what it makes (`pub const OUTPUT_VERSION: u32` in crates/horizon-prepare/src/lib.rs,
bumped by hand when the output changes and checked by CI in the follow-up). Preparers from
before the number are known by a fingerprint of their sources and exporters: v0.2.49 to
v0.2.64 prepare version 1's output (measured on the CI runners' preparations). Older versions
are compared as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:44:56 +01:00
rdbtCVSandOpenAI Codex b6efebc879 Play anvil result sounds once for every player
Deliver anvil level events to the acting player and keep their local sound out of positional sound capture. Extend the anvil LAN check to count sounds for both players using either player’s anvil result.

Co-Authored-By: OpenAI Codex <[email protected]>
2026-10-25 21:39:14 +00:00
socksproxandDevin 2cdb6362ca Particles keep their sprites over a resource reload
The particle engine copied the GUI atlas's sprite rects once at start; a pack or server-pack
change rebuilt the atlas but not the engine, so every named and set sprite then drew a stale
region — break crumbs showed other blocks and campfire smoke showed random items (#1923).
The engine now re-reads the rects and the packs' sprite sets on reload, and a particle whose
sprite-set index outlived the rebuild keeps its sprite instead of indexing past the new list.
The reload also layers content mods over the root again, which startup does but reload forgot,
so the first reload silently dropped their assets and data.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 22:38:40 +01:00
vlesmentieandClaude Opus 5.5 15877931db Merge origin/main into fix/water-cauldron-extinguish
Keeps both sides of #1823 (wither rose) and this branch (lava and water
cauldrons) in motion.rs's inside-block match, the MotionEvent variants,
game.rs and lan_actions.rs, and all three tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 18:22:46 -03:00
levzzz 61c5f29ab7 Game Rules and Statistics: the scroll bars can be dragged
Both lists drew a scroll bar but only listened to the mouse wheel: a press
inside the bar column, the drag that follows and the release were dropped.
`ui::Scroll` already models AbstractSelectionList's press/drag/release (the
server list uses it); the two screens now keep their scrolling in it and the
window passes the press, the pointer's moves while it is held and the release
along.

Fixes #1782
2026-10-26 02:13:10 +05:00
Ludovic MarieandClaude Opus 5.5 fada660310 Mod API: capability input (experimental): claimed items' use, mod keys
- WIT `input`: claim-items(ids) makes the use button on those items the
  mod's: use-start, then use-stop with the ticks held (button up, item
  out of the hand, or a screen opening); the game does nothing else
  with the click. register-key(name, label, key) for up to 16 keys
  (key.keyboard.r), heard as key-down / key-up while playing; the
  game's own mapping on the key still runs. held(), poll() (256 kept).
- game/mod_input.rs: play_mouse asks mod_use first (local and remote
  windows), the tick ends a use whose item left the hand, the keyboard
  and horizon-ctl's key send the physical key to mod_key.
- No claim and no key, no cost: one check each.
- Experimental: the manifest needs experimental = ["input"].
- The ui test guest gains /input_claim, /input_poll and /input_held,
  with a sandbox test. Docs: mods.md, stability.md, the changelog, the
  regenerated reference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:10:44 +01:00
rdbtCVSandCodex gpt-6.1-sol 40b3c1e3d6 Preserve requested GUI scale across temporary small surfaces
Keep framebuffer limits in rendering and explicit option cycling rather than overwriting the saved choice during startup or settings application.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-10-25 21:08:55 +00:00
Ludovic MarieandClaude Opus 5.5 2fb0ac186a Behaviour cache: hash the source files once per process
The snapshot's key hashes the 70 MB of source tables it was resolved from.
The client's tables and the world generator's are loaded from the same
folder, so a world opening hashed them a second time: a third of a second
of the server thread's start on a 4-thread laptop, before any chunk. The
hash is now kept for the process, by each file's length and modification
time; a changed file is read again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:04:13 +01:00
Ludovic MarieandClaude Opus 5.5 4a2b262343 Structure starts: decide chunks no ring search can reach without the rings
The 128 stronghold biome searches (two seconds of CPU on a 4-thread laptop)
ran when the first chunk of a new world looked up its structure starts, so
nothing near spawn was generated until they were done. Each search ends
within 8 chunks of its ring chunk, which is known before searching, and
strongholds lie 1,400 blocks out or more: a chunk with no ring search in
reach (exclusion zones included) is now decided without them, which is what
they would say. They run when a chunk near a ring, /locate or an eye of
ender needs them (ring_positions now searches on demand instead of returning
nothing before a lookup did).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:00:07 +01:00
socksproxandDevin 820cc211d3 Player heads render their owner's skin
Placed player_head blocks kept no profile: skulls had no block entity, so the
renderer fell back to a hardcoded steve for every head. Give skulls a real
BlockEntity carrying vanilla's SkullBlockEntity fields (profile,
note_block_sound, custom_name) so the placement pipeline lands
minecraft:profile in it the way block_entity_item already maps, encode and
decode it through save so regions keep it, send its update tag to remote
clients, and resolve the profile through the skin downloader the head items
and the tab list share: the downloaded skin slot once it lands, the
profile's DefaultPlayerSkin uuid pick while it fetches, SKIN_BY_TYPE steve
without a profile.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 21:55:02 +01:00
socksproxandDevin 8dcd00fc62 AGENTS.md: the feature-request loop
When an agent is asked for a feature it runs the whole loop itself: check open
PRs for the area first, work in a new worktree on the latest upstream main,
build and run pr_ready, then push to the fork and open the pull request
against upstream, never the fork.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 21:54:47 +01:00
rdbtCVSandCodex 95c336a387 fix(threads): lower helper thread priority on Android
Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
2026-10-25 20:50:57 +00:00
levzzzand[CC] <deepseek-v4.1-flash> b71623dfd7 Item cooldowns: the sweep on a slot, and no use while one runs
Nothing tracked `ItemCooldowns`: `draw_item_decorations` passed a cooldown of
0.0 with a note that there was none to shade, and ender pearls were held back
by an ad-hoc `pearl_cooldown` counter.

`horizon_client::cooldowns` keeps the `use_cooldown` component's entries by
cooldown group the way `Player.getCooldowns` does (start and end ticks, the
percent `getCooldownPercent` returns), `ItemInfo` now carries the item's
`use_cooldown`, and the game uses it where vanilla does:
`ServerPlayerGameMode.useItem`/useItemOn refuse a stack on cooldown,
`ItemStack.applyAfterUseComponentSideEffects` starts the entry when a use
finishes (a thrown pearl, a wind charge, an eaten chorus fruit),
`GuiGraphicsExtractor.itemCooldown` shades the slot, and a server's guests
keep their own and are sent `ClientboundCooldownPacket` (started, and 0 when
it ends), which a client applies.

Fixes #1763

Co-Authored-By: [CC] <deepseek-v4.1-flash> <[email protected]>
2026-10-26 01:50:22 +05:00
Alexander KrylovandHermes Agent 3762ab7cda Enchantments: the name and the level follow the selected language
The registry resolved every `description` from the pinned `en_us` map at load
and `full_name` took `enchantment.level.<n>` from the same table, so a tooltip
showed an English enchantment line whatever language the player picked.

Keep the description's translation key and resolve it, and the level, through
the current language at display time, with the English text as the fallback for
the server thread, the probes and an old resource root.

Refs #1774.

Co-Authored-By: Hermes Agent (Nous Research) <[email protected]>
2026-10-25 23:47:14 +03:00
levzzzand[CC] <deepseek-v4.1-flash> b3807d6e50 Chat: the Chat option hides what it says it hides
The Chat Settings option was saved and shown but never applied: Hidden and
Commands Only still sent and displayed ordinary chat, and Hidden still
displayed the server's messages.

Minecraft.computeChatAbilities turns the option into ChatRestriction's
permissions, and they are now honoured where vanilla honours them:
ChatScreen refuses to submit input they take (hasAllowedInput) and says why
in a red usage line, ClientPacketListener.sendChat/sendCommand stop it before
the packet, ChatListener drops the player, server and client sources the
option hides, and ClientInformation carries the visibility to a server (at
login, and again when it changes, as Options.broadcastOptions does).

Fixes #1376

Co-Authored-By: [CC] <deepseek-v4.1-flash> <[email protected]>
2026-10-26 01:45:17 +05:00
rdbtCVSandCodex 09ff66bfee Fix stale server digging after instant survival breaks
Clear completed guest digging so replanted flowers and crops are not broken again after attack is released. Add a LAN replanting regression for both single-player paths.

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
2026-10-25 20:39:44 +00:00
Ludovic MarieandClaude Opus 5.5 61c44c22ef Mod API: capability render (experimental): HUD shapes and camera shake
Mods draw through the game's own renderer, never their own shaders:

- WIT `render`: set-hud(shapes) with fill, quad (any four corners),
  sprite (the game's GUI sprites), item (scaled) and text shapes, up
  to 1024, kept until replaced; gui-size(); shake(strength, seconds).
- Drawn over the HUD after the extras, under chat and screens, hidden
  with F1 (game/mod_render.rs). Colours are 0xAARRGGBB.
- shake turns the view, not the player: jolts fade out squared, add up
  to 1, at most 3 degrees of yaw and 2 of pitch, scaled by Distortion
  Effects (screenEffectScale; 0 turns it off).
- Experimental: the manifest needs experimental = ["render"].
- No mod drawing, no cost: an empty iterator and an is_empty check.
- cargo horizon-mod check reports shakes and HUD shapes. The ui test
  guest gains /render_hud, /render_clear and /render_shake, with a
  sandbox test; HudBatch gets fill_quad.
- Docs: mods.md, stability.md, the changelog, the regenerated reference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 21:35:12 +01:00
sl4ppleware 386912a76d Hearts blink again when the server sets health: LocalPlayer.hurtTo's damageCooldownTime 2026-10-25 23:32:27 +03:00
vlesmentieandClaude Opus 5.5 72de6e0b70 Water cauldrons put out a burning player and lose a level
On top of the lava cauldron's inside test: water and powder snow
cauldrons are no longer skipped. Their entity-inside shape is the
cauldron's or their content, Block.column(12, 4, 6 + 3 per level), and
LayeredCauldronBlock.entityInside applies: on a server, a burning
player first asks for handleEntityOnFireInside (runBefore EXTINGUISH),
which lowers the fill level (lowerFillLevel, a powder snow cauldron
turning to water of its level first, block_change with no source); then
EXTINGUISH (Entity.clearFire) puts the fire out.

Fixes #1330.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:25:48 -03:00
Ludovic MarieandClaude Opus 5.5 ac47b988c9 Shader packs, clean room 42: culled entities, the first-person player, shadowPlayer and shadowLightBlockEntities in the shadow pass
Entities Horizon's entity culling hides from the camera keep their vertices in a hidden span that
only the pack's shadow pass draws; the local player's model is built in first person, hidden from
the camera, while the pack casts entity shadows. shadowPlayer draws the player alone when
shadowEntities is off, shadowLightBlockEntities the light-emitting block entities when
shadowBlockEntities is off. Without a shader pack nothing changes.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, §2.4, §3.2; no other
loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 21:21:05 +01:00
Ludovic MarieandClaude Opus 5.5 a013e35a61 Collision scans: pass the rest of an outer row in a contained section at once
On the rows along a box's bottom, top and sides every cell is outer, so in a
section no block reaches out of, the rest of the row up to the chunk's edge
is passed in one step instead of cell by cell. The candidate budget still
ends the scan where it did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 21:17:59 +01:00
socksproxandDevin 74e3b0adf6 ui: recapture the mouse when a mod's screen vanishes, borrow its widgets
Review on #1864: when a mod stops while its screen or settings page is
up, draw_mod_screen dropped the player back to Playing without
capture(true), leaving the mouse free until the next click into the
world. The dead surface now leaves through close_mod_screen, which puts
back the screen it covered and holds the mouse on a return to Playing;
the same goes for a screen dropped while it was up.

mod_ui_view also cloned the title and every widget (up to 64, lists to
512 rows) on each frame, click and scroll. It now borrows the mod's
stored widgets — the screen's scrolls live in a disjoint field — and the
click finds the picked row first so the &mut ui_select runs after.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 21:10:52 +01:00
vlesmentieandClaude Opus 5.5 de0f76476f Big dripleaves tilt under a player standing on them
The leaf's tilt ticks, its reset and its redstone reset were already in
horizon-world (big_dripleaf_tick, big_dripleaf_reset_tilt), but nothing
started them: BigDripleafBlock.entityInside was missing. An entity on
the ground whose feet are above the leaf's y + 0.6875 (canEntityTilt)
tilts a flat, unpowered leaf UNSTABLE and schedules its tick in 10.

The block tick's inside scan now also passes the host's and the LAN
guests' feet and on-ground flag to Behaviours::entity_on_big_dripleaf.

Fixes #1683.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:10:26 -03:00
Ludovic MarieandClaude Opus 5.5 200b756b4a Sculk: pass over idle sensors and catalysts in the block entity tick
A sculk sensor, shrieker or catalyst with no vibration chosen, travelling or
waiting, and no charge cursors, ticks without changing anything (vanilla's
VibrationSystem.Ticker.tick and SculkSpreader.updateCursors return at once).
The tick now leaves those out before asking whether the chunks around them
tick (nine lookups each) and before looking them up a second time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 20:53:31 +01:00
levzzzand[CC] <deepseek-v4.1-flash> bb9c474c64 End city banners keep their template patterns
A structure template saves a banner's layers in its block entity NBT, and
StructureTemplate.placeInWorld hands that NBT to the level, where
BannerBlockEntity.loadAdditional reads `patterns`. Horizon built the client
block entity from the block alone (BlockEntity::for_block), so the End
cities' magenta banners came out bare.

Fixes #1438.

Co-Authored-By: [CC] <deepseek-v4.1-flash> <[email protected]>
2026-10-26 00:53:17 +05:00
Ludovic MarieandClaude Opus 5.5 4459f132fe Collision scans: skip the outer cells of sections no block reaches out of
BlockCollisions keeps a block on the cells around the box (Cursor3D types 1
and 2) only if it has a large collision shape or is a moving piston. Most
sections hold neither in their palette, so the scan now asks the provider
once per section and passes those cells without reading them: a mob's box
reads about a fifth of the cells it did. Same hits, same order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 20:44:09 +01:00
rdbtCVSandOpenAI Codex GPT-6.1 bd09f8b03e Migrate player integration coverage to server-thread hosting
Co-Authored-By: OpenAI Codex GPT-6.1 <[email protected]>
2026-10-25 19:36:11 +00:00
vlesmentieandClaude Opus 5.5 89d6e1c2a5 Structure chests keep the enchantments their loot rolled
The loot rolls carry enchantments and potions (horizon_world::loot runs
enchant_with_levels, enchant_randomly and set_potion), but chests filled
when a structure is placed, and mineshaft chest minecarts, turned each
LootStack into an item with loot_item, which keeps only the item, count,
damage and exploration map. End city gear came out bare. Both now use
loot_item_with_components, as vaults, trial spawners and decorated pots
already do.

Fixes #1437.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 16:34:39 -03:00
rdbtCVSandOpenAI Codex GPT-6.1 84a3f1ee18 Emit sculk movement events for each server player
Co-Authored-By: OpenAI Codex GPT-6.1 <[email protected]>
2026-10-25 19:30:34 +00:00
rdbtCVSandOpenAI Codex GPT-6.1 9c7909f770 Advance remote fireballs between server tracker updates
Co-Authored-By: OpenAI Codex GPT-6.1 <[email protected]>
2026-10-25 19:23:55 +00:00
rdbtCVSandOpenAI Codex GPT-6.1 481e75bc33 Clear off-hand items in vanilla inventory slot order
Co-Authored-By: OpenAI Codex GPT-6.1 <[email protected]>
2026-10-25 19:16:36 +00:00
Ludovic MarieandClaude Opus 5.5 dab13669f5 Creative screen drops reach the server: SetCreativeModeSlot(-1)
A stack picked from a creative tab exists only on the client. Thrown out of
the creative screen as a server's client, it went out as a ContainerClick to
slot -999, which the server had no carried stack for, so nothing dropped. The
client now sends handleCreativeModeItemDrop's SetCreativeModeSlot(-1, stack),
and the server drops it from the player's hand, with vanilla's drop spam
throttle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 19:53:09 +01:00
vlesmentieandClaude Opus 5.5 e4a151c2e9 Menu buttons show the pointing hand under the mouse
26.3's AbstractWidget.handleCursor asks for CursorTypes.POINTING_HAND
when a widget is hovered, or NOT_ALLOWED when it is inactive, and the
frame applies the last request to the window (GuiGraphicsExtractor
requestCursor and applyCursor, Window.selectCursor). Horizon never
changed the cursor, so it stayed an arrow over buttons.

widgets.rs keeps the frame's request, ui::button and the resource pack
screen's buttons make it from the mouse hover (not keyboard focus), and
the game sets winit's Pointer, NotAllowed or Default cursor after each
frame when it changes.

Fixes #1347.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:49:15 -03:00
Ludovic MarieandClaude Opus 5.5 96199c23e7 Shader packs, clean room 41: entities and block entities in the shadow pass
shadow_entities and shadow_block (each falling back to shadow) load with
the entities' vertex inputs unless shadowEntities or shadowBlockEntities is
false (spec 2.4, 3.2; both on by default, OQ-19). They draw the same entity
and block-entity runs the gbuffers programs would, with the same per-draw
uniforms, into the shadow map after the solid terrain and before the
shadowtex1 copy. A run is uploaded when a gbuffers program or a shadow
program draws it; Horizon still draws the runs no gbuffers program covers.

Without a pack nothing changes: only the pack's entity code is touched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 19:20:17 +01:00
vlesmentieandClaude Opus 5.5 2c8930c48d Chickens flap while they fall on a client of a server
Chicken.aiStep updates flap and flapSpeed on the client too, for the
chickens it only displays. tick_remote_entities never did, so with
single player on its server thread (and on servers) a falling chicken
kept its wings folded. The wing part of chicken_ai_step is now
chicken_flap, and the remote tick runs it from the server's on-ground
flag; the falling slowdown and egg laying stay the server's.

Fixes #1706.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:16:32 -03:00
Ludovic MarieandClaude Opus 5.5 3a35e147e5 Server mods run in the game: server thread, in-frame, LAN hosts, dedicated
The game that simulates a world now starts its server mods (API 0.3,
experimental): single player's server thread, single player in-frame
(beside client mods), a LAN host either way, and the dedicated server.
Windows that are clients of a server never run them.

game/server_mods.rs: tick_server_mods at the end of the tick diffs the
players (player_joined, player_left), delivers the tick's chat and block
events in order, then calls tick. Block events come from players' breaking
and placing (the acting player is the guest during as_guest); chat from the
local chat path and the hub's new HostEvent::PlayerChat; a guest's /command
reaches its mod before vanilla's dispatcher. tell and command replies go to
their player (the window's chat or a SystemChat); broadcast goes to every
player and the log.

--dev-mod now works on the server thread, and servers check a dev mod's
file once a second from their tick. Every hook returns at once when no
server mod runs; without the mods feature they are empty stubs.

Docs: docs/mods.md (where server mods run, when hooks run, not yet),
docs/api/mods.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 18:48:13 +01:00
Ludovic MarieandClaude Opus 5.5 aa2f60b7bd Copper golem statues turn to their next pose when right-clicked
CopperGolemStatueBlock.useItemOn: anything but an axe, an empty hand too,
cycles copper_golem_pose with its sound and block_change game event; honeycomb
on a weathering statue passes on to waxing. Axe scraping, unwaxing and
stripping and honeycomb waxing now count the item as used, and waxing sends
its block_change game event, as vanilla's useOn does. The use_item_on harness
gains statue cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 18:43:03 +01:00
Ludovic MarieandClaude Opus 5.5 c965aad8d3 Shader packs, clean room 40: terrain in the shadow map, culled from the light
The shadow program now draws the world's terrain from the light's view.
The shadow pass culls its own section list against the shadow camera's
frustum (render distance, capped by shadowDistanceRenderMul), nearest
the light first, and draws only the faces toward the light. Its draws go
by arena page within 64-block bands from the light, as the camera's solid
draws do, so the flat path draws them in about ten calls per list instead
of one per page change (over a thousand with BSL). Its draws
follow the camera's translucent draws in the same instance and indirect
buffers, so the flat path gives them calls of their own. Sections never
sorted for the camera are sorted once so their translucent indices are
valid.

The frame's first shadow pass clears the shadow map and shadowcolor
buffers as it begins, instead of a separate pass that loads and stores
them all; the translucent shadow pass is timed under its own label.

Without a pack nothing changes: the shadow lists are empty and the
terrain stays one draw call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 18:36:20 +01:00
Ludovic MarieandClaude Opus 5.5 a276f81aba Shader packs, clean room 39: the run doc comment back on run
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:55:23 +01:00
Ludovic MarieandClaude Opus 5.5 1a39af6b62 /pregen: plan any radius at once, and skip a strip's rows outside the circle
Pregen::new counted the area chunk by chunk and split the strips with
an i32 product: /pregen start 30000000 overflowed, then hung the server
thread for hours. Rows are now counted from the circle's half-width,
the strip edges in i64, and each strip starts and ends at the rows the
circle reaches, so a band never walks empty corner rows. Unit tests
check that every chunk of squares and circles is swept once and that
the largest radius plans at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:36:22 +01:00
Ludovic MarieandClaude Opus 5.5 71f0ffde4b Prepare: a launcher's rewritten version file falls back to Mojang's (#1772)
Launchers like HMCL rewrite versions/<v>/<v>.json in the official layout
(same jars and libraries, their own fields), and horizon-prepare refused it
as a version Mojang may have republished. Mojang's copy saved as the imported
manifest.json is now used instead, and without one the error says the
launcher may have rewritten it and how to get Mojang's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:31:44 +01:00
Ludovic MarieandClaude Opus 5.5 df8b23637e horizon-mods: rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 17:09:21 +01:00
Ludovic MarieandClaude Opus 5.5 390da26cf4 horizon-mod-registry: the form's test sends a shader pack through the game's check
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 16:38:54 +01:00
Ludovic MarieandClaude Opus 5.5 1285247230 Registry: shader packs are checked by the game's own shader check, and open
The `shader` kind's check (index::inspect) reads the .hshader and runs
horizon_shader_api::check, the same check the game runs before it loads a
pack, so the registry's CI (`cargo horizon-mod check` / `registry build`)
refuses a pack the game would refuse, with each problem at its file and line.
Its facts are the manifest's id, version and shader API line. The kind's
files are .hshader, `cargo horizon-mod check` recognises them, and
registry::open takes shader submissions. Installing one from the launcher
stays refused (check_file) until the launcher installs shader packs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 16:31:05 +01:00
Ludovic MarieandClaude Opus 5.5 6320718491 Shader packs, clean room 39: shadow buffers, their samplers and shadowcomp
When the shadow pass runs, the pack gets real shadow buffers (spec 6.3):
shadowtex0 (cleared to 1.0 every frame), shadowtex1 (a copy, made only when
a program reads it) and shadowcolor0/1 (each with two sides, made only when
used, cleared to their ShadowClear colour, white by default), square at
shadowMapResolution within the device's limit.

Samplers: shadowtex0/watershadow, shadowtex1, `shadow` (shadowtex1 beside
watershadow) and the HW forms read the shadow map, through a linear depth
comparison when declared sampler2DShadow; shadowcolor/shadowcolor0/1 read
the colour buffers. In the shadow programs, buffer n is shadowcolor n and
colortex reads a stand-in. Without the shadow pass nothing changes: the
names read the stand-ins as before.

shadowcomp..shadowcomp99 run after the shadow pass and before prepare, each
drawing into the alt side of the shadowcolor buffers it writes and flipping
them after, as composite programs do with colortex (6.1.6). The shadow pass
itself draws nothing yet, so the map stays clear.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
sections 2.1, 5.2 (samplers), 6.1.6 and 6.3; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 16:25:54 +01:00
Ludovic MarieandClaude Opus 5.5 86d8d9e3a1 Shader packs, clean room 38: load the shadow programs
The shadow pass runs when some program reads a shadow buffer (shadow,
watershadow, shadowtex0/1, their HW forms, shadowcolor, shadowcolor0/1) or
shadow.enabled=true; shadow.enabled=false keeps it off (spec 2.5). Then
`shadow` (solid and cutout terrain), `shadow_water` falling back to
`shadow` (translucent terrain) and shadowcomp..shadowcomp99 load, in the
new Shadow and ShadowComp groups (2.1, 2.4). shadow_solid and shadow_cutout
are not used: the game's solid and cutout terrain is one draw.

Their output n writes shadowcolor n (6.3): draw buffer lists stop at the
first index past 1. translate_shadow gives a shadow program the shadow
camera's matrices as its model-view and projection (5.2). The game does not
draw any of them yet.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
sections 2.1, 2.4, 2.5, 5.2 and 6.3; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 16:25:34 +01:00
Ludovic MarieandClaude Opus 5.5 5dcbe222c9 Shader packs, clean room 37: shadow settings and the shadow camera
The stage files' shadow constants (shadowMapResolution, shadowDistance,
shadowDistanceRenderMul, shadowIntervalSize, sunPathRotation, shadowMapFov,
shadowNearPlane, shadowFarPlane, shadowHardwareFiltering[0|1] and the
shadowcolor0/1 Format, Clear and ClearColor) are read into Config::shadow
(spec 6.3, 7.1).

The shadow matrices are no longer a placeholder (OQ-6): the camera looks
from the shadow light, sits 128 blocks toward it from a point that moves in
steps of shadowIntervalSize along the shadow view's own axes, and projects
orthographically over shadowDistance each side (or in perspective with
shadowMapFov), between shadowNearPlane and shadowFarPlane.

sunPathRotation turns the sun and moon's path about the world's X axis:
sunPosition, moonPosition, shadowLightPosition and the shadow camera follow
it, and so do the sun, moon and stars a pack's gbuffers_skytextured and
gbuffers_skybasic draw.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
sections 6.3 and 7.1; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 16:25:34 +01:00
Ludovic MarieandClaude Opus 5.5 bcd42f50e9 cargo horizon-mod test: server mods' scripts
A test script drives a server mod as a server would: join = "Alex" brings a
player in (ids stable per name, so a rejoin is the same player), as = "Steve"
picks who acts (the first player on otherwise), and player, chat, command,
break and place are that player's doing; leave = "Alex" lets them go. Server
expectations: told (every players.tell, "Name: text") and broadcast; feedback
and error read the reply to the player who typed the command. Ticks call both
kinds of tick hooks, so one script format serves client and server mods.

The welcome example gets two scripts (greeting, a newcomer announced once
even after a reload, /online across dimensions, /mined per player), run by
the sandbox tests with coords-hud's; docs/mods.md lists the server keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:55:55 +01:00
Ludovic MarieandClaude Opus 5.5 c9f554d1c4 Mod API 0.3 (experimental): server mods' contract, runtime and SDK
A server mod runs where the world is simulated. Its manifest says side =
"server" and api = "0.3" (only a server mod may), and its component targets
the new WIT world horizon-server-mod:

- imports log and storage as client mods do, and the new capability players:
  online() (id, name, position, dimension, game mode, health), tell(id, text),
  broadcast(text), 8 lines per call shared with chat;
- exports server-events: init, tick, player-joined, player-left, chat, command
  (with the player who typed it; its feedback goes back to that player),
  block-broken and block-placed (with the block state as text).

horizon-mods: a second bindgen world sharing log and storage with the first;
a running mod holds either kind of hooks; Mods::load_for(Runs) starts only the
mods a game runs (the window client mods, the world's server server mods,
in-frame single player both) and marks the others Elsewhere. Client and server
commands are owned separately. The game passes Runs::Client for now, so
nothing changes in game until its server code calls these hooks.

The SDK gains horizon_mod_sdk::server (ServerMod, Registration,
export_server_mod!), the example server mod welcome (greets, announces
newcomers kept in storage, /online, /mined), and cargo horizon-mod check's
trial run plays a server mod with a player joining, chatting, typing its
commands and leaving. The manifest refuses client capabilities on a server
mod and players on a client mod. The generated reference, the guide, the
portal and the stability table describe it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:51:15 +01:00
Ludovic MarieandClaude Opus 5.5 749a2dc9bd Global level events reach a server's players; explosions play their packet's sound
ServerLevel.globalLevelEvent (an end portal opening, 1038; the dragon's
death roar, 1028) went to the Game's own audio without a position, which
is never forwarded: on the server thread, LAN and dedicated servers
nobody heard them. They now go to every guest as a global LevelEvent,
which a client plays two blocks from its camera towards the event
(LevelEventHandler.globalLevelEvent).

ClientPacketListener.handleExplosion plays the packet's explosionSound;
the client always played entity.generic.explode (a vanilla server's wind
charge sounded like TNT).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:30:43 +01:00
260dd423c9 Keep sprint as a state so a sprint-jump keeps its forward impulse
PlayerInput was rewriting the server sprint flag from the Ctrl and forward
keys. That flag is synced back onto the client, and jumpFromGround adds its
0.2 look-direction impulse only while the flag is set, so releasing Ctrl
before the jump (or double-tapping forward) produced a plain hop. Sprint
still starts and stops through PlayerCommand.

Co-Authored-By: Grok <[email protected]>

Co-authored-by: 一水合氨NH3-H2O <[email protected]>
2026-10-25 14:30:42 +00:00
Ludovic MarieandClaude Opus 5.5 7bffc4c670 cargo horizon-mod test: run a mod's TOML test scripts headless
A mod's tests/<name>.toml scripts run in the sandbox the game uses, with no game
and no window. The runner plays the game's part (the player and clock the mod
reads, ticks, frames, chat lines, commands, a reload) and each step checks what
the mod did: its commands, chat lines, command feedback and errors, HUD panel
and corner, or that it was turned off. A failing step names itself and prints
expected against got. Each script runs on a scratch copy, so storage starts
empty and is removed afterwards.

horizon_mods::testing (feature runtime) holds TestGame and Script; the cargo
subcommand builds the mod (or takes --hmod), filters scripts by name, and fails
when one does. The template gains tests/hello.toml, coords-hud gains panel and
where scripts, and the sandbox tests run the example's scripts and check the
runner's failures, reload and expected stops. Scripts don't care what language
the mod is written in, so script mods (Lua) get the same runner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:25:52 +01:00
Ludovic Marie 44ba133710 Merge branch 'feat/shader-packs-held-items' into feat/shader-packs-hand 2026-10-25 15:09:46 +01:00
Ludovic Marie aa04a30ad2 Merge branch 'feat/shader-packs-weather' into feat/shader-packs-held-items 2026-10-25 15:09:46 +01:00
Ludovic Marie 612024eff4 Merge branch 'feat/shader-packs-clouds' into feat/shader-packs-weather 2026-10-25 15:09:45 +01:00
Ludovic Marie c39579772c Merge branch 'feat/shader-packs-translucent-entities' into feat/shader-packs-clouds 2026-10-25 15:09:45 +01:00
Ludovic Marie 257654ef30 Merge branch 'feat/shader-packs-entities' into feat/shader-packs-translucent-entities 2026-10-25 15:09:44 +01:00
Ludovic Marie c4856e6feb Merge branch 'feat/shader-packs-alpha-test' into feat/shader-packs-entities 2026-10-25 15:09:44 +01:00
Ludovic Marie 90fe138e83 Merge branch 'feat/shader-packs-entity-spans' into feat/shader-packs-alpha-test 2026-10-25 15:09:44 +01:00
Ludovic Marie 15e0fcb3d8 Merge branch 'feat/shader-packs-sildurs' into feat/shader-packs-entity-spans 2026-10-25 15:09:43 +01:00
Ludovic Marie 07668d2d1e Merge branch 'feat/shader-packs-mip-current' into feat/shader-packs-sildurs 2026-10-25 15:09:43 +01:00
Ludovic Marie 202c421f6e Merge branch 'feat/shader-packs-biomes' into feat/shader-packs-mip-current 2026-10-25 15:09:43 +01:00
Ludovic Marie 90b5da76c4 Merge branch 'feat/shader-packs-normals' into feat/shader-packs-biomes 2026-10-25 15:09:42 +01:00
Ludovic Marie 57dca25dd6 Merge branch 'feat/shader-packs-block-ids' into feat/shader-packs-normals 2026-10-25 15:09:42 +01:00
Ludovic Marie dbc59979fb Merge branch 'feat/shader-packs-arena-storage' into feat/shader-packs-block-ids 2026-10-25 15:09:42 +01:00
Ludovic Marie 53db90264c Merge branch 'feat/shader-packs-sun-moon' into feat/shader-packs-arena-storage 2026-10-25 15:09:41 +01:00
Ludovic Marie 27f68454c1 Merge branch 'feat/shader-packs-sky' into feat/shader-packs-sun-moon 2026-10-25 15:09:41 +01:00
Ludovic Marie 1aad193be0 Merge branch 'feat/shader-packs-draw-uniforms' into feat/shader-packs-sky 2026-10-25 15:09:40 +01:00
Ludovic Marie c55f89ef98 Merge branch 'feat/shader-packs-mipmaps' into feat/shader-packs-draw-uniforms 2026-10-25 15:09:40 +01:00
Ludovic Marie 2617b67c79 Merge branch 'feat/shader-packs-timing' into feat/shader-packs-mipmaps 2026-10-25 15:09:39 +01:00
Ludovic Marie 15cf80921e Merge branch 'feat/shader-packs-water' into feat/shader-packs-timing 2026-10-25 15:09:39 +01:00
Ludovic Marie 60e8ec326a Merge branch 'feat/shader-packs-real-buffers' into feat/shader-packs-water 2026-10-25 15:09:39 +01:00
Ludovic Marie bf5c7e4ff2 Merge branch 'feat/shader-packs-custom-uniforms' into feat/shader-packs-real-buffers 2026-10-25 15:09:38 +01:00
Ludovic Marie aebc95fd00 Merge branch 'feat/shader-packs-run-globals' into feat/shader-packs-custom-uniforms 2026-10-25 15:09:37 +01:00
Ludovic Marie 754437fac6 Merge branch 'feat/shader-packs-terrain-draw' into feat/shader-packs-run-globals 2026-10-25 15:09:37 +01:00
Ludovic Marie 2f527aaaf2 Merge remote-tracking branch 'origin/main' into feat/shader-packs-terrain-draw
# Conflicts:
#	crates/horizon-client/src/gfx.rs
2026-10-25 15:09:36 +01:00
Ludovic MarieandClaude Opus 5.5 0f2a497f02 Trapped chests give their signal, barrels show they're open
TrappedChestBlock.getSignal is the chest's opener count (at most 15);
TrappedChestBlockEntity.signalOpenCount updates the blocks around it and
below it when the count changes. GameLevel answered 0 for every trapped
chest. BarrelBlockEntity's openers set open=true for the first one and
open=false when the last one leaves; nothing set it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 15:09:16 +01:00
Ludovic MarieandClaude Opus 5.5 319c7fcaee A server's client shows the nether portal effect
NetherPortalBlock.entityInside runs on the client's own level too: its
setAsInsidePortal drives LocalPlayer.handlePortalTransitionEffect (the
purple overlay, block.portal.trigger). The remote motion loop dropped
MotionEvent::InsidePortal, so single player on the server thread, LAN
guests and dedicated servers' players went through portals without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 14:58:51 +01:00
Kacpherek 4cd1504513 Pregen: report what a stalled band waits for, and requeue lost light
When the band hasn't moved for 30 seconds the task logs how many chunks
of its first row are not loaded, being lit, unlit with no light job or
not post-processed, with the streaming stage counts, and queues light
again for unlit chunks whose neighbours are all loaded.
2026-10-25 14:40:37 +01:00
Kacpherek 35254c4f02 Pregen: keep an empty dedicated server from pausing while it runs
pause-when-empty-seconds paused a server with nobody online after a
minute, and a paused server skips its tick: post-processing stopped, so
the band waited forever on a row of lit chunks. A running /pregen now
counts as activity; the countdown starts once it is done.
2026-10-25 14:40:37 +01:00
Kacpherek 1506c1808a Add /pregen: generate, light and save an area ahead of the players
A Chunky-like command for single player and servers: /pregen start
<radius> [square|circle] [<x> <z>], status, pause, continue and cancel,
with progress (chunks, chunks/s, time left) in the log and to the player
who started it.

The area is swept strip by strip by a band of rows that streaming treats
like a player's area (Streaming::set_band). A row is done once its chunks
are lit and post-processed; the rows behind the band then unload and are
saved, so memory holds only the rows in flight. The band's chunks are
ranked for decoration row by row as they come within reach, so a task
decorates in the same order however its jobs are timed. Between ticks
the server waits on the workers' results and schedules the next jobs at
once instead of once a tick.
2026-10-25 14:40:37 +01:00
cristibctrandOpenAI Codex c756a372a3 Fix stale Windows resource pack overlays
Invalidate version 3 overlays that can omit untouched vanilla resources. Cover folder and ZIP pack cache recovery, and use a writable timestamp handle in the Windows cache test.

Co-Authored-By: OpenAI Codex <[email protected]>
2026-10-25 15:32:57 +02:00
Ludovic MarieandClaude Sonnet 5.5 c5cfab5e07 Merge feat/server-dialog-screen into feat/styled-menu-titles
Clean merge.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 14:25:14 +01:00
Ludovic MarieandClaude Sonnet 5.5 ec2f1b2a0c Merge feat/server-dialog-screen into feat/server-dialog-inputs
Clean merge.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 14:25:14 +01:00
Ludovic MarieandClaude Sonnet 5.5 330a5205ae Merge feat/server-dialogs into feat/server-dialog-screen
Conflict: lib.rs module list (dialog_screen + discord_presence), both kept.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 14:24:52 +01:00
Ludovic MarieandClaude Sonnet 5.5 49dd31d36f Merge origin/main into feat/server-dialogs
Conflicts: lib.rs (dialog + discord_presence modules), packets/play.rs tests
(boss_event_round_trips + dialogs_round_trip), both kept.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 14:24:45 +01:00
Ludovic Marie e6b0f92427 Merge main 2026-10-25 14:21:57 +01:00
Ludovic MarieandClaude Opus 5.5 224b83c6a6 Shader packs, clean room 36: the hand
A pack with gbuffers_hand (or textured_lit, textured, basic; spec 2.3)
draws the first-person hand and held items after the opaque world, into
its own buffers and the world's depth, without blending and with the
entities' 0.1 alpha cut. The vertices are Horizon's hand geometry, read
as entities are; `gl_ProjectionMatrix` is the hand's own projection (the
hand's field of view and bob) with depth scaled by MC_HAND_DEPTH, while
`gbufferProjection` stays the world's (5.2). Horizon's own hand draw is
skipped only when the pack draws it.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1;
no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 13:48:03 +01:00
Ludovic MarieandClaude Opus 5.5 18cac82d44 Shader packs, clean room 35: held item ids and light
`item.properties` (spec 4.1) gives `heldItemId` and `heldItemId2` the
id of the main and off hand's item: -1 for an item the file lacks or an
empty hand, 0 without the file (5.3). `heldBlockLightValue(2)` are the
light levels of the held items' blocks, as Horizon's dynamic lights
already compute them. With `oldHandLight` (on unless the pack turns it
off, OQ-21) the first id and light are those of the brighter hand.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1;
no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 13:35:44 +01:00
Ludovic MarieandClaude Opus 5.5 173463acdf Shader packs, clean room 34: rain and snow
A pack with gbuffers_weather (or its fallbacks textured_lit, textured,
basic; spec 2.3) draws the game's rain and snow after translucent
terrain, blended, with vanilla's 0.1 alpha cut. The weather quads become
entity vertices with their UV animation applied on the CPU (the same
phase Horizon's weather shader computes; a test checks it against the
weather columns bit for bit), and rain and snow each read a copy of
their sprite, so the pack's `texture` repeats down the column as a
standalone texture would. The shared atlas gains COPY_SRC for that copy.

Without a pack nothing changes: Horizon's weather draw is skipped only
when the pack draws it.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1;
no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:51:53 +01:00
Ludovic MarieandClaude Opus 5.5 abe7047d19 Shader packs, clean room 33: clouds
A pack with gbuffers_clouds draws Horizon's cloud geometry itself (spec
2.3, OQ-3: no fallback), blended, after the opaque world. Horizon's own
cloud draw is skipped then, also when the pack's program writes nothing
(BSL and Complementary hide vanilla clouds that way). Without a pack the
cloud draw is unchanged.

The translator now rewrites a bare `discard;` or `return;` to
`if (true) discard;` / `if (true) return;`, so code a pack leaves after
it stays reachable for naga ("Expression not visited"). This also fixes
Complementary Unbound's gbuffers_skytextured.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1;
no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:32:10 +01:00
Ludovic MarieandClaude Opus 5.5 3bc38cebb4 YUNG jigsaws: the start is not counted, priority, depth and bounds rules run
From spec-yungsapi rev 3 §3, §3.1 and §3.2 (impl-questions IQ-2, IQ-3):
- the start piece does not count toward max_count;
- is_priority entries are tried first, in the pool's shuffled order, without
  a weighted draw; min_required_depth skips a pick (no draw) while the parent
  piece is shallower; ignore_bounds places without the free-space test (its
  box is still taken, IQ-12);
- the fallback was already shuffled only when reached.

The port no longer counts these three fields as lost. The layout harness gets
yung-probe and yung-probe2: the spec team's probe pack (built from the oracle
profile) carried as a mod, compared start by start with the oracle's census:
384 of 384 and 32 of 32 starts match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:17:21 +01:00
Ludovic MarieandClaude Opus 5.5 3a7d00a74c Shader packs, clean room 32: translucent entity parts and particles
A shader pack now draws particles with `gbuffers_particles` (falling
back to `gbuffers_textured_lit`, `gbuffers_textured`, `gbuffers_basic`)
and the entity parts that blend, a sneaking player's faded name tag and
entity shadows, with `gbuffers_entities_translucent` (falling back to
`gbuffers_entities`). Both blend with the translucent default unless
`blend.*` says otherwise; particles keep vanilla's alpha cut at 0.1.
Name tag text draws with `gbuffers_entities`, as cutout (2.3).

Particles draw after deferred, with translucent terrain, unless
`particles.ordering=before` or `particles.before.deferred=true`;
translucent entities draw before deferred unless
`separateEntityDraws=true` (3.2).

Without a shader pack nothing changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 10:11:09 +01:00
Ludovic MarieandClaude Opus 5.5 ab289a2cf3 Shader packs, clean room 31: entities and block entities
A shader pack now draws entities with `gbuffers_entities` and block
entities with `gbuffers_block` (or their fallbacks, spec 2.3), after
terrain. Each run of the entity spans is one draw with its own
`entityId` or `blockEntityId` and `entityColor` (the hurt red, the
white flashes) in a per-draw slot. Horizon still draws everything else
(particles, cracks, beams, name tags, shadows, End portals, clouds) in
its own single entity draw, without the runs the pack drew.

The entity vertices are read again at set 1, so the pack gets the face
normal where a vertex has none (block entities), `at_tangent` along the
texture's u and `mc_midTexCoord`, as for terrain.

Entities and block entities draw without blending, with the loader's
alpha test at GREATER 0.1, as cutout (OQ-23); name tags and shadows,
which blend, stay Horizon's for now.

`HORIZON_SHADER_PACK_TIMING` no longer panics when a pass skips a whole
report window (no entities in view).

Without a shader pack nothing changes: the split only runs while a pack
draws entities.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:51:55 +01:00
Ludovic MarieandClaude Opus 5.5 b5a791170d Shader packs, clean room 30: the loader's alpha test
Gbuffers programs get the loader's alpha test on output 0 when they
write `gl_FragData`/`gl_FragColor` (spec 3.2 `alphaTest.<program>`;
with `out` variables the pack tests alpha itself). `GbuffersInputs`
carries the geometry's default, none for terrain, water and the sky so
far; `alphaTest.<program>` replaces it for that program (`off`, or a GL
comparison and a reference).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:51:55 +01:00
Ludovic MarieandClaude Opus 5.5 eb6c81945a Lithostitched processors: unit tests rewritten from the spec
The previous tests of litho.rs are deleted unread (clean-room ruling of
2026-10-25). The new ones build their own block registry from a facts
table and run each processor through process_list against a one-block
world: block_swap's property copy (CTOV's beetroots), references in
order and discard_input, the probe pack's nested condition with else,
apply_random per piece and per block, set_block's providers and its
block entity modifier.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:29:53 +01:00
Ludovic Marie 8d9e1e95ac Merge remote-tracking branch 'origin/main' into fix/remote-tnt
# Conflicts:
#	tools/lan_e2e.py
2026-10-25 09:12:04 +01:00
Ludovic MarieandClaude Opus 5.5 d89fb16f60 Structure blocks harness: CTOV's known differences
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 09:06:14 +01:00
Ludovic MarieandClaude Opus 5.5 58e184f5d5 Structure blocks harness: place the oracle's own pieces, split piece boxes from their surroundings
The mod world now takes each saved start whose pieces are all jigsaw pieces
as the oracle saved it (chunk_dump's HORIZON_SAVED_STARTS, through a new
GeneratorWorker::use_saved_start and PoolPiece::from_saved), so the blocks
are checked whatever the layout: Lithostitched lays jigsaws out its own way
(spec-lithostitched OPEN-L5) and the layout harness checks layouts apart.
Lithostitched's wrapper elements place their delegate; 1.21.1 block states
are read in 26.3's shape.

Counts are split between positions inside a piece's box and around them
(terrain adaptation, decoration), and every mismatch class is written to
.local/structure-layout/<profile>/blocks-report.json.

A CTOV profile carries Lithostitched and ChoiceTheorem's Overhauled Village
from a pack's jar folder (.local/structure-oracle/pack-jars).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 08:51:17 +01:00
Ludovic MarieandClaude Opus 5.5 c43f4bdb2b Lithostitched's processors as the game's own types; replace the old Lithostitched conversion
Clean-room implementation from spec-lithostitched.md §3-§5 and spec-ctov.md §4.

The game reads Lithostitched's processors as its data writes them
(processor/litho.rs): block_swap (only the properties the new block can
have: ripe wheat becomes ripe carrots, beetroot keeps its default age),
reference, apply_random, condition (with else, one processor or a list),
set_block (simple and weighted providers, preserve_state, block entity
modifier) and discard_input; the conditions all_of, any_of, not,
random_chance, true and matching_blocks (input or location, properties).
Their random follows random_mode per block or per piece; Lithostitched's own
seeding is open (OPEN-L6), so a positional random of the world seed and the
processor stands in (impl-questions IQ-7).

horizon-port-pack's new lithostitched module carries the processors as they
are, with the processors nested in them carried, drops those the game cannot
read (lists named by tag, other providers) as Java processors, turns CTOV's
modular_compat into a reference when its mod is ported along (else nothing),
maps lithostitched:jigsaw to vanilla's jigsaw (vanilla layouts, the decision
on OPEN-L5), unwraps limited/guaranteed/delegating elements to their
delegate (limits counted as lost until the next PR) and writes
add_template_pool_elements modifiers as horizon:add_to pools when their
NeoForge load conditions pass.

Deleted unread: legacy_structure_mods/lithostitched.rs and horizon-world's
structure/processor/lithostitched.rs. Blind edits to the legacy folder,
located by exact text or the compiler's error position: its module line
removed, dead_code allowed on ctov (its modular compat is unused now) and on a
test helper, and ctov's modular compat test ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 08:51:17 +01:00
Ludovic MarieandClaude Opus 5.5 aac2f3a903 Shader packs, clean room 29: entity spans
While a shader pack is loaded, building the entity geometry records where
each entity's vertices begin, with its render stage (entities, block
entities, particles, breaking cracks) and its `entityId` or
`blockEntityId` from the pack's `entity.properties` and
`block.properties` (65535 for a name the file lacks, 0 without the
file). The spans reach the renderer in `Frame::entity_spans`, for the
pack's per-entity draws that follow; Horizon's own entity draw stays one
call and without a pack nothing is recorded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 07:44:21 +01:00
Ludovic MarieandClaude Opus 5.5 f80f4e01e7 Structure blocks harness: the blocks Horizon's structure mods place against the structure oracle's
The clean-room structure oracle saved, for each start of a mod world, the
blocks of its box and every position around it that differs from the no-mod
world of the same seed. tools/test_structure_blocks_parity.py generates the
same chunks in full with Horizon twice (26.3 alone, and with the mods carried
by horizon-port-pack as players' packs are) and compares: a position counts
only where Horizon's no-mod world equals the oracle's (1.21.1 and 26.3 differ
elsewhere), and a mismatch is reported by its no-mod, expected and Horizon
blocks, so a missing processor rule reads as one line.

Better Dungeons (3 seeds, 96 complete starts): every structure is listed as
known, with the reason: the placeholder processors, the biome modifier and the
mod's own structure types are not implemented yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 06:39:52 +01:00
Ludovic MarieandClaude Opus 5.5 7b35ca2799 Shader packs, clean room 28: Sildurs Vibrant renders
Three things kept Sildurs Vibrant black or wrong:

- Matrix and array varyings (`varying mat3 tbnMatrix;`): wgpu's stage
  interfaces take only scalars and vectors, so the translator now carries
  each column or element as its own varying and copies them out of and
  into a private global around the pack's `main`.
- Switch options defined in an included file whose name is not a shader
  extension (`#include "shaders.settings"`) were not read, so every
  `program.<name>.enabled` that tested them was false and the composites
  were skipped (OQ-13).
- `fogStart`/`fogEnd` mixed the start of one of vanilla's two fogs with
  the end of the other, so on clear days fog began at the camera and
  Sildurs' water turned white. They now come as the pair of the fog that
  is complete nearer (OQ-36).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 06:35:43 +01:00
Ludovic MarieandClaude Opus 5.5 379692f355 Port YUNG's worldgen as written; delete the old YUNG conversion and assembler
Clean-room (spec-yungsapi.md §2, §3, §5; no mod source read; the legacy
files were deleted unread). horizon-port-pack's new `yung` module carries
`yungsapi:yung_jigsaw` structures and `yungsapi:yung_single_element` pool
elements as the mods write them, so players' packs reach the YUNG draws of
the jigsaw assembler. Fields whose behaviour the specification leaves open
(adapt_noise, max_y/min_y, enhanced terrain, element conditions, modifiers,
priorities, depths, ignore_bounds) are counted as lost by name. YUNG's
other structure, placement and processor types go to the general code
(unsupported or dropped) until the specification covers them.

Deleted: legacy_structure_mods/yung.rs, horizon-world's structure/yung.rs,
the `horizon:yungsapi` keys and `horizon:disables`, which nothing writes
now. Two test initializers of the removed field (enhanced_terrain.rs,
piece_limited.rs) were removed by line from the compiler's error positions.

The layout harness now carries the mods through `horizon-port-pack carry`:
82 of 84 Better Dungeons starts match the oracle piece for piece, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 06:19:43 +01:00
Ludovic MarieandClaude Opus 5.5 9a8453c612 Shader packs, clean room 27: sample mip chains only while current
A program sampled every level of a buffer that has mipmaps, even after a
later program had rewritten the buffer: the levels below the first were
stale. Complementary's FXAA, which samples its colour buffer with implicit
derivatives inside branches, picked those levels at edges and drew black
dots along every edge. A buffer now binds its whole chain only while the
chain matches its content, and its first level otherwise (6.1.7).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 06:12:32 +01:00
Ludovic MarieandClaude Opus 5.5 bf59c0c4f7 Shader packs, clean room 26: biome uniforms and constants
Custom uniform expressions and programs now see the biome at the camera:
`biome`, `biome_category`, `biome_precipitation`, `temperature` and
`rainfall`, and the `BIOME_*`, `CAT_*` and `PPT_*` constants (spec 3.4).
Before, `biome` and every `BIOME_*` read 0, so a test such as
`biome == BIOME_PALE_GARDEN` held everywhere: Complementary drew the pale
garden's fog over every world, and BSL treated every biome as cold, dry,
swampy and so on at once.

OQ-11: `biome` is the index in the game's biome registry (vanilla's
biomes sorted by identifier); names from before the 1.18 renames map to
their successors; a `BIOME_` name that matches no biome reads -1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 06:12:32 +01:00
Ludovic Marie 30c4b5e80d Merge remote-tracking branch 'origin/main' into sh-top 2026-10-25 06:08:23 +01:00
Ludovic Marie 066f07968b Merge remote-tracking branch 'origin/refactor/port-pack-legacy-structure-mods' into feat/yung-port-as-written 2026-10-25 05:38:20 +01:00
Ludovic MarieandClaude Opus 5.5 732efe69bb Shader packs, clean room 25: terrain normals and tangents
Flat terrain's vertex stage reads its quad's first three corners from the
arena page (bound per page at set 3, beside mc_Entity's table) and gives
gl_Normal / vaNormal the face normal and at_tangent the tangent along
the texture's u, with w the handedness of bitangent = cross(tangent,
normal) (spec 5.1). The pack's terrain and water pipelines cull back
faces as the game's own terrain does (clockwise front faces, rows being
flipped to GL's): water's surface no longer shows its downward copy.

Flat draws call a hook per arena page (Flat::draw_with); the arena lists
its page buffers.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
5.1; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 05:16:38 +01:00
Ludovic MarieandClaude Opus 5.5 441f749c25 Shader packs, clean room 24: mc_Entity from block.properties
block.properties (spec 4.1) is read: `block.<id>=` names with optional
namespaces and state filters; the most specific matching entry wins.
Terrain vertices carry their sprite layer, not their block, so the game
builds a table of the block sprite layers: each takes the id of the block
named like its sprite, else the id most blocks drawing it share; y is 1
on the water and lava sprites. Flat terrain reads it from a storage
buffer at set 3; other draws and packs without the file read (-1, -1).
Building the table takes 14 ms for BSL, 39 ms for Complementary.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
4.1, 5.1, 5.3; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 04:59:39 +01:00
Ludovic MarieandClaude Opus 5.5 b940754555 Terrain vertex arena readable as storage where flat draws run
The terrain vertex arena's pages also get STORAGE usage on devices that
run flat draws (vertex storage and compute), so a shader pack's terrain
program can read the other corners of a vertex's quad to give packs a
face normal and tangent. Horizon's own pipelines are unchanged; the A/B
in the PR shows no frame-time change without a pack.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 04:23:38 +01:00
Ludovic MarieandClaude Opus 5.5 36f68ab838 Server dialogs: text and boolean inputs
A dialog's text inputs are edit boxes (labelled above, CommonLayouts.
labeledElement; width, max length and initial value from the dialog) and
its boolean inputs are checkboxes with their label. A click focuses a box
or toggles a box, Tab and Shift+Tab move between the text inputs, the
keys, shortcuts and typed text go to the focused one. What they hold
fills the command templates and custom actions' payloads.

With this, AuthMe's register and login dialogs work: players type their
password and join instead of being kicked after 30 s.

horizon-ctl's `type` types into the focused input of an open dialog (the
first one when none is), in configuration too. server_e2e's dialog check
now types a number and ticks a box, and checks the command the template
makes of them and the payload of a custom action.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 04:05:25 +01:00
Ludovic MarieandClaude Opus 5.5 230730d1f5 Shader packs, clean room 23: the sun and moon (gbuffers_skytextured)
gbuffers_skytextured (or gbuffers_textured, gbuffers_basic) draws the
frame's sun and moon quads, with their render stages, `texture` reading
the shared atlas their sprites live in. The sky's parts draw in vanilla's
order (disc, sunset, sun, moon, stars, void), in one render pass while
consecutive programs write the same buffers. The sun and moon add to the
sky (SRC_ALPHA, ONE) unless blend.<program> says otherwise. Horizon's
world pass skips its own sun and moon when the pack draws them; a part
without a program stays Horizon's.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
2.3, 5.4; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 04:02:13 +01:00
Ludovic MarieandClaude Opus 5.5 7d6583dc4d Shader packs, clean room 22: the sky (gbuffers_skybasic)
The pack's gbuffers_skybasic (or gbuffers_basic) draws vanilla's sky
geometry, as Horizon's own sky builds it: the disc at y 16, the sunset
fan while the sun is low, the stars and the void disc, each with its
render stage. One static vertex buffer; the frame's colours and rotations
sit in a small uniform the vertex inputs read. The sky draws after the
world copy and before terrain, at the far plane: only where nothing else
drew, without writing depth. It blends with the translucent default unless
blend.<program> says otherwise. Horizon's world pass then skips its own
sky disc, stars and void. The sun and moon stay Horizon's for now
(gbuffers_skytextured is next): the pack's sky covers them.

load_post takes the game's inputs per geometry (GameInputs);
GbuffersInputs gains statements run after the pack's main.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
2.1, 2.3, 5.4; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 03:45:24 +01:00
Ludovic MarieandClaude Opus 5.5 1fdb119587 Server menus keep their styled titles
A server's open_screen title is a text component, and container screens
draw it as AbstractContainerScreen does: in the label grey, under the
component's own colours, bold, italics and fonts, with the § codes a
literal holds. Horizon flattened it to a plain string, so a plugin's
gold and bold "Server Selector" menu showed in plain grey (#1645).
Chests, hoppers, dispensers, droppers, brewing stands and the other
workstations now draw the server's title. Before, the workstations
ignored it and showed their default name.

horizon-ctl's `screen` reports the title span by span (text, colour,
bold, italic). server_e2e's new `titles` check names a chest on the
vanilla server with a styled CustomName, opens it, and checks the title.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 03:30:04 +01:00
Ludovic MarieandClaude Opus 5.5 a7f8650c6b Server dialogs: the dialog screen, its buttons and their actions
A server's show_dialog (configuration and play) opens vanilla's
DialogScreen instead of being dropped: the header with the title and the
warning button, the message bodies in a scrolling column, the action
buttons packed into columns (MultiButtonDialogScreen) or side by side in
the footer (notice, confirmation). A button runs its click event: a
custom action goes back as custom_click_action, a command runs (in play;
in configuration vanilla only warns), show_dialog opens another dialog,
copy_to_clipboard copies. after_action closes the screen, leaves it, or
opens the WaitingForResponseScreen. The warning button opens the
"custom screen" warning, whose Disconnect leaves the server. clear_dialog
closes it, and so do the level loading screen and a disconnect. The world
and HUD blur behind it as behind any in-game screen.

Inputs come next; here they are not drawn and keep their initial values.

tools/server_e2e.py is a new harness: a vanilla 26.3 dedicated server and
one Horizon client. Its dialog check shows a dialog with /dialog show,
clicks a command button (the server's trigger), a custom action (the
server's debug log shows its payload) and a wait_for_response one, and
clears a dialog with /dialog clear.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 03:29:45 +01:00
Ludovic MarieandClaude Opus 5.5 b9b47f12da Shader packs, clean room 21: per-draw uniforms (renderStage)
A gbuffers program's renderStage, entityId, blockEntityId and entityColor
(spec 5.3, updated per draw) move to a block of their own at set 2 that
the game picks per draw with a dynamic offset: one slot per render stage.
Terrain draws as TERRAIN_SOLID, translucent terrain as
TERRAIN_TRANSLUCENT. The terrain test pack paints any other stage red.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
5.3, 5.4; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 03:29:21 +01:00
Ludovic MarieandClaude Opus 5.5 5e348aa479 Shader packs, clean room 20: buffer mipmaps
`const bool <buffer>MipmapEnabled = true;` in a deferred, composite or
final program's fragment stage now regenerates that buffer's mip chain
right before the program (6.1.7), on the side programs read, and only
when the buffer changed since its last chain this frame. Each level is
the average of the 2x2 texels above it; levels attach one at a time and
programs sample all of them. Unfilterable buffers (integer, 32-bit
float) get none, with a note.

BSL's bloom read every tap from the full-size buffer before; with its
chain composite4 drops from 0.38 to 0.29 ms at 720p on the Mac mini
(HORIZON_SHADER_PACK_TIMING, the chains included), and blurs as intended.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
section 6.1.7; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 03:03:54 +01:00
Ludovic MarieandClaude Opus 5.5 1d90d72a64 Server dialogs: the packets and the dialog model
show_dialog and clear_dialog in configuration and play, and
custom_click_action, the answer, in both. Dialog.DIRECT_CODEC as
horizon_client::dialog: the five dialog types, their bodies, inputs and
actions with vanilla's defaults, the values inputs hold, and
Action.createAction (a command template's $(key) substitution with
escapeWithoutQuotes, a custom action's payload of every input's tag).

Nothing uses them yet: the screen comes next.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 02:59:28 +01:00
Ludovic MarieandClaude Opus 5.5 b6345fc61d Shader packs, clean room 19: GPU time of each pass (developers' aid)
HORIZON_SHADER_PACK_TIMING=1 puts timestamps around every pass of a
shader pack, one frame in 30, and logs each pass's median every 30
timed frames. The frame after a timed one waits for the GPU before
reading them (Metal resolves timestamps without waiting for the passes
that write them). Passes overlap on tiled GPUs, so a pass is charged
from the later of its beginning and the previous pass's end.

This is what attributes a pack's cost to its own programs or to ours
when the machine is shared and FPS comparisons are noisy.

Clean-room: Horizon's own tooling, no spec section; no other loader's
code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 02:57:15 +01:00
Ludovic MarieandClaude Opus 5.5 3e2c30a852 Shader packs, clean room 18: translucent terrain drawn by the pack
With a pack whose gbuffers_water (or a fallback down gbuffers_terrain's
chain) loads, translucent terrain (water, stained glass) is drawn by it
after the deferred programs and before the composites, in place, sorted
back to front as the game sorts it, and Horizon's own translucent
terrain draw is skipped.

- blend.<program> (off, or four GL factors); translucent terrain
  defaults to SRC_ALPHA ONE_MINUS_SRC_ALPHA ONE ONE_MINUS_SRC_ALPHA, and
  only blendable buffer formats blend.
- depthtex1/depthtex2: depth without translucent terrain, a copy taken
  just before it when a later program reads them (before it, depthtex0
  itself). The hand is drawn after the pack, so depthtex2 = depthtex1.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1,
sections 2.1, 2.3, 3.2 (blend), 6.2 (depthtex1/2); no other loader's
code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 02:47:14 +01:00
Ludovic MarieandClaude Opus 5.5 a2ec3fc791 Shader packs, clean room 17: real packs' buffers and samplers
- RGBA16 and R11F_G11F_B10F buffers get their own formats where the device has them
  (16-bit normalized render targets need the adapter's format features): the float stand-in
  kept NaN and values past 1, and BSL's TAA history went black for good.
- Textures share one sampler variable per kind (linear, nearest, repeat, nearest-repeat,
  comparison): devices have as few as 16 sampler slots, Complementary's terrain program
  declares 23 textures.
- A gbuffers pass reading the depth buffer or a buffer it draws into reads a blank texture
  instead (a feedback loop: undefined in GL, refused by wgpu, and a crash here).
- A bind group layout that fails validation skips the program with the error's details
  instead of ending the game.
- shadowModelView / shadowProjection (and inverses) for programs that read them before the
  shadow pass exists: an orthographic camera 160 blocks each side, toward the shadow light.
- HORIZON_SHADER_PACK_SKIP=a,b leaves programs out (a developers' aid to bisect a pack).

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, sections 6.1, 6.7,
5.2; no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 02:03:17 +01:00
Ludovic MarieandClaude Opus 5.5 505e8e960f Shader packs, clean room 16: custom uniforms
`uniform.<type>.<name>` and `variable.<type>.<name>` of shaders.properties (3.4): an
expression parser with C precedence, the function table (math, vectors, `if`, `between`,
`equals`, `smooth`, `random`...), evaluated on the CPU once per frame in file order after the
frame's own uniforms. `smooth` keeps its state per call site and halves the distance to its
target every fade time (OQ-26 working answer). A name neither the frame nor the pack defines
reads 0 and is listed once in the log.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, section 3.4; no other
loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 02:01:48 +01:00
Ludovic MarieandClaude Opus 5.5 6c8880fbd8 Shader packs, clean room 15: globals initialized at run time, switch options
naga keeps only constant initializers of globals, so every initialized global that is not
`const` (and every conditional one) gets its value from a function of ours that main calls
first, one per declarator, converting as GLSL's initialization does (`vec2 v = atlasSize`).
`vec3 a = x, b = y;` no longer loses `b`.

Program-enable expressions (3.3) now see the pack's switch options that are on by default
(8.1): `#define NAME` with nothing after it, tested with `#ifdef`/`#ifndef` anywhere in the
pack (OQ-13 working answer). BSL's `deferred` (ambient occlusion) and its TAA ran with options
off before.

Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, sections 3.3, 8.1;
no other loader's code read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 02:00:40 +01:00
Ludovic MarieandClaude Opus 5.5 1fa46979c8 Server clients: primed TNT falls and burns its fuse by itself between updates
PrimedTnt keeps Entity's NO_OP InterpolationHandler and ticks on a client
too: a position packet puts it there at once, its own tick moves it on
(gravity, collisions, bounces, drag) and burns the fuse down, and a client
discards it when the fuse runs out. Horizon interpolated it towards each
update instead, so it trailed about two ticks behind the server.

lan_e2e's falling check now drops primed TNT too and checks that the
guest has it exactly where its fall from rest puts it for the fuse the
server sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 02:57:26 +02:00
Ludovic MarieandClaude Opus 5.5 0f9de6dbb0 Shader packs, clean room 14: terrain drawn by the pack's program
With a pack whose gbuffers_terrain (or a fallback) loads, solid and
cutout terrain is drawn by it into the pack's buffers, in place, between
prepare and deferred, and Horizon's own solid terrain draw is skipped.

- depthtex0 is now a Depth32Float attachment: the blit writes the
  world's depth there (GL window depth, GL rows), terrain tests and
  writes against it, so entities and terrain occlude each other; later
  programs sample it as before.
- The vertex glue reads Horizon's TerrainVertex on both draw paths
  (instanced, and flat with the page tables in bind group 1) and gives
  atlas coordinates, lightmap coordinates in 0-240, the vertex colour,
  mc_midTexCoord at the sprite's centre and mc_Entity = -1. Normals,
  tangents and block ids come later.
- texture/gtexture/tex sample the block atlas, lightmap the lightmap;
  atlasSize is set.
- Occlusion culling is off while a pack draws terrain (it reads the
  depth of Horizon's terrain draw), and flat draws stay on.
- Uniforms a program reads that are not provided yet are reported.
- Program building is shared by quads and terrain (build_pass, bind).
- terrain-test: Horizon's own pack for this slice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 01:39:28 +02:00
Ludovic MarieandClaude Opus 5.5 3d4b63c19e wasmtime 48 LTS: one wasm-tools version for the runtime, packing and the SDK
wasmtime 36 read WebAssembly with wasm-tools 0.236, wit-component (cargo
horizon-mod, the sandbox tests) used 0.239 and the SDK's wit-bindgen 0.247:
three copies of wasmparser, wasm-encoder, wit-parser and wasm-metadata.
wasmtime 48, the next long-term-support line (fixes until August 2028),
wit-component 0.254 and wit-bindgen 0.60 all use 0.254. No code change;
horizon-mods now needs Rust 1.95.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 15:25:10 +02:00
634 changed files with 41456 additions and 24245 deletions

No files matched your search

-1
View File
@@ -2,7 +2,6 @@
target/
.local/
**/node_modules/
website/
benchmarks/
packs/
mods/
+1 -1
View File
@@ -2,5 +2,5 @@
# where Git for Windows' core.autocrlf would check them out with CRLF.
docs/launcher-commands.md text eol=lf
docs/horizon-ctl-commands.md text eol=lf
website/src/tokens.css text eol=lf
crates/horizon-theme/tokens.css text eol=lf
docs/api/*-reference.md text eol=lf
+15 -8
View File
@@ -8,7 +8,7 @@ name: nightly audit
# gh workflow run "nightly audit" -f dry_run=true # the audit, without touching issues
on:
schedule:
# GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:00 in Paris.
# GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:07 in Paris today.
- cron: '7 1 * * *'
- cron: '7 2 * * *'
workflow_dispatch:
@@ -29,15 +29,21 @@ env:
jobs:
audit:
runs-on: [self-hosted, horizon-game]
timeout-minutes: 150
# The Mac mini's runners only: the audit compares with the previous one, so it stays on one platform.
runs-on: [self-hosted, horizon-game, macOS]
timeout-minutes: 240 # every harness (~80 min) plus lan_integration (~40 min an attempt under load, retried)
steps:
- name: 03:00 in Paris
- name: 03:07 in Paris
id: when
env:
SCHEDULE: ${{ github.event.schedule }}
run: |
hour=$(TZ=Europe/Paris date +%H)
if [[ "${{ github.event_name }}" == schedule && "$hour" != 03 ]]; then
echo "It is ${hour}:00 in Paris: the other schedule runs the audit."
# Which cron is 03:07 in Paris, from Paris's offset today: GitHub can start a schedule hours late, so the
# clock at start time can't tell (on 2026-10-26 both started after 04:00 Paris and both skipped).
offset=$(TZ=Europe/Paris date +%z)
ours=$([ "$offset" = +0200 ] && echo '7 1 * * *' || echo '7 2 * * *')
if [[ "${{ github.event_name }}" == schedule && "$SCHEDULE" != "$ours" ]]; then
echo "Paris is at UTC${offset} today: the '$ours' schedule runs the audit."
echo "run=false" >> "$GITHUB_OUTPUT"
else
echo "run=true" >> "$GITHUB_OUTPUT"
@@ -65,7 +71,8 @@ jobs:
run: |
echo "since=$(date +%Y-%m-%dT%H:%M:%S)" >> "$GITHUB_OUTPUT"
set +e
python3 tools/parity.py --all --timeout 1800 2>&1 | tee "$RUNNER_TEMP/audit.log"
# lan_integration (the whole lan_e2e suite) takes ~2,400 s under load, past the usual 1,800.
python3 tools/parity.py --all --timeout 3000 2>&1 | tee "$RUNNER_TEMP/audit.log"
echo "exit=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
{ echo '```'; tail -40 "$RUNNER_TEMP/audit.log"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
- name: Issues for the harnesses that regressed
+11 -4
View File
@@ -23,7 +23,11 @@ env:
jobs:
parity-main:
runs-on: [self-hosted, horizon-game]
# A Mac mini runner of its own (ludovics-mac-mini-2 holds only this label since 2026-10-26): behind PR parity jobs
# this run waited 2 h while every merge replaced the pending one, and on the release runner a release then waited
# behind the next run. PR parity jobs have ludovics-mac-mini and the desktop. Not the desktop: a job slowed down
# because the maintainer came back could time out, and a failure here bisects and comments on merges.
runs-on: [self-hosted, macOS, horizon-parity-main]
timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures
steps:
- uses: actions/checkout@v4
@@ -44,6 +48,9 @@ jobs:
GH_TOKEN: ${{ github.token }}
run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT"
- name: The harnesses the merges since then can affect
id: harnesses
# A failure here is judged by the next step: the run passes when every failed harness passes again at HEAD.
continue-on-error: true
env:
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.base.outputs.sha }}
@@ -51,8 +58,8 @@ jobs:
echo "Merges since ${BASE_SHA}:"
git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD"
python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400
- name: The merge that broke them
if: failure()
- name: A flake, or the merge that broke them
if: steps.harnesses.outcome == 'failure'
env:
GH_TOKEN: ${{ github.token }}
PARITY_HOSTS: ''
@@ -61,7 +68,7 @@ jobs:
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
python3 tools/parity_main.py bisect "$BASE_SHA" --comment
- name: Logs of the failed harnesses
if: failure()
if: steps.harnesses.outcome == 'failure'
uses: actions/upload-artifact@v4
with:
name: parity-main-logs
+21 -2
View File
@@ -36,11 +36,30 @@ jobs:
- name: Tools from the runner
run: bash tools/ci/runner-env.sh
- name: Vanilla data, and resources prepared by this preparer
run: bash tools/ci/vanilla-data.sh
env:
BASE_SHA: ${{ inputs.base }}
run: |
# main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on
# the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own.
set -euo pipefail
if git rev-parse --verify -q origin/main >/dev/null \
&& git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then
git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh"
bash "$RUNNER_TEMP/vanilla-data.sh"
else
bash tools/ci/vanilla-data.sh
fi
- name: The prepared output is the one the preparer's OUTPUT_VERSION says
env:
BASE_SHA: ${{ inputs.base }}
run: python3 tools/prepare_output.py check --cache --base "$BASE_SHA"
run: |
# The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither
# the tool nor the number, so there is nothing to check.
if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then
echo "This head's preparer has no OUTPUT_VERSION: nothing to check"
exit 0
fi
python3 tools/prepare_output.py check --cache --base "$BASE_SHA"
- name: The version constants are the pinned jar's
run: python3 tools/gen_version_consts.py --check
- name: The harnesses this change can affect
+46 -1
View File
@@ -79,9 +79,50 @@ jobs:
# 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
build:
exporters:
needs: decide
if: needs.decide.outputs.release == 'true'
# This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it.
runs-on: ${{ vars.MAC_RUNNER || 'ludovics-mac-mini' }}
# Three full preparations (two isolated, one batched) besides the compile.
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
ref: ${{ needs.decide.outputs.head }}
persist-credentials: false
clean: true
- uses: dtolnay/rust-toolchain@stable
- run: bash tools/ci/runner-env.sh
- run: bash tools/ci/vanilla-data.sh
- name: Compile and validate original exporters against the pinned jars
shell: bash
run: |
set -euo pipefail
# target/ is gone after the clean checkout, and vanilla-data.sh builds the preparer only when it
# prepares afresh.
cargo build --release --locked -p horizon-prepare
# Compiled here, never taken from the runner's shared preparations: pull requests' parity jobs
# write those (vanilla-data.sh links .local/exporters to them).
rm -rf .local/exporters
bundle=$(target/release/horizon-prepare compile-exporters --root "$PWD" | tail -1)
mkdir -p exporters
cp -R "$bundle/server" "$bundle/client" "$bundle/manifest.json" exporters/
# Only our classes and their manifest leave this runner.
stray=$(find exporters -type f ! -path exporters/manifest.json \
! \( -name '*.class' \( -path 'exporters/server/dev/horizonlab/parity/*' -o -path 'exporters/client/dev/horizonlab/parity/*' \) \))
[ -z "$stray" ] || { echo "::error::not one of our classes: $stray"; exit 1; }
python3 tools/check_prepare_exporters.py --binary target/release/horizon-prepare
- uses: actions/upload-artifact@v4
with:
name: original-exporters
path: exporters/
if-no-files-found: error
retention-days: 3
build:
needs: [decide, exporters]
if: needs.decide.outputs.release == 'true'
name: build ${{ matrix.name }}
strategy:
fail-fast: false
@@ -220,6 +261,10 @@ jobs:
path: ${{ runner.temp }}/smoke-test.json
if-no-files-found: error
retention-days: 3
- uses: actions/download-artifact@v4
with:
name: original-exporters
path: exporters
- name: Package
run: |
set -euo pipefail
+3
View File
@@ -31,3 +31,6 @@
/.horizon-cache/
/crash-reports/
/debug/
# Release-only compiled original exporter bundle.
/exporters/
+6 -5
View File
@@ -54,7 +54,8 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m
unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles),
`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`.
`docs/`, `.github/workflows/`. The website (playhorizon.dev) is the private ludovic111/horizon-site: its build
reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` and `crates/horizon-theme/tokens.css` from main.
## Build and test fast
@@ -66,7 +67,7 @@ cargo build --profile fast -p horizon-client # optimized, quick to link:
python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job)
python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them
python3 tools/parity.py mob_ai sculk # named harnesses
python3 tools/lan_e2e.py --check chest # two real games over LAN (host in-frame); --server-thread for the host on its server thread
python3 tools/lan_e2e.py --check chest # two real games over LAN (server-thread host); --in-frame compares the fallback
python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
```
@@ -156,7 +157,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
exactly as a LAN guest or a dedicated server's player does. This is what players run. Open
`[server-thread]` issues list the gaps left.
2. **In-frame (`--in-frame`, `--no-server-thread` or `HORIZON_SERVER_THREAD=0`):** the window's `Game` ticks
the world itself, one level that follows the player (`fn enter_dimension`). Most harnesses test this path.
the world itself, one level that follows the player (`fn enter_dimension`). Deterministic rule fixtures still use this path; player-facing integration uses the default server thread.
LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths
when you touch player-facing gameplay:
@@ -164,8 +165,8 @@ when you touch player-facing gameplay:
```sh
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # server thread
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --in-frame # in-frame
python3 tools/lan_e2e.py --check <name> # host in-frame, guest is a server client
python3 tools/lan_e2e.py --server-thread --check <name> # host on its server thread (portals, levels, distance, lava need it)
python3 tools/lan_e2e.py --check <name> # host on its server thread, guest is a server client
python3 tools/lan_e2e.py --in-frame --check <name> # comparison (portals, levels, distance, lava need server-thread mode)
python3 tools/parity.py dedicated_server server_entities server_player_damage
```
+2 -2
View File
@@ -4,8 +4,8 @@ Thanks for helping. Horizon is Minecraft: Java Edition 26.3 rewritten in Rust, a
everything is that **it plays exactly like vanilla**. This page is the short version of how we work; questions are
welcome on [Discord](https://discord.gg/HcTeMZxe5E).
This repository holds the game, the launcher and the website, plus the tools, tests and docs that build, check and
release them. Anything else (videos, Discord and other community material) lives elsewhere.
This repository holds the game and the launcher, plus the tools, tests and docs that build, check and release them.
The website (playhorizon.dev) is built in a separate repository from this one's README, `docs/api/` and roadmap. Anything else (videos, Discord and other community material) lives elsewhere.
**Where to start: [playhorizon.dev/hub](https://playhorizon.dev/hub).** It shows what is being done now and next
([ROADMAP.md](ROADMAP.md) in the repository), the work board, good first tasks, and the forms to report a bug or
Generated
+301 -310
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
resolver = "2"
[workspace.package]
+1 -1
View File
@@ -31,7 +31,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that re
Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/ludovic111/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its files from your own copy of Minecraft, and updates itself.
**You need** Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 JDK, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install).
**You need** Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 runtime, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install).
<table>
<tr>
+68 -54
View File
@@ -134,7 +134,7 @@ Better tools for mod makers: a test runner that needs no game window, templates
`cargo horizon-mod test` runs a mod's test scripts against a fake game snapshot ([#1816](https://github.com/ludovic111/horizon/issues/1816)) and, for server mods, scripted server events ([#1837](https://github.com/ludovic111/horizon/issues/1837)); the content template and the guides are merged ([#1859](https://github.com/ludovic111/horizon/issues/1859), [#1810](https://github.com/ludovic111/horizon/issues/1810), [docs/api/stability.md](docs/api/stability.md)). Left: templates for hud, server and machine mods, typed wrappers in the SDK, a frozen 0.1 compatibility mod that every runtime must load, a CI check that fails when a stable reference entry is removed without a new major version, and the SDK on crates.io once the API is stable.
More: [website/docs/test-a-mod.md](website/docs/test-a-mod.md)
More: [https://playhorizon.dev/docs/test-a-mod](https://playhorizon.dev/docs/test-a-mod)
</details>
@@ -160,6 +160,66 @@ Translatable components resolved through the selected language for items, contai
</details>
#### Cooldowns drawn on items
After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.
<details><summary>Technical</summary>
Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763).
More: [#1933](https://github.com/ludovic111/horizon/issues/1933)
</details>
#### Chat settings and team prefixes
The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.
<details><summary>Technical</summary>
Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce.
More: [#1932](https://github.com/ludovic111/horizon/issues/1932) · [#1841](https://github.com/ludovic111/horizon/issues/1841)
</details>
#### A pointing hand over buttons
The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.
<details><summary>Technical</summary>
26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347).
More: [#1897](https://github.com/ludovic111/horizon/issues/1897)
</details>
#### Ctrl+Backspace and scroll bars in menus
Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.
<details><summary>Technical</summary>
`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)).
More: [#1884](https://github.com/ludovic111/horizon/issues/1884) · [#1931](https://github.com/ludovic111/horizon/issues/1931)
</details>
#### Chickens flap while they fall
Chickens should flap their wings while they fall, not stand still in the air.
<details><summary>Technical</summary>
Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706).
More: [#1892](https://github.com/ludovic111/horizon/issues/1892)
</details>
### Rendering
#### Shader packs, written again from scratch
@@ -250,7 +310,7 @@ Horizon should run well on small machines: integrated graphics, the Steam Deck,
Partly done: an opt-in 60 FPS cap with fewer workers on battery, Far Detail Reduced for integrated GPUs and animated textures on the GPU (both shipped). Left: measured targets and fixes per class of machine (memory use, worker counts, startup) on a Steam Deck, old Intel and Apple Silicon Macs and 8 GB computers, reported on the Benchmarks page.
More: [docs/benchmark.md](docs/benchmark.md) · [website/docs/performance.md](website/docs/performance.md)
More: [docs/benchmark.md](docs/benchmark.md) · [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
</details>
@@ -540,7 +600,9 @@ You can port a mod to Horizon with your own AI agent on your own computer. Horiz
<details><summary>Technical</summary>
A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide ([website/docs/agents.md](website/docs/agents.md), [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off.
A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide (playhorizon.dev/docs/agents, [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off.
More: [https://playhorizon.dev/docs/agents](https://playhorizon.dev/docs/agents)
</details>
@@ -876,7 +938,9 @@ Run Horizon's built-in benchmark and share the report: every new computer makes
<details><summary>Technical</summary>
`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark <report>` shows what would be sent and uploads it ([website/docs/performance.md](website/docs/performance.md)). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711).
`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark <report>` shows what would be sent and uploads it (playhorizon.dev/docs/performance). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711).
More: [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
</details>
@@ -902,56 +966,6 @@ Armour and tools in End city chests should come enchanted, as in vanilla.
</details>
#### Cooldowns drawn on items
After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.
<details><summary>Technical</summary>
Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763).
</details>
#### Chat settings and team prefixes
The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.
<details><summary>Technical</summary>
Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce.
</details>
#### A pointing hand over buttons
The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.
<details><summary>Technical</summary>
26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347).
</details>
#### Ctrl+Backspace and scroll bars in menus
Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.
<details><summary>Technical</summary>
`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)).
</details>
#### Chickens flap while they fall
Chickens should flap their wings while they fall, not stand still in the air.
<details><summary>Technical</summary>
Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706).
</details>
## Recently shipped
- **OpenGL for old computers** (v0.2.63): Horizon now starts on old PCs whose graphics card has no Vulkan or DirectX 12 driver: it switches to OpenGL by itself, and Options > Graphics can pick OpenGL by hand. [#1917](https://github.com/ludovic111/horizon/issues/1917) · [#1920](https://github.com/ludovic111/horizon/issues/1920) · [#1936](https://github.com/ludovic111/horizon/issues/1936)
+2 -1
View File
@@ -17,4 +17,5 @@ by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1
`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`).
license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). `star.svg` is Horizon's own, drawn on
the same grid.
+68 -24
View File
@@ -1,10 +1,11 @@
//! `cargo horizon-mod check <file>`: what the registry checks of a submission,
//! run anywhere: its kind's own checks (docs/api/mod-index.md), its signature
//! when given a key, and for a mod a trial run in the sandbox: it must start,
//! survive ticks, frames, a chat line and each of its commands, and import
//! no more than its capabilities.
//! survive ticks, frames, a chat line and each of its commands (a server mod:
//! a player joining, chatting, typing them and leaving), and import no more
//! than its capabilities.
use horizon_mods::{
Clock, Mods, Output, Package, Player, Snapshot, Status,
Clock, GameMode, Mods, Output, Package, Player, ServerPlayer, Snapshot, Status,
index::{self, Facts, Kind},
manifest::component_imports,
};
@@ -46,6 +47,7 @@ impl Report {
"api": self.facts.api,
"side": self.facts.side,
"capabilities": self.facts.capabilities,
"api_level": self.facts.api_level,
"game": self.facts.game,
"requires": requires,
"sha256": self.sha256,
@@ -69,6 +71,8 @@ impl Report {
if let Some(side) = f.side {
let side = serde_json::to_value(side).unwrap_or_default();
out += &format!(", API {}, {}", f.api, side.as_str().unwrap_or("?"));
} else if self.kind == Kind::Shader {
out += &format!(", shader API {}", f.api);
} else if !f.api.is_empty() {
out += &format!(", format {}", f.api);
}
@@ -84,6 +88,9 @@ impl Report {
")\n {} bytes, SHA-256 {}, {signed}\n",
self.size, self.sha256
);
if let Some(level) = f.api_level {
out += &format!(" needs mod API level {level} or newer\n");
}
for c in &f.capabilities {
out += &format!(" may {}\n", c.describe());
}
@@ -113,6 +120,7 @@ pub fn kind_of(path: &Path) -> Option<Kind> {
"hmod" => Some(Kind::Mod),
"hpack" => Some(Kind::Modpack),
"zip" => Some(Kind::ResourcePack),
"hshader" => Some(Kind::Shader),
_ => None,
}
}
@@ -191,45 +199,81 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
if let Some(reason) = failed(&mods) {
return Err(format!("it didn't start: {reason}"));
}
report.commands = mods.commands().map(str::to_owned).collect();
let client: Vec<String> = mods.commands().map(str::to_owned).collect();
let server: Vec<String> = mods.server_commands().map(str::to_owned).collect();
report.commands = [client.clone(), server.clone()].concat();
// A server mod plays with one player on, who joins, chats and leaves.
let steve = ServerPlayer {
id: "00000000-0000-4000-8000-000000000001".into(),
name: "Steve".into(),
x: 0.5,
y: 64.0,
z: 0.5,
dimension: "minecraft:overworld".into(),
game_mode: GameMode::Survival,
health: 20.0,
};
let snapshot = |t: u64| Snapshot {
player: Some(Player {
x: 0.5 + t as f64 * 0.1,
y: 64.0,
z: 0.5,
yaw: 90.0,
pitch: 0.0,
health: 20.0,
food: 20,
dimension: "minecraft:overworld".into(),
}),
clock: Some(Clock {
game_time: t,
day_time: 1000 + t,
}),
players: vec![steve.clone()],
// The GUI of a 1280 x 720 window at scale 3.
gui_size: (427.0, 240.0),
..Snapshot::default()
};
mods.set_snapshot(snapshot(0));
mods.player_joined(&steve);
for t in 0..TICKS {
mods.set_snapshot(Snapshot {
player: Some(Player {
x: 0.5 + t as f64 * 0.1,
y: 64.0,
z: 0.5,
yaw: 90.0,
pitch: 0.0,
health: 20.0,
food: 20,
dimension: "minecraft:overworld".into(),
}),
clock: Some(Clock {
game_time: t,
day_time: 1000 + t,
}),
});
mods.set_snapshot(snapshot(t));
mods.tick(t);
mods.server_tick(t);
for _ in 0..FRAMES_PER_TICK {
mods.frame(1.0 / 60.0);
}
}
mods.chat("<Steve> hello");
for name in report.commands.clone() {
mods.command(&name);
mods.player_chat(&steve, "hello");
for name in &client {
mods.command(name);
}
for name in &server {
mods.server_command(&steve, name);
}
mods.set_snapshot(Snapshot::default());
mods.player_left(&steve);
for out in mods.drain() {
report.output.push(match out {
Output::Chat { text, .. } => format!("chat: {text}"),
Output::Feedback { text, error } => {
Output::Tell { text, .. } => format!("tell: {text}"),
Output::Broadcast { text, .. } => format!("broadcast: {text}"),
Output::Feedback { text, error } | Output::Reply { text, error, .. } => {
format!("{}: {text}", if error { "error" } else { "feedback" })
}
Output::Command { line } => format!("command: /{line}"),
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
Output::Shake { strength, seconds } => {
format!("shook the camera: {strength:.2} for {seconds:.1} s")
}
});
}
let shapes = mods.hud_shapes().count();
if shapes > 0 {
report.output.push(format!("drew {shapes} HUD shape(s)"));
}
match failed(&mods) {
Some(reason) => Err(format!("it stopped: {reason}")),
None => Ok(()),
@@ -275,7 +319,7 @@ mod tests {
.unwrap();
assert!(e.contains("signature"), "{e}");
let e = check(&pack, Kind::Shader, None, None).err().unwrap();
assert!(e.contains("shader packs open"), "{e}");
assert!(e.contains("horizon-shaders.toml"), "{e}");
assert!(check(&pack, Kind::Mod, None, None).is_err());
}
}
+68 -1
View File
@@ -6,12 +6,15 @@
//! `assets/` and `data/`; a folder without `Cargo.toml` is content only.
//! - `run [--game <horizon-client>] [-- <game args>]`: build, then play with
//! the mod; run `build` again and the game reloads it.
//! - `test [--debug] [--hmod <file>] [<name>]`: build, then run the mod's
//! `tests/*.toml` scripts in the sandbox, with no game.
//! - `check <file> [--json]`: what the registry checks of a submission
//! (`.hmod`, `.hpack`, resource pack `.zip`), with a trial run for a mod.
//! - `registry build|review|check|list`: the registry repository's CI.
use horizon_mods::{
Capability, Content, Manifest, Package,
manifest::{MANIFEST, component_imports, componentize},
testing::{Script, TestGame},
};
mod check;
mod registry;
@@ -36,9 +39,10 @@ fn main() -> ExitCode {
println!("Built {}", p.display());
}),
Some("run") => run(&args[1..]),
Some("test") => test(&args[1..]),
Some("check") => check(&args[1..]),
Some("registry") => registry::main(&args[1..]),
_ => Err("usage: cargo horizon-mod new <path> [--template code|content] | build [--debug] | run [--game <horizon-client>] [-- <game args>] | check <file> [--kind <kind>] [--key <public key> --signature <file.minisig>] [--json] | registry build|review|check|list".into()),
_ => Err("usage: cargo horizon-mod new <path> [--template code|content] | build [--debug] | run [--game <horizon-client>] [-- <game args>] | test [--debug] [--hmod <file>] [<name>] | check <file> [--kind <kind>] [--key <public key> --signature <file.minisig>] [--json] | registry build|review|check|list".into()),
};
match result {
Ok(()) => ExitCode::SUCCESS,
@@ -97,6 +101,10 @@ fn new(args: &[String]) -> Result<(), String> {
(MANIFEST, include_str!("../template/horizon-mod.toml")),
("src/lib.rs", include_str!("../template/src/lib.rs")),
(".gitignore", include_str!("../template/gitignore")),
(
"tests/hello.toml",
include_str!("../template/tests/hello.toml"),
),
];
// A block copying a vanilla one, with its model, name, loot, recipe and tag.
let content = [
@@ -270,6 +278,63 @@ fn check(args: &[String]) -> Result<(), String> {
Ok(())
}
/// `test`: every `tests/*.toml` script (those whose name holds `<name>`)
/// against the built mod, or the `.hmod` given with `--hmod`.
fn test(args: &[String]) -> Result<(), String> {
let hmod = match flag(args, "--hmod") {
Some(p) => PathBuf::from(p),
None => build(!args.iter().any(|a| a == "--debug"))?,
};
let filter = args
.iter()
.enumerate()
.find(|(i, a)| !a.starts_with("--") && (*i == 0 || args[i - 1] != "--hmod"))
.map(|(_, a)| a.as_str());
let mut scripts: Vec<PathBuf> = std::fs::read_dir("tests")
.map_err(|e| {
format!(
"tests/: {e} (a mod's tests are tests/<name>.toml: docs/mods.md, \"Testing a mod\")"
)
})?
.filter_map(|e| Some(e.ok()?.path()))
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
.filter(|p| filter.is_none_or(|f| p.to_string_lossy().contains(f)))
.collect();
scripts.sort();
if scripts.is_empty() {
return Err("no tests/*.toml to run".into());
}
println!(
"running {} scripts against {}",
scripts.len(),
hmod.display()
);
let mut failed = 0;
for path in &scripts {
let result = std::fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|text| Script::parse(&text))
.and_then(|script| {
let mut game = TestGame::load(&hmod)?;
script.run(&mut game)?;
Ok(script.steps.len())
});
match result {
Ok(steps) => println!("test {} ... ok ({steps} steps)", path.display()),
Err(e) => {
failed += 1;
println!("test {} ... FAILED\n {e}", path.display());
}
}
}
let passed = scripts.len() - failed;
if failed > 0 {
return Err(format!("{failed} failed, {passed} passed"));
}
println!("test result: ok. {passed} passed");
Ok(())
}
fn run(args: &[String]) -> Result<(), String> {
let path = build(true)?;
let game = flag(args, "--game")
@@ -312,6 +377,8 @@ mod tests {
);
let cargo = std::fs::read_to_string(path.join("Cargo.toml")).unwrap();
assert!(cargo.contains("name = \"my-mod\"") && cargo.contains(SDK_GIT));
let script = std::fs::read_to_string(path.join("tests/hello.toml")).unwrap();
assert_eq!(Script::parse(&script).unwrap().steps.len(), 3);
assert!(
new(&[path.display().to_string()]).is_err(),
"never overwrites"
@@ -0,0 +1,14 @@
# `cargo horizon-mod test` runs every tests/*.toml against the built mod, with no game:
# steps happen in order, and `expect` checks what the mod showed during the step.
# Every key: docs/mods.md, "Testing a mod".
[[step]]
expect.commands = ["hello"]
[[step]]
command = "hello world"
expect.chat = ["Hello world! (1 so far)"]
[[step]]
command = "hello again"
expect.chat = ["Hello again! (2 so far)"]
+4 -1
View File
@@ -12,16 +12,19 @@ horizon-assets = { path = "../horizon-assets" }
horizon-core = { path = "../horizon-core" }
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
horizon-threads = { path = "../horizon-threads" }
horizon-hdr = { path = "../horizon-hdr" }
horizon-world = { path = "../horizon-world" }
horizon-protocol = { path = "../horizon-protocol" }
# server.properties, eula.txt and the user lists, shared with horizon-server.
horizon-server-files = { path = "../horizon-server-files" }
# Shader packs: reading them and turning their GLSL into naga modules.
horizon-shaders = { path = "../horizon-shaders" }
# Horizon's own shader packs: the format, the stages and the check (docs/shaders.md).
horizon-shader-api = { path = "../horizon-shader-api" }
horizon-friends = { path = "../horizon-friends" }
# Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md).
# Their runtime is the `mods` feature.
horizon-mods = { path = "../horizon-mods", default-features = false }
horizon-mods = { path = "../horizon-mods", default-features = false, features = ["index"] }
wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl", "naga-ir"] }
winit = "0.30.13"
pollster = "0.4"
@@ -367,6 +367,7 @@ pub fn main() -> Result<()> {
lid: &|_| open,
sign: &|_| sign.as_ref(),
banner: &|_| layers.clone(),
skull: &|_| None,
glyph: &|c| atlas.glyph_cell(c),
};
let mut verts = Vec::new();
@@ -7,7 +7,7 @@
//! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT
use crate::pack_screen_fixture;
use horizon_client::{
chat::{ChatAction, ChatScreen, Commands},
chat::{ChatAbilities, ChatAction, ChatScreen, ChatVisibility, Commands},
command::vanilla,
hud::HudAtlas,
lang,
@@ -53,6 +53,7 @@ pub fn main() -> horizon_client::Result<()> {
history.len(),
w,
h,
ChatAbilities::new(ChatVisibility::Full),
);
screen.auto_suggestions = case["autoSuggest"] == true;
let mut closed = false;
@@ -0,0 +1,89 @@
use horizon_client::{
Result,
cushion::{self, World},
};
use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
use serde_json::Value;
use std::{
collections::HashMap,
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
};
struct Cell {
outline: VoxelShape,
collision: VoxelShape,
suffocating: bool,
}
struct Fixture(HashMap<[i32; 3], Cell>);
impl World for Fixture {
fn outline_bounds(&self, p: [i32; 3]) -> Option<Aabb> {
self.0
.get(&p)?
.outline
.bounds()
.map(|b| b.move_by(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64)))
}
fn collision_shapes(&self, _: Aabb) -> Vec<VoxelShape> {
self.0
.iter()
.map(|(p, c)| {
c.collision
.moved(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64))
})
.collect()
}
fn suffocating(&self, p: [i32; 3]) -> bool {
self.0.get(&p).is_some_and(|c| c.suffocating)
}
}
fn shape(value: &Value) -> Result<VoxelShape> {
let mut shape = VoxelShape::empty();
for b in value.as_array().unwrap() {
let f = |i: usize| b[i].as_f64().unwrap();
shape = shape.join(
&VoxelShape::from_box(Aabb::new(
Vec3::new(f(0), f(1), f(2)),
Vec3::new(f(3), f(4), f(5)),
))?,
ShapeOp::OR,
)?;
}
Ok(shape)
}
pub fn main() -> Result<()> {
let args: Vec<_> = crate::args().collect();
let mut out = BufWriter::new(File::create(&args[2])?);
for line in BufReader::new(File::open(&args[1])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let mut world = Fixture(HashMap::new());
for c in row["cells"].as_array().unwrap() {
let p = std::array::from_fn(|i| c[i].as_i64().unwrap() as i32);
world.0.insert(
p,
Cell {
outline: shape(&c[3])?,
collision: shape(&c[4])?,
suffocating: c[5].as_bool().unwrap(),
},
);
}
let p = &row["pos"];
let (x, y, z) = (
p[0].as_f64().unwrap(),
p[1].as_f64().unwrap(),
p[2].as_f64().unwrap(),
);
let bounds = Aabb::new(
Vec3::new(x - 0.5, y, z - 0.5),
Vec3::new(x + 0.5, y + 0.25, z + 0.5),
);
writeln!(
out,
"{} {}",
cushion::can_place(&world, bounds),
cushion::survives(&world, bounds)
)?;
}
Ok(())
}
@@ -9,7 +9,7 @@ use horizon_client::mesher::Vertex;
use horizon_client::mobs::{
Mob, MobData, MobTypes, Part, Species, allay,
anim::{self, Poses, State},
aquatic, body_anim as b_anim, equine, guardian,
aquatic, bat, body_anim as b_anim, equine, guardian,
keyframes::AnimationState,
render, shulker, sniffer, species, tame,
};
@@ -108,6 +108,22 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
match species {
Species::Bat => {
mob.extra.flag = flag("isResting");
mob.anim.states[0].started = case["flyAnimationState"].as_f64().map(|v| v as f32);
mob.anim.states[1].started = case["restAnimationState"].as_f64().map(|v| v as f32);
if let Some(ticks) = case["@batTicks"].as_array() {
for (i, flags) in ticks.iter().enumerate() {
mob.age = i as u32 + 1;
bat::set_resting(mob, flags.as_i64().unwrap_or(0) & 1 != 0);
if flag("@batInFrame") {
bat::tick(mob);
} else {
bat::setup_animation_states(mob);
}
}
}
}
Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32,
Species::Guardian | Species::ElderGuardian => {
mob.anim.v[guardian::TAIL] = num("tailAnimation");
@@ -377,7 +393,7 @@ pub fn main() -> horizon_client::Result<()> {
mob.extra.age = -24000;
}
mob.age = f("ageInTicks") as u32;
let state = State {
let mut state = State {
pos: f("walkAnimationPos"),
speed: f("walkAnimationSpeed"),
age: f("ageInTicks"),
@@ -389,6 +405,20 @@ pub fn main() -> horizon_client::Result<()> {
};
let mut poses = Poses::new(&model);
entity_state(&mut mob, def.species, case);
if let Some(ticks) = case["@walkTicks"].as_array() {
for speed in ticks {
mob.previous_limb_speed = mob.limb_speed;
mob.limb_speed += (speed.as_f64().unwrap() as f32 - mob.limb_speed) * 0.4;
mob.limb_position += mob.limb_speed;
}
if !case["@alive"].as_bool().unwrap() {
mob.health = 0.0;
}
let extracted = anim::state(&mob, f("@partial"));
state.pos = extracted.pos;
state.speed = extracted.speed;
}
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
let started = |k: &str| AnimationState {
@@ -456,14 +486,6 @@ pub fn main() -> horizon_client::Result<()> {
roll_amount: num("rollAmount"),
},
),
Species::Bat => b_anim::bat(
p,
s,
flag("isResting"),
&started("flyAnimationState"),
&started("restAnimationState"),
&animations,
),
Species::Armadillo => b_anim::armadillo(
p,
s,
@@ -590,7 +612,11 @@ pub fn main() -> horizon_client::Result<()> {
}
_ => anim::setup(&mob, s, p, &animations),
}
out.push_str(&format!("{}\n", emit(&model, &mut poses, case, layer)));
let mut result = emit(&model, &mut poses, case, layer);
if case["@walkTicks"].is_array() {
result["walk"] = json!([state.pos, state.speed]);
}
out.push_str(&format!("{result}\n"));
}
fs::write(&args[2], out)?;
Ok(())
@@ -319,6 +319,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
atlas,
comp(&m["text"]),
indicator,
horizon_client::chat::ChatSource::Client,
m["at"].as_u64().unwrap_or(0),
false,
);
@@ -28,6 +28,7 @@ mod cloud_fixture;
mod command_parse_fixture;
mod container_screen_probe;
mod creative_search_fixture;
mod cushion_placement_probe;
mod emitter_particles_probe;
mod enchanting_fixture;
mod entity_anim_fixture;
@@ -107,6 +108,7 @@ probes! {
block_transform_fixture,
breaking_fixture,
camera_probe,
cushion_placement_probe,
cauldron_fixture,
chat_screen_fixture,
cloud_fixture,
@@ -49,6 +49,7 @@ struct Scenario {
name: String,
ticks: i32,
time: i64,
difficulty: u8,
rain: bool,
thunder: bool,
origin: [i32; 2],
@@ -85,11 +86,13 @@ fn parse(text: &str) -> Vec<Scenario> {
"scenario" => {
s.name = f[1].to_owned();
s.time = 6000;
s.difficulty = 2;
for kv in &f[2..] {
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
match k {
"ticks" => s.ticks = v.parse().unwrap(),
"time" => s.time = v.parse().unwrap(),
"difficulty" => s.difficulty = v.parse().unwrap(),
"rain" => s.rain = true,
"thunder" => s.thunder = true,
"levelseed" => {}
@@ -598,6 +601,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool, now: i6
let _ = writeln!(out, " removed {reason}");
return;
}
let _ = write!(out, "\tleashed {}", u8::from(m.extra.leash.is_some()));
let p = m.position;
let v = m.velocity;
let _ = write!(
@@ -953,6 +957,10 @@ pub fn main() -> horizon_client::Result<()> {
for flag in &spec.flags {
match flag.as_str() {
"persistent" => m.persistent = true,
"named" => {
m.custom_name = Some("Peaceful regression".into());
m.persistent = true;
}
"ridden" => {
m.extra.head = Some("minecraft:red_harness".into());
m.rider = Some(horizon_client::mobs::equine::Rider::default());
@@ -977,6 +985,7 @@ pub fn main() -> horizon_client::Result<()> {
}
// Set once the brain exists (below).
x if x.starts_with("cooldown=") => {}
"dead" => m.health = 0.0,
"leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player),
x if x.starts_with("leashto=") => {
let n: u32 = x[8..].parse().unwrap();
@@ -1088,7 +1097,7 @@ pub fn main() -> horizon_client::Result<()> {
block_tags: &items.block_tags,
biomes: &biomes,
mob_griefing: true,
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0),
end: false,
world_seed: 0,
// FlatLevelSource.getSeaLevel.
@@ -1097,6 +1106,7 @@ pub fn main() -> horizon_client::Result<()> {
}
};
}
let mut dropped_leads = 0;
for t in 1..=s.ticks {
world.game_time += 1;
if s.daycycle {
@@ -1208,6 +1218,16 @@ pub fn main() -> horizon_client::Result<()> {
if !alive {
m.removed = true;
}
// Apply the same detach/drop event as Game::break_leash.
for event in &events[from..] {
if let MobEvent::LeashBreak { mob, drop, .. } = event
&& let Some(m) = mobs.iter_mut().find(|m| m.id == *mob)
&& horizon_client::mobs::leash::remove(m).is_some()
&& *drop
{
dropped_leads += 1;
}
}
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
villager_events(
&mut mobs,
@@ -1427,6 +1447,9 @@ pub fn main() -> horizon_client::Result<()> {
world.game_time,
);
}
if s.name.starts_with("leash_death_") {
let _ = writeln!(out, "{t} leads {dropped_leads}");
}
for e in &events {
if let MobEvent::Sound(name, _, volume, pitch) = e {
let _ = writeln!(
@@ -7,7 +7,7 @@ use horizon_client::{
biome::{BiomeInfo, Biomes, GrassModifier},
blocks::BlockFacts,
chunk::{Chunk, Light, MIN_Y, index},
mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
mesher::{EMISSION_BITS, MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
models,
};
use horizon_core::biome::BiomeZoom;
@@ -161,7 +161,15 @@ fn scene(
.iter()
.map(|v| {
let ([x, y, z], [u, w]) = (v.pos, v.uv());
json!([x, y, z, u, w, argb(v.color), light_coords(v.light)])
json!([
x,
y,
z,
u,
w,
argb(v.color | EMISSION_BITS),
light_coords(v.light)
])
})
.collect();
quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices}));
+74 -3
View File
@@ -58,7 +58,10 @@ enum Animate {
BubbleColumn {
drag: bool,
},
Fire,
/// `BaseFireBlock` (`SoulFireBlock.canBurn` is always true).
Fire {
soul: bool,
},
/// An active sculk sensor.
SculkSensor,
/// Potent sulfur that is not dry.
@@ -140,7 +143,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
"bubble_column" => Animate::BubbleColumn {
drag: prop("drag").as_deref() == Some("true"),
},
"fire" | "soul_fire" => Animate::Fire,
"fire" => Animate::Fire { soul: false },
"soul_fire" => Animate::Fire { soul: true },
"dried_ghast" => Animate::DriedGhast {
waterlogged: prop("waterlogged").as_deref() == Some("true"),
},
@@ -190,6 +194,8 @@ pub struct AnimateTables {
power_transmitter: Vec<bool>,
/// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil).
dried_ghast_sounds: Vec<bool>,
/// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged).
burnable: Vec<bool>,
/// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`).
ambient: Vec<Vec<(T, f32)>>,
}
@@ -220,6 +226,21 @@ impl AnimateTables {
})
.collect()
};
let behaviour: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("block-behaviours.json"))?)?;
let ignite_odds = behaviour["fire"]["igniteOdds"].as_object();
let burnable = (0..registry.len() as u32)
.map(|id| {
// FireBlock.getIgniteOdds: a waterlogged state never burns.
registry.state(BlockStateId(id)).is_some_and(|s| {
s.properties.get("waterlogged").map(String::as_str) != Some("true")
&& ignite_odds
.and_then(|m| m.get(s.name.as_str()))
.and_then(serde_json::Value::as_i64)
.is_some_and(|odds| odds > 0)
})
})
.collect();
let mut ambient = vec![Vec::new(); biomes.list.len()];
for (name, &id) in &biomes.index {
let path = root.join(format!(
@@ -248,6 +269,7 @@ impl AnimateTables {
power_provider: by_state("minecraft:enchantment_power_provider"),
power_transmitter: by_state("minecraft:enchantment_power_transmitter"),
dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"),
burnable,
ambient,
})
}
@@ -1103,7 +1125,7 @@ fn block_animate_tick(
}
}
}
Animate::Fire => {
Animate::Fire { soul } => {
let r = engine.random();
if next_int(r, 24) == 0 {
let (volume, pitch) = (1.0 + r.next_float(), r.next_float() * 0.7 + 0.3);
@@ -1115,6 +1137,55 @@ fn block_animate_tick(
pitch,
);
}
// BaseFireBlock.animateTick: three large smoke above the fire, or
// two at each burnable neighbour's face when nothing burnable or
// sturdy supports it (SoulFireBlock.canBurn is always true).
let can_burn = |p: [i32; 3]| {
soul || tables
.burnable
.get(ctx.state(p).0 as usize)
.copied()
.unwrap_or(false)
};
let below = [pos[0], pos[1] - 1, pos[2]];
let sturdy = ctx.facts.get(ctx.state(below)).sturdy_full & (1 << 1) != 0;
if !can_burn(below) && !sturdy {
// (neighbour, coordinate axis, face at the axis' high end): the
// west, east, north, south and above faces, in vanilla order.
for (at, axis, high) in [
([pos[0] - 1, pos[1], pos[2]], 0usize, false),
([pos[0] + 1, pos[1], pos[2]], 0, true),
([pos[0], pos[1], pos[2] - 1], 2, false),
([pos[0], pos[1], pos[2] + 1], 2, true),
([pos[0], pos[1] + 1, pos[2]], 1, true),
] {
if !can_burn(at) {
continue;
}
for _ in 0..2 {
let r = engine.random();
let d = [r.next_double(), r.next_double(), r.next_double()];
let mut p = [fx + d[0], fy + d[1], fz + d[2]];
// The face coordinate hugs the edge: `* 0.1F` (float).
p[axis] = if high {
f64::from(pos[axis]) + 1.0 - d[axis] * f64::from(0.1f32)
} else {
f64::from(pos[axis]) + d[axis] * f64::from(0.1f32)
};
add(engine, T::LargeSmoke, p, [0.0; 3]);
}
}
} else {
for _ in 0..3 {
let r = engine.random();
let p = [
fx + r.next_double(),
fy + r.next_double() * 0.5 + 0.5,
fz + r.next_double(),
];
add(engine, T::LargeSmoke, p, [0.0; 3]);
}
}
}
}
}
+31
View File
@@ -323,10 +323,15 @@ const QUIET_MESHES_PER_S: f64 = 100.0;
/// happened (`tools/perf_bench.py`'s `wait_loaded`). With `status.streaming`, the sections are
/// drawn once no stage has held work for half a second: blocks changing after the load (fluids
/// settling, random ticks) only remesh in bursts. Without it, meshing has to go quiet.
///
/// Right after a teleport (and at spawn) the game reports nothing queued and steady counts for over
/// a second before it starts loading: the counts must change once, or stay full for 5 s, and the
/// resident chunks reach [`view_chunks`], before "steady" means loaded.
fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result<Instant, String> {
let deadline = Instant::now() + LOAD_LIMIT;
let (mut last, mut changed, mut meshing) = (None, Instant::now(), Instant::now());
let mut previous: Option<(Instant, f64)> = None;
let (mut first, mut moved, began) = (None, false, Instant::now());
while Instant::now() < deadline {
let s = control.status();
let now = Instant::now();
@@ -339,6 +344,19 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result<Insta
(last, changed, previous, meshing) = (None, now, None, now);
} else {
let counts = (s["chunks"].as_u64(), s["generated_chunks"].as_u64());
let resident = counts.0.unwrap_or(0);
let min_chunks = view_chunks(s["render_distance"].as_u64().unwrap_or(0));
let first = *first.get_or_insert(counts);
moved = moved
|| counts != first
|| (min_chunks > 0
&& resident >= min_chunks
&& now - began > Duration::from_secs(5));
if min_chunks > 0 && (!moved || resident < min_chunks) {
(last, changed, previous, meshing) = (None, now, None, now);
thread::sleep(Duration::from_millis(50));
continue;
}
if last != Some(counts) {
(last, changed) = (Some(counts), now);
}
@@ -370,6 +388,12 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result<Insta
Err(format!("not loaded after {} s", LOAD_LIMIT.as_secs()))
}
/// 80% of the view circle (pi x RD^2): the game keeps 637 columns at RD 12 and 3725 at RD 32
/// (`tools/perf_bench.py`'s `view_chunks`).
fn view_chunks(distance: u64) -> u64 {
(0.8 * std::f64::consts::PI * (distance * distance) as f64) as u64
}
/// Vanilla's yaw facing from `start` to `end`.
fn yaw(start: [f64; 3], end: [f64; 3]) -> f64 {
(-(end[0] - start[0])).atan2(end[2] - start[2]).to_degrees()
@@ -420,6 +444,13 @@ mod tests {
assert!(scenes("nether").is_none());
}
#[test]
fn view_chunks_matches_perf_bench() {
assert_eq!(view_chunks(12), 361);
assert_eq!(view_chunks(32), 2573);
assert_eq!(view_chunks(0), 0);
}
#[test]
fn yaw_matches_vanilla() {
// South (+Z) is 0, west (-X) 90, east (+X) -90.
@@ -143,6 +143,7 @@ const PAGES: Ty = Ty::Enum(&[
"font",
"packs",
"mods",
"shader-packs",
"graphics",
"graphics-advanced",
"extras",
@@ -610,12 +610,17 @@ mod tests {
#[test]
fn unreachable_games_fail_with_status_3() {
let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None);
let home =
std::env::temp_dir().join(format!("horizon-ctl-unreachable-{}", std::process::id()));
std::fs::create_dir_all(&home).unwrap();
let mut s = Session::new(home.join("nobody.sock"), None);
s.home = home.clone();
let f = s.run(&["state".to_owned()]).unwrap_err();
assert_eq!(f.status, UNREACHABLE);
assert_eq!(f.reply["kind"], "connection");
let f = s.run(&["sleep".to_owned(), "x".to_owned()]).unwrap_err();
assert_eq!(f.status, USAGE);
std::fs::remove_dir_all(home).unwrap();
}
#[test]
+18 -7
View File
@@ -664,7 +664,9 @@ pub fn canonical(tag: &Tag) -> Option<Tag> {
}
"minecraft:trial_spawner" => {
// `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional
// and defaulted by vanilla; they are kept as loaded.
// and defaulted by vanilla; they are kept as loaded. No `spawn_data` is
// added: an absent one loads as Optional.empty and is not stored, and
// an empty entity would keep the spawner from ever picking a mob.
if let Tag::Compound(c) = tag {
for (k, v) in c {
let key = k.to_string_lossy();
@@ -676,12 +678,6 @@ pub fn canonical(tag: &Tag) -> Option<Tag> {
}
}
}
if !f.out.contains_key(&"spawn_data".into()) {
f.put(
"spawn_data",
Tag::compound([("entity", Tag::Compound(Compound::new()))]),
);
}
}
"minecraft:vault" => {
// `VaultConfig.DEFAULT` (when the config is absent): the trial key and the
@@ -827,6 +823,21 @@ mod tests {
canonical(&snbt(s)).expect("known type")
}
#[test]
fn a_trial_spawner_without_spawn_data_saves_none() {
let fresh = canon(
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#,
);
assert_eq!(fresh.get("spawn_data"), None);
let picked = canon(
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#,
);
assert_eq!(
picked.get("spawn_data"),
Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#))
);
}
#[test]
fn every_type_has_defaults() {
for id in TYPES.iter().chain(NEWEST.iter()) {
@@ -558,12 +558,11 @@ fn frac(x: f32) -> f32 {
/// `StringSplitter.splitLines(...).get(0)` for plain text: the first line,
/// wrapped at the last space that fits or mid-word when none does.
fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> String {
let chars: Vec<char> = line.chars().collect();
let mut width = 0.0;
let mut last_space = None;
for (i, &c) in chars.iter().enumerate() {
for (i, c) in line.char_indices() {
if c == '\n' {
return chars[..i].iter().collect();
return line[..i].to_owned();
}
if c == ' ' {
last_space = Some(i);
@@ -572,9 +571,11 @@ fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> Stri
if width > max_width {
let end = match last_space {
Some(s) if s > 0 => s,
_ => i.max(1),
_ if i > 0 => i,
// The first char alone is too wide: take that one char.
_ => c.len_utf8(),
};
return chars[..end].iter().collect();
return line[..end].to_owned();
}
}
line.to_owned()
@@ -730,6 +731,10 @@ pub struct Scene<'a> {
pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>,
/// Banner layers at a position: pattern texture and RGB tint, bottom first.
pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>,
/// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer`
/// profile → skin): a downloaded `skins/<sha1>` slot or the profile's
/// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve).
pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>,
/// Font glyph cell (none for blank glyphs such as the space) and advance.
pub glyph: &'a dyn Fn(char) -> (Option<Rect>, f32),
}
@@ -1279,6 +1284,13 @@ impl BlockEntityRenderer {
SkullType::Piglin => ("piglin_head", "entity/piglin/piglin"),
SkullType::Player => ("player_head", "entity/player/slim/steve"),
};
// SkullBlockRenderer.getRenderType: the profile's skin when it
// resolves, `SKIN_BY_TYPE` (steve) otherwise.
let texture = if *kind == SkullType::Player {
(scene.skull)(pos).unwrap_or(texture)
} else {
texture
};
let (Some(model), Some(paint)) =
(self.models.get(model), paint(texture, 0xFFFFFF, packed))
else {
@@ -1886,6 +1898,7 @@ mod tests {
lid: &|_| 0.0,
sign: &|_| None,
banner: &|_| Vec::new(),
skull: &|_| None,
glyph: &|_| (None, 0.0),
};
// Compare the cached world path with the original model renderer,
@@ -2086,4 +2099,13 @@ mod tests {
assert_eq!(out[1].pos, [2.0, 0.0, 0.0]);
assert_eq!(out[2].uv, [0.5, 0.5]);
}
#[test]
fn first_line_wraps_on_bytes_without_splitting_a_char() {
let advance = |c: char| if c == ' ' { 4.0 } else { 6.0 };
assert_eq!(first_line("ab cd ef", 13.0, &advance), "ab");
assert_eq!(first_line("abcdef", 13.0, &advance), "ab");
assert_eq!(first_line("\u{6771}", 3.0, &advance), "\u{6771}");
assert_eq!(first_line("ab\ncd", 100.0, &advance), "ab");
}
}
+203
View File
@@ -166,6 +166,38 @@ impl Contents {
Some(stack)
}
/// The stacks inside, in display order (the first is the next out).
pub fn items(&self) -> &[ItemStack] {
&self.items
}
/// `getNumberOfItemsToShow`: a full grid shows 11 and a `+N`, so the last
/// row keeps its fourth cell for the count.
pub fn shown_count(&self) -> usize {
let count = self.items.len();
let available: usize = if count > 12 { 11 } else { 12 };
let on_last_row = count % 4;
let empty = if on_last_row == 0 { 0 } else { 4 - on_last_row };
count.min(available.saturating_sub(empty))
}
/// The items the tooltip shows, and how many sit beyond them.
pub fn shown(&self) -> (&[ItemStack], u32) {
let n = self.shown_count();
let hidden = self.items[n..].iter().map(|s| s.count).sum();
(&self.items[..n], hidden)
}
/// The `Fraction` weight as the float the progress bar reads.
pub fn weight_fraction(&self) -> f32 {
self.weight.n as f32 / self.weight.d as f32
}
/// `Fraction.ONE`: a full bundle draws the full bar and says so.
pub fn is_full(&self) -> bool {
self.weight.n >= self.weight.d
}
/// `toImmutable`, written back into the bundle's component.
pub fn store(self, bundle: &mut ItemStack) {
bundle.data_mut().bundle_contents = self.items;
@@ -190,3 +222,174 @@ mod tests {
assert_eq!(over.how_many(Weight::new(1, 64)), 0);
}
}
// ------------------------------------------------------------- the tooltip
/// `ClientBundleTooltip`'s geometry, relative to the tooltip box's top-left:
/// the 96 pixel column of a 4 wide slot grid and the progress bar under it.
#[derive(Clone, Debug, PartialEq)]
pub struct TooltipLayout {
/// The component's own width (96) and height, the text's excluded.
pub width: f32,
pub height: f32,
/// Each slot's top-left and the stack in it, in reading order.
pub slots: Vec<([f32; 2], ItemStack)>,
/// The `+N` of the items past the grid: its top-left and the count.
pub overflow: Option<([f32; 2], u32)>,
/// The progress bar's top-left, its fill's width out of 94, and whether
/// the weight fills it (the full sprite).
pub bar: [f32; 2],
pub fill: f32,
pub full: bool,
/// `item.minecraft.bundle.empty` / `.full`, centred over the bar.
pub label: Option<&'static str>,
/// An empty bundle's description, wrapped at `width` from here.
pub empty_description: Option<[f32; 2]>,
}
/// The tooltip of a bundle's contents (`ClientBundleTooltip`), or None when
/// the stack is not a bundle. `x`/`y` are the box's top-left, `box_width` the
/// tooltip's width, which the component is centred in.
pub fn tooltip_layout(
items: &Items,
stack: &ItemStack,
x: f32,
y: f32,
box_width: f32,
) -> Option<TooltipLayout> {
let contents = Contents::of(items, stack)?;
let offset = ((box_width - 96.0) / 2.0).floor();
if contents.items().is_empty() {
// The description takes the top; the bar follows it.
let description_height = 9.0 * 2.0;
return Some(TooltipLayout {
width: 96.0,
height: description_height + 13.0 + 8.0,
slots: Vec::new(),
overflow: None,
bar: [x + offset, y + description_height + 4.0],
fill: 0.0,
full: false,
label: Some("item.minecraft.bundle.empty"),
empty_description: Some([x + offset, y]),
});
}
let (shown, hidden) = contents.shown();
// `gridSizeY` counts `slotCount()` (at most twelve), not the slots the
// overflow count leaves room for.
let rows = contents.items().len().min(12).div_ceil(4).max(1);
let grid_height = rows as f32 * 24.0;
let x_start = x + offset + 96.0;
let y_start = y + grid_height;
let mut slots = Vec::with_capacity(shown.len());
let mut overflow = None;
// Rows fill bottom-up and columns right-to-left, as vanilla draws them.
let mut slot = 0;
for row in 1..=rows {
for column in 1..=4 {
let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
if hidden > 0 && row == 1 && column == 1 {
overflow = Some((at, hidden));
} else if let Some(stack) = shown.get(slot) {
slots.push((at, stack.clone()));
slot += 1;
}
}
}
let weight = contents.weight_fraction();
Some(TooltipLayout {
width: 96.0,
height: grid_height + 13.0 + 8.0,
slots,
overflow,
bar: [x + offset, y + grid_height + 4.0],
// `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
fill: (weight * 94.0).trunc().clamp(0.0, 94.0),
full: contents.is_full(),
label: if contents.is_full() {
Some("item.minecraft.bundle.full")
} else {
None
},
empty_description: None,
})
}
#[cfg(test)]
mod tooltip_tests {
use super::*;
/// The prepared resources, when they are on this machine: the tooltip
/// asks the item registry whether a stack is a bundle.
fn items() -> Option<Items> {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3");
if !root.join("items.json").exists() {
return None;
}
let assets = crate::assets::Assets::load(&root).ok()?;
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).ok()?;
Items::load(&root, assets.registry, &facts).ok()
}
fn bundle_with(counts: &[(&str, u32)]) -> ItemStack {
let mut bundle = ItemStack::new("minecraft:bundle", 1);
bundle.data_mut().bundle_contents = counts
.iter()
.map(|(item, n)| ItemStack::new(item, *n))
.collect();
bundle
}
#[test]
fn a_grid_shows_twelve_stacks_and_counts_the_rest() {
let Some(items) = items() else { return };
let twelve: Vec<(&str, u32)> = (0..12).map(|_| ("minecraft:stone", 1)).collect();
let layout = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 96.0).unwrap();
assert_eq!(layout.slots.len(), 12);
assert_eq!(layout.overflow, None);
assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
// Rows fill bottom-up and columns right-to-left: the first item is in
// the bottom-right cell, the twelfth in the top-left.
assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
assert_eq!(layout.slots[11].0, [0.0, 0.0]);
// A wider tooltip centres the 96 pixel column in it.
let centred = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 120.0).unwrap();
assert_eq!(centred.slots[0].0[0], 12.0 + 96.0 - 24.0);
// Thirteen stacks: `getNumberOfItemsToShow` leaves the last row room
// for the count, so 8 slots show and `+6` (four stones and two dirt)
// takes the first cell.
let mut counts = twelve;
counts.push(("minecraft:dirt", 2));
let layout = tooltip_layout(&items, &bundle_with(&counts), 0.0, 0.0, 96.0).unwrap();
assert_eq!(layout.slots.len(), 8);
assert_eq!(layout.overflow, Some(([96.0 - 24.0, 48.0], 6)));
}
#[test]
fn the_bar_fills_with_the_weight_and_an_empty_bundle_explains_itself() {
let Some(items) = items() else { return };
let layout = tooltip_layout(&items, &bundle_with(&[]), 4.0, 8.0, 96.0).unwrap();
assert!(layout.slots.is_empty());
assert_eq!(layout.fill, 0.0);
assert_eq!(layout.label, Some("item.minecraft.bundle.empty"));
assert_eq!(layout.empty_description, Some([4.0, 8.0]));
assert_eq!(layout.bar, [4.0, 8.0 + 18.0 + 4.0]);
// A bundle holding one 64 stack is full: the whole bar, the full label.
let layout = tooltip_layout(
&items,
&bundle_with(&[("minecraft:stone", 64)]),
0.0,
0.0,
96.0,
)
.unwrap();
assert!(layout.full);
assert_eq!(layout.fill, 94.0);
assert_eq!(layout.label, Some("item.minecraft.bundle.full"));
// Something that is not a bundle has no component.
let dirt = ItemStack::new("minecraft:dirt", 1);
assert!(tooltip_layout(&items, &dirt, 0.0, 0.0, 96.0).is_none());
}
}
+34
View File
@@ -87,6 +87,19 @@ fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) {
}
}
/// `LayeredCauldronBlock.handleEntityOnFireInside`: a burning entity in a
/// water cauldron lowers it a level; a powder snow cauldron becomes a water
/// cauldron of its level first, then lowers.
pub fn extinguished(cauldron: &BlockState) -> BlockState {
if cauldron.name == "minecraft:powder_snow_cauldron" {
let mut water = cauldron.clone();
water.name = "minecraft:water_cauldron".into();
lowered(&water)
} else {
lowered(cauldron)
}
}
/// `LayeredCauldronBlock.lowerFillLevel`.
fn lowered(cauldron: &BlockState) -> BlockState {
let level: u8 = cauldron
@@ -296,3 +309,24 @@ pub fn interact(
_ => pass(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_burning_entity_lowers_water_and_melts_powder_snow() {
let water = |l| state("minecraft:water_cauldron", Some(l));
assert_eq!(extinguished(&water(3)), water(2));
assert_eq!(extinguished(&water(1)), state("minecraft:cauldron", None));
// Powder snow turns to water of its level, then lowers.
assert_eq!(
extinguished(&state("minecraft:powder_snow_cauldron", Some(3))),
water(2)
);
assert_eq!(
extinguished(&state("minecraft:powder_snow_cauldron", Some(1))),
state("minecraft:cauldron", None)
);
}
}
+167 -10
View File
@@ -19,6 +19,92 @@ mod tests;
/// GuiMessageTag.systemSinglePlayer's indicator colour.
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
/// `ChatVisiblity`: the Chat option's three values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChatVisibility {
Full,
System,
Hidden,
}
impl ChatVisibility {
/// Options.chatVisibility's saved value (0 full, 1 system, 2 hidden).
pub fn from_option(value: u8) -> Self {
match value {
0 => Self::Full,
1 => Self::System,
_ => Self::Hidden,
}
}
}
/// `ChatAbilities`: what the Chat option allows, as `Minecraft.computeChatAbilities`
/// derives it from the visibility alone (`ChatRestriction`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChatAbilities {
pub send_messages: bool,
pub send_commands: bool,
pub receive_player_messages: bool,
pub receive_system_messages: bool,
}
impl ChatAbilities {
/// `ChatRestriction.CHAT_AND_COMMANDS_DISABLED_BY_OPTIONS` (Hidden) takes
/// chat, commands, player messages and system messages;
/// `CHAT_DISABLED_BY_OPTIONS` (System) takes the chat and player messages.
pub fn new(visibility: ChatVisibility) -> Self {
match visibility {
ChatVisibility::Full => Self {
send_messages: true,
send_commands: true,
receive_player_messages: true,
receive_system_messages: true,
},
ChatVisibility::System => Self {
send_messages: false,
send_commands: true,
receive_player_messages: false,
receive_system_messages: true,
},
ChatVisibility::Hidden => Self {
send_messages: false,
send_commands: false,
receive_player_messages: false,
receive_system_messages: false,
},
}
}
/// `visibleMessagesFilter`: the client's own lines always show.
pub fn shows(&self, source: ChatSource) -> bool {
match source {
ChatSource::Player => self.receive_player_messages,
ChatSource::Server => self.receive_system_messages,
ChatSource::Client => true,
}
}
/// Whether the chat screen may send `input` (`hasAllowedInput`).
pub fn allows(&self, input: &str) -> bool {
if input.starts_with('/') {
self.send_commands
} else {
self.send_messages
}
}
}
impl Default for ChatAbilities {
fn default() -> Self {
Self::new(ChatVisibility::Full)
}
}
/// Where a chat line came from (`GuiMessageSource`): the visibility filters
/// player messages and the server's, while the client's own always show.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChatSource {
Player,
Server,
Client,
}
/// The chat options (doubles, as vanilla keeps them).
#[derive(Clone, Copy, Debug)]
pub struct ChatOptions {
@@ -71,6 +157,7 @@ struct Message {
added: u64,
content: Text,
indicator: Option<u32>,
source: ChatSource,
}
/// A wrapped line (`GuiMessage.Line`).
#[derive(Clone, Debug)]
@@ -105,6 +192,8 @@ pub struct Chat {
pub log: bool,
/// Messages added since the start, for the control socket's events.
pub received: u64,
/// The Chat option's `visibleMessageFilter` (`set_abilities`).
abilities: ChatAbilities,
}
impl Chat {
pub fn lines_per_page(&self, focused: bool) -> usize {
@@ -114,16 +203,32 @@ impl Chat {
fn max_width(&self) -> i32 {
(f64::from(self.options.width_px()) / self.options.scale).floor() as i32
}
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines.
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. A
/// message the Chat option hides is dropped, unlogged.
pub fn add(
&mut self,
atlas: &HudAtlas,
content: Text,
indicator: Option<u32>,
source: ChatSource,
ticks: u64,
focused: bool,
) {
// ChatComponent.logChatMessage: every message is in the log.
self.add_message(&atlas.font, content, indicator, source, ticks, focused);
}
fn add_message(
&mut self,
font: &crate::font::Font,
content: Text,
indicator: Option<u32>,
source: ChatSource,
ticks: u64,
focused: bool,
) {
if !self.abilities.shows(source) {
return;
}
// ChatComponent.logChatMessage: every message shown is in the log.
crate::logging::write_only(log::Level::Info, &format!("[CHAT] {}", content.plain()));
if self.log {
println!("[CHAT] {}", content.plain());
@@ -132,16 +237,17 @@ impl Chat {
added: ticks,
content,
indicator,
source,
};
self.add_lines(atlas, &message, focused);
self.add_lines(font, &message, focused);
self.messages.insert(0, message);
self.messages.truncate(100);
self.received += 1;
}
fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) {
fn add_lines(&mut self, font: &crate::font::Font, message: &Message, focused: bool) {
let width = self.max_width();
let content = self.displayed(&message.content);
for line in atlas.font.wrap_components(&content, width) {
for line in font.wrap_components(&content, width) {
if focused && self.scroll > 0 {
self.new_since_scroll = true;
self.scroll_by(1, focused);
@@ -167,16 +273,38 @@ impl Chat {
content.strip_legacy()
}
}
/// Re-wrap after a width or scale change (ChatComponent.rescaleChat).
/// Re-wrap after a width or scale change (ChatComponent.rescaleChat),
/// keeping only the messages the Chat option shows.
pub fn rescale(&mut self, atlas: &HudAtlas) {
self.rewrap(&atlas.font);
}
fn rewrap(&mut self, font: &crate::font::Font) {
self.scroll = 0;
self.new_since_scroll = false;
self.lines.clear();
let messages: Vec<Message> = self.messages.iter().rev().cloned().collect();
let messages: Vec<Message> = self
.messages
.iter()
.rev()
.filter(|m| self.abilities.shows(m.source))
.cloned()
.collect();
for m in &messages {
self.add_lines(atlas, m, false);
self.add_lines(font, m, false);
}
}
/// `ChatComponent.setVisibleMessageFilter`: the Chat option changed;
/// the messages it now hides leave the chat, those it shows again return.
pub fn set_abilities(&mut self, font: &crate::font::Font, abilities: ChatAbilities) {
if self.abilities != abilities {
self.abilities = abilities;
self.rewrap(font);
}
}
/// Whether a message from `source` would show (`visibleMessagesFilter`).
pub fn shows(&self, source: ChatSource) -> bool {
self.abilities.shows(source)
}
pub fn clear(&mut self) {
self.messages.clear();
self.lines.clear();
@@ -437,6 +565,8 @@ pub struct ChatScreen {
allow_suggestions: bool,
keep_suggestions: bool,
pub auto_suggestions: bool,
/// `CommandSuggestions.setRestrictions`: what the Chat option allows.
pub abilities: ChatAbilities,
}
/// Local completions waiting for the server's reply to request `id`.
struct Awaiting {
@@ -482,6 +612,7 @@ impl ChatScreen {
history_len: usize,
width: i32,
height: i32,
abilities: ChatAbilities,
) -> Self {
let mut input = TextField::new(4, height - 12, width - 4, 12);
input.max_length = 256;
@@ -505,6 +636,7 @@ impl ChatScreen {
allow_suggestions: false,
keep_suggestions: false,
auto_suggestions: true,
abilities,
};
s.update_command_info(m, c);
s
@@ -522,7 +654,8 @@ impl ChatScreen {
if (width, height) != (self.width, self.height) {
let value = self.input.value.clone();
let auto = self.auto_suggestions;
*self = Self::new(m, c, &value, self.history_pos, width, height);
let abilities = self.abilities;
*self = Self::new(m, c, &value, self.history_pos, width, height, abilities);
self.auto_suggestions = auto;
}
}
@@ -604,6 +737,14 @@ impl ChatScreen {
self.pending = Some((range.0, list));
self.usage_width = 0;
self.usage_position = 0;
// CommandSuggestions.updateCommandInfo: the Chat option may take
// the messages.
if !self.abilities.send_messages {
let line =
Text::translate("chat_screen.messages_not_allowed", &[]).with_color(text::RED);
self.usage_width = m.width(&line);
self.usage.push(line);
}
} else {
self.awaiting = None;
self.pending = None;
@@ -708,6 +849,15 @@ impl ChatScreen {
}
self.usage.extend(entries);
}
// CommandSuggestions.updateUsageInfo: the Chat option may take the
// commands, under the usage. (Vanilla also counts a command with a
// message argument, `/say hi`, as a message; Horizon's parse keeps no
// argument kinds, so only a bare message does.)
if !self.abilities.send_commands {
self.usage.push(
Text::translate("chat_screen.commands_not_allowed", &[]).with_color(text::RED),
);
}
self.usage_width = self.usage.iter().map(|u| m.width(u)).max().unwrap_or(0);
self.usage_position = if self.usage.is_empty() {
0
@@ -842,7 +992,14 @@ impl ChatScreen {
}
match key {
K::Escape => return ChatAction::Close,
K::Enter | K::NumpadEnter => return ChatAction::Submit(self.normalized()),
K::Enter | K::NumpadEnter => {
// ChatScreen.keyPressed: without `hasAllowedInput` the input
// stays, unsent, and the screen stays open.
if !self.abilities.allows(&self.input.value) {
return ChatAction::None;
}
return ChatAction::Submit(self.normalized());
}
K::ArrowUp => self.move_in_history(m, c, history, -1),
K::ArrowDown => self.move_in_history(m, c, history, 1),
_ => {
+145 -5
View File
@@ -2,6 +2,11 @@ use super::*;
use crate::{font::Font, hud::Rect};
use std::{collections::HashMap, path::Path};
/// The Chat option's default: no restriction.
fn full() -> ChatAbilities {
ChatAbilities::new(ChatVisibility::Full)
}
fn font() -> Font {
// The missing-glyph metrics let these tests run without game assets.
Font::load(
@@ -139,7 +144,7 @@ fn locate_coordinates_fill_chat_with_teleport_without_submitting() {
assert_eq!(link.component()["click_event"]["command"], expected);
let mut chat = Chat::default();
add(&mut chat, &font, Text::literal("Found at ").append(link));
let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360, full());
let x = 4.0 + f64::from(font.width("Found at "));
assert!(!screen.click(&m, &commands, x, 315.0));
let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else {
@@ -176,7 +181,15 @@ fn history_arrows_recall_messages_and_restore_the_draft() {
registries: &registries,
};
let history = vec!["first message".to_owned(), "latest message".to_owned()];
let mut screen = ChatScreen::new(&m, &commands, "unfinished draft", history.len(), 640, 360);
let mut screen = ChatScreen::new(
&m,
&commands,
"unfinished draft",
history.len(),
640,
360,
full(),
);
for (key, expected) in [
(ArrowUp, "latest message"),
(ArrowUp, "first message"),
@@ -213,7 +226,7 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() {
dispatcher,
registries: &registries,
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
screen.type_text(&m, &c, line);
screen
};
@@ -259,7 +272,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() {
let tab = |screen: &mut ChatScreen| {
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false);
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
screen.type_text(&m, &c, "/bossbar get pt");
let (request, sent) = screen.take_request().expect("the server is asked");
assert_eq!(sent, "/bossbar get pt");
@@ -281,7 +294,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() {
dispatcher: local,
registries: &registries,
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
screen.type_text(&m, &c, "/bossbar get pt");
assert_eq!(screen.take_request(), None);
}
@@ -327,3 +340,130 @@ fn a_server_component_keeps_its_click_and_hover_events() {
let past = 4.0 + f64::from(font.width("CLICK")) + 20.0;
assert!(chat.hover_at(&font, 360, past, 315.0).is_none());
}
/// `ChatVisiblity`: Commands Only keeps the chat out, Hidden takes the
/// commands too (`ChatAbilities`), and Enter sends nothing the option hides.
#[test]
fn the_chat_option_decides_what_may_be_sent() {
let font = font();
let m = Measure(&font);
let registries = Registries::default();
let c = Commands {
dispatcher: crate::command::vanilla::game_dispatcher(),
registries: &registries,
};
let enter = |screen: &mut ChatScreen| {
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Enter, false, false)
};
for (visibility, chat, command) in [
(ChatVisibility::Full, true, true),
(ChatVisibility::System, false, true),
(ChatVisibility::Hidden, false, false),
] {
let abilities = ChatAbilities::new(visibility);
assert_eq!(abilities.allows("hi"), chat, "{visibility:?}");
assert_eq!(abilities.allows("/time set day"), command, "{visibility:?}");
for (line, allowed) in [("hi", chat), ("/time set day", command)] {
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, abilities);
screen.type_text(&m, &c, line);
match enter(&mut screen) {
ChatAction::Submit(sent) => {
assert!(allowed, "{visibility:?} sent {sent}");
assert_eq!(sent, line);
}
ChatAction::None => assert!(!allowed, "{visibility:?} kept {line}"),
ChatAction::Close => panic!("Enter does not close the chat"),
}
}
}
}
/// The restriction the option sets is a usage line: red, under the input, for
/// a command the Chat option takes and for a message it takes.
#[test]
fn restricted_input_says_why_it_will_not_send() {
let font = font();
let m = Measure(&font);
let registries = Registries::default();
let c = Commands {
dispatcher: crate::command::vanilla::game_dispatcher(),
registries: &registries,
};
let usage = |visibility, line: &str| {
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, ChatAbilities::new(visibility));
screen.type_text(&m, &c, line);
screen.usage.iter().map(|t| t.plain()).collect::<Vec<_>>()
};
assert_eq!(usage(ChatVisibility::Full, "hi"), Vec::<String>::new());
// The font has no language files here, so the line is its key.
assert_eq!(
usage(ChatVisibility::System, "hi"),
["chat_screen.messages_not_allowed"]
);
// A command the option allows says nothing about the restriction.
assert!(
!usage(ChatVisibility::System, "/time set day")
.iter()
.any(|line| line == "chat_screen.commands_not_allowed")
);
assert!(
usage(ChatVisibility::Hidden, "/time set day")
.iter()
.any(|line| line == "chat_screen.commands_not_allowed")
);
}
/// `ChatComponent.setVisibleMessageFilter`: a message the Chat option hides
/// on arrival is dropped; one already in the chat leaves it while the option
/// hides its kind and comes back when it shows it again.
#[test]
fn the_chat_option_filters_the_lines_both_ways() {
let font = font();
let mut chat = Chat::default();
let says = |chat: &mut Chat, text: &str, source| {
chat.add_message(&font, Text::literal(text), None, source, 0, false);
};
let shown =
|chat: &Chat| -> Vec<String> { chat.lines.iter().map(|l| l.content.plain()).collect() };
says(&mut chat, "player", ChatSource::Player);
says(&mut chat, "server", ChatSource::Server);
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::System));
assert_eq!(shown(&chat), ["server"]);
says(&mut chat, "dropped", ChatSource::Player);
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Hidden));
says(&mut chat, "client", ChatSource::Client);
assert_eq!(shown(&chat), ["client"]);
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full));
assert_eq!(shown(&chat), ["client", "server", "player"]);
}
/// The in-frame LAN host's chat: a guest's line is a player message, so the
/// Chat option's player-message permission hides it at Commands Only and
/// Hidden; command feedback (`/list`, `/tp`) is a system message and stays
/// at Commands Only.
#[test]
fn a_guests_line_follows_the_player_message_permission() {
let font = font();
let shown = |visibility, source| {
let mut chat = Chat::default();
chat.set_abilities(&font, ChatAbilities::new(visibility));
chat.add_message(&font, Text::literal("line"), None, source, 0, false);
chat.messages.len()
};
for (visibility, player, system) in [
(ChatVisibility::Full, 1, 1),
(ChatVisibility::System, 0, 1),
(ChatVisibility::Hidden, 0, 0),
] {
assert_eq!(
shown(visibility, ChatSource::Player),
player,
"{visibility:?}"
);
assert_eq!(
shown(visibility, ChatSource::Server),
system,
"{visibility:?}"
);
}
}
+14
View File
@@ -24,6 +24,20 @@ pub fn block_strategy() -> Strategy {
Strategy::blocks(BLOCK_BITS.load(std::sync::atomic::Ordering::Relaxed))
}
/// Frees `columns` (`count` of them) on a short-lived thread of its own
/// when there are many: a teleport or a dimension change drops a few
/// thousand columns at once, and freeing their sections took the frame
/// 15-20 ms. A few are freed here.
pub fn free_columns<T: Send + 'static>(columns: T, count: usize) {
if count < 64 {
return;
}
// Should the thread not start, the closure drops `columns` here.
let _ = std::thread::Builder::new()
.name("Chunk freeing".into())
.spawn(move || drop(columns));
}
/// Sizes the block states' global palette for a registry of `states`.
pub fn set_block_states(states: usize) {
let bits = horizon_core::paletted::ceil_log2(states).max(16);
+5
View File
@@ -346,6 +346,11 @@ mod tests {
assert_eq!(filter_text(s, true), "abc\nde\u{80}");
assert_eq!(strip_formatting("§aRed§r §zx§"), "Red §zx§");
assert_eq!(helper_clipboard_contents("§lone\r\ntwo"), "one\ntwo");
// TextFieldHelper.getClipboardContents runs before insertText's filter.
assert_eq!(
filter_text(&helper_clipboard_contents("§aHello"), false),
"Hello"
);
}
struct Field {
+18
View File
@@ -92,6 +92,13 @@ impl<W: BlockCollisionWorld> BlockCollisionWorld for EntityCollisions<'_, W> {
) -> std::result::Result<bool, Self::Error> {
self.blocks.is_suffocating(chunk, block, p)
}
fn may_reach_out(
&mut self,
chunk: Self::Chunk,
section_y: i32,
) -> std::result::Result<bool, Self::Error> {
self.blocks.may_reach_out(chunk, section_y)
}
fn context_shape(
&mut self,
block: CollisionBlock,
@@ -262,6 +269,17 @@ impl<'w> BlockCollisionWorld for SceneCollisions<'w, '_> {
fn collision_block(&mut self, chunk: Self::Chunk, p: BlockPos) -> io::Result<CollisionBlock> {
self.binding.collision_block(chunk.block(p.x, p.y, p.z))
}
/// From the section's palette, without reading its blocks; a palette
/// of the whole registry reads every cell.
fn may_reach_out(&mut self, chunk: Self::Chunk, section_y: i32) -> io::Result<bool> {
let blocks = usize::try_from(section_y - (crate::chunk::MIN_Y >> 4))
.ok()
.and_then(|s| chunk.sections.get(s))
.map(|section| &section.blocks);
Ok(blocks.is_none_or(|blocks| {
blocks.is_global() || blocks.maybe_has(|v| self.binding.reaches_out(BlockStateId(v)))
}))
}
fn is_suffocating(
&mut self,
_: Self::Chunk,
@@ -592,3 +592,21 @@ fn mod_commands_join_the_tree_for_every_player() {
// The game's own tree is left as it was.
assert!(vanilla::game_dispatcher().find("where").is_none());
}
#[test]
fn horizon_commands_are_off_unless_the_server_turns_them_on() {
// By default the game runs vanilla's tree: /help lists no /pregen.
assert!(vanilla::game_dispatcher().find("pregen").is_none());
for dev in [false, true] {
let vanilla_tree = vanilla::game_tree(dev, false);
assert!(vanilla_tree.find("pregen").is_none());
let d = vanilla::game_tree(dev, true);
let parse = d.parse("pregen start 100 circle", &reg());
assert_eq!(parse.executable().unwrap().1, "pregen.start");
// Vanilla's commands are the same with or without it.
assert_eq!(
d.nodes[0].children.len(),
vanilla_tree.nodes[0].children.len() + 1
);
}
}
+62 -5
View File
@@ -538,12 +538,69 @@ fn apply_vanilla_order(d: &mut Dispatcher) {
}
/// The tree the game runs: a release integrated server's, or with
/// `HORIZON_DEV_COMMANDS` set the development one
/// (SharedConstants.DEBUG_DEV_COMMANDS).
/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands when
/// the server turned them on (`set_horizon_commands`).
pub fn game_dispatcher() -> &'static Dispatcher {
if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() {
dispatcher()
} else {
release_dispatcher()
game_tree(
std::env::var_os("HORIZON_DEV_COMMANDS").is_some(),
HORIZON_COMMANDS.load(std::sync::atomic::Ordering::Relaxed),
)
}
/// Whether this process's server has Horizon's own commands (`/pregen`). Off
/// by default, so `/help` and the command tree are vanilla's; a dedicated
/// server turns them on with `horizon-pregen=true` in server.properties, the
/// game with `--pregen` (docs/pregeneration.md).
static HORIZON_COMMANDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Turns Horizon's own commands on or off for the trees `game_dispatcher`
/// returns from now on.
pub fn set_horizon_commands(on: bool) {
HORIZON_COMMANDS.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// The server.properties key that turns `/pregen` on (Horizon's own; vanilla
/// ignores keys it doesn't know).
pub const PREGEN_PROPERTY: &str = "horizon-pregen";
pub(crate) fn game_tree(dev: bool, horizon: bool) -> &'static Dispatcher {
static HORIZON: [std::sync::OnceLock<Dispatcher>; 2] =
[const { std::sync::OnceLock::new() }; 2];
match (dev, horizon) {
(true, false) => dispatcher(),
(false, false) => release_dispatcher(),
(dev, true) => HORIZON[usize::from(dev)].get_or_init(|| {
let mut d = build_with(dev);
horizon_commands(&mut d, 0);
d
}),
}
}
/// Commands vanilla doesn't have, after its own: `/pregen`
/// (docs/pregeneration.md).
fn horizon_commands(d: &mut Dispatcher, root: usize) {
let pregen = d.literal(root, "pregen");
d.requires(pregen, GAMEMASTERS);
let start = d.literal(pregen, "start");
let radius = d.argument(
start,
"radius",
ArgType::Integer {
min: 0,
max: 30_000_000,
},
);
d.executes(radius, "pregen.start");
for shape in ["square", "circle"] {
let shape = d.literal(radius, shape);
d.executes(shape, "pregen.start");
let center = d.argument(shape, "center", ArgType::ColumnPos);
d.executes(center, "pregen.start");
}
for (word, id) in [
("pause", "pregen.pause"),
("continue", "pregen.continue"),
("cancel", "pregen.cancel"),
("status", "pregen.status"),
] {
let w = d.literal(pregen, word);
d.executes(w, id);
}
}
pub fn dispatcher() -> &'static Dispatcher {
@@ -275,4 +275,30 @@ mod tests {
Release::Click(Input::QuickMove)
);
}
/// A press whose release never arrives (the pointer left the window, or
/// the screen closed first) leaves `isQuickCrafting` set; the next screen
/// starts with its own state, as `AbstractContainerScreen` does, so the
/// reset the game runs on open/close makes clicks work again.
#[test]
fn a_lost_release_does_not_wedge_the_next_screen() {
let mut clicks = Clicks::default();
let slot = Target::<usize>::Slot(3);
// Pressed with a stack carried: a quick craft drag starts, and its
// release is lost.
assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None);
assert!(clicks.quick_crafting().is_some());
assert_eq!(
clicks.press(&slot, Button::Left, true, false, false),
None,
"the stuck drag swallows the next press"
);
// A new screen: fresh state, so the press is a normal click again.
clicks = Clicks::default();
assert!(clicks.quick_crafting().is_none());
assert_eq!(
clicks.press(&slot, Button::Left, true, false, false),
Some(Input::Pickup)
);
}
}
+181 -6
View File
@@ -49,6 +49,17 @@ pub struct Furnace {
/// rather than per item, and a save keeps it as the `RecipesUsed` compound.
pub recipes_used: HashMap<String, u32>,
}
/// The key `recipes_used` keeps a recipe under: its full id, as vanilla's `ResourceKey<Recipe>`
/// writes it in `RecipesUsed`. Horizon's own recipe ids are file names without the namespace, so
/// keeping both forms would write a key twice, and vanilla refuses such a furnace
/// ("Duplicate entry for key").
pub fn recipe_used_key(id: &str) -> String {
if id.contains(':') {
id.to_owned()
} else {
format!("minecraft:{id}")
}
}
/// A hopper's slots: the only plain container with five.
pub const HOPPER_SLOTS: usize = 5;
@@ -83,6 +94,117 @@ pub enum BlockEntity {
Beehive(Box<crate::beehive::Beehive>),
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
CommandBlock(Box<crate::command_block::CommandBlock>),
/// `CampfireBlockEntity` of campfires and soul campfires.
Campfire(Box<Campfire>),
/// `SkullBlockEntity` of every skull and head block.
Skull(Skull),
}
/// `CampfireBlockEntity`: four cooking slots, each with its
/// `cookingProgress` and `cookingTime` (the recipe's).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Campfire {
pub items: [Option<ItemStack>; 4],
pub progress: [i32; 4],
pub total: [i32; 4],
}
impl Campfire {
/// `placeFood`'s slot: the first empty one, given the item's
/// `campfire_cooking` time; it takes one item of `held`.
pub fn place_food(&mut self, held: &mut ItemStack, cooking_time: i32) -> bool {
let Some(slot) = self.items.iter().position(Option::is_none) else {
return false;
};
self.total[slot] = cooking_time;
self.progress[slot] = 0;
self.items[slot] = Some(ItemStack {
count: 1,
..held.clone()
});
held.count = held.count.saturating_sub(1);
true
}
/// `cookTick` (lit): each item's progress rises by one; the slots whose
/// progress reached their cooking time give up their item (the caller
/// drops its result).
pub fn cook_tick(&mut self) -> Vec<(usize, ItemStack)> {
let mut done = Vec::new();
for i in 0..4 {
if self.items[i].is_none() {
continue;
}
self.progress[i] += 1;
if self.progress[i] >= self.total[i]
&& let Some(item) = self.items[i].take()
{
done.push((i, item));
}
}
done
}
/// `cooldownTick` (unlit): the progress falls by two, no lower than 0.
/// Whether anything changed (`setChanged`).
pub fn cooldown_tick(&mut self) -> bool {
let mut changed = false;
for i in 0..4 {
if self.progress[i] > 0 {
changed = true;
self.progress[i] = (self.progress[i] - 2).clamp(0, self.total[i]);
}
}
changed
}
}
/// `SkullBlockEntity`: the player profile the head shows (kept as loaded:
/// a compound, or a string when it names a player only), the note block
/// sound and `custom_name`.
#[derive(Clone, Debug, Default)]
pub struct Skull {
pub profile: Option<horizon_world::nbt::Tag>,
pub note_block_sound: Option<String>,
pub custom_name: Option<horizon_world::nbt::Tag>,
/// What `profile` draws, read from it once rather than every frame.
pub skin: Option<SkullSkin>,
}
impl Skull {
pub fn new(
profile: Option<horizon_world::nbt::Tag>,
note_block_sound: Option<String>,
custom_name: Option<horizon_world::nbt::Tag>,
) -> Self {
let skin = profile.as_ref().map(SkullSkin::of);
Self {
profile,
note_block_sound,
custom_name,
skin,
}
}
}
/// `SkullBlockRenderer.getPlayerSkin` of a head's profile: its skin's URL
/// with the `skins/<sha1>` sprite it downloads to, and the
/// `DefaultPlayerSkin` drawn until that sprite is there (steve for a
/// profile with no id).
#[derive(Clone, Debug)]
pub struct SkullSkin {
pub download: Option<(String, String)>,
pub fallback: &'static str,
}
impl SkullSkin {
pub fn of(profile: &horizon_world::nbt::Tag) -> Self {
let download = crate::skins::profile_skin_url_nbt(profile).and_then(|url| {
let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?);
Some((url, location))
});
// DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id.
let fallback = crate::skins::profile_uuid_nbt(profile)
.map_or("entity/player/slim/steve", crate::tab_list::default_skin);
Self { download, fallback }
}
}
/// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every
/// `*_skull` and `*_head` but the piston's head.
fn is_skull(name: &str) -> bool {
name.ends_with("_skull") || (name.ends_with("_head") && name != "minecraft:piston_head")
}
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
/// and the ticks left in the crafting animation.
@@ -238,6 +360,9 @@ impl BlockEntity {
if name.ends_with("_banner") {
return Some(Self::Banner(Banner::default()));
}
if is_skull(name) {
return Some(Self::Skull(Skull::default()));
}
if name == "minecraft:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -247,6 +372,9 @@ impl BlockEntity {
if name == "minecraft:brewing_stand" {
return Some(Self::Brewing(Box::new(crate::brewing::BrewingStand::new())));
}
if name == "minecraft:campfire" || name == "minecraft:soul_campfire" {
return Some(Self::Campfire(Box::default()));
}
let size = match name {
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
n if n.ends_with("copper_chest") => 27,
@@ -283,6 +411,8 @@ impl BlockEntity {
Self::Vault(_) => "minecraft:vault",
Self::Beehive(_) => "minecraft:beehive",
Self::CommandBlock(_) => "minecraft:command_block",
Self::Skull(_) => "minecraft:skull",
Self::Campfire(_) => "minecraft:campfire",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -298,11 +428,13 @@ impl BlockEntity {
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => Vec::new(),
| Self::CommandBlock(_)
| Self::Skull(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
Self::Campfire(c) => c.items.iter().flatten().cloned().collect(),
}
}
pub fn slots(&self) -> &[Option<ItemStack>] {
@@ -315,14 +447,17 @@ impl BlockEntity {
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_) => &[],
| Self::Banner(_)
| Self::Skull(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => &[],
| Self::CommandBlock(_)
// Not a Container (only Clearable): hoppers don't reach in.
| Self::Campfire(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -335,14 +470,16 @@ impl BlockEntity {
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_) => &mut [],
| Self::Banner(_)
| Self::Skull(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => &mut [],
| Self::CommandBlock(_)
| Self::Campfire(_) => &mut [],
}
}
}
@@ -577,7 +714,10 @@ impl Furnace {
Some(out) => out.count += recipe.result.count,
None => self.items[2] = Some(recipe.result.clone()),
}
*self.recipes_used.entry(recipe.id.clone()).or_insert(0) += 1;
*self
.recipes_used
.entry(recipe_used_key(&recipe.id))
.or_insert(0) += 1;
if let Some(i) = self.items[0].as_mut() {
i.count -= 1;
if i.count == 0 {
@@ -631,6 +771,41 @@ mod tests {
use super::*;
use horizon_core::random::{LegacyRandom, RandomSource};
#[test]
fn campfire_slots_take_food_cook_it_and_cool_down() {
let mut c = Campfire::default();
let mut beef = ItemStack::new("minecraft:beef", 2);
// placeFood: the first free slot, one item, its recipe's time.
assert!(c.place_food(&mut beef, 600));
assert_eq!(beef.count, 1);
assert_eq!(c.items[0].as_ref().map(|s| s.count), Some(1));
assert_eq!((c.progress[0], c.total[0]), (0, 600));
let mut fish = ItemStack::new("minecraft:cod", 1);
assert!(c.place_food(&mut fish, 3));
assert_eq!(c.items[1].as_ref().map(|s| &*s.item), Some("minecraft:cod"));
// cookTick: the cod is done on its third tick, the beef keeps cooking.
assert!(c.cook_tick().is_empty());
assert!(c.cook_tick().is_empty());
let done = c.cook_tick();
assert_eq!(done.len(), 1);
assert_eq!((done[0].0, &*done[0].1.item), (1, "minecraft:cod"));
assert!(c.items[1].is_none());
assert_eq!(c.progress[0], 3);
// cooldownTick: two a tick, never below zero.
assert!(c.cooldown_tick());
assert_eq!(c.progress[0], 1);
assert!(c.cooldown_tick());
assert_eq!(c.progress[0], 0);
// Full: four slots, no fifth.
for _ in 0..3 {
let mut more = ItemStack::new("minecraft:potato", 1);
assert!(c.place_food(&mut more, 600));
}
let mut fifth = ItemStack::new("minecraft:potato", 1);
assert!(!c.place_food(&mut fifth, 600));
assert_eq!(fifth.count, 1);
}
/// A whole amount pays itself without a draw; a fraction is a chance of one more.
#[test]
fn create_experience_rounds_the_fraction_by_chance() {
+174
View File
@@ -0,0 +1,174 @@
//! `Player.getCooldowns()` (`ItemCooldowns`) as the game keeps it: the
//! `use_cooldown` component's entries by cooldown group, counted down once a
//! tick, and the percent `GuiGraphicsExtractor.itemCooldown` shades a slot
//! by. The world crate's `item_cooldowns` models vanilla's hash map and its
//! observers for the parity harness; this is the same data with the lookup a
//! slot needs, and no observer (vanilla's own player uses the plain class).
use crate::items::ItemStack;
use horizon_world::nbt::Tag;
use std::collections::HashMap;
use std::sync::Arc;
/// A stack's `minecraft:use_cooldown` component.
#[derive(Clone, Debug, PartialEq)]
pub struct UseCooldown {
pub seconds: f32,
/// `cooldown_group`: the group the entry is filed under, else the item.
pub group: Option<Arc<str>>,
}
impl UseCooldown {
/// `UseCooldown.ticks`: the seconds in ticks, truncated.
pub fn ticks(&self) -> i32 {
(self.seconds * 20.0) as i32
}
/// The component as `items.json` holds it.
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
let seconds = v.get("seconds")?.as_f64()? as f32;
Some(Self {
seconds,
group: v
.get("cooldown_group")
.and_then(|g| g.as_str())
.map(Arc::from),
})
}
/// The component as a stack's saved `components` holds it.
pub fn from_tag(t: &Tag) -> Option<Self> {
let Tag::Compound(c) = t else {
return None;
};
let text = |k: &str| match c.get(&horizon_world::nbt::JavaString::from(k)) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
};
let seconds = match c.get(&horizon_world::nbt::JavaString::from("seconds")) {
Some(Tag::Float(bits)) => f32::from_bits(*bits),
Some(Tag::Double(bits)) => f64::from_bits(*bits) as f32,
_ => return None,
};
Some(Self {
seconds,
group: text("cooldown_group").map(Arc::from),
})
}
}
/// The component a stack carries: its own patch first (`ItemStack.get`), then
/// the item's default from `items.json` (`ItemInfo::use_cooldown`).
pub fn component(stack: &ItemStack, default: Option<&UseCooldown>) -> Option<UseCooldown> {
stack
.data()
.and_then(|d| d.other("minecraft:use_cooldown"))
.and_then(UseCooldown::from_tag)
.or_else(|| default.cloned())
}
/// `ItemCooldowns.getCooldownGroup`: the component's group, else the item id.
pub fn group(stack: &ItemStack, default: Option<&UseCooldown>) -> Arc<str> {
component(stack, default)
.and_then(|c| c.group)
.unwrap_or_else(|| Arc::clone(&stack.item))
}
/// `ItemCooldowns`: start and end ticks by group, and the tick counter.
#[derive(Clone, Debug, Default)]
pub struct Cooldowns {
tick_count: i32,
entries: HashMap<Arc<str>, (i32, i32)>,
}
impl Cooldowns {
/// `getCooldownPercent`: what is left of the entry, from 1 to 0.
pub fn percent(&self, group: &str, partial_tick: f32) -> f32 {
let Some((start, end)) = self.entries.get(group) else {
return 0.0;
};
let duration = end.wrapping_sub(*start) as f32;
let remaining = *end as f32 - (self.tick_count as f32 + partial_tick);
(remaining / duration).clamp(0.0, 1.0)
}
/// `isOnCooldown`: whether the group still has time to run.
pub fn is_on_cooldown(&self, group: &str) -> bool {
self.percent(group, 0.0) > 0.0
}
/// `addCooldown`.
pub fn add(&mut self, group: Arc<str>, ticks: i32) {
self.entries.insert(
group,
(self.tick_count, self.tick_count.wrapping_add(ticks)),
);
}
/// `ItemCooldowns.tick`: the counter, then every entry that has run out,
/// which it hands back (`onCooldownEnded`).
pub fn tick(&mut self) -> Vec<Arc<str>> {
self.tick_count = self.tick_count.wrapping_add(1);
let done: Vec<Arc<str>> = self
.entries
.iter()
.filter(|(_, (_, end))| *end <= self.tick_count)
.map(|(group, _)| Arc::clone(group))
.collect();
self.entries.retain(|_, (_, end)| *end > self.tick_count);
done
}
/// `removeCooldown`.
pub fn remove(&mut self, group: &str) {
self.entries.remove(group);
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn stack(item: &str) -> ItemStack {
ItemStack::new(item, 1)
}
#[test]
fn the_percent_falls_from_one_to_zero_over_the_entry() {
let mut c = Cooldowns::default();
c.add(Arc::from("minecraft:ender_pearl"), 20);
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 1.0);
for _ in 0..10 {
assert!(c.tick().is_empty());
}
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.5);
// The partial tick moves it within the tick.
assert_eq!(c.percent("minecraft:ender_pearl", 0.5), 0.475);
for _ in 0..9 {
c.tick();
}
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
// ItemCooldowns.tick drops the entry at its end tick, and says so.
assert_eq!(c.tick(), [Arc::<str>::from("minecraft:ender_pearl")]);
assert!(!c.is_on_cooldown("minecraft:ender_pearl"));
assert!(c.is_empty());
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.0);
}
#[test]
fn the_group_comes_from_the_stack_then_the_item() {
let pearl = stack("minecraft:ender_pearl");
let default = UseCooldown::from_json(&json!({"seconds": 1.0})).expect("the component");
assert_eq!(&*group(&pearl, Some(&default)), "minecraft:ender_pearl");
// A stack's own component overrides the item's, group included.
let mut grouped = stack("minecraft:ender_pearl");
grouped.data_mut().set_other(
"minecraft:use_cooldown",
Some(Tag::compound([
("seconds", Tag::Float(2.0f32.to_bits())),
("cooldown_group", Tag::String("minecraft:pearls".into())),
])),
);
let c = component(&grouped, Some(&default)).expect("the stack's component");
assert_eq!(c.ticks(), 40);
assert_eq!(&*group(&grouped, Some(&default)), "minecraft:pearls");
// An item without the component has no cooldown.
assert!(component(&stack("minecraft:dirt"), None).is_none());
}
}
+2
View File
@@ -1612,7 +1612,9 @@ impl Recipes {
}
/// The `experience` of the cooking recipe with this file name, and 0 for one this data
/// pack does not have (a save from another pack can name it).
/// `id` with or without the `minecraft:` namespace (a furnace keeps the full id).
pub fn cooking_experience(&self, id: &str) -> f32 {
let id = id.strip_prefix("minecraft:").unwrap_or(id);
self.cooking
.iter()
.find(|c| c.id == id)
+40 -15
View File
@@ -1,7 +1,7 @@
//! Creative inventory (CreativeModeInventoryScreen): vanilla's tabs and their
//! contents as built by the game's own display generators
//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab.
use crate::{Result, items::ItemStack};
use crate::{Result, items::ItemStack, ui::EditBox};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
@@ -35,10 +35,8 @@ pub struct Creative {
pub scroll: f32,
/// The scrollbar is held (scrolling): dragging moves it.
pub scrolling: bool,
pub search: String,
/// When the search box took the focus (`EditBox.setFocused`): its
/// cursor blinks from then.
pub search_focused: std::time::Instant,
/// CreativeModeInventoryScreen's search box: an unbordered `EditBox` of 50.
pub search: EditBox,
/// The search tab's stacks, in its display order.
search_items: Vec<ItemStack>,
search_index: Vec<SearchEntry>,
@@ -284,8 +282,13 @@ impl Creative {
selected: 0,
scroll: 0.0,
scrolling: false,
search: String::new(),
search_focused: std::time::Instant::now(),
search: {
let mut search = EditBox::new(0.0, 0.0, 80.0, 9.0);
search.bordered = false;
search.max_length = 50;
search.text_color = u32::MAX;
search
},
search_items,
search_index,
}
@@ -306,12 +309,13 @@ impl Creative {
/// selectTab: a different tab empties the search box; the scrollbar goes to the top.
pub fn select(&mut self, tab: usize) {
if tab != self.selected {
self.search.clear();
self.search.set_value("");
}
self.selected = tab;
self.scroll = 0.0;
if self.tab().search {
self.search_focused = std::time::Instant::now();
self.search.focused = true;
self.search.reset_blink();
}
}
/// The search tab's stacks.
@@ -385,7 +389,7 @@ impl Creative {
let tab = self.tab();
if tab.search {
return self
.search_results(&self.search, names)
.search_results(&self.search.value, names)
.into_iter()
.map(|i| self.search_items[i].clone())
.collect();
@@ -754,13 +758,13 @@ mod tests {
(1, false, true),
(2, true, false),
] {
c.search = "anvil".into();
c.search.set_value("anvil");
c.scroll = 0.5;
c.select(selected);
assert_eq!(c.selected, selected);
assert_eq!(c.tab().inventory, inventory);
assert_eq!(c.tab().search, search);
assert!(c.search.is_empty());
assert!(c.search.value.is_empty());
assert_eq!(c.scroll, 0.0);
}
}
@@ -780,12 +784,12 @@ mod tests {
assert_eq!(c.tabs[0].items[0].item.as_ref(), "minecraft:anvil");
let mut c = c;
c.select(1);
c.search = "anvil".into();
c.search.set_value("anvil");
c.scroll = 0.5;
c.select(1);
assert_eq!((c.search.as_str(), c.scroll), ("anvil", 0.0));
assert_eq!((c.search.value.as_str(), c.scroll), ("anvil", 0.0));
c.select(0);
assert_eq!(c.search, "");
assert_eq!(c.search.value, "");
}
#[test]
@@ -899,4 +903,25 @@ mod tests {
c.scroll = 1.0;
assert_eq!(c.scroller_offset(), 95.0);
}
#[test]
fn search_edits_at_its_cursor() {
use winit::keyboard::KeyCode;
let mut c = creative(0);
c.select(1);
c.search.insert_text("hello world");
for _ in 0..5 {
assert!(c.search.key(KeyCode::ArrowLeft, false, false));
}
c.search.insert_text("X");
assert_eq!(c.search.value, "hello Xworld");
c.search.key(KeyCode::Home, false, true);
c.search.insert_text("Y");
assert_eq!(c.search.value, "Yworld");
// Ctrl+Left jumps a word; one step right and Backspace deletes before the cursor.
c.search.key(KeyCode::ArrowLeft, true, false);
c.search.key(KeyCode::ArrowRight, false, false);
c.search.key(KeyCode::Backspace, false, false);
assert_eq!(c.search.value, "world");
}
}
+59
View File
@@ -0,0 +1,59 @@
//! Cushion placement and support checks (`Cushion.canBePlacedAt`/`wouldSurviveAt`).
use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
pub trait World {
fn outline_bounds(&self, pos: [i32; 3]) -> Option<Aabb>;
fn collision_shapes(&self, bounds: Aabb) -> Vec<VoxelShape>;
fn suffocating(&self, pos: [i32; 3]) -> bool;
}
pub fn blocks_in(a: Aabb) -> impl Iterator<Item = [i32; 3]> {
let (lo, hi) = (a.min_position(), a.max_position());
let (x0, y0, z0) = (
lo.x.floor() as i32,
lo.y.floor() as i32,
lo.z.floor() as i32,
);
let (x1, y1, z1) = (
hi.x.floor() as i32,
hi.y.floor() as i32,
hi.z.floor() as i32,
);
(y0..=y1).flat_map(move |y| (z0..=z1).flat_map(move |z| (x0..=x1).map(move |x| [x, y, z])))
}
pub fn survives(world: &impl World, bounds: Aabb) -> bool {
let (lo, hi) = (bounds.min_position(), bounds.max_position());
let anchor = Aabb::new(
Vec3::new(lo.x, lo.y - 0.015625, lo.z),
Vec3::new(hi.x.next_down(), lo.y, hi.z.next_down()),
);
// The extra eighth block expands the scan, not the intersection test.
let supported = blocks_in(anchor.expand_towards(Vec3::new(0.0, -0.125, 0.0))).any(|p| {
world
.outline_bounds(p)
.is_some_and(|shape| shape.intersects(anchor))
});
supported && !blocks_in(bounds.next_deflated()).all(|p| world.suffocating(p))
}
pub fn can_place(world: &impl World, bounds: Aabb) -> bool {
if !survives(world, bounds) {
return false;
}
let (lo, hi) = (bounds.min_position(), bounds.max_position());
let slab = Aabb::new(lo, Vec3::new(hi.x, lo.y + 0.015625, hi.z)).next_deflated();
let Ok(mut remaining) = VoxelShape::from_box(slab) else {
return false;
};
for shape in world.collision_shapes(slab) {
let Ok(next) = remaining.join(&shape, ShapeOp::ONLY_FIRST) else {
return false;
};
remaining = next;
if remaining.is_empty() {
return false;
}
}
true
}
+42 -5
View File
@@ -84,6 +84,33 @@ impl Displayer {
}
}
/// Horizon's own lines: the shader pack's GPU time, then its costliest passes (`passes`: each
/// pass's median milliseconds, in the order they run).
pub fn shader_pass_lines(passes: &[(String, f32)]) -> Vec<String> {
const SHOWN: usize = 8;
if passes.is_empty() {
return Vec::new();
}
let total: f32 = passes.iter().map(|p| p.1).sum();
let mut lines = vec![format!(
"Shader pack GPU: {total:.2} ms in {} passes",
passes.len()
)];
let mut costliest: Vec<&(String, f32)> = passes.iter().collect();
costliest.sort_by(|a, b| b.1.total_cmp(&a.1));
lines.extend(
costliest
.iter()
.take(SHOWN)
.map(|(name, ms)| format!("{name}: {ms:.2} ms")),
);
if costliest.len() > SHOWN {
let rest: f32 = costliest[SHOWN..].iter().map(|p| p.1).sum();
lines.push(format!("{} more: {rest:.2} ms", costliest.len() - SHOWN));
}
lines
}
/// `Mth.wrapDegrees`.
fn wrap_degrees(angle: f32) -> f32 {
let wrapped = angle % 360.0;
@@ -194,18 +221,17 @@ pub fn scale(
pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec<GuiDraw> {
let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])];
for (lines, align_left) in [(columns[0], true), (columns[1], false)] {
let placed: Vec<(&String, i32, i32)> = lines
let placed: Vec<(&String, i32, i32, i32)> = lines
.iter()
.enumerate()
.filter(|(_, l)| !l.is_empty())
.map(|(i, l)| {
let w = font.width(l) as i32;
let left = if align_left { 2 } else { width - 2 - w };
(l, left, 2 + LINE_HEIGHT * i as i32)
(l, left, 2 + LINE_HEIGHT * i as i32, w)
})
.collect();
for (line, left, top) in &placed {
let w = font.width(line) as i32;
for (_, left, top, w) in &placed {
out.push(fill(
left - 1,
top - 1,
@@ -214,7 +240,7 @@ pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec
BACKGROUND,
));
}
for (line, left, top) in placed {
for (line, left, top, _) in placed {
out.push(GuiDraw::Text {
text: Text::literal(line.clone()),
x: left,
@@ -337,4 +363,15 @@ mod tests {
(1.0, [640, 360])
);
}
#[test]
fn shader_pass_lines_list_the_costliest_passes_first() {
assert!(shader_pass_lines(&[]).is_empty());
let passes: Vec<(String, f32)> = (0..10).map(|i| (format!("p{i}"), i as f32)).collect();
let lines = shader_pass_lines(&passes);
assert_eq!(lines[0], "Shader pack GPU: 45.00 ms in 10 passes");
assert_eq!(lines[1], "p9: 9.00 ms");
assert_eq!(lines[8], "p2: 2.00 ms");
assert_eq!(lines[9], "2 more: 1.00 ms");
}
}
+794
View File
@@ -0,0 +1,794 @@
//! Server dialogs (`net.minecraft.server.dialog`): what `Dialog.DIRECT_CODEC`
//! decodes from a `show_dialog` packet, the values its inputs hold, and the
//! click event an action makes of them (`Action.createAction`).
use crate::text::Text;
use horizon_world::nbt::Tag;
use serde_json::{Value, json};
/// `CommonDialogData` and the type's own fields.
#[derive(Clone, Debug)]
pub struct Dialog {
pub kind: Kind,
pub title: Text,
pub external_title: Option<Text>,
pub can_close_with_escape: bool,
pub pause: bool,
pub after_action: AfterAction,
pub body: Vec<Body>,
pub inputs: Vec<Input>,
}
/// The dialog types (`DialogTypes`).
#[derive(Clone, Debug)]
pub enum Kind {
/// `NoticeDialog`: one button, "OK" when the server names none.
Notice(Button),
Confirmation {
yes: Button,
no: Button,
},
MultiAction {
actions: Vec<Button>,
exit: Option<Button>,
columns: i32,
},
ServerLinks {
exit: Option<Button>,
columns: i32,
button_width: i32,
},
/// `DialogListDialog`: its dialogs as sent (ids, a tag or inline dialogs).
DialogList {
dialogs: Tag,
exit: Option<Button>,
columns: i32,
button_width: i32,
},
}
/// `DialogAction`: the screen after an action runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AfterAction {
Close,
None,
WaitForResponse,
}
/// `ActionButton`: `CommonButtonData` and what it does.
#[derive(Clone, Debug)]
pub struct Button {
pub label: Text,
pub tooltip: Option<Text>,
pub width: i32,
pub action: Option<Action>,
}
/// `Action`: a fixed click event, or one made from the inputs' values.
#[derive(Clone, Debug, PartialEq)]
pub enum Action {
/// `StaticAction`: a click event as it is.
Static(Click),
/// `CommandTemplate`: a command with `$(key)` replaced by input values.
RunCommand(String),
/// `CustomAll`: a custom click event whose payload is `additions` plus
/// every input's value under its key.
Custom { id: String, additions: Option<Tag> },
}
/// `ClickEvent`, the kinds a server may send (`isAllowedFromServer`).
#[derive(Clone, Debug, PartialEq)]
pub enum Click {
OpenUrl(String),
RunCommand(String),
SuggestCommand(String),
/// The dialog: an id of the `minecraft:dialog` registry or the dialog itself.
ShowDialog(Tag),
ChangePage(i32),
CopyToClipboard(String),
Custom {
id: String,
payload: Option<Tag>,
},
}
/// `DialogBody`.
#[derive(Clone, Debug)]
pub enum Body {
/// `PlainMessage`: centred text wrapped to `width`.
Message { contents: Text, width: i32 },
/// `ItemBody`: the item as `ItemStackTemplate` sent it.
Item {
item: Tag,
description: Option<(Text, i32)>,
show_decorations: bool,
show_tooltip: bool,
width: i32,
height: i32,
},
}
/// `Input`: the key its value goes by, and its control.
#[derive(Clone, Debug)]
pub struct Input {
pub key: String,
pub control: Control,
}
/// `InputControl`.
#[derive(Clone, Debug)]
pub enum Control {
Text {
width: i32,
label: Text,
label_visible: bool,
initial: String,
max_length: i32,
/// `MultilineOptions`: the most lines and the height, when set.
multiline: Option<(Option<i32>, Option<i32>)>,
},
Boolean {
label: Text,
initial: bool,
on_true: String,
on_false: String,
},
SingleOption {
width: i32,
/// Each option's id, its label and whether it is the initial one.
options: Vec<(String, Option<Text>, bool)>,
label: Text,
label_visible: bool,
},
NumberRange {
width: i32,
label: Text,
label_format: String,
start: f32,
end: f32,
initial: Option<f32>,
step: Option<f32>,
},
}
/// What an input holds while the dialog is open.
#[derive(Clone, Debug, PartialEq)]
pub enum InputValue {
Text(String),
Bool(bool),
/// The chosen option's index.
Option(usize),
/// The slider's position, 0 to 1.
Slider(f32),
}
fn text(t: &Tag) -> Text {
crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))
}
fn string(t: Option<&Tag>) -> Option<String> {
match t? {
Tag::String(s) => Some(s.to_string_lossy()),
_ => None,
}
}
fn number(t: Option<&Tag>) -> Option<f64> {
Some(match t? {
Tag::Byte(v) => f64::from(*v),
Tag::Short(v) => f64::from(*v),
Tag::Int(v) => f64::from(*v),
Tag::Long(v) => *v as f64,
Tag::Float(v) => f64::from(f32::from_bits(*v)),
Tag::Double(v) => f64::from_bits(*v),
_ => return None,
})
}
fn int(t: &Tag, key: &str, default: i32) -> i32 {
number(t.get(key)).map_or(default, |v| v as i32)
}
fn boolean(t: &Tag, key: &str, default: bool) -> bool {
number(t.get(key)).map_or(default, |v| v != 0.0)
}
fn list(t: Option<&Tag>) -> &[Tag] {
match t {
Some(Tag::List(items)) => items,
_ => &[],
}
}
/// A registry name without its default namespace.
fn path(id: &str) -> &str {
id.strip_prefix("minecraft:").unwrap_or(id)
}
impl Button {
/// `ActionButton.CODEC`.
fn parse(t: &Tag) -> Option<Self> {
Some(Self {
label: text(t.get("label")?),
tooltip: t.get("tooltip").map(text),
width: int(t, "width", 150),
action: t.get("action").and_then(Action::parse),
})
}
/// `NoticeDialog.DEFAULT_ACTION`.
fn ok() -> Self {
Self {
label: Text::translate("gui.ok", &[]),
tooltip: None,
width: 150,
action: None,
}
}
}
impl Click {
/// `ClickEvent.CODEC`, from its `action` (a click event in a component)
/// or `type` (an action) field.
pub fn parse(t: &Tag, kind: &str) -> Option<Self> {
let s = |key| string(t.get(key));
Some(match path(kind) {
"open_url" => Self::OpenUrl(s("url")?),
"run_command" => Self::RunCommand(s("command")?),
"suggest_command" => Self::SuggestCommand(s("command")?),
"show_dialog" => Self::ShowDialog(t.get("dialog")?.clone()),
"change_page" => Self::ChangePage(int(t, "page", 1)),
"copy_to_clipboard" => Self::CopyToClipboard(s("value")?),
"custom" => Self::Custom {
id: s("id")?,
payload: t.get("payload").cloned(),
},
_ => return None,
})
}
}
impl Action {
/// `Action.CODEC`, dispatched on `type`.
fn parse(t: &Tag) -> Option<Self> {
let kind = string(t.get("type"))?;
Some(match path(&kind) {
"dynamic/run_command" => Self::RunCommand(string(t.get("template"))?),
"dynamic/custom" => Self::Custom {
id: string(t.get("id"))?,
additions: t.get("additions").cloned(),
},
other => Self::Static(Click::parse(t, other)?),
})
}
/// `createAction`: the click event, given each input's key, control and value.
pub fn click(&self, inputs: &[Input], values: &[InputValue]) -> Option<Click> {
let values = || inputs.iter().zip(values);
Some(match self {
Self::Static(click) => click.clone(),
Self::RunCommand(template) => Click::RunCommand(substitute(template, &|key| {
values()
.find(|(i, _)| i.key == key)
.map(|(i, v)| i.control.substitution(v))
})),
Self::Custom { id, additions } => {
let mut tag = match additions {
Some(t @ Tag::Compound(_)) => t.clone(),
_ => Tag::Compound(Default::default()),
};
for (input, value) in values() {
if let Tag::Compound(map) = &mut tag {
map.insert(input.key.as_str().into(), input.control.tag(value));
}
}
Click::Custom {
id: id.clone(),
payload: Some(tag),
}
}
})
}
}
/// `ParsedTemplate.instantiate`: each `$(key)` replaced by its value, or by
/// nothing for a key no input has.
fn substitute(template: &str, value: &dyn Fn(&str) -> Option<String>) -> String {
let mut out = String::new();
let mut rest = template;
while let Some(at) = rest.find("$(") {
let Some(end) = rest[at..].find(')') else {
break;
};
out.push_str(&rest[..at]);
out.push_str(&value(&rest[at + 2..at + end]).unwrap_or_default());
rest = &rest[at + end + 1..];
}
out.push_str(rest);
out
}
/// `StringTag.escapeWithoutQuotes`.
fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' | '\'' | '\\' => {
out.push('\\');
out.push(c);
}
'\u{8}' => out.push_str("\\b"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\u{c}' => out.push_str("\\f"),
'\r' => out.push_str("\\r"),
c if c < ' ' => out.push_str(&format!("\\x{:02x}", c as u32)),
c => out.push(c),
}
}
out
}
impl Control {
/// `InputControl.MAP_CODEC`, dispatched on `type`.
fn parse(t: &Tag) -> Option<Self> {
let label = || t.get("label").map(text);
Some(match path(&string(t.get("type"))?) {
"text" => Self::Text {
width: int(t, "width", 200),
label: label()?,
label_visible: boolean(t, "label_visible", true),
initial: string(t.get("initial")).unwrap_or_default(),
max_length: int(t, "max_length", 32),
multiline: t.get("multiline").map(|m| {
let get = |key| number(m.get(key)).map(|v| v as i32);
(get("max_lines"), get("height"))
}),
},
"boolean" => Self::Boolean {
label: label()?,
initial: boolean(t, "initial", false),
on_true: string(t.get("on_true")).unwrap_or_else(|| "true".into()),
on_false: string(t.get("on_false")).unwrap_or_else(|| "false".into()),
},
"single_option" => Self::SingleOption {
width: int(t, "width", 200),
// SingleOptionInput.Entry.CODEC: a full entry or just its id.
options: list(t.get("options"))
.iter()
.filter_map(|o| match o {
Tag::String(id) => Some((id.to_string_lossy(), None, false)),
o => Some((
string(o.get("id"))?,
o.get("display").map(text),
boolean(o, "initial", false),
)),
})
.collect(),
label: label()?,
label_visible: boolean(t, "label_visible", true),
},
"number_range" => {
let float = |key| number(t.get(key)).map(|v| v as f32);
Self::NumberRange {
width: int(t, "width", 200),
label: label()?,
label_format: string(t.get("label_format"))
.unwrap_or_else(|| "options.generic_value".into()),
start: float("start")?,
end: float("end")?,
initial: float("initial"),
step: float("step"),
}
}
_ => return None,
})
}
/// The value it starts with.
pub fn initial(&self) -> InputValue {
match self {
Self::Text { initial, .. } => InputValue::Text(initial.clone()),
Self::Boolean { initial, .. } => InputValue::Bool(*initial),
Self::SingleOption { options, .. } => {
InputValue::Option(options.iter().position(|o| o.2).unwrap_or(0))
}
Self::NumberRange {
start,
end,
initial,
..
} => InputValue::Slider(to_slider(
initial.unwrap_or((start + end) / 2.0),
*start,
*end,
)),
}
}
/// `ValueGetter.asTemplateSubstitution`.
pub fn substitution(&self, value: &InputValue) -> String {
match (self, value) {
(Self::Text { .. }, InputValue::Text(s)) => escape(s),
(
Self::Boolean {
on_true, on_false, ..
},
InputValue::Bool(b),
) => if *b { on_true } else { on_false }.clone(),
(Self::SingleOption { options, .. }, InputValue::Option(i)) => {
options.get(*i).map(|o| o.0.clone()).unwrap_or_default()
}
(Self::NumberRange { .. }, InputValue::Slider(_)) => {
number_string(self.scaled(value).unwrap_or(0.0))
}
_ => String::new(),
}
}
/// `ValueGetter.asTag`.
pub fn tag(&self, value: &InputValue) -> Tag {
match (self, value) {
(Self::Boolean { .. }, InputValue::Bool(b)) => Tag::Byte(i8::from(*b)),
(Self::NumberRange { .. }, _) => {
Tag::Float(self.scaled(value).unwrap_or(0.0).to_bits())
}
(Self::Text { .. }, InputValue::Text(s)) => Tag::String(s.as_str().into()),
_ => Tag::String(self.substitution(value).as_str().into()),
}
}
/// `RangeInfo.computeScaledValue`: a number range's value at its slider position.
pub fn scaled(&self, value: &InputValue) -> Option<f32> {
let (
Self::NumberRange {
start,
end,
initial,
step,
..
},
InputValue::Slider(slider),
) = (self, value)
else {
return None;
};
let (start, end) = (*start, *end);
let in_range = start + slider * (end - start);
let Some(step) = step else {
return Some(in_range);
};
let first = initial.unwrap_or((start + end) / 2.0);
// Math.round: half up.
let steps = ((in_range - first) / step + 0.5).floor() as i32;
let result = first + steps as f32 * step;
let position = to_slider(result, start, end);
if (0.0..=1.0).contains(&position) {
return Some(result);
}
Some(first + (steps - steps.signum()) as f32 * step)
}
}
/// `RangeInfo.scaledValueToSlider`.
fn to_slider(value: f32, start: f32, end: f32) -> f32 {
if start == end {
0.5
} else {
(value - start) / (end - start)
}
}
/// `SliderImpl.valueToString`: whole numbers without a fraction, the rest as
/// Java's `Float.toString`.
pub fn number_string(v: f32) -> String {
if v == (v as i32) as f32 {
(v as i32).to_string()
} else {
crate::snbt::java_float(v)
}
}
impl Body {
/// `DialogBody.DIALOG_BODY_CODEC`.
fn parse(t: &Tag) -> Option<Self> {
let message = |t: &Tag| -> Option<(Text, i32)> {
// PlainMessage.CODEC: the full form or just its contents.
match t {
Tag::Compound(_) if t.get("contents").is_some() => {
Some((text(t.get("contents")?), int(t, "width", 200)))
}
t => Some((text(t), 200)),
}
};
Some(match path(&string(t.get("type"))?) {
"plain_message" => {
let (contents, width) = message(t)?;
Self::Message { contents, width }
}
"item" => Self::Item {
item: t.get("item")?.clone(),
description: t.get("description").and_then(message),
show_decorations: boolean(t, "show_decorations", true),
show_tooltip: boolean(t, "show_tooltip", true),
width: int(t, "width", 16),
height: int(t, "height", 16),
},
_ => return None,
})
}
}
impl Dialog {
/// `Dialog.DIRECT_CODEC`; `None` for a type or field it can't read
/// (vanilla fails the whole packet then).
pub fn parse(t: &Tag) -> Option<Self> {
let button = |key: &str| t.get(key).and_then(Button::parse);
let kind = match path(&string(t.get("type"))?) {
"notice" => Kind::Notice(match t.get("action") {
Some(b) => Button::parse(b)?,
None => Button::ok(),
}),
"confirmation" => Kind::Confirmation {
yes: button("yes")?,
no: button("no")?,
},
"multi_action" => Kind::MultiAction {
actions: list(t.get("actions"))
.iter()
.map(Button::parse)
.collect::<Option<Vec<_>>>()
.filter(|a| !a.is_empty())?,
exit: button("exit_action"),
columns: int(t, "columns", 2),
},
"server_links" => Kind::ServerLinks {
exit: button("exit_action"),
columns: int(t, "columns", 2),
button_width: int(t, "button_width", 150),
},
"dialog_list" => Kind::DialogList {
dialogs: t.get("dialogs")?.clone(),
exit: button("exit_action"),
columns: int(t, "columns", 2),
button_width: int(t, "button_width", 150),
},
_ => return None,
};
// DialogBody.COMPACT_LIST_CODEC: one body, or a list of them.
let body = match t.get("body") {
Some(Tag::List(items)) => items.iter().filter_map(Body::parse).collect(),
Some(one) => Body::parse(one).into_iter().collect(),
None => Vec::new(),
};
let inputs = list(t.get("inputs"))
.iter()
.filter_map(|i| {
Some(Input {
key: string(i.get("key"))?,
control: Control::parse(i)?,
})
})
.collect();
Some(Self {
kind,
title: text(t.get("title")?),
external_title: t.get("external_title").map(text),
can_close_with_escape: boolean(t, "can_close_with_escape", true),
pause: boolean(t, "pause", true),
after_action: match string(t.get("after_action")).as_deref() {
Some("none") => AfterAction::None,
Some("wait_for_response") => AfterAction::WaitForResponse,
_ => AfterAction::Close,
},
body,
inputs,
})
}
/// `onCancel`: what Escape (or closing it) does.
pub fn on_cancel(&self) -> Option<&Action> {
match &self.kind {
Kind::Notice(b) => b.action.as_ref(),
Kind::Confirmation { no, .. } => no.action.as_ref(),
Kind::MultiAction { exit, .. }
| Kind::ServerLinks { exit, .. }
| Kind::DialogList { exit, .. } => exit.as_ref().and_then(|b| b.action.as_ref()),
}
}
/// The buttons it draws, in order: the list, then the footer's.
pub fn buttons(&self) -> Vec<&Button> {
match &self.kind {
Kind::Notice(b) => vec![b],
Kind::Confirmation { yes, no } => vec![yes, no],
Kind::MultiAction { actions, exit, .. } => actions.iter().chain(exit).collect(),
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => exit.iter().collect(),
}
}
/// What `status` reports of it.
pub fn json(&self, values: &[InputValue]) -> Value {
let kind = match &self.kind {
Kind::Notice(_) => "notice",
Kind::Confirmation { .. } => "confirmation",
Kind::MultiAction { .. } => "multi_action",
Kind::ServerLinks { .. } => "server_links",
Kind::DialogList { .. } => "dialog_list",
};
let inputs: Vec<Value> = self
.inputs
.iter()
.zip(values)
.map(|(i, v)| {
let kind = match i.control {
Control::Text { .. } => "text",
Control::Boolean { .. } => "boolean",
Control::SingleOption { .. } => "single_option",
Control::NumberRange { .. } => "number_range",
};
json!({"key": i.key, "type": kind, "value": i.control.substitution(v)})
})
.collect();
json!({
"type": kind,
"title": self.title.plain(),
"body": self.body.iter().map(|b| match b {
Body::Message { contents, .. } => contents.plain(),
Body::Item { item, .. } => string(item.get("id")).unwrap_or_default(),
}).collect::<Vec<_>>(),
"inputs": inputs,
"buttons": self.buttons().iter().map(|b| b.label.plain()).collect::<Vec<_>>(),
"can_close_with_escape": self.can_close_with_escape,
"after_action": match self.after_action {
AfterAction::Close => "close",
AfterAction::None => "none",
AfterAction::WaitForResponse => "wait_for_response",
},
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn s(v: &str) -> Tag {
Tag::String(v.into())
}
/// The register dialog AuthMe 6 sends in configuration (the shape its
/// `show_dialog` packet has on the test bed).
fn register() -> Tag {
Tag::compound([
("type", s("minecraft:multi_action")),
("title", s("Register")),
("can_close_with_escape", Tag::Byte(0)),
("after_action", s("wait_for_response")),
(
"body",
Tag::compound([
("type", s("minecraft:plain_message")),
("contents", s("Choose a password")),
]),
),
(
"inputs",
Tag::List(vec![Tag::compound([
("type", s("minecraft:text")),
("key", s("password")),
("label", s("Password")),
])]),
),
(
"actions",
Tag::List(vec![
Tag::compound([
("label", s("Register")),
(
"action",
Tag::compound([
("type", s("minecraft:dynamic/custom")),
("id", s("authme:prejoin-register/submit")),
]),
),
]),
Tag::compound([
("label", s("Cancel")),
(
"action",
Tag::compound([
("type", s("minecraft:dynamic/run_command")),
("template", s("say $(password) $(missing)!")),
]),
),
]),
]),
),
])
}
#[test]
fn decodes_a_multi_action_dialog_with_defaults() {
let d = Dialog::parse(&register()).unwrap();
assert_eq!(d.title.plain(), "Register");
assert!(!d.can_close_with_escape);
assert!(d.pause);
assert_eq!(d.after_action, AfterAction::WaitForResponse);
assert!(matches!(&d.body[..], [Body::Message { width: 200, .. }]));
let Kind::MultiAction {
actions,
exit,
columns,
} = &d.kind
else {
panic!("{:?}", d.kind)
};
assert_eq!((actions.len(), exit.is_none(), *columns), (2, true, 2));
assert_eq!(actions[0].width, 150);
assert!(d.on_cancel().is_none());
let [
Input {
key,
control:
Control::Text {
max_length: 32,
width: 200,
..
},
},
] = &d.inputs[..]
else {
panic!("{:?}", d.inputs)
};
assert_eq!(key, "password");
}
#[test]
fn actions_carry_the_input_values() {
let d = Dialog::parse(&register()).unwrap();
let values = [InputValue::Text("p\"w".into())];
let Kind::MultiAction { actions, .. } = &d.kind else {
unreachable!()
};
let custom = actions[0]
.action
.as_ref()
.unwrap()
.click(&d.inputs, &values);
assert_eq!(
custom,
Some(Click::Custom {
id: "authme:prejoin-register/submit".into(),
payload: Some(Tag::compound([("password", s("p\"w"))])),
})
);
// The template escapes the text; a key no input has becomes nothing.
let command = actions[1]
.action
.as_ref()
.unwrap()
.click(&d.inputs, &values);
assert_eq!(command, Some(Click::RunCommand("say p\\\"w !".into())));
}
#[test]
fn a_notice_without_an_action_has_ok() {
let d = Dialog::parse(&Tag::compound([("type", s("notice")), ("title", s("Hi"))])).unwrap();
let Kind::Notice(b) = &d.kind else {
unreachable!()
};
assert_eq!(b.label, Text::translate("gui.ok", &[]));
// Without a title, or with an unknown type, there is no dialog.
assert!(Dialog::parse(&Tag::compound([("type", s("notice"))])).is_none());
assert!(Dialog::parse(&Tag::compound([("type", s("x")), ("title", s("Hi"))])).is_none());
}
#[test]
fn number_ranges_snap_to_their_step() {
let mut range = Control::NumberRange {
width: 200,
label: Text::literal("n"),
label_format: "options.generic_value".into(),
start: 0.0,
end: 10.0,
initial: Some(4.0),
step: Some(3.0),
};
assert_eq!(range.initial(), InputValue::Slider(0.4));
assert_eq!(range.scaled(&InputValue::Slider(0.62)), Some(7.0));
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(10.0));
let Control::NumberRange { step, .. } = &mut range else {
unreachable!()
};
*step = Some(4.0);
// 12 is out of range: one step less.
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(8.0));
assert_eq!(range.substitution(&InputValue::Slider(0.0)), "0");
assert_eq!(number_string(2.5), "2.5");
}
}
+382
View File
@@ -0,0 +1,382 @@
//! `DialogScreen` and its kinds (`SimpleDialogScreen`, `MultiButtonDialogScreen`):
//! where a server dialog's title, body, inputs and buttons go in a
//! `HeaderAndFooterLayout` (a 33 high header, the body in a `ScrollableLayout`,
//! the footer), and the `WaitingForResponseScreen` an answer can leave open.
use crate::{
dialog::{Body, Control, Dialog, Kind},
font::Font,
text::Text,
};
/// `HeaderAndFooterLayout.DEFAULT_HEADER_AND_FOOTER_HEIGHT`.
const BAR: f32 = 33.0;
/// `Checkbox.getBoxSize`.
pub const BOX: f32 = 17.0;
/// `DialogScreen.WARNING_BUTTON_SPRITES`: normal, disabled, highlighted.
pub const WARNING_SPRITES: [&str; 3] = [
"gui/sprites/dialog/warning_button",
"gui/sprites/dialog/warning_button_disabled",
"gui/sprites/dialog/warning_button_highlighted",
];
/// One drawn piece; `y` is from the top of the body (before it scrolls) for
/// the body's parts, from the top of the screen for the footer's.
#[derive(Clone, Debug, PartialEq)]
pub enum Part {
/// A line of text and where it starts.
Line(Text, f32, f32),
/// A text input's box.
Field { input: usize, rect: [f32; 4] },
/// A boolean input: the box, its label right of it.
Check { input: usize, rect: [f32; 4] },
/// A button of `Dialog::buttons`.
Button { index: usize, rect: [f32; 4] },
}
#[derive(Clone, Debug)]
pub struct Layout {
/// The title and where it is drawn.
pub title: (f32, f32),
pub warning: [f32; 4],
/// The body's visible area (`ScrollableLayout`'s container): x, y, w, h.
pub area: [f32; 4],
/// The body's full height: more than the area's scrolls.
pub content: f32,
pub body: Vec<Part>,
pub footer: Vec<Part>,
}
/// A laid-out element of a `LinearLayout` before it is placed.
struct Element {
w: f32,
h: f32,
parts: Vec<Part>,
}
impl Element {
/// Its parts moved to `(x, y)`.
fn at(self, x: f32, y: f32) -> impl Iterator<Item = Part> {
self.parts.into_iter().map(move |p| match p {
Part::Line(t, px, py) => Part::Line(t, px + x, py + y),
Part::Field { input, rect } => Part::Field {
input,
rect: shift(rect, x, y),
},
Part::Check { input, rect } => Part::Check {
input,
rect: shift(rect, x, y),
},
Part::Button { index, rect } => Part::Button {
index,
rect: shift(rect, x, y),
},
})
}
}
fn shift([x, y, w, h]: [f32; 4], dx: f32, dy: f32) -> [f32; 4] {
[x + dx, y + dy, w, h]
}
/// `FrameLayout.alignInDimension` at 0.5: the offset that centres `inner`.
fn centre(outer: f32, inner: f32) -> f32 {
((outer - inner) * 0.5).trunc()
}
/// `FocusableTextWidget` with the body's settings: `width` wide, the text
/// wrapped to `width - 8` and centred, 4 of padding all round.
fn message(font: &Font, contents: &Text, width: f32) -> Element {
let lines = font.split_lines(contents, width - 8.0);
let mid = (width / 2.0).trunc();
let parts = lines
.into_iter()
.enumerate()
.map(|(i, (line, _))| {
let x = mid - (font.width_text(&line) / 2.0).trunc();
Part::Line(line, x, 4.0 + 9.0 * i as f32)
})
.collect::<Vec<_>>();
Element {
w: width,
h: 9.0 * parts.len() as f32 + 8.0,
parts,
}
}
/// `InputControlHandlers`: the control for input `i`, if Horizon has it.
fn input(font: &Font, i: usize, control: &Control) -> Option<Element> {
Some(match control {
Control::Text {
width,
label,
label_visible,
..
} => {
let w = *width as f32;
if !label_visible {
return Some(Element {
w,
h: 20.0,
parts: vec![Part::Field {
input: i,
rect: [0.0, 0.0, w, 20.0],
}],
});
}
// CommonLayouts.labeledElement: the label, 4 below it the box,
// both on the left.
Element {
w: w.max(font.width_text(label)),
h: 9.0 + 4.0 + 20.0,
parts: vec![
Part::Line(label.clone(), 0.0, 0.0),
Part::Field {
input: i,
rect: [0.0, 13.0, w, 20.0],
},
],
}
}
Control::Boolean { label, .. } => {
let w = BOX + 4.0 + font.width_text(label);
Element {
w,
h: BOX,
parts: vec![Part::Check {
input: i,
rect: [0.0, 0.0, w, BOX],
}],
}
}
Control::SingleOption { .. } | Control::NumberRange { .. } => return None,
})
}
/// `DialogScreen.packControlsIntoColumns`: full rows in a grid 2 apart, what
/// is left in a centred row under them.
fn columns(widths: &[f32], columns: usize, first: usize) -> Element {
let columns = columns.max(1);
let full = widths.len() / columns * columns;
let row_width = |ws: &[f32]| ws.iter().sum::<f32>() + 2.0 * (ws.len().max(1) - 1) as f32;
let mut col = vec![0.0f32; columns];
for (i, w) in widths[..full].iter().enumerate() {
col[i % columns] = col[i % columns].max(*w);
}
let last = &widths[full..];
if !last.is_empty() {
// GridLayout spreads a cell over every column it spans (Divisor).
let spread = row_width(last) - 2.0 * (columns - 1) as f32;
let (each, extra) = ((spread / columns as f32).floor(), spread % columns as f32);
for (c, w) in col.iter_mut().enumerate() {
*w = w.max(each + f32::from(u8::from((c as f32) < extra)));
}
}
let x_of = |c: usize| col[..c].iter().sum::<f32>() + 2.0 * c as f32;
let mut parts = Vec::new();
for (i, w) in widths[..full].iter().enumerate() {
let (r, c) = (i / columns, i % columns);
parts.push(Part::Button {
index: first + i,
rect: [x_of(c) + centre(col[c], *w), 22.0 * r as f32, *w, 20.0],
});
}
let width = x_of(columns - 1) + col[columns - 1];
if !last.is_empty() {
let y = 22.0 * (full / columns) as f32;
let mut x = centre(width, row_width(last));
for (i, w) in last.iter().enumerate() {
parts.push(Part::Button {
index: first + full + i,
rect: [x, y, *w, 20.0],
});
x += w + 2.0;
}
}
let rows = full / columns + usize::from(!last.is_empty());
Element {
w: width,
h: (22.0 * rows as f32 - 2.0).max(0.0),
parts,
}
}
impl Layout {
/// `DialogScreen.init` and `repositionElements` on a `w` by `h` screen.
pub fn new(dialog: &Dialog, font: &Font, (w, h): (f32, f32)) -> Self {
// The header: the title, 10 right of it the warning button, both
// centred together.
let tw = font.width_text(&dialog.title);
let (hx, hy) = (centre(w, tw + 30.0), centre(BAR, 20.0));
let title = (hx, hy + centre(20.0, 9.0));
let warning = [hx + tw + 10.0, hy, 20.0, 20.0];
let mut elements: Vec<Element> = dialog
.body
.iter()
.filter_map(|b| match b {
Body::Message { contents, width } => Some(message(font, contents, *width as f32)),
Body::Item { .. } => None,
})
.collect();
elements.extend(
dialog
.inputs
.iter()
.enumerate()
.filter_map(|(i, input_)| input(font, i, &input_.control)),
);
let buttons = dialog.buttons();
let (listed, footer_buttons, footer_h) = match &dialog.kind {
Kind::MultiAction {
actions,
exit,
columns: n,
} => {
let widths: Vec<f32> = actions.iter().map(|b| b.width as f32).collect();
elements.push(columns(&widths, *n as usize, 0));
// ButtonListDialogScreen: the exit button in the footer, else a 5 high one.
let footer = exit.as_ref().map(|_| actions.len()).into_iter().collect();
(
actions.len(),
footer,
if exit.is_some() { BAR } else { 5.0 },
)
}
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => {
let footer = exit.as_ref().map(|_| 0).into_iter().collect();
(0, footer, if exit.is_some() { BAR } else { 5.0 })
}
// SimpleDialogScreen: the buttons side by side, 8 apart.
Kind::Notice(_) | Kind::Confirmation { .. } => {
(0, (0..buttons.len()).collect::<Vec<_>>(), BAR)
}
};
debug_assert!(listed + footer_buttons.len() <= buttons.len());
// The body: a column 10 apart, each element centred in it.
let body_w = elements.iter().map(|e| e.w).fold(0.0, f32::max);
let content = elements.iter().map(|e| e.h).sum::<f32>()
+ 10.0 * elements.len().saturating_sub(1) as f32;
// ScrollableLayout: 10 each side for the scrollbar (ReserveStrategy.BOTH),
// no higher than what the header and footer leave.
let area_w = body_w + 20.0;
let area_h = content.min(h - BAR - footer_h).max(0.0);
let area_y = (BAR + 30.0).min(h - footer_h - area_h);
let area_x = centre(w, area_w);
let mut body = Vec::new();
let mut y = 0.0;
for e in elements {
let (x, eh) = (area_x + 10.0 + centre(body_w, e.w), e.h);
body.extend(e.at(x, y));
y += eh + 10.0;
}
let widths: Vec<f32> = footer_buttons
.iter()
.map(|&i| buttons[i].width as f32)
.collect();
let row = widths.iter().sum::<f32>() + 8.0 * widths.len().saturating_sub(1) as f32;
let (mut x, fy) = (centre(w, row), h - footer_h + centre(footer_h, 20.0));
let mut footer = Vec::new();
for (&i, bw) in footer_buttons.iter().zip(&widths) {
footer.push(Part::Button {
index: i,
rect: [x, fy, *bw, 20.0],
});
x += bw + 8.0;
}
Self {
title,
warning: Self::in_bounds(warning, w, h),
area: [area_x, area_y, area_w, area_h],
content,
body,
footer,
}
}
/// `makeSureWarningButtonIsInBounds`.
fn in_bounds(r: [f32; 4], w: f32, h: f32) -> [f32; 4] {
if r[0] < 0.0 || r[1] < 0.0 || r[0] > w - 20.0 || r[1] > h - 20.0 {
[(w - 40.0).max(0.0), 5.0f32.min(h), 20.0, 20.0]
} else {
r
}
}
/// Every part where it is drawn with the body scrolled by `scroll`, and
/// whether it is in the body (clipped to its area).
pub fn placed(&self, scroll: f32) -> impl Iterator<Item = (Part, bool)> + '_ {
let dy = self.area[1] - scroll;
let body = self.body.iter().map(move |p| {
let p = match p.clone() {
Part::Line(t, x, y) => Part::Line(t, x, y + dy),
Part::Field { input, rect } => Part::Field {
input,
rect: shift(rect, 0.0, dy),
},
Part::Check { input, rect } => Part::Check {
input,
rect: shift(rect, 0.0, dy),
},
Part::Button { index, rect } => Part::Button {
index,
rect: shift(rect, 0.0, dy),
},
};
(p, true)
});
body.chain(self.footer.iter().map(|p| (p.clone(), false)))
}
}
/// `WaitingForResponseScreen`: its Back button's label after `ticks`, and
/// whether it shows and works (it shows after a second, works after five).
pub fn waiting_button(ticks: u32) -> (Text, bool, bool) {
let seconds = (ticks / 20).min(5);
let label = match seconds {
0 => Text::literal(""),
5 => Text::translate("gui.back", &[]),
s => Text::translate(
"gui.waitingForResponse.button.inactive",
&[Text::literal((5 - s).to_string())],
),
};
(label, seconds >= 1, seconds == 5)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grids_pack_full_rows_and_centre_the_rest() {
// AuthMe's two buttons: one row, 2 apart.
let two = columns(&[150.0, 150.0], 2, 0);
assert_eq!((two.w, two.h), (302.0, 20.0));
// Three in two columns: the third alone, centred under them.
let three = columns(&[150.0, 150.0, 150.0], 2, 0);
assert_eq!((three.w, three.h), (302.0, 42.0));
assert_eq!(
three.parts[2],
Part::Button {
index: 2,
rect: [76.0, 22.0, 150.0, 20.0]
}
);
// One in two columns spreads over both.
let one = columns(&[100.0], 2, 0);
assert_eq!(one.w, 100.0);
}
#[test]
fn the_waiting_screens_button_counts_down() {
assert!(!waiting_button(0).1);
assert_eq!(
waiting_button(20).0,
Text::translate(
"gui.waitingForResponse.button.inactive",
&[Text::literal("4")]
)
);
assert_eq!(
waiting_button(100),
(Text::translate("gui.back", &[]), true, true)
);
}
}
+50 -5
View File
@@ -33,7 +33,11 @@ impl Cost {
#[derive(Clone, Debug)]
pub struct Enchantment {
pub id: Arc<str>,
/// The name the pinned English map gave at load: the fallback for a
/// language that has no entry for the key below.
pub description: String,
/// `description`'s translation key (`enchantment.minecraft.<name>`).
pub description_key: String,
pub max_level: u32,
pub weight: u32,
pub anvil_cost: u32,
@@ -224,6 +228,7 @@ impl Enchantments {
.get(key)
.cloned()
.unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")),
description_key: key.to_owned(),
max_level: v["max_level"].as_u64().unwrap_or(1) as u32,
weight: v["weight"].as_u64().unwrap_or(1) as u32,
anvil_cost: v["anvil_cost"].as_u64().unwrap_or(0) as u32,
@@ -329,16 +334,26 @@ impl Enchantments {
}
/// `Enchantment.getFullname` as plain text and whether it is a curse (red).
pub fn full_name(&self, id: &str, level: u32) -> (String, bool) {
let language = crate::lang::current();
self.full_name_in(language.as_deref(), id, level)
}
/// `full_name` against `language`; `None` (no language loaded: a
/// dedicated server, the probes) keeps the English names loaded above.
pub fn full_name_in(
&self,
language: Option<&crate::lang::Language>,
id: &str,
level: u32,
) -> (String, bool) {
let tr = |key: &str| language.and_then(|l| l.get(key).map(str::to_owned));
let Some(e) = self.get(id) else {
return (format!("{id} {}", level_name(level)), false);
};
let mut name = e.description.clone();
let mut name = tr(&e.description_key).unwrap_or_else(|| e.description.clone());
if level != 1 || e.max_level != 1 {
name.push(' ');
name.push_str(
self.lang
.get(&format!("enchantment.level.{level}"))
.map_or(&level_name(level), |s| s),
&tr(&format!("enchantment.level.{level}")).unwrap_or_else(|| level_name(level)),
);
}
(name, self.is_curse(id))
@@ -771,7 +786,7 @@ pub(crate) mod tests {
let defs = [
(
"minecraft:sharpness",
json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}),
json!({"anvil_cost":1,"description":{"translate":"enchantment.minecraft.sharpness"},"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}),
),
(
"minecraft:smite",
@@ -795,6 +810,7 @@ pub(crate) mod tests {
.map(|(id, v)| Enchantment {
id: Arc::from(*id),
description: id.trim_start_matches("minecraft:").into(),
description_key: v["description"]["translate"].as_str().unwrap_or("").into(),
max_level: v["max_level"].as_u64().unwrap() as u32,
weight: v["weight"].as_u64().unwrap() as u32,
anvil_cost: v["anvil_cost"].as_u64().unwrap() as u32,
@@ -1088,4 +1104,33 @@ pub(crate) mod tests {
assert!(!e.compatible("minecraft:sharpness", "minecraft:smite"));
assert!(e.compatible("minecraft:sharpness", "minecraft:unbreaking"));
}
/// The enchantment's name and its level come from the selected language,
/// with the English name loaded above as the fallback.
#[test]
fn names_follow_the_language() {
struct Mem(HashMap<String, Vec<u8>>);
impl crate::lang::ResourceSource for Mem {
fn read(&self, path: &str) -> Option<Vec<u8>> {
self.0.get(path).cloned()
}
}
let ru = Mem(HashMap::from([(
"assets/minecraft/lang/ru_ru.json".to_owned(),
r#"{"enchantment.minecraft.sharpness":"Острота","enchantment.level.5":"V"}"#
.as_bytes()
.to_vec(),
)]));
let ru = crate::lang::Language::load(&[&ru], "ru_ru");
let e = sample();
assert_eq!(
e.full_name_in(Some(&ru), "minecraft:sharpness", 5).0,
"Острота V"
);
// mending carries no key in the fixture: the English name stays.
assert_eq!(
e.full_name_in(Some(&ru), "minecraft:mending", 1).0,
"mending"
);
}
}
+60 -7
View File
@@ -10,6 +10,8 @@ use crate::{
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::block_collision::BlockCollisionRegistry;
mod fluids;
#[derive(Clone, Debug)]
pub struct ItemEntity {
pub health: i32,
@@ -165,18 +167,16 @@ impl ItemEntity {
facts: &BlockFacts,
collision: &BlockCollisionRegistry<'_>,
no_physics: bool,
fluids: &crate::motion::FluidResources,
) -> bool {
self.ticks += 1;
self.previous = self.position;
if self.pickup_delay > 0 && self.pickup_delay != u32::MAX {
self.pickup_delay -= 1;
}
let eye = world.block(
self.position.x.floor() as i32,
(self.position.y + 0.1).floor() as i32,
self.position.z.floor() as i32,
);
let in_water = facts.get(eye).fluid == Fluid::Water;
// Entity.baseTick pushes before ItemEntity applies buoyancy and moves.
let (water_height, lava_height) = self.update_fluids(world, fluids);
let in_water = water_height > f64::from(0.1f32);
if in_water {
// ItemEntity.setUnderwaterMovement
self.velocity = Vec3::new(
@@ -184,7 +184,7 @@ impl ItemEntity {
self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 },
self.velocity.z * 0.99,
);
} else if facts.get(eye).fluid == Fluid::Lava {
} else if lava_height > f64::from(0.1f32) {
self.velocity = Vec3::new(
self.velocity.x * 0.95,
self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 },
@@ -245,6 +245,8 @@ impl ItemEntity {
}
}
self.age += 1;
// ItemEntity.tick refreshes immersion and pushes again after moving.
self.update_fluids(world, fluids);
self.age < 6000 && self.position.y > -128.0
}
/// `ItemEntity.isMergable` at `age`: a stack below its size whose pickup
@@ -589,6 +591,57 @@ impl Painting {
)
}
}
/// The `DyeColor` ordinal of a colour name (`DyeColor.byName`), white when
/// the name is unknown.
pub fn dye_index(name: &str) -> u8 {
crate::mobs::render::DYE_NAMES
.iter()
.position(|n| *n == name)
.unwrap_or(0) as u8
}
/// A cushion (`Cushion`, a `BlockAttachedEntity`): a 1 x 0.25 block pillow
/// that seats a player. It sits on the top face of a block, at the clicked
/// height, and is coloured by its `DyeColor`.
#[derive(Clone, Debug)]
pub struct Cushion {
pub id: u32,
/// `Entity.position`: the bottom centre of the cushion.
pub position: Vec3,
/// `BlockAttachedEntity.pos` (the saved `block_pos`).
pub pos: [i32; 3],
pub yaw: f32,
/// `DyeColor` ordinal: white 0, orange 1, ..., black 15.
pub color: u8,
/// BlockAttachedEntity.ticksSinceLastCheck.
pub check_interval: u32,
}
impl Cushion {
/// `Entity.makeBoundingBox`: x and z half a block out, y to y + 0.25.
pub fn bounds(&self) -> ([f64; 3], [f64; 3]) {
let p = self.position;
(
[p.x - 0.5, p.y, p.z - 0.5],
[p.x + 0.5, p.y + 0.25, p.z + 0.5],
)
}
/// The `DyeColor` name of the cushion.
pub fn color_name(&self) -> &'static str {
crate::mobs::render::DYE_NAMES[usize::from(self.color.min(15))]
}
/// `Cushion.getCushionItemStackWithData`: the matching coloured item.
pub fn item(&self) -> String {
format!("minecraft:{}_cushion", self.color_name())
}
/// `Cushion.interact`'s seat: the vehicle's PASSENGER attachment
/// `(0, 0.25, 0)` less the player's `(0, 0.6, 0)`.
pub fn seat(&self) -> Vec3 {
Vec3::new(self.position.x, self.position.y - 0.35, self.position.z)
}
/// `Entity.getDismountLocationForPassenger`: on top of the cushion.
pub fn dismount(&self) -> Vec3 {
Vec3::new(self.position.x, self.position.y + 0.25, self.position.z)
}
}
/// An item frame or glow item frame (`ItemFrame`).
#[derive(Clone, Debug)]
pub struct ItemFrame {
@@ -0,0 +1,216 @@
//! Dropped-item immersion and currents through the shared vanilla fluid helpers.
use super::ItemEntity;
use crate::{
motion::{FluidResources, FluidTags, LAVA, WATER},
world::World,
};
use horizon_core::{
geometry::{Aabb, Direction, Vec3},
position::BlockPos,
};
use horizon_world::{
entity_fluid::{
CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership,
FluidSections, FluidTagId,
},
fluid::{FluidHeightWorld, FluidKind, FluidState},
fluid_flow::{FluidFlowWorld, flow_at},
registry::BlockStateId,
};
type Error = std::convert::Infallible;
struct ItemFluidWorld<'a> {
item: &'a mut ItemEntity,
world: &'a World,
fluids: &'a FluidResources,
}
impl ItemEntity {
pub(super) fn update_fluids(&mut self, world: &World, fluids: &FluidResources) -> (f64, f64) {
let mut interaction = EntityFluidInteraction::new([WATER, LAVA]);
let mut scene = ItemFluidWorld {
item: self,
world,
fluids,
};
if interaction.update(&mut scene, false, 4096).is_err() {
return (0.0, 0.0);
}
let water_height = interaction.fluid_height(&scene, WATER);
let lava_height = interaction.fluid_height(&scene, LAVA);
let _ = interaction.apply_current(&mut scene, WATER, 0.014);
let _ = interaction.apply_current(
&mut scene,
LAVA,
if world.fast_lava {
0.007
} else {
0.0023333333333333335
},
);
(water_height, lava_height)
}
}
impl FluidMembership for ItemFluidWorld<'_> {
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
FluidTags.fluid_in_tag(kind, tag)
}
}
impl CurrentTarget for ItemFluidWorld<'_> {
type Error = Error;
fn is_player_class(&self) -> bool {
false
}
fn velocity(&mut self) -> Result<Vec3, Error> {
Ok(self.item.velocity)
}
fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Error> {
let v = self.item.velocity;
let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z);
if delta.is_finite() && sum.is_finite() {
self.item.velocity = sum;
}
Ok(())
}
}
impl FluidInteractionWorld for ItemFluidWorld<'_> {
type Error = Error;
type Chunk = ();
fn interaction_box(&mut self) -> Result<Option<Aabb>, Error> {
Ok(Some(
self.item.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)),
))
}
fn loaded_chunk(&mut self, x: i32, z: i32) -> Result<Option<()>, Error> {
Ok(self.world.chunks.contains_key(&(x, z)).then_some(()))
}
fn chunk_sections(&mut self, _: ()) -> Result<FluidSections<'_>, Error> {
static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS];
Ok(FluidSections {
minimum_section_y: crate::chunk::MIN_Y >> 4,
has_fluid: &SECTIONS,
})
}
fn bounding_box_min_y(&self) -> f64 {
self.item.position.y
}
fn block_x(&self) -> i32 {
self.item.position.x.floor() as i32
}
fn eye_y(&mut self) -> Result<f64, Error> {
Ok(self.item.position.y + f64::from(0.2125f32))
}
fn block_z(&self) -> i32 {
self.item.position.z.floor() as i32
}
fn fluid_state(&mut self, p: BlockPos) -> Result<FluidState, Error> {
Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z)))
}
fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32, Error> {
f.height_at(self, [p.x, p.y, p.z])
}
fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32, Error> {
f.camera_height_at(self, [p.x, p.y, p.z])
}
fn flow(&mut self, f: FluidState, p: BlockPos) -> Result<Vec3, Error> {
flow_at(self, f, p)
}
}
impl FluidHeightWorld for ItemFluidWorld<'_> {
type Error = Error;
fn fluid(&mut self, p: [i32; 3]) -> Result<FluidState, Error> {
Ok(self.fluids.fluid(self.world.block(p[0], p[1], p[2])))
}
fn sturdy_down(&mut self, p: [i32; 3]) -> Result<bool, Error> {
let state = self.world.block(p[0], p[1], p[2]);
Ok(self.fluids.sturdy(state, Direction::Down))
}
}
impl FluidFlowWorld for ItemFluidWorld<'_> {
type Error = Error;
type Block = BlockStateId;
fn fluid(&mut self, p: BlockPos) -> Result<FluidState, Error> {
Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z)))
}
fn block(&mut self, p: BlockPos) -> Result<BlockStateId, Error> {
Ok(self.world.block(p.x, p.y, p.z))
}
fn blocks_fluid_flow(&self, s: BlockStateId) -> bool {
self.fluids.blocks_flow(s)
}
fn is_ice_class(&self, s: BlockStateId) -> bool {
self.fluids.ice(s)
}
fn is_face_sturdy(
&mut self,
s: BlockStateId,
_: BlockPos,
d: Direction,
) -> Result<bool, Error> {
Ok(self.fluids.sturdy(s, d))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn items_follow_flowing_water_but_still_water_has_no_horizontal_push() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = crate::assets::Assets::load(&root).unwrap();
let render = assets.reload(&root).unwrap();
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap();
let fluids = FluidResources::new(&assets, &facts).unwrap();
let collision = crate::collisions::load(&root, assets.registry).unwrap();
let mut world = World::test_scene(&assets, &render, 3).unwrap();
let stone = assets.registry.default_state("minecraft:stone").unwrap();
let water = assets.registry.default_state("minecraft:water").unwrap();
let mut state = assets.registry.state(water).unwrap().clone();
state.properties.insert("level".into(), "1".into());
let flowing = assets.registry.resolve(&state).unwrap();
for x in 19..=21 {
for z in 19..=21 {
world.set(x, 3, z, stone).unwrap();
world.set(x, 4, z, water).unwrap();
}
}
let at = Vec3::new(20.5, 4.0, 20.5);
let item = ItemEntity {
id: 1,
health: 5,
fire_ticks: 0,
stack: crate::items::ItemStack {
item: "minecraft:sugar_cane".into(),
count: 1,
damage: 0,
extra: None,
},
thrower: None,
position: at,
previous: at,
velocity: Vec3::ZERO,
on_ground: false,
age: 0,
pickup_delay: 0,
bob_offset: 0.0,
ticks: 0,
};
let mut still = item.clone();
assert!(still.tick(&world, &facts, &collision, false, &fluids));
assert_eq!(still.position.x, at.x);
assert_eq!(still.velocity.x, 0.0);
world.set(21, 4, 20, flowing).unwrap();
let mut carried = item;
assert!(carried.tick(&world, &facts, &collision, false, &fluids));
// First push is damped by buoyancy before motion, second follows drag.
assert!((carried.position.x - at.x - 0.014 * 0.99).abs() < 1e-12);
assert!((carried.velocity.x - (0.014 * 0.99 * 0.98 + 0.014)).abs() < 1e-12);
for _ in 0..20 {
carried.tick(&world, &facts, &collision, false, &fluids);
}
assert!(carried.position.x > at.x + 0.5);
}
}
+15 -5
View File
@@ -25,6 +25,20 @@ impl Culler {
vertices: &mut Vec<crate::mesher::Vertex>,
start: usize,
opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
let hidden = self.hidden(vertices, start, opaque);
if hidden {
vertices.truncate(start);
}
hidden
}
/// Whether this entity's completed camera-relative mesh (`vertices[start..]`) is hidden.
pub fn hidden(
&self,
vertices: &[crate::mesher::Vertex],
start: usize,
opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
if start >= vertices.len() || self.remaining.get() == 0 {
return false;
@@ -42,11 +56,7 @@ impl Culler {
}
}
// Cover floating-point and rasterization edges as well as the vertices.
if self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque) {
vertices.truncate(start);
return true;
}
false
self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque)
}
/// Returns true only when a complete opaque block plane covers the bounds.
+74 -1
View File
@@ -6,7 +6,7 @@
//! survive a Horizon save.
use crate::{
arrows::Pickup,
entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting},
entities::{ArmorStand, Cushion, ExperienceOrb, ItemEntity, ItemFrame, Painting},
mobs::{Mob, MobType, Who},
projectiles::{Projectile, ProjectileKind},
save::{
@@ -1313,6 +1313,79 @@ pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, String)> {
let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8;
Some((pos, facing, text(tag.get("variant"))?))
}
/// Cushion.addAdditionalSaveData: the block it sits on and its colour.
pub fn cushion_to_nbt(c: &Cushion, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
let base = Base {
id: "minecraft:cushion",
uuid,
position: c.position,
motion: Vec3::ZERO,
rotation: [c.yaw, 0.0],
on_ground: false,
fall_distance: 0.0,
};
let mut tag = base.tag(raw);
put(&mut tag, "block_pos", Tag::IntArray(c.pos.to_vec()));
put(&mut tag, "color", string(c.color_name()));
tag
}
/// The position, block position, yaw and colour of a saved cushion.
pub fn cushion_from_nbt(tag: &Tag, id: u32) -> Option<Cushion> {
let position = position(tag)?;
let pos = match tag.get("block_pos") {
Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]],
_ => [
position.x.floor() as i32,
position.y.floor() as i32,
position.z.floor() as i32,
],
};
let yaw = match tag.get("Rotation") {
Some(Tag::List(l)) => l
.first()
.and_then(|v| crate::save::float(Some(v)))
.unwrap_or(0.0) as f32,
_ => 0.0,
};
let color =
crate::entities::dye_index(&text(tag.get("color")).unwrap_or_else(|| "white".into()));
Some(Cushion {
id,
position,
pos,
yaw,
color,
check_interval: 0,
})
}
#[cfg(test)]
mod cushion_tests {
use super::*;
#[test]
fn cushion_save_preserves_color_anchor_rotation_and_unknown_data() {
let cushion = Cushion {
id: 7,
position: Vec3::new(-1.5, 64.5, 3.5),
pos: [-2, 64, 3],
yaw: 270.0,
color: 14,
check_interval: 55,
};
let raw = Tag::compound([("CustomName", string("Seat"))]);
let tag = cushion_to_nbt(&cushion, [1, 2, 3, 4], Some(&raw));
assert_eq!(text(tag.get("CustomName")).as_deref(), Some("Seat"));
let loaded = cushion_from_nbt(&tag, 8).unwrap();
assert_eq!(loaded.id, 8);
assert_eq!(loaded.position, cushion.position);
assert_eq!(loaded.pos, cushion.pos);
assert_eq!(loaded.yaw, cushion.yaw);
assert_eq!(loaded.color_name(), "red");
assert_eq!(loaded.check_interval, 0);
assert_eq!(loaded.bounds(), cushion.bounds());
}
}
/// ItemFrame.addAdditionalSaveData.
pub fn item_frame_to_nbt(f: &ItemFrame, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
let (lo, hi) = f.bounds();
+36 -331
View File
@@ -1,4 +1,4 @@
//! Horizon's optional extras (zoom, FPS counter, keystroke overlay): their
//! Horizon's optional extras (minimap, lighting, inventory tools): their
//! settings, kept in `horizon-extras.txt` next to `options.txt` so that file
//! stays exactly vanilla's, and the logic behind them. Every extra is off by
//! default; see `docs/extras.md`. Horizon's own switches outside the Extras page
@@ -6,17 +6,8 @@
use std::{collections::VecDeque, fs, path::Path};
pub const FILE: &str = "horizon-extras.txt";
/// The name the options screen uses while the zoom key waits for a key.
pub const ZOOM_KEY: &str = "horizon.zoom";
/// The same for the sort key.
/// The name the options screen uses while the sort key waits for a key.
pub const SORT_KEY: &str = "horizon.sort";
/// Zoom levels the default cycles through, and the wheel's limits.
pub const ZOOM_LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10];
pub const ZOOM_MIN: f32 = 1.25;
/// `Camera.tickFov` keeps the field-of-view modifier at 0.1 or more.
pub const ZOOM_MAX: f32 = 10.0;
/// Each wheel step multiplies the zoom by this.
const ZOOM_STEP: f32 = 1.25;
/// The minimap's sizes in GUI pixels, and its zooms in blocks per pixel.
pub const MINIMAP_SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")];
@@ -81,6 +72,9 @@ pub struct Extras {
pub zoom_smooth: bool,
/// Divide mouse turning by the zoom.
pub zoom_sensitivity: bool,
/// The FPS counter and keystrokes extras are official mods now
/// (`moved_extras`): their old settings stay here until the game has
/// installed the mod for a player who had one on.
pub fps: bool,
pub fps_corner: Corner,
/// Also show the minimum and 1% low.
@@ -89,6 +83,9 @@ pub struct Extras {
pub keystrokes_corner: Corner,
/// Clicks per second under the mouse buttons.
pub keystrokes_cps: bool,
/// The official mods installed for the extras they replace, by mod id
/// (`movedToMods`): each is done once.
pub moved: Vec<String>,
pub minimap: bool,
pub minimap_corner: Corner,
/// Side in GUI pixels (`MINIMAP_SIZES`).
@@ -132,6 +129,7 @@ impl Default for Extras {
keystrokes: false,
keystrokes_corner: Corner::TopLeft,
keystrokes_cps: true,
moved: Vec::new(),
minimap: false,
minimap_corner: Corner::TopRight,
minimap_size: 96,
@@ -177,7 +175,7 @@ impl Extras {
"zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(),
"zoomLevel" => {
if let Ok(v) = value.parse::<u8>() {
e.zoom_level = v.clamp(2, ZOOM_MAX as u8);
e.zoom_level = v.clamp(2, 10);
}
}
"zoomSmooth" => e.zoom_smooth = flag(e.zoom_smooth),
@@ -190,6 +188,14 @@ impl Extras {
e.keystrokes_corner = Corner::parse(value, e.keystrokes_corner)
}
"keystrokesCps" => e.keystrokes_cps = flag(e.keystrokes_cps),
"movedToMods" => {
e.moved = value
.split(',')
.map(str::trim)
.filter(|id| !id.is_empty())
.map(str::to_owned)
.collect()
}
"minimap" => e.minimap = flag(e.minimap),
"minimapCorner" => e.minimap_corner = Corner::parse(value, e.minimap_corner),
"minimapSize" => {
@@ -219,7 +225,7 @@ impl Extras {
}
pub fn serialize(&self) -> String {
format!(
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\ndiscordPresence:{}\n",
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nmovedToMods:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\ndiscordPresence:{}\n",
bool_text(self.fullbright),
bool_text(self.dynamic_lights),
bool_text(self.zoom),
@@ -233,6 +239,7 @@ impl Extras {
bool_text(self.keystrokes),
self.keystrokes_corner.name(),
bool_text(self.keystrokes_cps),
self.moved.join(","),
bool_text(self.minimap),
self.minimap_corner.name(),
self.minimap_size,
@@ -254,11 +261,10 @@ impl Extras {
bool_text(self.discord_presence),
)
}
/// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for
/// Binds the extra key `name` (`SORT_KEY`); false for
/// another name (a vanilla mapping).
pub fn set_key(&mut self, name: &str, value: String) -> bool {
match name {
ZOOM_KEY => self.zoom_key = value,
SORT_KEY => self.sort_key = value,
_ => return false,
}
@@ -275,87 +281,12 @@ impl Extras {
}
}
/// The zoom key's state: held or not, and the zoom the wheel has set.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Zoom {
held: bool,
factor: f32,
}
impl Default for Zoom {
fn default() -> Self {
Self {
held: false,
factor: 1.0,
}
}
}
impl Zoom {
/// The key went down: start at the default level.
pub fn press(&mut self, level: u8) {
self.held = true;
self.factor = f32::from(level).clamp(ZOOM_MIN, ZOOM_MAX);
}
pub fn release(&mut self) {
self.held = false;
}
/// A press or release of the zoom key. Only a press while `playing` (no
/// screen or text field open) zooms; anywhere else the key belongs to
/// the screen, and the zoom lets go.
pub fn key(&mut self, pressed: bool, repeat: bool, playing: bool, level: u8) {
if !pressed || !playing {
self.release();
} else if !repeat {
self.press(level);
}
}
pub fn held(&self) -> bool {
self.held
}
/// Wheel steps while held (positive zooms in); false when not zooming.
pub fn scroll(&mut self, steps: f32) -> bool {
if !self.held {
return false;
}
self.factor = (self.factor * ZOOM_STEP.powf(steps)).clamp(ZOOM_MIN, ZOOM_MAX);
true
}
/// The zoom in effect: 1 when the key is up or the spyglass is in use
/// (scoping keeps vanilla's spyglass view).
pub fn factor(&self, scoping: bool) -> f32 {
if self.held && !scoping {
self.factor
} else {
1.0
}
}
}
/// Vanilla key mappings bound to the zoom key. The key still reaches them
/// (a key bound twice triggers both, as vanilla's do), so the Extras page
/// says so.
pub fn zoom_key_conflicts(e: &Extras, keys: &crate::keybinds::KeyBinds) -> Vec<&'static str> {
if e.zoom_key == "key.keyboard.unknown" {
return Vec::new();
}
crate::keybinds::MAPPINGS
.iter()
.map(|m| m.0)
.filter(|name| keys.get(name) == e.zoom_key)
.collect()
}
/// The field-of-view modifier target `Camera.tickFov` eases toward: vanilla's
/// (`getFieldOfViewModifier`) divided by the zoom. A zoom of 1 leaves it as is.
/// (`getFieldOfViewModifier`) divided by a mod's zoom (`render.set-zoom`). A
/// zoom of 1 leaves it as is.
pub fn fov_target(vanilla: f32, zoom: f32) -> f32 {
if zoom == 1.0 { vanilla } else { vanilla / zoom }
}
/// The mouse turning scale while zoomed.
pub fn turn_scale(zoom: f32, lower_sensitivity: bool) -> f64 {
if lower_sensitivity && zoom > 1.0 {
1.0 / f64::from(zoom)
} else {
1.0
}
}
/// Frame times over the last few seconds: frames per second, the minimum
/// and the 1% low, recomputed twice a second.
pub struct FpsCounter {
@@ -447,23 +378,6 @@ impl Cps {
pub enum Item {
Fullbright,
DynamicLights,
Zoom,
ZoomKey,
ZoomLevel,
ZoomSmooth,
ZoomSensitivity,
Fps,
FpsCorner,
FpsLows,
Keystrokes,
KeystrokesCorner,
KeystrokesCps,
Minimap,
MinimapCorner,
MinimapSize,
MinimapShape,
MinimapZoom,
MinimapRotate,
AutoReconnect,
MouseTweaks,
MouseTweaksWheel,
@@ -482,27 +396,6 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
Err("Lighting"),
Ok(Fullbright),
Ok(DynamicLights),
Err("Zoom"),
Ok(Zoom),
Ok(ZoomKey),
Ok(ZoomLevel),
Ok(ZoomSmooth),
Ok(ZoomSensitivity),
Err("Minimap"),
Ok(Minimap),
Ok(MinimapCorner),
Ok(MinimapSize),
Ok(MinimapShape),
Ok(MinimapZoom),
Ok(MinimapRotate),
Err("FPS counter"),
Ok(Fps),
Ok(FpsCorner),
Ok(FpsLows),
Err("Keystrokes"),
Ok(Keystrokes),
Ok(KeystrokesCorner),
Ok(KeystrokesCps),
Err("Inventory"),
Ok(MouseTweaks),
Ok(MouseTweaksWheel),
@@ -512,46 +405,16 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
Ok(AutoReconnect),
]
}
/// "1 block", "2 blocks", "½ block".
fn block_count(n: f32) -> String {
if n < 1.0 {
"½ block".into()
} else if n == 1.0 {
"1 block".into()
} else {
format!("{n} blocks")
}
}
fn next<T: Copy + PartialEq>(all: &[T], current: T, back: bool) -> T {
let i = all.iter().position(|v| *v == current).unwrap_or(0);
let n = all.len();
all[if back { (i + n - 1) % n } else { (i + 1) % n }]
}
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 => "Slower turning",
Item::Fps => "FPS counter",
Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => "Corner",
Item::Minimap => "Minimap",
Item::MinimapSize => "Size",
Item::MinimapShape => "Shape",
Item::MinimapZoom => "Zoom",
Item::MinimapRotate => "Turn with the player",
Item::AutoReconnect => "Auto-reconnect",
Item::MouseTweaks => "Mouse Tweaks controls",
Item::MouseTweaksWheel => "Scroll wheel moves items",
Item::Sort => "Sort buttons",
Item::SortKey => "Sort key",
Item::FpsLows => "Minimum and 1% low",
Item::Keystrokes => "Keystrokes",
Item::KeystrokesCps => "Clicks per second",
Item::NoAi => "No AI",
Item::AgentControl => "Agent Control",
Item::DiscordPresence => "Discord Rich Presence",
@@ -561,14 +424,10 @@ impl Item {
pub fn parent(self) -> Option<Item> {
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 | NoAi | AgentControl | DiscordPresence => {
Fullbright | DynamicLights | MouseTweaks | Sort | AutoReconnect | NoAi
| AgentControl | DiscordPresence => {
return None;
}
})
@@ -580,24 +439,9 @@ impl Item {
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.",
Item::ZoomSmooth => "Eases in and out like the spyglass.",
Item::ZoomSensitivity => "Turns slower the more you zoom in.",
Item::Fps => "Frames per second in a corner of the screen.",
Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => {
"Overlays in one corner stack."
}
Item::Minimap => "A map of the loaded terrain around you, in map colours.",
Item::MinimapSize => "How big the map is on screen.",
Item::MinimapShape => "Square or round.",
Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.",
Item::MinimapRotate => "Forward is up; off keeps north up.",
Item::AutoReconnect => {
"Rejoins a server after a lost connection or a restart, never after a kick or ban."
}
Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.",
Item::MouseTweaks => {
"Right-drag places one per slot, left-drag gathers the held item, Shift + left-drag moves every slot."
}
@@ -610,8 +454,6 @@ impl Item {
Item::SortKey => {
"Sorts the part under the cursor. Click, then press a key; Escape unbinds it."
}
Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.",
Item::KeystrokesCps => "Clicks in the last second under each mouse button.",
Item::NoAi => {
"Hides and turns off every AI feature: agent control, horizon-ctl and the MCP servers. The launcher's switch too."
}
@@ -627,8 +469,8 @@ impl Item {
pub fn cost(self) -> Option<crate::graphics_style::Cost> {
use crate::graphics_style::Cost;
match self {
Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
Item::Minimap | Item::DynamicLights => Some(Cost::Low),
Item::Fullbright => Some(Cost::None),
Item::DynamicLights => Some(Cost::Low),
Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None),
_ => None,
}
@@ -638,15 +480,6 @@ impl Item {
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,
Item::Fps => e.fps,
Item::FpsLows => e.fps_lows,
Item::Keystrokes => e.keystrokes,
Item::KeystrokesCps => e.keystrokes_cps,
Item::Minimap => e.minimap,
Item::MinimapRotate => e.minimap_rotate,
Item::AutoReconnect => e.auto_reconnect,
Item::MouseTweaks => e.mouse_tweaks,
Item::MouseTweaksWheel => e.mouse_tweaks_wheel,
@@ -660,65 +493,32 @@ impl Item {
/// The value of the other items, as their button shows it.
pub fn value(self, e: &Extras) -> String {
match self {
Item::ZoomKey => crate::keybinds::display_name(&e.zoom_key).plain(),
Item::SortKey => crate::keybinds::display_name(&e.sort_key).plain(),
Item::ZoomLevel => format!("{}x", e.zoom_level),
Item::FpsCorner => e.fps_corner.label().into(),
Item::KeystrokesCorner => e.keystrokes_corner.label().into(),
Item::MinimapCorner => e.minimap_corner.label().into(),
Item::MinimapSize => MINIMAP_SIZES
.iter()
.find(|s| s.0 == e.minimap_size)
.map_or("Medium", |s| s.1)
.into(),
Item::MinimapShape => if e.minimap_round { "Round" } else { "Square" }.into(),
Item::MinimapZoom => format!("{} per pixel", block_count(e.minimap_zoom)),
other => match other.switch(e) {
Some(true) => "On".into(),
_ => "Off".into(),
},
}
}
/// A click (`back` for the right button). The zoom key binds instead.
pub fn cycle(self, e: &mut Extras, back: bool) {
/// A click (`_back` for the right button: every item left is a switch,
/// so both flip it). The sort key binds instead.
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,
Item::Fps => e.fps = !e.fps,
Item::FpsLows => e.fps_lows = !e.fps_lows,
Item::Keystrokes => e.keystrokes = !e.keystrokes,
Item::KeystrokesCps => e.keystrokes_cps = !e.keystrokes_cps,
Item::ZoomLevel => e.zoom_level = next(&ZOOM_LEVELS, e.zoom_level, back),
Item::FpsCorner => e.fps_corner = next(&Corner::ALL, e.fps_corner, back),
Item::KeystrokesCorner => {
e.keystrokes_corner = next(&Corner::ALL, e.keystrokes_corner, back)
}
Item::Minimap => e.minimap = !e.minimap,
Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate,
Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect,
Item::MouseTweaks => e.mouse_tweaks = !e.mouse_tweaks,
Item::MouseTweaksWheel => e.mouse_tweaks_wheel = !e.mouse_tweaks_wheel,
Item::Sort => e.sort = !e.sort,
Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back),
Item::MinimapSize => {
let sizes: Vec<u8> = MINIMAP_SIZES.iter().map(|s| s.0).collect();
e.minimap_size = next(&sizes, e.minimap_size, back);
}
Item::MinimapShape => e.minimap_round = !e.minimap_round,
Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back),
Item::NoAi => e.no_ai = !e.no_ai,
Item::AgentControl => e.agent_control = !e.agent_control,
Item::DiscordPresence => e.discord_presence = !e.discord_presence,
Item::ZoomKey | Item::SortKey => {}
Item::SortKey => {}
}
}
/// The key name the options screen waits on for a key item.
pub fn key_name(self) -> Option<&'static str> {
match self {
Item::ZoomKey => Some(ZOOM_KEY),
Item::SortKey => Some(SORT_KEY),
_ => None,
}
@@ -750,6 +550,7 @@ mod tests {
e.fps_corner = Corner::BottomRight;
e.keystrokes = true;
e.keystrokes_cps = false;
e.moved = vec!["fps_overlay".into(), "keystrokes".into()];
e.minimap = true;
e.minimap_size = 128;
e.minimap_round = true;
@@ -775,43 +576,7 @@ mod tests {
}
#[test]
fn default_zoom_key_is_free_in_vanilla() {
let key = Extras::default().zoom_key;
assert!(crate::keybinds::key_code(&key).is_some());
assert!(
crate::keybinds::MAPPINGS.iter().all(|m| m.1 != key),
"{key} is a vanilla binding"
);
}
#[test]
fn zoom_is_vanilla_unless_held_and_not_scoping() {
let mut z = Zoom::default();
assert_eq!(z.factor(false), 1.0);
assert_eq!(fov_target(1.1, z.factor(false)), 1.1);
assert!(!z.scroll(1.0), "the wheel is the hotbar's when not zooming");
z.press(4);
assert_eq!(z.factor(false), 4.0);
assert_eq!(z.factor(true), 1.0, "the spyglass wins");
assert!((fov_target(1.0, 4.0) - 0.25).abs() < 1e-6);
assert!(z.scroll(1.0));
assert!((z.factor(false) - 5.0).abs() < 1e-5);
for _ in 0..40 {
z.scroll(1.0);
}
assert_eq!(z.factor(false), ZOOM_MAX);
for _ in 0..80 {
z.scroll(-1.0);
}
assert_eq!(z.factor(false), ZOOM_MIN);
z.release();
assert_eq!(z.factor(false), 1.0);
z.press(2);
assert_eq!(z.factor(false), 2.0, "each press starts at the default");
}
#[test]
fn zoom_target_eases_like_the_spyglass() {
fn a_mods_zoom_eases_like_the_spyglass() {
// Camera.tickFov halves the distance to the target each tick.
let mut camera = crate::camera::Camera::default();
camera.tick(None, 1.0);
@@ -835,55 +600,6 @@ mod tests {
assert!((floor - 7.0).abs() < 1e-3, "{floor}");
}
#[test]
fn the_zoom_key_only_zooms_while_playing() {
let mut z = Zoom::default();
// In chat, a sign, a text field or any screen: no zoom.
z.key(true, false, false, 4);
assert!(!z.held());
z.key(true, false, true, 4);
assert!(z.held());
// A screen opening while held lets go (its key presses are the screen's).
z.key(true, true, false, 4);
assert!(!z.held());
// Key repeats do not restart a zoom the wheel changed.
z.key(true, false, true, 4);
z.scroll(1.0);
z.key(true, true, true, 4);
assert!((z.factor(false) - 5.0).abs() < 1e-5);
z.key(false, false, true, 4);
assert!(!z.held());
}
#[test]
fn zoom_key_conflicts_name_the_vanilla_mappings() {
let mut e = Extras::default();
let mut keys = crate::keybinds::KeyBinds::default();
assert!(zoom_key_conflicts(&e, &keys).is_empty());
e.zoom_key = "key.keyboard.c".into();
assert_eq!(
zoom_key_conflicts(&e, &keys),
[
"key.saveToolbarActivator",
"key.debug.crash",
"key.debug.copyLocation"
]
);
keys.set("key.drop", "key.keyboard.z");
e.zoom_key = "key.keyboard.z".into();
assert_eq!(zoom_key_conflicts(&e, &keys), ["key.drop"]);
e.zoom_key = "key.keyboard.unknown".into();
keys.set("key.smoothCamera", "key.keyboard.unknown");
assert!(zoom_key_conflicts(&e, &keys).is_empty());
}
#[test]
fn sensitivity_scales_with_zoom() {
assert_eq!(turn_scale(1.0, true), 1.0);
assert_eq!(turn_scale(4.0, false), 1.0);
assert_eq!(turn_scale(4.0, true), 0.25);
}
#[test]
fn fps_counter_reports_rate_minimum_and_low() {
let mut c = FpsCounter::default();
@@ -937,20 +653,9 @@ mod tests {
#[test]
fn items_cycle_through_their_values() {
let mut e = Extras::default();
Item::ZoomLevel.cycle(&mut e, false);
assert_eq!(e.zoom_level, 6);
Item::ZoomLevel.cycle(&mut e, true);
Item::ZoomLevel.cycle(&mut e, true);
assert_eq!(e.zoom_level, 3);
Item::FpsCorner.cycle(&mut e, true);
assert_eq!(e.fps_corner, Corner::BottomRight);
Item::Zoom.cycle(&mut e, false);
assert_eq!(Item::Zoom.switch(&e), Some(true));
assert_eq!(Item::ZoomKey.value(&e), "Z");
Item::MinimapZoom.cycle(&mut e, true);
assert_eq!(Item::MinimapZoom.value(&e), "½ block per pixel");
Item::MinimapSize.cycle(&mut e, false);
assert_eq!(Item::MinimapSize.value(&e), "Large");
Item::Sort.cycle(&mut e, true);
assert_eq!(Item::Sort.value(&e), "On");
// The minimap's old keys still parse, for the move to its mod.
assert_eq!(
Extras::parse("minimapSize:7\nminimapZoom:3").minimap_zoom,
1.0
+3 -133
View File
@@ -1,7 +1,7 @@
//! The extras' HUD overlays (FPS counter, keystrokes): small boxes in the
//! vanilla font, in GUI pixels, stacked per corner (`docs/extras.md`).
//! HUD boxes in the corners: the minimap's place and mods' panels, small
//! boxes in GUI pixels stacked per corner (`docs/extras.md`).
use crate::{
extras::{Corner, FpsReading},
extras::Corner,
hud::{HudAtlas, HudBatch, Rect, rgba},
};
@@ -99,36 +99,6 @@ pub fn draw_minimap(
}
}
/// The FPS counter's text.
pub fn fps_text(r: FpsReading, lows: bool) -> String {
if lows {
format!("{} fps min {} 1% {}", r.fps, r.min, r.low)
} else {
format!("{} fps", r.fps)
}
}
pub fn draw_fps(
batch: &mut HudBatch,
atlas: &HudAtlas,
corners: &mut Corners,
corner: Corner,
reading: FpsReading,
lows: bool,
) {
let text = fps_text(reading, lows);
let w = HudBatch::text_width(atlas, &text) + 4.0;
let (x, y) = corners.place(corner, w, 12.0);
batch.fill(atlas, x, y, w, 12.0, BACKGROUND);
batch.text(
atlas,
&text,
x + 2.0,
y + 2.0,
rgba(255, 255, 255, 255),
true,
);
}
/// A box of text lines (a mod's HUD panel): `(text, 0xRRGGBB)` each.
pub fn draw_lines(
batch: &mut HudBatch,
@@ -155,95 +125,6 @@ pub fn draw_lines(
}
}
/// What the keystroke overlay shows.
pub struct Keystrokes {
/// Forward, left, back, right: held, and the bound key's name.
pub moves: [(bool, String); 4],
pub jump: bool,
pub attack: bool,
pub use_: bool,
/// Clicks per second of the left and right buttons, when shown.
pub cps: Option<(usize, usize)>,
}
const KEY: f32 = 22.0;
const GAP: f32 = 2.0;
/// The overlay's size.
pub fn keystrokes_size() -> (f32, f32) {
(3.0 * KEY + 2.0 * GAP, 3.0 * KEY + 3.0 * GAP + 10.0)
}
fn key_box(batch: &mut HudBatch, atlas: &HudAtlas, rect: [f32; 4], held: bool, lines: &[&str]) {
let [x, y, w, h] = rect;
let (fill, ink) = if held {
(rgba(255, 255, 255, 176), rgba(20, 20, 20, 255))
} else {
(BACKGROUND, rgba(255, 255, 255, 255))
};
batch.fill(atlas, x, y, w, h, fill);
let total = lines.len() as f32 * 9.0 - 1.0;
for (i, line) in lines.iter().enumerate() {
let tw = HudBatch::text_width(atlas, line);
let tx = (x + (w - tw) / 2.0).round();
let ty = (y + (h - total) / 2.0).round() + i as f32 * 9.0;
batch.text(atlas, line, tx, ty, ink, !held);
}
}
pub fn draw_keystrokes(
batch: &mut HudBatch,
atlas: &HudAtlas,
corners: &mut Corners,
corner: Corner,
k: &Keystrokes,
) {
let (w, h) = keystrokes_size();
let (x, y) = corners.place(corner, w, h);
let step = KEY + GAP;
let [forward, left, back, right] = &k.moves;
key_box(
batch,
atlas,
[x + step, y, KEY, KEY],
forward.0,
&[&forward.1],
);
for (i, key) in [left, back, right].into_iter().enumerate() {
key_box(
batch,
atlas,
[x + i as f32 * step, y + step, KEY, KEY],
key.0,
&[&key.1],
);
}
let mw = (w - GAP) / 2.0;
let my = y + 2.0 * step;
for (i, (held, label, cps)) in [
(k.attack, "LMB", k.cps.map(|c| c.0)),
(k.use_, "RMB", k.cps.map(|c| c.1)),
]
.into_iter()
.enumerate()
{
let rate = cps.map(|n| format!("{n} CPS"));
let lines: Vec<&str> = std::iter::once(label).chain(rate.as_deref()).collect();
key_box(
batch,
atlas,
[x + i as f32 * (mw + GAP), my, mw, KEY],
held,
&lines,
);
}
// The space bar: a line in a short key.
let sy = my + step;
key_box(batch, atlas, [x, sy, w, 10.0], k.jump, &[]);
let ink = if k.jump {
rgba(20, 20, 20, 255)
} else {
rgba(255, 255, 255, 255)
};
batch.fill(atlas, x + w / 2.0 - 12.0, sy + 4.0, 24.0, 2.0, ink);
}
#[cfg(test)]
mod tests {
use super::*;
@@ -259,15 +140,4 @@ mod tests {
assert_eq!(c.place(Corner::BottomRight, 50.0, 10.0), (348.0, 274.0));
assert_eq!(c.place(Corner::BottomLeft, 10.0, 10.0), (2.0, 288.0));
}
#[test]
fn fps_text_with_and_without_lows() {
let r = FpsReading {
fps: 144,
min: 61,
low: 98,
};
assert_eq!(fps_text(r, false), "144 fps");
assert_eq!(fps_text(r, true), "144 fps min 61 1% 98");
}
}
+25
View File
@@ -1201,6 +1201,31 @@ mod tests {
assert!(!font.take_patches().is_empty());
}
/// A renderer rebuilt over the same font (the loading screen's handoff)
/// makes its atlas texture from the textures alone, so the glyphs it had
/// rasterized into the previous texture must be placed into the new one.
#[test]
fn a_rebuilt_atlas_gets_its_glyphs_again() {
let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x));
let default = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#;
let root = root(
"rebuild",
&[
("assets/minecraft/font/default.json", default),
("assets/minecraft/textures/font/a.png", &sheet),
],
);
let font = load(&root);
let _ = std::fs::remove_dir_all(&root);
let first = font.glyph('a');
assert_eq!(font.take_patches().len(), 1);
font.reset_cache();
// Nothing is left over: drawing the character again places its pixels.
assert!(font.take_patches().is_empty());
assert_eq!(font.glyph('a').advance, first.advance);
assert_eq!(font.take_patches().len(), 1);
}
#[test]
fn provider_filters_follow_the_font_options() {
let sheet = png(8, 8, |x, _| x < 4);
File diff suppressed because it is too large. Load diff
+21
View File
@@ -300,6 +300,8 @@ struct Glide {
pub(super) struct Agent {
task: Option<Task>,
glide: Option<Glide>,
/// Control-fixture barrier: hold simulation and packet handling, not transport threads.
pub hold_server: bool,
}
pub(super) enum Handled {
@@ -390,6 +392,9 @@ impl Game<'_> {
Ok(())
}
pub(super) fn screen_label(&self) -> &'static str {
if self.dialog_open() {
return "dialog";
}
if self.title.is_some() {
return "title";
}
@@ -476,6 +481,8 @@ impl Game<'_> {
"absorption": p.health.absorption(),
// The hurt animation's ticks left (the camera's hurt tilt).
"hurt_time": p.health.hurt_animation_time,
// LivingEntity.deathTime while dead (the camera's death roll).
"death_time": self.death_time(),
"air": p.air,
"food": p.health.food.food,
"saturation": p.health.food.saturation,
@@ -485,6 +492,7 @@ impl Game<'_> {
})
});
json!({
"dialog": self.dialog_status(),
"screen": self.screen_label(),
"menu": self.title.as_ref().map(|_| self.title_value()),
"world": (self.title.is_none()).then(|| match &self.integrated {
@@ -663,6 +671,7 @@ impl Game<'_> {
});
if let Some(chat) = &self.ui.chat_screen {
v["chat_input"] = json!(chat.input.value);
v["chat_suggestions"] = json!(chat.suggestions_visible());
}
if self.title.is_some() {
v["menu"] = self.title_value();
@@ -682,6 +691,18 @@ impl Game<'_> {
v["craft_size"] = json!(self.craft_size);
v["station"] = json!(self.station.as_ref().map(|s| format!("{:?}", s.kind)));
v["container"] = json!(self.container);
// The title a server gave the menu, span by span as it is drawn.
if let Some(title) = self.remote_menu_title() {
let spans = title.spans.iter().map(|s| {
json!({
"text": s.text,
"color": s.style.color.map(|c| format!("#{c:06X}")),
"bold": s.style.is_bold(),
"italic": s.style.is_italic(),
})
});
v["title"] = json!(spans.collect::<Vec<_>>());
}
// The recipe book's buttons (GUI pixels): the book button, then
// the recipe buttons of the page, page arrows, filter and tabs.
let book = self.recipe_book_targets();
+1 -2
View File
@@ -515,8 +515,7 @@ impl Game<'_> {
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = stack_tip {
let lines = self.stack_tooltip(&stack);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
} else if let Some(key) = tooltip {
let text = self.translate(&key, &key);
self.draw_tooltip_lines(
@@ -8,10 +8,15 @@ use horizon_client::{
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
block_entity_render::BlockAnim,
collisions::{SceneCollisions, no_collision_empty},
containers::BlockEntity,
particles::{ParticleOptions, ParticleType},
save::number,
skins,
};
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::nbt::Tag;
/// The handle of the local player among a bell's gathered entities.
@@ -84,6 +89,16 @@ impl Game<'_> {
self.lid_openers_changed(other, open);
}
}
_ if self
.res
.facts()
.get(self.world.block(pos[0], pos[1], pos[2]))
.name
.as_ref()
== "minecraft:barrel" =>
{
self.barrel_openers_changed(key, open);
}
Some(Ticker::Shulker { .. }) => {
let shulker = self.be_anims.shulkers.entry(pos).or_default();
let (count, _) = if open {
@@ -102,15 +117,48 @@ impl Game<'_> {
/// `ChestBlockEntity.signalOpenCount`: block event 1 with the count, here
/// and for the guests.
fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) {
let count = self.lid_openers.entry(key).or_default();
*count = (*count + if open { 1 } else { -1 }).max(0);
let count = *count;
if count == 0 {
self.lid_openers.remove(&key);
}
let (before, count) = self.count_opener(key, open);
let pos = [key.0, key.1, key.2];
self.block_entity_event(pos, 1, count);
self.lan_block_event(pos, 1, count);
// TrappedChestBlockEntity.signalOpenCount: its signal is the count
// (`TrappedChestBlock.getSignal`), so the blocks around it and
// below it hear of a change.
let state = self.world.block(pos[0], pos[1], pos[2]);
if before != count && self.res.facts().get(state).name.as_ref() == "minecraft:trapped_chest"
{
let p = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| {
let block = b.block(state);
b.update_neighbors_at(level, ticks, p, block);
b.update_neighbors_at(level, ticks, p.offset(0, -1, 0), block);
});
}
}
/// `BarrelBlockEntity.openersCounter`: the first opener opens the barrel
/// (`open=true`), the last one to leave closes it (`updateBlockState`).
fn barrel_openers_changed(&mut self, key: (i32, i32, i32), open: bool) {
let (before, count) = self.count_opener(key, open);
if (before == 0) != (count == 0) {
self.set_bool_prop(
key,
"open",
count > 0,
horizon_world::level::flags::UPDATE_ALL,
);
}
}
/// One opener more (`open`) or less at `key`: the count before and after
/// (`ContainerOpenersCounter.incrementOpeners` / `decrementOpeners`).
fn count_opener(&mut self, key: (i32, i32, i32), open: bool) -> (i32, i32) {
let count = self.lid_openers.entry(key).or_default();
let before = *count;
*count = (before + if open { 1 } else { -1 }).max(0);
let after = *count;
if after == 0 {
self.lid_openers.remove(&key);
}
(before, after)
}
/// `BellBlockEntity.updateEntities`: the living entities whose bounding
/// box meets the bell's block box inflated by 48.
@@ -171,6 +219,11 @@ impl Game<'_> {
/// client tick (`ClientLevel.tickBlockEntities`).
pub(super) fn tick_block_entity_anims(&mut self) {
let Some(r) = &self.renderer else {
// A server has no window, but its gateways still run their
// server ticker.
if self.remote.is_none() {
self.tick_gateway_servers();
}
return;
};
// Sorted by position: the order they tick in, and a quick lookup.
@@ -330,6 +383,31 @@ impl Game<'_> {
}
self.be_anims.present = positions;
}
/// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the
/// gateways a server keeps a copy of, in block-ticking chunks
/// (`Level.tickBlockEntities`): the cooldown an entry started runs out,
/// and every 2400 ticks `triggerCooldown` sends its block event.
fn tick_gateway_servers(&mut self) {
let levels = self.tickets.levels();
let mut positions: Vec<[i32; 3]> = self
.be_anims
.gateway_servers
.keys()
.copied()
.filter(|p| levels.block_ticking_at(p[0], p[2]))
.collect();
positions.sort_unstable();
for pos in positions {
let triggered = self
.be_anims
.gateway_servers
.get_mut(&pos)
.is_some_and(EndGateway::portal_tick);
if triggered {
self.block_entity_event(pos, 1, 0);
}
}
}
/// `EndGatewayBlock.entityInside` on the server: whether the gateway at
/// `pos` let the entity in (`triggerCooldown`, with its block event).
pub(super) fn gateway_enter(&mut self, pos: [i32; 3]) -> bool {
@@ -392,4 +470,25 @@ impl Game<'_> {
pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 {
self.be_anims.lid(pos, partial)
}
/// `SkullBlockRenderer.getPlayerSkin`: the skin sprite of the profile of
/// the player head at `pos`. The skin download is started here; while it
/// is in flight (or when it cannot be got) the profile's default skin
/// stands in. A head with no profile answers None: `SKIN_BY_TYPE`.
pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> {
let Some(BlockEntity::Skull(skull)) =
self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
else {
return None;
};
let skin = skull.skin.as_ref()?;
if let Some((url, location)) = &skin.download {
self.skin_downloads
.borrow_mut()
.state(skins::Kind::Skin, url);
if self.gui.atlas.sprites.contains_key(location) {
return Some(location);
}
}
Some(skin.fallback)
}
}
@@ -56,6 +56,7 @@ impl Game<'_> {
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
_ => {}
}
}
@@ -92,7 +93,10 @@ impl Game<'_> {
| "minecraft:vault"
| "minecraft:beehive"
| "minecraft:bee_nest"
| "minecraft:brewing_stand" => Ticking::Yes,
| "minecraft:brewing_stand"
// Lit, cookTick; unlit, cooldownTick.
| "minecraft:campfire"
| "minecraft:soul_campfire" => Ticking::Yes,
"minecraft:jukebox" => {
let record = registry
.state(state)
+4 -1
View File
@@ -55,7 +55,7 @@ pub(super) struct Boat {
/// `ChestBoat.CONTAINER_SIZE`.
pub(super) const CHEST_SLOTS: usize = 27;
pub(super) const WIDTH: f64 = 1.375;
const HEIGHT: f64 = 0.5625;
pub(super) const HEIGHT: f64 = 0.5625;
impl Boat {
pub fn new(id: u32, wood: Arc<str>, position: Vec3, yaw: f32) -> Self {
Self {
@@ -587,6 +587,9 @@ impl Game<'_> {
}
/// The player's tick while riding: steer, tick the boat, sit in it.
pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> {
if self.tick_cushion_riding(keys) {
return Ok(());
}
let Some(i) = self.boats.iter().position(|b| Some(b.id) == self.riding) else {
if self.tick_cart_riding(keys) || self.tick_mount_riding(keys) {
return Ok(());
+346 -151
View File
@@ -17,7 +17,6 @@ use horizon_client::{
use horizon_core::position::BlockPos;
use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S};
use horizon_world::level::flags as level_flags;
use std::time::Instant;
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
@@ -27,8 +26,24 @@ const BLACK: u32 = 0xFF00_0000;
const PAGE_CHARS: usize = 1024;
const MAX_PAGES: usize = 100;
const LINES: usize = 14;
/// `BookSignScreen`'s title box.
const BOOK_TITLE: horizon_client::clipboard::FieldId = ("book.title", 0);
fn book_title_box() -> ui::EditBox {
let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
edit.bordered = false;
edit.max_length = 15;
edit.text_color = BLACK;
edit.focused = true;
edit
}
fn book_page_box() -> ui::EditBox {
let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
edit.bordered = false;
edit.multiline = true;
edit.max_length = PAGE_CHARS;
edit.text_color = BLACK;
edit.focused = true;
edit
}
pub(super) enum BookScreen {
Edit {
@@ -38,7 +53,10 @@ pub(super) enum BookScreen {
page: usize,
signing: bool,
title: String,
opened: Instant,
/// BookSignScreen's title box (`EditBox` of 15).
title_edit: ui::EditBox,
/// BookEditScreen's page (`MultiLineEditBox`).
page_edit: ui::EditBox,
},
View {
pages: Vec<String>,
@@ -84,13 +102,16 @@ impl Game<'_> {
if pages.is_empty() {
pages.push(String::new());
}
let mut page_edit = book_page_box();
page_edit.set_value(&pages[0]);
BookScreen::Edit {
slot: self.held_slot(),
pages,
page: 0,
signing: false,
title: String::new(),
opened: Instant::now(),
title_edit: book_title_box(),
page_edit,
}
}
"minecraft:written_book" => BookScreen::View {
@@ -239,34 +260,24 @@ impl Game<'_> {
Some(KeyCode::PageDown) => self.turn_page(true),
_ => {}
},
Some(BookScreen::Edit {
signing: true,
title,
..
}) => match key {
Some(BookScreen::Edit { signing: true, .. }) => match key {
Some(KeyCode::Escape) => {
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
*signing = false;
}
}
Some(KeyCode::Backspace) => {
if !self.text_selection.take(BOOK_TITLE, title) {
title.pop();
}
}
Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
if !title.trim().is_empty() {
let blank = self.book.as_ref().is_some_and(
|b| matches!(b, BookScreen::Edit { title, .. } if title.trim().is_empty()),
);
if !blank {
self.save_book(true);
}
}
Some(key) if self.book_title_key(key) => {}
_ => {
if let Some(typed) = text {
self.text_selection.take(BOOK_TITLE, title);
for c in typed.chars().filter(|c| !c.is_control()) {
if title.chars().count() < 15 {
title.push(c);
}
}
self.book_title_insert(typed);
}
}
},
@@ -274,24 +285,13 @@ impl Game<'_> {
Some(KeyCode::Escape) => self.save_book(false),
Some(KeyCode::PageUp) => self.turn_page(false),
Some(KeyCode::PageDown) => self.turn_page(true),
Some(KeyCode::Backspace) => {
if !self.take_page_selection() {
self.edit_page(|p| {
p.pop();
})
}
}
Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
self.take_page_selection();
self.type_into_page("\n")
}
Some(KeyCode::ArrowUp) => self.book_move_line(-1),
Some(KeyCode::ArrowDown) => self.book_move_line(1),
Some(KeyCode::Enter | KeyCode::NumpadEnter) => self.page_insert("\n"),
Some(key) if self.book_page_key(key) => {}
_ => {
if let Some(typed) = text {
let typed: String = typed.chars().filter(|c| !c.is_control()).collect();
if !typed.is_empty() {
self.take_page_selection();
}
self.type_into_page(&typed);
self.page_insert(typed);
}
}
},
@@ -302,99 +302,258 @@ impl Game<'_> {
pub(super) fn book_type(&mut self, text: &str) {
let text = text.replace("\\n", "\n");
match self.book.as_mut() {
Some(BookScreen::Edit {
signing: true,
title,
..
}) => {
for c in text.chars().filter(|c| !c.is_control()) {
if title.chars().count() < 15 {
title.push(c);
}
}
}
Some(BookScreen::Edit { .. }) => self.type_into_page(&text),
Some(BookScreen::Edit { signing: true, .. }) => self.book_title_insert(&text),
Some(BookScreen::Edit { .. }) => self.page_insert(&text),
_ => {}
}
}
/// Before typing on a page: Select All's selection is cleared (true).
fn take_page_selection(&mut self) -> bool {
match self.book.as_mut() {
Some(BookScreen::Edit { pages, page, .. }) => self
.text_selection
.take(("book.page", *page), &mut pages[*page]),
_ => false,
/// `BookSignScreen.keyPressed` on the title box.
fn book_title_key(&mut self, key: KeyCode) -> bool {
let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
let Some(BookScreen::Edit {
title, title_edit, ..
}) = self.book.as_mut()
else {
return false;
};
if !title_edit.key(key, ctrl, shift) {
return false;
}
title.clone_from(&title_edit.value);
true
}
/// Ctrl+A/C/V/X: the title box (an `EditBox` of 15) while signing, else
/// the page (`MultilineTextField.insertText`: line breaks kept, cut to
/// the 1024 characters left, rejected when it overflows the 14 lines).
pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
let font = &self.gui.atlas.font;
match self.book.as_mut() {
Some(BookScreen::Edit {
signing: true,
title,
..
}) => {
Self::append_shortcut(
&mut self.text_selection,
&mut self.clipboard,
BOOK_TITLE,
title,
shortcut,
15,
);
}
Some(BookScreen::Edit { pages, page, .. }) => {
// truncateInsertionText counts the whole value, selection included.
let room = PAGE_CHARS.saturating_sub(pages[*page].chars().count());
self.text_selection.apply(
("book.page", *page),
&mut pages[*page],
shortcut,
&mut self.clipboard,
|value, pasted| {
let text: String = horizon_client::clipboard::filter_text(pasted, true)
.chars()
.take(room)
.collect();
let next = format!("{value}{text}");
font.split(&Text::literal(&next), 114.0).len() <= LINES && {
*value = next;
true
}
},
);
}
_ => {}
}
}
fn edit_page(&mut self, f: impl FnOnce(&mut String)) {
if let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_mut() {
f(&mut pages[*page]);
}
}
/// MultiLineEditBox: characters that keep the page within 14 lines and 1024 characters.
fn type_into_page(&mut self, typed: &str) {
let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_ref() else {
fn book_title_insert(&mut self, text: &str) {
let Some(BookScreen::Edit {
title, title_edit, ..
}) = self.book.as_mut()
else {
return;
};
let mut text = pages[*page].clone();
for c in typed.chars() {
let mut next = text.clone();
next.push(c);
if next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES {
text = next;
title_edit.insert_text(text);
title.clone_from(&title_edit.value);
}
/// `BookEditScreen.keyPressed` on the page, apart from the line moves.
fn book_page_key(&mut self, key: KeyCode) -> bool {
let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
let before = match self.book.as_ref() {
Some(BookScreen::Edit { page_edit, .. }) => Some((
page_edit.value.clone(),
page_edit.cursor,
page_edit.highlight,
)),
_ => return false,
};
let handled = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
page_edit.key(key, ctrl, shift)
} else {
false
};
if handled {
self.page_keep(before);
}
handled
}
/// One character at a time, so a page stops at the last character that fits.
fn page_insert(&mut self, text: &str) {
for c in text.chars() {
self.page_change(|edit| edit.insert_text(&c.to_string()));
}
}
/// Ctrl+A/C/V/X: the title box while signing, else the page.
pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
let signing = matches!(self.book, Some(BookScreen::Edit { signing: true, .. }));
if signing {
if let Some(BookScreen::Edit {
title, title_edit, ..
}) = self.book.as_mut()
{
title_edit.shortcut(shortcut, &mut self.clipboard);
title.clone_from(&title_edit.value);
}
return;
}
let before = match self.book.as_ref() {
Some(BookScreen::Edit { page_edit, .. }) => Some((
page_edit.value.clone(),
page_edit.cursor,
page_edit.highlight,
)),
_ => None,
};
if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
page_edit.shortcut(shortcut, &mut self.clipboard);
}
self.page_keep(before);
}
/// Edit the page box, then keep it only within 14 lines and 1024 characters.
fn page_change(&mut self, f: impl FnOnce(&mut ui::EditBox)) -> bool {
let before = match self.book.as_ref() {
Some(BookScreen::Edit { page_edit, .. }) => Some((
page_edit.value.clone(),
page_edit.cursor,
page_edit.highlight,
)),
_ => return false,
};
let ran = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
f(page_edit);
true
} else {
false
};
ran && self.page_keep(before)
}
/// Write the page, or put the previous text back when it no longer fits.
fn page_keep(&mut self, before: Option<(String, usize, usize)>) -> bool {
let next = match self.book.as_ref() {
Some(BookScreen::Edit { page_edit, .. }) => page_edit.value.clone(),
_ => return false,
};
let ok = next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES;
let Some(BookScreen::Edit {
pages,
page,
page_edit,
..
}) = self.book.as_mut()
else {
return false;
};
if ok {
pages[*page].clone_from(&page_edit.value);
} else if let Some((value, cursor, highlight)) = before {
page_edit.value = value;
page_edit.cursor = cursor;
page_edit.highlight = highlight;
}
ok
}
/// ArrowUp and ArrowDown move a visual line, keeping the column.
fn book_move_line(&mut self, dir: isize) {
let shift = self.has_shift_down();
let (text, cursor) = match self.book.as_ref() {
Some(BookScreen::Edit {
pages,
page,
page_edit,
..
}) => (pages[*page].clone(), page_edit.cursor),
_ => return,
};
let rows = self.page_rows(&text);
let (x, line) = self.caret_on(&text, &rows, cursor);
let next = (line as isize + dir).clamp(0, rows.len() as isize - 1) as usize;
let (start, end) = rows[next];
let chars: Vec<char> = text.chars().collect();
let slice: String = chars[start..end].iter().collect();
let pos = start + self.gui.atlas.font.fit(&slice, x);
if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
page_edit.set_cursor(pos, shift);
}
}
/// Wrapped rows of a page as character ranges, the same breaks as `font.split`.
fn page_rows(&self, page: &str) -> Vec<(usize, usize)> {
let font = &self.gui.atlas.font;
let chars: Vec<char> = page.chars().collect();
let mut rows = Vec::new();
let mut start = 0;
while start < chars.len() {
let mut end = chars.len();
let mut next = chars.len();
let mut last_space = None;
for i in start..chars.len() {
if chars[i] == '\n' {
end = i;
next = i + 1;
break;
}
if chars[i] == ' ' {
last_space = Some(i);
}
let slice: String = chars[start..=i].iter().collect();
if font.width(&slice) > 114.0 {
match last_space {
Some(s) if s > start => {
end = s;
next = s + 1;
}
_ => {
end = i.max(start + 1);
next = end;
}
}
break;
}
}
rows.push((start, end));
start = next;
if start == chars.len() && chars.last() == Some(&'\n') {
rows.push((chars.len(), chars.len()));
}
}
self.edit_page(|p| *p = text);
if rows.is_empty() {
rows.push((0, 0));
}
rows
}
/// GUI x of the caret and the row it sits on.
fn caret_on(&self, page: &str, rows: &[(usize, usize)], cursor: usize) -> (f32, usize) {
let chars: Vec<char> = page.chars().collect();
for (i, &(start, end)) in rows.iter().enumerate() {
if cursor <= end || i + 1 == rows.len() {
let take = cursor.saturating_sub(start).min(end.saturating_sub(start));
let prefix: String = chars.iter().skip(start).take(take).collect();
return (self.gui.atlas.font.width(&prefix), i);
}
}
(0.0, 0)
}
fn page_index_at(&self, page: &str, local_x: f32, local_y: f32) -> usize {
let rows = self.page_rows(page);
let line = (local_y / 9.0).floor().max(0.0) as usize;
let line = line.min(rows.len().saturating_sub(1));
let (start, end) = rows[line];
let chars: Vec<char> = page.chars().collect();
let slice: String = chars[start..end].iter().collect();
start + self.gui.atlas.font.fit(&slice, local_x.max(0.0))
}
/// A click on the centred title (`EditBox.onClick`).
fn book_title_click(&mut self, field_x: f32, mx: f32) {
let shift = self.has_shift_down();
let Some(BookScreen::Edit {
title, title_edit, ..
}) = self.book.as_mut()
else {
return;
};
let tx = field_x + ((114.0 - self.gui.atlas.font.width(title)) / 2.0).floor();
let rel = (mx - tx).max(0.0);
let pos = self.gui.atlas.font.fit(title, rel);
title_edit.set_cursor(pos, shift);
}
/// A click on the open page.
fn book_page_click(&mut self, origin_x: f32, origin_y: f32, mx: f32, my: f32) {
let shift = self.has_shift_down();
let text = match self.book.as_ref() {
Some(BookScreen::Edit { pages, page, .. }) => pages[*page].clone(),
_ => return,
};
let pos = self.page_index_at(&text, mx - origin_x, my - origin_y);
if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
page_edit.set_cursor(pos, shift);
}
}
/// The page buttons (`pageForward` adds a page while editing).
fn turn_page(&mut self, forward: bool) {
let mut lectern_page = None;
match self.book.as_mut() {
Some(BookScreen::Edit { pages, page, .. }) => {
Some(BookScreen::Edit {
pages,
page,
page_edit,
..
}) => {
let before = *page;
if forward {
if *page + 1 >= pages.len() && pages.len() < MAX_PAGES {
pages.push(String::new());
@@ -405,6 +564,10 @@ impl Game<'_> {
} else if *page > 0 {
*page -= 1;
}
if *page != before {
let text = pages[*page].clone();
page_edit.set_value(&text);
}
}
Some(BookScreen::View {
lectern: Some(key), ..
@@ -764,6 +927,8 @@ impl Game<'_> {
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
*signing = false;
}
} else if inside(left + 36.0, 50.0, 114.0, 9.0) {
self.book_title_click(left + 36.0, mx);
}
}
Some(BookScreen::Edit { page, .. }) => {
@@ -780,6 +945,8 @@ impl Game<'_> {
} else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) {
click(self);
self.save_book(false);
} else if inside(left + 36.0, 32.0, 114.0, 14.0 * 9.0) {
self.book_page_click(left + 36.0, 32.0, mx, my);
}
}
Some(BookScreen::View {
@@ -865,7 +1032,7 @@ impl Game<'_> {
BookScreen::Edit {
signing: true,
title,
opened,
title_edit,
..
} => {
let edit = tr("book.editTitle", "Enter Book Title:");
@@ -881,19 +1048,35 @@ impl Game<'_> {
// The title box: an unbordered, centred EditBox of 114 with
// black text and no shadow; the value alone is centred, the
// cursor follows it.
let value = &title_edit.value;
let x = left + 36.0;
let tx = x + ((114.0 - HudBatch::text_width(atlas, title)) / 2.0).floor();
horizon_client::ui::append_field(
batch,
atlas,
title,
(tx, 50.0, x + 114.0 - tx),
(BLACK, false),
15,
self.text_selection.covers(BOOK_TITLE, title),
true,
opened.elapsed().as_millis(),
);
let tx = x + ((114.0 - HudBatch::text_width(atlas, value)) / 2.0).floor();
batch.text(atlas, value, tx, 50.0, BLACK, false);
if title_edit.cursor != title_edit.highlight {
let (a, b) = (
title_edit.cursor.min(title_edit.highlight),
title_edit.cursor.max(title_edit.highlight),
);
let pre: String = value.chars().take(a).collect();
let sel: String = value.chars().skip(a).take(b - a).collect();
let sx = tx + HudBatch::text_width(atlas, &pre);
batch.text_highlight(
atlas,
(sx, 49.0, HudBatch::text_width(atlas, &sel), 11.0),
true,
);
}
if title_edit.cursor_visible() {
let pre: String = value.chars().take(title_edit.cursor).collect();
batch.fill(
atlas,
tx + HudBatch::text_width(atlas, &pre),
49.0,
1.0,
9.0,
BLACK,
);
}
let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME);
let tw = HudBatch::text_width(atlas, &by);
batch.text(
@@ -941,12 +1124,12 @@ impl Game<'_> {
BookScreen::Edit {
pages,
page,
opened,
page_edit,
..
} => {
indicator(batch, *page, pages.len());
let blink = (opened.elapsed().as_millis() / 300) % 2 == 0;
let lines = self.book_lines(&pages[*page]);
let text = &pages[*page];
let lines = self.book_lines(text);
for (i, line) in lines.iter().take(LINES).enumerate() {
batch.text_styled(
atlas,
@@ -957,27 +1140,39 @@ impl Game<'_> {
false,
);
}
if blink {
// The cursor after the last character.
let last = lines
.last()
.map(|l| atlas.font.width_text(l))
.unwrap_or(0.0);
let row = lines.len().saturating_sub(1) as f32
+ if pages[*page].ends_with('\n') {
1.0
} else {
0.0
};
let x = if pages[*page].ends_with('\n') {
0.0
} else {
last
};
let rows = self.page_rows(text);
let (sel_a, sel_b) = (
page_edit.cursor.min(page_edit.highlight),
page_edit.cursor.max(page_edit.highlight),
);
if sel_a != sel_b {
let chars: Vec<char> = text.chars().collect();
for (i, &(start, end)) in rows.iter().enumerate().take(LINES) {
let from = sel_a.max(start);
let to = sel_b.min(end);
if from >= to {
continue;
}
let pre: String = chars[start..from].iter().collect();
let sel: String = chars[from..to].iter().collect();
batch.text_highlight(
atlas,
(
left + 36.0 + atlas.font.width(&pre),
top + 29.0 + i as f32 * 9.0,
atlas.font.width(&sel),
9.0,
),
true,
);
}
}
if page_edit.cursor_visible() {
let (x, row) = self.caret_on(text, &rows, page_edit.cursor);
batch.fill(
atlas,
left + 36.0 + x,
top + 29.0 + row * 9.0,
top + 29.0 + row as f32 * 9.0,
1.0,
9.0,
BLACK,
+190
View File
@@ -0,0 +1,190 @@
//! Campfires' cooking: `CampfireBlock.useItemOn` (`CampfireBlockEntity.placeFood`)
//! and the block entity's `cookTick` (lit) and `cooldownTick` (unlit). The
//! items drawn on the fire are `campfire_geometry`'s; a server's clients get
//! them through the block entity's update tag (`lan::chunks::entity_tag`).
use super::Game;
use horizon_assets::item_model::DisplayContext;
use horizon_client::{
Result, block_entities::Pos, block_entity_render::vertex_light, containers::BlockEntity,
items::ItemStack, mesher::Vertex, mobs::Who,
};
use horizon_core::position::BlockPos;
/// The `campfire_cooking` recipe kind (`RecipeType.CAMPFIRE_COOKING`).
const KIND: &str = "minecraft:campfire_cooking";
fn is_campfire(name: &str) -> bool {
name == "minecraft:campfire" || name == "minecraft:soul_campfire"
}
impl Game<'_> {
/// `CampfireBlock.useItemOn` with a held item that is a campfire recipe's
/// input (`RecipePropertySet.CAMPFIRE_INPUT`): on a server level the food
/// goes into the first free slot (`placeFood`), and the use is consumed
/// whether or not there was room. A client of a server leaves the placing
/// to the server. Whether the food went in; None when this isn't a
/// campfire use, so the item's own use runs.
pub(super) fn use_on_campfire(&mut self, pos: [i32; 3]) -> Result<Option<bool>> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !is_campfire(&self.res.facts().get(state).name) {
return Ok(None);
}
let Some(held) = self.held().cloned() else {
return Ok(None);
};
let Some(time) = self.res.recipes().cook(KIND, &held).map(|r| r.time as i32) else {
return Ok(None);
};
// A client of a server predicts the placing; the server decides.
if self.remote.is_some() {
return Ok(Some(true));
}
let key = (pos[0], pos[1], pos[2]);
let placed = match self.world.block_entities.get_mut(&key) {
Some(BlockEntity::Campfire(c)) => {
let mut one = held.clone();
c.place_food(&mut one, time)
}
_ => false,
};
if placed {
// ItemStack.consumeAndReturn: creative keeps the item.
self.consume_held();
self.stats.custom("interact_with_campfire", 1);
self.post_block_game_event(
"minecraft:block_change",
pos,
Some(Who::Player),
Some(state),
);
self.mark_block_entity_updated(key);
}
Ok(Some(placed))
}
/// `CampfireBlockEntity.cookTick` of a lit campfire, `cooldownTick` of an
/// unlit one. A finished item's result (the recipe's, or the item itself
/// when no recipe takes it any more) drops at the block's corner
/// (`Containers.dropItemStack` at its integer position), then the clients
/// see the slot empty and a `block_change` goes out.
pub(super) fn tick_campfire(&mut self, pos: Pos) -> Result<()> {
let state = self.world.block(pos.0, pos.1, pos.2);
let lit = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("lit"))
.is_some_and(|v| v == "true");
let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
return Ok(());
};
// BlockEntity.setChanged: a timer that moved is saved with the
// chunk (no update to the clients, who don't see the timers).
let changed = if lit {
c.items.iter().any(Option::is_some)
} else {
c.cooldown_tick()
};
if changed {
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
}
if !lit {
return Ok(());
}
let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
return Ok(());
};
let done = c.cook_tick();
for (_, item) in done {
let result = self
.res
.recipes()
.cook(KIND, &item)
.map_or_else(|| item.clone(), |r| r.result.clone());
self.campfire_drop(pos, result);
self.mark_block_entity_updated(pos);
self.post_block_game_event(
"minecraft:block_change",
[pos.0, pos.1, pos.2],
None,
Some(state),
);
}
Ok(())
}
/// `CampfireRenderer`: each cooking item lies on the fire, slot `i`
/// turned to `Direction.from2DDataValue((i + facing) % 4)`, laid flat
/// (90° about X), at a corner and three eighths of its size, drawn as a
/// FIXED item seeded by the block's position plus the slot.
pub(super) fn campfire_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
for (key, entity) in &self.world.block_entities {
let BlockEntity::Campfire(c) = entity else {
continue;
};
if c.items.iter().all(Option::is_none) {
continue;
}
let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
if at.distance_squared(camera) >= 64.0 * 64.0 {
continue;
}
// Direction.get2DDataValue: south 0, west 1, north 2, east 3.
let state = self.world.block(key.0, key.1, key.2);
let facing = match self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing"))
.map(String::as_str)
{
Some("west") => 1,
Some("north") => 2,
Some("east") => 3,
_ => 0,
};
let light = vertex_light(self.world.light(key.0, key.1, key.2));
let packed = BlockPos::new(key.0, key.1, key.2).pack();
for (i, stack) in c.items.iter().enumerate() {
let Some(stack) = stack else {
continue;
};
let seed = (packed as i32).wrapping_add(i as i32);
let item = self.resolve_item(stack, DisplayContext::Fixed, None, seed);
if item.is_empty() {
continue;
}
// Direction.toYRot: 90° per 2D step from south.
let yaw = -(((i + facing) % 4) as f32 * 90.0);
let pose = glam::Mat4::from_translation(
(at - camera).as_vec3() + glam::Vec3::new(0.5, 0.449_218_75, 0.5),
) * glam::Mat4::from_rotation_y(yaw.to_radians())
* glam::Mat4::from_rotation_x(90f32.to_radians())
* glam::Mat4::from_translation(glam::Vec3::new(-0.3125, -0.3125, 0.0))
* glam::Mat4::from_scale(glam::Vec3::splat(0.375));
self.submit_item_world(&item, pose, light, out);
}
}
}
/// `Containers.dropItemStack(level, x, y, z, stack)` at the block's
/// integer position.
fn campfire_drop(&mut self, pos: Pos, stack: ItemStack) {
let at = BlockPos::new(pos.0, pos.1, pos.2);
for piece in
horizon_world::level::removal::drop_item_stack(&mut self.world.random, at, stack.count)
{
self.spawn_item(
ItemStack {
count: piece.count,
..stack.clone()
},
piece.pos,
piece.motion,
0,
);
}
}
}
+63 -10
View File
@@ -2,7 +2,10 @@
//! (game rules, the world clock, difficulty), bound to the game.
use super::{Game, Screen};
use horizon_client::{
chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR},
chat::{
Chat, ChatAbilities, ChatAction, ChatScreen, ChatSource, ChatVisibility, Commands,
SYSTEM_INDICATOR,
},
command::Registries,
gamerules::GameRules,
hud::HudBatch,
@@ -425,6 +428,7 @@ impl Game<'_> {
self.ui.chat.recent.len(),
b.width as i32,
b.height as i32,
self.chat_abilities(),
);
screen.auto_suggestions = self.settings.auto_suggestions;
self.ui.chat_screen = Some(screen);
@@ -443,6 +447,10 @@ impl Game<'_> {
self.capture(true);
}
}
/// `Minecraft.computeChatAbilities` from the Chat option.
pub(super) fn chat_abilities(&self) -> ChatAbilities {
ChatAbilities::new(ChatVisibility::from_option(self.settings.chat_visibility))
}
/// A chat message from the game (ChatComponent.addServerSystemMessage).
pub(super) fn system_message(&mut self, text: Text) {
if let Some(capture) = self.chat_capture.as_mut() {
@@ -452,7 +460,32 @@ impl Game<'_> {
// Connected to a server (single player's own included), the chat on
// screen is the connection's: the game's own messages join it.
if self.remote.is_some() {
self.chat_line(text);
self.chat_line(text, ChatSource::Server);
return;
}
// The Chat option's Hidden level takes the server's messages too.
self.local_chat_line(text, Some(SYSTEM_INDICATOR), ChatSource::Server);
}
/// A player's chat line on the window's own chat: a LAN guest's message
/// while the host runs in-frame (`HostEvent::Chat`). `ChatListener`
/// checks `canReceivePlayerMessages` for these, so Commands Only and
/// Hidden drop them; command feedback (`/list`, `/tp`) is a system
/// message and takes the system-message permission instead.
pub(super) fn player_message(&mut self, text: Text) {
if let Some(capture) = self.chat_capture.as_mut() {
capture.push(text);
return;
}
// A server's client receives the line as a packet (PlayerChat or
// DisguisedChat) and filters it there.
if self.remote.is_none() {
self.local_chat_line(text, None, ChatSource::Player);
}
}
/// A line on the window's own chat when the Chat option lets `source`
/// through; running mods hear it.
fn local_chat_line(&mut self, text: Text, indicator: Option<u32>, source: ChatSource) {
if !self.ui.chat.shows(source) {
return;
}
let focused = self.screen == Screen::Chat;
@@ -460,7 +493,8 @@ impl Game<'_> {
self.ui.chat.add(
&self.gui.atlas,
text,
Some(SYSTEM_INDICATOR),
indicator,
source,
self.ticks,
focused,
);
@@ -570,7 +604,12 @@ impl Game<'_> {
}
}
/// ChatScreen.handleChatInput: history, then a command or a chat line.
/// The Chat option's restrictions stop the message here too, so a
/// control-socket `chat` cannot send what the player's setting hides.
pub(super) fn handle_chat_input(&mut self, message: &str) {
if !self.chat_abilities().allows(message) {
return;
}
self.ui.chat.add_recent(message);
// On a server (single player's own included) the server runs it,
// unless a client mod owns the command.
@@ -584,7 +623,10 @@ impl Game<'_> {
return;
}
if let Some(command) = message.strip_prefix('/') {
self.run_command(command);
// A client mod's command first, then a server mod's, as on a server.
if !self.mod_command(command) && !self.local_server_mod_command(command) {
self.run_command(command);
}
} else {
let line = Text::translate(
"chat.type.text",
@@ -592,13 +634,19 @@ impl Game<'_> {
);
let focused = self.screen == Screen::Chat;
let heard = self.mods.running().then(|| line.plain());
self.ui
.chat
.add(&self.gui.atlas, line, None, self.ticks, focused);
self.ui.chat.add(
&self.gui.atlas,
line,
None,
ChatSource::Player,
self.ticks,
focused,
);
if let Some(line) = heard {
self.mods_chat(&line);
}
self.lan_host_chat(message);
self.mod_player_chat(super::server_mods::Who::Local, message);
}
}
pub(super) fn chat_scroll(&mut self, amount: f32) {
@@ -898,9 +946,14 @@ impl Game<'_> {
Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]),
};
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.gui.atlas, message, None, self.ticks, focused);
self.ui.chat.add(
&self.gui.atlas,
message,
None,
ChatSource::Client,
self.ticks,
focused,
);
}
}
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
+13 -24
View File
@@ -63,8 +63,8 @@ impl Game<'_> {
}
}
}
/// Typing or a backspace in a field of the title screens: in the server
/// screens' append-only fields Select All's selection is replaced first.
/// Typing or a backspace in a title-screen field. A field that still only
/// appends replaces a Select All selection before the edit.
pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) {
let Some(title) = self.title.as_mut() else {
return;
@@ -86,42 +86,31 @@ impl Game<'_> {
}
/// Shortcuts in the creative inventory's search box (an `EditBox` of 50).
pub(super) fn creative_search_shortcut(&mut self, shortcut: EditShortcut) {
if Self::append_shortcut(
&mut self.text_selection,
&mut self.clipboard,
CREATIVE_SEARCH,
&mut self.creative_screen.search,
shortcut,
CREATIVE_SEARCH_CHARS,
) {
if self
.creative_screen
.search
.shortcut(shortcut, &mut self.clipboard)
{
self.creative_screen.scroll = 0.0;
}
}
/// A backspace in the creative search box: with Ctrl, the whole word
/// before the caret (`EditBox.deleteWords(-1)`), otherwise one character.
/// A Select All selection is what it deletes, as in `EditBox.keyPressed`.
/// A selection is what it deletes, as in `EditBox.keyPressed`.
pub(super) fn creative_search_backspace(&mut self, ctrl: bool) {
let search = &mut self.creative_screen.search;
if !self.text_selection.take(CREATIVE_SEARCH, search) {
if ctrl {
horizon_client::ui::delete_words(search, -1);
} else {
search.pop();
}
}
self.creative_screen
.search
.key(KeyCode::Backspace, ctrl, false);
self.creative_screen.scroll = 0.0;
}
/// Typing in the creative search box.
pub(super) fn creative_search_edit(&mut self, typed: Option<&str>) {
let search = &mut self.creative_screen.search;
self.text_selection.take(CREATIVE_SEARCH, search);
if let Some(text) = typed {
clipboard::append_limited(search, text, CREATIVE_SEARCH_CHARS);
self.creative_screen.search.insert_text(text);
self.creative_screen.scroll = 0.0;
}
self.creative_screen.scroll = 0.0;
}
}
/// `CreativeModeInventoryScreen`'s search box: `setMaxLength(50)`.
pub(super) const CREATIVE_SEARCH_CHARS: usize = 50;
pub(super) const CREATIVE_SEARCH: horizon_client::clipboard::FieldId = ("creative.search", 0);
+8 -3
View File
@@ -52,11 +52,16 @@ impl Game<'_> {
/// Remember who deals the next `damage_type` damage to the player.
pub(super) fn note_attacker(&mut self, damage_type: &str, mob: u32) {
if let Some(name) = self.mob_display_name(mob) {
self.combat
.pending
.push((damage_type.to_owned(), (mob, name)));
self.note_named_attacker(damage_type, mob, name);
}
}
/// `note_attacker` for an entity that is not one of `self.mobs` (the
/// ender dragon).
pub(super) fn note_named_attacker(&mut self, damage_type: &str, id: u32, name: Text) {
self.combat
.pending
.push((damage_type.to_owned(), (id, name)));
}
/// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the
/// source's `DamageEffects` (`Player.getHurtSound`).
pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) {
+114 -27
View File
@@ -1,6 +1,7 @@
//! Headless command runner for `tools/test_command_exec_parity.py`: with
//! `HORIZON_COMMAND_SCRIPT` and `HORIZON_COMMAND_OUTPUT` set, the opened world
//! runs without a window. Each script line is a JSON operation: `cmd` runs a
//! runs on its server thread with a connected, headless client. Each script
//! line is a JSON operation: `cmd` runs a
//! command as the player (Commands.performPrefixedCommand) and records every
//! system message it produced, as styled spans, with the results reported to
//! the player's `CommandResultCallback`; `tick` advances the game; `settle`
@@ -41,30 +42,100 @@ pub(super) fn spans(text: &Text) -> Value {
}
impl Game<'_> {
/// Pump the real client's connection, without predicting movement: the
/// oracle's player stays where commands put it. Errors cross the server
/// boundary through Integrated::stop, including script and save failures.
pub(super) fn wait_command_harness(&mut self) -> Result<()> {
let server = self.integrated.take().ok_or("command harness: no server")?;
while !server.stopped() {
self.poll_stationary_client()?;
std::thread::sleep(Duration::from_millis(2));
}
server.stop()
}
/// The owner's authoritative body and level, using the same swaps as a
/// server command. Always put them back, also when a script operation fails.
fn harness_owner<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
let owner = self
.serving
.as_ref()
.ok_or("command harness: not a server")?
.owner;
let mut host = self.lan.take().ok_or("command harness: no hub")?;
let guest = host.hub.guests.iter().find(|g| g.uuid == owner && g.placed);
let Some(guest) = guest else {
self.lan = Some(host);
return Err("command harness: owner is not connected".into());
};
let (conn, dim, back) = (guest.conn, super::Dim::from_id(&guest.dimension), self.dim);
if let Err(error) = self.enter_level(Some(&mut host), dim) {
self.lan = Some(host);
return Err(error);
}
let swap = self
.enter_guest(&mut host, conn)
.expect("the owner is not already acting");
self.lan = Some(host);
let result = f(self);
let mut host = self.lan.take().expect("the operation puts the hub back");
self.leave_guest(&mut host, swap);
host.hub.sync_all_effects();
self.run_level_teleports(&mut host);
let restored = self.enter_level(Some(&mut host), back);
self.lan = Some(host);
restored?;
result
}
/// The player's portal process finished in the nether portal it stands
/// in (the oracle's player is not ticked, so neither is the wait).
fn harness_portal(&mut self) -> Result<()> {
let Some(p) = &self.player else {
return Err("command harness: portal without a player".into());
};
let entry = horizon_core::position::BlockPos::containing(p.position);
let block = self.world.block(entry.x, entry.y, entry.z);
if &*self.res.facts().get(block).name != "minecraft:nether_portal" {
return Err("command harness: the player is not in a nether portal".into());
}
self.player_through_nether_portal(entry)
let (conn, plan) = self.harness_owner(|g| {
let p = g
.player
.as_ref()
.ok_or("command harness: portal without a player")?;
let entry = horizon_core::position::BlockPos::containing(p.position);
let block = g.world.block(entry.x, entry.y, entry.z);
if &*g.res.facts().get(block).name != "minecraft:nether_portal" {
return Err("command harness: the player is not in a nether portal".into());
}
let plan = g.portal_plan(
entry,
p.position,
p.dimensions.width,
p.dimensions.height,
true,
);
Ok((
g.lan_acting.ok_or("command harness: no acting owner")?,
plan,
))
})?;
// Start travel after restoring the owner's body: change_level updates
// its hub record, which leave_guest would otherwise overwrite.
self.in_owner_level(|g| {
let mut host = g.lan.take().ok_or("command harness: no hub")?;
g.start_server_trip(&mut host, conn, plan.dim, Some(plan));
g.lan = Some(host);
Ok(())
})
}
/// Load terrain until the player stands in lit chunks.
fn harness_settle(&mut self, deadline: Instant) -> Result<()> {
loop {
self.update_world();
self.spawn_player()?;
if let Some(p) = &self.player {
let (cx, cz) = (
(p.position.x.floor() as i32) >> 4,
(p.position.z.floor() as i32) >> 4,
);
if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
// Finish requested terrain before inspecting it, so worker
// timing cannot change which command positions are loaded.
if !self.streaming.busy()
&& (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz)))
{
// The oracle's settle also waits for the entities saved
// in those chunks (areEntitiesActuallyLoadedAndTicking):
// after a dimension change they come back from the save.
@@ -95,7 +166,19 @@ impl Game<'_> {
.and_then(|v| v.parse().ok())
.unwrap_or(600),
);
self.harness_settle(deadline)?;
// Join/configuration uses the normal hub, but never advances the world.
while !self
.lan
.as_ref()
.is_some_and(|h| h.hub.guests.iter().any(|g| g.placed && g.loaded))
{
self.tick_server(true)?;
if Instant::now() > deadline {
return Err("command harness: owner did not connect".into());
}
std::thread::sleep(Duration::from_millis(2));
}
self.harness_owner(|g| g.harness_settle(deadline))?;
let mut out = String::new();
for line in std::fs::read_to_string(script)?.lines() {
if line.trim().is_empty() {
@@ -107,9 +190,12 @@ impl Game<'_> {
let command = op["cmd"].as_str().unwrap_or("");
self.chat_capture = Some(Vec::new());
self.cmds.results = Some(Vec::new());
self.as_console(|g| {
g.run_command(command.strip_prefix('/').unwrap_or(command))
});
self.harness_owner(|g| {
g.as_console(|g| {
g.run_command(command.strip_prefix('/').unwrap_or(command))
});
Ok(())
})?;
let messages = self.chat_capture.take().unwrap_or_default();
let results = self.cmds.results.take().unwrap_or_default();
if op["record"].as_bool() != Some(false) {
@@ -124,17 +210,8 @@ impl Game<'_> {
}
"tick" => {
self.chat_capture = Some(Vec::new());
// The oracle's player has no client moving it: hold the
// player where commands put it while the game ticks.
let held = self.player.as_ref().map(|p| p.position);
for _ in 0..op["n"].as_u64().unwrap_or(1) {
self.update_world();
self.tick()?;
if let (Some(p), Some(at)) = (self.player.as_mut(), held) {
p.position = at;
p.velocity = horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0);
p.fall_distance = 0.0;
}
self.tick_server(false)?;
}
let messages = self.chat_capture.take().unwrap_or_default();
if op["record"].as_bool() == Some(true) {
@@ -147,7 +224,17 @@ impl Game<'_> {
out.push('\n');
}
}
"settle" => self.harness_settle(deadline)?,
"settle" => {
// Finish portal arrivals using connection-only passes too.
while !self.server_trips.is_empty() {
self.tick_server(true)?;
if Instant::now() > deadline {
return Err("command harness: portal did not arrive".into());
}
std::thread::sleep(Duration::from_millis(2));
}
self.harness_owner(|g| g.harness_settle(deadline))?;
}
"portal" => self.harness_portal()?,
other => return Err(format!("command harness: unknown op {other}").into()),
}
+42 -10
View File
@@ -10,6 +10,7 @@ mod items;
mod misc;
mod place;
mod players;
pub(super) mod pregen;
mod raid;
mod terrain_cmds;
mod text_commands;
@@ -84,16 +85,16 @@ fn format_double(v: f64) -> String {
impl Game<'_> {
/// Commands.performCommand for a line without its slash.
pub(super) fn run_command(&mut self, command: &str) {
pub(super) fn run_command(&mut self, command: &str) -> bool {
if self.mod_command(command) {
return;
return true;
}
let d = vanilla::game_dispatcher();
let parse = d.parse(command, &self.ui.registries);
let result = match parse.executable() {
Err(e) => {
self.syntax_failure(&e, command);
return;
return false;
}
Ok((ctx, _)) => {
let ctx = ctx.clone();
@@ -102,6 +103,7 @@ impl Game<'_> {
self.run_chain(&root, &ctx)
}
};
let ok = result.is_ok();
if let Err(e) = result {
if e.input.is_some() {
self.syntax_failure(&e, command);
@@ -113,6 +115,20 @@ impl Game<'_> {
if self.player.is_some() {
self.check_inventory_trigger();
}
ok
}
/// `run_command` with its output suppressed
/// (`CommandSourceStack.withSuppressedOutput`): the player's own source,
/// rights and checks, no feedback and no failure in the chat.
pub(super) fn run_command_quietly(&mut self, command: &str) -> bool {
let quiet = execute::Source {
silent: true,
..self.player_source()
};
let outer = self.command_source.replace(quiet);
let ok = self.run_command(command);
self.command_source = outer;
ok
}
fn syntax_failure(&mut self, e: &CommandError, command: &str) {
self.command_failure(e.message.clone());
@@ -751,13 +767,15 @@ impl Game<'_> {
&& !id.ends_with("get")
&& let Ok(t) = self.entities(ctx, "target", false)
{
self.cmds.waypoint_dirty.push(t[0]);
let target = self.waypoint_target(t[0]);
self.cmds.waypoint_dirty.push(target);
}
result
}
"ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx),
"spreadplayers" => self.cmd_spreadplayers(ctx),
id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx),
id if id.starts_with("pregen.") => self.cmd_pregen(id, ctx),
"fillbiome" => self.cmd_fillbiome(ctx),
id if id.starts_with("worldborder.") => self.cmd_worldborder(id, ctx),
id if id.starts_with("loot.") => self.cmd_loot(id, ctx),
@@ -1094,6 +1112,12 @@ impl Game<'_> {
Target::Player => {
// ServerPlayer.teleport: removeVehicle before placing the player.
self.stop_riding();
// A server's player teleported within their level is placed
// there at once: the arrival they were waiting for elsewhere
// in it (whose chunks lose their tickets) is abandoned.
if let Some(conn) = self.lan_acting {
self.server_trips.retain(|trip| !trip.is(conn));
}
if let Some(p) = self.player.as_mut() {
p.position = v;
p.velocity = Vec3::new(0.0, 0.0, 0.0);
@@ -2499,12 +2523,14 @@ impl Game<'_> {
};
let max = Self::int(ctx, "maxCount").unwrap_or(-1);
let counting = max == 0;
// Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried.
// Inventory slots 0..40: main, armor feet to head, off hand;
// then clearOrCountMatchingItems visits the crafting grid and carried stack.
let mut removed = 0i32;
let mut budget = if max < 0 { i32::MAX } else { max };
let all = |g: &Self| -> Vec<Option<ItemStack>> {
let mut v: Vec<Option<ItemStack>> = g.inventory.clone();
v.extend(g.armor.iter().cloned());
v.extend(g.armor.iter().rev().cloned());
v.push(g.offhand.clone());
v.extend(g.craft_grid.iter().cloned());
v.push(g.carried.clone());
v
@@ -2518,7 +2544,8 @@ impl Game<'_> {
.collect();
let mut slots: Vec<&mut Option<ItemStack>> = Vec::new();
slots.extend(self.inventory.iter_mut());
slots.extend(self.armor.iter_mut());
slots.extend(self.armor.iter_mut().rev());
slots.push(&mut self.offhand);
slots.extend(self.craft_grid.iter_mut());
slots.push(&mut self.carried);
for (slot, matches) in slots.into_iter().zip(matching) {
@@ -2836,9 +2863,14 @@ impl Game<'_> {
capture.push(line.clone());
}
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.gui.atlas, line, None, self.ticks, focused);
self.ui.chat.add(
&self.gui.atlas,
line,
None,
horizon_client::chat::ChatSource::Player,
self.ticks,
focused,
);
Ok(1)
}
/// MessageArgument: `@p`-style selectors in a message become names.
@@ -57,6 +57,8 @@ pub(in crate::game) struct CommandExtras {
/// The `CommandResultCallback` results of the outermost source, when a
/// harness records them.
pub results: Option<Vec<(bool, i32)>>,
/// The running `/pregen` task.
pub pregen: Option<super::pregen::PregenTask>,
}
use horizon_core::version::{BUILD_TIME, DATA_VERSION, STABLE, VANILLA_VERSION, VERSION_ID};
@@ -212,8 +214,22 @@ impl Game<'_> {
// ---- /waypoint ------------------------------------------------------
/// A guest's body is only `Player` during its turn; retained command state
/// must use its connection so the next server tick still finds that body.
pub(super) fn waypoint_target(&self, t: Target) -> Target {
match t {
Target::Player => self.lan_acting.map_or(t, Target::Guest),
_ => t,
}
}
/// A living entity's `waypoint_transmit_range` (`isTransmittingWaypoint`).
fn transmit_range(&mut self, t: Target) -> f64 {
if matches!(t, Target::Guest(_)) {
return self
.for_player(t, |g| g.transmit_range(Target::Player))
.unwrap_or(0.0);
}
if t == Target::Player {
return self
.player
@@ -242,7 +258,7 @@ impl Game<'_> {
fn waypoint_transmitters(&mut self) -> Vec<Target> {
if self.cmds.waypoints.is_none() {
let tracked = if self.transmit_range(Target::Player) > 0.0 {
vec![Target::Player]
vec![self.waypoint_target(Target::Player)]
} else {
Vec::new()
};
@@ -255,6 +271,12 @@ impl Game<'_> {
.collect();
self.cmds.waypoints = Some(alive.clone());
alive
.into_iter()
.map(|t| match t {
Target::Guest(conn) if self.lan_acting == Some(conn) => Target::Player,
_ => t,
})
.collect()
}
/// The waypoint part of a living entity's tick: dirty transmit ranges
/// track or untrack it.
@@ -277,7 +299,7 @@ impl Game<'_> {
fn waypoint_icon(&self, t: Target) -> WaypointIcon {
self.cmds
.waypoint_icons
.get(&t)
.get(&self.waypoint_target(t))
.cloned()
.unwrap_or_default()
}
@@ -387,6 +409,7 @@ impl Game<'_> {
&[Text::colored(name, rgb)],
)
};
let t = self.waypoint_target(t);
self.cmds.waypoint_icons.insert(t, icon);
// WaypointCommand.mutateIcon: untrack, change, track again.
self.waypoint_transmitters();
@@ -606,6 +629,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| lan.hub.singleplayer_owner != Some(g.uuid))
.filter(|g| match &s.player_name {
Some(name) => g.name.eq_ignore_ascii_case(name),
None => s.kind == 'a' || s.kind == 'e',
@@ -617,7 +641,7 @@ impl Game<'_> {
if host.is_empty() && guests.is_empty() {
return Err(err("argument.entity.notfound.player", &[]));
}
if self.lan.is_none() {
if self.lan.is_none() || (self.serving() && self.published_port().is_none()) {
return Err(err("commands.kick.singleplayer.failed", &[]));
}
let reason_raw = match ctx.get("reason") {
@@ -0,0 +1,276 @@
//! `/pregen`, Horizon's own command: generate, light and save every chunk of a
//! square or a circle ahead of the players (docs/pregeneration.md). The task
//! lives on the server and hands its band to the level's streaming, whose
//! workers do the work; chunks behind the band unload and are saved as any
//! chunk the players leave.
use super::{CommandError, Context, Dim, Game, R};
use horizon_client::{
lan::data::component_nbt,
pregen::{Pregen, Shape},
text::{self, Text},
};
use horizon_protocol::packets::play::{self, Clientbound as C};
use std::time::{Duration, Instant};
/// How often the progress is reported.
const REPORT_EVERY: Duration = Duration::from_secs(5);
/// How long the band may stay put before the task looks for what holds it.
const STALL: Duration = Duration::from_secs(30);
pub(in crate::game) struct PregenTask {
pregen: Pregen,
dim: Dim,
paused: bool,
/// Time spent running, up to the last pause, and when it last resumed.
ran: Duration,
resumed: Instant,
reported: Instant,
/// When the band last moved, to notice a task that stopped advancing.
moved: Instant,
/// The player who started it, told the progress too (a guest's connection).
owner: Option<u32>,
}
impl PregenTask {
fn running_for(&self) -> Duration {
if self.paused {
self.ran
} else {
self.ran + self.resumed.elapsed()
}
}
fn progress(&self) -> Text {
let p = &self.pregen;
let seconds = self.running_for().as_secs_f64();
let rate = p.done as f64 / seconds.max(1e-3);
let left = p.total - p.done;
let eta = if rate > 0.0 {
duration(left as f64 / rate)
} else {
"unknown".into()
};
Text::literal(format!(
"Pregenerating {}: {} of {} chunks ({:.1}%), {rate:.1} chunks/s, {} left",
self.dim.id(),
p.done,
p.total,
100.0 * p.done as f64 / p.total.max(1) as f64,
if p.done == p.total {
"nothing".into()
} else {
eta
},
))
}
}
fn failure(message: &str) -> CommandError {
CommandError::new(Text::literal(message))
}
/// `1h 02m 03s`.
fn duration(seconds: f64) -> String {
let s = seconds.round() as u64;
match (s / 3600, s / 60 % 60, s % 60) {
(0, 0, s) => format!("{s}s"),
(0, m, s) => format!("{m}m {s:02}s"),
(h, m, s) => format!("{h}h {m:02}m {s:02}s"),
}
}
impl Game<'_> {
pub(super) fn cmd_pregen(&mut self, id: &str, ctx: &Context) -> R<i32> {
match id {
"pregen.start" => {
if self.cmds.pregen.is_some() {
return Err(failure(
"Pregeneration is already running: /pregen cancel stops it",
));
}
let radius = Self::int(ctx, "radius").unwrap_or(0);
let shape = if ctx.literals.iter().any(|l| l == "circle") {
Shape::Circle
} else {
Shape::Square
};
let [x, z] = if ctx.get("center").is_some() {
self.column_arg(ctx, "center")?
} else {
let p = self.source_position();
[p[0].floor() as i32, p[2].floor() as i32]
};
let pregen = Pregen::new((x >> 4, z >> 4), radius >> 4, shape);
let now = Instant::now();
let total = pregen.total;
self.feedback(Text::literal(format!(
"Pregenerating {total} chunks of {}: a {} of radius {radius} around {x} {z}",
self.dim.id(),
match shape {
Shape::Square => "square",
Shape::Circle => "circle",
},
)));
self.cmds.pregen = Some(PregenTask {
pregen,
dim: self.dim,
paused: false,
ran: Duration::ZERO,
resumed: now,
reported: now,
moved: now,
owner: self.lan_acting,
});
Ok(total as i32)
}
"pregen.pause" | "pregen.continue" => {
let pause = id == "pregen.pause";
let task = self
.cmds
.pregen
.as_mut()
.ok_or_else(|| failure("No pregeneration is running"))?;
if task.paused != pause {
task.paused = pause;
if pause {
task.ran += task.resumed.elapsed();
} else {
task.resumed = Instant::now();
}
}
let (progress, dim) = (task.progress(), task.dim);
if pause && self.dim == dim {
self.streaming.set_band(None);
}
self.feedback(
Text::literal(if pause { "Paused. " } else { "Continuing. " }).append(progress),
);
Ok(1)
}
"pregen.cancel" => {
let task = self
.cmds
.pregen
.take()
.ok_or_else(|| failure("No pregeneration is running"))?;
if self.dim == task.dim {
self.streaming.set_band(None);
}
self.feedback(Text::literal("Cancelled. ").append(task.progress()));
Ok(task.pregen.done as i32)
}
_ => {
let task = self
.cmds
.pregen
.as_ref()
.ok_or_else(|| failure("No pregeneration is running"))?;
let progress = task.progress();
let done = task.pregen.done as i32;
self.feedback(progress);
Ok(done)
}
}
}
/// Move the task's band past the rows that are lit and hand it to the
/// level's streaming, and report the progress now and then. Runs before
/// each streaming update of the level in place.
pub(in crate::game) fn tick_pregen(&mut self) {
let Some(task) = self.cmds.pregen.as_mut() else {
return;
};
if task.dim != self.dim || task.paused {
return;
}
// A row is done once its chunks are lit and post-processed
// (`postprocess_chunks`, on the tick), as vanilla's are by the time
// they are FULL: then they may unload and be saved.
let (streaming, chunks) = (&mut self.streaming, &self.world.chunks);
if task.pregen.advance(|x, z| {
streaming.is_lit(x, z)
&& chunks
.get(&(x, z))
.is_some_and(|c| c.postprocess.is_empty())
}) {
task.moved = Instant::now();
}
streaming.set_band(task.pregen.band());
if task.moved.elapsed() >= STALL {
// Nothing advanced for a while: say what the first row waits
// for, and queue light again for chunks that lost their job.
task.moved = Instant::now();
let row = task.pregen.first_row();
let waiting = row
.iter()
.filter(|k| chunks.get(k).is_some_and(|c| !c.postprocess.is_empty()))
.count();
let [missing, lighting, unlit] = streaming.unstick_light(&mut self.world, &row);
log::warn!(
"Horizon: pregeneration waits on row {:?}: {missing} not loaded, {lighting} being lit, \
{unlit} unlit with no light job (queued again), {waiting} not post-processed; {:?}",
row.first(),
streaming.stages()
);
}
let finished = task.pregen.finished();
if finished || task.reported.elapsed() >= REPORT_EVERY {
task.reported = Instant::now();
let (owner, mut message) = (task.owner, task.progress());
if finished {
message = Text::literal("Done. ")
.append(message)
.with_color(text::GREEN);
self.cmds.pregen = None;
}
self.pregen_report(owner, message);
}
}
/// Whether the level in place has a running task, which the server pumps
/// between its ticks (`pump_pregen`).
pub(in crate::game) fn pregen_runs_here(&self) -> bool {
self.cmds
.pregen
.as_ref()
.is_some_and(|t| t.dim == self.dim && !t.paused)
}
/// The level a running task needs ticked, whoever is in it.
pub(in crate::game) fn pregen_level(&self) -> Option<Dim> {
self.cmds.pregen.as_ref().map(|t| t.dim)
}
/// Keep the workers fed until `until`: collect what they finished and
/// hand them the next jobs as soon as each one is done, rather than once
/// a tick.
pub(in crate::game) fn pump_pregen(&mut self, until: Instant) {
while self.pregen_runs_here() {
let now = Instant::now();
if now >= until {
break;
}
self.streaming
.wait((until - now).min(Duration::from_millis(5)));
self.update_world();
}
}
/// The console and the player who started the task get the progress.
fn pregen_report(&mut self, owner: Option<u32>, message: Text) {
if self.options.dedicated.is_some() {
super::super::dedicated::log("INFO", &message.plain());
} else {
log::info!("{}", message.plain());
}
if let Some(host) = &self.lan {
if let Some(g) = owner.and_then(|c| host.hub.guest(c)) {
g.send(&C::SystemChat(play::SystemChat {
content: component_nbt(&message.component()),
overlay: false,
}));
}
} else if self.options.dedicated.is_none() {
self.system_message(message);
}
}
}
@@ -30,7 +30,7 @@ fn ticks_to_seconds(ticks: i64) -> String {
impl Game<'_> {
// ---- /forceload ----------------------------------------------------------
fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> {
pub(super) fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> {
let c = self
.coords(ctx, name)
.ok_or_else(|| err("argument.pos2d.incomplete", &[]))?;
+82 -4
View File
@@ -11,6 +11,9 @@ use winit::{event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode};
const HELP: &[&str] = &[
"status game, player, streaming and renderer state",
"simulation authoritative projectiles in the owner's level",
"server-hold on|off hold simulation and player packets at a control-fixture barrier",
"stall MILLISECONDS stall the window thread (0..5000), leaving transport alive",
"key KEY down|up|tap|repeat press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
"release release every key and mouse button",
"mouse left|right|middle down|up|click",
@@ -238,9 +241,57 @@ impl Game<'_> {
}
"sculk" => Ok(Some(self.sculk_command(&words)?)),
"status" => Ok(Some(self.control_status())),
"stall" => {
let millis: u64 = arg(1)?.parse()?;
if millis > 5000 {
return Err("stall is limited to 5000 milliseconds".into());
}
std::thread::sleep(Duration::from_millis(millis));
ok()
}
"simulation" => {
self.require_world()?;
let value = if let Some(server) = &self.integrated {
server
.call(|g| {
g.in_owner_level(|g| {
json!({ "game_time": g.world.game_time, "projectiles": g.projectiles_status() })
})
})
.ok_or("the integrated server stopped")?
} else {
json!({ "game_time": self.world.game_time, "projectiles": self.projectiles_status() })
};
Ok(Some(value))
}
"server-hold" => {
self.require_world()?;
let held = match arg(1)? {
"on" => true,
"off" => false,
_ => return Err("server-hold on|off".into()),
};
if let Some(server) = &self.integrated {
server
.call(move |g| g.agent.hold_server = held)
.ok_or("the integrated server stopped")?;
} else if self.remote.is_some() {
return Err("server-hold requires the world's host".into());
} else {
self.agent.hold_server = held;
}
ok()
}
"pad" => Ok(Some(self.pad_command(&words)?)),
"key" => {
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
// A server's dialog takes the keys, in configuration too.
if self.dialog_open() {
if arg(2)? != "up" {
self.dialog_key(key, None, None)?;
}
return ok();
}
self.require_world()?;
// The sign editor takes raw presses (Enter, arrows, Backspace, Escape).
if self.sign_edit.is_some() {
@@ -288,11 +339,12 @@ impl Game<'_> {
self.debug_key(key, KeyAction::Release);
}
}
// The zoom extra sees the key as the keyboard hook does.
// Mods' keys (capability `input`) see the key as the keyboard
// hook does.
let action = arg(2)?;
self.extras_key(physical, action != "up", action == "repeat");
self.mod_key(physical, action != "up", action == "repeat");
if action == "tap" {
self.extras_key(physical, false, false);
self.mod_key(physical, false, false);
}
// Text screens consume raw presses; releases follow key binds.
let typing = matches!(self.screen, Screen::Chat | Screen::Options);
@@ -367,15 +419,19 @@ impl Game<'_> {
match arg(2)? {
"down" => {
self.extras_mouse(button, true);
self.mod_mouse_key(button, true);
self.play_mouse(button, true)?
}
"up" => {
self.extras_mouse(button, false);
self.mod_mouse_key(button, false);
self.play_mouse(button, false)?
}
"click" => {
self.extras_mouse(button, true);
self.mod_mouse_key(button, true);
self.extras_mouse(button, false);
self.mod_mouse_key(button, false);
self.play_mouse(button, true)?;
self.play_mouse(button, false)?;
}
@@ -496,10 +552,23 @@ impl Game<'_> {
"mobs" => {
self.require_world()?;
let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?;
if let Some(server) = &self.integrated {
let center = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
let value = server
.call(move |g| g.in_owner_level(|g| g.control_mobs_at(radius, center)))
.ok_or("the integrated server stopped")?;
return Ok(Some(value));
}
Ok(Some(self.control_mobs(radius)))
}
"hurtlog" => {
self.require_world()?;
if let Some(server) = &self.integrated {
let value = server
.call(|g| g.control_hurt_log())
.ok_or("the integrated server stopped")?;
return Ok(Some(value));
}
Ok(Some(self.control_hurt_log()))
}
"resume" => {
@@ -533,13 +602,17 @@ impl Game<'_> {
))
}
"type" => {
self.require_world()?;
let text = line
.trim_start()
.strip_prefix("type")
.unwrap_or("")
.strip_prefix(' ')
.unwrap_or("");
// A server's dialog, in configuration too.
if self.dialog_type(text) {
return ok();
}
self.require_world()?;
if self.book.is_some() {
self.book_type(text);
return ok();
@@ -596,6 +669,7 @@ impl Game<'_> {
"font" => Page::Font,
"packs" => Page::Packs,
"mods" => Page::Mods,
"shader-packs" => Page::ShaderPacks,
"graphics" => Page::Graphics,
"graphics-advanced" => Page::GraphicsAdvanced,
"extras" => Page::Extras,
@@ -609,6 +683,10 @@ impl Game<'_> {
}
self.open_options(self.title.is_some());
self.ui.options.show(page);
if page == Page::ShaderPacks {
self.settings.shader_packs =
horizon_client::shader_pack_list::scan(&Self::shader_packs_dir());
}
ok()
}
"chat-log" => {
+53 -24
View File
@@ -43,10 +43,6 @@ fn arrow_damage(arrow: &mut Projectile, fallback: &mut impl RandomSource) -> f32
#[derive(Default)]
pub(super) struct Creatures {
pub projectiles: Vec<Projectile>,
/// Player status effects applied by mobs: (effect, ticks left, amplifier).
pub pearl_cooldown: u32,
/// The wind charge's use cooldown (ticks).
pub wind_cooldown: u32,
/// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs).
pub wind_bursts: Vec<super::wind::Burst>,
/// Ticks left of the elder guardian's apparition (MobAppearanceParticle).
@@ -54,9 +50,9 @@ pub(super) struct Creatures {
/// The wandering trader spawner's clock.
pub trader: super::wandering_trader::Spawner,
}
struct ProjWorld<'a, 'w> {
w: &'a MobWorld<'w>,
targets: Vec<(Who, Aabb)>,
pub(super) struct ProjWorld<'a, 'w> {
pub w: &'a MobWorld<'w>,
pub targets: Vec<(Who, Aabb)>,
}
impl ProjectileWorld for ProjWorld<'_, '_> {
fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> {
@@ -316,6 +312,9 @@ impl Game<'_> {
/// The `mobs` command: nearby mobs with position, health and running goals.
pub(super) fn control_mobs(&self, radius: f64) -> serde_json::Value {
let center = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
self.control_mobs_at(radius, center)
}
pub(super) fn control_mobs_at(&self, radius: f64, center: Vec3) -> serde_json::Value {
let list: Vec<serde_json::Value> = self
.mobs
.iter()
@@ -374,6 +373,7 @@ impl Game<'_> {
// Drawn seated (Entity.isPassenger); set apart because the
// json! above is at the macro recursion limit.
state["passenger"] = m.extra.passenger.into();
state["guardian_beam"] = serde_json::json!(horizon_client::mobs::guardian::beam(m, 0.0));
state
})
.collect();
@@ -392,6 +392,9 @@ impl Game<'_> {
}
pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> {
let (rain, thunder) = self.world.weather.levels(1.0);
// Level.canHaveWeather: only the overworld's rain and thunder levels
// ever rise, so nothing rains or thunders in the Nether or the End.
let weather = self.dim == Dim::Overworld;
let player = self.player_view();
MobWorld {
world: &self.world,
@@ -408,8 +411,8 @@ impl Game<'_> {
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
game_time: self.world.game_time,
day_time: self.world.day_time,
raining: rain > 0.2,
thundering: thunder > 0.9,
raining: weather && rain > 0.2,
thundering: weather && thunder > 0.9,
nether: self.dim == Dim::Nether,
block_tags: &self.res.items().block_tags,
biomes: self.res.biomes(),
@@ -508,6 +511,17 @@ impl Game<'_> {
Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players),
_ => Default::default(),
};
// The guests' entity ids by connection, for the shulker bullets fired
// at the guest a mob sees.
let guest_ids: Vec<(u32, u32)> = match self.lan.as_ref() {
Some(host) if !guests.is_empty() => host
.hub
.guests
.iter()
.map(|g| (g.conn, g.entity_id as u32))
.collect(),
_ => Vec::new(),
};
let mut guest_events = Vec::new();
let level_random;
{
@@ -582,6 +596,19 @@ impl Game<'_> {
let kept = m.tick(&w, &mut scratch, &mut events);
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
if let Some(conn) = seen_guest {
// ShulkerBullet.finalTarget is the guest's entity: the
// bullet homes on it while the projectiles tick, where
// `Who::Player` is the host's own player.
if let Some(&(_, id)) = guest_ids.iter().find(|g| g.0 == conn) {
for e in &mut events[from..] {
if let MobEvent::Projectile(p) = e
&& let ProjectileKind::ShulkerBullet { target, .. } = &mut p.kind
&& *target == Who::Player
{
*target = Who::Mob(id);
}
}
}
let mut k = from;
while k < events.len() {
if super::lan_mobs::acts_on_player(&events[k]) {
@@ -642,7 +669,6 @@ impl Game<'_> {
self.tick_allays();
self.tick_breeze_effects();
self.tick_sniffer_effects();
self.tick_player_effects();
self.piglin_pickups();
self.sulfur_cube_pickups();
// Hurt and death sounds of damage dealt outside the mob ticks.
@@ -1040,7 +1066,10 @@ impl Game<'_> {
}
MobEvent::BreakBlock { pos, drop } => {
let old = self.world.block(pos[0], pos[1], pos[2]);
self.destroy_particles(pos, old);
// Block.spawnDestroyParticles: fire breaks leave nothing.
if !self.res.facts().get(old).has_class("BaseFireBlock") {
self.destroy_particles(pos, old);
}
if drop {
let drops = self.res.items().block_drops_in(
self.pack.assets.registry,
@@ -1062,6 +1091,9 @@ impl Game<'_> {
self.ensure_item_particle_sprites();
}
let options = horizon_client::particles::ParticleOptions::simple(ty);
if ty == horizon_client::particles::ParticleType::SonicBoom {
self.lan_sonic_boom(&options, at);
}
// Count 0: one particle exactly there, at rest.
if count == 0 {
self.particles.add(&options, at, [0.0; 3]);
@@ -1572,13 +1604,6 @@ impl Game<'_> {
}
self.give_player_effect("minecraft:wither", 40, 0);
}
/// Burning applied to the player by mobs.
fn tick_player_effects(&mut self) {
self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1);
if self.creatures.pearl_cooldown > 0 {
self.creatures.pearl_cooldown -= 1;
}
}
pub(super) fn hurt_player_by(&mut self, damage_type: &str, amount: f32) {
if self.creative {
return;
@@ -2879,14 +2904,14 @@ impl Game<'_> {
let kind = match item {
"minecraft:snowball" => ProjectileKind::Snowball,
"minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => ProjectileKind::Egg,
"minecraft:ender_pearl" => {
if self.creatures.pearl_cooldown > 0 {
return Ok(true);
"minecraft:ender_pearl" => ProjectileKind::EnderPearl,
"minecraft:wind_charge" => {
let thrown = self.throw_wind_charge()?;
if thrown {
self.apply_use_cooldown(stack);
}
self.creatures.pearl_cooldown = 20;
ProjectileKind::EnderPearl
return Ok(thrown);
}
"minecraft:wind_charge" => return self.throw_wind_charge(),
_ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack),
_ => return Ok(false),
};
@@ -2911,6 +2936,9 @@ impl Game<'_> {
);
self.creatures.projectiles.push(proj);
self.player_projectile_shot();
// ItemStack.use's applyAfterUseComponentSideEffects: the pearl's
// second is the `use_cooldown` component, as for any thrown item.
self.apply_use_cooldown(stack);
let sound = match kind {
ProjectileKind::Snowball => "minecraft:entity.snowball.throw",
ProjectileKind::Egg => "minecraft:entity.egg.throw",
@@ -3031,6 +3059,7 @@ impl Game<'_> {
continue;
}
}
self.mark_entity(entity_start, &mob.kind.id);
let light = self.world.light(
mob.position.x.floor() as i32,
(mob.position.y + mob.eye_height()).floor() as i32,
+494
View File
@@ -0,0 +1,494 @@
//! Cushions: `CushionItem.useOn` placement on the top face of a block,
//! `Cushion.canBePlacedAt`/`survives`, `Cushion.interact` (sit),
//! `BlockAttachedEntity.hurtServer` (break, dropping the matching colour),
//! `BlockAttachedEntity.tick` and `CushionRenderer`.
//!
//! A cushion is a `BlockAttachedEntity`, not a block: it has no block state,
//! only an entity whose `Pos` is the click point's height. Placement uses
//! outline bounds, collision shapes and suffocation predicates.
use super::{Game, Hit, view_vector};
use horizon_client::entities::{Cushion, dye_index};
use horizon_client::items::ItemStack;
use horizon_client::mobs::anim::Poses;
use horizon_core::geometry::{Aabb, Vec3};
use winit::keyboard::KeyCode;
/// `Direction.fromYRot(yaw).toYRot()`: the nearest 90 degree step.
pub(crate) fn snap_yaw(yaw: f32) -> f32 {
(((f64::from(yaw) / 90.0 + 0.5).floor() as i64) & 3) as f32 * 90.0
}
fn aabb(bounds: ([f64; 3], [f64; 3])) -> Aabb {
Aabb::new(
Vec3::new(bounds.0[0], bounds.0[1], bounds.0[2]),
Vec3::new(bounds.1[0], bounds.1[1], bounds.1[2]),
)
}
fn overlaps(a: Aabb, b: Aabb) -> bool {
a.intersects(b)
}
use horizon_client::cushion::blocks_in;
struct PlacementWorld<'a, 'r>(&'a Game<'r>);
impl horizon_client::cushion::World for PlacementWorld<'_, '_> {
fn outline_bounds(&self, p: [i32; 3]) -> Option<Aabb> {
let boxes = self.0.outline_boxes(p);
let mut shape = *boxes.first()?;
for b in &boxes[1..] {
for k in 0..3 {
shape[k] = shape[k].min(b[k]);
shape[k + 3] = shape[k + 3].max(b[k + 3]);
}
}
Some(Aabb::new(
Vec3::new(shape[0], shape[1], shape[2]),
Vec3::new(shape[3], shape[4], shape[5]),
))
}
fn collision_shapes(&self, bounds: Aabb) -> Vec<horizon_core::geometry::VoxelShape> {
let binding = self.0.res.collision();
let mut world = horizon_client::collisions::SceneCollisions {
world: &self.0.world,
binding,
subject: None,
};
// Include neighbour blocks whose collision shape can reach outside their cell.
blocks_in(bounds.inflate(Vec3::new(1.0, 1.0, 1.0)))
.filter_map(|p| {
let state = self.0.world.block(p[0], p[1], p[2]);
binding
.collision_shape(&mut world, state, p)
.ok()
.map(|s| s.moved(Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))))
})
.collect()
}
fn suffocating(&self, p: [i32; 3]) -> bool {
let state = self.0.world.block(p[0], p[1], p[2]);
let facts = self.0.res.facts().get(state);
let name = facts.name.as_ref();
// Blocks' explicit predicates, then the default causes_suffocation/full-shape rule.
match name {
"minecraft:dirt_path"
| "minecraft:farmland"
| "minecraft:mud"
| "minecraft:soul_sand" => true,
"minecraft:piston" | "minecraft:sticky_piston" => self
.0
.pack
.assets
.registry
.state(state)
.is_some_and(|s| s.properties.get("extended").is_some_and(|p| p == "false")),
"minecraft:mangrove_roots" | "minecraft:moving_piston" => false,
_ if name.ends_with("_leaves")
|| name.ends_with("glass")
|| name.ends_with("copper_grate") =>
{
false
}
// ShulkerBoxBlock: suffocating while closed; a box seen open
// here is rare enough to count as closed.
_ if name.ends_with("shulker_box") => true,
_ => {
facts.full_collision
&& self
.0
.res
.items()
.block_in_tag("minecraft:causes_suffocation", name)
}
}
}
}
impl Game<'_> {
/// The cushion under the crosshair, its distance and the hit point.
pub(super) fn cushion_hit(&self) -> Option<(usize, f64, [f64; 3])> {
let eye = self.eye_position()?;
let dir = view_vector(self.yaw, self.pitch);
let reach: f64 = if self.creative { 5.0 } else { 3.0 };
let mut best: Option<(usize, f64, [f64; 3])> = None;
for (i, c) in self.cushions.iter().enumerate() {
let Some(d) = super::ray_box(eye, dir, reach, aabb(c.bounds())) else {
continue;
};
if best.is_none_or(|b| d < b.1) {
best = Some((i, d, std::array::from_fn(|k| eye[k] + dir[k] * d)));
}
}
best
}
pub(super) fn cushion_survives(&self, c: &Cushion) -> bool {
horizon_client::cushion::survives(&PlacementWorld(self), aabb(c.bounds()))
}
/// `Cushion.destroyIfInFire`: a fire-tagged block inside the deflated box.
fn cushion_in_fire(&self, c: &Cushion) -> bool {
let bounds = aabb(c.bounds()).next_deflated();
blocks_in(bounds).any(|p| {
let facts = self.res.facts().get(self.world.block(p[0], p[1], p[2]));
self.res.items().block_in_tag("minecraft:fire", &facts.name)
})
}
/// `CushionItem.useOn`: on the top face only, spawning at the click's
/// height above the clicked block (or the replaceable block itself).
pub(super) fn place_cushion(&mut self, hit: &Hit, stack: &ItemStack) -> bool {
let Some(info) = self.res.items().get(&stack.item).cloned() else {
return false;
};
let Some(default_color) = info.cushion_color.as_deref() else {
return false;
};
let color_override = stack
.data()
.and_then(|d| d.other("minecraft:cushion/color"))
.and_then(|tag| match tag {
horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()),
_ => None,
});
let color = dye_index(color_override.as_deref().unwrap_or(default_color));
// CushionItem.recalculateContextForSpecialCollisionShapes: open containers
// (cauldrons, hoppers and composters) use the collision ray's actual height.
let mut adjusted = Hit {
pos: hit.pos,
face: hit.face,
point: hit.point,
};
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
if self.res.items().block_in_tag(
"minecraft:cushion_uses_collision_shape",
&self.res.facts().get(state).name,
) && let Some(eye) = self.eye_position()
{
let start = Vec3::new(eye[0], eye[1], eye[2]);
let point = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
let end = point.add_vector(point.subtract(start).normalize().scale(0.001));
let binding = self.res.collision();
let mut world = horizon_client::collisions::SceneCollisions {
world: &self.world,
binding,
subject: None,
};
if let Ok(shape) = binding.collision_shape(&mut world, state, hit.pos)
&& let Some(result) = shape.clip(
start,
end,
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
)
{
adjusted.face = result.direction.normal();
adjusted.point = [result.location.x, result.location.y, result.location.z];
}
}
let hit = &adjusted;
if hit.face != [0, 1, 0] {
return false;
}
// BlockPlaceContext: a replaceable clicked block is replaced.
let clicked = self
.res
.facts()
.get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]));
let pos = if clicked.replaceable {
hit.pos
} else {
std::array::from_fn(|i| hit.pos[i] + hit.face[i])
};
// `Vec3.atCenterOfWithY(clickedPos, clickLocation.y)`.
let y = hit.point[1];
let position = Vec3::new(f64::from(pos[0]) + 0.5, y, f64::from(pos[2]) + 0.5);
let bounds = aabb((
[position.x - 0.5, position.y, position.z - 0.5],
[position.x + 0.5, position.y + 0.25, position.z + 0.5],
));
if !horizon_client::cushion::can_place(&PlacementWorld(self), bounds) {
return false;
}
// `getEntitiesOfClass(Cushion.class, spawnAABB).isEmpty()`.
if self
.cushions
.iter()
.any(|c| overlaps(aabb(c.bounds()), bounds))
{
return false;
}
self.next_entity += 1;
let id = self.next_entity;
// `BlockAttachedEntity.setPos`: `BlockPos.containing(position)`.
let attached = [
position.x.floor() as i32,
position.y.floor() as i32,
position.z.floor() as i32,
];
self.cushions.push(Cushion {
id,
position,
pos: attached,
yaw: snap_yaw(self.yaw),
color,
check_interval: 0,
});
self.world
.modified
.insert((attached[0] >> 4, attached[2] >> 4));
// `destroyIfInFire`: placed into fire, it breaks at once.
let placed = self.cushions.len() - 1;
if self.cushion_in_fire(&self.cushions[placed]) {
self.break_cushion(placed, false);
}
self.audio.play(
"minecraft:entity.cushion.place",
Some([position.x, position.y, position.z]),
0.75,
0.8,
);
let ctx = self.who_context(Some(horizon_client::mobs::Who::Player), None);
self.post_game_event(
"minecraft:entity_place",
[position.x, position.y, position.z],
ctx,
);
if !self.creative {
self.consume_held();
}
true
}
/// `Cushion.interact`: sit down unless sneaking or already occupied.
pub(super) fn interact_cushion(&mut self) -> bool {
let Some((i, d, _)) = self.cushion_hit() else {
return false;
};
if !self.before_block(d) {
return false;
}
// isSecondaryUseActive.
if self.keys.contains(&KeyCode::ShiftLeft) {
return false;
}
let id = self.cushions[i].id;
let occupied = self.riding == Some(id)
|| self
.lan
.as_ref()
.is_some_and(|h| h.hub.guests.iter().any(|g| g.vehicle == Some(id)));
// `Cushion.interact`: an occupied cushion (`isVehicle`) passes.
if occupied {
return false;
}
// `Player.startRiding` gives up the vehicle it already has; the
// client never sends that click, so pass instead.
if self.riding.is_some() {
return false;
}
self.riding = Some(id);
let p = self.cushions[i].position;
self.audio.play(
"minecraft:entity.cushion.sit",
Some([p.x, p.y, p.z]),
1.0,
1.0,
);
self.swing_arm();
true
}
/// `Cushion.hurtServer` from a player: killed, then the item dropped.
pub(super) fn attack_cushion(&mut self) -> bool {
let Some((i, d, _)) = self.cushion_hit() else {
return false;
};
if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) {
return false;
}
// `skipAttackInteraction` when `mayInteract` is false.
if !self.may_build() {
return true;
}
self.break_cushion(i, true);
true
}
/// `Cushion.dropItem`: the break sound and particles, then the coloured
/// item unless drops are off or the breaker has infinite materials.
pub(super) fn break_cushion(&mut self, index: usize, by_player: bool) {
let c = self.cushions.remove(index);
let p = c.position;
self.world.modified.insert((c.pos[0] >> 4, c.pos[2] >> 4));
if self.riding == Some(c.id) {
self.riding = None;
}
self.audio.play(
"minecraft:entity.cushion.break",
Some([p.x, p.y, p.z]),
1.0,
1.0,
);
self.cushion_break_particles(&c);
if !self.ui.rules.bool("entity_drops") || (by_player && self.creative) {
return;
}
let stack = ItemStack {
item: std::sync::Arc::from(c.item()),
count: 1,
damage: 0,
extra: None,
};
self.spawn_item(stack, [p.x, p.y, p.z], [0.0; 3], 10);
}
/// `Cushion.showBreakingParticles`: ten of the matching wool block.
fn cushion_break_particles(&mut self, c: &Cushion) {
let name = format!("minecraft:{}_wool", c.color_name());
let Some(state) = self.pack.assets.registry.default_state(&name) else {
return;
};
let at = [
c.position.x.floor() as i32,
c.position.y.floor() as i32,
c.position.z.floor() as i32,
];
let Some((sprite, tint)) = self.particle_sprite(state, at) else {
return;
};
let options = horizon_client::particles::ParticleOptions::block(
horizon_client::particles::ParticleType::Block,
sprite,
tint,
);
let p = c.position;
self.particles.send_particles(
&options,
[p.x, p.y + 0.666_666_7, p.z],
[0.25, 0.0625, 0.25],
0.05,
10,
);
}
/// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100.
pub(super) fn tick_cushions(&mut self) {
let ticking = self.entity_ticking_area();
let mut i = 0;
while i < self.cushions.len() {
let p = self.cushions[i].position;
if !ticking(p.x.floor() as i32, p.z.floor() as i32) {
i += 1;
continue;
}
let previous = self.cushions[i].check_interval;
self.cushions[i].check_interval += 1;
if previous < 100 {
i += 1;
continue;
}
self.cushions[i].check_interval = 0;
let c = self.cushions[i].clone();
if self.cushion_in_fire(&c) || !self.cushion_survives(&c) {
self.break_cushion(i, false);
continue;
}
i += 1;
}
}
/// `Player.rideTick` on a cushion: hold the seat, and get up on sneak.
pub(super) fn tick_cushion_riding(&mut self, keys: super::Keys) -> bool {
let Some(c) = self
.cushions
.iter()
.find(|c| Some(c.id) == self.riding)
.cloned()
else {
return false;
};
if keys.shift {
let at = c.dismount();
self.riding = None;
if let Some(p) = self.player.as_mut() {
self.previous_position = p.position;
p.position = at;
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
// `Cushion.removePassenger`: the get-up sound for a rider that
// left rather than one whose cushion was killed.
self.audio.play(
"minecraft:entity.cushion.get_up",
Some([c.position.x, c.position.y, c.position.z]),
1.0,
1.0,
);
return true;
}
let seat = c.seat();
if let Some(p) = self.player.as_mut() {
self.previous_position = p.position;
p.position = seat;
p.velocity = Vec3::ZERO;
p.fall_distance = 0.0;
}
true
}
/// `CushionRenderer`: the coloured model, rotated to the nearest
/// direction, with its bottom on the cushion's position.
pub(super) fn cushion_geometry(
&self,
camera: glam::DVec3,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
let Some(model) = self.cushion_model.as_ref() else {
return;
};
let sprites = &self.gui.atlas.sprites;
for c in &self.cushions {
let entity_start = out.len();
let a = aabb(c.bounds());
let (lo, hi) = (a.min_position(), a.max_position());
let (lo, hi) = (
glam::DVec3::new(lo.x, lo.y, lo.z),
glam::DVec3::new(hi.x, hi.y, hi.z),
);
let range =
super::entity_culling::default_range(hi - lo, self.settings.entity_distance);
if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) {
continue;
}
let Some(uv) = sprites
.get(&format!("entity/cushion/{}_cushion", c.color_name()))
.map(|r| [r.u0, r.v0, r.u1, r.v1])
else {
continue;
};
let p = glam::DVec3::new(c.position.x, c.position.y, c.position.z) - camera;
let base = glam::Mat4::from_translation(p.as_vec3())
* glam::Mat4::from_rotation_y((180.0 - snap_yaw(c.yaw)).to_radians())
* glam::Mat4::from_rotation_x(std::f32::consts::PI)
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0));
// `EntityRenderer.getPackedLightCoords` probes at the eye height.
let l = self.world.light(
c.position.x.floor() as i32,
(c.position.y + 0.2125).floor() as i32,
c.position.z.floor() as i32,
);
let packed = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
horizon_client::mobs::render::draw(
model,
base,
&Poses::new(model),
uv,
0xFFFF_FFFF,
packed,
0,
out,
);
self.cull_entity_vertices(out, entity_start);
}
}
}
@@ -415,6 +415,13 @@ impl Game<'_> {
],
);
}
// Horizon's own: the shader pack's GPU time per pass (an empty group would move others).
let pass_lines = self.renderer.as_ref().map_or_else(Vec::new, |r| {
debug_overlay::shader_pass_lines(&r.shader_pass_times())
});
if !pass_lines.is_empty() {
d.group("shader pack", pass_lines);
}
// tps: DebugEntryTps for local and remote connections.
if self.player.is_some() {
let [tx, rx] = self.debug_charts.packet_rates.map(|n| n.round() as i64);
+11 -1
View File
@@ -155,6 +155,14 @@ pub(super) fn preflight(options: &mut Options) -> Result<bool> {
for w in &props.warnings {
log("WARN", w);
}
// Horizon's own commands are the owner's choice, off as on vanilla.
if props
.raw
.get(horizon_client::command::vanilla::PREGEN_PROPERTY)
.is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
{
horizon_client::command::vanilla::set_horizon_commands(true);
}
props.store(&settings)?;
let eula_file = PathBuf::from("eula.txt");
let agreed = match eula::agreed(&eula_file) {
@@ -667,7 +675,9 @@ impl Game<'_> {
self.poll_server_control(&mut state);
let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len());
if pause_after > 0 {
if players == 0 {
// A `/pregen` task keeps the server busy as a player would:
// paused, nothing would post-process its chunks.
if players == 0 && self.pregen_level().is_none() {
state.empty_ticks += 1;
} else {
state.empty_ticks = 0;
+611
View File
@@ -0,0 +1,611 @@
//! A server's dialogs bound to the game (`ClientCommonPacketListenerImpl.
//! showDialog` and `clearDialog`, `DialogScreen`, its `WarningScreen` and the
//! `WaitingForResponseScreen`): the screen over whatever is open (the
//! connecting screen in configuration), its inputs, and the actions its
//! buttons send back.
use super::Game;
use horizon_client::{
Result,
clipboard::EditShortcut,
confirm_screen::Confirm,
dialog::{AfterAction, Click, Control, Dialog, InputValue},
dialog_screen::{BOX, Layout, Part, WARNING_SPRITES, waiting_button},
hud::{HudBatch, rgba},
text::Text,
ui,
};
use horizon_world::nbt::Tag;
use std::time::Instant;
use winit::keyboard::KeyCode;
/// An open `DialogScreen`.
struct Open {
dialog: Dialog,
values: Vec<InputValue>,
/// The box of each text input.
fields: Vec<Option<ui::EditBox>>,
focus: Option<usize>,
scroll: ui::Scroll,
}
/// The dialog screens a server can open.
#[derive(Default)]
pub(super) struct DialogState {
open: Option<Open>,
/// `WaitingForResponseScreen`, since when.
waiting: Option<Instant>,
/// `DialogScreen.WarningScreen`, over the dialog.
warning: bool,
}
fn warning_texts() -> (Text, Text, [Text; 2]) {
let t = |key: &str| Text::translate(key, &[]);
(
t("menu.custom_screen_info.title"),
t("menu.custom_screen_info.contents"),
[t("menu.disconnect"), t("gui.back")],
)
}
impl Game<'_> {
/// Whether a dialog screen takes the input.
pub(super) fn dialog_open(&self) -> bool {
let d = &self.dialogs;
d.open.is_some() || d.waiting.is_some() || d.warning
}
/// `showDialog`: the dialog replaces an open one (and a waiting screen);
/// under the warning screen, it is what Back returns to.
pub(super) fn show_dialog(&mut self, tag: &Tag) {
let Some(dialog) = Dialog::parse(tag) else {
log::warn!("Horizon: failed to show dialog for data {tag:?}");
return;
};
let values = dialog.inputs.iter().map(|i| i.control.initial()).collect();
let fields = dialog
.inputs
.iter()
.map(|i| match &i.control {
Control::Text {
width,
initial,
max_length,
..
} => {
let mut edit = ui::EditBox::new(0.0, 0.0, *width as f32, 20.0);
edit.max_length = (*max_length).max(1) as usize;
edit.set_value(initial);
edit.focused = false;
Some(edit)
}
_ => None,
})
.collect();
self.dialogs.open = Some(Open {
dialog,
values,
fields,
focus: None,
scroll: ui::Scroll::default(),
});
self.dialogs.waiting = None;
self.capture(false);
}
/// `clearDialog`: the dialog closes (under the warning screen, Back then
/// returns to what was open before it).
pub(super) fn clear_dialog(&mut self) {
if self.dialogs.open.take().is_some() && !self.dialog_open() {
self.dialog_closed();
}
}
/// Every dialog screen goes (a disconnect, or the level loading screen).
pub(super) fn close_dialogs(&mut self) {
self.dialogs = DialogState::default();
}
fn dialog_closed(&mut self) {
if self.player.is_some() && self.screen == super::Screen::Playing && self.title.is_none() {
self.capture(true);
}
}
/// The input values as the controls hold them now.
fn dialog_values(open: &mut Open) {
for (value, field) in open.values.iter_mut().zip(&open.fields) {
if let Some(f) = field {
*value = InputValue::Text(f.value.clone());
}
}
}
/// `DialogScreen.runAction`: the click event, then the screen the dialog's
/// `after_action` leaves.
fn run_dialog_action(&mut self, click: Option<Click>, after: AfterAction) -> Result<()> {
match after {
AfterAction::None => {}
AfterAction::Close => self.dialogs.open = None,
AfterAction::WaitForResponse => {
self.dialogs.open = None;
self.dialogs.waiting = Some(Instant::now());
}
}
match click {
Some(Click::Custom { id, payload }) => {
if let Some(r) = &self.remote {
r.session.send_custom_click(&id, payload);
}
}
Some(Click::RunCommand(command)) => {
// In configuration there is nothing to run it (vanilla warns).
if self.player.is_some() {
let command = command.strip_prefix('/').unwrap_or(&command);
self.send_chat(&format!("/{command}"));
} else {
log::warn!(
"Horizon: commands are not supported in configuration, trying to run '{command}'"
);
}
}
Some(Click::ShowDialog(dialog)) => self.show_dialog_ref(&dialog),
Some(Click::CopyToClipboard(value)) => {
use horizon_client::clipboard::Clipboard;
self.clipboard.set(&value);
}
Some(other) => log::info!("Horizon: dialog action {other:?} is not supported yet"),
None => {}
}
if !self.dialog_open() {
self.dialog_closed();
}
Ok(())
}
/// A `show_dialog` click event's dialog: a registry id or the dialog itself.
fn show_dialog_ref(&mut self, dialog: &Tag) {
match dialog {
Tag::String(id) => {
let id = id.to_string_lossy();
let name = if id.contains(':') {
id.clone()
} else {
format!("minecraft:{id}")
};
let found = self.remote.as_ref().and_then(|r| {
let entries = r.registries.registries.get("minecraft:dialog")?;
entries.iter().find(|(n, _)| *n == name)?.1.clone()
});
match found {
Some(tag) => self.show_dialog(&tag),
None => log::warn!("Horizon: unknown dialog {id}"),
}
}
tag => self.show_dialog(tag),
}
}
/// `ClientboundShowDialogPacket` in play: a registry entry or the dialog.
pub(super) fn show_play_dialog(
&mut self,
dialog: &horizon_protocol::packets::play::DialogHolder,
) {
use horizon_protocol::packets::play::DialogHolder;
match dialog {
DialogHolder::Direct(tag) => self.show_dialog(tag),
DialogHolder::Registry(id) => {
let tag = self
.remote
.as_ref()
.and_then(|r| r.registries.data("minecraft:dialog", *id).cloned());
match tag {
Some(tag) => self.show_dialog(&tag),
None => log::warn!("Horizon: unknown dialog {id}"),
}
}
}
}
fn dialog_layout(&self) -> Option<Layout> {
let open = self.dialogs.open.as_ref()?;
Some(Layout::new(
&open.dialog,
&self.gui.atlas.font,
self.gui_size(),
))
}
pub(super) fn draw_dialog(&mut self, batch: &mut HudBatch) {
if !self.dialog_open() {
return;
}
let (w, h) = (batch.width, batch.height);
let cursor = self.cursor;
let atlas = &self.gui.atlas;
if self.player.is_none() {
// In place of the connecting screen, on its background.
batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255));
}
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.player.is_some());
if self.dialogs.warning {
let (title, message, [disconnect, back]) = warning_texts();
Confirm::new(&atlas.font, (w, h), &title, &message).draw(
batch,
atlas,
cursor,
[&disconnect, &back],
);
return;
}
if let Some(since) = self.dialogs.waiting {
// HeaderAndFooterLayout(33, 0) centred: the title, the button 33 below.
let ticks = (since.elapsed().as_millis() / 50) as u32;
let (label, visible, active) = waiting_button(ticks);
let title = Text::translate("gui.waitingForResponse.title", &[]);
let top = ((h - 53.0) / 2.0).trunc();
let tw = atlas.font.width_text(&title);
batch.text_styled(
atlas,
&title,
((w - tw) / 2.0).trunc(),
top + 12.0,
u32::MAX,
true,
);
if visible {
let (bx, by) = (((w - 200.0) / 2.0).trunc(), top + 33.0);
let hover = ui::hovered(cursor, bx, by, 200.0, 20.0);
ui::button(batch, atlas, bx, by, 200.0, 20.0, &label, active, hover);
}
return;
}
let Some(layout) = self.dialog_layout() else {
return;
};
let Some(open) = self.dialogs.open.as_mut() else {
return;
};
let atlas = &self.gui.atlas;
let [ax, ay, aw, ah] = layout.area;
open.scroll.clamp(ay, ay + ah, layout.content);
batch.text_styled(
atlas,
&open.dialog.title,
layout.title.0,
layout.title.1,
u32::MAX,
true,
);
let [wx, wy, ww, wh] = layout.warning;
let warn_hover = ui::hovered(cursor, wx, wy, ww, wh);
horizon_client::widgets::record("warning", layout.warning, true);
batch.sprite_scaled(
atlas,
WARNING_SPRITES[if warn_hover { 2 } else { 0 }],
wx,
wy,
ww,
wh,
u32::MAX,
);
let buttons = open.dialog.buttons();
let in_area = |y: f32| y >= ay && y < ay + ah;
let mut tooltip = None;
let mut start = None;
for (part, clipped) in layout.placed(open.scroll.amount) {
if clipped && start.is_none() {
start = Some(batch.vertices.len());
} else if !clipped && let Some(s) = start.take() {
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
}
match part {
Part::Line(text, x, y) => {
batch.text_styled(atlas, &text, x, y, u32::MAX, true);
}
Part::Field { input, rect } => {
if let Some(Some(edit)) = open.fields.get_mut(input) {
[edit.x, edit.y, edit.width, edit.height] = rect;
edit.focused = open.focus == Some(input);
edit.draw(batch, atlas, None);
}
}
Part::Check { input, rect } => {
let [x, y, cw, ch] = rect;
let hover = in_area(cursor.1) && ui::hovered(cursor, x, y, cw, ch);
let on = open.values.get(input) == Some(&InputValue::Bool(true));
let sprite = match (on, hover) {
(true, true) => "gui/sprites/widget/checkbox_selected_highlighted",
(true, false) => "gui/sprites/widget/checkbox_selected",
(false, true) => "gui/sprites/widget/checkbox_highlighted",
(false, false) => "gui/sprites/widget/checkbox",
};
let Control::Boolean { label, .. } = &open.dialog.inputs[input].control else {
continue;
};
horizon_client::widgets::record(&label.plain(), rect, true);
batch.sprite_scaled(atlas, sprite, x, y, BOX, BOX, u32::MAX);
batch.text_styled(
atlas,
label,
x + BOX + 4.0,
y + 4.0,
rgba(224, 224, 224, 255),
true,
);
}
Part::Button { index, rect } => {
let [x, y, bw, bh] = rect;
let hover =
(!clipped || in_area(cursor.1)) && ui::hovered(cursor, x, y, bw, bh);
let b = buttons[index];
ui::button(batch, atlas, x, y, bw, bh, &b.label, true, hover);
if hover && let Some(t) = &b.tooltip {
tooltip = Some(t.clone());
}
}
}
}
if let Some(s) = start {
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
}
if layout.content > ah {
ui::scrollbar(
batch,
atlas,
ax + aw - 6.0,
ay,
ay + ah,
layout.content,
open.scroll.amount,
);
}
if warn_hover {
tooltip = Some(Text::translate("menu.custom_screen_info.tooltip", &[]));
}
if let Some(t) = tooltip {
let lines: Vec<Text> = atlas
.font
.split_lines(&t, 170.0)
.into_iter()
.map(|l| l.0)
.collect();
ui::tooltip(batch, atlas, &lines, cursor);
}
}
/// A left click on a dialog screen.
pub(super) fn dialog_click(&mut self) -> Result<()> {
let cursor = self.cursor;
if self.dialogs.warning {
let (title, message, _) = warning_texts();
let answer = Confirm::new(&self.gui.atlas.font, self.gui_size(), &title, &message)
.answer_at(cursor);
match answer {
Some(true) => {
self.audio.play_button_click();
let reason = Text::translate("menu.custom_screen_info.disconnect", &[]);
return self.leave_server(Some(reason.plain()));
}
Some(false) => {
self.audio.play_button_click();
self.dialogs.warning = false;
if !self.dialog_open() {
self.dialog_closed();
}
}
None => {}
}
return Ok(());
}
if let Some(since) = self.dialogs.waiting {
let (w, h) = self.gui_size();
let active = waiting_button((since.elapsed().as_millis() / 50) as u32).2;
let (bx, by) = (
((w - 200.0) / 2.0).trunc(),
((h - 53.0) / 2.0).trunc() + 33.0,
);
if active && ui::hovered(cursor, bx, by, 200.0, 20.0) {
self.audio.play_button_click();
self.dialogs.waiting = None;
self.dialog_closed();
}
return Ok(());
}
let Some(layout) = self.dialog_layout() else {
return Ok(());
};
let [wx, wy, ww, wh] = layout.warning;
if ui::hovered(cursor, wx, wy, ww, wh) {
self.audio.play_button_click();
self.dialogs.warning = true;
return Ok(());
}
let Some(open) = self.dialogs.open.as_mut() else {
return Ok(());
};
let [_, ay, _, ah] = layout.area;
let mut action = None;
open.focus = None;
for (part, clipped) in layout.placed(open.scroll.amount) {
if clipped && !(cursor.1 >= ay && cursor.1 < ay + ah) {
continue;
}
match part {
Part::Field {
input,
rect: [x, y, w, h],
} if ui::hovered(cursor, x, y, w, h) => {
open.focus = Some(input);
if let Some(Some(edit)) = open.fields.get_mut(input) {
edit.focused = true;
edit.click(&self.gui.atlas, cursor.0, false, false);
}
}
Part::Check {
input,
rect: [x, y, w, h],
} if ui::hovered(cursor, x, y, w, h) => {
if let Some(InputValue::Bool(b)) = open.values.get_mut(input) {
*b = !*b;
}
action = Some(None);
}
Part::Button {
index,
rect: [x, y, w, h],
} if ui::hovered(cursor, x, y, w, h) => {
action = Some(Some(index));
}
_ => {}
}
}
let Some(action) = action else {
return Ok(());
};
self.audio.play_button_click();
let Some(index) = action else {
return Ok(());
};
let Some(open) = self.dialogs.open.as_mut() else {
return Ok(());
};
Self::dialog_values(open);
let d = &open.dialog;
let click = d.buttons()[index]
.action
.as_ref()
.and_then(|a| a.click(&d.inputs, &open.values));
let after = d.after_action;
self.run_dialog_action(click, after)
}
/// The mouse wheel over a dialog: its body scrolls 10 a step.
pub(super) fn dialog_scroll(&mut self, delta: f32) {
let Some(layout) = self.dialog_layout() else {
return;
};
if let Some(open) = self.dialogs.open.as_mut() {
let [_, ay, _, ah] = layout.area;
open.scroll.wheel(delta, 10.0, ay, ay + ah, layout.content);
}
}
/// A key pressed on a dialog screen: Escape closes what allows it, Tab
/// moves between the text inputs, the rest goes to the focused one
/// (`shortcut`: the press as an edit shortcut; `text`: what it types).
pub(super) fn dialog_key(
&mut self,
key: KeyCode,
shortcut: Option<EditShortcut>,
text: Option<&str>,
) -> Result<()> {
let escape = key == KeyCode::Escape;
if self.dialogs.warning {
if escape {
self.dialogs.warning = false;
if !self.dialog_open() {
self.dialog_closed();
}
}
return Ok(());
}
if let Some(since) = self.dialogs.waiting {
// shouldCloseOnEsc: once Back works.
if escape && waiting_button((since.elapsed().as_millis() / 50) as u32).2 {
self.dialogs.waiting = None;
self.dialog_closed();
}
return Ok(());
}
let ctrl = self.modifiers.control_key() || self.modifiers.super_key();
let shift = self.modifiers.shift_key();
let Some(open) = self.dialogs.open.as_mut() else {
return Ok(());
};
if escape {
if !open.dialog.can_close_with_escape {
return Ok(());
}
// onClose: the cancel action, and the screen closes.
Self::dialog_values(open);
let d = &open.dialog;
let click = d.on_cancel().and_then(|a| a.click(&d.inputs, &open.values));
return self.run_dialog_action(click, AfterAction::Close);
}
if key == KeyCode::Tab {
let texts: Vec<usize> = (0..open.fields.len())
.filter(|&i| open.fields[i].is_some())
.collect();
if !texts.is_empty() {
let at = open.focus.and_then(|f| texts.iter().position(|&i| i == f));
let next = match at {
None if shift => texts.len() - 1,
None => 0,
Some(p) if shift => (p + texts.len() - 1) % texts.len(),
Some(p) => (p + 1) % texts.len(),
};
open.focus = Some(texts[next]);
}
return Ok(());
}
let Some(Some(edit)) = open.focus.and_then(|f| open.fields.get_mut(f)) else {
return Ok(());
};
if let Some(shortcut) = shortcut {
edit.shortcut(shortcut, &mut self.clipboard);
return Ok(());
}
if edit.key(key, ctrl, shift) {
return Ok(());
}
let typed: String = text
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.collect();
if !typed.is_empty() {
edit.insert_text(&typed);
}
Ok(())
}
/// `type TEXT` with a dialog open: into the focused text input, or the
/// first one.
pub(super) fn dialog_type(&mut self, text: &str) -> bool {
let Some(open) = self.dialogs.open.as_mut() else {
return false;
};
let focus = open
.focus
.or_else(|| open.fields.iter().position(Option::is_some));
let Some(Some(edit)) = focus.and_then(|f| open.fields.get_mut(f)) else {
return false;
};
open.focus = focus;
edit.insert_text(text);
true
}
/// What `state` reports: the open dialog and its values, or the waiting
/// and warning screens.
pub(super) fn dialog_status(&self) -> serde_json::Value {
let d = &self.dialogs;
let screen = if d.warning {
Some("warning")
} else if d.waiting.is_some() {
Some("waiting_for_response")
} else {
None
};
let open = d.open.as_ref().map(|open| {
let mut values = open.values.clone();
for (value, field) in values.iter_mut().zip(&open.fields) {
if let Some(f) = field {
*value = InputValue::Text(f.value.clone());
}
}
open.dialog.json(&values)
});
serde_json::json!({ "open": open, "screen": screen })
}
}
@@ -90,6 +90,10 @@ enum Target {
impl Game<'_> {
/// Run every case of `spec` ("CASES,OUTPUT") and write the results.
pub(super) fn dispense_fixture(&mut self, spec: &str) -> Result<()> {
assert!(
!self.options.execution_role.is_client(),
"fixture requires a server Game"
);
let (input, output) = spec
.split_once(',')
.ok_or("HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT")?;
+219 -25
View File
@@ -12,11 +12,13 @@ use horizon_client::{
hud_layout, hud_overlays,
mesher::Vertex,
particles::{ParticleOptions, ParticleType},
text::Text,
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
use horizon_protocol::entity_data::Value;
use horizon_world::nbt::Tag;
/// Mob ids from here on are dragon parts (`SPECIAL + part`) and crystals
@@ -1691,25 +1693,8 @@ impl Game<'_> {
}
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
let p = d.position;
d.nearest_crystal = self
.crystals
.iter()
.enumerate()
.filter(|(_, c)| {
(c.position.x - p.x).abs() <= 32.0
&& (c.position.y - p.y).abs() <= 32.0
&& (c.position.z - p.z).abs() <= 32.0
})
.min_by(|a, b| {
let da = (a.1.position.x - p.x).powi(2)
+ (a.1.position.y - p.y).powi(2)
+ (a.1.position.z - p.z).powi(2);
let db = (b.1.position.x - p.x).powi(2)
+ (b.1.position.y - p.y).powi(2)
+ (b.1.position.z - p.z).powi(2);
da.total_cmp(&db)
})
.map(|(i, _)| i);
let nearest = self.nearest_crystal_to(p);
self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
}
let d = self.dragon.as_mut().expect("dragon");
d.yaw = wrap(d.yaw);
@@ -1870,7 +1855,7 @@ impl Game<'_> {
pl.velocity.z += zd / dd * 4.0;
}
if !sitting {
g.hurt_player_by("minecraft:mob_attack", 5.0);
g.dragon_hurts_player("minecraft:mob_attack", 5.0);
}
});
}
@@ -1879,7 +1864,7 @@ impl Game<'_> {
for h in heads {
if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(p.bounds) {
self.as_fight_player(p.who, |g| {
g.hurt_player_by("minecraft:mob_attack", 10.0);
g.dragon_hurts_player("minecraft:mob_attack", 10.0);
});
}
}
@@ -1971,9 +1956,10 @@ impl Game<'_> {
self.spawn_orbs([p.x, p.y, p.z], (xp as f32 * 0.08) as u32);
}
if t == 1 {
// Level event 1028: the death roar, heard everywhere.
self.audio
.play("minecraft:entity.ender_dragon.death", None, 5.0, 1.0);
// EnderDragon.tickDeath: global level event 1028, the death
// roar, heard everywhere.
let at = [p.x, p.y, p.z].map(|v| v.floor() as i32);
self.global_level_event(1028, at, 0);
}
if let Some(d) = self.dragon.as_mut() {
d.position.y += 0.1;
@@ -2160,10 +2146,20 @@ impl Game<'_> {
self.breath_clouds.append(&mut clouds);
for (who, amount) in harmed {
self.as_fight_player(who, |g| {
g.hurt_player_by("minecraft:indirect_magic", amount);
g.dragon_hurts_player("minecraft:indirect_magic", amount);
});
}
}
/// Damage from the dragon, which is its causing entity
/// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the
/// death message names it.
fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) {
if let Some(id) = self.dragon.as_ref().map(|d| d.id) {
let name = Text::translate("entity.minecraft.ender_dragon", &[]);
self.note_named_attacker(damage_type, id, name);
}
self.hurt_player_by(damage_type, amount);
}
/// `BossHealthOverlay.extractRenderState`: whatever `publish_boss_bars`
/// (or a server's packets) put on this client's overlay.
pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) {
@@ -3131,6 +3127,204 @@ impl Game<'_> {
let _ = self.activate_exit_portal();
self.fight.dirty = true;
}
/// `EnderDragon.checkCrystals`' search: the nearest crystal within 32
/// blocks on each axis.
fn nearest_crystal_to(&self, p: Vec3) -> Option<usize> {
self.crystals
.iter()
.enumerate()
.filter(|(_, c)| {
(c.position.x - p.x).abs() <= 32.0
&& (c.position.y - p.y).abs() <= 32.0
&& (c.position.z - p.z).abs() <= 32.0
})
.min_by(|a, b| {
let da = (a.1.position.x - p.x).powi(2)
+ (a.1.position.y - p.y).powi(2)
+ (a.1.position.z - p.z).powi(2);
let db = (b.1.position.x - p.x).powi(2)
+ (b.1.position.y - p.y).powi(2)
+ (b.1.position.z - p.z).powi(2);
da.total_cmp(&db)
})
.map(|(i, _)| i)
}
}
/// The dragon on a server's client (`ClientPacketListener.handleAddEntity`
/// and the client side of `EnderDragon.aiStep`): the server flies it and
/// sends its moves, health and phase; the client flaps its wings, keeps
/// its flight history and places its parts, so it can be drawn and hit.
impl Game<'_> {
/// `handleAddEntity` for `minecraft:ender_dragon`. Its constructor
/// sets the full health and the hovering phase until the server's
/// synched data says otherwise.
pub(super) fn spawn_remote_dragon(&mut self, id: i32, position: [f64; 3], yaw: f32) {
let at = Vec3::new(position[0], position[1], position[2]);
let mut d = Dragon::new(at, yaw, i64::from(id));
d.id = id as u32;
d.phase = Phase::from_id(10);
self.dragon = Some(d);
self.place_dragon_parts();
if let Some(d) = self.dragon.as_mut() {
for part in &mut d.parts {
part.1 = part.0;
}
}
}
/// The remote dragon, if `id` is it.
fn remote_dragon_mut(&mut self, id: i32) -> Option<&mut Dragon> {
self.dragon.as_mut().filter(|d| d.id as i32 == id)
}
/// `handleSetEntityData`: LivingEntity.DATA_HEALTH_ID and
/// EnderDragon.DATA_PHASE (`onSyncedDataUpdated` sets the phase).
pub(super) fn remote_dragon_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
let Some(d) = self.remote_dragon_mut(id) else {
return;
};
for (index, _, value) in values {
match (index, value) {
(9, Value::Float(health)) => d.health = *health,
(16, Value::Int(phase)) => d.set_phase(Phase::from_id(*phase)),
_ => {}
}
}
}
/// `handleSetEntityMotion`: the velocity its wings flap by.
pub(super) fn remote_dragon_motion(&mut self, id: i32, velocity: [f64; 3]) {
if let Some(d) = self.remote_dragon_mut(id) {
d.velocity = Vec3::new(velocity[0], velocity[1], velocity[2]);
}
}
/// `handleHurtAnimation` and `handleDamageEvent`: the red flash.
pub(super) fn remote_dragon_hurt(&mut self, id: i32) {
if let Some(d) = self.remote_dragon_mut(id) {
d.hurt_time = 10;
}
}
/// `handleRemoveEntities`, or a crystal removed: the healing beam
/// keeps pointing at the same crystal.
pub(super) fn remove_remote_dragon(&mut self, id: i32) {
if self.remote_dragon_mut(id).is_some() {
self.dragon = None;
return;
}
let Some(index) = self.crystals.iter().position(|c| c.id as i32 == id) else {
return;
};
if let Some(d) = self.dragon.as_mut() {
match d.nearest_crystal {
Some(n) if n == index => d.nearest_crystal = None,
Some(n) if n > index => d.nearest_crystal = Some(n - 1),
_ => {}
}
}
}
/// One client tick of the dragon. `lerp`: the step toward its last
/// sent position and yaw (LivingEntity's interpolation), and the
/// steps left including this one.
pub(super) fn tick_remote_dragon(&mut self, lerp: Option<([f64; 3], Option<f32>, u32)>) {
let Some(d) = self.dragon.as_mut() else {
return;
};
d.previous = d.position;
d.previous_yaw = d.yaw;
d.old_flap = d.flap;
d.ticks += 1;
d.hurt_time = (d.hurt_time - 1).max(0);
for part in &mut d.parts {
part.1 = part.0;
}
if let Some((target, yaw, steps)) = lerp {
let n = f64::from(steps.max(1));
d.position = Vec3::new(
d.position.x + (target[0] - d.position.x) / n,
d.position.y + (target[1] - d.position.y) / n,
d.position.z + (target[2] - d.position.z) / n,
);
if let Some(yaw) = yaw {
d.yaw += wrap(yaw - d.yaw) / steps.max(1) as f32;
}
}
if !d.alive() {
// EnderDragon.tickDeath on a client: it rises, and bursts
// from tick 180 to 200; the server removes it.
d.death_time += 1;
let (t, p) = (d.death_time, d.position);
if (180..=200).contains(&t) {
let r = &mut d.random;
let o = [
f64::from((r.next_float() - 0.5) * 8.0),
f64::from((r.next_float() - 0.5) * 4.0),
f64::from((r.next_float() - 0.5) * 8.0),
];
self.particles.add(
&ParticleOptions::simple(ParticleType::ExplosionEmitter),
[p.x + o[0], p.y + 2.0 + o[1], p.z + o[2]],
[0.0; 3],
);
}
if let Some(d) = self.dragon.as_mut() {
d.position.y += 0.1;
for part in &mut d.parts {
part.0.y += 0.1;
}
}
return;
}
// processFlappingMovement and onFlap: its wing beats, and their sound.
let flap_was = (d.old_flap * std::f32::consts::TAU).cos();
let v = d.velocity;
let mut flap_speed = 0.2 / ((v.x.hypot(v.z) as f32) * 10.0 + 1.0);
flap_speed *= 2f32.powf(v.y as f32);
d.flap += if d.phase.sitting() { 0.1 } else { flap_speed };
let flap_now = (d.flap * std::f32::consts::TAU).cos();
let at = [d.position.x, d.position.y, d.position.z];
if flap_was <= -0.3 && flap_now >= -0.3 {
let pitch = 0.8 + self.world.random.next_float() * 0.3;
self.audio
.play("minecraft:entity.ender_dragon.flap", Some(at), 5.0, pitch);
}
let d = self.dragon.as_mut().expect("dragon");
if !d.phase.sitting() {
d.growl -= 1;
if d.growl < 0 {
d.growl = 200 + d.random.next_int_bound(200).unwrap_or(0);
let pitch = 0.8 + self.world.random.next_float() * 0.3;
self.audio
.play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch);
}
}
// checkCrystals' search runs on a client too (the healing beam).
let d = self.dragon.as_mut().expect("dragon");
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
let p = d.position;
let nearest = self.nearest_crystal_to(p);
self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
}
let d = self.dragon.as_mut().expect("dragon");
d.yaw = wrap(d.yaw);
d.record();
self.place_dragon_parts();
}
/// The dragon's parts as a server's client attacks them: the server's
/// ids for `EnderDragonPart`s follow the dragon's.
pub(super) fn remote_dragon_part_hit(
&self,
eye: [f64; 3],
dir: [f64; 3],
reach: f64,
) -> Option<(i32, f64, [f64; 3])> {
let d = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0)?;
(0..8)
.filter_map(|i| {
let b = d.part_box(i);
let p = d.parts[i].0;
super::ray_box(eye, dir, reach, b)
.map(|t| ((d.id + 1 + i as u32) as i32, t, [p.x, p.y, p.z]))
})
.min_by(|a, b| a.1.total_cmp(&b.1))
}
}
#[cfg(test)]
+60 -7
View File
@@ -129,15 +129,32 @@ impl EndState {
survive: false,
});
}
/// One tick of a server's client: `step` moves each toward where the
/// server put it.
pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) {
/// `EyeOfEnder.tick` on a server's client: it moves by its last known
/// motion; only the server steers it.
pub(super) fn step_remote_eyes(&mut self) {
for e in &mut self.eyes {
e.previous = e.position;
e.life += 1;
e.position = glam::DVec3::from_array(step(e.id, e.position.to_array()));
e.position += e.velocity;
}
}
/// A server's move: an eye has no interpolation handler, so
/// `moveOrInterpolateTo` puts it there at once. False when `id` isn't one.
pub(super) fn move_remote_eye(&mut self, id: u32, at: [f64; 3]) -> bool {
let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else {
return false;
};
e.position = glam::DVec3::from_array(at);
true
}
/// `handleSetEntityMotion` for an eye. False when `id` isn't one.
pub(super) fn remote_eye_motion(&mut self, id: u32, velocity: [f64; 3]) -> bool {
let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else {
return false;
};
e.velocity = glam::DVec3::from_array(velocity);
true
}
pub(super) fn remove_remote_eye(&mut self, id: u32) {
self.eyes.retain(|e| e.id != id);
}
@@ -316,9 +333,10 @@ impl Game<'_> {
)?;
}
}
// Global LevelEvent 1038: END_PORTAL_SPAWN.
self.audio
.play("minecraft:block.end_portal.spawn", None, 1.0, 1.0);
// EnderEyeItem.useOn: global level event 1038 (END_PORTAL_SPAWN),
// heard by every player (vanilla places it at the frame's corner
// + (1, 0, 1); only its direction matters).
self.global_level_event(1038, c, 0);
}
Ok(true)
}
@@ -1098,6 +1116,7 @@ impl Game<'_> {
/// EyeOfEnder.tick: fly, then drop (4 in 5) or shatter after 80 ticks.
fn tick_eyes(&mut self) {
let mut eyes = std::mem::take(&mut self.end.eyes);
let mut shattered = Vec::new();
eyes.retain_mut(|eye| {
eye.previous = eye.position;
let next = eye.position + eye.velocity;
@@ -1121,10 +1140,44 @@ impl Game<'_> {
extra: None,
};
self.spawn_item(stack, at, [vx, 0.2, vz], 0);
} else {
shattered.push(at.map(|v| v.floor() as i32));
}
false
});
self.end.eyes = eyes;
for pos in shattered {
self.level_event_at(2003, pos, 0);
}
}
/// `LevelEventHandler` 2003: a shattered eye's item crumbs and two rings
/// of portal particles drawn in towards it.
pub(super) fn eye_break_particles(&mut self, pos: [i32; 3]) {
let (x, y, z) = (
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
);
let crumbs = self.item_particle(&ItemStack::new("minecraft:ender_eye", 1));
for _ in 0..8 {
let r = self.particles.random();
let v = [
r.next_gaussian() * 0.15,
r.next_double() * 0.2,
r.next_gaussian() * 0.15,
];
self.particles.add(&crumbs, [x, y, z], v);
}
let portal = ParticleOptions::simple(ParticleType::Portal);
let mut angle = 0.0f64;
while angle < std::f64::consts::PI * 2.0 {
let (c, s) = (angle.cos(), angle.sin());
let at = [x + c * 5.0, y - 0.4, z + s * 5.0];
self.particles.add(&portal, at, [c * -5.0, 0.0, s * -5.0]);
self.particles.add(&portal, at, [c * -7.0, 0.0, s * -7.0]);
angle += std::f64::consts::PI / 20.0;
}
}
/// `EyeOfEnder.tick` on a client: behind each eye (a quarter of its last
@@ -15,6 +15,11 @@ fn opaque(facts: &StateFacts) -> bool {
impl Game<'_> {
pub(super) fn prepare_entity_culling(&mut self, camera: glam::DVec3) {
// Spans tell the pack's passes which entities are hidden; without them, nothing changes.
self.pack_shadow_casters = match (&self.renderer, &self.pack_ids) {
(Some(r), Some(_)) => r.pack_shadow_casters(),
_ => (false, false),
};
let at = camera.to_array().map(|v| v.floor() as i32);
self.entity_culler = (self.settings.horizon.entity_culling
// Packs can replace an opaque block's model or texture.
@@ -28,24 +33,29 @@ impl Game<'_> {
/// Use complete generated geometry so equipment, animation and custom
/// models cannot stick out of an assumed collision-sized culling box.
pub(super) fn cull_entity_vertices(&self, vertices: &mut Vec<Vertex>, start: usize) {
if let Some(culler) = &self.entity_culler {
culler.cull_vertices(vertices, start, |pos| {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !opaque(self.res.facts().get(state)) {
return false;
}
let Some(y) = pos[1].checked_sub(MIN_Y) else {
return false;
};
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
// Newly edited or not-yet-uploaded terrain is not an occluder.
self.renderer
.as_ref()
.is_some_and(|r| r.has_section(section))
&& !self.world.dirty_sections.contains(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
let Some(culler) = &self.entity_culler else {
return;
};
let hidden = culler.hidden(vertices, start, |pos| {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !opaque(self.res.facts().get(state)) {
return false;
}
let Some(y) = pos[1].checked_sub(MIN_Y) else {
return false;
};
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
// Newly edited or not-yet-uploaded terrain is not an occluder.
self.renderer
.as_ref()
.is_some_and(|r| r.has_section(section))
&& !self.world.dirty_sections.contains(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
// A shader pack's shadow pass still draws what the camera cannot see.
if hidden && !(self.pack_shadow_casters.0 && self.hide_spans_from(start, vertices.len())) {
vertices.truncate(start);
}
}
}
+59 -98
View File
@@ -1,24 +1,22 @@
//! Horizon's extras in the game (`docs/extras.md`): the zoom key and wheel,
//! clicks for the keystroke overlay, frame times for the FPS counter, the
//! minimap's tiles and image, and their HUD. Each hook does nothing while its
//! extra is off.
//! Horizon's extras in the game (`docs/extras.md`); a mod's minimap
//! (`render.set-minimap`: its tiles, image and HUD) and zoom (`render.set-zoom`) on the camera; clicks
//! and frame times for mods (`input.clicks-per-second`, `render.frame-stats`).
//! Each hook does nothing while its extra is off and no mod runs.
use super::{Dim, Game, Screen};
use horizon_client::{
extras::{Corner, Cps, FpsCounter, Zoom, fov_target, turn_scale},
extras_hud::{self, Corners, Keystrokes},
extras::{Corner, Cps, FpsCounter, fov_target},
extras_hud::{self, Corners},
hud::{HudBatch, MINIMAP_SPRITE},
keybinds,
minimap::{self, Layer, Minimap, View},
multiplayer,
reconnect::{Retry, Tracker},
title::Mode,
};
use std::time::Duration;
use winit::{event::MouseButton, keyboard::KeyCode};
use winit::event::MouseButton;
#[derive(Default)]
pub(super) struct ExtrasState {
zoom: Zoom,
fps: FpsCounter,
/// Left and right mouse buttons: held, and their clicks.
mouse: [bool; 2],
@@ -36,41 +34,16 @@ impl Game<'_> {
fn extras_now(&self) -> f64 {
self.started.elapsed().as_secs_f64()
}
fn zoom_key(&self) -> Option<KeyCode> {
let e = &self.settings.extras;
e.zoom.then(|| keybinds::key_code(&e.zoom_key)).flatten()
}
/// A key press or release. The zoom key zooms only while playing with
/// no text open; the key itself always goes on to the screen and the key
/// binds, as a vanilla key mapping's would.
pub(super) fn extras_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) {
if self.zoom_key() != Some(key) {
return;
}
let playing = self.screen == Screen::Playing
&& self.title.is_none()
&& self.sign_edit.is_none()
&& self.book.is_none();
let level = self.settings.extras.zoom_level;
self.extras.zoom.key(pressed, repeat, playing, level);
}
/// Wheel steps while playing; true when zooming took them from the hotbar.
pub(super) fn extras_scroll(&mut self, steps: f32) -> bool {
self.settings.extras.zoom && self.extras.zoom.scroll(steps)
}
/// Mouse buttons while playing, for zoom and the keystroke overlay.
/// Mouse buttons while playing, for mods' clicks.
pub(super) fn extras_mouse(&mut self, button: MouseButton, pressed: bool) {
let e = &self.settings.extras;
if e.zoom && e.zoom_key == keybinds::mouse_name(button) {
self.extras.zoom.key(pressed, false, true, e.zoom_level);
}
let i = match button {
MouseButton::Left => 0,
MouseButton::Right => 1,
_ => return,
};
self.extras.mouse[i] = pressed;
if pressed && self.settings.extras.keystrokes {
// For mods (`input.clicks-per-second`).
if pressed && self.mods.running() {
let now = self.extras_now();
self.extras.cps[i].click(now);
}
@@ -80,20 +53,32 @@ impl Game<'_> {
// Under agent control the window may lack focus without pausing.
let focused = self.focused || self.control.is_some();
let playing = self.screen == Screen::Playing && self.title.is_none() && focused;
if !playing || !self.settings.extras.zoom {
self.extras.zoom.release();
}
if !playing {
self.extras.mouse = [false; 2];
}
self.update_minimap();
if self.settings.extras.fps {
// For mods (`render.frame-stats`).
if self.mods.running() {
let now = self.extras_now();
self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0);
} else {
self.extras.fps.clear();
}
}
/// The frame counter for mods: fps, min, 1% low.
#[cfg(feature = "mods")]
pub(super) fn frame_reading(&self) -> (u32, u32, u32) {
let r = self.extras.fps.reading();
(r.fps, r.min, r.low)
}
/// Attack and use clicks in the last second, and whether each is held.
#[cfg(feature = "mods")]
pub(super) fn mouse_reading(&mut self) -> ((u32, u32), [bool; 2]) {
let now = self.extras_now();
let [l, r] = &mut self.extras.cps;
let cps = (l.per_second(now) as u32, r.per_second(now) as u32);
(cps, self.extras.mouse)
}
/// Auto-reconnect: a connection to `address` as `name` starts.
pub(super) fn extras_connecting(&mut self, address: &str, name: &str) {
self.extras.reconnect.connecting(address, name);
@@ -143,25 +128,29 @@ impl Game<'_> {
}
Ok(())
}
/// The minimap's view of the player, if it shows.
fn minimap_view(&self) -> Option<View> {
let e = &self.settings.extras;
/// The minimap a mod shows (`render.set-minimap`): its corner, its side
/// in GUI pixels and its view of the player.
fn minimap_shown(&self) -> Option<(Corner, f32, View)> {
let p = self.player.as_ref()?;
let shown = e.minimap && self.title.is_none() && !self.ui.hide_gui;
shown.then_some(View {
if self.title.is_some() || self.ui.hide_gui {
return None;
}
let m = self.mod_minimap()?;
let view = View {
x: p.position.x,
z: p.position.z,
yaw: self.yaw,
rotate: e.minimap_rotate,
blocks_per_pixel: e.minimap_zoom,
round: e.minimap_round,
})
rotate: m.rotate,
blocks_per_pixel: m.blocks_per_pixel,
round: m.round,
};
Some((m.corner, m.size, view))
}
/// Refresh the minimap's tiles within the frame budget, recompose its
/// image when the view or a tile changed, and queue the upload.
fn update_minimap(&mut self) {
let Some(view) = self.minimap_view() else {
if !self.settings.extras.minimap || self.player.is_none() {
let Some((_, _, view)) = self.minimap_shown() else {
if self.mod_minimap().is_none() || self.player.is_none() {
self.extras.minimap.clear();
self.extras.minimap_dim = None;
}
@@ -209,45 +198,43 @@ impl Game<'_> {
rgba: self.extras.minimap.image.clone(),
});
}
/// The zoom in effect (1 unless the key is held).
fn zoom_factor(&self) -> f32 {
self.extras.zoom.factor(self.scoping())
/// A mod's zoom in effect (`render.set-zoom`): (factor, smooth, turning
/// scale); none is 1.
fn zoom_now(&self) -> (f32, bool, f64) {
self.mod_zoom().map_or((1.0, true, 1.0), |z| {
(z.factor, z.smooth, f64::from(z.turn))
})
}
/// The field-of-view modifier target, divided by a smooth zoom.
pub(super) fn zoomed_fov_target(&self, vanilla: f32) -> f32 {
if self.settings.extras.zoom_smooth {
fov_target(vanilla, self.zoom_factor())
} else {
vanilla
match self.zoom_now() {
(factor, true, _) => fov_target(vanilla, factor),
_ => vanilla,
}
}
/// The field of view in degrees, divided by an instant zoom.
pub(super) fn zoomed_fov_degrees(&self, fov: f32) -> f32 {
if self.settings.extras.zoom_smooth {
fov
} else {
fov / self.zoom_factor()
match self.zoom_now() {
(factor, false, _) => fov / factor,
_ => fov,
}
}
/// Mouse turning while zoomed.
pub(super) fn zoom_turn_scale(&self) -> f64 {
turn_scale(self.zoom_factor(), self.settings.extras.zoom_sensitivity)
self.zoom_now().2
}
/// The FPS counter and keystrokes, in the HUD layer (hidden with F1 by
/// the caller). The top left corner gives way to the debug screen.
/// The minimap and mods' corner panels, in the HUD layer (hidden with F1
/// by the caller). The top left corner gives way to the debug screen.
pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) {
let e = &self.settings.extras;
let mod_panels = self.mods.has_panels();
if !e.fps && !e.keystrokes && !e.minimap && !mod_panels {
let map = self.minimap_shown();
if map.is_none() && !mod_panels {
return;
}
let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows);
let (keys_on, keys_corner, cps_on) = (e.keystrokes, e.keystrokes_corner, e.keystrokes_cps);
let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size));
let visible = |corner| !(self.debug && corner == Corner::TopLeft);
let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height());
let atlas = &self.gui.atlas;
if let Some(view) = self.minimap_view()
if let Some((map_corner, map_size, view)) = map
&& visible(map_corner)
&& !self.extras.minimap.image.is_empty()
&& let Some(image) = atlas.sprites.get(MINIMAP_SPRITE).copied()
@@ -266,32 +253,6 @@ impl Game<'_> {
};
extras_hud::draw_minimap(batch, atlas, &mut corners, &look);
}
if fps_on && visible(fps_corner) {
let reading = self.extras.fps.reading();
extras_hud::draw_fps(batch, atlas, &mut corners, fps_corner, reading, lows);
}
if keys_on && visible(keys_corner) {
let now = self.extras_now();
let cps = cps_on.then(|| {
let [l, r] = &mut self.extras.cps;
(l.per_second(now), r.per_second(now))
});
let held = |k| self.keys.contains(&k);
let label = |name| keybinds::display_name(self.settings.keys.get(name)).plain();
let k = Keystrokes {
moves: [
(held(KeyCode::KeyW), label("key.forward")),
(held(KeyCode::KeyA), label("key.left")),
(held(KeyCode::KeyS), label("key.back")),
(held(KeyCode::KeyD), label("key.right")),
],
jump: held(KeyCode::Space),
attack: self.extras.mouse[0],
use_: self.extras.mouse[1],
cps,
};
extras_hud::draw_keystrokes(batch, &self.gui.atlas, &mut corners, keys_corner, &k);
}
if mod_panels {
self.draw_mod_panels(batch, &mut corners);
}
+93 -15
View File
@@ -17,6 +17,8 @@ use horizon_core::{
random::RandomSource,
};
pub(super) const FIREWORK_EXPLODE_EVENT: i8 = 17;
pub(super) struct Rocket {
/// The entity id a server tracks it by (0 until it is tracked).
pub id: u32,
@@ -71,6 +73,18 @@ impl Rocket {
(self.position, self.velocity)
}
}
/// `damageAmount * (float)Math.sqrt((5.0 - this.distanceTo(target)) / 5.0)`
/// from the rocket at `from` to a target at `to`; `Entity.distanceTo` sums
/// the squared offsets in floats.
fn blast_damage(damage: f32, from: Vec3, to: Vec3) -> f32 {
let (x, y, z) = (
(from.x - to.x) as f32,
(from.y - to.y) as f32,
(from.z - to.z) as f32,
);
let distance = f64::from(x * x + y * y + z * z).sqrt() as f32;
damage * ((5.0 - f64::from(distance)) / 5.0).sqrt() as f32
}
pub(super) fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
// The item's default component: flight 1, no explosions.
stack
@@ -249,23 +263,34 @@ impl Game<'_> {
/// `FireworkRocketEntity.explode` and `dealExplosionDamage`.
fn explode_rocket(&mut self, r: &Rocket) {
let at = [r.position.x, r.position.y, r.position.z];
// FireworkRocketEntity.explode broadcasts before discard. Send now:
// tick_lan removes missing tracked entities before flushing effects.
if r.id != 0
&& let Some(host) = &self.lan
{
host.hub
.entity_event(r.id as i32, FIREWORK_EXPLODE_EVENT, at);
}
if !r.explosions.is_empty() {
let damage = 5.0 + r.explosions.len() as f32 * 2.0;
// The player it boosts takes the full damage, a guest as well.
if r.attached {
match r.guest {
None => self.hurt_player_by("minecraft:fireworks", damage),
Some(conn) => {
if let Some(mut host) = self.lan.take() {
self.as_guest(&mut host, conn, |g| {
g.hurt_player_by("minecraft:fireworks", damage);
});
self.lan = Some(host);
}
}
}
}
let from = r.position;
// `attachedToEntity` takes the full damage, a guest as well; every
// other player in range and in sight takes the blast.
let boosted = r.guest.filter(|_| r.attached);
if r.attached && boosted.is_none() {
self.rocket_hurt_player(damage);
} else {
self.rocket_blast_player(from, damage);
}
if let Some(conn) = boosted
&& let Some(mut host) = self.lan.take()
{
self.as_guest(&mut host, conn, |g| g.rocket_hurt_player(damage));
self.lan = Some(host);
}
// Every other player in the level (LAN guests, the players of a
// server thread), each swapped in as the player.
self.each_guest_hit_except(boosted, |g| g.rocket_blast_player(from, damage));
let hits: Vec<(u32, f32)> = {
let world = self.mob_world_base(&[]);
self.mobs
@@ -285,7 +310,7 @@ impl Game<'_> {
);
world.clear_between(from, to, false)
});
sees.then(|| (m.id, damage * ((5.0 - d2.sqrt()) / 5.0).sqrt() as f32))
sees.then(|| (m.id, blast_damage(damage, from, m.position)))
})
.collect()
};
@@ -307,6 +332,59 @@ impl Game<'_> {
self.particles
.fireworks(at, v, r.explosions.clone(), camera);
}
/// FireworkRocketEntity.handleEntityEvent: use the synchronized item data.
pub(super) fn remote_firework_explosion(&mut self, id: i32) {
let camera = self.eye_position();
if let Some(r) = self.rockets.iter().find(|r| r.id == id as u32) {
let at = [r.position.x, r.position.y, r.position.z];
let v = [r.velocity.x, r.velocity.y, r.velocity.z];
self.particles
.fireworks(at, v, r.explosions.clone(), camera.unwrap_or(at));
}
}
/// `dealExplosionDamage` on a player that is not the rocket's
/// `attachedToEntity`: within 5 blocks, when the rocket sees its feet or
/// its middle (`ClipContext.Block.COLLIDER`, no fluids).
fn rocket_blast_player(&mut self, from: Vec3, damage: f32) {
let Some(p) = self.player.as_ref() else {
return;
};
let feet = p.position;
let d2 = (feet.x - from.x).powi(2) + (feet.y - from.y).powi(2) + (feet.z - from.z).powi(2);
if d2 > 25.0 {
return;
}
let height = f64::from(p.dimensions.height);
let sees = {
let world = self.mob_world_base(&[]);
(0..2).any(|step| {
let to = Vec3::new(feet.x, feet.y + height * 0.5 * f64::from(step), feet.z);
world.clear_between(from, to, false)
})
};
if sees {
self.rocket_hurt_player(blast_damage(damage, from, feet));
}
}
/// `hurtServer` with `damageSources().fireworks`: armor absorbs it and
/// wears (`hurtArmor`); creative and spectator players are immune.
fn rocket_hurt_player(&mut self, amount: f32) {
if self.creative || self.spectator() {
return;
}
let hurt = if let Some(p) = self.player.as_mut()
&& !p.health.dead_or_dying()
&& let Some(id) = self.motion.health.damage.id("minecraft:fireworks")
{
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false)
} else {
false
};
if hurt {
self.hurt_armor(amount);
}
}
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
/// lit at the rocket's light probe.
pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
+7 -7
View File
@@ -64,14 +64,14 @@ impl Game<'_> {
});
self.view.tick(eye, target);
}
/// The player's `deathTime` while dead or dying.
fn death_time(&self) -> Option<i32> {
/// The player's `deathTime` while dead or dying: whole ticks counted by
/// `LivingEntity.tickDeath`, so `deathTime + partialTicks` in
/// `Camera.extractRenderState` rises smoothly across frames.
pub(super) fn death_time(&self) -> Option<i32> {
let p = self.player.as_ref()?;
p.health.dead_or_dying().then(|| {
self.ui
.died_at
.map_or(0, |t| (t.elapsed().as_secs_f32() * 20.0) as i32)
})
p.health
.dead_or_dying()
.then(|| self.ui.death_time.min(i32::MAX as u32) as i32)
}
/// The fluid at the camera, as `Camera.getFluidInCamera` reports it.
pub(super) fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid {
+15 -4
View File
@@ -355,12 +355,23 @@ impl Game<'_> {
* glam::DMat4::from_rotation_y(y_rot.to_radians());
let light = self.world.light(f.pos[0], f.pos[1], f.pos[2]);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
// ItemFrameRenderer.getBlockLightLevel: a glow frame's model is at least 5 bright.
let frame_light = if f.glow {
(light & 0xF0) | (light & 15).max(5)
} else {
light
};
let frame_packed =
(u32::from(frame_light >> 4) * 16) | ((u32::from(frame_light & 15) * 16) << 8);
let mut quad =
|m: &glam::DMat4, corners: [[f64; 3]; 4], uv: [[f32; 2]; 4], light: u32| {
for (c, uv) in corners.iter().zip(uv) {
let p = m.transform_point3(glam::DVec3::from_array(*c));
// The frame model is drawn with the entity shader, lit by its face normal.
let at = corners.map(|c| m.transform_point3(glam::DVec3::from_array(c)));
let n = (at[1] - at[0]).cross(at[2] - at[0]).normalize_or_zero();
let normal = [0, 1, 2].map(|k| (n[k].clamp(-1.0, 1.0) * 127.0) as i8);
for (p, uv) in at.into_iter().zip(uv) {
out.push(Vertex {
normal: [0; 4],
normal: [normal[0], normal[1], normal[2], -127],
pos: p.as_vec3().to_array(),
uv,
layer: 0,
@@ -393,7 +404,7 @@ impl Game<'_> {
]
}),
map_uv(r, *uv),
packed,
frame_packed,
);
}
}
@@ -45,7 +45,8 @@ pub(super) struct RulesScreen {
initial: GameRules,
/// IntegerRuleEntry's boxes, by rule.
numbers: Vec<(&'static str, EditBox)>,
scroll: f32,
/// RuleList's scrolling: the wheel and the held scrollbar.
scroll: ui::Scroll,
/// ConfirmScreen "Game Rule Changes" in its place.
confirm: bool,
}
@@ -120,7 +121,7 @@ impl RulesScreen {
values: rules.clone(),
initial: rules.clone(),
numbers,
scroll: 0.0,
scroll: ui::Scroll::default(),
confirm: false,
}
}
@@ -156,12 +157,17 @@ impl RulesScreen {
})
.collect()
}
fn max_scroll(rows: usize, h: f32) -> f32 {
(ROW * rows as f32 + 4.0 - (h - HEADER - FOOTER)).max(0.0)
}
/// Entry `i`'s top: 2 under the list's top, less the scroll.
fn row_top(&self, i: usize) -> f32 {
HEADER + 2.0 - self.scroll.trunc() + ROW * i as f32
HEADER + 2.0 - self.scroll.amount.trunc() + ROW * i as f32
}
/// The list's scrollbar column (AbstractSelectionList: 6 pixels right of
/// the entries) and the pixels it scrolls.
fn bar(w: f32) -> f32 {
row_left(w) + ROW_WIDTH + 6.0 + 2.0
}
fn content(&self) -> f32 {
ROW * self.rows().len() as f32 + 4.0
}
/// getEntryAtPosition: the row under the pointer, inside the list.
fn hovered(&self, rows: usize, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option<usize> {
@@ -212,10 +218,28 @@ impl RulesScreen {
/// The mouse wheel (AbstractSelectionList: half an entry a step).
pub(super) fn wheel(&mut self, delta: f32, h: f32) {
if !self.confirm {
let max = Self::max_scroll(self.rows().len(), h);
self.scroll = (self.scroll - delta * ROW / 2.0).clamp(0.0, max);
let content = self.content();
self.scroll
.wheel(delta, ROW / 2.0, HEADER, h - FOOTER, content);
}
}
/// A press on the scrollbar holds it (AbstractSelectionList.updateScrolling).
pub(super) fn press_scrollbar(&mut self, cursor: (f32, f32), (w, h): (f32, f32)) -> bool {
let content = self.content();
self.scroll
.press(cursor, Self::bar(w), HEADER, h - FOOTER, content)
}
/// The pointer moved while the scrollbar is held.
pub(super) fn drag(&mut self, y: f32, h: f32) {
if self.scroll.held() {
let content = self.content();
self.scroll.drag(y, HEADER, h - FOOTER, content);
}
}
/// The button came up: the scrollbar lets go.
pub(super) fn release(&mut self) {
self.scroll.release();
}
fn focused(&mut self) -> Option<(Option<&'static str>, &mut EditBox)> {
if self.search.focused {
return Some((None, &mut self.search));
@@ -229,7 +253,7 @@ impl RulesScreen {
/// number sets its rule when valid (IntegerRuleEntry's responder).
fn edited(&mut self, rule: Option<&'static str>) {
let Some(name) = rule else {
self.scroll = 0.0;
self.scroll.amount = 0.0;
return;
};
let Some(r) = gamerules::rule(name) else {
@@ -286,6 +310,11 @@ impl RulesScreen {
if on(cx, cy, 150.0, 20.0) {
return self.close();
}
// A press on the scrollbar holds it and clicks nothing else.
if self.press_scrollbar(cursor, size) {
self.unfocus();
return None;
}
// A click moves the focus to the widget under it.
let (sx, sy) = search_at(w);
if on(sx, sy, SEARCH_WIDTH, 15.0) {
@@ -360,7 +389,8 @@ impl RulesScreen {
return;
}
let rows = self.rows();
self.scroll = self.scroll.clamp(0.0, Self::max_scroll(rows.len(), h));
let content = ROW * rows.len() as f32 + 4.0;
self.scroll.clamp(HEADER, h - FOOTER, content);
// RuleList: the in-world list background, its entries clipped to it,
// then the separators and scrollbar.
ui::list_background(batch, atlas, HEADER, h - FOOTER, true);
@@ -421,16 +451,14 @@ impl RulesScreen {
}
batch.clip_since(first, 0.0, HEADER, w, h - FOOTER);
ui::separators(batch, atlas, HEADER, h - FOOTER, true);
let content = ROW * rows.len() as f32 + 4.0;
let bar_x = left + ROW_WIDTH + 6.0 + 2.0;
ui::scrollbar(
batch,
atlas,
bar_x,
Self::bar(w),
HEADER,
h - FOOTER,
content,
self.scroll.trunc(),
self.scroll.amount.trunc(),
);
// The header: the title centred over the search box.
let title = Text::translate("editGamerule.title", &[]);
@@ -536,6 +564,29 @@ mod tests {
);
}
/// AbstractScrollArea: a press on the bar holds it, a drag moves the
/// list (to the ends past them), a release lets go.
#[test]
fn the_scroll_bar_can_be_held_dragged_and_let_go() {
let mut s = RulesScreen::new(&GameRules::default());
let (w, h) = (427.0, 240.0);
let (top, bottom, content) = (HEADER, h - FOOTER, s.content());
assert!(
content > bottom - top,
"the rules overflow a 240-high screen"
);
let bar = RulesScreen::bar(w);
assert!(!s.press_scrollbar((bar - 4.0, top + 5.0), (w, h)));
assert!(s.press_scrollbar((bar + 3.0, top + 5.0), (w, h)));
s.drag(top + 40.0, h);
assert!(s.scroll.amount > 0.0);
s.drag(bottom + 10.0, h);
assert_eq!(s.scroll.amount, content - (bottom - top));
s.release();
s.drag(top, h);
assert_eq!(s.scroll.amount, content - (bottom - top));
}
#[test]
fn edits_change_rules_and_bad_numbers_hold_done() {
let mut s = RulesScreen::new(&GameRules::default());
+1
View File
@@ -151,6 +151,7 @@ impl Game<'_> {
before(self.painting_hit().map(|h| h.1))
|| before(self.frame_hit().map(|h| h.1))
|| before(self.armor_stand_hit().map(|h| h.1))
|| before(self.cushion_hit().map(|h| h.1))
|| before(self.boat_hit().map(|h| h.1))
|| before(self.cart_hit().map(|h| h.1))
|| before(self.dragon_hit().map(|h| h.1))
+63 -4
View File
@@ -143,7 +143,7 @@ pub(super) struct Serving {
flags: Arc<Flags>,
tasks: Receiver<Task>,
/// The window's profile.
owner: u128,
pub(super) owner: u128,
/// Open to LAN or closed from inside a player's command, while the hub
/// is out of its place: applied after the tick.
pending: Option<Publish>,
@@ -222,7 +222,6 @@ impl Game<'_> {
options.report = None;
options.server = None;
options.world = None;
options.dev_mods.clear();
self.join_world_rest()?;
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
@@ -292,6 +291,9 @@ impl Game<'_> {
launch.create.as_ref(),
)?)?;
let saved = Box::new(self.level.clone());
// IntegratedServer runs the server mods; the window the client mods.
self.mods.dev = self.options.dev_mods.clone();
self.start_mods();
// Math.max(2, options.renderDistance): past vanilla's 32 when the
// window's render distance is (Horizon's options go to 64).
let view_distance = self.settings.render_distance.max(2);
@@ -357,9 +359,25 @@ impl Game<'_> {
});
let _ = ready.send(Ok((pipe, self.level.name.clone())));
self.settle_spawn()?;
if let (Some(script), Some(output)) = (
std::env::var_os("HORIZON_COMMAND_SCRIPT"),
std::env::var_os("HORIZON_COMMAND_OUTPUT"),
) {
// The script owns the clock: connection setup and terrain loading
// cannot add wall-clock-dependent world ticks to oracle output.
let result = self.run_command_harness(script.as_ref(), output.as_ref());
let stopped = self.stop_integrated();
return result.and(stopped);
}
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.run_tasks();
if self.agent.hold_server {
// Keep servicing control requests so the fixture can release the barrier.
// Unlike /tick freeze, no player's queued packets are applied here.
self.wait_for_next_server_tick(&mut next, true);
continue;
}
let paused = flags.paused.load(Ordering::Relaxed);
if paused {
// Only the connections run.
@@ -692,6 +710,48 @@ fn serve(
tasks: Receiver<Task>,
ready: &Sender<Ready>,
) -> Result<()> {
let mut server = server_game(res, pack, options, settings)?;
server.run_integrated(launch, flags, tasks, ready)
}
/// Component oracles supply their own synthetic levels and entity phases.
/// They still execute on a server Game, never the client's world.
pub(super) enum ComponentHarness {
Dispenser(String),
Sculk(String),
}
impl Game<'_> {
pub(super) fn run_component_harness(&self, fixture: ComponentHarness) -> Result<()> {
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let mut options = self.options.clone();
options.execution_role = ExecutionRole::IntegratedServer;
options.dedicated = Some(Vec::new());
options.server_thread = false;
let result = std::thread::Builder::new()
.name("Server thread".into())
.spawn(move || {
let run = || -> Result<()> {
let mut server = server_game(&res, pack, options, settings)?;
match fixture {
ComponentHarness::Dispenser(spec) => server.dispense_fixture(&spec),
ComponentHarness::Sculk(spec) => server.sculk_fixture(&spec),
}
};
run().map_err(|e| e.to_string())
})?
.join()
.map_err(|_| "the component harness server panicked")?;
result.map_err(Into::into)
}
}
fn server_game(
res: &Arc<Resources>,
pack: PackResources,
options: Options,
settings: Settings,
) -> Result<Game<'_>> {
// It draws nothing: only the font, which books and chat measure with.
let atlas = HudAtlas::fonts(&options.resources)?;
let gui = UiResources {
@@ -702,8 +762,7 @@ fn serve(
}),
};
let audio = Audio::silent(&options.resources);
let mut server = Game::new(res, pack, gui, options, settings, audio, None)?;
server.run_integrated(launch, flags, tasks, ready)
Game::new(res, pack, gui, options, settings, audio, None)
}
#[cfg(test)]
+91 -11
View File
@@ -14,7 +14,7 @@ use horizon_client::{
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
mobs::{Mob, leash::Holder},
mobs::{Mob, Who, leash::Holder},
text::Text,
};
use horizon_core::geometry::Vec3;
@@ -71,6 +71,8 @@ pub(super) struct LanHost {
/// Guests' commands waiting for the hub to be back in `self.lan`, where
/// a command can reach every player (game/lan_actions.rs).
pub commands: Vec<super::lan_actions::GuestCommand>,
/// Mods' quiet commands waiting to run a few a tick (game/lan_quiet.rs).
pub quiet: std::collections::VecDeque<super::lan_quiet::QuietBatch>,
/// The entities the guests track, described again every tick
/// (`lan_entities`) over last tick's states.
states: lan::entity::States,
@@ -145,6 +147,7 @@ pub(super) fn baby_index(kind: &str) -> Option<u8> {
fn mob_meta(
m: &Mob,
hub: &Hub,
player_entity: Option<i32>,
meta: &mut Vec<(u8, i32, Value)>,
defaults: &mut Vec<(u8, i32, Value)>,
) {
@@ -194,6 +197,32 @@ fn mob_meta(
let e = &m.extra;
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
match kind {
"minecraft:guardian" | "minecraft:elder_guardian" => {
// Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET.
if e.flag2 {
meta.push((16, serializer::BOOLEAN, Value::Bool(true)));
}
let target = if e.flag {
m.ai.target.and_then(|who| match who {
Who::Player => player_entity,
Who::Mob(id) => Some(id as i32),
})
} else {
None
};
if let Some(target) = target {
meta.push((17, serializer::INT, Value::Int(target)));
}
defaults.push((16, serializer::BOOLEAN, Value::Bool(false)));
defaults.push((17, serializer::INT, Value::Int(0)));
}
// Bat.DATA_ID_FLAGS: resting in bit 0, flying by default.
"minecraft:bat" => {
if e.flag {
meta.push((16, serializer::BYTE, Value::Byte(1)));
}
defaults.push((16, serializer::BYTE, Value::Byte(0)));
}
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared.
"minecraft:sheep" => {
let value = (e.color & 15) | if e.sheared { 16 } else { 0 };
@@ -596,6 +625,7 @@ impl Game<'_> {
waypoint_dead: Default::default(),
border_sent: None,
commands: Vec::new(),
quiet: std::collections::VecDeque::new(),
states: Default::default(),
});
self.audio.capture = Some(Vec::new());
@@ -634,6 +664,7 @@ impl Game<'_> {
self.world.light_log = None;
self.audio.capture = None;
self.lan_events.clear();
self.lan_critical_hits.clear();
self.streaming.extra.clear();
if announce {
self.system_message(Text::translate(
@@ -820,12 +851,13 @@ impl Game<'_> {
for m in self.mobs.iter().filter(|m| !m.removed) {
// The lead's holder: the player the mob sees (a guest, else the
// host) or another mob. A fence knot isn't an entity here.
let player_entity = mob_players
.get(&m.id)
.and_then(|conn| hub.guest(*conn))
.map(|g| g.entity_id)
.or(host_entity);
let leash = m.extra.leash.and_then(|h| match h {
Holder::Player => mob_players
.get(&m.id)
.and_then(|conn| hub.guest(*conn))
.map(|g| g.entity_id)
.or(host_entity),
Holder::Player => player_entity,
Holder::Mob(id) => Some(id as i32),
Holder::Knot(_) => None,
});
@@ -835,7 +867,7 @@ impl Game<'_> {
e.on_ground = m.on_ground;
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
e.needs_sync = m.needs_sync;
mob_meta(m, hub, &mut e.meta, &mut e.defaults);
mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults);
mob_equipment(m, hub, &mut e.equipment);
self.mob_attributes(m, &mut e.attributes);
e.leash = leash;
@@ -960,6 +992,9 @@ impl Game<'_> {
event @ (HostEvent::Chat { .. } | HostEvent::Warn(_) | HostEvent::Error(_)) => {
self.lan_log_event(event);
}
HostEvent::PlayerChat { sender, text } => {
self.mod_player_chat(super::server_mods::Who::Uuid(sender), &text);
}
HostEvent::Joined(conn) => {
self.lan_guest_joined(&mut host, conn, state.as_ref(), entities, spawn);
if self.options.dedicated.is_some()
@@ -1029,6 +1064,14 @@ impl Game<'_> {
}
host.states = states;
}
if !host.quiet.is_empty() {
self.lan = Some(host);
self.run_quiet_commands();
host = self
.lan
.take()
.expect("the hub is back after the quiet commands");
}
self.lan_flush_effects(&mut host);
if !paused {
self.tick_guests(&mut host);
@@ -1136,9 +1179,9 @@ impl Game<'_> {
for e in events {
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
// The acting guest does not predict the egg's teleport
// particles, nor bone meal's growth (BoneMealItem.useOn's
// levelEvent names no player).
let except = if matches!(*id, 2015 | 1505) {
// particles, bone meal's growth, or anvil result sounds
// (these levelEvent calls name no excluded player).
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
None
} else {
self.lan_acting
@@ -1162,8 +1205,30 @@ impl Game<'_> {
self.lan_entity_events.push((id, event, at));
}
}
/// `ServerPlayer.crit`: this window's emitter, and an animation for the
/// attacker's client and observers once the hub is back in place.
pub(super) fn critical_hit(
&mut self,
attacker: Option<u32>,
id: i32,
feet: [f64; 3],
width: f64,
height: f64,
) {
use horizon_client::particles::{ParticleOptions, ParticleType};
self.particles.tracking_emitter(
ParticleOptions::simple(ParticleType::Crit),
feet,
width,
height,
);
if self.audio.capture.is_some() {
self.lan_critical_hits.push((attacker, id));
}
}
/// Send the tick's level events, sounds and mob animations.
fn lan_flush_effects(&mut self, host: &mut LanHost) {
let critical_hits = std::mem::take(&mut self.lan_critical_hits);
for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) {
if kind == 2001 {
host.broken
@@ -1177,6 +1242,9 @@ impl Game<'_> {
for (id, event, at) in std::mem::take(&mut self.lan_entity_events) {
host.hub.entity_event(id, event, at);
}
for (kind, pos, data) in std::mem::take(&mut self.lan_global_events) {
host.hub.global_level_event(kind, pos, data);
}
self.lan_broadcast_effects(host);
if host.hub.guests.is_empty() {
host.mob_state.clear();
@@ -1233,6 +1301,14 @@ impl Game<'_> {
seen.insert(m.id, (m.hurt_time, dead, swing));
}
host.mob_state.insert(self.dim, seen);
for (attacker, target) in critical_hits {
let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| {
host.hub.guest(conn).map(|g| g.entity_id)
}) else {
continue;
};
host.hub.critical_hit(attacker, target);
}
}
/// Keep the chunks around every guest loaded.
@@ -1400,7 +1476,11 @@ impl Game<'_> {
let tag = if secure { "" } else { "[Not Secure] " };
super::dedicated::log("INFO", &format!("{tag}{line}"));
}
HostEvent::Chat { line, .. } => self.system_message(Text::literal(line)),
// Player chat (and `/say`'s or `/me`'s, which are chat messages
// too): the host's Chat option decides, as `ChatListener` does
// for the guests' packets. Command feedback is a system message
// and takes the system-message permission instead.
HostEvent::Chat { line, .. } => self.player_message(Text::literal(line)),
HostEvent::Warn(line) if dedicated => super::dedicated::log("WARN", &line),
HostEvent::Warn(line) => log::warn!("{line}"),
HostEvent::Error(line) if dedicated => super::dedicated::log("ERROR", &line),
+256 -102
View File
@@ -38,6 +38,11 @@ pub(super) struct GuestPlay {
use_delay: u32,
/// The shield's ItemCooldowns entry: an axe disabled it for this many ticks.
pub(super) shield_cooldown: u32,
/// `ServerGamePacketListenerImpl.dropSpamThrottler` (`TickThrottler(20, 1480)`): 20 for each
/// item a creative player drops from the creative screen, one less each tick.
creative_drops: u32,
/// The guest's `Player.getCooldowns()` (`Game::cooldowns` for its turn).
pub(super) cooldowns: horizon_client::cooldowns::Cooldowns,
attack_ticks: u32,
/// The main hand's item at the guest's last tick (`Game::attack_item`).
attack_item: Option<std::sync::Arc<str>>,
@@ -72,6 +77,10 @@ pub(super) struct GuestPlay {
last_inventory: u64,
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
pub(super) portal: horizon_client::nether_portal::PortalState,
/// `ServerPlayer.wonGame`: the End poem is showing, the player waits for
/// its client's PERFORM_RESPAWN (`respawn_requested`).
pub(super) won_game: bool,
pub(super) respawn_requested: bool,
/// `Player.takeXpDelay`: ticks until the next orb can be taken.
xp_delay: u32,
/// What last killed the guest outright (`/kill`): the death message's key.
@@ -84,15 +93,19 @@ pub(super) struct GuestPlay {
equipped: Option<Vec<Option<ItemStack>>>,
/// The guest's cast fishing hook (`Player.fishing`).
pub(super) hook: Option<super::fishing::Hook>,
sculk: super::sculk::PlayerEvents,
}
/// A guest's command waiting for the hub (`LanHost::commands`).
pub(super) struct GuestCommand {
conn: u32,
command: String,
permission: u8,
pub(super) conn: u32,
pub(super) command: String,
pub(super) permission: u8,
/// An integrated server's: no level teleports (yet).
integrated: bool,
pub(super) integrated: bool,
/// A mod's quiet command (game/lan_quiet.rs): its output suppressed, as
/// `CommandSourceStack.withSuppressedOutput` does.
pub(super) quiet: bool,
}
/// The game's own state while a guest's is swapped in (`enter_guest`), and
@@ -125,6 +138,8 @@ pub(super) struct GuestSwap {
using: Option<(usize, u32)>,
use_delay: u32,
pub(super) shield_cooldown: u32,
/// The guest's item cooldowns (`Game::cooldowns` for its turn).
cooldowns: horizon_client::cooldowns::Cooldowns,
attack_ticks: u32,
attack_item: Option<std::sync::Arc<str>>,
swing: horizon_client::first_person::SwingState,
@@ -252,6 +267,7 @@ impl Game<'_> {
if fresh {
// A new body (joined, respawned, changed level): nothing on it yet.
play.equipped = None;
play.sculk = Default::default();
}
let g = &mut host.hub.guests[i];
// The guest's body.
@@ -259,6 +275,7 @@ impl Game<'_> {
host.play.insert(conn, play);
return None;
};
self.sculk.swap_player(&mut play.sculk);
// The guest's own CombatTracker: damage to them is not the host's.
// A new body starts with no record of the last one.
let guest_combat = if fresh {
@@ -328,6 +345,7 @@ impl Game<'_> {
let using = std::mem::replace(&mut self.using, play.using.take());
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown);
let cooldowns = std::mem::replace(&mut self.cooldowns, std::mem::take(&mut play.cooldowns));
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
let swing = std::mem::replace(&mut self.swing, play.swing);
@@ -412,6 +430,7 @@ impl Game<'_> {
using,
use_delay,
shield_cooldown,
cooldowns,
attack_ticks,
attack_item,
swing,
@@ -469,6 +488,7 @@ impl Game<'_> {
using,
use_delay,
shield_cooldown,
cooldowns,
attack_ticks,
attack_item,
swing,
@@ -492,6 +512,7 @@ impl Game<'_> {
projectiles,
modifiers,
} = swap;
self.sculk.swap_player(&mut play.sculk);
// The guest's damage record back into their slot, the host's in place.
let guest_combat = std::mem::replace(&mut self.combat, combat);
self.guest_combat.insert(conn, guest_combat);
@@ -508,6 +529,16 @@ impl Game<'_> {
for packet in std::mem::replace(&mut self.guest_packets, packets) {
host.hub.send_to(conn, &packet);
}
// ServerItemCooldowns.onCooldownStarted: the guest's own cooldown.
for (group, duration) in std::mem::take(&mut self.guest_cooldowns) {
host.hub.send_to(
conn,
&C::Cooldown(play::Cooldown {
group: group.to_string(),
duration,
}),
);
}
(self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting;
play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause);
// An ender chest the guest opened: the menu shows their inventory
@@ -537,6 +568,7 @@ impl Game<'_> {
play.using = std::mem::replace(&mut self.using, using);
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown);
play.cooldowns = std::mem::replace(&mut self.cooldowns, cooldowns);
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
play.swing = std::mem::replace(&mut self.swing, swing);
@@ -847,7 +879,11 @@ impl Game<'_> {
.filter(|g| host.hub.here(g))
.filter(|g| {
g.menu.as_ref().is_some_and(|m| {
m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos)
(m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos))
|| m.pos.is_some_and(|k| {
k.1 == super::minecarts::CART_KEY_Y
&& !self.chest_vehicle_still_valid(k.2, g)
})
})
})
.map(|g| g.conn)
@@ -861,6 +897,35 @@ impl Game<'_> {
}
}
/// `ContainerEntity.isChestVehicleStillValid`: the chest minecart or chest
/// boat is still there and within the guest's entity interaction range
/// plus 4 of its box.
fn chest_vehicle_still_valid(&self, id: i32, g: &horizon_client::lan::guest::Guest) -> bool {
let bounds = self
.carts
.iter()
.find(|c| c.id as i32 == id)
.map(|c| c.bounds())
.or_else(|| {
self.boats
.iter()
.find(|b| b.id as i32 == id)
.map(|b| b.bounds())
});
let Some(b) = bounds else {
return false;
};
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
let (lo, hi) = (b.min_position(), b.max_position());
let d = [
eye[0] - eye[0].clamp(lo.x, hi.x),
eye[1] - eye[1].clamp(lo.y, hi.y),
eye[2] - eye[2].clamp(lo.z, hi.z),
];
let range = if g.creative() { 5.0 } else { 3.0 } + 4.0;
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range
}
/// A packet from a guest that the hub does not handle itself.
pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
@@ -1064,6 +1129,35 @@ impl Game<'_> {
}
S::MoveVehicle(p) => self.guest_move_vehicle(host, conn, &p),
S::PaddleBoat(p) => self.guest_paddle_boat(host, conn, [p.left, p.right]),
// handleSetCreativeModeSlot's drop: a slot below 0 is a stack thrown out of the
// creative screen (`handleCreativeModeItemDrop`), dropped from the player's hand.
S::SetCreativeModeSlot(p) if p.slot < 0 => {
if !host.hub.guests[gi].creative() {
return;
}
let Some(stack) = self.item_from_network(host, &p.item) else {
return;
};
if stack.count
> self
.res
.items()
.get(&stack.item)
.map_or(64, |i| i.max_stack)
{
return;
}
let play = host.play.entry(conn).or_default();
if play.creative_drops >= 1480 {
eprintln!(
"Player {} was dropping items too fast in creative mode, ignoring.",
host.hub.guests[gi].name
);
return;
}
play.creative_drops += 20;
self.as_guest(host, conn, |g| g.player_drop(stack));
}
S::SetCreativeModeSlot(p) => {
let g = &mut host.hub.guests[gi];
if !g.creative() || !(0..46).contains(&p.slot) {
@@ -1138,6 +1232,10 @@ impl Game<'_> {
{
self.container_changed(key);
}
// A vehicle's menu edits the vehicle's own items.
if let Some(Slots::Block(key)) = slots {
self.store_cart_items(key);
}
self.drop_guest_items(host, gi, drops);
}
S::ContainerClose(p) => {
@@ -1152,6 +1250,9 @@ impl Game<'_> {
self.guest_carried_back(host, gi);
}
S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command),
S::CustomPayload(p) if p.channel == horizon_protocol::quiet::CHANNEL => {
self.guest_quiet_commands(host, conn, &p.data)
}
S::ChatCommandSigned(p) => self.guest_signed_command(host, conn, p),
S::ChangeDifficulty(p) if host.hub.guests[gi].permission >= 2 => {
if !self.level.difficulty_locked && (0..=3).contains(&p.difficulty) {
@@ -1250,6 +1351,13 @@ impl Game<'_> {
self.guest_suggestions(host, conn, &payload);
}
S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p),
// handleClientCommand: PERFORM_RESPAWN after the poem leaves the End
// (the next server tick sends the player on).
S::ClientCommand(c)
if c.action == 0 && host.play.get(&conn).is_some_and(|p| p.won_game) =>
{
host.play.entry(conn).or_default().respawn_requested = true;
}
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
// ServerStatsCounter.sendStats.
S::ClientCommand(c) if c.action == 1 => {
@@ -1475,6 +1583,10 @@ impl Game<'_> {
);
return;
}
// A server mod's command, for every player whatever their level.
if self.guest_server_mod_command(host, conn, command.trim_start_matches('/')) {
return;
}
// An integrated server runs every player's commands at their own
// permission level (`CommandSourceStack.permissions`); a LAN world
// follows its Allow Commands, and a dedicated server leaves it to
@@ -1501,6 +1613,7 @@ impl Game<'_> {
command: command.trim_start_matches('/').to_owned(),
permission,
integrated,
quiet: false,
});
}
@@ -1515,41 +1628,54 @@ impl Game<'_> {
return;
}
let c = host.commands.remove(0);
let mut host = self.lan.take().expect("checked above");
let Some(swap) = self.enter_guest(&mut host, c.conn) else {
self.lan = Some(host);
continue;
};
self.lan = Some(host);
self.chat_capture = Some(Vec::new());
let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
self.run_command(&c.command);
self.ui.registries.permission = level;
let lines = self.chat_capture.take().unwrap_or_default();
let mut host = self.lan.take().expect("a command puts the hub back");
self.leave_guest(&mut host, swap);
host.hub.sync_all_effects();
if !c.integrated {
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(&mut host);
}
// What the command earned is announced before its feedback.
self.announce_guest_advancements(&mut host);
for line in lines {
host.hub.send_to(
c.conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
// The other operators hear of it; never the player whose command it was.
self.send_admin_feedback(&mut host, Some(c.conn));
self.lan = Some(host);
self.run_guest_command(c);
}
}
/// One guest's command as that guest, its feedback sent to them; false
/// when it failed (or the guest is gone).
pub(super) fn run_guest_command(&mut self, c: GuestCommand) -> bool {
let Some(mut host) = self.lan.take() else {
return false;
};
let Some(swap) = self.enter_guest(&mut host, c.conn) else {
self.lan = Some(host);
return false;
};
self.lan = Some(host);
self.chat_capture = Some(Vec::new());
let level = std::mem::replace(&mut self.ui.registries.permission, c.permission);
let ok = if c.quiet {
self.run_command_quietly(&c.command)
} else {
self.run_command(&c.command)
};
self.ui.registries.permission = level;
let lines = self.chat_capture.take().unwrap_or_default();
let mut host = self.lan.take().expect("a command puts the hub back");
self.leave_guest(&mut host, swap);
host.hub.sync_all_effects();
if !c.integrated {
// A teleport into another level happens before its feedback is sent.
self.run_level_teleports(&mut host);
}
// What the command earned is announced before its feedback.
self.announce_guest_advancements(&mut host);
for line in lines {
host.hub.send_to(
c.conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
// The other operators hear of it; never the player whose command it was.
self.send_admin_feedback(&mut host, Some(c.conn));
self.lan = Some(host);
ok
}
/// The `broadcastToAdmins` lines a command queued (`source`: the guest
/// whose it was; none for the host's or the console's): every other
/// operator gets them, and the console logs them as the server's own
@@ -1777,12 +1903,28 @@ impl Game<'_> {
continue;
}
if self.on_server_trip(conn) {
// LivingEntity.hurt kills at once (die), whether the level
// has loaded around the player or not: its respawn request
// is taken as soon as it comes.
self.guest_die(host, gi, conn);
continue;
}
let play = host.play.entry(conn).or_default();
// Player.tick's ItemCooldowns.tick, once a tick for each player
// (the shield an axe disabled).
// (the shield an axe disabled, a thrown pearl).
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
play.creative_drops = play.creative_drops.saturating_sub(1);
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
// the guest (a duration of 0 removes it).
for group in play.cooldowns.tick() {
host.hub.send_to(
conn,
&C::Cooldown(play::Cooldown {
group: group.to_string(),
duration: 0,
}),
);
}
let digging = play.digging;
let using = play.using.is_some();
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
@@ -1808,14 +1950,13 @@ impl Game<'_> {
g.use_delay -= 1;
}
});
// ServerPlayerGameMode.handleBlockBreakAction: a creative
// player's START breaks the block once (destroyAndAck) and
// leaves nothing being destroyed; its client sends no STOP.
// Kept, the dig broke whatever was put there next, every
// destroy delay, for as long as the player broke nothing else.
// ServerPlayerGameMode.handleBlockBreakAction: creative and
// instant survival STARTs finish without a STOP from the client.
// tick_mining clears mining on completion; forget the START too,
// so a flower or crop planted here later is not broken again.
if digging.is_some()
&& host.hub.guests[gi].creative()
&& let Some(play) = host.play.get_mut(&conn)
&& (host.hub.guests[gi].creative() || play.mining.is_none())
{
play.digging = None;
}
@@ -1851,69 +1992,72 @@ impl Game<'_> {
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
self.guest_orbs(host, gi);
if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead {
self.guest_forget_digging(host, conn);
// FishingHook.shouldStopFishing: its owner is dead.
if let Some(play) = host.play.get_mut(&conn) {
play.hook = None;
}
self.guest_die(host, gi, conn);
}
}
/// `ServerPlayer.die` for a guest whose health has run out: the death
/// message, the loot and experience, the death screen.
fn guest_die(&mut self, host: &mut LanHost, gi: usize, conn: u32) {
if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead {
self.guest_forget_digging(host, conn);
// FishingHook.shouldStopFishing: its owner is dead.
if let Some(play) = host.play.get_mut(&conn) {
play.hook = None;
}
let g = &mut host.hub.guests[gi];
if g.health <= 0.0 && !g.dead {
g.dead = true;
g.last_death = Some(g.position.map(|v| v.floor() as i32));
let (id, at) = (g.entity_id, g.position);
let reward = Experience {
level: g.xp_level,
progress: g.xp_progress,
total: g.xp_total,
}
.death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR);
let (name, uuid) = (g.name.clone(), g.uuid);
// ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3.
let drops = (g.game_mode != SPECTATOR)
.then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]);
let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take());
// ServerPlayer.die: with showDeathMessages, the message goes to
// the dying player's death screen and to everyone the team lets
// see it; without it, the death screen gets an empty one.
let message = if self.ui.rules.bool("show_death_messages") {
let me = self.player_text(&name, uuid);
let text = match cause {
Some(key) => horizon_client::text::Text::translate(&key, &[me]),
None if at[1] < f64::from(horizon_client::chunk::MIN_Y - 64) => {
horizon_client::text::Text::translate("death.attack.outOfWorld", &[me])
}
None => self.guest_death_message(conn, me),
};
let message = horizon_client::lan::data::component_nbt(&text.component());
let team = self.score.board.players_team(&name);
if horizon_client::scoreboard::own_death_message_shown(team) {
host.hub.system_message(message.clone());
if self.options.dedicated.is_some() {
super::dedicated::log(
"INFO",
&format!("System chat: {}", text.plain()),
);
} else if self.player.is_some() {
self.system_message(text);
}
}
let g = &mut host.hub.guests[gi];
if g.health <= 0.0 && !g.dead {
g.dead = true;
g.last_death = Some(g.position.map(|v| v.floor() as i32));
let (id, at) = (g.entity_id, g.position);
let reward = Experience {
level: g.xp_level,
progress: g.xp_progress,
total: g.xp_total,
}
.death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR);
let (name, uuid) = (g.name.clone(), g.uuid);
// ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3.
let drops =
(g.game_mode != SPECTATOR).then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]);
let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take());
// ServerPlayer.die: with showDeathMessages, the message goes to
// the dying player's death screen and to everyone the team lets
// see it; without it, the death screen gets an empty one.
let message = if self.ui.rules.bool("show_death_messages") {
let me = self.player_text(&name, uuid);
let text = match cause {
Some(key) => horizon_client::text::Text::translate(&key, &[me]),
None if at[1] < f64::from(horizon_client::chunk::MIN_Y - 64) => {
horizon_client::text::Text::translate("death.attack.outOfWorld", &[me])
}
message
} else {
literal("")
None => self.guest_death_message(conn, me),
};
host.hub.send_to(
conn,
&C::PlayerCombatKill(play::PlayerCombatKill { id, message }),
);
// LivingEntity.die: the death animation, the dying player included.
host.hub.entity_event(id, 3, at);
if let Some(eyes) = drops {
self.as_guest(host, conn, |game| game.drop_inventory(eyes));
let message = horizon_client::lan::data::component_nbt(&text.component());
let team = self.score.board.players_team(&name);
if horizon_client::scoreboard::own_death_message_shown(team) {
host.hub.system_message(message.clone());
if self.options.dedicated.is_some() {
super::dedicated::log("INFO", &format!("System chat: {}", text.plain()));
} else if self.player.is_some() {
self.system_message(text);
}
}
self.spawn_orbs(at, reward);
message
} else {
literal("")
};
host.hub.send_to(
conn,
&C::PlayerCombatKill(play::PlayerCombatKill { id, message }),
);
// LivingEntity.die: the death animation, the dying player included.
host.hub.entity_event(id, 3, at);
if let Some(eyes) = drops {
self.as_guest(host, conn, |game| game.drop_inventory(eyes));
}
self.spawn_orbs(at, reward);
}
}
@@ -2111,7 +2255,16 @@ impl Game<'_> {
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
// Player.tick ends with updatePlayerPose: a swimmer, or a player
// crawling under a block, takes the short box its moves are checked with.
let _ = w.update_player_pose();
let mut events = std::mem::take(&mut w.player.events);
// LayeredCauldronBlock.handleEntityOnFireInside along those moves.
for event in &events {
if let MotionEvent::CauldronExtinguish { pos } = event {
game.cauldron_extinguish(*pos);
}
}
// WitherRoseBlock.entityInside along those moves.
for event in &events {
if matches!(event, MotionEvent::InsideWitherRose) {
@@ -2153,6 +2306,7 @@ impl Game<'_> {
let Some((events, marked)) = events else {
return;
};
self.as_guest(host, conn, |game| game.tick_player_sculk_events());
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at),
+5 -1
View File
@@ -28,7 +28,11 @@ impl Game<'_> {
/// SignableCommand.of: the command's message arguments, by name, with
/// their text, not past a redirect to the root (`execute ... run`).
fn signable_arguments(&mut self, permission: u8, command: &str) -> Vec<(String, String)> {
pub(super) fn signable_arguments(
&mut self,
permission: u8,
command: &str,
) -> Vec<(String, String)> {
let parse = self.parse_as(permission, command);
let nodes = &vanilla::game_dispatcher().nodes;
let root = parse.context.root;
@@ -291,6 +291,11 @@ impl Game<'_> {
let at = host.hub.guests[gi].position;
self.award_furnace_recipes(pos, at);
}
// Slot.setChanged on a changed container slot: BlockEntity.setChanged,
// so the chunk is saved and comparators read the block again.
if changed.iter().any(|&s| s < items.len()) {
self.container_changed(pos);
}
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
host.hub.inventory_clicked(conn, p, &self.world, &changed);
true
@@ -245,6 +245,16 @@ impl Game<'_> {
}
out.push(e);
}
for c in &self.cushions {
let p = c.position;
let mut e = state(c.id, "minecraft:cushion", [p.x, p.y, p.z], c.yaw, false);
// Cushion.DATA_COLOR, set unless it is the default white.
if c.color != 0 {
e.meta
.push((8, serializer::DYE_COLOR, Value::Id(i32::from(c.color))));
}
out.push(e);
}
self.lan_projectile_states(host_entity, hub, out);
for o in &self.others {
let p = o.position;
+25 -2
View File
@@ -119,7 +119,17 @@ impl Game<'_> {
/// Runs `f` as each guest in play here, for what strikes every player in
/// an area (`Level.getEntities`), not only the window's own.
pub(super) fn each_guest_hit(&mut self, mut f: impl FnMut(&mut Self)) {
pub(super) fn each_guest_hit(&mut self, f: impl FnMut(&mut Self)) {
self.each_guest_hit_except(None, f);
}
/// [`Self::each_guest_hit`] leaving out the guest `except` (the one a
/// firework rocket is attached to, which it hurts on its own).
pub(super) fn each_guest_hit_except(
&mut self,
except: Option<u32>,
mut f: impl FnMut(&mut Self),
) {
let Some(mut host) = self.lan.take() else {
return;
};
@@ -127,7 +137,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && Some(g.conn) != except)
.map(|g| g.conn)
.collect();
for conn in conns {
@@ -171,6 +181,19 @@ impl Game<'_> {
})
.collect()
}
/// The same guests' feet and whether they stand on the ground, for the
/// blocks that also ask that (`BigDripleafBlock.canEntityTilt`).
pub(super) fn lan_guest_feet(&self) -> Vec<([f64; 3], bool)> {
let Some(host) = self.lan.as_ref() else {
return Vec::new();
};
host.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| (g.position, g.on_ground))
.collect()
}
/// The guests a projectile can hit, under their entity ids.
pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> {
@@ -25,6 +25,33 @@ fn rgb(c: [f32; 4]) -> [f32; 3] {
}
impl Game<'_> {
/// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point.
/// Keep the local event's rendering; connected players receive one at rest.
pub(super) fn lan_sonic_boom(&self, options: &ParticleOptions, at: [f64; 3]) {
let (Some(host), Some(particle)) = (&self.lan, self.network_particle(options, None)) else {
return;
};
let packet = C::LevelParticles(play::LevelParticles {
particle,
override_limiter: false,
always_show: false,
pos: at,
dist: [0.0; 3],
max_speed: [0.0; 3],
count: 0,
randomization: 0,
});
for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
// ServerLevel compares the player's block centre, strictly within 32.
let distance: f64 = (0..3)
.map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
.sum();
if distance < 32.0 * 32.0 {
g.send(&packet);
}
}
}
/// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's
/// network id and the data it carries (`state` for the block particles).
/// None while not serving, or for a particle whose data isn't sent from
@@ -161,12 +188,12 @@ impl Game<'_> {
+ (self.particles.random().next_float() - self.particles.random().next_float())
* 0.2)
* 0.7;
self.audio.play(
"minecraft:entity.generic.explode",
Some(p.center),
4.0,
pitch,
);
// The packet's explosionSound: a wind charge's burst, a bed's
// or anchor's blast, a modded sound.
let sound = self
.remote_sound_name(&p.sound)
.unwrap_or_else(|| "minecraft:entity.generic.explode".to_owned());
self.audio.play(&sound, Some(p.center), 4.0, pitch);
}
if let Some(options) = self.received_particle(&p.particle, p.center) {
self.particles.add(&options, p.center, [1.0, 0.0, 0.0]);
+22
View File
@@ -32,6 +32,8 @@ pub(super) enum Victim {
/// The attacker's side of the hit.
pub(super) struct Strike {
/// The attacking guest, kept after their turn through `as_guest` ends.
attacker: Option<u32>,
amount: f32,
scale: f32,
crit: bool,
@@ -119,6 +121,7 @@ impl Game<'_> {
}
self.swing_arm();
Some(Strike {
attacker: self.lan_acting,
amount,
scale,
crit,
@@ -250,6 +253,25 @@ impl Game<'_> {
Victim::Host => land(self),
Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false),
};
if hurt && s.crit {
let target = match victim {
Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)),
Victim::Guest(conn) => host
.hub
.guest(conn)
.and_then(|g| g.motion.as_deref().map(|p| (g.entity_id, p))),
};
if let Some((id, p)) = target {
let d = p.dimensions;
self.critical_hit(
s.attacker,
id,
[p.position.x, p.position.y, p.position.z],
f64::from(d.width),
f64::from(d.height),
);
}
}
let sound = match (hurt, s.crit, s.scale > 0.9) {
(false, ..) => "minecraft:entity.player.attack.nodamage",
(true, true, _) => "minecraft:entity.player.attack.crit",
+165
View File
@@ -0,0 +1,165 @@
//! Quiet commands (`horizon_protocol::quiet`): a Horizon client's mod sends a
//! batch of command lines in one payload, and the server runs each exactly as
//! that player typing it would (`guest_command`'s checks, the player's own
//! permission level, at the time it runs) with its output suppressed, as
//! vanilla's functions run (`CommandSourceStack.withSuppressedOutput`): no
//! feedback and no failure in anyone's chat. A batch waits in a queue and runs
//! [`PER_TICK`] lines a player a tick, so a mod can't flood a server; each
//! finished batch is one line in the server's log.
use super::{Game, lan::LanHost, lan_actions::GuestCommand};
use horizon_protocol::quiet;
use std::collections::{HashMap, VecDeque};
/// Lines a player may have waiting at most; a batch past it loses the rest.
pub(super) const PENDING: usize = 4096;
/// Lines run a player a tick at most.
pub(super) const PER_TICK: usize = 64;
/// A batch waiting to run.
pub(super) struct QuietBatch {
conn: u32,
mod_id: String,
lines: VecDeque<String>,
ran: usize,
failed: usize,
/// Lines past [`PENDING`], never run.
dropped: usize,
}
impl Game<'_> {
/// A `horizon:quiet_commands` payload from `conn`: queued (or logged as
/// refused when it breaks the payload's caps).
pub(super) fn guest_quiet_commands(&mut self, host: &mut LanHost, conn: u32, data: &[u8]) {
let Some(name) = host.hub.guest(conn).map(|g| g.name.clone()) else {
return;
};
let batch = match quiet::decode(data) {
Ok(b) => b,
Err(e) => {
super::dedicated::log(
"WARN",
&format!("{name} sent quiet commands that were refused: {e}"),
);
return;
}
};
let waiting: usize = host
.quiet
.iter()
.filter(|b| b.conn == conn)
.map(|b| b.lines.len())
.sum();
let room = PENDING.saturating_sub(waiting);
let dropped = batch.lines.len().saturating_sub(room);
host.quiet.push_back(QuietBatch {
conn,
mod_id: batch.mod_id,
lines: batch.lines.into_iter().take(room).collect(),
ran: 0,
failed: 0,
dropped,
});
}
/// The waiting batches, [`PER_TICK`] lines a player this tick, in order.
pub(super) fn run_quiet_commands(&mut self) {
let mut left: HashMap<u32, usize> = HashMap::new();
let mut i = 0;
loop {
let Some(host) = self.lan.as_mut() else {
return;
};
let Some(batch) = host.quiet.get_mut(i) else {
return;
};
let conn = batch.conn;
let budget = left.entry(conn).or_insert(PER_TICK);
let gone = host.hub.guest(conn).is_none();
if gone || batch.lines.is_empty() {
let batch = host.quiet.remove(i).expect("got it above");
if !gone {
let name = host
.hub
.guest(conn)
.map_or(String::new(), |g| g.name.clone());
super::dedicated::log("INFO", &summary(&name, &batch));
}
continue;
}
if *budget == 0 {
i += 1;
continue;
}
*budget -= 1;
let line = batch.lines.pop_front().expect("not empty");
let ok = self.run_quiet_line(conn, &line);
if let Some(batch) = self.lan.as_mut().and_then(|h| h.quiet.get_mut(i)) {
batch.ran += 1;
batch.failed += usize::from(!ok);
}
}
}
/// One line as `guest_command` would run it for `conn`, quietly. False
/// when it is refused or fails. A command that carries a chat message
/// (`say`, `msg`...) is refused: it would need the player's signature.
fn run_quiet_line(&mut self, conn: u32, line: &str) -> bool {
let allowed = self.options.dedicated.is_some() || self.allow_commands();
let Some(host) = self.lan.as_ref() else {
return false;
};
let integrated = host.hub.config.integrated;
if !integrated && (!host.settings.guest_commands || !allowed) {
return false;
}
let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else {
return false;
};
let command = line.trim_start_matches('/');
if !self.signable_arguments(permission, command).is_empty() {
return false;
}
self.run_guest_command(GuestCommand {
conn,
command: command.to_owned(),
permission,
integrated,
quiet: true,
})
}
}
/// The batch's line in the server's log.
fn summary(name: &str, b: &QuietBatch) -> String {
let mut line = format!(
"{name} ran {} quiet command(s) from mod {}: {} failed",
b.ran, b.mod_id, b.failed
);
if b.dropped > 0 {
line += &format!(", {} dropped (more than {PENDING} waiting)", b.dropped);
}
line
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_log_line_counts_the_batch() {
let b = QuietBatch {
conn: 1,
mod_id: "orbital".into(),
lines: VecDeque::new(),
ran: 12,
failed: 3,
dropped: 0,
};
assert_eq!(
summary("Alex", &b),
"Alex ran 12 quiet command(s) from mod orbital: 3 failed"
);
let b = QuietBatch { dropped: 5, ..b };
assert!(summary("Alex", &b).ends_with(", 5 dropped (more than 4096 waiting)"));
}
}
Loaded 100 of 634 files, more files were not shown because too many files have changed in this diff. Show more