Compare commits

..
Author SHA1 Message Date
Ludovic Marie aedfd10c93 Merge pull request #12220 from NikitaMGrimm/hdr-frame-rebuild
🤖 Agent: The HDR float frame follows HDR, Smooth Gradients and the picked pack at once by rebuilding the renderer; all of it is behind HORIZON_HDR_FRAME=float, so the default path only pays one bool check per frame.
2026-11-08 08:19:20 +01:00
Ludovic Marie f64f181d1d Merge pull request #12319 from glitchsnake/fix/11651-spawn-finalize
🤖 Agent: EntityType.create spawns (frogspawn tadpoles, infested silverfish, allay duplication, villager breeding, sniffer eggs, the thunder skeleton horse...) skip finalizeSpawn's rolls; I fixed the lightning witch, which vanilla still finalizes with CONVERSION (Villager.java:748).
2026-11-08 07:57:06 +01:00
Ludovic Marie fe020bb113 Merge pull request #12314 from NikitaMGrimm/warden-digging-test
🤖 Agent: The warden digging test ticks the warden at age 1, since the client moves tickCount on before it ticks; it had failed on main since #12110 wherever the vanilla data is prepared.
2026-11-08 07:45:06 +01:00
Ludovic Marie 0ae694bb66 Merge pull request #12308 from voidsipp/fix/round6-12001
🤖 Agent: F3 shows the debug overlay on the title screen and F3+F6 opens the debug options over the panorama, closing back to the title without grabbing the pointer, as TitleScreen allows.
2026-11-08 07:45:02 +01:00
Ludovic Marie 25b7c04314 Merge pull request #12307 from NikitaMGrimm/tnt-piston-powder
🤖 Agent: A piston push of primed TNT applies the blocks it moves through (powder snow, soul sand, slime), as the piston's Entity.move does. Stacked on #12290.
2026-11-08 07:44:59 +01:00
Ludovic Marie 1a8589a0dd Merge pull request #12305 from NikitaMGrimm/hdr-oit-written
🤖 Agent: Improved Transparency writes light on the float frame too, behind the same HDR_WRITE_LIGHT override. Stacked on #12302.
2026-11-08 07:44:55 +01:00
Ludovic Marie 7176e0df23 Merge pull request #12303 from Solenopsisbot/perf/worldgen-shape-capture
🤖 Agent: The decoration shape-capture vector is kept per region and restored on every path, including errors, instead of a fresh Vec per update.
2026-11-08 07:44:51 +01:00
Ludovic Marie fad4b0f5dd Merge pull request #12302 from NikitaMGrimm/hdr-vis-written
🤖 Agent: On the float frame the visibility buffer writes light itself; behind the HDR_WRITE_LIGHT override, false on the default frame. Stacked on #12282.
2026-11-08 07:44:48 +01:00
Ludovic Marie 8ca3dc19dd Merge pull request #12299 from d3xc0/android-touch-1
🤖 Agent: Adds the touch control layout model (schemes, 14 controls, load/save with defaults); nothing calls it yet, so players see no change.
2026-11-08 07:44:44 +01:00
Ludovic Marie 26ee23d376 Merge pull request #12296 from voidsipp/fix/round6-12089
🤖 Agent: An option button's pointer cursor follows hover only, while its focus still highlights it (AbstractWidget.handleCursor tests hover), and a click on a disabled button no longer focuses it.
2026-11-08 07:44:40 +01:00
Ludovic Marie fe524fefb2 Merge pull request #12293 from J5Casey/braid/screen-input-act
🤖 Agent: Screen drag and wheel get v2 hooks that lend the game mutably, heard just before v1; v1 keeps its signature and still hears the turn unless v2 cancels it or closes the screen.
2026-11-08 07:44:36 +01:00
Ludovic Marie bb26451389 Merge pull request #12292 from voidsipp/fix/round6-12218
🤖 Agent: A resting item in a lava cauldron burns: each lava cauldron its box meets (the cauldron's inside shape, not the air above) applies LAVA_IGNITE and its own lavaHurt, stopping once the item is gone; netherite stays immune, as the new oracle shows.
2026-11-08 07:44:33 +01:00
Horizon agentandClaude Opus 5.5 2e2635f83d Lightning: the witch from a villager is still finalized
Villager.thunderHit converts with finalizeSpawn(level, difficulty,
EntitySpawnReason.CONVERSION, null); only Pig.thunderHit skips it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 07:33:26 +01:00
Horizon agent aee2c83c2f Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 07:29:43 +01:00
Ludovic Marie 6ef71901bf Merge pull request #12316 from horizon-rust/fix/test-batch-starting-feedback
🤖 Agent: the batch-starting line now goes to the /test command's own source inside the command (TestBatchSummaryDisplayer); the test-instance block still uses the server source. Lifecycle stays 95/99: its 4 if-loaded records are an oracle artifact.
2026-11-08 07:13:17 +01:00
Ludovic Marie da954fba54 Merge pull request #12315 from horizon-rust/fix/mob-scores-until-removal
🤖 Agent: mob_died no longer resets scores at the death; vanilla does it in onDestroyed, so unloaded corpses keep them. The #12185 shulkers get fixed UUIDs so /scoreboard players list can match at all.
2026-11-08 07:13:14 +01:00
LokiandAntigravity 4f54fcf47b mobs: skip finalizeSpawn for EntityType.create spawns (fixes #11651)
Co-Authored-By: Antigravity <[email protected]>
2026-11-08 15:13:09 +09:00
Ludovic Marie 22e6e5c8a4 Merge pull request #12242 from NikitaMGrimm/entity-own-random
🤖 Agent: A new item's own random now makes its UUID (Mth.createInsecureUUID, the first two draws), then bobOffs, yaw and motion in that order, instead of a process-wide clock-seeded UUID; I merged main (the seed-sync gaps diagnostic this PR retires stays out).
2026-11-08 07:09:07 +01:00
Ludovic Marie d77d31fff1 Merge pull request #12245 from Solenopsisbot/perf/tick-scratch-reuse
🤖 Agent: Block contact scratch lists are kept on Game and restored on every Result path; I replaced extend(drain(..)) with append, the clippy error that failed verify (clippy -D warnings passes now).
2026-11-08 07:09:04 +01:00
Ludovic Marie 2c04e1ba85 Merge pull request #12211 from rdbtCVS/perf/beehive-stay
🤖 Agent: bees_stay_in_hive's night and rain answer is kept for the hive's turn instead of building the mob world per occupant.
2026-11-08 07:09:00 +01:00
Nikita Maximilian Grimm edddce4485 Merge remote-tracking branch 'origin/main' into warden-digging-test 2026-11-08 07:08:38 +01:00
Ludovic Marie 6ebe4a33c3 Merge pull request #11867 from MrCloudy2/fix/passengers-players
🤖 Agent: `execute on passengers` finds the players riding a vehicle on a server (the player in place, then the hub guests by their vehicle); I merged main, whose new mob-children arm now follows this PR's player_passengers, so both players and mob riders are found.
2026-11-08 07:04:32 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 4018f7925e Warden digging test ticks the warden at age 1, as the client does
Since #12110 a warden's client tick plays the heartbeat when its age is
a multiple of the beat delay. The test ticked a new warden at age 0, so
it heard a heartbeat. The client loop moves the age on before it ticks,
as vanilla's `tickCount++` does, so the game never ticks at age 0.

Fixes #12312

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 07:00:07 +01:00
Ludovic Marie cbb2b99022 Merge pull request #12285 from voidsipp/fix/round6-12201
🤖 Agent: An export that fails on a missing lib/tzdb.dat now names the Java to repair, matched only on the FileNotFound/NoSuchFile line for that exact path; other failures keep their message.
2026-11-08 06:58:24 +01:00
Ludovic Marie 7fdce634b4 Merge pull request #12283 from k3yh/loot-world-pack-ids
🤖 Agent: /loot and pack functions take the world's packs' loot tables: the id list comes from the loaded tables (root plus pack overlay) and is refreshed on /reload.
2026-11-08 06:58:20 +01:00
Ludovic Marie 7d084fc8aa Merge pull request #12282 from NikitaMGrimm/hdr-write-light
🤖 Agent: On the float frame every shader writes its own light; all of it sits behind the HDR_WRITE_LIGHT pipeline override, false on the default frame, so the SDR path compiles it out. Stacked on #12220 and #12247.
2026-11-08 06:54:56 +01:00
Ludovic Marie edb0905d0f Merge pull request #12267 from J5Casey/braid/menu-links
🤖 Agent: Mod menu types can show slots of other containers (native_menu_links) instead of mirroring them each tick; stacked on #12246, lands after it.
2026-11-08 06:54:53 +01:00
Ludovic Marie f6dda117a8 Merge pull request #12265 from voidsipp/fix/round6-12129
🤖 Agent: Other crates' records, native mods included, now reach latest.log from INFO with their target prefixed; they still stay off stderr, so only the log file grows.
2026-11-08 06:54:49 +01:00
Ludovic Marie 5c0ac57986 Merge pull request #12263 from J5Casey/braid/loot-custom-data
🤖 Agent: match_tool and loot predicates now test minecraft:custom_data as NbtUtils.compareNbt(pattern, data, true), with JSON patterns converted as JsonOps does; compare_nbt moved to horizon-world for both callers.
2026-11-08 06:54:45 +01:00
Ludovic Marie a12e378c46 Merge pull request #12262 from k3yh/loot-give-guests
🤖 Agent: /loot give gives to every target player, each guest with their own state in place via for_player, as LootCommand.playerGive does.
2026-11-08 06:54:41 +01:00
Ludovic Marie c1e81319cb Merge pull request #12259 from J5Casey/braid/player-break-api
🤖 Agent: native_player_break_block breaks a block as a given player through the game's own player-break path (spectator, adventure can_break, spawn protection, native_destroy_block, loot, wear, stats).
2026-11-08 06:54:38 +01:00
Ludovic Marie 7232e9f6bd Merge pull request #12255 from echo-ilovech3ss/fix-11887-mob-absorption
🤖 Agent: Death protection and milk removal clamp a mob's absorption to its remaining max_absorption (onAttributeUpdated), instead of subtracting 4 per Absorption level.
2026-11-08 06:54:34 +01:00
Ludovic Marie fe63866acc Merge pull request #12254 from rison1337/perf/tight-terrain-occlusion
🤖 Agent: CPU terrain occlusion tests each section's padded mesh bounds instead of the whole 18-block cell, so empty space no longer keeps a hidden section drawn; sections without bounds keep SECTION_BOX.
2026-11-08 06:54:31 +01:00
Ludovic Marie 4c66382f4e Merge pull request #12252 from masa-masa-0314/feat/realms-slot-pictures
🤖 Agent: Realms world slots draw their own pictures and template pages arrive page by page. Cost to note: the four 1024-tall slot pictures now live in the HUD atlas for every player, about one 1024-tall shelf of GPU memory; a follow-up should load them only while Realms screens are open.
2026-11-08 06:54:28 +01:00
Ludovic Marie 604e9cb82f Merge pull request #12251 from k3yh/loot-set-name-components
🤖 Agent: /loot now applies set_name and set_components to its drops, as a chest's roll already did, and names each drop by its display name in the feedback.
2026-11-08 06:54:24 +01:00
Ludovic Marie 205a2387c3 Merge pull request #12248 from vnsmoreira/attributes/timelines
🤖 Agent: Ports vanilla's timelines, keyframe tracks and all 32 easings into horizon-world with Java's float/double steps; nothing in the game calls it yet, only the two new oracles' probes.
2026-11-08 06:54:21 +01:00
Ludovic Marie 1d56d438df Merge pull request #12247 from NikitaMGrimm/hdr-light-function
🤖 Agent: One hdr_mark_light function serves the display and resolve passes; a GPU test checks it against the old code for every 8-bit mark and both easing modes.
2026-11-08 06:54:17 +01:00
Ludovic Marie 7a87965ec8 Merge pull request #12246 from J5Casey/braid/craft-grid-3
🤖 Agent: The recipe_sources native hook lets recipe placement into a mod menu type's grid take ingredients from containers the mod names; stacked on #12240 and #12233, lands after them.
2026-11-08 06:54:13 +01:00
Ludovic Marie 1334feb5fa Merge pull request #12244 from TheMrZZ/fix/h268-global-selector-order
🤖 Agent: An unbounded arbitrary @e walks the joined families in insertion order (EntityLookup.getEntities), falling back to the old order if the walk fails; it builds one count map per such query, other selectors keep their path.
2026-11-08 06:54:09 +01:00
Ludovic Marie fb75635ec3 Merge pull request #12243 from NikitaMGrimm/fn-tick-time
🤖 Agent: #minecraft:tick functions now run before the levels tick, so they read the game time from before the tick, and /schedule'd ones run in ServerLevel.tickTime once the clock has moved, as MinecraftServer.tickChildren orders them.
2026-11-08 06:54:06 +01:00
Horizon agent af4a313bc7 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	tools/test_command_exec_parity.py
2026-11-08 06:51:10 +01:00
Horizon agentandClaude Opus 5.5 9b0c6f48ea Drop the second passengers arm left by the main merge
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:50:09 +01:00
f030d9c807 HDR float frame: Improved Transparency writes light
With Improved Transparency on, the float frame's default lane no longer
stays marked: each see-through layer converts its own colour to light
(hdr_written) before it is weighted and accumulated, so the composite
lays light over the light behind it, as the forward passes do. Text,
shadows, weather and the border keep their source gain, as they do in
the forward passes; cracks keep their multiply blend outside the
accumulation, since it scales the light under them. Only a shader pack
keeps the frame marked now. The identity harness's float OIT session is
no longer an identity case; Improved Transparency with HDR off and on
the 16-bit frame are, and fail unless the option changed the picture.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:50:04 +01:00
Nikita Maximilian Grimm bf3191ed83 Merge branch 'tnt-fall-powder' into tnt-piston-powder 2026-11-08 06:46:41 +01:00
Nikita Maximilian Grimm 631eef433b Merge remote-tracking branch 'origin/main' into tnt-fall-powder
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-08 06:46:31 +01:00
SolenopsisbotandCodex 7ba6d345b0 perf: reuse decoration shape capture
Retain captured shape-update ticks across decoration queries while preserving ordering and error propagation.

Co-Authored-By: Codex <[email protected]>
2026-11-08 16:46:01 +11:00
Ludovic Marie 2d29c7f8e9 Merge pull request #12200 from TiggerTakkyTTT/fix/datapack-biome-ambient-particles
🤖 Agent: Datapack-added or replaced biomes keep their minecraft:visual/ambient_particles, so ambient particles use the world pack's biome instead of the prepared vanilla table.
2026-11-08 06:44:40 +01:00
Ludovic Marie 76bfbf1ad8 Merge pull request #12238 from itarqos5/feat/redstone-diff-harness
🤖 Agent: tools only: redstone_diff.py runs the same random circuit on vanilla and Horizon and compares every tick; nothing players run changes.
2026-11-08 06:44:36 +01:00
Arthur BlackandClaude Opus 5.5 87b5ae27a6 Touch layout model for on-screen controls
- Add touch::layout: control schemes, built-in controls, per-scheme placements and the saved settings file
- Visibility follows the scheme unless the player shows or hides a control; left-handed mirroring; D-pad jump/sneak swap
- Load falls back to defaults and sanitizes off-screen or non-finite values; save writes through a temp file
- Nothing uses it yet: the touch controls that read it come in the next pull requests
- Adapted from Starling (MIT, by Vasysik); credited in THIRD_PARTY_NOTICES.md

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-11-07 21:33:35 -08:00
voidsip 28acf8303c Exercise the title submenu control through debug keys 2026-11-07 23:32:55 -06:00
Ludovic Marie 2a66276bcc Merge pull request #12232 from Solenopsisbot/perf/defaults-ticket-fastpath
🤖 Agent: perf: unchanged ticket sources skip renormalisation, and item defaults load once per root; I fixed the fast path to compare the dragon arena too (it broke the watched-dragon-arena test).
2026-11-08 06:29:15 +01:00
Ludovic Marie 38f9ce31e7 Merge pull request #12210 from rdbtCVS/perf/streaming-cover
🤖 Agent: update records that the cover was refreshed at its start, so each waiting chunk no longer compares the ~200-entry extra areas list every tick.
2026-11-08 06:29:11 +01:00
Horizon agentandClaude Opus 5.5 67f84002d3 redstone_diff: start the game through lab.game_env
tests/test_game_home.py requires every script that starts the game to use it
(scratch folders, no audio) instead of setting HORIZON_NO_AUDIO by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:28:25 +01:00
Horizon agentandClaude Opus 5.5 97f4aa5e7f Tell /test's source when a batch starts, inside the command
Vanilla's TestCommand.trackAndStartRunner adds a TestBatchSummaryDisplayer
holding the command's source; GameTestRunner.start runs the first batch
inside the command, and testBatchStarting sends
"Starting environment <env> batch <n>" with sendSuccess(.., true). Horizon
queued the line as a server console broadcast for the next tick, so `/test
run` answered only "Running 1 test(s)..." (world_test_def 94/96,
world_test_def_lifecycle 6 of its 10 differing records, as #11992 noted).

A runner a command starts now sends the line through that command's source
while the command runs (`feedback`). A test instance block's runner keeps the
server's source (TestInstanceBlockEntity.runTest), as do later batches, which
start from the tick.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:28:23 +01:00
Horizon agentandClaude Opus 5.5 3b89ded9f9 Keep a dead mob's scores until its body is removed
Vanilla resets an entity's scores in ServerLevel.EntityCallbacks.onDestroyed
(Scoreboard.entityRemoved), when the entity is removed for good: a mob's body
twenty ticks after LivingEntity.die, never when it is unloaded. Horizon reset
them in mob_died, at the death. A mob killed in a frozen world and then
unloaded kept its scores in vanilla and lost them here, so a later
`/scoreboard players list` named 32 fewer holders (command_exec, after
#12185's shulker command damage case).

mob_died no longer resets them; score_destroyed_entities already resets every
removed entity's scores once a tick, and keeps an unloaded one's.

#12185's 32 shulkers had random UUIDs, which that list then named: Java and
Horizon could never print the same list. The case now gives them fixed
UUIDs, so the record is exact again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:28:23 +01:00
Nikita Maximilian Grimm 5c9bf7ad11 Merge branch 'tnt-fall-powder' into tnt-piston-powder 2026-11-08 06:27:20 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 de12dbd275 Slime slows piston-pushed TNT before the blocks it is in act
`Entity.applyEffectsFromBlocks` runs the supporting block's `stepOn`
before the blocks the entity is inside, so slime slows TNT before a
bubble column beside it lifts it. TNT's own tick had them the other
way round, and the piston push shares the same steps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:27:20 +01:00
J5CaseyandClaude Opus 5.5 957475f644 Native hooks: screen drag and wheel v2 with the game lent mutably
native_screen_mouse_dragged_pre and native_screen_mouse_scrolled_pre take
&self because their NativeScreenView borrows the game, so a mod can cancel
a drag or a wheel turn over a screen but can't click a slot there.
Mouse Tweaks-style mods (Mouse Tricks) inject into the private
inventory_drag_move and tweak_scroll instead and pin one Horizon commit.

Add native_screen_mouse_dragged_pre_v2 and
native_screen_mouse_scrolled_pre_v2 with &mut Game: the view's id and
pointer come by value, the rest as v1's. Each fires at v1's point, just
before v1, which hears the screen as v2 left it and nothing of an input
v2 canceled. Cancelling does what cancelling v1 does. v1 is unchanged.

Fragment tools/native-hook-fragments/screen_mouse_input_v2.json; native
bodies filled by `cargo run -p xtask -- mod-api`.

Fixes #12286

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KtNXhvTSpY15Rjzwuqh8Nf
2026-11-07 23:26:15 -06:00
Horizon agentandClaude Opus 5.5 33e0bf2aec Use append for the later cells (clippy::extend_with_drain)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:26:10 +01:00
Horizon agent dca25b7662 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 06:26:10 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 964e31a3c3 HDR float frame: the visibility buffer writes light
With HORIZON_VISBUFFER=1, the float frame's default lane no longer stays
marked: the visibility buffer's resolve writes its solid pixels' light
as fs_opaque does (solid_light), so the frame is written whole. The
identity harness's float visbuffer session is no longer an identity
case; the visibility buffer with HDR off and on the 16-bit frame are,
drawn flat so that the buffer runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:26:03 +01:00
Ludovic Marie da4e8d8d49 Merge pull request #12225 from NikitaMGrimm/block-entities-wait-entities
🤖 Agent: Block entities and scheduled ticks wait until their chunk's entities have loaded, as ServerLevel.isPositionTickingWithEntitiesLoaded gates them; the entities_pending set is cloned once per call.
2026-11-08 06:25:58 +01:00
Ludovic Marie efe5e70188 Merge pull request #12212 from rdbtCVS/perf/player-squares
🤖 Agent: With more than 8 players the level keeps them by 256-block square, built when a spawn pass first asks; smaller servers keep the plain scan.
2026-11-08 06:25:54 +01:00
Ludovic Marie 901e640591 Merge pull request #12209 from rdbtCVS/perf/creaking-heart-world
🤖 Agent: The creaking heart builds the mob world only for its update (about once a second), with server_tick split into start and update.
2026-11-08 06:25:51 +01:00
Ludovic Marie e7c443cdf6 Merge pull request #12208 from rdbtCVS/perf/spawner-delay
🤖 Agent: A spawner's delay counts down without building a level view when no player is in range, the common case, and builds it only when it may spawn.
2026-11-08 06:25:47 +01:00
Ludovic Marie baf9a32a0e Merge pull request #12207 from rdbtCVS/perf/structure-start-cache
🤖 Agent: The structure start cache keeps 262,144 chunks instead of 65,536: a few MB more for far fewer regenerated starts while exploring.
2026-11-08 06:25:43 +01:00
Ludovic Marie 854a5dc246 Merge pull request #12206 from rdbtCVS/perf/decoration-rank
🤖 Agent: Decoration ranks are unique, so only chunks without a rank are measured and the queue is a heap that pops until the workers are full, instead of a full sort per update.
2026-11-08 06:25:38 +01:00
Ludovic Marie 8c672e7f9e Merge pull request #12219 from NikitaMGrimm/item-escape-gravity
🤖 Agent: An item pushed out of a solid block takes its gravity step before the escape push (#12018), and the new command_exec case pins two ticks whose height and motion are exact whatever the random push speed.
2026-11-08 06:25:35 +01:00
Ludovic Marie 4a1f7dfad4 Merge pull request #12215 from NikitaMGrimm/test-randoms-sync
🤖 Agent: Harness-only seed sync: the seed sync proof is its own isolated command_exec group, so its fixed seeds cannot leak into the groups after it.
2026-11-08 06:25:31 +01:00
Ludovic Marie e6d44af84e Merge pull request #12236 from martipops/settings/shell-graphics
🤖 Agent: The Graphics page describes its rows and the shell draws and drives them; I merged main's three-state GPU Culling into the new test helpers (focus_on, key), graphics_ui tests pass.
2026-11-08 06:25:27 +01:00
Ludovic Marie 23ea8d66a6 Merge pull request #12235 from itarqos5/fix/setblock-notify-after-shape-updates
🤖 Agent: /setblock and /fill notify neighbours after all shape updates (BlockInput.place, ServerLevel.updateNeighboursOnBlockSet), so a wire beside a block that pops off ends as a cross; I merged main (fill's note-block normalisation kept) and marked the two resource-backed tests #[ignore], as the other HORIZON_TEST_RESOURCES tests are, since CI has no resources.
2026-11-08 06:25:24 +01:00
Nikita Maximilian Grimm 8abbc6b9e4 Merge remote-tracking branch 'origin/main' into tnt-fall-powder 2026-11-08 06:23:27 +01:00
voidsip f2fe9c1dfe Keep title submenu debug-options handling unchanged 2026-11-07 23:22:01 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 6a11db7ef7 Frame identity harness: the float visibility buffer session draws flat
The visibility buffer draws only frames drawn flat, which frames without
a pack are by default only on Metal and some Intel drivers, so elsewhere
float_visbuffer compared the forward passes. It now sets
HORIZON_FLAT_DRAWS=1 and fails unless the game built the buffer. The
module docs list the sessions added on this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:19:47 +01:00
voidsip 7a5d306949 Show title-screen debug information and options 2026-11-07 23:19:38 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 66d06e23f7 A spent piston push still applies TNT's block effects
Once `limitPistonMovement` has used the tick's 0.51, `Entity.move`
returns at once, but `moveEntityByPiston` still runs
`applyEffectsFromBlocks`, so a second piston's push still lets slime
under the TNT slow it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 06:18:11 +01:00
voidsip 417677fdda Match cauldron contact tolerances and repeated damage callbacks 2026-11-07 23:15:03 -06:00
k3yhandClaude Opus 5.5 8721db0e28 /loot and a pack's functions name the world's packs' loot tables
The commands' minecraft:loot_table ids came from the resource root's
folders, so /loot refused a world data pack's table, and a pack's
function naming one was dropped at load. ResourceOrIdArgument looks the
id up in the server's registries, which hold the world's packs. The ids
are now the world's loot table map (Items::loot_table_ids): set when the
world opens and again before admit_store parses the packs' functions.

New command corpus group: loot world pack tables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:09:20 -05:00
Nikita Maximilian Grimm 190c17fc7a Merge branch 'tnt-fall-powder' into tnt-piston-powder 2026-11-08 06:01:36 +01:00
Ludovic Marie 9e1abc64d1 Merge pull request #12169 from abit-foggy/codex/studio-c1-c2-topbar-timeline
🤖 Agent: Studio's top bar and timeline are Horizon-only and off unless Studio is opened; the only gameplay touch is the fov/play_input hooks, which read the new state only while Studio is open.
2026-11-08 05:58:14 +01:00
Ludovic Marie d1782f8954 Merge pull request #12233 from J5Casey/braid/craft-grid-1
🤖 Agent: A mod menu's crafting grid crafts through the crafting table's own recipe lookup (lan_crafting), so mod grids and the table agree on every recipe.
2026-11-08 05:58:10 +01:00
Ludovic Marie 00c184e250 Merge pull request #12239 from voidsipp/fix/gateway-item-corpus
🤖 Agent: A replaced end gateway's cached server cooldown is discarded, so a new gateway at the same spot does not inherit its teleport cooldown; covered by the new gateway_replacement oracle.
2026-11-08 05:58:06 +01:00
Ludovic Marie c4b55f1113 Merge pull request #12237 from TheMrZZ/fix/h197-loaded-arrow-mob-can-break
🤖 Agent: A mob-owned arrow may break a block only with its own saved can_break predicate and mob_griefing on; predicates with nbt, components or predicates conjuncts fail closed instead of matching on blocks alone.
2026-11-08 05:57:53 +01:00
Ludovic Marie 7054def60b Merge pull request #12234 from voidsipp/fix/empty-stored-enchantments
🤖 Agent: An enchanted_book with empty stored_enchantments keeps the component instead of dropping it, as ItemEnchantments.EMPTY still saves.
2026-11-08 05:57:49 +01:00
Ludovic Marie 776a3b08a0 Merge pull request #12229 from NikitaMGrimm/fix-fluids-drag-test
🤖 Agent: The item flowing-water test now expects vanilla's float drags (0.98F/0.8F widened to double), the values Entity.handleFluid really produces.
2026-11-08 05:57:45 +01:00
Horizon agent f79643821e Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:57:41 +01:00
Ludovic Marie 3b52978005 Merge pull request #12224 from Solenopsisbot/perf/hotpath-microalloc
🤖 Agent: Rebased onto main: the hot-path buffers (command args, protocol buf, redstone, json folder) are reused instead of reallocated, with the args tests covering the reused path.
2026-11-08 05:57:41 +01:00
Ludovic Marie f4c7a94ad6 Merge pull request #12214 from rdbtCVS/perf/sulfur-grid
🤖 Agent: All geysers of one block-entity pass share one mob grid kept until the mob list's next write; the effect and push loops restamp it only because they change no mob box.
2026-11-08 05:57:37 +01:00
Ludovic Marie 252f02e02a Merge pull request #12213 from rdbtCVS/perf/cart-grid
🤖 Agent: A cart's push and pickup read neighbouring carts and mobs from grids; any mutable access to the mob list bumps its stamp, and with native mods loaded both full scans stay, since a hook can move entities unseen.
2026-11-08 05:57:32 +01:00
Nikita Maximilian Grimm 1d267df0b3 Merge remote-tracking branch 'origin/main' into tnt-fall-powder 2026-11-08 05:57:31 +01:00
Horizon agent 9651982e21 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:57:28 +01:00
Ludovic Marie 3e3a0ffa10 Merge pull request #12216 from rdbtCVS/fix/guest-hit-mob
🤖 Agent: A guest's effect and sting hits now credit the mob that swung, matching LivingEntity.hurtServer's attacker; stacked on #12204, lands after it.
2026-11-08 05:57:28 +01:00
Ludovic Marie 11a7d2cd89 Merge pull request #12204 from rdbtCVS/perf/event-listeners
🤖 Agent: Melee hits and game events read the mobs near them from a grid instead of walking every mob; the grid is rebuilt on the mob list's next write (JoinList stamp), so a mob spawned mid-tick is still found.
2026-11-08 05:57:25 +01:00
Horizon agent 2415fb9e91 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/game/commands/execute.rs
#	tools/lan_e2e.py
2026-11-08 05:57:04 +01:00
Nikita Maximilian Grimm 6f395191c2 Merge branch 'tnt-fall-powder' into tnt-piston-powder 2026-11-08 05:56:08 +01:00
Horizon agentandClaude Opus 5.5 01eefdcc63 Ticket fast path: compare the dragon arena too
A watcher arriving at or leaving the End fight changes only Sources.dragon;
the unchanged-sources skip ignored it, so the arena never got (or lost) its
TicketType.DRAGON levels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:56:02 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 cafee2f14d A piston push of primed TNT applies the block effects
`Entity.move(MoverType.PISTON)` uses up TNT's pending stuck multiplier
(without scaling the push), reads its fall for powder snow's top, adds
to that fall and resets it on landing, and applies the block speed
factor. `moveEntityByPiston` then runs `applyEffectsFromBlocks`, so
powder snow it is pushed into makes it stuck, and slime under it slows
it. Horizon did none of this, so in a chunk that does not tick
entities pushed TNT kept its motion in powder snow and on soul sand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:55:41 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 bd8e0da359 Powder snow's top holds falling TNT until it reaches it
After a fall over 2.5, `PowderSnowBlock.getEntityInsideCollisionShape`
is the 0.9-high top, so the snow only makes the TNT stuck once a step
reaches that top. A TNT passing 2.5 just above the snow used to be made
stuck early, lose its fall and sink through.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:53:44 +01:00
J5CaseyandClaude Opus 5.5 bff8ecf203 Loot item predicates match minecraft:custom_data as vanilla
Block loot's `match_tool` (horizon-items) and the loot engine's
ItemPredicate (`item_matches`: `filtered`, entity `equipment`) ignored
`predicates."minecraft:custom_data"`, so any stack passed. They now test
it as `CustomDataPredicate` does (NbtPredicate.matches ->
CustomData.matchedBy -> NbtUtils.compareNbt(pattern, data, true)): a typed
NBT subset, lists matched element by element, absent custom data read as
`{}`, the pattern SNBT or a JSON object converted as DataFixerUpper does.

`compare_nbt` moves down to horizon-world (re-exported from nbt_path) so
the loot engine can use it, and a killer's equipment keeps its custom data
for entity loot predicates.

New harness loot_custom_data: a data pack's dirt table with a pool per
pattern behind match_tool, `loot give @s mine` with sticks carrying
different custom data, 66/66 records equal to vanilla. The loot engine's
`filtered` path gets the same vanilla matrix as a horizon-world test.

Fixes #12196

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KtNXhvTSpY15Rjzwuqh8Nf
2026-11-07 22:47:46 -06:00
k3yhandClaude Opus 5.5 affb2b6924 /loot give gives to every target player
The give branch of cmd_loot skipped every target but the player in
place, so the console's /loot give reached nobody on a dedicated
server, and a command block's /loot give @p gave nothing in single
player. Each target now goes through for_player, as cmd_give does
(LootCommand.playerGive gives to every target ServerPlayer).

New lan_e2e check: loot_give_guest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:45:11 -05:00
J5CaseyandClaude Opus 5.5 d450bc3b5d Mod menu types: linked slots that show other containers' slots
A content mod's menu type may declare `"links": {"from", "count"}`: those
slots show the slots of block containers a native mod names each tick the
menu is open (`native_menu_links(player, menu, pos, links)`), in order, as
real slots of the menu. Clicks, shift-clicks and drags run on the server's
menu engine and move the containers' own items, a changed container is
saved and its comparators update, and the block entity never holds the
linked slots. Linked slots with nothing behind them hold nothing and are
left out of clicks, as a hidden slot is.

This is what a crafting station's side panel needs (Tinkers' Construct's
shows the chest beside it); a tab per neighbour is a menu button that
changes what the mod links for that player.

Part of #12198.

Claude-Session: https://claude.ai/code/session_01KtNXhvTSpY15Rjzwuqh8Nf
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:44:11 -06:00
voidsip 3ac68d69d3 Keep option button cursors tied to pointer hover 2026-11-07 22:34:17 -06:00
Shreyas 22c6c667a2 Clamp a mob's absorption to maximum on death protection and milk removal 2026-11-08 10:00:00 +05:30
SolenopsisbotandCodex d91706378e perf: reuse block tick scratch buffers
Retain per-tick block contact, random tick, and entity-inside vectors on Game while restoring scratch across result exits and preserving vanilla ordering.

Co-Authored-By: Codex <[email protected]>
2026-11-08 15:26:47 +11:00
SolenopsisbotandCodex 92e96819f5 perf: skip repeated defaults and ticket normalization
Single-flight concurrent item-default loads and avoid rebuilding unchanged chunk-ticket sources while preserving normalization and portal expiry semantics.

Co-Authored-By: Codex <[email protected]>
2026-11-08 15:26:02 +11:00
Nikita Maximilian Grimm f9ed804bb7 Merge main into hdr-frame-rebuild: main has fixed the datapack test this PR's checks failed on 2026-11-08 05:25:58 +01:00
Horizon agentandClaude Opus 5.5 2394ee861d Mark the setblock order tests as needing prepared resources
CI has no HORIZON_TEST_RESOURCES, so they panicked there; like the other
resource-backed game tests they now run with --ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:25:17 +01:00
SolenopsisbotandCodex f54f5c41b6 perf: remove repeated hot-path allocations
Reuse ordered tick scratch, decode protocol varints directly, avoid selector character buffers, single-flight concurrent JSON folder loads, and keep redstone neighbor ordering on the stack.

Co-Authored-By: Codex <[email protected]>
2026-11-08 15:25:13 +11:00
voidsip 048eb18683 Burn dropped items that touch lava cauldrons 2026-11-07 22:23:14 -06:00
k3yhandClaude Opus 5.5 ace3883402 /loot applies set_name and set_components
The items loot engine, which /loot rolls with, skipped both functions:
the item came out without its name, lore, potion or book contents,
while a chest rolling the same table had them. set_name sets the
component its target names, as a chest's roll does. set_components
applies the patch as ItemStack.applyComponents does and reads the
stack back as saved components are read, so a potion's contents make
it a potion. The feedback names each drop by getDisplayName.

New command corpus group: loot set name and components.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:23:12 -05:00
rison1337andCodex 86e57cb74c Merge remote-tracking branch 'upstream/main' into perf/tight-terrain-occlusion
Co-Authored-By: Codex <[email protected]>
2026-11-08 09:22:59 +05:00
rison1337andCodex 33c96ac1f2 Use padded mesh bounds for CPU terrain occlusion
Reuse resident section bounds for phase-one retests and deferred occlusion tests, retaining a one-block total pad and the existing full-cell fallback.

Co-Authored-By: Codex <[email protected]>
2026-11-08 09:22:24 +05:00
2bc3726b4e HDR float frame: every shader writes light on the default lane
Under HORIZON_HDR_FRAME=float, with HDR on, no shader pack, and neither
Improved Transparency nor the visibility buffer requested, the world's
shaders write their own light (hdr_written) instead of a mark, and the
passes that only write marks, the hand's unmark and remark and the
resolve pass are skipped. A frame is all written or all marked. TAA's
history is dropped when that or the HDR parameters it holds change.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:22:16 +01:00
Horizon agent 3a05ee18c6 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/README.md
2026-11-08 05:22:03 +01:00
Horizon agent e1f9a8c096 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client-render/src/graphics_ui.rs
2026-11-08 05:22:03 +01:00
Horizon agent 0b2270dd45 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/game/commands.rs
2026-11-08 05:22:02 +01:00
Ludovic Marie 4dbb00502f Merge pull request #12110 from kacpherek/parity/batch-b
🤖 Agent: Fixed: `MobWorld` has no `end` field, so the fox village stroll now reads `dimension_type.has_fixed_time`, as `Level.isBrightOutside` does; it builds with main merged (lib and tests).
2026-11-08 05:21:19 +01:00
Ludovic Marie 6c75463502 Merge pull request #11714 from arslanarm/shaderpacks/fixture-terrain-notes
🤖 Agent: Requeued after a main merge (clean); the earlier clippy failure was in `horizon-core/src/density/interpolation.rs`, which this PR doesn't touch.
2026-11-08 05:21:15 +01:00
Horizon agent c471036d29 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	tools/command_exec_corpus.py
#	tools/test_command_exec_parity.py
2026-11-08 05:21:11 +01:00
Ludovic Marie 41de65db6e Merge pull request #11764 from rdbtCVS/fix/far-ring-brake-thresholds
🤖 Agent: Requeued after a main merge (clean); the earlier failure was main's native mod API stamp (`native_level_play_sound`) at that moment, not the brake thresholds.
2026-11-08 05:21:11 +01:00
Horizon agent 1c15d2b68c Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:21:03 +01:00
Horizon agent 0eb8b8ec26 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-08 05:21:01 +01:00
Horizon agent 1d0621ac38 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:20:50 +01:00
Horizon agent 1ebc813852 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:20:47 +01:00
Horizon agent 59994ad2a2 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:20:45 +01:00
Horizon agent 9a62e99376 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:20:42 +01:00
Horizon agent 0b10ddd665 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:20:39 +01:00
Horizon agent 406ac72d0a Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 05:20:35 +01:00
Ludovic Marie e2116fb8c2 Merge pull request #11783 from TheMrZZ/fix/fill-note-block-instrument
🤖 Agent: Requeued after a main merge: `fill_note_instrument_tests` sits beside main's commands.rs tests.
2026-11-08 05:17:35 +01:00
voidsip acb17d5694 Explain missing Java timezone data during preparation 2026-11-07 22:16:52 -06:00
Ludovic Marie 65a2bf4613 Merge pull request #11792 from MSedgeMC/fix/camel-breed-parent
🤖 Agent: Requeued after a main merge (clean): a wounded or ridden camel still refuses to start breeding, as in `Camel.canFallInLove`.
2026-11-08 05:16:30 +01:00
Ludovic Marie eb69b3986b Merge pull request #11860 from Joansitoh/fix/11853-patch-log-scroll
🤖 Agent: Requeued after a main merge; the earlier verify failure was a 60 s timeout in `test_entity_shadow_ownership` on a loaded runner, not this PR's launcher scroll change.
2026-11-08 05:16:26 +01:00
Ludovic Marie 389224abec Merge pull request #11879 from TheMrZZ/fix/h155-fork-function-feedback
🤖 Agent: Requeued after a main merge: the fork-feedback corpus case and its flag are kept beside main's new command corpus cases.
2026-11-08 05:16:22 +01:00
Ludovic Marie 3bea613053 Merge pull request #11890 from MrCloudy2/fix/rider-vehicle-teleport
🤖 Agent: Requeued after a main merge: `lan_e2e.py` keeps both sides' checks; the codec base still isn't reset by `handleTeleportEntity`.
2026-11-08 05:16:18 +01:00
Ludovic Marie a9d293cb18 Merge pull request #12012 from TheMrZZ/fix/h262-enderman-absolute-anger
🤖 Agent: Requeued after a main merge: only persist.rs's test modules conflicted; the absolute anger time read is unchanged.
2026-11-08 05:16:15 +01:00
Ludovic Marie cd8ebdff23 Merge pull request #12032 from MSedgeMC/fix/melee-home-chase
🤖 Agent: Requeued after a main merge: `melee_continue_tests` sits beside main's new goals.rs tests; the home check in `canContinueToUse` is unchanged.
2026-11-08 05:16:11 +01:00
Ludovic Marie 6edc5de20f Merge pull request #12162 from KBroneZ/claude/carry-1-20-folders
🤖 Agent: Requeued after a main merge: in report.rs, main's installed-data-pack branch comes before the carried-mod branch, which still marks 1.20 layouts Partial; port-pack checks clean.
2026-11-08 05:16:08 +01:00
Ludovic Marie 314edb02fc Merge pull request #12166 from KBroneZ/claude/datapack-support-text
🤖 Agent: Requeued after a main merge: all 86 lang files were merged key by key with main, keeping main's new strings and this PR's data pack text.
2026-11-08 05:16:04 +01:00
Ludovic Marie 5e2b6c675f Merge pull request #12177 from TheMrZZ/fix/h171-inline-feature-parse
🤖 Agent: Requeued after a main merge: only game.rs's test-module list conflicted (`inline_feature_parse_tests` beside main's new ones).
2026-11-08 05:16:00 +01:00
Ludovic Marie 01c53f23d2 Merge pull request #12193 from UnQuis/feat/opaque-ice-clean
🤖 Agent: Requeued after a main merge: the `graphics_ui.rs` conflict kept Opaque Ice's switch, and main's tri-state GPU culling no longer has a plain on/off arm there.
2026-11-08 05:15:57 +01:00
voidsip 40aed431b6 Keep native mod diagnostics in the game log 2026-11-07 22:13:47 -06:00
Nikita Maximilian Grimm 4c3cb9a51b Merge hdr-light-function-main (one mark-to-light function, on main) into the written lane 2026-11-08 05:10:32 +01:00
Nikita Maximilian Grimm 2052b918ec Merge remote-tracking branch 'origin/main' into tnt-fall-powder
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-08 05:09:46 +01:00
Horizon agentandClaude Opus 5.5 c23236bceb Fox village stroll: isBrightOutside reads the dimension's fixed time
MobWorld has no end field. Level.isBrightOutside is false in every
dimension with a fixed time (the Nether and the End).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:09:46 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 4ca78266a5 Primed TNT keeps a fall distance and powder snow holds it
Primed TNT is an Entity in vanilla, so `checkFallDamage` adds each step
down, narrowed to a float, to its double fall_distance, which resets on
landing or in water and is saved and read and written by /data. Powder
snow uses that distance: over 2.5 it holds TNT on a 0.9-high top, and
otherwise TNT goes in and is stuck (0.9/1.5/0.9) like in a cobweb. The
stuck multiplier is used on the next move, which then zeroes motion.

Double and float lists in saved entity data now store -0.0 as 0.0, as
`DoubleTag.valueOf` does, so TNT resting on a block reads Motion 0.0d.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 05:09:14 +01:00
Ludovic Marie cf9569747b Merge pull request #12191 from TheMrZZ/fix/h260-level-world-border
🤖 Agent: queued. The level in place reads its own saved `world_border` when the world opens, before any command, so a first `/worldborder set` is no longer overwritten later.
2026-11-08 05:06:47 +01:00
Ludovic Marie 423abdd863 Merge pull request #10280 from MSedgeMC/fix/jukebox-stop-vibration
🤖 Agent: jukebox stop now captures was_playing before clearing j.playing, so the stop vibration fires once. On main merge 904b3036a, sculk, server_player_sculk, server_wool_vibration and mob_command_damage_vibration pass on playhorizon. command_exec's only 2 mismatches are main's gateway_item case (same 16819/16821 on bare main b13dbf068).
2026-11-08 05:06:42 +01:00
Horizon agent 8f0a7f4494 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	launcher/lang/af.json
#	launcher/lang/ar.json
#	launcher/lang/az.json
#	launcher/lang/ba.json
#	launcher/lang/be.json
#	launcher/lang/bg.json
#	launcher/lang/br.json
#	launcher/lang/bs.json
#	launcher/lang/ca.json
#	launcher/lang/cs.json
#	launcher/lang/cv.json
#	launcher/lang/cy.json
#	launcher/lang/da.json
#	launcher/lang/de.json
#	launcher/lang/el.json
#	launcher/lang/eo.json
#	launcher/lang/es.json
#	launcher/lang/et.json
#	launcher/lang/eu.json
#	launcher/lang/fa.json
#	launcher/lang/fi.json
#	launcher/lang/fil.json
#	launcher/lang/fo.json
#	launcher/lang/fr.json
#	launcher/lang/fur.json
#	launcher/lang/fy.json
#	launcher/lang/ga.json
#	launcher/lang/gd.json
#	launcher/lang/gl.json
#	launcher/lang/haw.json
#	launcher/lang/he.json
#	launcher/lang/hi.json
#	launcher/lang/hr.json
#	launcher/lang/hu.json
#	launcher/lang/hy.json
#	launcher/lang/id.json
#	launcher/lang/ig.json
#	launcher/lang/is.json
#	launcher/lang/it.json
#	launcher/lang/ja.json
#	launcher/lang/ka.json
#	launcher/lang/kk.json
#	launcher/lang/kn.json
#	launcher/lang/ko.json
#	launcher/lang/ky.json
#	launcher/lang/la.json
#	launcher/lang/lb.json
#	launcher/lang/li.json
#	launcher/lang/lmo.json
#	launcher/lang/lo.json
#	launcher/lang/lt.json
#	launcher/lang/lv.json
#	launcher/lang/mk.json
#	launcher/lang/mn.json
#	launcher/lang/ms.json
#	launcher/lang/mt.json
#	launcher/lang/nl.json
#	launcher/lang/no.json
#	launcher/lang/oc.json
#	launcher/lang/pl.json
#	launcher/lang/pt-br.json
#	launcher/lang/pt.json
#	launcher/lang/ro.json
#	launcher/lang/ru.json
#	launcher/lang/sah.json
#	launcher/lang/se.json
#	launcher/lang/sk.json
#	launcher/lang/sl.json
#	launcher/lang/so.json
#	launcher/lang/sq.json
#	launcher/lang/sr.json
#	launcher/lang/sv.json
#	launcher/lang/szl.json
#	launcher/lang/ta.json
#	launcher/lang/th.json
#	launcher/lang/tr.json
#	launcher/lang/tt.json
#	launcher/lang/uk.json
#	launcher/lang/ur.json
#	launcher/lang/uz.json
#	launcher/lang/vec.json
#	launcher/lang/vi.json
#	launcher/lang/yi.json
#	launcher/lang/yo.json
#	launcher/lang/zh.json
#	launcher/lang/zu.json
2026-11-08 05:05:11 +01:00
Horizon agent 4b38881802 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-port-pack/src/report.rs
2026-11-08 05:04:10 +01:00
Horizon agent 7daecbbce2 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client-render/src/graphics_ui.rs
2026-11-08 05:03:21 +01:00
TheMrZZandCodex 1f5cd1e43b Preserve joined-family order in unbounded arbitrary entity selectors
Use the existing insertion traversal only at the qualified global selector branch.

Co-Authored-By: Codex <[email protected]>
2026-11-08 05:02:34 +01:00
Horizon agent d6be40bbf7 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:59:35 +01:00
Horizon agent e020e1d440 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:59:17 +01:00
Vinícius MoreiraandClaude Opus 5.5 01edf84d9f Environment attributes: timelines, keyframe tracks and easings
Ports net.minecraft.world.timeline and the keyframe machinery under it:
Timeline (clock, period, tracks, time markers, validateInternal),
AttributeTrack's codec (a modifier, override by default, and keyframes of
its argument), KeyframeTrack.validateKeyframes and validatePeriod,
KeyframeTrackSampler's looping segments and sampling,
argumentKeyframeLerp for every modifier, EasingType (cubic Bézier with
its Newton-Raphson and bisection solve) and all 32 Ease curves, with
Java's float and double steps (jmath, Mth's sine table). The layer stack
takes timelines as time-based layers that read their clock's ticks.

The new harness environment_timeline compares 3,464 cases with the pinned
client (every easing, the vanilla day, moon and early game tracks, and
synthetic and invalid tracks); environment_system now stacks the real
timelines between the biome and weather layers (36,000 lines).

Part of #11486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:59:14 -03:00
Horizon agent 8540619240 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/game/commands.rs
2026-11-08 04:59:13 +01:00
Horizon agent 97020c6abe Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:58:47 +01:00
Horizon agent 0a9ce82a0b Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:58:19 +01:00
Horizon agent 9dda4ce381 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	tools/command_exec_corpus.py
#	tools/test_command_exec_parity.py
2026-11-08 04:58:17 +01:00
Horizon agent 4d91ddc86c Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	tools/lan_e2e.py
2026-11-08 04:58:02 +01:00
Horizon agent e1ae4fb750 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/game/persist.rs
2026-11-08 04:57:35 +01:00
Horizon agent d0dc8f1ad6 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/mobs/goals.rs
2026-11-08 04:57:24 +01:00
Horizon agent 8ac6fa92a1 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:57:04 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 b1ebe3d6e0 Merge origin/main into fn-tick-time
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 04:56:57 +01:00
masa-masa-0314andZCode 8485f4c0ef Realms: the slot pictures, the template pages and the minigame list
- The world slots' pictures follow RealmsWorldSlotButton.State: the
  minigame image (or presets/isles.png when it has none), the empty
  frame, a slot's own template image, then the slot's panorama. The
  atlas now keeps the four slot pictures (the three 1024-tall faces and
  isles.png) at their own size: they were excluded as title/background
  and presets, and even once let through were dropped by the 512-tall
  GUI texture cap.
- WorldTemplate/WorldTemplateList read like JsonUtils' getStringOr,
  getIntOr and getUriNullable: numbers read as their JSON text (some ids
  and player counts are numbers, some counters are strings), and an
  empty link is no link — the row icons are not drawn and no empty URL
  can be opened.
- The template list fetches one page per job and appends it as it
  arrives, chaining the next page until isLastPage or an empty page,
  instead of waiting for every page before drawing the first row.
- The minigame list (RealmsWorldsTab.switchToMinigame) returns to the
  Worlds tab on Back and Escape, not to a reset screen.

Tests: 2250 lib tests pass (71 realms), scoped clippy clean.

Co-Authored-By: ZCode <[email protected]>
2026-11-08 11:56:47 +08:00
Horizon agent f38098f921 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/game.rs
2026-11-08 04:56:27 +01:00
J5CaseyandClaude Opus 5.5 87bb072d77 Native hook: recipe_sources, extra containers recipe placement takes from
`native_recipe_sources(player, menu, pos, sources)` lets a mod name
block containers (chests and the like, mod containers) that recipe
placement into a mod menu type's crafting grid may also take
ingredients from, after the player's inventory, as a crafting station
takes them from the chests beside it. No answer keeps vanilla's
placement.

Part of #12198.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:53:47 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 c7389334f1 A new item's own random makes its UUID, bob offset, yaw and motion
Vanilla's Entity takes its UUID from the first two draws of its own random
(Mth.createInsecureUUID); ItemEntity then draws bobOffs and the yaw from it,
and the constructor without a given motion draws the motion last. Horizon gave
every entity a clock-seeded UUID when first asked, drew a new item's motion
from a fresh random's first draws, its bobOffs from the particle random and a
loaded item's from the level's, and left the yaw at 0.

spawn_item_own makes all four from one own random in that order and replaces
dispenser::new_item_motion at its callers. A loaded or summoned item makes its
UUID (unless the tag has one) and bobOffs from its own random, so summoning no
longer shifts the level's random. Primed TNT from a block takes its UUID from
its own random too.

The seed sync proof now reads those UUIDs, the drop's rotation and motion, and
a TNT kick after a summoned item: 8/15 before, 15/15 after.

Fixes #12217

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 04:53:17 +01:00
itarqos5andClaude Sonnet 5.5 733d34582d tools: redstone_diff.py, whole redstone machines against vanilla one tick at a time
Runs hand-built circuits and random "soups" of redstone components through the real
tick loop in vanilla 26.3 (the bench mod's client, no server, no EULA) and in Horizon
(horizon-ctl), in a frozen world stepped with `tick step 1`, and prints the first tick
where the blocks differ and which ones. Narrowing: --near/--drop reduce a difference
to a few commands.

- RedstoneDiff + ServerLevelTickMixin in the bench mod snapshot the box before the
  first stepped tick and after each.
- `simulation blocks X1 Y1 Z1 X2 Y2 Z2` (horizon-ctl) reads the server's blocks, not
  the window's replica, which lags the server by design.
- agent.rs: `blocks_json`, shared by `blocks` and `simulation blocks`.

Only blocks are compared; entities are recorded, not diffed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-08 03:49:01 +00:00
Nikita Maximilian GrimmandGPT 6.1 Sol aac6bc2c2a HDR: one mark-to-light function for the display pass and the resolve pass
Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-08 04:48:49 +01:00
itarqos5andClaude Sonnet 5.5 af6fc73a51 /setblock and /fill notify neighbours after the shape updates, as vanilla does
Vanilla places a command's block with UPDATE_CLIENTS | UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS
(2|256), so Level.setBlock notifies no neighbour. The shape updates run inside
setBlock; ServerLevel.updateNeighboursOnBlockSet follows afterwards (for /fill,
after every block is in). Horizon placed with UPDATE_ALL (3), so the neighbours
heard of the block before its shape updates ran.

That is visible when the notice makes a block pop off: a comparator with nothing
under it breaks at its first notice and takes an attached wall torch with it. In
vanilla the wire between them had already connected to the torch, so it ends as a
cross; in Horizon the torch was gone first and the wire ended as a dot.

Found by tools/redstone_diff.py (two of 48 random circuits differed on vanilla
26.3 vs Horizon, reduced to four commands); after the change 144 random circuits
over three seeds match vanilla tick for tick.

- Behaviours::update_neighbours_on_block_set ports ServerLevel.updateNeighboursOnBlockSet.
- place_state takes `command`: setblock and fill use the vanilla flags; clone keeps
  its own flow. The strict variants are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-08 03:44:52 +00:00
Ludovic Marie 8bf4597a57 Merge pull request #12167 from J1zeee/fix/12022-piston-push-velocity-restitution
🤖 Agent: queued. Piston restitution bounces the entity's own velocity and runs for server entities only; the ground flag comes from #12168 (queued first).
2026-11-08 04:44:37 +01:00
TheMrZZandCodex gpt-6.1-sol cc3d62a7cd Preserve loaded arrow can_break for Mob block permissions
Carry the actual top-level projectile predicate through ArrowState load/save
and consult the existing matcher only for resolved Mob arrows under both
rules. Refuse unsupported conjuncts and preserve other projectile/drop paths.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-08 04:43:07 +01:00
J5CaseyandClaude Opus 5.5 3042d4068b Recipe placement fills a mod menu type's crafting grid
The recipe book's place packet and Horizon's viewer transfer channel go
to an open mod crafting menu (`lan_mod_craft_apply`) over its block
entity's grid, as a click does, with a ghost recipe when the items are
missing; the client's `native_place_recipe` and `native_transfer_recipe`
accept such a screen, so JEI ports and the Recipes mod fill it as they
fill a crafting table.

Part of #12198.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:41:25 -06:00
Ludovic Marie e1f01aff0b Merge pull request #12161 from TheMrZZ/fix/h141-mannequin-save
🤖 Agent: queued. A mannequin saves `profile`, `hidden_layers`, `main_hand` and `pose` always, and no `Mob` fields, since `Mannequin` is an `Avatar`, not a `Mob`.
2026-11-08 04:40:29 +01:00
Ludovic Marie 9c24961df0 Merge pull request #11830 from TheMrZZ/fix/h122-named-predicate-random
🤖 Agent: queued. Literal `random_chance` predicates in commands now draw from the world's random, as `LootContext` gets `level.getRandom()`; main merged in.
2026-11-08 04:40:25 +01:00
Ludovic Marie bbabaf720b Merge pull request #12000 from masa-masa-0314/feat/realms-ui-batch
🤖 Agent: queued. Realms screens follow vanilla's layout, state and input; the owner-UUID change was reverted (it would orphan tamed pets in Horizon-made worlds), and `under_world` skips parts with ':', with a test.
2026-11-08 04:40:21 +01:00
Ludovic Marie 1e1c77126d Merge pull request #12112 from kacpherek/parity/batch-d
🤖 Agent: queued. Equippable assets for armor, wings, capes and camera overlays; the End flash now uses `random_source::create()` after main dropped `SoundEngine::unseeded`, with a skybox gate in `tick_end_flash`.
2026-11-08 04:40:18 +01:00
Ludovic Marie 933ab57aa1 Merge pull request #12172 from NikitaMGrimm/t3/scheduled-item-tick-pass
🤖 Agent: queued. An item a scheduled block tick drops ticks in that tick's entity pass, as `EntityTickList.forEach` runs after the block ticks; a boat's lily pad drop still waits.
2026-11-08 04:38:14 +01:00
Ludovic Marie c5067a988b Merge pull request #11934 from TheMrZZ/fix/h203-mob-absorption-max
🤖 Agent: queued. Health Boost and Absorption hooks run for every accepted effect and `add_effect` returns its result after them; after #11883, #11959 and #12108.
2026-11-08 04:37:54 +01:00
Ludovic Marie 3936cafd12 Merge pull request #12194 from Solenopsisbot/perf/measurement-tools
🤖 Agent: queued. Startup trace step stats (count, median, p95, RSS) with a test; the compression bench was taken out, since the zlib reuse it measures is not on main.
2026-11-08 04:37:20 +01:00
Ludovic Marie 3b6d2fc635 Merge pull request #11802 from itarqos5/feat/far-tile-packed-quads-clean
🤖 Agent: queued. Far tiles' quads take a quarter of the arena; the decode helpers only tests use are now `#[cfg(test)]`, so clippy is clean.
2026-11-08 04:37:15 +01:00
Ludovic Marie bd6025952f Merge pull request #12138 from itarqos5/feat/auto-gpu-culling
🤖 Agent: queued. GPU culling Auto turns it on where the CPU limits the frame and keeps it only if frame time improves; the client_lib.rs conflict kept both `autotune` and main's `random_source`.
2026-11-08 04:36:42 +01:00
martipops 98abaa9217 Merge remote-tracking branch 'upstream/main' into settings/shell-graphics 2026-11-07 22:36:12 -05:00
Ludovic Marie c6eef4b0b7 Merge pull request #12139 from TheMrZZ/fix/h210-container-name-components
🤖 Agent: queued. Styled container names stay as the `CustomName` tag in the live block model, so a styled chest name survives a break; main's spill test now compares tags.
2026-11-08 04:36:09 +01:00
Ludovic Marie 1fb469a969 Merge pull request #12115 from TheMrZZ/fix/h274-test-guest-view
🤖 Agent: queued. `/test pos` picks the block from a connected source player's view, as `TestCommand` reads `source.getPlayer()`; rustfmt fixed after the main merge.
2026-11-08 04:35:36 +01:00
Ludovic Marie 7adf3992a5 Merge pull request #12197 from martipops/settings/shell-graphics-features
🤖 Agent: queued. Undo, a row's cost and the greyed-row reason are generic shell features with tests; Extras gets no Undo, and Graphics moves onto them in the next PR.
2026-11-08 04:35:15 +01:00
Ludovic Marie 8629067aa4 Merge pull request #11811 from TheMrZZ/fix/chorus-projectile-drops
🤖 Agent: queued. Arrows and snowballs breaking a chorus flower now drop it via `ChorusFlowerBlock.onProjectileHit` (`destroyBlock` with drops); main merged in.
2026-11-08 04:34:42 +01:00
voidsip 9f6d28e257 Discard a removed gateway's server cooldown state 2026-11-07 21:32:07 -06:00
Ludovic Marie ec2c0c8d1f Merge pull request #12011 from NikitaMGrimm/hdr-tone-curve
🤖 Agent: queued. The HDR float frame's tone curve eases highlights into the peak instead of clipping; it is HDR-only, so the SDR path doesn't change.
2026-11-08 04:29:50 +01:00
Ludovic Marie 358c4e0c01 Merge pull request #12150 from RINNECODER/up2/glsl-exact-overload
🤖 Agent: queued. GLSL overload resolution now prefers an exact argument match over a conversion, as the GLSL spec ranks them, so packs that overload on int/float pick the right function.
2026-11-08 04:29:46 +01:00
Ludovic Marie 90b4e7d794 Merge pull request #11821 from vnsmoreira/attributes/layer-stack
🤖 Agent: queued. Environment attributes now come from the layer stack (dimension, then biome with blending, then weather) in `EnvironmentAttributeSystem`'s order; main merged in since the review.
2026-11-08 04:27:14 +01:00
Ludovic Marie 989afe1c00 Merge pull request #11870 from IwantHappiness/translate-ru-lang
🤖 Agent: queued. The remaining Russian strings in the launcher and the game are translated, and the keys match en_us, so no string falls back to English.
2026-11-08 04:27:10 +01:00
Horizon agent 0dc90c1d29 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:26:07 +01:00
Horizon agent 3e4f2a7305 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:25:21 +01:00
Horizon agent 1c9380fa56 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:24:12 +01:00
voidsip 6e5cd517d7 Elide default stored enchantments when saving enchanted books 2026-11-07 21:23:25 -06:00
Ludovic Marie 5a0906f5f4 Merge pull request #12051 from ilguerro/perf/11126-structure-starts-templates
🤖 Agent: queued. A template start is read back only when every child decodes; one unreadable child sends the whole start to #11652's regeneration, so old saves get nothing worse. I couldn't rerun the ignored `saved_starts_match_generated_layouts` here (no prepared resources on this host); your 7/7 run and the parity run decide.
2026-11-08 04:22:28 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 b9404f32c3 Tick functions run before the game time moves on, and before that tick's scheduled functions
MinecraftServer.tickChildren runs the #minecraft:load and #minecraft:tick
functions before the world clocks and the levels tick; the Overworld's
ServerLevel.tickTime then raises the game time and runs the scheduled
functions due at the new time. Horizon raised the game time, the weather and
the day clock first, then ran the scheduled functions and the tick functions
after them, so a tick function read both clocks one tick ahead and a
`schedule ... 1t` from it waited a tick more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 04:19:23 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 951fe53102 Seed sync: run the proof group as a harness of its own
A script that syncs runs on fixed seeds to its end, so in the full command-exec
corpus every group after the proof drew from them, at seeds fixed by whatever
came before. With one more proof case (#12217), "experience orb stuck", whose
orb rarely ends otherwise on random seeds, landed on such a seed and failed on
every run. The group is isolated now and runs as tools/test_seed_sync_parity.py;
the main corpus runs without the agent, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 04:16:28 +01:00
Nikita Maximilian Grimm 7abea17aa3 Merge remote-tracking branch 'origin/main' into fix-fluids-drag-test 2026-11-08 04:06:21 +01:00
Ludovic Marie 0f56e3165a Merge pull request #12227 from horizon-rust/fix/keyring-timeout-12179
🤖 Agent: keyring calls now give up after 20 s on a thread of their own; a call still stuck makes later ones fail at once, so the account lock is never held forever (tested with a keyring that never answers).
2026-11-08 04:05:55 +01:00
Horizon agent 3943b0e8a7 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:05:32 +01:00
Horizon agent f7a3c0f2e4 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:05:24 +01:00
Horizon agent 92b1ae1132 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:05:20 +01:00
Horizon agent 316752b706 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:05:16 +01:00
Horizon agent aa3919d3ae Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:05:15 +01:00
Horizon agent a1afb474a5 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:05:03 +01:00
Horizon agent fdb6ad8b8f Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:04:55 +01:00
Horizon agent 7f505e07dd Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:04:36 +01:00
Horizon agentandClaude Opus 5.5 98b4d049fa launcher: give up on a keyring that never answers (#12179)
A Secret Service daemon that never answers (two keyrings racing for the
D-Bus name, a locked collection with no working prompter) held the
account lock forever: Play stayed on "Starting…" and printed nothing.

Every keychain call now runs on a thread and gives up after 20 s
(Bounded): on Linux the secrets file takes writes as before, and a
sign-in that can't be read says so instead of "no owner". While a
given-up call is still stuck, later calls fail at once. Play prints one
stderr line per step, and `account list` prints why a check failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 04:04:29 +01:00
Horizon agent 32faed9621 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 04:04:03 +01:00
Horizon agent af61f6751e Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/game/persist.rs
2026-11-08 04:03:35 +01:00
abit-foggyandCodex a4df995446 fix(studio): localize timeline marker labels
Co-Authored-By: Codex <[email protected]>
2026-11-07 17:03:20 -10:00
Ludovic Marie 6c2498236d Merge pull request #12222 from horizon-rust/fix/new-world-packs-test-meta
🤖 Agent: queued first. Main's correctness job fails on this test since #12086 met the folder metadata gate (84f695992), and every PR that merges main fails on it; verify is green here.
2026-11-08 04:02:16 +01:00
Ludovic Marie 7ddbb41f86 Merge pull request #12141 from RINNECODER/up2/compute-workgroups-limit
🤖 Agent: queued. A dispatch over 65,535 workgroups per dimension (the wgpu limit) is now split into several dispatches with the base passed along, so packs whose compute pass sizes from the screen still run at 4K and up.
2026-11-08 03:58:06 +01:00
Ludovic Marie 4b38e08b7f Merge pull request #11950 from senjinthedragon/item-entity-material-maps
🤖 Agent: queued. LabPBR `_n`/`_s` maps now reach entities, items, block entities and the hand; `set_shared_material_maps` now runs after `set_custom_sky` in loading_window.rs, so a pack reload binds both.
2026-11-08 03:58:03 +01:00
abit-foggy 5c00a74d4e Merge remote-tracking branch 'upstream/main' into codex/studio-c1-c2-topbar-timeline
# Conflicts:
#	crates/horizon-client/src/game/play_keys.rs
2026-11-07 16:50:47 -10:00
abit-foggyandCodex 858f248202 fix(studio): align C1+C2 replay controls
Co-Authored-By: Codex <[email protected]>
2026-11-07 16:50:04 -10:00
Nikita Maximilian GrimmandClaude Opus 5.5 290560bc52 Expect the float drags in the item flowing-water test
#11794 made the item's water and air drag floats (0.99F, 0.98F), as
vanilla's are; the test still expected the f64 constants, so it fails
wherever the vanilla data is prepared.

Fixes #12221

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:45:25 +01:00
Horizon agentandClaude Opus 5.5 30c20a7a54 datapack test: give the new-world packs a pack section
folder_metadata_present (Pack.readPackMetadata) now requires a pack section
with a description, so the {} metadata in #12086's test hid both packs and
seed_create_world returned None. This failed every PR's verify on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:43:49 +01:00
Ludovic Marie f96d9e89b5 Merge pull request #10283 from MSedgeMC/fix/cloud-save
🤖 Agent: removing an entity's chunk now drops its area-effect clouds too (breath_clouds.retain), and saves keep entity_base_tag's Entity fields. On main merge 8b583a15e, save_roundtrip, entity_nbt_boolean, orb_saved_uuid, stand_fall_save, conversion_water_save, mob_pickup_save and potion_effect_icon pass. command_exec's only 2 mismatches are main's gateway_item case (same on bare main b13dbf068).
2026-11-08 03:41:29 +01:00
Nikita Maximilian Grimm a45b450e56 Merge remote-tracking branch 'origin/main' into block-entities-wait-entities 2026-11-08 03:40:46 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 e6281842d8 Block entities and scheduled ticks wait for their chunk's entities to load
LevelChunk.isTicking and ServerLevel.isPositionTickingWithEntitiesLoaded
also need the chunk's entity section loaded (areEntitiesLoaded). It loads at
the end of a level tick, frozen or not (PersistentEntitySectionManager
.processPendingLoads), empty sections too. A chunk that loads now waits for
the end of the level's next pass before its block entities (bells, conduits,
gateways and sculk blocks included), moving pistons and scheduled ticks run.
The command harness's readiness waits mark their chunks loaded, as the
vanilla oracle's do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:35:18 +01:00
bulkandClaude Opus 5.5 842c094de7 Potent sulfur: find the mobs near a geyser from a grid
Every gassing geyser scanned every mob every 10 ticks, all on the same tick,
and every erupting one every tick. One grid of mob boxes is kept for the block
entity pass, until the mob list's next write; a geyser's own effects and
pushes move no mob, so the grid holds after them.

The mobs still get their effect and push in list order, and the gas reads
blocks only, so finding the reached mobs before any gets its effect changes
nothing.

(cherry picked from commit 2bad442a93, ported to the fields on Game)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:32:06 +00:00
bulkandClaude Opus 5.5 fc55599794 Credit the mob that swung for a guest's effect and sting hits
A cave spider's poison bite or a bee's sting on a guest named the mob
nearest to where the hit came from in X and Z, ignoring height, so a zombie
standing under the spider took the credit (the kill message, the hurt-by
advancement, the guest's revenge target). The event names the mob that
swung, as a plain melee hit does since the previous commit.

(cherry picked from commit 3ab80dc9d0, without its deletion of tools/bench_*.rs)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:32:06 +00:00
bulkandClaude Opus 5.5 12af27a781 Carts: read the carts and mobs near a cart from a grid
Each ticked cart compared its box with every cart, and a moving rideable cart
with every mob twice (and built the mob teams for each). A grid kept for the
tick answers in slot order, as the scans did. The cart grid follows each
ticked cart, is rebuilt when a cart is gone or added, and dropped after a
cart's command; the mob grid holds until the mob list's next write. With
native mods loaded, whose hooks can move either, the scans stay.

(cherry picked from commit 3613b40c6b, ported to the fields on Game)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:32:01 +00:00
Ludovic Marie bca5833f8d Merge pull request #12185 from Ragbie/fix/shulker-hurt-teleport-now
🤖 Agent: queued. A shulker's hurt teleport now runs inside the hurt, before the bullet's levitation, and riders get off where it stood (`unRide`); NoAI shulkers never teleport, as `teleportSomewhere` requires.
2026-11-08 03:31:45 +01:00
bulkandClaude Opus 5.5 ca0da4d9bb JoinList: count the writes, so a cache of the list can tell it is stale
A ListStamp names the list and how many times it was written through
`DerefMut` (every push, insert, retain or slot write). A cache built from
the list keeps the stamp and is rebuilt when the stamp differs; a swapped-in
list (another level's) has another name.

(part of commit 6b826d204a)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:31:42 +00:00
Ludovic Marie 4a8a101391 Merge pull request #12182 from TheMrZZ/fix/h283-built-in-component-delivery
🤖 Agent: queued. Four components (`provides_trim_material`, `provides_banner_patterns`, `can_place_on`, `can_break`) are now encoded in outgoing stacks with the synced registry IDs; anything unsupported drops the whole buffer, as before.
2026-11-08 03:31:41 +01:00
Ludovic Marie 07aab11e71 Merge pull request #12181 from TheApple05/codex/older-server-mapping-generation
🤖 Agent: queued. Every mapping value stays the same; the IDs the translators read come from generated pinned constants, and `--check` catches drift.
2026-11-08 03:31:37 +01:00
bulkandClaude Opus 5.5 fdd3d1e59c Stop walking every mob for each game event and melee hit
A game event posted outside the mob pass (a block placed, a door opened, an
explosion) looked through every mob of the level for the wardens and allays
that can hear it. The listener slots are now kept until the mob list is
written again (the previous commit's stamp), or another level's list is in
place.

Mob id lookups for game events, thorns and a hit's source go through the
mob index instead of a scan. A guest's melee event names the mob that
swung, so the hit credits that mob rather than the one nearest in x and z
to the player.

(cherry picked from commit 6b826d204a without its join_seq part, ported to the fields on Game)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:31:34 +00:00
Ludovic Marie bc21da03bc Merge pull request #12174 from NikitaMGrimm/saved-ticks-startup
🤖 Agent: queued. The server now waits for the saved tickets' chunks before the first tick (`prepareLevels`), so their saved ticks unpack at the time they were saved at; the wait gives up after 600 s.
2026-11-08 03:31:33 +01:00
Ludovic Marie 93fc4b2ba9 Merge pull request #12159 from itarqos5/tools/world-compare
🤖 Agent: queued. Tools only: `world_compare.py` and `perf_bench.py --seed`, no generator change; the seed report it answers is documented with the two seeds compared.
2026-11-08 03:31:30 +01:00
Ludovic Marie f3cc9257df Merge pull request #12080 from KBroneZ/claude/instances-folder
🤖 Agent: queued. `--folder` on the CurseForge `Instances` folder now finds its instances, and a Prism `instances` folder (same name where case is ignored) is not mistaken for it.
2026-11-08 03:31:26 +01:00
bulkandClaude Opus 5.5 8c1f6115d5 JoinList: count the writes, so a cache of the list can tell it is stale
A ListStamp names the list and how many times it was written through
`DerefMut` (every push, insert, retain or slot write). A cache built from
the list keeps the stamp and is rebuilt when the stamp differs; a swapped-in
list (another level's) has another name.

(part of commit 6b826d204a)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:31:25 +00:00
bulkandClaude Opus 5.5 069cc39f05 Carts: find the ticked cart at its slot and move it instead of cloning
push_from_ticked_cart searched the cart list for the ticked cart twice and
copied it in and out whole. The caller knows its slot: the ticked copy is
swapped into the slot for the push, and only the pushed cart is copied back,
over the copy it replaced (clone_from reuses its buffers). Lava hurting a cart
looks there first too.

Without mods a push changes velocities and riders, never the list, so the
cart is still in its slot after it (a debug assertion checks). With native
mods loaded a mount hook can change the list: the copies and the search by id
stay. The loot roll stays with the ticked copy, as #11526 made it: it comes
off before the swap and goes back after.

(cherry picked from commit 206905a2d5, without
the loot roll part of fb69aba537)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:31:22 +00:00
Ludovic Marie 0a407714e0 Merge pull request #12184 from sergue212fbright/fix/lod-slab-visibility
🤖 Agent: queued. Far terrain treats slabs as full cells like stairs, so a waterlogged slab keeps its own material instead of becoming water; the test walks every real slab state.
2026-11-08 03:31:22 +01:00
Ludovic Marie 3bb4e7827c Merge pull request #12164 from KBroneZ/claude/es-empty-shaderpacks
🤖 Agent: queued. An empty `shaderpacks/` (CurseForge and Sodium create it) no longer counts as a shader pack, for folders and archives alike; tests cover both.
2026-11-08 03:31:19 +01:00
Ludovic Marie 546eab04b7 Merge pull request #12168 from NikitaMGrimm/orb-piston-ground
🤖 Agent: queued. After every server push the ground flag is set to `verticalCollisionBelow` (`Entity.move` → `setOnGroundWithMovement`, which runs when `isLocalInstanceAuthoritative`), so a sideways push off a block clears it; #12167 builds on this.
2026-11-08 03:31:15 +01:00
Horizon agentandClaude Opus 5.5 a9fba955bd Leave the compression bench to the zlib reuse change
main still makes a new ZlibEncoder per record, so the bench would compare
two fresh encoders. It belongs with the change that adds the reuse (#12189).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:30:23 +01:00
Horizon agent e74f789659 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-08 03:28:10 +01:00
Horizon agent e02c201c97 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/game.rs
2026-11-08 03:28:04 +01:00
Horizon agentandClaude Opus 5.5 139e83fff8 Opaque Ice: own flag; IceBlock keeps frosted ice for fluids
Fluids read Info::ice through is_ice_class (instanceof IceBlock, frosted
ice included), so excluding frosted ice there changed fluid meshing with
the option off. Regular ice now gets its own opaque_ice flag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:25:30 +01:00
Horizon agentandClaude Opus 5.5 1d6e5d01b5 Piston restitution: the entity's own velocity, server entities only, ground flag from #12168
Restitution bounces the entity's velocity (getDeltaMovement), not the push.
It runs for server entities only, since a player's client moves the player.
It runs even when the step is too small to apply, as Entity.move does.
The ground flag is left to set_pushed_on_ground (#12168), which follows
setOnGroundWithMovement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:22:00 +01:00
Horizon agent 2adedf5570 Merge commit 'refs/cg72/pr-12168' into HEAD 2026-11-08 03:20:30 +01:00
Ludovic Marie 4e6920a319 Merge pull request #11829 from senjinthedragon/entity-motion-objects
🤖 Agent: queued. `at_velocity` now covers boats, minecarts, armor stands, frames, paintings, TNT, falling blocks, block entities and moving pistons; the `falling_block_visible` doc comment is back on its function.
2026-11-08 03:19:38 +01:00
Ludovic Marie c214f59711 Merge pull request #12076 from TheMrZZ/fix/h246-storage-alias
🤖 Agent: queued. A wildcard `data modify storage` that fails part way keeps the edits made so far, as vanilla's in-place NbtPath edit does; main merged in.
2026-11-08 03:19:34 +01:00
Nikita Maximilian Grimm 5e7e654901 Merge remote-tracking branch 'origin/main' into item-escape-gravity
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-08 03:18:38 +01:00
J5CaseyandClaude Opus 5.5 7e4e421224 Native mods: break a block as a player (native_player_break_block)
A helper-only fragment adds `native_player_break_block(uuid, pos,
into_inventory)` (`Host::player_break_block`), so a vein-mining mod can
break blocks as its player without injecting into the private
`Game::break_block`. It runs the game's own player break
(ServerPlayerGameMode.destroyBlock): the player's checks, the
`destroy_block` hook, loot for the held tool and its enchantments, tool
wear, stats, exhaustion and experience. With `into_inventory` the block's
drops go to the player's inventory, the rest dropped from them.

The break now reports whether it removed the block, and a break nested in
another's hook keeps the outer break's own-event position. The acting
guest's spawn protection is kept for their turn so the helper can check
it while the hub is out of reach.

Fixes #12195

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:18:20 -06:00
Horizon agentandClaude Opus 5.5 719fa5e2bd rustfmt game.rs (verify failed on it)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:17:03 +01:00
Horizon agentandClaude Opus 5.5 485323aaaf add_effect: keep the accepted result past the absorption and health boost hooks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:16:51 +01:00
Ludovic Marie 4a374440f4 Merge pull request #11883 from TheMrZZ/fix/h205-mob-health-boost
🤖 Agent: queued. Health Boost raises the max health modifier and clamps health down when it ends, as `HealthBoostMobEffect` does; #11934 builds on it.
2026-11-08 03:15:58 +01:00
Ludovic Marie b99e2087d3 Merge pull request #11848 from TheMrZZ/fix/h174-bell-block-entity
🤖 Agent: queued. Command reads keep the real bell block entity (and copper golem statue) instead of a synthesized one, so `data get block` matches vanilla's NBT; main merged in.
2026-11-08 03:15:55 +01:00
Ludovic Marie b84c97088f Merge pull request #11766 from TheMrZZ/fix/mob-effect-amplifier-codec
🤖 Agent: queued. Effect amplifiers decode as unsigned bytes (`Byte.toUnsignedInt`), so an amplifier of 200 no longer reads as -56; main merged in.
2026-11-08 03:15:51 +01:00
Ludovic Marie 57da7aecbc Merge pull request #11729 from TheMrZZ/fix/h195-command-damage-range
🤖 Agent: queued. `damage` predicate ranges compare the item's damage as `ItemDamagePredicate` does (range on damage, not durability); main merged in.
2026-11-08 03:15:47 +01:00
Ludovic Marie e93afc5ade Merge pull request #11728 from TheMrZZ/fix/summoned-leash-knot-lifecycle
🤖 Agent: queued. A summoned leash knot snaps to the block centre and dies without a fence, as `LeashFenceKnotEntity.survives` checks; main merged in.
2026-11-08 03:15:44 +01:00
Ludovic Marie a7296b75e0 Merge pull request #11708 from TheMrZZ/fix/h032-jukebox-saved-clock
🤖 Agent: queued. A jukebox without a song now saves no `ticks_since_song_started`, as `JukeboxSongPlayer` writes it only while playing; main merged in.
2026-11-08 03:15:40 +01:00
J5CaseyandClaude Opus 5.5 9d25e30101 Mod menu types: a crafting grid that crafts as the crafting table
A content mod's menu type may declare `"crafting": {"grid", "size",
"result"}`: those slots run vanilla's CraftingMenu logic on the menu
engine (live result, consumption and remainders on take, shift-click
crafting, recipe placement), over a grid the block entity keeps. The
result is the menu's own: the block entity never holds it, so hoppers,
comparators and a broken block can't dupe it, and the hub shows guests
the result the game made, again each tick the grid changed.

Part of #12198.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:15:16 -06:00
UnQuis 4543e2f454 Add an Opaque Ice performance option
A Horizon-only option, off by default, that draws regular ice opaque in the solid pass and culls faces between adjacent ice blocks. It follows the public description of Luxium's Opaque Ice and the design note in #11563; no Luxium source was read or copied.

Fixes #12192
2026-11-08 10:14:00 +08:00
Ludovic Marie 36584650ea Merge pull request #12152 from RINNECODER/up2/glsl-atomic-struct-copy
🤖 Agent: queued. Patch in vendored naga: copies of structs or arrays holding atomics go member by member, up to 64 scalars; larger ones stay whole copies, as noted.
2026-11-08 03:12:06 +01:00
Ludovic Marie aee2c63c3b Merge pull request #12143 from RINNECODER/up2/pack-image-formats
🤖 Agent: queued. The added formats (RGB10_A2, RGB10_A2UI, 16-bit SNORM) map to the wgpu formats `image_format` already binds; formats a GPU can't store into are still left out with a note.
2026-11-08 03:12:01 +01:00
Ludovic Marie ef23545cef Merge pull request #12126 from hunixcode/fix/translatable-fallback-literal
🤖 Agent: queued. A translatable with a fallback keeps the fallback as a literal, as `TranslatableContents` does, instead of looking it up as another key.
2026-11-08 03:11:58 +01:00
Ludovic Marie 92c708b3fe Merge pull request #12125 from hunixcode/fix/panel-unspecified-host
🤖 Agent: queued. The panel accepts LAN browsers when bound to 0.0.0.0 or :: only; a loopback bind still refuses them, so nothing new faces the network.
2026-11-08 03:11:55 +01:00
Ludovic Marie c6f935414d Merge pull request #12124 from itarqos5/perf/terrain-interpolant-packing
🤖 Agent: queued. Passing terrain's interpolants in 5 locations instead of 12; visbuffer reads `TerrainOut` only internally, so packs see no difference.
2026-11-08 03:11:51 +01:00
Ludovic Marie 73231e735d Merge pull request #12114 from p-stzhuk/fix/legacy-intel-metal
🤖 Agent: queued. The wgpu-hal change is in `third_party/`, gated to legacy Intel Metal; other GPUs take the same path as before.
2026-11-08 03:11:47 +01:00
Ludovic Marie a71408736f Merge pull request #12093 from vnsmoreira/packs/core-sky
🤖 Agent: queued. Pack `core/sky` and `core/stars` shaders apply only when a resource pack ships them; without one the sky pipeline is unchanged.
2026-11-08 03:11:44 +01:00
TiggerTakkyTTTandCodex fb4805072f Fix ambient particles for datapack biomes
Co-Authored-By: Codex <[email protected]>
2026-11-08 09:11:04 +07:00
Nikita Maximilian Grimm 111c22dd5e Merge remote-tracking branch 'origin/main' into test-randoms-sync 2026-11-08 03:09:04 +01:00
SolenopsisbotandCodex ce08c38337 perf: add opt-in startup and compression benchmarks
Measure startup step distributions and RSS, and compare reused versus fresh zlib streams with deterministic checksums.

Co-Authored-By: Codex <[email protected]>
2026-11-08 13:08:58 +11:00
Ludovic Marie 8d2900e6ce Merge pull request #12113 from kacpherek/parity/batch-e
🤖 Agent: queued. One cost: the stepped tracker paths add a Vec per tracked entity on the tracker tick; small, but it is the hot path, worth a look if MSPT moves.
2026-11-08 03:05:56 +01:00
Ludovic Marie cd1318bf02 Merge pull request #12111 from kacpherek/parity/batch-c
🤖 Agent: queued. Batch: sculk now hears bottles, golems, endermen and frames; portals dismount per vehicle tick as vanilla's `Entity.handlePortal` does.
2026-11-08 03:05:53 +01:00
Ludovic Marie 2f661c08ed Merge pull request #12109 from kacpherek/parity/batch-a
🤖 Agent: queued. Batch of server click answers; each case matches `Mob.interact`/`InteractionResult` and is in the batch's harnesses, which run in parity.
2026-11-08 03:05:49 +01:00
Ludovic Marie 1bf8766c1d Merge pull request #12103 from martipops/controller/direct-craft
🤖 Agent: queued. LT + A crafting a recipe repeatedly is new controller input; servers see the same clicks a mouse would send, so nothing server-side changes.
2026-11-08 03:05:46 +01:00
martipops 9f92bb23b4 Merge remote-tracking branch 'upstream/main' into settings/shell-graphics-features 2026-11-07 21:03:09 -05:00
Ludovic Marie 3e06612e08 Merge pull request #11826 from iseaprojects/i18n/es-es-remaining
🤖 Agent: queued. es.json was merged key by key with main (91 translations kept, main's new keys too), so no Spanish string main added is lost.
2026-11-08 03:02:29 +01:00
Ludovic Marie 15c0246614 Merge pull request #12147 from RINNECODER/up2/port-occludes
🤖 Agent: queued after #12145 (its base, queued). Main merged in and the stack rebuilt on #12145's head; verify is green at this head.
2026-11-08 03:02:25 +01:00
Ludovic Marie face534db3 Merge pull request #12132 from Evan-lhm/fix/launcher-blur-zero-sharp
🤖 Agent: queued. A 0 px blur skips the blur pass, so the plates are sharp and the GPU does no work for it.
2026-11-08 03:02:22 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 64f4bab6f3 Parity harnesses: unseeded randoms and entity ids can be synced between vanilla and Horizon
A test-only Java agent makes vanilla's RandomSupport.generateUniqueSeed step a
uniquifier of the calling thread's own, without the clock; HORIZON_TEST_SEEDS=1
does the same in Horizon's unique_seed. A command script's sync_randoms step sets
that uniquifier, the entity-id counter and the level's random in both engines,
and the "seed sync proof" group compares a drop's position, primed TNT's kick, a
dispensed item and the resting phase of four items exactly. The oracle cache
counts the agent jar as an input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:01:17 +01:00
Horizon agentandClaude Opus 5.5 52d1a0b475 lod/packed: from_bits and from_words are test-only
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:00:41 +01:00
Horizon agentandClaude Opus 5.5 c0fe9adca6 End flash sound: random_source::create (SoundEngine::unseeded left main)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:00:37 +01:00
Horizon agent 992ea05825 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 03:00:37 +01:00
Horizon agentandClaude Opus 5.5 2e11de8943 Compare spill test names as Tags (block_names holds the CustomName tag now)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:00:32 +01:00
Horizon agent 7351ad6d91 Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/client_lib.rs
2026-11-08 03:00:31 +01:00
Ludovic Marie 0a6eca805d Merge pull request #12154 from RINNECODER/up2/pack-comment-settings
🤖 Agent: queued. Comment settings end at their line, as the Iris probes in `read_stage` show it reads them line by line; live code still reads to the `;`.
2026-11-08 02:59:34 +01:00
Horizon agent e949fd4cc1 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 02:58:50 +01:00
Ludovic Marie ed0be44325 Merge pull request #12117 from sergue212fbright/fix/sign-text-formatting
🤖 Agent: queued. Bold is drawn as the shifted second pass and italic as the skew vanilla's `BakedGlyph` uses, and after the #11863 merge styled glyphs keep the HDR emission tier; the 102 sign cases pass.
2026-11-08 02:58:24 +01:00
Ludovic Marie 97e46ce1d5 Merge pull request #12050 from TheMrZZ/fix/h140-nautilus-cooldown-memory
🤖 Agent: queued. The Nautilus cooldown memory now exists only while it counts down and is erased at 0, as `Brain.setMemoryWithExpiry` does; its harness runs in parity.
2026-11-08 02:58:20 +01:00
Ludovic Marie 5669d66de3 Merge pull request #11990 from TheMrZZ/fix/h285-adventure-predicate-saved-forms
🤖 Agent: queued. A one-block predicate now saves as the bare id and partial `custom_data` keeps only the keys given, which is how `BlockPredicate`'s codec writes them; the residual corpus documents what is left.
2026-11-08 02:58:17 +01:00
Ludovic Marie f54fba8726 Merge pull request #12123 from NikitaMGrimm/tnt-piston-ground
🤖 Agent: queued. A sideways push leaves `onGround` false, as `PistonMovingBlockEntity.moveCollidedEntities` only sets it for upward pushes; main merged in since my review, no other change.
2026-11-08 02:58:13 +01:00
Ludovic Marie f86b98b203 Merge pull request #12118 from NikitaMGrimm/minecart-drop-motion
🤖 Agent: queued. A destroyed minecart drops its item and contents with `Containers.dropContents`' motions; same items, now in vanilla's spread.
2026-11-08 02:58:10 +01:00
Ludovic Marie 9842e75046 Merge pull request #12107 from martipops/settings/shell-fixes
🤖 Agent: queued. Building the settings rows once removes the per-frame rebuild, and Down from the search field lands in the list.
2026-11-08 02:58:07 +01:00
Ludovic Marie 99956fff22 Merge pull request #12106 from martipops/controller/nintendo-buttons
🤖 Agent: queued. The Nintendo row picks by position or by letter only in the glyph table; the bindings themselves don't move.
2026-11-08 02:58:03 +01:00
Ludovic Marie b23ad347d1 Merge pull request #12105 from NikitaMGrimm/execute-block-nbt
🤖 Agent: queued. `execute if block`, `fill` and `clone` now compare the block entity's NBT part of the predicate, as `BlockPredicateArgument` does.
2026-11-08 02:58:00 +01:00
Ludovic Marie 350e156a34 Merge pull request #12088 from KBroneZ/claude/datapack-jars-launcher
🤖 Agent: queued. Last of the series, after #12087: a profile with only data packs now plays instead of reporting nothing to install.
2026-11-08 02:57:55 +01:00
Ludovic Marie 502c15aba6 Merge pull request #12086 from KBroneZ/claude/new-world-datapacks
🤖 Agent: queued. First of the 12086 → 12087 → 12088 series (each includes the one before): new worlds get the game folder's `new-world-datapacks`, copied at creation only.
2026-11-08 02:55:14 +01:00
Ludovic Marie 147980da63 Merge pull request #12082 from KBroneZ/claude/found-on-this-computer
🤖 Agent: queued. Only reads other launchers' folders (no writes), and the 86 lang files carry the new strings.
2026-11-08 02:55:09 +01:00
Ludovic Marie 97e99a45b4 Merge pull request #12073 from KyttuXD/fix/metal-cutout-leaves-derivatives
🤖 Agent: queued. Metal now always draws vanilla terrain flat, whatever the section count, which is the path that was already used under the threshold.
2026-11-08 02:55:05 +01:00
Ludovic Marie 37cda82c81 Merge pull request #12060 from ZiQu-dev/fix/oit-cull-depth-metal
🤖 Agent: queued. The 4-ulp depth tolerance fixes the speckles on Metal where the OIT pass's depths differ by a few ulps from the opaque pass's.
2026-11-08 02:55:01 +01:00
Ludovic Marie c76ed64570 Merge pull request #12058 from Mik00000/perf/dimension-tick
🤖 Agent: queued. Ending the tick on the first level skips the dimension swap that did nothing, and the ray chunk cache is per raycast, so no stale chunk outlives one ray.
2026-11-08 02:54:58 +01:00
Ludovic Marie f63ad014e1 Merge pull request #12048 from ilguerro/perf/9996-load-palres
🤖 Agent: queued. One cost to know: the registry-wide cache has 8192 slots that are never reclaimed; past that it falls back to decoding, so it only stops helping, it doesn't grow.
2026-11-08 02:54:54 +01:00
Ludovic Marie 7b33d702f5 Merge pull request #12047 from ilguerro/perf/9996-load-packed
🤖 Agent: queued. The SWAR check tests 8 palette indices per word and has an exhaustive test against the scalar loop, so a bad index is still caught at the same position.
2026-11-08 02:54:50 +01:00
Ludovic Marie dfae932fec Merge pull request #12016 from MSedgeMC/fix/drowned-trident-continue
🤖 Agent: queued. The trident attack continues while `alive && (holding a trident || !nav.done)`, which is vanilla's condition rewritten; a drowned that drops its trident now switches to melee.
2026-11-08 02:54:47 +01:00
Ludovic Marie bf3a5f162f Merge pull request #12008 from MSedgeMC/fix/cat-tempt-tamed
🤖 Agent: queued. A tamed cat no longer starts the tempt goal, as `Cat.TemptGoal`'s `canUse` returns false once tamed.
2026-11-08 02:54:43 +01:00
Ludovic Marie 14fc6d55e0 Merge pull request #11985 from TheMrZZ/ci/overlap-note-faster
🤖 Agent: queued. Tools only: one `git cat-file --batch-check` for the heads instead of a process per PR, and the diffs fetched in parallel; same notes out.
2026-11-08 02:54:39 +01:00
Ludovic Marie 4e6a8131c2 Merge pull request #11980 from MSedgeMC/fix/trade-start-conditions
🤖 Agent: queued. `TradeWithPlayerGoal.canUse` also stops on hurt and on distance > 16; it reads `cx.w.player` like the existing LookAtTradingPlayer goal does, so guests on a server share that approximation.
2026-11-08 02:54:36 +01:00
Ludovic Marie 01451da341 Merge pull request #11977 from MSedgeMC/fix/ghast-still-float
🤖 Agent: queued. The happy ghast's still timeout now ends the float goal as in vanilla, so a parked ghast stays put instead of drifting.
2026-11-08 02:54:32 +01:00
Ludovic Marie 179ebb840a Merge pull request #11965 from MSedgeMC/fix/cube-jump-passenger
🤖 Agent: queued. A ridden cube mob now skips its jump-move as vanilla's `SlimeMoveControl` does while it is a passenger, so a slime on a boat no longer hops off its seat.
2026-11-08 02:54:28 +01:00
Ludovic Marie fca63b5eb8 Merge pull request #11868 from MrCloudy2/fix/rider-teleport-look
🤖 Agent: queued. Matches `ClientPacketListener.handleMovePlayer`: a passenger keeps its seat when the server's position packet comes, instead of snapping out of the vehicle for a tick.
2026-11-08 02:54:25 +01:00
Horizon agentandClaude Opus 5.5 c1cdeb19d4 rustfmt client_lib.rs (verify failed on it)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:50:17 +01:00
J1zeee b03127ab97 Merge fork/fix/12022-piston-push-velocity-restitution 2026-11-08 04:44:47 +03:00
Horizon agentandClaude Opus 5.5 1f9493c4fc Keep falling_block_visible's doc comment on it
The motion helpers went in between the comment and the function it describes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:44:31 +01:00
Nemotron 9524516752 Fix piston push not zeroing entity velocity in lazy chunks (#12022)
move_pushed applied the resolved movement to position only, leaving the
entity's velocity untouched. In a ticking chunk the entity's own tick
masks this (PrimedTnt::tick_among restitutes), but in a lazy chunk the
velocity survives: a primed TNT pushed by a piston into a wall, ceiling
or slime keeps 0.4 / -0.8 / -0.8 instead of vanilla's 0 / 0 / 0.64.

Add restitute_piston after apply_push: compare the post-piston-limit
movement (limited) with the post-collision result (resolved) and, as
Entity.move(MoverType.PISTON, …) does, zero blocked horizontal axes,
zero or slime-bounce the vertical axis, and update on_ground. Covers
Player, Guest and every Entity kind including PrimedTnt.

Add unit test a_pushed_tnt_loses_velocity_into_a_wall (needs prepared
resources) asserting the TNT's vx is zeroed by a wall.

Co-Authored-By: Nemotron <[email protected]>
2026-11-08 04:36:37 +03:00
Horizon agentandClaude Opus 5.5 a465c3efae rustfmt (verify failed on it)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:30:39 +01:00
Horizon agent 904b3036ab Merge remote-tracking branch 'origin/main' into m10280 2026-11-08 02:29:41 +01:00
Horizon agentandClaude Opus 5.5 85d56215e6 Merge main into #11826
es.json: main's file with this PR's 91 translations applied key by key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:28:45 +01:00
Horizon agentandClaude Opus 5.5 ebf06768f1 Merge main into #11950
Main moved build_renderer to game/loading_window.rs; the shared material maps
are set there now, after the custom sky as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:28:17 +01:00
Horizon agentandClaude Opus 5.5 fd03679d85 Merge main into #11829
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:27:35 +01:00
Horizon agentandClaude Opus 5.5 27ed9c66f7 Merge main into #11821
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:27:34 +01:00
Horizon agent 738861aae2 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 02:26:57 +01:00
Horizon agentandClaude Opus 5.5 c7ff85fdf4 Realms: keep the single-player owner UUID; skip drive and stream parts in downloads
- Merge main.
- The owner switch from the offline UUID to the account UUID (integrated.rs,
  lan/conn.rs, lan/playerdata.rs, net.rs, remote.rs) is left out: every world
  Horizon made names its player by the offline UUID, so tamed pets and other
  owner references would no longer know their player. It needs its own PR
  with a migration.
- A tar entry part with a colon (a drive prefix or an alternate data stream)
  would leave the world folder on Windows: skip it, with a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:26:29 +01:00
Horizon agent 175c2d453a Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 02:25:49 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 673d5cff49 Read the escape case exactly now that the float drags have landed
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:24:42 +01:00
Evrim CicekandClaude Opus 5.5 ca896819d7 rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 04:24:28 +03:00
GlockSmithandOpenAI Codex GPT-6 0a8df72a16 Keep slab materials in distant terrain
Retain top and bottom slab states in LOD chunk summaries instead of
discarding dry slabs or replacing waterlogged slabs with water. Use the
same full-cell approximation as the existing partial-block filter.

Check real summaries, coarse reduction and emitted faces for every
prepared slab state. All 72 LOD tests pass, including resource-backed
coverage of 606 slab states across 101 materials.

Refs horizon-rust/horizon#12180.

Co-Authored-By: OpenAI Codex GPT-6 <[email protected]>
2026-11-07 20:23:37 -05:00
Ludovic Marie b13dbf0687 Merge pull request #11837 from yahya-nusseibeh/fix/control-socket-path
🤖 Agent: queued. When `/tmp` is shared the socket goes into a private `horizon-<uid>` folder, so another user on the machine can't connect to or squat on the control socket.
2026-11-08 02:20:33 +01:00
Ludovic Marie 0cdb230b54 Merge pull request #11815 from ilguerro/fix/thorns-rest
🤖 Agent: queued at a3fd3597f (main merged in; the draw now uses `random_source::entity()`). Thorns rolls in EquipmentSlot order from the wearer's own random, as `EnchantmentHelper.doPostAttackEffects` does.
2026-11-08 02:20:29 +01:00
Ludovic Marie 6e919e4356 Merge pull request #11806 from MrCloudy2/fix/shield-disable-cooldown
🤖 Agent: queued. The defender now gets the Cooldown packet the server sets on the shield (`Player.disableShield`), so its client greys the shield out for the 100 ticks instead of letting it block client-side.
2026-11-08 02:20:26 +01:00
Ludovic Marie 92cf9ac888 Merge pull request #11799 from Detimes/fix-old-attribute-names
🤖 Agent: queued at 14bfb672f (main and #11750 merged in). UPDATE/REMOVE_MOB_EFFECT ids are renumbered for older clients; effects they don't know are dropped instead of showing as another effect.
2026-11-08 02:20:22 +01:00
Ludovic Marie 0961939b71 Merge pull request #11791 from MrCloudy2/fix/spear-stab-players
🤖 Agent: queued. One cost to keep in mind: `stab_players_for` builds a Vec for every guest using any item each tick (shields, food too); small, but a follow-up could return early when the item is not a spear.
2026-11-08 02:19:16 +01:00
Ludovic Marie 2cd05e462e Merge pull request #11789 from MSedgeMC/fix/camel-sit-room
🤖 Agent: queued. Same check as `Camel.canCamelChangePose` (the standing box against the blocks above), and the test uses a block at y+2 that blocks only the 2.375-tall standing pose.
2026-11-08 02:19:11 +01:00
Ludovic Marie 541f331f1e Merge pull request #11762 from Mayonesu0/perf/launcher-write-data-file
🤖 Agent: queued. The data file is written off the UI thread after `complete_assets`, and a stale one is dropped when the assets change, so a repaired install doesn't read an old index.
2026-11-08 02:19:07 +01:00
Ludovic Marie 973287971d Merge pull request #11759 from doodlyyousuf/251107-fix-guest-left-mob-xp
🤖 Agent: queued. Matches `LivingEntity.dropExperience`/`dropCustomDeathLoot`: experience and equipment follow `lastHurtByPlayerMemoryTime > 0`, while LAST_DAMAGE_PLAYER still needs the player to be resolvable, and the new test checks both sides.
2026-11-08 02:19:04 +01:00
Ludovic Marie 7648d874b9 Merge pull request #11750 from Detimes/fix-11722-old-pick-item
🤖 Agent: queued at fee1085be (main merged in). A 1.21.3 pick_item now becomes the same container swap a 1.21.4+ client sends, so older clients keep middle-click in survival.
2026-11-08 02:19:00 +01:00
Ludovic Marie b91f5f5892 Merge pull request #11741 from yahya-nusseibeh/fix/server-undrained-packets
🤖 Agent: queued. The count goes up at the one `NetEvent::Packet` send in `conn.rs` and down at the hub's drain, so the 2× inbox cap bounds what a flooding client can queue between ticks without touching the hot path otherwise.
2026-11-08 02:18:57 +01:00
Ludovic Marie f159a106a8 Merge pull request #11713 from Akirabane/feat/transfer-stop-wait
🤖 Agent: queued. The stop waits only with `[transfer]` on, and its 90 s bound stays under the supervisor's 120 s kill, so a proxy that never answers can't hang a stop. Built with 14 other PRs on main (pr_ready --quick green apart from known NixOS-only tests).
2026-11-08 02:18:54 +01:00
Ludovic Marie c805ee70c5 Merge pull request #11782 from Teiwazik/render/native-section-fade
🤖 Agent: I moved the distance blend per pixel (it was per triangle through the flat hdr_code). Before/after screenshots and frame time are in my comment: the pack's GPU frame is 121.1 vs 122.0 ms on lavapipe, same within noise.
2026-11-08 02:18:50 +01:00
TheMrZZandCodex 074aa1124f Encode four built-in item components for outgoing inventory stacks
Preserve typed holder and adventure-predicate payloads at the inventory bridge.

Co-Authored-By: Codex <[email protected]>
2026-11-08 02:15:11 +01:00
Horizon agent 14bfb672f8 Merge #11750 into #11799 (both add the last tests of client_session.rs)
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-protocol/src/adapter/client_session.rs
2026-11-08 02:14:29 +01:00
Horizon agent bf321a8425 Merge #11789 into #11792 (both add the last tests of camel.rs)
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/mobs/camel.rs
2026-11-08 02:14:01 +01:00
Horizon agent 2fdc1509ae Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 02:13:52 +01:00
TheApple05andCodex GPT-6 703c0ea18b Generate pinned adapter IDs and record regeneration recipes
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-08 01:13:25 +00:00
abit-foggyandCodex GPT-6 d15f455027 fix(studio): show replay UI and release cursor
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 15:08:30 -10:00
Nikita Maximilian Grimm 23f0fd6675 Merge remote-tracking branch 'origin/main' into item-escape-gravity 2026-11-08 02:06:55 +01:00
Horizon agent 8b583a15e1 Merge remote-tracking branch 'origin/main' into m10283
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-08 02:06:02 +01:00
Florian ErnstandClaude Opus 5.5 48782a8231 Refuse a malformed inline /place feature while the command is parsed
ResourceOrIdArgument decodes an inline value with the registry's codec
while the command is parsed, so a feature the ConfiguredFeature codec
refuses fails the parse: the command never runs, and an execute store
around it keeps its value. Horizon's parse accepted any compound for
minecraft:worldgen/feature and ran the codec only when the command
executed, which then failed and stored 0.

Where the server has its live features, the command registries now carry
a check that runs the same inline decode placement uses (the live
features' catalog and block bindings, through LiveFeatures::decode_inline),
without placing anything. A value it refuses fails the parse with
argument.resource_or_id.failed_to_parse. Without live features (a client,
or a server without the worldgen bundle) the parse is unchanged. The loot
table and every other registry keep their decode.

The message is the native codec's own (for example "invalid world
generation field: to_place"), not DataFixerUpper's text.

Fixes #12171.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:02:45 +01:00
Horizon agentandClaude Opus 5.5 43832ec794 Merge #12145 into #12147 (both change the map_color line)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:58:49 +01:00
Horizon agentandClaude Opus 5.5 d2d9dd7ae1 Merge main into #12112
The End flash moved to tick_end_flash here, while main (0b23212f4) switched
the flash and the dragon fight to the dimension type: keep main's
has_ender_dragon_fight check, and gate tick_end_flash on the End skybox as
main did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:58:14 +01:00
Evrim CicekandClaude Opus 5.5 c0a3af67b0 A teleporting shulker throws off whoever rides it where it stood (Entity.unRide)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:57:52 +03:00
Horizon agentandClaude Opus 5.5 acf0cabce9 Merge main into #12110
main (3443abbde) kept NoAI Nautilus out of the needs_water branch; this PR
gives every Nautilus its own handler, which already refills NoAI ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:57:46 +01:00
Ludovic Marie bc6016d19d Merge pull request #12157 from horizon-rust/agent/older-servers-8718
🤖 Agent: Follow-up to #8718. On main, lan_bot's older_clients_of_each_release_join_and_are_sent_chunks fails at 1.21.1 (the reverse step never adds 1.21.2's particle status to ClientInformation); CI misses it because the test returns early without prepared resources. With this it passes, as do all 440 horizon-protocol tests and, on the union, the particle harnesses block/emitter/entity/marker/native_client_particles, particle_providers, player_effect_amplifier and spell_ticks (8/8).
2026-11-08 01:55:30 +01:00
Horizon agent 72e6ef91db Merge #12108 into #11934 (same effect and attribute code)
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/game/commands/world_cmds.rs
#	tools/test_command_exec_parity.py
2026-11-08 01:53:30 +01:00
Horizon agent ab069b576c Merge #11959 into #11934 (same effect and attribute code)
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/mobs.rs
2026-11-08 01:53:27 +01:00
Horizon agent f521237d6c Merge #11883 into #11934 (same effect and attribute code)
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/game/commands/effects.rs
#	crates/horizon-client/src/game/potions.rs
#	crates/horizon-client/src/mobs.rs
#	crates/horizon-client/src/mobs/ai.rs
#	tools/test_command_exec_parity.py
2026-11-08 01:53:24 +01:00
Nikita Maximilian Grimm 18bbc46240 Merge remote-tracking branch 'origin/main' into item-escape-gravity 2026-11-08 01:53:09 +01:00
Florian ErnstandClaude Opus 5.5 a75a57bd18 Load the world border of the level in place when the world opens
Each level reads its world_border SavedData when it is made
(ServerLevel.getWorldBorder), so a restarted server has the saved border
in place before its first command. #11016 gave each level its own
border. But world open reset the border of the level in place to the
default, and the saved file was read only later, in load_scoreboard (the
first tick's functions, or the first scoreboard use). A first
/worldborder get after a restart read the default, and a first
/worldborder set was put back to the saved size soon after.

World open now reads the in-place level's border with load_border, as
open_level does for the other levels, and load_scoreboard no longer
touches the border.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:51:14 +01:00
Nikita Maximilian Grimm aed804a26d Merge remote-tracking branch 'origin/main' into saved-ticks-startup 2026-11-08 01:49:01 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 8ce0848a31 Harness: stop a server that never finishes starting
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:48:34 +01:00
Nikita Maximilian Grimm 48c080e387 Merge remote-tracking branch 'origin/main' into t3/scheduled-item-tick-pass 2026-11-08 01:48:27 +01:00
Horizon agentandClaude Opus 5.5 02e546660a Merge main into #12115
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:46:54 +01:00
Horizon agentandClaude Opus 5.5 46e77b05a8 Merge main into #12108
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:46:51 +01:00
Horizon agentandClaude Opus 5.5 3c73be2517 Merge main into #12076
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:46:42 +01:00
Evrim CicekandClaude Opus 5.5 917ce67f0d Test: a shulker bullet's hit teleports an open shulker before it returns
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:46:37 +03:00
Evrim CicekandClaude Opus 5.5 b11fe1da84 A shulker's hurt teleports it inside the hurt, as vanilla's does
Shulker.hurtServer calls teleportSomewhere() and hitByShulkerBullet() inside
the hurt. Mob::damage has no world, so the flags it leaves now run right
after the hurt: in the mob's own tick (hurt_teleports, also without AI) and
in the game layer (settle_hurt_teleports: /damage, explosions, projectile
hits, the creature outbox), before a bullet's levitation. teleportSomewhere
also refuses a NoAI shulker, keeps inside the world border and unRides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:46:36 +03:00
Evrim CicekandClaude Opus 5.5 fdb23b8ac6 Harness: a shulker's low-health teleport inside the hurt (/damage while frozen, poison past tick 281, NoAI)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:46:36 +03:00
Horizon agentandClaude Opus 5.5 ac85e523c7 Merge main into #12012
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:44:51 +01:00
Horizon agentandClaude Opus 5.5 386ab14035 Merge main into #11959
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:44:40 +01:00
Horizon agentandClaude Opus 5.5 ca82b37eb0 Merge main into #11934
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:44:15 +01:00
Horizon agentandClaude Opus 5.5 a505caa32a Merge main into #11883
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:43:50 +01:00
Horizon agentandClaude Opus 5.5 9aa5c9fe4a Merge main into #11879
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:43:47 +01:00
Horizon agentandClaude Opus 5.5 c7a2daa593 Merge main into #11848
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:43:43 +01:00
Horizon agentandClaude Opus 5.5 3584268d11 Merge main into #11830
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:43:26 +01:00
Horizon agentandClaude Opus 5.5 bf1070413f Merge main into #11811
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:43:18 +01:00
Horizon agentandClaude Opus 5.5 2573d1c76a Merge main into #11783
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:43:07 +01:00
Horizon agentandClaude Opus 5.5 3a967d8838 Merge main into #11766
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:42:56 +01:00
abit-foggyandCodex GPT-6 000e13fbe6 test(studio): isolate mouse drag hook fixture
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 14:42:49 -10:00
Ludovic Marie 40e3f368da Merge pull request #11720 from Teiwazik/seat/follow-plugin-seat-chains
🤖 Agent: I pushed 9bc110bae. The new second position_riders() call after the player moves rebuilt the whole mob index on every tick for every client; it now runs only when the riding graph has something on this player. I also added the missing passenger_vehicles field to main's studio Remote initializer (it did not compile on main) and drop passengers whose vehicle is removed. Both ignored tests pass with prepared resources, and so do the riding harnesses on a union with current main: boat_authority, boat_rider, boat_paddle_reset, mob_rider_navigation, mount_submerged, server_entities, vehicle_command_damage, dedicated_server (8/8).
2026-11-08 01:42:48 +01:00
Horizon agentandClaude Opus 5.5 bd967852e5 Merge main into #11729
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:39:31 +01:00
Horizon agentandClaude Opus 5.5 ecdecc8fd2 Merge main into #11728
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:38:55 +01:00
Horizon agentandClaude Opus 5.5 c4c084be94 Merge main into #11708
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:38:51 +01:00
abit-foggyandCodex GPT-6 6c5d89ffac fix(studio): own marker archive entry names
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 14:34:05 -10:00
Nikita Maximilian Grimm 6e72e2de7d Merge branch 'tnt-piston-ground' into orb-piston-ground 2026-11-08 01:29:33 +01:00
Nikita Maximilian Grimm 8b0028bbeb Merge remote-tracking branch 'origin/main' into t3/scheduled-item-tick-pass 2026-11-08 01:28:12 +01:00
abit-foggyandCodex GPT-6 e69f6a5050 feat(studio): add replay top bar and timeline
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 14:25:03 -10:00
itarqos5andClaude Sonnet 5.5 7c34cfa6b2 tools: world_compare.py compares a vanilla and a Horizon world of one seed
Reads the seed, spawn, biomes, structure starts and blocks two saved 26.x worlds
share, with a run-to-run floor from a second world of one game. Run on seed 12345
and a large negative seed: the spawn, every biome and every structure start match,
terrain blocks match to 99.3 to 99.9%, and decoration sits at vanilla's own floor
except trees, a few points under it. perf_bench.py gets --seed to make the worlds.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-08 00:21:56 +00:00
Ludovic Marie b399f0ddc5 Merge pull request #11775 from Teiwazik/older-servers/sign-update-order
🤖 Agent: Checked against the 26.3 client jar: ServerboundSignUpdatePacket's codec is pos, fixedSizeList(4) of stringUtf8(384), then SignTextSlot as an idMapper VarInt (BACK=0, FRONT=1), so reading the side last and writing it as the old boolean after the position is right. It only runs in the older-server adapter, so 26.3 servers are untouched. I merged main (the #8718 conflict in translate.rs: kept #8718's arms plus this one); 440 horizon-protocol tests and clippy pass.
2026-11-08 01:18:50 +01:00
Horizon agentandClaude Opus 5.5 a3fd3597f4 Thorns: draw from random_source::entity(), which replaced dispenser::entity_random on main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:16:10 +01:00
Horizon agent 1d9f455dac Merge remote-tracking branch 'origin/main' into HEAD 2026-11-08 01:15:53 +01:00
Horizon agent f97dffe988 Merge remote-tracking branch 'origin/main' into pr-11775
# Conflicts:
#	crates/horizon-protocol/src/adapter/translate.rs
2026-11-08 00:15:30 +00:00
KBroneZandClaude Opus 5.5 c6f52257e2 fix: count 1.20 recipe results in the reason only when there are some
The partial reason of a carried 1.20 mod leaves out the recipe clause
when no result names `item`, and says "1 recipe result names" for one.
docs/modpacks.md says how the game treats each 1.20-shaped file, as an
offscreen run of a carried synthetic 1.20 jar showed: one file at a
time, never the whole start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 02:12:22 +02:00
Florian ErnstandClaude Opus 5.5 07d0cfc344 Format the mannequin main-hand writer
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:11:37 +01:00
Horizon agentandClaude Opus 5.5 949eef6772 Russian launcher strings: fix the JSON and a placeholder
A missing comma after the horizon-server line made ru.json unreadable, so
the whole launcher fell back to English (the i18n tests failed on it).
The {mods} placeholder had been translated, so the count would never be
filled in. Also "подключиться" for two "Couldn't connect" lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:08:05 +01:00
KBroneZandClaude Sonnet 5.5 ecce33154e Launcher: installing a data pack counts what the game reads today
datapacks::READ named four kinds, so a pack of only recipes, loot tables, advancements or
worldgen was refused as changing nothing, and the install note listed them as not read. READ
now lists the kinds the game loads (worldgen by folder, so world presets still count as not
read), the refusal goes through trf(), and docs/datapack-upgrade.md no longer says worldgen is
not applied.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 02:07:21 +02:00
itarqos5andClaude Sonnet 5.5 d6f88d2483 feat(render): GPU Culling gets an Auto mode that tries it where the CPU limits the frame
GPU Culling pays where the CPU is the slower of CPU and GPU and costs where the
GPU is, and a machine's parts don't say which. Auto watches the frames' median CPU
and GPU times, tries it where the CPU is clearly the slower one, and keeps it only
if the frame's busier side dropped under 97%; a trial that didn't help is undone and
waits 5 minutes, then 20, then for good.

gpuCulling in horizon-graphics.txt is now false|true|auto (older files read as before);
Settings > Performance steps Off/On/Auto; horizon-ctl gpu-culling takes auto. Off stays
the default and no preset sets it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-08 00:04:36 +00:00
TheMrZZandCodex gpt-6.1-sol 0cdc4a49da Preserve styled container names in the live block model
Carry admitted Component tags through name state, saves and drops; let modeled name removal override stale source names.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-08 01:02:29 +01:00
Horizon agentandClaude Opus 5.5 fee1085bec Merge main into fix-11722-old-pick-item
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:02:24 +01:00
Horizon agentandClaude Opus 5.5 272518c1f2 Merge main into fix-old-attribute-names
Main already carries the 1.21.1 and 1.20.6 attribute tables (consolidated in
d79a36101); kept main's generated tables and this branch's mob effect renumbering.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:02:00 +01:00
abit-foggyandCodex GPT-6 68459f0442 feat(studio): persist timeline markers
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 14:02:00 -10:00
Nikita Maximilian Grimm 2877c7fbfa Merge remote-tracking branch 'origin/main' into saved-ticks-startup 2026-11-08 01:01:52 +01:00
KBroneZandClaude Sonnet 5.5 5be2aba2ae style(port-pack): rustfmt the shaderpacks test
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 02:01:09 +02:00
Nikita Maximilian GrimmandClaude Opus 5.5 6b371cdc48 HDR float frame: the frame follows HDR and the pack picked at once
Under HORIZON_HDR_FRAME=float, when HDR, Smooth Gradients or the pack picked call for another
frame than the renderer's, the renderer is made again on the same device before the next frame
draws, and the world is meshed again, as after a lost device. Without the switch nothing changes:
the frame stays until the next start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:00:38 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 1b63e0abc2 Startup waits for the forced chunks before the first tick, so saved ticks there fire on time
MinecraftServer.prepareLevels waits for the chunks the restored tickets hold
(ChunkLoadCounter) before the first tick, and the first tick unpacks their
saved block and fluid ticks at the game time they were saved at. Horizon's
dedicated and integrated servers started ticking while the forced chunks were
still streaming in, and the saved ticks were unpacked from the tick the chunk
arrived, one tick or more late.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:58:28 +01:00
Nikita Maximilian Grimm 9ab82c59cd Merge main into hdr-tone-curve: #11987 is on main now 2026-11-08 00:56:51 +01:00
Nemotron e0cbbdb50a Fix piston push not zeroing entity velocity in lazy chunks (#12022)
move_pushed applied the resolved movement to position only, leaving the
entity's velocity untouched. In a ticking chunk the entity's own tick
masks this (PrimedTnt::tick_among restitutes), but in a lazy chunk the
velocity survives: a primed TNT pushed by a piston into a wall, ceiling
or slime keeps 0.4 / -0.8 / -0.8 instead of vanilla's 0 / 0 / 0.64.

Add restitute_piston after apply_push: compare the post-piston-limit
movement (limited) with the post-collision result (resolved) and, as
Entity.move(MoverType.PISTON, …) does, zero blocked horizontal axes,
zero or slime-bounce the vertical axis, and update on_ground. Covers
Player, Guest and every Entity kind including PrimedTnt.

Add unit test a_pushed_tnt_loses_velocity_into_a_wall (needs prepared
resources) asserting the TNT's vx is zeroed by a wall.

Co-Authored-By: Nemotron <[email protected]>
2026-11-08 02:56:20 +03:00
KBroneZandClaude Sonnet 5.5 56ec50a875 fix(port-pack): an empty shaderpacks folder is not a shader pack to convert
The CurseForge app, and mods such as Sodium, create `shaderpacks/` in an instance
even when the player never installed a shader pack. Import counted the folder
itself as one "shader pack, conversion pending" file and listed it under "not yet",
so a client-only instance such as one with Sodium, Lithium, Jade, malilib and
Litematica reported 4 "not yet" rows for 3 mods. A folder instance now reports
shaderpacks/ only when it holds something, and a zip only when it has a file
under its shaderpacks/ (a bare directory entry no longer counts).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 01:54:47 +02:00
Florian ErnstandClaude Opus 5.5 066b6e9cef Save a mannequin's own fields and none of a Mob's
Mannequin extends Avatar extends LivingEntity; it is not a Mob.
Mannequin.addAdditionalSaveData always writes profile, hidden_layers,
main_hand and pose after LivingEntity's fields, and none of
Mob.addAdditionalSaveData's. Horizon left out the four unless they were
loaded, and wrote PersistenceRequired, CanPickUpLoot, LeftHanded and NoAI.

A mannequin now reads main_hand and hidden_layers into the main-arm and
hidden-layer state it already had (a list with an entry that is not a part
hides nothing, as the codec's failed read), and writes all four from its
live state: the empty profile when it has none, the hidden layers in
PlayerModelPart order, its arm and its pose. It neither reads nor saves
Mob.readAdditionalSaveData's flags, and its save drops the Mob-owned keys
over a stale loaded compound. Every other kind is unchanged.

Fixes #12135.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:53:14 +01:00
KBroneZandClaude Opus 5.5 172d7c51e6 fix: keep the 1.20 partial reason on one line of words
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:51:33 +02:00
Nikita Maximilian Grimm 5cf4a1dec8 Merge remote-tracking branch 'origin/main' into t3/scheduled-item-tick-pass 2026-11-08 00:49:17 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 4bf9b604f7 Keep the contact drop range half-open
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:49:15 +01:00
Nikita Maximilian Grimm b95e34a990 Merge remote-tracking branch 'origin/main' into tnt-piston-ground
# Conflicts:
#	crates/horizon-client/src/game/piston_push.rs
2026-11-08 00:46:47 +01:00
GlockSmithandOpenAI Codex GPT-6 e86ce41888 Merge main and retain HDR emission on styled sign text
Resolve the overlap with #11863 in the styled span and glyph loops. Keep its emission tier on glyphs, outlines and decoration quads, with regression coverage.

Co-Authored-By: OpenAI Codex GPT-6 <[email protected]>
2026-11-07 18:42:38 -05:00
Horizon agentandClaude Opus 5.5 458f0e4134 Native shader packs: blend the section fade by distance per pixel
The fade-in's 16-to-32-block distance blend was computed per vertex and
carried in the flat hdr_code, so it was one value per triangle (the
provoking vertex's) and near faces faded in steps. The flat bits now hold
only the section's own visibility (the same for the whole section), and
horizon_material_faded blends it by the interpolated spherical distance,
as terrain.wgsl's interpolated visibility does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:40:34 +00:00
Kacper 29b3374b5d Merge pull request #12098 from NikitaMGrimm/boat-drop-motion
A destroyed boat drops its item with vanilla's drop motion
2026-11-08 00:40:24 +01:00
Kacper 02042bf6b4 Merge pull request #12097 from NikitaMGrimm/boat-fire-timer
A boat burns: its fire timer counts down, fire hurts it and water puts it out, as in vanilla
2026-11-08 00:40:18 +01:00
Kacper 79e277451b Merge pull request #12095 from Web-mc1/fix/telemetry-scrub-word-boundaries
telemetry: match the user name exactly when lowercasing moves boundaries
2026-11-08 00:40:10 +01:00
Kacper e5c1ea0612 Merge pull request #12092 from Web-mc1/fix/java-properties-save-convert
java_properties: write a NUL and a non-BMP character as Java does
2026-11-08 00:40:03 +01:00
Kacper 2f39e246fe Merge pull request #12084 from KBroneZ/claude/windows-unused-mut
Fix Windows-only unused_mut on the TCP keepalive builders
2026-11-08 00:39:56 +01:00
Kacper 2cd9e12ecd Merge pull request #12078 from KBroneZ/claude/oracle-windows
Run tools/neoforge_oracle.py on Windows
2026-11-08 00:39:43 +01:00
Kacper 6d32a88a50 Merge pull request #12069 from senjinthedragon/horizon-uniforms-lights-tier
Shader packs: Horizon's dynamic lights as uniforms, horizonTier for terrain and entities
2026-11-08 00:39:37 +01:00
Kacper 124e88e731 Merge pull request #12068 from NikitaMGrimm/fix/diode-moving-piston-support
A repeater or comparator on a retracting piston stays, as in vanilla
2026-11-08 00:39:30 +01:00
Kacper 1a004614f8 Merge pull request #12056 from TheMrZZ/fix/h255-mob-piston-ground
Project ground after unoccupied server NoAI Mob piston movement
2026-11-08 00:39:23 +01:00
Kacper 1edf540479 Merge pull request #12054 from TheMrZZ/fix/h234-machine-recipe-placement
Route recipe-book placement into actual furnace menus
2026-11-08 00:39:16 +01:00
Kacper 9bccc1056f Merge pull request #12053 from TheMrZZ/fix/h245-sulfur-bucket
Pick up a sulfur cube with an empty bucket
2026-11-08 00:39:09 +01:00
Kacper d144af4a11 Merge pull request #12049 from ilguerro/perf/9996-load-loadlight
Load saved light directly from its layers instead of expanding and repacking
2026-11-08 00:39:03 +01:00
Kacper 616707f3d7 Merge pull request #12033 from Vaspyyy/feat/native-muffle-sounds
Native mod API: muffle the game's sounds for a while, as ears ringing after a blast (native_muffle_sounds)
2026-11-08 00:38:56 +01:00
Kacper 1c5744ac24 Merge pull request #12014 from Vaspyyy/fix/native-mod-image-slot
Native mods: a game built with horizon-mixins gets the mod image slot, native-mods.json or not
2026-11-08 00:38:49 +01:00
Kacper c124718cbc Merge pull request #12002 from MrCloudy2/fix/sprint-hit-slowdown
lan_e2e: sprint-hit-slowdown runs up instead of teleporting, and catches a missing slowdown
2026-11-08 00:38:43 +01:00
Kacper 0b8f18dd40 Merge pull request #11992 from TheMrZZ/fix/h275-test-defs-world-packs
Load a world's test instances from its data packs when it opens
2026-11-08 00:38:36 +01:00
Kacper e51c277db7 Merge pull request #11987 from NikitaMGrimm/hdr-hud-composite
HDR float frame: the HUD and menus lay over the world's light
2026-11-08 00:38:29 +01:00
Kacper fc61e4e9ff Merge pull request #11986 from NikitaMGrimm/hdr-entity-marks
HDR: mobs get HDR lighting and held light sources shine again
2026-11-08 00:38:23 +01:00
Kacper 2c300290d5 Merge pull request #11983 from TheMrZZ/fix/h207-effective-equippable
Honor supported pumpkin Equippable overrides on item use
2026-11-08 00:38:10 +01:00
Kacper 16260920c3 Merge pull request #11969 from Mik00000/perf/mob-ai-stress-bench
mobs: reuse pathfinding allocation buffers and add stress_mob_ai benchmark
2026-11-08 00:38:03 +01:00
Kacper d84428c781 Merge pull request #11968 from TheMrZZ/fix/h237-clone-block-ticks
Copy a clone's pending block ticks to its destination
2026-11-08 00:37:57 +01:00
Kacper e5f23f8b40 Merge pull request #11958 from TheMrZZ/fix/h095-allay-liked-player-ttl
Keep an Allay's liked_player memory time to live and expire it
2026-11-08 00:37:50 +01:00
Kacper 17e4124d04 Merge pull request #11956 from Stink-O/native/hold-world
Native mod API: hold the terrain's picture while the world changes (`native_world_hold`)
2026-11-08 00:37:43 +01:00
Horizon agentandClaude Opus 5.5 37eafb6c1b Older clients: a 1.21.1 client's information gains 1.21.2's particle status
The reverse step for 1.21.1 clients passed ClientInformation through, so a
host read past its end. The older-server adapter now writes 1.21.1's real
layout (no particle status), which made lan_bot's
older_clients_of_each_release_join_and_are_sent_chunks fail at 1.21.1;
real 1.21.1 clients were refused the same way. The step appends
ParticleStatus.ALL in configuration and play.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:37:41 +00:00
Kacper 4df2329711 Merge pull request #11942 from glitchsnake/fix/11804-block-outline-entity-pick
client/render: omit block outline when an entity is targeted (fixes #11804)
2026-11-08 00:37:36 +01:00
Kacper 7ca3fdeedd Merge pull request #11900 from TheMrZZ/fix/h175-frozen-first-tick-water
Register a newly loaded chunk's tick queues before commands reach it
2026-11-08 00:37:29 +01:00
Kacper e4ca9aba95 Merge pull request #11899 from CocofireHD/fix/8390-some-block-entities-render-too-dark-or-have
Block entities: shade by the face normal so shader packs don't darken them twice
2026-11-08 00:37:22 +01:00
Kacper 9848261b44 Merge pull request #11897 from abit-foggy/codex/studio-b2-camera-path
Studio: free camera and camera paths
2026-11-08 00:37:15 +01:00
Kacper 7e66da154b Merge pull request #11896 from NikitaMGrimm/hdr-hud-layer
HDR float frame: HUD and menus record how much of the world they cover
2026-11-08 00:37:08 +01:00
Kacper 3b03674d14 Merge pull request #11893 from CocofireHD/fix/8875-resource-packs-doesn-t-work-well
Fonts: read a pack's missing font files from the game below the overlay
2026-11-08 00:37:01 +01:00
Kacper 3fe5ad0d19 Merge pull request #11892 from TheMrZZ/fix/h173-live-dungeon-spawner
Create missing live dungeon spawner block entities
2026-11-08 00:36:54 +01:00
Kacper a1926a4901 Merge pull request #11882 from CocofireHD/fix/10228-server-specific-resource-pack-not-loading-pr
HUD fonts: pack a bitmap sheet from any texture path and read it from the atlas
2026-11-08 00:36:47 +01:00
Kacper 8dd178353a Merge pull request #11878 from CocofireHD/fix/10095-crash-when-enabling-a-shader-pack-on-opengl
OpenGL: report the context's texture units and refuse a bad pack instead of crashing
2026-11-08 00:36:40 +01:00
Kacper 0845a33141 Merge pull request #11864 from TheMrZZ/fix/h150-direct-passenger-relations
fix: select direct mob passengers for execute relations
2026-11-08 00:36:33 +01:00
Kacper e05360eb74 Merge pull request #11863 from senjinthedragon/glow-ink-text-tier
HDR and shader packs: glowing sign text shines
2026-11-08 00:36:27 +01:00
Kacper b967051f4f Merge pull request #11861 from Joansitoh/fix/11849-home-tab-strip
fix(launcher): wrap Home's tab strip on narrow windows instead of scrolling it sideways
2026-11-08 00:36:20 +01:00
Kacper 6c723039a7 Merge pull request #11858 from TheMrZZ/fix/h170-place-feature-inline
Place valid inline features with /place feature
2026-11-08 00:36:13 +01:00
Kacper a2c4c2d4fc Merge pull request #11856 from Ragbie/fix/infested-hurt-draw-order
Infested draws at the hurt, before an enderman's or a shulker's own roll
2026-11-08 00:36:06 +01:00
Kacper 3b5b0d8a3c Merge pull request #11850 from GIGABAIT93/l10n/uk-nightly-1107
Ukrainian: the 445 strings uk_ua.json lacked (PvP & HUD, Studio, mods, cosmetics)
2026-11-08 00:35:59 +01:00
Kacper 15ebef6a69 Merge pull request #11847 from TheMrZZ/fix/h204-depleted-absorption
Remove a mob's Absorption effect once the absorption is used up
2026-11-08 00:35:52 +01:00
Kacper 40630164be Merge pull request #11839 from vnsmoreira/packs/polytone-legacy
Polytone: legacy math expressions, color and distance functions
2026-11-08 00:35:45 +01:00
Kacper c6a2fd5291 Merge pull request #11838 from vnsmoreira/packs/polytone-groups-fix
Polytone: leave keys beside the attribute groups alone
2026-11-08 00:35:37 +01:00
Kacper 29d41a899b Merge pull request #11836 from yahya-nusseibeh/fix/remote-view-distance-overflow
Multiplayer: a server's view distance and chunk centre can't overflow
2026-11-08 00:35:31 +01:00
Kacper 61d5d3bd8a Merge pull request #11835 from yahya-nusseibeh/fix/portmap-zero-lifetime
Play with Friends: refuse a port mapping granted no lifetime
2026-11-08 00:35:24 +01:00
Kacper 99bf985e0a Merge pull request #11834 from yahya-nusseibeh/fix/guest-tunnel-token
Play with Friends: the guest's loopback tunnel takes only its own client
2026-11-08 00:35:17 +01:00
Kacper dc098b606b Merge pull request #11833 from yahya-nusseibeh/fix/pack-overlay-prune
Resource packs: delete overlays no selection has used lately
2026-11-08 00:35:11 +01:00
Kacper 51f73ac425 Merge pull request #11832 from yahya-nusseibeh/fix/pack-overlay-budget
Resource packs: cap what one overlay build may unpack
2026-11-08 00:35:04 +01:00
Kacper ac9bd0527a Merge pull request #11827 from TheMrZZ/fix/h168-mob-fall-flying
Keep a mob's FallFlying flag and wear its glider as vanilla does
2026-11-08 00:34:57 +01:00
Kacper 8715111af1 Merge pull request #11825 from vnsmoreira/packs/polytone-expressions
Polytone: the scripting expression language
2026-11-08 00:34:50 +01:00
Kacper 790efa9cb7 Merge pull request #11818 from NikitaMGrimm/hdr-note-hud-first
HDR design note: the HUD's layer and the tone curve before light is written
2026-11-08 00:34:43 +01:00
Kacper ae46423a77 Merge pull request #11795 from Hiuoy/port-pack/renamed-tooltip-anvil
Port pack: RenderTooltipEvent.Color and AnvilRepairEvent under their 26.1 names
2026-11-08 00:34:36 +01:00
Kacper 9da1e6f55f Merge pull request #11794 from doodlyyousuf/251107-fix-entity-air-drag
fix: widen entity air and fluid drags from vanilla floats
2026-11-08 00:34:29 +01:00
Kacper e27e97e58b Merge pull request #11793 from TheMrZZ/fix/h149-local-coordinate-math-current
fix: match exact local command rotation arithmetic
2026-11-08 00:34:22 +01:00
Kacper 02b75ab1f3 Merge pull request #11788 from Teiwazik/render/taa-motion-clip
TAA upscaling smears the world under motion
2026-11-08 00:34:15 +01:00
Kacper 3be40a13a3 Merge pull request #11786 from Teiwazik/render/upscaling-sharpness
Upscaling Sharpness: sharpen the TAA-upscaled world
2026-11-08 00:34:07 +01:00
Kacper c69d499386 Merge pull request #11778 from Teiwazik/fix/framed-maps-slots
Framed maps: no slot taken from a map drawn this frame
2026-11-08 00:33:59 +01:00
Kacper 1a83468f0d Merge pull request #11776 from MSedgeMC/fix/frog-panic-speed
Frogs panic at AnimalPanic's 2.0 speed multiplier
2026-11-08 00:33:51 +01:00
Kacper 1abb582ab4 Merge pull request #11769 from MSedgeMC/port_map/stale-batch-two
port map: a row that survived a rename
2026-11-08 00:33:45 +01:00
Kacper d44210f9b4 Merge pull request #11765 from MSedgeMC/test/enchant-durability
test: compare enchantment durability effects
2026-11-08 00:33:38 +01:00
Kacper 3cefb44bba Merge pull request #11740 from Detimes/fix-11721-explode-radius
Older clients: explosions no longer fail for 1.21.8 and older; real radius for 1.21.1
2026-11-08 00:33:25 +01:00
Kacper 5c28d7f248 Merge pull request #11723 from TheMrZZ/fix/loaded-arrow-shot-game-event
Dispatch ordinary arrow shoot events on their first tick
2026-11-08 00:33:18 +01:00
Kacper b1dae52509 Merge pull request #11711 from MSedgeMC/test/falling-block
test: compare falling block landings
2026-11-08 00:33:11 +01:00
Kacper 341bd0ba5b Merge pull request #11709 from TheMrZZ/fix/connected-guest-attribute-commands
Route attribute commands through the selected guest body
2026-11-08 00:33:04 +01:00
Kacper 6e423b9caa Merge pull request #11701 from Alysia42/random-source
Parity: entity and RandomSource.create() randoms draw from the level's random or are hand-seeded
2026-11-08 00:32:57 +01:00
Kacper 604c3a6654 Merge pull request #11694 from TheMrZZ/fix/h289-mob-equipment-custom-data
fix: match typed custom data in mob equipment predicates
2026-11-08 00:32:51 +01:00
Kacper b229c37e45 Merge pull request #11691 from TheMrZZ/fix/warden-loaded-memory-slots
Bind loaded Warden memories to their runtime slots
2026-11-08 00:32:44 +01:00
Kacper dcb6409ebd Merge pull request #11681 from MSedgeMC/test/nether-portal-shape
test: compare nether portal frame search
2026-11-08 00:32:37 +01:00
Kacper 217b5e97f7 Merge pull request #11672 from TheMrZZ/fix/loot-kill-sheep-state
Bind actual sheep target state in loot-kill commands
2026-11-08 00:32:31 +01:00
Kacper 4fe3ed58b4 Merge pull request #11666 from Raydnde/fix/copper-chest-wax-and-viewers-11378
Waxing a double copper chest reaches both halves; a golem's open chest doesn't weather
2026-11-08 00:32:24 +01:00
Kacper c15fa6c55c Merge pull request #11659 from TheMrZZ/fix/camel-inherited-saved-fields
Save Camel inherited horse fields from modeled state
2026-11-08 00:32:17 +01:00
Kacper d6d3042086 Merge pull request #11656 from TheMrZZ/fix/h212-crafter-drop-name
fix: keep vanilla crafter drops unnamed
2026-11-08 00:32:10 +01:00
Kacper c929d96fa5 Merge pull request #11652 from ilguerro/perf/11126-structure-starts-jigsaw
Read saved jigsaw structure starts instead of regenerating them
2026-11-08 00:32:03 +01:00
Kacper 5555cd8cda Merge pull request #11634 from k3yh/cushion-selectors
Selectors find cushions
2026-11-08 00:31:56 +01:00
Kacper f85f824a27 Merge pull request #11633 from MSedgeMC/fix/old-stats-file
Move an old name-based stats file to the player's uuid
2026-11-08 00:31:49 +01:00
Kacper e1a8d50c79 Merge pull request #11625 from TheMrZZ/fix/loaded-sleeper-bed-position
Refresh loaded sleeper position at the bed on its first tick
2026-11-08 00:31:42 +01:00
Kacper b69935ff31 Merge pull request #11624 from TheMrZZ/fix/h290-pot-template-compounds
fix: save pot sherd string templates as item compounds
2026-11-08 00:31:35 +01:00
Kacper 900ce5e15b Merge pull request #11612 from k3yh/ride-vehicles
/ride takes armor stands, displays, interactions and markers as vehicles
2026-11-08 00:31:28 +01:00
Kacper 7435df4fae Merge pull request #11610 from TheMrZZ/fix/world-pack-enchantment-definitions
Load active world-pack enchantment definitions
2026-11-08 00:31:21 +01:00
Kacper afce5629b7 Merge pull request #11590 from TheMrZZ/fix/h145-required-function-tags
fix: reject function tags with unresolved required references
2026-11-08 00:31:14 +01:00
Kacper 7f22f76867 Merge pull request #11576 from TheMrZZ/fix/folder-datapack-metadata
Require folder data-pack metadata sections before discovery
2026-11-08 00:31:06 +01:00
Kacper 08cb78f385 Merge pull request #11573 from vnsmoreira/attributes/modifiers
Environment attributes: the registry and modifiers, checked against vanilla
2026-11-08 00:30:59 +01:00
Kacper ebaea75be6 Merge pull request #11565 from TheMrZZ/fix/function-command-admission
Reject functions containing invalid ordinary commands
2026-11-08 00:30:52 +01:00
Kacper ad2aabd6cf Merge pull request #11558 from Vaspyyy/perf/vault-players-lazy
Vaults: list the players only when a vault looks for them (−12.6% tick_block_entities)
2026-11-08 00:30:46 +01:00
Kacper 534feb4833 Merge pull request #11544 from voidsipp/fix/11328-trade-modifiers
Fix trade modifiers and potion payment matching
2026-11-08 00:30:39 +01:00
Kacper b7d134d2ef Merge pull request #11540 from voidsipp/fix/11330-explosion-item-health
Spill contents when explosions destroy dropped containers
2026-11-08 00:30:32 +01:00
Kacper 921f2fa118 Merge pull request #11533 from TheMrZZ/fix/loot-mine-executor-presence
Carry actual loot-mine executor presence into block drops
2026-11-08 00:30:25 +01:00
Kacper 0429cd882f Merge pull request #11526 from Vaspyyy/perf/cart-push-loot
Minecarts: keep the loot roll out of the copies a cart push makes (−52% tick_carts)
2026-11-08 00:30:17 +01:00
Kacper b68f5b5327 Merge pull request #11509 from voidsipp/fix/smithing-transform-11307
Fix smithing transform optional inputs and result templates
2026-11-08 00:30:10 +01:00
Kacper d21170f02d Merge pull request #11508 from TheMrZZ/fix/camel-loaded-pose-timestamp
Preserve loaded Camel pose timestamp boundaries
2026-11-08 00:30:03 +01:00
Kacper 6488524356 Merge pull request #11498 from TheMrZZ/fix/effective-item-component-validation
Reject stackable damageable item command inputs
2026-11-08 00:29:56 +01:00
Kacper c9e8e4e8e0 Merge pull request #11497 from voidsipp/fix/11316-stack-tool-mining
Respect stack tool mining rules and actual eye immersion
2026-11-08 00:29:49 +01:00
Kacper b0abfbd196 Merge pull request #11491 from DUzzL/fix/10041-adventure-placed-entities
Adventure mode: honor can_place_on for placed entities and fireworks
2026-11-08 00:29:42 +01:00
Kacper 2c0564db8c Merge pull request #11485 from voidsipp/fix/11317-block-crack-feedback
Match player mining crack stages and broadcast distance
2026-11-08 00:29:34 +01:00
Kacper 41a021365e Merge pull request #11483 from TheMrZZ/fix/llama-saved-temper
Preserve signed equine temper across load and save
2026-11-08 00:29:28 +01:00
Kacper ef36a05d90 Merge pull request #11480 from brasga-a/fix/11314-player-food-predicate
Player predicates test food level and saturation
2026-11-08 00:29:21 +01:00
Kacper ab4a0fd56e Merge pull request #11478 from DUzzL/fix/11379-copper-golem-name
Keep the copper golem's name on its statue
2026-11-08 00:29:14 +01:00
Kacper 0e12cc64de Merge pull request #11474 from voidsipp/fix/11319-gateway-item-motion
Preserve item motion through End gateways
2026-11-08 00:29:07 +01:00
Kacper 4a6da129ce Merge pull request #11467 from voidsipp/fix/round5-5-11321
Respect world borders for pistons and natural spawning
2026-11-08 00:29:00 +01:00
Kacper 29f5ef342c Merge pull request #11466 from MSedgeMC/fix/region-external
Region: a chunk's external stream reads even when its stub length disagrees or its .mcc is missing
2026-11-08 00:28:53 +01:00
Kacper 672c9a7974 Merge pull request #11465 from TheMrZZ/fix/h097-loaded-air-first-tick
Discard loaded air falling blocks on their first tick
2026-11-08 00:28:46 +01:00
Kacper 3d275f03bf Merge pull request #11459 from DUzzL/fix/11387-beacon-effect-overlap
Beacon: select players by bounding-box overlap
2026-11-08 00:28:38 +01:00
Kacper 1dd7423d00 Merge pull request #11457 from voidsipp/fix/round5-1-11333
Respect Silent on explosions and potion impacts
2026-11-08 00:28:31 +01:00
RINNECODERandClaude Opus 5.5 c56e9312ee Port pack: a mod's own rarity or map colour stays the template's, not a refused mod
NeoForge lets mods add item rarities (Immersive Engineering's masterwork) and some blocks carry a
map colour id past 26.3's 61 (Mekanism's gas blocks: 63). The game refuses the whole content
root for either, so one such file left every block of the mod out. They now keep the template's
and the report names them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:28:23 -06:00
Kacper 9c0c0c7210 Merge pull request #11456 from MrCloudy2/fix/dropper-container-entities
Droppers insert into chest boats and container minecarts
2026-11-08 00:28:23 +01:00
Kacper 671a85a7f2 Merge pull request #11455 from NikitaMGrimm/frame-identity-no-fall
Frame identity: keep the player on a block while the scenes are built
2026-11-08 00:28:15 +01:00
Kacper 63a8290dcb Merge pull request #11445 from MSedgeMC/test/furnace-tick
furnace: direct block-entity tick parity (burn table, XP, mid-cook reset)
2026-11-08 00:28:08 +01:00
Kacper fbd9b2ce23 Merge pull request #11434 from DUzzL/fix/11306-anvil-grindstone
Read stack names and durability components in anvil and grindstone
2026-11-08 00:28:00 +01:00
Kacper e290e2c196 Merge pull request #11433 from TheMrZZ/fix/falling-live-data-adoption
Adopt live FallingBlock data updates
2026-11-08 00:27:53 +01:00
Kacper 5671fc9619 Merge pull request #11432 from MSedgeMC/fix/phantom-anchor-save
Save a phantom's circling anchor with its chunk
2026-11-08 00:27:46 +01:00
Kacper 436e839ebf Merge pull request #11425 from TheMrZZ/fix/h051-kill-vehicle-contents
Spill explicit vehicle container contents on kill removal
2026-11-08 00:27:39 +01:00
Kacper 860f3f05d5 Merge pull request #11423 from DUzzL/fix/11311-scaffold-water
Read scaffolding as its stable shape in fluid wall tests
2026-11-08 00:27:33 +01:00
Kacper 88d7c0eb2c Merge pull request #11422 from voidsipp/fix/round5-6-11320
Preserve comparator output and hopper cooldown across saves
2026-11-08 00:27:26 +01:00
Kacper 2cf505bbd7 Merge pull request #11421 from DUzzL/fix/11324-spawn-heightmap
Fix natural spawn height bound off by one
2026-11-08 00:27:19 +01:00
Kacper cd218ea58e Merge pull request #11420 from TheMrZZ/fix/falling-block-state-default
Use modern falling-block state decoding and sand fallback
2026-11-08 00:27:12 +01:00
Kacper 161c4e5677 Merge pull request #11414 from voidsipp/fix/round5-3-11315
Honor block drops and RNG order for mining XP
2026-11-08 00:27:05 +01:00
Kacper a6dc594cdf Merge pull request #11413 from ilguerro/fix/w149
A server player's glide ends on a climbable (as_guest copies fall_flying back)
2026-11-08 00:26:58 +01:00
Kacper 013c3952a7 Merge pull request #11411 from ilguerro/fix/w167
Wait for the client's load after the End credits respawn
2026-11-08 00:26:51 +01:00
Kacper 5365f2be63 Merge pull request #11407 from ilguerro/fix/w157
Drop a converting piglin's inventory like vanilla
2026-11-08 00:26:44 +01:00
Kacper 0f23639844 Merge pull request #11400 from ilguerro/fix/w144
Search neighboring columns for dolphin breathing like vanilla
2026-11-08 00:26:38 +01:00
Kacper 997fe4515d Merge pull request #11390 from UMCEKO/dims/dragon-facts
The dragon fight follows has_ender_dragon_fight (#11282, 5/9)
2026-11-08 00:26:30 +01:00
Kacper 5d16154c0b Merge pull request #11366 from UMCEKO/dims/mob-facts
Mobs and spawn rules read the dimension type (#11282, 4/9)
2026-11-08 00:26:24 +01:00
Kacper 47e562e8b9 Merge pull request #11350 from AlfaRojo/fix/sky-darken-truncates
Sky darkening truncates the light level, as updateSkyBrightness does
2026-11-08 00:26:16 +01:00
Kacper 74b8550421 Merge pull request #11344 from UMCEKO/dims/gameplay-facts
Gameplay reads the dimension type, not the dimension (#11282, 3/9)
2026-11-08 00:26:09 +01:00
RINNECODERandClaude Opus 5.5 9f52bf9a83 Port pack: a block that can't occlude (noOcclusion) carries occludes=false
The oracle reports can_occlude per state, but the carry ignored it: a
full-cube block made with noOcclusion() (one its block entity draws) took
its template's occlusion and hid the faces behind it, leaving a hole.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:26:03 -06:00
Kacper 54c3a21b29 Merge pull request #11116 from Delete228/content-context-geometry-upstream
Native content: resolve block geometry by entity context
2026-11-08 00:26:02 +01:00
Kacper d6f0b3042f Merge pull request #11098 from Delete228/native-state-entity-factory-upstream
Native mods: create block entities from the actual state
2026-11-08 00:25:55 +01:00
Kacper 0422dbc79f Merge pull request #10559 from rison1337/perf/cache-trim-preparation
Reuse unchanged armor-trim preparation across frames
2026-11-08 00:25:48 +01:00
Kacper 914c1e9a3b Merge pull request #10552 from ilguerro/perf/9996-surface
Write surface rule runs of one block at once
2026-11-08 00:25:41 +01:00
Kacper 62dd244cb6 Merge pull request #10511 from TheMrZZ/fix/noai-nautilus-air
Keep superclass air refill for NoAI Nautilus
2026-11-08 00:25:34 +01:00
Kacper 0e446e4336 Merge pull request #10242 from TheMrZZ/fix/h297-potion-effect-icon
Save default icon flags in custom potion effects
2026-11-08 00:25:27 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 a9612bdabc Apply an item's gravity before pushing it out of a block
ItemEntity.tick applies gravity (or the fluid movement) first and then
moveTowardsClosestSpace, whose 0.75 scales the already-fallen vertical
speed. The push ran before tick_move_before_block_effects, so gravity
came after it. Pass the escape speed into the move and apply it right
after gravity; the native block-contact pipeline is unchanged.

Fixes #12018

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:25:22 +01:00
Kacper 48344d0a6b Merge pull request #10210 from TheMrZZ/fix/h103-trade-reputation-gate
Defer villager trade reputation until its AI phase
2026-11-08 00:25:20 +01:00
Kacper 87d4a87960 Merge pull request #10201 from DUzzL/fix/10147-projectile-catchup-stutter
Unstick arrows and tridents the server sets moving
2026-11-08 00:25:13 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 a20d3296b4 A sideways piston push no longer leaves an experience orb marked on ground
The orb kept its own vertical-only on-ground rule for a piston push. It
now takes the server's end-of-move rule that items, primed TNT and armor
stands use: on ground only when the push's downward part was blocked.

Fixes #12100

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:23:06 +01:00
RINNECODERandClaude Opus 5.5 eadbb41095 Shader packs: run a workGroups over 65535 per dimension
wgpu caps a dispatch at 65535 work groups per dimension and panics past it;
GLSL packs may ask for more (131072). A larger workGroups now runs as the
same number of groups in a shape within the limit, and main works out each
group's place in the declared dispatch, so gl_WorkGroupID,
gl_GlobalInvocationID and gl_NumWorkGroups read what they would there. The
shape uses every group exactly, so no group leaves before a barrier. A
count no shape holds skips the program with a note; an oversized
workGroupsRender dispatch is not run instead of panicking.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:22:07 -06:00
RINNECODERandClaude Opus 5.5 bc59734a29 Shader packs: copy a struct or array holding atomics as its declared type
naga's GLSL frontend turns a uint/int that an atomic*() call touches into
an atomic type after parsing. A load or store of a whole struct or array
holding such a member then had the upgraded type: `Cell c = buf.cells[i];`
and `uint copy[4] = shared_counts;` failed validation. A whole struct or
fixed-size array of integers in a buffer or shared memory is now loaded
and stored member by member, so each copy keeps its declared type.

Vendored-naga patch: third_party/naga/src/front/glsl/context.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:20:58 -06:00
RINNECODERandClaude Opus 5.5 626c60740d Shader packs: make an image in its layout qualifier's format
An image declared RGB10_A2, RGB10_A2UI or a 16-bit SNORM format was made
as an RGBA8, RGBA8UI or 8-bit SNORM texture, so a shader binding it as
layout(rgb10_a2) etc. was refused ("is rgb10_a2 but its texture is
Rgba8Unorm"). Each now gets the wgpu format of its GLSL qualifier; one the
GPU can't store into is left out with a note, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:20:58 -06:00
RINNECODERandClaude Opus 5.5 0bd5a4f201 Shader packs: an exact argument beats a conversion in GLSL overloads
naga's GLSL frontend never compared an exactly matching argument with the
previous best overload's conversion there, so greaterThanEqual(ivec3, uvec3)
found the uvec3 overload no better than the vec3 one and reported
"Ambiguous best function". GLSL 4.60 §6.1 ranks an exact match above any
implicit conversion: the uvec3 overload wins. Zephyr Starlight's
shadowcomp1-4 failed on it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:20:49 -06:00
RINNECODERandClaude Opus 5.5 cf0b0d02c8 Shader packs: a setting in a comment may end at its line
Packs list their const settings in a block comment one per line with no
';' (`const vec4 colortex6ClearColor = vec4(0.0, 0.0, 0.0, 1.0)`). The
reader looked for the next ';' and took every following line as the value,
so each such setting was refused as 'not a vec4' (Zephyr Starlight logged
85 multi-line notes) and its clear colour was lost. In a comment a
declaration now ends at the first ';' or line end; live code still reads to
the ';'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:20:49 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 60fff3987f Keep the drops of entities' block contacts on the next tick
tick_blocks applies the entities' block contacts (a boat breaking a lily
pad) before the scheduled ticks; vanilla runs them inside each entity's
own tick, so their drops still wait for the next tick.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:19:02 +01:00
Evan-lhmandClaude Opus 5.5 1b93764780 Launcher: a 0 px blur leaves the glass plates sharp (#12062)
With the blur at 0 the plates still read their backdrop bilinearly between
texel centres, and a texel is 3 to 6 logical pixels of pixel art, so the
scene behind the glass stayed slightly soft. With no blur, read the texel
under the point instead.

Fixes #12062

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:18:19 +01:00
Horizon agentandClaude Opus 5.5 52aad2205d Older servers: keep the particle markers inside the adapter's connections
The render crate read a trail duration of -1 as the pre-1.21.4 marker, and
the client read particle ids -2/-3 as the old entity-effect providers, for
any server: a 26.3 server sending those values got the legacy behaviour.
The client now decides from the connection's release (received_particle)
and passes an explicit legacy_trail_lifetime option; a current server's
-1 stays a lifetime of -1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:18:13 +00:00
KBroneZandClaude Opus 5.5 da4d26b00d feat: carry 1.20 jars' data under 1.21's folder names
A content mod jar whose data files are mostly in the folders 1.21
renamed (recipes/, loot_tables/, structures/, advancements/,
predicates/, item_modifiers/, functions/ and tags/blocks, items,
entity_types, fluids, game_events, functions) was refused by `carry`.
Now the carry moves each such file to the singular name 26.3 reads.
A file the jar also ships under the new name keeps that copy, and a
1.21 jar's stale plural folder is left as it was.

The JSON stays 1.20's: a recipe whose result names its item as `item`
(before 1.20.5), which 26.3 skips, is kept as it is instead of counted
as upgraded, and NBT in loot functions, ingredients and predicates is
not upgraded yet. The report therefore marks such a mod partial
whatever its harness says, and says why. `check` still refuses 1.20
jars until the JSON steps of #10262 land.

Part of #10262.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 01:14:06 +02:00
KBroneZandClaude Sonnet 5.5 342315073f Launcher: the data pack support text says what the game reads today
The browser's data pack note still said recipes, loot tables, advancements, other tags and
worldgen were not read. The game reads them now. The note goes through tr() and is in all
86 language tables (translated in 14, English elsewhere).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 01:13:03 +02:00
martipopsandClaude Opus 5.5 de0132b638 Controllers: the craft prompt says Quick Craft, and its setting's description is shorter
Two words, like the guide's other rows, and the same name as Quick Craft on
Servers. The exact rule (single player, LAN worlds from the server list) stays
in docs/controllers.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:12:25 -05:00
Nikita Maximilian Grimm 30f1fc145d Merge remote-tracking branch 'origin/main' into t3/scheduled-item-tick-pass 2026-11-08 00:10:09 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 f509e284bf Tick an item a scheduled block tick drops in that tick's entity pass
ServerLevel.tick runs the block ticks and block events before
entityTickList.forEach, so a dropper's item ticks on the tick it is
dispensed. The item cutoff was taken right after the tick functions;
take it just before the entity pass instead. Primed TNT and falling
blocks keep their own packet cutoff (#10063).

Fixes #12017

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 00:10:05 +01:00
itarqos5andClaude Sonnet 5.5 3d5216e717 perf(render): pass terrain's interpolants in 5 locations, not 12
Terrain's vertex stage exported 20 scalars in 12 interpolant locations. A GPU's
vertex stage pays per location (AMD gives each a parameter slot): on an RX 580 the
12 cost 3.2 ns per quad and the same values in 5 cost 1.6. TerrainOut stays the type
the shader code uses; TerrainWire crosses the stage boundary, each component
interpolated on its own and the integers flat, so a pixel gets the same values.

RX 580, Vulkan, 1080p, render distance 16: village 523.7 -> 590.8 FPS (+12.8%),
forest 267.6 -> 323.7 (+21.0%).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-07 23:09:46 +00:00
Horizon agentandClaude Opus 5.5 9bc110bae6 Riding: skip the extra rider pass when nothing rides the player
The second position_riders() call after the player moves rebuilt the mob
index every tick for every client; run it only when the riding graph has
something on this player. Also forget passengers whose vehicle is removed,
and add the new field to main's second (studio) Remote initializer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:08:57 +00:00
hunix 14ba691e53 Components: keep a translatable fallback literal instead of looking it up as a key
The component parser translated a missing key's fallback as if it were another key, so a fallback that named a
real key showed that key's translation. It now builds the text through Text::translate_with_fallback, as
TranslatableContents.decompose does (Language.getOrDefault(key, fallback)), which also keeps the fallback in the
component's JSON. Fixes #12042.
2026-11-07 13:02:44 -10:00
hunix 877cb37978 Web panel: accept LAN browsers when bound to 0.0.0.0 or ::
Bound to every interface, the panel's Host check accepts any IP address with the bind's port (and localhost),
which a rebound DNS name can never be, and the login link names this computer's network address instead of
0.0.0.0. Fixes #12039.
2026-11-07 13:02:44 -10:00
Nikita Maximilian Grimm 83535ddcc1 Merge remote-tracking branch 'origin/main' into minecart-drop-motion 2026-11-07 23:58:46 +01:00
Nikita Maximilian Grimm 2c672eae2d Merge remote-tracking branch 'origin/main' into tnt-piston-ground 2026-11-07 23:58:26 +01:00
bulkandClaude Opus 5.5 12273a4e8e Natural spawning: find the players near a spawn start by square
Every spawn start measured its distance to every player to keep those
within reach of its attempts. With more than 8 players, the level keeps them
by the 256-block square they stand in, built once a pass first asks, and a
start reads the 3×3 squares around it: every player within reach is in
them, and the nearest one is the same in any order. The spawn draws are
untouched.

(the player-square part of commit e3b70aace7; its region spawning is left
out)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:56:49 +00:00
sergue212fbrightandOpenAI Codex GPT-6 796047f1e8 Render styled sign text and animate obfuscated glyphs
Follow vanilla 26.3 sign layout and baked glyph geometry, preserving styles through clipping and rebuilding animated sign meshes. Extend the block-entity oracle with styled components and glyph vertices.

Co-Authored-By: OpenAI Codex GPT-6 <[email protected]>
2026-11-07 17:53:48 -05:00
Kacpherek 34194ab7ec test: give the remote mining fixture's remote_break_restricted the position it now takes 2026-11-07 23:47:06 +01:00
Florian ErnstandClaude Opus 5.5 7803f1351e Cite AttributeMap.pack for the sulfur cube attribute save
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:46:38 +01:00
Florian ErnstandClaude Opus 5.5 c9b07b1ffb Pick /test pos's block with a connected source player's view
TestCommand.showPos takes the source player (getPlayerOrException) and
that player's own pick: its eyes and view, not the execute position. So
`execute as <connected player> run test pos` from another player answers
with the block that player looks at, and the issuer is told. Horizon
only accepted the player in place, so the command did nothing.

For a connected player as the source, /test pos now picks the block with
that player in place (for_player) and only the pick runs there; the test
is looked up in the command's level and the issuer told afterwards. Every
other source keeps its current rule, and the highlight packet is
unchanged.

Fixes #12102.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:45:41 +01:00
Kacpherek ec77214342 Send a bounce in the tick it happens: move the update clock to its next interval (ServerEntity.sendChanges) 2026-11-07 23:42:53 +01:00
PetroandOpenAI GPT-6 Luna bec6ac6448 Fix legacy Intel Metal startup and terrain rendering
Use compatible compute shaders and direct terrain draws on older Intel Metal.

Co-Authored-By: OpenAI GPT-6 Luna <[email protected]>
2026-11-07 23:42:25 +01:00
Kacpherek a2b3f669ef Swing at a wandering trader only for a named name tag, not a lead or an unnamed tag (NameTagItem, Entity.interact) 2026-11-07 23:42:05 +01:00
Kacpherek 7bfecd3fd1 Time the End flash by the End's own clock (ClientLevel.tick: getDefaultClockTime) 2026-11-07 23:41:38 +01:00
Kacpherek 43ef30f98c Draw wings and move the cape only for a chest-slot equippable (HumanoidArmorLayer.shouldRender) 2026-11-07 23:41:25 +01:00
Nikita Maximilian Grimm 2dbcb75cfa Merge remote-tracking branch 'origin/main' into execute-block-nbt 2026-11-07 23:41:15 +01:00
Kacpherek ce4f0d7074 Let shears in hand still take a camel's back seat or open a ridden mount's inventory (Entity.interact falls through to mobInteract) 2026-11-07 23:41:12 +01:00
Kacpherek 4ba236928d Run no heartbeat sound or random draw for the warden on the server thread (Warden.tick's client branch only) 2026-11-07 23:41:04 +01:00
Kacpherek GIT_COMMITTER_NAME=Kacpherek [email protected] [email protected] 34c5bb84e6 Keep a silent breeze's whirl and idle sounds quiet (EntityBoundSoundInstance.canPlaySound) 2026-11-07 23:40:45 +01:00
Kacpherek GIT_COMMITTER_NAME=Kacpherek [email protected] [email protected] e809bed768 Play the warden's heartbeat once in single player: the server thread's copy is a local sound too 2026-11-07 23:40:45 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 34f528ffcb Drop a destroyed minecart's item and contents with vanilla's motions
VehicleEntity.destroy spawns the cart item through spawnAtLocation, with an
ItemEntity's own motion (0.2 up, random sideways). A container cart's contents
go through Containers.dropContents: a spot in the cart's block, pieces of 10 to
30 with the level random's scatter and no pickup delay, every slot drawing its
spot, and chestVehicleDestroyed drops the emptied container again. Fixes #12099.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:40:28 +01:00
Kacpherek 031037cee5 Send stepped move paths only for living entities, as vanilla's SteppedInterpolationTracker does 2026-11-07 23:39:00 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 7f6f26a33a A shulker lid's push sets the pushed entity's on-ground flag the same way
ShulkerBoxBlockEntity.moveCollidedEntities pushes through Entity.move too,
so it ends in the same setOnGroundWithMovement as a piston's push.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:30:46 +01:00
Kacpherek 70342ed68b Show your own crit particles on critical hits against other players on servers (Player.attackVisualEffects, LocalPlayer.crit) 2026-11-07 23:30:01 +01:00
Kacpherek 98d7553124 Unlock used_ender_eye advancements when throwing an eye of ender (UsedEnderEyeTrigger.trigger)
EnderEyeItem.use now fires the minecraft:used_ender_eye criterion with the squared horizontal distance to the located structure, matched against the distance bounds squared as MinMaxBounds.Doubles.matchesSqr does.
2026-11-07 23:29:23 +01:00
Kacpherek ef6fc399f5 List the blocks an item can break or be placed on in its tooltip (AdventureModePredicate.addToTooltip) 2026-11-07 23:29:04 +01:00
Kacpherek 94aeeac20d Flash the End sky on servers and pan its rumble toward the flash (ClientLevel.tick, DirectionalSoundInstance)
The End flash state now ticks on every client, so servers, LAN guests and single player show the sky flash and its light. Its weather.end_flash sound plays 30 ticks later ten blocks from the camera toward the flash, follows the camera, and is skipped under the credits.
2026-11-07 23:28:35 +01:00
Kacpherek 7f51885a85 Show mobs bouncing on slime blocks and beds to other players without cutting the bounce short (SteppedInterpolationTracker) 2026-11-07 23:28:17 +01:00
Kacpherek 5ecd155b76 Stop cracking blocks a can_break tool may not break in adventure mode on servers (Player.blockActionRestricted) 2026-11-07 23:27:33 +01:00
Kacpherek 5fe374444f Keep riders in the portal when they get off a vehicle standing in one (LivingEntity.dismountVehicle)
Getting off a boat, minecart or mount whose block is in #minecraft:portals now takes the free-position branch straight up from the rider, as for a removed vehicle, instead of the vehicle's side dismount spot.
2026-11-07 23:27:14 +01:00
Kacpherek c3f7e94775 Let foxes stroll into villages at night (Fox.FoxStrollThroughVillageGoal) 2026-11-07 23:26:35 +01:00
Kacpherek ff50de2553 Shear saddles off horses, striders, camels and nautili with a sound (Mob.attemptToShearEquipment)
Shears now take the saddle off any #can_equip_saddle mob, not only pigs, and play the saddle's shearing sound item.saddle.unequip unless the mob is silent. A mount wearing horse or nautilus armor is left alone, since vanilla shears that body armor first.
2026-11-07 23:26:20 +01:00
Kacpherek d4ea299fdd Let adventure-mode can_break and can_place_on predicates with nbt or components match their blocks (BlockPredicate.matches(BlockInWorld)) 2026-11-07 23:25:54 +01:00
Kacpherek 5383881562 Mark worlds with experimental features as Experimental in the world list (LevelSummary.createInfo) 2026-11-07 23:25:20 +01:00
Kacpherek 1c402c47a7 Anger piglins that see a player break a chest boat (ContainerEntity.chestVehicleDestroyed)
A survival player's hit that breaks a chest boat with entity_drops on angers the piglins that see it, as AbstractChestBoat.destroy does through chestVehicleDestroyed.
2026-11-07 23:25:04 +01:00
Kacpherek 6e5f7e88f7 Hold a lead at the right point while gliding, riptiding or swimming in third person (Player.getRopeHoldPosition)
The lead now hangs from the body's yaw, not the head's, follows the eased position, and uses vanilla's gliding/riptide and swimming hold points.
2026-11-07 23:24:48 +01:00
Kacpherek 75dd0dde7d Save and load a mob's hurt immunity as invulnerable_time (Entity.load / saveWithoutId)
A mob writes invulnerable_time while it has hurt immunity left and reads it back with a default of 0, so /data get shows it, /data merge sets it, and the immunity survives a save and reload.
2026-11-07 23:24:42 +01:00
Kacpherek 8c4e3bb507 Pour a water bottle onto dirt to make mud at once on servers instead of drinking it (PotionItem.useOn) 2026-11-07 23:24:38 +01:00
Kacpherek dabae908cd Keep hidden server list entries, so Direct Connection servers remember pack and Code of Conduct answers (ServerList.save, ServerList.add) 2026-11-07 23:24:26 +01:00
Kacpherek 211b53f598 Let a ravager's roar knock armor stands away when mob griefing is on (Ravager.roar) 2026-11-07 23:24:19 +01:00
Kacpherek 2d94afaa61 Keep counting time since last rest on the death screen (ServerPlayer.doTick)
time_since_rest now counts every tick the player is not sleeping, dead or alive, as ServerPlayer.doTick does; time_since_death still counts only while alive.
2026-11-07 23:23:39 +01:00
Kacpherek 14a5193b41 Use up a knowledge book and swing the arm at once on servers (KnowledgeBookItem.use) 2026-11-07 23:23:35 +01:00
Kacpherek 00d050bb8f Show each worn item's own camera overlay (Hud.extractCameraOverlays)
Items a server or datapack gives a camera_overlay now draw it in first person when worn in their equippable slot, and a carved pumpkin whose equippable was removed no longer blurs the screen.
2026-11-07 23:23:29 +01:00
Kacpherek 7225a84b10 Count thrown snowballs, eggs, pearls, potions and xp bottles as used (throwable Item.use)
Throwing a snowball, egg, ender pearl, splash or lingering potion or bottle o' enchanting awards the used statistic, as SnowballItem, EggItem, EnderpearlItem, ThrowablePotionItem and ExperienceBottleItem.use do.
2026-11-07 23:23:21 +01:00
Kacpherek 40afd73cd8 Draw wings and hide the cape by the chest stack's own equippable (WingsLayer.submit, CapeLayer.hasLayer)
A chestplate a server gives elytra wings now shows them and hides the cape, and an elytra whose equippable was changed or removed no longer shows elytra wings.
2026-11-07 23:23:03 +01:00
Kacpherek c54c8c0f42 Let a beached nautilus dry out instead of drowning, and spare NoAI ones (Nautilus.handleAirSupply) 2026-11-07 23:23:02 +01:00
Kacpherek 939d492535 Let sculk hear item frames break as a block change too (ItemFrame.dropItem)
A frame broken by a player, an explosion or losing its support posts block_change after its drops, as ItemFrame.dropItem(level, causedBy) does, on top of the entity_die it already posted.
2026-11-07 23:22:57 +01:00
Kacpherek 41934f3d93 Let sculk hear items knocked out of item frames (ItemFrame.hurtServer)
Punching the item out of a frame posts block_change with the attacker as source after the item drops.
2026-11-07 23:22:45 +01:00
Kacpherek 85a6a8b9dc Let sculk hear items put into or turned in item frames (ItemFrame.interact)
Putting an item in a frame or rotating it posts block_change with the player as source, after the item or rotation changes.
2026-11-07 23:22:36 +01:00
Kacpherek 4ca3d55e78 Draw worn armour from the stack's own equippable asset (HumanoidArmorLayer.renderArmorPiece)
Armour a server or a command gives a different or removed equippable now renders with that asset, or not at all, and only in its own slot, on players, mobs and armour stands. The head layer draws a helmet item when its equippable has no asset.
2026-11-07 23:22:27 +01:00
Kacpherek b97f0f61d7 Let sculk hear endermen pick up and put down blocks (EnderMan block goals)
EndermanTakeBlockGoal.tick posts block_destroy and EndermanLeaveBlockGoal.tick posts block_place, each with the enderman and the block state as context.
2026-11-07 23:22:05 +01:00
Kacpherek 0c40da1a82 Let an opening shulker lift and push you on servers too (Shulker.onPeekAmountChange on the client) 2026-11-07 23:22:04 +01:00
Kacpherek e01adc67e3 Let Thorns hurt a player who sweeps its wearer in PvP (Player.doSweepAttack's doPostAttackEffects) 2026-11-07 23:21:48 +01:00
Kacpherek 32137ae44f Answer pandas' clicks on servers as vanilla does: scared ones pass, ones on their back swing, adults leave bamboo to the off hand (Panda.mobInteract) 2026-11-07 23:21:39 +01:00
Kacpherek 9503a3cc7d Let sculk hear copper golems open and close chests (ContainerOpenersCounter)
The first golem to open a chest half posts container_open with the golem as source, the last to close it posts container_close (incrementOpeners / decrementOpeners), and the openers recheck posts a sourceless container_close when the golems have walked off (recheckOpeners).
2026-11-07 23:21:26 +01:00
Kacpherek 7c4a6d1ea6 Use the held item on a pig or strider someone already rides on servers (Pig/Strider.mobInteract) 2026-11-07 23:21:14 +01:00
Kacpherek 3c4d936707 Say "formerly known as" when a renamed player joins a server (PlayerList.placeNewPlayer) 2026-11-07 23:21:11 +01:00
Kacpherek 44f5a37e64 Open a wandering trader's trades on servers without swinging the arm (WanderingTrader.mobInteract) 2026-11-07 23:21:01 +01:00
Kacpherek 5ffd5c6515 Use the held item on a sleeping villager on servers instead of swallowing the click (Villager.mobInteract) 2026-11-07 23:20:45 +01:00
Kacpherek 8cd7616054 Let breezes whirl and idle on servers too (Breeze.tick and Breeze.playAmbientSound on the client) 2026-11-07 23:20:44 +01:00
Kacpherek ea99e6572c Let sculk hear glass bottles filling and count their uses (BottleItem.use)
Filling a bottle from water now plays the fill sound at the player and posts fluid_pickup at the water block; both the water and the dragon's breath branch award the used statistic (BottleItem.turnBottleIntoItem), and collecting dragon's breath fires player_interacted_with_entity on the cloud.
2026-11-07 23:20:32 +01:00
Kacpherek c5dbb620c2 Let sneak-clicks and clicks on occupied cushions reach the held item on servers, without an arm swing (Cushion.interact) 2026-11-07 23:20:24 +01:00
Kacpherek 642ac0d489 Play the warden's heartbeat on servers too (Warden.tick's client branch) 2026-11-07 23:19:51 +01:00
Kacpherek 92bedb26d0 Show team colours and prefixes in /list on LAN worlds (ListPlayersCommand.listPlayers uses Player.getDisplayName) 2026-11-07 23:19:40 +01:00
Nikita Maximilian Grimm 3d8924dcc8 Merge remote-tracking branch 'origin/main' into tnt-piston-ground 2026-11-07 23:15:42 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 8ad82f9ac0 A piston push sets an item's or primed TNT's on-ground flag as vanilla does
Entity.move(MoverType.PISTON) ends in setOnGroundWithMovement on a server,
for every push: a sideways push clears the flag, and so does a free push
down. The ArmorStand-only repair in move_pushed becomes a trait method that
items, primed TNT and armor stands share.

Fixes #12029

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:15:41 +01:00
Web-mc1 77290ac3c1 telemetry: match the user name exactly when lowercasing moves boundaries
`replace_word` lowercased the text to find the user's name in any case, and
used that copy whenever it had the same byte length as the text. Equal
lengths don't imply equal boundaries: `İ` (U+0130) grows from 2 bytes to 3
and `K` (U+212A) shrinks from 3 to 1, so a text holding both keeps its
length while its offsets move. A match then sliced the original text
mid-character and panicked.

Use the lowercased copy only when the two share their character boundaries.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-11-08 11:12:29 +13:00
Nikita Maximilian Grimm daa43de927 Merge remote-tracking branch 'origin/main' into boat-drop-motion 2026-11-07 23:10:52 +01:00
Nikita Maximilian Grimm 3fb98b187f Merge remote-tracking branch 'origin/main' into boat-fire-timer 2026-11-07 23:10:51 +01:00
martipopsandClaude Opus 5.5 76db917ded Controller settings: a Nintendo Buttons row (By Position / By Letter)
The Device page gets a row beside Button Glyphs that toggles
PadSettings::nintendo_letters, so players no longer edit
horizon-controller.txt to make A confirm and jump on a Nintendo pad.
Its description says what A and B do in each mode. Always shown, like
the DualSense rows. docs/controllers.md points at the row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:09:01 -05:00
VaspyyyandClaude Opus 5.5 1ba320ca73 Vaults: list the players only when a vault looks for them
with_vault built the list of every player (lan_present: eye heights, effects,
omens) for every loaded vault every tick. VaultBlockEntity.Server.tick reads the
players only when the vault's state may change (stateUpdatingResumesAt, once a
second), so the list is now built at the first ask, from the same game state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:01:12 +01:00
Vinícius MoreiraandClaude Opus 5.5 721d4cfa44 Resource packs: a pack's core/sky and core/stars shaders
A resource pack's core/sky now draws the overworld's sky disc and its
core/stars the stars, as vanilla's SkyRenderer does with the SKY and
STARS pipelines: the disc of buildSkyDisc(16) with the sky colour in
ColorModulator and the sky's fog, the stars with their brightness, both
turned with the camera only. Without such a pack the sky draws natively.

Packs use this to tint the night sky or add a haze to the horizon. With
Visual Effects+'s sky shaders alone, Horizon's sky now reads within a few
units of the Java client's at noon, sunset and night.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:47:59 -03:00
martipopsandClaude Opus 5.5 78b21e4afb Graphics moves onto the settings shell
Part of #11487. The graphics screen now describes its pages and rows
(`GraphicsScreen`), and the shell draws them, takes the clicks, the wheel,
the stick, the keys and the pad's focus, as it does for Extras. What each
setting does, its saved value, its cost and its description stay in
graphics_ui as they were; Undo puts back the same settings.

What changes beyond what the shell gives every page: the HDR shortcut row
shows its key on a key button, as Extras' Sort key does, instead of between
arrows. The screen's own keyboard, scrolling and drawing code goes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:47:11 -05:00
martipopsandClaude Opus 5.5 26496db7c3 Merge upstream/main into controller/direct-craft
Main moved key_pressed to game/play_keys.rs and inventory_press to
game/inventory_input.rs; the craft's stop on a key or mouse press moves
with them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:46:48 -05:00
Web-mc1 37b79d1b63 java_properties: write a NUL and a non-BMP character as Java does
saveConvert pushed one UTF-16 unit at a time and marked a surrogate half with
a NUL sentinel, then ran fix_surrogates over the whole value, which split every
NUL in the result. A \u0000 that is part of a value (legal in a .properties
file) was therefore taken for a marker: "k=\u0000\uD83D\uDE00x" came back from
store with the NUL and both halves of the pair replaced, and since
server.properties is rewritten on every start the value could not survive a
round trip. Walk chars() instead: a Rust str's UTF-16 units always pair up, so
Java's per-char loop needs no marker, and a character past U+FFFF is still
escaped as the two units Java escapes it as.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-11-08 10:44:43 +13:00
martipopsandClaude Opus 5.5 d5f931ca64 Controllers: LT + A on a recipe crafts it, held to keep crafting
LT + A on a crafting book recipe crafts it into the inventory: a tap makes
one, each further LT + A while one is in flight makes one more, and held past
the repeat delay it keeps going until a button comes up, the items run out
or the inventory is full. One request at a time, each waiting for the
server's answer; a result moves only with room for all of it as the client
last saw the inventory. A result that isn't the recipe's stops the craft with
nothing moved, and two seconds with no answer stops it with nothing more
sent. A refused LT + A (a carried stack, another recipe still finishing, not
allowed here) is plain A.

It's free in single player and on LAN worlds joined from the server list's
LAN entries; everywhere else, joins by address included, it waits for Quick
Craft on Servers. On any server but single player's own, placements keep
250 ms apart, under Paper's default limit on recipe placements (5 a second
over 4 seconds); on servers that need the option, every request also keeps
a tick apart.

On the crafting book LT changes the category as it comes up unless A was
pressed meanwhile; RT, and both triggers on the furnace books, change it as
they go down, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:41:47 -05:00
KyttuXDandClaude Haiku 5.5 702b0895bd Draw vanilla terrain flat on Metal at any section count
On Metal, vanilla terrain drew flat only past 1600 listed sections. Cave
culling can drop the listed count below that on a normal view, and the
per-section path then drops cutout leaves on Intel Metal: the canopy above
trunks vanished. Flat draws keep them, so Metal now always draws flat.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-07 16:41:30 -05:00
martipopsandClaude Opus 5.5 a08827d6d5 Settings shell: Undo, a row's cost and why it is greyed
Part of #11487. What the graphics screen has that the shell couldn't say
yet, for any screen that wants it:

- Undo over Done once a row changed something, putting back what the
  screen says it changes (`Screen::undoes`, `Screen::undo`), from the
  settings as the screen found them. Tab and the arrows reach it.
- A row's cost, a square and the cost in its colour after its name in the
  strip.
- Why a greyed row can't be used, in the strip, muted, instead of what it
  does.
- `Shell::show` opens a screen at one of its pages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:37:34 -05:00
martipopsandClaude Opus 5.5 4465238c9c Settings shell: build rows once, Down from search to the list, reveal clipped rows
Part of #11487.

- The shell keeps the rows it built and builds them again only when what
  they read changes: the screen's stamp of its settings, a press or slide,
  the search, the page, the size or the language. On Extras, a pad session
  of 727 frames built them twice instead of 751 times.
- On a screen with no page list, Down from the search field goes to the
  first row instead of Done, for the shell's keys and, through a declared
  focus link, for the pad and the keyboard's focus.
- A row the list hides part of scrolls fully into view when the pad or the
  keyboard focuses or presses it (AbstractSelectionList.setSelected), so A
  presses it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:35:56 -05:00
Nikita Maximilian Grimm 43943df1ef Merge remote-tracking branch 'origin/main' into boat-drop-motion 2026-11-07 22:29:00 +01:00
KBroneZandClaude Opus 5.5 8906102eb9 chore(launcher): add the found list's string before each table's last entry
Inserting "Found on this computer" before the last entry of each language
table, instead of after it, adds one line per file and leaves the last line
alone, so other pull requests that append strings don't conflict with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:23:19 +02:00
KBroneZandClaude Sonnet 5.5 0a51d6dc5c fix: shadow the TCP keepalive instead of mutating it, so Windows builds are lint-clean
`let mut keepalive` was only assigned under
`#[cfg(not(any(target_os = "windows", target_os = "openbsd")))]`, so on
Windows and OpenBSD clippy reported `unused_mut` and `-D warnings` failed.
Shadow the binding under the same cfg instead; behaviour is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:22:22 +02:00
KBroneZandClaude Opus 5.5 21ca2fdd1d refactor(launcher): drop the found list's caption; check slugs against import
The "Found on this computer" heading says enough on its own, and the caption
cost a string in every language table. The test now checks that each found
instance's slug is the one importing it gives, so the Open button keeps
pointing at the pack an import made.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:15:51 +02:00
Nikita Maximilian Grimm 89a515a8d7 Merge remote-tracking branch 'origin/main' into boat-fire-timer 2026-11-07 22:14:37 +01:00
KBroneZandClaude Sonnet 5.5 a0f9368edf feat: the launcher plays a profile that only has data packs
Imported.datapacks counts the packs in a profile's home/new-world-datapacks,
`can_play` and `apply_profile` accept a profile with only data packs, and
`outcome` and `modpack list` count them.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:13:52 +02:00
KBroneZandClaude Sonnet 5.5 1f86e14b9a feat: port data-only mod jars as data packs for a modpack's new worlds
A mod jar with no classes, a pack.mcmeta and a data/ folder is a data pack.
For a 26.2 or 26.3 modpack, `port` now upgrades such jars to 26.3 (the
upgrade-datapack code; 26.3 ones are copied) into the profile's
home/new-world-datapacks/ instead of carrying them as content mods, which
dropped their data/minecraft overrides. The game copies that folder into
each new world it creates.

Before its jar is read, a mod whose Modrinth project also ships as a data
pack counts as data tier, so `fetch` gets the jar; the jar then decides.
The coverage report lists such a jar as partial.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:13:51 +02:00
SenjinandClaude Opus 5.5 5ec521bb7b Shader packs: Horizon's dynamic lights as uniforms, horizonTier for terrain and entities
horizonDynamicLightCount and horizonDynamicLight0..15 give a pack Horizon
Extras' dynamic lights, nearest first (camera-relative position, light
level). horizonTier gives terrain, entity and hand programs a face's HDR
tier: 0 none, 1 to 4 low to very bright, plus 4 on terrain when the whole
face shines. Opt-in: a pack that declares none of them sees no change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:13:03 +01:00
Nikita Maximilian Grimm 80bbced3fc Merge remote-tracking branch 'origin/main' into fix/diode-moving-piston-support 2026-11-07 22:12:23 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 c30b863128 Let water a boat drops into along its move put its fire out
Entity.collidedWithFluid sweeps the box along the whole move, so water reaches
the boat down to the lower of its start and end bottoms in every step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:12:17 +01:00
KBroneZandClaude Opus 5.5 690d434afa feat(launcher): list other launchers' modpacks on the Modpacks page
The Modpacks page now opens with "Found on this computer": the modpack
instances the CurseForge app, Prism Launcher, MultiMC, the Modrinth App,
ATLauncher and the official launcher keep in their usual folders, read with
`other_launchers::scan` on a thread. Each row shows the app, Minecraft
version and loader, and imports the instance with one click through the
same path as "Import an instance folder…" (a Prism instance from its own
folder, so its `mmc-pack.json` still names the version). A pack already
imported opens instead.

Only instances with a `mods` folder of their own are listed: the official
launcher's profiles that play in its own folder are the player's everyday
game, not a pack. The two new strings are in every language table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:10:54 +02:00
Florian ErnstandClaude Opus 5.5 c0806b9ee3 Keep a failed wildcard set's edit in command storage
StorageDataAccessor.getData returns the stored compound itself, and
DataCommands.manipulateData edits it in place. A wildcard set on a
non-empty byte, int or long array clears the array before it rejects a
string, so the command fails with nothing counted and the storage keeps
the cleared array. Horizon edited a copy and dropped it on the failure.

On that failure, a /data modify on storage now puts the edited compound
back with CommandStorage::set_unsaved: only an id that is stored is
replaced, and the storage is not marked for saving, as vanilla calls no
setData. The error, the result, the success path and the entity and
block copies are unchanged.

Fixes #12057.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:08:42 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 f57811dd0d Drop a destroyed boat's item with an item entity's own motion
VehicleEntity.destroy spawns the boat item through spawnAtLocation, so it
leaves with ItemEntity's default motion (0.2 up, random sideways), not
straight up at 0.1. Chest contents keep their own scatter. Fixes #12026.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:05:45 +01:00
KBroneZandClaude Opus 5.5 70bc17720c fix(launcher): keep a Prism root's instances folder from reading as CurseForge's
Where folder names ignore case (Windows, macOS), a Prism or MultiMC root's
`instances` folder is also `Instances`, so `in_folder` took it for the
CurseForge app's modding folder and found nothing. It now reads that folder
as CurseForge's only when none of its instances has an `mmc-pack.json`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:03:37 +02:00
Nikita Maximilian GrimmandClaude Opus 5.5 73e054f827 Apply a boat's fire block effects in the order its move meets the blocks
Entity.checkInsideBlocks meets the blocks of the box a move starts in before
the ones it reaches, each once, and each step lights before it puts out: a
boat that leaves water for fire in one move ends up burning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:01:24 +01:00
Mik00000 e1434f2ee4 perf(game): reduce dimension swap overhead and cache raycast chunk lookups 2026-11-07 22:58:20 +02:00
bulkandClaude Opus 5.5 25ea320338 Streaming: rank decoration by rank alone
Decoration scheduling measured, sorted and ranked every proto chunk each update.
Ranks are unique, so only chunks without one need their distance; the rest
pop from a heap until the workers are busy. A server with 200 players spread
over the map held ~57,000 protos and spent a fifth of its tick here.

The heap pops in the order the full sort gave; unranked chunks at the same
distance now go by position instead of where the unstable sort left them.

(cherry picked from commit d20e7bf74e)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:57:34 +00:00
KBroneZandClaude Opus 5.5 6fa7f8896a feat(launcher): find instances in the CurseForge app's Instances folder
`instance others --folder` and `copy-from --folder` now accept a folder whose
children are CurseForge instances, the `Instances` folder the app shows the
player, as well as the modding folder above it. Before, that folder found
nothing.

When nothing is found, the message says where it looked (the folder named, or
every default folder the scan reads) and which folders it expects. The
CurseForge folder is joined one component at a time, so its path no longer
shows mixed separators on Windows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:57:04 +02:00
Florian ERNSTandCodex 67a39ecaac Project ground after unoccupied server NoAI Mob piston movement
Co-Authored-By: Codex <[email protected]>
2026-11-07 21:56:55 +01:00
KBroneZandClaude Sonnet 5.5 199d9d74f8 fix: run tools/neoforge_oracle.py on Windows
Windows users cannot create symlinks without a privilege (WinError 1314), and NeoForge's
unix_args.txt gives "Illegal char <:>" there. Link the server's libraries folder with a
junction and the mod jars with a hard link, copying when that fails; use win_args.txt on
Windows. Linux and macOS keep the symlinks and unix_args.txt. Adds tests/test_neoforge_oracle.py.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 22:55:49 +02:00
TheMrZZandCodex 1005076a59 Route recipe-book placement through actual furnace menus
Reuse the existing machine menu cache, shared placement and authoritative
slot writeback for ordinary PlaceRecipe packets. Preserve inventory/table
placement and the separate Horizon recipe-transfer route.

Fixes #12009

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
2026-11-07 21:49:12 +01:00
bulkandClaude Opus 5.5 94ed2f4cc8 Beehives: ask once per hive turn whether bees stay in
bees_stay_in_hive built the mob world (every mob and player) for each occupant
whose time was up. The night and rain it reads hold for the hive's turn.

(cherry picked from commit 3430283af0)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:48:44 +00:00
bulkandClaude Opus 5.5 517f54d076 Streaming: know the extra cover is current instead of comparing it
Every in-range check compared the cover's copy of the extra list (about 200
entries on a spread server) with the live one, for each waiting chunk each
tick. The cover is refreshed at the start of update; update now says so and
the checks trust it, with a debug assertion that they still match.

(cherry picked from commit f61e6ed98d)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:48:44 +00:00
bulkandClaude Opus 5.5 9626c7446e Creaking hearts: build the mob world only for the heart's update
A heart built the mob world (every player, the teams, the weather) each tick,
but reads it only in the update about once a second. server_tick is split at
that point; the game builds the world for the update only. The heart's
creaking, asked for a few times a tick, is found through the mob index
instead of a scan.

(cherry picked from commit a1cf6491dd, with the mob index
in place of its own slot map)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:48:44 +00:00
bulkandClaude Opus 5.5 da2b437f49 Spawners: count the delay down without building a level
BaseSpawner.serverTick only decrements a running delay. The level (every
player, the mob world) was built for each spawner near a player every tick
first.

(cherry picked from commit 1f06b720c9)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:48:44 +00:00
bulkandClaude Opus 5.5 6e0f482e83 Structure starts: keep four times as many chunks cached
Players spread far apart read more start chunks than the cache held, so
outposts' and trial chambers' jigsaws were built again on the server thread
whenever natural spawning asked about them.

(cherry picked from commit da2c8d2d48)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:48:44 +00:00
Nikita Maximilian Grimm 8189734106 Merge remote-tracking branch 'origin/main' into fix/diode-moving-piston-support 2026-11-07 21:46:30 +01:00
KBroneZandClaude Sonnet 5.5 1f29c88a49 feat: copy a game folder's new-world-datapacks into every new world
A game folder can hold a `new-world-datapacks` folder. Create New World now
seeds its temporary data pack folder from it and selects those packs, and a
world opened without the Create screen (`--world`, the control socket) gets
a copy when it has no level.dat yet. Each world keeps its own copy. Without
the folder nothing changes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 22:46:25 +02:00
Nikita Maximilian GrimmandClaude Opus 5.5 bf0f0dd811 Wear off a driven boat's damage before it burns, and let water it left put it out
AbstractBoat.tick decays the damage before Entity.baseTick burns the boat, also
for a boat its rider's client moves, and the block effects follow the whole
move, so water the boat started in still puts it out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:44:44 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 007458a627 A repeater or comparator on a retracting piston stays, as in vanilla
DiodeBlock.canSurviveOn asks isFaceSturdy(level, pos, UP, RIGID) of the
block below, in canSurvive and in updateShape with the neighbour's new
state. A retracting piston base is a moving_piston whose block entity
shape holds the extended base, so its top face is rigid. The diode checks
read the raw state's exported facts instead, saw no support, and broke the
repeater or comparator. Both paths now go through the contextual rigid
support, which takes the state a shape update hands over.

The redstone catalog harness gains fixed lever/piston/diode contraptions
for both piston and both diode kinds (#12019).

Fixes #12019

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:29:19 +01:00
Nikita Maximilian Grimm 9c30028167 Merge remote-tracking branch 'origin/main' into execute-block-nbt 2026-11-07 21:28:43 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 0d49b282c0 Read a block predicate's NBT with the argument's own SNBT grammar
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:28:40 +01:00
Florian ErnstandClaude Opus 5.5 099fb70e6a Pick up a sulfur cube with an empty bucket
SulfurCube.mobInteract ends with Bucketable.bucketMobPickup, and a sulfur
cube is picked up with an empty bucket (canBePickedUpWithBucket), not a
water bucket. Horizon's bucket pickup only knew the water bucket's mobs,
so a click with a bucket left the cube where it was.

After the cube's own baby, primed, shears and swallow branches, an empty
bucket now plays the sulfur fill sound, fills a sulfur_cube_bucket, fires
filled_bucket and player_interacted_with_entity, drops the leash, discards
the cube and gives the bucket through ItemUtils.createFilledResult, as the
other bucketable mobs do. The native bucket hook hears it.

The filled bucket carries SulfurCube.saveToBucketTag: the cube's age and
age_locked in bucket_entity_data, and its body block as
sulfur_cube_content when it has one. Other species keep their bucket data.

The command harness gets a mob_interact op: the connected player's real
Interact packet on a mob, on both sides.

Fixes #12044.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:26:20 +01:00
Florian ErnstandClaude Opus 5.5 38a1babc5a Use the archetype data's float for the knockback modifier amount
The archetype table keeps knockback resistance as a decimal double for
the physics code. The data's modifier amount is the float widened
(0.4000000059604645 for slow_bouncy), so /attribute read 0.4 and 0.7
where vanilla reads 0.4000000059604645 and 0.699999988079071.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:26:16 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 c7aef39dd5 Burn boats: live fire timer, fire damage and both block-effect passes
A boat now keeps Entity.remainingFireTicks: Entity.baseTick burns it down a
tick at a time and hurts it every 20 ticks, and the two applyEffectsFromBlocks
of AbstractBoat.tick light it on fire blocks, hurt it once per fire block,
let water, powder snow and rain put it out and clear the cooldown. Saves,
/data, portals and the root vehicle write the live Fire; loads and /data
merge read it. Fixes #12025.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:24:20 +01:00
TheMrZZandCodex gpt-6.1-sol d7c3fefcfa Preserve Nautilus cooldown memory presence and lifetime
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 21:23:19 +01:00
Florian ERNSTandCodex 8b48b0d74e test: checkpoint H255 piston ground regression before claim-cap decision
Qualified old-source failure only; no production repair or fixed-pass claim.

Co-Authored-By: Codex <[email protected]>
2026-11-07 21:19:53 +01:00
Florian ErnstandClaude Opus 5.5 3e5e8c4841 Give a sulfur cube its body archetype attribute modifiers
SulfurCube.collectEquipmentChanges runs in LivingEntity.tick
(detectEquipmentUpdates) when the body item changed. It removes the
previous body's archetype modifiers and adds the new body's as transient
modifiers: knockback_resistance, explosion_knockback_resistance and
bounciness (add_value), friction_modifier and air_drag_modifier
(add_multiplied_total). /attribute read the defaults for these five on a
cube with a body.

A sulfur cube now has its own attribute map from its type's defaults.
The five attributes go to that map, and the tick adopts the body's
modifiers there with the existing AttributeInstance operations. A
transient modifier shadows a permanent one with the same id, and the
removal takes both, as in vanilla. The archetype table also gets its
explosion knockback resistance, from the 26.3 data.

The save writes the base and the permanent modifiers of these instances,
not the transient ones. A command change of the knockback base or of a
permanent modifier also goes to the store that the bodiless physics
reads, so that effect stays as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:18:07 +01:00
Nikita Maximilian Grimm 5664a950e8 Merge remote-tracking branch 'origin/main' into execute-block-nbt 2026-11-07 21:17:10 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 538422f3c7 Match the NBT part of a block predicate against the block entity
execute if|unless block, fill ... replace and clone ... filtered tested only
the block state; BlockPredicateArgument also compares the {...} part with the
block entity's full saved data (NbtUtils.compareNbt), and a block without a
block entity fails it.

Fixes #12030

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:17:09 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 80e3532c4a docs: HDR design note: step 4 writes light a whole frame at a time
A blended draw over a surface of the other kind leaves one mark for both, so a frame that mixes
marked and written light would clip the written light and lift it again, or leave the marked part
unlifted. Step 4 now goes path by path: the frame-case rebuild first, then every marking shader on
the default path in one pull request, then Improved Transparency and the visibility buffer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 21:06:12 +01:00
Florian ErnstandClaude Opus 5.5 b528247824 Merge origin/main into fix/h275-test-defs-world-packs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:59:27 +01:00
Florian ErnstandClaude Opus 5.5 ed1ce7495e Merge origin/main into fix/chorus-projectile-drops
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:59:09 +01:00
MSedgeMC d1f8cccb7c A mob stops chasing a target outside its home
`MeleeAttackGoal.canContinueToUse`'s follow branch returns
`isWithinHome(target.blockPosition()) && !(target is a spectator or
creative player)`. Horizon's `MeleeAttack::can_continue` only refused a
creative player: a mob with a home kept chasing past its radius, and a
player who became a spectator was still chased.
2026-11-07 19:46:00 +00:00
MSedgeMC e8da3a8e21 A drowned stops the trident attack when it loses the trident
`DrownedTridentAttackGoal` overrides `canUse` with the trident test and
inherits `RangedAttackGoal.canContinueToUse`, which calls `canUse()` again
(and falls back to a target it is still walking towards). Horizon's
`DrownedTridentAttack::can_continue` asked only the base ranged goal, so a
drowned whose trident was gone kept the trident attack running once its
path was finished.
2026-11-07 19:42:47 +00:00
Mateusz KorniakandClaude Opus 5.5 3004b64927 Fix speckled players with Improved Transparency on Metal
fs_oit_cull writes the nearest opaque see-through depth into the depth
buffer, and the later OIT stages test GreaterEqual against it, so an opaque
fragment is compared with its own depth. On Metal, position.z can differ from
the rasterizer's depth by an ulp, which dropped random pixels of players and
mannequins (horizontal dashes, text behind showing through). Write the depth
4 ulps farther: the fragment still passes, anything visibly behind is culled.

Checked on macOS (Metal, Apple M1) with a mannequin and a text display; not
yet on Linux (Vulkan).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:38:40 +01:00
Florian ERNSTandCodex 60a2c3f164 Preserve loaded NoAI Enderman absolute anger timestamps
Co-Authored-By: Codex <[email protected]>
2026-11-07 20:36:12 +01:00
VaspyyyandClaude Opus 5.5 abdf311e3b Native mod API: muffle the game's sounds for a while (native_muffle_sounds)
After a close blast a mod can now dull and quieten the world's sounds while
its own ringing plays clearly: native_muffle_sounds(amount, lowpass, ticks,
exempt) turns every sound down by `amount` and low-passes it by `lowpass`
(down to 300 Hz), both fading back over `ticks` client ticks and held while
the game is paused. The sound events in `exempt` play through untouched,
those already playing too.

The mixer mixes the muffled sounds into a bus of their own, runs two
one-pole low-pass stages and the duck over it, and adds it to the exempt
ones. The level glides over 20 ms so tick-sized steps don't click. While no
muffle is set or once it has faded, sounds mix straight into the output as
before. The sound engine marks a channel exempt as it starts, and marks the
playing ones again when the list changes.

Helper-only fragment muffle_sounds. Fixes #12006

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:34:54 +01:00
MSedgeMC f96e0fba0f A tamed cat stops being tempted
`CatTemptGoal` overrides `canUse` with `!cat.isTame()` but does not
override `canContinueToUse`; `TemptGoal.canContinueToUse` ends with
`return this.canUse()`, so taming a cat mid-tempt ends the goal. Horizon's
`CatTempt::can_continue` ran only the base `Tempt` continue, which never
asked whether the cat was tamed, so a cat tamed while following a fish
kept following it.
2026-11-07 19:32:24 +00:00
VaspyyyandClaude Opus 5.5 653a4a99fe Native mods: a game horizon-mixins built has the mod image slot
The HUD atlas reserved `horizon/modimage` (native_mod_image, API 355) only
when the launcher's native-mods.json listed mods, so a bundle applied with
horizon-mixins by hand or by a mod's own script built a game whose
native_mod_image always returned false.

horizon-mixins leaves .horizon-mixins-stage.json at the root of every
workspace it changes, naming each injection's and module's mod. The build
script turns a record that names mods into HORIZON_MIXIN_MODS, and
built_with_native_mods counts it and installed trait mods as well as
native-mods.json. A release or Nightly has none of them and keeps no slot.

Fixes #12005

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:26:53 +01:00
Mik00000 65c35da0dc mobs: reuse pathfinding allocation buffers across queries 2026-11-07 21:21:07 +02:00
Nikita Maximilian GrimmandClaude Opus 5.5 4fa237a12e HDR layered frame: a tone curve eases the light into the peak
After the post effects and before the camera overlays, ITU-R BT.2390's EETF in PQ rolls the
light off into the peak, on its brightest channel so it keeps its hue. It takes over the HDR
lighting's easing and the light sources' cap at the peak, which the resolve pass no longer
applies. The knee stays where the lighting's was, 60% of the peak.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:14:01 +01:00
MrCloudy2andClaude Opus 5.5 772088790c lan_e2e: sprint-hit-slowdown builds its sprint with a run-up
An absolute /tp zeroes the player's speed, as vanilla's does
(TeleportCommand's relatives carry no DELTA), so the check's teleport
right before the hit left the guest at walking speed and the check
failed on main. The guest now runs 19 ticks from 8 blocks out and
clicks in reach. The slowdown assertion is tightened: the first
post-hit sample must be under 0.75 of the sprint speed and then climb,
which fails with the client's 0.6 cut removed (the old 0.9 bound did not).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:14:01 +01:00
masa-masa-0314andZCode aaa674f54b Realms: the screens follow vanilla's layout, state and input
The parity work after the per-screen PRs (#9714, #9836, #9909, #9926,
#9968, #9982, #10032, #10391, #10448, #11640), as verified in the local
playtest builds:

- Main list: RealmsMainScreen's header and footer geometry, row content
  and status light, scrolling, notices, selection narration, and the
  60 s/10 s/300 s data-fetcher periods.
- Configuration screen: the four tabs (MenuTabBar), GridLayout columns,
  slot options, region preference, invite codes and their edit screen,
  the players tab (invites, operators, removal), the subscription tab
  and the tab keyboard.
- World screens: RealmsResetWorldScreen's tiles, the template list, the
  upload selection and upload screen, and the PDP rows and keyboard.
- Backups: RealmsBackupScreen/RealmsBackupInfoScreen on the current wire
  (lastModifiedDate, metadata as strings, a local changeList), restore
  as RestoreTask (retries, abort), and the complete Download Latest flow:
  DownloadTask, RealmsDownloadLatestWorldScreen's size check, bar, speed
  and cancel, and FileDownload's tar.gz unpack (name cleanup, world/
  entries only, level.dat renamed, resource pack SHA-1 checked).
- Settings: RealmsSettingsTab's GridLayout/ScrollableLayout, the
  distance sliders, the name validation, and tooltips drawn after every
  widget.
- Service: the ops/invites endpoints, the invite answer's players, the
  backup age on the wall clock, null gameMode, and news persistence.
- Integrated server: the owner and the memory connection's login use the
  account profile (IntegratedServer.setSingleplayerProfile,
  ServerboundHelloPacket), so a world without singleplayer_uuid (a Realms
  download) loads the owner's players/data file; saveAllChunks'
  saveDataTag(profile.id()) is mirrored by save_owner.

Tests: 2166 lib tests pass (65 realms), scoped clippy clean.

Co-Authored-By: ZCode <[email protected]>
2026-11-08 03:00:28 +08:00
Florian ErnstandClaude Opus 5.5 ad475b0573 Load a world's test instances from its data packs when it opens
/test only knew the test instances of the game's own data: read_test_def
read options.resources, and the selector ids were the exported built-in
ones, so a test a world's data pack defined was "No matches for
selector". Vanilla 26.3 loads Registries.TEST_INSTANCE from the packs the
world enables when it loads: later packs override earlier ones and the
built-in data, and /reload or /datapack do not change it.

When a world opens (the end of load_world_state), the built-in pack's and
the initially enabled packs' test_instance files are read once, in pack
order, through the existing test instance decoder. They become the
world's test definitions (test_defs) and its minecraft:test_instance ids,
replacing the previous world's. /reload and /datapack leave them as they
are. A game with no world opened reads the game's own data as before.

Fixes #11976

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:59:12 +01:00
Florian ERNSTandCodex aa019cfaa4 Canonicalize two saved adventure predicate forms
Co-Authored-By: Codex <[email protected]>
2026-11-07 19:58:10 +01:00
Horizon agent dd0050e268 Merge remote-tracking branch 'origin/main' into cg65v-10559
# Conflicts:
#	crates/horizon-client/src/game.rs
2026-11-07 19:56:17 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 9e962f6350 HDR layered frame docs: say what a screenshot shows without promising the tone curve changes it
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:55:14 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 78ea4b6d02 HDR layered frame: drop the coverage debug flag the display pass no longer reads
The coverage view is chosen once, when the shader is wrapped; nothing reads the field after.
Also lets a test fill the coverage with its own f64.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:51:26 +01:00
Florian ErnstandClaude Opus 5.5 56a578f0a6 Merge origin/main into fix/h170-place-feature-inline
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:50:54 +01:00
Florian ErnstandClaude Opus 5.5 e2367a4b6a Skip the full Mob tick tests without the vanilla data
CI has no prepared resources, so the assert on the test world failed
there. Do what the other test-world tests do: check nothing when the
data is missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:49:30 +01:00
Florian ErnstandClaude Opus 5.5 596fda5618 Overlap note: check heads in one git call, diff in parallel
The workflow's clone is blobless, so `git cat-file -e` on a head it
does not hold fetches it from the server, one round trip per check.
On busy days the job ran into its 10-minute timeout. Check every head
in one `cat-file --batch-check` with lazy fetching off, and run the
diffs on 8 threads so their blob fetches overlap. A note for #11723
now takes 13 s instead of 170 s; `show` over every open pull request
29 s instead of 785 s, with the same notes.

Closes #11984

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:42:34 +01:00
TheMrZZandCodex gpt-6.1-sol 46b257b1d5 fix: honor supported Equippable overrides on item use
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 19:38:39 +01:00
MSedgeMC 8b0c8e40a6 A trader stops trading when hurt or out of reach
`TradeWithPlayerGoal.canUse` refuses a trader that `wasHurtRecently` or
whose trading player is more than four blocks away, but Horizon's
`TradeWithPlayer::can_use` checked neither. A wandering trader that took a
hit, or whose customer walked off, stayed in the stand-still trade goal
where vanilla ends the trade.
2026-11-07 18:34:07 +00:00
MSedgeMC d980cd810d A happy ghast on a still timeout stops floating
`HappyGhast.HappyGhastFloatGoal` overrides `canUse` with
`!isOnStillTimeout() && super.canUse()`. `FloatGoal` does not override
`canContinueToUse`, so `Goal.canContinueToUse` asks that same overridden
`canUse` on every tick: a player standing on the ghast makes it stop
floating. Horizon's `HappyGhastFloat::can_continue` re-ran only
`Float.can_use`, so the goal kept hopping in water under a player who was
holding it still.
2026-11-07 18:31:37 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 196bea6f1a HDR marks: entities, the hand and translucent particles mark at the entity pipeline's depth bias
#7820 gave the entity pipeline a constant depth bias of 128 so entities win the tie with
coplanar terrain. HDR output marks what it draws by drawing the same quads again, alpha only,
GreaterEqual against the depth it left, but without the bias: every mark tested a hair behind
that depth and failed. Mobs lost their HDR lighting, light sources in the hand stopped shining,
and the empty hand only looked right by reading the ground's mark behind it.

The marks after entities, the hand (unmark and mark) and translucent particles now draw at the
same bias. Translucent items, additive draws and the OIT stage follow unbiased pipelines and
keep the unbiased mark.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:27:20 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 cdabdddb6b HDR float frame: the HUD and menus lay over the world's light
On the float HDR frame the last pass guessed which pixels still showed the world
(`shows_world`) and clipped everything else at white, so the world's light dropped to
SDR under the chat's see-through background, a menu's backdrop and the coloured camera
overlays. Where the device records HUD coverage (#11896) the frame is now drawn in
layers, as the HDR note's step 3 specifies:

- After the world and the hand, `Hdr::resolve` turns the frame's marks into light once.
  The camera overlays, post effects and entity outlines draw on light after it.
- `keep_world` becomes a pass: the world clipped to white, alpha 0, into a HUD target in
  the frame's format, which the HUD and menus draw on with their unchanged blends.
- The last pass lays the HUD over the world's light by its coverage, in gamma as the HUD
  blends (H = P - (1 - c) B, then H ui^(1/2.2) + (1 - c) W). UI Brightness scales the
  HUD's own part.
- The menu blur blurs that composite, light included, and makes it the world the menu
  draws over.

Until the tone curve, a screenshot is the HUD target and the world icon the world, both
clipped at white; the -hdr.png is the full picture. The legacy path, the 16-bit frame and
HDR off are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:27:07 +01:00
abit-foggyandCodex GPT-6 e5fe17622c chore(studio): merge main into B2 branch
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 08:20:11 -10:00
Florian ErnstandClaude Opus 5.5 78efabcfa7 Copy a clone's pending block ticks to its destination
/clone placed the blocks but not the block ticks pending in its source
box, so a strict clone of fresh sand never fell, while vanilla 26.3's
CloneCommands.clone ends with LevelTicks.copyAreaFrom over the whole
source box.

cmd_clone now calls the existing LevelTicks::copy_area with the source
box and the destination offset, after the placements and block
entities and before the empty-count failure, as vanilla does. The core
copy (the box filter, trigger times, priorities, sub-tick reordering
and dedup) is unchanged. Block ticks only, in the same level.

Fixes #11963

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:16:16 +01:00
MSedgeMC 8d783c0ff0 A cube mob keeps still while it is a passenger
`AbstractCubeMob.CubeMobKeepOnJumpingGoal.canUse` is
`!this.cubeMob.isPassenger()`, but Horizon's `CubeKeepJumping::can_use`
returned true unconditionally. A slime or magma cube riding a boat, a
minecart or another mob therefore kept hopping and steering its vehicle
every tick, where vanilla leaves the vehicle alone.
2026-11-07 18:14:53 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 cbe9ddfa3f HDR marks: entities, the hand and translucent particles mark at the entity pipeline's depth bias
#7820 gave the entity pipeline a constant depth bias of 128 so entities win the tie with
coplanar terrain. HDR output marks what it draws by drawing the same quads again, alpha only,
GreaterEqual against the depth it left, but without the bias: every mark tested a hair behind
that depth and failed. Mobs lost their HDR lighting, light sources in the hand stopped shining,
and the empty hand only looked right by reading the ground's mark behind it.

The marks after entities, the hand (unmark and mark) and translucent particles now draw at the
same bias. Translucent items, additive draws and the OIT stage follow unbiased pipelines and
keep the unbiased mark.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 19:14:43 +01:00
Stink-OandClaude Opus 5.5 749c5405f6 World hold: its import on a line of its own, apart from the shared mod_api list
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:13:53 +00:00
Mik00000 bc8912c13f bench: add stress_mob_ai scene for active mob AI and pathfinding 2026-11-07 20:02:57 +02:00
Florian ERNSTandCodex 408e2606d8 Preserve weaker Mob effects through countdown and promotion
Keep active tuples authoritative and carry only fallback EffectInstance subtrees through Mob load/save and the audited mutation boundaries. Reuse the existing pure duration operation after server work.

Co-Authored-By: Codex <[email protected]>
2026-11-07 18:59:12 +01:00
Florian ErnstandClaude Opus 5.5 40ad3a91c9 Keep an Allay's liked_player memory time to live and expire it
An Allay loaded with a finite minecraft:liked_player memory kept it
forever and saved it without its ttl: the loader read only the memory's
presence and value, the save wrote the value, and nothing counted the
memory down.

- The memory's time to live is kept next to the existing liked-player
  state (None for a memory that never expires), read on load and
  written on save as MemorySlot.visit does.
- The Allay's AI step, which NoAI skips like customServerAiStep, ticks
  it as MemorySlot.tick does: it counts down, and is cleared on the
  tick after it reaches 0.
- Giving an item sets the memory without a time to live
  (Brain.setMemory), taking it back erases it, and the /data path that
  keeps the memory keeps its time to live too.

Fixes #11936

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:42:50 +01:00
SenjinandClaude Opus 5.5 fb3f1bce90 Shader packs: LabPBR maps for entities, items and the hand
The shared atlas's textures (items, entities, block entities) now bring
their _n and _s maps to shader packs as paged maps: 16x16 pages of the
atlas, only those holding a mapped texture stored, found through a page
table at the map's start. The programs drawing that geometry read
normals and specular through hz_pagedTexture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:39:19 +01:00
abit-foggyandCodex GPT-6 114b09babe feat(studio): autocomplete studio commands
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 07:37:39 -10:00
LokiandAntigravity 0a85491338 client/render: omit block outline when an entity is targeted (fixes #11804)
Co-Authored-By: Antigravity <[email protected]>
2026-11-08 02:31:51 +09:00
Florian ErnstandClaude Opus 5.5 833bb5cab4 Merge origin/main into fix/h155-fork-function-feedback
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:23:43 +01:00
IwantHappiness 5d9d9fb3ab Merge branch 'main' into translate-ru-lang 2026-11-07 20:18:57 +03:00
Florian ErnstandClaude Opus 5.5 65e2abae80 Count Absorption in a mob's max_absorption and clamp its amount to it
Absorption adds 4 per level to max_absorption (an ADD_VALUE modifier),
and LivingEntity clamps the absorption amount to getMaxAbsorption: when
the effect starts (setAbsorptionAmount) and when it goes
(onAttributeUpdated). A mob's max_absorption lived only in the command's
per-target attribute map, without the effect's modifier; /effect clear
left the amount, and expiry subtracted 4 per level, so a mob with a
raised base lost absorption it keeps in vanilla.

The mob's max_absorption now uses the attribute map it already has for
armor; its effective value counts the effect in the ADD_VALUE phase. The
add clamps the amount to it, /effect clear and expiry clamp to what is
left. The command-set base and modifiers stay unsaved, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:17:00 +01:00
Florian ErnstandClaude Opus 5.5 5f2e3cb14d Register a newly loaded chunk's tick queues before commands reach it
In a frozen level, water a command placed in newly forceloaded chunks
before the next world tick never flowed: the chunks' tick containers
were only registered by tick_blocks (a running world tick) or by
postprocessing, so the water's flow tick found no container and was
dropped. Vanilla registers them when the chunk becomes a full chunk
(LevelChunk.registerTickContainerInLevel), before any command sees it.

update_world now runs the existing sync_tick_chunks once the streamed
chunks are resident and the unloaded ones are saved with their ticks,
so registration comes before the tick's commands and world tick. Only
an authoritative game (not a server's client) registers.

Fixes #11873

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:06:05 +01:00
CocofireHDandopencode a61d272adc Block entities: shade by the face normal so packs don't darken them twice
A block entity's faces were baked with `minecraft_mix_light` and their
normal left zero. A shader pack's `gbuffers_block` (or its fallback)
receives the unshaded colour and the face normal from Iris, then applies
its own lighting, so Horizon's baked shade was applied a second time:
chests, shulkers, banners and the rest came out darker than the terrain
around them (#8390).

`draw_part` now emits the tint alone and the face's world normal
(`normal.w` = 127), and the entity shader applies `minecraft_mix_light`
from it, as it already does for mobs. Lights that are not the level's (an
item preview's `Lighting.Entry`, which the entity shader cannot know)
stay baked into the colour with `normal.w` 0, which is the path
`game/item_draw` gives block-entity items in inventories and hands.

The parity harness compares the tint and the face normal; the loom's GUI
preview keeps its baked `ITEMS_FLAT` colour. The chest cache test now
checks the nether flag reaches the shader instead of changing a baked
colour, so the cached geometry serves both dimensions.

Fixes #8390

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-07 18:05:25 +01:00
abit-foggyandCodex GPT-6 d607c2f137 feat(studio): add freecam and camera paths
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-07 07:04:37 -10:00
SenjinandClaude Opus 5.5 dddf351a05 Shader packs: at_velocity for the player's own model
Its vertices fell in the unmarked run that closes the mobs', so in third
person (and in a pack's shadow pass) its at_velocity read zero.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:03:19 +01:00
Delete228andCodex e54dcc07cf Merge Horizon main into the stateful block entity PR
Co-authored-by: Codex <[email protected]>
2026-11-07 20:00:52 +03:00
Florian ERNSTandCodex 6079903ffc Create missing live dungeon spawner block entities
Carry the already selected mob through an optional creation-only level hook. Preserve existing entries and the generation initializer and RNG order.

Co-Authored-By: Codex <[email protected]>
2026-11-07 17:54:52 +01:00
CocofireHDandopencode 3a7f276eab Fonts: read a pack font file the overlay lacks from the game
A pack that adds font providers over the game's own can leave the overlay without the vanilla font sheets its merged font/default.json names. Every glyph then became the missing box. Read a bitmap sheet, TrueType file or Unihex file the overlay lacks from the game's own root, as vanilla's resource stack keeps the game below every pack. Font definitions stay the overlay's, so a pack filter can still hide one.

Fixes #8875

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-07 17:54:37 +01:00
MrCloudy2andClaude Opus 5.5 570d53a780 A move packet counts from the position the server last reported
ClientPacketListener.handleMoveEntity decodes a move's delta from the
entity's position codec base, which AddEntity, a move and a position sync
set and a TeleportEntity leaves alone. Horizon counted it from the
tracked position, which the teleport had moved: when a command teleported
a vehicle, its rider was told the teleport and then the tracker's delta,
and saw the vehicle (and themselves) as far again past where it was.

lan_e2e gains `vehicle-teleport`: a strider the guest rides, teleported
3 blocks, is where the server has it in the guest's game.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:51:29 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 beaad0e79d HUD coverage: drop a pack's colour outputs the HUD has no target for
A pack text shader may declare colour outputs past location 0. The HUD's
pipelines have one target, so they went nowhere, but the coverage wrapper kept
them, and one at location 1 collided with the coverage and dropped a shader
that works today.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:50:19 +01:00
Horizon agentandClaude Opus 5.5 ab37cfb5aa Merge origin/main into #11497
items.rs tests: keeps this branch's tool-rules test and main's command
loot zero-count test, which both landed at the same place.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:48:34 +01:00
Horizon agentandClaude Opus 5.5 92b2977e3b Merge origin/main into #11474
end.rs: keeps this branch's live gateway items; main's only change there
(item_entity_to_nbt_with_items) was inside the saved-item path this
branch removes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:46:53 +01:00
CocofireHDandopencode f178cbe003 HUD atlas: pack a bitmap font's sheet from any texture path
A bitmap provider's file may be any texture, and HUD packs keep sheets outside textures/font. HudAtlas already received the sheet from the font commit, but only if the texture was packed: WALKED_TEXTURE_FOLDERS did not include custom paths such as textures/lumiere/hud, so those sheets still fell back to per-glyph run-time copies. Collect every bitmap provider's file while building the atlas, deduplicated against the walked textures, so its glyphs use the sheet's atlas rect.

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-07 17:35:29 +01:00
CocofireHDandopencode 0478b4deec Fonts: use an atlas sheet outside textures/font for server HUDs
A bitmap provider may name any texture, and server HUD packs keep their glyph sheets under their own namespace or a path such as textures/lumiere/hud. The HUD atlas already holds those textures, but Font only looked up sheets under font/, so every glyph was decoded from disk and copied into the 512-row run-time region one by one. When that region filled, a glyph became the 6-pixel missing glyph, shifting the rest of the HUD line.

Look the sheet up by its atlas name for every namespace and keep every atlas sprite available to the font. Glyphs now use the sheet's atlas rect, so their advances come from the original texels and the run-time region is not involved.

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-07 17:35:29 +01:00
TheMrZZandCodex gpt-6.1-sol 8db7c3ddc0 fix: preserve plain forked function feedback order
Prepare starts for eligible actual sources before executing their owned function calls. Keep the existing body, callback, store and fallback paths, and consume or clear invocation slots around leaf execution.

Add frozen Java/Game command parity and causal store, return, error and fallback controls.

Fixes #11824

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 17:33:05 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 b5a1d40dc6 HDR coverage view: magenta at paper white, not PQ's 10 000 nits
In PQ output the debug view mixed toward PQ (1, 0, 1), so any covered pixel
blew out. Mix toward BT.709 magenta at the paper white instead, encoded like
the picture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:32:22 +01:00
IwantHappinessandNemotron 4cc2a04c25 Translate remaining Russian launcher and game strings
Translate still-English UI strings in launcher/lang/ru.json and the game's
crates/horizon-client/assets/horizon/lang/ru_ru.json (particle culling
settings). Keep proper nouns, acronyms, key names, paths and env vars in
English.

Co-Authored-By: Nemotron <[email protected]>
2026-11-07 19:20:43 +03:00
MrCloudy2andClaude Opus 5.5 a61825404a A vehicle's teleports leave its rider's look alone
ClientPacketListener.handleMovePlayer applies a position packet only when
the player is no passenger, and still accepts the teleport. Horizon's
client applied it to a rider too, look included: a map whose datapack
teleports the vehicle every tick (`tp @s ~ ~ ~ 0 0` on a strider) snapped
the rider's view back 20 times a second. A rider now keeps its own
position and look and answers the teleport with them.

lan_e2e gains `rider-look`: a tick function teleports the strider the
guest rides, and the guest's view stays where they turned it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:18:26 +01:00
Florian ErnstandClaude Opus 5.5 1a9c87059b Merge origin/main into fix/connected-guest-attribute-commands
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:15:12 +01:00
Florian ErnstandClaude Opus 5.5 ce25d100ef Merge origin/main into fix/mob-effect-amplifier-codec
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:15:10 +01:00
Florian ErnstandClaude Opus 5.5 4d8e70da2c Merge origin/main into fix/h297-potion-effect-icon
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:14:59 +01:00
Florian ErnstandClaude Opus 5.5 8efbe1c75e Merge origin/main into fix/h051-kill-vehicle-contents
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:14:58 +01:00
Florian ErnstandClaude Opus 5.5 df25b701c5 Merge origin/main into fix/loaded-sleeper-bed-position
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:14:54 +01:00
Florian ErnstandClaude Opus 5.5 8b577fc24c Merge origin/main into fix/h032-jukebox-saved-clock
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:14:51 +01:00
Florian ErnstandClaude Opus 5.5 974305151d Merge origin/main into fix/summoned-leash-knot-lifecycle
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:14:50 +01:00
Florian ErnstandClaude Opus 5.5 e6941baa5a Merge origin/main into fix/h195-command-damage-range
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:14:49 +01:00
TheMrZZandCodex gpt-6.1-sol 3890e57c13 fix: select direct mob passengers for execute relations
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 17:14:06 +01:00
Florian ErnstandClaude Opus 5.5 2282116773 Place valid inline features with /place feature
/place feature refused every inline feature value with "An unexpected
error occurred", although vanilla 26.3 places it like a named one
(PlaceCommand.placeFeature over a ResourceOrHolderArgument value) and
reports commands.place.feature.success.inline.

The inline value is read with the existing SNBT-to-JSON pair, decoded
by the same feature codec as a named feature (feature_with_blocks,
uncached), and placed through the same Feature.place path with the
level random. A feature that does not place reports
commands.place.feature.failed; a value that does not decode keeps the
plain failure.

Fixes #11843

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:10:54 +01:00
MrCloudy2andClaude Opus 5.5 d72b2a555b execute on passengers finds the players riding a vehicle on a server
Entity.getPassengers holds players as well as mobs. Horizon's `on
passengers` named the player in place when a mob had a rider flag, and no
server player: a map's datapack, running with no player in place, never
found the player riding its strider, and a command the host ran named the
host instead of the guest riding. It now gives the player in place when
they ride the entity, and each other player of the level riding it.

Mob and boat passengers are left to #11810.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:10:47 +01:00
Florian ErnstandClaude Opus 5.5 7cd9dbc7a2 Let Health Boost raise a mob's healing maximum and clamp when it goes
Health Boost is a max_health attribute modifier. The attribute getter
already counted it, but Mob::heal clamps to the cached attrs.max_health,
which the effect paths never refreshed, and nothing lowered Health when
the effect went (LivingEntity.onAttributeUpdated). Adding the effect,
/effect clear and its expiry now refresh the cache and lower Health above
the new maximum; the add still heals nothing.

Sulfur cubes and wolves write their maximum straight into the cache
(sulfur_cube::set_size, tame::set_tame), outside the attribute model,
and keep their current behavior. Other effect removal paths are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:10:03 +01:00
c74ff0070b HDR float frame: every HUD and menu draw writes its coverage of the world
With HORIZON_HDR_FRAME=float, HDR on and no shader pack, on devices with independent blending, each
HUD and menu pipeline gets a variant with a second output into an R8 target: how much of the world
behind it the draw hides (docs/design/hdr-linear-light.md, The HUD and menus). The fragment shader
is wrapped as it is, so the primary colour, its blend and alpha are unchanged, and the coverage
follows the draw's final colour and blend: layering by its alpha, additive draws not at all,
darkening ones by how much they darken, inverting and replacing ones fully. HORIZON_HDR_DEBUG=coverage
tints it magenta in the last pass; nothing else reads it yet. A resource pack text shader without a
colour output is dropped as an unusable one is, instead of panicking.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:05:50 +01:00
JoansitohandClaude Sonnet 5.5 6d1746d729 launcher: the Home patch log and console logs keep the wheel to themselves
Their overflow_y_scroll lists lacked the on_scroll stop_propagation every other
inner scroller has, so a wheel turn the list could not use (up at the top, or
down at the end) scrolled the whole page behind it.

Fixes #11853

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 17:04:07 +01:00
JoansitohandClaude Sonnet 5.5 af13271b86 fix(launcher): wrap Home's tab strip on narrow windows instead of scrolling it sideways
Fixes #11849

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 16:58:59 +01:00
GIGABAIT93andClaude Opus 5.5 0df4792709 Ukrainian: the 445 strings uk_ua.json lacked (PvP & HUD, Studio, mods, cosmetics)
PvP & HUD, Replay Studio, the music page, Browse Mods, the resource pack
browser, cosmetics and emotes, moderation and tempban, the controller page,
graphics tooltips and recipe transfer. Placeholders, leading and trailing
spaces match en_us; durations use abbreviations (хв, год, дн.) so one form
reads right for every number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:56:20 +02:00
Florian ERNSTandCodex 2dd6879bc4 Keep actual bell block entities for command reads
Co-Authored-By: Codex <[email protected]>
2026-11-07 16:55:24 +01:00
Evrim CicekandClaude Opus 5.5 51eae8d435 rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 18:50:56 +03:00
CocofireHDandopencode 7142128a7a wgpu-hal GL: report the context's texture units per stage
The GL backend reported MAX_TEXTURE_SLOTS (16, WebGL2's minimum) as max_sampled_textures_per_shader_stage even on desktop GL, where drivers usually offer 32. A native shader pack's sky pipeline layout declares the terrain's 10 sampled textures and the frame's 9, so it was refused at 16 although the driver accepts it (#10095).

Query GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS and GL_MAX_TEXTURE_IMAGE_UNITS, take the lower, and cap at the arrays' new 32 slots (MAX_SAMPLERS likewise). On WebGL2 the query still yields 16.

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-07 16:49:30 +01:00
CocofireHDandopencode 81df2a1864 Renderer: refuse a native shader pack instead of panicking
A layout or pipeline the backend cannot take (a stage's bindings past its sampled-texture limit, say) reaches the device's error scope. A native pack built its frame, stages and passes outside one, so wgpu's validation error hit the default handler and crashed the game (#10095). Build the pack in a scope and return the first error, which the shader pack screen already shows as a refusal.

The test asks for OpenGL's minimum 16 sampled textures per stage and builds a sky-only pack whose layout needs 19: the pack is an error, not a validation panic.

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-07 16:49:30 +01:00
SenjinandClaude Opus 5.5 edb550ac32 HDR and shader packs: glowing sign text shines
Glow ink text was full-bright in the lightmap only: HDR output and shader packs that light
with their own GI (and read the HDR tier, horizonTier) showed it as dark as plain text.
Its glyphs now carry the low HDR tier, like other things that glow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:48:02 +01:00
yahya-nusseibehandClaude Opus 5.5 f2e081520f Resource packs: take the unpack budget without fetch_update
CI's stable Rust deprecates AtomicU64::fetch_update in favour of
try_update, which the workspace's minimum Rust (1.95) doesn't have, so
clippy -D warnings failed. A compare_exchange_weak loop does the same
on every version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 17:47:21 +02:00
Florian ErnstandClaude Opus 5.5 f1ea540f08 Remove a mob's Absorption effect once the absorption is used up
AbsorptionMobEffect.applyEffectTick, asked on every tick, answers false
when the absorption amount is 0, so MobEffectInstance.tickServer drops
the effect before its duration counts down, finite or infinite. A mob's
effect tick had no Absorption case: a used-up Absorption stayed until it
expired. It now ends through the existing removal path; other effects,
infinite ones included, are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:34:19 +01:00
Stink-OandClaude Opus 5.5 aa2220fcf6 Native mod API: hold the terrain's picture while the world changes (native_world_hold)
A client mod asks once a frame (`hold.hold()`, or `hold.hold_within(x, z, radius)` for circles):
sections already on screen that are meshed again are uploaded as ever but wait beside the meshes
drawn, and letting go swaps them all in on one frame with nothing left to upload. Smaller circles
let go of what they leave. In single player, far terrain waits too for the columns the server
changes beyond the view inside the hold, and takes them in when it lets go of them. Bounded: 30 s,
1 GiB of waiting meshes, the arena running out; ended so, it stays off until no mod asks for a
frame. Clearing the sections (another world or dimension) and unloading columns drop what waits;
arena compaction moves waiting meshes too. Renderer::upload keeps its order on the normal path
(before_mesh / upload_mesh / after_mesh). Tests in gfx/hold.rs; docs in native-mods.md; fragment
world_hold.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:34:09 +00:00
8cd009e149 Read saved template structure starts before regenerating them
Part of #11126. Builds on #11652.

Decode shipwreck, ocean ruin, igloo, ruined portal, woodland mansion,
nether fossil and end city pieces from saved starts. Rebuild template
boxes and placement settings like vanilla's tag constructors, retaining
the whole-start regeneration fallback for unsupported or broken pieces.

Cover every new type with resource-free round trips and extend the
prepared-resource generation/read comparison across all three dimensions.

Piece ids go through #11652's saved_piece_id first; any other id is
matched with or without the minecraft: namespace, not lowercased, as
Identifier.parse reads it.

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:33:44 +01:00
Vinícius MoreiraandClaude Opus 5.5 12dd25d421 Polytone: legacy math expressions, color and distance functions
Older packs write expressions in the legacy syntax: uppercase variables
(AGE, DISTANCE_SQUARED, RAIN...), pi and e, and bare rand(), gaussian()
and noise(). Each variable now runs as the scripting call the wiki maps
it to, and a legacy expression keeps the old argument order of lerp,
smoothstep and color. The color functions (red, color, withAlpha,
lerpColor, hsb, lerpHsb...) follow vanilla's ARGB channel rules, and
dist/distSquare join the math table. All expressions of Visual
Effects+ now compile.

Part of #11486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 12:25:21 -03:00
SenjinandClaude Opus 5.5 ebfcad98f6 Shader packs: at_velocity for blocks a piston moves
A moving block (and an extending or retracting head) is drawn with the entities while it
moves, and read zero at_velocity: flying machines and piston contraptions smeared under a
pack's TAA. Each marks its own run, (6 << 32) | the cell it moves to, which stays the same
while it moves; a finished one keeps that key until the chunk mesh shows the block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:25:09 +01:00
Vinícius MoreiraandClaude Opus 5.5 c6c0a97e57 Polytone: the scripting expression language
Expressions such as `o.age() * 0.1`, ternaries, `&&`/`||`, strings,
local variables, `if` blocks and calls on context objects are parsed
once when the pack loads, with every name resolved, so a typo is a load
error. A Host answers the context objects (o, p, c, g, r, v), their
methods and the game's global functions; the math functions follow
Java's Math. 1461 of the 1520 distinct expressions of Visual Effects+
compile; the rest use the legacy uppercase names, which come next.

Part of #11486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 12:22:21 -03:00
Vinícius MoreiraandClaude Opus 5.5 edab7b313f Polytone: leave keys beside the attribute groups alone
An attributes_modifiers object with a group (`base`...) no longer refuses
the file over a key that is none of the modifier's groups: it is left
alone, so a pack Polytone loads isn't rejected over an entry neither reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 12:21:34 -03:00
yahya-nusseibehandClaude Opus 5.5 d94fdae0b9 Agent control: no shared /tmp socket path, and bench refuses bad numbers
Without XDG_RUNTIME_DIR (containers, some WSL and minimal setups) the
control socket was /tmp/horizon-control.sock, a fixed name in a folder
every user shares. Another user who bound it first made --control fail
to start, and horizon-ctl then talked to their socket.

When the temporary directory is shared (world-writable, as /tmp), the
default endpoint is now horizon-<uid>/horizon-control.sock in it. The
game makes that folder 0700, and both the game and horizon-ctl refuse
it unless it is a real folder, owned by this user, that no one else may
enter. A temporary directory of the user's own (macOS's $TMPDIR) is
used as before, so nothing moves there. The launcher's copy of the
default endpoint (game_tools.rs) follows the same rule.

Separately, `bench -1` or `bench nan` panicked the game in
Duration::from_secs_f64; bench now takes 0 to 86400 seconds and refuses
anything else.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 17:20:50 +02:00
Florian ERNSTandCodex e16378accd Use world RNG for literal command predicate chances
Co-Authored-By: Codex <[email protected]>
2026-11-07 16:19:02 +01:00
Florian ErnstandClaude Opus 5.5 4924374fa5 Keep a mob's FallFlying flag and wear its glider as vanilla does
A mob loaded or summoned with FallFlying:1b kept the flag even when it
could not glide, and a gliding mob's elytra never wore. The flag was
only the raw tag's value: the loader did not read it, the save only
supplied a default, and the mob tick had no updateFallFlying step.

- mob_from_nbt reads FallFlying into the mob, and mob_to_nbt writes the
  mob's current flag (LivingEntity.read/addAdditionalSaveData).
- The mob's aiStep, with or without AI, runs updateFallFlying while the
  flag is set: canGlide (ground, vehicle, levitation, a glider whose
  next damage does not break it) clears the flag; every 20 glide ticks
  Util.getRandom picks a glider from the mob's own random.
- The game applies that wear with the existing durability path
  (Unbreaking from the level's random) to the mob's kept stack.
- LivingEntity.tick counts fallFlyTicks after aiStep.

Glide travel, checkFallDistanceAccumulation and the ELYTRA_GLIDE game
event are not part of this change.

Fixes #11809

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:14:52 +01:00
iseaprojectsandDeepSeek V4.1 Flash d1dd934be2 Spanish: finish the launcher and es_es strings
The launcher's es.json still held 91 English values: the mod-port status sentences, release notices, look-and-feel settings, the SSH hosting panel and several install/update results. Translate them, and fix Back from the body part (Espalda) to Atrás.

es_es.json was 20 keys short of en_us.json: every /studio replay message, Play in Background and the controller-focus note. Add them so Spanish screens no longer fall back to English.

Closes #11814.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
2026-11-07 11:08:01 -04:00
Horizon agentandClaude Opus 5.5 b86fa679b9 function_tags harness: run without --work-dir
tools/parity.py runs every harness with no arguments, so the harness's
required --work-dir made it fail on every CI run before reaching the
oracle. Without the flag it now captures into a fresh
.local/function-tags-parity; an explicit --work-dir must still be new.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:05:53 +01:00
Horizon agentandClaude Opus 5.5 45da47c08b Merge origin/main into #11666
game.rs: keeps this branch's wax_on_sound (honeycomb) beside main's
transform_copper_chest_neighbour (axe/hoe/shovel transformers, #33ec06ab12).
test_use_item_on_parity.py: keeps both the honeycomb double-chest cases
and main's block transformer cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:03:22 +01:00
yahya-nusseibehandClaude Opus 5.5 04449d8b73 Multiplayer: a server's view distance and chunk centre can't overflow
view_distance and chunk_center come straight from Login,
SetChunkCacheRadius and SetChunkCacheCenter, any i32 a server sends.
remote_chunk_in_range added 3 to the radius and subtracted the centre,
and the streaming radius and sent_radius added 1: a server sending
i32::MAX or i32::MIN panicked a debug build, and in release (no
overflow checks) the wrapped range dropped every loaded chunk.

The storage range is now in_storage_range: the same ClientChunkCache
rule (radius at least 2, plus 3), with a saturating add and abs_diff,
so nothing changes for any radius a real server sends. The +1s
saturate too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 17:00:32 +02:00
Horizon agentandClaude Opus 5.5 da0b4899ff Merge origin/main into #11480
Keeps both imports in command_exec_corpus.groups(): this branch's
player_food_predicate_corpus and main's treasure_map_copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 16:00:14 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 50b1d6232e docs: HDR design note: marks turned into light once in step 3, tests for mixed light and TAA
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:52:07 +01:00
yahya-nusseibehandClaude Opus 5.5 706cf3b3fa Resource packs: delete overlays no selection has used lately
Each distinct pack selection gets its own overlay folder under
.horizon-cache/resourcepacks, holding a full unpacked copy of its zip
packs, and nothing removed old ones. Every server pack, and every new
version of one, left a permanent copy the player can't see: ten
servers with 100 MiB packs kept about a gigabyte.

resource_root now marks the overlay it returns as used by this process
(a shared lock on <overlay>.overlay-cache.use, held until the process
exits, whose time is the last use), then keeps the 8 most recently used
overlays in the folder and deletes the rest. An overlay another
process uses or is building is skipped, so two games sharing a game
folder never pull one out from under each other; the marker goes before
the folder, so a half-deleted overlay is never reused. The lock files
stay, as build() already requires.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 16:45:03 +02:00
yahya-nusseibehandClaude Opus 5.5 439b609a94 Play with Friends: the guest's loopback tunnel takes only its own client
After the encrypted join, the guest offered the session on a random
127.0.0.1 port for 30 s and handed it to the first loopback connection.
Any other local user or process that found the port first got the
authenticated session to the host's server, and a web page aiming
fetch at local ports could send HTTP into the tunnel and make the
player's own join fail.

serve_loopback now returns a Loopback with the port, a random 16-byte
token and the thread. A connection must send the token within a second
of connecting (compared in constant time); anything else is dropped and
the port keeps waiting until its deadline. The client's join_friend
passes the token on, and run() writes it raw before the handshake.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 16:42:17 +02:00
Nikita Maximilian GrimmandClaude Opus 5.5 537291b26d docs: HDR design note: the HUD's layer and the tone curve before light is written
Light written into the frame can't be taken back out from under the HUD, and without the tone curve it clips at
the peak, so step 3 now holds the HUD's own layer and the tone curve, and step 4 the shader groups. The look
target names the differences allowed (rounding, light behaving as light under glass, water and anti-aliasing)
and the artifacts that aren't.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:41:33 +01:00
MrCloudy2andClaude Opus 5.5 a95c0e022d lan_e2e shield: each player's own game shows the disabled shield's cooldown
The shield check now also asks each player's window what its hotbar
draws over the shield (a new `shield_cooldown_shown` in the control
state: ItemCooldowns' percent for minecraft:shield). Right after the
vindicator's axe disables it the cooldown shows, and after the 100 ticks
it is gone. On main both players' games showed none (#11805).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:41:24 +01:00
Horizon agentandClaude Opus 5.5 5ee3b9da9a Run the NoAI nautilus harness without --binary, as parity.py does
parity.py and parity-main call tools/test_*_parity.py without --binary or --work-dir, so the harness failed in 0 s there. Use harness_args.ensure_work_dir, as a98ba0273 did for the dolphin and spell-ticks harnesses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:41:01 +01:00
Horizon agentandClaude Opus 5.5 307d82bb63 Merge main into #10511
Conflicts kept from both sides: crates/horizon-client/src/mobs/ai.rs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:41:01 +01:00
Florian ERNSTandCodex 282a7005c8 Fix chorus-flower drops from arrow and snowball impacts
Co-Authored-By: Codex <[email protected]>
2026-11-07 15:40:50 +01:00
yahya-nusseibehandClaude Opus 5.5 1e38170d49 Play with Friends: refuse a port mapping granted no lifetime
In PCP and NAT-PMP a lifetime of 0 means the mapping is deleted, but a
success reply carrying 0 was taken as a mapping. Mapping::due() was
then always true, so the host renewed on every 100 ms wake-up of its
loop (a UDP exchange each time, under the reach mutex) while
advertising a direct address that no longer existed.

pcp_map and natpmp_map now refuse a zero lifetime when they asked for
one (a delete, which asks for zero, still expects zero), and due()
never fires sooner than 30 s after the last renewal, so a router that
grants a few seconds isn't asked again ten times a second either.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 16:36:25 +02:00
yahya-nusseibehandClaude Opus 5.5 b0600cec3c Resource packs: cap what one overlay build may unpack
Applying packs builds an on-disk overlay: every file under assets/ in
every zip pack was inflated (up to 1 GiB each, whole in memory) and
written out, on every worker thread at once. A gigabyte of zeros
deflates to about a megabyte, so a server pack at the 250 MiB download
limit could write some 240 GiB to the player's disk and hold a 1 GiB
buffer per thread, once the player accepted the pack prompt. Vanilla
never unpacks a pack.

Zip::copy_to now streams an entry to its file 64 KiB at a time, taking
each piece from a byte budget shared by the whole build: 16 times the
zips' size on disk, at least 64 MiB, at most 8 GiB. Past it the build
fails with FileTooLarge (so the reload drops the server packs, as for
any failed build) and the half-written overlay folder is removed. An
unreadable entry still costs only that file. Memory per thread is now
the compressed entry plus one piece.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 16:31:41 +02:00
Evrim CicekandClaude Opus 5.5 c8753a2ea4 Infested's throw in floats as JOML does; the unit test hurts through Mob::damage
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:31:04 +03:00
MrCloudy2andClaude Opus 5.5 2f3743d282 An axe disabling a shield sends the defender the shield's cooldown
BlocksAttacks.disable adds the item cooldown (ItemCooldowns.addCooldown
on the shield's group), which ServerItemCooldowns sends a player as
Cooldown(minecraft:shield, 100) and ends with 0. Horizon only set its own
shield counter, so a guest's client never heard of it: no cooldown on the
hotbar, and a held right click could show the shield raised while the
server had it down. The disable now also goes through the item cooldowns.

Fixes #11805

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:25:58 +01:00
SenjinandClaude Opus 5.5 381c5a1e62 Shader packs: at_velocity for boats, minecarts, armor stands, frames, paintings, TNT, falling blocks and block entities
They were drawn in runs marked only by type, so a pack's at_velocity read zero on them even
while they or the camera moved (TAA smeared them). Each now marks its own motion run:
(3 << 32) | entity id, (4 << 32) | id for an item frame's held item, (5 << 32) | position for a
block entity, with a closing mark after each group; maps stay unmarked (keyed by map id).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:25:24 +01:00
Evrim CicekandClaude Opus 5.5 3fc5044868 Infested draws at the hurt, before an enderman's or a shulker's own roll
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:21:38 +03:00
Evrim CicekandClaude Opus 5.5 e44fc5af01 mob AI parity: an effect flag, an infested enderman in the rain and a poisoned shulker
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:21:38 +03:00
itarqos5andClaude Opus 5 6a634e49e2 feat(render): a compact layout for far tiles' quads, a quarter of the arena
Chunk sections already put their solid quads in the arena as one 24-byte
record each instead of four 24-byte vertices (`mesher::packed`). Far tiles
never could: that record's coordinates are a block grid of 16, and a far
tile's quads are merged rectangles of a voxel column's exposed side,
hundreds of blocks wide. So they stayed at four vertices a quad, and at
`lodDistance` 256 they were by far the largest thing the renderer held.

A far quad is much more regular than a chunk's, though -- a rectangle in an
axis-aligned plane, one colour, one light and one layer across all four
corners, with UVs `lod::mesh::emit_quad` derives from the positions -- so a
record of its own holds it in the same 24 bytes, and terrain.wgsl's
`far_corner` does what that function did. The two layouts share the arena
and the pipeline; a draw's base vertex says which it is (`FAR_BASE`).

Measured on a settled LodTest at `lodDistance` 256, render distance 16, the
same binary with `HORIZON_FAR_PACK=0` and without, each run settled on the
same 4424 tiles and the same quad count to within four:

                      far vertices   arena pages   GPU allocated
    four vertices        492.5 MiB       960.0        1241.7 MiB
    a record a quad      127.4 MiB       640.0         921.8 MiB

365 MiB less vertex data, and 320 MiB less video memory actually allocated
rather than merely accounted for. 24.8 bytes a quad: a record each, and the
few quads that spill. Both figures repeated exactly over two pairs of runs.

Frame time is unchanged. Over the same flight, the mean of two pairs:

                      avg FPS   1% low   GPU avg
    four vertices       171.0     95.8    5.390 ms
    a record a quad     170.3     94.9    5.420 ms

The pairs disagree on the sign -- the compact layout was 1.5% slower in one
and 0.7% faster in the other -- so the difference is run variance, not the
cost of expanding a record. Worth stating because one pair alone read as a
regression.

Nothing here reasons about which record is right for a quad: `pack` builds
one, rebuilds the four vertices from it, and keeps it only if they come back
bit for bit. A quad no record reproduces is kept as its four vertices, as
`mesher::packed` keeps one; in practice that is the fluid faces, whose
surface sits at 8/9 of a block, and about 1% of quads.

`lod::mesh`'s `every_quad_the_mesher_emits_packs_and_comes_back` holds the
layout and the mesher to each other over real terrain, which the layout's
own tests cannot: they check its records against its own copy of what
`emit_quad` does, and would pass just as well if the two had drifted.

A same-build control says the picture does not change: two launches of the
identical build differ in 50.7% of pixels (16.0% above the animation noise
floor, worst channel delta 76), because far-tile refinement does not settle
identically between launches. Packed against unpacked differs in 40.5%
(12.8% above the floor, worst 77) -- less than the control.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-07 14:13:34 +00:00
Teiwazik 1eb3b7f6c3 Merge remote-tracking branch 'origin/main' into tmp-seat/follow-plugin-seat-chains 2026-11-07 15:12:38 +01:00
TeiwazikandClaude Opus 5.5 43e106cece Upscaling Sharpness: English texts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:08:56 +01:00
umcekoandClaude Opus 5.5 1c8113ce32 Merge origin/main into #11344
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:05:06 +03:00
TeiwazikandClaude Opus 5.5 4b5b667560 Upscaling Sharpness: German and Russian texts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:54:09 +01:00
HiuoyandClaude Opus 5.5 f898655ae6 Port pack: RenderTooltipEvent.Color and AnvilRepairEvent under their 26.1 names
NeoForge 26.1 has neither. A tooltip is drawn from a style's textures, picked
in RenderTooltipEvent.Texture, and the anvil take is AnvilCraftEvent, whose
.Pre comes before the inputs are used and the anvil is damaged (no break
chance). `events` now looks the 1.21.1 names up under those, so ATM10's 6
Color and 4 AnvilRepair users are answered by the hooks that exist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:54:03 +04:00
73fa431ac5 fix: widen entity air and fluid drags from vanilla floats
Vanilla Entity.getAirDrag is 0.98F. PrimedTnt, FallingBlockEntity and
ItemEntity scaled motion by the f64 0.98, so after four ticks a TNT's
Motion x was 0.092236816 instead of 0.09223682318…. Item underwater
and lava drags, LlamaSpit air drag, and hurting-projectile inertia
were the same class of float-widened constants.

Fixes #6814

Co-Authored-By: OpenCode <[email protected]>
Co-authored-by: monkeycode-ai <[email protected]>
Co-authored-by: monkeycode-ai <[email protected]>
2026-11-07 13:53:30 +00:00
MSedgeMC 2f7a46dfd3 port_map: the Camel.canMate row no longer records the canParent gap 2026-11-07 13:48:54 +00:00
MSedgeMC dfe4c2cb51 Test that a wounded or ridden camel cannot breed
Two camels in love in a built world: the breed goal starts, then one loses a
point of health and is refused, and a rider also refuses it. Without the
canParent guard the wounded camel still starts the goal.
2026-11-07 13:48:54 +00:00
MSedgeMC 3ed00f4071 A wounded or ridden camel no longer starts breeding
`Camel.canMate` is `partner instanceof Camel && this.canParent() &&
camel.canParent()`, and `AbstractHorse.canParent` requires no vehicle or
passenger and full health (a camel's `isTamed` is always true). The shared
`Breed` goal applied those checks only to horses, donkeys and llamas, so a
camel stayed free to breed while hurt or carried.

Camels still pair only with camels: the `camel` flag feeds the canParent
guard only, not the partner species rule.
2026-11-07 13:48:54 +00:00
TheMrZZandCodex gpt-6.1-sol e135804a52 fix: match exact local command rotation arithmetic
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 14:46:33 +01:00
MrCloudy2andClaude Opus 5.5 36add718c0 Spears stab other players: the charge and the jab reach players on a server
KineticWeapon.damageEntities and PiercingWeapon.attack hit every entity
along the view, players included (PiercingWeapon.canHitEntity:
canHarmPlayer, not the same vehicle). Horizon's stab targets were the
mobs only. A guest's spear now also reaches the other players of its
level; each stab is worked out as the attacker in their turn and lands
through the PvP path once the hub is back, with the spear's damage type,
the 0.4 push and the weapon's Knockback, the dismount, thorns and the
kill score, then the attacker's wear, stats, exhaustion and hit feedback.

The kill score and thorns of pvp_land move into pvp_aftermath, shared by
both. lan_e2e gains a `spear` check: a jab and a sprinting charge hurt
the host, and with the pvp game rule off neither does.

Fixes #11790

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:42:20 +01:00
MSedgeMC 077164ff2f port_map: the camel RandomSitting row no longer records the pose gap 2026-11-07 13:39:44 +00:00
MSedgeMC c953fe79cb Test that a sitting camel cannot stand under a two-block ceiling
The test builds a world with a stone ceiling cell inside the standing box
but above the sitting box, then asks RandomSitting, the arm the goal
selector calls: 200 asks must all be refused. A second camel with open sky
fires within the same 200, so the refusal is the pose check and not the
state setup. Dropping the can_change_pose conjunct fails the first loop.
2026-11-07 13:39:44 +00:00
MSedgeMC 92282c7476 A sitting camel stands up only when its standing box fits
`CamelAi.RandomSitting.checkExtraStartConditions` ends with
`body.canCamelChangePose()`, which is
`wouldNotSuffocateAtTargetPose(isCamelSitting() ? STANDING : SITTING)`.
RandomSitting did not ask, so a camel sitting under a ceiling that blocks
its 2.375 tall standing box (its sitting pose is 0.945 tall) stood up into
it. The `can_change_pose` helper already existed for the elastic leash pull.
2026-11-07 13:39:43 +00:00
TeiwazikandClaude Opus 5.5 6689a656a0 TAA: clip history to the neighbourhood spread, weigh new frames more under motion
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:39:08 +01:00
TeiwazikandClaude Opus 5.5 fc64f0ee27 Upscaling Sharpness: CAS sharpen after TAA upscaling
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:38:31 +01:00
TeiwazikandClaude Sonnet 5.5 052c2eb962 Native shader packs: sections fade in toward the fog colour like vanilla terrain
The fade-in rides the high 16 bits of the flat hdr_code varying (no new
location); solid and translucent colours mix toward the fog colour after
the pack's material, alpha kept.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 14:35:56 +01:00
Florian ERNSTandCodex 1066efbafb Normalize note-block instruments during fill
Co-Authored-By: Codex <[email protected]>
2026-11-07 14:35:22 +01:00
TeiwazikandClaude Sonnet 5.5 4a20af007c Framed maps: no slot taken from a map drawn this frame
The atlas holds 256 map pictures. Every framed map in range claimed one, seen or not, so past 256 the maps took slots from each other within one frame and showed each other's pictures. Now a frame's outline is culled before its map claims a slot, the nearest claim first, and a slot shown this frame is never given away: past the slots, the far maps go undrawn.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 14:33:28 +01:00
MSedgeMC aadec58092 port_map: the FrogAi.initCoreActivity panic gap is closed 2026-11-07 13:32:24 +00:00
MSedgeMC a90c5f8179 Test the panic speed a hurt frog's move control reads
Drives the real goal selector on a built test world: hurt the frog with a
PANIC_CAUSES damage, tick the goals once, and assert the panic goal started
and left vanilla's 2.0 in `Navigation.speed_modifier`, the value
`SmoothSwimmingMoveControl` multiplies. Reverting the constant fails it with
1.25 against 2.0.
2026-11-07 13:32:24 +00:00
MSedgeMC c1e649f61b Frogs panic at AnimalPanic's 2.0 speed multiplier
`FrogAi.initCoreActivity` builds the brain's core activity with
`AnimalPanic(2.0F)`, but the goal list used 1.25.

`PanicGoal.start` hands the multiplier to `PathNavigation.moveTo`, and
`SmoothSwimmingMoveControl.tick` computes
`speedModifier * getAttributeValue(MOVEMENT_SPEED)` and then multiplies by
0.1 on land or 0.02 in water. A frog's movement speed is 1.0, so a fleeing
frog should move 0.2 blocks a tick on land and 0.04 in water; at 1.25 it
moved 0.125 and 0.025, 60% slower.
2026-11-07 13:32:24 +00:00
TeiwazikandClaude Sonnet 5.5 fdc056c8ac Older servers: send sign_update with the side before the lines
26.3 ends sign_update with the side as a VarInt; 26.2 and older read it as a
boolean right after the position. Forwarding the packet unchanged made the
server misread it and kick the player on Done.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 14:23:33 +01:00
VaspyyyandClaude Opus 5.5 eff292b1e2 Minecarts: keep the rolled loot out of the copies a cart push makes
push_from_ticked_cart cloned the ticked cart into the list and back each tick,
and with it a chest cart's rolled loot: its whole Items list as NBT. The stored
cart already goes without the loot for the tick (tick_carts_now takes it), so
the copies do too and the loot stays with the ticked cart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:20:35 +01:00
Horizon agent a6b863754b Merge origin/main into PR #11672
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/game/commands/terrain_cmds.rs
#	crates/horizon-items/src/items.rs
2026-11-07 14:19:04 +01:00
Horizon agent 04b8ed64ca Merge origin/main into PR #11625
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/mobs/ai.rs
2026-11-07 14:17:57 +01:00
Horizon agent 1c81831b12 Merge origin/main into PR #11533
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/game/commands/terrain_cmds.rs
2026-11-07 14:17:31 +01:00
Horizon agent 547c7decbc Merge origin/main into PR #11508
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	crates/horizon-client/src/game/persist.rs
2026-11-07 14:16:30 +01:00
e8a5564059 Cache decoded saved palette entries in the block registry
A saved area resolves the same dozen block states in every section of every column, but decode_column built a format!-ed String key and parsed each entry through BlockState::from_nbt into a per-column HashMap. The registry now memoizes palette entries by their NBT in an FxHashMap keyed by the tag itself, so a repeated entry costs one hash and one comparison and allocates nothing; the per-entry resolution rules move with it unchanged. Loading the 529-column saved area drops Persistent::load from 1,467.8M to 1,284.3M instructions.

Part of #9996.

A first draft by DeepSeek V4.1 Flash, via pi, reviewed and reworked.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Codex (gpt-6.1-terra) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:15:22 +01:00
70a0a29eec Check packed palette indices one word at a time
Loading a generated area spends 16% of Persistent::load (the worker's
chunk load) in PalettedContainer::from_packed, and nearly all of it is
check_indices: a scalar bounds check of every entry of every section
(~10.6 instructions per entry, 22M entries per 529-column area).

check_indices now rejects a whole word at once. Adding 2^bits - palette
to a word lifts every field by that much, so a field carries out of its
own bits exactly when its index is past the palette; the carry out of
each bit is computed for the whole word with (a & b) | ((a | b) & !sum).
A field can only appear bad where a genuinely bad field precedes it in
the same word (a carry adds one to it), which never turns an accepted
input into a rejected one, and the offending word is rescanned entry by
entry on the error path so the reported index is the same first
offending entry as before. The last word's padding fields are biased by
zero, so they cannot look bad, as the entry-by-entry scan ignored them.
The same set of inputs is accepted: the early return when the palette
holds exactly 2^bits entries was already there and stays.

Part of #9996.

A first draft by DeepSeek V4.1 Flash, via pi, reviewed and reworked.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Codex (gpt-6.1-terra) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:15:22 +01:00
5cffcf1370 Load saved light directly from its layers instead of expanding and repacking
The saved sky and block nibble layers are already the resident Light::Sky and Light::Block layout. Choose the resident variant from the layers and copy the stored layer when only one kind of light varies, so only sections where both vary still expand their light into a full array. Missing layers still inherit the bottom row above and dimensions without sky light still ignore saved sky layers.

Part of #9996.

A first draft by DeepSeek V4.1 Flash, via pi, reviewed and reworked.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Codex (gpt-6.1-terra) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:15:22 +01:00
Horizon agentandClaude Opus 5.5 a52b9e48f3 Merge #11366 (main merged) into #11390
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:10:37 +01:00
Horizon agentandClaude Opus 5.5 21a27ca73e Merge origin/main into #11433 (main builds again after #11767)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:10:29 +01:00
Horizon agentandClaude Opus 5.5 17e7655cdf Merge origin/main into #11366 (main builds again after #11767)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:10:29 +01:00
Horizon agentandClaude Opus 5.5 f8ab91d422 Merge origin/main into #11445 (main builds again after #11767)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:10:28 +01:00
Horizon agentandClaude Opus 5.5 6b72630759 Merge origin/main into #11116 (main builds again after #11767)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:10:28 +01:00
Horizon agentandClaude Opus 5.5 d4515b62ec Merge origin/main into #11425 (main builds again after #11767)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:10:28 +01:00
MSedgeMC 4583362634 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-07 13:09:26 +00:00
MSedgeMC d00cf662b1 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-07 13:09:20 +00:00
MSedgeMC 6deb10741a port_map: client-007's prepareQuadFlat row cites the renamed helper 2026-11-07 13:07:59 +00:00
Horizon agentandClaude Opus 5.5 7770124ea0 Merge #11366's fix into #11390
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:06:02 +01:00
Horizon agentandClaude Opus 5.5 78ab0c3b39 living.rs landing test: MobWorld's level and dimension_type in place of nether/end (main's #10445 test)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:06:02 +01:00
Horizon agentandClaude Opus 5.5 7c7d13c458 Merge origin/main into #11390 (through #11366's resolved main merge)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:01:51 +01:00
Horizon agentandClaude Opus 5.5 ed7114b4a0 Merge origin/main into #11366 (spawn_rules_fixture: main's spawn_selection imports, without the Dimension this PR removes)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:01:39 +01:00
Horizon agentandClaude Opus 5.5 acbb98aa5c Merge origin/main into #11433 (keep both data.rs test modules)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:00:23 +01:00
Horizon agentandClaude Opus 5.5 385877d1fc Merge origin/main into #11445 (keep both probe fixtures)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:00:13 +01:00
Horizon agentandClaude Opus 5.5 771ccd721f Merge origin/main into #11425 (keep both commands.rs test modules and command_exec imports)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:59:55 +01:00
Horizon agentandClaude Opus 5.5 b9e272b1ab Merge origin/main into #11116 (keep both native-mods.md paragraphs)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:59:18 +01:00
Florian ERNSTandCodex 2688eb16d6 Decode Mob effect amplifiers as unsigned bytes
Co-Authored-By: Codex <[email protected]>
2026-11-07 13:52:45 +01:00
MSedgeMC 8fe6762146 test: compare enchantment durability effects
Add a direct Unbreaking and Mending durability comparison over the real
enchantment registry: item_damage remove_binomial (small and large paths)
and repair_with_xp, with --no-mending reproducing the Unbreaking corpus.
2026-11-07 12:50:41 +00:00
TeiwazikandClaude Sonnet 5.5 ff28824d42 Riding: boat riders keep their own seat
position_riders re-seated every mob whose vehicle is not a mob through
passenger_riding_position, which puts every boat rider in seat 0 from
the boat's position. seat_boat_mobs had already placed them, so remote
players on a moving boat jumped between the two seats each pass.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 13:44:21 +01:00
bulkandClaude Sonnet 5.5 a0c5f26cc2 Far ring brake: pull in over 50 ms, grow back under 45 ms
The ring got stuck at its smallest on servers whose normal tick sits
between 25 and 40 ms, since it only grew back under 25 ms.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 12:43:37 +00:00
TeiwazikandClaude Sonnet 5.5 45978aaf67 Seat test: import Vec3 and play packets
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 13:43:19 +01:00
24fa04d753 fix: drop mob XP after the guest who hurt it has left
Vanilla LivingEntity.dropExperience and Mob.dropCustomDeathLoot key on
lastHurtByPlayerMemoryTime, not whether that player is still in the
world. Horizon folded both into Death.player, so a guest who left
within the 100-tick memory made drops::die skip experience and
equipment.

Give die a player_killed flag from the timer. LAST_DAMAGE_PLAYER stays
None when killer_uuid cannot resolve them.

Fixes #11674

Co-Authored-By: OpenCode <[email protected]>
Co-authored-by: monkeycode-ai <[email protected]>
2026-11-07 12:29:23 +00:00
Mayonesu0 1429b27098 Merge remote-tracking branch 'origin/main' into perf/launcher-write-data-file 2026-11-07 13:20:05 +01:00
DetimesandClaude Opus 5.5 c78882c7da Older clients: attributes and effects in the client's numbering
1.21.2 dropped the generic./player./zombie. attribute prefixes, so the id tables of 1.21.1 and 1.20.6 (matched by
name) had no attribute runs and every update_attributes value was left out for those clients. They are regenerated
with the renames. Mob effect ids were never renumbered: update_mob_effect and remove_mob_effect now go through the
client's table, and an effect added after its release is not sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 12:16:51 +00:00
Horizon agentandClaude Opus 5.5 40dd7109bb Merge origin/main into random-source
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:09:37 +01:00
Horizon agentandClaude Opus 5.5 1db1b34dcb Merge origin/main into perf/11126-structure-starts-jigsaw
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:08:04 +01:00
Horizon agentandClaude Opus 5.5 d30b514728 Merge origin/main into fix/old-stats-file
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:06:46 +01:00
DetimesandClaude Opus 5.5 6993f213b6 step_1_21_1: drop the import the explode rewrite no longer uses
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 12:05:41 +00:00
Horizon agentandClaude Opus 5.5 511771b9f9 Merge origin/main into fix/11317-block-crack-feedback
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:03:03 +01:00
Horizon agentandClaude Opus 5.5 344382682e Merge origin/main into fix/11314-player-food-predicate
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:02:36 +01:00
Detimes bb22bf6570 Merge remote-tracking branch 'upstream/main' into fix-11722-old-pick-item 2026-11-07 11:58:27 +00:00
Detimes edef044a68 Merge remote-tracking branch 'upstream/main' into fix-11721-explode-radius 2026-11-07 11:58:27 +00:00
DetimesandClaude Opus 5.5 c7f54b7461 Older clients: a 1.21.3 client's pick-item swaps the slot into its hand
1.21.3 and older clients send pick_item with the inventory slot that holds the picked block's item; 26.3 has no
such packet and the adapter dropped it. It now becomes a container_click swap of that slot with the held hotbar
slot (tracked from set_carried_item and set_held_slot), state id 0 so the server resends the inventory.

Fixes #11722

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:58:27 +00:00
DetimesandClaude Opus 5.5 47fd58c339 Older clients: real explosion radius for 1.21.1, explosions no longer fail for 1.21.8 and older
The 1.21.8 and 1.21.1 explode steps re-read a payload the renumbering had already put in the client's ids with
the pinned codec, so the particle's layout was chosen by the wrong id and sending any explosion failed. They now
read and write through the client's ids. 1.21.1's step read the knockback as three doubles where 1.21.4's step
leaves a double and two floats. 1.21.1's strength is 26.3's radius instead of a fixed 3.0.

Fixes #11721

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:54:53 +00:00
Horizon agent 88a75f983b Merge remote-tracking branch 'origin/main' into cg65v-10210 2026-11-07 12:54:24 +01:00
Horizon agent dbd5775947 Merge remote-tracking branch 'origin/main' into cg65v-10210
# Conflicts:
#	crates/horizon-client/src/game/command_harness.rs
#	mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java
#	tools/test_command_exec_parity.py
2026-11-07 12:39:25 +01:00
Mayonesu0andClaude Opus 5.5 199e8193fd Launcher: write a prepared version's data file after installing it
A version's first start read its thousands of small files one by one, about
100 s under Windows Defender here, because only the game wrote
horizon-data.bin, and only after that slow start. The launcher now writes it
in the background once an install or import has its resources, reading on up
to 8 threads (43 s against 281 s on one, on a fresh copy); the start then
loads in 1.2 s. The game stays the fallback, on its one idle thread.

A reused version no longer copies the data file, which names its own root.
complete_assets removes the file when it adds something, as the file answers
missing for what it lacks. A write removes what a stopped writer left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 12:38:08 +01:00
TheMrZZandCodex gpt-6.1-sol ac4859eab4 fix: match command damage-only item predicate ranges
Evaluate the supported damage-only subpredicate against modeled damage and
existing effective component presence. Preserve removal precedence and leave
unsupported conjunctions on their existing path.

Fixes #11715

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 12:23:52 +01:00
Florian ERNSTandCodex 087c763432 Normalize summoned leash knots and check their fence support
Co-Authored-By: Codex <[email protected]>
2026-11-07 12:23:27 +01:00
Horizon agentandClaude Opus 5.5 5a65831d4a Merge #11483's head (main with the clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:53:46 +01:00
Horizon agentandClaude Opus 5.5 64f9bb1a61 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:53:08 +01:00
Horizon agentandClaude Opus 5.5 991983679c Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:52:41 +01:00
Florian ERNSTandCodex c2b59b6f99 Dispatch ordinary arrow shoot events on their first tick
Co-Authored-By: Codex <[email protected]>
2026-11-07 11:52:23 +01:00
Horizon agentandClaude Opus 5.5 b844b69826 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:51:48 +01:00
Horizon agentandClaude Opus 5.5 c2386a4616 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:50:06 +01:00
Horizon agentandClaude Opus 5.5 c524b40874 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:49:40 +01:00
Horizon agentandClaude Opus 5.5 d53411a24e Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:49:15 +01:00
Horizon agentandClaude Opus 5.5 db503217e3 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:48:22 +01:00
Horizon agentandClaude Opus 5.5 dddf61b000 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:47:28 +01:00
Horizon agentandClaude Opus 5.5 48986d7fd8 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:46:34 +01:00
exampleandClaude Opus 5.5 7746c0ef78 Merge main: picks up #11716's lint fix for verify
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:45:49 +01:00
Horizon agentandClaude Opus 5.5 fbbe20dc9c Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:45:40 +01:00
Horizon agentandClaude Opus 5.5 b9928751e4 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:45:12 +01:00
Horizon agentandClaude Opus 5.5 ed98ebc8a1 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:44:46 +01:00
TeiwazikandClaude Sonnet 5.5 55a54edebe Riding: follow plugin seat chains through invisible vehicles
Plugins seat players on text displays, interactions, armor stands or area
effect clouds that ride another player. Resolve the seat through the whole
chain of vehicles, keep the packet riding graph, move the local rider with a
moving seat, and use the Avatar attachment height for player vehicles.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 11:44:41 +01:00
Horizon agentandClaude Opus 5.5 c0ca0cce68 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:43:51 +01:00
Horizon agentandClaude Opus 5.5 984f2d9f06 Merge main (clippy as_chunks lint fix)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:43:23 +01:00
Horizon agentandClaude Opus 5.5 3ed97c7339 Merge main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:39:07 +01:00
Riccardo GuerrieroandClaude Opus 5.5 3f1b851c07 Merge origin/main into #11400 (main's 1.95 lint fix for interpolation.rs)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:37:51 +01:00
Horizon agentandClaude Opus 5.5 aa7516532a Merge main; drop run logs and the unrun diagnostic
tools/test_warden_memory_full_diagnostic.py is not a test_*_parity.py harness, so nothing runs it, and it is 816/839 by design. The canonical owned-memories harness stays. Drops the docs/parity run logs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:37:36 +01:00
Riccardo GuerrieroandClaude Opus 5.5 c9f2efa210 A player's Thorns hurts the mob as the player's thorns hit
Thorns on the player answered a mob's hit with generic damage that had no
attacker, so the mob was not knocked back, did not turn on the player and
dropped no experience when it died of it. It now hurts the mob by
`minecraft:thorns` damage the player caused (`DamageEntity` with the
wearer as owner), rolled from the mob's own random, and the held weapon's
Breach applies as on any hit by the player.

The whole equipment counts, in `EquipmentSlot` order: the main hand, the
off hand, then feet up to head (Thorns' slots are `any`), so a Thorns
piece held in a hand answers too. Each piece rolls its chance, hurts the
attacker and wears in that order, also when the attacker is already dead.
A piece that takes no wear, or a creative player's, is left alone.

A mob hit by thorns damage plays `enchant.thorns.hit` where it stands
when the hit lands whole, silent or not (`playSecondaryHurtSound`).

Part of #9954.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:34:28 +01:00
Horizon agentandClaude Opus 5.5 43c987818b Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:32:52 +01:00
Horizon agentandClaude Opus 5.5 a94924cd72 Merge origin/main into fix/loot-kill-sheep-state
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:32:52 +01:00
Horizon agentandClaude Opus 5.5 fa9500a04d Stop pinning camel temper to variant3 in the pose test
The pose test asserted that Temper lands in the legacy variant3 byte. #11483/#11659 move every equine's temper to the signed equine_temper field; the assertion was outside this test's subject (LastPoseTick), so drop it rather than pin the storage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:30:49 +01:00
Horizon agentandClaude Opus 5.5 81a719f832 Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:30:20 +01:00
Horizon agentandClaude Opus 5.5 029358df0d Merge #11483 (signed equine temper) into fix/camel-inherited-saved-fields
Both PRs added a signed AbstractHorse temper: #11483 for the seven horse and llama species, this one for camels. Keep one field, equine_temper, for every equine: the loader reads Temper unclamped for all of them, temper()/modify_temper() use it for camels too, and the camel saver writes it. The camel_temper field and the camel byte-clamp path are gone; tests follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:30:16 +01:00
Horizon agentandClaude Opus 5.5 ec62d53993 Merge origin/main into fix/camel-inherited-saved-fields
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:28:36 +01:00
Horizon agentandClaude Opus 5.5 23b6a5da91 crack feedback tests: give the test guest main's new Joined.configured
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:25:26 +01:00
Horizon agentandClaude Opus 5.5 1e1e48831a Merge origin/main into fix/11317-block-crack-feedback
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:25:20 +01:00
Horizon agentandClaude Opus 5.5 8a38d8831f Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:21:39 +01:00
Horizon agentandClaude Opus 5.5 4595cfca2f Merge origin/main into fix/loaded-sleeper-bed-position
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:21:38 +01:00
Horizon agentandClaude Opus 5.5 d7889ba66c Merge origin/main into fix/h290-pot-template-compounds
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:20:30 +01:00
Horizon agentandClaude Opus 5.5 78634140b3 Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:19:26 +01:00
Horizon agentandClaude Opus 5.5 5ebfcbdf7f Merge origin/main into fix/world-pack-enchantment-definitions
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:19:26 +01:00
Horizon agentandClaude Opus 5.5 c3083e75cb Fog test: clone the start state, FogState is no longer Copy
FogState now holds the torch flicker's LegacyRandom, so main's rain fog
test (settled_rain_fog_is_its_target_and_easing_is_unchanged) moved
`start` twice; verify failed on E0382.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:18:11 +01:00
Horizon agent 67728a8568 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-07 11:17:34 +01:00
Horizon agentandClaude Opus 5.5 9a1da6539a Merge origin/main into fix/h145-required-function-tags
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:15:52 +01:00
Horizon agentandClaude Opus 5.5 c9af605b1f Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:13:33 +01:00
Horizon agentandClaude Opus 5.5 b7772e4a84 Merge origin/main into fix/folder-datapack-metadata
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:13:32 +01:00
Horizon agentandClaude Opus 5.5 199eaad7da Merge #11631 into #11652: one RENAMES table
#11631 adds saved_piece_id (PiecesContainer.load's RENAMES) to the same file; read_jigsaw_start now asks it instead of its own copy of the four old ids. The upper-case id case is dropped from the test: Identifier.parse refuses upper case, so vanilla never reads 'MINECRAFT:JIGSAW' as a jigsaw piece. Land #11631 first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:13:04 +01:00
Horizon agentandClaude Opus 5.5 2d05c9517f Merge origin/main into #11480
command_exec_corpus.groups: keep main's mob_name_predicate_corpus import beside this branch's player_food_predicate_corpus one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:11:02 +01:00
Horizon agentandClaude Opus 5.5 e3e18fc523 Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:10:09 +01:00
Horizon agentandClaude Opus 5.5 c082361b4d Merge origin/main into fix/function-command-admission
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:10:09 +01:00
Horizon agentandClaude Opus 5.5 2860d47ffd Merge origin/main into #11666
Main's #11661 added LevelAccess::container_open and its test for the open copper chest; this branch keeps that name and its test and drops its own container_has_viewers, folding the copper golems' chests into GameLevel::container_open. The recheck_container_openers doc comments #11661 left stranded above container_open are back on their function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:10:07 +01:00
Horizon agentandClaude Opus 5.5 a1ec90f7fc Stats: a joining player's old name-based file moves too
load_guest_records read stats/<uuid>.json directly, and on the server thread (the default single player) and on LAN and dedicated servers every player joins through it, so locateStatsFile only reached the in-frame path. The guest's own name goes to locate_player_json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:08:59 +01:00
Horizon agentandClaude Opus 5.5 4d9d2cee62 Saved pieces: read an id without its namespace; move tag_json's doc back
Identifier.parse reads 'nvi' as minecraft:nvi, so RENAMES applies to a bare id too. The new saved_piece_id had been inserted between tag_json and its doc comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:08:17 +01:00
Horizon agentandClaude Opus 5.5 ed53fe24ad Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:06:33 +01:00
Horizon agentandClaude Opus 5.5 9fc3a4f0fc Merge origin/main into fix/loot-mine-executor-presence
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:06:32 +01:00
Arslan ArmanulyandClaude Opus 5.5 d3e7858cda Shader packs: GPU example fixtures give their packs terrain programs
Since a pack with no program for terrain or translucent terrain gets the
notes "no program for terrain; nothing draws it" and "no program for
translucent terrain; nothing draws it", standard_pack_gpu_entities and
entity_shadow_ownership failed their no-notes assertions: their packs had
entity programs only. Both packs now also have gbuffers_terrain and
gbuffers_water. The fixtures draw no terrain, and every other assertion is
unchanged.

Fixes #11710

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 15:06:18 +05:00
MSedgeMC c19b0817a0 test: compare falling block landings
Add a direct parity suite for the landing branch of
FallingBlockEntity.tick: real falling entities into air, solid blocks,
water, plants, slabs, cobwebs and moving pistons, with concrete powder's
water contact and the anvil landing event behind --no-contact.
2026-11-07 10:05:19 +00:00
Horizon agentandClaude Opus 5.5 3cb902bb21 Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:04:50 +01:00
Horizon agentandClaude Opus 5.5 9f8ce3033d Merge origin/main into fix/camel-loaded-pose-timestamp
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:04:49 +01:00
Horizon agentandClaude Opus 5.5 7cad6a50ff Drop the docs/parity run logs
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:03:19 +01:00
Horizon agentandClaude Opus 5.5 9712ebdde7 Merge origin/main into fix/effective-item-component-validation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:03:18 +01:00
Florian ERNSTandCodex 70cedfb11a Route attribute commands through the selected guest body
Co-Authored-By: Codex <[email protected]>
2026-11-07 11:02:58 +01:00
TheMrZZandCodex gpt-6.1-sol 6d5c7c51a6 Preserve modeled jukebox saved-song clock presence
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 11:01:17 +01:00
Horizon agentandClaude Opus 5.5 63d0b51776 Drop the docs/parity run log
Run logs are not docs; the PR body keeps the numbers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:00:08 +01:00
Horizon agentandClaude Opus 5.5 8917e8a9cb Merge origin/main into fix/llama-saved-temper
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:00:07 +01:00
Horizon agentandClaude Opus 5.5 354ba4a38a Merge origin/main into fix/h097-loaded-air-first-tick
Keep main's fall_step(entities) signature with the air guard first;
keep main's vibration_tests module beside the new test module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:57:58 +01:00
AkirabaneandClaude Opus 5.5 8e0b157254 dedicated: a stop waits for a proxy to move the players out first
With [transfer] on and players on, a stop (/stop, a stop signal, the
supervisor's stop or restart) now waits stop_wait_seconds (10 by default,
0 to 60, 0 stops at once as before) so a proxy told server/stopping can
move the players out first. The log says "Stopping in 10 s: a proxy may
move the players out first", which horizon-server takes as the start of
the stop. Every login is refused as server_shutdown, and the server ticks
on and answers the proxy's requests.

The wait ends as soon as no player is placed, at its time when no
hand-over is frozen, and at the latest a freeze's longest time later, so a
hand-over started in time finishes; the whole wait is cut at 90 s, within
the supervisor's 120 s for a stop, so stop_wait_seconds and
max_freeze_seconds may add up to 90 at most when the stop waits. No freeze
starts that this limit would cut: a player its source saved after the
target placed it would be on both servers. A freeze lasts ticks, so its
length is reckoned at the tick length of the moment (the rate's, or longer
on a server slower than its rate). A second stop ends the wait. Then the
stop goes on as vanilla's.

Refs #7484

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:51:02 +01:00
Alysia Zappavigna 4bb27d7c90 Merge remote-tracking branch 'upstream/main' into pr-11701 2026-11-07 20:48:42 +11:00
Ludovic MarieandClaude Opus 5.5 5e90d9f10b Merge origin/main into #11411; the credits test's Joined takes main's configured field
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:18:16 +01:00
Horizon agentandClaude Opus 5.5 faa8a4a52a Merge origin/main into #11413; the glide test's Joined and LanHost take main's new fields
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:17:40 +01:00
Ludovic Marie 6c0de3509d Merge remote-tracking branch 'origin/main' into w-11413 2026-11-07 10:17:26 +01:00
Horizon agentandClaude Opus 5.5 70ac0a01b8 Merge origin/main into #11457; the silent TNT test passes main's entity boxes (none)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:16:57 +01:00
Ludovic Marie 85a5c9f340 Merge remote-tracking branch 'origin/main' into w-11457 2026-11-07 10:16:57 +01:00
Horizon agentandClaude Opus 5.5 4aaf71dc39 Merge origin/main into #11411; main's spectator portal trips are not a credits respawn
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:10:54 +01:00
Ludovic Marie 6a3359d943 Merge remote-tracking branch 'origin/main' into w-11411 2026-11-07 10:10:44 +01:00
Horizon agentandClaude Opus 5.5 6397e50017 Merge origin/main into #11116; main's block_meets_player names its entity a Player
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:10:20 +01:00
Ludovic Marie fe36131256 Merge remote-tracking branch 'origin/main' into w-11116 2026-11-07 10:10:11 +01:00
TheMrZZandCodex gpt-6.1-sol 50467de40e fix: match typed custom data in mob equipment predicates
Project only typed custom-data snapshots from existing mob equipment
stacks and evaluate the admitted SNBT subset predicate. Preserve prior
view fields and unsupported unprojected-consumer behavior.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 10:05:55 +01:00
Horizon agentandClaude Opus 5.5 a7f5e08990 rustfmt the merge resolution
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 10:05:52 +01:00
Florian ERNSTandCodex d4d2214cfb Bind loaded Warden memories to their runtime slots
Co-Authored-By: Codex <[email protected]>
2026-11-07 09:59:36 +01:00
Horizon agentandClaude Opus 5.5 8368732e4e Merge origin/main into #11425
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 09:50:55 +01:00
Horizon agentandClaude Opus 5.5 e8edf93a48 Merge origin/main into #11457
splash takes both the PR's silent flag and main's hit motion (#11388).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 09:49:08 +01:00
Horizon agentandClaude Opus 5.5 dce6093276 Merge origin/main into #11414
Keep the mining experience cases alongside main's survival-only switch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 09:36:43 +01:00
Horizon agentandClaude Opus 5.5 b8a6663a3a Drop the run report from docs/
The evidence stays in the PR description.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 09:31:02 +01:00
Horizon agentandClaude Opus 5.5 05a81f37b5 Drop the run report from docs/
The evidence stays in the PR description.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 09:30:32 +01:00
MSedgeMC 1bc23d7a17 test: compare nether portal frame search
The portal parity suite only sent entities through portals: the PortalShape
search that turns an obsidian frame into portal blocks was never exercised.
Add a shape family over real frames and a --no-shape switch that reproduces
the previous corpus byte for byte.
2026-11-07 08:16:39 +00:00
Alysia Zappavigna e297f7245b ambience tests: import SoundEngine 2026-11-07 19:09:01 +11:00
Alysia Zappavigna 640dd0bcf5 ambience tests: import SoundEngine 2026-11-07 19:05:56 +11:00
Alysia Zappavigna 175fbe9e52 Merge commit '37d8dc0e5' into random-source
# Conflicts:
#	crates/horizon-client/src/game/lightning.rs
2026-11-07 18:56:19 +11:00
Alysia Zappavigna fde182860f random_source: repeat under HORIZON_STILL; tidy imports 2026-11-07 18:56:10 +11:00
Alysia Zappavigna 3fc0eb473e random_source: one RandomSource.create(); entity and level randoms as vanilla 2026-11-07 18:46:43 +11:00
Florian ERNSTandCodex f9eb279790 Bind actual mob target state in loot-kill predicates
Co-Authored-By: Codex <[email protected]>
2026-11-07 08:46:18 +01:00
exampleandClaude Opus 5.5 69ca4f94b7 Waxing a double copper chest reaches both halves; an open one doesn't weather
HoneycombItem.useOn gives a double chest's other half its game event and
particles and plays a second sound from the clicked block, on the server and
in the client's prediction. The wax sound leaves out the acting player and
goes out in the blocks source.

WeatheringCopperChestBlock.randomTick skips the attempt, and its draw, while
getEntitiesWithContainerOpen has anyone: a player's menu, or a copper golem
(CopperGolem.hasContainerOpen), a double chest counting for both halves.

Fixes #11378

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 08:24:54 +01:00
Florian ERNSTandCodex b322275555 Save Camel inherited horse fields from modeled state
Co-Authored-By: Codex <[email protected]>
2026-11-07 08:11:46 +01:00
TheMrZZandCodex gpt-6.1-sol b8d3a3b132 fix: keep vanilla crafter drops unnamed
Exclude actual crafters from automatic dropped-item name capture while
preserving chest/shulker names, contents and the other copy policies.
Cover the real destruction route against a frozen fresh Java reference.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 07:53:50 +01:00
yahya-nusseibehandClaude Opus 5.5 d689881e68 Cap the packets a connection queues for the hub between ticks
A connection's network thread hands every play packet to the hub over
an unbounded channel. The hub's inbox caps (INBOX_LIMIT packets,
INBOX_BYTES bytes) apply only as it drains that channel at the start of
a tick, so while one tick runs long (an autosave, chunk generation) a
client can queue tiny packets without bound, each a boxed Serverbound
many times its size on the wire.

Each connection now counts what it handed the hub and the hub hasn't
taken yet (Undrained, shared between the network thread and the
guest's PlayerSender). Past twice the inbox caps the network thread
disconnects the client with the same message as the packet-rate kick
(disconnect.exceeded_packet_rate) and logs a warning; the hub
uncounts each packet as it takes it. A client within the inbox caps
never comes near.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-07 08:06:12 +02:00
MSedgeMC 03c5e6b091 port_map: PlayerList.locateStatsFile is ported
The row said the name-based stats file is not moved to the uuid file. It names the function that
does it, and the segment rule that decides whether vanilla would look for it at all.
2026-11-07 05:49:55 +00:00
MSedgeMC f4cdc0873c test: pin the old stats file moving to the uuid name
The test works in a temporary world folder: nothing is written when there is nothing to move, the
`players/stats/<name>.json` file lands on the uuid name and is not left behind, a uuid file that
already exists wins and leaves the old file alone, and the segment check refuses capitals and
separators while accepting a lowercase name with dashes, dots and digits.
2026-11-07 05:49:55 +00:00
MSedgeMC f802d6cc2c fix: move an old name-based stats file to the player's uuid
PlayerList.locateStatsFile: the stats file is `stats/<uuid>.json`, but a version that wrote
`stats/<player name>.json` left its numbers under the old name. When the uuid file does not exist
yet and the name is one vanilla would write as a path segment
(FileUtil.isValidPathSegment: `[-._a-z0-9]`, and not `.` or `..` — the check is on
`<name>.json`, so a capital letter in the player's name refuses it), the old file is moved to the
uuid name and that is the file that is read; a failed move leaves the old one in place.

Horizon always resolved the uuid path, so a world opened after such a version started with empty
stats. The 26.3 advancements file has no name-based form (`PlayerList.getPlayerAdvancements`
resolves the uuid directory directly), so only stats move.
2026-11-07 05:49:55 +00:00
k3yhandClaude Opus 5.5 29a511747d Selectors find cushions
A cushion is an ordinary entity in vanilla (a BlockAttachedEntity), but
Horizon had no command target for it: @e never matched one, so execute
if entity, tag, data get, tp and kill missed every cushion. Target::Cushion
joins the level's candidates like a painting; /kill removes it with no
drop and lets its rider go, /tp moves it with its block, data get writes
it through cushion_to_nbt.

Fixes #11626.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 00:44:33 -05:00
MSedgeMC 3afa8e234b port_map: the two saved-start rows say which piece ids are read
PiecesContainer.load now names saved_piece_id, where the rename table lives,
and StructureStart.loadStaticStart spells out that a jigsaw start (the renamed
old ids included) comes back from its saved pieces while another structure's
start comes back from the generator's rebuild of its chunk.
2026-11-07 05:41:18 +00:00
MSedgeMC efe0b28747 test: the four old jigsaw piece ids are read, other piece types are not
A piece tag named minecraft:nvi, pcp, bastionremnant or runtime comes back as
jigsaw, as does minecraft:jigsaw itself; a monument, stronghold or jungle
temple piece (OMB, SHCC, TeJP) comes back as nothing so the start keeps the
generator's rebuild, and so does a tag with no id or one that is not a
compound. With the table narrowed to minecraft:jigsaw alone the first four
fail.
2026-11-07 05:41:18 +00:00
MSedgeMC c7d9d1aedd fix: a saved start's pieces use the ids an old save wrote for jigsaw
PiecesContainer.load maps four piece ids - minecraft:nvi, minecraft:pcp,
minecraft:bastionremnant and minecraft:runtime - to minecraft:jigsaw before it
looks the type up: a save from before those pieces were jigsaw wrote them under
the older names with the same pool-element tag. The saved-start reader only
took the literal minecraft:jigsaw id, so such a start fell through to the
generator's rebuild of its chunk, and where that rebuild makes a different
layout (a world whose structure data or version moved on) the start came back
with no pieces at all: nothing placed, nothing bearding the terrain.

saved_piece_id now holds that rename table for the reader; a piece of another
type (a monument's or a stronghold's, whose NBT is not a pool piece's) still
sends the start to the rebuild.
2026-11-07 05:41:18 +00:00
Florian ERNSTandCodex 6c6efb8d74 Refresh loaded sleeper position from bed geometry on first tick
Co-Authored-By: Codex <[email protected]>
2026-11-07 06:31:19 +01:00
TheMrZZandCodex gpt-6.1-sol fc711c3f6d fix: save pot sherd string templates as item compounds
Encode bare item templates using the primary record form while preserving
compound counts and components. Cover actual canonical load/save and the
real command route against a frozen fresh Java reference.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 06:14:22 +01:00
k3yhandClaude Opus 5.5 945f40e8ff /ride takes armor stands, displays, interactions and markers as vehicles
RideCommand.mount forces the ride (startRiding(vehicle, true, true)), so
any entity takes a rider. Horizon only took boats, carts and mobs. A rider
now sits at the vehicle's default passenger attachment (its box height,
less the rider's own vehicle attachment) and gets off on sneak on top of
it, as Entity does for a vehicle that overrides neither.

Fixes #11603.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 23:40:02 -05:00
Florian ERNSTandCodex 4aeb14b3ba Load active world-pack enchantment definitions
Co-Authored-By: Codex <[email protected]>
2026-11-07 05:35:26 +01:00
k3yhandClaude Opus 5.5 b9854b1d82 /ride seats and unseats any server player, whoever runs it
RideCommand.mount and dismount work on any ServerPlayer in vanilla. Horizon's
/ride reached only the player in place, so the console, a function, a command
block or another player could not seat a guest (every player of a server or a
LAN world, and in single player too): the guest's turn now runs through
for_player, as native_mount does. A guest as the vehicle answers
cant_ride_players, as any player does.

Fixes #11602.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 23:16:44 -05:00
TheMrZZandCodex gpt-6.1-sol f3fcb0ca25 fix: reject function tags with unresolved required references
Propagate required dependency failures before expanding function tags so
invalid tags cannot run partial members. Skip whole invalid optional children
while preserving the existing ordered, deduplicated expansion.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-07 04:38:01 +01:00
Vinícius MoreiraandClaude Opus 5.5 dd4528f4e4 Environment attributes: the layer stack, biome blending and weather
Ports EnvironmentAttributeSystem: every attribute is its default run
through layers in the order they are added, leading constant layers folded
into the base (bakeLayerSampler) and the result sanitized. The dimension
type's attributes are constant layers; the biome layer reads the biome at
the position, or for spatially interpolated attributes the
SpatialAttributeInterpolator mix that GaussianSampler accumulates; the
weather layers (WeatherAttributes.RAIN and THUNDER) blend by the rain and
thunder levels with each type's state-change lerp. Timelines plug in as
time layers and come next; nothing in the game uses the stack yet.

Entries of types not ported yet (append, overlay) are kept as no-ops so a
biome's other attributes still load.

The new harness environment_system compares 900 stacks with the pinned
client (36,000 lines), with the vanilla biome and dimension type data.

Part of #11486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 23:38:15 -03:00
Florian ERNSTandCodex 84f6959921 fix: require folder data-pack metadata sections
Reject folders without parseable metadata, an object pack section and a non-null description before exposing their contents. Preserve existing parser and format behavior.

Co-Authored-By: Codex <[email protected]>
2026-11-07 03:35:13 +01:00
Vinícius MoreiraandClaude Opus 5.5 f2c9af4827 Environment attributes: the registry and modifiers, checked against vanilla
Ports vanilla 26.3's environment attribute registry (EnvironmentAttributes:
types, defaults, ranges) and one EnvironmentAttributeMap entry: a value or
a {modifier, argument} object, parsed as its codec does (hex, list and int
colors, FloatWithAlpha, BlendToGray) and applied as AttributeModifier.apply
with float math in Java's order (ARGB.alphaBlend, addRgb, subtractRgb,
multiply, greyscale, scaleRGB, srgbLerp; Math.min/max). The layer stack
that sums these comes next; nothing uses the module yet.

The new harness environment_attribute_modifier compares 8,835 cases with
the pinned client, the registry included.

Part of #11486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 23:07:36 -03:00
Florian ERNSTandCodex 0de6eeb024 fix: reject functions containing invalid ordinary commands
Validate candidate functions at actual compilation permission before exposing them, using refreshed world content and candidate registry IDs.

Co-Authored-By: Codex <[email protected]>
2026-11-07 02:55:05 +01:00
Kevin RamirezandClaude Fable 5.1 3aadba6aba CI: run verify again after a wall-clock test flaked on the slow runner
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 19:43:57 -06:00
voidsip 8c991c7472 Isolate trade parity runs and format modifiers 2026-11-06 19:39:51 -06:00
Florian ERNSTandCodex 593e9e05cc Carry actual loot-mine executor presence into block drops
Co-Authored-By: Codex <[email protected]>
2026-11-07 02:20:33 +01:00
voidsip e03f69d607 fix: spill contents of items destroyed by explosions 2026-11-06 19:16:27 -06:00
Horizon agent eadca0ce30 Merge main into #10242
# Conflicts:
#	tools/command_exec_corpus.py
#	tools/test_command_exec_parity.py
2026-11-07 02:01:07 +01:00
Horizon agent 3e88f5909b Merge main into #10210
# Conflicts:
#	tools/test_command_exec_parity.py
2026-11-07 02:00:23 +01:00
Horizon agent ab6900b4c9 Merge main into #10283
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-07 01:57:18 +01:00
Horizon agent d64be662fe Merge main into #10559 2026-11-07 01:53:52 +01:00
Horizon agent 3b3f6aa00f Merge main into #10552 2026-11-07 01:53:46 +01:00
Horizon agent 58e32ea813 Merge main into #10280 2026-11-07 01:53:40 +01:00
Horizon agent e2268eb854 Merge main into #10201 2026-11-07 01:53:35 +01:00
Florian ERNSTandCodex 8b9e8417af Preserve loaded Camel pose timestamp boundaries
Co-Authored-By: Codex <[email protected]>
2026-11-07 01:42:37 +01:00
Kevin RamirezandClaude Fable 5.1 1426129516 CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 18:33:12 -06:00
voidsip a932bc6c86 Create recipe directory for isolated smithing menu fixture 2026-11-06 18:28:12 -06:00
Florian ERNSTandCodex 2aa9308e47 Reject stackable damageable item command inputs
Co-Authored-By: Codex <[email protected]>
2026-11-07 01:04:42 +01:00
Kevin RamirezandClaude Fable 5.1 23c572b374 CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 18:03:09 -06:00
voidsip 8158bcae73 Use the item codec crate in the mining parity probe 2026-11-06 17:45:50 -06:00
voidsip 62724ffccf Record scoped mining parity source and artifact hashes 2026-11-06 17:41:16 -06:00
DUzzL 52105d2c9b Adventure mode: gate placed entities and firework on can_place_on 2026-11-07 00:38:11 +01:00
voidsip 9782763e82 Cover mining component admission and explicit break slots 2026-11-06 17:35:52 -06:00
voidsip 2eb6044dfc Keep remote mining fixture compatible with speed cache 2026-11-06 17:34:56 -06:00
Florian ERNSTandCodex dd47001112 Record signed equine temper proof and scope
Co-Authored-By: Codex <[email protected]>
2026-11-07 00:32:23 +01:00
Kevin RamirezandClaude Fable 5.1 6564896c45 CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 17:23:11 -06:00
Florian ERNSTandCodex b775c66123 Preserve signed equine temper independently of gameplay limits
Co-Authored-By: Codex <[email protected]>
2026-11-07 00:10:40 +01:00
voidsip e3295a9974 Trim gateway fixture trailing blank line 2026-11-06 17:10:23 -06:00
voidsip 8554155932 Remove obsolete saved gateway arrival helper 2026-11-06 17:00:00 -06:00
MSedgeMC d114d2ef89 test: a stub with inline data or no .mcc still reads the .mcc
Without the change the first reads `Err(InvalidData, "external chunk stub has
inline data")` and the second `Err(Os { code: 2, kind: NotFound })` instead of
the 4000 bytes in `c.-32.0.mcc` and an absent chunk.
2026-11-06 22:56:48 +00:00
MSedgeMC 30a3b019ff fix: read a chunk's external stream the way RegionFile reads it
`RegionFile.getChunkDataInputStream` never trusts the stub's length once the
external flag is set: `streamLength != 0` only logs "Chunk has both internal and
external streams" and the stream comes from the `.mcc`. When the `.mcc` is not a
regular file, `createExternalChunkInputStream` answers `null`, so the chunk is
absent. Horizon refused both: a stub that also declared inline data failed with
"external chunk stub has inline data", and a stub whose `.mcc` was gone failed
with a `NotFound` io error, which aborts a reader where vanilla skips the chunk.
2026-11-06 22:56:47 +00:00
voidsip 4807f13288 Format world border regression assertions 2026-11-06 16:56:09 -06:00
TheMrZZandCodex gpt-6.1-sol 1d72cf2ed8 Discard loaded falling air before age and physics
Use the existing air predicate and Gone result at the start of the actual falling-block tick. Cover admitted command actors with a real Game tick regression and frozen Java parity controls.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-06 23:53:32 +01:00
brasgaandClaude Opus 5.5 5b9fe567ec Player predicates test food level and saturation (#11314)
PlayerPredicate.matches calls FoodPredicate.matches on the player's
FoodData: the food level in `level`, then the saturation, a float
compared as a double, in `saturation`. The player facts carried no food
and the matcher never read `food`, so any food bounds passed.

PlayerFacts now holds the food, always filled (two numbers), for the
player in place and for a server's other players, and player_facts tests
it after the level, as vanilla does.

The command_exec harness gets a group that fills and drains the player's
food in player loops and tests named food predicates, a non-player, and
a tick advancement whose player condition asks only for food.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 19:53:29 -03:00
DUzzL 9558ecf848 Keep the copper golem's name on its statue 2026-11-06 23:49:15 +01:00
Kevin RamirezandClaude Fable 5.1 d6802414fa CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 16:43:06 -06:00
DUzzL a7d2edbfb9 Beacon: select players by bounding-box overlap with the effect box 2026-11-06 23:37:57 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 5d44519d5b Frame identity: keep the player on a block while the scenes are built
Left in the air at y 163, the player fell into the sea below while prepare() ran, which unlocked the boat
recipes: their toast showed over the first shots at a different moment each run, so main against itself
failed in the top right corner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 23:27:38 +01:00
voidsip 7914cfe741 Keep saved-creeper radius test compatible with silence metadata 2026-11-06 16:23:43 -06:00
MSedgeMC c3326aed5e test: direct furnace block-entity tick parity
The command-execution furnace family could not give a checkable gap control
on this host, so this is a direct AbstractFurnaceBlockEntity.serverTick
harness instead: a real RecipeManager and a furnace, blast furnace or smoker
in a block-update level, compared with FurnaceCooking::tick. It pins the
cooking_fuel burn table for every fuel item, the 200/100/100 cook times and
speed multiplier, fuel consumption and LIT state, RecipesUsed experience, a
full output slot, timer decay, and an input changed mid-cook. --no-change
reproduces the corpus before that family.

757/757 cases match the pinned client.
2026-11-06 22:20:04 +00:00
voidsip 088b9e37e5 Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11330-explosion-item-health 2026-11-06 16:13:47 -06:00
voidsip 98cfa7ef55 Merge current upstream main into stack tool mining fix 2026-11-06 16:13:44 -06:00
voidsip a79aa4f977 test: add headless dropped-item explosion regression 2026-11-06 16:13:38 -06:00
voidsip 55d7ad61f1 Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11328-trade-modifiers 2026-11-06 16:13:33 -06:00
voidsip 2b839bce3d Keep smithing regression compatible with baseline APIs 2026-11-06 16:13:32 -06:00
voidsip 929ad64e2a Match trade enchantment modifiers and provider costs 2026-11-06 16:13:26 -06:00
voidsip 5345f12b9d Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/smithing-transform-11307 2026-11-06 16:12:56 -06:00
voidsip b1e79509ac Fix smithing transform optional inputs and result templates 2026-11-06 16:12:45 -06:00
voidsip bf40027865 Fix stack tool mining rules and immersion checks 2026-11-06 16:12:44 -06:00
voidsip 0289686b53 Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11317-block-crack-feedback 2026-11-06 16:12:21 -06:00
voidsip eeb3c04215 Match server crack stages and observer range 2026-11-06 16:12:13 -06:00
voidsip 9af63f81d3 Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11319-gateway-item-motion 2026-11-06 16:12:06 -06:00
voidsip 4fd7c5c271 Keep dropped items live through End gateways 2026-11-06 16:11:57 -06:00
voidsip c0aef4ac41 Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/round5-5-11321 2026-11-06 16:09:25 -06:00
voidsip 9e11182d53 Respect world borders for pistons and natural spawning 2026-11-06 16:09:24 -06:00
voidsip 854e12bf62 Merge upstream main for source-silence validation 2026-11-06 16:08:31 -06:00
MrCloudy2andClaude Opus 5.5 858582b279 Droppers insert into chest boats and container minecarts
DropperBlock.dispenseFrom finds its target with HopperBlockEntity.getContainerAt:
the block's container, else a container entity (chest boat or raft, chest or
hopper minecart) whose box meets the space in front, picked at random. Horizon's
dropper only asked for a block container, so items fell out next to a chest boat
instead of going in. It now falls back to the entity lookup hoppers already use.

The dispenser harness gains 48 dropper cases with chest boats, rafts and chest
and hopper minecarts centred in front, reaching in from beyond, just past the
space, two at once, behind a chest block and non-container vehicles. The oracle
and the fixture print the container entity's items (Tinv lines).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 23:06:16 +01:00
voidsip c06d1d81c4 Respect Silent on explosions and potion impacts 2026-11-06 16:06:09 -06:00
Florian ERNSTandCodex a44cdec48e Adopt live falling-block data into the resident entity
Co-Authored-By: Codex <[email protected]>
2026-11-06 23:03:23 +01:00
Kevin RamirezandClaude Fable 5.1 03e72bc0b0 CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 16:03:08 -06:00
MSedgeMC 197ad9fcc5 port_map: Phantom's anchor_pos is read and written
`tools/port_map/game2-002.tsv` recorded `gap: minor: anchor_pos is not read` and
`not written` for `Phantom.readAdditionalSaveData` and
`Phantom.addAdditionalSaveData`. Both now carry the anchor and say how: the key
only for a phantom that has an anchor, absent or unreadable as no anchor.
2026-11-06 22:00:10 +00:00
MSedgeMC 58feda2a09 test: a phantom's circling anchor through the chunk save
`mob_from_nbt` and `mob_to_nbt` are the pair `Game::load_mob` and
`Game::mob_tree_nbt` go through, so the test loads and saves a phantom by its
compound. A phantom at (0.5, 75, 0.5) whose save names `anchor_pos: [100, 64,
-40]` loads with that anchor, circles to (109.66, 62, -37.41) - the anchor,
`distance*cos(angle)` across and `-4 + height` up - and a phantom that moved its
anchor to (9, 70, -3) saves that position, not the one its compound came in
with. A phantom with no anchor loads with none and saves no `anchor_pos`.

Without reading the anchor the load gives the phantom (0, 80, 0), its own
position five blocks up, and the circle point (9.66, 78, 2.59); without writing
it the save keeps the stale (100, 64, -40).
2026-11-06 22:00:10 +00:00
MSedgeMC c02c215c62 fix: save a phantom's circling anchor with its chunk
`Phantom.addAdditionalSaveData` writes the anchor the phantom circles around
beside its size, and `readAdditionalSaveData` takes it back:

    protected void readAdditionalSaveData(final ValueInput input) {
       super.readAdditionalSaveData(input);
       this.anchorPoint = input.<BlockPos>read("anchor_pos", BlockPos.CODEC).orElse(null);
       this.setPhantomSize(input.getIntOr("size", 0));
    }

    protected void addAdditionalSaveData(final ValueOutput output) {
       super.addAdditionalSaveData(output);
       output.storeNullable("anchor_pos", BlockPos.CODEC, this.anchorPoint);
       output.putInt("size", this.getPhantomSize());
    }

Horizon models that anchor in `extra.home`, which
`PhantomCircleAroundAnchorGoal.selectNext` centres the circle on
(`anchor + (distance*cos(angle), -4 + height, distance*sin(angle))`), but
`mob_to_nbt` wrote only `size` and `mob_from_nbt` read only `size`. A phantom
saved and reloaded therefore kept the anchor `register` gives every new phantom
- its own position five blocks up, vanilla's `finalizeSpawn` value - instead of
the one in its save: a phantom at (0.5, 75, 0.5) loaded with
`anchor_pos: [100, 64, -40]` came back anchored at (0, 80, 0), and its first
circle point was (9.66, 78, 2.59) rather than (109.66, 62, -37.41).

`TagValueOutput.storeNullable` writes the key only for a non-null value, and
`read(...).orElse(null)` gives null for a save without one, so a phantom with no
anchor now writes no `anchor_pos` and loads back with none - the circle then
fills it with its own `blockPosition()`, as vanilla's does.
2026-11-06 22:00:10 +00:00
TheMrZZandCodex gpt-6.1-sol 008aba983e Spill explicit vehicle container contents on kill removal
Write back live menu slots before spilling chest boats, chest rafts and
container carts. Reuse the container split/motion algorithm through its
actual double-origin path, preserving integer callers and empty-slot draws.
Keep ordinary hurt, hull, lead and pending-loot policies separate.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-06 22:45:56 +01:00
Delete228andCodex 0c66644118 Merge Horizon main into the PR branch
Co-authored-by: Codex <[email protected]>
2026-11-07 00:45:54 +03:00
Kevin RamirezandClaude Fable 5.1 fdc26c707e CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 15:43:30 -06:00
Riccardo Guerriero 01b3be1502 Merge remote-tracking branch 'origin/main' into perf/11126-structure-starts-jigsaw 2026-11-06 22:42:17 +01:00
voidsip 9c292718aa Persist comparator output and hopper transfer cooldown 2026-11-06 15:40:57 -06:00
Florian ERNSTandCodex 7b53924423 Use modern falling-block state decoding and sand fallback
Co-Authored-By: Codex <[email protected]>
2026-11-06 22:36:12 +01:00
Kevin RamirezandClaude Fable 5.1 d4984f2ca0 CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 15:36:08 -06:00
DUzzL dd2d21f0f9 Fix natural spawn height bound off by one
NaturalSpawner.getRandomPosWithin samples up to chunk.getHeight(WORLD_SURFACE)+1,
and ChunkAccess.getHeight is firstAvailable-1, so the bound is firstAvailable.
Horizon already stored firstAvailable and added one more. Also correct the
oracle's fake LevelChunk.getHeight.
2026-11-06 22:30:06 +01:00
umcekoandClaude Sonnet 5.5 5fa72fe13a Gameplay reads the dimension type for lava, water, beds and anchors (#11282, 3/9)
Fast lava, water evaporation, bed and anchor rules, the raid-bright check, the
day timeline, ambient light and the default clock of /time read the level's
dimension type facts instead of matching on the level, as vanilla reads
DimensionType and its attributes. No behaviour change for the three built-in
levels.

Part of #11282

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 00:27:09 +03:00
umcekoandClaude Sonnet 5.5 0b23212f49 The dragon fight follows has_ender_dragon_fight (#11282, 5/9)
The fight tick, end crystal fire and respawn, the boss bar, the fight dragon
check, the exit portal and the DRAGON chunk ticket read the dimension type's
has_ender_dragon_fight, and the End flashes read its End skybox. No behaviour
change for the three built-in levels.

Part of #11282

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 00:27:09 +03:00
umcekoandClaude Sonnet 5.5 5db025666c Mobs and spawn rules read the dimension type (#11282, 4/9)
MobWorld carries the level key and its dimension type facts instead of nether
and end flags, and the spawn light test samples the type's
monster_spawn_light_level as vanilla's DimensionType.MonsterSettings does.
Fast lava, snow golem melting, piglin zombification, fixed-time and day
timeline checks read the type's facts. No behaviour change for the three
built-in levels; random draws are unchanged.

Part of #11282

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 00:27:09 +03:00
voidsip c558b29549 Honor block drops and RNG order for mining XP 2026-11-06 15:19:27 -06:00
DUzzL 37f8ebb618 Read scaffolding as its stable shape in fluid wall tests 2026-11-06 22:15:14 +01:00
Kevin RamirezandClaude Fable 5.1 ab98869192 CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 15:14:22 -06:00
DUzzL bedf076c56 Read stack components in anvil and grindstone results 2026-11-06 22:10:39 +01:00
Kevin RamirezandClaude Fable 5.1 7416b4a5f6 CI: run the checks again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 14:57:15 -06:00
26210e2da4 Read saved jigsaw structure starts before regenerating them
Part of #11126.

Load complete jigsaw starts from the owning chunk's structures.starts into
its shared generator cache, retaining regeneration for unsupported or
undecodable starts. Read pending saves in every dimension and preserve
reference counts alongside the original piece layout.

Cover resource-free round trips, generated layouts across two seeds and
pending-record loading from a different referencing chunk.

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WZzq8KX3vDMZy53y1vXqeT
2026-11-06 21:50:30 +01:00
Kevin RamirezandClaude Fable 5.1 b97af5d3da CI: run verify again after the runner ran out of disk
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 14:28:11 -06:00
rdbtCVSandClaude Opus 5.5 5c05eacc6d Let the remote motion handler reset a trident's stuck timer
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 20:17:07 +00:00
rdbtCVSandClaude Opus 5.5 ed8eaed845 Merge origin/main into PR #10201
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 20:11:11 +00:00
rdbtCVSandClaude Opus 5.5 0a6d5eb0a7 Merge origin/main into PR #10511
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 20:09:33 +00:00
Kevin RamirezandClaude Fable 5.1 ef6f7a2170 Sky darkening truncates the light level, as updateSkyBrightness does (#11323)
Level.updateSkyBrightness is `(int)(15.0F - skyLightLevel)`: the float
truncated. Horizon's environment::sky_darken (and the End copy in
Game::sky_darken) rounded, stepping the darkening up half a level early
at dusk and late at dawn, which moves bed eligibility and the light-
dependent spawns with it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-11-06 14:00:13 -06:00
Riccardo Guerriero 425b65a99f Merge remote-tracking branch 'origin/main' into fix/w149 2026-11-06 20:45:56 +01:00
a222a7e47a End a server player's glide on a climbable like vanilla
LivingEntity.travelFallFlying stops the glide on a climbable, and a
server simulates its players' travel (AUTHORITATIVE_SIDE_AND_SERVER).
Horizon's server travel cleared the flag only on the guest's temporary
body; as_guest now copies it back, so the glide ends on the server and
the client, which takes the flag from the server, stops gliding too.

Co-Authored-By: Codex (gpt-6.1-terra) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 20:45:15 +01:00
c4dcf2d2c8 Wait for the client's load after the End credits respawn
handleClientCommand(PERFORM_RESPAWN) for a player who won the game
calls restartClientLoadTimerAfterRespawn, as the death respawn does: the
player's movement and actions wait, and isInvulnerableTo spares it, until
its client reports the level loaded or 60 ticks pass. Horizon restarted
the timer only after a death.

Co-Authored-By: Codex (gpt-6.1-terra) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 20:41:08 +01:00
be7591c70b Drop a converting piglin's inventory like vanilla
Piglin.finishConversion cancels the admire, then drops every non-empty
stack of its inventory with spawnAtLocation (whole stacks, components
kept), then converts; the converted sound comes before all of it. Horizon
dropped only the admired off-hand item, before the sound, and the
inventory was lost with the piglin.

Co-Authored-By: Codex (gpt-6.1-terra) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 20:16:57 +01:00
Delete228andCodex be3fbc2d2b Supply entity kinds in collision probe fixtures
Co-authored-by: Codex <[email protected]>
2026-11-06 16:58:15 +03:00
Delete228andCodex 7af3e1ec44 Test stateful mod block entity lookup in the tooling fixture
Co-authored-by: Codex <[email protected]>
2026-11-06 16:58:15 +03:00
Delete228andCodex 79fe067a7e Declare the state factory with the GameLevel hook points
Co-authored-by: Codex <[email protected]>
2026-11-06 16:41:39 +03:00
MSedgeMC 4304cc44b5 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-06 13:39:30 +00:00
cb62d074db Search neighboring columns for dolphin breathing like vanilla
Match vanilla's column order and fallback when choosing a breathing destination.

Co-Authored-By: Codex (gpt-6.1-terra) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 14:35:37 +01:00
Delete228andCodex 796db06bf8 Resolve mod block shapes from entity context
Co-Authored-By: Codex <[email protected]>
2026-11-06 15:32:57 +03:00
Delete228andCodex 177548d416 Create native block entities from their actual block state
Co-Authored-By: Codex <[email protected]>
2026-11-06 15:21:47 +03:00
Horizon agentandClaude Opus 5.5 96c7d68d0d Unloading a chunk takes its lingering clouds with it
entity_chunks(remove = true) is the unload path: every other kind it
writes is also taken out of the level, and the potion clouds were not,
so a chunk loaded again got a second cloud on the same spot. The new
test unloads and reloads a cloud and expects one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 13:11:04 +01:00
Horizon agentandClaude Opus 5.5 5988321440 Jukebox: post jukebox_stop_play only while a song plays
JukeboxSongPlayer.stop posts the event inside `if (this.song != null)`:
taking a disc out (by hand or by a hopper) after its song ended is silent.
The test takes the finished disc out and expects only the end's event.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 13:11:02 +01:00
Horizon agentandClaude Opus 5.5 5ca811b47a Merge main into #10210; drop the packet trace and receipts
The merchant fixture compares strict command and menu records, so the raw
packet trace (net/command_trace.rs in the client receive loop, the Java
trace reader, the oracle's serialized channel) and the per-operation
receipts were diagnostics only. The production client no longer writes or
joins anything for them; tools/test_merchant_gate_parity.py is a thin
wrapper like the other command_exec fixtures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 13:04:15 +01:00
Horizon agent 7c32d1c4d6 Merge main into #10242
# Conflicts:
#	crates/horizon-items/src/item_data.rs
#	tools/command_exec_corpus.py
#	tools/test_command_exec_parity.py
2026-11-06 13:01:20 +01:00
Horizon agent 47dc19fa20 Merge main into #10283 2026-11-06 12:54:39 +01:00
Horizon agent 9141f1d538 Merge main into #10280 2026-11-06 12:54:33 +01:00
Horizon agentandClaude Opus 5.5 2ce4e8da11 Reset a remote trident's life on motion; cover lerpMotion in the remote motion test
ThrownTrident inherits AbstractArrow.lerpMotion, which restarts life even
when the motion is zero. The remote motion test compiles remote_motion out
of remote.rs, so its fixture needs the arrow fields; it now also checks
that zero motion keeps a stuck arrow in place and non-zero motion frees it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:38:30 +01:00
Horizon agent 3f1af338cb Merge main into #10201 2026-11-06 12:37:53 +01:00
rison1337andCodex GPT-6 786bd54096 Merge main to pick up mob_to_nbt build fixes
Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-06 15:33:17 +05:00
Riccardo Guerriero 16cdc3afd9 Merge remote-tracking branch 'origin/main' into perf/9996-surface 2026-11-06 10:27:43 +01:00
rison1337andCodex GPT-6 69d388deb0 Reuse completed armor-trim preparation between frames
Keep the completed ordered request list for the current atlas so an
unchanged overflow does not regenerate and upload every trim each frame.
Preserve final LRU residents, retry failures, and invalidate the cache
when equipment, atlas contents or the graphics device changes.

Fixes #10539

Co-Authored-By: Codex GPT-6 <[email protected]>
2026-11-06 14:01:59 +05:00
Riccardo GuerrieroandClaude Opus 5.5 0855321d41 A surface run above the minimum surface level stops there
Below the level the band takes its other variant, which may give another
block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Fekd3xkgubE8VfXrALh2td
2026-11-06 09:50:34 +01:00
Riccardo GuerrieroandClaude Opus 5.5 db6a8b7f44 Write surface rule runs of one block at once
`build_surface_shared` applies the compiled rule at every solid block of a
column. In the Overworld most bands specialise to "the ore veins, then one
block" (deepslate), so 1.7M rule applications per 64 chunks produce ~1M block
writes, each walking the rule tree from the top and going through
`set_block`/`set_block_worldgen_column`.

A band variant that is a block rule, or ore veins followed by one, gives that
block at every position where no vein places one. The walk now writes the whole
run of solid blocks at once: the top y through the single-block path, the rest
through `TerrainChunk::fill_solid_run`, stopping at the first y where a vein
can place a block (each vein's first test, its density), at the band's bottom
and at the write bounds. Only blocks that are opaque for the stage's heightmaps
and carry no fluid take this path, so one update at the run's top leaves the
maps as a write per block does.

`CompiledRule::apply` on a sequence also tests its conditional children in the
loop instead of through a recursive call.

Instructions (callgrind, proto phase, 64 chunks, seed 12345): Overworld
6.49 G -> 6.03 G (-7.0%), surface stage 1.98 G -> 1.53 G (-23%), rule
applications 599 M -> 329 M; Nether 2.97 G -> 2.73 G (-8.1%).

A first draft by DeepSeek V4.1 Flash, via pi, reviewed and reworked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 09:50:34 +01:00
Florian ERNSTandCodex 3443abbde5 Keep superclass air refill for NoAI Nautilus
Skip only the Nautilus custom air handler under NoAI, preserving the existing Breath/drown path and normal custom behavior. Cover actual Game and full Mob ticks against fresh Java.

Co-Authored-By: Codex <[email protected]>
2026-11-06 07:59:32 +01:00
MSedgeMC a33e5b574a The ledger knows a cloud's save is ported
AreaEffectCloud.addAdditionalSaveData was listed missing, which was right: only
the reader existed. game/potions.rs::potion_cloud_to_nbt writes it now, from
entity_chunks.
2026-11-05 22:12:59 +00:00
MSedgeMC 78cf6e36a0 Test that a lingering cloud survives a save
A cloud with a poison and a slowness effect, one of them hidden and one ambient,
written with potion_cloud_to_nbt and read back with potion_cloud_from_nbt: the
position, age, duration, radius, the four use settings, the duration scale,
RadiusPerTick, the effect list and the colour all come back. The test also
checks that the compound carries the field names vanilla's
readAdditionalSaveData looks for, and that it is saved as
minecraft:area_effect_cloud.
2026-11-05 22:12:59 +00:00
MSedgeMC bd991e7917 A lingering potion's cloud survives a save
AreaEffectCloud.addAdditionalSaveData writes the cloud's age, duration, radius,
the four use settings, RadiusPerTick, potion_duration_scale and its
potion_contents, and the client already read every one of them back
(game/potions.rs::load_potion_cloud): a cloud that was loaded from a save came
back whole. Nothing ever wrote one, though. entity_chunks writes the dragon, the
crystals, the item frames, the fangs and the rest kind by kind, and the
lingering clouds -- which live in breath_clouds, not in entity_lists! -- were in
none of those, so every replacement pass dropped the cloud a thrown potion or a
creeper left behind.

The save side now writes them: game/potions.rs::potion_cloud_to_nbt builds the
compound on the entity fields entity_nbt::entity_base_tag gives it, and
entity_chunks adds one tag per potion-bearing cloud of the chunk. A dragon's own
breath carries no potion and is not written.

The reader moved out of the Game method into potion_cloud_from_nbt, so the pair
can be tested against itself. The client keeps no potion id, so the effects are
written as custom_effects with the colour the cloud was drawn in, and the custom
particle and owner reference the vanilla cloud also saves have no counterpart
here.
2026-11-05 22:12:58 +00:00
MSedgeMC 18f1a16d12 test: a jukebox that stops posts jukebox_stop_play
A windowless game with a jukebox at (0, 64, 0): a disc put in and popped back
out posts one G 0,64,0 minecraft:jukebox_stop_play, a song ticked to its end
posts one, a broken jukebox posts none from this path (the world's spill posts
it) and a jukebox that never held a disc posts nothing.
2026-11-05 22:04:17 +00:00
MSedgeMC c7fc74cb26 fix: a jukebox that stops playing tells the listeners
JukeboxSongPlayer.stop posts GameEvent.JUKEBOX_STOP_PLAY at the block (and level
event 1011), and both ways a song ends reach it: popOutTheItem, when the disc is
taken out or a hopper pulls it, and tick's own hasFinished branch.

Horizon posted that event only from the world's removal path, so a broken
jukebox was heard but a jukebox whose disc was pulled out by hand, or whose song
ran out, was silent to a sculk sensor beside it. The paths that keep the block
now go through stop_song_heard; jukebox_removed keeps the plain stop_song,
because the world's spill already posts the same event once for it.
2026-11-05 22:04:17 +00:00
TheMrZZandCodex gpt-6.1-sol 93365662aa Save default icon flags in custom potion effects
Resolve an absent saved show_icon from show_particles while preserving
explicit icon bytes and the remaining potion fields. Keep this in the
saved item encoder, without changing the general component view.

Add resource-free decoded/modelled codec coverage and a guarded,
zero-tick chest command regression against the pinned Java behavior.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-05 21:52:58 +01:00
TheMrZZandCodex gpt-6.1-sol 751423b897 Defer villager trade reputation to the eligible AI phase
Retain the real last trader on the villager when a trade is accepted,
then deliver the coalesced reputation event after Brain.tick. Keep it
across menu close and live NoAI edits, and refresh current offer prices
when the event actually runs.

Add an actual-owner merchant regression with complete raw capture and
separate strict-all byte-order diagnostics.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-05 20:39:57 +01:00
DUzzL 219a56f260 Unstick arrows and tridents the server sets moving (AbstractArrow.lerpMotion) 2026-11-05 20:27:46 +01:00
936 changed files with 88631 additions and 7768 deletions

No files matched your search

+1 -1
View File
@@ -168,7 +168,7 @@ state stays separate from the library tests. This compiles gameplay twice for ex
| Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` |
| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server`, `horizon-anticheat` (L: `lan/anticheat.rs`) |
| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `options_file.rs`; `horizon-client-core/src/block_entity_nbt.rs`; G: `saving.rs`, `persist.rs` (entities), `world_session.rs` (opening and closing a world); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` |
| Input | game.rs `fn window_event`; G: `play_keys.rs` (`fn key_pressed`), `play_input.rs` (`fn play_mouse`, toggled keys, the hotbar wheel); crate `horizon-client-input` (`keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `clipboard.rs`); L: `osk.rs`; G: `pad.rs`, `pad_menu.rs`, `pointer_capture.rs` (mouse look, pointer grab) |
| Input | game.rs `fn window_event`; G: `play_keys.rs` (`fn key_pressed`), `play_input.rs` (`fn play_mouse`, toggled keys, the hotbar wheel); crate `horizon-client-input` (`keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `clipboard.rs`); L: `osk.rs`; G: `pad.rs`, `pad_menu.rs`, `pad_craft.rs`, `pointer_capture.rs` (mouse look, pointer grab) |
| Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` |
| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `mobs/cem.rs` + `mobs/cem_anim.rs` (OptiFine/EMF entity models and their animations); `horizon-client-core/src/lang.rs`; crates `horizon-assets`, `horizon-optifine`; G: `packs.rs` |
| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) |
+13 -2
View File
@@ -46,8 +46,11 @@ original classes, game shaders, textures or prepared resources are distributed h
`third_party/wgpu-hal` is [wgpu-hal](https://github.com/gfx-rs/wgpu) 30.0.1 by the gfx-rs
developers, with upstream fixes applied
([gfx-rs/wgpu#10124](https://github.com/gfx-rs/wgpu/pull/10124),
[gfx-rs/wgpu#10714](https://github.com/gfx-rs/wgpu/pull/10714)). It is licensed under MIT or
Apache-2.0; both licenses are in that folder (`LICENSE.MIT`, `LICENSE.APACHE`).
[gfx-rs/wgpu#10714](https://github.com/gfx-rs/wgpu/pull/10714)). Its GL backend also reports
the context's sampled textures and samplers per shader stage (usually 32 on desktop GL,
where WebGL2's minimum 16 was reported before), so a pipeline layout the driver accepts is
not refused. It is licensed under MIT or Apache-2.0; both licenses are in that folder
(`LICENSE.MIT`, `LICENSE.APACHE`).
## naga
@@ -306,3 +309,11 @@ Permission to use, copy, modify, and distribute this
software is freely granted, provided that this notice
is preserved.
```
## Starling
`crates/horizon-client-render/src/touch/layout.rs` is adapted from the touch layout of
[Starling](https://github.com/starling-client/starling), an Android port of Horizon, at commit
[150a414b09a1](https://github.com/starling-client/starling/tree/150a414b09a18c900489d9462a7fc035dae744b7)
(`android` branch), written mostly by Vasysik. Starling is licensed under the same MIT license as
Horizon (Copyright (c) 2026 Ludovic Marie and the Horizon contributors).
+2 -2
View File
@@ -290,12 +290,12 @@ pub fn normalize_quaternion(q: [f32; 4]) -> [f32; 4] {
[x * inv, y * inv, z * inv, w * inv]
}
/// JOML `Math.sin(float)` without fast math.
fn joml_sin(rad: f32) -> f32 {
pub fn joml_sin(rad: f32) -> f32 {
f64::from(rad).sin() as f32
}
/// JOML `Math.cosFromSin(float, float)` without fast math: the magnitude from
/// the sine, the sign from the angle's quadrant (exact zeros at right angles).
fn cos_from_sin(sin: f32, angle: f32) -> f32 {
pub fn cos_from_sin(sin: f32, angle: f32) -> f32 {
let cos = (1.0 - sin * sin).sqrt();
let tau = (std::f64::consts::PI * 2.0) as f32;
let a = angle + std::f32::consts::FRAC_PI_2;
@@ -217,9 +217,10 @@ pub fn stack(tag: &Tag) -> Option<Tag> {
Some(Tag::compound(out))
}
/// `ItemStackTemplate.CODEC`: an item id or `{id, count?, components?}`.
/// Encoding uses the primary record form, including for a bare item id.
fn template(tag: &Tag) -> Option<Tag> {
match tag {
Tag::String(_) => Some(tag.clone()),
Tag::String(_) => Some(Tag::compound([("id", tag.clone())])),
Tag::Compound(_) => {
let mut out = vec![("id", string(&text(tag.get("id"))?))];
if let Some(count) = int(tag.get("count")).filter(|c| *c != 1) {
@@ -1011,3 +1012,69 @@ mod tests {
assert_eq!(items[1].get("count"), Some(&Tag::Int(5)));
}
}
#[cfg(test)]
mod pot_template_tests {
use super::*;
use horizon_world::nbt::parse_snbt;
#[test]
fn decorated_pot_string_template_load_save_uses_item_compound() {
let parse = |s: &str| parse_snbt(s).expect("valid input NBT").0;
let input = |front: &str| {
let mut tag = parse(
r#"{id:"minecraft:decorated_pot",x:4,y:200,z:4,sherds:{back:{id:"minecraft:brick"},right:{id:"minecraft:archer_pottery_sherd"}},item:{id:"minecraft:wheat",count:3,components:{"minecraft:custom_name":"H290 item"}}}"#,
);
let Tag::Compound(root) = &mut tag else {
unreachable!()
};
let Some(Tag::Compound(sides)) = root.get_mut(&"sherds".into()) else {
unreachable!()
};
sides.insert("front".into(), parse(front));
tag
};
let other_fields = |loaded: &Tag, saved: &Tag| {
assert_eq!(saved.get("id"), loaded.get("id"));
for key in ["x", "y", "z", "item"] {
assert_eq!(saved.get(key), loaded.get(key), "{key}");
}
let loaded_sides = loaded.get("sherds").unwrap();
let saved_sides = saved.get("sherds").unwrap();
for side in ["back", "right"] {
assert_eq!(saved_sides.get(side), loaded_sides.get(side), "{side}");
}
assert_eq!(saved_sides.get("left"), None);
};
let plain = r#"{id:"minecraft:angler_pottery_sherd"}"#;
let defaults = r#"{id:"minecraft:angler_pottery_sherd",count:1,components:{}}"#;
let rich = r#"{id:"minecraft:angler_pottery_sherd",count:3,components:{"minecraft:custom_data":{h290:1},"minecraft:custom_name":"H290 sherd"}}"#;
// Actual canonical load/save entry, not the private template helper.
for (front, expected) in [(plain, plain), (defaults, plain), (rich, rich)] {
let loaded = input(front);
let original = loaded.clone();
let saved = canonical(&loaded).expect("actual decorated-pot codec");
other_fields(&loaded, &saved);
assert_eq!(
saved.get("sherds").unwrap().get("front"),
Some(&parse(expected))
);
assert_eq!(canonical(&saved).as_ref(), Some(&saved));
assert_eq!(loaded, original, "read-only canonicalization");
}
println!(
"H290 actual canonical compound/default/count/components, other sides/item/name and idempotency controls admitted"
);
let loaded = input(r#""minecraft:angler_pottery_sherd""#);
let original = loaded.clone();
let saved = canonical(&loaded).expect("actual decorated-pot codec");
other_fields(&loaded, &saved);
assert_eq!(loaded, original, "read-only canonicalization");
assert_eq!(
saved.get("sherds").unwrap().get("front"),
Some(&parse(plain)),
"string template must save the primary item compound",
);
assert_eq!(canonical(&saved).as_ref(), Some(&saved));
}
}
+41 -3
View File
@@ -412,10 +412,11 @@ pub fn to_text_with(
.collect()
})
.unwrap_or_default();
let translated = Text::translate(key, &args);
// TranslatableContents.decompose: Language.getOrDefault(key, fallback), so the
// fallback is the template itself, never looked up as another key.
match o.get("fallback").and_then(Value::as_str) {
Some(fallback) if translated.plain() == key => Text::translate(fallback, &args),
_ => translated,
Some(fallback) => Text::translate_with_fallback(key, fallback, &args),
None => Text::translate(key, &args),
}
} else if let Some(sel) = o.get("selector").and_then(Value::as_str) {
resolve(sel)
@@ -513,6 +514,43 @@ pub fn name_text(tag: &Tag) -> Text {
#[cfg(test)]
mod tests {
use super::*;
use crate::lang::{self, Language, ResourceSource};
struct Mem(std::collections::HashMap<String, Vec<u8>>);
impl ResourceSource for Mem {
fn read(&self, path: &str) -> Option<Vec<u8>> {
self.0.get(path).cloned()
}
}
/// TranslatableContents.decompose: Language.getOrDefault(key, fallback). A missing key
/// shows the fallback as written, even when the fallback is another key the language has.
#[test]
fn a_translatable_fallback_stays_literal() {
let pack = Mem([(
"assets/minecraft/lang/en_us.json".to_owned(),
br#"{"real.key": "Translated", "greet": "Hello %s"}"#.to_vec(),
)]
.into());
let ((), _) = lang::scoped(Language::load(&[&pack], "en_us"), || {
let parse = |v: Value| to_text(&v, &mut |_| Text::empty()).plain();
let missing = serde_json::json!({"translate": "missing.key", "fallback": "real.key"});
assert_eq!(parse(missing), "real.key");
// The fallback is a template: its arguments are filled in.
let args = serde_json::json!({"translate": "missing.key", "fallback": "Hi %s", "with": ["Steve"]});
assert_eq!(parse(args), "Hi Steve");
// A key the language has wins over its fallback.
let found =
serde_json::json!({"translate": "greet", "fallback": "real.key", "with": ["Alex"]});
assert_eq!(parse(found), "Hello Alex");
// A component built with the constructor keeps its meaning through its JSON.
let built = Text::translate_with_fallback("missing.key", "real.key", &[]);
let again = to_text(&built.component(), &mut |_| Text::empty());
assert_eq!(again.plain(), built.plain());
assert_eq!(again.component(), built.component());
});
}
/// SnbtGrammar: a compound or list may end with one comma; two in a row
/// stay an error.
#[test]
+18
View File
@@ -46,6 +46,21 @@ thread_local! {
}
/// The current language's `bidirectional`, read for every drawn string.
static BIDIRECTIONAL: AtomicBool = AtomicBool::new(false);
/// Counts the languages set (`set`): another count is another language, so text looked up
/// before it may read otherwise.
static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
thread_local! {
/// Counts the scopes this thread entered and left (`scoped`), which no other thread sees.
static SCOPE_GENERATION: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Which language text looks up in now, on this thread, as a count that changes whenever that
/// can: both counts only grow, so their sum changes when either does.
pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed) + SCOPE_GENERATION.get()
}
fn scope_changed() {
SCOPE_GENERATION.set(SCOPE_GENERATION.get() + 1);
}
/// A source of resource files: the prepared root plus packs, highest priority last.
pub trait ResourceSource {
@@ -524,6 +539,7 @@ pub fn available(sources: &[&dyn ResourceSource]) -> Vec<LanguageInfo> {
pub fn set(language: Language) {
BIDIRECTIONAL.store(language.bidirectional, Ordering::Relaxed);
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language));
GENERATION.fetch_add(1, Ordering::Relaxed);
}
pub fn current() -> Option<Arc<Language>> {
if let Some(language) = SCOPE.with(|s| s.borrow().as_ref().map(|s| s.language.clone())) {
@@ -543,6 +559,7 @@ pub fn scoped<R>(language: Language, f: impl FnOnce() -> R) -> (R, Vec<String>)
impl Drop for Restore {
fn drop(&mut self) {
SCOPE.with(|s| *s.borrow_mut() = self.0.take());
scope_changed();
}
}
let outer = SCOPE.with(|s| {
@@ -552,6 +569,7 @@ pub fn scoped<R>(language: Language, f: impl FnOnce() -> R) -> (R, Vec<String>)
})
});
let _restore = Restore(outer);
scope_changed();
let result = f();
let missed = SCOPE.with(|s| {
s.borrow_mut()
+1 -20
View File
@@ -1,6 +1,7 @@
//! NBT paths (`NbtPathArgument`): `foo.bar[0]`, `[]`, `list[{id:1}]`,
//! `{root:match}`, with get, set, insert and remove on a tag tree, and the
//! partial NBT comparison (`NbtUtils.compareNbt`) selectors and conditions use.
pub use horizon_world::nbt::compare_nbt;
use horizon_world::nbt::{Compound, JavaString, Tag, parse_snbt};
/// An error carrying the translation key and its arguments.
@@ -47,26 +48,6 @@ fn get_child<'a>(c: &'a Compound, name: &str) -> Option<&'a Tag> {
c.get(&key(name))
}
/// `NbtUtils.compareNbt(expected, actual, true)`.
pub fn compare_nbt(expected: &Tag, actual: Option<&Tag>) -> bool {
let Some(actual) = actual else { return false };
if std::mem::discriminant(expected) != std::mem::discriminant(actual) {
return false;
}
match (expected, actual) {
(Tag::Compound(e), Tag::Compound(a)) => {
a.len() >= e.len() && e.iter().all(|(k, v)| compare_nbt(v, a.get(k)))
}
(Tag::List(e), Tag::List(a)) => {
if e.is_empty() {
return a.is_empty();
}
a.len() >= e.len() && e.iter().all(|x| a.iter().any(|y| compare_nbt(x, Some(y))))
}
_ => expected == actual,
}
}
// ---- list-like tags ----------------------------------------------------------
/// The elements of a list or array tag.
@@ -89,6 +89,31 @@ pub struct Registries {
pub trigger_objectives: Vec<String>,
/// Objectives with the `trigger` criterion -> holder -> whether its score is locked.
pub trigger_scores: BTreeMap<String, BTreeMap<String, bool>>,
/// The `ConfiguredFeature` codec for an inline `minecraft:worldgen/feature`
/// value (`ResourceOrIdArgument`), where the source has the server's live
/// features; None leaves the decode to when the command runs.
pub inline_feature: Option<InlineFeatureCheck>,
}
/// A codec check of an inline value: its error message when it does not decode.
#[derive(Clone)]
pub struct InlineFeatureCheck(
std::sync::Arc<dyn Fn(&horizon_world::nbt::Tag) -> Result<(), String> + Send + Sync>,
);
impl InlineFeatureCheck {
pub fn new(
check: impl Fn(&horizon_world::nbt::Tag) -> Result<(), String> + Send + Sync + 'static,
) -> Self {
Self(std::sync::Arc::new(check))
}
pub fn check(&self, value: &horizon_world::nbt::Tag) -> Result<(), String> {
(self.0)(value)
}
}
impl std::fmt::Debug for InlineFeatureCheck {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("InlineFeatureCheck(..)")
}
}
/// The ids and tag ids of one registry.
#[derive(Clone, Debug, Default)]
+8 -1
View File
@@ -583,6 +583,10 @@ pub struct PadSettings {
/// The sneak button flips sneaking (Bedrock's default) instead of
/// holding it, unless vanilla's toggle crouch is on already.
pub toggle_sneak: bool,
/// LT + A on a recipe crafts on every server, not only in single player and on LAN worlds
/// found in the server list. Off by default: a server's rules may count a repeated craft as a
/// macro.
pub craft_on_servers: bool,
pub glyphs: GlyphStyle,
/// A Nintendo pad's face buttons go by their letters (A confirms and jumps, as on the
/// Switch's own menus and keyboard) instead of their places (B, at the bottom, does): on
@@ -614,6 +618,7 @@ impl Default for PadSettings {
look_deadzone: 0.12,
trigger_threshold: 0.4,
toggle_sneak: true,
craft_on_servers: false,
glyphs: GlyphStyle::Auto,
nintendo_letters: cfg!(target_os = "horizon"),
keyboard: TextKeyboard::Auto,
@@ -684,6 +689,7 @@ impl PadSettings {
s.trigger_threshold = unit(s.trigger_threshold).clamp(0.1, 0.9)
}
"toggleSneak" => s.toggle_sneak = flag(s.toggle_sneak),
"craftOnServers" => s.craft_on_servers = flag(s.craft_on_servers),
"glyphs" => s.glyphs = GlyphStyle::parse(value),
"nintendoLetters" => s.nintendo_letters = flag(s.nintendo_letters),
"keyboard" => s.keyboard = TextKeyboard::parse(value),
@@ -745,7 +751,8 @@ impl PadSettings {
self.keyboard.name(),
);
text.push_str(&format!(
"gameplayGuide:{}\npointerSpeed:{}\nscrollSpeed:{}\nrepeatDelay:{}\nrepeatInterval:{}\n",
"craftOnServers:{}\ngameplayGuide:{}\npointerSpeed:{}\nscrollSpeed:{}\nrepeatDelay:{}\nrepeatInterval:{}\n",
bool_text(self.craft_on_servers),
self.guide_detail.name(),
self.pointer_speed, self.scroll_speed, self.repeat_delay, self.repeat_interval,
));
@@ -32,6 +32,11 @@ fn pack(properties: &str, shadow: Option<&str>, reads_shadow: bool) -> horizon_s
write("final.fsh", if reads_shadow { SHADOW_READ } else { COLOUR });
write("gbuffers_entities.vsh", VERTEX);
write("gbuffers_entities.fsh", COLOUR);
// Terrain programs keep the load free of "nothing draws it" notes; no terrain is drawn.
for terrain in ["gbuffers_terrain", "gbuffers_water"] {
write(&format!("{terrain}.vsh"), VERTEX);
write(&format!("{terrain}.fsh"), COLOUR);
}
if let Some(shadow) = shadow {
write("shadow.vsh", VERTEX);
write("shadow.fsh", shadow);
@@ -245,6 +245,7 @@ fn replay(window: Arc<Window>) -> Result<(), Box<dyn std::error::Error>> {
settings.fxaa,
settings.taa,
settings.upscale,
0.85,
);
let mut notes = Vec::new();
let mut note = |what: &str, result: horizon_client_render::Result<()>| {
@@ -660,6 +661,7 @@ fn remesh(
blend_radius,
smooth_lighting,
cutout_leaves,
opaque_ice: false,
translucent_layers: &[],
leaf_culling,
};
@@ -50,10 +50,14 @@ fn pack(renderer: &mut Renderer, folder: &Path, valid: bool) {
std::fs::create_dir_all(&shaders).unwrap();
let vertex = "#version 120\nvarying vec2 uv; void main(){gl_Position=ftransform();uv=gl_MultiTexCoord0.xy;}\n";
let fragment = "#version 120\nuniform int entityId; uniform int blockEntityId; uniform vec4 entityColor; void main(){gl_FragData[0]=vec4(float(entityId)/255.0,entityColor.a,float(blockEntityId)/255.0,1.0);}\n";
// The terrain programs keep the load free of "nothing draws it" notes; this
// fixture draws no terrain.
for program in [
"gbuffers_entities",
"gbuffers_block",
"gbuffers_entities_translucent",
"gbuffers_terrain",
"gbuffers_water",
] {
std::fs::write(shaders.join(format!("{program}.vsh")), vertex).unwrap();
std::fs::write(
+267 -5
View File
@@ -47,6 +47,53 @@ struct Channel {
world: u32,
/// The sound file it started and when, to tell another player's copy of it.
started: Option<(String, std::time::Instant)>,
/// Its sound event plays clearly through a mod's muffle (`Audio::muffle`).
unmuffled: bool,
}
/// The cutoff of the muffle's low-pass at full strength: the world heard through ringing ears.
const MUFFLED_CUTOFF: f32 = 300.0;
/// The cutoff it sweeps down from as its strength rises.
const OPEN_CUTOFF: f32 = 20_000.0;
/// How long the muffle takes to glide to a new level: a game tick's step (50 ms) would click.
const MUFFLE_GLIDE: f32 = 0.02;
/// A mod's muffle (`Audio::muffle`) in the mixer: the other sounds are mixed apart, low-passed by
/// two one-pole stages and turned down, then added to the sounds it leaves clear. While it is off
/// (never set, or faded out) the sounds mix straight into the output, as without it.
#[derive(Default)]
struct Muffle {
/// `[amount, lowpass]`, each 0 to 1, as the game's tick last set them.
target: [f32; 2],
/// Where the output is now, gliding to `target`.
current: [f32; 2],
/// The low-pass stages' state for the left and right output channels.
stages: [[f32; 2]; 2],
/// The muffled sounds of one buffer, reused.
bus: Vec<f32>,
}
impl Muffle {
fn active(&self) -> bool {
self.target != [0.0; 2] || self.current.iter().any(|v| *v > 1e-4)
}
/// Adds `bus` (the muffled sounds) to `data`, low-passed and turned down.
fn apply(&mut self, bus: &[f32], data: &mut [f32], channels: usize, rate: u32) {
let rate = rate as f32;
let glide = 1.0 - (-1.0 / (MUFFLE_GLIDE * rate)).exp();
for (frame, muffled) in data.chunks_mut(channels).zip(bus.chunks(channels)) {
for (current, target) in self.current.iter_mut().zip(self.target) {
*current += (target - *current) * glide;
}
let [amount, lowpass] = self.current;
let gain = 1.0 - amount;
let cutoff = OPEN_CUTOFF * (MUFFLED_CUTOFF / OPEN_CUTOFF).powf(lowpass);
let a = 1.0 - (-std::f32::consts::TAU * cutoff / rate).exp();
for ((out, s), stage) in frame.iter_mut().zip(muffled).zip(&mut self.stages) {
stage[0] += (s - stage[0]) * a;
stage[1] += (stage[0] - stage[1]) * a;
// Dry at no strength, so a muffle that only turns sounds down leaves them as they were.
*out += (s + (stage[1] - s) * lowpass) * gain;
}
}
}
}
#[derive(Default)]
struct Mixer {
@@ -65,6 +112,8 @@ struct Mixer {
cameras: Vec<([f64; 3], Basis, u32)>,
/// Per-source gain/pan/step cache for one buffer, reused across callbacks.
voices: Vec<(ChannelId, [f32; 3], f64)>,
/// A mod's muffle of the sounds it does not exempt.
muffle: Muffle,
limiter_peak: f32,
/// The output device the stream was opened on (`Library.currentDeviceName`).
#[cfg(feature = "audio")]
@@ -100,6 +149,21 @@ pub struct Heard {
pub range: f32,
pub looping: bool,
}
/// A mod's muffle (`Audio::muffle`): its full strength, and the ticks it fades over and has left.
#[derive(Clone, Copy, Debug, PartialEq)]
struct MuffleFade {
amount: f32,
lowpass: f32,
ticks: u32,
left: u32,
}
impl MuffleFade {
/// `[amount, lowpass]` now: full when set, falling in a straight line to none.
fn level(&self) -> [f32; 2] {
let left = self.left as f32 / self.ticks as f32;
[self.amount * left, self.lowpass * left]
}
}
/// The mixer side of the engine (`Backend`).
pub struct MixerBackend {
mixer: Arc<Mutex<Mixer>>,
@@ -247,6 +311,8 @@ pub struct Audio {
pub stopped: std::collections::BTreeMap<String, u32>,
/// The volume sliders' `SoundPreviewHandler`.
preview: crate::sound_preview::SoundPreview,
/// A mod's muffle fading out (`muffle`), advanced by `tick`.
muffle: Option<MuffleFade>,
/// `SoundEngine.lastSeenDevices`: the system default output last seen.
#[cfg(feature = "audio")]
default_seen: Option<String>,
@@ -439,6 +505,7 @@ impl Backend for MixerBackend {
owner: self.owner,
world: self.world,
started: None,
unmuffled: false,
},
);
Some(id)
@@ -466,6 +533,9 @@ impl Backend for MixerBackend {
fn set_relative(&mut self, channel: ChannelId, relative: bool) {
self.with(channel, |c| c.relative = relative);
}
fn set_unmuffled(&mut self, channel: ChannelId, unmuffled: bool) {
self.with(channel, |c| c.unmuffled = unmuffled);
}
/// `getCompleteBuffer` (cached, else decoded on the decoder thread) or
/// `getStream` (decoded on a thread of its own), then attach and
/// `alSourcePlay`. A sound that cannot load leaves its source initial,
@@ -702,6 +772,13 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0));
voices.push((*id, [left, right, gain], step));
}
// A mod's muffle: the sounds it doesn't exempt mix into a bus of their own first.
let muffling = mixer.muffle.active();
let mut bus = std::mem::take(&mut mixer.muffle.bus);
if muffling {
bus.clear();
bus.resize(data.len(), 0.0);
}
for (id, [left, right, gain], step) in voices.iter().copied() {
let Some(c) = mixer.channels.get_mut(&id) else {
continue;
@@ -711,7 +788,12 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
};
let source_channels = source_channels as usize;
let frames = samples.len() / source_channels;
for frame in data.chunks_mut(channels) {
let out: &mut [f32] = if muffling && !c.unmuffled {
&mut bus
} else {
&mut *data
};
for frame in out.chunks_mut(channels) {
let mut i = c.position as usize;
if i + 1 >= frames {
if c.looping && frames > 1 {
@@ -746,6 +828,14 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) {
}
}
mixer.voices = voices;
if muffling {
mixer.muffle.apply(&bus, data, channels, rate);
} else {
// Off: the next muffle starts from silence, not from the last one's filter.
mixer.muffle.current = [0.0; 2];
mixer.muffle.stages = [[0.0; 2]; 2];
}
mixer.muffle.bus = bus;
// Limit the whole buffer together, preserving waveform and stereo balance
// instead of flattening each overloaded sample; release over 200 ms
// (OpenAL Soft's output limiter, `ALC_OUTPUT_LIMITER_SOFT`, releases
@@ -1071,12 +1161,13 @@ impl Audio {
listener: [0.0; 3],
listener_yaw: 0.0,
master: 1.0,
random: LegacyRandom::new(crate::sound_engine::unique_seed()),
random: crate::random_source::create(),
source_override: None,
capture: None,
heard: Default::default(),
stopped: Default::default(),
preview: Default::default(),
muffle: None,
#[cfg(feature = "audio")]
default_seen: if live { default_output_name() } else { None },
#[cfg(feature = "audio")]
@@ -1232,12 +1323,13 @@ impl Audio {
listener: [0.0; 3],
listener_yaw: 0.0,
master: self.master,
random: LegacyRandom::new(crate::sound_engine::unique_seed()),
random: crate::random_source::create(),
source_override: None,
capture: None,
heard: Default::default(),
stopped: Default::default(),
preview: Default::default(),
muffle: None,
// The device belongs to the first player's output, which looks after it.
#[cfg(feature = "audio")]
default_seen: self.default_seen.clone(),
@@ -1370,6 +1462,50 @@ impl Audio {
}
self.sync_volumes();
self.engine.tick(paused, ctx, &mut self.backend);
// A paused game holds a mod's muffle where it is, as it holds the sounds.
if !paused && let Some(fade) = &mut self.muffle {
fade.left = fade.left.saturating_sub(1);
let level = fade.level();
if fade.left == 0 {
self.muffle = None;
self.engine.set_unmuffled(Vec::new(), &mut self.backend);
}
self.set_muffle_level(level);
}
}
/// A mod's muffle (`native_muffle_sounds`): `amount` (0 to 1) of every sound's volume taken
/// away and `lowpass` (0 to 1) dulling it, from untouched to a 300 Hz low-pass, fading in a
/// straight line to none over `ticks` client ticks; the sound events in `exempt` (namespaced,
/// `mymod:ear.ringing`) play clearly through it, those already playing too. It replaces any
/// muffle in place; `ticks` 0 or no strength ends it. The output's, so in splitscreen every
/// player hears it. False for an amount or strength outside 0 to 1.
pub fn muffle(&mut self, amount: f32, lowpass: f32, ticks: u32, exempt: &[&str]) -> bool {
if !(0.0..=1.0).contains(&amount) || !(0.0..=1.0).contains(&lowpass) {
return false;
}
let on = ticks > 0 && (amount > 0.0 || lowpass > 0.0);
let exempt = if on {
exempt
.iter()
.map(|e| crate::sound_events::normalize(e))
.collect()
} else {
Vec::new()
};
self.engine.set_unmuffled(exempt, &mut self.backend);
self.muffle = on.then_some(MuffleFade {
amount,
lowpass,
ticks,
left: ticks,
});
self.set_muffle_level(self.muffle.map_or([0.0; 2], |fade| fade.level()));
true
}
fn set_muffle_level(&mut self, level: [f32; 2]) {
if let Ok(mut m) = self.backend.mixer.lock() {
m.muffle.target = level;
}
}
/// The `uiSoundReserve` extra: positional sounds leave
/// `sound_engine::HEARD_RESERVE` static channels free (off: vanilla's pool).
@@ -1468,6 +1604,14 @@ impl Audio {
let id = self.engine.add(instance, false);
self.engine.play_delayed(id, ticks);
}
/// `SoundManager.playDelayed` of an instance the caller made: it starts
/// `ticks` sound-engine ticks from now.
pub fn play_instance_after(&mut self, instance: SoundInstance, ticks: i32) {
*self.heard.entry(instance.identifier.clone()).or_default() += 1;
self.sync_volumes();
let id = self.engine.add(instance, false);
self.engine.play_delayed(id, ticks);
}
/// `play` for this client only: a sound a packet's handler plays
/// (`playLocalSound`), which the guests play from that packet themselves.
pub fn play_unshared(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) {
@@ -1482,7 +1626,7 @@ impl Audio {
"minecraft:ui.button.click",
1.0,
0.25,
SoundEngine::unseeded(),
crate::random_source::create(),
),
false,
);
@@ -1624,7 +1768,7 @@ impl Audio {
f64::from(pos[2]) + 0.5,
];
let event = crate::sound_events::normalize(event);
let instance = SoundInstance::for_jukebox_song(&event, at, SoundEngine::unseeded());
let instance = SoundInstance::for_jukebox_song(&event, at, crate::random_source::create());
self.play_instance(instance, true).0
}
/// Stop and drop a held instance.
@@ -1835,6 +1979,7 @@ mod tests {
owner: 0,
world: 0,
started: None,
unmuffled: false,
}
}
@@ -2255,6 +2400,123 @@ mod tests {
assert_eq!(data, [0.5; 2]);
}
/// One second of a `hz` sine at 48 kHz, amplitude 0.3 (looped, it repeats seamlessly).
fn sine(hz: f32) -> Vec<f32> {
(0..48_000)
.map(|i| 0.3 * (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())
.collect()
}
fn rms(data: &[f32]) -> f32 {
(data.iter().map(|s| s * s).sum::<f32>() / data.len() as f32).sqrt()
}
/// `seconds` of the mixer's stereo output, in the 10 ms buffers an output stream asks for.
fn listen(m: &mut Mixer, seconds: f32) -> Vec<f32> {
let mut out = Vec::new();
let mut buffer = [0.0; 960];
for _ in 0..(seconds * 100.0).round() as usize {
mix(m, &mut buffer, 2, 48_000);
out.extend_from_slice(&buffer);
}
out
}
#[test]
fn a_muffle_dulls_and_quietens_every_sound_but_the_exempt_ones() {
// A looping tone heard through a muffle of `[amount, lowpass]`, once it has settled.
let heard = |hz: f32, muffle: [f32; 2], unmuffled: bool| {
let mut m = Mixer::default();
let mut c = channel(sine(hz), None, [0.0, 0.0, 2.0], true);
c.unmuffled = unmuffled;
m.channels.insert(1, c);
m.muffle.target = muffle;
listen(&mut m, 0.2);
listen(&mut m, 0.2)
};
let plain = |hz: f32| rms(&heard(hz, [0.0; 2], false));
// Fully low-passed, a 6 kHz whine all but goes and a 100 Hz hum keeps most of its level.
assert!(rms(&heard(6000.0, [0.0, 1.0], false)) < plain(6000.0) * 0.05);
assert!(rms(&heard(100.0, [0.0, 1.0], false)) > plain(100.0) * 0.8);
// Half the volume taken and no low-pass: half the level, the tone itself untouched.
let ducked = rms(&heard(6000.0, [0.5, 0.0], false)) / plain(6000.0);
assert!((ducked - 0.5).abs() < 1e-3, "{ducked}");
// An exempt sound plays through as if there were no muffle, sample for sample.
assert_eq!(
heard(6000.0, [0.5, 1.0], true),
heard(6000.0, [0.0; 2], false)
);
}
#[test]
fn a_faded_muffle_leaves_the_sound_as_it_was() {
let mixer = || {
let mut m = Mixer::default();
m.channels
.insert(1, channel(sine(3000.0), None, [2.0, 0.0, 1.0], true));
m
};
let (mut muffled, mut plain) = (mixer(), mixer());
muffled.muffle.target = [0.7, 1.0];
assert_ne!(listen(&mut muffled, 0.1), listen(&mut plain, 0.1));
muffled.muffle.target = [0.0; 2];
listen(&mut muffled, 0.5);
listen(&mut plain, 0.5);
assert_eq!(listen(&mut muffled, 0.1), listen(&mut plain, 0.1));
}
#[test]
fn a_mods_muffle_fades_with_the_game_ticks_and_spares_its_exempt_sounds() {
let mut audio = Audio::silent(Path::new("/nonexistent/horizon-test-assets"));
audio.engine.registry.add_file(
"minecraft",
br#"{"ambient.cave":{"sounds":["ambient/cave/cave1"]}}"#,
&|_, _| true,
);
audio.engine.registry.add_file(
"hztest",
br#"{"ear.ringing":{"sounds":["ear/ringing"]}}"#,
&|_, _| true,
);
// The engine makes its channels; with no output, none loads a file.
audio.engine.loaded = true;
let marks = |audio: &Audio| {
let m = audio.backend.mixer.lock().unwrap();
let mut marks: Vec<_> = m
.channels
.iter()
.map(|(&id, c)| (id, c.unmuffled))
.collect();
marks.sort();
marks
};
let level = |audio: &Audio| audio.backend.mixer.lock().unwrap().muffle.target;
let close =
|a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6;
// Two sounds already playing, and one exempt sound started under the muffle.
audio.play("ambient.cave", None, 1.0, 1.0);
audio.play("hztest:ear.ringing", None, 1.0, 1.0);
assert!(audio.muffle(0.8, 1.0, 4, &["hztest:ear.ringing"]));
audio.play("hztest:ear.ringing", None, 1.0, 1.0);
assert_eq!(marks(&audio), [(1, false), (2, true), (3, true)]);
assert!(close(level(&audio), [0.8, 1.0]));
let ticks = TickContext::default();
audio.tick(false, &ticks);
assert!(close(level(&audio), [0.6, 0.75]), "{:?}", level(&audio));
// A paused game holds it.
audio.tick(true, &ticks);
assert!(close(level(&audio), [0.6, 0.75]), "{:?}", level(&audio));
for _ in 0..3 {
audio.tick(false, &ticks);
}
assert_eq!(level(&audio), [0.0; 2]);
// Over: its exemptions go with it.
assert_eq!(marks(&audio), [(1, false), (2, false), (3, false)]);
// Out of range changes nothing.
assert!(!audio.muffle(1.5, 0.0, 10, &[]));
assert_eq!(level(&audio), [0.0; 2]);
}
#[test]
fn output_devices_are_looked_at_again_only_when_the_cards_change() {
// No fingerprint (not Linux, or the cards could not be read): the list
@@ -0,0 +1,314 @@
//! GPU Culling's Auto mode: the setting switched by what limits the frame, measured here.
//!
//! GPU Culling moves the walk over the near sections and the listing of their draws from the
//! render thread to the GPU. That pays where the CPU is the slower of the two and costs where
//! the GPU is, and which a machine is can't be told from its parts: a fast CPU with a modest
//! GPU, a slow one with a strong GPU and every mix between depend on the scene, the render
//! distance and the resolution. So Auto watches the frames' own CPU and GPU times, and only
//! where the CPU is clearly the slower one it tries GPU Culling, measures the frame again, and
//! keeps it if the frame got faster. A trial that didn't help is undone and not repeated for
//! minutes of play, then for longer, then not until the next start, so a machine or a scene it
//! doesn't suit loses a few frames' time a few times, not every half minute.
//!
//! A verdict is the medians of a window of frames (`WINDOW`), which a few slow frames (a chunk
//! load, say) don't move. Nothing here reads the GPU or draws anything: the caller feeds it the
//! frames and applies what it answers.
/// Frames in one verdict.
pub const WINDOW: usize = 240;
/// The CPU's time must be this many times the GPU's for a window to count as CPU-bound.
const CPU_BOUND: f32 = 1.3;
/// Below this CPU time, in milliseconds, a frame is fast enough that neither matters.
const WORTH_TRYING_MS: f32 = 1.5;
/// A trial is kept when the frame's busier side dropped under this share of what it was.
const KEEP_BELOW: f32 = 0.97;
/// Windows of CPU-bound frames in a row before a trial.
const STREAK: u8 = 2;
/// Windows left out after a switch, while its effects settle.
const SETTLE: u8 = 1;
/// How long, in milliseconds of frames watched, after the first and the second trial that didn't
/// help before another; after a third there is none.
const RETRY_AFTER_MS: [f64; 2] = [5.0 * 60_000.0, 20.0 * 60_000.0];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
/// Off, looking for a CPU-bound frame.
Watching,
/// On for a trial: left out `SETTLE` windows, then measured against the frame before.
Trial,
/// The trial made the frame faster: on from here.
Kept,
}
/// What Auto has decided and why, a step at a time.
#[derive(Clone, Debug)]
pub struct GpuCullingAuto {
cpu: Vec<f32>,
gpu: Vec<f32>,
on: bool,
state: State,
/// CPU-bound windows in a row.
streak: u8,
/// The frame's busier side before the trial, in milliseconds.
before: f32,
/// Windows still left out after a switch.
settling: u8,
/// The frames watched so far, in milliseconds of their own time.
clock_ms: f64,
/// When the next trial may start, on that clock.
retry_at_ms: f64,
/// Trials that didn't help.
rejected: usize,
}
impl Default for GpuCullingAuto {
fn default() -> Self {
Self::new()
}
}
impl GpuCullingAuto {
pub fn new() -> Self {
Self {
cpu: Vec::with_capacity(WINDOW),
gpu: Vec::with_capacity(WINDOW),
on: false,
state: State::Watching,
streak: 0,
before: 0.0,
settling: 0,
clock_ms: 0.0,
retry_at_ms: 0.0,
rejected: 0,
}
}
/// Whether Auto has GPU Culling on now.
pub fn on(&self) -> bool {
self.on
}
/// Where Auto is, for the status: `watching`, `trial` or `kept`.
pub fn state(&self) -> &'static str {
match self.state {
State::Watching => "watching",
State::Trial => "trial",
State::Kept => "kept",
}
}
/// Back to the start: off, with nothing measured (the mode changed, or the world did).
pub fn reset(&mut self) {
*self = Self::new();
}
/// One frame's CPU time, a GPU time where its timestamps have arrived, and its whole time,
/// in milliseconds. Answers the new state when this frame completed a window that changed it.
pub fn observe(&mut self, cpu_ms: f32, gpu_ms: Option<f32>, frame_ms: f32) -> Option<bool> {
self.clock_ms += f64::from(frame_ms);
self.cpu.push(cpu_ms);
if let Some(gpu) = gpu_ms {
self.gpu.push(gpu);
}
if self.cpu.len() < WINDOW {
return None;
}
let cpu = median(&mut self.cpu);
// A GPU that can't be timed leaves nothing to compare with: Auto stays as it is.
let gpu = (self.gpu.len() >= WINDOW / 4).then(|| median(&mut self.gpu));
self.cpu.clear();
self.gpu.clear();
self.verdict(cpu, gpu?)
}
fn verdict(&mut self, cpu: f32, gpu: f32) -> Option<bool> {
if self.settling > 0 {
self.settling -= 1;
return None;
}
match self.state {
State::Kept => None,
State::Watching => {
if self.clock_ms < self.retry_at_ms {
return None;
}
let bound = cpu >= WORTH_TRYING_MS && cpu > gpu * CPU_BOUND;
self.streak = if bound { self.streak + 1 } else { 0 };
if self.streak < STREAK {
return None;
}
self.streak = 0;
self.before = cpu.max(gpu);
self.state = State::Trial;
self.settling = SETTLE;
self.on = true;
Some(true)
}
State::Trial => {
if cpu.max(gpu) < self.before * KEEP_BELOW {
self.state = State::Kept;
return None;
}
self.state = State::Watching;
self.retry_at_ms = RETRY_AFTER_MS
.get(self.rejected)
.map_or(f64::INFINITY, |wait| self.clock_ms + wait);
self.rejected += 1;
self.on = false;
Some(false)
}
}
}
}
fn median(values: &mut [f32]) -> f32 {
values.sort_by(f32::total_cmp);
values[values.len() / 2]
}
#[cfg(test)]
mod tests {
use super::*;
/// A window of frames at constant times, each as long as its busier side; the last answer.
fn window(auto: &mut GpuCullingAuto, cpu: f32, gpu: f32) -> Option<bool> {
(0..WINDOW)
.filter_map(|_| auto.observe(cpu, Some(gpu), cpu.max(gpu)))
.last()
}
/// A machine whose CPU limits the frame is tried, and keeps GPU Culling when the frame
/// gets faster.
#[test]
fn a_cpu_bound_frame_tries_it_and_keeps_it_when_it_helps() {
let mut auto = GpuCullingAuto::new();
assert!(!auto.on());
// One CPU-bound window is not yet a verdict.
assert_eq!(window(&mut auto, 5.0, 2.0), None);
assert_eq!(window(&mut auto, 5.0, 2.0), Some(true));
assert!(auto.on());
assert_eq!(auto.state(), "trial");
// The window after the switch is left out, whatever it shows.
assert_eq!(window(&mut auto, 9.0, 9.0), None);
// The frame's busier side went from 5.0 to 3.0 ms.
assert_eq!(window(&mut auto, 3.0, 2.6), None);
assert_eq!(auto.state(), "kept");
assert!(auto.on());
// Kept stays kept, even if a later scene is GPU-bound.
assert_eq!(window(&mut auto, 1.0, 8.0), None);
assert!(auto.on());
}
/// Where it didn't help, it is undone, and not tried again for 5 minutes, then 20, then
/// not at all: a scene it doesn't suit is not tried every half minute.
#[test]
fn a_trial_that_does_not_help_is_undone_and_waits_longer_each_time() {
let mut auto = GpuCullingAuto::new();
// One window is 240 frames of 5 ms: 1.2 s. A trial, and its rejection:
let reject = |auto: &mut GpuCullingAuto| {
window(auto, 5.0, 2.0);
assert_eq!(window(auto, 5.0, 2.0), Some(true));
window(auto, 5.0, 2.0);
// The GPU took over the frame: 5.0 ms before, 5.4 after.
assert_eq!(window(auto, 2.5, 5.4), Some(false));
assert!(!auto.on());
assert_eq!(auto.state(), "watching");
};
reject(&mut auto);
// CPU-bound as ever, and left alone for 5 minutes of frames: 250 windows.
let mut waited = 0;
while window(&mut auto, 5.0, 2.0).is_none() {
waited += 1;
}
assert!((248..=252).contains(&waited), "{waited}");
// That window started the second trial; it is rejected too.
window(&mut auto, 5.0, 2.0);
assert_eq!(window(&mut auto, 2.5, 5.4), Some(false));
// Now 20 minutes: 1000 windows.
let mut waited = 0;
while window(&mut auto, 5.0, 2.0).is_none() {
waited += 1;
}
assert!((998..=1002).contains(&waited), "{waited}");
window(&mut auto, 5.0, 2.0);
assert_eq!(window(&mut auto, 2.5, 5.4), Some(false));
// A third rejection is for good.
for _ in 0..5000 {
assert_eq!(window(&mut auto, 5.0, 2.0), None);
}
assert!(!auto.on());
}
/// A GPU-bound machine is never switched: its frame is the GPU's.
#[test]
fn a_gpu_bound_frame_is_left_alone() {
let mut auto = GpuCullingAuto::new();
for _ in 0..20 {
assert_eq!(window(&mut auto, 0.5, 3.6), None);
}
assert!(!auto.on());
}
/// Within the margin neither side limits the frame, and a single CPU-bound window among
/// others breaks no streak into a trial.
#[test]
fn neither_a_balanced_nor_an_occasional_cpu_bound_frame_is_tried() {
let mut auto = GpuCullingAuto::new();
for _ in 0..10 {
assert_eq!(window(&mut auto, 3.0, 2.6), None);
}
for _ in 0..10 {
assert_eq!(window(&mut auto, 5.0, 2.0), None);
assert_eq!(window(&mut auto, 2.0, 2.0), None);
}
assert!(!auto.on());
}
/// Fast frames aren't worth a trial, bound or not.
#[test]
fn a_frame_under_the_floor_is_not_tried() {
let mut auto = GpuCullingAuto::new();
for _ in 0..10 {
assert_eq!(window(&mut auto, 1.2, 0.2), None);
}
assert!(!auto.on());
}
/// Without GPU times (a GPU that can't be timed) there is nothing to compare.
#[test]
fn frames_without_gpu_times_decide_nothing() {
let mut auto = GpuCullingAuto::new();
for _ in 0..WINDOW * 10 {
assert_eq!(auto.observe(8.0, None, 8.0), None);
}
assert!(!auto.on());
}
/// A spike in a window doesn't move its verdict: the median ignores it.
#[test]
fn a_few_slow_frames_do_not_make_a_window_cpu_bound() {
let mut auto = GpuCullingAuto::new();
for _ in 0..4 {
let mut answer = None;
for i in 0..WINDOW {
// One frame in ten is a 30 ms chunk load, the rest are GPU-bound.
let cpu = if i % 10 == 0 { 30.0 } else { 0.8 };
answer = answer.or(auto.observe(cpu, Some(3.0), 3.0));
}
assert_eq!(answer, None);
}
assert!(!auto.on());
}
#[test]
fn reset_starts_over() {
let mut auto = GpuCullingAuto::new();
window(&mut auto, 5.0, 2.0);
window(&mut auto, 5.0, 2.0);
assert!(auto.on());
auto.reset();
assert!(!auto.on());
assert_eq!(auto.state(), "watching");
assert_eq!(window(&mut auto, 5.0, 2.0), None);
}
}
+25 -1
View File
@@ -1,6 +1,7 @@
//! Biome colours from the pinned biome definitions and colormaps
//! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`).
use crate::Result;
use horizon_client_core::particle_type::ParticleType;
use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom};
use serde_json::Value;
use std::{
@@ -106,11 +107,28 @@ pub struct BiomeInfo {
/// The biome's own fog colour attribute; otherwise the dimension's applies.
pub fog: Option<u32>,
pub water_fog: u32,
/// `minecraft:visual/ambient_particles` entries and their probabilities.
pub ambient_particles: Vec<(ParticleType, f32)>,
/// `BiomeGenerationSettings.features`: the placed feature ids of each
/// `GenerationStep.Decoration` step, in order.
pub features: Vec<Vec<String>>,
}
impl BiomeInfo {
fn ambient_particles(v: &Value) -> Vec<(ParticleType, f32)> {
let list = &v["attributes"]["minecraft:visual/ambient_particles"];
let entries = list["argument"].as_array().or_else(|| list.as_array());
entries
.into_iter()
.flatten()
.filter_map(|entry| {
Some((
ParticleType::from_name(entry["particle"]["type"].as_str()?)?,
entry["probability"].as_f64().unwrap_or(0.0) as f32,
))
})
.collect()
}
/// `Biome.getHeightAdjustedTemperature`: the frozen modifier, then cooler
/// with height above `sea_level + 17`.
pub fn temperature_at(&self, pos: BlockPos, sea_level: i32) -> f32 {
@@ -245,6 +263,7 @@ impl BiomeInfo {
sky: color(&attributes["minecraft:visual/sky_color"]),
fog: color(&attributes["minecraft:visual/fog_color"]),
water_fog: color(&attributes["minecraft:visual/water_fog_color"]).unwrap_or(0x050533),
ambient_particles: Self::ambient_particles(v),
features: v["features"]
.as_array()
.into_iter()
@@ -563,7 +582,9 @@ mod pack_tests {
#[test]
fn packs_replace_in_place_and_add_after_the_builtin_biomes() {
let base = builtin(&["minecraft:meadow", "minecraft:plains", "minecraft:river"]);
let red = json!({"temperature": 2.0, "effects": {"water_color": "#ff0000"}});
let red = json!({"temperature": 2.0, "effects": {"water_color": "#ff0000"},
"attributes": {"minecraft:visual/ambient_particles": {
"argument": [{"particle": {"type": "minecraft:ash"}, "probability": 0.25}]}}});
let hot = json!({"effects": {"grass_color": 0x123456}});
let files = [
("pack:zeta", &hot),
@@ -576,6 +597,9 @@ mod pack_tests {
assert_eq!(world.id("minecraft:river"), 2);
assert_eq!(world.get(2).water, 0xFF0000);
assert_eq!(world.get(2).temperature, 2.0);
assert_eq!(world.get(2).ambient_particles.len(), 1);
assert_eq!(world.get(2).ambient_particles[0].0.name(), "ash");
assert_eq!(world.get(2).ambient_particles[0].1, 0.25);
// New biomes follow, in registry order.
assert_eq!(world.id("minecraft:molten_peaks"), 3);
assert_eq!(world.id("pack:zeta"), 4);
@@ -77,6 +77,9 @@ pub struct BlockEntities {
/// The fluid tanks of mod blocks' block entities, by block state id;
/// built with `states`, like the containers.
mod_fluids: FxHashMap<u32, Arc<ModFluidTanks>>,
/// State-aware native factory ownership. Shared across level snapshots;
/// an empty slice means the declarations have not yet been compiled.
stateful_entities: Arc<[bool]>,
/// The energy buffers of mod blocks' block entities, by block state id;
/// built with `states`, like the containers.
mod_energy: FxHashMap<u32, Arc<ModEnergyBuffer>>,
@@ -209,6 +212,21 @@ impl BlockEntities {
pub fn mod_fluids(&self, state: u32) -> Option<&Arc<ModFluidTanks>> {
self.mod_fluids.get(&state)
}
pub fn set_stateful_entities(&mut self, states: Vec<bool>) {
self.stateful_entities = states.into();
}
pub fn has_stateful_entity_table(&self) -> bool {
!self.stateful_entities.is_empty()
}
pub fn stateful_entities(&self) -> Arc<[bool]> {
self.stateful_entities.clone()
}
pub fn stateful_entity(&self, state: u32) -> bool {
self.stateful_entities
.get(state as usize)
.copied()
.unwrap_or(false)
}
pub fn set_mod_energy(&mut self, energy: FxHashMap<u32, Arc<ModEnergyBuffer>>) {
self.mod_energy = energy;
}
@@ -3,20 +3,22 @@
//! decorated pots, conduits, enchanting-table and lectern books and copper
//! golem statues, End portals and End gateways. Models are vanilla's baked `LayerDefinitions` layers
//! (`entity-models.json`); transforms, animation and textures follow each
//! vanilla renderer. Faces are lit like the `entity` shader: the lightmap at
//! the block plus `minecraft_mix_light` with the level's two diffuse lights.
//! vanilla renderer. Faces carry their tint and world normal: the entity
//! shader (and a shader pack) applies `minecraft_mix_light` from the normal, as
//! vanilla's does.
use crate::{
Result,
bidi::visual,
block_entity_anim::{self, EnchantingBook},
breaking::entity_geometry,
fast_hash::FxHashMap,
font::Glyph,
font::{Font, Glyph},
gfx::mark_oit,
hud::Rect,
mesher::{CULL_BACK, Vertex},
models::load_visibility,
signs::{self, SignData, SignText},
text::{Style, Text},
world::World,
};
use glam::{DVec3, Mat4, Quat, Vec3};
@@ -128,6 +130,14 @@ fn pack_color(rgb: u32, alpha: u32, brightness: f32) -> u32 {
let c = |shift: u32| (((rgb >> shift) & 255) as f32 * brightness) as u32;
alpha << 24 | c(0) << 16 | c(8) << 8 | c(16)
}
/// A world normal as `Vertex::normal` holds it: RGBA8_SNORM, `w` positive so
/// the entity shader and a shader pack both shade by it. Block-entity models
/// carry no normals of their own (vanilla computes each face's from its
/// polygon, then `minecraft_mix_light` uses it in the shader).
fn pack_normal(normal: Vec3) -> [i8; 4] {
let c = |v: f32| (v.clamp(-1.0, 1.0) * 127.0).round() as i8;
[c(normal.x), c(normal.y), c(normal.z), 127]
}
/// Everything a draw call needs besides the geometry.
#[derive(Clone, Copy)]
@@ -165,6 +175,7 @@ pub fn draw_part(
light,
lights,
glow,
..
} = paint;
for poly in &part.polygons {
let pos = poly.map(|v| m.transform_point3(Vec3::new(v[0], v[1], v[2]) / 16.0));
@@ -177,11 +188,21 @@ pub fn draw_part(
} else {
normal
};
let color = pack_color(tint, 255, diffuse(normal, lights));
// The colour is the tint alone when the caller shades by the level's
// lights: the entity shader applies `minecraft_mix_light` from the
// normal, as vanilla does, so a shader pack receives the unshaded
// colour Iris gives it (a baked shade would be applied a second time
// by the pack's lighting). Other lights (an item preview's
// `Lighting.Entry`) are not the shader's to know, so those stay baked
// into the colour, as before.
let baked = !(lights == diffuse_lights(false) || lights == diffuse_lights(true));
let brightness = if baked { diffuse(normal, lights) } else { 1.0 };
let color = pack_color(tint, 255, brightness);
let normal = if baked { [0; 4] } else { pack_normal(normal) };
for (r, light) in std::iter::once((r, light)).chain(glow.map(|g| (g, FULL_BRIGHT))) {
for (v, position) in poly.iter().zip(pos) {
out.push(Vertex {
normal: [0; 4],
normal,
pos: position.to_array(),
uv: [r.u0 + (r.u1 - r.u0) * v[3], r.v0 + (r.v1 - r.v0) * v[4]],
layer: 0,
@@ -600,30 +621,26 @@ fn frac(x: f32) -> f32 {
x - x.floor()
}
/// `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 {
/// `StringSplitter.findLineBreak`: first line, with styled advances.
fn first_line(line: &Text, max_width: f32, advance: &dyn Fn(char, &Style) -> f32) -> Text {
let mut width = 0.0;
let mut visible = false;
let mut last_space = None;
for (i, c) in line.char_indices() {
for (i, (c, style)) in line.chars().enumerate() {
if c == '\n' {
return line[..i].to_owned();
return line.slice(0, i);
}
if c == ' ' {
last_space = Some(i);
}
width += advance(c);
if width > max_width {
let end = match last_space {
Some(s) if s > 0 => s,
_ if i > 0 => i,
// The first char alone is too wide: take that one char.
_ => c.len_utf8(),
};
return line[..end].to_owned();
let step = advance(c, style);
width += step;
if visible && width > max_width.max(1.0) {
return line.slice(0, last_space.unwrap_or(i));
}
visible |= step != 0.0;
}
line.to_owned()
line.clone()
}
/// `AbstractSignRenderer.isOutlineVisible`: the camera within 16 blocks of
@@ -641,7 +658,7 @@ fn sign_text_near(pos: [i32; 3], camera: DVec3) -> bool {
/// `AbstractSignRenderer.submitSignText`: four centred lines, glowing text
/// full-bright with an 8x outline in the dark colour. The font colours each
/// glyph by its style (`Font.StringRenderOutput`): a line's own colour wins,
/// else the sign's. A line is one call per run of one colour.
/// else the sign's. Keep style boundaries for glyphs and decoration effects.
fn sign_text_calls(
scene: &Scene,
data: &SignData,
@@ -653,27 +670,43 @@ fn sign_text_calls(
let line_height = data.line_height();
let midpoint = (4.0 * line_height / 2.0).floor();
let dark = 0xFF00_0000 | text.dark_color();
let (color, outline, light) = if text.glowing {
let (color, outline, light, tier) = if text.glowing {
let c = text.text_color();
(
0xFF00_0000 | c,
if c == 0 || near { dark } else { 0 },
240 | 240 << 8,
crate::mesher::LOW,
)
} else {
(dark, 0, vertex_light(packed))
(dark, 0, vertex_light(packed), 0)
};
let advance = |c: char, style: &Style| {
let g = scene
.font
.map_or_else(|| (scene.glyph)(c), |f| f.glyph_styled(c, style));
g.advance + if style.is_bold() { g.offset } else { 0.0 }
};
let advance = |c: char| (scene.glyph)(c).advance;
let mut calls: Vec<TextCall> = Vec::with_capacity(text.lines.len());
for i in 0..text.lines.len() {
// The line that fits, in the order it is drawn (getVisualOrder).
let line = text.line_text(i);
let line = line.resolved();
let flat: String = line.chars().map(|(c, _)| c).collect();
let fits = first_line(&flat, data.max_line_width(), &advance);
let shown = line.slice(0, fits.chars().count());
let shown = if let Some(font) = scene.font {
font.split_formatted(&line, data.max_line_width())
.into_iter()
.next()
.unwrap_or_default()
.resolved()
.into_owned()
} else {
first_line(&line.resolved(), data.max_line_width(), &advance)
};
let shown = visual(&shown);
let width = shown.chars().map(|(c, _)| advance(c)).sum::<f32>().ceil();
let width = shown
.chars()
.map(|(c, s)| advance(c, s))
.sum::<f32>()
.ceil();
let x = -((width as i32) / 2) as f32;
let y = i as f32 * line_height - midpoint;
let first = calls.len();
@@ -683,19 +716,22 @@ fn sign_text_calls(
.style
.color
.map_or(color, |rgb| 0xFF00_0000 | (rgb & 0xFF_FFFF));
match calls[first..].last_mut() {
Some(last) if last.color == run => last.text.push_str(&span.text),
_ => calls.push(TextCall {
matrix: m,
x: x + pen,
y,
text: span.text.clone(),
color: run,
outline,
light,
}),
}
pen += span.text.chars().map(advance).sum::<f32>();
calls.push(TextCall {
matrix: m,
x: x + pen,
y,
text: span.text.clone(),
style: span.style.clone(),
color: run,
outline,
light,
tier,
});
pen += span
.text
.chars()
.map(|c| advance(c, &span.style))
.sum::<f32>();
}
if calls.len() == first {
// A line with no text is still a call, of no glyphs.
@@ -704,15 +740,28 @@ fn sign_text_calls(
x,
y,
text: String::new(),
style: Style::default(),
color,
outline,
light,
tier,
});
}
}
calls
}
fn sign_text_animated(data: &SignData) -> bool {
[&data.front, &data.back].into_iter().any(|side| {
(0..side.lines.len()).any(|i| {
side.line_text(i)
.resolved()
.chars()
.any(|(c, s)| c != ' ' && s.obfuscated == Some(true))
})
})
}
/// How far the text of an outlined call sits in front of its outline, in
/// text units (`Font.DisplayMode.POLYGON_OFFSET`, see `draw_text`).
const TEXT_OVER_OUTLINE: f32 = 0.05;
@@ -726,72 +775,131 @@ const TEXT_OVER_OUTLINE: f32 = 0.05;
/// reader instead (a twentieth of a font pixel, invisible) rather than
/// z-fighting with the outline under it.
fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec<Vertex>) {
text_vertices(scene.glyph, call, out);
let glyph = |c| {
let Some(font) = scene.font else {
return (scene.glyph)(c);
};
let g = font.glyph_styled(c, &call.style);
if call.style.obfuscated == Some(true) && c != ' ' {
font.random_glyph(&call.style, g.advance)
} else {
g
}
};
text_vertices(&glyph, scene.font.map(Font::white), call, out);
}
/// `draw_text` with the font's glyph cells and advances from `glyph`: the
/// `BakedSheetGlyph.renderChar` / `Font.PreparedTextBuilder.accept`: the
/// text of `call` as glyph quads in its matrix's plane, 1 unit a font pixel,
/// y down as the font's, with its outline when it has one. A native mod's
/// block entity draws its text this way (`native_draw_text`).
pub fn text_vertices(glyph: &dyn Fn(char) -> Glyph, call: &TextCall, out: &mut Vec<Vertex>) {
let mut emit = |dx: f32, dy: f32, z: f32, argb: u32| {
let mut x = call.x + dx;
let y0 = call.y + dy;
for ch in call.text.chars() {
pub fn text_vertices(
glyph: &dyn Fn(char) -> Glyph,
white: Option<Rect>,
call: &TextCall,
out: &mut Vec<Vertex>,
) {
let bold = call.style.is_bold();
let mut quad = |corners: [(f32, f32); 4], cell: Rect, z: f32, argb: u32| {
let uvs = [
[cell.u0, cell.v1],
[cell.u1, cell.v1],
[cell.u1, cell.v0],
[cell.u0, cell.v0],
];
let color = 0xFF00_0000 | (argb & 255) << 16 | (argb >> 8 & 255) << 8 | (argb >> 16 & 255);
for ((x, y), uv) in corners.into_iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: call.matrix.transform_point3(Vec3::new(x, y, z)).to_array(),
uv,
layer: u32::from(call.tier) << 16,
color,
light: call.light,
glint_uv: [0.0; 2],
});
}
};
let mut emit = |dx: f32, dy: f32, z: f32, argb: u32, outline: bool| {
let mut pen = call.x;
for (i, ch) in call.text.chars().enumerate() {
let g = glyph(ch);
let x = pen + dx * g.offset;
let y = call.y + dy * g.offset;
let advance = g.advance + if bold { g.offset } else { 0.0 };
if let Some(cell) = g.rect {
// BakedSheetGlyph: the glyph's own box from the pen, not a
// fixed 8x8 cell (a Unifont glyph is 0.5 units per texel).
let (x0, x1) = (x + g.left, x + g.right);
let (top, bottom) = (y0 + g.top, y0 + g.bottom);
let corners = [(x0, bottom), (x1, bottom), (x1, top), (x0, top)];
let uvs = [
[cell.u0, cell.v1],
[cell.u1, cell.v1],
[cell.u1, cell.v0],
[cell.u0, cell.v0],
];
let c =
0xFF00_0000 | (argb & 255) << 16 | (argb >> 8 & 255) << 8 | (argb >> 16 & 255);
for ((cx, cy), uv) in corners.into_iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: call
.matrix
.transform_point3(Vec3::new(cx, cy, z))
.to_array(),
uv,
layer: 0,
color: c,
light: call.light,
glint_uv: [0.0, 0.0],
});
let thick = if bold { 0.1 } else { 0.0 };
let shear = |v| {
if call.style.is_italic() {
1.0 - 0.25 * v
} else {
0.0
}
};
for copy in 0..=usize::from(bold) {
let x0 = x + copy as f32 * g.offset + g.left - thick;
let x1 = x + copy as f32 * g.offset + g.right + thick;
let top = y + g.top - thick;
let bottom = y + g.bottom + thick;
quad(
[
(x0 + shear(g.bottom), bottom),
(x1 + shear(g.bottom), bottom),
(x1 + shear(g.top), top),
(x0 + shear(g.top), top),
],
cell,
z + copy as f32 * 0.001,
argb,
);
}
}
x += g.advance;
// `Font.prepare8xTextOutline` discards effects: only the front
// text gets underline/strikethrough, including over spaces.
if !outline && let Some(white) = white {
let x0 = if i == 0 { x - 1.0 } else { x };
for (enabled, top) in [
(call.style.strikethrough, 3.5),
(call.style.underlined, 8.0),
] {
if enabled == Some(true) {
quad(
[
(x0, y + top + 1.0),
(x + advance, y + top + 1.0),
(x + advance, y + top),
(x0, y + top),
],
white,
z + 0.01,
argb,
);
}
}
}
pen += advance;
}
};
if call.outline != 0 {
for (dx, dy) in [
(-1.0, -1.0),
(0.0, -1.0),
(1.0, -1.0),
(-1.0, 0.0),
(1.0, 0.0),
(-1.0, 1.0),
(0.0, 1.0),
(1.0, 1.0),
] {
emit(dx, dy, 0.0, call.outline);
for dx in -1..=1 {
for dy in -1..=1 {
if dx != 0 || dy != 0 {
emit(dx as f32, dy as f32, 0.0, call.outline, true);
}
}
}
}
let z = if call.outline != 0 {
TEXT_OVER_OUTLINE
} else {
0.0
};
emit(0.0, 0.0, z, call.color);
emit(
0.0,
0.0,
if call.outline != 0 {
TEXT_OVER_OUTLINE
} else {
0.0
},
call.color,
false,
);
}
/// Block-entity fields the level ticks, at one position (vanilla's own field
@@ -824,12 +932,16 @@ pub struct TextCall {
pub x: f32,
pub y: f32,
pub text: String,
pub style: Style,
/// ARGB.
pub color: u32,
/// ARGB outline colour, 0 for none.
pub outline: u32,
/// Horizon packed light (sky*16 | block*16 << 8).
pub light: u32,
/// HDR emission tier of its glyphs (`mesher::hdr_tier`), 0 for none: glowing sign text
/// shines in HDR output and in shader packs (`horizonTier`), as full-bright text does in SDR.
pub tier: u8,
}
/// Inputs from the game for one frame of block-entity rendering.
@@ -868,6 +980,8 @@ pub struct Scene<'a> {
pub skull: &'a dyn Fn([i32; 3]) -> Option<String>,
/// Font glyph: atlas cell (none for blank glyphs such as the space), box and advance.
pub glyph: &'a dyn Fn(char) -> Glyph,
/// Font providers, effects and random glyphs for styled sign text.
pub font: Option<&'a Font>,
/// Changes whenever `glyph` may answer differently (`Font::epoch`): sign
/// text laid out under another value is laid out again.
pub glyphs: u64,
@@ -1029,6 +1143,7 @@ struct SignTextEntry {
/// Game time it was last drawn.
used: i64,
vertices: Vec<Vertex>,
animated: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct StaticKey {
@@ -2335,9 +2450,11 @@ impl BlockEntityRenderer {
let entry = match signs.entry(pos) {
std::collections::hash_map::Entry::Occupied(mut occupied) => {
let entry = occupied.get_mut();
let changed = entry.data != *data;
if (entry.state, entry.packed, entry.near, entry.glyphs)
!= (state, packed, near, glyphs)
|| entry.data != *data
|| changed
|| entry.animated
{
entry.vertices.clear();
self.render_one(
@@ -2352,7 +2469,10 @@ impl BlockEntityRenderer {
&mut entry.vertices,
);
entry.state = state;
entry.data.clone_from(data);
if changed {
entry.animated = sign_text_animated(data);
entry.data.clone_from(data);
}
entry.packed = packed;
entry.near = near;
entry.glyphs = glyphs;
@@ -2373,6 +2493,7 @@ impl BlockEntityRenderer {
&mut vertices,
);
vacant.insert(SignTextEntry {
animated: sign_text_animated(data),
state,
data: data.clone(),
packed,
@@ -3612,6 +3733,7 @@ mod tests {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
// Compare the cached world path with the original model renderer,
@@ -3774,6 +3896,105 @@ mod tests {
// Straight down: ambient only.
assert!((diffuse(-Vec3::Y, lights) - 0.4).abs() < 1e-6);
}
/// A face's colour carries its tint alone and its normal carries the
/// shading: the entity shader applies `minecraft_mix_light` from it, as a
/// shader pack's lighting does, so a baked shade would be applied twice.
#[test]
fn a_face_keeps_its_tint_and_normal_for_the_shader_to_shade() {
let quad = |y: f32, z0: f32, z1: f32| {
[
[0.0, y, z0, 0.0, 0.0],
[0.0, y, z1, 0.0, 1.0],
[16.0, y, z1, 1.0, 1.0],
[16.0, y, z0, 1.0, 0.0],
]
};
// Opposite windings: the first faces up, the second down.
let part = ModelPart {
pose: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
polygons: vec![quad(0.0, 0.0, 16.0), quad(16.0, 16.0, 0.0)],
children: vec![],
};
let mut out = Vec::new();
draw_part(
&part,
"root",
Mat4::IDENTITY,
&|_, _| {},
Paint {
sprite: Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 16,
h: 16,
},
tint: 0x123456,
light: 0,
lights: diffuse_lights(false),
glow: None,
},
&mut out,
);
assert_eq!(out.len(), 8);
// The same tint on both faces: no directional shade baked in (`pack_color`
// stores the tint in the vertex colour's BGR byte order).
let tint = pack_color(0x12_3456, 255, 1.0);
assert!(out.iter().all(|v| v.color == tint));
let (up, down) = (&out[0], &out[4]);
assert_eq!(up.normal, [0, 127, 0, 127]);
assert_eq!(down.normal, [0, -127, 0, 127]);
// The shader still gets the difference the old baked colours held.
let lights = diffuse_lights(false);
let up_normal = Vec3::new(0.0, f32::from(up.normal[1]) / 127.0, 0.0);
let down_normal = Vec3::new(0.0, f32::from(down.normal[1]) / 127.0, 0.0);
assert!(diffuse(up_normal, lights) > diffuse(down_normal, lights));
}
/// Lights the entity shader does not know (an item preview's
/// `Lighting.Entry`) stay baked into the colour, and `normal.w` 0 tells
/// the shader to keep it: `game/item_draw` passes those for block-entity
/// items in inventories and hands.
#[test]
fn lights_other_than_the_levels_stay_baked() {
let part = ModelPart {
pose: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
polygons: vec![[
[0.0, 0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 16.0, 0.0, 1.0],
[16.0, 0.0, 16.0, 1.0, 1.0],
[16.0, 0.0, 0.0, 1.0, 0.0],
]],
children: vec![],
};
let lights = (Vec3::X, Vec3::Z);
let mut out = Vec::new();
draw_part(
&part,
"root",
Mat4::IDENTITY,
&|_, _| {},
Paint {
sprite: Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 16,
h: 16,
},
tint: 0x12_3456,
light: 0,
lights,
glow: None,
},
&mut out,
);
let baked = pack_color(0x12_3456, 255, diffuse(Vec3::Y, lights));
assert!(out.iter().all(|v| v.color == baked));
assert!(out.iter().all(|v| v.normal == [0; 4]));
assert_ne!(baked, pack_color(0x12_3456, 255, 1.0));
}
#[test]
fn part_poses_compose_like_model_part() {
let part = ModelPart {
@@ -3907,6 +4128,7 @@ mod tests {
skull: &|_| None,
glyph: &glyph,
glyphs: 0,
font: None,
dynamic_visible: None,
};
let mut call = TextCall {
@@ -3914,9 +4136,11 @@ mod tests {
x: 0.0,
y: 0.0,
text: "Hi".into(),
style: Style::default(),
color: 0xFFFF_FF00,
outline: 0xFF33_3300,
light: 240 | 240 << 8,
tier: 0,
};
let mut out = Vec::new();
draw_text(&scene, &call, &mut out);
@@ -3980,6 +4204,7 @@ mod tests {
skull: &|_| None,
glyph: &glyph,
glyphs: 0,
font: None,
dynamic_visible: None,
};
let call = TextCall {
@@ -3987,9 +4212,11 @@ mod tests {
x: 10.0,
y: 2.0,
text: "ab".into(),
style: Style::default(),
color: 0xFF00_0000,
outline: 0,
light: 240 | 240 << 8,
tier: 0,
};
let mut out = Vec::new();
draw_text(&scene, &call, &mut out);
@@ -4009,6 +4236,83 @@ mod tests {
assert_eq!(boxes, [[10.0, 14.0, 2.0, 10.0], [15.0, 19.0, 2.0, 10.0]]);
}
#[test]
fn styled_sign_quads_follow_vanilla_glyph_and_effect_bounds() {
let white = Rect {
u0: 0.0,
v0: 0.0,
u1: 0.1,
v1: 0.1,
w: 1,
h: 1,
};
let glyph = |c| Glyph {
rect: (c != ' ').then_some(white),
left: 0.0,
right: 4.0,
top: 0.0,
bottom: 8.0,
advance: 5.0,
offset: 0.5,
};
let mut call = TextCall {
matrix: Mat4::IDENTITY,
x: 0.0,
y: 0.0,
text: "A ".into(),
color: 0xff123456,
outline: 0,
light: 240,
tier: crate::mesher::LOW,
style: Style {
bold: Some(true),
italic: Some(true),
underlined: Some(true),
strikethrough: Some(true),
..Default::default()
},
};
let mut out = Vec::new();
text_vertices(&glyph, Some(white), &call, &mut out);
// BakedSheetGlyph: bold expands by 0.1, italic shears by 1 - y/4,
// the second bold glyph is 0.5 along and 0.001 in front (Unihex).
assert_eq!(out.len(), 24);
for (got, expected) in out[0].pos.iter().zip([-1.1, 8.1, 0.0]) {
assert!((got - expected).abs() < 1e-6);
}
assert!((out[4].pos[0] - out[0].pos[0] - 0.5).abs() < 1e-6);
assert_eq!(out[4].pos[2], 0.001);
assert_eq!(out[8].pos, [-1.0, 4.5, 0.01]);
assert_eq!(out[12].pos, [-1.0, 9.0, 0.01]);
assert_eq!(out[21].pos, [11.0, 9.0, 0.01]); // underline crosses the space
assert!(out.iter().all(|v| v.color == 0xff563412 && v.light == 240));
call.outline = 0xff010203;
out.clear();
text_vertices(&glyph, Some(white), &call, &mut out);
// Eight outlines contain glyphs only; effects appear once, in front.
assert_eq!(out.len(), 8 * 8 + 24);
assert!((out[0].pos[0] - -1.6).abs() < 1e-6);
assert!(out[64..].iter().all(|v| v.pos[2] >= TEXT_OVER_OUTLINE));
// The glow tier reaches bold copies, outlines and decoration quads.
assert!(out.iter().all(|v| v.layer >> 16 == 1));
call.tier = 0;
out.clear();
text_vertices(&glyph, Some(white), &call, &mut out);
assert!(out.iter().all(|v| v.layer >> 16 == 0));
}
#[test]
fn styled_sign_clipping_counts_bold_width_and_preserves_resets() {
let line = Text::legacy("§lAB§r東Z");
let advance = |_: char, s: &Style| 5.0 + if s.is_bold() { 0.5 } else { 0.0 };
let shown = first_line(&line, 16.0, &advance);
assert_eq!(shown.plain(), "AB東");
assert_eq!(
shown.chars().map(|(_, s)| s.is_bold()).collect::<Vec<_>>(),
[true, true, false]
);
}
/// The front text calls of a sign whose every glyph advances 6.
fn front_calls(data: &SignData, near: bool) -> Vec<(String, f32, f32, u32, u32)> {
let world = World::new(BlockStateId(0), 1);
@@ -4037,6 +4341,7 @@ mod tests {
skull: &|_| None,
glyph: &glyph,
glyphs: 0,
font: None,
dynamic_visible: None,
};
sign_text_calls(&scene, data, &data.front, Mat4::IDENTITY, 0, near)
@@ -4176,7 +4481,9 @@ mod tests {
..changed.clone()
};
let wide = std::cell::Cell::new(6.0);
let glyph_reads = std::cell::Cell::new(0);
let glyph = |c: char| {
glyph_reads.set(glyph_reads.get() + 1);
let u = f32::from(c as u8 % 16) / 16.0;
let rect = Rect {
u0: u,
@@ -4219,6 +4526,7 @@ mod tests {
skull: &|_| None,
glyph: &glyph,
glyphs: 0,
font: None,
dynamic_visible: None,
};
let check = |scene: &Scene, pos: [i32; 3], state: u32| {
@@ -4262,6 +4570,23 @@ mod tests {
wide.set(5.0);
scene.glyphs = 1;
check(&scene, pos, 1);
// With the same game time and data, plain text reuses its vertices,
// but obfuscated text must ask the font for fresh glyphs each frame.
let mut vertices = Vec::new();
let reads = glyph_reads.get();
renderer.render(&scene, [(pos, 1)].iter(), &mut vertices);
assert_eq!(glyph_reads.get(), reads);
let animated = SignData {
front: text("§kSecret", false),
..Default::default()
};
let animated_sign = |_| Some(&animated);
scene.sign = &animated_sign;
renderer.render(&scene, [(pos, 0)].iter(), &mut vertices);
let reads = glyph_reads.get();
renderer.render(&scene, [(pos, 0)].iter(), &mut vertices);
assert!(glyph_reads.get() > reads);
scene.sign = &first_sign;
// Signs out of view for a while are dropped.
scene.game_time = 2 * SIGN_TEXT_KEEP;
check(&scene, pos, 0);
@@ -4269,11 +4594,23 @@ mod tests {
}
#[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");
let advance = |c: char, _: &Style| if c == ' ' { 4.0 } else { 6.0 };
assert_eq!(
first_line(&Text::literal("ab cd ef"), 13.0, &advance).plain(),
"ab"
);
assert_eq!(
first_line(&Text::literal("abcdef"), 13.0, &advance).plain(),
"ab"
);
assert_eq!(
first_line(&Text::literal("\u{6771}"), 3.0, &advance).plain(),
"\u{6771}"
);
assert_eq!(
first_line(&Text::literal("ab\ncd"), 100.0, &advance).plain(),
"ab"
);
}
/// `rendertype_end_portal` culls back faces, and `AbstractEndPortalRenderer`
/// submits the unit cube's two Y faces. Both are wound outward, so of each
@@ -4377,6 +4714,7 @@ mod tests {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let mut verts = Vec::new();
@@ -4463,6 +4801,7 @@ mod tests {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
// A closed single chest of `block` drawn by `renderer`: positions and UVs.
@@ -358,6 +358,7 @@ fn batched_callbacks_preserve_entity_ranges_and_allow_immediate_culling() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
// Reverse local-position order to check that cache indexing does not
@@ -447,6 +448,7 @@ fn static_cache_qualifies_local_positions_by_section_and_drops_old_entries() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let options = CacheOptions {
@@ -502,6 +504,7 @@ fn gpu_static_cache_uses_section_local_chests_and_keeps_visibility_separate() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let blocks = [([100, 70, -32], 0)];
@@ -689,6 +692,7 @@ fn sign_text_cache_can_be_disabled_and_reenabled_without_changing_output() {
skull: &|_| None,
glyph: &glyph,
glyphs: 0,
font: None,
dynamic_visible: None,
};
let blocks = [([0, 64, 0], 0)];
@@ -743,6 +747,7 @@ fn shulker_cache_tracks_settled_poses_and_does_not_freeze_opening_animation() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let blocks = [([0, 64, 0], 0)];
@@ -845,6 +850,7 @@ fn shulker_cache_covers_all_colors_and_facing_directions() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let options = CacheOptions {
@@ -900,6 +906,7 @@ fn cached_bells_keep_shaking_until_the_animation_ends() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let blocks = [([0, 64, 0], 0)];
@@ -962,6 +969,7 @@ fn cached_closed_chests_match_the_direct_model_and_rebuild_when_opening() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let blocks = [([0, 64, 0], 0)];
@@ -993,7 +1001,9 @@ fn cached_closed_chests_match_the_direct_model_and_rebuild_when_opening() {
scene.nether = true;
let nether_closed = render_cached(&scene);
assert_same_vertices(&nether_closed, &render_direct(&renderer, &scene, &blocks));
assert_vertices_differ(&closed_again, &nether_closed);
// The nether is the entity shader's flag now (`entity_light`'s `l1` and
// `globals.time.y`), not a baked colour, so the cached geometry serves both.
assert_same_vertices(&closed_again, &nether_closed);
}
#[test]
@@ -1058,6 +1068,7 @@ fn closed_chest_cache_covers_all_materials_and_atlas_reloads() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let pos = [0, 64, 0];
@@ -1147,6 +1158,7 @@ fn double_chest_cache_bypasses_both_halves_while_either_lid_is_open() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let pair = [([0, 64, 0], 0), ([1, 64, 0], 1)];
@@ -1223,6 +1235,7 @@ fn decorated_pot_cache_tracks_sherds_and_bypasses_wobble_animation() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let blocks = [([0, 64, 0], 0)];
@@ -1302,6 +1315,7 @@ fn banner_cache_keeps_the_pole_static_while_the_flag_and_patterns_update() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let blocks = [([0, 64, 0], 0)];
@@ -1369,6 +1383,7 @@ fn cached_wall_banner_poles_use_the_wall_model() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let pos = [0, 64, 0];
@@ -1417,6 +1432,7 @@ fn copper_statue_cache_rebuilds_when_its_pose_state_changes() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let options = CacheOptions {
@@ -1523,6 +1539,7 @@ fn copper_statue_cache_covers_weathering_waxing_and_all_poses() {
skull: &|_| None,
glyph: &|_| Glyph::default(),
glyphs: 0,
font: None,
dynamic_visible: None,
};
let options = CacheOptions {
+9 -1
View File
@@ -576,7 +576,7 @@ pub struct Chunk {
/// Block entities read from a save, moved into the world on arrival.
pub block_entities: Vec<((i32, i32, i32), block_entity::BlockEntity)>,
/// `CustomName` of the container block entities (shown as the screen title).
pub block_names: Vec<((i32, i32, i32), String)>,
pub block_names: Vec<((i32, i32, i32), Tag)>,
/// Generation postprocessing marks (ProtoChunk.postProcessing) as world
/// positions, applied once by LevelChunk.postProcessGeneration.
pub postprocess: Vec<[i32; 3]>,
@@ -620,6 +620,14 @@ impl Chunk {
entities: Vec::new(),
}
}
/// The original `structures.starts`, including starts with unknown pieces.
pub fn saved_structure_starts(&self) -> Option<&horizon_world::nbt::Compound> {
let structures = self.saved.as_ref()?.root.get(&"structures".into())?;
match structures.get("starts")? {
horizon_world::nbt::Tag::Compound(starts) => Some(starts),
_ => None,
}
}
/// The minimum block Y of the column.
#[inline]
pub fn min_y(&self) -> i32 {
@@ -59,6 +59,9 @@ pub enum BlockEntity {
CreakingHeart(Box<CreakingHeart>),
/// `BannerBlockEntity`: the pattern layers.
Banner(Banner),
/// `CopperGolemStatueBlockEntity`: its own components, which hold the
/// custom name of the golem it was (`createStatue`).
CopperGolemStatue(Compound),
/// `CrafterBlockEntity`.
Crafter(Crafter),
/// `SpawnerBlockEntity` (`crate::mobs::spawner`).
@@ -80,6 +83,8 @@ pub enum BlockEntity {
/// `DaylightDetectorBlockEntity`: no data, only the ticker
/// (`DaylightDetectorBlock.tickEntity`).
DaylightDetector,
/// `BellBlockEntity`: saved identity only; ringing state is kept separately.
Bell,
/// Suspicious sand and gravel: saved loot and the transient brushed face.
Brushable(Box<Brushable>),
/// A shelf holds three displayed item stacks.
@@ -449,6 +454,9 @@ pub struct Jukebox {
pub items: [Option<ItemStack>; 1],
/// `ticks_since_song_started`, while a song plays.
pub ticks: i64,
/// `JukeboxBlockEntity.saveAdditional` writes the clock only when its song
/// reference exists. Keep this separate from legacy playback adoption.
pub song_clock_present: bool,
pub playing: bool,
}
impl Jukebox {
+23 -2
View File
@@ -208,7 +208,7 @@ where
Ok(resolve_world_movement(
self,
MovementRequest {
entity: EntityIdentity(0),
entity: context.entity().unwrap_or(EntityIdentity(0)),
context,
bounds,
movement,
@@ -279,7 +279,7 @@ impl SceneCollisions<'_, '_> {
Ok(resolve_world_movement(
self,
MovementRequest {
entity: EntityIdentity(0),
entity: context.entity().unwrap_or(EntityIdentity(0)),
context,
bounds,
movement,
@@ -300,6 +300,7 @@ impl SceneCollisions<'_, '_> {
CollisionContext::for_entity(
CollisionEntity {
identity: EntityIdentity(0),
kind: horizon_world::collision_context::EntityContextKind::Living,
y,
descending: false,
main_hand: Some(CollisionItem::EMPTY),
@@ -335,6 +336,26 @@ where
{
no_collision_in(world, bounds, true)
}
/// `CollisionGetter.noCollision(entity, bounds)`: retain the real entity snapshot.
pub fn no_collision_with_context<W, E>(
world: &mut W,
bounds: Aabb,
context: CollisionContext<'_>,
) -> bool
where
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
{
no_world_collision(
world,
CollisionCheckRequest {
entity: context.entity().unwrap_or(EntityIdentity(0)),
context,
bounds,
candidate_budget: 1_000_000,
},
)
.unwrap_or(false)
}
fn no_collision_in<W, E>(world: &mut W, bounds: Aabb, fluids: bool) -> bool
where
W: BlockCollisionWorld<Error = E> + EntityMovementWorld<Error = E>,
+78 -14
View File
@@ -19,26 +19,75 @@ pub struct ModMenuType {
pub slots: usize,
pub data_slots: usize,
pub results: Vec<usize>,
/// its crafting grid, if it has one (`crafting`).
pub crafting: Option<ModCrafting>,
/// its linked slots, if it has any (`links`).
pub links: Option<ModLinks>,
}
/// a mod menu type's linked slots: `count` container slots from `from` on,
/// which show the slots of the containers a native mod links them to
/// (`native_menu_links`) instead of the block entity's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModLinks {
pub from: usize,
pub count: usize,
}
impl ModLinks {
/// The linked container slots.
pub fn slots(&self) -> std::ops::Range<usize> {
self.from..self.from + self.count
}
}
/// a mod menu type's crafting grid: `size`x`size` container slots from
/// `grid` on, row by row, and the slot showing what they craft. The block
/// entity holds the grid; the result is the menu's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModCrafting {
pub grid: usize,
pub size: usize,
pub result: usize,
}
impl ModCrafting {
/// The grid's container slots.
pub fn grid_slots(&self) -> std::ops::Range<usize> {
self.grid..self.grid + self.size * self.size
}
}
static MOD_MENU_TYPES: std::sync::OnceLock<Vec<ModMenuType>> = std::sync::OnceLock::new();
/// registers the content mods' menu types, `(id, slots, data slots,
/// results)`, a list set once per process (false when it already was).
pub fn register_mod_menu_types(
menus: impl IntoIterator<Item = (String, usize, usize, Vec<usize>)>,
) -> bool {
/// One menu type as [`register_mod_menu_types`] takes it: `(id, slots, data
/// slots, results, crafting, links)`.
pub type ModMenuTypeEntry = (
String,
usize,
usize,
Vec<usize>,
Option<ModCrafting>,
Option<ModLinks>,
);
/// registers the content mods' menu types, a list set once per process
/// (false when it already was).
pub fn register_mod_menu_types(menus: impl IntoIterator<Item = ModMenuTypeEntry>) -> bool {
if MOD_MENU_TYPES.get().is_some() {
return false;
}
let menus = menus
.into_iter()
.map(|(id, slots, data_slots, results)| ModMenuType {
id: Box::leak(id.into_boxed_str()),
slots,
data_slots,
results,
});
let menus =
menus.into_iter().map(
|(id, slots, data_slots, results, crafting, links)| ModMenuType {
id: Box::leak(id.into_boxed_str()),
slots,
data_slots,
results,
crafting,
links,
},
);
MOD_MENU_TYPES.set(menus.collect()).is_ok()
}
@@ -392,9 +441,15 @@ impl BlockEntity {
if name == "minecraft:end_gateway" {
return Some(Self::EndGateway(EndGateway::default()));
}
if name == "minecraft:bell" {
return Some(Self::Bell);
}
if name == "minecraft:daylight_detector" {
return Some(Self::DaylightDetector);
}
if name.ends_with("copper_golem_statue") {
return Some(Self::CopperGolemStatue(Default::default()));
}
if name == "minecraft:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -460,6 +515,7 @@ impl BlockEntity {
Self::CommandBlock(_) => crate::command_block::Mode::of_block(name).is_some(),
Self::Skull(_) => is_skull(name),
Self::Banner(_) => name.ends_with("_banner"),
Self::CopperGolemStatue(_) => name.ends_with("copper_golem_statue"),
Self::Shelf(_) => name == "minecraft:shelf" || name.ends_with("_shelf"),
Self::Mod(_) => !name.starts_with("minecraft:"),
Self::Beehive(_) => matches!(name, "minecraft:beehive" | "minecraft:bee_nest"),
@@ -483,6 +539,7 @@ impl BlockEntity {
Self::Crafter(_) => name == "minecraft:crafter",
Self::EndGateway(_) => name == "minecraft:end_gateway",
Self::DaylightDetector => name == "minecraft:daylight_detector",
Self::Bell => name == "minecraft:bell",
Self::StructureBlock(_) => name == "minecraft:structure_block",
Self::TestBlock(_) => name == "minecraft:test_block",
Self::TestInstanceBlock(_) => name == "minecraft:test_instance_block",
@@ -510,6 +567,7 @@ impl BlockEntity {
Self::Lectern(_) => "minecraft:lectern",
Self::Sculk(s) => s.id(),
Self::Banner(_) => "minecraft:banner",
Self::CopperGolemStatue(_) => "minecraft:copper_golem_statue",
Self::Crafter(_) => "minecraft:crafter",
Self::CreakingHeart(_) => "minecraft:creaking_heart",
Self::Spawner(_) => "minecraft:mob_spawner",
@@ -520,6 +578,7 @@ impl BlockEntity {
Self::Skull(_) => "minecraft:skull",
Self::EndGateway(_) => "minecraft:end_gateway",
Self::DaylightDetector => "minecraft:daylight_detector",
Self::Bell => "minecraft:bell",
Self::Brushable(_) => "minecraft:brushable_block",
Self::Campfire(_) => "minecraft:campfire",
Self::ChiseledBookshelf(_) => "minecraft:chiseled_bookshelf",
@@ -554,11 +613,12 @@ impl BlockEntity {
| Self::TestBlock(_)
| Self::TestInstanceBlock(_)
| Self::DaylightDetector
| Self::Bell
| Self::Brushable(_) => Vec::new(),
Self::Mod(m) => m.items.iter().flatten().cloned().collect(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
Self::Banner(_) | Self::CopperGolemStatue(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
Self::Campfire(c) => c.items.iter().flatten().cloned().collect(),
Self::ChiseledBookshelf(b) => b.items.iter().flatten().cloned().collect(),
@@ -575,6 +635,7 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
| Self::CopperGolemStatue(_)
| Self::EndGateway(_)
| Self::Skull(_)
| Self::PotentSulfur(_)
@@ -583,6 +644,7 @@ impl BlockEntity {
| Self::TestBlock(_)
| Self::TestInstanceBlock(_)
| Self::DaylightDetector
| Self::Bell
| Self::Brushable(_) => &[],
Self::Jukebox(j) => &j.items,
Self::Crafter(c) => &c.items,
@@ -609,6 +671,7 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
| Self::CopperGolemStatue(_)
| Self::EndGateway(_)
| Self::Skull(_)
| Self::PotentSulfur(_)
@@ -617,6 +680,7 @@ impl BlockEntity {
| Self::TestBlock(_)
| Self::TestInstanceBlock(_)
| Self::DaylightDetector
| Self::Bell
| Self::Brushable(_) => &mut [],
Self::Jukebox(j) => &mut j.items,
Self::Crafter(c) => &mut c.items,
@@ -83,6 +83,13 @@ fn choice_description(opt: Opt, pad: &PadSettings) -> Option<&'static str> {
GlyphStyle::PlayStation => "Always shows PlayStation buttons.",
GlyphStyle::Nintendo => "Always shows Nintendo buttons.",
},
Opt::PadNintendoButtons => {
if pad.nintendo_letters {
"A, on the right, confirms and jumps and B goes back, as on a Switch."
} else {
"B, at the bottom, confirms and jumps and A goes back, as on other controllers."
}
}
Opt::PadKeyboard => match pad.keyboard {
gamepad::TextKeyboard::Auto => {
"Opens Steam's keyboard on a Steam Deck under Steam, and Horizon's otherwise."
@@ -184,6 +191,10 @@ pub fn rows() -> Vec<(Page, Vec<(&'static str, Vec<Setting>)>)> {
Opt::PadGameplayGuide,
"Show the buttons for what you can do, while you play with a controller.",
),
option(
Opt::PadCraftOnServers,
"Lets LT + A craft on servers other than your own worlds. Some servers count it as a macro.",
),
option(
Opt::PadTriggerThreshold,
"How far a trigger is pulled before it counts as pressed.",
@@ -261,6 +272,10 @@ pub fn rows() -> Vec<(Page, Vec<(&'static str, Vec<Setting>)>)> {
Opt::PadGlyphs,
"Follow the controller, or always show one family's buttons.",
),
option(
Opt::PadNintendoButtons,
"Whether a Nintendo controller's A and B work by where they sit or by their letters.",
),
info(Info::Using, "The buttons menus show right now."),
],
),
@@ -333,6 +348,7 @@ impl Item {
Item::Option(Opt::PadAdaptiveTriggers) => Some(c.adaptive_triggers),
Item::Option(Opt::PadInvertX) => Some(c.invert_x),
Item::Option(Opt::PadInvertY) => Some(c.invert_y),
Item::Option(Opt::PadCraftOnServers) => Some(c.craft_on_servers),
_ => None,
}
}
@@ -1332,6 +1348,7 @@ mod tests {
Opt::PadLookDeadzone,
Opt::PadTriggerThreshold,
Opt::PadGlyphs,
Opt::PadNintendoButtons,
Opt::PadKeyboard,
Opt::PadPointerSpeed,
Opt::PadScrollSpeed,
@@ -1429,6 +1446,53 @@ mod tests {
assert!((s.controller.move_deadzone - before - 0.01).abs() < 0.001);
}
/// The Device page's Nintendo Buttons row sits with the glyphs, steps between its two
/// values rather than ticking a box, and what it sets is what the controller file keeps.
#[test]
fn the_nintendo_buttons_row_flips_letters_and_the_file_keeps_it() {
let (page, group) = rows()
.into_iter()
.flat_map(|(page, groups)| groups.into_iter().map(move |g| (page, g)))
.find(|(_, (_, rows))| {
rows.iter()
.any(|r| r.item == Item::Option(Opt::PadNintendoButtons))
})
.unwrap();
assert_eq!((page, group.0), (Page::Device, "Glyphs"));
let mut s = Settings::default();
let item = Item::Option(Opt::PadNintendoButtons);
assert!(item.steps(&s));
s.controller.nintendo_letters = false;
let mut ui = ControllerUi {
focus: Some(Target::Item(item)),
..ControllerUi::default()
};
// Vanilla's caption and value template; Horizon's own words come bundled.
struct Vanilla;
impl lang::ResourceSource for Vanilla {
fn read(&self, path: &str) -> Option<Vec<u8>> {
(path == "assets/minecraft/lang/en_us.json")
.then(|| br#"{"options.generic_value": "%s: %s"}"#.to_vec())
}
}
let value = |ui: &ControllerUi, s: &Settings| {
lang::scoped(lang::Language::load(&[&Vanilla], "en_us"), || {
ui.parts(item, s)
})
.0
};
assert_eq!(value(&ui, &s).0, "Nintendo Buttons");
assert_eq!(value(&ui, &s).1.as_deref(), Some("By Position"));
let actions = key(&mut ui, &mut s, K::Enter);
assert!(actions.contains(&Action::Changed), "{actions:?}");
assert!(s.controller.nintendo_letters);
assert_eq!(value(&ui, &s).1.as_deref(), Some("By Letter"));
assert!(PadSettings::parse(&s.controller.serialize()).nintendo_letters);
key(&mut ui, &mut s, K::Enter);
assert!(!s.controller.nintendo_letters);
assert!(!PadSettings::parse(&s.controller.serialize()).nintendo_letters);
}
/// What the screen draws at the bottom of the page changes with the choice, in every one of
/// these settings.
#[test]
@@ -1438,6 +1502,7 @@ mod tests {
for (opt, choices) in [
(Opt::PadGameplayGuide, 3),
(Opt::PadGlyphs, 4),
(Opt::PadNintendoButtons, 2),
(Opt::PadKeyboard, 3),
(Opt::PadLightbar, 3),
] {
@@ -1470,6 +1535,7 @@ mod tests {
for opt in [
Opt::PadGameplayGuide,
Opt::PadGlyphs,
Opt::PadNintendoButtons,
Opt::PadKeyboard,
Opt::PadLightbar,
] {
+245 -15
View File
@@ -141,7 +141,8 @@ impl DataPack {
pub fn discover(world: &Path) -> Vec<DataPack> {
discover_folder(&world.join("datapacks"))
}
/// Packs in Create World's temporary pack folder, before a world exists.
/// `FolderRepositorySource.loadPacks`: packs in Create World's temporary
/// folder or a world's data-pack directory, with required folder metadata.
pub fn discover_folder(dir: &Path) -> Vec<DataPack> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
@@ -150,7 +151,7 @@ pub fn discover_folder(dir: &Path) -> Vec<DataPack> {
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
let path = e.path();
if path.is_dir() && path.join("pack.mcmeta").exists() {
if path.is_dir() && folder_metadata_present(&path) {
packs.push(DataPack {
id: format!("file/{name}"),
source: Source::Dir(path),
@@ -168,6 +169,22 @@ pub fn discover_folder(dir: &Path) -> Vec<DataPack> {
packs.sort_by(|a, b| a.id.cmp(&b.id));
packs
}
/// `Pack.readPackMetadata`: even its fallback codec requires a pack section
/// and description. Keep this folder gate separate from format compatibility
/// and the existing interpretation of the description component.
fn folder_metadata_present(path: &Path) -> bool {
let Some(meta) = std::fs::read(path.join("pack.mcmeta"))
.ok()
.and_then(|bytes| crate::packs::parse_meta(&bytes))
else {
return false;
};
meta.as_object()
.and_then(|root| root.get("pack"))
.and_then(serde_json::Value::as_object)
.and_then(|pack| pack.get("description"))
.is_some_and(|description| !description.is_null())
}
/// The resources root's built-in feature packs (`ServerPacksSource`
/// scanning the game's `data/minecraft/datapacks`): every folder with a
/// `pack.mcmeta`, a feature pack (`PackSource.FEATURE`). Off until a world
@@ -261,6 +278,43 @@ pub fn screen_packs(dir: &Path, resources: &Path) -> Vec<crate::pack_screen::Pac
}
infos
}
/// The folder of a game folder whose packs every new world there starts with: a modpack's profile
/// keeps the packs of its data-only jars here (`horizon-port-pack`). Each world gets its own copy,
/// as Create World's packs do, so a world keeps working when the folder changes. Vanilla has no
/// such folder, and without one nothing here happens.
pub const NEW_WORLD_PACKS: &str = "new-world-datapacks";
/// Create World's temporary pack folder holding `game_dir`'s [`NEW_WORLD_PACKS`], and their ids,
/// to show them selected in the Data Packs screen. `None` when there are none.
pub fn seed_create_world(game_dir: &Path) -> Option<(PathBuf, Vec<String>)> {
let from = game_dir.join(NEW_WORLD_PACKS);
let ids: Vec<String> = discover_folder(&from).into_iter().map(|p| p.id).collect();
if ids.is_empty() {
return None;
}
let seeded = temp_folder()
.map_err(|e| e.to_string())
.and_then(|dir| copy(&from, &dir).map(|()| dir));
match seeded {
Ok(dir) => Some((dir, ids)),
Err(e) => {
log::warn!("Horizon: data packs for new worlds: {e}");
None
}
}
}
/// A world about to be created without Create World (`--world`, the control socket) gets
/// `game_dir`'s [`NEW_WORLD_PACKS`]. The game turns on every pack it finds in a world.
pub fn install_new_world_packs(game_dir: &Path, world: &Path) -> Result<(), String> {
let from = game_dir.join(NEW_WORLD_PACKS);
let exists = |name: &str| world.join(name).exists();
if !from.is_dir() || exists("level.dat") || exists("level.dat_old") {
return Ok(());
}
copy(&from, &world.join("datapacks"))
}
/// A new empty folder for Create World's packs
/// (`Files.createTempDirectory("mcworld-")`).
pub fn temp_folder() -> std::io::Result<PathBuf> {
@@ -608,7 +662,7 @@ pub struct DataStore {
/// `item_modifier` files, for `/item modify`.
pub item_modifiers: BTreeMap<String, serde_json::Value>,
/// The content tables' raw files from the packs after the built-in one:
/// `recipe/`, `recipe_filter/`, `loot_table/`, `advancement/`, `dialog/`, `damage_type/`, `data_maps/` and `tags/…/` files, by
/// `recipe/`, `recipe_filter/`, `loot_table/`, `advancement/`, `dialog/`, `damage_type/`, `data_maps/`, `enchantment/` and `tags/…/` files, by
/// `<kind-dir>/<ns>:<path>`, each id's files in pack order. The tables
/// merge them over what they read from the resource root.
pub files: BTreeMap<String, Vec<Vec<u8>>>,
@@ -617,7 +671,7 @@ pub struct DataStore {
}
/// `<kind-dir>/<ns>:<path>` for a pack file the content tables read:
/// `recipe/`, `recipe_filter/`, `loot_table/`, `advancement/`, `trade_set/`,
/// `villager_trade/`, `dialog/`, `damage_type/`, `data_maps/` or `tags/<sub>/`, where the id keeps the sub
/// `villager_trade/`, `dialog/`, `damage_type/`, `data_maps/`, `enchantment/` or `tags/<sub>/`, where the id keeps the sub
/// path so a nested tag kind stays addressable.
fn content_id(file: &str) -> Option<String> {
let rest = file.strip_prefix("data/")?;
@@ -625,7 +679,7 @@ fn content_id(file: &str) -> Option<String> {
let (kind, rest) = rest.split_once('/')?;
let kind = match kind {
"recipe" | "recipe_filter" | "loot_table" | "advancement" | "trade_set"
| "villager_trade" | "dialog" | "damage_type" | "data_maps" => kind,
| "villager_trade" | "dialog" | "damage_type" | "data_maps" | "enchantment" => kind,
// A tag id is `{ns}:{path-under-tags}` (`tags/worldgen/biome/
// test:sub/mytag`), the whole path after the namespace, so nested
// registries keep their directory (`TagLoader`'s id shape).
@@ -659,6 +713,7 @@ impl DataStore {
"damage_type",
"data_maps",
"dialog",
"enchantment",
"function",
"item_modifier",
"loot_table",
@@ -714,15 +769,55 @@ impl DataStore {
}
s
}
/// `FunctionManager.getTag`: the functions a tag expands to (nested tags
/// included, each function once).
/// `ServerFunctionLibrary.getTag`: only valid function tags expand
/// (nested tags included, each function once).
pub fn tag_functions(&self, id: &str) -> Vec<String> {
let mut out = Vec::new();
let mut seen_fns = std::collections::HashSet::new();
let mut seen_tags = std::collections::HashSet::new();
self.expand(id, &mut out, &mut seen_fns, &mut seen_tags);
let invalid = self.invalid_function_tags(id);
self.expand(id, &mut out, &mut seen_fns, &mut seen_tags, &invalid);
out
}
/// `TagLoader.tryBuildTag`: missing required members invalidate their tag and
/// required parents. Optional invalid children contribute nothing.
/// Resolve against the current accepted function map, without caching a
/// candidate store or changing the existing expansion's cycle handling.
fn invalid_function_tags<'a>(&'a self, id: &'a str) -> std::collections::HashSet<&'a str> {
let mut invalid = std::collections::HashSet::new();
let mut parents: std::collections::HashMap<&str, Vec<&str>> =
std::collections::HashMap::new();
let mut seen = std::collections::HashSet::new();
let mut pending = vec![id];
while let Some(tag) = pending.pop() {
if !seen.insert(tag) {
continue;
}
let Some(entries) = self.function_tags.get(tag) else {
invalid.insert(tag);
continue;
};
for (entry, required) in entries {
if let Some(child) = entry.strip_prefix('#') {
pending.push(child);
if *required {
parents.entry(child).or_default().push(tag);
}
} else if *required && !self.functions.contains_key(entry) {
invalid.insert(tag);
}
}
}
pending.extend(invalid.iter().copied());
while let Some(child) = pending.pop() {
for &parent in parents.get(child).into_iter().flatten() {
if invalid.insert(parent) {
pending.push(parent);
}
}
}
invalid
}
/// Depth-first walk keeping first-seen order. Each tag is expanded at most
/// once, so reference cycles end and nesting depth is not capped.
fn expand<'a>(
@@ -731,18 +826,19 @@ impl DataStore {
out: &mut Vec<String>,
seen_fns: &mut std::collections::HashSet<&'a str>,
seen_tags: &mut std::collections::HashSet<&'a str>,
invalid: &std::collections::HashSet<&'a str>,
) {
if !seen_tags.insert(id) {
if invalid.contains(id) || !seen_tags.insert(id) {
return;
}
let Some(entries) = self.function_tags.get(id) else {
return;
};
for (e, required) in entries {
for (e, _) in entries {
match e.strip_prefix('#') {
Some(inner) => self.expand(inner, out, seen_fns, seen_tags),
Some(inner) => self.expand(inner, out, seen_fns, seen_tags, invalid),
None => {
if (self.functions.contains_key(e) || *required) && seen_fns.insert(e) {
if self.functions.contains_key(e) && seen_fns.insert(e) {
out.push(e.clone());
}
}
@@ -924,6 +1020,97 @@ pub fn worldgen_overrides(
mod tests {
use super::*;
#[test]
fn folder_metadata_is_required_before_contents_are_discovered() {
let root =
std::env::temp_dir().join(format!("horizon-folder-metadata-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
for (name, metadata) in [
("broken", Some("{")),
("root_empty", Some("{}")),
("root_array", Some("[]")),
("pack_empty", Some(r#"{"pack":{}}"#)),
("pack_string", Some(r#"{"pack":"bad"}"#)),
("missing", None),
(
"full",
Some(
r#"{"pack":{"description":"full","pack_format":121,"min_format":[121,0],"max_format":[121,0]}}"#,
),
),
(
"description",
Some(r#"{"pack":{"description":"description only"}}"#),
),
("numeric", Some(r#"{"pack":{"description":42}}"#)),
("null", Some(r#"{"pack":{"description":null}}"#)),
("bom", Some("\u{feff}{\"pack\":{\"description\":\"BOM\"}}")),
(
"comment",
Some("{\"pack\":{\"description\":\"comment\"}}\n// trailing"),
),
] {
let dir = root.join(name);
std::fs::create_dir_all(dir.join("data/h146/function")).unwrap();
std::fs::write(
dir.join(format!("data/h146/function/{name}.mcfunction")),
"scoreboard players set admitted h146 1\n",
)
.unwrap();
if let Some(metadata) = metadata {
std::fs::write(dir.join("pack.mcmeta"), metadata).unwrap();
}
}
let packs = discover_folder(&root);
assert_eq!(
packs.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
[
"file/bom",
"file/comment",
"file/description",
"file/full",
"file/numeric"
]
);
let store = DataStore::load(&packs.iter().collect::<Vec<_>>());
assert_eq!(
store
.functions
.keys()
.map(String::as_str)
.collect::<Vec<_>>(),
[
"h146:bom",
"h146:comment",
"h146:description",
"h146:full",
"h146:numeric"
]
);
let numeric = packs.iter().find(|p| p.id == "file/numeric").unwrap();
let raw: serde_json::Value =
serde_json::from_slice(&numeric.read("pack.mcmeta").unwrap()).unwrap();
assert_eq!(raw["pack"]["description"], 42);
// Builtin and feature construction still have their independent paths.
let resources = root.join("resources");
let feature = resources.join("data/minecraft/datapacks/feature");
std::fs::create_dir_all(&feature).unwrap();
std::fs::write(
feature.join("pack.mcmeta"),
r#"{"pack":{"description":"feature"}}"#,
)
.unwrap();
assert_eq!(
feature_packs(&resources)
.iter()
.map(|p| p.id.as_str())
.collect::<Vec<_>>(),
["feature"]
);
assert_eq!(DataPack::builtin(&resources).id, "vanilla");
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn data_map_files_are_content_files_keyed_by_map_namespace_and_registry() {
assert_eq!(
@@ -951,6 +1138,35 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn a_game_folder_s_new_world_packs_go_into_new_worlds_only() {
let root = std::env::temp_dir().join(format!("hz-new-world-packs-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let (game, world, old) = (root.join("game"), root.join("new"), root.join("old"));
assert!(seed_create_world(&game).is_none());
assert_eq!(install_new_world_packs(&game, &world), Ok(()));
assert!(!world.join("datapacks").exists());
for pack in ["void", "islands"] {
let dir = game.join(NEW_WORLD_PACKS).join(pack);
std::fs::create_dir_all(dir.join("data/v/function")).unwrap();
std::fs::write(dir.join("pack.mcmeta"), r#"{"pack":{"description":""}}"#).unwrap();
std::fs::write(dir.join("data/v/function/a.mcfunction"), "say a").unwrap();
}
let (temp, ids) = seed_create_world(&game).unwrap();
assert_eq!(ids, ["file/islands", "file/void"]);
assert!(temp.join("void/data/v/function/a.mcfunction").is_file());
let _ = std::fs::remove_dir_all(&temp);
install_new_world_packs(&game, &world).unwrap();
let ids: Vec<String> = discover(&world).into_iter().map(|p| p.id).collect();
assert_eq!(ids, ["file/islands", "file/void"]);
// A world that exists already keeps the packs it has.
std::fs::create_dir_all(&old).unwrap();
std::fs::write(old.join("level.dat"), "").unwrap();
install_new_world_packs(&game, &old).unwrap();
assert!(discover(&old).is_empty());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn enabled_packs_override_worldgen_in_order() {
let dir = std::env::temp_dir().join(format!("hz-datapack-worldgen-{}", std::process::id()));
@@ -961,7 +1177,7 @@ mod tests {
std::fs::write(path, t).unwrap();
};
for pack in ["a", "b", "off"] {
write(pack, "pack.mcmeta", "{}");
write(pack, "pack.mcmeta", r#"{"pack":{"description":"fixture"}}"#);
write(pack, "data/minecraft/worldgen/noise/cave.json", pack);
write(pack, "data/p/structure/room/a.nbt", pack);
write(
@@ -1132,6 +1348,20 @@ mod tests {
#[test]
fn tag_resolution_dedupes_fast_ends_cycles_and_nests_deeply() {
let mut store = DataStore::default();
// Every referenced function exists; missing required ones invalidate a tag.
for id in (0..25_000)
.map(|i| format!("t:f{i}"))
.chain(["t:x", "t:y", "t:deep"].map(str::to_owned))
{
store.functions.insert(
id.clone(),
Function {
id,
lines: Vec::new(),
parameters: Vec::new(),
},
);
}
let big: Vec<(String, bool)> = (0..50_000)
.map(|i| (format!("t:f{}", i % 25_000), true))
.collect();
@@ -1216,13 +1446,13 @@ mod tests {
write(
"fns",
"pack.mcmeta",
r#"{"pack":{"min_format":121,"max_format":121}}"#,
r#"{"pack":{"description":"fixture","min_format":121,"max_format":121}}"#,
);
write("fns", "data/x/function/f.mcfunction", "say hi");
write(
"off",
"pack.mcmeta",
r#"{"pack":{"min_format":121,"max_format":121}}"#,
r#"{"pack":{"description":"fixture","min_format":121,"max_format":121}}"#,
);
std::fs::create_dir_all(&dir).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(dir.join("old.zip")).unwrap());
+35 -4
View File
@@ -33,7 +33,10 @@ struct Globals {
hdr_windows: array<vec4<f32>, 2>,
// HDR lighting: x how strongly the sky lights the world now (`Sky::sky_light_factor`),
// y what the sky and fog get: the same, but none under water.
// w: this entire frame writes light, so alpha is coverage rather than a mark.
hdr_light: vec4<f32>,
hdr_settings: vec4<f32>,
hdr_shares: vec4<f32>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@@ -276,6 +279,18 @@ fn crumbling_uv(uv: vec2<f32>, packed_origin: vec2<f32>, sprite_size: vec2<f32>,
}
// CRUMBLING_UV_END
@fragment fn fs_entity(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
return entity_written_color(in, front);
}
fn entity_written_color(in: Out, front: bool) -> vec4<f32> {
let color = entity_color(in, front);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 && in.overlay != 11u && in.overlay != 12u {
var mark = hdr_entity_mark(in);
if in.overlay == 4u { mark = hdr_scene_alpha(globals.hdr_light.y); }
return vec4(hdr_written(color.rgb, mark, globals.hdr_settings, globals.hdr_shares), color.a);
}
return color;
}
@fragment fn fs_entity_unmarked(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
return entity_color(in, front);
}
fn entity_color(in: Out, front: bool) -> vec4<f32> {
@@ -358,15 +373,23 @@ fn shadow_color(in: Out) -> vec4<f32> {
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
let texel = textureSample(atlas, atlas_sampler, uv);
if texel.a < 0.1 { discard; }
return vec4(0.0, 0.0, 0.0, hdr_entity_mark(in));
}
fn hdr_entity_mark(in: Out) -> f32 {
var uv = in.uv;
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
let texel = textureSample(atlas, atlas_sampler, uv);
// Additive and procedural colour draws can survive where the legacy mark pass skips.
if texel.a < 0.1 { return 1.0; }
// Fog hides a light source and the light on a surface as it hides everything else.
let fogged = max(linear_fog(in.fog_distance.x, globals.fog.x, globals.fog.y),
linear_fog(in.fog_distance.y, globals.fog.z, globals.fog.w)) * globals.fog_color.a;
if in.tier == 0u {
return vec4(0.0, 0.0, 0.0, hdr_scene_alpha(mix(in.scene, globals.hdr_light.y, fogged)));
return hdr_scene_alpha(mix(in.scene, globals.hdr_light.y, fogged));
}
// A layer that fades (the warden's) shines by what's left of it.
let y = brightness(texel.rgb * in.color.rgb) * in.color.a * (1.0 - fogged);
return vec4(0.0, 0.0, 0.0, hdr_mark(in.tier, y));
return hdr_mark(in.tier, y);
}
fn brightness(c: vec3<f32>) -> f32 {
let l = pow(max(c, vec3(0.0)), vec3(2.2));
@@ -407,7 +430,11 @@ fn celestial_color(in: Out) -> vec4<f32> {
return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color;
}
@fragment fn fs_celestial(in: Out) -> @location(0) vec4<f32> {
return celestial_color(in);
let color = celestial_color(in);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
return vec4(hdr_written(color.rgb, hdr_entity_mark(in), globals.hdr_settings, globals.hdr_shares), color.a);
}
return color;
}
// The sky's celestial pass (sun, moon, the End sky): fs_celestial's light,
@@ -424,7 +451,11 @@ fn celestial_color(in: Out) -> vec4<f32> {
let y = brightness(added);
// Only what's past the tier's window takes the mark: a soft edge keeps the sky's light,
// or it would come out darker than the sky around it.
if y < globals.hdr_windows[1][clamp(tier, 1u, 4u) - 1u] { return vec4(added, 0.0); }
let full = y >= globals.hdr_windows[1][clamp(tier, 1u, 4u) - 1u];
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
return vec4(hdr_written(added, select(1.0, hdr_mark(tier, y), full), globals.hdr_settings, globals.hdr_shares), color.a);
}
if !full { return vec4(added, 0.0); }
return vec4(added, 1.0 - hdr_mark(tier, y));
}
@@ -399,8 +399,11 @@ pub fn apply_weather(sky: &mut Sky, rain: f32, thunder: f32) {
pub fn sky_darken(environment: &Environment, day_time: i64, rain: f32, thunder: f32) -> i32 {
let mut sky = environment.sample(day_time, None, None);
apply_weather(&mut sky, rain, thunder);
// Level.updateSkyBrightness: darkening from the sky light level.
(15.0 - 15.0 * sky.sky_light_level).round() as i32
// Level.updateSkyBrightness: `(int)(15.0F - skyLightLevel)`, the float
// truncated, not rounded (#11323): the darkening steps up only once the
// light has fallen a whole level. `sky_light_level` is the attribute as a
// fraction of 15, so the product is its raw value in `f32`.
(15.0 - 15.0 * sky.sky_light_level) as i32
}
#[cfg(test)]
+67 -1
View File
@@ -5,7 +5,7 @@ use crate::{
lang,
options_ui::{Event, Page},
settings::Settings,
settings_shell::{Group, Output, Row, Screen, Sheet, Value},
settings_shell::{self as shell, Group, Output, Row, Screen, Sheet, Value},
};
const TITLE: &str = "horizon.pages.extras";
@@ -85,6 +85,10 @@ impl Screen for ExtrasScreen {
fn note_lines(&self) -> usize {
NOTE_LINES
}
/// The rows read the extras, the mods and whether cosmetics are offered.
fn stamp(&self, s: &Settings) -> u64 {
shell::stamp_of(&(&s.extras, &s.mods, horizon_cosmetics::enabled()))
}
fn sheets(&self, s: &Settings) -> Vec<Sheet<(), ExtraRow>> {
let mut groups = vec![Group {
name: MODS,
@@ -228,4 +232,66 @@ mod tests {
assert!(s.extras.sort);
assert_eq!(screen.wheel_step(&mut s, ExtraRow::Zoom(0), true), None);
}
/// Extras has no Undo: a change leaves none to press or reach.
#[test]
fn a_change_on_extras_leaves_no_undo() {
use crate::settings_shell::{Columns, Target};
use winit::keyboard::KeyCode as K;
let mut s = Settings::default();
let mut shell = Shell::<ExtrasScreen>::default();
let at = shell.point_at(&s, SIZE, ExtraRow::Item(Item::Sort));
assert!(
!shell
.click(&mut s, at, SIZE, false, false, false)
.is_empty()
);
assert!(s.extras.sort && !shell.changed());
let cols = Columns::of(SIZE.0, SIZE.1).with_note_lines(NOTE_LINES);
let [x, y, ..] = cols.button(1);
assert!(
shell
.click(&mut s, (x + 2.0, y + 2.0), SIZE, false, false, false)
.is_empty()
);
assert!(s.extras.sort);
let reached = (0..100).any(|_| {
shell.key(&mut s, K::Tab, None, false, SIZE);
shell.focused() == Some(Target::Undo)
});
assert!(!reached);
}
/// A page with no page list has Done under the search field: Down goes to the first row
/// instead, from the keys and, as the frame declares it, from a controller's focus.
#[test]
fn down_from_the_search_field_lands_on_the_first_row() {
use crate::{hud::HudBatch, settings_shell::Columns, ui};
use winit::keyboard::KeyCode as K;
let atlas = crate::hud::HudAtlas::build(std::path::Path::new("/nonexistent")).unwrap();
let mut s = Settings::default();
let mut shell = Shell::<ExtrasScreen>::default();
let mut batch = HudBatch::new([1708, 960]);
shell.draw(&s, &mut batch, &atlas, (0.0, 0.0), false, None);
crate::widgets::end_frame(1);
let size = (batch.width, batch.height);
let cols = Columns::of(size.0, size.1).with_note_lines(NOTE_LINES);
// The Mods group's note can't take the focus: the first item can.
let first = ExtraRow::Item(Item::OwnNameTag);
let at = shell.point_at(&s, size, first);
let [x, y, w, h] = crate::widgets::linked_step(cols.search(), true).unwrap();
assert!(ui::hovered(at, x, y, w, h));
assert_eq!(crate::widgets::linked_step(cols.search(), false), None);
let [x, y, w, h] = cols.search();
shell.click(
&mut s,
(x + w / 2.0, y + h / 2.0),
size,
false,
false,
false,
);
shell.key(&mut s, K::ArrowDown, None, false, size);
assert_eq!(shell.focused_row(), Some(first));
}
}
+20 -15
View File
@@ -9,6 +9,7 @@ use crate::{
environment::Sky,
world::World,
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::path::Path;
/// `FogType` of the camera position.
@@ -64,7 +65,7 @@ impl FogTables {
}
/// Fog state that evolves over time.
#[derive(Clone, Copy, Debug, Default)]
#[derive(Clone, Debug)]
pub struct FogState {
/// `LocalPlayer.waterVisionTime` (0..600).
pub water_vision_time: i32,
@@ -72,24 +73,28 @@ pub struct FogState {
pub rain_fog_multiplier: f32,
/// `LightmapRenderStateExtractor.blockLightFlicker`.
pub block_light_flicker: f32,
flicker_seed: u64,
/// `LightmapRenderStateExtractor.random`: `RandomSource.create()`.
flicker_random: LegacyRandom,
}
impl Default for FogState {
fn default() -> Self {
Self {
water_vision_time: 0,
rain_fog_multiplier: 0.0,
block_light_flicker: 0.0,
flicker_random: crate::random_source::create(),
}
}
}
impl FogState {
fn next_float(&mut self) -> f32 {
// splitmix64: the vanilla source is unseeded `RandomSource.create()`.
self.flicker_seed = self.flicker_seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.flicker_seed;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
((z ^ (z >> 31)) >> 40) as f32 / (1u32 << 24) as f32
}
/// `LightmapRenderStateExtractor.tick`: the torch light flickers.
pub fn tick_flicker(&mut self) {
let r = &mut self.flicker_random;
let (a, b, c, d) = (
self.next_float(),
self.next_float(),
self.next_float(),
self.next_float(),
r.next_float(),
r.next_float(),
r.next_float(),
r.next_float(),
);
self.block_light_flicker += (a - b) * c * d * 0.1;
self.block_light_flicker *= 0.9;
@@ -750,7 +755,7 @@ mod tests {
rain_fog_multiplier: 0.1,
..FogState::default()
};
let mut settled = start;
let mut settled = start.clone();
settle_rain_fog(&mut settled, 0.5, 15, true);
assert_eq!(settled.rain_fog_multiplier, 0.5);
let mut eased = start;
+135 -32
View File
@@ -126,11 +126,16 @@ struct Cache {
random: horizon_core::random::LegacyRandom,
}
pub struct Font {
/// The atlas rects of the sheets under `textures/font`.
/// The atlas rects of every texture, by resource name: a bitmap provider's
/// `file` may name any texture, not only one under `textures/font`.
sheets: HashMap<String, Rect>,
missing: Glyph,
white: Rect,
root: PathBuf,
/// The game's own resources, below a pack overlay: a font file the overlay
/// lacks (a pack adds providers over vanilla's, or the overlay left a
/// directory out) is read from here, as vanilla's resource stack does.
fallback: Option<PathBuf>,
/// Atlas size and the reserved dynamic region (y, height).
atlas: (u32, u32),
region: (u32, u32),
@@ -199,6 +204,13 @@ fn parse_hex(text: &[u8], out: &mut HashMap<u32, HexGlyph>) {
out.insert(codepoint, HexGlyph { rows, left, right });
}
}
/// A resource file's bytes, from `root` or, when the overlay lacks it, from
/// the game's own resources below (`defaults`).
fn read_resource(root: &Path, defaults: Option<&Path>, path: &str) -> Option<Vec<u8>> {
std::fs::read(root.join(path))
.ok()
.or_else(|| defaults.and_then(|d| std::fs::read(d.join(path)).ok()))
}
fn read_json(root: &Path, path: &str) -> Option<serde_json::Value> {
serde_json::from_slice(&std::fs::read(root.join(path)).ok()?).ok()
}
@@ -281,6 +293,7 @@ fn hex_advance(h: &HexGlyph) -> f32 {
/// pixels, copied into the atlas when first drawn.
fn load_bitmap(
root: &Path,
defaults: Option<&Path>,
p: &serde_json::Value,
sheets: &HashMap<String, Rect>,
pixels: &[u8],
@@ -290,22 +303,36 @@ fn load_bitmap(
let mut out = HashMap::new();
let file = p["file"].as_str().unwrap_or("");
let (ns, name) = file.split_once(':').unwrap_or(("minecraft", file));
let in_atlas = (ns == "minecraft")
.then(|| sheets.get(name.trim_end_matches(".png")).copied())
.flatten();
let name = name.trim_end_matches(".png");
// The atlas names the default namespace's textures by their path and every
// other namespace's as `namespace:path` (HudAtlas::build).
let atlas_name = if ns == "minecraft" {
name.to_owned()
} else {
format!("{ns}:{name}")
};
let in_atlas = sheets.get(&atlas_name).copied();
// The sheet: its size, and its pixels when they are not in the atlas.
let (sw, sh, sheet) = match in_atlas {
Some(rect) => {
let (w, h) = rect.texels(atlas);
(w, h, None)
}
None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) {
Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))),
Err(_) => {
log::warn!("font sheet {file} could not be read");
return out;
None => {
let path = resource_path(file, "textures", "");
let sheet = crate::hud::decode(&root.join(&path)).or_else(|first| {
defaults
.and_then(|d| crate::hud::decode(&d.join(&path)).ok())
.ok_or(first)
});
match sheet {
Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))),
Err(_) => {
log::warn!("font sheet {file} could not be read");
return out;
}
}
},
}
};
let rows: Vec<Vec<char>> = p["chars"]
.as_array()
@@ -382,11 +409,13 @@ fn load_bitmap(
}
/// `TrueTypeGlyphProviderDefinition.load`: a TrueType file (not CFF) under
/// `font/`, its Unicode characters but the `skip` ones.
fn load_true_type(root: &Path, p: &serde_json::Value) -> Option<TrueType> {
fn load_true_type(root: &Path, defaults: Option<&Path>, p: &serde_json::Value) -> Option<TrueType> {
let file = p["file"].as_str()?;
let data = std::fs::read(root.join(resource_path(file, "font", "")))
.map_err(|e| log::warn!("font file {file}: {e}"))
.ok()?;
let path = resource_path(file, "font", "");
let Some(data) = read_resource(root, defaults, &path) else {
log::warn!("font file {file} could not be read");
return None;
};
// FT_Get_Font_Format must say TrueType: CFF outlines ("OTTO") are refused.
if data.starts_with(b"OTTO") {
log::warn!("font file {file} is not in TTF format");
@@ -486,13 +515,16 @@ impl TrueType {
)
}
}
fn load_hex(root: &Path, p: &serde_json::Value) -> HashMap<u32, HexGlyph> {
fn load_hex(root: &Path, defaults: Option<&Path>, p: &serde_json::Value) -> HashMap<u32, HexGlyph> {
let mut glyphs = HashMap::new();
let Some(file) = p["hex_file"].as_str() else {
return glyphs;
};
let path = root.join(resource_path(file, "", "").replace("//", "/"));
let Ok(zip) = Zip::open(&path) else {
let path = resource_path(file, "", "").replace("//", "/");
let Some(zip) = Zip::open(&root.join(&path))
.ok()
.or_else(|| defaults.and_then(|d| Zip::open(&d.join(&path)).ok()))
else {
return glyphs;
};
let names: Vec<String> = zip
@@ -603,7 +635,24 @@ impl Font {
region: (u32, u32),
white: Rect,
) -> Self {
Self::load_with(root, sprites, pixels, atlas, region, white, false)
Self::load_with(root, None, sprites, pixels, atlas, region, white, false)
}
/// [`Font::load`] over a pack overlay: a sheet, TrueType file or Unihex
/// file the overlay lacks is read from `defaults`, the game's own
/// resources, as vanilla's resource stack does. (Definitions stay the
/// overlay's: a pack's filter may hide one from a lower pack.)
#[allow(clippy::too_many_arguments)]
pub fn load_over(
root: &Path,
defaults: &Path,
sprites: &HashMap<String, Rect>,
pixels: &[u8],
atlas: (u32, u32),
region: (u32, u32),
white: Rect,
) -> Self {
let fallback = (root != defaults).then_some(defaults);
Self::load_with(root, fallback, sprites, pixels, atlas, region, white, false)
}
/// A server measures text but never draws it. Decode bitmap sheets only
/// to obtain advances, then release their pixels; never rasterize glyphs.
@@ -616,10 +665,21 @@ impl Font {
w: 1,
h: 1,
};
Self::load_with(root, &HashMap::new(), &[], (1, 1), (0, 0), white, true)
Self::load_with(
root,
None,
&HashMap::new(),
&[],
(1, 1),
(0, 0),
white,
true,
)
}
#[allow(clippy::too_many_arguments)]
fn load_with(
root: &Path,
fallback: Option<&Path>,
sprites: &HashMap<String, Rect>,
pixels: &[u8],
atlas: (u32, u32),
@@ -627,11 +687,7 @@ impl Font {
white: Rect,
metrics_only: bool,
) -> Self {
let sheets = sprites
.iter()
.filter(|(k, _)| k.starts_with("font/"))
.map(|(k, v)| (k.clone(), *v))
.collect();
let sheets = sprites.clone();
let font = Self {
sheets,
missing: Glyph {
@@ -645,6 +701,7 @@ impl Font {
},
white,
root: root.to_owned(),
fallback: fallback.map(|p| p.to_owned()),
atlas,
region,
metrics_only,
@@ -656,11 +713,8 @@ impl Font {
pending: Vec::new(),
full: false,
},
random: horizon_core::random::LegacyRandom::new(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as i64),
),
// `Font.random`: `RandomSource.create()`.
random: crate::random_source::create(),
}),
generation: std::cell::Cell::new(next_generation()),
uniform: false,
@@ -698,6 +752,7 @@ impl Font {
Filter::of(p),
load_bitmap(
&self.root,
self.fallback.as_deref(),
p,
&self.sheets,
pixels,
@@ -708,7 +763,7 @@ impl Font {
"unihex" => Some(Provider::Unihex(Filter::of(p), p.clone(), None)),
"ttf" => Some(Provider::TrueType(
Filter::of(p),
Box::new(load_true_type(&self.root, p)?),
Box::new(load_true_type(&self.root, self.fallback.as_deref(), p)?),
)),
_ => None,
})
@@ -868,7 +923,8 @@ impl Font {
}
}
Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => {
let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def));
let glyphs = glyphs
.get_or_insert_with(|| load_hex(&self.root, self.fallback.as_deref(), def));
if let Some(h) = glyphs.get(&u32::from(c)).copied()
&& !(non_fishy && fishy_advance(hex_advance(&h)))
{
@@ -1026,7 +1082,8 @@ impl Font {
}
}
Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => {
let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def));
let glyphs = glyphs
.get_or_insert_with(|| load_hex(&self.root, self.fallback.as_deref(), def));
if let Some(h) = glyphs.get(&u32::from(c)) {
return Some(hex_advance(h));
}
@@ -1512,6 +1569,52 @@ mod tests {
assert!(texels.iter().any(|t| t[0] == 255));
}
/// A bitmap provider's `file` can name any texture. When the atlas has that
/// texture (HUD packs keep their glyph sheets outside `textures/font`), the
/// glyphs are read from it instead of being copied into the small run-time
/// region one by one; the region then cannot fill up and turn later glyphs
/// into the missing one, whose advance shifts the rest of a HUD line.
#[test]
fn a_bitmap_sheet_outside_font_is_read_from_the_atlas() {
let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x));
let (_, _, pixels) = crate::hud::decode_bytes(&sheet).unwrap();
let rect = Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 16,
h: 8,
};
for (ns, file, key) in [
("minecraft", "minecraft:hud/sheet.png", "hud/sheet"),
(
"hudengine",
"hudengine:font/sheet.png",
"hudengine:font/sheet",
),
] {
let def = format!(
r#"{{"providers":[{{"type":"bitmap","file":"{file}","ascent":7,"chars":["ab"]}}]}}"#
);
// The image is only in the atlas: the pack's copy is not on disk.
let root = root(
ns,
&[("assets/minecraft/font/default.json", def.as_bytes())],
);
let sprites = HashMap::from([(key.to_string(), rect)]);
let font = Font::load(&root, &sprites, &pixels, (16, 8), (0, 8), white());
let _ = std::fs::remove_dir_all(&root);
assert_eq!(font.glyph('a').advance, 3.0, "{ns}");
assert_eq!(font.glyph('b').advance, 7.0, "{ns}");
assert!(font.glyph('a').rect.is_some(), "{ns}");
assert!(
font.take_patches().is_empty(),
"{ns}: the atlas sheet is not copied into the run-time region"
);
}
}
#[test]
fn styles_pick_their_font_and_unknown_fonts_draw_missing_glyphs() {
let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x));
File diff suppressed because it is too large. Load diff
+12 -1
View File
@@ -879,6 +879,7 @@ mod tests {
solid,
solid_slots: u64::from(solid) * 4,
packed: false,
packed_far: false,
sides: crate::mesher::Sides::unsorted(solid),
translucent,
sort: super::super::translucency::SortState::new(Vec::new()),
@@ -1047,7 +1048,15 @@ mod tests {
hdr: None,
}
};
let mut flat = flat::Flat::new(&device, &terrain_layout, 4 * GRAIN, 0, pipeline, solid);
let mut flat = flat::Flat::new(
&device,
&terrain_layout,
4 * GRAIN,
0,
false,
pipeline,
solid,
);
let stride = std::mem::size_of::<crate::mesher::TerrainVertex>() as u64;
let mut translucent = Arena::translucent(&device, stride, 4 * GRAIN);
translucent.page_limit = 4 * GRAIN;
@@ -1083,6 +1092,7 @@ mod tests {
solid: 64,
solid_slots: 64 * 4,
packed: false,
packed_far: false,
sides: crate::mesher::Sides::unsorted(64),
translucent: 128,
sort: super::super::translucency::SortState::new(Vec::new()),
@@ -1310,6 +1320,7 @@ mod tests {
solid,
solid_slots: u64::from(solid) * 4,
packed: false,
packed_far: false,
sides: crate::mesher::Sides::unsorted(solid),
translucent,
sort: super::super::translucency::SortState::new(Vec::new()),
@@ -67,6 +67,7 @@ fn copy(mesh: &SectionMesh) -> SectionMesh {
sides: mesh.sides,
translucent: mesh.translucent.clone(),
packed: mesh.packed.clone(),
packed_far: mesh.packed_far,
solid_tints: Vec::new(),
visibility: mesh.visibility,
block_entities: mesh.block_entities.clone(),
@@ -0,0 +1,436 @@
//! A resource pack's `core/sky` and `core/stars` shaders: the overworld's sky disc and stars drawn
//! with the pack's GLSL (`SkyRenderer.renderSkyDisc`, `renderStars`), as a pack that adds a haze
//! to the horizon or tints the night sky expects. Without one the sky draws natively (`fs_sky` in
//! terrain.wgsl, stars.rs).
use glam::Mat4;
use horizon_shaders::{CoreProgram, Glue};
use wgpu::util::DeviceExt;
/// `DefaultVertexFormat.POSITION`: the disc's and the stars' vertices.
pub(crate) const GLUE: Glue = Glue {
inputs: &[("Position", "vec3")],
prelude: "layout(location = 0) in vec3 hz_position;",
setup: "Position = hz_position;",
// 26.3's ProjMat already has wgpu's reversed 0 to 1 depth (Projection: zZeroToOne).
finish: "",
vertex_id: "int(gl_VertexIndex)",
};
/// Each uniform block's offset in the one buffer (`core_shader::BLOCKS` order).
const BLOCK_OFFSETS: [u64; 4] = [0, 256, 512, 768];
const BLOCK_SIZES: [u64; 4] = [48, 64, 160, 48];
/// `SkyRenderer.buildSkyDisc(16)`: a fan around the point 16 above the camera, out to 512 every
/// 45 degrees, as a triangle list.
pub(crate) fn disc_triangles() -> Vec<[f32; 3]> {
let rim: Vec<[f32; 3]> = (-180..=180)
.step_by(45)
.map(|i: i32| {
let a = (i as f32).to_radians();
[512.0 * a.cos(), 16.0, 512.0 * a.sin()]
})
.collect();
rim.windows(2)
.flat_map(|edge| [[0.0, 16.0, 0.0], edge[0], edge[1]])
.collect()
}
/// One of the sky's pack pipelines with its vertices and uniforms.
struct Part {
pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
vertices: wgpu::Buffer,
count: u32,
}
impl Part {
fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
program: &CoreProgram,
name: &str,
blend: Option<wgpu::BlendState>,
triangles: &[[f32; 3]],
) -> Option<Self> {
// A pack's shader is untrusted: the backend failing to compile it is an internal error.
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
let module = |stage, module: &naga::Module| {
device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(&format!("Resource pack {name} ({stage})")),
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module.clone())),
})
};
let vertex = module("vertex", &program.vertex);
let fragment = module("fragment", &program.fragment);
// Vanilla's SKY and STARS pipelines have no samplers: a pack that reads one is not used.
let entries: Vec<wgpu::BindGroupLayoutEntry> = (0..4)
.map(|binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(BLOCK_SIZES[binding as usize]),
},
count: None,
})
.collect();
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some(name),
entries: &entries,
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some(name),
size: 1024,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let resources: Vec<wgpu::BindGroupEntry> = (0..4)
.map(|i| wgpu::BindGroupEntry {
binding: i as u32,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &uniform,
offset: BLOCK_OFFSETS[i],
size: wgpu::BufferSize::new(BLOCK_SIZES[i]),
}),
})
.collect();
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(name),
layout: &layout,
entries: &resources,
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(name),
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(name),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &vertex,
entry_point: Some("main"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: 12,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &wgpu::vertex_attr_array![0 => Float32x3],
})],
},
primitive: wgpu::PrimitiveState::default(),
// The sky is drawn first, behind everything: no depth test, no depth write.
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(false),
depth_compare: Some(wgpu::CompareFunction::Always),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &fragment,
entry_point: Some("main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let internal = pollster::block_on(internal.pop());
if let Some(e) = internal.or(pollster::block_on(validation.pop())) {
log::warn!("the resource pack's {name} shader is not used: {e}");
return None;
}
let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(name),
contents: bytemuck::cast_slice(triangles),
usage: wgpu::BufferUsages::VERTEX,
});
Some(Self {
pipeline,
group,
uniform,
vertices,
count: triangles.len() as u32,
})
}
fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.vertices.slice(..));
pass.draw(0..self.count, 0..1);
}
}
/// The packs' sky disc and stars pipelines, each present when a pack replaces that shader.
pub(super) struct CoreSky {
disc: Option<Part>,
stars: Option<Part>,
}
impl CoreSky {
/// `None` when neither shader is replaced or neither builds.
pub(super) fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
disc: Option<&CoreProgram>,
stars: Option<&CoreProgram>,
) -> Option<Self> {
let disc = disc.and_then(|program| {
// RenderPipelines.SKY: ColorTargetState.DEFAULT, no blending.
Part::new(device, format, program, "sky", None, &disc_triangles())
});
let stars = stars.and_then(|program| {
// RenderPipelines.STARS: BlendFunction.OVERLAY (src alpha and one; alpha one, zero).
let overlay = wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
};
let triangles = super::stars::star_triangles();
Part::new(device, format, program, "stars", Some(overlay), &triangles)
});
(disc.is_some() || stars.is_some()).then_some(Self { disc, stars })
}
pub(super) fn draws_disc(&self) -> bool {
self.disc.is_some()
}
pub(super) fn draws_stars(&self) -> bool {
self.stars.is_some()
}
/// Uploads the disc's and the stars' blocks: `sky` and `stars` from [`uniforms`].
pub(super) fn prepare(
&self,
uploads: &mut super::upload::Uploads,
encoder: &mut wgpu::CommandEncoder,
sky: &[u8],
stars: Option<&[u8]>,
) {
if let Some(disc) = &self.disc {
uploads.buffer(encoder, &disc.uniform, 0, sky);
}
if let (Some(part), Some(data)) = (&self.stars, stars) {
uploads.buffer(encoder, &part.uniform, 0, data);
}
}
/// The disc, in place of the native sky colour. The caller sets its own group 0 again after.
pub(super) fn draw_disc(&self, pass: &mut wgpu::RenderPass<'_>) {
if let Some(disc) = &self.disc {
disc.draw(pass);
}
}
/// The stars, in place of the native ones. The caller sets its own group 0 again after.
pub(super) fn draw_stars(&self, pass: &mut wgpu::RenderPass<'_>) {
if let Some(stars) = &self.stars {
stars.draw(pass);
}
}
}
/// The std140 blocks for one sky draw: `Globals`, `Projection` (`projection`, far enough for the
/// disc's 512-block rim), `DynamicTransforms` (`model_view`: the camera's rotation, times the
/// stars' rotation for them; `color`: the sky colour, or the star brightness in every channel)
/// and `Fog` (`fog_color`, `fog`: environmental start and end, render distance start and end,
/// sky end, clouds end).
pub(super) fn uniforms(
globals: [u8; 48],
projection: Mat4,
model_view: Mat4,
color: [f32; 4],
fog_color: [f32; 4],
fog: [f32; 6],
) -> Vec<u8> {
let mut data = vec![0f32; 256];
data[64..80].copy_from_slice(&projection.to_cols_array());
let transforms = 128;
data[transforms..transforms + 16].copy_from_slice(&model_view.to_cols_array());
data[transforms + 16..transforms + 32].copy_from_slice(&Mat4::IDENTITY.to_cols_array());
data[transforms + 32..transforms + 36].copy_from_slice(&color);
data[192..196].copy_from_slice(&fog_color);
data[196..202].copy_from_slice(&fog);
let mut bytes: Vec<u8> = bytemuck::cast_slice(&data).to_vec();
bytes[..48].copy_from_slice(&globals);
bytes
}
#[cfg(test)]
mod tests {
use super::*;
/// `buildSkyDisc(16)`: eight triangles from the point above the camera to the rim, which
/// starts and ends at x -512 (cos 180°) and passes through z -512, x 512 and z 512.
#[test]
fn the_disc_is_vanillas_fan_as_triangles() {
let triangles = disc_triangles();
assert_eq!(triangles.len(), 24);
assert!(triangles.chunks(3).all(|t| t[0] == [0.0, 16.0, 0.0]));
let rim: Vec<[f32; 3]> = triangles.chunks(3).map(|t| t[1]).collect();
let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);
assert!(near(rim[0], [-512.0, 16.0, 0.0]));
assert!(near(rim[2], [0.0, 16.0, -512.0]));
assert!(near(rim[4], [512.0, 16.0, 0.0]));
assert!(near(rim[6], [0.0, 16.0, 512.0]));
assert!(near(triangles[23], [-512.0, 16.0, 0.0]));
}
/// The prepared resources (`HORIZON_RESOURCES`, or `.local/horizon-client/<version>`), where
/// vanilla's sky shader and its includes are.
fn resources() -> std::path::PathBuf {
std::env::var_os("HORIZON_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION)
})
}
/// Vanilla's `sky.vsh` with a pack's fragment shader that paints `ColorModulator` (the sky
/// colour) where the disc is: looking at the horizon, the top half of the target is the
/// disc, the bottom half stays clear.
#[test]
fn a_pack_sky_shader_paints_the_disc_above_the_horizon() {
let root = resources();
let Ok(vertex) =
std::fs::read_to_string(root.join("assets/minecraft/shaders/core/sky.vsh"))
else {
eprintln!("skipping: no prepared resources at {}", root.display());
return;
};
let include = |id: &str| {
let (namespace, path) = id.split_once(':')?;
std::fs::read_to_string(root.join(format!("assets/{namespace}/{path}"))).ok()
};
let fragment = "#version 330\n#include <minecraft:dynamictransforms.glsl>\n\
layout(location = 0) out vec4 fragColor;\n\
void main() {\n fragColor = ColorModulator;\n}\n";
let program = horizon_shaders::translate_core(&vertex, fragment, &[], &include, &GLUE)
.expect("the sky shaders translate");
let instance = crate::gfx::test_gpu::instance();
let Some((device, queue)) =
pollster::block_on(instance.request_adapter(&Default::default()))
.ok()
.and_then(|adapter| {
pollster::block_on(adapter.request_device(&Default::default())).ok()
})
else {
eprintln!("no GPU: skipping");
return;
};
const SIZE: u32 = 64;
let format = wgpu::TextureFormat::Rgba8Unorm;
let sky = CoreSky::new(&device, format, Some(&program), None).expect("the sky pipeline");
let projection = crate::gfx::world_projection(90.0, 1.0, 2048.0);
let data = uniforms(
[0; 48],
projection,
Mat4::IDENTITY,
[0.25, 0.5, 1.0, 1.0],
[0.0; 4],
[1e6; 6],
);
queue.write_buffer(&sky.disc.as_ref().unwrap().uniform, 0, &data);
let target = |format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: SIZE,
height: SIZE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | usage,
view_formats: &[],
})
};
let color = target(format, wgpu::TextureUsages::COPY_SRC);
let depth = target(
wgpu::TextureFormat::Depth32Float,
wgpu::TextureUsages::empty(),
);
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(SIZE * SIZE * 4),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let color_view = color.create_view(&Default::default());
let depth_view = depth.create_view(&Default::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &color_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
});
sky.draw_disc(&mut pass);
}
encoder.copy_texture_to_buffer(
color.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &read,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(SIZE * 4),
rows_per_image: Some(SIZE),
},
},
color.size(),
);
queue.submit([encoder.finish()]);
read.slice(..)
.map_async(wgpu::MapMode::Read, |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let pixels = read.slice(..).get_mapped_range().unwrap().to_vec();
let at = |x: usize, y: usize| pixels[(y * 64 + x) * 4..(y * 64 + x) * 4 + 4].to_vec();
// Row 0 is the top: the disc, in the sky colour; the bottom row is below the horizon.
let top = at(32, 4);
assert!(
top.iter()
.zip([64u8, 128, 255, 255])
.all(|(&p, w)| p.abs_diff(w) <= 1),
"{top:?}"
);
assert_eq!(at(32, 60), vec![0, 0, 0, 0]);
}
}
+11 -2
View File
@@ -10,8 +10,8 @@
//! second pass, draws the sections whose box was seen; the others' draws have
//! an instance count of 0.
//!
//! The picture stays the one without culling: the boxes (grown by a block,
//! the farthest a block model reaches out of its cell) are drawn front faces
//! The picture stays the one without culling: the boxes around the mesh's
//! geometry (padded by a block) are drawn front faces
//! only, so a fragment is the box's nearest point on its pixel, and the
//! fragment shader runs only where the depth test passes (forced early), so a
//! section is left out only where all of its fragments would fail the depth
@@ -45,6 +45,15 @@ use std::sync::{
const WORDS: u64 = 5 * 4;
/// A tested section's box, around its origin: its cell grown by a block.
pub const SECTION_BOX: [[f32; 3]; 2] = [[-1.0; 3], [17.0; 3]];
/// Mesh bounds already contain `BOUNDS_PAD`; grow them to a block of padding
/// in total, keeping the box's faces off the geometry. Without mesh bounds,
/// keep the section cell grown by a block, as before.
pub fn section_box(bounds: Option<[glam::Vec3; 2]>) -> [[f32; 3]; 2] {
bounds.map_or(SECTION_BOX, |[low, high]| {
let pad = glam::Vec3::splat(1.0 - crate::mesher::SectionMesh::BOUNDS_PAD);
[(low - pad).to_array(), (high + pad).to_array()]
})
}
/// The bit that marks a far tile's slot (`Renderer::tile_cull_slot`): tiles
/// count their slots apart from the sections' resident ones.
pub const TILE: u32 = 1 << 31;
@@ -16,8 +16,8 @@ struct Globals {
// `place`): the first pass's first draw, both passes' draw counts (the
// second's in the high 16 bits), the second pass's first draw. No draws:
// phase 1 drew it, and the test only tells whether it is still in sight.
// Then its box's lowest and highest corner around the origin (a section's:
// -1 and 17, `SECTION_BOX`).
// Then its box's lowest and highest corner around the origin: a section's
// padded mesh bounds, or -1 and 17 (`SECTION_BOX`) without mesh bounds.
struct Test {
data: vec4<u32>,
low: vec4<f32>,
@@ -53,8 +53,8 @@ fn corner(origin: vec3<f32>, low: vec3<f32>, high: vec3<f32>, c: u32) -> vec3<f3
);
}
// Each tested section's or far tile's box, grown by a block (block models
// reach one block out of their cell), drawn after phase 1 against its depth
// Each tested section's or far tile's geometry box, padded by a block,
// drawn after phase 1 against its depth
// with back faces culled: a front face fragment that passes the depth test
// is the box's nearest point on that pixel in front of phase 1's depth, so
// the section may show there. A box failing everywhere would have every
@@ -33,6 +33,9 @@ struct Uniform {
brightness: f32,
mode: u32,
pad: [u32; 2],
hdr_settings: [f32; 4],
hdr_shares: [f32; 4],
hdr_light: [f32; 4],
}
#[repr(C)]
@@ -45,6 +48,8 @@ struct Vertex {
pub(super) struct CustomSky {
pipelines: Vec<wgpu::RenderPipeline>,
written_gain: Option<f32>,
written_debug: bool,
layout: wgpu::BindGroupLayout,
sampler: wgpu::Sampler,
uniform: wgpu::Buffer,
@@ -136,7 +141,10 @@ impl CustomSky {
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Custom sky shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("custom_sky.wgsl").into()),
source: wgpu::ShaderSource::Wgsl(
(include_str!("../hdr_light.wgsl").to_owned() + include_str!("custom_sky.wgsl"))
.into(),
),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Custom sky layout"),
@@ -146,7 +154,11 @@ impl CustomSky {
let attributes = wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x2, 2 => Float32x4];
let pipelines = MODES
.iter()
.map(|&mode| {
.copied()
.map(|mode| (mode, false, false))
.chain((format == super::LINEAR_FRAME).then_some((Blend::Screen, true, false)))
.chain((format == super::LINEAR_FRAME).then_some((Blend::Add, false, true)))
.map(|(mode, written_screen, debug_add)| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Custom sky layer"),
layout: Some(&pipeline_layout),
@@ -174,14 +186,31 @@ impl CustomSky {
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_custom_sky"),
compilation_options: Default::default(),
entry_point: Some(if debug_add {
"fs_custom_sky_screen_light"
} else {
"fs_custom_sky"
}),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[(
"HDR_WRITE_LIGHT",
f64::from(u8::from(format == super::LINEAR_FRAME)),
)],
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format,
// The frame's alpha is HDR output's mark (hdr.wgsl): the sky
// under the layers keeps its own.
blend: Some(wgpu::BlendState {
color: blend(mode),
color: if written_screen {
wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Constant,
..blend(mode)
}
} else {
blend(mode)
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::One,
@@ -215,6 +244,8 @@ impl CustomSky {
});
Self {
pipelines,
written_gain: None,
written_debug: false,
layout,
sampler,
uniform,
@@ -295,7 +326,20 @@ impl CustomSky {
encoder: &mut wgpu::CommandEncoder,
clip: Mat4,
draws: &[Draw],
globals: &super::Globals,
) {
self.written_gain = (globals.hdr_light[3] != 0.0).then(|| {
let mark =
((1.0 - 0.24 * globals.hdr_light[1]).clamp(0.0, 1.0) * 255.0).round() / 255.0;
if globals.hdr_settings[2] > 0.5 && globals.hdr_settings[0] > 1.0 {
(1.0 + (globals.hdr_settings[1] - 1.0) * (1.0 - mark) / 0.24).powf(1.0 / 2.2)
} else {
1.0
}
});
self.written_debug = self.written_gain.is_some()
&& globals.hdr_settings[3] > 0.5
&& globals.hdr_settings[2] > 0.5;
self.frame.clear();
for draw in draws.iter().take(MAX_DRAWS) {
if usize::from(draw.image) >= self.groups.len() {
@@ -307,6 +351,9 @@ impl CustomSky {
brightness: draw.brightness.clamp(0.0, 1.0),
mode: mode as u32,
pad: [0; 2],
hdr_settings: globals.hdr_settings,
hdr_shares: globals.hdr_shares,
hdr_light: globals.hdr_light,
};
let offset = STRIDE * self.frame.len() as u64;
uploads.buffer(encoder, &self.uniform, offset, bytemuck::bytes_of(&uniform));
@@ -323,7 +370,35 @@ impl CustomSky {
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {
pass.set_vertex_buffer(0, self.vertices.slice(..));
for (i, &(image, mode)) in self.frame.iter().enumerate() {
pass.set_pipeline(&self.pipelines[usize::from(mode)]);
let screen_debug = usize::from(mode) == 5 && self.written_debug;
if screen_debug {
// Greyscale debug is not a uniform RGB gain. Attenuate with the original
// source first, then add its converted light, without changing the factor.
pass.set_pipeline(&self.pipelines[4]);
pass.set_bind_group(
0,
&self.groups[usize::from(image)],
&[(STRIDE * i as u64) as u32],
);
pass.draw(0..36, 0..1);
}
let index = if screen_debug {
10
} else if usize::from(mode) == 5 && self.written_gain.is_some() {
9
} else {
usize::from(mode)
};
if let Some(gain) = self.written_gain {
let gain = f64::from(gain);
pass.set_blend_constant(wgpu::Color {
r: gain,
g: gain,
b: gain,
a: 1.0,
});
}
pass.set_pipeline(&self.pipelines[index]);
pass.set_bind_group(
0,
&self.groups[usize::from(image)],
@@ -394,7 +469,10 @@ mod tests {
#[test]
fn the_shader_validates() {
let module = naga::front::wgsl::parse_str(include_str!("custom_sky.wgsl")).unwrap();
let module = naga::front::wgsl::parse_str(
&(include_str!("../hdr_light.wgsl").to_owned() + include_str!("custom_sky.wgsl")),
)
.unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
@@ -413,4 +491,243 @@ mod tests {
assert_eq!(v.position.iter().filter(|c| c.abs() == 1.0).count(), 3);
}
}
#[test]
fn written_custom_sky_modes_keep_factors_and_scale_only_screen_source() {
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
return;
};
let (device, queue) =
pollster::block_on(adapter.request_device(&Default::default())).unwrap();
let source = include_str!("../hdr_light.wgsl").to_owned()
+ include_str!("custom_sky.wgsl")
+ r#"
@vertex fn test_vertex(@builtin(vertex_index) i: u32) -> Out {
let p = vec2(f32((i << 1u) & 2u), f32(i & 2u));
return Out(vec4(p * 2.0 - 1.0, 0.0, 1.0), vec2(0.5), vec4(0.0, 0.0, 1.0, 1.0));
}
"#;
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let sky = CustomSky::new(&device, wgpu::TextureFormat::Rgba16Float);
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&sky.layout)],
..Default::default()
});
let image = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&[204, 102, 51, 128],
);
let image = image.create_view(&Default::default());
let sampler = device.create_sampler(&Default::default());
let target = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&Default::default());
// Independent scalar expectation: a sky mark of 206/255 gives this gamma gain.
let gain = (1.0f32 + 3.0 * (1.0 - 206.0 / 255.0) / 0.24).powf(1.0 / 2.2);
for (mode_index, mode, debug) in MODES
.iter()
.copied()
.enumerate()
.map(|(i, m)| (i, m, false))
.chain([(5, Blend::Screen, true)])
{
let uniform = Uniform {
clip_from_sky: Mat4::IDENTITY.to_cols_array_2d(),
brightness: 0.7,
mode: mode_index as u32,
pad: [0; 2],
hdr_settings: [5.0, 4.0, 1.0, f32::from(u8::from(debug))],
hdr_shares: [0.2, 0.5, 0.6, 1.0],
hdr_light: [0.8, 0.8, 1.0, 1.0],
};
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::bytes_of(&uniform),
usage: wgpu::BufferUsages::UNIFORM,
});
let color = if debug {
blend(Blend::Add)
} else if mode == Blend::Screen {
wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Constant,
..blend(mode)
}
} else {
blend(mode)
};
let pipeline_for = |entry, color| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("test_vertex"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(entry),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[("HDR_WRITE_LIGHT", 1.0)],
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba16Float,
blend: Some(wgpu::BlendState {
color,
alpha: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let pipeline = pipeline_for(
if debug {
"fs_custom_sky_screen_light"
} else {
"fs_custom_sky"
},
color,
);
let attenuate = debug.then(|| pipeline_for("fs_custom_sky", blend(Blend::Burn)));
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &sky.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&image),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 2.0,
g: 2.0,
b: 2.0,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
let g = f64::from(gain);
pass.set_blend_constant(wgpu::Color {
r: g,
g,
b: g,
a: 1.0,
});
pass.set_bind_group(0, &group, &[0]);
if let Some(attenuate) = &attenuate {
pass.set_pipeline(attenuate);
pass.draw(0..3, 0..1);
}
pass.set_pipeline(&pipeline);
pass.draw(0..3, 0..1);
}
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 256,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(256),
rows_per_image: None,
},
},
target.size(),
);
queue.submit([encoder.finish()]);
readback.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let data = readback.get_mapped_range(..).unwrap();
let got = half::f16::from_le_bytes([data[0], data[1]]).to_f32();
let (d, t, k) = (2.0, 0.8, 128.0 / 255.0 * 0.7);
let expected = if debug {
let grey = (0.2126f32 * 0.8f32.powf(2.2)
+ 0.7152 * 0.4f32.powf(2.2)
+ 0.0722 * 0.2f32.powf(2.2))
.powf(1.0 / 2.2);
gain * grey * k + d * (1.0 - t * k)
} else {
match mode {
Blend::Add => d + gain * t * k,
Blend::Subtract => d - gain * t * k,
Blend::Multiply => d * (1.0 + (t - 1.0) * k),
Blend::Dodge => d + d * t * k,
Blend::Burn => d * (1.0 - t * k),
Blend::Screen => gain * t * k + d * (1.0 - t * k),
Blend::Replace => gain * t,
Blend::Overlay => 2.0 * d * (0.5 + (t - 0.5) * k),
Blend::Alpha => gain * t * k + d * (1.0 - k),
}
};
assert!(
(got - expected).abs() < 0.004,
"{mode:?} debug {debug}: {got} expected {expected}"
);
}
eprintln!("HDR custom sky GPU ran all nine modes and debug Screen over above-white light");
}
}
@@ -8,6 +8,10 @@ struct Layer {
brightness: f32,
// horizon_optifine::sky::Blend, in gfx/custom_sky.rs's MODES order.
mode: u32,
pad: vec2<u32>,
hdr_settings: vec4<f32>,
hdr_shares: vec4<f32>,
hdr_light: vec4<f32>,
}
@group(0) @binding(0) var<uniform> layer: Layer;
@group(0) @binding(1) var sky_texture: texture_2d<f32>;
@@ -42,20 +46,34 @@ const REPLACE: u32 = 6u;
const OVERLAY: u32 = 7u;
const ALPHA: u32 = 8u;
@fragment fn fs_custom_sky(in: Out) -> @location(0) vec4<f32> {
fn custom_sky_color(in: Out) -> vec4<f32> {
let half = 0.5 / vec2<f32>(textureDimensions(sky_texture));
let uv = clamp(in.uv, in.cell.xy + half, in.cell.zw - half);
let t = textureSample(sky_texture, sky_sampler, uv);
let k = t.a * layer.brightness;
var color = t.rgb;
if HDR_WRITE_LIGHT && layer.hdr_light.w != 0.0 &&
(layer.mode == ADD || layer.mode == SUBTRACT || layer.mode == REPLACE || layer.mode == ALPHA) {
color = hdr_written(color, 1.0 - 0.24 * layer.hdr_light.y, layer.hdr_settings, layer.hdr_shares);
}
switch layer.mode {
// dst * src: white leaves the sky alone.
case MULTIPLY: { return vec4(mix(vec3(1.0), t.rgb, k), 1.0); }
// 2 * dst * src: grey leaves it alone.
case OVERLAY: { return vec4(mix(vec3(0.5), t.rgb, k), 1.0); }
case REPLACE: { return vec4(t.rgb, 1.0); }
case REPLACE: { return vec4(color, 1.0); }
// mix(dst, src, alpha).
case ALPHA: { return vec4(t.rgb, k); }
case ALPHA: { return vec4(color, k); }
// add, subtract, dodge, burn, screen: the layer premultiplied, black leaves it alone.
default: { return vec4(t.rgb * k, 1.0); }
default: { return vec4(color * k, 1.0); }
}
}
@fragment fn fs_custom_sky(in: Out) -> @location(0) vec4<f32> {
return custom_sky_color(in);
}
@fragment fn fs_custom_sky_screen_light(in: Out) -> @location(0) vec4<f32> {
let color = custom_sky_color(in);
return vec4(hdr_written(color.rgb, 1.0 - 0.24 * layer.hdr_light.y, layer.hdr_settings, layer.hdr_shares), color.a);
}
+17 -2
View File
@@ -106,6 +106,8 @@ pub struct Flat {
phase2_calls: wgpu::Buffer,
phase2_call_capacity: u64,
phase2_call_data: Vec<[u32; 5]>,
/// GPU culling's phase 2 uses indirect draws; flat draws without culling do not.
indirect_execution: bool,
/// The copy of phase 2's draws, and its ranges.
phase2_group: Option<(wgpu::BindGroup, u32)>,
/// The layout of a page's bind group 1 (shader packs' terrain pipelines share it).
@@ -365,6 +367,7 @@ impl Flat {
terrain_layout: &wgpu::BindGroupLayout,
page_vertices: u64,
min_sections: usize,
indirect_execution: bool,
pipeline: impl Fn(
&wgpu::PipelineLayout,
&str,
@@ -489,10 +492,16 @@ impl Flat {
device,
"Flat section draw calls, phase 2",
20,
wgpu::BufferUsages::INDIRECT | storage_usage,
storage_usage
| if indirect_execution {
wgpu::BufferUsages::INDIRECT
} else {
wgpu::BufferUsages::empty()
},
),
phase2_call_capacity: 1,
phase2_call_data: Vec::new(),
indirect_execution,
phase2_group: None,
draw_layout,
blocks_per_page: page_vertices.div_ceil(GRAIN),
@@ -645,6 +654,7 @@ impl Flat {
timing: Option<&mut super::pack_timing::PassTiming>,
) -> bool {
self.phase2_group = None;
let phase2 = phase2.filter(|_| self.indirect_execution);
let phase1_draws = if phase2.is_some() {
phase1_draws
} else {
@@ -753,7 +763,12 @@ impl Flat {
device,
"Flat section draw calls, phase 2",
self.phase2_call_capacity * 20,
wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::STORAGE,
wgpu::BufferUsages::STORAGE
| if self.indirect_execution {
wgpu::BufferUsages::INDIRECT
} else {
wgpu::BufferUsages::empty()
},
);
}
if phase2_calls > 0 {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,65 @@
// The light of colour `f` under the world's mark `a` (the alpha the world left, hdr_mark) where
// the world `shows`, else the colour clipped at white; and whether a light source lifted it.
// `eased` for the last pass, which eases it into the peak itself; the layered frame leaves that
// to the tone curve (fs_tonemap).
struct ReferenceLit {
light: vec3<f32>,
lifted: bool,
};
fn reference_lit(f: vec3<f32>, a: f32, shows: bool, eased: bool) -> ReferenceLit {
var lifted = false;
// Light over 1 (a float frame's) shows only where the world does and carries
// no mark (alpha 1), up to the peak: light written as light. Marked pixels clip
// at white before their lift, as on a unorm frame, so light sources, the sun and
// HDR lighting look as they do there; so do the HUD, menus and HDR Lighting off.
let c = select(min(f, vec3(1.0)), f, shows && a == 1.0);
// Gamma 2.2, as SDR displays and the compositors' SDR paths decode it.
var light = pow(c, vec3(2.2));
// HDR lighting: alpha between 0.76 and 1 is how much of it the surface gets. Vanilla's
// light is albedo times lightmap, so this is the lightmap going past 1. It eases into the
// peak from 60% of it, so bright textures keep their detail. Unmarked light (alpha 1)
// gets no gain and no knee: the clamp to the peak below is all it needs here.
if shows && a >= 0.75 && a < 1.0 {
let top = max(light.r, max(light.g, light.b));
let gain = 1.0 + (params.scene - 1.0) * (1.0 - a) / 0.24;
let v = top * gain;
let knee = max(0.6 * params.peak, 1.0);
var out = v;
if eased && v > knee && params.peak > knee {
out = knee + (params.peak - knee) * (1.0 - exp(-(v - knee) / (params.peak - knee)));
}
light *= select(gain, out / max(top, 1e-4), eased && v > knee);
}
// The world's alpha is below 0.75 on light sources, the sun and the moon
// (terrain.wgsl, entity.wgsl): its band of 0.175 is the tier, the lower the
// brighter, and where in the band how much (hdr_mark).
if shows && a < 0.75 {
let band = u32(clamp(floor((a + 0.005) / 0.175), 0.0, 3.0));
let tier = 3u - band;
let lift = 1.0 - clamp((a - 0.175 * f32(band)) / 0.165, 0.0, 1.0);
if lift > 0.0 {
let top = max(light.r, max(light.g, light.b));
var gain = 1.0 + (params.peak - 1.0) * params.share[tier] * lift;
if eased {
gain = min(gain, params.peak / max(top, 1e-4));
}
light *= max(gain, 1.0);
lifted = true;
}
}
// HORIZON_HDR_DEBUG=1: what isn't lifted turns grey, what is keeps its
// colour with a magenta tint, so a lift shows on any colour.
if params.debug > 0.5 && params.world > 0.5 {
if lifted {
light *= vec3(1.0, 0.6, 1.0);
} else {
light = vec3(dot(light, vec3(0.2126, 0.7152, 0.0722)));
}
}
if eased {
light = min(light, vec3(params.peak));
}
return ReferenceLit(light, lifted);
}
@@ -0,0 +1,818 @@
use super::{
Hdr, Output,
tests::{gpu, texel},
};
use wgpu::TextureFormat as F;
use wgpu::util::DeviceExt;
const TERRAIN_VERTEX: &str = r#"
override TEST_TIER: u32 = 0u;
override TEST_OVERLAY: u32 = 0u;
@vertex fn test_vertex(@builtin(vertex_index) i: u32) -> TerrainWire {
let p = vec2(f32((i << 1u) & 2u), f32(i & 2u));
var o: TerrainOut;
o.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
o.uv = vec2(0.5);
o.local = vec3(p.x, 0.0, p.y);
o.color = vec4(0.8, 0.9, 0.7, select(1.0, 0.5, globals.misc.z > 0.5));
o.scene = vec2(15.0);
o.spherical = globals.misc.x;
o.cylindrical = globals.misc.x;
o.visibility = globals.misc.y;
o.emission = TEST_TIER;
o.emissive_layer = select(0xffffffffu, 1u, TEST_OVERLAY != 0u);
return to_wire(o);
}
"#;
const ENTITY_VERTEX: &str = r#"
override TEST_TIER: u32 = 0u;
override TEST_OVERLAY: u32 = 0u;
@vertex fn test_vertex(@builtin(vertex_index) i: u32) -> Out {
let p = vec2(f32((i << 1u) & 2u), f32(i & 2u));
var o: Out;
o.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
o.uv = vec2(0.5);
o.color = vec4(0.8, 0.9, 0.7, 1.0);
o.back_color = o.color;
o.light_color = vec4(0.7, 0.8, 0.9, 1.0);
o.overlay_color = vec4(1.0);
o.scene = 0.8;
o.tier = TEST_TIER;
o.overlay = TEST_OVERLAY;
o.wrap = vec2(0.0, 1.0);
o.proj = vec4(0.4, 0.6, 0.0, 1.0);
o.fog_distance = vec2(globals.misc.x);
return o;
}
"#;
struct Draw<'a> {
device: &'a wgpu::Device,
queue: &'a wgpu::Queue,
terrain: bool,
shader: wgpu::ShaderModule,
layout: wgpu::PipelineLayout,
bindings: wgpu::BindGroupLayout,
group: wgpu::BindGroup,
}
impl<'a> Draw<'a> {
fn render_oit(
&self,
hdr: &mut Hdr,
kind: &str,
tier: u32,
overlay: u32,
written: bool,
) -> [f32; 4] {
use super::super::oit::{Stage, stage_targets};
let source = if self.terrain {
super::super::terrain_shader()
+ include_str!("../oit.wgsl")
+ include_str!("../oit_world.wgsl")
+ TERRAIN_VERTEX
} else {
super::super::entity_shader()
+ include_str!("../oit.wgsl")
+ include_str!("../oit_features.wgsl")
+ include_str!("../oit_clouds.wgsl")
+ ENTITY_VERTEX
}
.replace(
"o.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0)",
"o.clip = vec4(p * 2.0 - 1.0, 0.5, 1.0)",
);
let shader = self
.device
.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("actual OIT fragments"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let screen_shader = self
.device
.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(
(super::super::terrain_shader()
+ include_str!("../oit.wgsl")
+ include_str!("../oit_world.wgsl")
+ TERRAIN_VERTEX)
.into(),
),
});
let make = |format| {
self.device
.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default())
};
let bounds = make(F::Rgba32Float);
let depth = make(F::Depth32Float);
let coeff = [make(F::Rgba16Float), make(F::Rgba16Float)];
let accumulated = make(F::Rgba16Float);
let uniform = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&[0.0_f32, 1.0, 0.0, 0.0]),
usage: wgpu::BufferUsages::UNIFORM,
});
let frame = hdr.frame(self.device, [1, 1]);
let view = frame.create_view(&Default::default());
let mut encoder = self.device.create_command_encoder(&Default::default());
super::tests::fill(&mut encoder, &frame, [2.5, 1.8, 0.9, 1.0]);
let constants = [
("HDR_WRITE_LIGHT", f64::from(u8::from(written))),
("TEST_TIER", f64::from(tier)),
("TEST_OVERLAY", f64::from(overlay)),
];
for stage in 0..4 {
let textures: Vec<_> = match stage {
0 => vec![],
1 => vec![&bounds],
2 => vec![&bounds, &coeff[0], &coeff[1]],
_ => vec![&bounds, &coeff[0], &coeff[1], &accumulated],
};
let mut entries = vec![wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}];
entries.extend(
textures
.iter()
.enumerate()
.map(|(i, _)| wgpu::BindGroupLayoutEntry {
binding: i as u32 + 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}),
);
let bindings = self
.device
.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &entries,
});
let mut resources = vec![wgpu::BindGroupEntry {
binding: 0,
resource: uniform.as_entire_binding(),
}];
resources.extend(
textures
.iter()
.enumerate()
.map(|(i, t)| wgpu::BindGroupEntry {
binding: i as u32 + 1,
resource: wgpu::BindingResource::TextureView(t),
}),
);
let group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bindings,
entries: &resources,
});
let layout = self
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&self.bindings), None, Some(&bindings)],
..Default::default()
});
let suffix = ["bounds", "transmittance", "accumulate", "composite"][stage];
let entry = if stage == 3 {
"fs_oit_composite".to_owned()
} else if self.terrain {
format!("fs_oit_{suffix}")
} else {
format!("fs_oit_{kind}_{suffix}")
};
let targets = if stage == 3 {
vec![Some(wgpu::ColorTargetState {
format: F::Rgba16Float,
blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})]
} else {
stage_targets([Stage::DepthBounds, Stage::Transmittance, Stage::Accumulate][stage])
};
let shader = if stage == 3 { &screen_shader } else { &shader };
let pipeline = self
.device
.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(&entry),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: shader,
entry_point: Some("test_vertex"),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &constants,
..Default::default()
},
buffers: &[],
},
primitive: Default::default(),
depth_stencil: (stage == 3).then_some(wgpu::DepthStencilState {
format: F::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::Always),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: shader,
entry_point: Some(&entry),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &constants,
..Default::default()
},
targets: &targets,
}),
multiview_mask: None,
cache: None,
});
let outputs = match stage {
0 => vec![&bounds],
1 => vec![&coeff[0], &coeff[1]],
2 => vec![&accumulated],
_ => vec![&view],
};
let attachments: Vec<_> = outputs
.iter()
.map(|v| {
Some(wgpu::RenderPassColorAttachment {
view: v,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: if stage == 3 {
wgpu::LoadOp::Load
} else {
wgpu::LoadOp::Clear(if stage == 0 {
wgpu::Color {
r: -(f32::MAX as f64),
g: 0.0,
b: 0.0,
a: 0.0,
}
} else {
wgpu::Color::TRANSPARENT
})
},
store: wgpu::StoreOp::Store,
},
})
})
.collect();
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &attachments,
depth_stencil_attachment: (stage == 3).then_some(
wgpu::RenderPassDepthStencilAttachment {
view: &depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
},
),
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &self.group, &[]);
pass.set_bind_group(2, &group, &[]);
pass.draw(0..3, 0..1);
}
texel(self.device, self.queue, encoder, &frame)
}
fn new(
device: &'a wgpu::Device,
queue: &'a wgpu::Queue,
terrain: bool,
globals: &super::super::Globals,
alpha: u8,
) -> Self {
let source = if terrain {
super::super::terrain_shader() + TERRAIN_VERTEX
} else {
super::super::entity_shader() + ENTITY_VERTEX
};
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("actual HDR draw shader"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let mut entries = vec![];
for binding in 0..if terrain { 13 } else { 8 } {
let sampler = if terrain {
binding == 2 || binding == 4
} else {
binding == 2 || binding == 4 || binding == 6
};
let ty = if binding == 0 {
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
}
} else if sampler {
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)
} else {
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
multisampled: false,
view_dimension: if terrain && binding != 3 && binding != 12 {
wgpu::TextureViewDimension::D2Array
} else {
wgpu::TextureViewDimension::D2
},
}
};
entries.push(wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty,
count: None,
});
}
let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &entries,
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&bindings)],
..Default::default()
});
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::bytes_of(globals),
usage: wgpu::BufferUsages::UNIFORM,
});
let texture = |layers, data: &[u8]| {
device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: layers,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: F::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
data,
)
};
let array = texture(2, &[200, 100, 50, alpha, 240, 210, 80, 128]);
let array = array.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
let image = texture(1, &[200, 100, 50, alpha]).create_view(&Default::default());
let threshold = texture(1, &[0, 0, 0, 0]).create_view(&Default::default());
let sampler = device.create_sampler(&Default::default());
let resources: Vec<_> = entries
.iter()
.map(|entry| wgpu::BindGroupEntry {
binding: entry.binding,
resource: match entry.ty {
wgpu::BindingType::Buffer { .. } => uniform.as_entire_binding(),
wgpu::BindingType::Sampler(_) => wgpu::BindingResource::Sampler(&sampler),
wgpu::BindingType::Texture {
view_dimension: wgpu::TextureViewDimension::D2Array,
..
} => wgpu::BindingResource::TextureView(&array),
_ => wgpu::BindingResource::TextureView(if entry.binding == 12 {
&threshold
} else {
&image
}),
},
})
.collect();
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bindings,
entries: &resources,
});
Self {
device,
queue,
terrain,
shader,
layout,
bindings,
group,
}
}
fn render(
&self,
hdr: &mut Hdr,
written: bool,
entry: &str,
tier: u32,
overlay: u32,
background: [f64; 4],
) -> [f32; 4] {
let constants = [
("HDR_WRITE_LIGHT", f64::from(u8::from(written))),
("TEST_TIER", f64::from(tier)),
("TEST_OVERLAY", f64::from(overlay)),
];
let pipeline = |entry, mark| {
self.device
.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&self.layout),
vertex: wgpu::VertexState {
module: &self.shader,
entry_point: Some("test_vertex"),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &constants,
..Default::default()
},
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &self.shader,
entry_point: Some(entry),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &constants,
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format: F::Rgba16Float,
blend: Some(if mark || (self.terrain && entry != "fs_translucent") {
wgpu::BlendState::REPLACE
} else {
wgpu::BlendState::ALPHA_BLENDING
}),
write_mask: if mark {
wgpu::ColorWrites::ALPHA
} else {
wgpu::ColorWrites::ALL
},
})],
}),
multiview_mask: None,
cache: None,
})
};
let color = pipeline(entry, false);
let mark = (!self.terrain && !written && entry == "fs_entity").then(|| {
pipeline(
if overlay == 4 {
"fs_hdr_cloud_mark"
} else {
"fs_hdr_mark"
},
true,
)
});
let frame = hdr.frame(self.device, [1, 1]);
let view = frame.create_view(&Default::default());
let mut encoder = self.device.create_command_encoder(&Default::default());
{
let [r, g, b, a] = background;
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r, g, b, a }),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
pass.set_bind_group(0, &self.group, &[]);
pass.set_pipeline(&color);
pass.draw(0..3, 0..1);
if let Some(mark) = &mark {
pass.set_pipeline(mark);
pass.draw(0..3, 0..1);
}
}
if !written {
hdr.begin(self.queue, true);
hdr.resolve(&mut encoder, None);
}
texel(self.device, self.queue, encoder, &frame)
}
}
#[test]
fn actual_opaque_writers_match_marks_then_resolve() {
let Some((device, queue)) = gpu() else {
eprintln!("HDR draw GPU unavailable");
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
(hdr.paper_white, hdr.peak) = (203.0, 1000.0);
let (settings, shares) = hdr.draw_params(true);
let mut count = 0;
for fog in [0.0, 0.5, 1.0] {
for visibility in [1.0, 0.4] {
let globals = super::super::Globals {
fog_color: [0.2, 0.3, 0.4, 1.0],
fog: [0.0, 1.0, 0.0, 1.0],
fog_ends: [100.0, 100.0, 0.0, 0.0],
misc: [fog, visibility, 0.0, 0.0],
filtering: [0.0, 1.0, 0.0, 0.0],
hdr_windows: hdr.windows(),
hdr_light: [0.8, 0.8, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
..bytemuck::Zeroable::zeroed()
};
for terrain in [true, false] {
let draw = Draw::new(&device, &queue, terrain, &globals, 255);
for tier in 0..=4 {
for overlay in if terrain {
vec![0, 1]
} else {
vec![0, 6, 9, 10, 38]
} {
let entries = if terrain {
vec!["fs_opaque", "fs_solid"]
} else {
vec!["fs_entity"]
};
for entry in entries {
let marked =
draw.render(&mut hdr, false, entry, tier, overlay, [0.0; 4]);
let written =
draw.render(&mut hdr, true, entry, tier, overlay, [0.0; 4]);
// The marked path stores half floats before conversion; the written
// one stores after it. Allow two half-float ULPs in gamma light.
for i in 0..3 {
assert!(
(marked[i] - written[i]).abs() <= 0.002 * marked[i].max(1.0),
"{terrain} {entry} tier {tier} overlay {overlay} fog {fog} visibility {visibility}: {marked:?} {written:?}"
);
}
assert_eq!(written[3], 1.0);
count += 1;
}
}
}
}
}
}
eprintln!("HDR actual draw GPU ran {count} opaque comparisons");
}
#[test]
fn actual_translucent_writers_blend_their_own_light() {
let Some((device, queue)) = gpu() else {
eprintln!("HDR blend GPU unavailable");
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
fog_ends: [100.0, 100.0, 0.0, 0.0],
misc: [0.0, 1.0, 0.0, 0.0],
filtering: [0.0, 1.0, 0.0, 0.0],
hdr_windows: hdr.windows(),
hdr_light: [0.8, 0.8, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
..bytemuck::Zeroable::zeroed()
};
// Texel alpha 100 is clear glass's kind of texel, below the 0.6 the marked frame's
// `fs_translucent_mark` skips: written, it still gets its own light.
for (terrain, entry, overlay, tier, tint_alpha, texel_alpha) in [
(true, "fs_translucent", 0, 0, 1.0, 180),
(true, "fs_translucent", 0, 0, 0.5, 180),
(true, "fs_translucent", 0, 0, 1.0, 100),
(false, "fs_entity", 0, 3, 1.0, 180),
(false, "fs_entity", 4, 0, 1.0, 180),
] {
let mut globals = globals;
globals.misc[2] = if tint_alpha < 1.0 { 1.0 } else { 0.0 };
let draw = Draw::new(&device, &queue, terrain, &globals, texel_alpha);
let src = draw.render(&mut hdr, true, entry, tier, overlay, [0.0; 4]);
let dst = [2.5, 1.8, 0.9, 1.0];
let got = draw.render(&mut hdr, true, entry, tier, overlay, dst);
let alpha = f32::from(texel_alpha) / 255.0 * tint_alpha;
if terrain {
// Full block light leaves mark 194/255 whatever the texel's alpha, even when
// vertex coverage is halved.
let gain = (1.0 + (settings[1] - 1.0) * (1.0 - 194.0 / 255.0) / 0.24).powf(1.0 / 2.2);
let expected = 200.0 / 255.0 * 0.8 * gain * alpha;
assert!(
(src[0] - expected).abs() < 0.002,
"coverage {tint_alpha}: {src:?}, expected {expected}"
);
}
for i in 0..3 {
let want = src[i] + dst[i] as f32 * (1.0 - alpha);
assert!(
(got[i] - want).abs() < 0.003,
"{entry} {overlay}: {got:?} expected {want}"
);
}
assert!(got[0] > 1.0);
}
eprintln!("HDR actual blend GPU ran terrain, particle and cloud equations");
}
#[test]
fn unmarked_entity_users_keep_their_source_gain() {
let Some((device, queue)) = gpu() else {
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
fog_ends: [100.0, 100.0, 0.0, 0.0],
hdr_windows: hdr.windows(),
hdr_light: [1.0, 1.0, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
..bytemuck::Zeroable::zeroed()
};
let draw = Draw::new(&device, &queue, false, &globals, 255);
for (entry, overlay) in [
("fs_entity_unmarked", 0),
("fs_entity_shadow", 0),
("fs_energy_swirl", 0),
("fs_entity", 11),
("fs_entity", 12),
] {
let raw = draw.render(&mut hdr, true, entry, 0, overlay, [0.0; 4]);
let mut hdr_off = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
hdr_off.look = false;
let legacy = draw.render(&mut hdr_off, false, entry, 0, overlay, [0.0; 4]);
for i in 0..3 {
assert!(
(raw[i] - legacy[i]).abs() < 0.001,
"{entry} {overlay}: {raw:?} {legacy:?}"
);
}
}
}
#[test]
fn additive_texels_below_the_mark_cutoff_keep_their_gain() {
let Some((device, queue)) = gpu() else {
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
hdr_windows: hdr.windows(),
hdr_light: [1.0, 1.0, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
..bytemuck::Zeroable::zeroed()
};
let draw = Draw::new(&device, &queue, false, &globals, 16);
let background = [0.0, 0.0, 0.0, 1.0];
let marked = draw.render(&mut hdr, false, "fs_celestial", 4, 0, background);
let written = draw.render(&mut hdr, true, "fs_celestial", 4, 0, background);
// The old mark draw discards this texel; source alpha still contributes its colour.
let red = (200.0 / 255.0) * 0.8 * 0.7 * (16.0 / 255.0);
assert!(
(written[0] - red).abs() < 0.0001,
"{written:?}: expected {red}"
);
for i in 0..3 {
assert!(
(written[i] - marked[i]).abs() < 0.0001,
"{written:?} {marked:?}"
);
}
}
fn check_oit_writer(terrain: bool, kind: &str, overlay: u32, tier: u32, alphas: &[u8]) {
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
eprintln!("OIT GPU unavailable");
return;
};
if !adapter
.features()
.contains(wgpu::Features::FLOAT32_BLENDABLE)
{
eprintln!("OIT unsupported on {:?}", adapter.get_info());
return;
}
eprintln!(
"OIT GPU {:?}: {kind}, alphas {alphas:?}",
adapter.get_info()
);
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_features: wgpu::Features::FLOAT32_BLENDABLE,
..Default::default()
}))
.unwrap();
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
fog_ends: [100.0, 100.0, 0.0, 0.0],
misc: [0.0, 1.0, 0.0, 0.0],
filtering: [0.0, 1.0, 0.0, 0.0],
hdr_windows: hdr.windows(),
hdr_light: [0.8, 0.8, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
..bytemuck::Zeroable::zeroed()
};
for &alpha in alphas {
let draw = Draw::new(&device, &queue, terrain, &globals, alpha);
let got = draw.render_oit(&mut hdr, kind, tier, overlay, true);
let unconverted = draw.render_oit(&mut hdr, kind, tier, overlay, false);
let entry = if terrain {
"fs_translucent"
} else if kind == "lightning" {
"fs_celestial"
} else {
"fs_entity"
};
let mut expected = draw.render(
&mut hdr,
true,
entry,
tier,
overlay,
if kind == "lightning" {
[0.0; 4]
} else {
[2.5, 1.8, 0.9, 1.0]
},
);
if kind == "lightning" {
for (c, background) in expected[..3].iter_mut().zip([2.5, 1.8, 0.9]) {
*c += background;
}
}
for i in 0..3 {
assert!(
(got[i] - expected[i]).abs() < 0.006,
"{kind} alpha {alpha}: {got:?} expected {expected:?}"
);
}
assert_eq!(got[3], 1.0);
assert!(got[0] > 1.0, "OIT clipped light: {got:?}");
assert!(
(got[0] - unconverted[0]).abs() > 0.01,
"test must distinguish missing conversion: {got:?} {unconverted:?}"
);
}
}
#[test]
fn actual_oit_terrain_writes_its_own_light_including_clear_glass() {
check_oit_writer(true, "terrain", 0, 0, &[180, 100]);
}
#[test]
fn actual_oit_particle_writes_its_own_light() {
check_oit_writer(false, "entity", 0, 3, &[180]);
}
#[test]
fn actual_oit_cloud_writes_its_own_light() {
check_oit_writer(false, "cloud", 4, 0, &[180]);
}
#[test]
fn actual_oit_additive_adds_converted_light_without_coverage() {
check_oit_writer(false, "lightning", 0, 4, &[180]);
}
@@ -0,0 +1,335 @@
//! A held world (`WorldHold`, the native hook `native_world_hold`): the terrain goes on being
//! drawn as it stands while what changes under it is meshed, and all of it takes its place on
//! one frame. A section already on screen that is meshed again is uploaded to the arena as ever,
//! over as many frames as its mesh takes to come, but waits beside the mesh drawn (`Hold`);
//! letting go only swaps which of the two is drawn, with nothing left to upload. Sections not on
//! screen yet (terrain streaming in) are not held.
//!
//! Both meshes of a waiting section are in memory, so a hold costs up to what the changed land's
//! new meshes come to. It is bounded, and each bound lets go at once rather than losing anything:
//! `MAX_BYTES` of waiting meshes, `MAX_HOLD` of time, and the arena running out
//! (`Renderer::upload`). It never outlives what asked for it: the mods are asked every frame,
//! and the sections' being cleared (the world left, another dimension) drops what waits. A hold
//! that ended by itself (spent) stays ended until no mod has asked for a frame.
use super::SectionKey;
use crate::fast_hash::{FxHashMap, FxHashSet};
use std::time::{Duration, Instant};
/// The longest a hold lasts.
pub(super) const MAX_HOLD: Duration = Duration::from_secs(30);
/// The most bytes of new meshes that wait.
pub(super) const MAX_BYTES: u64 = 1 << 30;
/// The most circles a hold is kept to (`WorldHold::hold_within`).
pub const MAX_AREAS: usize = 64;
/// What the mods ask of the terrain's picture this frame (`native_world_hold`): nothing, all of
/// it held, or only the sections inside some circles. Several mods add up: one holding all of it
/// holds all of it, and circles join.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WorldHold {
all: bool,
within: Vec<[f64; 3]>,
}
impl WorldHold {
/// Hold the whole world's terrain as it is drawn, this frame.
pub fn hold(&mut self) {
self.all = true;
}
/// Hold the sections whose middle lies within `radius` blocks of (`x`, `z`), this frame. A
/// circle that isn't finite or has a negative radius is left out, as are those past
/// `MAX_AREAS`.
pub fn hold_within(&mut self, x: f64, z: f64, radius: f64) {
let good = x.is_finite() && z.is_finite() && radius.is_finite() && radius >= 0.0;
if good && self.within.len() < MAX_AREAS {
self.within.push([x, z, radius]);
}
}
/// Whether anything is held.
pub fn is_held(&self) -> bool {
self.all || !self.within.is_empty()
}
/// Whether section `key` is in what is held: all of the world, or a circle its middle lies in.
pub fn covers(&self, key: SectionKey) -> bool {
if self.all {
return true;
}
let (x, z) = (f64::from(key.0) * 16.0 + 8.0, f64::from(key.2) * 16.0 + 8.0);
self.within
.iter()
.any(|&[cx, cz, r]| (x - cx).powi(2) + (z - cz).powi(2) <= r * r)
}
}
/// What a frame's ask means for the sections waiting.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Release {
/// They go on waiting.
None,
/// Those the hold no longer covers take their place.
Outside,
/// All of them take their place.
All,
}
/// A section waiting behind the hold and the bytes its new mesh takes.
struct Waiting<S> {
section: S,
bytes: u64,
}
/// The renderer's side of a hold: whether it is on, what it covers, and the sections waiting.
pub(super) struct Hold<S> {
ask: WorldHold,
since: Option<Instant>,
spent: bool,
waiting: FxHashMap<SectionKey, Waiting<S>>,
bytes: u64,
}
impl<S> Default for Hold<S> {
fn default() -> Self {
Self {
ask: WorldHold::default(),
since: None,
spent: false,
waiting: FxHashMap::default(),
bytes: 0,
}
}
}
impl<S> Hold<S> {
/// Whether a new mesh of section `key` waits.
pub fn holds(&self, key: SectionKey) -> bool {
self.since.is_some() && !self.spent && self.ask.covers(key)
}
pub fn is_empty(&self) -> bool {
self.waiting.is_empty()
}
pub fn bytes(&self) -> u64 {
self.bytes
}
/// A frame's ask, at `now`.
pub fn ask(&mut self, ask: &WorldHold, now: Instant) -> Release {
if !ask.is_held() {
let was = self.since.is_some();
(self.since, self.spent) = (None, false);
self.ask = WorldHold::default();
return if was && !self.waiting.is_empty() {
Release::All
} else {
Release::None
};
}
if self.spent {
return Release::None;
}
let since = *self.since.get_or_insert(now);
if now.saturating_duration_since(since) >= MAX_HOLD {
log::warn!(
"Horizon: a mod held the world for {} s: let go",
MAX_HOLD.as_secs()
);
self.spend();
return Release::All;
}
if *ask == self.ask {
return Release::None;
}
// (fewer circles or smaller: some of what waits is let go; more: nothing waits that didn't)
self.ask.clone_from(ask);
if self.waiting.is_empty() {
Release::None
} else {
Release::Outside
}
}
/// Ended by itself: nothing waits from now on, until no mod has asked for a frame.
/// What waited is the caller's to place (`take_all`) or drop.
pub fn spend(&mut self) {
self.spent = self.since.is_some();
}
/// Section `key`'s new mesh waits: the one that waited before for it comes back, to free.
/// The bool is whether what waits is now too much (`MAX_BYTES`).
pub fn wait(&mut self, key: SectionKey, section: S, bytes: u64) -> (Option<S>, bool) {
let old = self.take(key);
self.bytes += bytes;
self.waiting.insert(key, Waiting { section, bytes });
(old, self.bytes > MAX_BYTES)
}
/// Section `key`'s waiting mesh, no longer waiting.
pub fn take(&mut self, key: SectionKey) -> Option<S> {
if self.waiting.is_empty() {
return None;
}
let w = self.waiting.remove(&key)?;
self.bytes -= w.bytes;
Some(w.section)
}
/// Everything waiting, no longer waiting.
pub fn take_all(&mut self) -> Vec<(SectionKey, S)> {
self.bytes = 0;
self.waiting.drain().map(|(k, w)| (k, w.section)).collect()
}
/// What waits that the hold no longer covers.
pub fn take_outside(&mut self) -> Vec<(SectionKey, S)> {
let ask = &self.ask;
let all = self.since.is_none() || self.spent;
let out: Vec<_> = self
.waiting
.extract_if(|&k, _| all || !ask.covers(k))
.collect();
self.bytes -= out.iter().map(|(_, w)| w.bytes).sum::<u64>();
out.into_iter().map(|(k, w)| (k, w.section)).collect()
}
/// What waits in these columns, which are going.
pub fn take_columns(&mut self, columns: &FxHashSet<(i32, i32)>) -> Vec<S> {
if self.waiting.is_empty() {
return Vec::new();
}
let out: Vec<_> = self
.waiting
.extract_if(|k, _| columns.contains(&(k.0, k.2)))
.collect();
self.bytes -= out.iter().map(|(_, w)| w.bytes).sum::<u64>();
out.into_iter().map(|(_, w)| w.section).collect()
}
/// The sections are all gone: what waits goes with them and the hold is spent.
pub fn clear(&mut self) {
self.waiting.clear();
self.bytes = 0;
self.spend();
}
pub fn sections(&self) -> impl Iterator<Item = &S> {
self.waiting.values().map(|w| &w.section)
}
pub fn sections_mut(&mut self) -> impl Iterator<Item = &mut S> {
self.waiting.values_mut().map(|w| &mut w.section)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn all() -> WorldHold {
let mut h = WorldHold::default();
h.hold();
h
}
fn within(circles: &[[f64; 3]]) -> WorldHold {
let mut h = WorldHold::default();
for &[x, z, r] in circles {
h.hold_within(x, z, r);
}
h
}
#[test]
fn a_hold_covers_sections_by_their_middle() {
assert!(all().covers((900, 0, -900)));
assert!(!WorldHold::default().covers((0, 0, 0)));
assert!(within(&[[8.0, 8.0, 1.0]]).covers((0, 3, 0)));
assert!(!within(&[[0.0, 0.0, 11.0]]).covers((0, 3, 0)));
assert!(within(&[[0.0, 0.0, 12.0]]).covers((0, 3, 0)));
assert!(within(&[[1000.0, 0.0, 1.0], [24.0, 8.0, 0.5]]).covers((1, 0, 0)));
assert!(within(&[[-8.0, -8.0, 0.0]]).covers((-1, 0, -1)));
}
#[test]
fn bad_circles_are_left_out_and_there_are_at_most_max_areas() {
let h = within(&[
[f64::NAN, 0.0, 5.0],
[0.0, f64::INFINITY, 5.0],
[0.0, 0.0, -1.0],
[0.0, 0.0, f64::INFINITY],
]);
assert!(!h.is_held());
let mut many = WorldHold::default();
for i in 0..MAX_AREAS + 10 {
many.hold_within(i as f64 * 100.0, 0.0, 1.0);
}
assert_eq!(many.within.len(), MAX_AREAS);
// (several mods: all of it from one holds all of it)
many.hold();
assert!(many.covers((-5000, 0, 5000)));
}
#[test]
fn a_hold_starts_and_lets_go_when_no_one_asks() {
let (mut g, t) = (Hold::<u32>::default(), Instant::now());
assert_eq!(g.ask(&WorldHold::default(), t), Release::None);
assert!(!g.holds((0, 0, 0)));
assert_eq!(g.ask(&all(), t), Release::None);
assert!(g.holds((0, 0, 0)));
assert_eq!(g.ask(&all(), t + Duration::from_secs(5)), Release::None);
// (nothing waited: nothing to place)
assert_eq!(g.ask(&WorldHold::default(), t), Release::None);
g.ask(&all(), t);
g.wait((0, 0, 0), 7, 100);
assert_eq!(g.ask(&WorldHold::default(), t), Release::All);
assert_eq!(g.take_all(), vec![((0, 0, 0), 7)]);
assert!(!g.holds((0, 0, 0)));
}
#[test]
fn a_hold_ends_by_itself_and_stays_ended_until_let_go() {
let (mut g, t) = (Hold::<u32>::default(), Instant::now());
g.ask(&all(), t);
assert_eq!(g.ask(&all(), t + MAX_HOLD), Release::All);
assert!(!g.holds((0, 0, 0)));
assert_eq!(g.ask(&all(), t + MAX_HOLD * 2), Release::None);
assert!(!g.holds((0, 0, 0)));
g.ask(&WorldHold::default(), t + MAX_HOLD * 2);
g.ask(&all(), t + MAX_HOLD * 3);
assert!(g.holds((0, 0, 0)));
}
#[test]
fn smaller_circles_let_go_what_they_leave() {
let (mut g, t) = (Hold::<u32>::default(), Instant::now());
g.ask(&within(&[[0.0, 0.0, 100.0]]), t);
assert!(g.holds((0, 0, 0)) && g.holds((5, 0, 0)) && !g.holds((7, 0, 0)));
g.wait((0, 0, 0), 1, 10);
g.wait((5, 0, 0), 2, 20);
assert_eq!(g.ask(&within(&[[0.0, 0.0, 100.0]]), t), Release::None);
assert_eq!(g.ask(&within(&[[0.0, 0.0, 40.0]]), t), Release::Outside);
assert_eq!(g.take_outside(), vec![((5, 0, 0), 2)]);
assert_eq!((g.sections().count(), g.bytes()), (1, 10));
assert!(!g.holds((5, 0, 0)));
// (to all of it again: nothing more is let go, and all of it waits again)
assert_eq!(g.ask(&all(), t), Release::Outside);
assert!(g.take_outside().is_empty());
assert!(g.holds((5, 0, 0)));
}
#[test]
fn what_waits_is_counted_and_capped() {
let (mut g, t) = (Hold::<u32>::default(), Instant::now());
g.ask(&all(), t);
assert_eq!(g.wait((0, 0, 0), 1, MAX_BYTES - 10), (None, false));
// (a newer mesh of the same section replaces it, and the old one comes back to free)
assert_eq!(g.wait((0, 0, 0), 2, MAX_BYTES - 20), (Some(1), false));
assert_eq!(g.bytes(), MAX_BYTES - 20);
assert_eq!(g.wait((1, 0, 0), 3, 20), (None, false));
assert_eq!(g.wait((2, 0, 0), 4, 1), (None, true));
assert_eq!(g.take((1, 0, 0)), Some(3));
assert_eq!(g.take((1, 0, 0)), None);
assert_eq!(g.bytes(), MAX_BYTES - 19);
}
#[test]
fn columns_going_and_the_sections_cleared_drop_what_waits() {
let (mut g, t) = (Hold::<u32>::default(), Instant::now());
g.ask(&all(), t);
g.wait((0, 0, 0), 1, 10);
g.wait((0, 5, 0), 2, 10);
g.wait((3, 0, 0), 3, 10);
let gone: FxHashSet<(i32, i32)> = [(0, 0)].into_iter().collect();
let mut dropped = g.take_columns(&gone);
dropped.sort_unstable();
assert_eq!(dropped, vec![1, 2]);
assert_eq!((g.sections().count(), g.bytes()), (1, 10));
g.clear();
assert!(g.is_empty() && g.bytes() == 0 && !g.holds((3, 0, 0)));
// (cleared while held: spent until let go; with no hold, nothing to end)
assert_eq!(g.ask(&all(), t), Release::None);
assert!(!g.holds((3, 0, 0)));
let mut none = Hold::<u32>::default();
none.clear();
none.ask(&all(), t);
assert!(none.holds((3, 0, 0)));
}
}
@@ -0,0 +1,485 @@
//! HUD coverage beside its unchanged colour and alpha, only on the float HDR lane.
pub(crate) const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Unorm;
pub(crate) fn supported(
lane: (bool, bool, bool),
hdr_offered: bool,
attachments: u32,
flags: wgpu::DownlevelFlags,
format: wgpu::TextureFormatFeatures,
) -> bool {
!lane.0
&& lane.1
&& lane.2
&& hdr_offered
&& attachments >= 2
&& flags.contains(wgpu::DownlevelFlags::INDEPENDENT_BLEND)
&& format
.allowed_usages
.contains(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
&& format
.flags
.contains(wgpu::TextureFormatFeatureFlags::BLENDABLE)
}
pub(crate) fn attachment(view: &wgpu::TextureView) -> wgpu::RenderPassColorAttachment<'_> {
wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
}
}
pub(crate) fn clear(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) {
let mut color = attachment(view);
color.ops.load = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT);
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HUD coverage reset"),
color_attachments: &[Some(color)],
..Default::default()
});
}
pub(crate) struct Pipeline {
plain: wgpu::RenderPipeline,
coverage: Option<wgpu::RenderPipeline>,
}
impl Pipeline {
/// `None` when `enabled` and the shader can't be given a coverage output (a resource
/// pack's, which the caller then doesn't use).
pub(crate) fn new(
device: &wgpu::Device,
desc: &wgpu::RenderPipelineDescriptor<'_>,
source: wgpu::ShaderSource<'_>,
enabled: bool,
) -> Option<Self> {
let coverage = if enabled {
Some(pipeline(device, desc, source)?)
} else {
None
};
Some(Self {
plain: device.create_render_pipeline(desc),
coverage,
})
}
pub(crate) fn get(&self, coverage: bool) -> &wgpu::RenderPipeline {
if coverage {
self.coverage.as_ref().expect("HUD coverage pipeline")
} else {
&self.plain
}
}
}
/// Keep the primary output and all its blend factors, including destination alpha. Wrap the
/// final shader result, so pack text's alpha, early returns and discard all apply to coverage.
/// `None` for a fragment shader without a colour output at location 0.
pub(super) fn pipeline(
device: &wgpu::Device,
desc: &wgpu::RenderPipelineDescriptor<'_>,
source: wgpu::ShaderSource<'_>,
) -> Option<wgpu::RenderPipeline> {
let mut desc = desc.clone();
let fragment = desc.fragment.as_mut()?;
let mut module = match source {
wgpu::ShaderSource::Wgsl(s) => naga::front::wgsl::parse_str(&s).ok()?,
wgpu::ShaderSource::Naga(m) => m.into_owned(),
_ => return None,
};
let primary = fragment.targets.first()?.clone()?;
let blend = primary.blend.unwrap_or(wgpu::BlendState::REPLACE).color;
let additive = matches!(
(blend.src_factor, blend.dst_factor),
(
wgpu::BlendFactor::One
| wgpu::BlendFactor::Src
| wgpu::BlendFactor::SrcAlpha
| wgpu::BlendFactor::Zero,
wgpu::BlendFactor::One
)
) && blend.operation == wgpu::BlendOperation::Add;
wrap(&mut module, fragment.entry_point?, blend)?;
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: desc.label,
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)),
});
let over = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
};
let targets = [
Some(primary),
Some(wgpu::ColorTargetState {
format: FORMAT,
blend: Some(wgpu::BlendState {
color: over,
alpha: over,
}),
write_mask: if additive {
wgpu::ColorWrites::empty()
} else {
wgpu::ColorWrites::RED
},
}),
];
fragment.module = &shader;
fragment.targets = &targets;
Some(device.create_render_pipeline(&desc))
}
fn wrap(module: &mut naga::Module, name: &str, blend: wgpu::BlendComponent) -> Option<()> {
use naga::{Expression as E, Statement as S, TypeInner as T};
use wgpu::BlendFactor as B;
let span = naga::Span::UNDEFINED;
let entry = module.entry_points.iter_mut().find(|e| e.name == name)?;
// Checked before anything is taken apart: a resource pack's shader may have no colour.
let result = entry.function.result.clone()?;
if let T::Struct { members, .. } = &module.types[result.ty].inner {
members
.iter()
.find(|m| matches!(m.binding, Some(naga::Binding::Location { location: 0, .. })))?;
} else if !matches!(
result.binding,
Some(naga::Binding::Location { location: 0, .. })
) {
return None;
}
let mut original = std::mem::take(&mut entry.function);
entry.function.arguments = original.arguments.clone();
for arg in &mut original.arguments {
arg.binding = None;
}
original.result.as_mut().unwrap().binding = None;
original.name = Some("hud_color".into());
let function = module.functions.append(original, span);
let f = &mut entry.function;
let args = (0..f.arguments.len())
.map(|i| f.expressions.append(E::FunctionArgument(i as u32), span))
.collect();
let call = f.expressions.append(E::CallResult(function), span);
f.body.push(
S::Call {
function,
arguments: args,
result: Some(call),
},
span,
);
let one = f
.expressions
.append(E::Literal(naga::Literal::F32(1.0)), span);
let start = f.expressions.len();
let (mut members, mut values, color, offset) = match &module.types[result.ty].inner {
T::Struct {
members,
span: size,
} => {
// HUD pipelines have one target, so a pack's other colour outputs went nowhere;
// left in, one at location 1 would collide with the coverage.
let (members, values): (Vec<_>, Vec<_>) = members
.iter()
.enumerate()
.filter(|(_, m)| {
!matches!(m.binding, Some(naga::Binding::Location { location, .. }) if location != 0)
})
.map(|(i, m)| {
let value = f.expressions.append(
E::AccessIndex {
base: call,
index: i as u32,
},
span,
);
(m.clone(), value)
})
.unzip();
let color = members
.iter()
.position(|m| {
matches!(m.binding, Some(naga::Binding::Location { location: 0, .. }))
})
.unwrap();
let color = values[color];
(members, values, color, *size)
}
_ => (
vec![naga::StructMember {
name: Some("color".into()),
ty: result.ty,
binding: result.binding,
offset: 0,
}],
vec![call],
call,
16,
),
};
let mut component = |index| {
f.expressions
.append(E::AccessIndex { base: color, index }, span)
};
let [r, g, b, a] = [component(0), component(1), component(2), component(3)];
let mut math = |fun, arg, arg1| {
f.expressions.append(
E::Math {
fun,
arg,
arg1: Some(arg1),
arg2: None,
arg3: None,
},
span,
)
};
let low = math(naga::MathFunction::Min, r, g);
let low = math(naga::MathFunction::Min, low, b);
let high = math(naga::MathFunction::Max, r, g);
let high = math(naga::MathFunction::Max, high, b);
// A scalar cannot reproduce RGB-dependent replacement or inversion: surviving pixels
// cover fully, so the later composite cannot leak world light through them.
let c = if blend.operation != wgpu::BlendOperation::Add {
one
} else {
match (blend.src_factor, blend.dst_factor) {
(B::SrcAlpha | B::One, B::OneMinusSrcAlpha) => a,
(B::Zero, B::OneMinusSrc) => high,
// Multiplying retains src.rgb (or 1 - alpha + src.rgb) of the backdrop.
// Use the greatest channel darkening, as for the credits vignette above.
(B::Zero, B::Src)
| (B::Dst, B::Zero)
| (B::Dst, B::OneMinusSrcAlpha)
| (B::Dst, B::Src) => {
let top = if blend.dst_factor == B::OneMinusSrcAlpha {
a
} else {
one
};
let factor = if blend.dst_factor == B::Src && blend.src_factor == B::Dst {
f.expressions.append(
E::Binary {
op: naga::BinaryOperator::Add,
left: low,
right: low,
},
span,
)
} else {
low
};
f.expressions.append(
E::Binary {
op: naga::BinaryOperator::Subtract,
left: top,
right: factor,
},
span,
)
}
_ => one,
}
};
let c = f.expressions.append(
E::Math {
fun: naga::MathFunction::Saturate,
arg: c,
arg1: None,
arg2: None,
arg3: None,
},
span,
);
let scalar = module.types.insert(
naga::Type {
name: None,
inner: T::Scalar(naga::Scalar::F32),
},
span,
);
members.push(naga::StructMember {
name: Some("coverage".into()),
ty: scalar,
binding: Some(naga::Binding::Location {
location: 1,
interpolation: None,
sampling: None,
blend_src: None,
per_primitive: false,
}),
offset,
});
let ty = module.types.insert(
naga::Type {
name: Some("HudCoverage".into()),
inner: T::Struct {
members,
span: (offset + 4).next_multiple_of(16),
},
},
span,
);
values.push(c);
let value = f.expressions.append(
E::Compose {
ty,
components: values,
},
span,
);
f.result = Some(naga::FunctionResult { ty, binding: None });
f.body.push(S::Emit(f.expressions.range_from(start)), span);
f.body.push(S::Return { value: Some(value) }, span);
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coverage_requires_the_no_pack_float_hdr_lane_and_independent_r8_blending() {
let flags = wgpu::DownlevelFlags::INDEPENDENT_BLEND;
let format = wgpu::TextureFormatFeatures {
allowed_usages: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
flags: wgpu::TextureFormatFeatureFlags::BLENDABLE,
};
let lane = (false, true, true);
assert!(supported(lane, true, 2, flags, format));
// Switch unset (including legacy 16-bit HDR and 0.1 packs), HDR off, a 0.2
// pack's float frame, and unsupported devices never allocate coverage.
for other in [
(false, false, true),
(true, false, true),
(true, true, true),
(false, true, false),
] {
assert!(!supported(other, true, 2, flags, format));
}
assert!(!supported(lane, false, 2, flags, format));
assert!(!supported(lane, true, 1, flags, format));
assert!(!supported(
lane,
true,
2,
wgpu::DownlevelFlags::empty(),
format
));
assert!(!supported(
lane,
true,
2,
flags,
wgpu::TextureFormatFeatures {
flags: wgpu::TextureFormatFeatureFlags::empty(),
..format
}
));
assert!(!supported(
lane,
true,
2,
flags,
wgpu::TextureFormatFeatures {
allowed_usages: wgpu::TextureUsages::TEXTURE_BINDING,
..format
}
));
}
#[test]
fn disabled_coverage_builds_only_the_original_pipeline() {
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
return;
};
let Ok((device, _)) = pollster::block_on(adapter.request_device(&Default::default()))
else {
return;
};
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(
"@vertex fn vs() -> @builtin(position) vec4<f32> { return vec4(0.0); }".into(),
),
});
let desc = wgpu::RenderPipelineDescriptor {
label: None,
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::Always),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: None,
multiview_mask: None,
cache: None,
};
// The coverage source must not even be parsed outside the lane.
let pipeline = Pipeline::new(
&device,
&desc,
wgpu::ShaderSource::Wgsl("invalid".into()),
false,
)
.unwrap();
assert!(pipeline.coverage.is_none());
}
#[test]
fn coverage_wraps_the_debug_crosshair_without_changing_world_entry_points() {
let mut module = naga::front::wgsl::parse_str(&crate::gfx::terrain_shader()).unwrap();
wrap(
&mut module,
"fs_debug_line",
wgpu::BlendState::ALPHA_BLENDING.color,
)
.unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
}
#[test]
fn coverage_replaces_a_colour_output_the_hud_has_no_target_for() {
let mut module = naga::front::wgsl::parse_str(
"struct Out { @location(0) color: vec4<f32>, @location(1) unused: vec4<f32> }
@fragment fn fs() -> Out { return Out(vec4(0.5), vec4(1.0)); }",
)
.unwrap();
wrap(&mut module, "fs", wgpu::BlendState::ALPHA_BLENDING.color).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
let result = module.entry_points[0].function.result.as_ref().unwrap();
let naga::TypeInner::Struct { members, .. } = &module.types[result.ty].inner else {
panic!("the wrapped entry returns a struct");
};
let names: Vec<_> = members.iter().map(|m| m.name.as_deref().unwrap()).collect();
assert_eq!(names, ["color", "coverage"]);
}
}
@@ -98,8 +98,24 @@ fn interfaces(source: &str) -> Vec<Interface> {
/// The shaders as the renderer assembles them, by the `.wgsl` files each is made of.
fn composed() -> Vec<(&'static str, Vec<&'static str>, String)> {
let entity = crate::overlay::wgsl_constants() + include_str!("../entity.wgsl");
let entity = super::entity_shader();
vec![
(
"HDR",
vec!["hdr.wgsl", "hdr_light.wgsl"],
super::hdr::shader(),
),
("terrain", vec!["terrain.wgsl"], super::terrain_shader()),
(
"stars",
vec!["stars.wgsl"],
include_str!("../hdr_light.wgsl").to_owned() + include_str!("stars.wgsl"),
),
(
"custom sky",
vec!["custom_sky.wgsl"],
include_str!("../hdr_light.wgsl").to_owned() + include_str!("custom_sky.wgsl"),
),
("entity", vec!["entity.wgsl"], entity.clone()),
(
"GPU culling occlusion test",
@@ -124,14 +140,14 @@ fn composed() -> Vec<(&'static str, Vec<&'static str>, String)> {
(
"improved transparency world",
vec!["terrain.wgsl", "oit.wgsl", "oit_world.wgsl"],
include_str!("../terrain.wgsl").to_owned()
super::terrain_shader()
+ include_str!("../oit.wgsl")
+ include_str!("../oit_world.wgsl"),
),
(
"visibility buffer",
vec!["terrain.wgsl", "visbuffer.wgsl"],
include_str!("../terrain.wgsl").to_owned() + include_str!("../visbuffer.wgsl"),
super::terrain_shader() + include_str!("../visbuffer.wgsl"),
),
(
"improved transparency world border",
@@ -49,9 +49,23 @@ struct HorizonMaterialOut {
@location(14) @interpolate(flat) normal: vec3<f32>,
}
fn horizon_material_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f32>,
light: vec2<u32>, origin: vec3<f32>) -> HorizonMaterialOut {
let pos = horizon_material_displace(position + origin, uv, layer, color, light);
return horizon_material_out(pos, uv, layer, color, vec2<f32>(light));
light: vec2<u32>, origin: vec4<f32>) -> HorizonMaterialOut {
let pos = horizon_material_displace(position + origin.xyz, uv, layer, color, light);
var out = horizon_material_out(pos, uv, layer, color, vec2<f32>(light));
// The section's fade-in (`RenderSection.getVisibility`), as how far it is from whole, in the
// high 16 bits of `hdr_code`: no varying of its own, and 0 (whole) where nothing fades. It is
// the same for the whole section, so the flat varying loses nothing.
let instance = horizon_terrain_instance_visibility(origin.w);
out.hdr_code |= u32(round((1.0 - instance) * 65535.0)) << 16u;
return out;
}
// terrain.wgsl's fade-in (terrain.vsh's chunkVisibility): whole within 16 blocks, the section's
// own visibility from 32 out, toward the fog colour, alpha kept. The distance blend runs here on
// the interpolated distance, as vanilla's interpolated `visibility`, not once per triangle.
fn horizon_material_faded(in: HorizonMaterialOut, color: vec4<f32>) -> vec4<f32> {
let instance = 1.0 - f32(in.hdr_code >> 16u) / 65535.0;
let visibility = mix(1.0, instance, clamp((in.spherical - 16.0) / 16.0, 0.0, 1.0));
return vec4(mix(horizon_terrain_globals.fog_color.rgb, color.rgb, visibility), color.a);
}
// `light`: sky, block, 16 per level.
fn horizon_material_out(pos: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f32>,
@@ -94,7 +108,7 @@ fn horizon_material_out(pos: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>,
@location(5) origin: vec4<f32>) -> HorizonMaterialOut {
return horizon_material_vertex(position, horizon_terrain_terrain_uv(uv, origin.w), layer,
color, light, origin.xyz);
color, light, origin);
}
@vertex fn horizon_material_vs_flat(
@builtin(vertex_index) vertex: u32,
@@ -103,7 +117,7 @@ fn horizon_material_out(pos: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f
) -> HorizonMaterialOut {
let origin = horizon_terrain_slot_origins[horizon_terrain_block_slots[vertex >> 8u]];
return horizon_material_vertex(position, horizon_terrain_terrain_uv(uv, origin.w), layer,
color, light, origin.xyz);
color, light, origin);
}
// The prelude's `block_normal_map` and `block_specular_map`: the resource packs' LabPBR maps
// in the pack's frame group (3), one array each, a blank 1x1 without them.
@@ -181,9 +195,10 @@ struct HorizonMaterialSolid {
// What `fs_solid` leaves in the frame's alpha for HDR output, from the sprite before the pack's
// material: the pack decides the colour, Horizon still knows which pixels are light sources.
fn horizon_material_mark(in: HorizonMaterialOut, texel: vec4<f32>) -> f32 {
if in.hdr_code > 0u {
let whole = in.hdr_code > 4u;
let tier = select(in.hdr_code, in.hdr_code - 4u, whole);
let code = in.hdr_code & 15u;
if code > 0u {
let whole = code > 4u;
let tier = select(code, code - 4u, whole);
let l = in.layer & 0x7fffu;
let t = textureLoad(horizon_terrain_emission_thresholds,
vec2(i32(l % horizon_terrain_SPRITE_SPLIT), i32(l / horizon_terrain_SPRITE_SPLIT)), 0);
@@ -202,7 +217,7 @@ fn horizon_material_mark(in: HorizonMaterialOut, texel: vec4<f32>) -> f32 {
return horizon_material_solid(in);
}
fn horizon_material_solid(in: HorizonMaterialOut) -> HorizonMaterialSolid {
let color = horizon_material_color(in, false);
let color = horizon_material_faded(in, horizon_material_color(in, false));
let texel = horizon_terrain_sprite(in.uv, in.layer & 0x7fffu);
// Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; }
@@ -216,7 +231,7 @@ fn horizon_material_solid(in: HorizonMaterialOut) -> HorizonMaterialSolid {
return out;
}
@fragment fn horizon_material_fs_translucent(in: HorizonMaterialOut) -> @location(0) vec4<f32> {
let color = horizon_material_color(in, true);
let color = horizon_material_faded(in, horizon_material_color(in, true));
if color.a < 0.01 { discard; }
return horizon_material_fogged(color, in.spherical, in.cylindrical);
}
@@ -294,7 +309,8 @@ pub struct NativeMaterial {
/// every name it declares prefixed.
fn vanilla_terrain() -> String {
prefixed(
section(TERRAIN, "struct Globals {", "// Sky (SkyRenderer)"),
&(include_str!("../hdr_light.wgsl").to_owned()
+ section(TERRAIN, "struct Globals {", "// Sky (SkyRenderer)")),
PREFIX,
)
}
@@ -582,6 +598,25 @@ mod tests {
report.stages.remove(0)
}
/// The fade-in packed above the HDR code: a section a quarter visible (`section_instance`
/// with step 1: mantissa `1 - visibility` = 0.75) keeps its visibility through the code, and
/// a fragment 24 blocks away, half-way into the 16-block blend, is 1 - (1 - 0.25) / 2 = 0.625
/// visible; the code's low nibble survives.
#[test]
fn the_fade_in_rides_the_hdr_code() {
let w = f32::from_bits(1.0f32.to_bits() | (0.75 * 8_388_608.0) as u32);
// `horizon_material_vertex`.
let instance = 1.0 - (w.to_bits() & 0x7fffff) as f32 / 8_388_608.0;
let code = 7u32 | (((1.0 - instance) * 65535.0).round() as u32) << 16;
// `horizon_material_faded` and `horizon_material_mark`.
let unpacked = 1.0 - (code >> 16) as f32 / 65535.0;
assert!((unpacked - 0.25).abs() < 1.0 / 65535.0);
let blend = ((24.0f32 - 16.0) / 16.0).clamp(0.0, 1.0);
let visibility = 1.0 + (unpacked - 1.0) * blend;
assert!((visibility - 0.625).abs() < 1.0 / 65535.0);
assert_eq!(code & 15, 7);
}
#[test]
fn the_terrain_takes_a_prefix_and_validates_with_a_pack() {
let terrain = vanilla_terrain();
@@ -90,6 +90,27 @@ impl NativePack {
report: Report,
constants: &[(String, f64)],
lights: super::block_light::LightTable,
) -> Result<(Self, Vec<String>), String> {
// A backend may refuse a layout or pipeline the pack asks for (a stage's bindings
// past its sampled-texture limit, say, as OpenGL's 16 was before #10095): the pack
// is refused with that error instead of a validation panic in the renderer.
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let built = Self::build(device, queue, terrain, report, constants, lights);
let refused = pollster::block_on(scope.pop());
match (built, refused) {
(Ok(built), None) => Ok(built),
(Ok(_), Some(e)) => Err(e.to_string()),
(Err(e), _) => Err(e),
}
}
fn build(
device: &wgpu::Device,
queue: &wgpu::Queue,
terrain: &TerrainShape<'_>,
report: Report,
constants: &[(String, f64)],
lights: super::block_light::LightTable,
) -> Result<(Self, Vec<String>), String> {
let (globals, format) = (terrain.globals, terrain.format);
let textures = super::native_post::pack_textures(device, queue, &report);
@@ -278,9 +299,90 @@ impl NativePack {
#[cfg(test)]
mod tests {
use super::chosen_shadow;
use super::{NativePack, TerrainShape, chosen_shadow};
use horizon_shader_api::manifest::{OptionKind, PackOption, Shadow};
/// A device with OpenGL's minimum 16 sampled textures per stage refuses a pack whose
/// sky adds the terrain's 10 to the frame's 9: that is the pack's error to report, not
/// a validation panic (#10095).
#[test]
fn a_pack_the_backend_refuses_is_an_error_not_a_panic() {
use horizon_shader_api::{MANIFEST, Pack, check};
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
return;
};
let mut limits = adapter.limits();
limits.max_sampled_textures_per_shader_stage = 16;
let Ok((device, queue)) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_limits: limits,
..Default::default()
}))
else {
return;
};
// The terrain's group 0: its uniform and the 10 sampled textures (_terrain.wgsl_'s
// 8 sprite arrays, the lightmap and the emission thresholds).
let entry = |binding, ty| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty,
count: None,
};
let mut entries = vec![entry(
0,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
)];
entries.extend((1..=10).map(|binding| {
entry(
binding,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
)
}));
let globals = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &entries,
});
let empty = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[],
});
let terrain = TerrainShape {
globals: &globals,
flat: None,
sprites: [1.0, 2048.0],
format: wgpu::TextureFormat::Rgba8Unorm,
sprite_tags: &[],
sprite_materials: &[],
entities: &empty,
weather_groups: [&empty, &empty],
pbr: None,
};
let manifest = "schema = 1\nid = \"t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.1\"\n\
[sky]\nfile = \"sky.wgsl\"\n";
let files = [
(MANIFEST, manifest),
(
"sky.wgsl",
"fn sky(input: SkyInput) -> vec4<f32> { return input.color; }\n",
),
]
.map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec()))
.into();
let report = check(&Pack::from_files(files).unwrap()).unwrap();
let built = NativePack::new(&device, &queue, &terrain, report, &[], Default::default());
assert!(built.is_err(), "the pack should be refused");
}
fn option(id: &str, kind: OptionKind) -> PackOption {
PackOption {
id: id.into(),
@@ -73,10 +73,15 @@ pub struct WorldDrawn<'a> {
pub entities: &'a [Vertex],
pub spans: &'a [EntitySpan],
/// Which entity each run of `entities` is, recorded every frame (`Frame::entity_motion`):
/// the run's first vertex and the entity, `(1 << 32) | id` for a mob or a player and
/// `(2 << 32) | id` for a dropped item (their entity ids), 0 for anything else. A run lasts
/// until the next. Unlike `spans`, whose ids name a type, these follow one entity from
/// frame to frame (API 371).
/// the run's first vertex and the entity, `(1 << 32) | id` for a mob or a player,
/// `(2 << 32) | id` for a dropped item, `(3 << 32) | id` for another entity (boat,
/// minecart, armor stand, item frame, painting, primed TNT, falling block) and
/// `(4 << 32) | id` for an item frame's held item (their entity ids), `(5 << 32) | p` for a
/// block entity (`p`: its position, x and z in 11 bits each, y in 10), `(6 << 32) | p`
/// for a block a piston moves (`p`: the cell it moves to), `7 << 32` for the player's own
/// model, 0 for anything else.
/// A run lasts until the next. Unlike `spans`, whose ids name a type, these follow one
/// entity from frame to frame (API 371).
pub motion: &'a [(u32, u64)],
/// The shared atlas entity UVs point into.
pub atlas: Option<&'a wgpu::Texture>,
@@ -512,7 +512,8 @@ fn shader_source(
format!(
"{head}// Horizon's terrain (terrain.wgsl)\n{}{solid}{}{displace}{ENTRIES}",
prefixed(
section(TERRAIN, "struct Globals {", "// Sky (SkyRenderer)"),
&(include_str!("../hdr_light.wgsl").to_owned()
+ section(TERRAIN, "struct Globals {", "// Sky (SkyRenderer)")),
PREFIX
),
super::native_post::line_helpers(api)
@@ -30,6 +30,7 @@ pub struct NativeSky {
/// terrain.wgsl's sky with every name it declares (and `globals`) prefixed.
fn vanilla_sky() -> String {
let text = [
include_str!("../hdr_light.wgsl"),
section(TERRAIN, "struct Globals {", "@group(0) @binding(1)"),
section(TERRAIN, "fn linear_fog(", "fn apply_fog("),
section(TERRAIN, "struct SkyOut {", "// rendertype_lines"),
+22 -5
View File
@@ -192,7 +192,7 @@ impl Oit {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon improved transparency"),
source: wgpu::ShaderSource::Wgsl(
(include_str!("../terrain.wgsl").to_owned()
(super::terrain_shader()
+ include_str!("../oit.wgsl")
+ include_str!("../oit_world.wgsl"))
.into(),
@@ -253,7 +253,14 @@ impl Oit {
..Default::default()
})
};
let constants = [("SPRITE_ARRAYS", sprites[0]), ("SPRITE_SPLIT", sprites[1])];
let constants = [
("SPRITE_ARRAYS", sprites[0]),
("SPRITE_SPLIT", sprites[1]),
(
"HDR_WRITE_LIGHT",
f64::from(u8::from(format == super::LINEAR_FRAME)),
),
];
let add = wgpu::BlendOperation::Add;
let depth = |write| {
Some(wgpu::DepthStencilState {
@@ -464,7 +471,10 @@ impl Oit {
fragment: Some(wgpu::FragmentState {
module: &cloud_shader,
entry_point: Some(fragment),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &constants[2..],
..Default::default()
},
targets: &stage_targets(stage),
}),
multiview_mask: None,
@@ -488,7 +498,14 @@ impl Oit {
Stage::Accumulate,
),
];
let features = Features::new(device, &layouts, features[0], features[1], features[2]);
let features = Features::new(
device,
&layouts,
features[0],
features[1],
features[2],
format,
);
Self {
uniform,
layouts,
@@ -912,7 +929,7 @@ mod tests {
#[test]
fn the_terrain_shader_validates() {
validate(
&(include_str!("../terrain.wgsl").to_owned()
&(crate::gfx::terrain_shader()
+ include_str!("../oit.wgsl")
+ include_str!("../oit_world.wgsl")),
&[
@@ -55,6 +55,7 @@ impl Features {
entity: &wgpu::BindGroupLayout,
weather: &wgpu::BindGroupLayout,
border: &wgpu::BindGroupLayout,
format: wgpu::TextureFormat,
) -> Self {
let entity_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon improved transparency features"),
@@ -113,6 +114,15 @@ impl Features {
bind_group_layouts: &[groups[0], groups[1], Some(&layouts[stage as usize])],
..Default::default()
});
let fragment = if kind.label == "text" && stage == Stage::Accumulate {
"fs_oit_text_accumulate".to_owned()
} else {
format!("fs_oit_{}_{suffix}", kind.name)
};
let constants = [(
"HDR_WRITE_LIGHT",
f64::from(u8::from(format == super::LINEAR_FRAME)),
)];
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(&format!("OIT {} {suffix}", kind.label)),
layout: Some(&layout),
@@ -136,8 +146,15 @@ impl Features {
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module,
entry_point: Some(&format!("fs_oit_{}_{suffix}", kind.name)),
compilation_options: Default::default(),
entry_point: Some(&fragment),
compilation_options: wgpu::PipelineCompilationOptions {
constants: if kind.name == "border" {
&[]
} else {
&constants
},
..Default::default()
},
targets: &stage_targets(stage),
}),
multiview_mask: None,
@@ -728,6 +728,13 @@ impl PackAtlas {
),
("mc_Entity", entity),
("at_midBlock", mid_block),
// Horizon's own: the face's HDR tier (`mesher::emitting`'s code in the colour's low
// alpha nibble): 0 for none, 1 to 4 for low to very bright, plus 4 when the whole
// face shines (`mesher::WHOLE`).
(
"horizonTier",
"float(15u - (uint(round(hz_v_color.a * 255.0)) & 15u))",
),
(
"mc_midTexCoord",
"vec4((hz_cell + hz_mid) * hz_scale, 0.0, 1.0)",
@@ -750,6 +757,7 @@ impl PackAtlas {
alpha_test: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
}
}
}
@@ -157,6 +157,7 @@ fn terrain_fade_reaches_pack_pixels_through_real_instances() {
flat,
geometry,
origin,
0x80ffffff,
);
let fade = if requested { expected } else { 1.0 };
let expected = [
@@ -182,6 +183,96 @@ fn terrain_fade_reaches_pack_pixels_through_real_instances() {
assert_eq!(count, 98);
}
/// `horizonTier`: the HDR tier the mesher marks a light source's faces with (`mesher::emitting`),
/// read by a pack's terrain program, flat or instanced.
#[test]
fn terrain_tier_reaches_pack_pixels() {
let instance = crate::gfx::test_gpu::instance();
let adapter = match pollster::block_on(instance.request_adapter(&Default::default())) {
Ok(adapter) => adapter,
Err(error) => {
eprintln!("SKIP terrain tier GPU control: no adapter: {error}");
return;
}
};
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).unwrap();
let array = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 2,
height: 2,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let mut encoder = device.create_command_encoder(&Default::default());
let atlas = PackAtlas::new(&device, &mut encoder, &[array], 1, 1, 2).unwrap();
queue.submit([encoder.finish()]);
let folder = ProbePack(
std::env::temp_dir().join(format!("horizon-terrain-tier-{}", std::process::id())),
);
std::fs::create_dir_all(folder.0.join("shaders")).unwrap();
std::fs::write(
folder.0.join("shaders/gbuffers_terrain.vsh"),
"#version 330\nin float horizonTier;\nout vec4 observation;\n\
void main() {\nobservation = vec4(horizonTier, 0.0, 0.0, 0.0);\n\
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n}",
)
.unwrap();
std::fs::write(
folder.0.join("shaders/gbuffers_terrain.fsh"),
"#version 330\nin vec4 observation;\nlayout(location = 0) out uvec4 pixel;\n\
void main() { pixel = floatBitsToUint(observation); }",
)
.unwrap();
let pack = horizon_shaders::Pack::open(&folder.0).unwrap();
let mut macros = horizon_shaders::Macros::standard();
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
use crate::mesher::{BRIGHT, LOW, VERY_BRIGHT, WHOLE, emitting};
// No light, low, very bright, and bright all over (4 more).
let cases = [
(0, 0.0),
(LOW, 1.0),
(VERY_BRIGHT, 4.0),
(BRIGHT | WHOLE, 7.0),
];
for flat in [false, true] {
let post = horizon_shaders::load_post(
&pack,
"",
&properties,
&macros,
&horizon_shaders::GameInputs {
terrain: Some(atlas.terrain_inputs(flat)),
..Default::default()
},
);
let program = post
.terrain
.as_ref()
.unwrap_or_else(|| panic!("{:?}", post.notes));
for (tier, expected) in cases {
let origin = section_instance([0.0; 3], 0, 1.0);
let pixel = sample(
&device,
&queue,
&atlas,
program.program.as_ref().unwrap(),
flat,
false,
origin,
emitting(0xffff_ffff, tier),
);
assert_eq!(pixel[0], expected, "tier {tier} flat={flat}");
}
}
}
fn sample(
device: &wgpu::Device,
queue: &wgpu::Queue,
@@ -190,6 +281,7 @@ fn sample(
flat: bool,
geometry: bool,
origin: [f32; 4],
color: u32,
) -> [f32; 4] {
let buffer = |bytes: &[u8], usage| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
@@ -209,7 +301,7 @@ fn sample(
let slots = buffer(bytemuck::bytes_of(&0u32), wgpu::BufferUsages::STORAGE);
let vertices: Vec<_> = [[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.]]
.into_iter()
.map(|pos| TerrainVertex::new(pos, [0.25, 0.75], 0, 0x80ffffff, 0))
.map(|pos| TerrainVertex::new(pos, [0.25, 0.75], 0, color, 0))
.collect();
let data = buffer(
bytemuck::cast_slice(&vertices),
@@ -30,7 +30,7 @@ pub fn buffers() -> [Option<wgpu::VertexBufferLayout<'static>>; 1] {
/// What `gbuffers_entities` and `gbuffers_block` read from an entity vertex: camera-relative
/// position, the shared atlas's UV, colour, light (block, sky in 16ths) and the world-oriented
/// normal. The quad's corners, read from the same vertices at set 1, give the face normal where
/// the vertex has none (block entities) and `at_tangent` along the texture's u, as for terrain.
/// the vertex has none (custom geometry) and `at_tangent` along the texture's u, as for terrain.
pub fn inputs() -> horizon_shaders::GbuffersInputs {
let words = std::mem::size_of::<Vertex>() / 4;
let mut declarations = "layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in vec2 hz_v_uv;\n\
@@ -107,6 +107,10 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
"at_velocity",
"hz_velocity(gbufferModelView, gbufferPreviousModelView)",
),
// Horizon's own, as for terrain: the HDR tier of a light-giving item, particle or glowing
// text (`mesher::hdr_tier`, the overlay's high bits), 0 for none, 1 to 4 for low to very
// bright.
("horizonTier", "float((hz_v_overlay >> 16u) & 255u)"),
];
horizon_shaders::GbuffersInputs {
declarations,
@@ -123,6 +127,8 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
}),
item_id_declared: false,
far_depth: false,
// Entities, items and block entities read the shared atlas: its own maps (paged_maps.rs).
paged_maps: true,
}
}
@@ -186,6 +192,7 @@ pub fn cloud_inputs() -> horizon_shaders::GbuffersInputs {
alpha_test: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
}
}
@@ -1628,3 +1635,44 @@ mod velocity_translate_tests {
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod tier_translate_tests {
/// A pack's entity and hand programs may read `horizonTier`, the overlay's HDR tier.
#[test]
fn a_pack_reading_horizon_tier_translates_for_entities_and_the_hand() {
let dir = std::env::temp_dir().join(format!("hz-entity-tier-{}", std::process::id()));
let shaders = dir.join("shaders");
std::fs::create_dir_all(&shaders).unwrap();
std::fs::write(
shaders.join("gbuffers_entities.vsh"),
"#version 120\nattribute float horizonTier;\nvarying float t;\n\
void main() {\n gl_Position = ftransform();\n t = horizonTier;\n}\n",
)
.unwrap();
std::fs::write(
shaders.join("gbuffers_entities.fsh"),
"#version 120\nvarying float t;\nvoid main() {\n gl_FragData[0] = vec4(t);\n}\n",
)
.unwrap();
let pack = horizon_shaders::Pack::open(&dir).unwrap();
let m = horizon_shaders::Macros::standard();
let vsh = horizon_shaders::preprocess(&pack, "gbuffers_entities.vsh", &m);
let fsh = horizon_shaders::preprocess(&pack, "gbuffers_entities.fsh", &m);
for (who, inputs) in [
("entities", super::inputs()),
("hand", super::super::pack_hand::inputs()),
] {
let attribute = inputs.attributes.iter().find(|(n, _)| n == "horizonTier");
assert!(attribute.is_some(), "{who}");
horizon_shaders::translate_gbuffers(
&vsh,
&fsh,
horizon_shaders::Target::Buffers,
&inputs,
)
.unwrap_or_else(|e| panic!("{who}: {e:?}"));
}
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -82,6 +82,9 @@ pub(super) fn format(f: Format, packed_float: bool) -> wgpu::TextureFormat {
_ => rgba,
};
match (f.kind, f.bits) {
(Kind::Unorm, 10) => T::Rgb10a2Unorm,
(Kind::Uint, 10) => T::Rgb10a2Uint,
(Kind::Snorm, 16) => pick(T::R16Snorm, T::Rg16Snorm, T::Rgba16Snorm),
(Kind::Int, 8) => pick(T::R8Sint, T::Rg8Sint, T::Rgba8Sint),
(Kind::Int, 16) => pick(T::R16Sint, T::Rg16Sint, T::Rgba16Sint),
(Kind::Int, _) => pick(T::R32Sint, T::Rg32Sint, T::Rgba32Sint),
@@ -52,6 +52,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
alpha_test: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
}
}
@@ -0,0 +1,207 @@
//! Paged maps (`paged_maps.rs`) through the translator's `hz_pagedTexture` and the pass's
//! binding: a pack reads the map's texels at the colour's coordinates.
use super::*;
use wgpu::util::DeviceExt;
/// The atlas the fixture's coordinates are in, and the one mapped texture's place.
const ATLAS: (u32, u32) = (64, 32);
const SPRITE: [u32; 4] = [20, 4, 20, 20];
/// The fixture's normal map texel at texel (x, y) of its texture.
fn texel(x: u32, y: u32) -> [u8; 4] {
[x as u8 * 10, y as u8 * 10, 7, 255]
}
#[test]
#[ignore = "requires a host GPU; missing adapter is a failure"]
fn a_pack_reads_paged_maps_at_the_colours_coordinates() {
let instance = crate::gfx::test_gpu::instance();
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).unwrap();
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_limits: adapter.limits(),
..Default::default()
}))
.unwrap();
let root = std::env::temp_dir().join(format!("horizon-paged-pack-{}", std::process::id()));
std::fs::create_dir_all(root.join("shaders")).unwrap();
std::fs::write(
root.join("shaders/gbuffers_terrain.vsh"),
"#version 120\nvoid main(){gl_Position=gl_Vertex;}",
)
.unwrap();
// Each pixel reads one atlas texel's centre: in the texture (on four pages), beside it,
// on a page without maps, and the specular map, which no texture has.
std::fs::write(
root.join("shaders/gbuffers_terrain.fsh"),
r#"#version 120
uniform sampler2D normals;
uniform sampler2D specular;
vec2 at(float x, float y) { return (vec2(x, y) + 0.5) / vec2(64.0, 32.0); }
void main() {
int x = int(floor(gl_FragCoord.x));
if (x == 0) gl_FragData[0] = texture2D(normals, at(20.0, 4.0));
else if (x == 1) gl_FragData[0] = texture2D(normals, at(39.0, 23.0));
else if (x == 2) gl_FragData[0] = texture2D(normals, at(31.0, 15.0), 2.0);
else if (x == 3) gl_FragData[0] = texture2DLod(normals, at(32.0, 16.0), 3.0);
else if (x == 4) gl_FragData[0] = texture2D(normals, at(19.0, 4.0));
else if (x == 5) gl_FragData[0] = texture2D(normals, at(50.0, 30.0));
else if (x == 6) gl_FragData[0] = texture2D(specular, at(25.0, 10.0));
else gl_FragData[0] = texture2D(normals, at(33.0, 5.0));
}
"#,
)
.unwrap();
let [x0, y0, w, h] = SPRITE;
let normal: Vec<u8> = (0..w * h).flat_map(|i| texel(i % w, i / w)).collect();
let [normals, specular] = crate::paged_maps::build(
ATLAS,
&[crate::paged_maps::SpriteMaps {
rect: SPRITE,
maps: [Some(normal), None],
}],
16384,
);
assert!(specular.is_none());
let normals = normals.unwrap();
let map = device
.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: Some("Fixture paged normal map"),
size: wgpu::Extent3d {
width: normals.width,
height: normals.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&normals.pixels,
)
.create_view(&Default::default());
let pack = horizon_shaders::Pack::open(&root).unwrap();
let macros = horizon_shaders::Macros::standard();
let properties = horizon_shaders::Properties::parse("alphaTest.gbuffers_terrain=off", &macros);
let inputs = horizon_shaders::GameInputs {
terrain: Some(horizon_shaders::GbuffersInputs {
body: "vec2 p = vec2(float((gl_VertexIndex << 1) & 2), float(gl_VertexIndex & 2)); hz_Vertex=vec4(p*2.0-1.0,0.0,1.0);".into(),
paged_maps: true,
..Default::default()
}),
..Default::default()
};
let post = horizon_shaders::load_post(&pack, "", &properties, &macros, &inputs);
assert!(post.terrain.is_some(), "{:?}", post.notes);
let world = World {
sprite_rects: &[],
atlas: None,
material_maps: None,
lightmap: map.clone(),
terrain: Some(Geometry {
buffers: &[],
table: None,
depth_write: true,
atlas: None,
material_maps: false,
ids: None,
cull: false,
}),
block_ids: &[],
celestial: None,
gui_size: [1, 1],
clouds: None,
weather: false,
hand: false,
};
let mut post = PackPost::new(
&device,
&queue,
&adapter,
post,
wgpu::TextureFormat::Rgba8Unorm,
world,
&Default::default(),
)
.expect("the pack runs");
let mut pass = post
.terrain
.take()
.unwrap_or_else(|| panic!("terrain pipeline must compile: {:?}", post.notes));
// As the entity passes are (`paged`), with the maps the renderer hands over.
pass.paged = true;
post.set_paged_maps([Some(map), None]);
post.copied |= 1;
post.resize(&device, [8, 1]);
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 256,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
{
let _clear = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Initialize fixture depth"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &post.targets.as_ref().unwrap().depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
});
}
let group = post.bind(&device, &queue, &mut encoder, &mut pass, [8, 1]);
{
let mut render = post.begin(&mut encoder, &pass);
render.set_pipeline(pass.render());
render.set_bind_group(0, &group, &[]);
if pass.draw {
post.draws.bind(&mut render, "TERRAIN_SOLID");
}
render.draw(0..3, 0..1);
}
let output = post.targets.as_ref().unwrap().color[0].as_ref().unwrap()[0].texture();
encoder.copy_texture_to_buffer(
output.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &read,
layout: wgpu::TexelCopyBufferLayout {
bytes_per_row: Some(256),
..Default::default()
},
},
wgpu::Extent3d {
width: 8,
height: 1,
depth_or_array_layers: 1,
},
);
queue.submit([encoder.finish()]);
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let data = read.slice(..).get_mapped_range().unwrap();
let local = |x: u32, y: u32| texel(x - x0, y - y0);
let expected = [
local(20, 4),
local(39, 23),
local(31, 15),
local(32, 16),
crate::sprites::FLAT_NORMAL,
crate::sprites::FLAT_NORMAL,
crate::sprites::NO_SPECULAR,
local(33, 5),
];
for (i, e) in expected.iter().enumerate() {
assert_eq!(&data[i * 4..i * 4 + 4], e, "pixel {i}");
}
std::fs::remove_dir_all(root).unwrap();
}
@@ -61,6 +61,9 @@ mod shadow_faces_tests;
#[cfg(test)]
mod r11f_image_tests;
#[cfg(test)]
mod work_group_fold_tests;
#[cfg(test)]
mod forced_flip_tests;
@@ -430,6 +433,9 @@ struct Pass {
/// What `texture` reads instead of the block atlas.
atlas: Option<wgpu::TextureView>,
material_maps: bool,
/// Draws the shared atlas's geometry: `normals` and `specular` are its paged maps
/// (`PackPost::set_paged_maps`), as its programs were translated to read them.
paged: bool,
/// Reads `mc_Entity`'s table (`PackPost::block_ids`).
ids: bool,
/// Bind groups by the sides read (bits 0–15), the buffers whose mip chain is current (bits
@@ -674,6 +680,8 @@ pub struct PackPost {
custom: horizon_shaders::Custom,
atlas: Option<wgpu::TextureView>,
material_maps: Option<[wgpu::TextureView; 2]>,
/// The shared atlas's normal and specular paged maps (`set_paged_maps`).
paged_maps: [Option<wgpu::TextureView>; 2],
lightmap: wgpu::TextureView,
deferred_pre: u16,
composite_pre: u16,
@@ -2179,6 +2187,7 @@ fn build_pass(
draw,
atlas: geometry.and_then(|g| g.atlas.clone()),
material_maps: geometry.is_some_and(|g| g.material_maps),
paged: false,
ids: geometry.is_some_and(|g| g.ids.is_some()),
groups: HashMap::new(),
portal_groups: HashMap::new(),
@@ -2319,6 +2328,7 @@ fn build_compute(
draw: false,
atlas: None,
material_maps: false,
paged: false,
ids: false,
groups: HashMap::new(),
portal_groups: HashMap::new(),
@@ -2357,6 +2367,13 @@ impl Refused {
}
impl PackPost {
/// The shared atlas's normal and specular paged maps (`paged_maps.rs`), which the programs
/// drawing its geometry read as `normals` and `specular`; set before the first frame (a pass's
/// bind groups are kept once made). A missing one reads as the dummy (flat, no specular).
pub fn set_paged_maps(&mut self, maps: [Option<wgpu::TextureView>; 2]) {
self.paged_maps = maps;
}
/// Builds the pipelines of `post` for a screen of `screen` format. An error when the pack
/// can't show anything on the screen: the game turns it off, as a pack that fails to load.
///
@@ -2780,6 +2797,13 @@ impl PackPost {
ids: None,
cull: false,
});
// Programs drawing the shared atlas's geometry read its paged maps (`pack_entities::inputs`).
let paged = |pass: Option<Pass>| {
pass.map(|mut pass| {
pass.paged = true;
pass
})
};
let entity_passes = programs.map(|p| {
p.zip(entity_geometry.as_ref()).and_then(|(p, g)| {
if p.name == "gbuffers_damagedblock" {
@@ -2792,15 +2816,15 @@ impl PackPost {
ids: g.ids,
cull: false,
};
build(p, Some(&decal))
paged(build(p, Some(&decal)))
} else {
build(p, Some(g))
paged(build(p, Some(g)))
}
})
});
let shadow_entities = shadow_programs.map(|p| {
p.zip(entity_geometry.as_ref())
.and_then(|(p, g)| build(p, Some(g)))
.and_then(|(p, g)| paged(build(p, Some(g))))
});
let entities = entity_vertices
.filter(|_| (entity_passes.iter().chain(&shadow_entities)).any(Option::is_some))
@@ -2843,7 +2867,7 @@ impl PackPost {
ids: None,
cull: false,
};
build(p, Some(&g)).map(|pass| (pass, geometry))
paged(build(p, Some(&g))).map(|pass| (pass, geometry))
});
// Translucent held items, drawn from the hand's own buffer.
let hand_water = post.hand_water.and_then(|p| {
@@ -2857,7 +2881,7 @@ impl PackPost {
ids: None,
cull: false,
};
build(p, Some(&g))
paged(build(p, Some(&g)))
});
let weather = post
.weather
@@ -3296,6 +3320,7 @@ impl PackPost {
custom,
atlas: world.atlas.as_ref().map(|a| a.0.clone()),
material_maps: world.material_maps,
paged_maps: [None, None],
lightmap: world.lightmap,
deferred_pre: mask(&post.deferred_pre),
composite_pre: mask(&post.composite_pre),
@@ -3656,6 +3681,12 @@ impl PackPost {
Source::Dummy if s.dimension == wgpu::TextureViewDimension::D1 => {
&self.dummy_1d
}
Source::Normals if pass.paged => {
self.paged_maps[0].as_ref().unwrap_or(&self.dummy_normal)
}
Source::Specular if pass.paged => {
self.paged_maps[1].as_ref().unwrap_or(&self.dummy_black)
}
Source::Normals => self
.material_maps
.as_ref()
@@ -3756,6 +3787,16 @@ impl PackPost {
[n(0), n(1), 1]
});
let (pipeline, groups) = (pipeline.clone(), groups);
// wgpu panics on a dispatch over its limit. The translator reshapes a large
// `workGroups`; a `workGroupsRender` that large is not run.
let most = device.limits().max_compute_workgroups_per_dimension;
if groups.iter().any(|&n| n > most) {
log::warn!(
"shader pack: {}: {groups:?} work groups is over {most} per dimension; not run",
pass.name
);
return;
}
for image in (0..self.images.len()).filter(|k| pass.snapshots & 1 << k != 0) {
pack_images::snapshot(encoder, &self.images[image]);
}
@@ -6256,6 +6297,34 @@ mod tests {
);
}
#[test]
fn an_image_is_made_in_its_layout_qualifiers_format() {
// `image.x = … RGB10_A2 …` read through `layout(rgb10_a2) image2D x`.
for q in [
"rgba32f",
"rgba16f",
"rg16f",
"r11f_g11f_b10f",
"r32f",
"rgba16",
"rgb10_a2",
"rgba8",
"rg8",
"r16",
"rgba16_snorm",
"rgba8_snorm",
"r8_snorm",
"rgba32i",
"r16i",
"rgb10_a2ui",
"rgba8ui",
"r32ui",
] {
let def = Format::parse(q).unwrap();
assert_eq!(Some(pack_images::format(def, true)), image_format(q), "{q}");
}
}
#[test]
fn samplers_read_custom_textures_of_their_type() {
use wgpu::TextureSampleType as T;
@@ -6301,6 +6370,10 @@ mod destination_tests;
#[path = "pack_material_tests.rs"]
mod material_tests;
#[cfg(test)]
#[path = "pack_paged_maps_tests.rs"]
mod paged_maps_tests;
#[cfg(test)]
mod rgb_alpha_tests;
@@ -322,7 +322,7 @@ fn check(sampler: &str, stage: Stage, scene: Scene, expected: [u8; 4]) {
let hand = matches!(scene, Scene::Terrain { hand: true, .. });
let water = matches!(scene, Scene::Terrain { water: true, .. } | Scene::WaterOnly);
let inputs=horizon_shaders::GameInputs {
terrain:terrain.then(|| horizon_shaders::GbuffersInputs { declarations:"layout(location=0)in vec3 fixture_position;\n".into(),body:"hz_Vertex=vec4(fixture_position,1.0);hz_Color=vec4(1.0);hz_MultiTexCoord0=vec4(0.0);hz_MultiTexCoord1=vec4(240.0);hz_MultiTexCoord2=vec4(240.0);hz_Normal=vec3(0.0,0.0,1.0);\n".into(),attributes:vec![],after:String::new(),alpha_test:None,item_id_declared:false,far_depth:false }),
terrain:terrain.then(|| horizon_shaders::GbuffersInputs { declarations:"layout(location=0)in vec3 fixture_position;\n".into(),body:"hz_Vertex=vec4(fixture_position,1.0);hz_Color=vec4(1.0);hz_MultiTexCoord0=vec4(0.0);hz_MultiTexCoord1=vec4(240.0);hz_MultiTexCoord2=vec4(240.0);hz_Normal=vec3(0.0,0.0,1.0);\n".into(),attributes:vec![],after:String::new(),alpha_test:None,item_id_declared:false,far_depth:false,paged_maps:false }),
hand:hand.then(crate::gfx::pack_hand::inputs),..Default::default()
};
let mut post = gpu.load(
@@ -719,6 +719,7 @@ fn shadow_depth_map_reads(
alpha_test: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
}),
..Default::default()
};
@@ -46,6 +46,7 @@ fn pack() -> Post {
terrain: Some(horizon_shaders::GbuffersInputs {
item_id_declared: false,
far_depth: false,
paged_maps: false,
declarations: "layout(location=0)in vec3 fixture_position;\n".into(),
body: "hz_Vertex=vec4(fixture_position,1.0);hz_Color=vec4(1.0);\
hz_MultiTexCoord0=vec4(0.0);hz_MultiTexCoord1=vec4(240.0);\
@@ -0,0 +1,57 @@
//! A `workGroups` over wgpu's 65535 per dimension runs, and its programs read the work group
//! built-ins of the dispatch they declared. The programs are original.
use super::destination_tests::Fixture;
use super::*;
use std::io::{Cursor, Write};
fn pack() -> Post {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let mut add = |name: &str, source: &str| {
zip.start_file(
format!("shaders/{name}"),
zip::write::SimpleFileOptions::default(),
)
.unwrap();
zip.write_all(source.as_bytes()).unwrap();
};
// 70000 x 1 x 2 groups; the last 64 of the second layer each paint one pixel, green when
// the built-ins agree with that dispatch.
add(
"composite.csh",
"#version 430\nlayout(local_size_x=1) in;\nconst ivec3 workGroups=ivec3(70000,1,2);\n\
layout(rgba8) writeonly uniform image2D colorimg0;\n\
void main() {\n uint first = 70000u - 64u;\n\
if (gl_WorkGroupID.z != 1u || gl_WorkGroupID.x < first) return;\n\
uint k = gl_WorkGroupID.x - first;\n\
bool ok = gl_WorkGroupID.y == 0u && gl_NumWorkGroups == uvec3(70000u, 1u, 2u)\n\
&& gl_GlobalInvocationID == gl_WorkGroupID;\n\
imageStore(colorimg0, ivec2(k % 8u, k / 8u), ok ? vec4(0, 1, 0, 1) : vec4(1, 0, 0, 1));\n}\n",
);
add(
"final.vsh",
"#version 120\nvarying vec2 uv;\nvoid main() { uv=gl_MultiTexCoord0.xy; gl_Position=ftransform(); }\n",
);
add(
"final.fsh",
"#version 330 compatibility\nuniform sampler2D colortex0;\nin vec2 uv;\n\
void main() { gl_FragColor = texelFetch(colortex0, ivec2(gl_FragCoord.xy), 0); }\n",
);
let pack =
horizon_shaders::Pack::from_zip_bytes("original-fold", zip.finish().unwrap().into_inner())
.unwrap();
let mut macros = horizon_shaders::Macros::standard();
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
horizon_shaders::load_post(&pack, "", &properties, &macros, &Default::default())
}
#[test]
fn a_dispatch_over_the_limit_reads_its_declared_work_groups() {
let Some(gpu) = Fixture::new() else { return };
let post = pack();
assert!(post.notes.is_empty(), "{:?}", post.notes);
let mut post = gpu.build(post);
let pixels = gpu.render(&mut post, [8, 8]);
for (k, got) in pixels.iter().enumerate() {
assert_eq!(*got, [0, 255, 0, 255], "pixel {k}; notes {:?}", post.notes);
}
}
@@ -104,6 +104,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
alpha_test: None,
item_id_declared: false,
far_depth: true,
paged_maps: false,
}
}
@@ -131,6 +132,7 @@ pub fn celestial_inputs() -> horizon_shaders::GbuffersInputs {
alpha_test: None,
item_id_declared: false,
far_depth: true,
paged_maps: false,
}
}
@@ -355,6 +355,25 @@ pub const NAMES: &[&str] = &[
"hasSkylight",
"hasCeiling",
"cloudTime",
// Horizon's own: Horizon Extras' dynamic lights (`dynamic_light.rs`), nearest first: how
// many, and each one's camera-relative position and light level (zeros past the count).
"horizonDynamicLightCount",
"horizonDynamicLight0",
"horizonDynamicLight1",
"horizonDynamicLight2",
"horizonDynamicLight3",
"horizonDynamicLight4",
"horizonDynamicLight5",
"horizonDynamicLight6",
"horizonDynamicLight7",
"horizonDynamicLight8",
"horizonDynamicLight9",
"horizonDynamicLight10",
"horizonDynamicLight11",
"horizonDynamicLight12",
"horizonDynamicLight13",
"horizonDynamicLight14",
"horizonDynamicLight15",
"isElytraFlying",
"cloudHeight",
];
@@ -929,6 +948,12 @@ impl FrameUniforms {
"gbufferProjectionInverse" => m4(projection_inverse),
"gbufferPreviousModelView" => m4(previous_view),
"gbufferPreviousProjection" => m4(previous_projection),
"horizonDynamicLightCount" => Value::i(&[frame.dynamic_lights.len() as i32]),
n if dynamic_light_index(n).is_some() => Value::f(
&(dynamic_light_index(n).and_then(|k| frame.dynamic_lights.get(k)))
.copied()
.unwrap_or([0.0; 4]),
),
"heldItemId" => Value::i(&[inputs.held_items[0]]),
"heldItemId2" => Value::i(&[inputs.held_items[1]]),
"heldBlockLightValue" => Value::i(&[inputs.held_light[0]]),
@@ -1785,6 +1810,29 @@ pub(super) mod initial_history_tests {
assert_eq!(crate::clouds::drift(256 * 400 + 3, 0.25, 256), 3.25);
}
#[test]
fn the_dynamic_lights_reach_the_pack_nearest_first() {
let hud = HudBatch::new([800, 450]);
let mut f = frame(&hud);
let lights = [[1.0, 2.0, 3.0, 14.0], [-4.0, 0.5, 6.0, 7.0]];
f.dynamic_lights = &lights;
let mut u = FrameUniforms::default();
u.update(&f, &PackInputs::default(), [800, 450]);
let count = index("horizonDynamicLightCount").unwrap();
assert_eq!(int(&u, count), 2);
assert_eq!(float(&u, "horizonDynamicLight0")[..4], lights[0]);
assert_eq!(float(&u, "horizonDynamicLight1")[..4], lights[1]);
// Past the count, and the last of the sixteen: zeros.
assert_eq!(float(&u, "horizonDynamicLight2")[..4], [0.0; 4]);
assert_eq!(float(&u, "horizonDynamicLight15")[..4], [0.0; 4]);
assert_eq!(index("horizonDynamicLight16"), None);
// Off (no lights): none.
f.dynamic_lights = &[];
u.update(&f, &PackInputs::default(), [800, 450]);
assert_eq!(int(&u, count), 0);
assert_eq!(float(&u, "horizonDynamicLight0")[..4], [0.0; 4]);
}
#[test]
fn environmental_smoothing_starts_at_the_first_inputs_without_resetting_each_frame() {
let hud = HudBatch::new([800, 450]);
@@ -2534,6 +2582,12 @@ pub(super) mod initial_history_tests {
}
}
/// `horizonDynamicLight<k>`'s `k`, for the lights `Frame::dynamic_lights` holds.
fn dynamic_light_index(name: &str) -> Option<usize> {
let k: usize = name.strip_prefix("horizonDynamicLight")?.parse().ok()?;
(k < crate::dynamic_light::MAX).then_some(k)
}
#[cfg(test)]
#[path = "pack_uniforms/ftransform_test.rs"]
mod ftransform_test;
@@ -46,6 +46,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
}),
item_id_declared: false,
far_depth: false,
paged_maps: false,
}
}
@@ -124,6 +124,10 @@ impl<T> Resident<T> {
pub fn get_mut(&mut self, slot: u32) -> &mut T {
&mut self.items[slot as usize].1
}
/// Padded mesh bounds of the section in `slot`, relative to its origin.
pub fn bounds(&self, slot: u32) -> Option<[Vec3; 2]> {
self.bounds[slot as usize]
}
/// Sections from now on count from `min_y` (a level of another column).
pub fn set_min_y(&mut self, min_y: i32) {
self.min_y = min_y;
+17 -2
View File
@@ -46,6 +46,9 @@ pub fn star_triangles() -> Vec<[f32; 3]> {
struct Uniform {
clip_from_sky: [[f32; 4]; 4],
color: [f32; 4],
hdr_settings: [f32; 4],
hdr_shares: [f32; 4],
hdr_light: [f32; 4],
}
pub(super) struct Stars {
@@ -93,7 +96,9 @@ impl Stars {
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Stars shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("stars.wgsl").into()),
source: wgpu::ShaderSource::Wgsl(
(include_str!("../hdr_light.wgsl").to_owned() + include_str!("stars.wgsl")).into(),
),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Stars layout"),
@@ -129,7 +134,13 @@ impl Stars {
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_stars"),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[(
"HDR_WRITE_LIGHT",
f64::from(u8::from(format == super::LINEAR_FRAME)),
)],
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format,
// RenderPipelines.STARS: the celestial blend (src alpha, one), with the
@@ -165,11 +176,15 @@ impl Stars {
encoder: &mut wgpu::CommandEncoder,
clip_from_sky: Mat4,
brightness: f32,
globals: &super::Globals,
) {
let b = brightness.clamp(0.0, 1.0);
let uniform = Uniform {
clip_from_sky: clip_from_sky.to_cols_array_2d(),
color: [b; 4],
hdr_settings: globals.hdr_settings,
hdr_shares: globals.hdr_shares,
hdr_light: globals.hdr_light,
};
uploads.buffer(encoder, &self.uniform, 0, bytemuck::bytes_of(&uniform));
}
@@ -4,6 +4,9 @@ struct Stars {
clip_from_sky: mat4x4<f32>,
// starBrightness in every channel (RenderSystem.setShaderColor).
color: vec4<f32>,
hdr_settings: vec4<f32>,
hdr_shares: vec4<f32>,
hdr_light: vec4<f32>,
}
@group(0) @binding(0) var<uniform> stars: Stars;
@@ -16,5 +19,8 @@ struct Stars {
// fully lifted wherever they show at all. Nothing else reads the frame's alpha.
@fragment fn fs_stars() -> @location(0) vec4<f32> {
let b = stars.color.a;
if HDR_WRITE_LIGHT && stars.hdr_light.w != 0.0 {
return vec4(hdr_written(stars.color.rgb * b, 0.175, stars.hdr_settings, stars.hdr_shares), b);
}
return vec4(stars.color.rgb * b, 0.175);
}
@@ -8,6 +8,10 @@ pub(super) fn pipelines(
) -> [wgpu::RenderPipeline; 3] {
std::array::from_fn(|i| {
let mut constants = sprite_constants.to_vec();
constants.push((
"HDR_WRITE_LIGHT",
f64::from(u8::from(format == super::LINEAR_FRAME)),
));
constants.push(("NATIVE_MODEL_ALPHA_CUTOFF", [0.0, 0.1, 0.5][i]));
// The ordinary Vertex ABI is unchanged. This material's private payload uses
// normal's four bytes for a float z, and glint UV for float normal x/y.
@@ -65,13 +65,18 @@ impl Visbuffer {
let resolve_constants: Vec<(&str, f64)> = constants
.iter()
.copied()
.chain([("VIS_BLOCKS_PER_PAGE", blocks_per_page as f64)])
.chain([
("VIS_BLOCKS_PER_PAGE", blocks_per_page as f64),
(
"HDR_WRITE_LIGHT",
f64::from(u8::from(color == super::LINEAR_FRAME)),
),
])
.collect();
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon visibility buffer"),
source: wgpu::ShaderSource::Wgsl(
(include_str!("../terrain.wgsl").to_owned() + include_str!("../visbuffer.wgsl"))
.into(),
(super::terrain_shader() + include_str!("../visbuffer.wgsl")).into(),
),
});
let fragment = wgpu::ShaderStages::FRAGMENT;
@@ -55,6 +55,13 @@ pub struct Post {
sampler: wgpu::Sampler,
copy: wgpu::RenderPipeline,
fxaa: wgpu::RenderPipeline,
/// Contrast-adaptive sharpening of TAA's upscaled picture: the jittered frames are
/// spread over more output pixels, and the blend softens edges.
sharpen: wgpu::RenderPipeline,
/// The strength `sharpen` was built with (`set_sharpness`), and what rebuilding it takes.
sharpness: f32,
shader: wgpu::ShaderModule,
pipeline_layout: wgpu::PipelineLayout,
format: wgpu::TextureFormat,
/// World resolution relative to the window (0.5..=2.0).
pub scale: f32,
@@ -72,6 +79,7 @@ pub struct Post {
/// The last TAA frame's unjittered `view_proj` and camera, `None` once a frame ran without it.
taa_previous: Option<(DMat4, DVec3)>,
taa_this_frame: TaaUniform,
light_key: Option<([f32; 4], [f32; 4], [[f32; 4]; 2])>,
}
impl Post {
@@ -232,8 +240,12 @@ impl Post {
..Default::default()
});
Self {
shader: shader.clone(),
pipeline_layout: pipeline_layout.clone(),
copy: pipeline("fs_copy", &pipeline_layout, format),
fxaa: pipeline("fs_fxaa", &pipeline_layout, format),
sharpen: sharpen_pipeline(device, &shader, &pipeline_layout, format, 0.85),
sharpness: 0.85,
layout,
sampler,
format,
@@ -247,6 +259,19 @@ impl Post {
taa_frame: 0,
taa_previous: None,
taa_this_frame: bytemuck::Zeroable::zeroed(),
light_key: None,
}
}
// History stores the baked gain as well as the picture. Reject it before jitter records
// the next frame whenever that gain or the frame's representation changes.
pub(super) fn light_representation(
&mut self,
key: Option<([f32; 4], [f32; 4], [[f32; 4]; 2])>,
) {
if self.light_key != key {
self.taa_previous = None;
self.light_key = key;
}
}
@@ -474,6 +499,21 @@ impl Post {
}
}
/// The Upscaling Sharpness setting, 0..=1: rebuilds the sharpen pipeline when it changed.
pub fn set_sharpness(&mut self, device: &wgpu::Device, sharpness: f32) {
let sharpness = sharpness.clamp(0.0, 1.0);
if sharpness != self.sharpness {
self.sharpen = sharpen_pipeline(
device,
&self.shader,
&self.pipeline_layout,
self.format,
sharpness,
);
self.sharpness = sharpness;
}
}
/// The size of the world's own target, when it has one.
pub fn size(&self) -> Option<[u32; 2]> {
self.target.as_ref().map(|t| t.size)
@@ -535,7 +575,12 @@ impl Post {
pass.set_bind_group(0, &taa.resolve[i], &[]);
pass.draw(0..3, 0..1);
drop(pass);
self.finish_with(encoder, screen, &taa.show[i], timing);
let pipeline = if self.upscale > 1.0 {
&self.sharpen
} else {
&self.copy
};
self.draw_onto(encoder, screen, &taa.show[i], pipeline, timing);
}
/// Draw what `group` binds (`bind`) onto `screen`.
@@ -545,6 +590,23 @@ impl Post {
screen: &wgpu::TextureView,
group: &wgpu::BindGroup,
timing: Option<&mut super::pack_timing::PassTiming>,
) {
let pipeline = if self.antialias {
&self.fxaa
} else {
&self.copy
};
self.draw_onto(encoder, screen, group, pipeline, timing);
}
/// Draw what `group` binds onto `screen` through `pipeline`.
fn draw_onto(
&self,
encoder: &mut wgpu::CommandEncoder,
screen: &wgpu::TextureView,
group: &wgpu::BindGroup,
pipeline: &wgpu::RenderPipeline,
timing: Option<&mut super::pack_timing::PassTiming>,
) {
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: screen,
@@ -561,16 +623,51 @@ impl Post {
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(if self.antialias {
&self.fxaa
} else {
&self.copy
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, group, &[]);
pass.draw(0..3, 0..1);
}
}
/// `fs_sharpen` at `sharpness` (its override), drawing onto `format`.
fn sharpen_pipeline(
device: &wgpu::Device,
shader: &wgpu::ShaderModule,
layout: &wgpu::PipelineLayout,
format: wgpu::TextureFormat,
sharpness: f32,
) -> wgpu::RenderPipeline {
let constants = [("sharpness", f64::from(sharpness))];
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Horizon sharpen"),
layout: Some(layout),
vertex: wgpu::VertexState {
module: shader,
entry_point: Some("vs_post"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: shader,
entry_point: Some("fs_sharpen"),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &constants,
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
}
/// This frame's clip space to the previous frame's, for camera-relative projections:
/// a point `camera - previous_camera` further from the previous camera than from this one.
pub(super) fn reprojection(
@@ -647,6 +744,42 @@ mod tests {
}
}
#[test]
fn written_light_changes_reject_history_before_the_next_jitter() {
let Some((device, _)) = test_device() else {
return;
};
let mut post = Post::new(&device, wgpu::TextureFormat::Rgba16Float);
post.taa = true;
if !post.supports_taa() {
return;
}
let key = (
[5.0, 4.0, 1.0, 0.0],
[0.2, 0.5, 0.6, 1.0],
[[0.1; 4], [0.4; 4]],
);
for key in [Some(key), None, Some(key)] {
post.light_representation(key);
post.jitter([32, 32], true, Mat4::IDENTITY, DVec3::ZERO);
assert_eq!(post.taa_this_frame.jitter[2], 1.0);
post.light_representation(key);
post.jitter([32, 32], true, Mat4::IDENTITY, DVec3::ZERO);
assert_eq!(post.taa_this_frame.jitter[2], 0.0);
}
for field in 0..16 {
let mut changed = key;
match field {
0..=3 => changed.0[field] += 0.01,
4..=7 => changed.1[field - 4] += 0.01,
_ => changed.2[(field - 8) / 4][(field - 8) % 4] += 0.01,
}
post.light_representation(Some(changed));
post.jitter([32, 32], true, Mat4::IDENTITY, DVec3::ZERO);
assert_eq!(post.taa_this_frame.jitter[2], 1.0);
}
}
fn test_device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = crate::gfx::test_gpu::instance();
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
@@ -33,7 +33,7 @@ pub(super) fn pipeline(
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: shader,
entry_point: Some("fs_entity"),
entry_point: Some("fs_entity_unmarked"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
@@ -67,7 +67,7 @@ struct Out { @builtin(position) pos:vec4<f32>, @location(0) color:vec4<f32> }
@vertex fn vs_entity(@location(0) pos:vec3<f32>, @location(3) color:vec4<f32>)->Out {
return Out(vec4(pos,1.0),color);
}
@fragment fn fs_entity(v:Out)->@location(0) vec4<f32> { return v.color; }
@fragment fn fs_entity_unmarked(v:Out)->@location(0) vec4<f32> { return v.color; }
"#
.into(),
),
+96 -9
View File
@@ -532,6 +532,54 @@ pub fn smooth_gradients_offered() -> bool {
SMOOTH_GRADIENTS_OFFERED.load(std::sync::atomic::Ordering::Relaxed)
}
/// GPU Culling's setting: off, on where it is offered, or Auto, which has it on only where the
/// CPU limits the frame and it makes the frame faster (`autotune::GpuCullingAuto`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum GpuCullingMode {
#[default]
Off,
On,
Auto,
}
impl GpuCullingMode {
pub const ALL: [GpuCullingMode; 3] = [
GpuCullingMode::Off,
GpuCullingMode::On,
GpuCullingMode::Auto,
];
/// The value in `horizon-graphics.txt`: `true` and `false` as the switch wrote them.
pub fn key(self) -> &'static str {
match self {
Self::Off => "false",
Self::On => "true",
Self::Auto => "auto",
}
}
/// The word `horizon-ctl gpu-culling` takes.
pub fn name(self) -> &'static str {
match self {
Self::Off => "off",
Self::On => "on",
Self::Auto => "auto",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Off => "Off",
Self::On => "On",
Self::Auto => "Auto",
}
}
fn parse(s: &str, default: Self) -> Self {
match s {
"true" | "on" => Self::On,
"false" | "off" => Self::Off,
"auto" => Self::Auto,
_ => default,
}
}
}
/// Whether GPU Culling (`Graphics::gpu_culling`) can be switched on here, and why not: set when a
/// renderer starts, and again when its pass can't be set up or its buffers stop fitting in video
/// memory. Where it isn't offered the settings grey its switch out with the reason, and the saved
@@ -672,8 +720,9 @@ pub struct Graphics {
/// Near solid terrain culled, and its draws listed, on the GPU (`gfx::gpu_culling`), where it
/// is offered (`gpu_culling_offer`). Off by default (GPU Culling, Performance graphics); it
/// applies at once, and no preset sets it. Every save writes it, so a default turned on later
/// needs a new key, as `batchTranslucent` did.
pub gpu_culling: bool,
/// needs a new key, as `batchTranslucent` did. Auto turns it on only where the CPU limits the
/// frame and it makes the frame faster (`autotune`).
pub gpu_culling: GpuCullingMode,
/// Skip drawing entities hidden behind opaque terrain, synchronously or asynchronously.
pub entity_culling: EntityCullingMode,
/// Minimum entity population for coarse AABB culling; zero disables it.
@@ -684,6 +733,8 @@ pub struct Graphics {
/// vanilla's fancy leaves. Ignored with a resource pack that may replace
/// the vanilla leaf models ([`Graphics::leaf_culling_effective`]).
pub leaf_culling: LeafCullingMode,
/// Draw regular ice opaque in the solid pass, without its see-through texture.
pub opaque_ice: bool,
/// Cache settled shulker-box models.
pub cache_shulker_boxes: bool,
/// Cache sign-text geometry.
@@ -725,6 +776,8 @@ pub struct Graphics {
pub taa: bool,
/// TAA upscaling; anything but `Native` comes with `taa` on.
pub upscaling: Upscaling,
/// How much the upscaled picture is sharpened, 0..=100 (percent of the most).
pub upscaling_sharpness: u32,
/// F2 screenshots at this many times the game's resolution: 1, 2, 4 or 8.
pub screenshot_quality: u32,
/// Frame generation (Horizon setting), off by default.
@@ -784,11 +837,12 @@ impl Default for Graphics {
far_detail: FarDetail::Full,
blue_map: crate::bluemap::Settings::default(),
cave_culling: true,
gpu_culling: false,
gpu_culling: GpuCullingMode::Off,
entity_culling: EntityCullingMode::Off,
entity_culling_precheck: 64,
particle_culling: ParticleCullingMode::Off,
leaf_culling: LeafCullingMode::Off,
opaque_ice: false,
cache_shulker_boxes: false,
// Sign text has used its renderer cache independently of the new model caches.
cache_signs: true,
@@ -813,6 +867,7 @@ impl Default for Graphics {
fxaa: false,
taa: false,
upscaling: Upscaling::Native,
upscaling_sharpness: 85,
screenshot_quality: 1,
frame_generation: FrameGeneration::Off,
hdr: false,
@@ -882,13 +937,14 @@ impl Graphics {
}
"blueMapAutoDetect" => g.blue_map.auto_detect = flag(g.blue_map.auto_detect),
"caveCulling" => g.cave_culling = flag(g.cave_culling),
"gpuCulling" => g.gpu_culling = flag(g.gpu_culling),
"gpuCulling" => g.gpu_culling = GpuCullingMode::parse(value, g.gpu_culling),
"entityCulling" => g.entity_culling = EntityCullingMode::parse(value),
"entityCullingPrecheck" => {
g.entity_culling_precheck = number(g.entity_culling_precheck).min(512)
}
"particleCulling" => g.particle_culling = ParticleCullingMode::parse(value),
"leafCulling" => g.leaf_culling = LeafCullingMode::parse(value),
"opaqueIce" => g.opaque_ice = flag(g.opaque_ice),
"blockEntityCache" => {
let enabled = flag(false);
g.cache_shulker_boxes = enabled;
@@ -935,6 +991,9 @@ impl Graphics {
"fxaa" => g.fxaa = flag(g.fxaa),
"taa" => g.taa = flag(g.taa),
"upscaling" => g.upscaling = Upscaling::parse(value),
"upscalingSharpness" => {
g.upscaling_sharpness = number(g.upscaling_sharpness).min(100)
}
"screenshotQuality" => {
g.screenshot_quality = Some(number(0))
.filter(|q| SCREENSHOT_QUALITIES.contains(q))
@@ -980,7 +1039,7 @@ impl Graphics {
}
pub fn serialize(&self) -> String {
let mut text = format!(
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nentityCullingPrecheck:{}\nparticleCulling:{}\nleafCulling:{}\nblockEntityCacheShulkerBoxes:{}\nblockEntityCacheSigns:{}\nblockEntityCacheDecoratedPots:{}\nblockEntityCacheBells:{}\nblockEntityCacheChests:{}\nblockEntityCacheBanners:{}\nblockEntityCacheCopperGolemStatues:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\ntextureBudgetMiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\nditherCutoutMips:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\ntaa:{}\nupscaling:{}\nscreenshotQuality:{}\nframeGeneration:{}\nhdr:{}\nhdrPaperWhite:{}\nhdrPeak:{}\nhdrBlackLevel:{}\nhdrUiBrightness:{}\nhdrLighting:{}\nhdrKey:{}\nbatteryMode:{}\nshadowCache:{}\ngraphicsApi:{}\npickedShaderPack:{}\nbatchTranslucent:{}\nhdrSmoothGradients:{}\ngpuCulling:{}\n",
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nentityCullingPrecheck:{}\nparticleCulling:{}\nleafCulling:{}\nopaqueIce:{}\nblockEntityCacheShulkerBoxes:{}\nblockEntityCacheSigns:{}\nblockEntityCacheDecoratedPots:{}\nblockEntityCacheBells:{}\nblockEntityCacheChests:{}\nblockEntityCacheBanners:{}\nblockEntityCacheCopperGolemStatues:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\ntextureBudgetMiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\nditherCutoutMips:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\ntaa:{}\nupscaling:{}\nupscalingSharpness:{}\nscreenshotQuality:{}\nframeGeneration:{}\nhdr:{}\nhdrPaperWhite:{}\nhdrPeak:{}\nhdrBlackLevel:{}\nhdrUiBrightness:{}\nhdrLighting:{}\nhdrKey:{}\nbatteryMode:{}\nshadowCache:{}\ngraphicsApi:{}\npickedShaderPack:{}\nbatchTranslucent:{}\nhdrSmoothGradients:{}\ngpuCulling:{}\n",
self.preset.name(),
self.lod_distance,
self.far_detail.name(),
@@ -989,6 +1048,7 @@ impl Graphics {
self.entity_culling_precheck,
self.particle_culling.name(),
self.leaf_culling.name(),
bool_text(self.opaque_ice),
bool_text(self.cache_shulker_boxes),
bool_text(self.cache_signs),
bool_text(self.cache_decorated_pots),
@@ -1019,6 +1079,7 @@ impl Graphics {
bool_text(self.fxaa),
bool_text(self.taa),
self.upscaling.name(),
self.upscaling_sharpness,
self.screenshot_quality,
self.frame_generation.name(),
bool_text(self.hdr),
@@ -1034,7 +1095,7 @@ impl Graphics {
self.shader_pack,
bool_text(self.translucent_batching),
bool_text(self.hdr_smooth_gradients),
bool_text(self.gpu_culling),
self.gpu_culling.key(),
);
text += &self.blue_map.serialize();
text
@@ -1174,11 +1235,12 @@ mod tests {
servers: Vec::new(),
},
cave_culling: false,
gpu_culling: true,
gpu_culling: GpuCullingMode::On,
entity_culling: EntityCullingMode::Synchronous,
entity_culling_precheck: 128,
particle_culling: ParticleCullingMode::Asynchronous,
leaf_culling: LeafCullingMode::SolidAggressive,
opaque_ice: true,
cache_shulker_boxes: true,
cache_signs: true,
cache_decorated_pots: true,
@@ -1202,6 +1264,7 @@ mod tests {
fxaa: true,
taa: true,
upscaling: Upscaling::Balanced,
upscaling_sharpness: 40,
screenshot_quality: 4,
frame_generation: FrameGeneration::Fsr31,
hdr: true,
@@ -1263,8 +1326,32 @@ mod tests {
assert!(!Graphics::parse("hdr:true\nhdrSmoothGradients:false\n").wide_frame());
assert!(Graphics::parse("translucentBatching:false\n").translucent_batching);
// GPU Culling is opt-in: only the file or its switch turns it on.
assert!(!Graphics::default().gpu_culling);
assert!(Graphics::parse("gpuCulling:true\n").gpu_culling);
assert_eq!(Graphics::default().gpu_culling, GpuCullingMode::Off);
assert_eq!(
Graphics::parse("gpuCulling:true\n").gpu_culling,
GpuCullingMode::On
);
// Auto is a third value of the same key. A file from before it reads as before, and an
// older Horizon reading `auto` finds a value it doesn't know and keeps Off.
assert_eq!(
Graphics::parse("gpuCulling:auto\n").gpu_culling,
GpuCullingMode::Auto
);
assert_eq!(
Graphics::parse("gpuCulling:false\n").gpu_culling,
GpuCullingMode::Off
);
assert_eq!(
Graphics::parse("gpuCulling:maybe\n").gpu_culling,
GpuCullingMode::Off
);
for mode in GpuCullingMode::ALL {
let g = Graphics {
gpu_culling: mode,
..Graphics::default()
};
assert_eq!(Graphics::parse(&g.serialize()).gpu_culling, mode);
}
// 0 is Auto; anything else is a peak the slider reaches.
assert_eq!(Graphics::parse("hdrPeak:0\n").hdr_peak, 0);
assert_eq!(Graphics::parse("hdrPeak:50\n").hdr_peak, 200);
File diff suppressed because it is too large. Load diff
+139 -72
View File
@@ -33,6 +33,11 @@ struct Params {
@group(0) @binding(2) var<uniform> params: Params;
// Horizon's logo, 1 inside, 0 outside, for calibration's test pictures.
@group(0) @binding(3) var logo: texture_2d<f32>;
// The float frame with HUD coverage (Hdr::layered): the frame keeps the world as light
// (fs_resolve), the HUD draws on a picture of its own (`hud`, fs_keep), and `coverage` says how
// much of the world it hides there (gfx/hud_coverage.rs).
@group(0) @binding(4) var coverage: texture_2d<f32>;
@group(0) @binding(5) var hud: texture_2d<f32>;
// Light sources are lifted evenly rather than by a highlight curve: vanilla's
// textures were drawn for SDR, so a curve on their brightest pixels blows out
@@ -149,80 +154,28 @@ fn calibration_nits(p: vec2<f32>, size: vec2<f32>) -> f32 {
return vec4(0.0);
}
@fragment fn fs_hdr(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let at = vec2<i32>(pos.xy);
// Calibration: above its controls the test picture, straight in nits, past
// paper white, the lift and the black level.
fn lit(f: vec3<f32>, a: f32, shows: bool, eased: bool) -> Lit {
return hdr_mark_light(f, a, shows, eased, vec4(params.peak, params.scene, params.world, params.debug), params.share);
}
// Calibration: above its controls the test picture, straight in nits, past
// paper white, the lift and the black level.
fn calibrating(pos: vec4<f32>) -> bool {
let size = vec2<f32>(textureDimensions(frame));
if params.calibration.x > 0.5 && pos.y < size.y * params.calibration.z {
let nits = vec3(calibration_nits(pos.xy, size));
if params.pq > 0.5 {
return vec4(pq(nits), 1.0);
}
return vec4(nits / 80.0, 1.0);
return params.calibration.x > 0.5 && pos.y < size.y * params.calibration.z;
}
fn calibration_picture(pos: vec4<f32>) -> vec4<f32> {
let nits = vec3(calibration_nits(pos.xy, vec2<f32>(textureDimensions(frame))));
if params.pq > 0.5 {
return vec4(pq(nits), 1.0);
}
let f = frame_texel(textureLoad(frame, at, 0));
// What covers the world here (Hdr::keep_world): nothing at 0, the hand at
// 1/255 (Hdr::mark_hand: drawn at the world's brightness), else the HUD or a
// menu, by how much.
let covered = f.a > 0.0;
let hand = covered && f.a < 1.5 / 255.0;
let ui = select(f.a, 0.0, hand);
let w = frame_texel(textureLoad(world, at, 0));
// The world's alpha is below 0.75 on light sources, the sun and the moon
// (terrain.wgsl, entity.wgsl): only those shine, and only where nothing was
// drawn over them since: grey text over the white sun still looks like the sun
// darkened, but it raised the frame's alpha. Its band of 0.175 is the tier, the
// lower the brighter, and where in the band how much (hdr_mark). The hand
// writes its own alpha there (Hdr::hand_light_view): 1, or a light source it holds.
var lifted = false;
let shows = params.world > 0.5 && params.peak > 1.0
&& (hand || (!covered && shows_world(f.rgb, w.rgb)));
// Light over 1 (a float frame's) shows only where the world does and carries
// no mark (alpha 1), up to the peak: light written as light. Marked pixels clip
// at white before their lift, as on a unorm frame, so light sources, the sun and
// HDR lighting look as they do there; so do the HUD, menus and HDR Lighting off.
let c = select(min(f.rgb, vec3(1.0)), f.rgb, shows && w.a == 1.0);
// Gamma 2.2, as SDR displays and the compositors' SDR paths decode it.
var light = pow(c, vec3(2.2));
// HDR lighting: alpha between 0.76 and 1 is how much of it the surface gets. Vanilla's
// light is albedo times lightmap, so this is the lightmap going past 1. It eases into the
// peak from 60% of it, so bright textures keep their detail. Unmarked light (alpha 1)
// gets no gain and no knee: the clamp to the peak below is all it needs here.
if shows && w.a >= 0.75 && w.a < 1.0 {
let top = max(light.r, max(light.g, light.b));
let gain = 1.0 + (params.scene - 1.0) * (1.0 - w.a) / 0.24;
let v = top * gain;
let knee = max(0.6 * params.peak, 1.0);
var out = v;
if v > knee && params.peak > knee {
out = knee + (params.peak - knee) * (1.0 - exp(-(v - knee) / (params.peak - knee)));
}
light *= select(gain, out / max(top, 1e-4), v > knee);
}
if shows && w.a < 0.75 {
let band = u32(clamp(floor((w.a + 0.005) / 0.175), 0.0, 3.0));
let tier = 3u - band;
let lift = 1.0 - clamp((w.a - 0.175 * f32(band)) / 0.165, 0.0, 1.0);
if lift > 0.0 {
let top = max(light.r, max(light.g, light.b));
let gain = min(1.0 + (params.peak - 1.0) * params.share[tier] * lift, params.peak / max(top, 1e-4));
light *= max(gain, 1.0);
lifted = true;
}
}
// HORIZON_HDR_DEBUG=1: what isn't lifted turns grey, what is keeps its
// colour with a magenta tint, so a lift shows on any colour.
if params.debug > 0.5 && params.world > 0.5 {
if lifted {
light *= vec3(1.0, 0.6, 1.0);
} else {
light = vec3(dot(light, vec3(0.2126, 0.7152, 0.0722)));
}
}
light = min(light, vec3(params.peak));
// The HUD and menus at their own brightness, by how much they cover.
light *= mix(1.0, params.ui, ui);
return vec4(nits / 80.0, 1.0);
}
// Light in units of paper white, as the swapchain takes it: HDR10 or scRGB, the black level
// lifted.
fn display(light: vec3<f32>) -> vec4<f32> {
let scrgb = light * params.paper;
if params.pq > 0.5 {
let e = pq(BT709_TO_BT2020 * scrgb * 80.0);
@@ -233,3 +186,117 @@ fn calibration_nits(p: vec2<f32>, size: vec2<f32>) -> f32 {
}
return vec4(scrgb, 1.0);
}
@fragment fn fs_hdr(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
if calibrating(pos) {
return calibration_picture(pos);
}
let at = vec2<i32>(pos.xy);
let f = frame_texel(textureLoad(frame, at, 0));
// What covers the world here (Hdr::keep_world): nothing at 0, the hand at
// 1/255 (Hdr::mark_hand: drawn at the world's brightness), else the HUD or a
// menu, by how much.
let covered = f.a > 0.0;
let hand = covered && f.a < 1.5 / 255.0;
let ui = select(f.a, 0.0, hand);
let w = frame_texel(textureLoad(world, at, 0));
// The world's marks lift only where nothing was drawn over them since: grey text over
// the white sun still looks like the sun darkened, but it raised the frame's alpha. The
// hand writes its own alpha there (Hdr::hand_light_view): 1, or a light source it holds.
let shows = params.world > 0.5 && params.peak > 1.0
&& (hand || (!covered && shows_world(f.rgb, w.rgb)));
var light = lit(f.rgb, w.a, shows, true).light;
// The HUD and menus at their own brightness, by how much they cover.
light *= mix(1.0, params.ui, ui);
return display(light);
}
// Hdr::resolve, after the world and the hand: the marks they left (`world` holds the frame as
// they drew it) become light in the frame, in gamma as the frame stores it, alpha 1, past the
// peak if they lift it there (the tone curve eases it in). What draws after it (camera overlays,
// the menu blur) draws on light, and nothing is lifted later.
@fragment fn fs_resolve(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let w = frame_texel(textureLoad(world, vec2<i32>(pos.xy), 0));
let shows = params.world > 0.5 && params.peak > 1.0;
return vec4(pow(lit(w.rgb, w.a, shows, false).light, vec3(1.0 / 2.2)), 1.0);
}
// The tone curve's knee: up to it light stays as it is. Where HDR lighting eased into the peak
// before the curve (`lit`), 60% of it, so bright textures keep their detail; at least paper white.
fn tone_knee(headroom: f32) -> f32 {
return max(0.6 * headroom, 1.0);
}
// The tone curve on light whose brightest channel is `top`, in units of paper white `paper`
// nits: what to scale the light by, so it ends at most `headroom` (above 1). ITU-R BT.2390's
// EETF in PQ, without the black level lift (`display` does that): the same up to its knee, then
// a Hermite spline that reaches the peak level, at the source's peak. That peak is where the knee
// lands at `tone_knee`, PQ's 10 000 nits at most; light past it shows at the peak. The brightest
// channel sets the scale for all three, so light keeps its hue as it eases (lava stays orange)
// and no channel passes the peak.
fn tone_scale(top: f32, headroom: f32, paper: f32) -> f32 {
if top <= tone_knee(headroom) {
return 1.0;
}
let peak = pq(vec3(headroom * paper)).x;
let source = min(3.0 * peak - 2.0 * pq(vec3(tone_knee(headroom) * paper)).x, 1.0);
let e = pq(vec3(top * paper)).x / source;
let max_lum = peak / source;
let ks = 1.5 * max_lum - 0.5;
if e >= 1.0 {
return headroom / top;
}
if e <= ks {
return 1.0;
}
let t = (e - ks) / (1.0 - ks);
let t2 = t * t;
let t3 = t2 * t;
let p = (2.0 * t3 - 3.0 * t2 + 1.0) * ks + (t3 - 2.0 * t2 + t) * (1.0 - ks) + (3.0 * t2 - 2.0 * t3) * max_lum;
return pq_nits(vec3(p * source)).x / paper / top;
}
// Hdr::tonemap, after the post effects and before the camera overlays (docs/design/
// hdr-linear-light.md, `[tonemap]`): the light (`world` holds the frame) eased into the peak, in
// gamma, where scaling the light by s scales the stored colour by s^(1/2.2). Light up to the
// knee stays exactly as stored. With no headroom, a clip at white.
@fragment fn fs_tonemap(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let g = textureLoad(world, vec2<i32>(pos.xy), 0).rgb;
if params.peak <= 1.0 {
return vec4(min(g, vec3(1.0)), 1.0);
}
let top = pow(max(max(g.r, max(g.g, g.b)), 0.0), 2.2);
let s = tone_scale(top, params.peak, params.paper * 80.0);
return vec4(select(g * pow(s, 1.0 / 2.2), g, s == 1.0), 1.0);
}
// Hdr::keep_world: the HUD's backdrop, the world clipped to white with alpha 0, the frame as
// the HUD found it before.
@fragment fn fs_keep(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let w = textureLoad(frame, vec2<i32>(pos.xy), 0).rgb;
return vec4(clamp(w, vec3(0.0), vec3(1.0)), 0.0);
}
// The HUD over the world in gamma, the space the HUD blends in: its own part, what its backdrop
// B doesn't explain (H = P - (1 - c) B, exact for the layering blends), at UI Brightness, over
// (1 - c) of the world, light above white included. Where the world is at or below white, at
// 100%, that is the HUD's picture as drawn.
fn layered(at: vec2<i32>) -> vec3<f32> {
let w = max(textureLoad(frame, at, 0).rgb, vec3(0.0));
let p = clamp(textureLoad(hud, at, 0).rgb, vec3(0.0), vec3(1.0));
let c = textureLoad(coverage, at, 0).r;
let h = max(p - (1.0 - c) * min(w, vec3(1.0)), vec3(0.0));
return h * pow(params.ui, 1.0 / 2.2) + (1.0 - c) * w;
}
// Hdr::composite: the picture so far, stored as the frame stores light, for the menu blur.
@fragment fn fs_composite(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
return vec4(layered(vec2<i32>(pos.xy)), 1.0);
}
@fragment fn fs_hdr_layered(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
if calibrating(pos) {
return calibration_picture(pos);
}
return display(min(pow(layered(vec2<i32>(pos.xy)), vec3(2.2)), vec3(params.peak)));
}
@@ -0,0 +1,76 @@
override HDR_WRITE_LIGHT: bool = false;
// The light of colour `f` under the world's mark `a` (the alpha the world left, hdr_mark) where
// the world `shows`, else the colour clipped at white; and whether a light source lifted it.
// `eased` for the last pass, which eases it into the peak itself; the layered frame leaves that
// to the tone curve (fs_tonemap).
struct Lit {
light: vec3<f32>,
lifted: bool,
};
fn hdr_mark_light(f: vec3<f32>, a: f32, shows: bool, eased: bool, settings: vec4<f32>, shares: vec4<f32>) -> Lit {
var lifted = false;
// Light over 1 (a float frame's) shows only where the world does and carries
// no mark (alpha 1), up to the peak: light written as light. Marked pixels clip
// at white before their lift, as on a unorm frame, so light sources, the sun and
// HDR lighting look as they do there; so do the HUD, menus and HDR Lighting off.
let c = select(min(f, vec3(1.0)), f, shows && a == 1.0);
// Gamma 2.2, as SDR displays and the compositors' SDR paths decode it.
var light = pow(c, vec3(2.2));
// HDR lighting: alpha between 0.76 and 1 is how much of it the surface gets. Vanilla's
// light is albedo times lightmap, so this is the lightmap going past 1. It eases into the
// peak from 60% of it, so bright textures keep their detail. Unmarked light (alpha 1)
// gets no gain and no knee: the clamp to the peak below is all it needs here.
if shows && a >= 0.75 && a < 1.0 {
let top = max(light.r, max(light.g, light.b));
let gain = 1.0 + (settings.y - 1.0) * (1.0 - a) / 0.24;
let v = top * gain;
let knee = max(0.6 * settings.x, 1.0);
var out = v;
if eased && v > knee && settings.x > knee {
out = knee + (settings.x - knee) * (1.0 - exp(-(v - knee) / (settings.x - knee)));
}
light *= select(gain, out / max(top, 1e-4), eased && v > knee);
}
// The world's alpha is below 0.75 on light sources, the sun and the moon
// (terrain.wgsl, entity.wgsl): its band of 0.175 is the tier, the lower the
// brighter, and where in the band how much (hdr_mark).
if shows && a < 0.75 {
let band = u32(clamp(floor((a + 0.005) / 0.175), 0.0, 3.0));
let tier = 3u - band;
let lift = 1.0 - clamp((a - 0.175 * f32(band)) / 0.165, 0.0, 1.0);
if lift > 0.0 {
let top = max(light.r, max(light.g, light.b));
var gain = 1.0 + (settings.x - 1.0) * shares[tier] * lift;
if eased {
gain = min(gain, settings.x / max(top, 1e-4));
}
light *= max(gain, 1.0);
lifted = true;
}
}
// HORIZON_HDR_DEBUG=1: what isn't lifted turns grey, what is keeps its
// colour with a magenta tint, so a lift shows on any colour.
if settings.w > 0.5 && settings.z > 0.5 {
if lifted {
light *= vec3(1.0, 0.6, 1.0);
} else {
light = vec3(dot(light, vec3(0.2126, 0.7152, 0.0722)));
}
}
if eased {
light = min(light, vec3(settings.x));
}
return Lit(light, lifted);
}
// Marks are decoded at the precision of the original 8-bit frame, even in a float target.
fn hdr_quantized_mark(mark: f32) -> f32 {
return round(saturate(mark) * 255.0) / 255.0;
}
fn hdr_written(color: vec3<f32>, mark: f32, settings: vec4<f32>, shares: vec4<f32>) -> vec3<f32> {
let shows = settings.z > 0.5 && settings.x > 1.0;
return pow(hdr_mark_light(max(color, vec3(0.0)), hdr_quantized_mark(mark), shows, false, settings, shares).light, vec3(1.0 / 2.2));
}
+295 -69
View File
@@ -100,12 +100,18 @@ pub struct HudAtlas {
/// A resource pack's own `core/rendertype_lines` shader for the block outline, translated;
/// none draws the outline natively.
pub lines_shader: Option<std::sync::Arc<horizon_shaders::CoreProgram>>,
/// The packs' `core/sky` and `core/stars`, when a pack replaces them.
pub sky_shader: Option<std::sync::Arc<horizon_shaders::CoreProgram>>,
pub stars_shader: Option<std::sync::Arc<horizon_shaders::CoreProgram>>,
/// The packs' OptiFine random entity textures, whose variants this atlas packs.
pub random_textures: horizon_optifine::random_textures::RandomTextures,
/// Their emissive overlays (`_e`), packed here too.
pub emissive: std::sync::Arc<horizon_optifine::emissive::Emissive>,
/// ETF's blinking frames (`_blink`), packed here too.
pub blinks: horizon_optifine::blink::Blinks,
/// Of the shared atlas's textures, their LabPBR normal and specular maps as paged maps
/// (`paged_maps.rs`), read while loading for shader packs (`sprites::labpbr_maps`).
pub material_maps: std::sync::Arc<[Option<crate::paged_maps::PagedMap>; 2]>,
white: Rect,
}
/// Atlas rows reserved for glyphs rasterized at run time.
@@ -531,6 +537,49 @@ fn cit_sprite(root: &Path, id: &str) -> Option<(PackedImage, Option<TextureFlags
let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta);
Some(((name.to_owned(), w, h, pixels), flags, animation.is_some()))
}
/// The texture of every `bitmap` font provider. A provider's `file` may name
/// any texture, so a pack's glyph sheet need not live under `textures/font`.
fn bitmap_font_textures(root: &Path) -> Vec<PathBuf> {
fn jsons(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() {
jsons(&path, out);
} else if path.extension().is_some_and(|e| e == "json") {
out.push(path);
}
}
}
let assets = root.join("assets");
let mut defs = Vec::new();
for ns in fs::read_dir(&assets).into_iter().flatten().flatten() {
jsons(&ns.path().join("font"), &mut defs);
}
let mut out = Vec::new();
let mut seen = HashSet::new();
for def in defs {
let Ok(bytes) = fs::read(&def) else { continue };
let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes);
let Ok(json) = serde_json::from_slice::<serde_json::Value>(bytes) else {
continue;
};
for p in json["providers"].as_array().into_iter().flatten() {
if p["type"] != "bitmap" {
continue;
}
let Some(file) = p["file"].as_str() else {
continue;
};
let (ns, path) = file.split_once(':').unwrap_or(("minecraft", file));
let path = assets.join(ns).join("textures").join(path);
if path.is_file() && seen.insert(path.clone()) {
out.push(path);
}
}
}
out
}
/// Folders of `assets/minecraft/textures/` that [`HudAtlas::pack`] walks for
/// the full atlas. A pack may add others through `atlases/blocks.json`.
const WALKED_TEXTURE_FOLDERS: &[&str] = &[
@@ -845,6 +894,10 @@ impl HudAtlas {
&[],
&crate::gfx::core_lines::GLUE,
);
let sky =
|name| pack_text::load_core(root, defaults, name, &[], &crate::gfx::core_sky::GLUE);
atlas.sky_shader = sky("sky");
atlas.stars_shader = sky("stars");
Ok(atlas)
}
/// Empty slots written at run time: map textures (game/maps.rs), the
@@ -924,6 +977,7 @@ impl HudAtlas {
revision: Self::next_revision(),
pixels: Vec::new(),
packed: None,
material_maps: Default::default(),
galactic_widths: [0; 128],
width: 1,
height: 1,
@@ -938,6 +992,8 @@ impl HudAtlas {
glint_armor: (Vec::new(), 1, 1),
text_shader: None,
lines_shader: None,
sky_shader: None,
stars_shader: None,
random_textures: Default::default(),
emissive: Arc::default(),
blinks: Default::default(),
@@ -986,6 +1042,7 @@ impl HudAtlas {
(glyph_top, height - glyph_top),
white,
),
material_maps: Default::default(),
galactic_widths: galactic_widths(&sprites, &pixels, width, height),
pixels,
packed: None,
@@ -1002,6 +1059,8 @@ impl HudAtlas {
white,
text_shader: None,
lines_shader: None,
sky_shader: None,
stars_shader: None,
random_textures: Default::default(),
emissive: Default::default(),
blinks: Default::default(),
@@ -1102,6 +1161,18 @@ impl HudAtlas {
for folder in folders {
walk(&textures.join(folder), &mut files);
}
// A bitmap provider's `file` may be outside the walked folders (HUD
// packs keep their glyph sheets under their own namespace or path).
// Pack those sheets too, so Font reads them from the atlas instead of
// copying every glyph into the small run-time region.
if folders.contains(&"font") {
let mut seen: HashSet<PathBuf> = files.iter().cloned().collect();
files.extend(
bitmap_font_textures(root)
.into_iter()
.filter(|p| seen.insert(p.clone())),
);
}
// Content mods' entity textures: their equipment assets name them as
// `<ns>:<path>`, and native mods draw their block entities with them
// (`native_draw_quad`: `<ns>:entity/...`); and their mob effects'
@@ -1137,9 +1208,21 @@ impl HudAtlas {
}
}
}
// The title panorama and the New World preset pictures load on their own. The
// Realms world-slot pictures are drawn from this atlas (vanilla draws their
// textures full size): the three faces and `presets/isles.png` stay, costing
// one 1024-tall shelf.
files.retain(|p| {
let s = p.to_string_lossy();
!s.contains("title/background") && !s.contains("presets")
let s = p.to_string_lossy().replace('\\', "/");
let slot_picture = [
"textures/gui/title/background/panorama_0.png",
"textures/gui/title/background/panorama_2.png",
"textures/gui/title/background/panorama_3.png",
"textures/gui/presets/isles.png",
]
.iter()
.any(|kept| s.ends_with(kept));
slot_picture || (!s.contains("title/background") && !s.contains("presets"))
});
// OptiFine random entity variants, under the names their scan gives them (those
// outside `textures/` are `<ns>:optifine/random/...`).
@@ -1214,61 +1297,87 @@ impl HudAtlas {
extra.sort();
files.extend(extra);
}
type Decoded = (PackedImage, Option<TextureFlags>, Option<(u32, u32)>, bool);
let decode_one = |path: &PathBuf| -> Option<Decoded> {
let name = if let Some(name) = named.get(path) {
name.clone()
} else {
match path.strip_prefix(&textures) {
Ok(rel) => rel.with_extension("").to_string_lossy().replace('\\', "/"),
Err(_) => {
let rel = path.strip_prefix(&assets).ok()?.with_extension("");
let rel = rel.to_string_lossy().replace('\\', "/");
let (namespace, rest) = rel.split_once("/textures/")?;
format!("{namespace}:{rest}")
// A texture's LabPBR maps, as decoded (width, height, RGBA8), for shader packs.
type Maps = [Option<(u32, u32, Vec<u8>)>; 2];
let read_maps = full && crate::sprites::labpbr_maps();
type Decoded = (
PackedImage,
Option<TextureFlags>,
Option<(u32, u32)>,
bool,
Option<Box<Maps>>,
);
let decode_one =
|path: &PathBuf| -> Option<Decoded> {
let name = if let Some(name) = named.get(path) {
name.clone()
} else {
match path.strip_prefix(&textures) {
Ok(rel) => rel.with_extension("").to_string_lossy().replace('\\', "/"),
Err(_) => {
let rel = path.strip_prefix(&assets).ok()?.with_extension("");
let rel = rel.to_string_lossy().replace('\\', "/");
let (namespace, rest) = rel.split_once("/textures/")?;
format!("{namespace}:{rest}")
}
}
};
// LabPBR's maps beside a texture are the world's (sprites.rs), not images to draw.
if let Some(base) = name.strip_suffix("_n").or_else(|| name.strip_suffix("_s"))
&& textures.join(format!("{base}.png")).is_file()
{
return None;
}
let image = decode(path)
.map_err(|e| log::warn!("skipped GUI texture {}: {e}", path.display()))
.ok()?;
let mcmeta = horizon_core::prepared_files::read_to_string(
&path.with_extension("png.mcmeta"),
)
.ok();
let animation = animation_of(mcmeta.as_deref());
// An animated strip keeps its first frame.
let frames =
animation.is_some() || name.starts_with("block/") || name.starts_with("item/");
let (w, h, pixels) = if frames {
first_frame(image, animation.as_ref())
} else {
image
};
// The default texture's size, when a pack's differs from it.
let gui_size = default_textures
.as_ref()
.and_then(|d| png_size(&d.join(format!("{name}.png"))))
.map(|(dw, dh)| {
let side = dw.min(dh);
if frames { (side, side) } else { (dw, dh) }
})
.filter(|&size| size != (w, h));
let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta);
let animated = frames && animation.is_some();
let (gw, gh) = gui_size.unwrap_or((w, h));
let maps = read_maps
.then(|| {
let stem = path.file_stem()?.to_str()?;
let maps: Maps = ["_n", "_s"].map(|suffix| {
decode(&path.with_file_name(format!("{stem}{suffix}.png"))).ok()
});
maps.iter().any(Option::is_some).then(|| Box::new(maps))
})
.flatten();
// The Realms world-slot pictures are 1024-tall GUI textures drawn as
// they are; the cap that keeps other GUI textures small does not
// apply to them.
let tall_picture = matches!(
name.as_str(),
"gui/title/background/panorama_0"
| "gui/title/background/panorama_2"
| "gui/title/background/panorama_3"
| "gui/presets/isles"
);
(gw <= 1024 && (gh <= 512 || tall_picture || name.starts_with("font/")))
.then_some(((name, w, h, pixels), flags, gui_size, animated, maps))
};
// LabPBR's maps beside a texture are the world's (sprites.rs), not images to draw.
if let Some(base) = name.strip_suffix("_n").or_else(|| name.strip_suffix("_s"))
&& textures.join(format!("{base}.png")).is_file()
{
return None;
}
let image = decode(path)
.map_err(|e| log::warn!("skipped GUI texture {}: {e}", path.display()))
.ok()?;
let mcmeta =
horizon_core::prepared_files::read_to_string(&path.with_extension("png.mcmeta"))
.ok();
let animation = animation_of(mcmeta.as_deref());
// An animated strip keeps its first frame.
let frames =
animation.is_some() || name.starts_with("block/") || name.starts_with("item/");
let (w, h, pixels) = if frames {
first_frame(image, animation.as_ref())
} else {
image
};
// The default texture's size, when a pack's differs from it.
let gui_size = default_textures
.as_ref()
.and_then(|d| png_size(&d.join(format!("{name}.png"))))
.map(|(dw, dh)| {
let side = dw.min(dh);
if frames { (side, side) } else { (dw, dh) }
})
.filter(|&size| size != (w, h));
let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta);
let animated = frames && animation.is_some();
let (gw, gh) = gui_size.unwrap_or((w, h));
(gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some((
(name, w, h, pixels),
flags,
gui_size,
animated,
))
};
let threads = std::thread::available_parallelism().map_or(2, |n| n.get());
let chunk = files.len().div_ceil(threads).max(1);
let decoded: Vec<_> = std::thread::scope(|scope| {
@@ -1287,7 +1396,11 @@ impl HudAtlas {
let mut gui_sizes = HashMap::new();
let mut animated: Vec<String> = Vec::new();
let mut images: Vec<PackedImage> = Vec::with_capacity(decoded.len());
for (image, image_flags, gui_size, is_animated) in decoded {
let mut maps: HashMap<String, Box<Maps>> = HashMap::new();
for (image, image_flags, gui_size, is_animated, image_maps) in decoded {
if let Some(m) = image_maps {
maps.insert(image.0.clone(), m);
}
if let Some(f) = image_flags {
flags.insert(image.0.clone(), f);
}
@@ -1462,11 +1575,34 @@ impl HudAtlas {
}
sprite_animations.push((rect, animation));
}
// Each mapped texture's maps at its size in the atlas, paged.
let material_maps = if maps.is_empty() {
Default::default()
} else {
let mapped: Vec<crate::paged_maps::SpriteMaps> = maps
.iter()
.filter_map(|(name, m)| {
let rect = sprites.get(name)?;
let (tw, th) = rect.texels((width, height));
let x = (rect.u0 * width as f32).round() as u32;
let y = (rect.v0 * height as f32).round() as u32;
Some(crate::paged_maps::SpriteMaps {
rect: [x, y, tw, th],
maps: m.each_ref().map(|map| {
let (mw, mh, pixels) = map.as_ref()?;
crate::paged_maps::fit(pixels, (*mw, *mh), (tw, th))
}),
})
})
.collect();
crate::paged_maps::build((width, height), &mapped, MAX_ATLAS_SIZE)
};
let white = sprites["horizon/white"];
let glint = Self::glint_texture(root, defaults, "enchanted_glint_item");
let glint_armor = Self::glint_texture(root, defaults, "enchanted_glint_armor");
let font = crate::font::Font::load(
let font = crate::font::Font::load_over(
root,
defaults,
&sprites,
&pixels,
(width, height),
@@ -1475,6 +1611,7 @@ impl HudAtlas {
);
Ok(Self {
revision: Self::next_revision(),
material_maps: std::sync::Arc::new(material_maps),
galactic_widths: galactic_widths(&sprites, &pixels, width, height),
pixels,
packed: None,
@@ -1490,6 +1627,8 @@ impl HudAtlas {
glint_armor,
text_shader: None,
lines_shader: None,
sky_shader: None,
stars_shader: None,
random_textures,
emissive,
blinks,
@@ -2379,17 +2518,19 @@ impl HudUniform {
}
}
}
use crate::gfx::hud_coverage::{self, Pipeline};
pub struct HudRenderer {
pub sprite_animations: Vec<(Rect, crate::sprites::SpriteAnimation, (usize, usize, u32))>,
/// The shared atlas texture, for run-time glyph uploads.
pub atlas_texture: Option<wgpu::Texture>,
pipeline: wgpu::RenderPipeline,
pipeline: Pipeline,
/// `RenderPipelines.CROSSHAIR`.
invert_pipeline: wgpu::RenderPipeline,
additive_pipeline: wgpu::RenderPipeline,
depth_pipeline: wgpu::RenderPipeline,
vignette_pipeline: wgpu::RenderPipeline,
end_portal_pipeline: wgpu::RenderPipeline,
invert_pipeline: Pipeline,
additive_pipeline: Pipeline,
depth_pipeline: Pipeline,
vignette_pipeline: Pipeline,
end_portal_pipeline: Pipeline,
/// The layout of `group`, which the CIT glint pipelines share.
layout: wgpu::BindGroupLayout,
group: wgpu::BindGroup,
@@ -2399,6 +2540,7 @@ pub struct HudRenderer {
buffer: wgpu::Buffer,
capacity: u64,
format: wgpu::TextureFormat,
coverage: bool,
atlas_view: wgpu::TextureView,
/// The resource pack's text shader, when it has one that works.
pack_text: Option<pack_text::PackText>,
@@ -2413,6 +2555,7 @@ impl HudRenderer {
view: &wgpu::TextureView,
glint_view: &wgpu::TextureView,
glint_sampler: &wgpu::Sampler,
coverage: bool,
) -> Result<Self> {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon HUD"),
@@ -2525,7 +2668,7 @@ impl HudRenderer {
let attributes =
wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4,3=>Float32,4=>Float32x2];
let create = |label, blend, fragment_entry, depth: bool| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
let desc = wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
@@ -2559,7 +2702,9 @@ impl HudRenderer {
}),
multiview_mask: None,
cache: None,
})
};
let source = wgpu::ShaderSource::Wgsl(include_str!("hud.wgsl").into());
Pipeline::new(device, &desc, source, coverage).expect("the HUD's coverage")
};
let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main", false);
let depth_pipeline = create(
@@ -2650,6 +2795,7 @@ impl HudRenderer {
buffer,
capacity,
format,
coverage,
atlas_view: view.clone(),
pack_text: None,
zoom: 1.0,
@@ -2664,7 +2810,7 @@ impl HudRenderer {
textures: Option<&cit_glint::GlintTextures>,
) {
self.cit_glint = textures.and_then(|t| {
cit_glint::CitGlintPass::new(device, queue, self.format, &self.layout, t)
cit_glint::CitGlintPass::new(device, queue, self.format, &self.layout, t, self.coverage)
});
}
/// Draw the GUI's text with `shader` (`HudAtlas::text_shader`), or natively.
@@ -2674,7 +2820,7 @@ impl HudRenderer {
shader: Option<&horizon_shaders::CoreProgram>,
) {
self.pack_text = shader.and_then(|shader| {
pack_text::PackText::new(device, self.format, &self.atlas_view, shader)
pack_text::PackText::new(device, self.format, &self.atlas_view, shader, self.coverage)
});
}
pub fn animate_sprites(
@@ -2823,6 +2969,7 @@ impl HudRenderer {
self.draw_range(
encoder,
target,
None,
depth,
batch,
size,
@@ -2836,6 +2983,7 @@ impl HudRenderer {
&self,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
coverage: Option<&wgpu::TextureView>,
depth: &wgpu::TextureView,
batch: &HudBatch,
size: [u32; 2],
@@ -2845,7 +2993,7 @@ impl HudRenderer {
if vertices.is_empty() || size.contains(&0) {
return;
}
let attachments = [Some(wgpu::RenderPassColorAttachment {
let mut attachments = vec![Some(wgpu::RenderPassColorAttachment {
view: target,
resolve_target: None,
depth_slice: None,
@@ -2854,6 +3002,9 @@ impl HudRenderer {
store: wgpu::StoreOp::Store,
},
})];
if let Some(view) = coverage {
attachments.push(Some(hud_coverage::attachment(view)));
}
let runs = batch.runs_in(vertices);
let mut at = 0;
while at < runs.len() {
@@ -2905,16 +3056,17 @@ impl HudRenderer {
Blend::EndPortal => &self.end_portal_pipeline,
Blend::CitGlint(blend) => {
if let Some(cit) = &self.cit_glint {
cit.draw(&mut pass, *blend, range.clone());
cit.draw(&mut pass, *blend, range.clone(), coverage.is_some());
}
continue;
}
};
let pipeline = pipeline.get(coverage.is_some());
match &self.pack_text {
Some(pack_text) if *blend == Blend::Alpha => {
for (part, text) in pack_text::text_runs(&batch.vertices, range.clone()) {
if text {
pack_text.draw(&mut pass, part);
pack_text.draw(&mut pass, part, coverage.is_some());
pass.set_bind_group(0, &self.group, &[]);
} else {
pass.set_pipeline(pipeline);
@@ -2933,6 +3085,10 @@ impl HudRenderer {
}
}
#[cfg(test)]
#[path = "hud/coverage_tests.rs"]
mod coverage_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -3891,6 +4047,30 @@ texture=wide",
assert_eq!(((r.w, r.h), r.texels(size)), (gui, texels), "{name}");
}
}
/// A bitmap font's `file` may be any texture, not only one under
/// `textures/font`; the atlas packs it so the font can read its glyphs
/// from there instead of copying them into the run-time region.
#[test]
fn a_bitmap_font_sheet_outside_font_is_packed() {
let root = std::env::temp_dir().join(format!("horizon-font-pack-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
write_png(&root, "hud/sheet", 16, 8);
let def = root.join("assets/minecraft/font/default.json");
fs::create_dir_all(def.parent().unwrap()).unwrap();
fs::write(
&def,
r#"{"providers":[{"type":"bitmap","file":"minecraft:hud/sheet.png","ascent":7,"chars":["ab"]}]}"#,
)
.unwrap();
let atlas = HudAtlas::build(&root).unwrap();
let _ = fs::remove_dir_all(&root);
let rect = atlas
.sprites
.get("hud/sheet")
.expect("the font sheet is packed");
assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 8));
}
/// A content mod's GUI textures join the atlas under its namespace;
/// its other textures and vanilla's names stay as they were.
#[test]
@@ -4010,6 +4190,52 @@ texture=wide",
.unwrap();
root
}
/// A pack layer that adds a font provider over the game's own resources:
/// its `font/default.json` names `minecraft:font/test.png`, which only the
/// game's root holds (`HudAtlas::build_over`'s `defaults`).
fn pack_font_over_defaults(name: &str) -> (PathBuf, PathBuf) {
let base = std::env::temp_dir().join(format!(
"horizon-font-fallback-{name}-{}",
std::process::id()
));
let pack = base.join("pack");
let vanilla = base.join("vanilla");
fs::create_dir_all(pack.join("assets/minecraft/font")).unwrap();
fs::create_dir_all(vanilla.join("assets/minecraft/textures/font")).unwrap();
fs::write(
pack.join("assets/minecraft/font/default.json"),
r#"{"providers":[{"type":"bitmap","file":"minecraft:font/test.png","ascent":7,"chars":["ab"]}]}"#,
)
.unwrap();
let mut pixels = vec![0u8; 16 * 8 * 4];
for y in 0..8 {
for x in (0..3).chain(8..13) {
pixels[(y * 16 + x) * 4 + 3] = 255;
}
}
let mut encoder = png::Encoder::new(
fs::File::create(vanilla.join("assets/minecraft/textures/font/test.png")).unwrap(),
16,
8,
);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(&pixels)
.unwrap();
(pack, vanilla)
}
#[test]
fn a_pack_overlay_reads_font_sheets_from_the_game_below_it() {
let (pack, vanilla) = pack_font_over_defaults("sheets");
let atlas = HudAtlas::build_over(&pack, &vanilla).unwrap();
let glyph = atlas.font.glyph('a');
let _ = fs::remove_dir_all(pack.parent().unwrap());
assert!(glyph.rect.is_some(), "text draws, not the missing glyph");
assert!(glyph.advance > 0.0);
}
#[test]
fn the_fonts_only_atlas_measures_text_like_the_full_one() {
let root = two_glyph_font("atlas");
@@ -5,6 +5,7 @@
//! vanilla's glint's is. Without enchantment rules nothing here is made.
use super::HudVertex;
use crate::gfx::hud_coverage::Pipeline;
use horizon_optifine::cit::{Blend, Factor, Kind, Rule};
use std::path::Path;
@@ -230,7 +231,7 @@ pub fn blend_state(blend: Option<Blend>) -> wgpu::BlendState {
/// pipeline per blend.
pub(super) struct CitGlintPass {
group: wgpu::BindGroup,
pipelines: Vec<wgpu::RenderPipeline>,
pipelines: Vec<Pipeline>,
}
impl CitGlintPass {
@@ -241,6 +242,7 @@ impl CitGlintPass {
format: wgpu::TextureFormat,
hud: &wgpu::BindGroupLayout,
textures: &GlintTextures,
coverage: bool,
) -> Option<Self> {
use wgpu::util::DeviceExt;
if textures.is_empty() {
@@ -381,7 +383,7 @@ impl CitGlintPass {
.blends
.iter()
.map(|&blend| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
let desc = wgpu::RenderPipelineDescriptor {
label: Some("CIT glint"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
@@ -409,7 +411,9 @@ impl CitGlintPass {
}),
multiview_mask: None,
cache: None,
})
};
let source = wgpu::ShaderSource::Wgsl(include_str!("../hud.wgsl").into());
Pipeline::new(device, &desc, source, coverage).expect("the CIT glint's coverage")
})
.collect();
Some(Self { group, pipelines })
@@ -421,9 +425,10 @@ impl CitGlintPass {
pass: &mut wgpu::RenderPass<'_>,
blend: u8,
vertices: std::ops::Range<u32>,
coverage: bool,
) {
if let Some(pipeline) = self.pipelines.get(usize::from(blend)) {
pass.set_pipeline(pipeline);
pass.set_pipeline(pipeline.get(coverage));
pass.set_bind_group(1, &self.group, &[]);
pass.draw(vertices, 0..1);
}
@@ -0,0 +1,311 @@
use super::*;
use crate::gfx::hud_coverage;
struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
hud: HudRenderer,
}
impl Gpu {
fn new() -> Option<Self> {
let instance = crate::gfx::test_gpu::instance();
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
if !hud_coverage::supported(
(false, true, true),
true,
adapter.limits().max_color_attachments,
adapter.get_downlevel_capabilities().flags,
adapter.get_texture_format_features(hud_coverage::FORMAT),
) {
eprintln!("skipping HUD coverage: adapter lacks independent blending or R8 rendering");
return None;
}
let (device, queue) =
pollster::block_on(adapter.request_device(&Default::default())).ok()?;
let atlas = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 2,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
&[255, 255, 255, 255, 255, 255, 255, 0],
);
let view = atlas.create_view(&Default::default());
let hud = HudRenderer::new(
&device,
wgpu::TextureFormat::Rgba16Float,
&view,
&view,
&device.create_sampler(&Default::default()),
true,
)
.unwrap();
Some(Self { device, queue, hud })
}
fn texture(&self, format: wgpu::TextureFormat) -> wgpu::Texture {
self.device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 4,
height: 2,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
})
}
fn draw(&self, batch: &HudBatch, initial: f64, coverage: bool) -> (Vec<u8>, Vec<u8>) {
let frame = self.texture(wgpu::TextureFormat::Rgba16Float);
let mask = self.texture(hud_coverage::FORMAT);
let depth = self.texture(wgpu::TextureFormat::Depth32Float);
let [frame_view, mask_view, depth_view] =
[&frame, &mask, &depth].map(|t| t.create_view(&Default::default()));
self.queue
.write_buffer(&self.hud.buffer, 0, bytemuck::cast_slice(&batch.vertices));
self.queue.write_buffer(
&self.hud.uniform,
0,
bytemuck::bytes_of(&HudUniform::new([4.0, 2.0, 1.0, 0.75], batch.end_portal, 0)),
);
let mut encoder = self.device.create_command_encoder(&Default::default());
for (view, value) in [(&frame_view, 0.3), (&mask_view, initial)] {
let mut attachment = hud_coverage::attachment(view);
attachment.ops.load = wgpu::LoadOp::Clear(wgpu::Color {
r: value,
g: value,
b: value,
a: value,
});
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(attachment)],
..Default::default()
});
}
self.hud.draw_range(
&mut encoder,
&frame_view,
coverage.then_some(&mask_view),
&depth_view,
batch,
[4, 2],
0..batch.vertices.len() as u32,
None,
);
let buffers = [&frame, &mask].map(|t| {
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 512,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
t.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(256),
rows_per_image: None,
},
},
t.size(),
);
buffer
});
self.queue.submit([encoder.finish()]);
let [color, mask] = buffers.map(|buffer| {
buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
self.device
.poll(wgpu::PollType::wait_indefinitely())
.unwrap();
buffer.get_mapped_range(..).unwrap().to_vec()
});
(
color
.chunks(256)
.flat_map(|r| r[..32].iter().copied())
.collect(),
mask.chunks(256)
.flat_map(|r| r[..4].iter().copied())
.collect(),
)
}
fn check(&self, batch: &HudBatch, initial: f64, expected: [u8; 4]) {
let (plain, _) = self.draw(batch, initial, false);
let (color, mask) = self.draw(batch, initial, true);
assert_eq!(color, plain, "coverage changed the primary colour or alpha");
for (got, want) in mask.iter().zip(expected.repeat(2)) {
assert!(
got.abs_diff(want) <= 1,
"coverage {mask:?}, expected {expected:?}"
);
}
}
}
fn quad(batch: &mut HudBatch, blend: Blend, color: u32, x: f32, uv: f32) {
let start = batch.vertices.len();
batch.quad(
[[x, 0.0], [x + 2.0, 0.0], [x + 2.0, 2.0], [x, 2.0]],
[[uv, 0.5]; 4],
color,
);
batch.blend_since(start, blend);
}
#[test]
fn coverage_follows_hud_blends_discard_scissor_and_depth_without_changing_colour() {
let Some(gpu) = Gpu::new() else {
return;
};
for (blend, color, initial, count, expected) in [
(Blend::Alpha, rgba(255, 255, 255, 128), 0.0, 2, 192),
(Blend::Additive, rgba(255, 255, 255, 128), 0.3, 1, 77),
(Blend::Invert, rgba(255, 255, 255, 32), 0.0, 1, 255),
(Blend::EndPortal, rgba(255, 255, 255, 255), 0.0, 1, 255),
(Blend::Vignette, rgba(102, 102, 102, 255), 0.0, 1, 102),
] {
let mut batch = HudBatch::new([4, 2]);
for _ in 0..count {
quad(&mut batch, blend, color, 0.0, 0.25);
}
// Crosshair fragments with zero texture alpha discard; EndPortal has no discard.
if blend == Blend::Invert {
quad(&mut batch, blend, color, 2.0, 0.75);
}
gpu.check(
&batch,
initial,
[
expected,
expected,
(initial * 255.0).round() as u8,
(initial * 255.0).round() as u8,
],
);
}
let mut batch = HudBatch::new([4, 2]);
for depth in [0.25, 0.75] {
quad(
&mut batch,
Blend::Alpha,
rgba(255, 255, 255, 128),
0.0,
0.25,
);
let start = batch.vertices.len() - 6;
for vertex in &mut batch.vertices[start..] {
vertex.depth = depth;
}
}
batch.blends.push((0..12, Blend::Depth([1, 0, 2, 2])));
gpu.check(&batch, 0.0, [0, 128, 0, 0]);
}
#[test]
fn coverage_preserves_each_cit_blend_and_its_destination_alpha() {
let Some(mut gpu) = Gpu::new() else {
return;
};
use horizon_optifine::cit::parse_blend;
for (name, expected) in [
("alpha", 128),
("add", 0),
("dodge", 0),
("glint", 0),
("burn", 102),
("multiply", 26),
("overlay", 51),
("screen", 255),
("subtract", 255),
("replace", 255),
("0 768", 153),
("774 0", 153),
("770 771 772 773", 128),
] {
let textures = cit_glint::GlintTextures {
width: 1,
height: 1,
pixels: vec![102, 102, 102, 128],
slots: vec![cit_glint::Slot {
rgba: [1.0; 4],
blur: false,
blend: 0,
}],
blends: vec![parse_blend(name).unwrap()],
..Default::default()
};
gpu.hud
.set_cit_glints(&gpu.device, &gpu.queue, Some(&textures));
let mut batch = HudBatch::new([4, 2]);
quad(
&mut batch,
Blend::CitGlint(0),
rgba(0, 0, 0, 255),
0.0,
0.25,
);
quad(
&mut batch,
Blend::CitGlint(0),
rgba(0, 0, 0, 255),
2.0,
0.75,
);
gpu.check(&batch, 0.0, [expected, expected, 0, 0]);
}
}
#[test]
fn coverage_uses_pack_texts_final_alpha_and_discard() {
let Some(mut gpu) = Gpu::new() else {
return;
};
// A translated-style struct result and early return; no dependency on game resources.
let program = horizon_shaders::CoreProgram {
vertex: naga::front::wgsl::parse_str("@vertex fn main(@location(0) p: vec2<f32>) -> @builtin(position) vec4<f32> { return vec4(p.x / 2.0 - 1.0, 1.0 - p.y, 0.0, 1.0); }").unwrap(),
fragment: naga::front::wgsl::parse_str("struct Result { @location(0) color: vec4<f32> } @fragment fn main(@builtin(position) p: vec4<f32>) -> Result { if p.x > 2.0 { discard; } return Result(vec4(0.4, 0.2, 0.1, 0.5)); }").unwrap(),
};
gpu.hud.set_text_shader(&gpu.device, Some(&program));
assert!(gpu.hud.pack_text.is_some());
let mut batch = HudBatch::new([4, 2]);
for x in [0.0, 2.0, 0.0, 2.0] {
quad(&mut batch, Blend::Alpha, rgba(255, 255, 255, 255), x, 0.25);
}
for v in &mut batch.vertices {
v.text = 1;
}
gpu.check(&batch, 0.0, [191, 191, 0, 0]);
}
#[test]
fn a_pack_text_shader_without_a_colour_output_is_dropped_not_wrapped() {
let Some(mut gpu) = Gpu::new() else {
return;
};
let program = horizon_shaders::CoreProgram {
vertex: naga::front::wgsl::parse_str("@vertex fn main(@location(0) p: vec2<f32>) -> @builtin(position) vec4<f32> { return vec4(p, 0.0, 1.0); }").unwrap(),
fragment: naga::front::wgsl::parse_str("@fragment fn main() -> @location(1) vec4<f32> { return vec4(1.0); }").unwrap(),
};
gpu.hud.set_text_shader(&gpu.device, Some(&program));
assert!(gpu.hud.pack_text.is_none());
}
@@ -8,6 +8,7 @@ use std::sync::Arc;
use horizon_shaders::{CoreProgram, Glue};
use super::{HudBatch, HudVertex};
use crate::gfx::hud_coverage::Pipeline;
/// GUI text's vertex format (`POSITION_TEX_COLOR`) from the HUD's vertices. A glyph is two
/// triangles here, its corners top left, top right, bottom right, top left, bottom right, bottom
@@ -81,7 +82,7 @@ const BLOCK_SIZES: [u64; 4] = [48, 64, 160, 48];
/// The pipeline and its resources.
pub(super) struct PackText {
pipeline: wgpu::RenderPipeline,
pipeline: Pipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
}
@@ -92,6 +93,7 @@ impl PackText {
format: wgpu::TextureFormat,
atlas: &wgpu::TextureView,
program: &CoreProgram,
coverage: bool,
) -> Option<Self> {
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let module = |label, module: &naga::Module| {
@@ -179,7 +181,7 @@ impl PackText {
..Default::default()
});
let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
let desc = wgpu::RenderPipelineDescriptor {
label: Some("Resource pack text"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
@@ -208,11 +210,17 @@ impl PackText {
}),
multiview_mask: None,
cache: None,
});
};
let source = wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(program.fragment.clone()));
let pipeline = Pipeline::new(device, &desc, source, coverage);
if let Some(e) = pollster::block_on(scope.pop()) {
log::warn!("the resource pack's text shader is not used: {e}");
return None;
}
let Some(pipeline) = pipeline else {
log::warn!("the resource pack's text shader is not used: it has no colour output");
return None;
};
Some(Self {
pipeline,
group,
@@ -234,8 +242,13 @@ impl PackText {
/// Draw `range` (whole glyph quads) with the pack's shader; the caller sets its own
/// pipeline and bind group again after.
pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, range: std::ops::Range<u32>) {
pass.set_pipeline(&self.pipeline);
pub(super) fn draw(
&self,
pass: &mut wgpu::RenderPass<'_>,
range: std::ops::Range<u32>,
coverage: bool,
) {
pass.set_pipeline(self.pipeline.get(coverage));
pass.set_bind_group(0, &self.group, &[]);
pass.draw(range.clone(), range.start..range.start + 1);
}
+4
View File
@@ -5,6 +5,7 @@ pub mod assets;
pub mod atlas_sources;
pub mod audio;
pub mod auth;
pub mod autotune;
pub mod ban_notice;
pub mod bidi;
pub mod biome;
@@ -84,6 +85,7 @@ pub mod pack_screen;
pub mod packs;
pub mod pad_cursor;
pub mod pad_glyph;
pub mod paged_maps;
pub mod par;
pub mod particles;
pub mod poi_sections;
@@ -94,6 +96,7 @@ pub mod preedit;
pub mod providers;
pub mod pvp;
pub mod pvp_hud;
pub mod random_source;
pub mod screen_draw;
pub mod screen_effects;
pub mod sculk;
@@ -125,6 +128,7 @@ pub mod test_block;
pub mod test_instance_block;
pub mod testgen;
pub mod title_edition;
pub mod touch;
pub mod trims;
pub mod ui;
pub mod vault;
+77 -1
View File
@@ -9,6 +9,7 @@ use crate::{
};
pub mod cache;
mod mesh;
pub mod packed;
use horizon_world::registry::BlockStateId;
use std::{
collections::VecDeque,
@@ -559,7 +560,8 @@ pub(crate) fn state_kinds(facts: &BlockFacts) -> Vec<u8> {
}
/// Blocks that fill their cell but neither draw solid nor collide as a full
/// block: far terrain draws them as blocks, or patches of powder snow leave
/// holes in mountains (and paths and fields dips).
/// holes in mountains (and paths and fields dips). Slabs use the same
/// full-cell approximation as stairs, so distant slab builds remain visible.
fn nearly_full(name: &str) -> bool {
matches!(
name,
@@ -568,6 +570,7 @@ fn nearly_full(name: &str) -> bool {
| "minecraft:farmland"
| "minecraft:honey_block"
) || name.ends_with("_stairs")
|| name.ends_with("_slab")
|| name.contains("fence")
|| name.contains("_wall")
|| name.contains("bars")
@@ -1414,7 +1417,13 @@ impl Lod {
&edges,
&input.finer,
);
// Sorts the quads by facing side, and clears
// the compact layout: a far tile has no tints
// for `mesher::packed`, so its own records
// (`lod::packed`) are laid out here, from the
// quads in the order the sort left them.
mesh.sort_solid();
crate::lod::packed::lay_out(&mut mesh);
let [ox, _, oz] = job.key.origin();
let size = job.key.size();
mesh.keep = keep_finer
@@ -3977,6 +3986,73 @@ mod tests {
}
#[test]
#[ignore = "requires prepared models/textures in HORIZON_TEST_RESOURCES"]
fn slab_materials_survive_chunk_summaries_and_draw_far_faces() -> crate::Result<()> {
use crate::{assets::Assets, biome::Biomes, light::LightTables, mesher::MeshTables};
let root = std::path::PathBuf::from(
std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"),
);
let assets = Arc::new(Assets::load(&root)?);
let render = Arc::new(assets.reload(&root)?);
let facts = BlockFacts::load(&root, assets.registry)?;
let context = WorkerContext {
light: Arc::new(LightTables::load(&root, assets.registry, &facts)?),
tables: Arc::new(MeshTables::new(
&assets,
&render,
&facts,
crate::models::load_visibility(&root, assets.registry)?,
)?),
assets: assets.clone(),
render,
biomes: Arc::new(Biomes::load(&root)?),
};
let kinds = state_kinds(&facts);
let mut chunk = Chunk::empty(0, 0);
let mut mesher = mesh::Mesher::default();
let mut materials = FxHashSet::default();
// Real top, bottom, double and waterlogged states: a waterlogged slab
// must keep its material rather than become a column of plain water.
for (i, f) in facts.states.iter().enumerate() {
if !f.name.ends_with("_slab") {
continue;
}
materials.insert(f.name.as_ref());
let state = BlockStateId(i as u32);
chunk.set(3, 90, 3, state.0);
let columns = summarize(&chunk, &kinds);
let column = &columns[3 * 16 + 3];
assert_eq!(column.spans.len(), 1, "{} state {i}", f.name);
assert_eq!(column.spans[0].state, state, "{} state {i}", f.name);
assert_eq!((column.spans[0].min, column.spans[0].max), (90, 91));
assert_eq!(Column::reduced(&columns, 0, 0, 4).spans, column.spans);
let mesh = mesher.mesh(
TileKey {
x: 0,
z: 0,
level: 0,
},
&columns.iter().collect::<Vec<_>>(),
&FxHashSet::default(),
None,
&context,
&std::array::from_fn(|_| Vec::new()),
&[],
);
// Like stairs, far slabs use the existing full-cell approximation.
assert_eq!(mesh.solid.len(), 6 * 4, "{} state {i}", f.name);
assert!(mesh.translucent.is_empty(), "{} state {i}", f.name);
}
for name in [
"minecraft:smooth_stone_slab",
"minecraft:oak_slab",
"minecraft:cut_copper_slab",
] {
assert!(materials.contains(name), "missing fixture {name}");
}
Ok(())
}
#[test]
#[ignore = "requires prepared models/textures in HORIZON_TEST_RESOURCES"]
fn real_mesh_clips_near_chunks_and_preserves_water_and_edited_surfaces() -> crate::Result<()> {
use crate::{
assets::Assets, biome::Biomes, light::LightTables, mesher::MeshTables,
@@ -1386,6 +1386,52 @@ mod tests {
let p = |i: usize| glam::Vec3::from(q[i].pos);
(p(1) - p(0)).cross(p(2) - p(0))
}
/// Every solid quad the mesher emits packs into a far record, and the
/// record gives the quad back bit for bit (`lod::packed`).
///
/// `lod::packed`'s own tests check its records against its own copy of what
/// `emit_quad` does, which would pass just as well if the two had drifted
/// apart. This checks them against the real mesher, over terrain that makes
/// faces of every axis and winding: a hill of varied heights, a material
/// boundary, a light boundary and water.
#[test]
fn every_quad_the_mesher_emits_packs_and_comes_back() {
let mut columns = columns();
for (i, column) in columns.iter_mut().enumerate() {
let (x, z) = (i % CELLS, i / CELLS);
let top = 4 + (x as i16 % 5) * 2 + (z as i16 % 3);
let state = if (x + z) % 7 == 0 { 3 } else { 1 };
let light = if x % 4 == 0 { 16 } else { 240 };
column.spans = vec![
Span {
light,
..span(0, top, state)
},
// Water over the lower ground, for the fluid faces too.
span(top, 12.max(top + 1), 2),
]
.into();
}
let mesh = mesh(&columns);
let quads = mesh.solid.as_chunks::<4>().0;
assert!(
quads.len() > 50,
"{} quads is too few to say much",
quads.len()
);
for (i, quad) in quads.iter().enumerate() {
let words = crate::lod::packed::pack(quad)
.unwrap_or_else(|| panic!("quad {i} of {} did not pack", quads.len()));
let back = crate::lod::packed::corners(words)
.unwrap_or_else(|| panic!("quad {i}'s record names no face"));
assert_eq!(
bytemuck::cast::<_, [[u32; 6]; 4]>(back),
bytemuck::cast::<_, [[u32; 6]; 4]>(*quad),
"quad {i} came back changed"
);
}
}
#[test]
fn flat_solid_cube_merges_to_six_faces_with_block_scaled_uvs() {
let mut columns = columns();
@@ -0,0 +1,440 @@
//! The compact layout of a far tile's solid quads in the arena: one 24-byte
//! record each instead of four 24-byte vertices.
//!
//! A far tile's quads are not blocks' faces -- they are merged rectangles of a
//! voxel column's exposed side, hundreds of blocks wide -- so none of them fits
//! `mesher::packed`'s record, whose coordinates are a block grid of 16. They
//! are far more regular than a chunk's quads instead: a rectangle in an
//! axis-aligned plane, with one colour, one light and one sprite layer across
//! all four corners, and UVs that `lod::mesh::emit_quad` derives from the
//! positions. So a record holds what that function was given, and
//! terrain.wgsl's `far_corner` does what it did:
//!
//! - word 0: the colour (RGBA8), the same for all four corners;
//! - word 1: the sprite layer, and the light in the high half;
//! - word 2: the plane, the coordinate all four corners share, as an `i32`;
//! - word 3: the rectangle's low edge along the face's first axis, as an `i32`;
//! - word 4: its low edge along the second, as an `i32`;
//! - word 5: the plane's axis, whether the corners are reversed, the
//! rectangle's width and height, and `FULL` clear.
//!
//! Nothing here reasons about which record is right for a quad: `pack` builds
//! one, rebuilds the four vertices from it with the same code the shader
//! mirrors, and keeps it only if they come back bit for bit. A quad no record
//! reproduces -- a fractional coordinate, a rectangle too wide, a face whose
//! UVs were scaled down to fit (`lod::mesh::MAX_PIECES`) -- is kept as its four
//! vertices, exactly as `mesher::packed` keeps one.
use crate::mesher::{TerrainVertex, packed};
/// Word 5's bit of a quad kept as four vertices; word 0 is then the slots from
/// the record to its first vertex. The same bit `mesher::packed` uses, so the
/// two layouts place their records and spilled vertices alike.
pub use crate::mesher::packed::FULL;
/// The draws' base vertex of a compact far mesh, above `packed::PACKED_BASE`:
/// `FAR_BASE + 4 * slot + corner` is a corner of the quad whose record is at
/// `slot`. terrain.wgsl's `section_corner` reads the layout off the index, so
/// a far tile and a chunk section can share one arena and one pipeline.
pub const FAR_BASE: u32 = 1 << 29;
/// Whether far tiles meshed from now on get this layout: `HORIZON_FAR_PACK=0`
/// stops them and leaves chunk sections' own layout alone, so the two can be
/// told apart in one build. `HORIZON_PACKED_QUADS=0` stops both.
pub fn far_packing() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("HORIZON_FAR_PACK").as_deref() != Ok("0"))
}
/// The widest rectangle a record's 11-bit width and height hold. `lod::mesh`
/// splits a face at `MAX_FACE` = 1024 blocks unless it scales its UVs instead,
/// and a scaled face does not pack, so this is never the binding limit.
const MAX_EXTENT: i64 = (1 << 11) - 1;
/// Which axis a face's plane lies on, and what `lod::mesh::emit_quad` makes of
/// the other two. The names are that function's: `u` is the rectangle's first
/// axis and `v` its second, and the UV of a corner is `[u, -v]` of it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Axis {
/// Up and Down: the plane is y, u is x and v is z.
Y,
/// North and South: the plane is z, u is x and v is y.
Z,
/// West and East: the plane is x, u is z and v is y.
X,
}
impl Axis {
const ALL: [Self; 3] = [Self::Y, Self::Z, Self::X];
fn bits(self) -> u32 {
match self {
Self::Y => 0,
Self::Z => 1,
Self::X => 2,
}
}
#[cfg(test)]
fn from_bits(bits: u32) -> Option<Self> {
Self::ALL.into_iter().find(|a| a.bits() == bits)
}
}
/// A face as `lod::mesh::emit_quad` was given it, which is all a record holds.
#[derive(Clone, Copy, Debug)]
struct Face {
axis: Axis,
/// Whether the corners go round the other way, as they do for Down, South
/// and East (that function's `points.reverse()`).
reversed: bool,
plane: i32,
u0: i32,
v0: i32,
du: u32,
dv: u32,
layer: u16,
light: u16,
color: u32,
}
impl Face {
/// The four vertices of it, as `lod::mesh::emit_quad` writes them. Kept
/// here and not shared with that function because it is what the shader
/// mirrors: the two have to agree, and `a_record_rebuilds_what_the_mesher_
/// emitted` is what holds them to it.
fn vertices(self) -> [TerrainVertex; 4] {
let (p, u0, v0) = (self.plane as f32, self.u0 as f32, self.v0 as f32);
let u1 = u0 + self.du as f32;
let v1 = v0 + self.dv as f32;
let mut points = match self.axis {
Axis::Y => [[u0, p, v1], [u1, p, v1], [u1, p, v0], [u0, p, v0]],
Axis::Z => [[u0, v1, p], [u1, v1, p], [u1, v0, p], [u0, v0, p]],
Axis::X => [[p, v1, u1], [p, v1, u0], [p, v0, u0], [p, v0, u1]],
};
if self.reversed {
points.reverse();
}
let uvs = points.map(|pos| match self.axis {
Axis::Y => [pos[0], -pos[2]],
Axis::Z => [pos[0], -pos[1]],
Axis::X => [pos[2], -pos[1]],
});
let corner = [0, 1].map(|i| {
uvs.iter()
.map(|uv| uv[i])
.fold(f32::INFINITY, f32::min)
.floor()
});
let mut out = [TerrainVertex::tiled([0.0; 3], [0.0; 2], 0, 0, 0); 4];
for ((to, pos), uv) in out.iter_mut().zip(points).zip(uvs) {
*to = TerrainVertex::tiled(
pos,
[uv[0] - corner[0], uv[1] - corner[1]],
self.layer,
self.color,
self.light,
);
}
out
}
fn words(self) -> [u32; 6] {
[
self.color,
u32::from(self.layer) | u32::from(self.light) << 16,
self.plane as u32,
self.u0 as u32,
self.v0 as u32,
self.axis.bits() | u32::from(self.reversed) << 2 | self.du << 3 | self.dv << 14,
]
}
/// The face a record names, or `None` for a record that spills its quad's
/// vertices (`FULL`) or that does not name an axis.
#[cfg(test)]
fn from_words(w: [u32; 6]) -> Option<Self> {
if w[5] & FULL != 0 {
return None;
}
Some(Self {
axis: Axis::from_bits(w[5] & 3)?,
reversed: (w[5] >> 2) & 1 != 0,
plane: w[2] as i32,
u0: w[3] as i32,
v0: w[4] as i32,
du: (w[5] >> 3) & 0x7ff,
dv: (w[5] >> 14) & 0x7ff,
layer: w[1] as u16,
light: (w[1] >> 16) as u16,
color: w[0],
})
}
}
/// A whole number in `i32`, or `None`.
fn whole(v: f32) -> Option<i32> {
(v.fract() == 0.0 && (f32::from(i16::MIN) * 16.0..=f32::from(i16::MAX) * 16.0).contains(&v))
.then_some(v as i32)
}
/// `quad`'s record, if one gives back its four vertices exactly.
pub fn pack(quad: &[TerrainVertex; 4]) -> Option<[u32; 6]> {
let first = quad[0];
// One colour, one light and one layer across the four corners, which is
// what lets a record hold them once.
if quad
.iter()
.any(|v| (v.color, v.light, v.layer) != (first.color, first.light, first.layer))
{
return None;
}
let lo = [0, 1, 2].map(|k| quad.iter().map(|v| v.pos[k]).fold(f32::INFINITY, f32::min));
let hi = [0, 1, 2].map(|k| {
quad.iter()
.map(|v| v.pos[k])
.fold(f32::NEG_INFINITY, f32::max)
});
// Every axis and winding the mesher can have emitted; the round trip below
// says which one it was, so nothing here has to work it out.
for axis in Axis::ALL {
let (plane, u, v) = match axis {
Axis::Y => (1, 0, 2),
Axis::Z => (2, 0, 1),
Axis::X => (0, 2, 1),
};
if lo[plane] != hi[plane] {
continue;
}
let (Some(plane), Some(u0), Some(v0)) = (whole(lo[plane]), whole(lo[u]), whole(lo[v]))
else {
continue;
};
let (Some(u1), Some(v1)) = (whole(hi[u]), whole(hi[v])) else {
continue;
};
let (du, dv) = (i64::from(u1 - u0), i64::from(v1 - v0));
if du > MAX_EXTENT || dv > MAX_EXTENT {
continue;
}
for reversed in [false, true] {
let face = Face {
axis,
reversed,
plane,
u0,
v0,
du: du as u32,
dv: dv as u32,
layer: first.layer,
light: first.light,
color: first.color,
};
let words = face.words();
// The record is kept only where it gives the quad back exactly, so
// a quad this layout cannot hold is spilled rather than altered.
if bytemuck::cast::<_, [[u32; 6]; 4]>(face.vertices())
== bytemuck::cast::<_, [[u32; 6]; 4]>(*quad)
{
return Some(words);
}
}
}
None
}
/// The four corners a record names, as the shader rebuilds them; `None` for a
/// record that spills its quad's vertices. For the tests that hold this layout
/// and `lod::mesh` to each other.
#[cfg(test)]
pub fn corners(words: [u32; 6]) -> Option<[TerrainVertex; 4]> {
Face::from_words(words).map(Face::vertices)
}
/// Lays a far tile's solid quads out compactly in `mesh.packed`, where the
/// renderer reads that layout. Call it after `SectionMesh::sort_solid`, which
/// reorders the quads and clears whatever layout was there.
pub fn lay_out(mesh: &mut crate::mesher::SectionMesh) {
if !packed::packing() || !far_packing() {
return;
}
mesh.packed = layout(&mesh.solid);
mesh.packed_far = !mesh.packed.is_empty();
}
/// A far tile's solid quads laid out compactly: a record each in mesh order,
/// then the vertices of the quads no record fits. Empty where that would not
/// be smaller than the vertices.
pub fn layout(solid: &[TerrainVertex]) -> Vec<[u32; 6]> {
let quads = solid.as_chunks::<4>().0;
let records: Vec<Option<[u32; 6]>> = quads.iter().map(pack).collect();
packed::place(&records, quads)
}
#[cfg(test)]
mod tests {
use super::*;
/// The four corners as bits: `TerrainVertex` has no `PartialEq`, and bit
/// identity is the guarantee the layout makes in any case.
fn words_of(quad: [TerrainVertex; 4]) -> [[u32; 6]; 4] {
bytemuck::cast(quad)
}
fn face() -> Face {
Face {
axis: Axis::Y,
reversed: false,
plane: 71,
u0: -48,
v0: 112,
du: 16,
dv: 7,
layer: 3,
light: 0xF0F0,
color: 0xFF_80_40_20,
}
}
/// Every axis and winding survives the words, so `from_words` and the
/// shader's `far_corner` read what `words` wrote.
#[test]
fn a_face_survives_its_record() {
for axis in Axis::ALL {
for reversed in [false, true] {
let want = Face {
axis,
reversed,
..face()
};
let got = Face::from_words(want.words()).expect("a record names a face");
assert_eq!(
words_of(got.vertices()),
words_of(want.vertices()),
"{axis:?} {reversed}"
);
assert_eq!((got.axis, got.reversed), (axis, reversed));
assert_eq!((got.plane, got.u0, got.v0), (want.plane, want.u0, want.v0));
assert_eq!((got.du, got.dv), (want.du, want.dv));
assert_eq!(
(got.layer, got.light, got.color),
(want.layer, want.light, want.color)
);
}
}
}
/// The widest and the most distant rectangle a record claims to hold comes
/// back exactly, so the bit fields are wide enough for what they say.
#[test]
fn the_extremes_a_record_claims_come_back() {
let want = Face {
du: MAX_EXTENT as u32,
dv: MAX_EXTENT as u32,
plane: i32::from(i16::MAX),
u0: -8_000_000,
v0: 8_000_000,
layer: u16::MAX,
light: u16::MAX,
color: u32::MAX,
..face()
};
let got = Face::from_words(want.words()).expect("a record names a face");
assert_eq!((got.du, got.dv), (want.du, want.dv));
assert_eq!((got.plane, got.u0, got.v0), (want.plane, want.u0, want.v0));
assert_eq!(
(got.layer, got.light, got.color),
(want.layer, want.light, want.color)
);
}
/// Any quad the mesher could have emitted packs, and unpacks to the very
/// vertices it emitted: this is the whole guarantee the layout makes.
#[test]
fn a_record_rebuilds_what_the_mesher_emitted() {
let mut packed = 0;
for axis in Axis::ALL {
for reversed in [false, true] {
for (du, dv) in [(1, 1), (16, 1), (1, 16), (37, 91), (1024, 1024)] {
let want = Face {
axis,
reversed,
du,
dv,
..face()
};
let quad = want.vertices();
let words = pack(&quad).expect("the mesher's own quad packs");
let back = Face::from_words(words).expect("a record names a face");
assert_eq!(
words_of(back.vertices()),
words_of(quad),
"{axis:?} {reversed} {du}x{dv}"
);
packed += 1;
}
}
}
assert_eq!(packed, 30, "every case packed");
}
/// A quad this layout cannot hold is refused rather than altered: the
/// corners disagreeing on a colour, a fractional coordinate, and a
/// rectangle wider than the width field.
#[test]
fn a_quad_no_record_fits_is_refused() {
let mut uneven = face().vertices();
uneven[2].color ^= 1;
assert!(pack(&uneven).is_none(), "corners differ in colour");
let mut fraction = face().vertices();
fraction[0].pos[0] += 0.5;
assert!(pack(&fraction).is_none(), "a fractional coordinate");
let wide = Face {
du: MAX_EXTENT as u32 + 1,
..face()
};
assert!(pack(&wide.vertices()).is_none(), "wider than the field");
}
/// A tile of quads that all pack takes a quarter of the slots its vertices
/// would, which is the point of the layout.
#[test]
fn a_tile_that_packs_takes_a_quarter_of_the_slots() {
let mut solid = Vec::new();
for n in 0..64 {
solid.extend(
Face {
u0: n * 4,
..face()
}
.vertices(),
);
}
let out = layout(&solid);
assert_eq!(out.len(), solid.len() / 4, "a slot a quad, none spilled");
for (quad, record) in solid.as_chunks::<4>().0.iter().zip(&out) {
let face = Face::from_words(*record).expect("a record names a face");
assert_eq!(words_of(face.vertices()), words_of(*quad),);
}
}
/// A tile whose quads mostly spill keeps the vertices and gives up on the
/// layout rather than growing: `place` is what decides, and this holds it
/// to the same rule `mesher::packed` follows.
#[test]
fn a_tile_that_mostly_spills_keeps_its_vertices() {
let mut solid = Vec::new();
for n in 0..64 {
let mut quad = Face {
u0: n * 4,
..face()
}
.vertices();
quad[1].color ^= 1;
solid.extend(quad);
}
assert!(layout(&solid).is_empty(), "no layout smaller than vertices");
}
}
+94 -5
View File
@@ -6,8 +6,8 @@
//! keeps 7 archives a day, the newest with the highest index.
//!
//! Messages go through the `log` facade. Horizon's own still print their plain text on stderr,
//! as they did before the log existed; other crates' errors only reach the file (their
//! warnings are mostly the Vulkan loader's startup chatter).
//! as they did before the log existed. Other crates, including native mods and their helper
//! crates, reach the file through INFO too, with their target prefixed to identify the source.
use std::collections::{HashMap, VecDeque};
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
@@ -424,14 +424,18 @@ fn ours(target: &str) -> bool {
impl log::Log for Logger {
fn enabled(&self, meta: &log::Metadata) -> bool {
meta.level() <= log::Level::Info
&& (ours(meta.target()) || meta.level() <= log::Level::Error)
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let message = record.args().to_string();
let horizon = ours(record.target());
let message = if horizon {
record.args().to_string()
} else {
format!("[{}] {}", record.target(), record.args())
};
let current = std::thread::current();
let thread = match current.name() {
Some("main") => self.main_thread,
@@ -460,7 +464,7 @@ impl log::Log for Logger {
),
_ => {}
}
let stderr = ours(record.target()).then(|| message.clone());
let stderr = horizon.then(|| message.clone());
self.send(thread, level, &message, stderr);
if gate == Gate::Last {
self.write(
@@ -652,6 +656,91 @@ pub fn newest_crash_report(home: &Path) -> Option<PathBuf> {
mod tests {
use super::*;
#[test]
fn native_mod_records_reach_the_file_with_their_targets() {
use log::Log;
let dir =
std::env::temp_dir().join(format!("horizon-native-log-test-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let (out, receive) = mpsc::channel();
let writer = Writer {
file: Some(open_latest(&dir).unwrap().unwrap()),
dir: dir.clone(),
date: Local::now().date_naive(),
};
let handle = std::thread::spawn(move || writer.run(receive));
let logger = Logger {
out,
recent: Mutex::new(VecDeque::new()),
main_thread: "Render thread",
floods: Mutex::new(Floods::default()),
};
for (target, level, message) in [
("meridian_horizon::save", log::Level::Warn, "save failed"),
("meridian_core::map", log::Level::Info, "map opened"),
("wgpu_core::device", log::Level::Error, "device lost"),
("meridian_core::map", log::Level::Debug, "debug detail"),
("meridian_core::map", log::Level::Trace, "trace detail"),
] {
logger.log(
&log::Record::builder()
.args(format_args!("{message}"))
.level(level)
.target(target)
.build(),
);
}
logger.flush();
drop(logger);
handle.join().unwrap();
let text = fs::read_to_string(dir.join("latest.log")).unwrap();
fs::remove_dir_all(&dir).unwrap();
assert!(
text.contains("[meridian_horizon::save] save failed"),
"{text}"
);
assert!(text.contains("[meridian_core::map] map opened"), "{text}");
assert!(text.contains("[wgpu_core::device] device lost"), "{text}");
assert!(!text.contains("debug detail"));
assert!(!text.contains("trace detail"));
}
#[test]
fn horizon_stderr_and_external_file_records_stay_separate() {
use log::Log;
let (out, receive) = mpsc::channel();
let logger = Logger {
out,
recent: Mutex::new(VecDeque::new()),
main_thread: "Render thread",
floods: Mutex::new(Floods::default()),
};
for target in ["horizon_client::game", "meridian_core", "wgpu_hal::vulkan"] {
logger.log(
&log::Record::builder()
.args(format_args!("diagnostic"))
.level(log::Level::Info)
.target(target)
.build(),
);
let Out::Write {
stderr,
record: (_, _, message),
..
} = receive.try_recv().unwrap()
else {
panic!("a diagnostic must write a record")
};
if ours(target) {
assert_eq!(stderr.as_deref(), Some("diagnostic"));
assert_eq!(message, "diagnostic");
} else {
assert!(stderr.is_none());
assert_eq!(message, format!("[{target}] diagnostic"));
}
}
}
#[test]
fn a_player_dir_keeps_the_shared_files_in_the_game_folder() {
let (game, player) = (Path::new("/games/shared"), Path::new("/games/players/alex"));
+29 -5
View File
@@ -202,20 +202,44 @@ impl MenuBlur {
target: &wgpu::TextureView,
size: [u32; 2],
radius: f32,
mut timing: Option<&mut crate::gfx::pack_timing::PassTiming>,
timing: Option<&mut crate::gfx::pack_timing::PassTiming>,
) {
self.ensure(device, size);
let work = self.work_size(size);
let copy = if self.half { 2 } else { 0 };
let copy = self.source(device, size).0;
encoder.copy_texture_to_texture(
frame.as_image_copy(),
self.targets[copy].0.as_image_copy(),
copy.as_image_copy(),
wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
);
self.blur(device, queue, encoder, target, size, radius, timing);
}
/// The blur's copy of a frame of `size`, for a picture drawn into it rather than copied
/// (HDR output's composite, `Hdr::composite`), then `blur`.
pub fn source(
&mut self,
device: &wgpu::Device,
size: [u32; 2],
) -> (wgpu::Texture, wgpu::TextureView) {
self.ensure(device, size);
self.targets[if self.half { 2 } else { 0 }].clone()
}
/// Blur what `source` holds into `target`, as `apply` blurs its copy of the frame.
#[allow(clippy::too_many_arguments)]
pub fn blur(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
size: [u32; 2],
radius: f32,
mut timing: Option<&mut crate::gfx::pack_timing::PassTiming>,
) {
self.ensure(device, size);
let work = self.work_size(size);
let radius = if self.half { radius / 2.0 } else { radius };
if self.half {
// A radius of 0 samples each half-size pixel's 2x2 block at its shared
+36 -12
View File
@@ -347,6 +347,10 @@ pub struct SectionMesh {
/// model order before.
pub sides: Sides,
pub translucent: Vec<TerrainVertex>,
/// Whether `packed` holds far tile records (`lod::packed`) rather than
/// section records (`mesher::packed`): the two are read apart, by the base
/// vertex their draws use.
pub packed_far: bool,
/// `solid` in the compact layout (`packed`), when the renderer reads it and it is
/// smaller; empty otherwise. Made by `sort_solid`.
pub packed: Vec<[u32; 6]>,
@@ -379,6 +383,7 @@ impl Default for SectionMesh {
sides: Sides::default(),
translucent: Vec::new(),
packed: Vec::new(),
packed_far: false,
solid_tints: Vec::new(),
visibility: ALL_VISIBLE,
block_entities: Vec::new(),
@@ -413,6 +418,7 @@ impl SectionMesh {
self.solid.clear();
self.translucent.clear();
self.packed.clear();
self.packed_far = false;
self.solid_tints.clear();
self.block_entities.clear();
self.lights.clear();
@@ -442,6 +448,7 @@ impl SectionMesh {
self.sides = sides::sort_tinted(&mut self.solid, &mut self.solid_tints);
self.bounds = self.compute_bounds();
self.packed.clear();
self.packed_far = false;
if packed::packing() && quads > 0 && self.solid_tints.len() == quads {
self.packed = packed::layout(&self.solid, &self.solid_tints);
}
@@ -652,7 +659,11 @@ struct Info {
/// and a full collision shape. The only block leaf culling treats as solid.
opaque_cube: bool,
blocks_flow: bool,
/// `instanceof IceBlock` (frosted ice too): fluids read it.
ice: bool,
/// Regular ice, the block the Opaque Ice option draws opaque; frosted ice
/// keeps its see-through, cracking look.
opaque_ice: bool,
sturdy: u8,
/// Occlusion face per direction: 0 empty, 1 the full-block singleton, 2 partial.
face: [u8; 6],
@@ -844,6 +855,7 @@ impl MeshTables {
),
blocks_flow: assets.blocks_fluid_flow.contains(&*s.name),
ice: s.has_class("IceBlock"),
opaque_ice: s.has_class("IceBlock") && !s.has_class("FrostedIceBlock"),
sturdy: s.sturdy_full,
face,
cover,
@@ -1251,6 +1263,8 @@ fn row_masks_match_cell_definition() {
#[cfg(test)]
mod leaf_culling_tests;
#[cfg(test)]
mod opaque_ice_tests;
#[cfg(test)]
mod reuse_tests;
#[cfg(test)]
mod tint_tests;
@@ -1580,6 +1594,8 @@ pub struct Mesher<'a> {
pub smooth_lighting: bool,
/// The `cutoutLeaves` option (fancy graphics); off makes leaves opaque.
pub cutout_leaves: bool,
/// The `opaqueIce` option: regular ice draws opaque in the solid pass.
pub opaque_ice: bool,
/// Sprite layers a shader pack moves into the translucent pass, by layer.
pub translucent_layers: &'a [bool],
/// What the worker does with leaf faces inside a canopy.
@@ -1705,6 +1721,9 @@ impl Mesher<'_> {
let other = &info[neighbor as usize];
// LeavesBlock.skipRendering with opaque leaves.
let opaque_leaves = !self.cutout_leaves && state.leaves && other.leaves;
// Opaque Ice: faces between two ice blocks are hidden, as they are
// between two opaque blocks.
let opaque_ice = self.opaque_ice && state.opaque_ice && other.opaque_ice;
let culled_leaf = match self.leaf_culling {
LeafCullingMode::Hollow | LeafCullingMode::Hidden => {
state.leaves
@@ -1722,6 +1741,7 @@ impl Mesher<'_> {
_ => false,
};
visible[d as usize] = !opaque_leaves
&& !opaque_ice
&& !culled_leaf
&& self
.visibility
@@ -1950,9 +1970,11 @@ impl Mesher<'_> {
// The face's own UVs, already packed: no per-vertex rounding.
std::array::from_fn(|i| (vertex(tint, i, face.uv_fixed[i]), q.uv[i]))
};
// Opaque leaves (forceOpaque) and leaves a leaf-culling mode proved internal draw in the
// solid layer whatever their sprite.
let solid_leaves = !self.cutout_leaves && state.leaves || interior_leaf;
// Opaque leaves (forceOpaque), leaves a leaf-culling mode proved internal and Opaque
// Ice draw in the solid layer whatever their sprite.
let force_solid = !self.cutout_leaves && state.leaves
|| interior_leaf
|| self.opaque_ice && state.opaque_ice;
let own = TileLayer::Layer {
layer: face.layer as u16,
translucent: face.translucent,
@@ -1972,8 +1994,8 @@ impl Mesher<'_> {
TileLayer::Skip | TileLayer::Default => own,
};
match pick {
Pick::Keep => self.quad(out, solid_leaves, own, corners.map(|c| c.0), tint),
Pick::Tile(t) => self.quad(out, solid_leaves, tile(t), corners.map(|c| c.0), tint),
Pick::Keep => self.quad(out, force_solid, own, corners.map(|c| c.0), tint),
Pick::Tile(t) => self.quad(out, force_solid, tile(t), corners.map(|c| c.0), tint),
Pick::Quarters(tiles) => {
let cuts = cuts(&corners);
for s in cuts.windows(2) {
@@ -1982,7 +2004,7 @@ impl Mesher<'_> {
.map(|(s, t)| bilinear(&corners, s, t));
let quarter = quarter_of(&piece);
let piece = piece.map(|c| c.0);
self.quad(out, solid_leaves, tile(tiles[quarter]), piece, tint);
self.quad(out, force_solid, tile(tiles[quarter]), piece, tint);
}
}
}
@@ -2031,17 +2053,17 @@ impl Mesher<'_> {
}
}
}
/// One terrain quad with sprite `tile`, in the pass its alpha needs (`solid_leaves`: no
/// One terrain quad with sprite `tile`, in the pass its alpha needs (`force_solid`: no
/// alpha cutout whatever the sprite).
fn quad(
&self,
out: &mut SectionMesh,
solid_leaves: bool,
force_solid: bool,
tile: TileLayer,
v: [TerrainVertex; 4],
tint: Option<u32>,
) {
self.quad_as(out, solid_leaves, tile, v, true, tint);
self.quad_as(out, force_solid, tile, v, true, tint);
}
/// Whether [`Mesher::quad`] draws `tile` in the translucent pass.
fn translucent(&self, tile: TileLayer) -> bool {
@@ -2065,7 +2087,7 @@ impl Mesher<'_> {
fn quad_as(
&self,
out: &mut SectionMesh,
solid_leaves: bool,
force_solid: bool,
tile: TileLayer,
mut v: [TerrainVertex; 4],
by_sprite: bool,
@@ -2082,14 +2104,16 @@ impl Mesher<'_> {
if self.tables.is_animated(layer) {
out.note_sprite_layer(layer);
}
let translucent = if by_sprite {
let translucent = if force_solid {
false
} else if by_sprite {
self.translucent(tile)
} else {
translucent
};
// Quads over opaque texels draw in the solid layer: no alpha cutout (a dirt path's side
// skips its clear top row). All four vertices share the layer.
let layer = if opaque && !translucent || solid_leaves {
let layer = if opaque && !translucent || force_solid {
layer | OPAQUE_LAYER
} else {
layer
@@ -343,6 +343,7 @@ mod tests {
opaque_cube: opaque,
blocks_flow: false,
ice: false,
opaque_ice: false,
sturdy: 0,
face: [0; 6],
cover: [0.0; 6],
@@ -83,6 +83,7 @@ fn mesh(
blend_radius: 0,
smooth_lighting: false,
cutout_leaves: true,
opaque_ice: false,
translucent_layers: &[],
leaf_culling: mode,
};
@@ -0,0 +1,140 @@
//! Opaque Ice through the real mesher: regular ice moves from the translucent
//! pass to the solid pass without its texture alpha, keeps its faces toward
//! air, loses the faces between two ice blocks, and leaves other translucent
//! blocks alone. Needs prepared resources, like the other mesher geometry tests.
use super::*;
use crate::{
assets::{Assets, RenderAssets},
biome::Biomes,
blocks::BlockFacts,
chunk::Chunk,
models,
};
struct Fixture {
assets: Assets,
biomes: Biomes,
render: RenderAssets,
visibility: horizon_world::block_render::FaceVisibility,
tables: MeshTables,
}
fn fixture() -> Fixture {
let root = std::env::var_os("HORIZON_MESH_TEST_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3")
});
let assets = Assets::load(&root).unwrap();
let facts = BlockFacts::load(&root, assets.registry).unwrap();
let biomes = Biomes::load(&root).unwrap();
let render = assets.reload(&root).unwrap();
let visibility = models::load_visibility(&root, assets.registry).unwrap();
let tables = MeshTables::new(&assets, &render, &facts, visibility.clone()).unwrap();
Fixture {
assets,
biomes,
render,
visibility,
tables,
}
}
fn state(f: &Fixture, name: &str) -> u32 {
f.assets.registry.default_state(name).unwrap().0
}
fn mesh(f: &Fixture, chunk: &Chunk, opaque_ice: bool) -> SectionMesh {
let region = [[Some(chunk); 3]; 3];
let mut mesher = Mesher {
nether_shading: false,
shader_pack_lighting: false,
separate_ao: false,
shader_pack: false,
assets: &f.assets,
render: &f.render,
tables: &f.tables,
biomes: &f.biomes,
visibility: f.visibility.clone(),
zoom: BiomeZoom::new(0),
blend_radius: 0,
smooth_lighting: false,
cutout_leaves: true,
opaque_ice,
translucent_layers: &[],
leaf_culling: LeafCullingMode::Off,
};
mesher.mesh(&region, 0)
}
const BASE: i32 = MIN_Y + 4;
#[test]
#[ignore = "requires prepared 26.3 resources (HORIZON_MESH_TEST_RESOURCES or .local/horizon-client/26.3)"]
fn off_keeps_regular_ice_in_the_translucent_pass() {
let f = fixture();
let mut chunk = Chunk::empty(0, 0);
chunk.set(8, BASE, 8, state(&f, "minecraft:ice"));
let mesh = mesh(&f, &chunk, false);
assert!(mesh.solid.is_empty());
assert_eq!(mesh.translucent.len(), 24);
}
#[test]
#[ignore = "requires prepared 26.3 resources (HORIZON_MESH_TEST_RESOURCES or .local/horizon-client/26.3)"]
fn on_draws_regular_ice_opaque_in_the_solid_pass() {
let f = fixture();
let mut chunk = Chunk::empty(0, 0);
chunk.set(8, BASE, 8, state(&f, "minecraft:ice"));
let mesh = mesh(&f, &chunk, true);
assert!(mesh.translucent.is_empty());
let quads = mesh.solid.as_chunks::<4>().0;
assert_eq!(quads.len(), 6);
for quad in quads {
assert!(
quad.iter().all(|v| v.layer & OPAQUE_LAYER != 0),
"an opaque ice quad kept its texture alpha"
);
}
}
#[test]
#[ignore = "requires prepared 26.3 resources (HORIZON_MESH_TEST_RESOURCES or .local/horizon-client/26.3)"]
fn on_culls_the_face_between_two_ice_blocks() {
let f = fixture();
let ice = state(&f, "minecraft:ice");
let mut chunk = Chunk::empty(0, 0);
chunk.set(7, BASE, 8, ice);
chunk.set(8, BASE, 8, ice);
let mesh = mesh(&f, &chunk, true);
assert!(mesh.translucent.is_empty());
// Two cubes, six faces each, minus the face they share.
assert_eq!(mesh.solid.len(), 10 * 4);
}
#[test]
#[ignore = "requires prepared 26.3 resources (HORIZON_MESH_TEST_RESOURCES or .local/horizon-client/26.3)"]
fn on_leaves_other_translucent_blocks_alone() {
let f = fixture();
let mut chunk = Chunk::empty(0, 0);
chunk.set(4, BASE, 8, state(&f, "minecraft:ice"));
chunk.set(12, BASE, 8, state(&f, "minecraft:slime_block"));
let mesh = mesh(&f, &chunk, true);
assert_eq!(mesh.solid.len(), 24, "only the ice cube is solid");
assert!(
mesh.translucent.len() >= 24,
"the slime cube is still translucent"
);
}
#[test]
#[ignore = "requires prepared 26.3 resources (HORIZON_MESH_TEST_RESOURCES or .local/horizon-client/26.3)"]
fn on_leaves_frosted_ice_translucent() {
let f = fixture();
let mut chunk = Chunk::empty(0, 0);
chunk.set(8, BASE, 8, state(&f, "minecraft:frosted_ice"));
let mesh = mesh(&f, &chunk, true);
assert!(mesh.solid.is_empty());
assert_eq!(mesh.translucent.len(), 24);
}
@@ -208,6 +208,18 @@ pub fn layout(solid: &[TerrainVertex], tints: &[u32]) -> Vec<[u32; 6]> {
.zip(tints)
.map(|(q, &t)| pack_quad(q, t))
.collect();
place(&records, quads)
}
/// A mesh's solid range from a record per quad, `None` where no record fits:
/// the records in mesh order, padded to a multiple of 4 slots, then the four
/// vertices of each quad without one, whose record holds the distance to them
/// (`FULL`). Empty where that would not be smaller than the vertices, which is
/// what makes the layout never a loss.
///
/// Shared with `lod::packed`, whose records hold a far tile's quads instead but
/// spill and pad the same way.
pub fn place(records: &[Option<[u32; 6]>], quads: &[[TerrainVertex; 4]]) -> Vec<[u32; 6]> {
let n = quads.len();
let packed = records.iter().filter(|r| r.is_some()).count();
let full = n - packed;
@@ -229,7 +241,7 @@ pub fn layout(solid: &[TerrainVertex], tints: &[u32]) -> Vec<[u32; 6]> {
}));
}
out.resize(n + pad, [0; 6]);
for (q, record) in quads.iter().zip(&records) {
for (q, record) in quads.iter().zip(records) {
if record.is_none() {
out.extend(
q.iter()
@@ -181,6 +181,7 @@ fn a_shader_pack_lights_the_faces_itself() {
blend_radius: 0,
smooth_lighting: false,
cutout_leaves: true,
opaque_ice: false,
translucent_layers: &[],
leaf_culling: LeafCullingMode::Off,
};
@@ -237,6 +238,7 @@ fn a_shader_pack_lights_every_nether_face_like_an_up_face() {
blend_radius: 0,
smooth_lighting: false,
cutout_leaves: true,
opaque_ice: false,
translucent_layers: &[],
leaf_culling: LeafCullingMode::Off,
};
@@ -289,6 +291,7 @@ fn separate_ao_passes_ao_in_alpha_without_darkening_rgb() {
blend_radius: 0,
smooth_lighting: true,
cutout_leaves: true,
opaque_ice: false,
translucent_layers: &[],
leaf_culling: LeafCullingMode::Off,
};
@@ -364,6 +367,7 @@ fn reused_mesh_matches_fresh_geometry_across_sections_and_resource_reload() {
blend_radius: 2,
smooth_lighting: reload == 0,
cutout_leaves: reload == 0,
opaque_ice: false,
translucent_layers: &[],
leaf_culling: LeafCullingMode::Off,
};
@@ -513,6 +517,7 @@ fn a_shader_pack_s_still_water_top_starts_at_its_south_west_corner() {
blend_radius: 0,
smooth_lighting: true,
cutout_leaves: true,
opaque_ice: false,
translucent_layers: &[],
leaf_culling: LeafCullingMode::Off,
};
@@ -92,6 +92,7 @@ fn info(solid: bool) -> Info {
opaque_cube: solid,
blocks_flow: false,
ice: false,
opaque_ice: false,
sturdy: 0,
face: [0; 6],
cover: [0.0; 6],
@@ -21,7 +21,11 @@ fn oit_cloud_color(in: Out, front: bool, fade: bool) -> vec4<f32> {
return oit_add_transmittance(1.0 - color.a, in.clip.z, in.clip.xy);
}
@fragment fn fs_oit_cloud_accumulate(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
let color = oit_cloud_color(in, front, true);
var color = oit_cloud_color(in, front, true);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
color = vec4(hdr_written(color.rgb, hdr_scene_alpha(globals.hdr_light.y),
globals.hdr_settings, globals.hdr_shares), color.a);
}
let seen = oit_sample_transmittance(vec2<i32>(in.clip.xy),
oit_normalize_depth(in.clip.z, in.clip.xy), 1.0 - color.a);
return vec4(color.rgb * color.a, color.a) * seen;
@@ -12,6 +12,10 @@
return oit_transmittance_fragment(entity_color(in, front).a, in.clip);
}
@fragment fn fs_oit_entity_accumulate(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
return oit_accumulate_fragment(entity_written_color(in, front), in.clip);
}
// Text keeps its source gain, as fs_entity_unmarked does in the forward pass.
@fragment fn fs_oit_text_accumulate(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
return oit_accumulate_fragment(entity_color(in, front), in.clip);
}
// `OIT_ENTITY_SHADOW`.
@@ -56,6 +60,9 @@
return OitCoefficients(vec4(0.0), vec4(0.0));
}
@fragment fn fs_oit_lightning_accumulate(in: Out) -> @location(0) vec4<f32> {
let color = celestial_color(in);
var color = celestial_color(in);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
color = vec4(hdr_written(color.rgb, hdr_entity_mark(in), globals.hdr_settings, globals.hdr_shares), color.a);
}
return oit_accumulate_additive(vec4(color.rgb, min(0.99, color.a)), 0.0, in.clip);
}
@@ -9,19 +9,25 @@ fn oit_terrain_color(in: TerrainOut) -> vec4<f32> {
}
// Stage 1: (-nearest, furthest, nearest device depth, nearest opaque device
// depth), combined by max blending.
@fragment fn fs_oit_bounds(in: TerrainOut) -> @location(0) vec4<f32> {
@fragment fn fs_oit_bounds(wire: TerrainWire) -> @location(0) vec4<f32> {
let in = from_wire(wire);
let color = oit_terrain_color(in);
let linear = oit_linear_depth(in.clip.z);
let opaque = select(0.0, in.clip.z, color.a > OIT_FULLY_OPAQUE_ALPHA);
return vec4(-linear, linear, in.clip.z, opaque);
}
// Stage 2.
@fragment fn fs_oit_transmittance(in: TerrainOut) -> OitCoefficients {
@fragment fn fs_oit_transmittance(wire: TerrainWire) -> OitCoefficients {
let in = from_wire(wire);
let color = oit_terrain_color(in);
return oit_add_transmittance(1.0 - color.a, in.clip.z, in.clip.xy);
}
// Stage 3: premultiplied colour, weighted by the transmittance in front.
@fragment fn fs_oit_accumulate(in: TerrainOut) -> @location(0) vec4<f32> {
@fragment fn fs_oit_accumulate(wire: TerrainWire) -> @location(0) vec4<f32> {
let in = from_wire(wire);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
hdr_normal = normalize(cross(dpdy(in.local), dpdx(in.local)));
}
let color = oit_terrain_color(in);
let seen = oit_sample_transmittance(vec2<i32>(in.clip.xy),
oit_normalize_depth(in.clip.z, in.clip.xy), 1.0 - color.a);
@@ -30,6 +36,13 @@ fn oit_terrain_color(in: TerrainOut) -> vec4<f32> {
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
// The fog colour is premultiplied by the same weight.
let rgb = mix(weighted.rgb, globals.fog_color.rgb * weighted.a, f * globals.fog_color.a);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
let mark = hdr_scene_alpha(mix(hdr_scene(in.scene.x, in.scene.y, hdr_facing()),
globals.hdr_light.y, f * globals.fog_color.a));
// Convert the surface before weighting; its mark never belongs to the light behind it.
let fogged = mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a);
return vec4(hdr_written(fogged, mark, globals.hdr_settings, globals.hdr_shares) * weighted.a, weighted.a);
}
return vec4(rgb, weighted.a);
}
@@ -42,7 +55,12 @@ struct OitFragment {
@fragment fn fs_oit_cull(@builtin(position) pos: vec4<f32>) -> OitFragment {
let b = textureLoad(oit_bounds, vec2<i32>(pos.xy), 0);
let opaque = oit_linear_depth(b.a);
return OitFragment(vec4(b.r, min(b.g, opaque), b.b, b.a), b.a);
// The later stages test GreaterEqual against this depth, so the opaque fragment itself must still
// pass: Metal's `position.z` can differ from the rasterizer's depth by an ulp, which dropped
// random pixels of an opaque body. A few ulps farther (a positive float's bits minus one is
// the next smaller value) keeps it, and culls anything behind it by a visible distance.
let culled_depth = select(0.0, bitcast<f32>(bitcast<u32>(b.a) - 4u), b.a > 0.0);
return OitFragment(vec4(b.r, min(b.g, opaque), b.b, b.a), culled_depth);
}
// The sum over the world, renormalized to the coverage the transform gives.
@fragment fn fs_oit_composite(@builtin(position) pos: vec4<f32>) -> OitFragment {
+186 -132
View File
@@ -312,11 +312,13 @@ impl Opt {
Opt::PadRepeatInterval => "horizon.options.repeat_interval",
Opt::PadInvertX => "horizon.options.invert_x",
Opt::PadInvertY => "horizon.options.invert_y",
Opt::PadCraftOnServers => "horizon.options.craft_on_servers",
Opt::PadToggleSneak => "horizon.options.sneak_button",
Opt::PadMoveDeadzone => "horizon.options.move_deadzone",
Opt::PadLookDeadzone => "horizon.options.look_deadzone",
Opt::PadTriggerThreshold => "horizon.options.trigger_threshold",
Opt::PadGlyphs => "horizon.options.button_glyphs",
Opt::PadNintendoButtons => "horizon.options.nintendo_buttons",
Opt::PadKeyboard => "horizon.options.on_screen_keyboard",
Opt::PadGameplayGuide => "horizon.options.gameplay_guide",
Opt::ModelPart(i) => [
@@ -848,6 +850,7 @@ impl Opt {
}),
Opt::PadInvertX => on_off(s.controller.invert_x),
Opt::PadInvertY => on_off(s.controller.invert_y),
Opt::PadCraftOnServers => on_off(s.controller.craft_on_servers),
Opt::PadToggleSneak => tr(if s.controller.toggle_sneak {
"options.key.toggle"
} else {
@@ -864,6 +867,11 @@ impl Opt {
GlyphStyle::PlayStation => "horizon.options.glyphs.playstation",
GlyphStyle::Nintendo => "horizon.options.glyphs.nintendo",
}),
Opt::PadNintendoButtons => tr(if s.controller.nintendo_letters {
"horizon.options.nintendo_buttons.letter"
} else {
"horizon.options.nintendo_buttons.position"
}),
Opt::PadKeyboard => tr(match s.controller.keyboard {
gamepad::TextKeyboard::Auto => "horizon.options.keyboard.auto",
gamepad::TextKeyboard::Horizon => "horizon.options.keyboard.horizon",
@@ -1150,7 +1158,13 @@ impl Opt {
}
Opt::PadInvertX => s.controller.invert_x = !s.controller.invert_x,
Opt::PadInvertY => s.controller.invert_y = !s.controller.invert_y,
Opt::PadCraftOnServers => {
s.controller.craft_on_servers = !s.controller.craft_on_servers
}
Opt::PadToggleSneak => s.controller.toggle_sneak = !s.controller.toggle_sneak,
Opt::PadNintendoButtons => {
s.controller.nintendo_letters = !s.controller.nintendo_letters
}
Opt::PadLightbar => {
let all = gamepad::Lightbar::ALL;
let i = all
@@ -1645,7 +1659,7 @@ pub struct OptionsUi {
pub minecart_improvements: bool,
/// Scroll the selected language into the middle on the next layout.
center_language: bool,
pub graphics: crate::graphics_ui::GraphicsUi,
graphics: shell::Shell<crate::graphics_ui::GraphicsScreen>,
pub controller: crate::controller_ui::ControllerUi,
/// Horizon Extras, on the settings shell.
extras: shell::Shell<crate::extras_ui::ExtrasScreen>,
@@ -2086,9 +2100,6 @@ impl OptionsUi {
.pack_screen
.as_ref()
.is_some_and(|p| p.search_focused()),
Page::Graphics | Page::GraphicsAdvanced | Page::GraphicsHdr => {
self.graphics.typing()
}
Page::Controller | Page::PadBinds => self.controller.typing(),
_ if Self::shader_page(self.page()).is_some() => self.shader.typing(),
_ => match self.shell() {
@@ -2201,9 +2212,6 @@ impl OptionsUi {
if page == Page::Packs {
self.pack_screen = None;
}
if let Some(at) = Self::graphics_page(page) {
self.graphics.open(at);
}
if let Some(at) = Self::controller_page(page) {
self.controller.open(at);
}
@@ -2213,6 +2221,9 @@ impl OptionsUi {
if let Some(shell) = self.shell_mut() {
shell.open();
}
if let Some(at) = Self::graphics_page(page) {
self.graphics.show(at);
}
if page == Page::SplitSetup {
self.split_setup.reset();
}
@@ -2229,15 +2240,27 @@ impl OptionsUi {
fn shell(&self) -> Option<&dyn shell::Hosted> {
match self.page() {
Page::Extras => Some(&self.extras),
page if Self::graphics_page(page).is_some() => Some(&self.graphics),
_ => None,
}
}
fn shell_mut(&mut self) -> Option<&mut dyn shell::Hosted> {
match self.page() {
Page::Extras => Some(&mut self.extras),
page if Self::graphics_page(page).is_some() => Some(&mut self.graphics),
_ => None,
}
}
/// A controller's or the keyboard's focus landed on `rect`: a row of a shell screen's list
/// that is partly hidden scrolls all into view. How far it moved down, when it moved.
pub fn reveal(&mut self, s: &Settings, size: (f32, f32), rect: [f32; 4]) -> Option<f32> {
self.shell_mut()?.reveal(s, size, rect)
}
/// The window's size, for the graphics screen's vanilla rows that step through its
/// resolutions: before each input that can press one.
fn graphics_framebuffer(&mut self) {
self.graphics.screen.framebuffer = self.framebuffer;
}
/// What a shell screen's outputs do to these options.
fn shell_events(&mut self, s: &mut Settings, outputs: Vec<shell::Output>) -> Vec<Event> {
let mut events = Vec::new();
@@ -2245,43 +2268,17 @@ impl OptionsUi {
match output {
shell::Output::Event(event) => events.push(event),
shell::Output::BindKey(name) => self.selected_key = Some(name),
shell::Output::Push(page) => self.push(page),
shell::Output::Push(page) => {
if page == Page::HdrCalibration {
self.calibration = Some(crate::hdr_calibration::Calibration::new(s));
}
self.push(page);
}
shell::Output::Done => events.extend(self.back(s)),
}
}
events
}
/// What the graphics screen's actions do to these options.
fn graphics_events(
&mut self,
s: &mut Settings,
actions: Vec<crate::graphics_ui::Action>,
) -> Vec<Event> {
use crate::graphics_ui::Action;
let mut events = Vec::new();
for action in actions {
match action {
Action::ButtonClick => events.push(Event::ButtonClick),
Action::Changed => events.push(Event::Changed),
Action::SliderDrag => events.push(Event::SliderDrag),
Action::BindKey(name) => self.selected_key = Some(name),
Action::Calibrate => {
self.calibration = Some(crate::hdr_calibration::Calibration::new(s));
self.push(Page::HdrCalibration);
}
// The Shaders page's Shader Packs...: the list of either kind, as the page
// opens it from anywhere.
Action::ShaderPacks => {
events.push(Event::ListShaderPacks);
s.shader_options = None;
events.push(Event::OpenShaderOptions);
self.push(Page::ShaderPacks);
}
Action::Done => events.extend(self.back(s)),
}
}
events
}
/// What the controller screen's actions do to these options.
fn controller_events(
&mut self,
@@ -3690,11 +3687,6 @@ impl OptionsUi {
c.draw(batch, atlas, cursor);
return;
}
if Self::graphics_page(self.page()).is_some() {
self.graphics.binding = self.selected_key;
self.graphics.draw(s, batch, atlas, cursor, self.in_world);
return;
}
if Self::controller_page(self.page()).is_some() {
self.controller.binding = self.selected_pad_action;
self.controller.draw(s, batch, atlas, cursor, self.in_world);
@@ -3708,6 +3700,8 @@ impl OptionsUi {
let in_world = self.in_world;
if let Some(shell) = self.shell_mut() {
shell.draw(s, batch, atlas, cursor, in_world, waiting);
// The keys lay the screen out at the size it was drawn at.
self.size = (batch.width, batch.height);
return;
}
if self.page() == Page::SplitSetup {
@@ -3797,22 +3791,16 @@ impl OptionsUi {
}
match &wd.kind {
WKind::Button { label, active, act } => {
if matches!(act, Act::Done) {
ui::action_button(
batch,
atlas,
crate::widgets::Action::Done,
wd.x,
wd.y,
wd.w,
wd.h,
label,
*active,
hover,
);
} else {
ui::button(batch, atlas, wd.x, wd.y, wd.w, wd.h, label, *active, hover);
}
ui::focused_button(
batch,
atlas,
[wd.x, wd.y, wd.w, wd.h],
label,
*active,
pointer_over,
is_focused,
matches!(act, Act::Done).then_some(crate::widgets::Action::Done),
);
crate::widgets::last_narratable(|n| {
narrate_widget(n, s, wd, hover, list_key, framebuffer);
});
@@ -4061,21 +4049,6 @@ impl OptionsUi {
let outcome = c.click((x, y), size, drag);
return self.calibration_outcome(s, outcome);
}
if Self::graphics_page(self.page()).is_some() {
// Waiting on a key: a mouse button binds, as on Key Binds.
if self.selected_key.is_some() && !drag {
let button = if right {
winit::event::MouseButton::Right
} else {
winit::event::MouseButton::Left
};
return self.bind_mouse(s, button);
}
let actions =
self.graphics
.click(s, (x, y), size, framebuffer, drag, right, self.shift);
return self.graphics_events(s, actions);
}
if self.shell().is_some() {
// Waiting on a key: a mouse button binds, as on Key Binds.
if self.selected_key.is_some() && !drag {
@@ -4087,6 +4060,8 @@ impl OptionsUi {
return self.bind_mouse(s, button);
}
let shift = self.shift;
self.framebuffer = framebuffer;
self.graphics_framebuffer();
let outputs = self.shell_mut().map_or_else(Vec::new, |shell| {
shell.click(s, (x, y), size, drag, right, shift)
});
@@ -4228,6 +4203,11 @@ impl OptionsUi {
if wd.list && (y < top || y >= bottom) {
continue;
}
// AbstractWidget.mouseClicked rejects inactive buttons before the
// container can focus them.
if matches!(wd.kind, WKind::Button { active: false, .. }) {
return events;
}
// A click focuses the widget for its highlight only: vanilla's wheel
// steps a keyboard-focused widget from anywhere, not a clicked one.
self.focus = Some(focus_id(wd_idx, &wd));
@@ -4369,8 +4349,7 @@ impl OptionsUi {
let slider = self.dragging.take().is_some();
let (shader_slider, shader_pack) = self.shader.release();
let shell_slider = self.shell_mut().is_some_and(|shell| shell.release());
let graphics_slider =
self.graphics.release() | self.controller.release() | shader_slider | shell_slider;
let graphics_slider = self.controller.release() | shader_slider | shell_slider;
let calibration_slider = self.calibration.as_mut().is_some_and(|c| c.release());
let split_drop = self.split_setup.release();
if slider || graphics_slider || calibration_slider {
@@ -4437,7 +4416,6 @@ impl OptionsUi {
/// wheel wherever the cursor is. Focus left by a click does not count
/// (`focus_from_keyboard`): honouring it toggled the clicked option on every
/// later wheel event, from anywhere on the screen, while the list never scrolled.
/// The graphics screen has its own wheel (`GraphicsUi::wheel`).
pub fn wheel(
&mut self,
s: &mut Settings,
@@ -4451,14 +4429,11 @@ impl OptionsUi {
if self.resource_error.is_some() {
return Vec::new();
}
self.graphics_framebuffer();
if let Some(shell) = self.shell_mut() {
let outputs = shell.wheel(s, size, cursor, amount);
return self.shell_events(s, outputs);
}
if Self::graphics_page(self.page()).is_some() {
let actions = self.graphics.wheel(s, size, cursor, framebuffer, amount);
return self.graphics_events(s, actions);
}
if self.page() == Page::Studio {
self.studio.wheel(amount);
return Vec::new();
@@ -4550,10 +4525,6 @@ impl OptionsUi {
shell.scroll(s, size, amount);
return;
}
if Self::graphics_page(self.page()).is_some() {
self.graphics.scroll(s, size, amount);
return;
}
if self.page() == Page::Studio {
self.studio.wheel(amount);
return;
@@ -4750,8 +4721,6 @@ impl OptionsUi {
if shell.typing() {
shell.type_text(text);
}
} else if Self::graphics_page(self.page()).is_some() && self.graphics.typing() {
self.graphics.type_text(text);
} else if Self::controller_page(self.page()).is_some() && self.controller.typing() {
self.controller.type_text(text);
} else if Self::shader_page(self.page()).is_some() && self.shader.typing() {
@@ -4790,9 +4759,6 @@ impl OptionsUi {
if let Some(shell) = self.shell_mut() {
return shell.shortcut(shortcut, clipboard);
}
if Self::graphics_page(self.page()).is_some() {
return self.graphics.shortcut(shortcut, clipboard);
}
if Self::controller_page(self.page()).is_some() {
return self.controller.shortcut(shortcut, clipboard);
}
@@ -4909,24 +4875,13 @@ impl OptionsUi {
return Vec::new();
}
if Self::graphics_page(self.page()).is_some() {
let size = (self.size.0.max(480.0), self.size.1.max(240.0));
let fb = [self.framebuffer[0].max(480), self.framebuffer[1].max(240)];
let (actions, handled) = self.graphics.key_modifiers(s, key, text, shift, size, fb);
let mut events = self.graphics_events(s, actions);
if key == K::Escape {
events.extend(self.back(s));
return events;
}
if handled {
return events;
}
return events;
}
let gui = (
self.size.0.max(MIN_KEY_GUI.0),
self.size.1.max(MIN_KEY_GUI.1),
);
// The size it was drawn at; before the first draw, one its keys can lay out at.
let gui = if self.size.0 > 0.0 && self.size.1 > 0.0 {
self.size
} else {
MIN_KEY_GUI
};
self.graphics_framebuffer();
if let Some(shell) = self.shell_mut() {
let outputs = shell.key(s, key, text, shift, gui);
return self.shell_events(s, outputs);
@@ -6101,6 +6056,104 @@ mod tests {
assert_eq!(s.file.fullscreen_resolution, None);
}
#[test]
fn pointer_cursor_leaves_a_clicked_option_while_its_focus_stays() {
use crate::widgets::{Cursor, take_cursor};
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::Video);
let size = (480.0, 480.0);
let (widgets, top, bottom, _) = ui.layout(&s, size.0, size.1);
let button = widgets
.iter()
.find(|wd| {
matches!(
wd.kind,
WKind::Button {
active: true,
act: Act::Cycle(_),
..
}
) && (!wd.list || wd.y >= top && wd.y + wd.h <= bottom)
})
.expect("visible cycle button");
let over = (button.x + 1.0, button.y + 1.0);
ui.click(
&mut s,
&atlas,
over.0,
over.1,
size,
[480, 480],
false,
false,
);
ui.release();
assert!(
ui.focus.is_some(),
"the accepted click keeps vanilla's focus"
);
assert!(!ui.focus_from_keyboard);
let _ = take_cursor();
ui.draw(&s, &mut HudBatch::new([480, 480]), &atlas, over);
assert_eq!(take_cursor(), Cursor::PointingHand);
ui.draw(&s, &mut HudBatch::new([480, 480]), &atlas, (-10.0, -10.0));
assert_eq!(take_cursor(), Cursor::Arrow, "focus is not mouse hover");
assert!(
ui.focus.is_some(),
"moving the pointer does not clear focus"
);
ui.focus_from_keyboard = true;
ui.draw(&s, &mut HudBatch::new([480, 480]), &atlas, (-10.0, -10.0));
assert_eq!(
take_cursor(),
Cursor::Arrow,
"keyboard focus is not mouse hover either"
);
}
#[test]
fn pointer_cursor_leaves_a_disabled_option_without_focusing_it() {
use crate::widgets::{Cursor, take_cursor};
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::KeyBinds);
let size = (480.0, 480.0);
let (widgets, top, bottom, _) = ui.layout(&s, size.0, size.1);
let button = widgets
.iter()
.find(|wd| {
matches!(wd.kind, WKind::Button { active: false, .. })
&& (!wd.list || wd.y >= top && wd.y + wd.h <= bottom)
})
.expect("visible disabled button");
let over = (button.x + 1.0, button.y + 1.0);
let _ = take_cursor();
ui.draw(&s, &mut HudBatch::new([480, 480]), &atlas, over);
assert_eq!(take_cursor(), Cursor::NotAllowed);
assert!(
ui.click(
&mut s,
&atlas,
over.0,
over.1,
size,
[480, 480],
false,
false
)
.is_empty()
);
assert!(
ui.focus.is_none(),
"an inactive widget rejects the click before focus"
);
ui.draw(&s, &mut HudBatch::new([480, 480]), &atlas, (-10.0, -10.0));
assert_eq!(take_cursor(), Cursor::Arrow);
}
#[test]
fn a_clicked_extras_tooltip_leaves_with_the_pointer() {
let atlas = atlas();
@@ -7616,7 +7669,7 @@ mod tests {
/// Packs... opens the pack list, listed afresh, and Done comes back to that page.
#[test]
fn the_graphics_shaders_page_opens_the_shader_pack_list() {
use crate::graphics_ui::{H, Item, Target};
use crate::graphics_ui::{H, Item};
use winit::keyboard::KeyCode;
let atlas = atlas();
let mut s = Settings::default();
@@ -7625,15 +7678,15 @@ mod tests {
..Default::default()
};
ui.show(Page::Graphics);
ui.graphics.open(crate::graphics_ui::Page::Shaders);
let packs = Target::Item(Item::Horizon(H::ShaderPacks));
ui.graphics.show(crate::graphics_ui::Page::Shaders);
let packs = Item::Horizon(H::ShaderPacks);
assert!(
(0..40).any(|_| {
ui.key(&mut s, &atlas, KeyCode::Tab, None);
ui.graphics.focus == Some(packs)
ui.graphics.focused_row() == Some(packs)
}),
"{:?}",
ui.graphics.focus
ui.graphics.focused()
);
let events = ui.key(&mut s, &atlas, KeyCode::Enter, None);
assert_eq!(ui.page(), Page::ShaderPacks);
@@ -7642,7 +7695,10 @@ mod tests {
assert!(events.contains(&Event::OpenShaderOptions), "{events:?}");
ui.back(&mut s);
assert_eq!(ui.page(), Page::Graphics);
assert_eq!(ui.graphics.page(), crate::graphics_ui::Page::Shaders);
assert_eq!(
ui.graphics.open_page(),
Some(crate::graphics_ui::Page::Shaders)
);
}
#[test]
@@ -7865,14 +7921,20 @@ mod tests {
#[test]
fn the_graphics_screens_wheel_scrolls_even_over_a_slider_being_changed() {
use crate::graphics_ui::{H, Item, Target};
use crate::graphics_ui::{H, Item};
use winit::keyboard::KeyCode as K;
let mut s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::Graphics);
ui.graphics.show(crate::graphics_ui::Page::Performance);
let size = (640.0, 360.0);
s.horizon.chunk_updates = 16;
ui.graphics.focus = Some(Target::Item(Item::Horizon(H::ChunkUpdates)));
ui.graphics.can_change_value = true;
let chunk_updates = Item::Horizon(H::ChunkUpdates);
// Tab onto it: the arrows change it.
while ui.graphics.focused_row() != Some(chunk_updates) {
shell::Hosted::key(&mut ui.graphics, &mut s, K::Tab, None, false, size);
}
assert!(ui.graphics.changes_value());
let before = ui.graphics.scroll_amount();
ui.wheel(&mut s, size, (320.0, 150.0), [1920, 1080], -1.0);
assert_eq!(s.horizon.chunk_updates, 16);
@@ -7902,29 +7964,21 @@ mod tests {
// 2. Horizon Graphics page through OptionsUi:
// Tab onto ChunkUpdates slider, ArrowRight adjusts value, Space toggles can_change_value
ui.show(Page::Graphics);
ui.graphics.open(crate::graphics_ui::Page::Performance);
ui.graphics.show(crate::graphics_ui::Page::Performance);
s.horizon.chunk_updates = 10;
let chunk_updates = crate::graphics_ui::Item::Horizon(crate::graphics_ui::H::ChunkUpdates);
ui.size = size;
ui.framebuffer = [854, 480];
// Tab into controls
for _ in 0..80 {
ui.key(&mut s, &atlas, K::Tab, None);
if ui.graphics.focus
== Some(crate::graphics_ui::Target::Item(
crate::graphics_ui::Item::Horizon(crate::graphics_ui::H::ChunkUpdates),
))
{
if ui.graphics.focused_row() == Some(chunk_updates) {
break;
}
}
assert_eq!(
ui.graphics.focus,
Some(crate::graphics_ui::Target::Item(
crate::graphics_ui::Item::Horizon(crate::graphics_ui::H::ChunkUpdates)
))
);
assert!(ui.graphics.can_change_value);
assert_eq!(ui.graphics.focused_row(), Some(chunk_updates));
assert!(ui.graphics.changes_value());
// Right arrow steps ChunkUpdates to 11
let events = ui.key(&mut s, &atlas, K::ArrowRight, None);
@@ -7933,7 +7987,7 @@ mod tests {
// Space toggles can_change_value to false
ui.key(&mut s, &atlas, K::Space, None);
assert!(!ui.graphics.can_change_value);
assert!(!ui.graphics.changes_value());
// ArrowRight does not change ChunkUpdates when can_change_value is false
ui.key(&mut s, &atlas, K::ArrowRight, None);
+112 -7
View File
@@ -462,7 +462,7 @@ fn read_meta(source: &Source) -> Option<serde_json::Value> {
/// The first JSON value of a `pack.mcmeta`: what follows it is ignored, as some packs sign the
/// file with a comment after the closing brace. Gson reads past a UTF-8 byte order mark;
/// serde_json rejects it.
fn parse_meta(bytes: &[u8]) -> Option<serde_json::Value> {
pub(crate) fn parse_meta(bytes: &[u8]) -> Option<serde_json::Value> {
serde_json::Deserializer::from_slice(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes))
.into_iter()
.next()?
@@ -837,24 +837,55 @@ fn build_overlay_uncached(
dependencies,
&mut extract,
)?;
// What the zips may unpack to, all threads together: a server's pack is a download the
// player only accepts, and a gigabyte of zeros deflates to a megabyte, so without it a pack
// at the download limit wrote hundreds of gigabytes here. Vanilla never unpacks a pack.
let budget = std::sync::atomic::AtomicU64::new(unpack_budget(packs));
// Inflating and writing a big pack's files one by one was most of a cold build; its
// folders all exist by now.
crate::par::par_map(&extract, |(owner, inner, target)| {
let extracted: io::Result<()> = crate::par::par_map(&extract, |(owner, inner, target)| {
let Some(Some(z)) = zips.get(*owner) else {
return Ok(());
};
// One unreadable entry costs that file, not the pack: an error here
// failed the build and the reload dropped every server pack in the stack.
match z.read(inner) {
Ok(bytes) => fs::write(target, bytes),
let copied = fs::File::create(target).and_then(|file| {
let mut file = io::BufWriter::new(file);
z.copy_to(inner, &mut file, &budget)?;
io::Write::flush(&mut file)
});
match copied {
Ok(()) => Ok(()),
// Past the budget the build fails, and the reload drops the server packs.
Err(e) if e.kind() == io::ErrorKind::FileTooLarge => Err(e),
// One unreadable entry costs that file, not the pack: an error here
// failed the build and the reload dropped every server pack in the stack.
Err(e) => {
log::warn!("Horizon: skipping unreadable pack entry {inner}: {e}");
let _ = fs::remove_file(target);
Ok(())
}
}
})
.into_iter()
.collect()
.collect();
if extracted.is_err() {
// What was unpacked before the budget ran out goes too, not only the marker.
let _ = fs::remove_dir_all(out);
}
extracted
}
/// The most the zip packs in `packs` may unpack to in one overlay: 16 times their size on disk
/// (real packs are mostly PNGs and JSON, a few times smaller zipped at most), at least 64 MiB
/// for a small pack of text, and never past 8 GiB.
fn unpack_budget(packs: &[Pack]) -> u64 {
packs
.iter()
.filter_map(|p| match &p.source {
Source::Zip(z) => fs::metadata(z).ok().map(|m| m.len()),
Source::Dir(_) => None,
})
.sum::<u64>()
.saturating_mul(16)
.clamp(64 << 20, 8 << 30)
}
/// Files vanilla loads from every pack in turn (`getResourceStack`) rather
/// than from the top pack only.
@@ -1000,7 +1031,10 @@ pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> io::Result
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
});
let out = cache.join(format!("{hash:016x}"));
cache::hold(&out)?;
build_overlay(vanilla, packs, &out)?;
// Old selections' overlays would otherwise stay for good, each a whole unpacked copy.
cache::prune(cache);
Ok(out)
}
@@ -1736,6 +1770,77 @@ mod tests {
let _ = fs::remove_dir_all(base);
}
#[test]
fn a_pack_that_unpacks_past_its_budget_fails_and_leaves_nothing() {
use std::io::Write as _;
let base = std::env::temp_dir().join(format!("horizon-pack-bomb-{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let vanilla = base.join("vanilla");
fs::create_dir_all(vanilla.join("assets/minecraft/textures/block")).unwrap();
fs::write(
vanilla.join("assets/minecraft/textures/block/stone.png"),
b"vanilla",
)
.unwrap();
fs::create_dir_all(base.join("packs")).unwrap();
let pack = |name: &str, files: &[(&str, usize)]| {
let path = base.join("packs").join(name);
let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap());
let deflated = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated);
zip.start_file("pack.mcmeta", deflated).unwrap();
zip.write_all(br#"{"pack":{"description":"d","pack_format":97}}"#)
.unwrap();
let zeros = vec![0u8; 1 << 20];
for (file, mib) in files {
zip.start_file(*file, deflated).unwrap();
for _ in 0..*mib {
zip.write_all(&zeros).unwrap();
}
}
zip.finish().unwrap();
fs::metadata(&path).unwrap().len()
};
// Four 24 MiB files of zeros: well under the per-file limit, 96 MiB in all from a zip of
// a few hundred KiB, past the 64 MiB a small pack may unpack to.
let size = pack(
"bomb.zip",
&[
("assets/minecraft/textures/block/a.png", 24),
("assets/minecraft/textures/block/b.png", 24),
("assets/minecraft/textures/block/c.png", 24),
("assets/minecraft/textures/block/d.png", 24),
],
);
assert!(size < 1 << 20, "the bomb is small: {size} bytes");
let packs = discover(&vanilla, &base.join("packs"));
assert_eq!(packs.len(), 1);
let out = base.join("overlay");
let error = build_overlay(&vanilla, &packs, &out).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::FileTooLarge, "{error}");
assert!(
!out.exists(),
"what was unpacked before the budget ran out stays"
);
// The same files within the budget unpack whole.
fs::remove_file(base.join("packs/bomb.zip")).unwrap();
pack(
"fine.zip",
&[
("assets/minecraft/textures/block/a.png", 24),
("assets/minecraft/textures/block/b.png", 24),
],
);
let packs = discover(&vanilla, &base.join("packs"));
build_overlay(&vanilla, &packs, &out).unwrap();
assert_eq!(
fs::metadata(out.join("assets/minecraft/textures/block/b.png"))
.unwrap()
.len(),
24 << 20
);
let _ = fs::remove_dir_all(&base);
}
#[test]
fn zip_entries_never_leave_the_overlay() {
use std::io::Write as _;
let base = std::env::temp_dir().join(format!("horizon-pack-escape-{}", std::process::id()));
@@ -297,6 +297,107 @@ fn lock_path(out: &Path) -> PathBuf {
marker_path(out).with_extension("lock")
}
/// The overlays [`prune`] keeps in a cache folder, newest use first. Each holds a whole unpacked
/// copy of its zip packs, and every server pack, and every new version of one, makes another.
pub(super) const KEEP: usize = 8;
/// The file whose shared lock says a process uses `out`, and whose time is its last use.
fn use_path(out: &Path) -> PathBuf {
marker_path(out).with_extension("use")
}
/// Marks `out` as used by this process until it exits ([`prune`] never deletes it), and as used
/// now. The lock is taken before the overlay is built or read, so a prune in another process
/// that took the folder first finishes deleting it before this one rebuilds it.
pub(super) fn hold(out: &Path) -> io::Result<()> {
use std::sync::{Mutex, PoisonError};
static HELD: Mutex<Vec<(PathBuf, fs::File)>> = Mutex::new(Vec::new());
if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
let mut held = HELD.lock().unwrap_or_else(PoisonError::into_inner);
let at = match held.iter().position(|(path, _)| path == out) {
Some(at) => at,
None => {
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(use_path(out))?;
file.lock_shared()?;
held.push((out.into(), file));
held.len() - 1
}
};
// Only the order of the prune depends on it: a filesystem without the time loses nothing.
let _ = held[at].1.set_modified(std::time::SystemTime::now());
Ok(())
}
/// Deletes the overlays in `cache` past the [`KEEP`] most recently used, skipping any that a
/// process holds ([`hold`]) or builds. Only `<16 hex digits>` folders are overlays.
pub(super) fn prune(cache: &Path) {
let Ok(entries) = fs::read_dir(cache) else {
return;
};
let mut overlays: Vec<(std::time::SystemTime, PathBuf)> = entries
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.len() == 16 && n.bytes().all(|b| b.is_ascii_hexdigit()))
&& p.is_dir()
})
.map(|p| {
// An overlay built before use files existed goes by its marker or its folder.
let used = [use_path(&p), marker_path(&p), p.clone()]
.iter()
.find_map(|f| fs::metadata(f).and_then(|m| m.modified()).ok())
.unwrap_or(std::time::UNIX_EPOCH);
(used, p)
})
.collect();
overlays.sort_by_key(|(used, _)| std::cmp::Reverse(*used));
for (_, old) in overlays.into_iter().skip(KEEP) {
if let Err(e) = remove_unused(&old) {
log::warn!(
"Horizon: couldn't remove the old pack overlay {}: {e}",
old.display()
);
}
}
}
/// Deletes the overlay `out` unless a process builds or uses it. The lock files stay: deleting
/// them would let two processes lock different files of the same name.
fn remove_unused(out: &Path) -> io::Result<()> {
let open = |path: PathBuf| {
fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
};
let building = open(lock_path(out))?;
let using = open(use_path(out))?;
for lock in [&building, &using] {
match lock.try_lock() {
Ok(()) => {}
Err(fs::TryLockError::WouldBlock) => return Ok(()),
Err(fs::TryLockError::Error(e)) => return Err(e),
}
}
// The marker first: a folder half deleted is never taken for a built one.
match fs::remove_file(marker_path(out)) {
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {}
}
fs::remove_dir_all(out)
}
pub(super) fn build(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<()> {
if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
@@ -368,6 +469,77 @@ mod tests {
use crate::{packs, text::Text};
use std::sync::atomic::{AtomicUsize, Ordering};
#[test]
fn prune_keeps_the_most_recently_used_overlays_and_those_in_use() {
let f = Fixture::new();
let cache = f.0.join("cache");
let now = std::time::SystemTime::now();
// KEEP + 4 overlays, overlay 0 used last; one more not an overlay.
let overlays: Vec<PathBuf> = (0..KEEP + 4)
.map(|i| {
let out = cache.join(format!("{i:016x}"));
f.write(&format!("cache/{i:016x}/assets/a.png"), b"x");
f.write(&format!("cache/{i:016x}.overlay-cache.json"), b"{}");
let used = fs::File::create(use_path(&out)).unwrap();
used.set_modified(now - std::time::Duration::from_secs(60 * i as u64))
.unwrap();
out
})
.collect();
f.write("cache/notes/keep.txt", b"x");
// Another process uses the oldest, and builds the second oldest.
let using = fs::File::open(use_path(&overlays[KEEP + 3])).unwrap();
using.lock_shared().unwrap();
let building = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(lock_path(&overlays[KEEP + 2]))
.unwrap();
building.lock().unwrap();
prune(&cache);
let kept: Vec<bool> = overlays.iter().map(|o| o.is_dir()).collect();
let mut expected = vec![true; KEEP];
expected.extend([false, false, true, true]);
assert_eq!(kept, expected);
assert!(
!marker_path(&overlays[KEEP]).exists(),
"never reused half deleted"
);
assert!(cache.join("notes/keep.txt").exists());
// Released, they go at the next prune.
drop((using, building));
prune(&cache);
assert_eq!(
overlays.iter().filter(|o| o.is_dir()).count(),
KEEP,
"only the most recent stay"
);
assert!(overlays[..KEEP].iter().all(|o| o.is_dir()));
}
#[test]
fn an_overlay_held_by_this_process_is_never_pruned() {
let f = Fixture::new();
let cache = f.0.join("cache");
let held = cache.join("00000000000000ff");
f.write("cache/00000000000000ff/assets/a.png", b"x");
hold(&held).unwrap();
// Older than KEEP others, and still in use.
let old = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
fs::File::options()
.write(true)
.open(use_path(&held))
.unwrap()
.set_modified(old)
.unwrap();
for i in 0..KEEP {
f.write(&format!("cache/{i:016x}/assets/a.png"), b"x");
}
prune(&cache);
assert!(held.is_dir());
}
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
@@ -0,0 +1,237 @@
//! The shared atlas's LabPBR maps (`_n`, `_s` beside an item's, entity's or block's texture),
//! for shader packs: a map the size of the atlas would be mostly empty (only some textures have
//! maps) and as large as the atlas itself, so each is a paged map instead. The atlas is cut into
//! 16x16 pages; only pages holding a mapped texture get one in the map's pool, found through a
//! page table at the map's start. Packs read the maps with the colour's coordinates, as for
//! terrain: the translator turns their reads into `hz_pagedTexture` (horizon-shaders,
//! `PAGED_READ`, which documents the layout this writes).
/// A page's side, in texels.
pub const PAGE: u32 = 16;
/// Texels before the page table: the atlas's size, and the map's value where it has none.
const HEADER: u32 = 2;
/// One paged map, RGBA8.
#[derive(Clone, Debug, PartialEq)]
pub struct PagedMap {
pub width: u32,
pub height: u32,
pub pixels: Vec<u8>,
}
/// A texture's maps: its place in the atlas (x, y, width, height, in texels) and its normal and
/// specular images at that size (RGBA8), each where it has one.
pub struct SpriteMaps {
pub rect: [u32; 4],
pub maps: [Option<Vec<u8>>; 2],
}
/// The normal and specular paged maps of an atlas of `size` texels, each `None` where no texture
/// has that map; `max_side` is the GPU's largest texture side.
pub fn build(size: (u32, u32), sprites: &[SpriteMaps], max_side: u32) -> [Option<PagedMap>; 2] {
[
(0, crate::sprites::FLAT_NORMAL),
(1, crate::sprites::NO_SPECULAR),
]
.map(|(kind, default)| {
let mapped = sprites
.iter()
.filter_map(|s| s.maps[kind].as_deref().map(|m| (s.rect, m)));
build_one(size, mapped, default, max_side)
})
}
fn build_one<'a>(
(width, height): (u32, u32),
sprites: impl Iterator<Item = ([u32; 4], &'a [u8])>,
default: [u8; 4],
max_side: u32,
) -> Option<PagedMap> {
let (pages_x, pages_y) = (width.div_ceil(PAGE), height.div_ceil(PAGE));
// Each atlas page's place in the pool, plus one (0: none).
let mut table = vec![0u32; (pages_x * pages_y) as usize];
let mut pool: Vec<Vec<u8>> = Vec::new();
let blank: Vec<u8> = default.repeat((PAGE * PAGE) as usize);
for ([x, y, w, h], map) in sprites {
if w == 0 || h == 0 || map.len() < (w * h * 4) as usize || x + w > width || y + h > height {
continue;
}
for py in y / PAGE..=(y + h - 1) / PAGE {
for px in x / PAGE..=(x + w - 1) / PAGE {
let entry = &mut table[(py * pages_x + px) as usize];
if *entry == 0 {
pool.push(blank.clone());
*entry = pool.len() as u32;
}
let page = &mut pool[*entry as usize - 1];
// The sprite's texels on this page.
let (x0, x1) = (x.max(px * PAGE), (x + w).min((px + 1) * PAGE));
let (y0, y1) = (y.max(py * PAGE), (y + h).min((py + 1) * PAGE));
for ty in y0..y1 {
let src = (((ty - y) * w + (x0 - x)) * 4) as usize;
let dst = (((ty - py * PAGE) * PAGE + (x0 - px * PAGE)) * 4) as usize;
let len = ((x1 - x0) * 4) as usize;
page[dst..dst + len].copy_from_slice(&map[src..src + len]);
}
}
}
}
if pool.is_empty() || pool.len() >= 1 << 24 {
return None;
}
let entries = HEADER + pages_x * pages_y;
// The narrowest map width (whole pages) that keeps it within the GPU's side.
let (side, rows, map_height) = [1024, 2048, 4096, 8192, 16384]
.into_iter()
.filter(|&s| s <= max_side)
.map(|s| {
let rows = entries.div_ceil(s).next_multiple_of(PAGE);
let per_row = s / PAGE;
(s, rows, rows + (pool.len() as u32).div_ceil(per_row) * PAGE)
})
.find(|&(_, _, h)| h <= max_side)?;
let mut pixels = vec![0u8; (side * map_height * 4) as usize];
let header = [
width as u8,
(width >> 8) as u8,
height as u8,
(height >> 8) as u8,
];
pixels[..4].copy_from_slice(&header);
pixels[4..8].copy_from_slice(&default);
for (i, &k) in table.iter().enumerate() {
let at = (HEADER as usize + i) * 4;
pixels[at..at + 4].copy_from_slice(&[k as u8, (k >> 8) as u8, (k >> 16) as u8, 255]);
}
let per_row = side / PAGE;
for (k, page) in pool.iter().enumerate() {
let k = k as u32;
let (ox, oy) = (k % per_row * PAGE, rows + k / per_row * PAGE);
for row in 0..PAGE {
let dst = (((oy + row) * side + ox) * 4) as usize;
let src = (row * PAGE * 4) as usize;
pixels[dst..dst + (PAGE * 4) as usize]
.copy_from_slice(&page[src..src + (PAGE * 4) as usize]);
}
}
Some(PagedMap {
width: side,
height: map_height,
pixels,
})
}
/// `map` (RGBA8, `mw` by `mh`) at `w` by `h`, nearest: a map drawn for a strip of animation
/// frames keeps its first, the colour's shape from its top.
pub fn fit(map: &[u8], (mw, mh): (u32, u32), (w, h): (u32, u32)) -> Option<Vec<u8>> {
if mw == 0 || mh == 0 || w == 0 || h == 0 || map.len() < (mw * mh * 4) as usize {
return None;
}
// The first frame of a strip as tall as the colour's frame is wide, scaled.
let frame_h = (u64::from(mw) * u64::from(h) / u64::from(w)).clamp(1, u64::from(mh)) as u32;
let mut out = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
let sy = (u64::from(y) * u64::from(frame_h) / u64::from(h)) as u32;
for x in 0..w {
let sx = (u64::from(x) * u64::from(mw) / u64::from(w)) as u32;
let at = ((sy * mw + sx) * 4) as usize;
out.extend_from_slice(&map[at..at + 4]);
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
/// What `PAGED_READ` returns at texel (x, y) of the atlas.
fn read(map: &PagedMap, (width, height): (u32, u32), (x, y): (u32, u32)) -> [u8; 4] {
let texel = |at: u32| {
let at = (at * 4) as usize;
[0, 1, 2, 3].map(|c| map.pixels[at + c])
};
let at = |x: u32, y: u32| texel(y * map.width + x);
let h = texel(0);
assert_eq!(
(
u32::from(h[0]) | u32::from(h[1]) << 8,
u32::from(h[2]) | u32::from(h[3]) << 8
),
(width, height)
);
let pages = (width.div_ceil(PAGE), height.div_ceil(PAGE));
let e = texel(2 + (y / PAGE) * pages.0 + x / PAGE);
let k = u32::from(e[0]) | u32::from(e[1]) << 8 | u32::from(e[2]) << 16;
if k == 0 {
return texel(1);
}
let rows = (2 + pages.0 * pages.1)
.div_ceil(map.width)
.next_multiple_of(16);
let per_row = map.width / 16;
at(
(k - 1) % per_row * 16 + x % 16,
rows + (k - 1) / per_row * 16 + y % 16,
)
}
#[test]
fn mapped_textures_read_back_and_the_rest_reads_the_default() {
let size = (4096, 2048);
// A 20x20 texture across four pages, and one without a specular map.
let normal: Vec<u8> = (0..20 * 20)
.flat_map(|i: u32| [i as u8, (i >> 8) as u8, 7, 255])
.collect();
let sprites = [
SpriteMaps {
rect: [30, 40, 20, 20],
maps: [Some(normal.clone()), Some(vec![9; 20 * 20 * 4])],
},
SpriteMaps {
rect: [1000, 1000, 16, 16],
maps: [Some(vec![3; 16 * 16 * 4]), None],
},
];
let [normals, specular] = build(size, &sprites, 16384);
let (normals, specular) = (normals.unwrap(), specular.unwrap());
for y in 0..20 {
for x in 0..20 {
let i = ((y * 20 + x) * 4) as usize;
assert_eq!(read(&normals, size, (30 + x, 40 + y)), normal[i..i + 4]);
assert_eq!(read(&specular, size, (30 + x, 40 + y)), [9; 4]);
}
}
// The texels beside it on its pages, and pages without a map.
assert_eq!(read(&normals, size, (29, 40)), crate::sprites::FLAT_NORMAL);
assert_eq!(read(&normals, size, (2000, 5)), crate::sprites::FLAT_NORMAL);
assert_eq!(
read(&specular, size, (1005, 1005)),
crate::sprites::NO_SPECULAR
);
assert_eq!(read(&normals, size, (1005, 1005)), [3; 4]);
// Five pages: a table of 2 + 256 x 128 entries, 33 rows at 1024 wide (48, whole pages),
// then a row of pages.
assert_eq!((normals.width, normals.height), (1024, 64));
}
#[test]
fn nothing_mapped_makes_no_map() {
let sprites = [SpriteMaps {
rect: [0, 0, 16, 16],
maps: [None, None],
}];
assert_eq!(build((1024, 1024), &sprites, 16384), [None, None]);
}
#[test]
fn a_map_fits_its_texture() {
// A 2x map is sampled down; a strip of frames keeps its first.
let map: Vec<u8> = (0..4 * 8).flat_map(|i: u8| [i, 0, 0, 255]).collect();
let fitted = fit(&map, (4, 8), (2, 2)).unwrap();
assert_eq!(
fitted.chunks(4).map(|p| p[0]).collect::<Vec<_>>(),
[0, 2, 8, 10]
);
}
}
+18 -8
View File
@@ -60,6 +60,10 @@ pub struct ParticleOptions {
pub mod_particle: Option<String>,
/// Pre-1.20.5 entity-effect providers use spawn velocity as RGB; true is the ambient provider.
pub legacy_entity_effect: Option<bool>,
/// A pre-1.21.4 server's trail, which had no duration: TrailParticle.Provider chose
/// `nextInt(40) + 10` after constructing the particle. Set by the client for an older
/// server only, never read from the wire.
pub legacy_trail_lifetime: bool,
}
impl ParticleOptions {
pub fn simple(ty: ParticleType) -> Self {
@@ -75,6 +79,7 @@ impl ParticleOptions {
vibration: None,
mod_particle: None,
legacy_entity_effect: None,
legacy_trail_lifetime: false,
}
}
/// A native mod's `SimpleParticleType`: the sprite set of
@@ -3485,9 +3490,7 @@ impl ParticleEngine {
scaled(o.color[2], jb),
);
q.size = 0.26;
// The older-server adapter marks pre-1.21.4 TargetColorParticleOption with -1.
// Its TrailParticle.Provider chose nextInt(40) + 10 after constructing the particle.
q.lifetime = if duration == -1 {
q.lifetime = if o.legacy_trail_lifetime {
self.level_random.next_int_bound(40).unwrap_or(0) + 10
} else {
duration
@@ -5764,12 +5767,12 @@ mod tests {
fn legacy_trails_choose_a_lifetime_for_each_particle_from_the_level_random() {
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
engine.seed_randoms(1, 42, 2);
let legacy = ParticleOptions {
legacy_trail_lifetime: true,
..ParticleOptions::trail([1.0, 2.0, 3.0], 0x7f3f1f, -1)
};
for _ in 0..5 {
engine.create(
&ParticleOptions::trail([1.0, 2.0, 3.0], 0x7f3f1f, -1),
[0.0; 3],
[0.0; 3],
);
engine.create(&legacy, [0.0; 3], [0.0; 3]);
}
// java.util.Random(42).nextInt(40) + 10, as vanilla 1.21.3 TrailParticle.Provider does.
assert_eq!(
@@ -5786,6 +5789,13 @@ mod tests {
[0.0; 3],
);
assert_eq!(engine.pending.last().unwrap().lifetime, 37);
// A current server's -1 is a lifetime like any other, not the old marker.
engine.create(
&ParticleOptions::trail([1.0, 2.0, 3.0], 0x7f3f1f, -1),
[0.0; 3],
[0.0; 3],
);
assert_eq!(engine.pending.last().unwrap().lifetime, -1);
}
#[test]
fn sizes_follow_vanilla_curves() {
Loaded 100 of 936 files, more files were not shown because too many files have changed in this diff. Show more