Compare commits

...
Author SHA1 Message Date
rdbt ae0c0273f5 Merge pull request #15050 from DUzzL/fix/15047-portpack-placeholder
port-pack: accept a lone placeholder mod id template
2026-11-11 22:12:46 +00:00
rdbt ff0dbe7864 Merge pull request #15064 from ilguerro/fix/zombie-fire-aspect-rules
Zombies burn you only with a bare hand, on the difficulty's chance
2026-11-11 22:12:41 +00:00
rdbt e4042d5a2e Merge pull request #15066 from MSedgeMC/fix/reset-keys-active
The Controls Reset All button is inactive until a binding changes
2026-11-11 22:12:36 +00:00
rdbt 9fe0fd9cc7 Merge pull request #15073 from KBroneZ/claude/up-7843
A client plays with the server's block and item tags
2026-11-11 22:12:30 +00:00
rdbt 8ae679f4e1 Merge pull request #15105 from vnsmoreira/packs/s00-arrays
Core shaders: an array sized by its initializer only translates (#9386)
2026-11-11 22:12:24 +00:00
rdbt c493a84388 Merge pull request #15114 from angel2rider/docs/agents-map-lang-coverage
docs: the agents map says what lang_coverage.py --summary prints
2026-11-11 22:12:15 +00:00
rdbt d1255f85ab Merge pull request #15124 from MSedgeMC/fix/crafter-slot-state-mark
port: a crafter's slot state write marks the chunk
2026-11-11 22:12:10 +00:00
rdbt f176986623 Merge pull request #15129 from qaesen/fix-plugin-resource-packs-8570
FIX(hud): enable full compatibility for plugin resource packs (Nexo, ItemsAdder, BetterModel) (fixes #8570)
2026-11-11 22:12:05 +00:00
rdbt f0832b0998 Merge pull request #15145 from angel2rider/fix/14539-portal-cooldown
Entity.saveWithoutId writes the live PortalCooldown, not the loaded one
2026-11-11 22:11:59 +00:00
rdbt 55477b7c27 Merge pull request #15146 from MSedgeMC/fix/end-gateway-age-marks
port: an end gateway's ageing marks the chunk
2026-11-11 22:11:54 +00:00
rdbt 947c085c0f Merge pull request #15148 from MSedgeMC/fix/chat-delay-slider
The Chat Delay control is a working slider
2026-11-11 22:11:49 +00:00
rdbt 9b49d846f0 Merge pull request #15162 from MSedgeMC/fix/server-icon-1024
A server icon is kept up to 1024x1024, not only 64x64
2026-11-11 22:11:44 +00:00
rdbt e4822fe906 Merge pull request #15169 from MSedgeMC/fix/tooltip-attribute-stack
Tooltip attribute modifiers come from the stack
2026-11-11 22:08:49 +00:00
rdbt 24a2bf3900 Merge pull request #15184 from MSedgeMC/fix/region-damaged
Region: a chunk the file cannot deliver is absent, not an error
2026-11-11 22:08:45 +00:00
rdbt b2a2758162 Merge pull request #15187 from MSedgeMC/fix/chunk-default-pos
Chunk storage: a chunk without xPos/zPos is the chunk at 0, 0
2026-11-11 22:08:39 +00:00
rdbt 6757c5ed35 Merge pull request #15188 from MSedgeMC/fix/backdrop
A text backdrop frames the glyphs by one pixel
2026-11-11 22:08:35 +00:00
rdbt f57714de73 Merge pull request #15189 from angel2rider/fix/7899-ssbo-binary-init
Shader packs: a buffer object can start with the bytes of a file
2026-11-11 22:08:30 +00:00
rdbt 7b02095700 Merge pull request #15193 from DUzzL/fix/15180-enderman-place
Enderman: check carried block survival when placing; play stare sound from synced data
2026-11-11 22:08:25 +00:00
rdbt 78249e7c9e Merge pull request #15195 from MSedgeMC/fix/scrollcursor
The pack list's scrollbar shows its hover and drag cursor
2026-11-11 22:08:20 +00:00
rdbt 1e10e533cb Merge pull request #15219 from yahya-nusseibeh/fix/legacy-trim-preview-bounds
Bound legacy smithing-trim previews from old servers
2026-11-11 22:08:16 +00:00
rdbt a2d3ac8b64 Merge pull request #15226 from yahya-nusseibeh/fix/protocol-plain-text-cap
Protocol text: a disconnect reason can't expand past 1 MiB
2026-11-11 22:08:11 +00:00
rdbt 8e26a88f53 Merge pull request #15232 from yahya-nusseibeh/fix/supervisor-queued-work
Supervisor: apply queued restores and updates before every start
2026-11-11 22:08:07 +00:00
rdbt 6b704ba6f3 Merge pull request #15233 from yahya-nusseibeh/fix/server-toml-atomic
Server: write server.toml atomically under one lock, and keep the world if a restore fails
2026-11-11 22:08:02 +00:00
rdbt f8f2571c0b Merge pull request #15236 from yahya-nusseibeh/fix/launcher-accounts-atomic
Launcher: save accounts.json atomically and merge what a launch renewed
2026-11-11 22:07:57 +00:00
rdbt 9c08a53ebf Merge pull request #15242 from yahya-nusseibeh/fix/forged-log-lines
Server: players can't forge the game's log lines or flood the log
2026-11-11 22:07:53 +00:00
rdbt 083321a7fd Merge pull request #15251 from yahya-nusseibeh/fix/realms-download-files
Client: private Realms temp files, a bounded pax record, and no leaked boot-screen font
2026-11-11 22:07:45 +00:00
rdbt bbe8dfd73f Merge pull request #15254 from yahya-nusseibeh/fix/server-backup-settings-edges
Server: backup and settings edge cases
2026-11-11 22:07:41 +00:00
rdbt 0b4c9b627e Merge pull request #15353 from Akirabane/fix/login-query-payload-cap
Login: a custom-query payload over 1 MiB is refused, as vanilla refuses it
2026-11-11 22:07:36 +00:00
rdbt 1a42c8bf10 Merge pull request #15357 from Akirabane/fix/waypoint-icon-saved
A player's /waypoint modify icon is saved with the player, as vanilla saves it
2026-11-11 22:07:31 +00:00
rdbt b2ae481dee Merge pull request #15362 from DylanGonzaloFerreyra/split-play-hud
Move the boss bar, scoreboard and team packets into play/hud.rs
2026-11-11 22:07:26 +00:00
rdbt 6f3ec8b315 Merge pull request #15368 from AlfaRojo/fix/decorated-pot-normals
The decorated pot keeps its face normals and still culls
2026-11-11 22:07:21 +00:00
rdbt f7c43dd03b Merge pull request #15202 from loicpiller/feature/9432-realms-availability
Realms: the availability check vanilla makes before use (1/2)
2026-11-11 22:07:16 +00:00
rdbt 8ba548a33d Merge pull request #15205 from Akirabane/tooling/5879-water-e2e-cases
anticheat_e2e: prediction-water plays kelp, a waterfall, a changing current and waterlogged blocks
2026-11-11 22:07:11 +00:00
rdbt 07257993e6 Merge pull request #15214 from Akirabane/fix/12358-route-no-window
Finding the gateway on Windows opens no console window
2026-11-11 22:07:06 +00:00
rdbt bda383e91b Merge pull request #15271 from rdbtCVS/fix/far-chunk-gaps
Fix missing chunks and stalled retries beyond the server view distance
2026-11-11 22:07:01 +00:00
rdbt b78c1e633a Merge pull request #15348 from kacpherek/tooling/pr-ready-quick
pr_ready: run the harnesses only where CI's parity job would
2026-11-11 22:06:57 +00:00
rdbt 117db61043 Merge pull request #15422 from kacpherek/fix/14887-naga-subgroup-2d
Shader packs: allow subgroup ids in 2-D compute workgroups
2026-11-11 22:06:51 +00:00
rdbt b32ba7fa20 Merge pull request #15423 from kacpherek/fix/14886-naga-quad-swap
Shader packs: translate the subgroupQuadSwap functions
2026-11-11 22:06:46 +00:00
rdbt 95a330832d Merge pull request #15185 from MSedgeMC/fix/conversion-absorption
A converting mob keeps its golden hearts
2026-11-11 22:06:36 +00:00
rdbt eb0b785ec8 Merge pull request #15186 from MSedgeMC/port_map/zombie-drowning-rows
port map: the drowning conversion has rows
2026-11-11 22:06:31 +00:00
rdbt 0742928943 Merge pull request #15447 from kacpherek/fix/uk-ua-stale-key
main is red: a stale Ukrainian string and a sulfur cube harness group
2026-11-11 22:06:23 +00:00
Ludovic Marie 692a4d8059 Merge pull request #15413 from horizon-rust/server-tick-untimed-spans
🤖 Agent: timing spans around every untimed call of a level's pass (about 200 ms of the SMP's 250-330 ms overworld pass had none, #15349); spans read nothing while off, and no behaviour changes.
2026-11-11 22:42:03 +01:00
Ludovic Marie ceff58d796 Merge pull request #15409 from horizon-rust/fix/watchdog-server-stack
🤖 Agent: the watchdog now reads the stuck server thread's stack (a SIGURG handler installed only when a tick hangs, 5 s wait, else the report says why), so the next SMP freeze (#15349) names the function it was in; nothing changes until a tick hangs.
2026-11-11 22:41:59 +01:00
Kacpherek 31915393c1 command_exec: the sulfur cube size group shrinks its cubes before killing them
tests/test_command_exec_group_cleanup.py fails on main since #13823: the new 'sulfur cube size attributes' group kills its cubes after its last tick without shrinking them, so a size 2 cube would split inside the next group. Same shrink as the other sulfur cube groups; both commands are setup commands, so no record changes.
2026-11-11 22:32:22 +01:00
Kacpherek b36e25ab16 Ukrainian: drop the HDR peak hint en_us no longer has
en_us dropped "Your display's reported peak is often too high: calibrate to set it up." in 1c93067327; #14706 added its Ukrainian text back today, so lang::tests::bundled_files_are_served_and_have_no_stale_or_repeated_keys fails on main and on every pull request tested against it.
2026-11-11 22:32:10 +01:00
Kacper e86000f6eb Merge pull request #15309 from Akirabane/docs/port-map-game-003-fixed-gaps
port map: two rows of game-003.tsv no longer list gaps that are fixed
2026-11-11 22:29:58 +01:00
Kacper 1bd446f250 Merge pull request #15306 from Akirabane/docs/port-map-game2-001-fixed-gaps
port map: three rows of game2-001.tsv no longer list gaps that are fixed
2026-11-11 22:29:46 +01:00
Kacper 08be24761f Merge pull request #15223 from yahya-nusseibeh/fix/control-one-line-requests
horizon-server: a management kick reason can't inject control requests
2026-11-11 22:29:22 +01:00
Kacper ccbb5f85bc Merge pull request #15052 from DUzzL/fix/15048-rabbit-yaw
Rabbit: start the move control in MOVE_TO towards the origin like vanilla
2026-11-11 22:28:30 +01:00
Kacper e705c9175d Merge pull request #15036 from DUzzL/fix/15017-dispense-position
Fix dispense position float order to match vanilla
2026-11-11 22:28:11 +01:00
Kacper 2d6af5f5ea Merge pull request #14917 from Detimes/perf-block-event-queue
Perf: the block-event queue pops and dedupes in O(1)
2026-11-11 22:27:44 +01:00
Kacper 6cc36c6f3a Merge pull request #15229 from yahya-nusseibeh/fix/management-connection-cap
Cap management and API connections, and give a request one deadline
2026-11-11 22:20:45 +01:00
Kacper 60f0ab264d Merge pull request #15055 from ilguerro/fix/pot-comparator-signal
A comparator beside a decorated pot reads its item
2026-11-11 22:20:28 +01:00
Kacper 29f46b1320 Merge pull request #15045 from DUzzL/fix/14941-camel-lastposetick
Keep a camel's saved LastPoseTick an absolute game time while it is not ticking
2026-11-11 22:20:11 +01:00
Kacper 7a756c4b47 Merge pull request #14756 from ilguerro/perf/worldgen-noise
Worldgen: the range choice picks its values without a branch per block
2026-11-11 22:19:41 +01:00
Kacper b3e977c932 Merge pull request #15305 from Akirabane/fix/lan-keep-alive-pending-id
LAN: a keep-alive answer that is not the pending one disconnects the guest, as vanilla does
2026-11-11 22:18:55 +01:00
Kacper 7b3c73f790 Merge pull request #15298 from Akirabane/fix/lan-owner-name-taken
LAN: a login with the host's own name is refused while the host is online, as vanilla does
2026-11-11 22:18:38 +01:00
Kacper d740d99388 Merge pull request #15279 from Akirabane/fix/fov-walking-speed-from-server
The field of view uses the walking speed the server sends in the abilities packet
2026-11-11 22:18:21 +01:00
Kacper 915337910a Merge pull request #15130 from vnsmoreira/packs/polytone-limit-join
Polytone: a type's limit and exclusion_radius count only particles in the world
2026-11-11 22:18:04 +01:00
Kacper cf1f44ac13 Merge pull request #15035 from KBroneZ/claude/up-8688
Preview the anvil with a server's data-pack enchantments
2026-11-11 22:17:46 +01:00
Kacper 8ea9f4a20f Merge pull request #14944 from Detimes/perf-held-item
Perf: borrow the held item in tick_guests instead of cloning the stack
2026-11-11 22:17:19 +01:00
Kacper 94233f3ce1 Merge pull request #14882 from vermingov/fix/fire-short-14879
A mob and an armor stand narrow a loaded Fire to a short (#14879)
2026-11-11 22:16:23 +01:00
Kacper 8778015009 Merge pull request #14877 from vermingov/fix/mob-hurt-time-short-14876
A mob narrows a loaded HurtTime and DeathTime to a short (#14876)
2026-11-11 22:16:06 +01:00
Kacper 114e8cad52 Merge pull request #14787 from DUzzL/fix/14754-leash-knot-nosave
Skip leash knots when saving chunk entities
2026-11-11 22:15:49 +01:00
Kacper c63152903d Merge pull request #14777 from foudretbr/fix/drowned-husk-conversion-and-cure-timer
fix(mobs): align drowned and husk conversion ticks and cure random with vanilla (#14770)
2026-11-11 22:15:32 +01:00
Kacper 35b1b3358d Merge pull request #14686 from Mayonesu0/up-14542-armor-stand-first-tick-attrs
A loaded armor stand saves the movement_speed its first tick makes
2026-11-11 22:15:15 +01:00
Kacper 33859e433d Merge pull request #14636 from NikitaMGrimm/parity/ominous-spawner-loaded-rotation
An ominous item spawner keeps the rotation, OnGround and fall_distance it was loaded with
2026-11-11 22:14:58 +01:00
Kacper b5bba8a620 Merge pull request #14591 from DUzzL/fix/14465-item-frame-facing
Wrap item frame and painting facing bytes like vanilla's Direction codecs
2026-11-11 22:14:41 +01:00
Kacper ca7044d165 Merge pull request #14560 from Ragbie/refactor/entity-nbt-orb
Move the experience orb NBT out of entity_nbt.rs
2026-11-11 22:14:24 +01:00
Kacper 93beed5df7 Merge pull request #14183 from DUzzL/fix/14157-sign-four-lines
Load a sign side empty unless messages has exactly 4 lines
2026-11-11 22:14:06 +01:00
Kacper 7c61110eee Merge pull request #14162 from RLC248/fix/mace-smash-motion-at-hit
A mace smash on a player sends the attacker's motion after the hit
2026-11-11 22:13:49 +01:00
Kacper edd751003e Merge pull request #14147 from MSedgeMC/fix/sheep-colour-codec
An unknown saved sheep colour reads white
2026-11-11 22:13:32 +01:00
Kacper 571e833b48 Merge pull request #13823 from NikitaMGrimm/parity/sulfur-cube-bucket-health
A sulfur cube saves its size's max_health and keeps its size's speed after a reload
2026-11-11 22:13:15 +01:00
Kacper c8e1eb6619 Merge pull request #15286 from GIGABAIT93/ci/prepare-lock-link
CI vanilla data: horizon-prepare's lock file is no prepared output
2026-11-11 21:48:30 +01:00
Kacper 31578f0509 Merge pull request #15208 from KBroneZ/claude/up-15164
Random tick chunks in position order, not chunk load order
2026-11-11 21:48:18 +01:00
Kacper 12ddb73e82 Merge pull request #15172 from angel2rider/tools/tools-a-flag-is-not-a-directory-or-a-folder
tools: a flag is not a directory or a folder
2026-11-11 21:48:10 +01:00
Kacper d0f5bccf60 Merge pull request #13737 from RINNECODER/up10/boat-table-trig
Boats: Mth's sine table for steering, dismounts and minecart pushes; lastYd for water entry
2026-11-11 21:42:00 +01:00
Kacper a5df8273bb Merge pull request #15358 from ilguerro/fix/spider-hard-effect
Spiders spawned at runtime get their Hard-difficulty effect
2026-11-11 21:34:16 +01:00
Kacper a0bede5135 Merge pull request #15297 from bct8925/adreno-vulkan
Adreno on Vulkan: pack the shaders' indexed tables, and test occlusion in the shader
2026-11-11 21:34:08 +01:00
Kacper 470578dd2e Merge pull request #15163 from MSedgeMC/fix/bundle-tooltip-lines
An empty bundle's tooltip is as tall as its description
2026-11-11 21:34:00 +01:00
Kacper a5fce8fada Merge pull request #15153 from tarzinio/fix-edit-queue-cap
Cap the occlusion edit queue when cave culling is off
2026-11-11 21:33:53 +01:00
Kacper f9a645f1ec Merge pull request #15125 from MSedgeMC/fix/potion-douse-source
port: a doused campfire's block_change carries the potion's owner
2026-11-11 21:33:45 +01:00
Kacper a93fe71b74 Merge pull request #15118 from MSedgeMC/ledger/rows-3
port_map: SelectWorldScreen's button states are all modelled
2026-11-11 21:33:35 +01:00
Kacper 203baeb0bd Merge pull request #15107 from angel2rider/tools/velocity-probe-protocol
tools: the velocity probe reads the protocol it announces, instead of writing 777 by hand
2026-11-11 21:33:26 +01:00
Kacper 307029382a Merge pull request #15106 from vnsmoreira/packs/s00-vertex-index
Core shaders: a pack's gl_VertexIndex reads the glue's vertex number
2026-11-11 21:33:19 +01:00
Kacper 098012518a Merge pull request #15077 from ilguerro/fix/zombie-powder-snow-sunburn
Keep a zombie in powder snow from catching fire in daylight
2026-11-11 21:33:11 +01:00
Kacper a21d37c81d Merge pull request #15028 from sunrise-org/dims/render-facts
Sky, shading and ambient light follow the dimension type (#11282, 7/9)
2026-11-11 21:33:03 +01:00
Kacper 2c1584e88c Merge pull request #14708 from Akirabane/structure-mobs-preload-13857
Server: the mob data generation finalizes with is read when the world opens
2026-11-11 21:32:32 +01:00
Kacper c7d7576e77 Merge pull request #14706 from GIGABAIT93/l10n/uk-nightly-1110
Ukrainian: the 96 strings uk_ua.json lacked (radial menu, HDR, fuel)
2026-11-11 21:32:25 +01:00
Kacper 37bee174e9 Merge pull request #14406 from rdbtCVS/perf/heightmap-columns
Heightmaps: a write marks its column, found again alone on its next read (split of #13644, part 1)
2026-11-11 21:31:24 +01:00
Kacper 34afc9aced Merge pull request #14389 from vnsmoreira/fix/comparator-setblock-output
A comparator placed with OutputSignal by /setblock keeps it
2026-11-11 21:31:14 +01:00
Kacper 1f31436c29 Merge pull request #14345 from MSedgeMC/fix/command-block-edit-mark
Editing a command block marks its chunk
2026-11-11 21:31:05 +01:00
Kacper 99d9a0b931 Merge pull request #14022 from MSedgeMC/fix/weapon-disable-blocking-component
Disable-blocking seconds come from a stack's weapon component
2026-11-11 21:30:09 +01:00
Kacper 3eeeb544f0 Merge pull request #13836 from NikitaMGrimm/projectile-uuid-draws
A projectile draws its UUID and its shot from its own random, as vanilla does
2026-11-11 21:30:02 +01:00
Kacper d5157fe7d6 Merge pull request #13832 from RINNECODER/up13/vehicle-below-world
Boats and minecarts more than 64 blocks under the world are discarded
2026-11-11 21:29:54 +01:00
Kacper f740fdae36 Merge pull request #14678 from horizon-rust/split/external-pipeline-hook
Renderer: the ExternalPipeline hook for shader packs (layer plan M6, step a)
2026-11-11 21:18:41 +01:00
Kacper 2a9ba00903 Merge pull request #15204 from senjinthedragon/oit-crack-size
Cracks keep their size with Improved Transparency and a pack's own destroy stages
2026-11-11 21:12:58 +01:00
Kacper 32d6154943 Merge pull request #15178 from angel2rider/tools/tests-the-two-ci-scripts-that-had-no-test
tests: the two CI scripts that had no test
2026-11-11 21:12:51 +01:00
Kacper 33e30ec6fc Merge pull request #15174 from angel2rider/tools/tools-roadmap-py-s-help-says-the-python-tests-ru
tools: roadmap.py's help says the Python tests run its checks, not CI
2026-11-11 21:12:43 +01:00
Kacper cb89d995c6 Merge pull request #15155 from MSedgeMC/fix/slider-resize-cursor
A dragged slider shows the horizontal resize cursor
2026-11-11 21:12:36 +01:00
Kacper 8a6cf18c34 Merge pull request #15119 from MSedgeMC/port_map/campfire-marked-updated
port_map: CampfireBlockEntity.markUpdated is covered on both paths
2026-11-11 21:12:27 +01:00
Kacper c49a0ebf5b Merge pull request #15117 from MSedgeMC/ledger/rows-2
port_map: the Language page draws the accuracy warning
2026-11-11 21:12:19 +01:00
Kacper 69b930572d Merge pull request #15116 from MSedgeMC/ledger/rows-1
port_map: the Direct Connection screen's Join button state and initial focus
2026-11-11 21:12:12 +01:00
Kacper b891b50a74 Merge pull request #15094 from angel2rider/tools/generate-lan-command-order-help
tools: generate_lan_command_order.py prints usage instead of running the generator on --help
2026-11-11 21:12:04 +01:00
Kacper d8441062e9 Merge pull request #15089 from angel2rider/tools/lang-coverage-show-keys
tools: lang_coverage.py no longer drops --show-keys when --summary is given
2026-11-11 21:11:56 +01:00
Kacper 014dab78fc Merge pull request #15087 from angel2rider/tools/anvil-dump-help
tools: anvil_dump.py asks for its file instead of crashing on --help, and gets a test
2026-11-11 21:11:49 +01:00
Kacper b99d24ae9e Merge pull request #15076 from senjinthedragon/pass-timing-names
Shader pack timing: passes of one name count as their sum, compute passes apart
2026-11-11 21:11:41 +01:00
Kacper e5ba661931 Merge pull request #15067 from MSedgeMC/fix/preset-slider-floor
The graphics preset slider's stops follow vanilla's floor mapping
2026-11-11 21:11:34 +01:00
Kacper 9a1340b14a Merge pull request #14803 from shawshanker18/fix/tests-sibling-imports
tests: import sibling test modules by their own name
2026-11-11 21:11:27 +01:00
Kacper 0fc29c6adb Merge pull request #13839 from NikitaMGrimm/hdr-shaders-pack-no-lift
HDR output: a shaders/ pack's alpha isn't lifted as light sources
2026-11-11 21:11:20 +01:00
Kacper 501446443c Merge pull request #12156 from RINNECODER/up2/metal-sprite-arrays
Block sprites: on Metal the arrays grow past 512 layers when the sprites need it
2026-11-11 21:10:42 +01:00
Kacpherek ba299deb2d Shader packs: translate subgroupQuadSwap Horizontal, Vertical and Diagonal
naga's GLSL frontend did not know the GL_KHR_shader_subgroup_quad swaps, so any program using
them (FidelityFX SPD in several packs) failed with Unknown function. They map to naga's QuadSwap gather.
2026-11-11 21:00:56 +01:00
Kacpherek dfd289adfc Shader packs: allow subgroup ids in 2-D compute workgroups
naga rejected gl_SubgroupID and gl_SubgroupInvocationID when the workgroup had more than one
dimension, a WGSL rule GLSL does not have, so pack compute passes with a 2-D workgroup were skipped.
2026-11-11 20:58:47 +01:00
Kacpherek 4e03ad84b9 Merge main into pr-15055
# Conflicts:
#	crates/horizon-client/src/game/machines.rs
2026-11-11 20:53:28 +01:00
Kacper 084b20d5cf Merge pull request #15367 from AlfaRojo/fix/recipe-search-tooltip-only
Recipe book search without a colon matches tooltip lines only
2026-11-11 20:47:54 +01:00
Kacper 78b9b261e2 Merge pull request #15366 from AlfaRojo/fix/jukebox-placed-no-block-change
A jukebox placed with a record posts no block_change
2026-11-11 20:47:34 +01:00
Kacper fed1c51351 Merge pull request #15356 from ilguerro/fix/magma-cube-armor
Magma cubes take the damage their size's armor absorbs
2026-11-11 20:47:15 +01:00
Kacper 3dcdffb682 Merge pull request #15354 from ilguerro/fix/farm-milk-pitch-shear-event
Fix milk pitch and shear vibrations for farm animals
2026-11-11 20:46:55 +01:00
Kacper 0ac3ddb034 Merge pull request #15350 from masa-masa-0314/refactor/friends-list-updates
Friends: separate the existing list update handler
2026-11-11 20:46:35 +01:00
Kacper d54f748d38 Merge pull request #15311 from Akirabane/refactor/remove-seen-player-rep
mobs: remove Seen.player_rep, a field written for every villager and never read
2026-11-11 20:46:16 +01:00
Kacper 4deb873ce6 Merge pull request #15282 from Akirabane/fix/fall-location-trapdoors
A fall from a trapdoor says ladder, as vanilla's FallLocation does
2026-11-11 20:45:56 +01:00
Kacpherek 969effa7e0 Merge main into fix/far-chunk-gaps 2026-11-11 20:45:19 +01:00
Kacpherek 258ff26bd6 Merge main into fix/15048-rabbit-yaw 2026-11-11 20:43:58 +01:00
Kacpherek f85370184c Merge main into fix/15047-portpack-placeholder 2026-11-11 20:43:50 +01:00
Kacpherek b58389b53c Merge main into fix/14941-camel-lastposetick 2026-11-11 20:43:43 +01:00
Kacpherek bd20630159 Merge main into fix/15017-dispense-position 2026-11-11 20:43:28 +01:00
yahya-nusseibeh a0118a4bfc Merge upstream main into fix/server-backup-settings-edges 2026-11-11 21:33:01 +02:00
yahya-nusseibeh 61bd1fcfe4 Merge upstream main into fix/realms-download-files 2026-11-11 21:32:58 +02:00
yahya-nusseibeh d77c870a98 Merge upstream main into fix/forged-log-lines 2026-11-11 21:32:47 +02:00
yahya-nusseibeh 3fdf92d7f4 Merge upstream main into fix/launcher-accounts-atomic 2026-11-11 21:32:35 +02:00
yahya-nusseibeh 1d37d845bd Merge upstream main into fix/server-toml-atomic 2026-11-11 21:32:32 +02:00
yahya-nusseibeh 9df2ce4dc1 Merge upstream main into fix/management-connection-cap 2026-11-11 21:32:23 +02:00
yahya-nusseibeh 6f509879fd Merge upstream main into fix/protocol-plain-text-cap 2026-11-11 21:32:21 +02:00
yahya-nusseibeh 8246b4ac62 Merge upstream main into fix/control-one-line-requests 2026-11-11 21:32:18 +02:00
yahya-nusseibeh 1fbb508e06 Merge upstream main into fix/legacy-trim-preview-bounds 2026-11-11 21:32:10 +02:00
Kacper 8235bf1380 Merge pull request #15308 from Akirabane/docs/port-map-game2-004-fixed-gaps
port map: three rows of game2-004.tsv no longer list gaps that are fixed
2026-11-11 20:22:32 +01:00
Kacper 8561fae7bb Merge pull request #15295 from Akirabane/fix/ladder-slide-flying-client
A flying client body does not stop sliding down a ladder by sneaking, as LocalPlayer does
2026-11-11 20:22:13 +01:00
Kacper 7c4bda6333 Merge pull request #15283 from masa-masa-0314/fix/realms-reset-generate-click
Realms: make Generate New World respond to mouse clicks
2026-11-11 20:21:53 +01:00
Kacper 2c7fe19a83 Merge pull request #15265 from Akirabane/fix/item-modify-list-operation
/item modify: a list operation that cannot be done leaves the list unchanged
2026-11-11 20:21:31 +01:00
Kacper f21b8ed58e Merge pull request #15238 from yahya-nusseibeh/fix/portmap-bounds
Friends: bound router answers, and keep a bad one from crashing or freezing the game
2026-11-11 20:21:11 +01:00
Kacper 904f1ddb00 Merge pull request #15059 from ilguerro/fix/goat-ram-feeding-shield
Goats stop ramming while fed or bred, and a shield halves a ram's push
2026-11-11 20:20:50 +01:00
Kacper b8d68e1848 Merge pull request #15049 from KBroneZ/claude/up-15039
A player's copper chest plays its own hinge sound
2026-11-11 20:20:29 +01:00
Kacper 3192c16c2c Merge pull request #14781 from Raymon82777/ios/threads-task-info
horizon-threads: resident memory on iOS through Mach task_info
2026-11-11 20:20:09 +01:00
Kacper e3dbea7830 Merge pull request #14639 from MSedgeMC/fix/trader-defend-spectator
A trader llama ignores a spectator attacker
2026-11-11 20:19:46 +01:00
Kacper 1b1fc9e4dd Merge pull request #14638 from MSedgeMC/fix/vex-dead-owner-target
A vex ignores a dead owner target
2026-11-11 20:19:26 +01:00
Kacper d8b9d1aee7 Merge pull request #14637 from NikitaMGrimm/parity/noai-tadpole-ages
A tadpole with NoAI still ages and grows into a frog
2026-11-11 20:19:06 +01:00
Kacper 93dc4ef3d1 Merge pull request #14165 from iseaprojects/fix/11374-raids-before-spawns
Tick raids before natural and custom spawning
2026-11-11 20:18:45 +01:00
Kacper f0b31a7bbe Merge pull request #13759 from DUzzL/fix/13732-unbreakable-tools
Unbreakable stacks take no tool wear
2026-11-11 20:18:24 +01:00
Kacper 6f3d762140 Merge pull request #13750 from MSedgeMC/fix/guide-equippable-swappable
A pad guide reads a stack's equippable slot and swappable flag
2026-11-11 20:17:53 +01:00
Kacper e142656a86 Merge pull request #13726 from MSedgeMC/fix/editbox-utf16-length
An edit box's maximum length counts UTF-16 code units, as Java's does
2026-11-11 20:17:17 +01:00
Kacper 0e7273581f Merge pull request #12488 from MSedgeMC/fix/breed-partner-panic
A breeding animal stops when its partner panics
2026-11-11 20:16:57 +01:00
DetimesandClaude Opus 5.5 e317cb70da Merge upstream/main into perf-block-event-queue
Resolves the conflict with main so verify and parity can run again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 19:09:44 +00:00
yahya-nusseibeh 8bbb380e2a Merge remote-tracking branch 'upstream/main' into fix/supervisor-queued-work 2026-11-11 21:09:28 +02:00
yahya-nusseibehandClaude Opus 5.5 3ffd798109 Keep switch()'s doc comment above switch
The queued-work change split it so apply_queued took the first half.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 21:08:35 +02:00
Horizon agentandClaude Opus 5.5 99e14c6d02 Name the untimed parts of a server level's pass in tick spans
The official SMP's slow-tick lines spend ~200 ms of a 300 ms overworld
pass outside every named span. Spans now wrap each untimed call of the
level loop (enter_level, the mods' level hooks, streaming, update_world),
of tick/tick_world and of update_world, and level_tick wraps the world
tick, so the line names where that time goes.

Refs #15349

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 20:02:43 +01:00
Kacper a89f338f75 Merge pull request #14668 from readerkid/fix/io-pool-kick-test
Make the io_pool kick test say which packet is which, not which goes first
2026-11-11 19:45:00 +01:00
Kacper 40aa0acf24 Merge pull request #14657 from Ragbie/tests/world-border-scratch-world
levels world border tests start from a new scratch world, so they pass on a second run
2026-11-11 19:44:39 +01:00
Kacper 29afd2d73a Merge pull request #14216 from voduff/hidden-effect-promotion
Mobs: a promoted weaker Absorption clamps the amount to its maximum
2026-11-11 19:44:17 +01:00
Kacper 4062bda9c8 Merge pull request #14212 from iseaprojects/fix/11380-cart-pushable-by
Filter a moving cart's pushes by its teams' collision rules
2026-11-11 19:43:57 +01:00
Horizon agentandClaude Opus 5.5 62a2f69feb Merge main into the ExternalPipeline hook
gfx.rs: keep both imports (external's shadow helpers and main's section_fade).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 19:40:18 +01:00
Horizon agentandClaude Opus 5.5 18ceb494e9 Server watchdog: put the server thread's stack in the crash report
ServerWatchdog's report only had the last 50 log lines, so a tick stuck
for 60 s on the official server (#15349) never said where. The watchdog now
interrupts the server thread with a signal (Linux, Android, Apple) whose
handler captures that thread's backtrace, and the report carries it as its
stack, as vanilla's report carries the server thread's stack. A thread that
does not answer in 5 s, or a system without the signal, is named in the
report's details instead.

Refs #15349

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 19:35:19 +01:00
AkirabaneandClaude Sonnet 5.5 356c6c1cb3 Merge origin/main into local/R04-fall-location-trapdoors
Keep both the trapdoor fall_location_of and its test module and main's
mob-hit impl block in game/combat.rs.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 19:31:48 +01:00
Kevin RamirezandClaude Opus 5.5 e664d20ec8 A jukebox placed with a record posts no block_change
JukeboxBlock.setPlacedBy sets has_record with level.setBlock alone;
only JukeboxBlockEntity.notifyItemChangedInJukebox posts the
block_change game event. Since #14900 set_has_record posted it for the
placement too, and use_item_on failed 79 cases on main.

Fixes #15320

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 12:30:54 -06:00
Vinícius Moreira 5a52b1c13c Merge commit 'a85af177a8' into packs/polytone-limit-join 2026-11-11 15:27:30 -03:00
Kevin RamirezandClaude Opus 5.5 b745f39a11 The decorated pot keeps its face normals and still culls
#11899 left the shade of a world block entity to the entity shader,
which reads Vertex::normal, but the decorated pot's arm still
overwrote every normal with CULL_BACK (a baked-colour quad) to cull
the back faces of its flat top and bottom: the pot had neither a shade
nor a normal. mesher::cull_back keeps a shaded quad's normal with
SHADED_CULL_W (shade and cull, as the bat does) and gives CULL_BACK to
a baked one. The harness accepts SHADED_CULL_W as a shaded normal.

Fixes #15322

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 12:26:40 -06:00
Kacper 69ba5a7b63 Merge pull request #15239 from yahya-nusseibeh/fix/port-pack-panics
Port-pack: report odd worldgen JSON instead of panicking, and end a panicking modpack step
2026-11-11 19:20:37 +01:00
Kacper 2e2218eced Merge pull request #15176 from angel2rider/tools/tools-port-ledger-py-reads-the-pinned-version-fr
tools: port_ledger.py reads the pinned version from the lock file
2026-11-11 19:20:18 +01:00
Kacper f4e5eb5bcd Merge pull request #15109 from angel2rider/tools/port-modules-say-how-they-are-used
tools: the port modules say how they are used, and the port report finds every version site
2026-11-11 19:19:58 +01:00
Kacper 49667c9f3b Merge pull request #15097 from angel2rider/tools/git-version-check
tools: say git 2.38 or newer is required, instead of printing git's usage
2026-11-11 19:19:38 +01:00
Kacper 37050a4985 Merge pull request #14704 from Hiuoy/layers/get-the-game-hook
Layer split: the "no prepared files" screen gets playhorizon.dev through a hook
2026-11-11 19:19:17 +01:00
Kacper 7d76c6bb80 Merge pull request #14582 from voduff/fix/14577-preedit-test-lock
The preedit tests take turns with the composition state
2026-11-11 19:18:58 +01:00
Kacper a1cd2db8eb Merge pull request #14562 from MSedgeMC/fix/social-search-caret
A click in the social screen's search box places its caret
2026-11-11 19:18:38 +01:00
Kacper c2157fb2db Merge pull request #14420 from voduff/fix/14266-thread-loot
A test's world-pack loot tables stay on its own thread
2026-11-11 19:18:18 +01:00
Kacper fb03ea2f84 Merge pull request #14141 from MSedgeMC/fix/dragon-sitting-damage
A perched dragon keeps its saved damage through a reload
2026-11-11 19:17:59 +01:00
Kacper 92705c55fe Merge pull request #13754 from v0ntr3n/fix/remote-fishing-rod-cast
Show other players' fishing rods as cast while their bobber is out
2026-11-11 19:17:39 +01:00
AkirabaneandClaude Sonnet 5.5 871dc11a41 A player's /waypoint modify icon is saved as locator_bar_icon, as vanilla does
Waypoint.Icon is written to the player's tag when it has data (a style
other than the default, or a colour) and read back when nothing is held
in memory. A tag without the key gives the default icon.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 18:57:42 +01:00
rdbt a85af177a8 Merge pull request #15347 from kacpherek/docs/vanilla-then-better
docs: vanilla first, then better; drop the license rules; time rules for agents
2026-11-11 17:56:38 +00:00
masa-masa-0314andZCode 7961f052d6 refactor(friends): separate the existing list update handler
Move list state, foreground scheduling and the single background updater
into a private list_updates module. Retain the public social paths and
move the original state-mapping test without changing its assertions.

This is R1 after merged #15182, reapplied independently to main at
b66b2f8372. Preserve shared state, lock scopes,
request order and existing cache, failure and timing behavior.

Refs #15183

Co-Authored-By: ZCode <[email protected]>
2026-11-12 01:45:34 +08:00
AkirabaneandClaude Sonnet 5.5 654cefca28 Login custom queries: refuse a payload over 1048576 bytes, as vanilla does
ClientboundCustomQueryPacket and ServerboundCustomQueryAnswerPacket read what is
left of the packet as the payload and throw "Payload may not be larger than
1048576 bytes" past MAX_PAYLOAD_SIZE. Horizon read it with Rest, of any size.
RestN<N> is Rest with that limit; both packets use it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 18:45:01 +01:00
Dylan FerreyraandClaude Opus 5.5 4b430232ed Move the boss bar, scoreboard and team packets into play/hud.rs
BossAction, BossEvent, NumberFormat, SetDisplayObjective, ResetScore,
SetScore, SetObjective, TeamParameters and SetPlayerTeam, with their
codecs and the boss bar's two flag helpers, move byte for byte into
packets/play/hud.rs. play.rs re-exports the nine public items, so every
`packets::play::…` path still resolves.

The port map follows: the two rest-012 rows that name boss_flags and
SetPlayerTeam::write point at the new file.

Part of #13063.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:43:17 -03:00
rdbt 663ed839ff Merge pull request #14384 from Cx188/fix/14209-remove-manual-vanilla-parity
ci: remove the obsolete manual vanilla-parity job
2026-11-11 17:40:18 +00:00
rdbt 41e2db604b Merge pull request #15324 from NikitaMGrimm/ci/quarantine-never-green
Parity: six harnesses that never passed run by name only
2026-11-11 17:40:08 +00:00
rdbt 7d5427bb4f Merge pull request #15085 from angel2rider/ci/run-cargo-with-locked
ci: run cargo with --locked so a stale Cargo.lock fails instead of being rewritten
2026-11-11 17:39:36 +00:00
rdbt cbc97b2529 Merge pull request #15325 from NikitaMGrimm/ci/audit-first-failure
Nightly audit: a harness that fails in its first audit gets an issue too
2026-11-11 17:39:07 +00:00
rdbt 86a8472693 Merge pull request #15327 from NikitaMGrimm/ci/parity-main-bisect-budget
parity-main: the bisect stops on a time budget and the next run goes on from there
2026-11-11 17:38:54 +00:00
rdbt b621a878d3 Merge pull request #14087 from horizon-rust/fix/hoglin-repeat-attack
A hoglin hits from its fight activity, 41 ticks apart
2026-11-11 17:38:17 +00:00
rdbt 0d8f2ef270 Merge pull request #14088 from horizon-rust/fix/zombie-villager-random-profession
command_exec reads the zombie villagers' profession only where it is not random
2026-11-11 17:38:09 +00:00
rdbt e68a3c6974 Merge pull request #14219 from NikitaMGrimm/fix/command-exec-group-isolation
command_exec removes what each group leaves alive before the next group
2026-11-11 17:38:00 +00:00
rdbt 5bf9ac1931 Merge pull request #14086 from horizon-rust/fix/allay-pickup-cooldown
An allay stays on its pickup cooldown at 0; /item replace triggers inventory_changed
2026-11-11 17:37:52 +00:00
rdbt 8b3db9eec1 Merge pull request #14579 from Mayonesu0/up-12830-last-hurt-by-mob-load
A saved last_hurt_by_mob is read back and ends as in vanilla
2026-11-11 17:37:44 +00:00
rdbt 9c1245513c Merge pull request #15346 from horizon-rust/fix/parity-main-preserve-failures
Preserve parity failure logs before diagnosis
2026-11-11 17:37:12 +00:00
rdbt 4a3d5daf95 Merge pull request #15337 from horizon-rust/fix/ci-ubuntu-dns-7b5e12e1
ci: evaluate Ubuntu 24.04 for hosted checks
2026-11-11 17:36:13 +00:00
rdbtCVSandCodex GPT-6.1 Terra 199c56fd1a Preserve parity failure logs before bisect
Co-Authored-By: Codex GPT-6.1 Terra <[email protected]>
2026-11-11 17:29:52 +00:00
Kacpherek deb0b34fcb pr_ready: run the harnesses only where CI's parity job would
CI leaves most pull requests' harnesses to parity-main and runs them on the pull request only when it changes a harness, an oracle, a probe or the runner (parity-scope in ci.yml). pr_ready ran every affected harness locally whenever the vanilla data was there: about 80 harness-minutes per pull request by the repository's own numbers. It now follows CI's scope and lists the others; --harnesses runs them anyway.
2026-11-11 18:16:52 +01:00
Kacpherek b0211887f2 docs: tell agents where time goes and what they can skip
AGENTS.md gets a short "Don't lose time" section from measured agent sessions and CI: check for duplicates first, find code with the map, cargo check while working, no polling loops, one test per changed behaviour, don't hunt unrelated red checks, finish when a rule is unclear. CONTRIBUTING asks for a harness only where vanilla has something to compare.
2026-11-11 18:14:48 +01:00
Kacpherek 99f82f18a9 docs: drop the license rules the removed CONTRIBUTING section left in three docs
docs/cleanroom, docs/native-hooks-neoforge and docs/how-horizon-is-built linked to the removed section and repeated its rules. The history of code removed for its license stays in how-horizon-is-built.
2026-11-11 18:14:07 +01:00
Kevin RamirezandClaude Opus 5.5 2a8da2bd76 Recipe book search without a colon matches tooltip lines only
FullTextSearchTree.searchPlainText searches the plain-text tree (the
results' tooltip lines) alone; the id path is only searched for a
namespace:path query. #14910 also matched the item id path, so
recipe_book_view failed on main ("light_blue_candle" found recipes).

Fixes #15321

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 11:10:49 -06:00
Kacpherek e5177563e9 docs: drop the per-pull-request license rules from CONTRIBUTING and the template
The license section and the template's "Other projects' code" block are removed by a Horizon Team decision: agents lost time on them and misread them.
2026-11-11 17:58:09 +01:00
Kacpherek 531a071845 docs: parity first, then improve on vanilla where players gain from it
CONTRIBUTING now says Horizon works in two stages: first it plays exactly like vanilla, then it improves on it. Performance work keeps compatibility with vanilla clients, servers and saves and the gameplay players rely on, but need not copy vanilla's internal order, random calls or slow paths. Pull requests say what they no longer reproduce exactly and how it was checked.
2026-11-11 17:54:24 +01:00
rdbtCVSandCodex GPT-6.1 Sol 49cdc775d8 Keep hosted verification and launcher routing aligned
Allow the supported pinned Ubuntu 24.04 fallback in the runner-policy check while preserving the shared pool-routing and privilege guards.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:54:00 +00:00
rdbt b66b2f8372 Merge pull request #15331 from NikitaMGrimm/ci/quarantine-regressed
Parity: command_exec and four regressed harnesses run by name only until their fix
2026-11-11 16:53:13 +00:00
rdbt e14b35cecb Merge pull request #14390 from voduff/map-moved-fns-2
port map: rows follow remove_entity and the minecart save fns
2026-11-11 16:47:27 +00:00
rdbtCVSandCodex GPT-6.1 Sol 4e71c65c5c ci: test Ubuntu 24.04 for hosted verification DNS failures
Refs #15336. Pin the GitHub-hosted verify fallback for a controlled CI run; preserve the existing self-hosted routing and checks.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:46:17 +00:00
rdbtandCodex GPT-6.1 Sol 9a8c769601 Merge pull request #15291 from KBroneZ/claude/up-feature-parse
Report missing inline-feature fields against the complete flat feature map, matching the vanilla decoder.

Validation: 84/84 strict vanilla records, the feature-codec unit test, and all 5 Pong compatibility tests passed locally; required verify passed on f55a82aa12.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:39:20 +00:00
rdbtCVSandCodex GPT-6.1 Sol f8a833cc41 Merge main to pick up the corrected Pong test field
Keep the gate change unchanged and include main #15250, which carries the validated Guest.record test correction.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:37:21 +00:00
rdbt 5a58f445a6 Merge pull request #15250 from KBroneZ/claude/up-interaction-data
Print an Interaction's width before its interaction record
2026-11-11 16:34:36 +00:00
rdbtCVSandCodex GPT-6.1 Sol ddd66cd75f Follow the movement-record relocation in the existing Pong test
Match the already validated fix in #14219, #14088, #15250 and #15291: Guest.record holds the prediction record directly after main #14005.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:26:41 +00:00
rdbtCVSandCodex GPT-6.1 Sol 12315601fd Keep the two repaired harnesses in the automatic parity gate
The requested bulk merge includes #15250 and #15291. Keep interaction_data and inline_feature_parse selected so those fixes retain automatic coverage.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:21:59 +00:00
rdbt fe0dc37392 Merge pull request #14859 from NikitaMGrimm/fix/wrapper-work-dirs
frame_map_writes and wolf_anger_writes run in work folders of their own
2026-11-11 16:18:51 +00:00
rdbt 8f3adbae40 Merge pull request #15264 from Akirabane/fix/rcon-utf16-units
RCON: cut a command's output at 4096 UTF-16 units, as vanilla does
2026-11-11 16:11:05 +00:00
rdbtCVSandCodex GPT-6.1 Sol 678ed9eb24 Merge main into map-moved-fns-2 and retain the PlayerEntry note
Resolve the port-ledger conflict by retaining the explicit social_screen.rs::Entry description. The other path corrections are already on main.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:11:04 +00:00
rdbt 61444edbef Merge pull request #15257 from yahya-nusseibeh/fix/telemetry-bounds
Telemetry: refuse an impossible official player count
2026-11-11 16:10:57 +00:00
rdbt d38111c32a Merge pull request #15255 from yahya-nusseibeh/fix/server-connection-limits
Server: per-address RCON places, write timeouts for event streams, digest token compare
2026-11-11 16:10:49 +00:00
rdbt 0e87353bd8 Merge pull request #15246 from yahya-nusseibeh/fix/friends-relay-hardening
Friends and relay: bounded handshakes, endpoints, STUN and UPnP input
2026-11-11 16:10:42 +00:00
rdbt 74039da8e1 Merge pull request #15228 from yahya-nusseibeh/fix/relay-budgets
Relay: keep real codes joinable and registrations bounded per site
2026-11-11 16:10:34 +00:00
rdbt 5d71cad052 Merge pull request #15227 from yahya-nusseibeh/fix/command-intern-cap
Commands: a server's registry names can't leak without bound
2026-11-11 16:10:27 +00:00
rdbt 0bdf9ff9d8 Merge pull request #15224 from yahya-nusseibeh/fix/config-key-whitespace
horizon-server: a space in a config key can't get past the API's deny-list
2026-11-11 16:10:20 +00:00
rdbt e94ffb5b10 Merge pull request #15222 from yahya-nusseibeh/fix/backup-save-on-always
horizon-server: a backup always turns saving back on
2026-11-11 16:10:14 +00:00
rdbt 0065a8925a Merge pull request #14632 from MSedgeMC/port_map/game2-009-only2
port map: the game2-009 rows whose gaps are gone
2026-11-11 16:10:06 +00:00
rdbt 91f26d5aa2 Merge pull request #14606 from MSedgeMC/port_map/game-005-spawn-egg-paths
port map: the spawn egg block-entity rows point at spawn_eggs.rs
2026-11-11 16:09:58 +00:00
rdbt d0706e0059 Merge pull request #15272 from Akirabane/fix/identifier-namespace-dot-dot
Identifier: the namespace .. is refused, as vanilla's isValidNamespace does
2026-11-11 16:09:35 +00:00
rdbt 5c0a3b5ecf Merge pull request #15256 from yahya-nusseibeh/fix/server-list-writes-checked
Server: list edits report a failed save, server.properties is written atomically, plain params
2026-11-11 16:09:25 +00:00
rdbt fb0127a07f Merge pull request #15234 from yahya-nusseibeh/fix/service-system-sudo-user
Server: a --system unit runs as the account that ran sudo, never root
2026-11-11 16:09:15 +00:00
rdbt 9aa200334a Merge pull request #15225 from yahya-nusseibeh/fix/management-secret-os-random
Server files: the management secret comes from OS randomness, not the seed's stream
2026-11-11 16:09:04 +00:00
rdbt 7c0b174bbf Merge pull request #15083 from senjinthedragon/terrain-one-draw
Shader packs: one program's solid and cutout terrain draw in one pass
2026-11-11 16:08:54 +00:00
rdbt b52cee2760 Merge pull request #14575 from MSedgeMC/ledger/moved-citations-2
port map: finish the moved-module citations from the week's splits
2026-11-11 16:08:43 +00:00
rdbtCVSandCodex GPT-6.1 Sol 82d4e2faa9 Follow the guest movement record in the existing Pong test
Compatibility fix for main pull request #14005: the record moved out of anticheat onto Guest. Preserve the existing tick_end assertion.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:06:33 +00:00
rdbtCVSandCodex GPT-6.1 Sol fa6140c555 Follow the guest movement record in the existing Pong test
Compatibility fix for main pull request #14005: the record moved out of anticheat onto Guest. Preserve the existing tick_end assertion.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:06:33 +00:00
rdbtCVSandCodex GPT-6.1 Sol 9945e0cb21 Follow the guest movement record in the existing Pong test
Compatibility fix for main pull request #14005: the record moved out of anticheat onto Guest. Preserve the existing tick_end assertion.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:01:02 +00:00
rdbtCVSandCodex GPT-6.1 Sol f55a82aa12 Follow the guest movement record in the existing Pong test
Compatibility fix for main pull request #14005: the record moved out of anticheat onto Guest. Preserve the existing tick_end assertion.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:01:02 +00:00
rdbtCVSandCodex GPT-6.1 Sol f72c7f644d Follow the guest movement record in the existing Pong test
Compatibility fix for main pull request #14005: the record moved out of anticheat onto Guest. Preserve the existing tick_end assertion.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:01:02 +00:00
rdbtCVSandCodex GPT-6.1 Sol 15ed0df804 Follow the guest movement record in the existing Pong test
Compatibility fix for main pull request #14005: the record moved out of anticheat onto Guest. Preserve the existing tick_end assertion.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 16:01:01 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 1b2c3b4ae2 parity: command_exec runs by name only while a few of its commands differ in every run
Part of #15316.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:59:56 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 9d87f01363 parity: four harnesses that regressed on main run by name only until their fix
use_item_on (#15320), recipe_book_view (#15321), block_entity_render
(#15322) and fishing_hook_entities (#15323) passed at main's last green
parity-main (fdc87aecd, 2026-11-07) and fail now whatever a pull request
changes. Each has an issue naming the merge, or the range, that broke it.

Part of #15316.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:59:55 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 e10f3459c8 nightly audit: the new issue's wording covers a harness an earlier audit left out
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:59:11 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 2b43458b4a parity-main: the search's budget starts after HEAD and the base ran; a comment that failed is tried again
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:59:10 +01:00
rdbtCVSandCodex GPT-6.1 Sol 9d97041ffb Follow the guest movement record in the existing Pong test
Compatibility fix for main pull request #14005: the record moved out of anticheat onto Guest. Preserve the existing tick_end assertion.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:53:37 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 05e964cd8f docs: wrap the audit line
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:51:19 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 5a56eb3ae1 nightly audit: a harness that fails in its first audit gets an issue too
An issue was opened only for a harness that passed in the previous audit,
so one merged while its pull request's parity job failed or was skipped
never got one: nine such harnesses failed on main unreported (#15158).

Part of #15316.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:51:13 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 38ce5cfa4e parity-main: the bisect stops on a time budget and the next run goes on from there
Seven runs between 2026-11-09 and 11-11 searched up to 1,500 merges until
the job's 240 minutes ended, named no merge, and the next run started again
from nothing. The search now has --budget minutes (90), then says between
which merges each harness broke. What it learnt is kept in
.local/parity-runner/bisect.json while the base is the same, so the next
run narrows it further, and a merge already named gets no second comment.

Part of #15316.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:50:21 +01:00
rdbt 2be5079ae1 Merge pull request #14237 from itarqos5/test/vanilla-redstone-rules
Tests: vanilla's piston, tripwire hook and observer rules, each pinned (8 tests)
2026-11-11 15:48:35 +00:00
rdbt 1d5957fb9d Merge pull request #14222 from NikitaMGrimm/parity-process-tree
Harnesses take what they started with them: a dead harness or runner no longer leaves games running
2026-11-11 15:47:56 +00:00
rdbt 9c03f504a2 Merge pull request #14375 from DylanGonzaloFerreyra/split-play-advancements
Move the advancement packets out of play.rs into play/advancements.rs
2026-11-11 15:47:36 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 fc78a29fee parity: eight harnesses that never passed run by name only
They merged while their pull request's parity job failed or was skipped and
fail on main whatever a change touches (#15158), so every pull request that
selects them fails and parity-main cannot pass. They still run when named and
in the nightly audit, and come off the list with their fix.

Part of #15316.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 16:47:23 +01:00
rdbtCVSandCodex GPT-6.1 Sol d05a66c6f2 Merge current main before command fixture validation
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:46:51 +00:00
rdbtCVSandCodex GPT-6.1 Sol 461c878b6a Clarify the Rust cooldown field reference
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:46:51 +00:00
rdbt 216aca09f6 Merge pull request #15182 from masa-masa-0314/refactor/friends-social-model
Friends: separate existing account-social models and parsing
2026-11-11 15:46:25 +00:00
rdbt ff11e449d3 Merge pull request #15147 from MSedgeMC/fix/wheel-sensitivity-log
The mouse wheel sensitivity slider is logarithmic
2026-11-11 15:46:20 +00:00
rdbtCVSandCodex GPT-6.1 Sol 31c5e22e7f Merge current main into parity fix #15291
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:45:17 +00:00
rdbt 687f3f6d3f Merge pull request #14397 from MSedgeMC/fix/port-focus
The LAN port box is focusable while LAN is off
2026-11-11 15:45:16 +00:00
rdbt 6e5784e4fa Merge pull request #14464 from Solenopsisbot/t3/fix-saved-present-mode
Apply saved present mode before first gameplay frame
2026-11-11 15:44:39 +00:00
rdbtCVSandCodex GPT-6.1 Sol e653778213 Merge current main into parity fix #15250
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:44:35 +00:00
rdbtCVS 82134c2755 Merge main and preserve both command comparison test suites
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>

# Conflicts:
#	tests/test_command_exec_comparison.py
2026-11-11 15:44:10 +00:00
rdbtCVSandCodex GPT-6.1 Sol cd4e6696fa Merge current main before attacker reference validation
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:43:42 +00:00
rdbtCVSandCodex GPT-6.1 Sol 06560cdd7d Keep deferred-hit timer guidance beside its ordering helper
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:43:16 +00:00
rdbtCVSandCodex GPT-6.1 Sol 1420b5bd29 Merge current main before hoglin regression validation
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:37:42 +00:00
rdbtCVSandCodex GPT-6.1 Sol cef4066d7e Keep the allay pickup predicate in its feature module
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:36:55 +00:00
rdbt 77e510c3ab Merge pull request #14005 from horizon-rust/layers/movement-record
Movement prediction: the client-tick record moves into the engine (layer plan M6)
2026-11-11 15:34:21 +00:00
rdbtCVSandCodex GPT-6.1 Sol 20cd32f3a4 Gate allay item pickup on cooldown memory presence
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:29:38 +00:00
rdbtCVSandCodex GPT-6.1 Sol f0fb237cc2 Merge current main before validating allay cooldowns
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:29:22 +00:00
rdbtandCodex GPT-6.1 Sol eebd726751 Merge pull request #14085 from horizon-rust/fix/invulnerable-time-attribute-order
Canonicalize root entity attribute-list order while preserving all values, styles and other record fields.

Validation: 9 focused comparison tests and 105/105 strict vanilla parity records pass; current-head required verify is green.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:28:36 +00:00
rdbt 3acf30529b Merge pull request #15079 from angel2rider/docs/prerequisites
docs: the prerequisites say Python 3.11+ and git 2.38+
2026-11-11 15:28:23 +00:00
rdbt 197fa1e294 Merge pull request #14683 from NikitaMGrimm/hdr-pass-rules-blend
docs: HDR pass rules, tone-weighted blending is for linear light and sharpening eases off above white
2026-11-11 15:28:18 +00:00
rdbtandCodex GPT-6.1 Sol cd0b263747 Merge pull request #15092 from MSedgeMC/fix/worker-count-hybrid-test
Correct the automatic-worker assertion for machines with fewer performance cores.

Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:26:31 +00:00
rdbtCVSandCodex GPT-6.1 Sol 1fce5ccdbf Shrink the new sulfur size fixture before its cleanup
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:24:48 +00:00
rdbtCVSandCodex GPT-6.1 Sol 244b166781 Merge main into command fixture isolation
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:24:32 +00:00
rdbtCVSandCodex GPT-6.1 Sol f2b247edda Preserve attacker field ordering and wrapping timestamps
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:23:09 +00:00
rdbtCVSandCodex GPT-6.1 Sol 7baaa34948 Count down deferred hurt timers only after a reset
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:22:20 +00:00
rdbtCVSandCodex GPT-6.1 Sol 517889c893 Merge main into attacker reference loading fix
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:22:20 +00:00
rdbtCVSandCodex GPT-6.1 Sol 95fe2c81f2 Merge main into hoglin attack fix
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:21:30 +00:00
rdbtCVSandCodex GPT-6.1 Sol 6d783a4116 Cover full integer values in saved allay cooldowns
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>
2026-11-11 15:21:02 +00:00
rdbtCVS 9f32ef4233 Merge main into allay cooldown fix
Co-Authored-By: Codex GPT-6.1 Sol <[email protected]>

# Conflicts:
#	crates/horizon-client/src/mobs/allay.rs
2026-11-11 15:20:29 +00:00
AkirabaneandClaude Sonnet 5.5 a77b71a4ed mobs: remove Seen.player_rep, which nothing reads
Mob::seen wrote a villager's reputation of the player into every Seen it
built, and no code reads the field (git grep finds only its definition and
that write; the trading code reads the gossip itself). Remove the field and
the lookup. The `player` parameter of Mob::seen is now unused and is named
_player: it has many callers, and a later change can drop it from them.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 16:12:02 +01:00
AkirabaneandClaude Sonnet 5.5 67063cfdcc port_map: the two death-message rows of game-003.tsv no longer list gaps
CombatTracker.getMessageForAssistedFall and DamageSource.getLocalizedDeathMessage
are ported with their .item forms; the rows now say what the code does.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 16:03:27 +01:00
AkirabaneandClaude Sonnet 5.5 9d1b4c1b34 port_map: three rows of game2-004.tsv no longer list gaps
Piglin.holdInOffHand, PiglinAi.holdInOffhand and Drowned.rangedAttackUncertainty
are ported as vanilla's bytecode reads; the rows now say what the code does.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 16:02:34 +01:00
KBroneZandClaude Opus 5.5 48f231af5d test: pin that random-tick chunks come out in position order
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 17:02:18 +02:00
AkirabaneandClaude Sonnet 5.5 60c4d1d4f4 port_map: three rows of game2-001.tsv no longer list gaps
Wolf.getLeashOffset, ArmorStand.brokenByAnything and HangingEntity.canCoexist
are ported as vanilla's bytecode reads; the rows now say what the code does.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 16:00:58 +01:00
Riccardo Guerriero cf6ff9c340 Merge origin/main into fix/goat-ram-feeding-shield 2026-11-11 15:57:04 +01:00
yahya-nusseibehandClaude Opus 5.5 83a152c98a Keep this change apart from the other open fixes' lines
Moves a new test (or a doc comment) so the branch merges cleanly with the other open pull
requests that touch the same file, in any order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 16:46:08 +02:00
bct8925andClaude Opus 5.5 a09d036f50 Adreno on Vulkan: pack the shaders' indexed tables, and test occlusion in the shader
Qualcomm's Adreno Vulkan driver (Adreno 740, build 0676.41 of 2023-08-14) fails to link a
shader that indexes a constant array by vertex or pixel, which naga makes a private array, and
wgpu reports the failed pipeline as a lost device: the renderer never starts. The occlusion
test's box corners (cull.wgsl, gpu_occlusion.wgsl), the panorama cube (panorama.wgsl) and the
fading tiles' Bayer matrix (terrain.wgsl) are packed into u32 words read through a switch
instead, with tests that the packed tables are the old ones.

With the early depth test, occlusion culling on that driver now and then left sections out for
a frame (the world flashing black or see-through as a block broke); Adreno on Vulkan tests the
boxes in the shader, as Metal and DirectX 12 do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 09:39:27 -05:00
levzzz f23176af0f Merge pull request #15285 from levzzz5154/policy/read-restricted-source
Allow reading source under restrictive licenses
2026-11-11 19:36:18 +05:00
yahya-nusseibehandClaude Opus 5.5 482c381f6b Client: private Realms temp files, a bounded pax record, and no leaked boot-screen font
- Realms downloads and uploads used predictable names in the shared temp folder and
  File::create, which follows a planted link or reuses a planted file. They now use an
  unguessable name and a new owner-only file (create_new, 0600).
- A pax record whose length was shorter than its own prefix ("1 x") sliced backwards and
  panicked the Realms download worker; it is now refused.
- The Windows boot-screen painter restored its fonts in the wrong order, leaving one selected so
  DeleteObject failed: one HFONT leaked per repaint. It now restores the DC's own font.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 16:31:51 +02:00
KBroneZandClaude Opus 5.5 909d7a2134 fix: a missing inline feature field names the whole map, as vanilla does
In 26.3 Feature.DIRECT_CODEC dispatches on `type` straight to the type's
own map codec: there is no `config` wrapper, so `config` is just another
unread key and a missing field's DFU error names the whole map. The
command codec still fell back to a `config` sub-map, so
`{type:"minecraft:simple_block",config:{}}` reported `MapLike[{}]`. The
inline_feature_parse parity harness (#15158) now matches 84/84 records.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 16:27:39 +02:00
GIGABAIT93andClaude Opus 5.5 95ff1c5769 CI vanilla data: horizon-prepare's lock file is no prepared output
vanilla-data.sh moves whatever a preparation adds to .local/ into
shared-local/prepared/<key> and links it back. Since the preparer locks
.local/ (.horizon-prepare.lock), that took the lock file too: .local/'s
lock became a link into one preparation. Once that preparation is
pruned (four kept, two runners share them) the link dangles, the
`.local/*` glob that drops old links skips dotfiles, and the next
preparation fails: ".local/.horizon-prepare.lock: No such file or
directory".

The lock now stays a plain file: it is left out of the entries, a link
to it is removed, and old .entries that list it are skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 16:25:46 +02:00
levzzzandOpenAI GPT-6.1 7ca851a78d Allow reading source under restrictive licenses
Co-Authored-By: OpenAI GPT-6.1 <[email protected]>
2026-11-11 19:24:37 +05:00
masa-masa-0314andZCode 916764cc31 fix(realms): route reset tile mouse clicks through existing actions
Forward coordinate-hit Reset World tiles to actions 70-75 so Generate New
World reaches the existing CreateWorldRequest flow. Keep active tasks from
accepting either coordinate clicks or direct tile actions.

Follow Minecraft 26.3 RealmsResetWorldScreen.init/FrameButton and
RealmsCreateWorldFlow.createWorld. Extend the existing regression with
actual mouse coordinates, bounds, creation metadata and running-task gates.

Fixes #15273

Co-Authored-By: ZCode (new-provider/gpt-6.1-sol) <[email protected]>
2026-11-11 22:15:46 +08:00
yahya-nusseibehandClaude Opus 5.5 f46f2dbc98 Rate-limit refused quiet commands without a new LanHost field
game/lan.rs is over 3000 lines and may not grow (docs/layers.md#file-size): a refused payload is
now logged at most once a second, kept in lan_quiet.rs, instead of once per connection through a
LanHost field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 16:06:08 +02:00
yahya-nusseibehandClaude Opus 5.5 b62be5565d A router read that times out at the deadline is "too slow" on every platform
On Linux a socket read timeout is reported as WouldBlock, so a read cut short by the last part of
the deadline came back as that error instead of TimedOut (seen in CI's
a_router_trickling_its_answer_runs_out_of_time). Both kinds now end the request as TimedOut.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 16:06:03 +02:00
AkirabaneandClaude Sonnet 5.5 16e97dca16 Motion: a flying client player keeps sliding down a ladder when it sneaks
LocalPlayer.isSuppressingSlidingDownLadder is !abilities.flying &&
super.isSuppressingSlidingDownLadder(), with LivingEntity's being
isShiftKeyDown() and ServerPlayer not overriding it. Horizon answered the
sneak for every body. A client body (client_side) that is flying no longer
suppresses the slide; a server body still looks at the sneak alone.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 14:52:33 +01:00
982c71f54d Spiders spawned at runtime get their Hard-difficulty effect
Spider.finalizeSpawn (Spider.java:160-172) rolls
nextFloat() < 0.1F * getSpecialMultiplier() on HARD, then nextInt(5) for
Speed, Strength, Regeneration or Invisibility, and applies it for good
(MobEffectInstance(effect, -1)), for every spawn reason. Only the chunk
generation port did that; the runtime finalizer (summon, spawn eggs,
spawners, natural spawning) had no spider arm. Add one, share the
setRandomEffect mapping (Spider.java:207-217) between both paths, and pin
the odds, duration, effect set and the CaveSpider exception with a test.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:47:10 +01:00
AkirabaneandClaude Sonnet 5.5 268553de31 Fall location: a trapdoor counts as a ladder, as vanilla does
FallLocation.blockToFallLocation returns LADDER for Blocks.LADDER or a
block in #minecraft:trapdoors; Horizon mapped only the ladder by name, so a
fall off a climbed trapdoor said other_climbable. Move the name match into
fall_location_of and give it whether the block is in the trapdoors tag.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 14:41:26 +01:00
AkirabaneandClaude Sonnet 5.5 af65ddae12 LAN: only the pending keep-alive answer counts
ServerCommonPacketListenerImpl.handleKeepAlive accepts an answer whose id is
the pending challenge; any other answer disconnects the player with
disconnect.timeout unless they are the singleplayer owner.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 14:38:56 +01:00
rdbtCVSandGPT 6.1 Sol 8f27aaeb01 test: retain summoned zombie villager profession domain coverage
Replace only the two unseeded equality probes with deterministic built-in profession-domain checks. Keep saved VillagerData and all finalized reads exact, with regression tests for the corpus and strict feedback/callback comparison.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 13:35:33 +00:00
rdbtCVSandGPT 6.1 Sol 3e75c0f077 Constrain attribute canonicalization to root entity data
Keep quoted text, nested custom lists, modifier order and every styled
separator exact. Cover values, duplicate entries, modifier IDs and actual
state differences with regression tests; preserve the contributor commit.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 13:33:38 +00:00
rdbtCVSandCodex gpt-6.1-sol 23d4652362 Fix gaps and stalled retries in saved far-chunk sending
Send lit resident far columns with complete light layers, scan past blocked entries within the existing budget, and retain missing chunks for retry without player movement.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-11 13:33:14 +00:00
AkirabaneandClaude Sonnet 5.5 765ff1ed80 LAN: a login with the owner's name is refused while the owner is online
IntegratedPlayerList.canPlayerLogin returns multiplayer.disconnect.name_taken
when the joining name is the singleplayer owner's (ignoring case) and a player
of that name is online.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 14:31:35 +01:00
AkirabaneandClaude Sonnet 5.5 a64e9c8037 Identifier: refuse the namespace ".." as vanilla does
Identifier.isValidNamespace returns false for the namespace "..", and
otherwise accepts a-z, 0-9, '_', '-' and '.'. from_parts only checked the
characters, so Identifier::parse("..:x") succeeded.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 14:28:47 +01:00
AkirabaneandClaude Opus 5.5 6b2d1cd585 Field of view: divide by the walking speed of the server's abilities packet
ClientPacketListener.handlePlayerAbilities sets the local player's walking speed from the packet
(Abilities.setWalkingSpeed), and AbstractClientPlayer.getFieldOfViewModifier divides the movement
speed by it. Horizon kept the packet but always divided by 0.1, so a server that sends another
walking speed got a different field of view (walking speed 0.2 with a movement speed of 0.2: 1.5
instead of 1.0).

The abilities code moves out of game/remote.rs, a big file, into game/remote_abilities.rs, with the
walking speed the field of view now reads (default 0.1 before any packet) and its test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:28:04 +01:00
AkirabaneandClaude Sonnet 5.5 b50a91cb67 /item modify: a list operation that cannot be done leaves the list unchanged
ListOperation.Append, Insert and ReplaceSection give the old list back when
the result would pass the limit (256 for lore) or the offset is past the end
of the list. The command cut every result to 256 entries and moved an offset
past the end to the end instead.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 14:27:24 +01:00
levzzz 1bec6d447a Merge pull request #15211 from horizon-rust/docs/owners-council
Docs: two org owners (P28), council code owners and security managers
2026-11-11 18:23:06 +05:00
b23dd07fa9 Magma cubes take the damage their size's armor absorbs
MagmaCube.setSize (MagmaCube.java:60-66) writes size * 3 into
Attributes.ARMOR; LivingEntity.getArmorValue (LivingEntity.java:1883-1885)
reads that base back. Mob armor now reads the set attribute base instead of
only the type's armor default, so a summoned size-4 cube keeps its 12 armor.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:22:11 +01:00
AkirabaneandClaude Sonnet 5.5 d08c04020c RCON: cut a command's output at 4096 UTF-16 units, as vanilla does
RconClient.sendCmdResponse cuts the Java string with substring at 4096
UTF-16 units, so a character outside the BMP can straddle a cut, and
String.getBytes(UTF_8) writes each lone half as '?'. Horizon counted
characters instead. Split the output on UTF-16 units and write a lone
surrogate half as '?'.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 14:20:49 +01:00
KBroneZandClaude Opus 5.5 d83b716d13 fix: print an Interaction's width before its interaction record
`width` and `interaction` share a HashMap bucket at every table size, and
keys sharing a bucket iterate in insertion order. java_hash_order ranked
neither, so they fell back to key order and `interaction` came first,
while Interaction.addAdditionalSaveData writes width, height, attack,
interaction and response in that order. The interaction_data parity
harness (#15158) now matches 120/120 records.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 15:16:58 +02:00
rdbtCVSandGPT 6.1 Sol dc35fac460 Fix weapon component formatting and extend regression coverage
Cover prototype inheritance, zero-default replacement, custom weapons, empty stacks, and persisted component removal without changing the contributor's gameplay fix.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 13:05:59 +00:00
yahya-nusseibehandClaude Opus 5.5 8ded4de3fe Telemetry: refuse an impossible official player count
The official server's players.online (any u64 from a plain status ping) went into the history
as i64: above i64::MAX it wrapped negative, and near it SUM() overflowed, failing
/v1/live/history?source=official until the rows were pruned. A count above a million is now
treated as no answer: that minute stays empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 14:59:39 +02:00
yahya-nusseibehandClaude Opus 5.5 db69868ebb Friends and relay: bounded handshakes, endpoints, STUN and UPnP input
- Host: the inbound handshake slot is an RAII guard, so a failed spawn can't leak one of
  MAX_HANDSHAKES until the direct port takes nothing.
- Sessions authenticate at most 16 direct-race streams, each under one 6 s deadline instead of a
  per-read timeout a peer could drip past.
- Invite decode takes at most MAX_ENDPOINTS (8), as encode writes: a crafted code can't make the
  guest dial thousands of addresses.
- A STUN attempt has one deadline, so datagrams arriving faster than the read timeout can't keep
  the query, and the host's setup, going forever.
- A UPnP description's controlURL, URLBase or serviceType with control characters or spaces is
  ignored instead of reaching a request line or header.
- The guest's direct-race listener handles each inbound stream on its own thread with a deadline.
- Relay: the connection count is given back by a guard, and attach tokens compare in constant time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 14:45:28 +02:00
yahya-nusseibehandClaude Opus 5.5 adb97c68d7 Server: list edits report a failed save, server.properties is written atomically, plain params
- UserList add/remove only log a failed save, so with a read-only or full disk the CLI and the
  stopped server's API said "Banned X" or "Made X a server operator" though the file still said
  otherwise. Each change is now saved and checked (saved()).
- ServerProperties::store wrote server.properties in place, default mode: a crash at start left a
  short file read as defaults (a new management secret, settings dropped), readable by other
  accounts. It now writes a new file (0600 when new, an existing file's mode kept) renamed over.
- system_message/kick translatable parameters are plain text, as vanilla's Message takes them,
  not components tellraw would resolve with the console's rights.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 14:42:44 +02:00
AkirabaneandClaude Sonnet 5.5 f7224c29ee Finding the gateway on Windows opens no console window
`portmap::default_gateway` runs `route print` on Windows. A program with no
console of its own, such as the launcher, got a console window for it each
time. The command now starts with CREATE_NO_WINDOW, as the other crates'
commands do.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 13:42:12 +01:00
yahya-nusseibehandClaude Opus 5.5 978f37d092 Server: backup and settings edge cases
- Backup zips (which hold server.toml and server.properties with the API token, RCON password
  and management secret) are created owner-only.
- Pruning automatic backups deletes only `<stamp>-auto.zip`, not a backup labelled by hand
  "nightly-auto".
- backups.every no longer panics on a wide last character ("6é") or overflows on a huge number.
- A Discord rate-limit header of "NaN" no longer ends the Discord thread.
- world.name may not be ".", nor backups, logs or .horizon, which pointed the world at the server
  folder or the supervisor's own folders.
- init stops instead of replacing a whitelist.json or ops.json it could not read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 14:39:48 +02:00
yahya-nusseibehandClaude Opus 5.5 e0d880754e Server: per-address RCON places, write timeouts for event streams, digest token compare
- One address could hold all 16 RCON places idle and keep the operator's own client out; each
  address now gets at most 4.
- Management notifications went to every client from one thread with blocking writes: a client
  that stopped reading stalled them for everyone. Management sockets get a 10 s write timeout
  and a client whose write fails is closed.
- The event stream (SSE) gets a write timeout too, so a client that stops reading doesn't pin
  its thread forever.
- same_token compares SHA-256 digests, so its time doesn't show the token's length.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 14:36:44 +02:00
Horizon agentandClaude Opus 5.5 e415db6e71 Docs: two org owners (P28), council code owners (P35) and security managers (P36)
The council's polls are applied: rdbtCVS is the second organisation owner,
the council team holds CODEOWNERS and the security-manager role. The pages
that said Ludovic alone held these powers now say who does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:35:38 +01:00
KBroneZandClaude Opus 5.5 87d97ec860 test: keep the random tick order test beside block_ticks (game.rs may not grow)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:27:42 +02:00
KBroneZandClaude Opus 5.5 7117330d80 fix: random tick chunks in position order, not chunk load order
tick_blocks built the random-tick list from the world map's keys, an
FxHashMap filled as the streaming workers finish, so two runs of one world
random-ticked their chunks in different orders and the level random's draws
landed on different blocks. Game::random_tick_chunks now sorts the list by
chunk position. Vanilla walks its simulation tracker's fastutil table, whose
slot order follows that table's history; position order is deterministic.

Fixes #15164

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:19:06 +02:00
AkirabaneandClaude Opus 5.5 77303a4d58 anticheat_e2e: prediction-water plays kelp, a waterfall, a changing current and waterlogged blocks
#5879 lists these as the unknown blocks around the water flags of the official server. water_play now
builds each one beside the player (the server only fills loaded chunks), checks through the client that
the blocks are there as built, and plays in them: sprint-swimming down and up a kelp forest and holding
jump at its surface; jump held at a waterfall's foot, walking into it across the water it spreads,
sinking down it from the top, and standing at its foot while it stops and starts again; standing and
walking in a channel whose source goes and comes back; standing on waterlogged slabs, walking into
waterlogged fences and up waterlogged stairs.

The check's client renders offscreen when HORIZON_E2E_HEADLESS is set, as agent_control_e2e.py does,
so a run on a desktop opens no window that takes the focus.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:17:06 +01:00
yahya-nusseibehandClaude Opus 5.5 7da7209026 Server: players can't forge the game's log lines or flood the log
- The supervisor matched "Stopping server" and "Done (" anywhere in a stdout line, so chat
  saying "/INFO]: Stopping server" told management clients the server was stopping and hid the
  real notice. It now looks at the message after the first "/INFO]: " only.
- A quiet-commands payload's mod id went unescaped into the dedicated server's stdout and log:
  a newline in it forged whole lines. decode now refuses control characters, DEL and the
  section sign in the mod id and every line, as a chat command must pass.
- An empty batch (3 bytes) was queued and logged as a summary line, before any permission check,
  hundreds of times a tick; it is now ignored, a batch with no room is counted on the player's
  last waiting one, and a refused payload is logged once per connection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 14:14:04 +02:00
SenjinandClaude Opus 5.5 57ffe914c0 Cracks keep their size with Improved Transparency and a pack's own destroy stages
With Improved Transparency the cracks draw vanilla's destroy_oit_stage_* sprites, but the
crumbling shaders took their size from destroy_stage_0. A resource pack that replaces only the
plain stages at a higher resolution made the crack window larger than its sprite, so it showed
neighbouring atlas sprites (#11164). crumbling_sprite now reads the set the cracks draw.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 13:03:54 +01:00
yahya-nusseibehandClaude Opus 5.5 c72e912d73 Port-pack: report odd worldgen JSON instead of panicking, and end a panicking modpack step
serde_json's index panics on a Map missing the key and on a non-object Value: a density
function "spline" without its "spline" field, a template pool whose elements aren't objects, or
a structure whose horizon:piece_limited isn't an object panicked the port. In the launcher that
killed pack_job's thread before PackDone, so the Modpacks page stayed busy until a restart.

Those reads now use get/get_mut and skip what isn't there, and pack_job turns a panic in a step
into an error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:55:10 +02:00
rdbtCVSandGPT 6.1 Sol 4cb7f5a348 Merge main into vehicle-below-world, preserving the moved cart lookup
Keep main's minecart index/display extraction and expose cart_at to the below-world discard helper. Vehicle discard behavior is unchanged.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 11:53:09 +00:00
yahya-nusseibehandClaude Opus 5.5 9a384a124b Friends: bound router answers, and keep a bad one from crashing or freezing the game
- dechunk sliced the device's chunk size into a from_utf8_lossy string: a chunk ending inside a
  character panicked the sharing thread, under the reach lock on renewal, and the poisoned lock
  then crashed the game at Host::stop. It now stops at such a chunk, and stop() and the renewal
  loop take the lock even when poisoned.
- A router's HTTP answer has one 10 s deadline (each read was limited, not the answer), SSDP
  discovery tries at most 8 gateways, and the mapping is renewed outside the reach lock, so
  stopping sharing no longer waits on a slow device.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:50:34 +02:00
yahya-nusseibehandClaude Opus 5.5 ccf20df11d Launcher: save accounts.json atomically and merge what a launch renewed
Play loads accounts.json, asks the services about each account (several requests, 20 s
timeouts), then saved that whole old copy without the lock: a sign-in finished meanwhile was
dropped (its secrets orphaned in the keychain) and a sign-out came back. save_to also wrote in
place, so a crash or full disk mid-write left a file read as no accounts.

save_to now writes a new file and renames it over the old one, and the launch paths save with
save_renewed: under the accounts' lock, the renewed names and skins go into accounts.json as it
is now, keeping accounts added or removed since.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:47:42 +02:00
Loïc PILLERandClaude Fable 5.2 bbdbf1a285 Realms: the availability check vanilla makes before use (#9432)
RealmsAvailability: GET mco/client/compatible, then GET mco/available for
a compatible client, once per account and shared by every caller. Nothing
consumes it yet: the Realms screen's gate and its refusal screens follow.

- realms/client.rs: client_compatible, has_parental_consent, and
  RealmsError::message (vanilla's errorMessage, split out of text()).
- realms/availability.rs: Availability, Pending, AvailabilityCache, get,
  current. Non-blocking; only an unexpected error is checked again.
- docs/realms-availability.md: how a screen consumes it (#14986).
- realms.rs: the module line, and a stale ResetKind comment made one line
  so the file does not grow.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 12:39:13 +01:00
yahya-nusseibehandClaude Opus 5.5 63f703ccb8 Server: a --system unit runs as the account that ran sudo, never root
`sudo horizon-server service install --system`, as the help says to run it, wrote `User=root`:
sudo resets USER to root, so the network-facing server (game port, RCON, management API, panel)
ran as root and left root-owned files in the operator's folder. The unit now runs as SUDO_USER,
else USER, and refuses to be written for root (from a root shell).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:36:49 +02:00
yahya-nusseibehandClaude Opus 5.5 06d1d236bb Server: write server.toml atomically under one lock, and keep the world if a restore fails
- server.toml was read, changed and written in place with no lock by management clients, the
  API, the CLI and sync_back: two overlapping writes dropped one change, and a crash after the
  truncate left an empty file, which reads as every default and was then written into
  server.properties. Writers in the process now hold one lock, and server.toml and
  server.properties are written to a temporary file renamed over the old one.
- A whole-world restore whose last rename failed returned with the world moved aside and no
  world in its place, and the game then made a new one. The old world is now moved back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:34:33 +02:00
yahya-nusseibehandClaude Opus 5.5 c8370400c6 Supervisor: apply queued restores and updates before every start
- A restore or update asked for while the game was stopped (or while it was already
  stopping) was only consumed on Exit::Restart, so the game started on the current world and
  the request waited for some later, unrelated restart, and a stuck update kept every later
  one refused. Both are now applied at the head of the loop, before every start.
- An update timeout is clamped to a day (API, supervisor) and refused past it by the CLI:
  Instant + a huge Duration panicked the supervisor after it had switched releases.
- A repeated stop from the API or the management protocol no longer kills the game while it
  saves; only a second signal from a person does, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:31:24 +02:00
yahya-nusseibehandClaude Opus 5.5 289aba5aa5 Cap management and API connections, and give a request one deadline
The management server spawned a thread for every connection with no cap, and read the
upgrade request before authentication with only a 10 s timeout per read, so a byte every few
seconds held a connection forever, and a 1 MiB Content-Length was allocated up front. An
unauthenticated client could open thousands.

http::read_request now has one deadline for the whole request (REQUEST_DEADLINE, 10 s), grows
the body as it arrives, and both the management listener and http::serve hold at most
MAX_OPEN (64) connections at once through a Slot given back on drop; past it a new connection
is closed unanswered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:22:14 +02:00
MSedgeMC aa8769a5ac port_map: AbstractScrollArea.extractScrollbar's cursor requests 2026-11-11 11:17:57 +00:00
MSedgeMC 84c2f81616 test: the pack scrollbar asks for the hand, then the resize cursor
Over the bar the cursor is PointingHand; with the bar held it is ResizeNs.
2026-11-11 11:17:57 +00:00
yahya-nusseibehandClaude Opus 5.5 e559d499fb Relay: keep real codes joinable and registrations bounded per site
- The relay-wide unknown-code budget now refuses only joins whose code turns out unknown:
  a handful of /24s or /48s could keep it empty and every guest with a real code got
  RateLimited. Per-address and per-site budgets are still checked before the lookup.
- Behind the PROXY protocol, a connection from outside RELAY_PROXY_FROM is closed before
  anything is read, as the docs say, instead of holding a slot for first_line.
- Registrations get a per-site budget (IPv4 /24, IPv6 /48; 30 a minute, burst 10) on top of
  the per-/64 one, and ended nameplates expire oldest first from a queue instead of a scan of
  the whole map under the global lock on every registration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 13:17:55 +02:00
MSedgeMC 90562aede1 fix: the pack list's scrollbar asks for its cursor
AbstractScrollArea.extractScrollbar requests POINTING_HAND over a scrollable
bar and RESIZE_NS while it is held. The pack screen drew its scroller without
asking, so the pointer stayed an arrow over both lists. The draw now requests
the hand or the resize cursor from the held state it already tracks.
2026-11-11 11:17:37 +00:00
DUzzL 54ef9e095a Enderman: require the carried block to survive when placing it; play the stare sound from synced data 2026-11-11 12:02:27 +01:00
MSedgeMC f852a2d582 port_map: the drowning conversion has rows
`Zombie.isUnderWaterConverting` and the `ConversionTracker` it drives had no
row, nor did the two husk overrides that send the conversion to a zombie; the
behaviour is `undead.rs::custom_server_ai_step`, and the row cites it for
each method the jar declares there.

Names read from `javap -p` on 26.3: `Zombie.isUnderWaterConverting`,
`Zombie.convertsInWater`, `Zombie.convertsToWhenDrowning`,
`Zombie.getConversionSound`, `ConversionTracker.tick`, `Husk.convertsInWater`,
`Husk.convertsToWhenDrowning`, `Husk.getConversionSound` and
`ZombieVillager.convertsInWater` (false in the jar, so it is not part of the
arm).

`map-check`: 165 rows, no problems.
2026-11-11 10:44:44 +00:00
MSedgeMC 7f625eeb61 test: a chunk without a position loads at the origin
Without the change `ChunkData::new` answers
`Err(InvalidData, "chunk is missing xPos")` for the first case.
2026-11-11 10:44:35 +00:00
MSedgeMC bc01321fa4 fix: a chunk without xPos/zPos is the chunk at 0, 0
`SerializableChunkData.parse` builds the position with `getIntOr("xPos", 0)`
and `getIntOr("zPos", 0)`, so a chunk that does not carry either tag is the
chunk at 0, 0 and `Tag.asInt` accepts the narrower integer tags as well as
`Int`. `ChunkData::new` refused the whole chunk, so an edited or hand-written
chunk without them could not be opened at all.
2026-11-11 10:44:35 +00:00
MSedgeMC 4c68279066 port_map: Font.PreparedTextBuilder.markBackground's glyph box 2026-11-11 10:35:27 +00:00
MSedgeMC 424af5fc17 test: the backdrop frames the glyphs by one pixel
The fill is (x - 1, y - 1) to (x + w, y + 9): one above and left, the advance
right, nine down.
2026-11-11 10:35:27 +00:00
TheGTandOpenCode 7d2ecff35c Shader packs: a buffer object can start with the bytes of a file
The documented `bufferObject.<n> = <size> <file>` form was refused:
the loader read the value as a size and nothing else, so a pack with
`bufferObject.2 = 16 data/seed.bin` lost its buffer with the note
"not a buffer object".

The loader now reads that form: the file's bytes come from the pack,
relative to `shaders`, and the buffer starts with them. A file that is
not there, that leaves the pack, or that is bigger than the buffer it
fills is refused with a note, as the other pack properties are.

Co-Authored-By: OpenCode <[email protected]>
2026-11-11 10:35:09 +00:00
MSedgeMC e4920df1c1 fix: a text backdrop frames the glyphs by one pixel
Font.PreparedTextBuilder.markBackground reaches one pixel left of the first
glyph and one above it, the glyph advance to the right and nine pixels down.
Horizon drew two pixels on every side (right and bottom included), so every
HUD title, action bar, boss bar and selected-item backdrop was a couple of
pixels too large. The fill now matches the glyph box.
2026-11-11 10:35:07 +00:00
MSedgeMC 47312851b0 test: a damaged or cut-off chunk reads as absent
Without the change the four length cases fail with `Err(InvalidData, "invalid
chunk payload length")` and the cut-off case with `Err(UnexpectedEof, "failed
to fill whole buffer")`.
2026-11-11 10:25:19 +00:00
MSedgeMC f48c714adc fix: a chunk the region file cannot deliver is absent, not an error
`RegionFile.getChunkDataInputStream` answers `null` whenever the file cannot
hand over the chunk: a header cut off by the end of the file ("Chunk header is
truncated"), a declared length of 0 ("allocated, but stream is missing"), a
length past the chunk's sectors ("stream is truncated") or a payload shorter
than its own header. Horizon returned an `Err` for all four, so a reader that
walks a region gave up on the whole file instead of skipping the chunk.
2026-11-11 10:25:19 +00:00
MSedgeMC 6be3db13d7 port_map: the convertCommon row says which path copies absorption
The gap note said absorption is never copied; the SINGLE path now does.
2026-11-11 10:25:11 +00:00
MSedgeMC e3e8b4c973 test: a zombie's absorption crosses into its drowned
A zombie at 3.0 absorption converts through `single` into a drowned: the new
mob reads 3.0. Without the copy the new mob has 0.0, the effect having been
copied but not the field the effect filled.
2026-11-11 10:25:11 +00:00
MSedgeMC f3946c6bbb fix: a converting mob keeps its absorption
`ConversionType.convertCommon` copies the effects, then
`to.setAbsorptionAmount(from.getAbsorptionAmount())` - the golden hearts an
absorption effect left on the mob are a plain field, and the effect copy does
not rebuild them.

`conversion::single` copied the effects but never the field, so a zombie with
three absorption hearts that turned into a drowned came out with none.
2026-11-11 10:16:19 +00:00
masa-masa-0314andZCode 08095e81cb refactor(friends): separate account-social models and parsing
Move the existing DTOs and response parsing into a private model module,
retaining public social paths and the existing parsing tests. Keep wire
and presence helpers visible only inside the social module tree.

Document the small pure-move preparation sequence, including a mandatory
manager module and a vanilla audit gate after all structural steps.
No cache, scheduling, action or UI behavior changes are included.

Fixes #15179

Co-Authored-By: ZCode <[email protected]>
2026-11-11 18:16:07 +08:00
rdbt b880384691 Merge pull request #15161 from horizon-rust/fix/parity-revert-13953 2026-11-11 10:00:11 +00:00
TheGTandOpenCode 3993570cb3 tests: the two CI scripts that had no test
tools/ci/legacy_releases.py writes the pinned SHA-256s of the releases
published before signing began, and tools/ci/resolve_reviewer_ids.py
fills in the numeric GitHub IDs the comment commands decide by. Twelve
of their thirteen siblings under tools/ci/ have a test; these two did
not, although both are pure functions over what GitHub returns.

Co-Authored-By: OpenCode <[email protected]>
2026-11-11 09:58:06 +00:00
12498072b0 Fix milk pitch and shear vibrations for farm animals
Milking a cow, goat or mooshroom plays at pitch 1.0 with no level-random draw, as AbstractCow.mobInteract, Goat.mobInteract and MushroomCow.mobInteract do.

Shearing a sheep or mooshroom by hand now posts GameEvent.SHEAR with the player, as Sheep.mobInteract and MushroomCow.mobInteract do.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 10:57:36 +01:00
TheGTandOpenCode 5ee4540940 tools: port_ledger.py reads the pinned version from the lock file
Its two version lookups fell back to a literal "26.3" when the lock
file was missing or had no version, so a version bump that touched
only research-lock.json left the ledger looking in the wrong folder.
tools/lab.py already reads the pinned version from there; the
fallback now uses it.

Co-Authored-By: OpenCode <[email protected]>
2026-11-11 09:56:38 +00:00
TheGTandOpenCode 8a1de3ebdb tools: roadmap.py's help says the Python tests run its checks, not CI
Its help marked "build --check" and "check --offline" as (CI), but no
workflow runs them: CI runs tests/test_roadmap.py, which checks the same
two things (the generated files match the toml, and the file keeps its
rules). The help pointed contributors at a command CI never runs.

Co-Authored-By: OpenCode <[email protected]>
2026-11-11 09:55:08 +00:00
TheGTandOpenCode e690aec116 tools: a flag is not a directory or a folder
Three tools took their first argument as a path to write into or
download into, so "--help" created ./--help: the pad glyphs wrote
14 PNGs into it, and fetch_dxc.py downloaded Microsoft's 22 MB archive
into it. runner_pause.py, a watcher the service runs with no
arguments, started watching whatever it was given and then crashed on
a folder that was not there yet.

They print their usage and exit instead, and the shared dev-tool test
covers the two that write.

Co-Authored-By: OpenCode <[email protected]>
2026-11-11 09:53:34 +00:00
MSedgeMC 9823bf6c48 port_map: Tooltip attribute modifiers come from the stack 2026-11-11 09:52:00 +00:00
MSedgeMC 47f735a888 test: Tooltip attribute modifiers come from the stack 2026-11-11 09:52:00 +00:00
MSedgeMC 30ae132596 fix: Tooltip attribute modifiers come from the stack 2026-11-11 09:52:00 +00:00
Ludovic Marie 77a34310b0 Merge pull request #15159 from horizon-rust/governance/codeowners-council
🤖 Agent: CODEOWNERS moves from @ludovic111 to @horizon-rust/council, as the council decided (P35); the team exists with the six members and write access; reviewer tests pass. Paths guarded by /nightly are unchanged.
2026-11-11 10:39:41 +01:00
umcekoandClaude Opus 5.5 0cec8f447b Merge main into dims/render-facts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 12:25:08 +03:00
Horizon agentandClaude Opus 5.5 7627df18b0 CODEOWNERS: the council team reviews release paths (P35)
The council decided (P35, 2026-11-10) that code-owner reviews move from the
founder to a GitHub team of the six council members. The team
horizon-rust/council exists and has write access, which code owners need.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 10:17:07 +01:00
MSedgeMC e559e8646f port_map: ClientBundleTooltip's empty description height 2026-11-11 09:11:14 +00:00
MSedgeMC c48801cb57 test: an empty bundle's height follows its description lines
Three wrapped lines reserve 3 * 9 + 13 + 8 pixels and put the bar at 3 * 9 +
4, not the fixed two-line height.
2026-11-11 09:11:14 +00:00
MSedgeMC 200a255241 fix: an empty bundle's tooltip is as tall as its description
ClientBundleTooltip.getEmptyBundleBackgroundHeight is
getEmptyBundleDescriptionTextHeight(font) + 13 + 8, and that height is
font.split(BUNDLE_EMPTY_DESCRIPTION, 96).size() * 9: the description's wrapped
line count at one decimal. Horizon hardcoded two lines (18), so a translation
whose description wraps to three lines drew the progress bar and the box's
bottom two pixels too high.

tooltip_layout and bundle_tooltip take the line count; the tooltip's probe and
draw compute it from the same font and 96 pixel width the description is drawn
at. SmithingScreen's slot icons moved to game/smithing_icons.rs so the
3,000-line stations.rs does not grow.
2026-11-11 09:10:51 +00:00
MSedgeMC 0f6a5b1b58 port_map: ServerData.validateIcon's 1024 limit 2026-11-11 09:06:59 +00:00
MSedgeMC e9c6b85aa8 test: an icon up to 1024 square is kept
64, 128 and 1024 pixel PNGs are kept (128 and 1024 would fail the old
64x64-only gate); 1025 and a non-PNG are not.
2026-11-11 09:06:59 +00:00
MSedgeMC c01e5ea7bd fix: a server icon is kept up to 1024x1024, not only 64x64
ServerData.validateIcon keeps any PNG whose width and height are at most 1024
(MAX_ICON_SIZE); FaviconTexture.upload still needs exactly 64x64 to draw one.
Horizon used icon_pixels (64x64 only) as the gate too, so a server whose
favicon was, say, 128x128 had its icon dropped from servers.dat and never
saved on join. valid_icon now answers the save question, and icon_pixels keeps
answering the draw one.
2026-11-11 09:06:37 +00:00
Horizon agent ee66246131 Merge remote-tracking branch 'origin/main' into fix/parity-revert-13953
# Conflicts:
#	tools/parity_hosts.json
2026-11-11 10:06:20 +01:00
Horizon agentandClaude Opus 5.5 766a5d4c87 Parity: container_screen's oracle skips the first release; stand_lodestone is named-only
container_screen: the oracle makes its screens with Unsafe.allocateInstance,
which skips AbstractContainerScreen's constructor and so its
`skipNextRelease = true`. #13723 made Horizon's Clicks start that way,
as the real screen does, and the oracle then disagreed on every case
whose first event is a release (373 cases). The oracle now sets the
field the constructor would.

stand_lodestone needs --work-dir, a frozen Java run (--reference-dir)
and a built game (--binary), which an automatic run never passes, so it
failed in 0 s on every runner. It joins the other capture-preserving
harnesses in parity_hosts.json's named_only: it runs when named, and
in the nightly audit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 10:06:01 +01:00
MSedgeMC b29c0cc050 port_map: AbstractSliderButton.handleCursor's resize cursor 2026-11-11 09:05:21 +00:00
MSedgeMC a10e37401c test: a dragged slider asks for the horizontal resize cursor
Not hovered asks nothing; dragged resizes; hovered at rest points; inactive is
not allowed.
2026-11-11 09:05:21 +00:00
MSedgeMC 8943e13768 fix: a dragged slider shows the horizontal resize cursor
AbstractSliderButton.handleCursor asks for RESIZE_EW while dragging,
POINTING_HAND when hovered and NOT_ALLOWED when inactive. Horizon's
widget_cursor only knew the hand and the forbidden sign, so the shell's
sliders (their held state already known in RowView) never asked for the resize
cursor. widgets::slider_cursor adds it, the shell's slider rows call it, and
the client maps Cursor::ResizeEw to EwResize.
2026-11-11 09:05:00 +00:00
tarzinio eb56315c76 Cap the occlusion edit queue when cave culling is off
Fixes #15152
2026-11-11 09:50:20 +01:00
MSedgeMC 5add9e31c0 refactor: the wheel module declares itself after mod shell_pages
The #[path] mod wheel block sat right after pub use Opt, the anchor the
widgets PR uses. It now sits after mod shell_pages, and its test moved into
the module's own #[cfg(test)] mod tests instead of appending to
options_ui_graphics_tests.rs, so the three siblings touch disjoint lines. No
behaviour changes.
2026-11-11 08:45:48 +00:00
MSedgeMC d77a09e09f refactor: the preset module declares itself by mod graphics_tests
The #[path] mod preset block sat before use crate::{, the same anchor the
widgets and wheel PRs use. It and its pub(crate) use now sit just above the
test modules at the end of the file, and the preset test moved into the
module's own #[cfg(test)] mod tests, so it no longer appends to
options_ui_graphics_tests.rs either. No behaviour changes.
2026-11-11 08:38:35 +00:00
MSedgeMC 12782bd26c port_map: Options.chatDelay's message and slider 2026-11-11 08:29:08 +00:00
MSedgeMC 28c51ac694 test: the Chat Delay row says its delay
Default reads None; 2.0 and 6.0 seconds read the delay message with one
decimal; back to zero reads None. The slider test from the previous commit
still pins the tenths.
2026-11-11 08:29:08 +00:00
MSedgeMC 3df28380e8 fix: the Chat Delay row shows its delay
Options.chatDelay's message is options.chat.delay_none at zero and
options.chat.delay with the delay to one decimal otherwise (both label and
value_text). This folds the message half of #15068 into this PR, so one change
covers the control: the IntRange(0, 60) slider from the previous commits and
the message here.

For merge hygiene the new values module sits above mod shell_pages (not after
pub use Opt) and the ChatDelay arms lead their matches (not after the wheel
sensitivity arm), so the wheel-sensitivity PR's hunks do not touch these lines.
2026-11-11 08:29:08 +00:00
MSedgeMC 00c3584214 port_map: OptionInstance.IntRangeBase.toSliderValue and the Chat Delay tenths 2026-11-11 08:12:38 +00:00
MSedgeMC f288262d66 test: the Chat Delay slider runs from 0 to 6 seconds in tenths
0.0, 3.0 and 6.0 sit at 0, 1/2 and 1 of the track (a stored 6.5 clamps), the
slider has 60 steps, and set_slider stores 0.0, 3.0 and 6.0.
2026-11-11 08:12:38 +00:00
MSedgeMC 5a75c90dbc fix: the Chat Delay control is a working slider
Options.chatDelay is IntRange(0, 60) xmap(v -> v / 10.0, v -> v * 10, true),
a slider from 0 to 6 seconds in tenths: toSliderValue is (tenths / 60) and
fromSliderValue is floor(map(v, 0, 1, 0, 61)) / 10. Horizon had no kind or
set_slider arm for it, so the Accessibility row drew a button whose click
changed nothing. The value labels (generic, on_off, chat_px) moved to
options_ui_values.rs with the mapping so options_ui.rs does not grow.
2026-11-11 08:12:38 +00:00
MSedgeMC 8918f22af2 port_map: TheEndGatewayBlockEntity.portalTick marks the chunk
The server ticker's age change is a `setChanged`.
2026-11-11 08:10:12 +00:00
MSedgeMC c8f98e4a8c test: an ageing end gateway marks the chunk
`a_gateway_that_ages_marks_the_chunk` ticks a gateway one server tick: the
age reads 1 and its chunk is in `world.modified`. Without the mark the
chunk stays clean.
2026-11-11 08:10:05 +00:00
MSedgeMC 1e12fc40bc fix: an end gateway's ageing marks the chunk
`TheEndGatewayBlockEntity.portalTick` ages the block entity and ends with
`setChanged`, so the age the beam and the chunk save read is saved.

Horizon's `tick_end_gateway` copied the server age onto the block entity
but never marked the chunk.
2026-11-11 08:09:43 +00:00
MSedgeMC 0779ef7099 port_map: Options.mouseWheelSensitivity's logarithmic slider 2026-11-11 08:07:20 +00:00
MSedgeMC f6850ed4a5 test: the mouse wheel sensitivity slider steps by 10^(i/100)
The default 1.0 sits two thirds along, 0.01 and 10.0 at the ends, a third of
the way is 0.1, and the value setter goes through the same mapping.
2026-11-11 08:07:20 +00:00
MSedgeMC ec1ab4c1a9 fix: the mouse wheel sensitivity slider is logarithmic
Options.mouseWheelSensitivity is an IntRange(-200, 100) through
logMouse/unlogMouse: the value is 10^(i/100), so the slider's handle sits at
(i + 200) / 300 and a drag picks the step by floor(map(v, 0, 1, -200, 101)).
Horizon used a straight line from 0.01 to 10.0, which put the default 1.0 at
0.099 of the track and made every drag pick a different sensitivity.
2026-11-11 08:07:16 +00:00
TheGTandOpenCode 26c04d14c3 Entity.saveWithoutId writes the live PortalCooldown, not the loaded one
A mob, an item and a vehicle kept the PortalCooldown they were loaded
with, so their countdown never showed in a save or in /data get entity.
The portal state ticks the countdown down every tick, as
Entity.processPortalCooldown does; the save now takes it from there, as
the projectile writer already did.

Fixes #14539

Co-Authored-By: OpenCode <[email protected]>
2026-11-11 07:59:37 +00:00
TheGT 78ca3e6736 Merge remote-tracking branch 'origin/main' into tools/generate-lan-command-order-help 2026-11-11 07:37:31 +00:00
TheGT 1d59235bc6 Merge remote-tracking branch 'origin/main' into tools/anvil-dump-help 2026-11-11 07:34:40 +00:00
TheGT ffd67ee750 Merge remote-tracking branch 'origin/main' into ci/run-cargo-with-locked 2026-11-11 07:33:14 +00:00
TheGT ef207822ad Merge remote-tracking branch 'origin/main' into docs/prerequisites 2026-11-11 07:31:49 +00:00
TheGT 7faa273f45 Merge remote-tracking branch 'origin/main' into tools/lang-coverage-show-keys
# Conflicts:
#	tools/lang_coverage.py
2026-11-11 07:30:11 +00:00
Vinícius MoreiraandClaude Opus 5.5 a6deb3e7de Polytone: exclusion_radius sees only particles already in the world
Measured on the mod: two particles of a type with exclusion_radius 2,
spawned a block apart in the same tick, both show, with or without
physics; one born inside a block (dropped) keeps no clear one from
spawning beside it. Horizon also counted the pending particles of the
tick, so the second was refused. The check now looks only at those that
joined; a later tick's spawn near them is still excluded.

Part of #11486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 04:06:29 -03:00
qaesen 63976a33d7 hud: add progressive downscaling fallback for oversized server packs (fixes #8570) 2026-11-11 07:48:51 +01:00
Vinícius MoreiraandClaude Opus 5.5 aed6fcaad9 Polytone: a particle that never joins takes no place under its type's limit
Measured on the mod: with limit 1, one particle with physics born inside a
block and one clear of it in the same tick, the clear one shows. Horizon
counted the pending one, which is dropped only when it joins, so the clear
one was refused and nothing showed. A pending particle with physics now
counts only once it joins: the limit is checked again at the join, after
the drop.

Part of #11486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 03:43:40 -03:00
MSedgeMC f09967622c port_map: AbstractThrownPotion.douseFire carries the owner's source
The campfire's block-change event is posted from the potion's owner.
2026-11-11 05:19:53 +00:00
MSedgeMC f561a0f625 test: a doused campfire posts block_change from the potion owner
`a_doused_campfire_posts_block_change_from_the_potion_owner` puts a lit
campfire at (2, 4, 3) and douses it with a mob owner: the block reads
unlit and the posted events hold
`("minecraft:block_change", [2.5, 4.5, 3.5], Some(Who::Mob(7)))`.
With no source passed the event's source is None.
2026-11-11 05:19:53 +00:00
MSedgeMC d0321de02b fix: a doused campfire's block_change carries the potion's owner
`AbstractThrownPotion.douseFire` passes `getOwner()` to
`CampfireBlock.douse(entity, level, pos, state)`, which calls
`level.gameEvent(entity, GameEvent.BLOCK_CHANGE, pos)`: the sculk sensor
hears the campfire go out from the potion's owner (possibly no owner at
all).

Horizon's `potion_hit_block`/`douse_fire` posted the event with no
source; the candle path stays sourceless, as vanilla's
`AbstractCandleBlock.extinguish(null, ...)` is.
2026-11-11 05:19:53 +00:00
readerkid 9fc6f9d529 Make the io_pool kick test say which packet is which, not which goes first
The packet queued with `served.send` and the one the probe sends from
`Session::tick` are framed by different paths: `Conn::serve` takes the first
from the outbox, `Conn::sweep` frames the second straight into `out`. Whichever
the worker thread reaches first is written first, and the sweep is on a timer,
so a CI run took the probe's packet (id 33) before the queued one and the test's
two `assert_eq!`s failed. The order is common, but not something the pool
promises.

The test now takes both packets and tells them apart, then checks what it is
about: the kick goes after the queued packet, `kicked` is reported, the
connection closes, and nothing follows the kick. The kick is still sent only
after both packets arrived, so that part stays ordered.

Fixes #14660

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-11-10 21:14:32 -08:00
MSedgeMC 1a2d9072d6 port_map: CrafterBlockEntity.setSlotState marks the chunk
The menu's slot state write-back lands on the block entity and marks it.
2026-11-11 05:03:37 +00:00
MSedgeMC e01e03f4db test: a slot toggled in the menu marks the crafter's chunk
`a_slot_toggled_in_the_menu_lands_on_the_crafter` opens a crafter with
slot 3 disabled, clicks it with an empty hand and checks the block
entity: the slot is enabled and the chunk is marked. Without the mark the
click leaves `world.modified` empty.
2026-11-11 05:03:37 +00:00
MSedgeMC efd000579d fix: a crafter's slot state write marks the chunk
`CrafterBlockEntity.setSlotState` ends with `setChanged`, which is what
saves a toggled slot. Horizon applied the menu's slot states to the block
entity on every click (`menu_click`'s write-back) but never marked the
chunk, so a disabled slot could be lost on save.

The write-back is now `Game::apply_crafter_slot_states`: it copies the
menu's flags, and when one changed calls `container_changed` (the
container-marking path, which also re-reads comparators).
2026-11-11 05:03:37 +00:00
MSedgeMC 0340e90e89 port_map: CampfireBlockEntity.markUpdated is covered on both paths
Placing food marks the block entity (chunk modified, clients synced) and
a moved cooking timer marks it in the tick; the row kept the old gap.
2026-11-11 05:02:08 +00:00
MSedgeMC f4c4b3c8bd port_map: SelectWorldScreen's button states are modelled 2026-11-11 05:00:30 +00:00
MSedgeMC 126a017432 port_map: the Language page draws the accuracy warning 2026-11-11 05:00:28 +00:00
MSedgeMC cf44da6903 port_map: DirectJoinServerScreen's Join button state and initial focus 2026-11-11 05:00:26 +00:00
MSedgeMC 9c99f95069 Merge remote-tracking branch 'upstream/main' into fix/reset-keys-active 2026-11-11 04:54:10 +00:00
TheGTandOpenCode f2708c690f docs: the agents map says what lang_coverage.py --summary prints
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:52:56 +00:00
yahya-nusseibehandClaude Opus 5.5 62f7e8ef03 Bound legacy smithing-trim previews from old servers
A 1.20.2-1.21.4 server's smithing-trim display (or trim recipe) is expanded into one
SmithingTrim per pattern, each with its own copy of the base and material displays. Those
can themselves be trim displays, so a few hundred bytes asked for billions of nodes.

Refuse a preview whose patterns x (base + material weight) exceeds MAX_TRIM_PREVIEW (4096),
counted with the new SlotDisplay::weight, both in SlotDisplay::read (1.21.2-1.21.4) and in
the 1.21.1 trim recipe translation; the 1.21.1 path also builds each display once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 06:51:11 +02:00
Vinícius MoreiraandClaude Opus 5.5 f5bad28164 Comparator: each doc comment above its own function
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 01:47:37 -03:00
TheGTandOpenCode 45bfbc8a5f tools: the port modules say how they are used, and the port report finds every version site
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:45:59 +00:00
yahya-nusseibehandClaude Opus 5.5 7145f30254 Commands: a server's registry names can't leak without bound
Every Commands packet becomes a dispatcher, and every resource-style
argument the vanilla tree doesn't match goes through intern(), which
Box::leaks its registry name for the life of the game. The name is the
server's, up to 32767 bytes and unchecked, so a server sending trees of
new names packet after packet leaked megabytes each time until the
client ran out of memory.

intern() now keeps only resource-location names of at most 256 bytes,
and at most 1024 of them; anything else is kept as "" (no suggestions
for that argument).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 06:45:22 +02:00
TheGTandOpenCode 071a5d1d3a tools: the velocity probe reads the protocol it announces, instead of writing 777 by hand
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:42:45 +00:00
yahya-nusseibehandClaude Opus 5.5 b689e1dfa2 Protocol text: a disconnect reason can't expand past 1 MiB
text::plain flattens a server's Disconnect component into one String,
and format_java copies an argument once per %1$s in the server's own
`fallback` template. A fallback of 16 000 "%1$s" (64 KB) whose argument
is the same construct, nested three levels (well inside the depth-32
guard), asked for about 4e12 bytes; the allocation failed and the client
aborted instead of showing the reason. The login phase's json_text, a
second copy of the same expansion, had no depth limit either.

plain, format_java and json_text now stop at MAX_TEXT (1 MiB), cut at a
character boundary (push_capped). A disconnect screen needs a few
hundred bytes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 06:40:51 +02:00
Vinícius MoreiraandClaude Opus 5.5 8204825b4e Core shaders: an array sized by its initializer only translates (#9386)
naga's GLSL front end refuses `const float[] w = float[](...)` and
`float w[] = ...`, which vanilla's GL compiler sizes from the initializer.
The size is written in, in the declarator and the constructor. Brackets
are matched in one pass and the declarator is looked for at most 256 bytes
back, so a long line stays linear.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 01:37:49 -03:00
Vinícius MoreiraandClaude Opus 5.5 680e91bdf9 Core shaders: a helper taking the sampler it reads translates (#9386)
naga's GLSL front end refuses sampler2D function parameters that vanilla's
GL compiler takes. Each such function is copied once per set of samplers
its callers pass, the copy reading those samplers by name: overloads keep
their own bodies, nested calls are rewritten inside out, prototypes become
the copies' prototypes, and copies go after their samplers' declarations
(lucasmts59's finding in review).

Pack text is untrusted. Brackets are matched in one pass and the scans for
calls have a budget, so no text freezes a load. A sampler parameter with
no name, edits that would overlap, or anything else the rewrite can't
follow leave the whole shader as the pack wrote it, for naga to refuse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 01:37:33 -03:00
TheGTandOpenCode e43c0f75dc tools: say git 2.38 or newer is required, instead of printing git's usage
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:32:53 +00:00
yahya-nusseibehandClaude Opus 5.5 7d84ad3777 Server files: the management secret comes from OS randomness, not the seed's stream
SystemEntropy is splitmix64 seeded from 8 bytes. On a first start with
no secret and no level-seed (both defaults), the 40 characters of
management-server-secret were outputs 1-40 of that stream and the world
seed was output 41; splitmix64's mixer is a bijection, so the world
seed (which ops read with /seed, and seed crackers recover from
terrain) gave back the state and every secret character. The secret is
kept when the owner later enables the management server. On Windows the
seed fell back to the clock, so the secret depended only on the start
time.

Secrets (the management secret, the TLS keystore password) now come
from OsEntropy, every draw straight from getrandom with rejection
sampling, as vanilla's SecureRandom. SystemEntropy itself is seeded
from getrandom too, the clock only if that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 06:32:18 +02:00
TheGTandOpenCode 6b855fe0c7 tools: generate_lan_command_order.py prints usage instead of running the generator on --help
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:29:43 +00:00
MSedgeMC 14bc8fbebe graphics: the automatic worker count is not always one per available processor 2026-11-11 04:29:25 +00:00
yahya-nusseibehandClaude Opus 5.5 56a25648ac horizon-server: a space in a config key can't get past the API's deny-list
PATCH /api/v1/config checked the raw JSON key with changeable_remotely,
which doesn't trim it, then applied "{key}={value}" through
parse_change, which does. A key " engine.path" (or "\tapi.allow_public",
" discord.webhook", " properties.enable-rcon") passed the deny-list and
was written to server.toml: at the next restart the API or panel opened
to the internet, chat went to another webhook, RCON came on, or the
supervisor ran another program.

changeable_remotely now refuses any key with whitespace or control
characters in it, so what it checks is what gets applied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 06:28:23 +02:00
yahya-nusseibehandClaude Opus 5.5 a2864d9edd horizon-server: a management kick reason can't inject control requests
players/kick put the management client's reason, newlines included,
into "console kick <name> <reason>", which Control::ask writes as one
line to the game's control endpoint. The endpoint reads one request per
line, so a reason of "x\nconsole op Mallory" ran a second request: any
console command, or any other control verb, which the management
protocol never offers.

The kick reason now drops control characters, and Control::ask itself
refuses a request with \n or \r before sending anything, so every caller
is covered (the API's /command also refuses \r now, as it did \n).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 06:26:10 +02:00
yahya-nusseibehandClaude Opus 5.5 5323f98c42 horizon-server: a backup always turns saving back on
A backup turned autosave off, then flushed. If the flush failed (the
control connection's 30 s reply timeout on a big world or a slow disk),
the ? returned before `console save-on` was sent, and the game kept
running with autosave off until the next backup that succeeded;
scheduled backups take this path, so a crash in that window lost
everything played since.

Once save-off has been asked, saving is now always turned back on: over
the same connection after a good backup, and over a fresh one when the
flush failed (a reply that timed out leaves the old one out of step).
The flush gets its own 300 s reply timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 06:23:41 +02:00
TheGTandOpenCode 4ffda2343e tools: lang_coverage.py no longer drops --show-keys when --summary is given
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:23:14 +00:00
TheGTandOpenCode dcddf81a20 tools: anvil_dump.py asks for its file instead of crashing on --help, and gets a test
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:20:00 +00:00
TheGTandOpenCode 70a011535b ci: run cargo with --locked so a stale Cargo.lock fails instead of being rewritten
Co-Authored-By: OpenCode <[email protected]>
2026-11-11 04:16:07 +00:00
Vinícius MoreiraandClaude Opus 5.5 c0998126c0 Core shaders: a pack's gl_VertexIndex reads the glue's vertex number
26.3 packs write gl_VertexIndex where older ones wrote gl_VertexID: both
mean vanilla's vertex number, four per quad. Only gl_VertexID read the
glue's expression, so on the text pipeline (six vertices per glyph) a
26.3 pack read the raw index. Both now read it; the glue's own code above
the pack's keeps the real index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 01:09:48 -03:00
SenjinandClaude Opus 5.5 9b006dcab6 Shader packs: one program's solid and cutout terrain draw in one pass
A pack whose one terrain program (gbuffers_terrain) draws both solid and
cutout terrain ran it twice over the solid list, each pass moving the other
part's quads off-screen: every solid-terrain vertex was shaded twice (0.6 ms a frame measured with a path-traced pack on an RTX 2080).

Now the game also gives the loader terrain's inputs for one pass
(GameInputs::terrain_one_pass, GbuffersInputs::parts): the vertex stage
works out its quad's part from the sprite layer, as before, and hands it to
the fragment stage as a flat varying, which applies that part's alpha test.
alphaTestRef becomes a per-part value in both stages (0 for solid, 0.5 for
cutout, as Iris 1.11.7 did in #9307's probes), and alphaTest.gbuffers_terrain
still replaces both parts' tests. When both tests are the same, nothing
changes in the shader. Packs with gbuffers_terrain_solid or _cutout keep
their two passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 05:09:25 +01:00
TheGTandOpenCode minimax-m3.1-flash-free 172965a9a0 docs: the prerequisites say Python 3.11+ and git 2.38+
Co-Authored-By: OpenCode minimax-m3.1-flash-free <[email protected]>
2026-11-11 04:06:30 +00:00
a54d9f825a Keep a zombie in powder snow from catching fire in daylight
Mob.isSunBurnTick (Mob.java:500-506) counts isInPowderSnow and wasInPowderSnow
as not burnable, so a mob standing in powder snow never ignites; Horizon only
tested water and rain, so a zombie in powder snow ignited in daylight and
PowderSnowBlock.entityInside (PowderSnowBlock.java:88-99) then destroyed the
block under it with mobGriefing and put it out, leaving it to burn freely.
The scan at burn time is isInPowderSnow; m.in_powder_snow, the scan baseTick
made before the mob travelled, is wasInPowderSnow.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 05:05:20 +01:00
SenjinandClaude Opus 5.5 d990e4f79c Shader pack timing: passes of one name count as their sum, compute passes apart
HORIZON_SHADER_PACK_TIMING pushed every pass's time into the window of its name, so two passes of
one name in a frame (a program drawn over several render passes, or deferred2.csh beside
deferred2.fsh) shared a window and its median was the time of neither. A frame's passes of one
name now add up to one sample, and a compute pass is timed as "<name> (compute)".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 05:00:09 +01:00
MSedgeMC d7107e8f1b Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:41 +00:00
MSedgeMC 4caa4a90c3 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:31 +00:00
MSedgeMC 8d47c940e6 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:22 +00:00
MSedgeMC 0d92a3d997 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:19 +00:00
MSedgeMC 7d6b37b8e6 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:12 +00:00
MSedgeMC 451fb4ebd9 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:09 +00:00
MSedgeMC 6895c1dcc1 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:07 +00:00
0ce71c6934 Zombies burn you only with a bare hand, on the difficulty's chance
`Zombie.doHurtTarget` (Zombie.java:315-325) rolls `effectiveDifficulty * 0.3`
for a burn of `2 * (int)effectiveDifficulty` seconds only when
`super.doHurtTarget` landed, the main hand is empty and the zombie is on fire,
and every species that extends `Zombie` inherits it: a burning husk, drowned,
zombie villager and zombified piglin now burn too, while a zombie holding a
weapon and a blow a shield took whole no longer do. The chance is drawn in
`do_hurt_target` where vanilla draws it, in the mob's own tick, and the game
lights the burn only for the blow it rides.

The turtle egg's break sound also draws its pitch from the level random
(Zombie.java:553-555): `0.9 + level.getRandom().nextFloat() * 0.2`.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 04:42:19 +01:00
KBroneZ e7499779c8 Merge remote-tracking branch 'upstream/main' into claude/up-8688 2026-11-11 05:33:30 +02:00
KBroneZ f211a2ee96 Merge remote-tracking branch 'upstream/main' into claude/up-15039 2026-11-11 05:33:28 +02:00
KBroneZ c1503f7ada Merge remote-tracking branch 'upstream/main' into claude/up-7843 2026-11-11 05:33:13 +02:00
Nikita Maximilian GrimmandClaude Fable 5.2 4f76f9b35d Merge remote-tracking branch 'origin/main' into projectile-uuid-draws
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 04:25:26 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 619e45830a Merge remote-tracking branch 'origin/main' into parity/noai-tadpole-ages
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 04:24:07 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 bd8ae9f1ed Merge remote-tracking branch 'origin/main' into parity/ominous-spawner-loaded-rotation
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 04:23:26 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 95848131df Merge remote-tracking branch 'origin/main' into parity/sulfur-cube-bucket-health
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 04:21:24 +01:00
Vinícius MoreiraandClaude Opus 5.5 f0a379cbc1 Merge main into fix/comparator-setblock-output: main compiles again (#15038)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:57:09 -03:00
Nikita Maximilian Grimm 41a9e808e1 Merge remote-tracking branch 'origin/main' into hdr-shaders-pack-no-lift 2026-11-11 03:40:32 +01:00
rdbt 04a26210e3 Merge pull request #15038 from horizon-rust/fix/main-ci-after-bulk-merge
Fix CEM compilation and scaled mob culling bounds
2026-11-11 02:39:18 +00:00
f6af16d3ef Goats stop ramming while fed or bred, and a shield halves a ram's push
GoatAi.initRamActivity wants TEMPTING_PLAYER and BREED_TARGET absent, and
GoatAi.updateActivity picks RAM before IDLE, so a goat being fed or bred only
follows; a player who starts feeding it during the prepare also ends the
activity (PrepareRamNearestTarget.stop starts the cooldown).

RamTarget.tick runs applyItemBlocking a second time for its mobAttack push and
scales it by blockingFactor (0.5 when the victim's raised item blocked part of
the hit). The push now names the damage the hit dealt so the host can do that,
and blockingFactor * speedFactor keeps vanilla's float-then-double order.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 03:03:46 +01:00
MSedgeMC 90187f9942 port_map: KeyBindsScreen's Reset All active state 2026-11-11 02:01:31 +00:00
MSedgeMC 57bf54407a test: Reset All's active state follows the bindings
The default map has nothing to reset; moving one binding turns it on, setting
it back or reset_all turns it off.
2026-11-11 02:01:31 +00:00
MSedgeMC 5666c93e13 fix: Reset All is greyed out until a binding changes
KeyBindsScreen.extractRenderState walks the mappings and sets
resetButton.active from KeyMapping.isDefault, so the button is inactive until
some binding differs from its default. Horizon drew it active and reset every
mapping on any click.
2026-11-11 02:01:31 +00:00
MSedgeMC e6eeff4d10 port_map: SliderableEnum.fromSliderValue's floor mapping 2026-11-11 01:41:38 +00:00
MSedgeMC 811ea89472 test: the graphics preset slider's four stops
0.24, 0.25, 0.49, 0.5, 0.74, 0.75 and 1.0 pick Fast/Fancy/Fabulous/Custom by
the floor mapping, and the value setter moves the preset through them.
2026-11-11 01:41:38 +00:00
MSedgeMC 5f51a346c8 fix: the graphics preset slider uses vanilla's floor stops
OptionInstance.SliderableEnum.fromSliderValue maps a slider position by
floor(v * values.size()), with 1.0 just below, and clamps to the last value:
the four GraphicsPreset values change at 0.25, 0.5 and 0.75. Horizon rounded
v * 3, so dragging to 0.2 picked Fancy instead of Fast and 0.8 Fabulous
instead of Custom.
2026-11-11 01:41:38 +00:00
KBroneZandClaude Opus 5.5 a1bc8fc608 fix: a client plays with the server's block and item tags
The client kept only the dialog tags of ClientboundUpdateTagsPacket and
read block and item tags from the game's own files, so a data pack's or
plugin's tags (climbable, mineable, ...) never reached a player on a
server. Dynamic now keeps every registry's tags; a server session builds
the game's Items with the server's block and item tags in place of its
own (by name, through the built-in registries), and Game::items() reads
it. The play-state packet after /reload replaces them the same way
(ClientPacketListener.handleUpdateTags).

The server tables (the synced enchantments from #9301 and now the items)
move to game/remote_tables.rs, so remote.rs shrinks.

Closes #7843

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 03:39:00 +02:00
MSedgeMC 59a74c49ac port map: the citations the later splits left behind (feeding, step, section_fade, remote_removal, minecarts/nbt, Fox.SleepGoal) 2026-11-11 01:18:03 +00:00
DUzzL ee581f9834 Rabbit: start the move control in MOVE_TO towards (0, 0, 0) like the constructor's setSpeedModifier(0.0) 2026-11-11 02:12:23 +01:00
MSedgeMC 4919ef98dd Restore the weapon component test the merge dropped 2026-11-11 01:07:56 +00:00
MSedgeMC e723d9ea15 Merge main: keep weapon_damage beside weapon_disable_blocking 2026-11-11 01:07:39 +00:00
DUzzL 822fbc2af9 port-pack: read a lone placeholder mod id template instead of failing with a TOML error 2026-11-11 02:00:40 +01:00
Vinícius MoreiraandClaude Opus 5.5 9c31a83fed A comparator placed with OutputSignal by /setblock keeps it
BlockInput.place loads the tag into the comparator's block entity, and
ComparatorBlockEntity.loadAdditional reads getIntOr(OutputSignal, 0).
Horizon keeps a comparator's output beside the block entities and only
/data wrote it; /setblock and /fill now load it through the same
load_comparator_output.

Fixes #13870

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:59:37 -03:00
MSedgeMC a899c56c45 Merge main; keep both sides' rows 2026-11-11 00:59:17 +00:00
MSedgeMC cff772e57a Merge main; keep both sides' rows 2026-11-11 00:59:15 +00:00
MSedgeMC 1165a5c119 Merge main; keep both sides' rows 2026-11-11 00:59:13 +00:00
KBroneZandClaude Opus 5.5 c25d5e6d71 fix: a player's copper chest plays its own hinge sound
container_edge_sound sent every block named *chest* to block.chest.open
and close. Vanilla's ChestBlockEntity opener counter plays the block's
getOpenChestSound/getCloseChestSound, which a copper chest takes from
CopperChestBlock.getHingeSound by its weather state. The copper golem's
transport path already had that mapping; it moves to
transport_items::chest_hinge_sound and both paths use it.

Closes #15039

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 02:53:12 +02:00
MSedgeMC 59d9424230 Merge upstream/main into fix/command-block-edit-mark 2026-11-11 00:42:21 +00:00
MSedgeMC fe8bffe676 Merge remote-tracking branch 'upstream/main' into fix/vex-dead-owner-target
# Conflicts:
#	tools/port_map/game2-003.tsv
2026-11-11 00:41:48 +00:00
MSedgeMC f5541f7c45 Merge upstream/main into fix/social-search-caret 2026-11-11 00:41:23 +00:00
DUzzL 0e9f555a5b Keep a camel's saved LastPoseTick an absolute game time while it is not ticking 2026-11-11 01:20:10 +01:00
rdbtCVSandCodex f37bcae92c Scale culling margins with the mob model root
Include the root model scale in the appendage margin so animated elder guardian vertices remain inside the precheck bounds. The existing prepared-model coverage test remains unchanged.

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
2026-11-10 23:55:39 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 6e036e8918 Merge origin/main into projectile-uuid-draws
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 00:52:29 +01:00
rdbtCVSandCodex 04b53013c8 Fix CEM own-model lookup shadowing
Keep the own-file map available when selecting the layers covered by a model.

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
2026-11-10 23:45:10 +00:00
Nikita Maximilian Grimm 41e78cbe12 Merge remote-tracking branch 'origin/main' into hdr-shaders-pack-no-lift
# Conflicts:
#	docs/graphics.md
2026-11-11 00:40:08 +01:00
rdbt 5070174aef Merge pull request #14707 from masa-masa-0314/docs/friends-overlay-part2-spec
Docs: propose the Friends overlay Part 2 plan
2026-11-10 23:31:27 +00:00
rdbt 5841fdc1e7 Merge pull request #14658 from readerkid/fix/cem-armour-layers
Map CEM's armour models to the layers 26.3 draws, and the rabbit's feet
2026-11-10 23:31:23 +00:00
rdbt 2093fb4d0d Merge pull request #14627 from MrCloudy2/fix/piston-cactus-vehicles
A cactus pricks a boat or a minecart a piston pushes
2026-11-10 23:31:19 +00:00
rdbt 4e84f9e7fe Merge pull request #14623 from MrCloudy2/fix/projectile-hits-tnt
A projectile hits primed TNT
2026-11-10 23:31:14 +00:00
rdbt 6d45e61cdc Merge pull request #14621 from MrCloudy2/fix/wind-bursts-all-push
Every wind burst of a tick pushes an entity that ticks after the projectiles
2026-11-10 23:31:10 +00:00
rdbt 960c03a4a1 Merge pull request #14619 from MrCloudy2/fix/projectile-fluid-current
A flying projectile is pushed by the water and lava it touches
2026-11-10 23:31:06 +00:00
rdbt 7618cdca8e Merge pull request #14533 from MrCloudy2/fix/geyser-through-scaffolding
A geyser goes through scaffolding seen from below
2026-11-10 23:30:59 +00:00
rdbt 31c02b8f59 Merge pull request #14513 from Detimes/gap-line-of-sight
Native hooks: line of sight between entities and a clear-sight block ray
2026-11-10 23:30:55 +00:00
rdbt 67c6dfbca9 Merge pull request #14512 from Detimes/gap-riding-getters
Native hooks: read the vehicle an entity rides and its passengers
2026-11-10 23:30:51 +00:00
rdbt 7ef8abd367 Merge pull request #14510 from Detimes/gap-server-props-read
Native hooks: read the dedicated server's online mode, port and proxy forwarding
2026-11-10 23:30:47 +00:00
rdbt 63f20e8f30 Merge pull request #14498 from MrCloudy2/fix/geyser-launches-projectiles
A geyser launches projectiles, boats and minecarts
2026-11-10 23:30:42 +00:00
rdbt f25fdf5828 Merge pull request #14490 from MSedgeMC/fix/wither-side-head-los
A wither's side head does not pick targets through a wall
2026-11-10 23:30:38 +00:00
rdbt 87ef5ed8d9 Merge pull request #14484 from MrCloudy2/fix/wind-charge-hurts-vehicles
A wind charge's hit damages a boat or a minecart
2026-11-10 23:30:33 +00:00
rdbt 31e1d6aedf Merge pull request #14462 from ilguerro/fix/spilled-items-pop-up
Items spilled from a destroyed shulker box or bundle pop upward again
2026-11-10 23:30:29 +00:00
rdbt cc4067a168 Merge pull request #14441 from voduff/fix/12038-cube-body-item-replace
A sulfur cube's body takes a swallowable block through /item replace
2026-11-10 23:30:25 +00:00
umcekoandClaude Opus 5.5 a97cefe7f7 Merge main into dims/render-facts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 02:30:21 +03:00
rdbt f7c9520898 Merge pull request #14437 from J5Casey/fix/synced-recipe-display-numbers
Recipe book numbers a server's synced recipes as the server does
2026-11-10 23:30:21 +00:00
rdbt 417728114c Merge pull request #14430 from horizon-rust/split/crate-lang
Crates ship their own lang files: horizon_platform::lang (layer plan M5)
2026-11-10 23:30:17 +00:00
rdbt 1f2fd92867 Merge pull request #14402 from vnsmoreira/packs/polytone-physics-spawn
Polytone: a particle with physics born inside a block never joins
2026-11-10 23:30:13 +00:00
rdbt b955f83e5b Merge pull request #14401 from DUzzL/fix/14382-jmath-pow-nan
Fix jmath::pow NaN special cases to match Java Math.pow
2026-11-10 23:30:09 +00:00
rdbt 916dd0cebb Merge pull request #14332 from yahya-nusseibeh/fix/registry-rusqlite-0.41
Mod registry: bundle SQLite 3.54 through rusqlite 0.41
2026-11-10 23:30:04 +00:00
rdbt b4977c3700 Merge pull request #14277 from Detimes/gap-mob-death-message
Native hooks: living_death_message (mob death message)
2026-11-10 23:30:00 +00:00
rdbt 8cbfc508ae Merge pull request #14271 from Detimes/gap-entity-lookup
Native hooks: read-only entity lookup by UUID and entity data in any level
2026-11-10 23:29:55 +00:00
rdbt 1843b792ff Merge pull request #14270 from Mik00000/perf/lighting-propagation-batch
perf(light): reuse scratch queues during incremental relight and preserve lazy section loading
2026-11-10 23:29:51 +00:00
rdbt 8b6513f833 Merge pull request #14021 from MSedgeMC/fix/weapon-damage-component
Weapon wear comes from a stack's weapon component
2026-11-10 23:29:47 +00:00
rdbt 3895a99900 Merge pull request #13988 from MSedgeMC/fix/banner-layer-codec
A banner with an invalid layer loads no patterns
2026-11-10 23:29:42 +00:00
rdbt 70f3965c0a Merge pull request #13761 from TheMrZZ/fix/h194-item-count-predicate-2
Match item count equality against the actual stack
2026-11-10 23:29:38 +00:00
rdbt e51f313b02 Merge pull request #11559 from voidsipp/fix/11329-villager-reputation-events
Use cached villager murder witnesses
2026-11-10 23:29:34 +00:00
rdbt 339bda5ed2 Merge pull request #11536 from voidsipp/fix/11336-potion-contents
Expire custom potion contents on tipped arrows
2026-11-10 23:29:29 +00:00
rdbt 0cc2963ccf Merge pull request #11484 from voidsipp/fix/11318-portal-cooldowns
Keep entity-specific Nether portal cooldowns
2026-11-10 23:29:25 +00:00
rdbt 1b27a37702 Merge pull request #15009 from DUzzL/fix/14956-powder-snow-order
Mobs: tick freezing after the move and block effects
2026-11-10 23:26:54 +00:00
rdbt d4d833f199 Merge pull request #14945 from CocofireHD/fix/14857-zombie-villager-profession
A zombie villager's profession is the constructor's draw from its own random (#14857)
2026-11-10 23:26:50 +00:00
rdbt 1101314498 Merge pull request #14775 from NongTham/fix/14664-bed-explosion-flying-kick
test: allow-flight in bed_explosion parity harness (fixes #14664)
2026-11-10 23:26:46 +00:00
rdbt 68b4c07179 Merge pull request #14549 from vivescene/docs/agents-review-when-asked
AGENTS.md: review pull requests only when asked, and submit a decision
2026-11-10 23:26:42 +00:00
rdbt 395789e107 Merge pull request #14509 from Detimes/gap-map-colors-read
Native hooks: read a map's colours (native_map_colors)
2026-11-10 23:26:37 +00:00
rdbt 9223dc0e30 Merge pull request #14446 from Mayonesu0/up-12937-dispenser-equip
Dispensers equip server players and respect armor stand slot locks
2026-11-10 23:26:33 +00:00
rdbt d9fe05af0d Merge pull request #14439 from horizon-rust/split/friends-title-icon
Title screen's Friends icon is inactive without an invite-code resolver (spec #14167 step 4)
2026-11-10 23:26:29 +00:00
rdbt f02798aed5 Merge pull request #14130 from MSedgeMC/port_map/destroy-progress-and-daylight
port map: the destroy-progress stage and the daylight ticker rows are ports
2026-11-10 23:26:25 +00:00
rdbt 900933aae2 Merge pull request #13762 from TheMrZZ/fix/h211-shulker-drop-lock-2
Preserve external locks on destroyed shulker boxes
2026-11-10 23:26:21 +00:00
rdbt 2ef31a7618 Merge pull request #15014 from darkliro/perf/linux-hybrid-cores
threads: detect performance cores on Linux hybrid CPUs
2026-11-10 23:26:03 +00:00
rdbt cbf533a8ae Merge pull request #14360 from NikitaMGrimm/frame-data-count
/data on an item frame detaches its old map when only the stack's count changes
2026-11-10 23:25:53 +00:00
rdbt ccc233474d Merge pull request #13753 from glitchsnake/fix/12935-sculk-particle-resume-reload
sculk: resume vibration particle on reload (fixes #12935)
2026-11-10 23:25:25 +00:00
rdbt 1b16aaecbf Merge pull request #15027 from NikitaMGrimm/fix/hold-fullbright-replay
Main compiles again: hold_fullbright's replay check and the firework tests' new_rocket calls
2026-11-10 23:20:47 +00:00
KBroneZandClaude Opus 5.5 15dc5e301c test: keep the remote anvil test beside anvil.rs, stations.rs not growing
stations.rs is over the 3000-line limit and may not grow
(docs/layers.md#file-size): the test module hangs off stations/anvil.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 01:18:36 +02:00
Nikita Maximilian GrimmandClaude Fable 5.2 2160d3e4d1 The firework event tests pass new_rocket its random
#14603 gave new_rocket the rocket's own random as a fourth argument; the
tests added by 188817342 still called it with three, so the client's tests
stopped compiling on main.

Refs #15025

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 00:08:01 +01:00
Nikita Maximilian Grimm 4536ec51ca Merge remote-tracking branch 'origin/main' into fix/hold-fullbright-replay 2026-11-11 00:01:35 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 b02f367216 Merge origin/main into projectile-uuid-draws
dispenser.rs: main (#14603) moved the firework rocket out of the match
into launch_angled_rocket, which makes the rocket's own random. This
branch only renamed the random argument in that arm, so main's version
stays and the arm goes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:58:45 +01:00
DUzzL 29bfd0e362 Fix dispense position float order to match vanilla 2026-11-10 23:57:50 +01:00
umcekoandClaude Sonnet 5.5 d07042696f Sky, shading and ambient light follow the dimension type (#11282, 7/9)
A datapack dimension (`data/<ns>/dimension/`) gets its own `DimensionType`, and
vanilla's renderer reads the skybox, cardinal light, ambient light and
attributes from it, not from the level's key. The client's draw choices now
read the level's dimension type facts the same way.

- Cardinal light picks the diffuse lights and the section shading; the type's
  `has_skylight` picks the section sky light.
- The skybox picks the sun, moon, stars and clouds, the End sky and its flashes,
  the sun shadows and the shader sky type; the ambient light picks the entity
  shadow darkening.
- The day timeline, `water_evaporates` and `piglins_zombify` pick the firefly
  bush and creaking effects, the dripstone particle and the piglin conversion
  shake; the minimap reads the level shape's ceiling.
- `Resources::environment_of` picks the environment table by dimension type id.

For the Overworld, the Nether and the End every site returns what it did before.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 01:57:34 +03:00
Nikita Maximilian GrimmandClaude Fable 5.2 72d1238876 hold_fullbright asks the replay whether it plays
#14335 read Game::studio_replay, which the layer split had moved to
Game::replay before it merged, so main stopped compiling.

Fixes #15025

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 23:51:58 +01:00
rdbt 214469a4bf Merge pull request #14737 from ilguerro/fix/sitting-cat-blocks-comparator
Silence a chest's comparator while a cat sits on it
2026-11-10 22:51:41 +00:00
Nikita Maximilian Grimm 370af10365 Merge remote-tracking branch 'origin/main' into parity/noai-tadpole-ages
# Conflicts:
#	crates/horizon-client/src/mobs/ai.rs
#	crates/horizon-client/src/mobs/aquatic.rs
2026-11-10 23:51:39 +01:00
rdbt b2bfa61fb1 Merge pull request #14987 from DUzzL/fix/14856-shulker-armor
A shulker keeps its armor attribute once its lid has moved
2026-11-10 22:49:57 +00:00
rdbt 5f4dbb058b Merge pull request #14969 from vermingov/fix/villager-food-level-14967
A villager narrows a loaded FoodLevel to a byte (#14967)
2026-11-10 22:49:50 +00:00
rdbt 292dfe14e1 Merge pull request #14955 from DUzzL/fix/14832-zombie-villager-cure
A zombie villager starts its cure when it loads a ConversionTime
2026-11-10 22:49:45 +00:00
rdbt 506624b951 Merge pull request #14951 from Web-mc1/fix/biome-get-empty
Fix biome table panic when empty
2026-11-10 22:49:39 +00:00
rdbt e7fb465789 Merge pull request #14935 from TheMrZZ/slot-sources/holder-tag-codec
Slot sources: holder and tag codec, and slot-source tags in DataStore
2026-11-10 22:49:33 +00:00
rdbt 31af1ed8ad Merge pull request #14932 from Detimes/perf-replay-excuse
Perf: the replay excuse tests the distance before the entity kind
2026-11-10 22:49:28 +00:00
rdbt af3a8d235b Merge pull request #14928 from MSedgeMC/fix/crafter-recipe-book
port: a crafter's grid counts for the recipe book
2026-11-10 22:49:22 +00:00
rdbt 3c564f0e2b Merge pull request #14910 from oloion/fix/custom-crafting-recipes-book
client: show custom server crafting recipes in recipe book
2026-11-10 22:49:17 +00:00
rdbt 45c4e0d744 Merge pull request #14900 from MSedgeMC/fix/jukebox-block-change
port: a disc coming or going posts block_change
2026-11-10 22:49:12 +00:00
rdbt 802056c402 Merge pull request #14892 from NikitaMGrimm/shader-api-primaries-key
Shader API 0.2: [frame] primaries, and the rule for new names
2026-11-10 22:49:06 +00:00
rdbt fc604a958a Merge pull request #14785 from MSedgeMC/fix/merchant-scroller-cursor
The merchant's trade scroller shows its cursor
2026-11-10 22:49:01 +00:00
rdbt 8f98a65be5 Merge pull request #14776 from NongTham/fix/14715-modifier-key-handling
input: clear modifiers on focus loss and heal alt and super keys (fixes #14715)
2026-11-10 22:48:56 +00:00
rdbt 75dc9db341 Merge pull request #14772 from foudretbr/fix/attack-speed-attribute-modifiers
fix(game): evaluate attack_speed attribute modifiers for player attack cooldown (#14721)
2026-11-10 22:48:51 +00:00
rdbt eb161b9c99 Merge pull request #14745 from MSedgeMC/fix/feed-never-baby
A mob that cannot be a baby does not take the food that grows it
2026-11-10 22:48:44 +00:00
rdbt 7687b2a619 Merge pull request #14742 from foudretbr/fix/modifier-key-debug-shortcuts-focus-loss
fix(input): reset debug keys modifier state on window focus loss (#14715)
2026-11-10 22:48:39 +00:00
rdbt 1d50e158b9 Merge pull request #14723 from ilguerro/fix/firework-silent-explode-stat
Firework rockets: honour Silent, post EXPLODE, count block launches
2026-11-10 22:48:33 +00:00
rdbt 58b5d93f8f Merge pull request #14710 from glitchsnake/fix/14467-squid-noai-motion
mobs: apply squid sinking velocity on land under NoAI (fixes #14467)
2026-11-10 22:48:28 +00:00
rdbt 9951ef958d Merge pull request #14705 from Skr1zzzz/falling-model-cache
Falling blocks: cache each model's vertices instead of rebuilding them every frame
2026-11-10 22:48:22 +00:00
rdbt 8cb5c02d4b Merge pull request #14703 from ilguerro/fix/horses-do-not-climb
Stop horses, llamas, camels and flying monsters climbing vines and ladders
2026-11-10 22:48:17 +00:00
rdbt b75ffd9554 Merge pull request #14699 from NikitaMGrimm/hdr-pq-dither
HDR10 output: the last pass dithers its 10 bits, so a clear sky doesn't band
2026-11-10 22:48:12 +00:00
rdbt c7552a32e5 Merge pull request #14697 from ilguerro/fix/phantoms-glass-roof
Spawn phantoms under a glass roof
2026-11-10 22:48:07 +00:00
rdbt ff03932fb0 Merge pull request #14693 from ilguerro/fix/turtle-frog-lay-events
Post block_place when turtles and frogs lay eggs, and stop bred turtles bursting hearts
2026-11-10 22:48:02 +00:00
rdbt 6a007e8e02 Merge pull request #14691 from ilguerro/fix/campfire-candle-douse
Sneaking keeps the held food off campfires and candles answer pick-block
2026-11-10 22:47:57 +00:00
rdbt a4b71ca8ba Merge pull request #14689 from ilguerro/fix/shulker-teleport-vibration
Post a shulker teleport's game event for sculk sensors
2026-11-10 22:47:52 +00:00
rdbt 1386a7fd1f Merge pull request #14677 from YourPancakes/perf/skip-full-cube-shape-allocation
perf(world): avoid full-cube allocation in collision checks
2026-11-10 22:47:47 +00:00
rdbt 5f029bb260 Merge pull request #14672 from YourPancakes/perf/cache-flat-compute-bind-groups
perf(render): cache flat compute bind groups
2026-11-10 22:47:42 +00:00
KBroneZandClaude Opus 5.5 57b2669f0a fix: preview the anvil with a server's data-pack enchantments
On a server whose data pack adds an enchantment, the anvil showed the red
cross for a book of it: the client's result prediction read the world's
own enchantment table, which lacks the entry. AnvilMenu.createResult on
the client reads the synced registry, so the station previews and the menu
engine now read Game::enchantments(), the server's table in a server
session and the world's otherwise.

Closes #8688

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 00:47:40 +02:00
rdbt 23a2b65c29 Merge pull request #14667 from vnsmoreira/fix/dispensed-item-random
A dispensed item draws its constructor's motion from its own random
2026-11-10 22:47:37 +00:00
rdbt 62165d135d Merge pull request #14665 from YourPancakes/perf/sky-octagon-half-planes
perf(render): evaluate sky octagon with half-planes
2026-11-10 22:47:31 +00:00
rdbt 2732d737a1 Merge pull request #14653 from Ragbie/tests/pad-parity-actions
pad::parity_tests: the pad_press helper records the press, so four tests pass again
2026-11-10 22:47:25 +00:00
rdbt a1807b93a1 Merge pull request #14629 from Ragbie/tests/tnt-silence-stack
TNT silence tests run on an 8 MiB stack, so they don't overflow on Windows
2026-11-10 22:47:18 +00:00
rdbt 53c0b0694b Merge pull request #14602 from ilguerro/fix/sniffer-dig-vibration-silence
Keep animal_brain.rs at main's line count
2026-11-10 22:47:13 +00:00
rdbt cc3e92cadd Merge pull request #14600 from ilguerro/fix/bred-wolf-voice
Move the bred offspring's draws and their test out of creatures.rs
2026-11-10 22:47:08 +00:00
rdbt 27e0787a23 Merge pull request #14592 from NikitaMGrimm/parity/bucket-mob-from-bucket
A mob from a bucket is not persistent, a sulfur cube keeps its bucket's age, and tadpoles never despawn
2026-11-10 22:47:02 +00:00
rdbt f312c30454 Merge pull request #14585 from foudretbr/fix/cat-default-variant-black
fix(mobs): default cat variant to black when omitted
2026-11-10 22:46:57 +00:00
rdbt a79db77ac1 Merge pull request #14573 from MSedgeMC/ledger/moved-citations
port map: point citations at the modules they moved to
2026-11-10 22:46:52 +00:00
rdbt 5fde1275b5 Merge pull request #14556 from ilguerro/fix/wall-hanging-sign-click-command
Run a waxed wall hanging sign's click command instead of chaining a sign
2026-11-10 22:46:46 +00:00
rdbt 7ebdfbc3ee Merge pull request #14508 from Ragbie/tests/mob-landing-neighbourhood
mob_landing_support_tests load the chunks a pig needs to tick
2026-11-10 22:46:41 +00:00
rdbt 9e4e43a69b Merge pull request #14496 from horizon-rust/fix/service-images-path-crates
Telemetry and mod registry images copy every crate their lockfile builds
2026-11-10 22:46:35 +00:00
rdbt 78f286e657 Merge pull request #14492 from Ragbie/fix/landing-vibrations
Primed TNT and falling blocks make a vibration when they land
2026-11-10 22:46:28 +00:00
rdbt 71e8f7c8cd Merge pull request #14489 from MSedgeMC/fix/wololo-visibility
An invisible blue sheep is not wololoed from five blocks
2026-11-10 22:46:23 +00:00
rdbt 91429d906a Merge pull request #14488 from MSedgeMC/fix/sulfur-tempt-visibility
A sulfur cube's tempt range shrinks for an invisible player
2026-11-10 22:46:17 +00:00
rdbt 846e34c2eb Merge pull request #14486 from vnsmoreira/fix/golden-horse-armor
A horse draws its golden armour
2026-11-10 22:46:10 +00:00
rdbt a084ad2f35 Merge pull request #14468 from Solenopsisbot/fix/high-contrast-pack-hang
Fix startup hang with High Contrast resource pack
2026-11-10 22:46:05 +00:00
rdbt 10588c9b4c Merge pull request #14448 from ilguerro/fix/frame-vibrations
Let sculk hear item frame changes as vanilla does
2026-11-10 22:46:00 +00:00
rdbt 8ad2bee66a Merge pull request #14434 from MSedgeMC/fix/written-book-resolve
port: a written book resolves its selectors and scores when it is opened
2026-11-10 22:45:54 +00:00
rdbt 3e8dbbc2df Merge pull request #14423 from YourPancakes/perf/skip-swim-below-block-reads
perf(mobs): skip redundant swim block reads
2026-11-10 22:45:49 +00:00
rdbt bbe1ec5372 Merge pull request #14415 from YourPancakes/perf/villager-item-sensing-index
perf(mobs): reuse item cells for villager sensing
2026-11-10 22:45:43 +00:00
rdbt 1f6cf55e1c Merge pull request #14413 from MSedgeMC/fix/shulker-neighbor-updates
port: a shulker box lid updates its neighbours as it moves
2026-11-10 22:45:38 +00:00
MSedgeMC 9ce725cca5 fix: the social screen's click routing names the class that dispatches it
`SocialInteractionsScreen` declares no `mouseClicked` at all: its clicks come
from `ContainerEventHandler.mouseClicked`, the inherited child dispatch, which
reaches the search box's `EditBox.onClick` before the tabs, the rows' buttons
and Done. The body and the port map had attributed that to an override on the
screen.

`social_screen::click_kind` now answers which child the click belongs to -
`Click::Search` for the box, `Click::Action` for the list - and `Game::social_click`
performs it. The test drives `click_kind`: both corners of the box are the
box's, the pixels left of and just below it are nobody's, and Done's centre is
the list's `Action::Done`. Without the search branch the two inside corners
read `None`.

The caret move itself still needs the GUI atlas (`EditBox::click`), so it sits
in `Game::social_click` and is not asserted: every `Game` test in this crate
needs prepared resources and is `#[ignore]`d.
2026-11-10 22:40:35 +00:00
Nikita Maximilian Grimm f9c3e85868 Merge remote-tracking branch 'origin/main' into parity/ominous-spawner-loaded-rotation
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-10 23:36:02 +01:00
Nikita Maximilian Grimm ad3c08df6e Merge remote-tracking branch 'origin/main' into parity/noai-tadpole-ages
# Conflicts:
#	crates/horizon-client/src/mobs/ai.rs
2026-11-10 23:29:39 +01:00
Nikita Maximilian Grimm b555275591 Merge remote-tracking branch 'origin/main' into parity/sulfur-cube-bucket-health
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-10 23:27:21 +01:00
d9ed797708 Heightmaps: clone stale bits before concurrently refreshed heights
A snapshot could copy an old cached height and then a stale bit another reader had just cleared, retaining the old height as clean. Acquire the stale-bit snapshot first: marked columns rescan, and cleared bits publish the refreshed height. A concurrent Chunk snapshot test covers both heightmaps and fails with the original ordering.

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

Co-Authored-By: OpenCode GPT 6.1 Sol <[email protected]>
2026-11-10 22:03:40 +00:00
darkliroandAntigravity fb9b1d3542 threads: detect performance cores on Linux hybrid CPUs
Count performance cores on Linux systems with asymmetric core frequencies
(such as Intel Alder Lake, Raptor Lake, Meteor Lake and ARM big.LITTLE)
via sysfs cpufreq, bringing parity with the Apple silicon performance core
heuristics from #11294.

Co-Authored-By: Antigravity <[email protected]>
2026-11-10 23:00:02 +01:00
MSedgeMC 4d4aec1c7a fix: one rejected banner layer clears the saved list
`BannerPatternLayers.CODEC` is `Layer.CODEC.listOf()` and
`BannerBlockEntity.loadAdditional` resolves it with `ValueInput.read` plus
`Optional.orElse(BannerPatternLayers.EMPTY)`, so a single layer the codec
rejects leaves no layers at all. The branch kept the valid ones with a
`filter_map`, which is the partial behaviour the body says it fixed.

The list now reads all or nothing, and the test asserts the empty answer for a
mixed list, a missing field, and that a list of valid layers still reads back
(and round-trips), so an always-empty result cannot pass it.
2026-11-10 21:58:02 +00:00
DUzzL a8a5843f59 Mobs: tick freezing after the move and block effects, like LivingEntity.aiStep 2026-11-10 22:40:06 +01:00
c45072ca0e A comparator beside a decorated pot reads its item
DecoratedPotBlock.getAnalogOutputSignal goes through
AbstractContainerMenu.getRedstoneSignalFromBlockEntity ->
getRedstoneSignalFromContainer, but Horizon keeps a pot's one slot in the
chunk's saved block entity rather than world.block_entities, so the
container signal found no container and read 0. The comparator path now
builds the pot's ContainerSingleItem view from the saved tag (the same one
hopper insertion already used) and reads the slot through it, so a pot
with items powers a comparator and a hopper insertion updates it.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:31:22 +01:00
CocofireHDandDeepSeek V4.1 Flash 63a2feba79 A zombie villager's profession is the constructor's draw from its own random (#14857)
`ZombieVillager.defineSynchedData` seeds `DATA_VILLAGER_DATA` from
`initializeZombieVillagerData(this.random)`: one `nextInt(15)` on the entity's
own random, made inside `Entity`'s constructor. Horizon built a synthetic
`LegacyRandom` out of the mob's random state and id instead, so the profession
never matched vanilla's and the mob's own random never advanced.

The draw also has to sit in the right place in the stream. `Entity.<init>`
makes the UUID's two draws and then calls `defineSynchedData` last, while the
yaw `living_random` used to take belongs to `LivingEntity`'s constructor, after
it. So `living_random` now returns the random straight after the UUID, and the
two draws it left behind move to `zombie_villager::constructor_draws`, which
`Mob::with_random` calls in vanilla's order. Nothing moves for other kinds:
those draws are constants, so their streams are unchanged.

Two draws vanilla never makes are gone as well. `ZombieVillager.finalizeSpawn`
only picks the villager type and never rolls a profession, and neither does the
spawn path. `readAdditionalSaveData` redraws only for a finalized save with no
`VillagerData`, which `read_nbt` now matches.

Verified with the issue's repro (`parity_fuzz.py --replay`, seed 998): vanilla
`butcher` against Horizon `nitwit` before, both `butcher` after. The replay's
other difference, `Motion[1]` -0.0784 against 0.0, is pre-existing on
`origin/main` and untouched here. `seed_sync`, `zombie_cure_sound` and
`world_spawn#1`-`#4`/`world_spawn_sync` pass.

`mobs.rs` is past the 3000-line limit, so it gains no lines: the helper lives in
`zombie_villager.rs` and `living_random` loses the yaw line it used to take.

Co-Authored-By: DeepSeek V4.1 Flash (OpenCode) <[email protected]>

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-10 21:38:36 +01:00
DUzzL b228e6bef7 A shulker keeps its armor attribute once its lid has moved 2026-11-10 20:51:41 +01:00
Verm 6a246dd81d A villager narrows a loaded FoodLevel to a byte (#14967)
Villager.readAdditionalSaveData reads it with getByteOr, which narrows
any numeric tag (IntTag.byteValue is (byte)(value & 255)): FoodLevel:300
loads as 44. The loader kept the raw number.
2026-11-10 19:20:30 +00:00
Web-mc1 4c49ec3523 Fix biome table panic when empty 2026-11-11 07:47:48 +13:00
Oloion 2e6f3cd716 client: show custom server crafting recipes in recipe book (fixes #14608) 2026-11-10 21:32:19 +03:00
DetimesandClaude Opus 5.5 14ac9b88e5 Merge upstream/main into perf-block-event-queue
Brings the branch up to date and lays out the new code and tests as
rustfmt wants them, which the verify job checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:26:50 +00:00
Mayonesu0andClaude Sonnet 5.5 9528d81b2f The last_hurt_by_mob corpus gains a pig naming its own UUID
Adds a fourth NoAI pig (self) summoned with last_hurt_by_mob set to its
own UUID, read at the same points as echo, so vanilla 26.3 shows that
EntityReference.getEntity resolves the holder too and baseTick ends the
record after 100 ticks.

Part of #12830

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 19:17:45 +01:00
DetimesandClaude Opus 5.5 289e90d636 Merge upstream/main into perf-replay-excuse
Brings the branch up to date and lays out the new code and tests as
rustfmt wants them, which the verify job checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:16:08 +00:00
Mayonesu0andClaude Opus 5.5 3275cd1602 Dispensers pick players in getEntitiesOfClass order, loaded or not
Players are entities of the level from placeNewPlayer/respawn on, so a
guest whose client is still loading is equipped too, and guests and the
local player sort with the mobs and stands: entity sections first
(EntitySectionStorage.forEachAccessibleNonEmptySection, SectionPos.asLong
order), then join order by entity id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 19:15:33 +01:00
Mayonesu0andClaude Sonnet 5.5 a100957b30 Dispensers equip server players and respect armor stand slot locks
EquipmentDispenseItemBehavior picks the first living entity in front that
canEquipWithDispenser, players included; ArmorStand.canUseSlot rejects locked
slots and hands without arms. Fixes #12937

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 19:15:33 +01:00
Verm 452d4be9dc A server player's saved Fire is narrowed to a short too
Entity.load reads Fire with getShortOr for every entity. The player's
loader read it, Air and TicksFrozen through one unnarrowed read; Fire
is now narrowed, the other two stay ints as vanilla reads them.
2026-11-10 18:05:35 +00:00
DetimesandClaude Opus 5.5 c08c3e765c Test: held_attack_item returns the item the old clone returned
Checks the borrowed lookup against the clone-and-flatten expression it
replaces, over an empty slot, filled slots, slots past the end and an
empty inventory.

Refs #14939

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:01:58 +00:00
masa-masa-0314andZCode 3dcdbf8947 docs: ground Friends overlay split plan in 26.3 source review
Replace the open-ended UI scope with eight reviewable work packages and
separate backend, toast, face and host-adapter steps. Record vanilla
entry/lifecycle requirements, old-port defects, evidence limits and the
maintainer decisions required before implementation.

Keep the account overlay distinct from the approved host/share migration;
leave the old implementation PR and isolated merge branch untouched.

Co-Authored-By: ZCode <[email protected]>
2026-11-11 02:01:45 +08:00
DetimesandClaude Opus 5.5 d386833f8b Perf: borrow the held item in tick_guests instead of cloning the stack
tick_guests cloned the whole ItemStack of every guest's selected slot
every tick, only to compare its item with play.attack_item. The new
held_attack_item helper borrows the item, and the Arc is cloned only
when the held item changed. Same result, no clone on the common path.

Refs #14939

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:01:39 +00:00
DUzzL 5da9065a8d Start the cure when a zombie villager loads a ConversionTime
ZombieVillager.readAdditionalSaveData calls startConverting, so a saved cure swaps weakness for strength on load.
2026-11-10 18:56:44 +01:00
MSedgeMC a04de39fea port_map: CrafterBlockEntity.fillStackedContents is a port
The crafter's nine slots are the menu's MAIN container and count for the
recipe book's craftable check.
2026-11-10 17:45:24 +00:00
MSedgeMC 76d95dbcc9 test: a crafter's grid is stacked for the recipe book
`a_crafters_grid_counts_for_the_recipe_book` opens a crafter menu, puts
four oak planks in its first slot and asks the stacked contents whether
an oak-plank ingredient can be crafted. Without the crafter arm the same
call fails.
2026-11-10 17:45:13 +00:00
MSedgeMC b9ad2da17e fix: a crafter's grid counts for the recipe book
`CrafterBlockEntity.fillStackedContents` hands the crafter's nine slots
to the recipe book's stacked contents (`accountSimpleStack` each), so an
open crafter's grid counts towards the craftable check.

Horizon's `Menu::stacked_contents` read the player's inventory, the mod
sources and the `GRID` container, but a crafter's slots are its `MAIN`
container (`CrafterMenu.addSlots`): with a crafter open the book saw an
empty grid and marked nothing craftable.
2026-11-10 17:45:13 +00:00
DetimesandClaude Haiku 5.5 fab1e1a3e6 Test: entity_near matches the scan it replaced
Differential test over 2000 seeded random inputs: entity sets of up to 40
states (all four kinds, own and other ids), guest positions and slacks,
with entities placed on or next to every edge of the close box, checked
against a verbatim copy of the old scan. Plus an inclusive-edge test and
the own/item/orb exclusions. The inputs are multiples of 1/8 so the box
edges are exact in f64. No world or game resources needed; cargo not run.

Refs #14920

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 17:41:19 +00:00
DetimesandClaude Haiku 5.5 f6d8444698 Perf: test the distance before the kind in the replay's entity excuse
excused() ran a string compare on each entity's kind before the box test,
for every guest every tick. Move the box test first (it is a pure float
check) and move the entity scan into entity_near, so the excuse can be
checked against the old scan. The boolean result is unchanged: the
predicates are pure and any() is order-independent.

Refs #14920

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 17:40:37 +00:00
Shashanksaraswat123939 918e56994c ci: re-run checks (verify was cancelled when #14802 closed) 2026-11-10 21:33:19 +04:00
MSedgeMC b5a64cf86b port_map: JukeboxBlockEntity.notifyItemChangedInJukebox is a port
A disc coming or going sets `has_record` and posts `block_change` at the
box; the row kept the old gap.
2026-11-10 17:24:58 +00:00
MSedgeMC 0966aa0d3f test: a disc change posts block_change
`a_disc_change_posts_block_change` places a jukebox, records the posted
game events and calls `set_has_record`: the box posts
`minecraft:block_change` at its centre with no source. Without the post
the recorded list is empty.
2026-11-10 17:15:39 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 9188926fff Shader API 0.2: [frame] primaries, and the rule for new names
A 0.2 pack can't show a colour outside sRGB today: the contract says every
colour is in BT.709 primaries, forever. This adds the key that will let a
pack ask for more, before 0.2 is on by default and packs are written against
that contract.

- `[frame] primaries = "bt709"` (the default) or `"bt2020"`. The check takes
  `"bt2020"` only with `blend = "linear"`, since a change of primaries is only
  right in linear light. The game refuses a `"bt2020"` pack for now, as it
  refuses `blend = "linear"`.
- `Frame` gains `primaries` and `luminance` (that space's luminance weights)
  after `black_level`. The renderer writes 0 and BT.709's weights. The
  uploaded buffer grows by 16 bytes; 0.1 declares the same prefix as before.
- The reference's "Room to grow" says a later release adds a name to a
  stage's prelude only under a manifest key the pack sets or in a new stage.
  `tests/names.rs` holds each 0.2 prelude to its list of names
  (`tests/names-0.2/`), and shows why: a pack's own `fn depth_at` in a post
  stage is refused as a redefinition, its own `fn to_bt709` passes.

No pack's picture changes: a pack without the key, a `"bt709"` pack and 0.1
packs draw as before.

Part of #14584 (step 1) and #12989.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 18:13:34 +01:00
MSedgeMC b920f8a432 fix: a disc coming or going posts block_change
`JukeboxBlockEntity.notifyItemChangedInJukebox` sets the `has_record`
block state with update flag 2 and then calls
`level.gameEvent(..., GameEvent.BLOCK_CHANGE, pos)`: sculk sensors hear a
disc enter or leave a jukebox. Horizon's `set_has_record` changed the
state but posted no game event.
2026-11-10 17:09:19 +00:00
Florian ErnstandClaude Opus 5.5 16fb5cfed0 Slot sources: holder and tag codec, and slot-source tags in DataStore
SlotSources.CODEC admits a registered holder (`ns:id`), a holder list and a
`#tag` holder set wherever a slot source is accepted, and validates the
`group`, `limit_slots`, `filtered`, `contents` and `slot_range` shapes
(including a `slot_range` source context) against the loaded registry.

DataStore loads `tags/slot_source` in the same pass as the definitions, in
pack order with `replace`. `slot_source_tag` resolves a tag as TagLoader
does: first-seen member order, nested tags, required members and cycles
rejected. The command registry publishes the tags that resolve.

Part 1 of 3 for #13091 (PR #13951 is the last part).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:04:33 +01:00
TheMrZZandCodex gpt-6.1-sol ef9f8e86d7 Keep item-count and shulker harness registrations merge-compatible
Share only isolated-group/filter metadata; each PR keeps its own corpus and gameplay change. Preserve hopper-pot exact selection and all existing groups.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-10 18:04:14 +01:00
TheMrZZandCodex gpt-6.1-sol b91c2d4965 Keep item-count and shulker harness registrations merge-compatible
Share only isolated-group/filter metadata; each PR keeps its own corpus and gameplay change. Preserve hopper-pot exact selection and all existing groups.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-10 18:04:12 +01:00
TheMrZZandCodex gpt-6.1-sol 1cf4775de9 Merge main into PR13762 to pick up landed CI fixes
Preserve maintainer merge history; include deterministic git-slim temporary repository maintenance settings from #14090.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-10 18:02:06 +01:00
TheMrZZandCodex gpt-6.1-sol bdf670abdf Merge main into PR13761 to pick up landed CI fixes
Preserve maintainer merge history; include deterministic git-slim temporary repository maintenance settings from #14090.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-10 18:02:03 +01:00
Verm 32621f2275 A mob and an armor stand narrow a loaded Fire to a short (#14879)
Entity.load reads Fire with getShortOr, which narrows any numeric tag
(IntTag.shortValue is (short)(value & 65535)): Fire:40000 loads as
-25536. The arrow, the other projectiles and the boat already narrowed
it; the mob's and the armor stand's loaders kept the raw number.
2026-11-10 16:57:36 +00:00
Verm b6172e204f A mob narrows a loaded HurtTime and DeathTime to a short (#14876)
LivingEntity.readAdditionalSaveData reads both with getShortOr, which
narrows any numeric tag (IntTag.shortValue is (short)(value & 65535)):
HurtTime:40000 loads as -25536 and never counts down. The loader kept
the raw number, so such a mob counted down from 40000 and was drawn
hurt all the while.
2026-11-10 16:50:37 +00:00
DetimesandClaude b642094bb6 Test: block-event queue matches the old Vec behaviour
Replays pushes, duplicates, pops with re-queues during a run, deferred
events put back after the run, and retains against the old Vec model
(contains + push, remove(0)) and checks queue contents and pop order
after every step. Also checks 5000 distinct events pop in queue order
and a duplicate is dropped. No game resources needed.

Refs #14873

Co-Authored-By: Claude <[email protected]>
2026-11-10 16:41:27 +00:00
DetimesandClaude e2cb60d768 Perf: block-event queue is O(1) per event, not O(E^2) per tick
run_block_events and client_drain_block_events popped with Vec::remove(0),
which shifts the whole tail per event, and block_event deduped with a
linear contains. The queue is now a VecDeque (pop_front) with an
FxHashSet mirror for the dedupe. BlockEventData derives Hash.

All queue writes go through Ticks::queue_block_event, pop_block_event
and retain_block_events so the set cannot drift. Queue order, dedupe
results and the re-queue and reschedule paths are unchanged.

Refs #14873

Co-Authored-By: Claude <[email protected]>
2026-11-10 16:41:21 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 8df65734b7 frame_map_writes and wolf_anger_writes run in work folders of their own
Both wrapped the command_exec driver without --work-dir, so they shared
.local/command-exec-parity with each other and with command_exec, and two
running at once read each other's scripts and worlds.

Fixes #14855

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 17:20:39 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 1b5800c3ab command_exec cleanup keeps the End's dragon; bird flap sensors seeds each bird itself
The End's own dragon flies above the cleanup's floor at times, and killing it started vanilla's
death sequence. bird flap sensors ran on item honey bounce's seed sync, 36 groups earlier, and
failed in more than half of the runs once the cleanup ran between them (0 of 9 without it): each
bird now gets its own sync, with entity ids clear of the world's loaded entities.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 17:08:46 +01:00
Mayonesu0andClaude Sonnet 5.5 2a67bd988c A saved last_hurt_by_mob naming the mob itself resolves like any other
EntityReference.getEntity looks the UUID up in the level and returns any
matching LivingEntity, the holder included, so LivingEntity.baseTick ends
such a record after 100 ticks. resolve_last_hurt_by_refs dropped a
reference equal to the mob's own UUID, leaving it unresolved and saved for
ever. Remove that exclusion and cover it with a test.

Part of #12830

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 16:30:47 +01:00
Nikita Maximilian Grimm 66ead25e8d Merge remote-tracking branch 'origin/main' into fix/command-exec-group-isolation 2026-11-10 16:21:50 +01:00
readerkid 327b811914 Map CEM's armour models to the layers 26.3 draws, and the rabbit's feet
CEM names a humanoid's armour with two models, `<mob>_outer_armor` and
`<mob>_inner_armor`, but 26.3 draws it on four layers of the model: the helmet,
the chestplate, the boots and the thinner leggings. A CEM name gave one layer
key, so no armour file reached any of them, and the 24 armour layers of the
zombie family's baby models were unreachable.

An armour model now reshapes every layer it covers: the outer one the helmet,
the chestplate and the boots, the inner one the leggings. Layers a model does
not have are dropped by the existing check against vanilla's layers, so no list
of mobs has to track the game, and a baby keeps its own file through the suffix
rule.

The rabbit's `left_foot`/`right_foot` mapped to `left_hind_foot`/
`right_hind_foot`, which 26.3 no longer has: the haunch carries the box under an
empty hind leg, so the foot is the haunch and the thigh the leg.

`mobs::cem::tests::names_reach_horizons_models` (ignored: needs the prepared
resources) passes with no gaps.

Fixes #8426

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-11-10 07:16:11 -08:00
Horizon agentandClaude Opus 5.5 938dcd673c Revert #13953: entity ticking waits for chunks two columns away
This reverts merge 5248e83f28 (#13953).

Since it merged (2026-11-09 15:51Z), entities in the command_exec
fixture world stop ticking: they no longer fall, die, despawn or pick
items up, and command_exec fails 159/184 (it passes at the merge's
parent, and fails at the merge, both run here). Every PR whose change
selects command_exec has failed parity since.

Vanilla's gate is right, but Horizon does not keep the ring around a
forceloaded or ticketed chunk resident the way vanilla's ticket levels
do (a FORCED ticket gives its neighbours FULL), so the residency check
holds back chunks vanilla ticks. #13852 needs that ring modelled first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 14:02:07 +01:00
Shashanksaraswat123939 ffdd56a5e0 tests: import sibling test modules by their own name
test_item_model_property and test_port_ledger imported their helpers as
tests.test_world_input_capture and tests.test_class_index, while every
other test imports siblings by module name (unittest discover puts tests/
on sys.path). The tests. form resolves to any installed top-level tests
package first, so both modules failed to import wherever one exists.
2026-11-10 16:40:16 +04:00
NongTham e1848e08a4 input: clear modifiers on focus loss and heal alt and super keys (fixes #14715) 2026-11-10 19:10:27 +07:00
foudretbr 3661bfd7c2 fix(game): evaluate attack_speed attribute modifiers for player attack cooldown (#14721) 2026-11-10 12:55:27 +01:00
foudretbr fc3ac6a620 fix(mobs): align drowned and husk conversion ticks and cure random with vanilla (#14770) 2026-11-10 12:52:35 +01:00
MSedgeMC a08205b8ec port_map: MerchantScreen.extractScroller is ported 2026-11-10 11:44:30 +00:00
MSedgeMC 41fdaa3f0c test: the merchant scroller's thumb asks for its cursor
Eight offers put the thumb at the track's top; a hand over it, the vertical
resize while dragged, nothing left of the thumb or past its bottom edge, and
the disabled scroller of seven offers asks for nothing.
2026-11-10 11:44:30 +00:00
MSedgeMC 2398317072 fix: the merchant's trade scroller shows its cursor
MerchantScreen.extractScroller requests CursorTypes.POINTING_HAND over the
scroller's thumb, or RESIZE_NS while it is dragged. Horizon drew the thumb
but asked for no cursor, so the pointer stayed an arrow over it.
2026-11-10 11:44:30 +00:00
DUzzL 800b42b719 Skip leash knots when saving chunk entities (EntityType.noSave) 2026-11-10 12:33:41 +01:00
MSedgeMC 669e1a162a Move takes_food into mobs/ai/feeding.rs so ai.rs may not grow 2026-11-10 11:29:46 +00:00
Ray McDonaldandClaude Opus 5.5 c46a72196e horizon-threads: resident memory on iOS through Mach task_info
libc declares proc_pidinfo/proc_taskinfo for macOS only, so horizon-threads
didn't compile for aarch64-apple-ios. iOS reads MACH_TASK_BASIC_INFO's
resident size instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 06:12:10 -05:00
NongTham d645b72e8b test: allow-flight in bed_explosion parity harness (fixes #14664) 2026-11-10 18:05:15 +07:00
Loki 3bc4e3035c Merge remote-tracking branch 'origin/main' into fix/12935-sculk-particle-resume-reload 2026-11-10 19:47:20 +09:00
Riccardo GuerrieroandClaude Fable 5.2 9ee7b165cd Worldgen: the range choice picks its values without a branch per block
RangeChoiceSampler::sample_volume kept or replaced each value with a
conditional the compiler turned into one branch per value. Final density
runs it over a chunk's whole 16x384x16 volume (the noodle caves), where the
choice changes often, so the branch was mispredicted: about 4.5% of proto
generation time at one thread.

The select now runs in its own function over plain slices, on the values'
bits, which the compiler vectorizes. Each value is the one vanilla's
conditional store leaves; a test checks it bit for bit against a scalar
reference, with NaN bounds, NaN selectors and signed zeros.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MWgQD4Rbxknozw5LZ
2026-11-10 11:47:04 +01:00
foudretbr 15183261d9 fix(input): reset debug keys modifier state on window focus loss (#14715) 2026-11-10 11:25:52 +01:00
MSedgeMC adbc523e5c port_map: the canAgeUp feeding branch
AgeableMob.canAgeUp to ai.rs::can_age_up, and Animal.mobInteract's food
branches to ai.rs::takes_food: an adult at age 0 that canFallInLove, else
canAgeUp.
2026-11-10 10:20:16 +00:00
MSedgeMC 7f5b3462df test: feeding a frog at a baby's age leaves the food in the hand
A frog and a cow, both at Age -24000, through takes_food and feed_animal: the
frog refuses the food and keeps the age, the cow takes it and grows a tenth.

Without the fix the frog takes it: took_food=true ate=true age=-21600, where
the test wants false, false and -24000. The cow reads the same either way
(age -21600).
2026-11-10 10:20:13 +00:00
MSedgeMC c106b315ad fix: a mob that cannot be a baby does not take the food that grows it
Animal.mobInteract's growing branch is `canAgeUp()`, which is
`isBaby() && !isAgeLocked()`, not `getAge() < 0`. ai::takes_food still
decided that branch from the raw age, so a frog spawned with Age at
getBabyStartAge (AgeableMob.finalizeSpawn's group baby is not gated on
canBeABaby), a camel husk (AbstractHorse's group spawn is 20 percent), or a
slime, magma cube, parrot or zombie nautilus with a negative age took the
food: it ate the item, played the eating sound and grew a tenth towards 0,
where vanilla refuses the click.

takes_food now asks can_age_up(m), the port of canAgeUp, the same predicate
the rest of the feeding code already used.
2026-11-10 10:20:06 +00:00
MSedgeMC c3121e9a5a Rebuild the weapon component read on current main without dropping attribute_modifiers 2026-11-10 09:59:59 +00:00
1d9040c05a Silence a chest's comparator while a cat sits on it
ChestBlock.isChestBlockedAt is a redstone conductor above the chest or a
cat sitting in the block above it (ChestBlock.java:318-319, the cat test
at :327-338). getAnalogOutputSignal (:346-348) reads getContainer(..,
false), whose combine(.., false) (:279) uses that predicate, so a blocked
chest combines to nothing and the comparator reads 0.

The comparator's container view (machines::Containers::view) only checked
the conductor; the cat test lived on the menu path alone. Hand the level's
mobs to the view and share one isCatSittingOnChest helper with the menu
path (chest_blocked_at). A hopper's getContainer(.., true) still ignores
the block, so hoppers and menus behave as before.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 09:19:23 +01:00
Skr1zzzzandClaude Opus 5.5 a35b729ccf Keep game.rs from growing: the falling model cache takes the start position
`falling_model_vertices` works out the model seed from the block's starting
position itself, so its call in the falling-block loop fits on one line and
game.rs ends up shorter than on main (docs/layers.md#file-size).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 11:14:38 +03:00
LokiandAntigravity 27cded80d5 mobs: apply squid sinking velocity on land under NoAI (fixes #14467)
Co-Authored-By: Antigravity <[email protected]>
2026-11-10 15:36:11 +09:00
AkirabaneandClaude Opus 5.5 9c0c8ed4f4 Server: the mob data generation finalizes with is read when the world opens
The first mob a fresh chunk generates (spawnOriginalMobs) read the structure mob
finalizer's data on the server's tick: every mob type, the biome tags, the spawn
registries, the enchantments and the item tags, from the prepared resources.
Where those files are slow to read, that one read stalled the server for 6 to
7 s, a minute after players first walked into new terrain (#13857).

The terrain now starts that read on a thread of its own when its level loads
(every dimension but the End, whose chunks generate no mobs). The cell stays a
OnceLock: a mob that needs the data before the read ends waits for it, and the
data is read once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 07:23:29 +01:00
masa-masa-0314andZCode 64e74bffd2 docs: propose friends overlay Part 2 spec
Co-Authored-By: ZCode <[email protected]>
2026-11-10 14:19:11 +08:00
GIGABAIT93andClaude Opus 5.5 5a452cc97f Ukrainian: the 96 strings uk_ua.json lacked (radial menu, HDR, fuel)
The controller's radial menu and its page, the HDR options' tooltips and
the recipe viewer's fuel tooltip. Placeholders and edge spaces match
en_us.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 08:06:12 +02:00
HiuoyandClaude f7c7e37999 Layer split: the "no prepared files" screen gets its page through a hook
A new get_the_game hook (horizon-hooks, re-exported by horizon-platform)
answers with the page to open and the screen's texts as translation keys.
horizon-official-servers answers it with Horizon's launcher text and
horizon_addresses::WEBSITE. With no hook, the engine screen and
missing_resources say how to prepare the files and offer only Quit.
The screen's strings are now translation keys. The no_resources.rs entry
leaves tools/addresses.json's allowed list.

Closes #14479

Co-Authored-By: Claude <[email protected]>
2026-11-10 09:59:36 +04:00
Nikita Maximilian GrimmandClaude Fable 5.2 db26868e4f HDR10 output: the last pass dithers its 10 bits
The float frame is smooth, but the last pass rounded it to the HDR10
swapchain's 10 bits as it was. Around 90 nits one PQ code is a 1% step
in light, and a clear noon sky is two or three codes tall, so it showed
as wide flat bands with hard edges (#12989's audit, F3).

The pass into the HDR10 swapchain now adds triangular noise of one code
either way to the PQ signal, each channel's own, as the last thing
before the write: over the world and the HUD alike, after the black
level lift. A gradient shows as grain one code deep and its mean is the
light meant.

- The noise is a fixed function of the pixel (PCG's 3D integer hash):
  no frame counter, state or texture, so a still picture stays still
  and HORIZON_STILL needs nothing.
- Black stays black: within a code of 0 or of the top the noise shrinks
  to what fits, so a signal of 0 is written as 0, one of 1 as 1023,
  nothing leaves the range, and near-black isn't lifted.
  In that last code the rounded mean leans to the end (a third of a
  code from it shows as an eighth): the accepted price of a true 0.
- A pipeline override constant (`pq_dither`) turns it on for the HDR10
  swapchain's pipeline alone. scRGB (a float swapchain), SDR, the SDR
  screenshot, recordings and the screenshot's HDR10 copy (`-hdr.png`)
  are as before, byte for byte; calibration's test pictures keep their
  exact codes.

Refs #12989

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 06:45:33 +01:00
5cfbc7e3ea Stop horses, llamas, camels and flying monsters climbing vines and ladders
AbstractHorse.onClimbable (horses, donkeys, mules, the undead horses, llamas,
trader llamas, camels, camel husks), Ghast.onClimbable, Phantom.onClimbable
and HappyGhast.onClimbable all return false, so LivingEntity never takes its
climbable branch for them: no 0.15 clamp and fall reset in handleOnClimbable,
no 0.2 climb against a wall in handleRelativeFrictionAndCalculateMovement, no
fall reset for a ridden mount in handleMoveVehicle, and isPushable keeps them
pushable in vines. Mob::on_climbable now answers that false, which every
caller (travel, pushEntities, the vehicle fall reset) already reads.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 06:36:40 +01:00
Mayonesu0andClaude Sonnet 5.5 37bbe0bdea A loaded armor stand saves the movement_speed its first tick makes
armor_stand_to_nbt kept a saved `attributes: []` over the stand's live
speed_instance (or_insert), so a stand loaded with an empty list never saved
the movement_speed instance LivingEntity.aiStep -> removeFrost creates.
Append it to the saved list once the stand has ticked, keeping the other
saved instances. The mob corpus gains a stand summoned with `attributes:[]`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 06:26:14 +01:00
3f1f2fd3a8 Spawn phantoms under a glass roof
PhantomSpawner.tick asks Level.canSeeSky, which is "sky light 15 here"
(BlockAndLightGetter.canSeeSky), not a scan for a full collision cube:
glass and stained glass keep the sky light and spawn phantoms, while
stone, water and a slab roof do not. The advancement location predicate
read the same hand-rolled scan and now reads the sky light too.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 05:50:01 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 c8d9a748ac docs: HDR pass rules, tone-weighted blending is for linear light and sharpening eases off above white
Rule 3 told every pass that keeps a history to blend tone-weighted. Measured on Horizon's
own TAA, which accumulates the float frame's gamma, that raised the sun scene's largest
per-pixel standard deviation from 11 to 27 PQ code values. The rule now goes by the encoding
a pass accumulates: tone-weighted for linear light (a 0.2 pack's post buffers, or the frame
under linear storage), as stored for vanilla's gamma.

Rule 2 named the sharpening's limit above 1 as a fault to fix. Measured, sharpening the sun's
edge as the rest raises its flicker under upscaling by 55 to 69% for 1 to 6% more detail, so
the limit stays and the rule says why.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 05:22:27 +01:00
YourPancakes ab7d9f4c50 perf(world): avoid full-cube allocation in collision checks 2026-11-10 07:18:19 +03:00
Horizon agentandClaude Opus 5.5 8642db5c99 Renderer: the ExternalPipeline hook, with the shadow request and its culling in gfx/external.rs
Step a of #14035 (layer plan M6). An external shader pipeline implements
ExternalPipeline; the renderer calls begin_frame and shadow_request on world
frames, resize and reset_history, and draws vanilla's way where it doesn't
answer. Nothing sets one yet: each point is one Option test.

ShadowView moves from pack_post (re-exported there) and ShadowCull,
shadow_box, shadow_runs and shadow_casters from gfx.rs, unchanged: the
engine's side of the shadow frame point.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 05:17:39 +01:00
YourPancakesandChatGPT 4f1b40d9ca fix(render): keep binding cache out of oversized gfx.rs
Co-Authored-By: ChatGPT (GPT-6) <[email protected]>
2026-11-10 07:12:21 +03:00
YourPancakes 81a8d04a1f perf(render): cache flat compute bind groups 2026-11-10 06:55:35 +03:00
Vinícius MoreiraandClaude Opus 5.5 e1a6c5e363 A dispensed item draws its constructor's motion from its own random
DefaultDispenseItemBehavior.spawnItem builds the item with the
five-argument ItemEntity constructor, which draws a default motion (two
nextDouble) from the item's own random before spawnItem sets the thrown
one. Horizon passed the thrown motion straight in and skipped those draws,
so every later draw from the item's random, starting with
moveTowardsClosestSpace's escape speed, came two doubles early.
spawn_item_thrown makes the draws; the dispenser, the vault and the trial
spawner use it.

Fixes #14537

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:30:20 -03:00
YourPancakes 89733192ca perf(render): evaluate sky octagon with half-planes 2026-11-10 06:26:52 +03:00
b973a2ed28 Post block_place when turtles and frogs lay eggs, and stop bred turtles bursting hearts
Turtle.TurtleLayEggGoal sets the egg then posts GameEvent.BLOCK_PLACE, and its lay-egg pitch comes from level.getRandom(); TryLaySpawnOnFluidNearLand posts the same event for frogspawn. Turtle.TurtleBreedGoal.breed overrides Animal.breed, so Animal.finalizeSpawnChildFromBreeding's entity event 18 never runs for a bred turtle (Frog.spawnChildFromBreeding still calls it).

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 04:13:00 +01:00
Evrim CicekandClaude Opus 5.5 8392c05178 levels world border tests start from a new scratch world (#14654)
They opened HORIZON_HOME/h260 without removing it, so a second run found
the border the first had saved and its first worldborder set changed
nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 06:00:05 +03:00
Evrim CicekandClaude Opus 5.5 03a6255967 pad::parity_tests: pad_press records the press as pad_button does (#14648)
Since the radial menu, Pad::holds_action reads the actions pad_button
records for a pressed button; the helper called pad_action directly, so
four tests read a held action as not held.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 05:53:11 +03:00
6539061751 Sneaking keeps the held food off campfires and candles answer pick-block
ServerPlayerGameMode.useItemOn skips the block's useItemOn while sneaking
with something in either hand, so CampfireBlock.useItemOn never places the
food; the item's own use (eating) runs instead. The block use it does
consume triggers ITEM_USED_ON_BLOCK, which the campfire placement now fires
too. CampfireBlock.douse and AbstractCandleBlock.extinguish post
BLOCK_CHANGE after the extinguish sound, so water on a lit campfire or a
lit candle is heard by sculk sensors, and CandleCakeBlock.getCloneItemStack
answers a cake for the plain candle cake as well as the dyed ones.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 03:52:09 +01:00
MSedgeMC 44b65a8226 port_map: map TraderLlamaDefendWanderingTraderGoal.canUse player validity 2026-11-10 01:57:41 +00:00
MSedgeMC 3dfc15e206 test: a trader llama does not defend against a spectator 2026-11-10 01:57:41 +00:00
MSedgeMC f55124aaf7 fix: a trader llama ignores a spectator attacker 2026-11-10 01:57:22 +00:00
MSedgeMC 63e9728c2e port_map: map VexCopyOwnerTargetGoal.canUse target validity 2026-11-10 01:56:57 +00:00
MSedgeMC 3955c94576 test: a vex does not copy a dead owner target 2026-11-10 01:56:57 +00:00
MSedgeMC 63a4c6f103 fix: a vex ignores a dead owner target 2026-11-10 01:56:39 +00:00
DetimesandClaude Haiku 5.5 7059358371 Catalog test: accept living_death_message as a free function
living_death_message is a free function in horizon_client_lib::living_death,
so the test needs a set for that module like hunger, landing and chat.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 01:52:12 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 fa19462873 An ominous item spawner's loaded yaw wraps at 360 too
Entity.load ends with setRot, which takes the yaw and the pitch % 360.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:47:46 +01:00
MSedgeMC aa25cc6cb3 port_map: the game2-009 rows whose gaps are gone
Six rows still described behaviour the code has, and two of them cited
`Game::use_spawn_egg` in `creatures.rs`, where it no longer lives (it is
in `creatures/spawn_eggs.rs`):

- `SpawnEggItem.spawnMob`: the spawn path posts
  `minecraft:entity_place` at the spawn position (the dispenser path does
  too), so sculk sensors hear the egg; the path is now cited.
- `PotionContents.getAllEffects`: `brewing::contents_effects` is the
  potion's effects plus the stack's `custom_effects`, and
  `finish_drinking` applies them.
- `PiercingWeapon.makeHitSound`: the jab's sound plays at the target
  through `audio.play`, shared with the LAN guests.
- `TooltipDisplay.withHidden`: the loot table's
  `minecraft:toggle_tooltips` is applied in `loot.rs::Context::run`, next
  to the `/item modify` path.
- `SlotDisplay.Composite.resolve`: `Book::stacks` flattens a composite
  into its members' stacks.
2026-11-10 01:35:55 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 e65ca98d9d A tadpole with NoAI still ages and grows into a frog
Tadpole.aiStep counts the age up, and NoAI only skips serverAiStep, so a
NoAI tadpole ages, shows its age lock's particles and grows up like any
other. The NoAI branch of the mob tick now runs the aquatic aiStep parts
that NoAI doesn't skip from one place in aquatic.rs.

Fixes #14615

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:33:24 +01:00
Evrim CicekandClaude Opus 5.5 d05c54b48e TNT silence tests run on an 8 MiB stack
Fixes #14628: the five source_silence_game tests overflowed the 2 MiB
test thread in a Windows debug build (4 MiB is enough) and took the whole
horizon-client lib run down.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 04:29:15 +03:00
9f9d226294 Post a shulker teleport's game event for sculk sensors
Shulker.teleportSomewhere calls level.gameEvent(GameEvent.TELEPORT,
oldPos, Context.of(this)) after setPos and before level event 2016. Emit
the matching MobEvent at the old block's centre so sculk sensors and
wardens hear the teleport.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 02:27:58 +01:00
MrCloudy2andClaude Opus 5.5 0a9ceaedb2 Every wind burst of a tick pushes an entity that ticks after the projectiles
apply_late_wind_pushes gave each entity only the first push held for it.

Harness: tools/test_wind_bursts_all_push_parity.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:12:50 +01:00
MrCloudy2andClaude Opus 5.5 d64e5172b6 A flying projectile is pushed by the water and lava it touches
Entity.baseTick's updateFluidInteraction applies the fluids' currents to a
thrown or hurting projectile (Entity.isPushedByFluid); only arrows had it.

Harness: tools/test_projectile_fluid_current_parity.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:12:49 +01:00
MrCloudy2andClaude Opus 5.5 faa8141c2f A cactus pricks a boat or a minecart a piston pushes
moveEntityByPiston's applyEffectsFromBlocks reaches CactusBlock.entityInside,
even for a push that moves the vehicle nowhere. The pricked vehicles are
hurt once the tick's pushes are over, so the targets found first stay valid.

Harness: tools/test_piston_cactus_vehicles_parity.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:12:42 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 4976814641 An ominous item spawner keeps the rotation, OnGround and fall_distance it was loaded with
Entity.load reads Rotation (its pitch clamped to -90..90 after % 360),
OnGround and fall_distance, and a spawner never moves or turns, so its
save writes them back. Horizon saved 0 for all three.

Fixes #14572

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:10:54 +01:00
MrCloudy2andClaude Opus 5.5 2d5e7839c6 A projectile hits primed TNT (PrimedTnt.isPickable)
Primed TNT joins the boats and minecarts in the list of objects every
projectile, the trident included, can strike: a wind charge bursts on it, a
snowball breaks on it, an arrow or a trident turns back.

Harness: tools/test_projectile_hits_tnt_parity.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:10:37 +01:00
MSedgeMC c06d152243 port_map: the spawn egg block-entity rows point at spawn_eggs.rs
`Game::apply_spawn_egg_entity_data` moved from `creatures.rs` to
`creatures/spawn_eggs.rs`, so `EntityType.appendCustomEntityStackConfig`
and `EntityType.updateCustomEntityTag` cited a function that is not
there. The leash row's gap is gone too: the tick checks the leashed
mob's life and its player holder's life and spectator state, so a dead
or spectating holder drops the lead.
2026-11-10 01:08:52 +00:00
Detimes 7a47e7a21f Merge remote-tracking branch 'upstream/main' into gap-line-of-sight 2026-11-10 01:06:25 +00:00
188817342b Firework rockets: honour Silent, post EXPLODE, count block launches
`FireworkRocketEntity.explode` posts `GameEvent.EXPLODE` from `getOwner()` at
the rocket before the damage, and the entity event passes `!isSilent()` to
`createFireworks`, which gates only the blast and the twinkle of
`FireworkParticles.Starter`, so a silent rocket keeps its sparks and flash.
A rocket launched from a block face also counts as a use, as
`ItemStack.useOn` does for `FireworkRocketItem.useOn`'s SUCCESS.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 02:05:57 +01:00
Detimes 56c7214447 Merge remote-tracking branch 'upstream/main' into gap-riding-getters 2026-11-10 00:54:38 +00:00
Skr1zzzzandClaude Opus 5.5 c1d32a0f93 Falling blocks: cache each model's vertices instead of rebuilding them every frame
The falling-block loop rebuilt every block's model vertices each frame: the
model lookup, two sprite hash lookups per face, shading and uv mapping. They
depend only on the block state and the model variant picked, so they are now
kept in model space per state and variant; each frame copies them, applies the
same translation as before and sets the block's light. The output is the same,
bit for bit.

8,100 falling sand blocks (fast profile, Windows 11, Ryzen 5 7500F, RTX 3070 Ti):
151 -> 247 fps, CPU 6.6 -> 4.0 ms per frame.

Part of #13007

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 03:50:36 +03:00
Nikita Maximilian GrimmandClaude Opus 5.5 861914b486 Merge origin/main into parity/bucket-mob-from-bucket
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 01:46:34 +01:00
foudretbr d1ca042ab8 fix(mobs): default cat variant to black when omitted (#14540) 2026-11-10 01:45:52 +01:00
Detimes 1e66c75589 Merge remote-tracking branch 'upstream/main' into gap-server-props-read 2026-11-10 00:40:40 +00:00
voduffandClaude Opus 5.5 7373b8cf73 The preedit tests take turns with the composition state (#14577)
preedit's state is one static for the process, and three tests change it while
cargo runs them in parallel: one's reset or should_suppress_key could land in
another, which failed at random in CI. They now hold a test-only lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:29:33 +00:00
Mayonesu0andClaude Sonnet 5.5 68ad338029 A saved last_hurt_by_mob is read back and ends as in vanilla
LivingEntity.readAdditionalSaveData reads last_hurt_by_mob as a lazy
EntityReference (the UUID) and sets lastHurtByMobTimestamp to
tickCount - ticks_since_last_hurt_by_mob. getLastHurtByMob only answers once
the UUID resolves to a living entity in the level, and baseTick ends the
record when that entity is dead or more than 100 ticks old.

- Mob.ai keeps the bare UUID (last_hurt_by_ref) until the game resolves it
  into last_hurt_by (a mob, or the player) before the mobs' baseTicks.
- baseTick (mobs/hurt_by.rs) ends a resolved record as vanilla does; a
  reference naming nothing stays, keeps aging, and is saved as it is.
- setLastHurtByMob(who/null) clears an unresolved reference.
- The tests' world loads the 2-column neighbourhood entities need to tick.
- The corpus gains a pig naming an entity that arrives later.

Part of #12830

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 01:28:46 +01:00
Detimes bd6bf2422b Merge remote-tracking branch 'upstream/main' into gap-mob-death-message 2026-11-10 00:25:43 +00:00
MSedgeMC f888d26173 port map: finish the moved-module citations, including the render and remote splits 2026-11-10 00:23:20 +00:00
MSedgeMC 72879fc35b port map: point citations at the modules they moved to
The game, entity_nbt, stations, creatures, minecarts, particles and remote modules were split this week; twenty rows
still named the file a function left.
2026-11-10 00:17:52 +00:00
voidsip 38b2b41791 Name the arrow expiry harness for its actual coverage 2026-11-09 18:12:25 -06:00
DUzzL f2b0c69f72 Wrap item frame and painting facing bytes like Direction.from3DDataValue/from2DDataValue 2026-11-10 01:04:45 +01:00
Riccardo GuerrieroandClaude Opus 5.5 5f40c762f6 Move the bred offspring's draws and their test out of creatures.rs
creatures.rs is over the 3000-line limit (docs/layers.md#file-size): the
coat coin, the wolf pup's voice and the test of both move to
game/creatures/bred_draws.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 01:03:44 +01:00
46988764a5 Bred wolf pups get a random voice, and pups take their coat coin from the parent
Wolf.getBreedOffspring picks the pup's voice with
WolfSoundVariants.pickRandomSoundVariant from the breeding parent's random,
after the collar colour mix; Horizon left every bred pup on the classic
voice. The cow, pig, chicken, fox, cat and wolf getBreedOffspring also draw
the coat coin (which parent's variant the baby gets) from the parent's own
random, where Horizon spent a level draw for every species but the
mooshroom.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
2026-11-10 01:03:38 +01:00
valuttaandClaude Opus 5.5 2289b7a732 AGENTS.md: how an agent reviews, after rdbtCVS's review prompt
Asked by a maintainer to review open pull requests, an agent takes them
one at a time, oldest first, skipping drafts, its person's own and ones
already reviewed. It checks function, regressions, tests and scope,
reports only points with a file:line, each marked by severity, and
submits Approve or Request changes, never a plain comment. Based on the
review prompt rdbtCVS shared.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:57:43 +01:00
MSedgeMC c9cf9cb18b port_map: SocialInteractionsScreen.init and mouseClicked 2026-11-09 23:57:24 +00:00
MSedgeMC 33754abe21 test: a click in the social search box is the box's own
The box's rectangle and the pixels just outside it; the list starts below, so
nothing else can claim the click.
2026-11-09 23:57:24 +00:00
MSedgeMC 5a67941d3f fix: a click in the social screen's search box places its caret
SocialInteractionsScreen.mouseClicked gives super.mouseClicked the widgets
first, so the search EditBox's onClick runs on a click inside it and puts the
caret under the pointer. Horizon's social click only knew the tabs, the rows
and Done; clicking the search box moved nothing.
2026-11-09 23:57:24 +00:00
voduff d68f241a0e Merge remote-tracking branch 'origin/main' into fix/12038-cube-body-item-replace 2026-11-09 23:52:09 +00:00
valuttaandClaude Opus 5.5 176f5b3475 AGENTS.md: review pull requests only when asked, post only findings
An agent asked for some reviews swept about 300 open pull requests, most
reviews saying it found nothing. Agents now review a pull request only
when its author or a maintainer asks for it, post only findings someone
can act on as a real review, and skip reviews that found nothing.
Maintainers' own agents may run wider passes when the maintainer asks.

Closes #14545.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:48:26 +01:00
MSedgeMC 34d39e0da0 Rebuild the weapon wear read on current main 2026-11-09 23:48:14 +00:00
Evrim CicekandClaude Opus 5.5 6d0d16d48b Move the experience orb NBT out of entity_nbt.rs
Part of #14043: a pure move to entity_nbt/orb.rs, so the orb's
fall_distance (#14440) lands in the moved file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:47:49 +03:00
MSedgeMC 7b73baf589 Rebuild the weapon component read on current main 2026-11-09 23:45:27 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 a45aa615ef A mob from a bucket is not persistent, a sulfur cube keeps its bucket's age, and tadpoles never despawn
MobBucketItem.spawn loads the bucket's entity data and sets fromBucket,
never PersistenceRequired. SulfurCube.loadFromBucketTag reads its own
lowercase age keys, and Tadpole.fromBucket is always true, so
requiresCustomPersistence keeps every tadpole.

Fixes #14538

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:42:55 +01:00
MrCloudy2andClaude Fable 5.2 c7ca421167 A geyser goes through scaffolding seen from below
PotentSulfurBlockEntity reads its column with
CollisionContext.positionContext(the height under it); the shapes were read
with no context, so scaffolding kept its full top and stopped the geyser.

Harness: tools/test_geyser_scaffolding_parity.py.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 00:22:30 +01:00
Riccardo GuerrieroandClaude Opus 5.5 c1540bd026 Keep animal_brain.rs at main's line count
The file is over 3000 lines and may not grow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:17:15 +01:00
8683a6b570 Post sniffer digging vibrations and mute the right sniffer sounds
Sniffer.emitDiggingParticles posts GameEvent.ENTITY_ACTION at the head block every ten ticks for the whole dig, outside the dust window. Only sounds that go through Entity.playSound are silenced: the state transitions and the seed drop, not playLocalSound's searching sound or the block's hit sound. A bred pair's egg takes its push from ItemEntity's own random.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 00:14:57 +01:00
DetimesandClaude Haiku 5.5 d88c0d9011 Adapt living death message test impls to the generated hook shape
The generated Hooks trait takes the event only: entity, kind and message are
its fields, so the test impls take one argument.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 23:11:58 +00:00
SolenopsisbotandCodex 62ed49d4a4 fix: satisfy game file size check
Co-Authored-By: Codex <[email protected]>
2026-11-10 10:05:52 +11:00
DetimesandClaude Haiku 5.5 9f861b1624 Use contains_key in entity lookup test (clippy unnecessary_get_then_check)
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 23:04:34 +00:00
Evrim Cicek bdf33dd2a3 Merge remote-tracking branch 'upstream/main' into tests/mob-landing-neighbourhood 2026-11-10 02:01:58 +03:00
MrCloudy2andClaude Fable 5.2 016630efda Keep creatures.rs from growing: the vehicle re-tick lives in wind.rs
The file-size rule (docs/layers.md#file-size). hurt_vehicle moves with it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 00:01:01 +01:00
MrCloudy2andClaude Fable 5.2 3a953f4f9a A geyser launches projectiles, boats and minecarts
PotentSulfurBlockEntity.LAUNCH_ENTITY_TICKER pushes every entity in the
column; only mobs, items and primed TNT were.

Harness: tools/test_geyser_launch_parity.py.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 23:55:52 +01:00
Horizon agentandClaude Opus 5.5 91b743b549 Telemetry and mod registry images copy every crate their lockfile builds
Railway's builds of both services fail since horizon-telemetry gained horizon-addresses (and the
platform crates) and horizon-mods gained horizon-release-sign: the Dockerfiles copy a fixed list of
crates, so cargo can't find the new path dependencies. The old deployments keep running, so nothing
looked broken. Copy every path crate of each service's own Cargo.lock, watch them in railway.json,
and test both lists against the lockfiles so the next new dependency fails verify instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 23:54:45 +01:00
Evrim CicekandClaude Opus 5.5 59923087d5 mob_landing_support_tests load the 5x5 chunks entities need to tick
Fixes #14493: since #13953 an entity ticks only once every chunk within 2
columns is loaded; with only chunk (0, 0) the pig never fell.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 01:51:39 +03:00
MSedgeMC 763b6f6c8c port_map: map WitherBoss side-head target sight 2026-11-09 22:49:37 +00:00
MSedgeMC 88c287eb7e test: a wither's side head does not pick through a wall 2026-11-09 22:49:37 +00:00
MSedgeMC 94f499bdbe fix: wither side heads need sight of a target 2026-11-09 22:49:37 +00:00
MSedgeMC f943e82857 port_map: map EvokerWololoSpellGoal.canUse visibility range 2026-11-09 22:49:30 +00:00
MSedgeMC 6efab1f890 test: an invisible blue sheep is not wololoed from five blocks 2026-11-09 22:49:30 +00:00
MSedgeMC 34b5ab04b0 fix: scale the evoker's wololo range by visibility 2026-11-09 22:49:30 +00:00
MSedgeMC a76ea00dde port_map: map SulfurCubeTemptGoal.canUse visibility range 2026-11-09 22:49:22 +00:00
MSedgeMC d7c7e06634 test: an invisible player tempts a sulfur cube only within two blocks 2026-11-09 22:49:22 +00:00
MSedgeMC 7f8a855d78 fix: scale a sulfur cube's tempt range by visibility 2026-11-09 22:49:22 +00:00
Evrim Cicek 5f68b5da25 Merge remote-tracking branch 'upstream/main' into fix/landing-vibrations 2026-11-10 01:36:24 +03:00
MrCloudy2andClaude Fable 5.2 ca01155bce A wind charge passes a vehicle an earlier charge of the tick broke
Vanilla ticks entities one after the other, so a charge never meets a boat or
minecart that an earlier charge already broke. The tick's hits are all found
first here, so such a charge ticks again without the broken vehicle.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 23:28:23 +01:00
Evrim CicekandClaude Opus 5.5 2740471e60 A falling block a piston pushes keeps Entity.move's fall bookkeeping
A piston's push is Entity.move(MoverType.PISTON): the drop adds to the
falling block's fall, and landing runs fallOn and posts HIT_GROUND in
that step. Review finding on #14440.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 01:28:02 +03:00
3f63aa1f5c Run a waxed wall hanging sign's click command instead of chaining a sign
WallHangingSignBlock.shouldTryToChainAnotherHangingSign lets the hanging sign
in hand chain onto the sign only when the side the player faces cannot execute
its click commands (SignBlockEntity.canExecuteClickCommands), so a waxed sign
with a run_command hands the click to SignBlock.useWithoutItem, which runs it
and returns SUCCESS_SERVER.

The client now answers that for the wall case as it already did for the
ceiling one (chains_hanging_sign: isHittingEditableSide by the sign's FACING
axis), so the click runs the command, plays the waxed-sign failure and places
nothing; the world sim's unconditional Pass for the wall edge is gone.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-09 23:26:38 +01:00
Solenopsisbot a151569d72 Merge remote-tracking branch 'origin/main' into t3/fix-high-contrast-pack-hang 2026-11-10 09:23:34 +11:00
Vinícius MoreiraandClaude Opus 5.5 bad4b0ef9a A horse draws its golden armour
The horse armour layer took its texture from the item id
(golden_horse_armor -> horse_body/golden), but the golden armour's
equippable asset_id is minecraft:gold, whose horse_body texture is
entity/equipment/horse_body/gold. The layer found no texture and drew
nothing. horse_armor_asset maps each horse armour to its equipment
asset; a test checks every vanilla horse armour against items.json and
equipment/*.json.

Fixes #13826

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:23:28 -03:00
SolenopsisbotandCodex 9482ae7472 Apply saved present mode before gameplay
Co-Authored-By: Codex <[email protected]>
2026-11-10 09:20:12 +11:00
SolenopsisbotandCodex 3a22ba32c2 Fix texture metadata parsing during pack startup
Co-Authored-By: Codex <[email protected]>
2026-11-10 09:17:35 +11:00
0xRinne 92125370de Merge branch 'main' into up2/metal-sprite-arrays 2026-11-09 16:16:54 -06:00
MrCloudy2andClaude Fable 5.2 eedbb1717c A wind charge's hit damages a boat or a minecart
AbstractWindCharge.onHitEntity hurts what it hit by one point before the
burst; a vehicle takes it through VehicleEntity.hurtServer and breaks on the
fifth hit of a tick. wind_charge_damage only looked among the mobs.

Harness: tools/test_wind_charge_vehicle_parity.py.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 23:11:56 +01:00
Evrim CicekandClaude Opus 5.5 fad8e4e555 Primed TNT and falling blocks post hit_ground when they land
Part of #14440: PrimedTnt and FallingBlockEntity move with Entity.move and
keep its checkFallDamage, which posts HIT_GROUND after the block's fallOn
when they land after a fall (a piston's push too, for TNT). Extends the
`entity landing sensors` command-exec group.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 01:06:08 +03:00
Horizon agent dbbe0e6bf5 Merge origin/main (brings #14090's test_git_slim fix) 2026-11-09 22:59:17 +01:00
5a78eee6ca Items spilled from a destroyed shulker box or bundle pop upward again
`ItemUtils.onContainerDestroyed` makes each stack a destroyed item held
with `new ItemEntity(level, x, y, z, stack)`, whose motion is 0.2 up and
0.2 less 0.1 sideways from the *item's* own random
(ItemEntity.java:61-66). The spill drew three doubles from the level
random instead, so the stacks barely rose and the level's stream
advanced three times per stack. Route it through `spawn_item_own`,
which already draws the four-argument constructor's motion (#13938).

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-09 22:49:34 +01:00
Horizon agentandClaude Opus 5.5 e11233f2dc The title screen's Friends icon is inactive without an invite-code resolver (spec #14167 step 4)
Join a Friend opens from vanilla's Friends icon slot, unchanged in place
and size at every GUI scale; it is now drawn inactive, and takes no click,
key or controller press, when no Hooks::tunnel resolver is registered
(net::joins_friends), as the pause menu's icon is without a sharing page.
horizon-official registers horizon-friends' resolver, so players of the
official game see no change; the plain executable, which refuses every
friend: address, no longer opens a screen that cannot join.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 22:45:31 +01:00
J5CaseyandClaude Opus 5.5 941e45b1ba Recipe book: number a server's synced recipes as the server does (#14435)
A client sent the server's recipes (horizon:recipe_content) numbered its
recipe book displays from its own files, while the server numbers them over
its recipe set, a world's data pack recipes included. Each pack recipe moved
the server's numbers past the client's, and the server's book entries, put
over the book by number, replaced other recipes with server:N entries.

The display numbers now come from the synced recipe set itself
(RecipeIndex::load_from_sources), for the book, its toasts and the
RecipeBookAdd toasts; without synced recipes nothing changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KtNXhvTSpY15Rjzwuqh8Nf
2026-11-09 15:45:03 -06:00
voduffandClaude Opus 5.5 916064d1ac A sulfur cube's body takes a swallowable block through /item replace
SulfurCube.getEquipmentSlotForItem answers BODY for every
#sulfur_cube_swallowable item, so the body's SlotAccess takes it. Horizon
checked only the item's own equippable slot and refused every block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:42:45 +00:00
MSedgeMC 4ef09a8e0d port_map: the written book resolution rows are ports
`resolveForItem`, `resolve`, `markResolved`, `resolvePage` and
`isPageTooLarge` cite `WrittenBook::resolve` and `resolve_held_book`.
The spawn egg rows cited `Game::use_spawn_egg` in `creatures.rs`, where
it no longer is: the function lives in `creatures/spawn_eggs.rs`.
2026-11-09 21:39:30 +00:00
MSedgeMC d9cf8f497c test: a written book's pages resolve and keep their resolved flag
The resolve test rewrites a selector page and a score page (a plain page
is left alone), marks the book resolved and then leaves a resolved book
alone; the over-long test keeps the raw pages past 32767 characters and
still marks the book resolved; the codec test round-trips `resolved`.
2026-11-09 21:39:30 +00:00
MSedgeMC a321aa6c73 fix: a written book resolves its selectors and scores when it is opened
`WrittenBookContent.resolveForItem` runs in `ServerPlayer.openItemGui`:
`resolve` replaces every page's selectors and scores with the text they
name and marks the book resolved, and a page whose resolved text passes
`resolvePage`'s 32767 characters cancels the resolution (the book is only
marked resolved).

Horizon kept the page components (`WrittenBook.page_tags`) but never
resolved them and had no resolved flag, so a page holding a selector
showed its raw component text and a book could not be told as resolved.

`WrittenBook` gains `resolved` (read and written by the component codec),
`WrittenBook::resolve` ports the resolution, and `Game::resolve_held_book`
resolves the book in the acting hand when `use_book` opens it (a LAN
guest's copy is the mirrored inventory, so its slot is sent back).
`set_written_book_pages` was already applied in `loot.rs`.
2026-11-09 21:39:30 +00:00
Vinícius MoreiraandClaude Opus 5.5 2490c57d3e Polytone: the drop happens when the particle joins, not at its first tick
Dropping a particle with physics at its first tick still drew it for one
frame, so a falling leaf flickered with the newest wide copy through it.
The check now runs when a pending particle joins the engine list, and
set_polytone moves unchanged to particles/polytone.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:32:03 -03:00
voidsip e624d71b21 Remove a needless borrow in the arrow fixture 2026-11-09 15:31:36 -06:00
Horizon agentandClaude Opus 5.5 a190dbbc0d Crates ship their own lang files: horizon_hooks::lang (layer plan M5)
horizon_hooks::lang::register(&'static [(code, json)]), re-exported as
horizon_platform::lang. The game's entry installs the registered files
into horizon_client::lang; Language::load reads them in the horizon
namespace right after the engine's bundled file for the same language,
before packs, and the engine's file wins on a key both have. Regional
variants share one alias table with the bundled files (fr_ca -> fr_fr,
de_ch -> de_de without ß). Nothing registered: languages load as before.

tools/lang_coverage.py reports crates/*/assets/lang beside the game's
folder; a crate's review record is tools/lang_review/<crate>/, and
--mark-reviewed puts each key in the folder that holds it. lang.rs's
file checks run on every crate folder, and a crate key the engine also
has fails them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 22:30:16 +01:00
YourPancakes f779b500ec perf(mobs): skip redundant swim block reads 2026-11-10 00:16:52 +03:00
YourPancakes 4ed92f7176 perf(mobs): reuse item cells for villager sensing 2026-11-10 00:06:46 +03:00
MSedgeMC 6e8edf7ad2 port_map: ShulkerBoxBlockEntity.doNeighborUpdates is a port
The row said the four lid-step calls were counted and dropped;
`Behaviours::shulker_neighbor_updates` now runs them, and `tick_shulkers`
calls it once per counted update.
2026-11-09 21:04:49 +00:00
MSedgeMC deb5860d9e test: a shulker lid reaches all six neighbours
`a_shulker_lid_updates_the_shapes_and_redstone_of_its_neighbours`
observes the level as `shulker_neighbor_updates` runs: each of the six
neighbours gets one `neighborChanged` from the shulker's block, with its
own state as the changed state. Without the call the level sees none.
2026-11-09 21:04:49 +00:00
MSedgeMC 6dc2d97de4 fix: a shulker box lid updates its neighbours as it moves
`ShulkerBoxBlockEntity.tick` calls `doNeighborUpdates` when its lid
starts or finishes opening or closing: the box's collision shape moved,
so the neighbours' shapes are updated (flag 3) and their
`neighborChanged` runs. Horizon's render tick counted those four calls
(`ShulkerTick.neighbor_updates`) and the game dropped them, so redstone
beside a moving shulker box never saw the update.

`Behaviours::shulker_neighbor_updates` ports the two calls, and
`tick_shulkers` runs it once per counted update. The box's collision
shape for the same ticks already reaches the world through
`shulker_collision_state`.
2026-11-09 21:04:49 +00:00
voduffandClaude Opus 5.5 b0074207ca A test's world-pack loot tables stay on its own thread (#14266)
The loot data is one slot per process. A test that installed a world pack's
armor_stand table warmed that slot, and every other test's stand break rolled
it too. load_thread_loot_data keeps such a test's loot data on its own thread,
ahead of the slot; a game never sets it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:56:22 +00:00
DUzzL 920e317f53 Make jmath::pow return NaN like Java for NaN exponent and |x|==1 with infinite y 2026-11-09 21:47:25 +01:00
Vinícius MoreiraandClaude Opus 5.5 9286b28e24 Polytone: a particle with physics born inside a block goes at once
A custom particle with has_physics whose box starts inside a block's
collision is dropped before its first tick, so its emitters never run.
Falling leaves start 0.05 under their leaf block, and a pack's leaf with a
0.08 hitbox reaches into it: in Java such a leaf never falls, while here
every one fell, and a leaf that emits a resting copy of itself each tick
left trails of them under every tree until the frame rate collapsed.

Compared in game against Java 26.3 with Polytone, with particles of its
own: a box overlapping a block by 0.01 goes, 0.01 clear of it lives, and
a particle without physics lives either way; the emitters do run every
tick. A test covers the three cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:45:54 -03:00
MSedgeMC 58abbd0e4a port_map: WorldOptionsScreen.updatePortControlsState is ported 2026-11-09 20:45:32 +00:00
MSedgeMC e6bc09eeb9 test: the LAN-off port box is read-only but focusable
The caret still moves and Backspace changes nothing while LAN is off; turning
LAN on makes the same key edit the port.
2026-11-09 20:45:32 +00:00
MSedgeMC 3ea0ce07a2 fix: the LAN port box is focusable while LAN is off
WorldOptionsScreen.updatePortControlsState makes the port box read-only
without LAN (setEditable) but leaves it focusable: clicking it selects and
copies the port. Horizon dropped the focus instead, so with LAN off the port
could not even be selected or copied.
2026-11-09 20:45:32 +00:00
voidsip df4b2599b4 Load the portal fixture's entity-ticking neighborhood 2026-11-09 14:43:57 -06:00
Riccardo Guerriero 8aea9cb52b Merge remote-tracking branch 'origin/main' into fix/frame-vibrations 2026-11-09 21:40:02 +01:00
voduffandClaude Opus 5.5 07a82eccf3 port map: rows follow remove_entity and the minecart save fns; PlayerEntry is a class row
remove_entity moved to game/remote_removal.rs, Minecart::to_nbt/from_nbt to
game/minecarts/nbt.rs. A class row takes home, not port.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:37:56 +00:00
fd7b18c787 Heightmaps: test that a write finds its own column again
A write two below the height asks about no block on the next read; a write at or
above it is found again down that column alone, and the other columns keep theirs.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:36:39 +00:00
Cx188andCodex 0bdc77efb6 Remove obsolete manual vanilla parity job (#14209)
Use the existing nightly and reusable parity runners instead of a second
manual inventory. Keep the JFR checks and describe their JDK fixtures.
All 84 removed harness commands remain in parity discovery.

Co-Authored-By: Codex (GPT-6) <[email protected]>
2026-11-09 23:31:54 +03:00
5c7ea99917 Heightmaps: a write marks its column, found again alone on its next read
A block written at or above a column's height (grass spreading, a crop, a mob breaking a
block) used to drop the whole chunk's map, and the next spawn attempt there scanned all 256
columns again. The write now marks that column; its next read finds its height down that
column only. The heights are those a rebuild gives. Natural spawning on the bench: 4.8 ms a
tick to 4.0.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:26:42 +00:00
Dylan FerreyraandClaude Opus 5.5 3914d39e80 Move the advancement packets out of play.rs into play/advancements.rs
AdvancementDisplay, Advancement, UpdateAdvancements and
SeenAdvancements, with their codecs, move byte for byte into
packets/play/advancements.rs. play.rs re-exports the four public items,
so every `packets::play::…` path still resolves.

The port map follows: the two rows that name UpdateAdvancements::read
and SeenAdvancements::write point at the new file.

Part of #13063.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:23:15 -03:00
voidsip 8aaa338f08 Separate Nether portal cooldown handling from gateway changes 2026-11-09 14:20:39 -06:00
voidsip 79b62aaaea Keep witness visibility inputs on seen villagers 2026-11-09 14:17:44 -06:00
Detimes 02b3b03618 Merge remote-tracking branch 'upstream/main' into gap-line-of-sight 2026-11-09 20:17:13 +00:00
DetimesandClaude Haiku 5.5 0acd52bcb5 Work in progress
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 20:17:11 +00:00
Detimes 02f00f9b83 Merge remote-tracking branch 'upstream/main' into gap-riding-getters 2026-11-09 20:17:08 +00:00
Detimes 7d75faab81 Merge remote-tracking branch 'upstream/main' into gap-server-props-read 2026-11-09 20:17:05 +00:00
Detimes 0eddebf75e Merge remote-tracking branch 'upstream/main' into gap-map-colors-read 2026-11-09 20:17:04 +00:00
DetimesandClaude Haiku 5.5 baab01b031 Work in progress
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 20:17:03 +00:00
Detimes 034c4b6e5c Merge remote-tracking branch 'upstream/main' into gap-mob-death-message 2026-11-09 20:16:59 +00:00
Detimes 566027307e Merge remote-tracking branch 'upstream/main' into gap-entity-lookup 2026-11-09 20:16:57 +00:00
voidsip e8dbc42da7 Use the oracle memory constructor entity-list type 2026-11-09 14:13:14 -06:00
voidsip adfc70d2f3 Split custom arrow contents and expiration from potion impacts 2026-11-09 14:10:51 -06:00
voidsip 9da6aa25e5 Split cached villager murder witnesses from hurt attribution 2026-11-09 14:10:25 -06:00
voidsip acf9008e49 Merge commit '38174db59bfd5bf90027bd727f894b141c9e72dc' into split/11536-preserve-live
# Conflicts:
#	.github/workflows/ci.yml
2026-11-09 14:06:12 -06:00
voidsip 7e32b7d0da Merge main before splitting villager reputation fixes 2026-11-09 14:06:08 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 c14ab8d543 Merge remote-tracking branch 'origin/main' into frame-data-count
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:05:56 +01:00
voidsip cd9441f90e Merge commit '38174db59bfd5bf90027bd727f894b141c9e72dc' into split/11484-review 2026-11-09 14:05:52 -06:00
RINNECODERandClaude Opus 5.5 d5bd80fcf7 Block sprites: the Metal warning lives in surface_setup, as gfx.rs may not grow
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 14:04:18 -06:00
Nikita Maximilian Grimm 021bbb8225 Merge commit '716988614' into parity-process-tree 2026-11-09 20:59:17 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 4da0ea5197 parity: start sccache's server outside the harness jobs on Windows
A server started by a harness's build joined that harness's job (sccache
doesn't ask to break away) and ended with it, failing other harnesses'
in-flight compiles (os error 10054). The runner now starts it before any
build, in a job of its own, with no idle timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:58:50 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 ac296614af /data on an item frame detaches its old map when only the stack's count changes
ItemFrame.readAdditionalSaveData compares the Item stack as read with
ItemStack.matches, count included, and removes the framed map on a
mismatch; only setItem then keeps one item. apply_entity_nbt compared
against item_frame_from_nbt's stack, already cut to one, so a count-only
change kept the old map's marker. It now compares the stack as read.

Fixes #14178

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:58:37 +01:00
Horizon agent fd85857547 Merge origin/main into fix/editbox-utf16-length 2026-11-09 20:57:20 +01:00
RINNECODER f5df9ca25a Merge main into #12156 2026-11-09 13:54:52 -06:00
MSedgeMC 9f6b9e408d port_map: the command block edit marks the chunk 2026-11-09 19:51:59 +00:00
MSedgeMC a81a3151c3 test: an edited command block dirties its chunk 2026-11-09 19:51:59 +00:00
MSedgeMC bc9c686b25 fix: editing a command block marks its chunk 2026-11-09 19:51:59 +00:00
yahya-nusseibehandClaude Opus 5.5 5328ec28b5 Mod registry: bundle SQLite 3.54 through rusqlite 0.41
The registry's own workspace still resolved rusqlite 0.37 ->
libsqlite3-sys 0.35, which bundles a SQLite older than 3.54
(RUSTSEC-2026-0459: uninitialised page-cache memory from a crafted
database opened with a "-wal" file of another page size). The registry
only opens its own database, so this isn't reachable as deployed, but
it is the same upgrade the telemetry server and the root workspace
already made: rusqlite 0.41 resolves libsqlite3-sys 0.39.1, and
fallible_uint keeps the u64/usize conversions working as before (an
error past i64::MAX).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-09 21:36:55 +02:00
Nikita Maximilian GrimmandClaude Opus 5.5 f11565b4ae Merge main into #13839; graphics.md's HDR paragraph is main's (with #14129) plus this PR's sentence
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:34:12 +01:00
DetimesandClaude Haiku 5.5 de6cc998df Native hooks: read the vehicle an entity rides and its passengers
Adds the read-only helpers native_vehicle_of(entity) and
native_passengers_of(entity) for server mods (vanilla Entity.getVehicle
and getPassengers, first = controlling passenger). Helper-only fragment
riding_getters.json; API number is assigned when the fragment is stamped.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 19:00:46 +00:00
DetimesandClaude Haiku 5.5 03b7d245b5 Native hooks: living_death_message (mob death message) (work in progress)
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 18:59:43 +00:00
RINNECODERandClaude Opus 5.5 790d1be209 Block sprites: warn when Metal arrays grow past 512 layers, with the layer count and GPU
So a texture-corruption report from a big pack can be tied to the lifted cap at once (#12155).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:57:33 -06:00
DetimesandClaude Haiku 5.5 a6204f1f3a Native hooks: read-only entity lookup by UUID and entity data in any level (work in progress)
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 18:57:08 +00:00
Mik00000 c2dd2d935d perf(light): reuse scratch queues during incremental relight and preserve lazy section loading
- Reuse thread-local scratch queues (`RelightScratch`) across BFS light propagation passes, avoiding reallocation during incremental relighting.
- Pass borrowed slices `&[Pos]` to `relight_layer` to avoid redundant `Vec<Pos>` heap allocations.
- Cache consecutive vertical column lookups in `lt_sources` to avoid redundant map lookups.
- Preserve lazy loading of sections in `Region`, only loading and cloning sections that are actually read or written.
- Add `relight_single_block_bench` and update `relight_bench` to verify timings for both single-block and large batch edits.
2026-11-09 20:55:36 +02:00
Horizon agent 073e8db61c Merge remote-tracking branch 'origin/main' into rpn4-14216
# Conflicts:
#	crates/horizon-client/src/mobs/ai.rs
2026-11-09 19:55:31 +01:00
Horizon agentandClaude Opus 5.5 4787069c5b Sign sides: keep the first 4 valid lines, as SignText's codec does
Run against the 26.3 SignBlockEntity: an entry that fails is dropped
(ListCodec's partial) and Util.fixedSize keeps the first 4 lines of a
longer list with the colour and glow; only fewer than 4 valid lines load
the empty side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:54:19 +01:00
Horizon agentandClaude Opus 5.5 fa250c3c93 Sheep colour: read Color as Codec.BYTE does (byteValue)
DyeColor.LEGACY_ID_CODEC is Codec.BYTE: an int tag of 259 reads as byte 3
(light blue), not white.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:53:53 +01:00
DetimesandClaude Haiku 5.5 9f04ad5318 Native hooks: read the dedicated server's online mode, port and proxy forwarding
Mods can read whether a dedicated server runs in online mode, the port it
listens on and whether it takes its players from a Velocity proxy
(forwarding.secret). The values come from the live network config and
listening socket, so they match what the server does. None off a dedicated
server and before it listens. The forwarding secret is never returned.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 18:47:11 +00:00
itarqos5andClaude Sonnet 5.5 41d1c3adfe Tests: an observer ignores changes on the sides it does not face
`ObserverBlock.updateShape` reacts only when the direction to the changed neighbour is its
FACING. A change behind it, beside it, above it or below it starts no pulse.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 df7437d02b Tests: an observer pulses from two to four ticks after its faced side changes
`ObserverBlock.updateShape` schedules a tick two out when the block it faces changes; that tick
turns it on and schedules another two out, which turns it off. A lamp behind it is lit by the
pulse (`getSignal` answers 15 only for its facing); lamps in front of it, beside it and above it
are not.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 622eda982a Tests: tripwire hooks attach from two to forty-one blocks apart
`TripWireHookBlock.calculateState` scans `for i in 1..42` along the hook's facing for a hook
facing back and ends with `attached &= receiverPos > 1`: hooks attach 2 to 41 blocks apart and
never side by side or 42 apart. Both hooks are placed the way a player places them, because
vanilla runs the calculation from `setPlacedBy`, not from `setBlock`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 cdc8772455 Tests: a piston refuses the blocks that have a block entity
`PistonBaseBlock.isPushable` ends in `!state.hasBlockEntity()`, so a chest, furnace, barrel or
hopper ahead of a powered piston keeps it retracted and stays where it is.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 d289ee5de2 Tests: a piston pushes a retracted piston and refuses an extended one
`PistonBaseBlock.isPushable` answers false for a piston with EXTENDED set, so a push that meets
it fails and the pusher stays retracted, while a retracted one is pushed along. Both kinds.

The extended piston is held extended by a power source of its own, out of the pusher's reach:
unpowered it retracts on the tick, and that retraction updates the pusher, which then pushes it
(vanilla does the same; the first draft of this test asserted the wrong end state).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 3a5bc7ef94 Tests: glazed terracotta is pushed in line and never dragged sideways
26.3 gives `PushReaction.PUSH` to glazed terracotta alone, and `PistonBaseBlock.isPushable`
answers `direction == connectionDirection` for it: a slime block beside it cannot drag it, where
it drags an ordinary block, and in line with the push it moves like any other.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 7725516a3e Tests: slime and honey each drag their own kind and never each other
`PistonStructureResolver.canStickToEachOther`: a slime block drags slime and a honey block drags
honey, but a slime block and a honey block never stick to each other. Four pairings, each with
the block beside the one the piston faces either dragged or left where it was.

Built in open air: a slime block on stone drags the floor along too (vanilla's as well), which
would make the check about something else.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 577c82ffd3 Tests: a piston moves twelve blocks and refuses a thirteenth
`PistonStructureResolver.addBlockLine` refuses once `toPush` would hold
more than twelve blocks, and then the whole push fails: the piston stays
retracted, it does not move twelve of them. Pins 11 and 12 moving, with
the head where the first block stood, and 13 moving none.

The port matched vanilla; the ledger lists `PistonStructureResolver.resolve`
among the ported methods no parity harness covers.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
itarqos5andClaude Sonnet 5.5 401373bc22 Tests: the moving-piston tests of level/tests.rs get a file of their own
The five tests from `pistons_pop_fragile_blocks_and_refuse_obsidian` to
`replacing_a_moving_piston_leaves_its_extended_base` move, unchanged, to
level/tests/pistons.rs, beside the barrel and trigger suites that were split
out the same way. They are the piston tests that stood in the middle of a
4176-line file; the piston rules the next commits pin go in the same place,
so one file holds them. This takes 191 lines out of tests.rs.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:34:25 +00:00
Horizon agentandClaude Opus 5.5 272fcfa34c mace.rs: pass the borrowed stack as it is (clippy needless_borrow)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:27:53 +01:00
Horizon agent 1324281e8b Merge remote-tracking branch 'rv3n/14141' into rv3-fix-14141 2026-11-09 19:21:20 +01:00
Horizon agentandClaude Opus 5.5 997007191a Banner layers: leave out only the layer the codec rejects
TagValueInput.read returns the codec error's partial value, and DFU's list
codec keeps the valid elements as that partial (checked against
datafixerupper 10.0.21): vanilla keeps the other layers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:21:03 +01:00
voduffandClaude Opus 5.5 c93edbe286 Mobs: a promoted weaker Absorption clamps the amount to its maximum (#11384)
LivingEntity.onEffectUpdated(effect, true) runs when a hidden effect
instance is promoted, and its refreshDirtyAttributes clamps absorption
to the new max_absorption. Horizon clamped only when Absorption was
gone, so Absorption II's 8 survived the promotion of a hidden
Absorption I (max 4). tick_effects now clamps whenever the tick changed
max_absorption.

mob_absorption_max_corpus gains a promote case (494/494; main: 493/494).

Part of #11384

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:19:10 +00:00
Nikita Maximilian Grimm 2f1ad94bf7 Merge remote-tracking branch 'origin/main' into parity-process-tree 2026-11-09 19:12:43 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 a0f6aeafce pr_ready: the Windows check reaper is a daemon and holds its own process
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:10:00 +01:00
Horizon agentandClaude Opus 5.5 0d6c974c99 Merge main into #13839; graphics.md's HDR paragraph is main's plus this PR's sentence
Main rewrote the UI Brightness part of the HDR paragraph; this PR only added
the sentence that a shaders/ pack's picture is not lifted. Main's paragraph is
kept with that sentence inserted where the PR put it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:09:06 +01:00
iseaprojectsandopencode 91f580a2a2 Filter a moving cart's pushes by its teams' collision rules
`OldMinecartBehavior.pushAndPickupEntities` asks
`EntitySelector.pushableBy(this.minecart)` for what a moving rideable cart
pushes, so the cart's own team's collision rule and the target's both decide;
Horizon passed `None` for the cart's team on mobs and never filtered carts.
A still or unrideable cart keeps vanilla's else branch, which pushes every
pushable minecart with no team filter.

The per-candidate answer comes from `Game::cart_push_allowed` beside the
other team lookups; `pickup_from_cart` gets the cart's team from the same
`team_with_owner`. Two ignored tests on the real server game fixture cover
every collision rule over cart-to-cart pushes, the stationary branch, and a
cow the cart may not board.

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-09 14:07:58 -04:00
Nikita Maximilian Grimm 2ec731aadf Merge remote-tracking branch 'origin/main' into fix/command-exec-group-isolation 2026-11-09 19:06:02 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 de08483605 process_tree: a Windows check's exit ends what it left; close a job Popen never used
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:03:35 +01:00
MSedgeMC 9790d9d81c Merge remote-tracking branch 'upstream/main' into fix/weapon-damage-component 2026-11-09 18:02:49 +00:00
MSedgeMC 6a31935f68 Merge upstream/main 2026-11-09 18:00:32 +00:00
MSedgeMC 81b88d62be Merge upstream/main 2026-11-09 18:00:17 +00:00
MSedgeMC 4694211e8d Merge remote-tracking branch 'upstream/main' into fix/weapon-disable-blocking-component 2026-11-09 17:59:40 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 ace3563955 command_exec cleanup reaches the other levels in Horizon; groups shrink the cubes they kill last
A dying cube mob is out of every selector's reach and splits 20 ticks later, inside the next group, so
the three groups that end by killing their size-2+ sulfur cubes shrink them first. Horizon resolves an
@s of another level only from that level, so each level's cleanup runs in it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:59:32 +01:00
MSedgeMC ae0ab270ff Merge remote-tracking branch 'upstream/main' into fix/weapon-damage-component 2026-11-09 17:59:18 +00:00
Horizon agentandClaude Opus 5.5 28214f02a7 Move the perched-dragon test into the module that has dragon()
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:59:09 +01:00
Horizon agentandClaude Opus 5.5 7b74e2243b Merge main into #13726; ui.rs keeps both new edit box tests
insert_text auto-merged main's read-only guard with this PR's UTF-16 room;
main's read-only test and this PR's UTF-16 test were appended at the same
place, both kept whole.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:58:46 +01:00
MSedgeMC 0ff4404c9e Merge remote-tracking branch 'upstream/main' into fix/weapon-disable-blocking-component 2026-11-09 17:54:04 +00:00
Horizon agentandClaude Opus 5.5 5bb1789373 Name the test's Tag: dragon.rs's test module has no import of it
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:54:00 +01:00
MSedgeMC e865160f46 Merge remote-tracking branch 'upstream/main' into fix/weapon-damage-component 2026-11-09 17:53:42 +00:00
DUzzL b50a445987 Load a sign side empty unless messages has exactly 4 lines 2026-11-09 18:50:32 +01:00
MSedgeMC 16d4b2c348 fix: read the sheep colour through the saved tag
`Option::and_then` gives the closure the `&Tag`, not the option the save
helpers take; pass it through `Some` so the branch compiles.
2026-11-09 17:49:57 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 4c593f0ca7 Harnesses take what they started with them: games, servers and builds
A harness that exited or crashed left the rest of its process group running, and on Windows a parity.py or
pr_ready.py that died left its harnesses and their games running too (taskkill /T can't follow a dead parent).
tools/process_tree.py starts each harness in its own Job Object on Windows (KILL_ON_JOB_CLOSE, started suspended
so nothing escapes before it joins) and, on POSIX, kills the rest of its session's group once it exits, before
it is reaped. pr_ready.py runs its Windows checks the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:49:37 +01:00
iseaprojectsandopencode d413223251 Tick raids before natural and custom spawning
`ServerLevel.tick` runs `raids.tick` before `getChunkSource().tick`, so a
wave that lands in a tick joins before that tick's natural and custom
spawns and takes the lower entity ids. `tick_creatures` did the opposite:
natural spawning, then the custom spawners, then the raids.

The three phases move into `Game::tick_spawners`, in vanilla's order, each
with its own span; the LAN sync bracket still covers exactly them. A new
ignored test builds the real server game fixture, records spans and asserts
the phase order.

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-09 13:41:39 -04:00
Nikita Maximilian GrimmandClaude Opus 5.5 ac90e00807 command_exec group cleanup test: the zombie burned in daylight, it was not unloaded
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:37:25 +01:00
RLC248 d702f7cf60 A mace smash sends the attacker's motion after the hit
MaceItem.hurtEnemy resets the attacker's fall and sets its motion, and the
server sends that motion to the attacker in a ClientboundSetEntityMotionPacket
right after the hit. A LAN guest's PvP mace smash now sends the motion the
hit gave it, as it already did for mob hits. The server_knockback harness no
longer lists pvp-mace as a known difference.

Fixes #8246
2026-11-09 18:31:54 +01:00
rdbtCVSandClaude Sonnet 5.5 c7a360b9bb Merge main into fix/h194-item-count-predicate-2
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 17:28:42 +00:00
MSedgeMC f6a6dcc007 fix: drop needless borrows in the weapon disable paths 2026-11-09 17:24:58 +00:00
MSedgeMC 3df13bccbd port_map: the sheep's colour id follows the codec's out-of-bounds strategy
`tools/port_map/game-012.tsv` records `Sheep.readAdditionalSaveData`; its
`Color` read now goes through `mobs/farm.rs::saved_color`, which gives white
for an id the legacy codec does not know.
2026-11-09 17:23:00 +00:00
MSedgeMC 851627a847 test: an unknown sheep colour reads white
`mob_from_nbt` is what `Game::load_mob` goes through. A sheep with
`Color: 99b` loads with `extra.color == 0` (white), not the wrapped 3.

Without the codec bound the sheep loads light blue: `left: 3`, `right: 0`.
2026-11-09 17:23:00 +00:00
MSedgeMC 0a36da7779 fix: an unknown saved sheep colour reads white
`Sheep.readAdditionalSaveData` reads `Color` with
`DyeColor.LEGACY_ID_CODEC` and `orElse(DEFAULT_COLOR)`. The codec's id map is
`ByIdMap.continuous(..., OutOfBoundsStrategy.ZERO)`, so an id outside 0..=15
reads as the first colour, white.

Horizon masked the id with `& 15`: a saved `Color: 99b` became light blue (3)
instead of white, and a negative id became a wrapped colour the sheep never
had.

The read now accepts only 0..=15 and gives white for anything else, in
`mobs/farm.rs::saved_color` beside the sheep's other colour code.
2026-11-09 17:23:00 +00:00
MSedgeMC 8f2b122754 port_map: the dragon's sitting damage is read back
`tools/port_map/game2-001.tsv` recorded `EnderDragon.readAdditionalSaveData`
with a gap: `sitting_damage_received` was not read. The row now says
`Dragon::from_nbt` reads it with `getFloatOr`, 0 when absent.
2026-11-09 17:22:03 +00:00
MSedgeMC cbd47615bc test: a perched dragon's stored damage survives the chunk save
`Dragon::to_nbt`/`Dragon::from_nbt` are the pair the dragon's chunk entity
uses. A perched dragon with `sitting_damage = 12.5` saves
`sitting_damage_received: 12.5f` and `from_nbt` gives 12.5 back. A compound
with no such key loads 0.0.

Without the read the reloaded dragon has 0.0: `left: 0.0`, `right: 12.5`.
2026-11-09 17:22:03 +00:00
MSedgeMC 04822910b5 fix: a perched dragon keeps its saved damage through a reload
`EnderDragon.addAdditionalSaveData` writes `sitting_damage_received` (the
damage a perched dragon has taken since it sat down, which makes it take off
at a quarter of its health), and `readAdditionalSaveData` reads it back with
`getFloatOr("sitting_damage_received", 0)`.

Horizon wrote the field in `Dragon::to_nbt` but `Dragon::from_nbt` ignored it:
a perched dragon saved after some damage but before taking off reloaded with
`sitting_damage` 0 and had to be hit for the whole quarter again.

`Dragon::from_nbt` now reads the float, 0 when absent, as vanilla does. The
health read is folded into one line so the over-3000-line file does not grow.
2026-11-09 17:22:03 +00:00
MSedgeMC 9e68efc05b port_map: the destroy-progress stage and the daylight ticker rows are ports
`guest_dig_feedback` sends `(int)(progress * 10)`, the stage
`incrementDestroyProgress` computes, and `tick_daylight_detector` gates on
the dimension type's sky light, so the End is excluded like the Nether.
Both rows still described the old gaps.
2026-11-09 17:19:46 +00:00
rdbtCVSandClaude Sonnet 5.5 b8ceaa3ed4 Merge main into fix/h211-shulker-drop-lock-2
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 17:09:21 +00:00
Nikita Maximilian Grimm 070902e9f5 Merge remote-tracking branch 'origin/main' into fix/command-exec-group-isolation 2026-11-09 18:00:50 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 6c4df147a7 command_exec removes what each group leaves alive before the next group
Groups share one world, so an entity a group left stayed visible to later groups' unbounded selectors.
The bell group's persistent zombie burned in daylight and died at a random tick in each engine, which
made the entities group's PersistenceRequired check flaky. The harness now kills, between two groups,
the non-player entities above the groups' floor (y 100 in the overworld, 128 elsewhere), shrinking
cube mobs first and killing twice so drops go too. World-generated entities below stay out of it.
The wolf anger clock diagnostic continues the group before it and is named in CONTINUES_PREVIOUS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:59:59 +01:00
Horizon agentandClaude Opus 5.5 3f044a9aca The command harness records only what a command's own broadcastChanges announced
run_command checks InventoryChangeTrigger after every command; vanilla's
/loot give calls no broadcastChanges, so its Diamonds! comes on the
player's next tick, outside the command's record (inline_loot_reference).
/item replace on a player marks what its own check announced
(cmds.broadcast_announced); the harness records those and leaves the
rest for the tick.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:57:19 +01:00
Horizon agentandClaude Opus 5.5 e749b17104 mob_attacks_mob and the hit catch-up move to combat.rs: creatures.rs may not grow
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:44:46 +01:00
Horizon agentandClaude Opus 5.5 1340e54376 cargo fmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:23:08 +01:00
Horizon agentandClaude Opus 5.5 3925efc44e adapter_requested_split: the same rule in the lines it had
gfx.rs is over 3000 lines and may not grow (tools/check_file_size.py).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:10:40 +01:00
Horizon agentandClaude Opus 5.5 fb7b0f4ca3 mobs.rs and goals.rs don't grow: two helpers move out
totem_death_effects goes to mobs/living.rs (LivingEntity.checkTotemDeathProtection), and
RandomPos.moveUpToAboveSolid to mobs/random_pos.rs. Pure moves; no behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:03:47 +01:00
MSedgeMC f8599e2685 Disable-blocking seconds come from a stack's weapon component
LivingEntity.getSecondsToDisableBlocking reads
Weapon.disableBlockingForSeconds. Horizon read the prototype's value, so a
patched weapon disabled a shield for 0 seconds instead of its own.

Test: a diamond sword with disable_blocking_for_seconds 1.5 reports 1.5.
2026-11-09 16:00:10 +00:00
MSedgeMC 02a8a61de4 Weapon wear comes from a stack's weapon component
ItemStack.postHurtEnemy uses Weapon.itemDamagePerAttack from the stack's
component. Horizon read the item prototype's weapon damage, so a patched
weapon wore 0 or the prototype's amount instead of its own.

Test: a diamond sword with item_damage_per_attack 3 wears 3 per hit.
2026-11-09 16:00:01 +00:00
Horizon agentandClaude Opus 5.5 c80f0361be Projectiles: put shoot_own's doc comment back on shoot_own
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:49:12 +01:00
Horizon agentandClaude Opus 5.5 c08d2b301e Merge origin/main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:49:12 +01:00
MSedgeMC 6a68afa6cc A banner with an invalid layer loads no patterns
BannerPatternLayers.CODEC reads its layer list all or nothing: one layer the
codec rejects leaves the empty layer list. Horizon skipped only the bad layer,
so a banner kept the layers before it.
2026-11-09 15:32:06 +00:00
Horizon agent 3c5c7d6077 Merge remote-tracking branch 'origin/main' into fix-11484
# Conflicts:
#	crates/horizon-client/src/game/nether_portal.rs
2026-11-09 16:31:19 +01:00
Horizon agentandClaude Opus 5.5 f3b08a0988 Merge main into #12156
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:27:21 +01:00
Horizon agentandClaude Opus 5.5 5171e9c09c Breed: a panicking partner is refused and stops the goal
The snapshot carried the panic state but Breed never read it:
getFreePartner skips a panicking partner and canContinueToUse ends the
goal when the partner panics. The test only skipped on CI (no prepared
resources), so it looked green without the check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:23:17 +01:00
Horizon agent 871fb3a448 Merge main into the breed panic fix 2026-11-09 16:23:09 +01:00
Horizon agent d93a9a4be4 Merge remote-tracking branch 'origin/main' into fix-11536 2026-11-09 16:21:50 +01:00
Horizon agentandClaude Opus 5.5 2b6aed3dc7 Leave the other harnesses' work folders as on main
A run- folder per invocation under .local/<harness>/ is never removed by runner-gc (it only
looks one level down), and these four harnesses aren't this fix's. Main's harness fixes own them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:21:48 +01:00
Horizon agentandClaude Opus 5.5 53d1d825ee Leave the file-size check's CI change to #13882
The same fix (compare with the main the pull request lands on) is open as #13882. A change to
.github/ also keeps a fork's runs from being approved automatically, so this branch got no parity.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:14:35 +01:00
Horizon agent 6db95ffc1e Merge remote-tracking branch 'origin/main' into fix-11536 2026-11-09 16:14:15 +01:00
Horizon agentandClaude Opus 5.5 5ae9f06129 cargo fmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:06:26 +01:00
Horizon agentandClaude Opus 5.5 13061c109f lan_bot: the record is the guest's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:41:16 +01:00
Horizon agentandClaude Opus 5.5 40eb5c7fd7 Record: the teleport's restart reads the guest's record
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:40:35 +01:00
Horizon agentandClaude Opus 5.5 04a8acc5a3 Movement prediction: the client-tick record moves from horizon-anticheat into the engine's replay
Layer plan M6, step toward dropping horizon-client-lib -> horizon-anticheat. The record
(horizon_anticheat::prediction) is what the engine's movement replay (lan::prediction) plays again:
it moves to lan/prediction/record.rs unchanged. The guest holds it and the client's sprint
(was Player.record / Player.sprinting). Behaviour unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:32:06 +01:00
Horizon agentandClaude Opus 5.5 add5b203c6 A hoglin hits from its fight activity, 41 ticks apart
HoglinAi.updateActivity runs after the brain, so a hoglin given an attack
target enters the fight activity at the end of that tick and its
MeleeAttack hits from the next one: the goal now acts only in the fight
activity (brain_step runs after the goals). MeleeAttack.create(40) sets
ATTACK_COOLING_DOWN for 40 brain ticks and MemorySlot.tick erases it on
the 41st, so hits come 41 ticks apart (16 for a baby).

A hit one mob's tick deals another is handled after the mob loop, after
the target's own tick; vanilla deals it inside the attacker's tick, so a
target later in the list counts HurtTime and its damage cooldown down
once more that tick. The pig hit by a hoglin read HurtTime 10 on the tick
of the hit; vanilla's reads 9.

hoglin_repeat_attack reports its rand- rows instead of comparing them:
each hit is attack / 2 + level.getRandom().nextInt(attack), and
Level.random is RandomSource.create(); two vanilla runs disagree on the
pigs' Health.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 14:05:50 +01:00
Horizon agentandClaude Opus 5.5 a93975ceb5 An allay stays on its pickup cooldown at 0; /item replace triggers inventory_changed
CountDownCooldownTicks keeps ITEM_PICKUP_COOLDOWN_TICKS while it counts
down and erases it the tick after it reached 0 (stop), and
Allay.isOnPickupCooldown is the memory's presence: an allay loaded with
{value:30} saves {value:0} on its 31st tick, then nothing. ints[3] now
holds the value plus one (allay::pickup_cooldown).

EntityItemAccessor calls containerMenu.broadcastChanges for a player
whose slots /item replace changed, so InventoryChangeTrigger (here the
Diamonds! announcement) comes before the command's message. The command
harness now announces what a command earned before its feedback, as a
guest's command does (announce_guest_advancements); it left the
announcement for the next tick, outside the command's record.

allay_pickup_cooldown reports its rand- rows instead of comparing them:
the natural allay's flight starts at its first item scan
(Sensor.randomlyDelayStart with the allay's own random, which is
RandomSource.create()), and two vanilla runs of the script disagree on
those 30 rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 14:05:01 +01:00
Horizon agentandClaude Opus 5.5 3ef15455e3 command_exec reads the zombie villagers' random profession only where it is not random
ZombieVillager.defineSynchedData picks the profession with
VILLAGER_PROFESSION.getRandom(this.random), and Entity.random is
RandomSource.create(): the first two subjects' profession:none check
passed 1 time in 15 on either side, so 'zombie villager summoned data'
matched 9/10 from run to run. The third subject's profession comes from
its save and stays checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:49:15 +01:00
Horizon agentandClaude Opus 5.5 cef8682971 Drop the item count fixture nothing runs
Its name matches no harness pattern; test_command_exec_parity.py --only
"item count predicate" already compares the group with vanilla.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:44:27 +01:00
Horizon agentandClaude Opus 5.5 67d694dd9c shulker_lock_drop runs by name only
It needs --work-dir and --reference-dir, which an automatic parity run
doesn't pass, so without the named_only entry it fails at startup on
every pull request that selects it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:43:10 +01:00
Horizon agentandClaude Opus 5.5 7b25b8ed80 Sculk reload particle: interpolate in doubles as vanilla does
VibrationSystem.Ticker.tryReloadVibrationParticle computes alpha as a double.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:35:18 +01:00
Florian Ernst c2e4f28c3f Start CI again: the previous run stayed queued with no jobs 2026-11-09 13:25:01 +01:00
Florian Ernst 8e26753cda Start CI again: the previous run stayed queued with no jobs 2026-11-09 13:24:59 +01:00
Horizon agentandClaude Opus 5.5 ec08a90d43 invulnerable_time compares a mob's attributes list unordered
AttributeMap.pack lists the instances in the iteration order of an
Object2ObjectOpenHashMap keyed by Holder.Reference, which keeps
Object.hashCode: an identity hash. The same script run under another
main class saves the pig's list in another order, so the oracle's
order is the JVM's, not the game's. All 11 differences on main were
that order. The driver gets unordered_attributes(), which sorts the
entries of every attributes list in a record and keeps their text and
styles; the harness compares through it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:22:31 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 32c375e0ae HDR output: a shaders/ pack's alpha isn't lifted as light-source marks
With HDR on and a shaders/ (OptiFine/Iris format) pack running, the last
pass read the alpha the pack's final program leaves in the frame as
Horizon's light-source marks and lifted those pixels above paper white.
A pack that leaves alpha below 0.75 had most of its picture brightened as
if it were torches or lava, and HDR Lighting turned that on and off.

Horizon doesn't light the world under such a pack (HDR lighting is
already off there), so the lift is now off too: the pack is shown at
paper white, as a 0.2 pack is. The decision moves into a small pure
function in gfx/output.rs with a unit test. HDR off doesn't change.

Fixes #13807.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:11:02 +01:00
RINNECODERandClaude Opus 5.5 e31eeeb2bc Boats and minecarts more than 64 blocks under the world are discarded
Entity.checkBelowWorld runs in AbstractBoat.tick (through Entity.baseTick,
after the fire) and in AbstractMinecart.tick (after its hurt and damage wear
off), before either moves: under the level's floor minus 64, onBelowWorld
discards it. Horizon had no such check for vehicles, so a boat or minecart
that fell out of the world kept falling for ever (#8024 measured one at
y -243 where vanilla had removed it by tick 33).

The discard ejects the mob riders where they are and spills a chest boat's or
container minecart's slots (AbstractChestBoat.remove,
AbstractMinecartContainer.remove), with no ENTITY_DIE and no vehicle item.
The logic lives in game/boats/below_world.rs; minecarts.rs keeps its size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 05:41:46 -06:00
voidsip edfe18495e Keep reputation damage and visibility helpers in focused modules 2026-11-09 05:35:03 -06:00
voidsip 8ede2ff197 Keep potion sound regression in its own module 2026-11-09 05:22:24 -06:00
voidsip f1696089ef Merge commit 'b25a050be818408360d7cf97956350212dda0686' into fix/11329-villager-reputation-events
# Conflicts:
#	crates/horizon-client/src/game/creatures.rs
#	crates/horizon-client/src/game/native_hooks.rs
2026-11-09 05:20:13 -06:00
voidsip a4925a7954 Merge commit 'b25a050be818408360d7cf97956350212dda0686' into fix/11336-potion-contents 2026-11-09 05:19:15 -06:00
voidsip 085b4109e3 Merge commit '3690aa6119b9235be7e3b79680c156da8979479b' into fix/11336-potion-contents 2026-11-09 05:19:05 -06:00
voidsip 4a6942b8e9 Merge commit '3690aa6119b9235be7e3b79680c156da8979479b' into fix/11329-villager-reputation-events 2026-11-09 05:18:51 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 08d02c752f Format the shot calls that lost their random argument
A projectile added keeps an earlier UUID for its id (a client copy's from the
spawn packet) through or_insert again, so the client copy needs no reset.

Part of #12561

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 12:13:18 +01:00
Nikita Maximilian Grimm 31edfa94fb Merge remote-tracking branch 'origin/main' into parity/sulfur-cube-bucket-health 2026-11-09 12:07:49 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 3a35efafa8 Keep a loaded sulfur cube's saved Health in its own load
entity_nbt.rs may not grow (over 3000 lines), so the sulfur cube's own load
re-reads its saved Health after sizing it instead of the living load
skipping the Health Boost clamp: the result is the same, the clamp to the
unsized maximum no longer sticks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 11:57:18 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 916b481669 Size a loaded sulfur cube before its Health Boost clamp
The living load refreshed a Health Boost holder's maximum and clamped its
Health before sulfur_cube::from_nbt sized it, so a size-3 cube saved with
Health 12 under Health Boost dropped to the constructor size's 8. Vanilla
sizes the cube (AbstractCubeMob.readAdditionalSaveData) before
LivingEntity's setHealth; its own load now sets the maximum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 11:44:42 +01:00
Nikita Maximilian Grimm 8db4b7bc14 Merge remote-tracking branch 'origin/main' into projectile-uuid-draws 2026-11-09 11:37:10 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 b5fd8221fc Keep a loaded projectile's UUID through Projectile::own_uuid
The loads take the own random's UUID through one helper, so persist.rs and
creatures.rs keep their size. A client copy drops its own random's UUID: the
spawn packet's, kept before it is added, wins.

Part of #12561

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 11:37:08 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 2ba5206ba9 A sulfur cube saves its size's max_health and movement_speed
SulfurCube.setSize sets the max_health (4 per size) and movement_speed
(0.2 + 0.1 * size) attribute bases, so every load, spawn, split and bucket
release leaves both instances to save. Horizon's set_size wrote the cached
values only: the save held no max_health, and from the first tick a
movement_speed of the type's 0.7, which a reloaded cube then moved at.
set_size now records the bases (the spawn path did that alone before), the
load applies saved bases after the size as LivingEntity does, and Health
Boost changes refresh a sulfur cube's maximum like any model-owned one.

Fixes #13801

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 11:26:12 +01:00
Florian ErnstandClaude Opus 5.5 1efd1c20c9 Keep game.rs from growing: Pending::record_from reads name and lock
The file-size check (docs/layers.md#file-size) does not let a file over
3000 lines grow. Breaking a block entity and dropping its resources both
read the custom name and lock from the world, so a helper does it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 10:52:54 +01:00
Florian ErnstandClaude Opus 5.5 d8c00ad64e Keep commands.rs from growing: count matcher and tests in their own files
The file-size check (docs/layers.md#file-size) does not let a file over
3000 lines grow. The count bounds matcher moves to commands/item_count.rs
and the ignored test module to game/item_count_predicate_tests.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 10:52:21 +01:00
Florian ErnstandClaude Opus 5.5 e2f472508d Preserve external locks on destroyed shulker boxes
Squashed and rebased onto main from #11627.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 10:01:28 +01:00
Florian ErnstandClaude Opus 5.5 38060a67ba Match item count equality against the actual stack
Squashed and rebased onto main from #11658.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 10:01:28 +01:00
DUzzL a48be025f1 Skip item wear for unbreakable stacks 2026-11-09 09:59:02 +01:00
LokiandAntigravity 6c199da5f6 sculk: resume vibration particle on reload (fixes #12935)
Co-Authored-By: Antigravity <[email protected]>
2026-11-09 17:46:05 +09:00
MSedgeMC f65d12322e A pad guide reads a stack's equippable slot and swappable flag
The controller guide offers Equip only when Equippable.swapWithEquipmentSlot
applies: the stack's slot is an armour slot and swappable is true. Horizon
read the item prototype for both.

Test: a helmet patched swappable:0b no longer offers Equip, and its patched
slot is used.
2026-11-09 08:43:41 +00:00
Tran Anh Van c4a108b5c3 Keep original f64 PI constant in rod_hand_position 2026-11-09 15:36:22 +07:00
Tran Anh Van 4628acd092 Restore original PI constant type in rod_hand_position 2026-11-09 15:29:29 +07:00
RINNECODERandClaude Opus 5.5 65b8c76509 Boats: Mth's sine table for steering and dismounts, and lastYd for water entry
Boat steering, a boat rider's dismount vector and a minecart rider's push
used the platform's sine and cosine, where vanilla uses `Mth`'s 65,536
entry table, so a boat paddled at most yaws drifted from vanilla's path
(about 1e-4 of the push per tick). They now go through
`horizon_core::geometry::trig`, as `AbstractBoat.controlBoat`,
`Entity.getCollisionHorizontalEscapeVector` (reusing the mounts port)
and `Entity.getInputVector` do. The dismount also uses vanilla's float
products: the boat's width times `Mth.SQRT_OF_TWO`, the 1.0E-5F margin and
the player's 0.6F width.

`getWaterLevelAbove` scans from the hull's top up to
`ceil(maxY - lastYd)`, where `lastYd` is the boat's vertical velocity at
its last `checkFallDamage` (before collisions zero it); Horizon scanned
only the hull top's own row, so a boat falling fast into deep water could
pick another surface height.

Fixes #11381

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 02:26:58 -06:00
Tran Anh Van 71cf748116 Show other players' fishing rods as cast while their bobber is out
When drawing held items for non-local entities in held_item_geometry,
set fishing_cast_with_this_item from the remote hooks' active owner
state and the holding hand (with the main hand taking precedence when
both hold fishing rods), matching FishingRodCast and FishingHook's
client owner tracking.
2026-11-09 15:24:37 +07:00
MSedgeMC 86d2c0d5cd Edit box test expectations count the maximum in UTF-16 units
The two native text field replacement tests pinned the old character count:
a maxLength of 4 kept four code points and one of 3 kept three. EditBox's
maxLength is Java String.length(), so the emoji takes two of them: 4 units
keep "a😀b" and 3 keep "a😀", which is what vanilla's setValue truncation
leaves.
2026-11-09 08:20:36 +00:00
MSedgeMC 9523592a93 An edit box's maximum length counts UTF-16 code units, as Java's does
EditBox.maxLength caps Java `String.length()`: UTF-16 code units, so a
character outside the BMP takes two of them. Horizon measured the limit in
Rust chars (code points) in both edit box ports, so a chat box with a maximum
of 256 accepted 256 emoji where vanilla accepts 128, and a pasted emoji could
take a place the next character should have been refused.

`ui::EditBox` (the screens' field) and `screen_draw::TextField` (the chat box
and the native screen API's field) now measure the maximum in UTF-16 units and
keep whole characters, which is the prefix vanilla's insertText keeps after
its half-surrogate guard drops the split one.
2026-11-09 08:03:43 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 412e1a72c9 A projectile shoots with its own random after its UUID's draws
Vanilla's Entity makes its UUID from the first two draws of its own random
(Mth.createInsecureUUID), and Projectile.shoot spreads the shot with that same
random, from which an arrow keeps drawing (AbstractArrow.setBaseDamageFromMob,
its later rolls). Horizon shot dispensed, crossbow and mob projectiles with a
fresh random that never drew the UUID, player throws with the level's random,
gave an arrow's later draws a random of their own, and gave projectiles a
clock-seeded UUID when first asked.

An arrow now makes its own random in Projectile::new and draws its UUID first;
another kind makes it at the shot (shoot_own), the same stream since nothing
draws between. Every shot goes through shoot_own, the arrow keeps the random,
and the skeleton's base damage comes from it. add_projectile keeps the UUID; a
player's trident takes its shot's. Loaded and summoned projectiles take their
own random's UUID unless the tag has one.

The seed sync proof reads a dispensed arrow's and snowball's UUID and Motion
and a summoned arrow's UUID: 25/30 on main, 30/30 with this.

Part of #12561

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 05:21:24 +01:00
voidsip 42b04e0238 Update reputation damage and guest fixtures for main 2026-11-08 20:23:13 -06:00
voidsip b37b703f1c Run portal cooldown proof in a scratch game directory 2026-11-08 19:19:22 -06:00
voidsip 94cad99398 Merge commit 'f858ee752f1c0e76b6d200ec846645532536aded' into fix/11336-potion-contents 2026-11-08 18:41:12 -06:00
voidsip d7dc5628e2 Merge commit 'f858ee752f1c0e76b6d200ec846645532536aded' into fix/11329-villager-reputation-events 2026-11-08 18:38:26 -06:00
voidsip 8b45d15486 Merge commit 'f858ee752f1c0e76b6d200ec846645532536aded' into fix/11318-portal-cooldowns 2026-11-08 18:38:26 -06:00
voidsip e8f93ffc67 Merge main into villager reputation fix 2026-11-08 18:38:25 -06:00
voidsip 2e0f86f312 Merge main and preserve entity portal cooldown phases 2026-11-08 18:38:25 -06:00
voidsip 167caf28d0 Merge commit '976346aff5bfa09c6d8e364c347bdf1791618a98' into fix/11336-potion-contents 2026-11-08 18:13:04 -06:00
Riccardo GuerrieroandClaude Opus 5.5 2485e58daa Merge origin/main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 22:50:33 +01:00
MSedgeMC 555ab73579 Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	crates/horizon-client/src/mobs/goals.rs
2026-11-08 15:19:47 +00:00
Horizon agentandClaude Opus 5.5 f4c1e560e8 Drop the .analysis scratch files
They are a local analysis's inputs and outputs, not part of the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 13:28:19 +01:00
MSedgeMC fcfec5fe13 A breeding animal stops when its partner panics
`BreedGoal.getFreePartner` drops a panicking partner and
`BreedGoal.canContinueToUse` requires `!partner.isPanicking()`. Horizon's
`Breed` neither snapshotted the panic state nor tested it, so a pair kept
breeding after one of them started panicking.
2026-11-08 12:26:50 +00:00
voidsip 36bad2c06e Give parity harnesses fresh default capture directories 2026-11-07 20:35:20 -06:00
voidsip 7c7bca2e7b Update potion fixture for silent impact argument 2026-11-07 20:35:19 -06:00
voidsip 58552b8cb9 Merge commit 'bc6016d19d4dd6f11f6b954fc3b121546f069ffb' into fix/11336-potion-contents 2026-11-07 20:25:35 -06:00
RINNECODERandClaude Opus 5.5 61127ad12d Block sprites: on Metal the arrays grow past 512 layers when the sprites need it
Metal keeps 512 layers per sprite array, so the 8 arrays terrain.wgsl binds
hold at most 4096 block textures and a set with more (10,271) was refused
at startup. The split now grows to fit the arrays (up to the GPU's limit
per array) only when the textures need it; up to 4096 it stays 512, as
before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:26:09 -06:00
b064c12aca Let sculk hear item frame changes
Post BLOCK_CHANGE at the frame from ItemFrame.interact, hurtServer and
dropItem, after the changes and drops vanilla performs first. Preserve
BlockAttachedEntity.kill ordering and discard unsupported frames without
a spurious ENTITY_DIE.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
2026-11-07 21:18:13 +01:00
Horizon agentandClaude Opus 5.5 959a89ef67 Merge origin/main into #11559
/damage: keeps this branch's villager reputation flush after a hurt and
main's enderman teleport settle (they act on different mobs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:51:59 +01:00
Horizon agentandClaude Opus 5.5 1cf0e13b61 Merge origin/main into fix/11329-villager-reputation-events
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:05:20 +01:00
Horizon agentandClaude Opus 5.5 37541674a9 Merge origin/main into fix/11336-potion-contents
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:04:25 +01:00
Horizon agentandClaude Opus 5.5 18e0854d00 Merge main into fix/11329-villager-reputation-events
Main split projectile_hit into a wrapper and projectile_hit_inner: the
reputation flush now runs in the wrapper after the inner hit. Trident and
wind charge hits keep both the reputation flush and main's absorbed-damage
and post-attack calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:09:28 +01:00
Horizon agentandClaude Opus 5.5 04914f8c33 Merge main into fix/11336-potion-contents
Keep both sides of the potions.rs test modules; the contents fixture passes
the impact motion that main's splash now takes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:07:05 +01:00
Horizon agentandClaude Opus 5.5 c2a2fe370f Skip entities outside a gateway before the per-id lookups
entity_portal_delay walks every entity list; it ran for every item, mob,
boat, cart and pearl in the End each tick.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:01:48 +01:00
voidsip 65d35f3261 Initialize configuration history for reputation test guests 2026-11-06 22:02:27 -06:00
voidsip b4dea2a473 Merge commit '77936bf4bee3ec7d641f54b97a3da09f9b72e213' into fix/11329-villager-reputation-events 2026-11-06 21:52:56 -06:00
voidsip bfa20f0413 Initialize upstream native command fields in reputation fixture 2026-11-06 21:31:46 -06:00
voidsip 05c7788a8f Merge commit '41944ed91474c6af28572d2e2273b6b2bd0bcf1e' into fix/11329-villager-reputation-events 2026-11-06 21:22:00 -06:00
voidsip 35ab895667 Validate villager reputation with isolated game and vanilla fixtures 2026-11-06 19:47:29 -06:00
voidsip 178a2bf8b4 Correct isolated potion fixture admission and default invocation 2026-11-06 18:36:13 -06:00
voidsip 673a2515e8 Add stock-compatible accepted-hurt regression fixture 2026-11-06 17:55:03 -06:00
voidsip 93d57cf58c Validate potion components with isolated vanilla methods 2026-11-06 17:52:39 -06:00
voidsip 4f935ae226 Use the standard prepared resource path in the focused harness 2026-11-06 17:28:28 -06:00
voidsip 8eba763b33 Keep legacy cooldown fixture type explicit 2026-11-06 17:14:40 -06:00
voidsip 85029c85e5 Verify portal counters without starting a server 2026-11-06 17:14:13 -06:00
voidsip e08699893a Merge current main into villager reputation fix 2026-11-06 16:15:57 -06:00
voidsip b714d73e46 Deliver villager reputation from accepted damage sources 2026-11-06 16:13:29 -06:00
voidsip 72cd6e42ee Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11336-potion-contents 2026-11-06 16:13:16 -06:00
voidsip 9baf83e129 Fix thrown potion stack components and arrow expiration 2026-11-06 16:13:02 -06:00
voidsip 2d04344265 Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11318-portal-cooldowns 2026-11-06 16:12:27 -06:00
voidsip 226e365523 Use entity-specific portal cooldowns and preserve live counters 2026-11-06 16:12:12 -06:00
voidsip bcc1264dff Share identity-aware merchant price refresh helpers 2026-11-06 15:33:49 -06:00
610 changed files with 28768 additions and 5124 deletions

No files matched your search

+12 -12
View File
@@ -1,16 +1,16 @@
# Changes to these files wait for Ludovic's review once branch protection requires code owners' reviews
# Changes to these files wait for a council member's review (council poll P35, 2026-11-10) once branch protection requires code owners' reviews
# (tools/ci/protect_pipeline.sh, docs/security.md). They are what builds, signs and ships releases, the code that
# checks downloads before installing them (backend.rs downloads, installs and updates the launcher itself; links.json
# says where from; the Cargo.toml files pick the crates that do it), and this file. Everything else merges as soon as
# `verify` passes.
/.github/ @ludovic111
/tools/ci/ @ludovic111
/tools/release_train.py @ludovic111
/crates/horizon-release-sign/ @ludovic111
/crates/horizon-server/src/update.rs @ludovic111
/crates/horizon-server/Cargo.toml @ludovic111
/launcher/src/signed.rs @ludovic111
/launcher/src/backend.rs @ludovic111
/launcher/links.json @ludovic111
/launcher/Cargo.toml @ludovic111
/packaging/ @ludovic111
/.github/ @horizon-rust/council
/tools/ci/ @horizon-rust/council
/tools/release_train.py @horizon-rust/council
/crates/horizon-release-sign/ @horizon-rust/council
/crates/horizon-server/src/update.rs @horizon-rust/council
/crates/horizon-server/Cargo.toml @horizon-rust/council
/launcher/src/signed.rs @horizon-rust/council
/launcher/src/backend.rs @horizon-rust/council
/launcher/links.json @horizon-rust/council
/launcher/Cargo.toml @horizon-rust/council
/packaging/ @horizon-rust/council
-7
View File
@@ -32,13 +32,6 @@
<!-- The vanilla classes and methods this follows (tools/rea_vanilla.py), and the harness that checks it.
"Horizon-only" for a feature vanilla doesn't have; "none" for tooling or docs. -->
## Other projects' code
<!-- "none", or for each project you read or copied from: its link at the commit, its license (only MIT,
BSD-2-Clause, BSD-3-Clause, Apache-2.0, ISC, zlib, 0BSD, MIT-0, Unlicense or CC0-1.0), and what you took.
CONTRIBUTING.md "Only original code". Shader packs: also the sections of docs/cleanroom/shader-packs-spec.md,
the documentation pages and the packs you used. -->
## Self-check
<!-- Paste the block `python3 tools/pr_ready.py` prints (`--base upstream/main` from a fork). -->
+10 -360
View File
@@ -40,7 +40,7 @@ jobs:
${{ vars.SELF_HOSTED_CI != 'off' && vars.SELF_HOSTED_CI != 'light' && (vars.SELF_HOSTED_CI == 'all' ||
github.event_name == 'pull_request' && (endsWith(format('{0}', github.event.pull_request.number), '0') ||
endsWith(format('{0}', github.event.pull_request.number), '1'))) &&
fromJSON('["self-hosted", "linux", "horizon-checks"]') || 'ubuntu-latest' }}
fromJSON('["self-hosted", "linux", "horizon-checks"]') || 'ubuntu-24.04' }}
timeout-minutes: 45
steps:
- uses: actions/checkout@v7
@@ -119,22 +119,22 @@ jobs:
if: steps.rust.outputs.required != 'false'
run: |
cargo +stable fmt --all -- --check
cargo +stable clippy --workspace --all-targets -- -D warnings
cargo +stable clippy --workspace --all-targets --locked -- -D warnings
# The server build (released as horizon-engine): the game without sound or controllers.
cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings
cargo +stable clippy -p horizon-client --all-targets --locked --no-default-features -- -D warnings
# Libraries, binaries and integration tests, then doc tests: not the ~275 examples, which clippy above already
# type-checks and the parity job builds and runs (they were most of this step's build and link time).
# cargo test, not nextest: nextest's process per test reloads each binary's shared tables for every test, and on
# cargo test --locked, not nextest: nextest's process per test reloads each binary's shared tables for every test, and on
# these 4-core runners it was no faster (#4978).
- name: Test Rust core and voxel kernel correctness
if: steps.rust.outputs.required != 'false'
run: |
cargo +stable test --workspace --lib --bins --tests
cargo +stable test --locked --workspace --lib --bins --tests
# The full content-root tests (#[ignore]d: minutes each on a laptop). The same build as above; they need the
# prepared vanilla data, so without it they pass at once. Keep the target selection identical to avoid
# recompiling the workspace with a different dependency graph.
cargo +stable test --workspace --lib --bins --tests mod_content::tests:: -- --ignored
cargo +stable test --workspace --doc
cargo +stable test --locked --workspace --lib --bins --tests mod_content::tests:: -- --ignored
cargo +stable test --locked --workspace --doc
# The launcher is its own workspace (launcher/Cargo.toml), so verify's cargo runs never build it. A pull request that
# changes it or a crate it builds is checked here, and so is every push to main: two pull requests can each pass
# alone and break it together (#2059 and the registry ratings did, 2026-10-26).
@@ -143,7 +143,7 @@ jobs:
${{ vars.SELF_HOSTED_CI != 'off' && vars.SELF_HOSTED_CI != 'light' && (vars.SELF_HOSTED_CI == 'all' ||
github.event_name == 'pull_request' && (endsWith(format('{0}', github.event.pull_request.number), '0') ||
endsWith(format('{0}', github.event.pull_request.number), '1'))) &&
fromJSON('["self-hosted", "linux", "horizon-checks"]') || 'ubuntu-latest' }}
fromJSON('["self-hosted", "linux", "horizon-checks"]') || 'ubuntu-24.04' }}
timeout-minutes: 45
steps:
- uses: actions/checkout@v7
@@ -313,358 +313,8 @@ jobs:
head: ${{ github.event.pull_request.head.sha }}
full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
frame_identity: ${{ contains(github.event.pull_request.labels.*.name, 'frame-identity') }}
# Horizon never downloads the game. These jobs need a self-hosted Linux runner
# (label horizon-game) holding the maintainer's own copy: the official launcher's
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
# HORIZON_SERVER_JAR. Start them by hand: gh workflow run checks --ref <branch>.
vanilla-parity:
if: github.event_name == 'workflow_dispatch'
runs-on: [self-hosted, linux, horizon-game]
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.12'
- name: Install Rust toolchain
run: rustup toolchain install stable --profile minimal
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: '25'
- name: Compare Rust foundations with pinned vanilla client and server bytecode
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_rust_parity.py --prepare
- name: Check Rust world-data interoperability with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_world_parity.py
- name: Compare scheduled ticks and saved tick data with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_tick_parity.py
- name: Compare simulation geometry and cached block collision shapes
env:
RUSTUP_TOOLCHAIN: stable
run: |
python tools/test_geometry_parity.py
python tools/test_collision_parity.py
- name: Compare noise samplers and density kernels with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_noise_parity.py
- name: Compare compiled density samplers with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_density_parity.py
- name: Compare world-generation JSON codecs with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_worldgen_parity.py
- name: Compare heightmap predicates and chunk mutations with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_heightmap_parity.py
- name: Compare pre-light chunk status transitions and block writes
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_chunk_stage_parity.py
- name: Compare feature placement into resident neighboring chunks
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_feature_region_parity.py
- name: Compare nested feature selectors and sequences
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_feature_graph_parity.py
- name: Compare named feature holders and placed-feature tags
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_feature_catalog_parity.py
- name: Compare configured fill-layer block placement
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_fill_layer_parity.py
- name: Compare replacement-rule codecs and evaluation
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_rule_test_parity.py
- name: Compare simple-block placement and feature composition
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_simple_block_parity.py
- name: Compare block-column sampling and obstruction
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_column_parity.py
- name: Compare vertical pillars and cap feature placement
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_pillar_parity.py
- name: Compare exactly-one-neighbor feature spreading
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_neighbor_spread_parity.py
- name: Compare block-pile support and placement
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_pile_parity.py
- name: Compare disk replacement and postprocessing
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_disk_parity.py
- name: Compare block-blob support search and geometry
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_blob_parity.py
- name: Compare spring placement and fluid tick scheduling
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_spring_parity.py
- name: Compare vine attachment priority and placement
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_vines_parity.py
- name: Compare underwater magma floor scans and occlusion
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_underwater_magma_parity.py
- name: Compare blue-ice seeding and growth attempts
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_blue_ice_parity.py
- name: Compare spike geometry and discontinuous roots
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_spike_parity.py
- name: Compare End podium construction and destruction requests
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_end_podium_parity.py
- name: Rust End gateway parity
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_end_gateway_parity.py
- name: Compare bonus chest placement and conditional loot seeding
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_bonus_chest_parity.py
- name: Compare recursive chorus generation and connection refreshes
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_chorus_plant_parity.py
- name: Compare small speleothem patches and waterlogged points
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_speleothem_parity.py
- name: Compare replacement blob search and Manhattan shells
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_replace_blobs_parity.py
- name: Compare bamboo stalks, podzol patches and leafy caps
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_bamboo_parity.py
- name: Compare Nether delta rims and shifted contents
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_delta_parity.py
- name: Compare biome freezing and snow eligibility
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_weather_parity.py
- name: Compare frozen top layers and snowy ground updates
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_snow_freeze_parity.py
- name: Compare generation-stage tick storage and routing
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_generation_tick_parity.py
- name: Compare below-zero upgrade metadata codecs
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_retrogen_data_parity.py
- name: Compare below-zero upgrade lifecycle and block transformations
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_retrogen_chunk_parity.py
- name: Compare chunk-status metadata, ordering and codecs
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_chunk_status_parity.py
- name: Compare proto-chunk block-entity storage and coordinates
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_entity_storage_parity.py
- name: Compare ordered single-block replacement features
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_replace_block_parity.py
- name: Compare scattered ore placement and air-exposure checks
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_scattered_ore_parity.py
- name: Compare resident bulk-section access and raw writes
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_bulk_section_parity.py
- name: Compare biome feature ordering and cycle detection
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_feature_sort_parity.py
- name: Compare world-generation random wrappers and seeding
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_worldgen_random_parity.py
- name: Compare biome filtering and top-level feature context
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_placement_parity.py
- name: Compare biome decoration feature scheduling and seeding
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_decoration_parity.py
- name: Compare decoration against resident biome and terrain sections
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_decoration_region_parity.py
- name: Compare block-state provider choices and rotation
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_state_provider_parity.py
- name: Compare contained fluids and height queries with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_fluid_parity.py
- name: Compare entity obstruction with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_entity_obstruction_parity.py
- name: Compare block solidity and replaceability with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_properties_parity.py
- name: Compare face slicing and block support with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_face_support_parity.py
- name: Compare cached block support with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_support_parity.py
- name: Compare dynamic block support with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_dynamic_support_parity.py
- name: Compare moving-piston collision and interpolation with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_piston_shape_parity.py
- name: Compare supported block survival rules with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_survival_parity.py
- name: Compare noise-stage chunk filling with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_terrain_parity.py
- name: Compare structure terrain-adaptation density with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_structure_density_parity.py
- name: Compare seeded material bands and surface queries with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_material_surface_parity.py
- name: Compare material condition codecs and rule evaluation with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_material_condition_parity.py
- name: Compare biome temperatures and cache behavior with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_temperature_parity.py
- name: Compare badlands and frozen-ocean extensions with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_material_extension_parity.py
- name: Compare bundled material-rule libraries with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_material_rule_library_parity.py
- name: Compare fixed, checkerboard and End biome sources with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_source_parity.py
- name: Compare seeded cave paths and failure state with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_cave_carver_parity.py
- name: Compare seeded canyon paths and width factors with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_canyon_carver_parity.py
- name: Compare initial block-writing feature algorithms with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_basic_feature_parity.py
- name: Compare feature placement chains with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_feature_placement_parity.py
- name: Compare feature placement primitives with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_placement_parity.py
- name: Compare anchored height providers with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_height_provider_parity.py
- name: Compare scalar value providers with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_value_provider_parity.py
- name: Compare cave and canyon geometric primitives with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_carving_geometry_parity.py
- name: Compare carving-mask traversal and callback mutations with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_carving_mask_parity.py
- name: Compare registry-bound biome-source codecs with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_source_codec_parity.py
- name: Compare all four biome-source kinds in chunk generation with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_generation_parity.py
- name: Compare chunk biome filling and failure state with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_chunk_parity.py
- name: Compare biome zoom and seed obfuscation with pinned vanilla
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_biome_zoom_parity.py
- name: Compare surface-stage chunks with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_material_stage_parity.py
- name: Compare block-state JSON codecs with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_block_state_codec_parity.py
- name: Compare vertical anchors with pinned vanilla client and server
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_anchor_parity.py
- name: Compare float logarithms at domain and rounding boundaries
env:
RUSTUP_TOOLCHAIN: stable
run: python tools/test_float_log_parity.py
# JFR analysis uses JDK-generated fixture recordings on the self-hosted Linux runner.
# Start a manual checks dispatch with: gh workflow run checks --ref <branch>.
jfr-analysis:
if: github.event_name == 'workflow_dispatch'
runs-on: [self-hosted, linux, horizon-game]
+12 -9
View File
@@ -58,6 +58,18 @@ jobs:
echo "Merges since ${BASE_SHA}:"
git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD"
python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400
- name: Preserve the initial failure logs
if: steps.harnesses.outcome == 'failure'
run: |
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
- name: Upload the initial failure logs
if: steps.harnesses.outcome == 'failure'
uses: actions/upload-artifact@v7
with:
name: parity-main-logs
path: .local/parity-main-logs/
if-no-files-found: warn
retention-days: 7
- name: A flake, or the merge that broke them
if: steps.harnesses.outcome == 'failure'
env:
@@ -65,13 +77,4 @@ jobs:
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.base.outputs.sha }}
run: |
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
python3 tools/parity_main.py bisect "$BASE_SHA" --comment
- name: Logs of the failed harnesses
if: steps.harnesses.outcome == 'failure'
uses: actions/upload-artifact@v7
with:
name: parity-main-logs
path: .local/parity-main-logs/
if-no-files-found: ignore
retention-days: 7
+35 -7
View File
@@ -1,7 +1,9 @@
# Horizon: a map for agents
Minecraft: Java Edition 26.3 rewritten in Rust (wgpu). Vanilla is the specification wherever it has the
feature. Read [CONTRIBUTING.md](CONTRIBUTING.md) once; this page tells you where things are.
feature; performance work may differ inside as long as it stays compatible with vanilla
([CONTRIBUTING.md](CONTRIBUTING.md#when-it-doesnt-have-to-be-11)). Read [CONTRIBUTING.md](CONTRIBUTING.md) once;
this page tells you where things are.
Feature → files → harness for the most-changed areas: [docs/architecture.md](docs/architecture.md).
## Rules that bite
@@ -35,7 +37,6 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
- Small PRs (< ~500 lines). Labels: `feature` (players get something new), `skip-release` (they see no
change), none for a fix. Agents never add `release-now`: the maintainer decides it. Merges ship in batches of 5, or after
6 hours ([docs/release-flow.md](docs/release-flow.md)).
- Contributors first: `gh pr list --state open --search <area>` before you start; never duplicate theirs.
- **No hardcoded user-facing strings.** Keep UI translation-ready from the start. In the launcher (`launcher/`), wrap visible text with `tr("...")` or `trf("... {arg} ...", &[("arg", &val)])` from `crate::i18n` instead of raw string literals or `format!`. In the game, use translation keys (`Text::tr`, `lang::get`), never hardcoded English strings.
- **Claim before you start**: comment `/claim` on the issue (no issue yet: open one, then claim it). An assigned
issue is taken, and so is one labelled `in progress` (claimed on Discord): pick another. `/unclaim` when you stop;
@@ -47,6 +48,29 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
- **Render passes keep HDR's light.** A pass that reads, filters or redraws the world's picture (upscaling,
anti-aliasing, sharpening, frame generation, post effects, captures) follows [docs/hdr-passes.md](docs/hdr-passes.md).
## Don't lose time
Where agent time went, measured on sessions and CI in November 2026: reading code, compiling `horizon-client`,
waiting in loops, and work someone else had already done. Tests were a small part.
- **Check nobody else is on it.** One in three pull requests closed unmerged was a duplicate. Before you write
code, look at the issue's linked pull requests and run
`gh pr list --state open --search "<issue number, function or file name>"`; then `/claim`.
- **Find code with the map, not by reading.** Start from the tables below and
`python3 tools/port_ledger.py where Class.method`. Read the function you change and its callers, not whole
files.
- **Compile cheaply while you work.** `cargo check -p <crate>` after an edit. Clippy, fmt and tests run once, at
the end, through `pr_ready.py`. `cargo clippy -p horizon-client` and `cargo build -p horizon-client` are the
slowest commands here: never after every edit, and build the game only when you need to run it.
- **Don't wait in loops.** Start a long command in the background and carry on, or wait for it once. No
`sleep` or `until grep` polling of builds, harnesses or CI.
- **One test per changed behaviour.** None for a refactor or a file move, none that reads source text, and no
harness where vanilla has nothing to compare (Horizon's own features, performance work).
- **A red check isn't always yours.** When `verify` fails in a test your change can't reach, say so in the pull
request and move on; don't hunt it.
- **Unsure about a rule? Finish the work.** Take the reading that lets you finish, and say in the pull request
which one you took. Don't stop, and don't change direction halfway.
## Crates
Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-server` are separate workspaces.
@@ -96,6 +120,7 @@ reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` an
- Use independent expected values or a vanilla oracle; do not derive the answer from the code under test.
- Test outcomes, not only calls to stubs. Use mocks to isolate behavior, not as the behavior itself.
- Skip tests of trivial constants, derives and getters, or behavior already covered by another test.
- One test per changed behaviour is enough. A refactor or a move that changes no behaviour gets no new test.
- Avoid pinning implementation details; a harmless refactor should not break a behavior test.
- Make slow tests faster without removing cases or weakening their coverage.
- Never delete parity harnesses or tests that pin vanilla behaviour: they are the spec.
@@ -103,8 +128,8 @@ reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` an
## Build and test fast
```sh
python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR
python3 tools/pr_ready.py --quick # same without harnesses
python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests; paste its block in the PR
python3 tools/pr_ready.py --harnesses # also the affected harnesses (by default only when you change a harness, oracle, probe or the runner, as in CI)
cargo test -p horizon-client -p horizon-client-lib --lib --bins --tests # skips the examples (pr_ready does this); `--doc` separately
cargo test -p horizon-client-lib --lib mod_content::tests:: -- --ignored # the slow content-root tests, #[ignore]d; pr_ready runs them when mod content, assets, blocks or items change
cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e
@@ -113,7 +138,8 @@ python3 tools/parity.py --changed-files paths.txt --list # which harnesses cov
python3 tools/parity.py mob_ai sculk # named harnesses
python3 tools/lan_e2e.py --check chest # two real games over LAN (server-thread host)
python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
python3 tools/lang_coverage.py --summary # the keys each language still misses, and its English leftovers
python3 tools/lang_coverage.py --summary # one line per language: how many keys it carries and what it misses
python3 tools/lang_coverage.py --summary --show-keys # the same, then the keys behind the counts
```
- Harnesses and the game need the vanilla data in `.local/` (`minecraft/`, `horizon-client/26.3`, `datagen/`,
@@ -152,7 +178,8 @@ python3 tools/lang_coverage.py --summary # the keys each language still misses
- A harness runs the oracle against the real 26.3 jars and the Rust probe on the same inputs, then compares
their JSON. Oracle runs are cached by `tools/parity_shim.py`; `--fresh` reruns them.
- Mirror vanilla's `Math` calls with `horizon_core::jmath`, and vanilla's RNG with `horizon_core::random`:
random draws must happen in vanilla's order.
random draws must happen in vanilla's order. Performance work may break that order where no player can rely
on it; the pull request says so ([CONTRIBUTING.md](CONTRIBUTING.md#when-it-doesnt-have-to-be-11)).
## horizon-client: where things live
@@ -215,7 +242,8 @@ player does (#1514). A window's `Game` never ticks a world itself: the old in-fr
Open `[server-thread]` issues list the gaps left.
Single player, LAN guests and dedicated servers all run the server code, so a fix there serves all three.
Test the server thread when you touch player-facing gameplay:
When you change how the server and its clients talk (packets, tracking, guests, the server thread itself), check
it there. Other gameplay fixes are covered by their own harness and CI's parity job:
```sh
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # server thread
+30 -37
View File
@@ -1,7 +1,8 @@
# Contributing to Horizon
Thanks for helping. Horizon is Minecraft: Java Edition 26.3 rewritten in Rust, and the one rule that shapes
everything is that **it plays exactly like vanilla**. This page is the short version of how we work; questions are
everything is that **it plays like vanilla**: first exactly like it, then better where players gain from it
([vanilla first, then better](#vanilla-first-then-better)). This page is the short version of how we work; questions are
welcome on [Discord](https://discord.gg/playhorizon).
This repository holds the game and the launcher, plus the tools, tests and docs that build, check and release them.
@@ -23,7 +24,7 @@ here.
## Build it
- **Prerequisites:** Rust (stable), Python 3.10+, JDK 25, and on Linux the ALSA and udev headers
- **Prerequisites:** Rust (stable), Python 3.11+, JDK 25, git 2.38 or newer, and on Linux the ALSA and udev headers
(`libasound2-dev libudev-dev`).
- **Resources:** Horizon never downloads the game; it prepares its resources from your own copy of Minecraft 26.3, as
described in [Build from source](README.md#build-from-source).
@@ -36,7 +37,10 @@ here.
- **Launcher:** its own Cargo workspace in `launcher/` (`cd launcher && cargo run`; on NixOS, `nix-shell` first).
## Vanilla first
## Vanilla first, then better
Horizon gets there in two stages. First it plays exactly like vanilla; that is what parity work is for. Then it
improves on vanilla where players gain from it, mostly speed: FPS, TPS, loading, memory.
Wherever vanilla has a feature, vanilla is the specification, down to the order of random calls. "Parity" here means
Horizon gives the same results as the pinned 26.3 client and server for the same inputs, checked by a **harness**: a
@@ -49,8 +53,10 @@ and compares their outputs.
- **One version: 26.3.** Parity work targets 26.3 until its parity is good, redstone first. Don't open pull requests
that move Horizon to a newer Minecraft version for now; to join servers on a newer version, put a Via proxy
(ViaVersion, ViaProxy) in front of them.
- **Gameplay changes come with a harness**, new or extended, so the next change can't silently break them.
[The parity workflow](docs/parity-workflow.md) shows how harnesses run; copy a nearby one.
- **Ports of vanilla behaviour come with a harness**, new or extended, so the next change can't silently break
them. [The parity workflow](docs/parity-workflow.md) shows how harnesses run; copy a nearby one. Where vanilla
has nothing to compare (Horizon's own features, performance work, refactors), no harness is needed: one Rust
test of the changed behaviour, or the numbers before and after.
- **Horizon's own features** (the launcher, the new menus) follow [the design system](docs/design-system.md) and are
off by default wherever they would change the vanilla look.
- **Three layers: engine, platform, Horizon.**
@@ -67,40 +73,26 @@ and compares their outputs.
The pre-push hook checks the full history reachable from the branches and tags being pushed. Run
`python3 tools/check_public_tree.py --history` to audit the history of all local refs.
## Only original code, or code whose license allows it
### When it doesn't have to be 1:1
Horizon is MIT. Its code is written from Minecraft 26.3 itself and from public documentation. Since 30 October 2026
another project's source may also be read and used, **only when that project's license allows it**:
Parity is about what players and the vanilla game see, not about copying vanilla's internals. Performance work (a
multithreaded server tick, rendering, chunk loading, memory) doesn't have to keep vanilla's internal order or its
exact random calls. It has to work together with normal Minecraft:
- **Allowed:** MIT, MIT-0, BSD-2-Clause, BSD-3-Clause, 0BSD, ISC, zlib, Apache-2.0, Unlicense, and the CC0-1.0
public-domain dedication. That code may be read, copied or adapted.
- **Off limits, even to read:** GPL, LGPL (Iris), AGPL, MPL, EPL, Polyform (Sodium), the Creative Commons licenses
(CC BY, CC BY-SA, CC BY-NC and the others; CC0 is a public-domain dedication, not one of them), custom or
"source available" licenses, all rights reserved (OptiFine), and any project with no license or an unclear one.
Don't read, copy, translate or paraphrase their source, and don't send code an AI tool wrote from it. Being able
to download a mod or a pack does not give you the right to read its files.
- **Java's own library is GPL too.** OpenJDK's source (`java.lang.Math`, `StrictMath`, `FdLibm`, `HashMap`, the
sorts, `Double.toString`, HotSpot's intrinsics...) is GPL-2.0, so it is off limits like the rest. Reproduce Java's
behaviour from its API documentation (the Javadoc) and from what a JVM returns, or from a permissive original such
as Sun's fdlibm C sources (see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)); see #6741.
- **Check the license yourself.** Read the LICENSE file at the commit you use and the header of each file you take:
some repositories mix licenses, and a file under another license is off limits. A license that changed: the one at
your commit counts. In doubt, don't: ask in #contributors first.
- **Say it in the pull request:** the project, a link to the commit, its license, and what you read or copied. A
pull request that used another project's source without saying so is closed.
- **Copied or adapted code** keeps its copyright line and license notice at the top of the file, and gets an entry
in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Apache-2.0 code also keeps its NOTICE text and says what
was changed.
User documentation and file formats are fine to read, and packs and mods are fine to run and observe, whatever their
license. Shader packs are a clean-room rewrite of the pack format, produced from a written description of it (see
#1561): the [specification and its provenance log](docs/cleanroom/README.md) are public. They carry no foreign
source, and the rules above still apply to anything you read while working on them. A shader-pack pull request
names its sources: the sections of that specification, the documentation pages and the packs it ran.
- **Vanilla clients and servers still work with it.** A vanilla 26.3 client plays on a Horizon server, Horizon joins
vanilla servers, and saves and worlds open in both, as before.
- **The game still plays the same.** Farms, redstone, mobs and drops work the way players know from vanilla. A
difference may only show where no player can rely on it, such as which of two mobs ticks first or exactly which
random number a mob gets.
- **Vanilla's slow paths aren't copied.** When vanilla spends a lot of FPS or TPS on something that can reach the
same result faster, Horizon does it faster. Copying a performance problem isn't parity.
- **Say what changes.** The pull request names the vanilla behaviour it no longer reproduces exactly, why players
won't notice it or why it's worth it, and how it was checked: numbers before and after, and the harnesses that
still pass. A change players could notice, such as a different tick order on a busy server, goes behind a setting.
## Vendor libraries and Java mods
- **Upscalers and latency tools.** AMD FSR (MIT) may go in the repository, like any code under an allowed license.
- **Upscalers and latency tools.** AMD FSR (MIT) may go in the repository.
NVIDIA's DLSS, Reflex and any other library under an NVIDIA license may not: they ship only as an optional native mod
that downloads NVIDIA's files itself, on the player's machine. No NVIDIA binaries, headers or SDK files in the
repository.
@@ -117,9 +109,10 @@ python3 tools/pr_ready.py --base upstream/main # or origin/main if you work on
```
It looks at what your branch changes and runs what matters: rustfmt, clippy with warnings denied, the tests of the
crates you touched (and the launcher's), generated files, `Cargo.lock`, the Python tests, and the vanilla harnesses
your change can affect. Without the vanilla data on your machine it lists those harnesses instead; CI runs them.
`--quick` skips the harnesses. It exits non-zero when something fails.
crates you touched (and the launcher's), generated files, `Cargo.lock` and the Python tests. Like CI, it runs the
vanilla harnesses only when your branch changes a harness, an oracle, a probe or the runner; otherwise it lists the
ones your change can affect, and main's parity run checks them after the merge. `--harnesses` runs them on your
machine anyway (it needs the vanilla data). It exits non-zero when something fails.
For the game workspace, Clippy checks all targets of the touched crates and their transitive workspace dependents,
including examples. The dependency scope includes optional, platform, build and development dependencies. Tests run
Generated
+1
View File
@@ -1947,6 +1947,7 @@ name = "horizon-server-files"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"getrandom 0.3.4",
"horizon-core",
"horizon-protocol",
"horizon-world",
+1 -1
View File
@@ -530,7 +530,7 @@ unable to act, and never puts an account that is tied to a person into anyone el
| Account | Today | Can it be shared? | Plan |
| --- | --- | --- | --- |
| **GitHub organisation** (horizon-rust) | One owner (the founder) | Yes: an organisation can have several owners | **Step 1:** a second owner from the council, chosen by a 2/3 poll in the council's first week, with two-factor authentication on. **Step 2:** a `council` team; CODEOWNERS reviews and the release tools' owner powers (`paused`, `/nightly remove`) move from the founder to that team |
| **GitHub organisation** (horizon-rust) | Two owners since 2026-11-11: the founder and rdbtCVS (P28); a `council` team holds CODEOWNERS (P35) and is the security managers (P36) | Yes: an organisation can have several owners | **Step 1:** a second owner from the council, chosen by a 2/3 poll in the council's first week, with two-factor authentication on. **Step 2:** a `council` team; CODEOWNERS reviews and the release tools' owner powers (`paused`, `/nightly remove`) move from the founder to that team |
| **Discord server** | Owned by the founder | Partly: a server has exactly one owner; powers can be given through roles | **Step 1:** the 🏛️ Council role gets moderation and ban permissions; Kira applies the outcomes of passed polls, so nobody needs Manage Roles; two-factor authentication becomes required for moderation. Ownership itself stays with the founder until a legal entity exists |
| **Kira** (bot application, Railway service) | The founder's Discord developer account and Railway | The bot: yes (a Discord developer team). Railway: adding members may need a paid plan | **Step 1:** a Discord developer team with two council members. Railway members once the council decides on money |
| **Official server** (hosting panel) | The founder's account | Yes: panel sub-users | **Step 1:** sub-users for the Server and SMP lead and for one council member |
+1 -1
View File
@@ -109,7 +109,7 @@ horizon-ctl break -1 65 -3 # mines it; replies with
## Build from source
Needs Rust 1.90+, Python 3.10+, JDK 25, and on Linux `libasound2-dev libudev-dev`. `horizon-prepare` builds the game's resources from **your own copy** of Java Edition 26.3 (checked against `research-lock.json`) and never downloads it:
Needs Rust 1.90+, Python 3.11+, JDK 25, and on Linux `libasound2-dev libudev-dev`. `horizon-prepare` builds the game's resources from **your own copy** of Java Edition 26.3 (checked against `research-lock.json`) and never downloads it:
1. **Client:** play 26.3 once in the official launcher. Horizon reads `~/.minecraft` (or `--minecraft-dir` / `HORIZON_MINECRAFT_DIR`).
2. **Server jar:** the 26.3 server jar (`downloads.server.url` in `versions/26.3/26.3.json`), passed once with `--server-jar` or `HORIZON_SERVER_JAR`.
+26
View File
@@ -358,3 +358,29 @@ state of Starling's `crates/horizon-client-render/src/touch.rs` at the same comm
`crates/horizon-client-render/src/android_runtime.rs` and `android_runtime/tests/` are adapted from the
input part of Starling's `crates/horizon-client-render/src/android_runtime.rs` at the same commit.
## PCG3D hash
`hash3` in `crates/horizon-client-render/src/hdr.wgsl`, the noise HDR10 output's dither is made from, is the
`pcg3d` hash of Mark Jarzynski and Marc Olano ("Hash Functions for GPU Rendering", Journal of Computer Graphics
Techniques 9(3), 2020), from <https://github.com/markjarzynski/PCG3D>. Copyright 2020 Mark Jarzynski & Marc Olano,
licensed under MIT:
```
Copyright 2020 Mark Jarzynski & Marc Olano
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
+4
View File
@@ -23,6 +23,10 @@ pub const WITHDRAWN_PARTNER_SERVER: &str = "afri-network.co.za";
/// (the telemetry server's status checks).
pub const OFFICIAL_SERVER_STATUS: &str = "play.playhorizon.dev:24454";
/// Horizon's website, where the launcher is downloaded: the game started without its prepared
/// files sends the player there.
pub const WEBSITE: &str = "https://playhorizon.dev";
/// The cosmetics service: cosmetics, emotes, "Show me as a Horizon player"
/// (`HORIZON_COSMETICS_API` overrides it).
pub const COSMETICS_API: &str = "https://cosmetics.playhorizon.dev";
+2 -12
View File
@@ -21,7 +21,6 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
pub mod combat;
pub mod prediction;
pub mod timer;
/// What one check's violation level leads to.
@@ -162,8 +161,8 @@ checks! {
/// Prediction: each move played again from the client's own inputs with vanilla's movement code,
/// and compared (speed, step, fly, jesus...). Each player's client ticks are recorded
/// (`prediction::Record`), with a ping a tick to place what the server changes, and played again
/// (horizon-client's `lan::prediction`). A move that lands farther than `tolerance` from the
/// (horizon-client's `lan::prediction::record`), with a ping a tick to place what the server changes,
/// and played again (`lan::prediction`). A move that lands farther than `tolerance` from the
/// replay flags, by how far it lands (one `tolerance` off weighs 1, at most 5 a tick), and the
/// setback puts the player back where its moves last agreed. A tick near what the replay can't
/// play yet (another entity, a block change or abilities the client hadn't seen, a moving piston,
@@ -279,15 +278,6 @@ pub struct Player {
pub timer: timer::Balance,
/// The server tick and height where the ground last held the player.
pub ground: Option<(u64, f64)>,
/// The client ticks the prediction plays again (only while it runs).
pub record: Option<Box<prediction::Record>>,
/// Sprinting as the client's own commands left it (ServerboundPlayerCommandPacket's
/// START_SPRINTING and STOP_SPRINTING: LocalPlayer.wasSprinting), which the record's ticks take.
/// Not the server's player: a hit with extra knockback stops its sprint
/// (Player.causeExtraKnockback), the client's own `Player.attack` doesn't (a mob's `hurtClient`
/// is false), and once the server's flag reaches it LocalPlayer.aiStep starts the sprint again
/// while the sprint key is held, with nothing to say: wasSprinting never changed.
pub sprinting: bool,
/// The attacks of the client tick being heard.
pub attacks: combat::Attacks,
}
@@ -271,15 +271,31 @@ fn int_array(tag: Option<&Tag>) -> Option<&Vec<i32>> {
fn is_pos(tag: &Tag) -> bool {
matches!(tag, Tag::IntArray(v) if v.len() == 3)
}
/// The default `SignText`: four empty lines, black, not glowing.
fn empty_sign_side() -> Tag {
Tag::compound([
("messages", Tag::List(vec![string(""); 4])),
("color", string("black")),
("has_glowing_text", boolean(false)),
])
}
/// The loaded `SignText` of one side, or the empty text.
pub fn sign_side(tag: Option<&Tag>) -> Tag {
let empty = || string("");
let mut messages: Vec<Tag> = match tag.and_then(|t| t.get("messages")) {
Some(Tag::List(list)) => list.iter().filter_map(component).collect(),
_ => Vec::new(),
// `SignText.DIRECT_CODEC`: `messages` is a component list (an entry that
// fails is dropped, `ListCodec`'s partial result) cut to 4 lines by
// `Util.fixedSize`. Fewer than 4 valid lines fail the side, and
// `SignBlockEntity.loadAdditional` then loads an empty one; more keep the
// first 4 with the side's colour and glow.
let lines: Option<Vec<Tag>> = match tag.and_then(|t| t.get("messages")) {
Some(Tag::List(list)) => {
let lines: Vec<Tag> = list.iter().filter_map(component).take(4).collect();
(lines.len() == 4).then_some(lines)
}
_ => None,
};
let Some(messages) = lines else {
return empty_sign_side();
};
messages.resize_with(4, empty);
messages.truncate(4);
let mut out = vec![
("messages", Tag::List(messages)),
(
@@ -957,6 +973,32 @@ mod tests {
assert_eq!(structure.get("showboundingbox"), Some(&Tag::Byte(1)));
}
#[test]
fn sign_side_needs_exactly_four_messages() {
let ok = snbt("{messages:[\"a\",\"\",\"\",\"\"],color:\"red\",has_glowing_text:1b}");
let side = sign_side(Some(&ok));
assert_eq!(side.get("color"), Some(&string("red")));
// A fifth line, or a bad entry among five, leaves the first 4 valid
// lines with the colour (checked against the 26.3 codec).
for kept in [
"{messages:[\"a\",\"\",\"\",\"\",\"e\"],color:\"red\",has_glowing_text:1b}",
"{messages:[\"a\",1,\"\",\"\",\"\"],color:\"red\",has_glowing_text:1b}",
] {
let side = sign_side(Some(&snbt(kept)));
assert_eq!(side.get("messages"), ok.get("messages"), "{kept}");
assert_eq!(side.get("color"), Some(&string("red")), "{kept}");
}
for bad in [
"{color:\"red\",has_glowing_text:1b}",
"{messages:[\"a\",\"b\"],color:\"red\",has_glowing_text:1b}",
"{messages:[\"a\",\"\",\"\",1],color:\"red\",has_glowing_text:1b}",
] {
let side = sign_side(Some(&snbt(bad)));
assert_eq!(side, sign_side(None), "{bad}");
assert_eq!(side.get("color"), Some(&string("black")));
}
}
#[test]
fn canonical_is_idempotent() {
for id in TYPES.iter().chain(NEWEST.iter()) {
+172 -37
View File
@@ -74,11 +74,70 @@ pub trait ResourceSource {
vec!["minecraft".into()]
}
}
/// The bundled file a language reads, and whether it drops `ß`: a regional variant reads its
/// language's file (Swiss German writes "ss" for "ß", as vanilla's de_ch does).
fn bundled_code(code: &str) -> (&str, bool) {
match code {
"ko" => ("ko_kr", false),
"hr" => ("hr_hr", false),
"de_at" => ("de_de", false),
"de_ch" => ("de_de", true),
"fr_ca" | "fr_ch" => ("fr_fr", false),
"es_ar" | "es_cl" | "es_ec" | "es_mx" | "es_uy" | "es_ve" => ("es_es", false),
code => (code, false),
}
}
/// Lang files crates above the engine ship (`horizon_hooks::lang`), each a list of
/// (code, JSON) pairs. The game's entry installs them once, before any language loads.
static CRATE_FILES: std::sync::OnceLock<&'static [&'static [(&'static str, &'static str)]]> =
std::sync::OnceLock::new();
/// Installs the crates' lang files (`horizon_hooks::lang::engine::all()`). Only the first call
/// counts.
pub fn install_crate_files(files: &'static [&'static [(&'static str, &'static str)]]) {
let _ = CRATE_FILES.set(files);
}
/// The crates' entries for language `code` (through [`bundled_code`]'s variants) that the
/// engine's own `horizon` file for it doesn't have: on a key both have, the engine wins.
fn read_crate_files(files: &[&[(&str, &str)]], code: &str, map: &mut HashMap<String, String>) {
if files.is_empty() {
return;
}
let (file, swiss) = bundled_code(code);
let mut own = HashMap::new();
if let Some(bytes) = Bundled.read(&format!("assets/horizon/lang/{code}.json")) {
read_lang_file(&bytes, &mut own);
}
for (c, json) in files.iter().flat_map(|f| f.iter()) {
if *c != file {
continue;
}
let mut theirs = HashMap::new();
if swiss {
read_lang_file(json.replace('ß', "ss").as_bytes(), &mut theirs);
} else {
read_lang_file(json.as_bytes(), &mut theirs);
}
for (key, value) in theirs {
if !own.contains_key(&key) {
map.insert(key, value);
}
}
}
}
/// Horizon's own strings, compiled in so they need no prepared resources.
struct Bundled;
impl ResourceSource for Bundled {
fn read(&self, path: &str) -> Option<Vec<u8>> {
let body = match path {
let code = path
.strip_prefix("assets/horizon/lang/")?
.strip_suffix(".json")?;
let (file, swiss) = bundled_code(code);
let path = format!("assets/horizon/lang/{file}.json");
let body = match path.as_str() {
"assets/horizon/lang/en_us.json" => {
include_str!("../../horizon-client/assets/horizon/lang/en_us.json")
}
@@ -103,10 +162,10 @@ impl ResourceSource for Bundled {
"assets/horizon/lang/tr_tr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/tr_tr.json")
}
"assets/horizon/lang/ko_kr.json" | "assets/horizon/lang/ko.json" => {
"assets/horizon/lang/ko_kr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/ko_kr.json")
}
"assets/horizon/lang/hr_hr.json" | "assets/horizon/lang/hr.json" => {
"assets/horizon/lang/hr_hr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/hr_hr.json")
}
"assets/horizon/lang/pt_pt.json" => {
@@ -331,30 +390,20 @@ impl ResourceSource for Bundled {
"assets/horizon/lang/vec_it.json" => {
include_str!("../../horizon-client/assets/horizon/lang/vec_it.json")
}
"assets/horizon/lang/de_de.json" | "assets/horizon/lang/de_at.json" => {
"assets/horizon/lang/de_de.json" => {
include_str!("../../horizon-client/assets/horizon/lang/de_de.json")
}
// Swiss German writes "ss" for "ß", as vanilla's de_ch does.
"assets/horizon/lang/de_ch.json" => {
let de = include_str!("../../horizon-client/assets/horizon/lang/de_de.json");
return Some(de.replace('ß', "ss").into_bytes());
}
"assets/horizon/lang/fr_fr.json"
| "assets/horizon/lang/fr_ca.json"
| "assets/horizon/lang/fr_ch.json" => {
"assets/horizon/lang/fr_fr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/fr_fr.json")
}
"assets/horizon/lang/es_es.json"
| "assets/horizon/lang/es_ar.json"
| "assets/horizon/lang/es_cl.json"
| "assets/horizon/lang/es_ec.json"
| "assets/horizon/lang/es_mx.json"
| "assets/horizon/lang/es_uy.json"
| "assets/horizon/lang/es_ve.json" => {
"assets/horizon/lang/es_es.json" => {
include_str!("../../horizon-client/assets/horizon/lang/es_es.json")
}
_ => return None,
};
if swiss {
return Some(body.replace('ß', "ss").into_bytes());
}
Some(body.as_bytes().to_vec())
}
fn namespaces(&self) -> Vec<String> {
@@ -438,6 +487,16 @@ impl Language {
/// from every namespace and every source in priority order (later sources
/// override).
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
let crate_files = CRATE_FILES.get().copied().unwrap_or_default();
Self::load_with(sources, code, crate_files)
}
/// [`Language::load`] with these crates' lang files.
fn load_with(
sources: &[&dyn ResourceSource],
code: &str,
crate_files: &[&[(&str, &str)]],
) -> Self {
let mut map = HashMap::new();
let mut codes = vec![DEFAULT];
if code != DEFAULT {
@@ -453,12 +512,14 @@ impl Language {
sources.iter().flat_map(|s| s.namespaces()).collect();
for c in codes {
for namespace in &namespaces {
for source in sources {
let Some(bytes) = source.read(&format!("assets/{namespace}/lang/{c}.json"))
else {
continue;
};
read_lang_file(&bytes, &mut map);
for (i, source) in sources.iter().enumerate() {
if let Some(bytes) = source.read(&format!("assets/{namespace}/lang/{c}.json")) {
read_lang_file(&bytes, &mut map);
}
// The crates' text right after the engine's own (`Bundled`, the first source).
if i == 0 && namespace == "horizon" {
read_crate_files(crate_files, c, &mut map);
}
}
}
}
@@ -688,6 +749,43 @@ mod tests {
);
}
#[test]
fn a_crates_text_loads_after_the_engines_and_before_packs() {
static CRATE: &[(&str, &str)] = &[
(
"en_us",
r#"{"test.crate.hello": "Hello", "horizon.osk.close": "Shut", "test.crate.packed": "Crate"}"#,
),
(
"de_de",
r#"{"test.crate.hello": "Grüß dich", "horizon.osk.close": "Zu"}"#,
),
("fr_fr", r#"{"test.crate.hello": "Bonjour"}"#),
];
let pack = Mem(HashMap::from([(
"assets/horizon/lang/en_us.json".to_owned(),
br#"{"test.crate.packed": "Pack"}"#.to_vec(),
)]));
let load = |code| Language::load_with(&[&pack], code, &[CRATE]);
let en = load("en_us");
assert_eq!(en.get("test.crate.hello"), Some("Hello"));
// The engine's own file wins on a key both have; a pack wins over both.
assert_eq!(en.get("horizon.osk.close"), Some("Close"));
assert_eq!(en.get("test.crate.packed"), Some("Pack"));
let de = load("de_de");
assert_eq!(de.get("test.crate.hello"), Some("Grüß dich"));
assert_eq!(de.get("horizon.osk.close"), Some("Schließen"));
// Regional variants read their language's file, as the engine's do.
assert_eq!(load("de_ch").get("test.crate.hello"), Some("Grüss dich"));
assert_eq!(load("fr_ca").get("test.crate.hello"), Some("Bonjour"));
// A language the crate lacks falls back to its English.
assert_eq!(load("pl_pl").get("test.crate.hello"), Some("Hello"));
// Without crate files, nothing changes.
let plain = Language::load_with(&[&pack], "de_de", &[]);
assert_eq!(plain.get("test.crate.hello"), None);
assert_eq!(plain.len() + 1, de.len());
}
#[test]
fn a_scoped_language_is_the_calling_threads_and_reports_what_it_lacks() {
let empty = Mem(HashMap::new());
@@ -739,6 +837,20 @@ mod tests {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../horizon-client/assets/horizon/lang")
}
/// The crates whose own lang files the game loads (`crates/<name>/assets/lang`,
/// registered through `horizon_hooks::lang`), with that folder.
fn crate_lang_dirs() -> Vec<(String, std::path::PathBuf)> {
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut dirs: Vec<_> = std::fs::read_dir(&crates)
.unwrap()
.flatten()
.map(|e| (e.file_name().into_string().unwrap(), e.path()))
.map(|(name, path)| (name, path.join("assets/lang")))
.filter(|(_, dir)| dir.join("en_us.json").is_file())
.collect();
dirs.sort();
dirs
}
/// The keys of a flat bundled file in file order, duplicates included (a map
/// would keep only the last of two equal keys). One `"key": "value"` per line.
fn file_keys(body: &str) -> Vec<String> {
@@ -776,11 +888,33 @@ mod tests {
#[test]
fn bundled_files_are_served_and_have_no_stale_or_repeated_keys() {
let dir = bundled_dir();
let engine = check_lang_dir(&bundled_dir(), true);
assert!(
engine.1 >= 7,
"found {} bundled lang files in {}",
engine.1,
bundled_dir().display()
);
// A crate's files pass the same checks. Its keys are its own: on a key the engine's
// files also have, the engine's text would win and hide the crate's.
for (name, dir) in crate_lang_dirs() {
let (en, _) = check_lang_dir(&dir, false);
for key in en.keys() {
assert!(
!engine.0.contains_key(key),
"{name}: {key} is also the engine's"
);
}
}
}
/// The checks every lang folder passes: flat maps, no repeated key, no key en_us lacks, the
/// same placeholders as English, no empty text. Its en_us and how many files it has.
fn check_lang_dir(dir: &std::path::Path, bundled: bool) -> (HashMap<String, String>, usize) {
let en_body = std::fs::read_to_string(dir.join("en_us.json")).unwrap();
let en: HashMap<String, String> = serde_json::from_str(&en_body).unwrap();
let mut seen = 0;
for entry in std::fs::read_dir(&dir).unwrap().flatten() {
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let name = entry.file_name().into_string().unwrap();
let Some(code) = name.strip_suffix(".json") else {
continue;
@@ -789,7 +923,7 @@ mod tests {
// A file that Bundled::read does not name is never loaded.
let path = format!("assets/horizon/lang/{name}");
assert!(
Bundled.read(&path).is_some(),
!bundled || Bundled.read(&path).is_some(),
"{name} is not served by Bundled"
);
let body = std::fs::read_to_string(entry.path()).unwrap();
@@ -815,11 +949,7 @@ mod tests {
assert!(!value.trim().is_empty(), "{code}: {key} is empty");
}
}
assert!(
seen >= 7,
"found {seen} bundled lang files in {}",
dir.display()
);
(en, seen)
}
#[test]
@@ -834,10 +964,10 @@ mod tests {
}
}
}
let en: HashMap<String, String> = serde_json::from_str(
&std::fs::read_to_string(bundled_dir().join("en_us.json")).unwrap(),
)
.unwrap();
let english = |dir: &std::path::Path| -> HashMap<String, String> {
serde_json::from_str(&std::fs::read_to_string(dir.join("en_us.json")).unwrap()).unwrap()
};
let mut en = english(&bundled_dir());
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut files = Vec::new();
for krate in [
@@ -847,6 +977,11 @@ mod tests {
] {
rust_files(&crates.join(krate).join("src"), &mut files);
}
// A crate that ships lang files names its keys in its own sources.
for (name, dir) in crate_lang_dirs() {
en.extend(english(&dir));
rust_files(&crates.join(name).join("src"), &mut files);
}
assert!(files.len() > 100, "found only {} sources", files.len());
let mut found = 0;
for file in files {
+25
View File
@@ -320,7 +320,12 @@ pub fn java_hash_order(
"FallFlying",
"sleeping_pos",
"Brain",
"last_hurt_by_player",
"last_hurt_by_player_memory_time",
"last_hurt_by_mob",
"ticks_since_last_hurt_by_mob",
"equipment",
"locator_bar_icon",
// ArmorStand.
"Invisible",
"Small",
@@ -337,6 +342,12 @@ pub fn java_hash_order(
"immovable",
"description",
"hide_description",
// Interaction.addAdditionalSaveData.
"width",
"height",
"attack",
"interaction",
"response",
];
// BlockEntity.saveMetadata writes the position after the entity's data.
const AFTER: &[&str] = &["x", "y", "z"];
@@ -436,6 +447,20 @@ mod tests {
);
}
#[test]
fn interaction_compound_orders_width_before_interaction_in_shared_bucket() {
// `width` and `interaction` share a bucket at every table size;
// `Interaction.addAdditionalSaveData` writes `width` first.
let tag = parse_snbt(
r#"{Air:300s,Fire:0s,Invulnerable:0b,Motion:[0.0d,0.0d,0.0d],OnGround:0b,PortalCooldown:0,Pos:[4.5d,100.0d,4.5d],Rotation:[0.0f,0.0f],UUID:[I;66,0,0,1],fall_distance:0.0d,height:1.25f,interaction:{player:[I;1,2,3,4],timestamp:9L},response:0b,width:1.0f}"#,
)
.unwrap()
.0;
assert_eq!(
pretty(&tag).plain(),
"{Motion: [0.0d, 0.0d, 0.0d], Invulnerable: 0b, fall_distance: 0.0d, Air: 300s, OnGround: 0b, PortalCooldown: 0, Rotation: [0.0f, 0.0f], Pos: [4.5d, 100.0d, 4.5d], response: 0b, Fire: 0s, width: 1.0f, interaction: {player: [I; 1, 2, 3, 4], timestamp: 9L}, UUID: [I; 66, 0, 0, 1], height: 1.25f}",
);
}
#[test]
fn compact_form_matches_vanilla() {
assert_eq!(
rt("{b:1b,a:\"x\",c:[1,2],d:1.5f,e:2d,f:3L,g:4s}"),
@@ -356,6 +356,12 @@ impl KeyBinds {
pub fn is_default(&self, name: &str) -> bool {
self.get(name) == Self::default_of(name)
}
/// `KeyBindsScreen.extractRenderState`: Reset All is active only while a
/// mapping differs from its default (`KeyMapping.isDefault`, the bound key
/// against `defaultKey`).
pub fn changed_from_defaults(&self) -> bool {
self.keys.keys().any(|name| !self.is_default(name))
}
pub fn set(&mut self, name: &str, key: &str) {
if let Some((n, _, _)) = all_mappings().find(|m| m.0 == name) {
self.keys.insert(n, key.to_owned());
@@ -645,6 +651,22 @@ mod tests {
assert_eq!(k.translate_all(KeyCode::Digit9), [Ok(KeyCode::Digit9)]);
assert_eq!(k.translate_all(KeyCode::F3), [Ok(KeyCode::F3)]);
}
/// `KeyBindsScreen.extractRenderState`: Reset All is active only while a
/// binding differs from its default.
#[test]
fn reset_all_is_active_only_after_a_binding_moves() {
let mut keys = KeyBinds::default();
assert!(!keys.changed_from_defaults());
keys.set("key.attack", "key.mouse.right");
assert!(keys.changed_from_defaults());
// Setting a mapping back to its own default leaves nothing to reset.
keys.set("key.attack", KeyBinds::default_of("key.attack"));
assert!(!keys.changed_from_defaults());
keys.set("key.jump", "key.keyboard.z");
keys.reset_all();
assert!(!keys.changed_from_defaults());
}
#[test]
fn display_names() {
assert_eq!(display_name("key.keyboard.w").plain(), "W");
+61 -1
View File
@@ -7,7 +7,7 @@ use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
path::Path,
sync::Arc,
sync::{Arc, OnceLock},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -398,7 +398,37 @@ impl Biomes {
pub fn contains(&self, name: &str) -> bool {
self.index.contains_key(name)
}
/// The biome at `id`, clamped to the last entry when `id` is past the
/// table (a stale column from an older registry keeps its id).
///
/// When the table is empty (a resource pack with no biome files), returns
/// a shared default plains biome instead of panicking on `list.len() - 1`.
pub fn get(&self, id: u16) -> &BiomeInfo {
if self.list.is_empty() {
static DEFAULT: OnceLock<BiomeInfo> = OnceLock::new();
return DEFAULT.get_or_init(|| BiomeInfo {
spawns: HashMap::new(),
spawn_costs: HashMap::new(),
creature_probability: 0.0,
increased_fire_burnout: false,
name: "minecraft:plains".to_owned(),
temperature: 0.8,
frozen: false,
downfall: 0.4,
precipitation: false,
grass: 0x7f_c0_55,
modifier: GrassModifier::None,
foliage: 0x6a_ab_37,
dry_foliage: 0x79_75_54,
water: 0x3f_76_e4,
sky: None,
fog: None,
water_fog: 0x3f_76_e4,
ambient_particles: Vec::new(),
features: Vec::new(),
attributes: Default::default(),
});
}
&self.list[usize::from(id).min(self.list.len() - 1)]
}
/// The name of biome `id`, plains (as for an unknown name) when the id is
@@ -795,4 +825,34 @@ mod blend_tests {
}
assert!(at(-2.0) > 0.0 && at(-2.0) < 0.5);
}
/// An empty biome table (a resource pack with no biome files) must not
/// panic on `get`: before the fix, `list.len() - 1` underflowed.
#[test]
fn get_on_empty_biome_table_returns_default_instead_of_panicking() {
use std::sync::Arc;
let empty = Biomes {
builtin: Arc::new(Vec::new()),
index: HashMap::new(),
list: Vec::new(),
info_noise: SimplexNoise::with_skipped_offsets(&mut LegacyRandom::new(2345), true),
colormaps: Arc::new(Colormaps {
grass: Vec::new(),
foliage: Vec::new(),
dry: Vec::new(),
}),
packs: BTreeMap::new(),
};
// Any id returns the shared default plains biome, no panic.
let b = empty.get(0);
assert_eq!(b.name, "minecraft:plains");
let b = empty.get(65535);
assert_eq!(b.name, "minecraft:plains");
// Colours and temperature come from the default.
assert_eq!(b.temperature, 0.8);
assert_eq!(b.grass, 0x7f_c0_55);
assert_eq!(b.foliage, 0x6a_ab_37);
assert_eq!(b.water, 0x3f_76_e4);
}
}
@@ -15,7 +15,7 @@ use crate::{
font::{Font, Glyph},
gfx::mark_oit,
hud::Rect,
mesher::{CULL_BACK, Vertex},
mesher::{CULL_BACK, Vertex, cull_back},
models::load_visibility,
signs::{self, SignData, SignText},
text::{Style, Text},
@@ -3093,9 +3093,9 @@ impl BlockEntityRenderer {
}
}
// `DecoratedPotRenderer` submits every part with `entitySolid`, which culls
// back faces: the flat `top` and `bottom` planes show one side each.
// back faces: the flat `top` and `bottom` planes show one side each (#15322).
for vertex in &mut out[first..] {
vertex.normal = CULL_BACK;
vertex.normal = cull_back(vertex.normal);
}
}
Kind::EndPortal => {
@@ -4760,9 +4760,12 @@ mod tests {
28,
"the pot submits all of vanilla's quads"
);
// A part the shader shades keeps its normal (#15322): `w` alone says cull.
assert!(
verts.iter().all(|v| v.normal == CULL_BACK),
"entitySolid culls the pot's back faces"
verts
.iter()
.all(|v| v.normal[3] == crate::mesher::SHADED_CULL_W && v.normal[..3] != [0; 3]),
"entitySolid culls the pot's back faces and shades it by its normals"
);
}
+100
View File
@@ -84,6 +84,71 @@ pub fn contents_effects(stack: &ItemStack) -> Vec<(&'static str, i32, i32)> {
)
.collect()
}
/// `PotionContents.getAllEffects`, retaining each custom instance's flags.
pub fn contents_instances(stack: &ItemStack) -> Vec<crate::effects::EffectInstance> {
use horizon_client_core::nbt_value::{number, text};
use horizon_world::nbt::Tag;
let mut effects: Vec<_> = stack
.potion()
.and_then(potion)
.map_or(&[][..], |p| p.effects)
.iter()
.map(|(id, duration, amp)| crate::effects::EffectInstance::new(id, *duration, *amp))
.collect();
if let Some((_, Tag::List(custom))) = stack
.data()
.and_then(|d| d.potion_extra.iter().find(|(k, _)| k == "custom_effects"))
{
for e in custom {
let Some(def) = text(e.get("id")).and_then(|id| effect(&id)) else {
continue;
};
let mut instance = crate::effects::EffectInstance::new(
def.id,
number(e.get("duration")).unwrap_or(0) as i32,
number(e.get("amplifier")).unwrap_or(0).clamp(0, 255) as i32,
);
instance.ambient = number(e.get("ambient")).unwrap_or(0) != 0;
instance.visible = number(e.get("show_particles")) != Some(0);
effects.push(instance);
}
}
effects
}
/// `PotionContents.getColor`: an explicit colour wins; otherwise mix only
/// visible base and custom effects, with their amplifier weights.
pub fn contents_color(stack: &ItemStack) -> u32 {
use horizon_client_core::nbt_value::number;
if let Some(color) = stack
.data()
.and_then(|d| d.potion_extra.iter().find(|(k, _)| k == "custom_color"))
.and_then(|(_, v)| number(Some(v)))
{
return color as u32;
}
0xFF00_0000
| horizon_client_core::potions::effects_color(
contents_instances(stack)
.iter()
.filter(|e| e.visible)
.map(|e| (e.id, e.amplifier)),
)
}
/// `PotionContents.equals(EMPTY)`: colour and custom name also make contents
/// nonempty, even when there is no registered potion or custom effect.
pub fn contents_empty(stack: &ItemStack) -> bool {
use horizon_world::nbt::Tag;
stack.potion().is_none()
&& stack.data().is_none_or(|d| {
d.potion_extra
.iter()
.all(|(key, value)| match key.as_str() {
"custom_effects" => matches!(value, Tag::List(list) if list.is_empty()),
"custom_color" | "custom_name" => false,
_ => true,
})
})
}
/// Roman amplifier suffix (`potion.potency.N`) and duration lines of a potion.
pub fn tooltip(
potion: Option<&str>,
@@ -706,4 +771,39 @@ mod tests {
let lines = effect_lines([("minecraft:resistance", 15, 0)], 1.0, &translate);
assert_eq!(lines[0].0, "resistance");
}
#[test]
fn custom_contents_color_and_empty_semantics() {
use horizon_world::nbt::Tag;
let mut stack = ItemStack::new("minecraft:tipped_arrow", 1);
assert!(contents_empty(&stack));
stack
.data_mut()
.potion_extra
.push(("custom_effects".into(), Tag::List(Vec::new())));
assert!(contents_empty(&stack));
stack.data_mut().potion_extra = vec![(
"custom_effects".into(),
Tag::List(vec![
Tag::compound([
("id", Tag::String("minecraft:glowing".into())),
("amplifier", Tag::Int(1)),
]),
Tag::compound([
("id", Tag::String("minecraft:poison".into())),
("show_particles", Tag::Byte(0)),
]),
]),
)];
assert!(!contents_empty(&stack));
// Glowing's colour; hidden poison contributes no weight.
assert_eq!(contents_color(&stack), 0xFF94_A061);
stack
.data_mut()
.potion_extra
.push(("custom_color".into(), Tag::Int(123456)));
assert_eq!(contents_color(&stack), 123456);
stack.data_mut().potion_extra = vec![("custom_name".into(), Tag::String("test".into()))];
assert!(!contents_empty(&stack));
assert_eq!(contents_color(&stack), 0xFF38_5DC6);
}
}
+164 -19
View File
@@ -4,6 +4,7 @@
use horizon_core::paletted::{PalettedContainer, Strategy};
use horizon_world::nbt::{Compound, Tag};
use horizon_world::registry::BlockStateId;
use std::sync::atomic::{AtomicI16, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
pub mod block_entity;
@@ -457,6 +458,44 @@ impl Light {
}
}
}
/// One of a chunk's heightmaps (`Chunk::surface`): the heights, built whole on the first read,
/// and the columns a write may have moved since, each found again on its next read. Reads share
/// the chunk (helper threads read the world): a stale column is found the same by any of them.
#[derive(Default)]
struct Heights {
heights: OnceLock<Box<[AtomicI16; 256]>>,
stale: [AtomicU64; 4],
}
impl Heights {
/// `Heightmap.update`: a write two or more below column `i`'s height can't move it; any
/// other marks the column.
fn write(&mut self, i: usize, y: i32) {
let Some(heights) = self.heights.get_mut() else {
return;
};
let stale = self.stale[i >> 6].get_mut();
if *stale & 1 << (i & 63) == 0 && y >= i32::from(*heights[i].get_mut()) - 1 {
*stale |= 1 << (i & 63);
}
}
}
impl Clone for Heights {
fn clone(&self) -> Self {
let copy = Self::default();
// A reader can refresh a height and then clear its stale bit while we clone. Copy the
// bits first: a stale snapshot will rescan; a clean one acquires the refreshed height.
// Copying heights first could keep an old height with a newly cleared bit.
for (to, from) in copy.stale.iter().zip(&self.stale) {
to.store(from.load(Ordering::Acquire), Ordering::Relaxed);
}
if let Some(heights) = self.heights.get() {
let _ = copy.heights.set(Box::new(std::array::from_fn(|i| {
AtomicI16::new(heights[i].load(Ordering::Relaxed))
})));
}
copy
}
}
#[inline]
fn column(x: i32, z: i32) -> usize {
((z & 15) << 4 | (x & 15)) as usize
@@ -574,10 +613,10 @@ pub struct Chunk {
pub sections: Vec<Arc<Section>>,
/// `Heightmap.Types.WORLD_SURFACE` per column (`z << 4 | x`): one above
/// the highest non-air block, or the column's minimum Y. Built on the first read; a
/// `set` that can move a column's surface drops it.
surface: OnceLock<Box<[i16; 256]>>,
/// `set` that can move a column's surface marks that column, found again on its next read.
surface: Heights,
/// `Heightmap.Types.MOTION_BLOCKING` per column, kept like `surface`.
motion_blocking: OnceLock<Box<[i16; 256]>>,
motion_blocking: Heights,
pub lit: bool,
/// Light read from a save with `isLightOn`: no light job is needed.
pub light_loaded: bool,
@@ -618,8 +657,8 @@ impl Chunk {
z,
min_y: layout.min_y(),
sections: (0..layout.sections()).map(|_| empty.clone()).collect(),
surface: OnceLock::new(),
motion_blocking: OnceLock::new(),
surface: Heights::default(),
motion_blocking: Heights::default(),
lit: false,
light_loaded: false,
fresh: false,
@@ -698,12 +737,7 @@ impl Chunk {
// move it. Any other change rebuilds that map on the next read.
if previous != v {
for map in [&mut self.surface, &mut self.motion_blocking] {
if map
.get()
.is_some_and(|heights| y >= i32::from(heights[column(x, z)]) - 1)
{
*map = OnceLock::new();
}
map.write(column(x, z), y);
}
}
previous
@@ -714,24 +748,55 @@ impl Chunk {
let section = Arc::make_mut(&mut self.sections[s]);
section.blocks = Section::from_blocks(values);
section.compact();
self.surface = OnceLock::new();
self.motion_blocking = OnceLock::new();
self.surface = Heights::default();
self.motion_blocking = Heights::default();
}
/// `getHeight(Heightmap.Types.WORLD_SURFACE, x, z)` (`x`, `z` within the
/// chunk): one above the highest block that isn't `air`, or the column's
/// minimum Y.
/// Sections must change only through `set` once this has been read.
pub fn world_surface(&self, x: i32, z: i32, air: impl Fn(u32) -> bool) -> i32 {
let surface = self.surface.get_or_init(|| self.prime(|v| !air(v)));
i32::from(surface[column(x, z)])
self.height(&self.surface, x, z, |v| !air(v))
}
/// `getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)` (`x`, `z` within
/// the chunk): one above the highest state where `blocks` (a motion
/// blocking block or a fluid), or the column's minimum Y. Kept as
/// `world_surface` is.
pub fn motion_blocking(&self, x: i32, z: i32, blocks: impl Fn(u32) -> bool) -> i32 {
let heights = self.motion_blocking.get_or_init(|| self.prime(blocks));
i32::from(heights[column(x, z)])
self.height(&self.motion_blocking, x, z, blocks)
}
/// One column's height in `map`: the whole map built on its first read, a column a write
/// marked found again down that column alone.
fn height(&self, map: &Heights, x: i32, z: i32, counts: impl Fn(u32) -> bool) -> i32 {
let heights = map.heights.get_or_init(|| {
let built = self.prime(&counts);
Box::new(std::array::from_fn(|i| AtomicI16::new(built[i])))
});
let i = column(x, z);
let (word, bit) = (i >> 6, 1u64 << (i & 63));
if map.stale[word].load(Ordering::Acquire) & bit != 0 {
let height = self.column_height(i, &counts);
heights[i].store(height, Ordering::Relaxed);
map.stale[word].fetch_and(!bit, Ordering::Release);
return i32::from(height);
}
i32::from(heights[i].load(Ordering::Relaxed))
}
/// [`Self::prime`] for column `i` alone.
fn column_height(&self, i: usize, counts: impl Fn(u32) -> bool) -> i16 {
for (s, section) in self.sections.iter().enumerate().rev() {
if section.blocks.uniform().is_some_and(|v| !counts(v)) {
continue;
}
let base = self.min_y + s as i32 * 16;
if let Some(dy) = (0..16)
.rev()
.find(|&dy| counts(section.blocks.get(dy << 8 | i)))
{
return (base + dy as i32 + 1) as i16;
}
}
self.min_y as i16
}
/// `Heightmap.primeHeightmaps`: each section from the top, skipping
/// those of one state that doesn't count, until every column is found.
@@ -797,7 +862,7 @@ impl Chunk {
+ self.sections.capacity() * std::mem::size_of::<Arc<Section>>();
census.heightmap_bytes += [&self.surface, &self.motion_blocking]
.iter()
.filter(|map| map.get().is_some())
.filter(|map| map.heights.get().is_some())
.count()
* std::mem::size_of::<[i16; 256]>();
for section in &self.sections {
@@ -1020,9 +1085,89 @@ mod tests {
let before = chunk.world_surface(3, 3, is_air);
chunk.set(3, MIN_Y + HEIGHT, 3, stone);
chunk.set(3, before - 1, 3, chunk.get(3, before - 1, 3));
assert!(chunk.surface.get().is_some());
assert!(chunk.surface.heights.get().is_some());
assert_eq!(chunk.world_surface(3, 3, |_| unreachable!()), before);
}
/// A write two below a column's height can't move it, so the next read asks about no block;
/// a write at or above it (placing on top, clearing the top block) is found again on the next
/// read by looking down that column alone, and the other columns keep their heights.
#[test]
fn a_write_finds_its_own_column_again() {
// Each column holds its own state (16 + i), so a read that looks at another column's
// blocks shows up as a state that isn't air or this column's.
let state = |i: usize| 16 + i as u32;
let mut chunk = Chunk::empty(0, 0);
for i in 0..256 {
for y in MIN_Y..MIN_Y + 20 + (i as i32 % 7) {
chunk.set(i as i32 & 15, y, i as i32 >> 4, state(i));
}
}
let seen = std::cell::RefCell::new(Vec::new());
let surface = |c: &Chunk, i: usize| {
c.world_surface(i as i32 & 15, i as i32 >> 4, |v| {
seen.borrow_mut().push(v);
v == 0
})
};
let heights: Vec<i32> = (0..256).map(|i| surface(&chunk, i)).collect();
assert_eq!(heights[0], MIN_Y + 20);
assert_eq!(heights[6], MIN_Y + 26);
seen.borrow_mut().clear();
let (column, x, z) = (0x35, 5, 3);
let top = heights[column];
// Two below the height: the column keeps its map entry.
chunk.set(x, top - 2, z, 0);
assert_eq!(surface(&chunk, column), top);
assert!(seen.borrow().is_empty());
chunk.set(x, top - 2, z, state(column));
// At the height: placed on top, found again down this column only.
chunk.set(x, top, z, state(column));
assert_eq!(surface(&chunk, column), top + 1);
assert!(!seen.borrow().is_empty());
assert!(seen.borrow().iter().all(|&v| v == 0 || v == state(column)));
seen.borrow_mut().clear();
assert_eq!(surface(&chunk, column), top + 1);
for i in (0..256).filter(|&i| i != column) {
assert_eq!(surface(&chunk, i), heights[i]);
}
assert!(
seen.borrow().is_empty(),
"a read found again an untouched column"
);
// One below the height: the top block cleared, the height drops by one.
chunk.set(x, top, z, 0);
assert_eq!(surface(&chunk, column), top);
assert!(seen.borrow().iter().all(|&v| v == 0 || v == state(column)));
}
/// Chunk snapshots can be cloned while helper threads refresh a stale height. No snapshot
/// may retain the old height with its stale bit cleared, for either map.
#[test]
fn cloning_during_a_height_refresh_keeps_the_new_height() {
for _ in 0..4096 {
let mut chunk = Chunk::empty(0, 0);
chunk.set(0, MIN_Y + 4, 0, 1);
assert_eq!(chunk.world_surface(0, 0, |v| v == 0), MIN_Y + 5);
assert_eq!(chunk.motion_blocking(0, 0, |v| v != 0), MIN_Y + 5);
chunk.set(0, MIN_Y + 5, 0, 1);
let ready = std::sync::Barrier::new(2);
std::thread::scope(|scope| {
scope.spawn(|| {
ready.wait();
assert_eq!(chunk.world_surface(0, 0, |v| v == 0), MIN_Y + 6);
assert_eq!(chunk.motion_blocking(0, 0, |v| v != 0), MIN_Y + 6);
});
ready.wait();
for _ in 0..4 {
let snapshot = chunk.clone();
assert_eq!(snapshot.world_surface(0, 0, |v| v == 0), MIN_Y + 6);
assert_eq!(snapshot.motion_blocking(0, 0, |v| v != 0), MIN_Y + 6);
}
});
}
}
/// MOTION_BLOCKING ignores states that don't count (air, grass) and
/// follows writes as the surface map does, both maps kept at once.
#[test]
@@ -539,6 +539,7 @@ pub struct Data {
pub current: Option<Info>,
pub travel: i32,
pub selector: Selector,
pub reload_particle: bool,
}
/// Which sculk block entity this is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -4,11 +4,13 @@
//!
//! The pack's GLSL (26.3's `#include` or the older `#moj_import`, with explicit locations or
//! without) is written again as the Vulkan-flavoured GLSL 450 naga reads:
//! - GLSL vanilla's GL compiler takes and naga doesn't is rewritten first ([`glsl_fixups`]: a
//! helper taking the `sampler2D` it reads, an array sized by its initializer only);
//! - includes are inlined, each file once (as `GlslPreprocessor` imported them), from `include`;
//! - vanilla's uniform blocks get the bindings of [`BLOCKS`], and each of [`SAMPLERS`] is split
//! into a texture and a sampler object, combined again where the sampler is named;
//! - the vertex inputs become globals the caller's [`Glue`] fills before the pack's `main`
//! (renamed `hz_main`) runs, and `gl_VertexID` reads the glue's expression;
//! (renamed `hz_main`) runs, and `gl_VertexID` and `gl_VertexIndex` read the glue's expression;
//! - varyings get locations by name across the stages, the fragment output location 0.
use std::collections::HashSet;
@@ -18,6 +20,8 @@ use naga::ShaderStage;
use naga::front::glsl::{Frontend, Options};
use naga::valid::{Capabilities, ValidationFlags, Validator};
mod glsl_fixups;
/// Vanilla's uniform blocks (`shaders/include/*.glsl`) and their bindings in set 0.
pub const BLOCKS: [(&str, u32); 4] = [
("Globals", 0),
@@ -43,7 +47,7 @@ pub struct Glue<'a> {
pub setup: &'a str,
/// Statements after it, on `gl_Position`.
pub finish: &'a str,
/// The expression `gl_VertexID` reads.
/// The expression the pack's `gl_VertexID` and `gl_VertexIndex` read.
pub vertex_id: &'a str,
}
@@ -64,8 +68,8 @@ pub fn translate_core(
glue: &Glue,
) -> Result<CoreProgram, String> {
const CORE: &str = "minecraft:shaders/core/";
let vertex_text = strip_comments(&expand(vertex, CORE, include)?);
let fragment_text = strip_comments(&expand(fragment, CORE, include)?);
let vertex_text = glsl_fixups::fixups(&strip_comments(&expand(vertex, CORE, include)?));
let fragment_text = glsl_fixups::fixups(&strip_comments(&expand(fragment, CORE, include)?));
let mut names = Names::default();
let vertex_code = rewrite(&vertex_text, ShaderStage::Vertex, glue, &mut names)
.map_err(|e| format!("vertex shader: {e}"))?;
@@ -337,6 +341,8 @@ fn rewrite(
writeln!(out, "{ty} {name};").unwrap();
}
}
// Where the pack's own code starts: the glue above it is left as it is.
let pack_start = out.len();
let mut outputs: Vec<&str> = Vec::new();
for source_line in text.lines() {
for line in declaration_lines(source_line) {
@@ -462,11 +468,18 @@ fn rewrite(
if !vertex {
return Ok(out);
}
let mut code = replace_ident(
&rename_main(&out),
"gl_VertexID",
&format!("({})", glue.vertex_id),
// The pack's `gl_VertexID` and 26.3's `gl_VertexIndex` both mean vanilla's vertex number
// (four per quad, an `int`): both read the glue's expression, which for a pipeline that
// draws six vertices per quad turns its own `gl_VertexIndex` back into that number. Only the
// pack's code is rewritten, so the glue's expression keeps reading the real index.
let vertex_id = format!("({})", glue.vertex_id);
let pack = replace_ident(
&rename_main(&out[pack_start..]),
"gl_VertexIndex",
&vertex_id,
);
let pack = replace_ident(&pack, "gl_VertexID", &vertex_id);
let mut code = format!("{}{pack}", &out[..pack_start]);
write!(
code,
"void main() {{\n{}\nhz_main();\n{}\n}}\n",
@@ -633,6 +646,43 @@ mod tests {
assert_eq!(program.fragment.entry_points.len(), 1);
}
/// A 26.3 pack's `gl_VertexIndex` means vanilla's vertex number, four per quad. The text
/// pipeline draws six per glyph, so the pack's code must read the glue's `hz_vertex_id()`
/// (as `gl_VertexID` does), never the raw index.
#[test]
fn a_packs_gl_vertex_index_reads_the_glues_vertex_number() {
let vsh = "#version 330\n#include <minecraft:dynamictransforms.glsl>\n#include <minecraft:projection.glsl>\n\
in vec3 Position;\nin vec4 Color;\nin vec2 UV0;\nout vec4 vertexColor;\nout vec2 texCoord0;\n\
void main() {\n int corner = gl_VertexIndex % 4;\n\
gl_Position = ProjMat * ModelViewMat * vec4(Position + vec3(float(corner), 0.0, 0.0), 1.0);\n\
vertexColor = Color;\n texCoord0 = UV0;\n}\n";
let program = translate_core(vsh, VANILLA_FSH, &["IS_GUI"], &include, &GLUE).unwrap();
let module = &program.vertex;
let named = |name: &str| {
module
.functions
.iter()
.find(|(_, f)| f.name.as_deref() == Some(name))
.unwrap_or_else(|| panic!("no {name}"))
};
let (vertex_id, _) = named("hz_vertex_id");
let (_, pack_main) = named("hz_main");
fn calls(block: &naga::Block, target: naga::Handle<naga::Function>) -> bool {
block.iter().any(|statement| match statement {
naga::Statement::Call { function, .. } => *function == target,
naga::Statement::Block(inner) => calls(inner, target),
naga::Statement::If { accept, reject, .. } => {
calls(accept, target) || calls(reject, target)
}
naga::Statement::Loop {
body, continuing, ..
} => calls(body, target) || calls(continuing, target),
_ => false,
})
}
assert!(calls(&pack_main.body, vertex_id));
}
/// A 26.2-style pack shader as a HUD pack writes it: `#moj_import`, no locations, a flat
/// varying, `gl_VertexID`, `texelFetch` and `textureSize` on the glyph atlas, `GameTime`.
#[test]
@@ -0,0 +1,603 @@
//! GLSL that vanilla's GL compiler takes and naga's front end doesn't (#9386), rewritten into
//! what both take:
//! - a function with `sampler2D` parameters is copied once per set of samplers its callers pass
//! (all of them a shader's global samplers), the copy reading those samplers by name;
//! - an unsized array (`const float[] w = float[](...)`, `float w[] = ...`) takes the size its
//! initializer gives.
/// The longest shader rewritten (vanilla's, includes expanded, are a few KiB).
const MAX_LEN: usize = 64 * 1024;
/// The bytes the rewrite may scan for calls (the whole text per call it rewrites): thousands of
/// calls leave the text as it was rather than freeze a load.
const SCAN_BUDGET: usize = 64 << 20;
/// `text` with the rewrites, where they apply; anything they can't follow is left as it was.
pub(super) fn fixups(text: &str) -> String {
if text.len() > MAX_LEN {
return text.to_owned();
}
size_unsized_arrays(&specialize_sampler_params(text))
}
fn is_ident(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '_'
}
/// A name a sampler can have (`sampler2D ;` gives none, `t[2]` isn't one).
fn is_name(s: &str) -> bool {
s.chars().all(is_ident) && s.starts_with(|c: char| !c.is_ascii_digit()) && s != "sampler2D"
}
/// The identifier that ends right before byte `end` (whitespace skipped), and where it starts.
fn ident_before(text: &str, end: usize) -> Option<(usize, &str)> {
let trimmed = text[..end].trim_end();
let start = trimmed
.char_indices()
.rev()
.take_while(|(_, c)| is_ident(*c))
.last()?
.0;
let ident = &trimmed[start..];
(!ident.is_empty() && !ident.starts_with(|c: char| c.is_ascii_digit()))
.then_some((start, ident))
}
/// For each byte of `text`, the byte of the bracket closing the one opening there (counting
/// that kind of bracket only), or `None`: one pass, so a scan asking for many stays linear.
fn closings(text: &str) -> Vec<Option<usize>> {
let mut out = vec![None; text.len()];
let mut open: [Vec<usize>; 3] = Default::default();
for (i, b) in text.bytes().enumerate() {
let (kind, opens) = match b {
b'(' => (0, true),
b')' => (0, false),
b'[' => (1, true),
b']' => (1, false),
b'{' => (2, true),
b'}' => (2, false),
_ => continue,
};
if opens {
open[kind].push(i);
} else if let Some(at) = open[kind].pop() {
out[at] = Some(i);
}
}
out
}
/// The comma-separated parts of `list` at its own nesting level.
fn split_top(list: &str) -> Vec<&str> {
let mut parts = Vec::new();
let (mut depth, mut start) = (0i32, 0);
for (i, c) in list.char_indices() {
match c {
'(' | '[' | '{' => depth += 1,
')' | ']' | '}' => depth -= 1,
',' if depth == 0 => {
parts.push(&list[start..i]);
start = i + 1;
}
_ => {}
}
}
if !list[start..].trim().is_empty() || !parts.is_empty() {
parts.push(&list[start..]);
}
parts
}
/// A function at the file's top level whose parameters include a `sampler2D`.
struct SamplerFn {
name: String,
/// The header from its return type to its `{` (or `;` for a prototype), and the body after.
start: usize,
end: usize,
params: Vec<String>,
/// The indices of the `sampler2D` parameters and their names.
samplers: Vec<(usize, String)>,
/// `None` for a prototype.
body: Option<String>,
return_type: String,
}
fn sampler_functions(text: &str) -> Vec<SamplerFn> {
let closing = closings(text);
let mut out = Vec::new();
let mut depth = 0i32;
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'{' => depth += 1,
b'}' => depth -= 1,
b'(' if depth == 0 => {
if let (Some((name_at, name)), Some(close)) = (ident_before(text, i), closing[i])
&& let Some((type_at, return_type)) = ident_before(text, name_at)
{
let params: Vec<String> = split_top(&text[i + 1..close])
.into_iter()
.map(|p| p.trim().to_owned())
.collect();
let samplers: Vec<(usize, String)> = params
.iter()
.enumerate()
.filter(|(_, p)| p.split_whitespace().any(|w| w == "sampler2D"))
.map(|(n, p)| (n, p.split_whitespace().last().unwrap_or("").to_owned()))
.collect();
// One without a name is left for naga to refuse.
if !samplers.iter().all(|(_, name)| is_name(name)) {
i = close + 1;
continue;
}
let after = text[close + 1..].trim_start();
let next = close + 1 + (text[close + 1..].len() - after.len());
if !samplers.is_empty() && (after.starts_with('{') || after.starts_with(';')) {
let (end, body) = if after.starts_with('{') {
let Some(body_end) = closing[next] else {
break;
};
(body_end + 1, Some(text[next..=body_end].to_owned()))
} else {
(next + 1, None)
};
out.push(SamplerFn {
name: name.to_owned(),
start: type_at,
end,
params,
samplers,
body,
return_type: return_type.to_owned(),
});
i = end;
continue;
}
}
// Any other header: no other one sits in its parentheses.
if let Some(close) = closing[i] {
i = close + 1;
continue;
}
}
_ => {}
}
i += 1;
}
out
}
/// The calls to `name` outside `skip` (its own header): each call's span and arguments. The
/// bytes read are added to `scanned`.
fn calls<'a>(
scanned: &std::cell::Cell<usize>,
text: &'a str,
name: &str,
skip: &[(usize, usize)],
) -> Vec<(usize, usize, Vec<&'a str>)> {
scanned.set(scanned.get() + text.len());
let closing = closings(text);
let mut out = Vec::new();
let mut from = 0;
while let Some(found) = text[from..].find(name) {
let at = from + found;
from = at + name.len();
let before = text[..at].chars().next_back();
let rest = &text[at + name.len()..];
let open = at + name.len() + (rest.len() - rest.trim_start().len());
if before.is_some_and(is_ident)
|| !text[open..].starts_with('(')
|| skip.iter().any(|(s, e)| (*s..*e).contains(&at))
{
continue;
}
let Some(close) = closing[open] else {
continue;
};
scanned.set(scanned.get() + close - open);
out.push((at, close + 1, split_top(&text[open + 1..close])));
}
out
}
/// Every `from` standing as an identifier on its own, but not a member after a `.` (a
/// parameter `s` leaves the swizzle `c.s` alone).
fn replace_ident(text: &str, from: &str, to: &str) -> String {
if from.is_empty() {
return text.to_owned();
}
let mut out = String::with_capacity(text.len());
let mut done = 0;
while let Some(found) = text[done..].find(from) {
let at = done + found;
// Read in the whole text: a match right after another (`ss`) is part of it.
let before = text[..at].trim_end().chars().next_back();
let joined = text[..at].chars().next_back().is_some_and(is_ident);
let after = text[at + from.len()..].chars().next();
out.push_str(&text[done..at]);
if joined || before == Some('.') || after.is_some_and(is_ident) {
out.push_str(from);
} else {
out.push_str(to);
}
done = at + from.len();
}
out.push_str(&text[done..]);
out
}
/// A body with its sampler parameters reading `chosen`, all at once: a parameter named like
/// another's sampler (`mix2(sampler2D Sampler0, sampler2D Sampler1)` called with them swapped)
/// still reads its own.
fn read_samplers(body: &str, params: &[(usize, String)], chosen: &[String]) -> String {
let mut body = body.to_owned();
for (n, (_, param)) in params.iter().enumerate() {
body = replace_ident(&body, param, &format!("hz_sampler_param_{n}"));
}
for (n, sampler) in chosen.iter().enumerate().take(params.len()) {
body = replace_ident(&body, &format!("hz_sampler_param_{n}"), sampler);
}
body
}
/// The byte after `uniform sampler2D <name>;`, where the shader declares that sampler.
fn sampler_declaration_end(text: &str, name: &str) -> Option<usize> {
let mut from = 0;
while let Some(found) = text[from..].find("sampler2D") {
let at = from + found;
from = at + "sampler2D".len();
let before = text[..at].trim_end();
if !before.ends_with("uniform")
|| before[..before.len() - 7]
.chars()
.next_back()
.is_some_and(is_ident)
{
continue;
}
let rest = &text[from..];
let ident = rest.trim_start();
let len = ident.chars().take_while(|c| is_ident(*c)).count();
if &ident[..len] != name {
continue;
}
let after = ident[len..].trim_start();
if after.starts_with(';') {
return Some(text.len() - after.len() + 1);
}
}
None
}
/// The samplers a call passes for `f`'s `sampler2D` parameters, in order.
fn chosen_samplers(f: &SamplerFn, args: &[&str]) -> Vec<String> {
f.samplers
.iter()
.filter_map(|(n, _)| args.get(*n).map(|a| a.trim().to_owned()))
.collect()
}
/// One pass per function with `sampler2D` parameters, until none is left or one can't be
/// followed (a caller passes something that is no sampler's name).
fn specialize_sampler_params(original: &str) -> String {
let mut text = original.to_owned();
// Bytes scanned for calls so far, against [`SCAN_BUDGET`].
let scanned = std::cell::Cell::new(0usize);
let spent = || scanned.get() > SCAN_BUDGET;
for _ in 0..16 {
let functions = sampler_functions(&text);
// From the outside in: no call inside another function still to be copied.
let inside_another = |f: &SamplerFn, at: usize| {
functions
.iter()
.any(|g| g.name != f.name && g.body.is_some() && (g.start..g.end).contains(&at))
};
let spans_of = |f: &SamplerFn| -> Vec<(usize, usize)> {
functions
.iter()
.filter(|g| g.name == f.name)
.map(|g| (g.start, g.end))
.collect()
};
let Some(f) = functions.iter().find(|f| {
f.body.is_some()
&& !spent()
&& calls(&scanned, &text, &f.name, &spans_of(f))
.iter()
.all(|(at, ..)| !inside_another(f, *at))
}) else {
if spent() {
break;
}
// None left to copy.
return text;
};
let spans = spans_of(f);
let found = calls(&scanned, &text, &f.name, &spans);
// Each call's samplers must be plain names (a global's, or a later pass's parameter).
let mut variants: Vec<Vec<String>> = Vec::new();
let mut call_starts: Vec<usize> = Vec::new();
let mut followable = true;
for (at, _, args) in &found {
let chosen = chosen_samplers(f, args);
if chosen.len() != f.samplers.len() || !chosen.iter().all(|a| is_name(a)) {
followable = false;
break;
}
call_starts.push(*at);
if !variants.contains(&chosen) {
variants.push(chosen);
}
if variants.len() > 64 {
followable = false;
break;
}
}
// Overloads (`tap(sampler2D, vec2)` and `tap(sampler2D, vec3)`) each keep their own
// body; a call picks its samplers by position, so they must sit at the same places.
let same_places = functions.iter().filter(|g| g.name == f.name).all(|g| {
g.samplers
.iter()
.map(|s| s.0)
.eq(f.samplers.iter().map(|s| s.0))
});
if !followable || !same_places || spent() {
break;
}
// A body may call another overload of itself with its own sampler (vanilla's
// `sampleNearest` calls the six-argument one): once its sampler parameters read a
// sampler, those calls name that copy too, and their sets join the variants.
let rewrite_own_calls = |body: &str| -> Option<(String, Vec<Vec<String>>)> {
let mut body = body.to_owned();
let mut found = Vec::new();
let mut starts: Vec<usize> = calls(&scanned, &body, &f.name, &[])
.iter()
.map(|c| c.0)
.collect();
starts.sort_unstable_by(|a, b| b.cmp(a));
for start in starts {
if spent() {
return None;
}
let (end, chosen, with) = {
let (_, end, args) = calls(&scanned, &body, &f.name, &[])
.into_iter()
.find(|c| c.0 == start)?;
let chosen = chosen_samplers(f, &args);
let rest: Vec<&str> = args
.iter()
.enumerate()
.filter(|(n, _)| !f.samplers.iter().any(|(s, _)| s == n))
.map(|(_, a)| a.trim())
.collect();
let with = format!("{}_hz_{}({})", f.name, chosen.join("_"), rest.join(", "));
(end, chosen, with)
};
if chosen.len() != f.samplers.len() || !chosen.iter().all(|a| is_name(a)) {
return None;
}
found.push(chosen);
body.replace_range(start..end, &with);
}
Some((body, found))
};
let specialize = |g: &SamplerFn, chosen: &[String]| {
let body = read_samplers(g.body.as_deref().unwrap_or_default(), &g.samplers, chosen);
rewrite_own_calls(&body)
};
let same: Vec<&SamplerFn> = functions.iter().filter(|g| g.name == f.name).collect();
let mut next = 0;
while followable && next < variants.len() {
let chosen = variants[next].clone();
for g in same.iter().filter(|g| g.body.is_some()) {
match specialize(g, &chosen) {
Some((_, inner)) => {
for v in inner {
if !variants.contains(&v) {
variants.push(v);
}
}
}
None => followable = false,
}
}
next += 1;
followable &= variants.len() <= 64 && !spent();
}
if !followable {
break;
}
// One copy of an overload per set of samplers its callers pass, keeping its other
// parameters; a prototype becomes the copies' prototypes.
let signature = |g: &SamplerFn, chosen: &[String]| {
let params: Vec<&str> = g
.params
.iter()
.enumerate()
.filter(|(n, _)| !g.samplers.iter().any(|(s, _)| s == n))
.map(|(_, p)| p.as_str())
.collect();
format!(
"{} {}_hz_{}({})",
g.return_type,
g.name,
chosen.join("_"),
params.join(", ")
)
};
let copies_of = |g: &SamplerFn| -> String {
variants
.iter()
.map(|chosen| match &g.body {
Some(_) => {
let body = specialize(g, chosen).map(|(b, _)| b).unwrap_or_default();
format!("{} {body}\n", signature(g, chosen))
}
None => format!("{};\n", signature(g, chosen)),
})
.collect()
};
// Rebuild from the back: the calls, then the function's own spans (each prototype and
// definition becomes its copies). A call nested in another's arguments starts after it,
// so it is rewritten first, and the call around it is read again from the text as it is
// then. A copy reads its samplers by name, so definitions above their samplers'
// declaration (vanilla's `sample_lightmap.glsl` is included above `uniform sampler2D
// Sampler2;`) move after it, together and in their order, as long as no call comes first.
let first_call = call_starts.iter().copied().min().unwrap_or(usize::MAX);
let declared = variants
.iter()
.flatten()
.filter_map(|s| sampler_declaration_end(&text, s))
.max();
let mut edits: Vec<(usize, Option<(usize, String)>)> =
call_starts.into_iter().map(|at| (at, None)).collect();
let (mut moved, mut move_to) = (String::new(), None);
for g in &same {
match (
&g.body,
declared.filter(|&end| end > g.start && end <= first_call),
) {
(Some(_), Some(end)) => {
edits.push((g.start, Some((g.end, String::new()))));
moved.push_str(&copies_of(g));
move_to = Some(end);
}
_ => edits.push((g.start, Some((g.end, copies_of(g))))),
}
}
if let Some(end) = move_to {
edits.push((end, Some((end, format!("\n{moved}")))));
}
// Pack text is untrusted: edits that overlap, or off the text, leave it as it was.
let mut spans: Vec<(usize, usize)> = edits
.iter()
.filter_map(|(s, e)| e.as_ref().map(|(end, _)| (*s, *end)))
.collect();
spans.sort_unstable();
if spans.windows(2).any(|w| w[1].0 < w[0].1) {
break;
}
edits.sort_by_key(|(start, _)| std::cmp::Reverse(*start));
let mut sound = true;
for (start, edit) in edits {
let (end, with) = match edit {
Some(span) => span,
None => {
let found = calls(&scanned, &text, &f.name, &[])
.into_iter()
.find(|c| c.0 == start);
let Some((_, end, args)) = found else {
continue;
};
let rest: Vec<&str> = args
.iter()
.enumerate()
.filter(|(n, _)| !f.samplers.iter().any(|(s, _)| s == n))
.map(|(_, a)| a.trim())
.collect();
let copy = format!("{}_hz_{}", f.name, chosen_samplers(f, &args).join("_"));
(end, format!("{copy}({})", rest.join(", ")))
}
};
if start > end || text.get(start..end).is_none() || spent() {
sound = false;
break;
}
text.replace_range(start..end, &with);
}
if !sound {
break;
}
}
// One that couldn't be followed: the shader as written, never half rewritten.
original.to_owned()
}
/// Each array declared without a size that an initializer sizes: `T[] name = T[](a, b)` and
/// `T name[] = T[](a, b)` (or `T[2](...)`) are written with the size.
fn size_unsized_arrays(text: &str) -> String {
let mut text = text.to_owned();
let mut closing = closings(&text);
// Each array sized reads the text's brackets again: a few hundred are plenty.
let mut left = 256;
let mut from = 0;
while let Some(found) = text[from..].find('=') {
let eq = from + found;
from = eq + 1;
// `==`, `<=`, `>=`, `!=`, `+=` ... are no initializers.
let prev = text[..eq].chars().next_back();
let next = text[eq + 1..].chars().next();
if matches!(
prev,
Some('=' | '<' | '>' | '!' | '+' | '-' | '*' | '/' | '%' | '&' | '|' | '^')
) || next == Some('=')
{
continue;
}
// The constructor: `T [ n? ] (`.
let rest = &text[eq + 1..];
let ty_start = eq + 1 + (rest.len() - rest.trim_start().len());
let ty_len = text[ty_start..]
.chars()
.take_while(|c| is_ident(*c))
.count();
if ty_len == 0 {
continue;
}
let after_ty = &text[ty_start + ty_len..];
let bracket = ty_start + ty_len + (after_ty.len() - after_ty.trim_start().len());
if !text[bracket..].starts_with('[') {
continue;
}
let Some(bracket_end) = closing[bracket] else {
continue;
};
let after_bracket = &text[bracket_end + 1..];
let paren = bracket_end + 1 + (after_bracket.len() - after_bracket.trim_start().len());
if !text[paren..].starts_with('(') {
continue;
}
let Some(paren_end) = closing[paren] else {
continue;
};
// The declarator: `name []` or `T [] name`, between the statement's start and `=`.
// (Looked for on the line, at most 256 bytes back, so a long line stays linear.)
let mut back = eq.saturating_sub(256);
while !text.is_char_boundary(back) {
back += 1;
}
let statement_start = text[back..eq]
.rfind([';', '{', '}', '\n'])
.map_or(back, |i| back + i + 1);
let declarator = &text[statement_start..eq];
let Some(empty) = declarator.rfind('[') else {
continue;
};
let inside = &declarator[empty + 1..];
let Some(close) = inside.find(']') else {
continue;
};
if !inside[..close].trim().is_empty() {
continue;
}
let size = split_top(&text[paren + 1..paren_end]).len().to_string();
// Sized in the constructor too, where it isn't.
if text[bracket + 1..bracket_end].trim().is_empty() {
text.replace_range(bracket + 1..bracket_end, &size);
}
let at = statement_start + empty + 1;
text.replace_range(at..at + close, &size);
// The declarator is before `=`, so `=` moved by what its size changed.
from = eq + 1 + size.len() - close;
closing = closings(&text);
left -= 1;
if left == 0 {
break;
}
}
text
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,291 @@
//! The rewrites on GLSL a pack writes, with the text each gives written out by hand.
use super::*;
#[test]
fn a_sampler_parameter_becomes_a_copy_per_sampler_passed() {
let text = "vec4 blur(sampler2D tex, vec2 uv);\n\
vec4 blur(sampler2D tex, vec2 uv) { return texture(tex, uv) + texture(tex, uv * 2.0); }\n\
void main() { vec4 a = blur(Sampler0, uv); vec4 b = blur( Sampler1 , uv + 1.0); vec4 c = blur(Sampler0, uv); }\n";
let out = specialize_sampler_params(text);
assert!(!out.contains("sampler2D"), "{out}");
assert!(out.contains(
"vec4 blur_hz_Sampler0(vec2 uv) { return texture(Sampler0, uv) + texture(Sampler0, uv * 2.0); }"
));
assert!(out.contains("vec4 blur_hz_Sampler1(vec2 uv)"));
assert!(out.contains("blur_hz_Sampler0(uv)"));
assert!(out.contains("blur_hz_Sampler1(uv + 1.0)"));
// One copy per sampler, not per call (and its prototype, from the prototype above).
assert_eq!(out.matches("vec4 blur_hz_Sampler0(vec2 uv) {").count(), 1);
assert_eq!(out.matches("vec4 blur_hz_Sampler0(vec2 uv);").count(), 1);
}
#[test]
fn a_sampler_passed_on_through_another_function_is_followed() {
let text = "vec4 inner(sampler2D t, vec2 uv) { return texture(t, uv); }\n\
vec4 outer(vec2 uv, sampler2D s) { return inner(s, uv); }\n\
void main() { vec4 a = outer(uv, Sampler2); }\n";
let out = specialize_sampler_params(text);
assert!(!out.contains("sampler2D"), "{out}");
assert!(out.contains("outer_hz_Sampler2(uv)"), "{out}");
assert!(out.contains("inner_hz_Sampler2(uv)"), "{out}");
}
/// A call in another call's arguments is rewritten before the call around it, which is
/// then read again: neither edit lands on the other's old text.
#[test]
fn a_call_nested_in_another_calls_arguments_is_rewritten_inside_out() {
let text = "vec2 tap(sampler2D s, vec2 uv) { return texture(s, uv).xy; }\n\
void main() { vec2 a = tap(Sampler0, tap(Sampler0, uv));\n\
vec2 b = tap( Sampler1 , tap( Sampler0 , uv ) ); }\n";
let out = specialize_sampler_params(text);
assert!(!out.contains("sampler2D") && !out.contains("tap("), "{out}");
assert!(
out.contains("vec2 a = tap_hz_Sampler0(tap_hz_Sampler0(uv));"),
"{out}"
);
assert!(
out.contains("vec2 b = tap_hz_Sampler1(tap_hz_Sampler0(uv)); }"),
"{out}"
);
assert!(out.contains("vec2 tap_hz_Sampler0(vec2 uv) { return texture(Sampler0, uv).xy; }"));
assert!(out.contains("vec2 tap_hz_Sampler1(vec2 uv) { return texture(Sampler1, uv).xy; }"));
}
/// Overloads that differ past their sampler each keep their own body in their copies.
#[test]
fn overloads_with_a_sampler_each_keep_their_own_body() {
let text = "vec4 tap(sampler2D s, vec2 p) { return texture(s, p); }\n\
vec4 tap(sampler2D s, vec3 p) { return texture(s, p.xy / p.z); }\n\
void main() { vec4 a = tap(Sampler0, uv); vec4 b = tap(Sampler0, vec3(uv, 2.0)); }\n";
let out = specialize_sampler_params(text);
assert!(!out.contains("sampler2D"), "{out}");
assert!(
out.contains("vec4 tap_hz_Sampler0(vec2 p) { return texture(Sampler0, p); }"),
"{out}"
);
assert!(
out.contains("vec4 tap_hz_Sampler0(vec3 p) { return texture(Sampler0, p.xy / p.z); }"),
"{out}"
);
assert_eq!(out.matches("vec4 tap_hz_Sampler0(").count(), 2, "{out}");
assert!(out.contains("vec4 a = tap_hz_Sampler0(uv);"), "{out}");
assert!(
out.contains("vec4 b = tap_hz_Sampler0(vec3(uv, 2.0));"),
"{out}"
);
}
/// A copy reads its samplers by name, so it goes after a sampler declared below the helper
/// (vanilla's world `text.vsh` includes `sample_lightmap.glsl` above `Sampler2`).
#[test]
fn a_copy_goes_after_its_samplers_declaration() {
let text = "vec4 tap(sampler2D s, vec2 uv) { return texture(s, uv); }\n\
uniform sampler2D Sampler2;\n\
void main() { vec4 c = tap(Sampler2, vec2(0.5)); }\n";
let out = specialize_sampler_params(text);
let declared = out
.find("uniform sampler2D Sampler2;")
.expect("declaration kept");
let copy = out
.find("vec4 tap_hz_Sampler2(vec2 uv)")
.expect("copy written");
let call = out
.find("tap_hz_Sampler2(vec2(0.5))")
.expect("call rewritten");
assert!(declared < copy && copy < call, "{out}");
assert_eq!(out.matches("tap_hz_Sampler2(vec2 uv)").count(), 1, "{out}");
assert!(!out.contains("tap(sampler2D"), "{out}");
}
/// A pack's text is untrusted: a sampler declared inside the helper itself (and text that
/// isn't ASCII) gives edits that would overlap, so the shader is left as it is for the
/// translator to refuse: never a panic, never a half-rewritten shader.
#[test]
fn a_sampler_declared_inside_the_helper_never_panics() {
let text = "vec4 tap(sampler2D s, vec2 uv) { é uniform sampler2D Sampler0; x return texture(s, uv); ééé }\n\
void main() { fragColor = tap(Sampler0, vec2(0.0)); }\n";
let out = specialize_sampler_params(text);
assert_eq!(out, text);
}
/// Vanilla's `texture_sampling.glsl` shape: one overload calls the other with its own
/// sampler. That call is rewritten too, and both copies come after the sampler's declaration
/// in their own order, the called one first.
#[test]
fn an_overload_passing_its_sampler_to_another_is_followed() {
let text = "vec4 sampleNearest(sampler2D source, vec2 uv, vec2 pixelSize, vec2 du, vec2 dv, vec2 texelSize) { return texture(source, uv + du + dv); }\n\
vec4 sampleNearest(sampler2D source, vec2 uv, vec2 pixelSize) { return sampleNearest(source, uv, pixelSize, dFdx(uv), dFdy(uv), pixelSize); }\n\
uniform sampler2D Sampler0;\n\
void main() { vec4 c = sampleNearest(Sampler0, uv, px); }\n";
let out = specialize_sampler_params(text);
assert!(
!out.contains("sampleNearest(") && !out.contains("sampler2D source"),
"{out}"
);
let declared = out
.find("uniform sampler2D Sampler0;")
.expect("declaration");
let six = out
.find("vec4 sampleNearest_hz_Sampler0(vec2 uv, vec2 pixelSize, vec2 du, vec2 dv, vec2 texelSize)")
.expect("six-argument copy");
let three = out
.find("vec4 sampleNearest_hz_Sampler0(vec2 uv, vec2 pixelSize) { return sampleNearest_hz_Sampler0(uv, pixelSize, dFdx(uv), dFdy(uv), pixelSize); }")
.expect("three-argument copy calling the six-argument one");
let call = out
.find("vec4 c = sampleNearest_hz_Sampler0(uv, px);")
.expect("call");
assert!(declared < six && six < three && three < call, "{out}");
}
/// A prototype above `main` with the definition below it becomes the copies' prototypes, so
/// the call still has a declaration above it.
#[test]
fn a_prototype_becomes_the_copies_prototypes() {
let text = "uniform sampler2D Sampler0;\n\
vec4 tap(sampler2D s, vec2 uv);\n\
void main() { vec4 c = tap(Sampler0, uv); }\n\
vec4 tap(sampler2D s, vec2 uv) { return texture(s, uv); }\n";
let out = specialize_sampler_params(text);
let prototype = out
.find("vec4 tap_hz_Sampler0(vec2 uv);")
.expect("prototype copy");
let call = out.find("tap_hz_Sampler0(uv); }").expect("call");
let definition = out
.find("vec4 tap_hz_Sampler0(vec2 uv) { return texture(Sampler0, uv); }")
.expect("definition copy");
assert!(prototype < call && call < definition, "{out}");
}
/// Parameters named like the samplers they are passed, swapped, still read their own; and a
/// parameter `s` leaves the swizzle `c.s` alone.
#[test]
fn sampler_parameters_are_replaced_at_once_and_not_as_members() {
let text = "uniform sampler2D Sampler0;\nuniform sampler2D Sampler1;\n\
vec4 mix2(sampler2D Sampler0, sampler2D Sampler1, vec2 uv) { return texture(Sampler0, uv) - texture(Sampler1, uv); }\n\
vec4 swz(sampler2D s, vec2 uv) { vec4 c = texture(s, uv); return vec4(c.s, c.t, 0.0, 1.0); }\n\
void main() { vec4 a = mix2(Sampler1, Sampler0, uv) + swz(Sampler0, uv); }\n";
let out = specialize_sampler_params(text);
assert!(
out.contains("{ return texture(Sampler1, uv) - texture(Sampler0, uv); }"),
"{out}"
);
assert!(
out.contains("{ vec4 c = texture(Sampler0, uv); return vec4(c.s, c.t, 0.0, 1.0); }"),
"{out}"
);
}
#[test]
fn a_parameter_matched_twice_in_one_identifier_stays_whole() {
assert_eq!(replace_ident("c.ss + ss * s", "s", "t"), "c.ss + ss * t");
assert_eq!(replace_ident("brightness(s)", "s", "t"), "brightness(t)");
}
/// `fsh` translated beside a vertex shader that passes its position on.
fn translate(fsh: &str) -> Result<crate::core_shader::CoreProgram, String> {
let vsh = "#version 330\nin vec3 Position;\nout vec2 texCoord0;\n\
void main() {\n gl_Position = vec4(Position, 1.0);\n texCoord0 = Position.xy;\n}\n";
let glue = crate::core_shader::Glue {
inputs: &[("Position", "vec3")],
prelude: "layout(location = 0) in vec3 hz_position;",
setup: "Position = hz_position;",
finish: "",
vertex_id: "int(gl_VertexIndex)",
};
crate::core_shader::translate_core(vsh, fsh, &[], &|_| None, &glue)
}
/// #9386 end to end: naga refuses a helper taking the sampler it reads, as GLSL vanilla's GL
/// compiler takes it; the pack's shader translates, the helper a copy reading `Sampler0`.
#[test]
fn a_helper_taking_its_sampler_translates() {
let fsh = "#version 330\nuniform sampler2D Sampler0;\nin vec2 texCoord0;\nout vec4 fragColor;\n\
vec4 tap(sampler2D tex, vec2 at, float w) { return texture(tex, at) * w; }\n\
void main() {\n fragColor = tap(Sampler0, texCoord0, 0.5) + tap(Sampler0, texCoord0 + 0.01, 0.5);\n}\n";
let program = translate(fsh).unwrap();
let names: Vec<_> = program
.fragment
.functions
.iter()
.filter_map(|(_, f)| f.name.as_deref())
.collect();
assert!(names.contains(&"tap_hz_Sampler0"), "{names:?}");
assert!(!names.contains(&"tap"), "{names:?}");
}
/// A sampler parameter with no name used to hand `replace_ident` an empty name to replace,
/// which it found at the same place forever, growing the text until the game ran out of memory.
#[test]
fn a_sampler_parameter_without_a_name_is_left_as_it_was() {
let text = "uniform sampler2D Sampler0;\n\
vec4 tap(sampler2D ;, vec2 uv) { return texture(Sampler0, uv); }\n\
void main() { vec4 c = tap(Sampler0, uv); }\n";
assert_eq!(fixups(text), text);
assert_eq!(replace_ident("abc", "", "x"), "abc");
}
/// Each call rewritten reads the whole text again: thousands of them stop at the scan budget,
/// the shader left as it was (never half rewritten) instead of freezing the load.
#[test]
fn thousands_of_calls_are_left_as_they_were() {
let shader = format!(
"uniform sampler2D S;\nvec4 t(sampler2D s) {{ return texture(s, vec2(0.0)); }}\n\
void main() {{ vec4 c; {}}}\n",
"c = t(S);".repeat(5000)
);
assert_eq!(fixups(&shader), shader);
// A few of them are rewritten.
let few = shader.replace(&"c = t(S);".repeat(5000), &"c = t(S);".repeat(3));
assert_eq!(
fixups(&few).matches("c = t_hz_S(").count(),
3,
"{}",
fixups(&few)
);
}
#[test]
fn unsized_arrays_take_their_initializers_size() {
let text = "const float[] w = float[](0.25, 0.5, 0.25);\n\
const vec2 offsets[] = vec2[](vec2(1.0, 0.0), vec2(0.0, 1.0));\n\
float k[] = float[4](1.0, 2.0, 3.0, 4.0);\n\
bool same = a == b;\n";
let out = size_unsized_arrays(text);
assert!(
out.contains("const float[3] w = float[3](0.25, 0.5, 0.25);"),
"{out}"
);
assert!(
out.contains("const vec2 offsets[2] = vec2[2](vec2(1.0, 0.0), vec2(0.0, 1.0));"),
"{out}"
);
assert!(
out.contains("float k[4] = float[4](1.0, 2.0, 3.0, 4.0);"),
"{out}"
);
assert!(out.contains("bool same = a == b;"));
}
#[test]
fn a_wide_character_after_a_sized_array_never_panics() {
// Ten values make the size two digits, which moves the `=` two bytes right: the scan
// went on from where it used to be, inside the `é`.
let text = "float w[]\u{e9}= float[](0.,1.,2.,3.,4.,5.,6.,7.,8.,9.);\n";
assert_eq!(
size_unsized_arrays(text),
"float w[10]\u{e9}= float[10](0.,1.,2.,3.,4.,5.,6.,7.,8.,9.);\n"
);
}
/// #9386 end to end: naga refuses an array sized by its initializer only.
#[test]
fn an_array_sized_by_its_initializer_translates() {
let fsh = "#version 330\nuniform sampler2D Sampler0;\nin vec2 texCoord0;\nout vec4 fragColor;\n\
const float[] weights = float[](0.25, 0.5, 0.25);\n\
void main() {\n vec4 sum = vec4(0.0);\n\
for (int i = 0; i < 3; i++) {\n sum += texture(Sampler0, texCoord0 + float(i) * 0.01) * weights[i];\n }\n\
fragColor = sum;\n}\n";
let program = translate(fsh);
assert!(program.is_ok(), "{:?}", program.err());
}
+19 -6
View File
@@ -439,20 +439,33 @@ fn deliver(home: &Path, report: Report) -> Option<PathBuf> {
}
}
/// The report for a hung server tick, written by the watchdog thread
/// (`ServerWatchdog`): the stuck thread's stack is not available to Rust, so
/// the report carries none.
pub fn report_watchdog(home: &Path, side: &'static str, message: String) -> Option<PathBuf> {
/// The report for a hung server tick, written by the watchdog thread (`ServerWatchdog`): the
/// stack is the server thread's, read from the watchdog (`horizon_threads::stack_dump`), as
/// vanilla's report carries the server thread's stack; without it, the details say why.
pub fn report_watchdog(
home: &Path,
side: &'static str,
message: String,
server_stack: Result<String, horizon_threads::stack_dump::NoStack>,
) -> Option<PathBuf> {
let mut details = system_details(side);
let stack = match server_stack {
Ok(stack) => stack_lines(&stack, false),
Err(why) => {
details.push(("Server thread stack".into(), why.to_string()));
String::new()
}
};
deliver(
home,
Report {
time: Local::now(),
description: "Watching Server".into(),
error: format!("{message} (Watching Server)"),
stack: String::new(),
stack,
thread: thread_name(side),
side,
details: system_details(side),
details,
log: crate::logging::recent_lines(),
},
)
@@ -1,6 +1,7 @@
//! Data packs (`<world>/datapacks`: folders and zips with `pack.mcmeta`) and
//! the parts of them commands use: `.mcfunction` functions (with macros and
//! line continuation), function tags and predicates.
mod slot_sources;
use crate::zip::Zip;
use horizon_world::{
nbt::Tag,
@@ -663,6 +664,8 @@ pub struct DataStore {
pub item_modifiers: BTreeMap<String, serde_json::Value>,
/// `slot_source` definitions, evaluated against a command's live accessor.
pub slot_sources: BTreeMap<String, serde_json::Value>,
/// Slot-source tags belong to the same loaded snapshot as their definitions.
pub slot_source_tags: BTreeMap<String, Vec<(String, bool)>>,
/// The content tables' raw files from the packs after the built-in one:
/// `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
@@ -759,6 +762,16 @@ impl DataStore {
&& let Ok(v) = serde_json::from_slice(&bytes)
{
s.item_modifiers.insert(id, v);
} else if let Some(id) = resource_id(&f, "tags/slot_source", ".json")
&& let Some(bytes) = pack.read(&f)
&& let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes)
{
let entries = tag_entries(&v);
let slot = s.slot_source_tags.entry(id).or_default();
if v["replace"].as_bool() == Some(true) {
slot.clear();
}
slot.extend(entries);
} else if let Some(id) = resource_id(&f, "slot_source", ".json")
&& let Some(bytes) = pack.read(&f)
&& let Ok(v) = serde_json::from_slice(&bytes)
@@ -0,0 +1,86 @@
//! Slot-source holder-set tags share DataStore's pack ordering and snapshot.
use super::DataStore;
use std::collections::BTreeSet;
impl DataStore {
/// TagLoader's required-member validation and first-seen membership order.
pub fn slot_source_tag(&self, id: &str) -> Result<Vec<String>, String> {
fn visit(
store: &DataStore,
id: &str,
active: &mut BTreeSet<String>,
) -> Result<Vec<String>, String> {
if !active.insert(id.to_owned()) {
return Err(format!("Recursive slot-source tag #{id}"));
}
let result = (|| {
let entries = store
.slot_source_tags
.get(id)
.ok_or_else(|| format!("Unknown slot-source tag #{id}"))?;
let mut out = Vec::new();
for (entry, required) in entries {
let values = if let Some(tag) = entry.strip_prefix('#') {
visit(store, tag, active)
} else if store.slot_sources.contains_key(entry) {
Ok(vec![entry.clone()])
} else {
Err(format!("Unknown slot source {entry}"))
};
match values {
Ok(values) => {
for value in values {
if !out.contains(&value) {
out.push(value);
}
}
}
Err(error) if *required => return Err(error),
Err(_) => {}
}
}
Ok(out)
})();
active.remove(id);
result
}
visit(self, id, &mut BTreeSet::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn holder_set_tags_keep_order_required_members_and_snapshot_authority() {
let mut store = DataStore::default();
for name in ["t:a", "t:b"] {
store.slot_sources.insert(
name.into(),
serde_json::json!({"type":"slot_range","slots":"container.0"}),
);
}
store.slot_source_tags.insert(
"t:child".into(),
vec![("t:b".into(), true), ("t:a".into(), true)],
);
store.slot_source_tags.insert(
"t:all".into(),
vec![
("t:a".into(), true),
("#t:child".into(), true),
("t:absent".into(), false),
],
);
assert_eq!(store.slot_source_tag("t:all").unwrap(), ["t:a", "t:b"]);
store
.slot_source_tags
.get_mut("t:all")
.unwrap()
.push(("t:absent".into(), true));
assert!(store.slot_source_tag("t:all").is_err());
store
.slot_source_tags
.insert("t:cycle".into(), vec![("#t:cycle".into(), true)]);
assert!(store.slot_source_tag("t:cycle").is_err());
}
}
+2 -1
View File
@@ -155,7 +155,8 @@ fn entity_vertex(position: vec3<f32>, uv: vec2<f32>,
var back = c;
// Normal w: 0 keeps the baked colour, +-127 shades by the normal, and a small positive 1
// keeps the baked colour but culls back faces (entitySolid models such as the decorated pot).
// -126/127 shades like -127 and also culls (entityCutoutCull models such as the bat).
// -126/127 shades like -127 and also culls (entityCutoutCull models such as the bat, and the
// entitySolid decorated pot).
out.cull = select(0u, 1u, (normal.w > 0.0 && normal.w < 0.5) || (normal.w < 0.0 && normal.w > -0.996));
if abs(normal.w) >= 0.5 {
c = vec4(c.rgb * entity_light(normal.xyz, globals.time.y != 0.0), c.a);
+59 -170
View File
@@ -75,6 +75,7 @@ pub use entity_batch::{
WATER_MASK_OVERLAY, WORLD_TEXT_OVERLAY, WORLD_TEXT_POLYGON_OFFSET_OVERLAY, is_native_terrain,
mark_oit,
};
use external::{ShadowCull, shadow_box, shadow_casters, shadow_runs};
use section_fade::{
CHUNK_VISIBILITY_THRESHOLD, FadeInputs, chunk_visibility, fade_millis, section_instance,
section_visibility,
@@ -194,6 +195,7 @@ mod cull;
mod dx12_compiler;
mod end_sky;
pub mod entity_skin;
pub mod external;
mod flat;
mod frame_gen;
mod gpu_culling;
@@ -1369,8 +1371,10 @@ pub struct Renderer {
/// Per-frame scratch, kept to avoid allocating every frame.
visible: Vec<resident::Visible>,
visible_lods: Vec<lod::Visible>,
/// The sections a shader pack's shadow camera sees (`pack_post::ShadowView`).
/// The sections a shader pack's shadow camera sees (`external::ShadowView`).
shadow_visible: Vec<resident::Visible>,
/// The external shader pipeline world frames call (`external`); `None` draws vanilla's way.
external: Option<Box<dyn external::ExternalPipeline>>,
translucent_draws: Vec<(u64, usize, [u32; 5], (u32, Option<u32>))>,
origins: Vec<[f32; 4]>,
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
@@ -1496,7 +1500,7 @@ pub struct Renderer {
shadow_seen_scratch: crate::fast_hash::FxHashSet<SectionKey>,
/// Shadow translucent section draws, retained between frames.
shadow_translucent_scratch: Vec<(u64, [u32; 5], (u32, Option<u32>))>,
/// Lava's sprite layers, which a pack's solid terrain draws (`pack_atlas::terrain_parts`).
/// Lava's sprite layers, which a pack's solid terrain draws (`pack_atlas::game_terrain`).
pack_lava_layers: Vec<u16>,
pub hud: HudRenderer,
/// Vanilla's menu background blur, made on first use.
@@ -1577,9 +1581,9 @@ fn requested_split() -> Option<u32> {
.and_then(|v| v.parse().ok())
.filter(|&n| (1..=SPRITE_SPLIT).contains(&n))
}
fn adapter_requested_split(info: &wgpu::AdapterInfo, requested: Option<u32>) -> Option<u32> {
// Metal can fail to sample large mipmapped array textures despite advertising the layer limit.
requested.or_else(|| (info.backend == wgpu::Backend::Metal).then_some(512))
fn adapter_requested_split(info: &wgpu::AdapterInfo, asked: Option<u32>, n: u32) -> Option<u32> {
// Metal can fail on big mipmapped arrays (#8471): 512 layers each, more only for n > 8 x 512.
asked.or((info.backend == wgpu::Backend::Metal).then(|| n.div_ceil(SPRITE_ARRAYS).max(512)))
}
/// The split the CPU mip chains are cut by before the adapter is known.
fn sprite_split() -> u32 {
@@ -2108,7 +2112,7 @@ fn check_layers(adapter: &wgpu::Adapter, layers: u32) -> Result<u32> {
Ok(layer_split(
adapter.limits().max_texture_array_layers,
info.backend == wgpu::Backend::Gl,
adapter_requested_split(&info, requested_split()),
adapter_requested_split(&info, requested_split(), layers),
layers,
)?)
}
@@ -2823,10 +2827,8 @@ impl Renderer {
// Computed once: the sprite arrays, the shaders' constants and the
// shader pack atlas all cut the sprites by it.
let split = check_layers(&adapter, layers)?;
if split < sprite_split() {
log::info!("Horizon: {split} block textures per array (the GPU's limit)");
}
let info = adapter.get_info();
surface_setup::log_sprite_split(&info, split, layers);
crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info));
let size = window.inner_size();
let max_side = device.limits().max_texture_dimension_2d;
@@ -5242,6 +5244,7 @@ impl Renderer {
solid_runs: page_runs::PageRuns::default(),
phase2_runs: page_runs::PageRuns::default(),
shadow_runs: page_runs::PageRuns::default(),
external: None,
block_entities: Default::default(),
block_entity_section_revisions: Default::default(),
block_entity_membership_revisions: Default::default(),
@@ -5625,6 +5628,9 @@ impl Renderer {
self.offscreen = Some(Self::offscreen_target(&self.device, &self.config));
}
self.depth = Self::depth(&self.device, &self.config);
if let Some(pipeline) = &mut self.external {
pipeline.resize([width, height]);
}
}
/// Whether sections are drawn as one index list per frame (`flat`).
pub fn flat_draws(&self) -> bool {
@@ -7261,12 +7267,19 @@ impl Renderer {
}
Ok(report)
}
/// Sets the external shader pipeline world frames call (`external`), or none.
pub fn set_external_pipeline(&mut self, pipeline: Option<Box<dyn external::ExternalPipeline>>) {
self.external = pipeline;
}
/// Makes the running shader pack, of either kind, forget what it kept from earlier frames:
/// the next frame draws as a freshly loaded pack's first. Nothing to do without a pack.
pub fn reset_shader_pack_history(&mut self) {
// A frame still on the submit thread uses the targets and readbacks replaced
// here.
self.land_frame();
if let Some(pipeline) = &mut self.external {
pipeline.reset_history();
}
if let Some((_, Some(post))) = &mut self.pack_post {
post.reset_history(&self.device);
}
@@ -7540,10 +7553,6 @@ impl Renderer {
}
});
horizon_shaders::GameInputs {
terrain_parts: terrain
.as_ref()
.map(|t| pack_atlas::terrain_parts(t, &self.pack_lava_layers)),
terrain,
terrain_geometry,
entity_geometry: Some(pack_entities::geometry_inputs()),
sky: Some(pack_sky::inputs()),
@@ -7553,6 +7562,7 @@ impl Renderer {
weather: Some(pack_weather::inputs()),
lines: Some(pack_lines::inputs()),
hand: Some(pack_hand::inputs()),
..pack_atlas::game_terrain(terrain, &self.pack_lava_layers)
}
}
@@ -8603,6 +8613,13 @@ impl Renderer {
// A shader pack's shadow pass draws the sections in its camera's box, all of them (the
// occlusion graph follows the eye, not the light), within shadowDistanceRenderMul; for
// an Iris-format pack, only those whose shadow can fall into the camera's view.
let state = external::FrameState {
frame,
output: &output,
};
if let Some(pipeline) = self.external.as_mut().filter(|_| !frame.title) {
pipeline.begin_frame(&state);
}
let shadow_view = self
.pack_post
.as_ref()
@@ -8614,6 +8631,12 @@ impl Renderer {
let native = self.native.as_ref().filter(|_| !frame.title)?;
native.shadow.as_ref()?;
native.frame.shadow_view(frame)
})
.or_else(|| {
self.external
.as_ref()
.filter(|_| !frame.title)?
.shadow_request(&state)
});
// `LevelRenderer.extractSectionDrawGroups`' fade-in time, for the instances.
let fade_ms = fade_millis(frame.chunk_fade);
@@ -11903,13 +11926,12 @@ impl Renderer {
{
self.readback.present(&self.device, &mut encoder, image);
}
// A 0.2 pack is shown at paper white: HDR output lifts nothing of its world.
let lifts_world = !frame.title
&& self.output.frame.format != LINEAR_FRAME
&& self
.native
.as_ref()
.is_none_or(|n| n.frame.api == horizon_shader_api::Api::V0_1);
let lifts_world = output::lifts_world(
frame.title,
self.output.frame.format == LINEAR_FRAME,
self.shader_pack_kind() == Some("iris"),
self.native.as_ref().map(|n| n.frame.api),
);
match (&self.hdr, &surface_frame) {
(Some(hdr), Some(f)) => hdr.present(
&self.queue,
@@ -12745,61 +12767,6 @@ impl Cull for Frusta {
self.0.contains(min, max) || self.1.is_some_and(|f| f.contains(min, max))
}
}
/// A shader pack's shadow camera's box, and with `casters` only what can shade the camera's view
/// (`shadow_casters`): a box must meet all of them.
#[derive(Clone, Copy, Debug)]
pub struct ShadowCull {
pub light: Frustum,
pub casters: Option<[Frustum; 2]>,
/// `shadowDistance × shadowDistanceRenderMul`: only what lies within this many blocks of the
/// camera along each axis, a cube around it. Our probe's Iris 1.11.7 maps keep the sections
/// whose box, grown by `SHADOW_CASTER_MARGIN` as for the casters, meets that cube (#8464):
/// out to its corners, and a section 1 block past its side but not one 1.5 blocks past.
pub reach: Option<f32>,
}
impl ShadowCull {
/// Whether the camera-relative box `min..max`, grown by the margin, meets (`whole`: lies
/// within) `reach`'s cube.
fn within_reach(&self, min: Vec3, max: Vec3, whole: bool) -> bool {
let (min, max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.reach.is_none_or(|d| {
if whole {
min.cmpge(Vec3::splat(-d)).all() && max.cmple(Vec3::splat(d)).all()
} else {
max.cmpge(Vec3::splat(-d)).all() && min.cmple(Vec3::splat(d)).all()
}
})
}
}
/// How far past a section's 16 blocks the shadow pass looks for what can shade the view: our
/// probes' Iris 1.11.7 maps keep the sections whose box, grown by this much on every side, meets
/// `shadow_casters`' shape. Over 76 scenes at fields of view 30 to 110, Iris keeps every section
/// that needs up to 1.1224 blocks and drops every one that needs 1.1252 or more (#8464): one
/// growth, whatever the field of view, of 9/8 (a fit, not Iris's code). Without it the edges of
/// the wedge lose a column of terrain.
const SHADOW_CASTER_MARGIN: f32 = 1.125;
impl Cull for ShadowCull {
fn intersects(&self, min: Vec3, max: Vec3) -> bool {
let (grown_min, grown_max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.within_reach(min, max, false)
&& self.light.intersects(min, max)
&& self
.casters
.is_none_or(|c| c.iter().all(|f| f.intersects(grown_min, grown_max)))
}
fn contains(&self, min: Vec3, max: Vec3) -> bool {
let (grown_min, grown_max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.within_reach(min, max, true)
&& self.light.contains(min, max)
&& self
.casters
.is_none_or(|c| c.iter().all(|f| f.contains(grown_min, grown_max)))
}
/// Our probe's Iris 1.11.7 maps fit testing the casters' whole sections (a guess that matched).
fn tight(&self) -> bool {
self.casters.is_none()
}
}
/// The block entities of `sections` whose box, a block wider on every side, comes within the
/// 64 blocks block entities are drawn to (`Renderer::visible_block_entities_in_frustum`).
fn block_entities_within_reach<'a>(
@@ -12822,17 +12789,6 @@ fn block_entities_within_reach<'a>(
})
.flatten()
}
/// The shadow camera's box that the shadow pass draws terrain in: the sides of `view.cull`, and
/// its near and far planes only with `depth_planes`.
fn shadow_box(view: &pack_post::ShadowView) -> Frustum {
let mut planes = frustum(view.cull);
if !view.depth_planes {
// `frustum`'s faces at depth 0 and 1 take in everything.
planes[4] = Vec4::W;
planes[5] = Vec4::W;
}
Frustum { planes }
}
/// Camera-relative clip planes (`Frustum`).
#[derive(Clone, Copy, Debug)]
pub struct Frustum {
@@ -12956,21 +12912,6 @@ fn projection_center(view_proj: Mat4) -> Option<Vec3> {
let b = DVec3::new(rows[0].w, rows[1].w, rows[2].w);
Some((a.inverse() * -b).as_vec3())
}
/// The runs of a section's solid quads the shadow pass draws: every face within the unculled
/// distance, or everywhere for `every_face`; else the quads that can face the light.
fn shadow_runs(
sides: &Sides,
view: &pack_post::ShadowView,
origin: [f32; 3],
draw: impl FnMut(u32, u32),
) {
let unculled = view.unculled.is_some_and(|d| {
let o = Vec3::from(origin) + 8.0;
o.x.abs().max(o.z.abs()) <= d + 8.0
});
let toward = (!unculled && !view.every_face).then_some(view.light * 1.0e5);
facing_runs(sides, toward, origin, draw);
}
/// Calls `draw(first, quads)` for each run of a mesh's solid quads that can
/// face `eye` (`projection_center`), the mesh at the camera-relative
@@ -12997,68 +12938,6 @@ fn facing_runs_from(
None => sides.every(part, draw),
}
}
/// The camera's view `view_proj` (wgpu depth, reversed or not) stretched without end toward
/// `light` (a direction): the boxes whose shadow, cast away from the light, can fall into the
/// view. Its planes are the view's faces turned toward the light, and through each edge between
/// such a face and one turned away, the plane along the light; unused ones take in everything.
fn shadow_casters(view_proj: Mat4, light: Vec3) -> [Frustum; 2] {
let faces = frustum(view_proj);
let toward = faces.map(|p| p.truncate().dot(light) >= 0.0);
let inverse = view_proj.inverse();
// Corner (x, y, z) of clip space's box; `frustum`'s faces at x -1 and 1 are 0 and 1, at
// y -1 and 1 are 2 and 3, at depth 0 and 1 are 4 and 5.
let corner = |c: [usize; 3]| {
inverse.project_point3(Vec3::new(
c[0] as f32 * 2.0 - 1.0,
c[1] as f32 * 2.0 - 1.0,
c[2] as f32,
))
};
let corners: Vec<[usize; 3]> = (0..8).map(|i| [i & 1, (i >> 1) & 1, i >> 2]).collect();
let centre = corners.iter().map(|&c| corner(c)).sum::<Vec3>() / 8.0;
let mut planes = [Vec4::W; 12];
let mut n = 0;
for (k, &face) in faces.iter().enumerate() {
if toward[k] {
planes[n] = face;
n += 1;
}
}
for a in &corners {
for axis in 0..3 {
if a[axis] == 1 {
continue;
}
let mut b = *a;
b[axis] = 1;
// The edge from a to b lies on the faces of the two other axes.
let [f, g] = [(axis + 1) % 3, (axis + 2) % 3].map(|o| o * 2 + a[o]);
if toward[f] == toward[g] {
continue;
}
let (p, q) = (corner(*a), corner(b));
let normal = (q - p).cross(light);
if normal.length_squared() < 1e-12 {
continue;
}
let normal = normal.normalize();
let side = if normal.dot(centre - p) < 0.0 {
-1.0
} else {
1.0
};
// At most six such edges with at most four faces toward the light: 12 planes.
if let Some(plane) = planes.get_mut(n) {
*plane = (normal * side).extend(-normal.dot(p) * side);
n += 1;
}
}
}
let [a, b] = [0, 6].map(|i| Frustum {
planes: planes[i..i + 6].try_into().expect("six planes"),
});
[a, b]
}
fn taa_frustum(view_proj: Mat4, rendered_size: [u32; 2]) -> Frustum {
// TAA shifts clip x/y by at most half a rendered pixel times clip w.
// Widen x/y before extracting the planes: this includes every such shifted
@@ -15068,11 +14947,21 @@ mod sprite_upload_tests {
limit_bucket: None,
};
info.backend = wgpu::Backend::Metal;
assert_eq!(adapter_requested_split(&info, None), Some(512));
assert_eq!(adapter_requested_split(&info, Some(1024)), Some(1024));
assert_eq!(adapter_requested_split(&info, None, 1200), Some(512));
assert_eq!(
adapter_requested_split(&info, None, 512 * SPRITE_ARRAYS),
Some(512)
);
assert_eq!(adapter_requested_split(&info, Some(1024), 1200), Some(1024));
// More sprites than the arrays hold at 512: the arrays grow, up to the GPU's layers.
let split = adapter_requested_split(&info, None, 10_271);
assert_eq!(split, Some(1284));
assert_eq!(layer_split(2048, false, split, 10_271), Ok(1284));
let split = adapter_requested_split(&info, None, 2048 * SPRITE_ARRAYS + 1);
assert!(layer_split(2048, false, split, 2048 * SPRITE_ARRAYS + 1).is_err());
info.backend = wgpu::Backend::Vulkan;
assert_eq!(adapter_requested_split(&info, None), None);
assert_eq!(adapter_requested_split(&info, None, 10_271), None);
}
#[test]
@@ -15357,7 +15246,7 @@ mod shadow_face_tests {
}
/// The layers (faces) of the quads the shadow pass draws of `solid`.
fn drawn(view: &pack_post::ShadowView, origin: [f32; 3]) -> Vec<u16> {
fn drawn(view: &external::ShadowView, origin: [f32; 3]) -> Vec<u16> {
let mut solid = block([7.0, 7.0, 7.0]);
let sides = crate::mesher::sort_tinted(&mut solid, &mut Vec::new());
let mut layers = Vec::new();
@@ -15370,8 +15259,8 @@ mod shadow_face_tests {
layers
}
fn view(every_face: bool) -> pack_post::ShadowView {
pack_post::ShadowView {
fn view(every_face: bool) -> external::ShadowView {
external::ShadowView {
cull: Mat4::IDENTITY,
light: Vec3::Y,
distance: None,
@@ -15585,7 +15474,7 @@ mod shadow_caster_tests {
..horizon_shaders::Shadow::default()
};
let camera = DVec3::new(13.5, y + 1.62, -13.5);
let view = pack_post::ShadowView {
let view = external::ShadowView {
cull: pack_uniforms::shadow_culling_at(Vec3::Y, camera, &shadow),
light: Vec3::Y,
distance: None,
@@ -0,0 +1,42 @@
//! A bind group's validity depends on the identity of its buffers and the
//! bound slice, not on the bytes written into those buffers.
pub(super) struct BindingKey<B, const N: usize> {
pub first: u64,
pub count: u64,
pub buffers: [B; N],
}
impl<B: PartialEq, const N: usize> BindingKey<B, N> {
pub fn matches(&self, first: u64, count: u64, buffers: [&B; N]) -> bool {
self.first == first
&& self.count == count
&& self
.buffers
.iter()
.zip(buffers)
.all(|(old, new)| old == new)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn changes_to_any_resource_or_range_invalidate_the_binding() {
let key = BindingKey {
first: 16,
count: 8,
buffers: [1u64, 2, 3, 4],
};
assert!(key.matches(16, 8, [&1, &2, &3, &4]));
assert!(!key.matches(0, 8, [&1, &2, &3, &4]));
assert!(!key.matches(16, 9, [&1, &2, &3, &4]));
for i in 0..4 {
let mut resources = [1u64, 2, 3, 4];
resources[i] += 100;
assert!(!key.matches(16, 8, resources.each_ref()));
}
}
}
+48 -5
View File
@@ -37,7 +37,9 @@
//! are drawn in a pass of their own between the phases, which reads phase
//! 1's depth as a texture and makes the same comparison in the shader: the
//! fragment's depth against the stored one, greater or equal passing. The
//! same fragments pass, so the same sections are seen.
//! same fragments pass, so the same sections are seen. Adreno's Vulkan driver
//! takes that path too: with the early test it now and then leaves sections
//! out for a frame.
use std::num::NonZeroU64;
use std::sync::{
Arc,
@@ -220,17 +222,42 @@ const RESULTS_USAGE: wgpu::BufferUsages =
const READBACK_USAGE: wgpu::BufferUsages =
wgpu::BufferUsages::MAP_READ.union(wgpu::BufferUsages::COPY_DST);
/// The first `n` values of a packed lookup in WGSL `source` (`fn name`, as cull.wgsl's
/// `box_triangle_corner`): four bits each, eight a word, its words in the order of its cases.
#[cfg(test)]
pub(super) fn packed_lookup(source: &str, name: &str, n: usize) -> Vec<u32> {
let body = &source[source.find(&format!("fn {name}(")).expect("the lookup")..];
let body = &body[..body.find("return").expect("its return")];
let words: Vec<u32> = body
.split(|c: char| !c.is_ascii_alphanumeric())
.filter_map(|t| t.strip_prefix("0x")?.strip_suffix('u'))
.map(|hex| u32::from_str_radix(hex, 16).expect("a hex word"))
.collect();
(0..n)
.map(|v| (words[v / 8] >> (v % 8 * 4)) & 0xf)
.collect()
}
/// Qualcomm's PCI vendor id, which wgpu reports for Adreno GPUs.
const ADRENO: u32 = 0x5143;
impl Cull {
/// The device feature culling needs, where the adapter has it.
pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features {
adapter.features() & wgpu::Features::SHADER_EARLY_DEPTH_TEST
}
/// Where the device can run the test, if it can: Vulkan with early
/// depth tests, or Metal and DirectX 12 with the test in the shader, all
/// drawing an indirect multi-draw's entries with the instance counts the
/// GPU wrote, with fragment shaders that write storage.
/// depth tests (Adreno's in the shader), or Metal and DirectX 12 with the
/// test in the shader, all drawing an indirect multi-draw's entries with
/// the instance counts the GPU wrote, with fragment shaders that write
/// storage.
pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Option<DepthTest> {
let depth_test = match adapter.get_info().backend {
let info = adapter.get_info();
let depth_test = match info.backend {
// Adreno's Vulkan driver (the AYANEO Pocket DS's Adreno 740, build 0676.41) now and
// then leaves sections out with the early test, the world flashing black or
// see-through as a block breaks; the test in the shader, as on Metal, holds.
wgpu::Backend::Vulkan if info.vendor == ADRENO => DepthTest::InShader,
wgpu::Backend::Vulkan | wgpu::Backend::Gl
if device
.features()
@@ -772,4 +799,20 @@ mod tests {
.unwrap_or_else(|e| panic!("{depth_test:?}: {e:?}"));
}
}
/// The box's 12 triangles, as cull.wgsl and gpu_occlusion.wgsl draw them: two per face,
/// counter-clockwise seen from outside, corners by bit (x 1, y 2, z 4).
#[test]
fn the_packed_box_corners_are_the_box_triangles() {
let triangles = [
0, 6, 2, 0, 4, 6, 1, 3, 7, 1, 7, 5, 0, 1, 5, 0, 5, 4, 2, 7, 3, 2, 6, 7, 0, 3, 1, 0, 2,
3, 4, 5, 7, 4, 7, 6,
];
for source in [
include_str!("cull.wgsl"),
include_str!("gpu_occlusion.wgsl"),
] {
assert_eq!(packed_lookup(source, "box_triangle_corner", 36), triangles);
}
}
}
+16 -6
View File
@@ -34,11 +34,21 @@ struct Test {
@group(0) @binding(5) var<uniform> params: Params;
// The corners (bit 0: x, bit 1: y, bit 2: z) of the box's 12 triangles,
// counter-clockwise seen from outside.
const CORNERS = array<u32, 36>(
0u, 6u, 2u, 0u, 4u, 6u, 1u, 3u, 7u, 1u, 7u, 5u, 0u, 1u, 5u, 0u, 5u, 4u,
2u, 7u, 3u, 2u, 6u, 7u, 0u, 3u, 1u, 0u, 2u, 3u, 4u, 5u, 7u, 4u, 7u, 6u,
);
// counter-clockwise seen from outside: 0 6 2, 0 4 6, 1 3 7, 1 7 5, 0 1 5, 0 5 4,
// 2 7 3, 2 6 7, 0 3 1, 0 2 3, 4 5 7, 4 7 6.
// Packed four bits each, eight a word, read through a switch: a constant array indexed by the
// vertex would be a private array, which Adreno's Vulkan compiler (build 0676.41) fails to link.
fn box_triangle_corner(v: u32) -> u32 {
var word: u32;
switch v / 8u {
case 0u: { word = 0x31640260u; }
case 1u: { word = 0x05105717u; }
case 2u: { word = 0x76237245u; }
case 3u: { word = 0x54320130u; }
default: { word = 0x00006747u; }
}
return (word >> (v % 8u * 4u)) & 0xfu;
}
struct Box {
@builtin(position) position: vec4<f32>,
@@ -95,7 +105,7 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box
out.position = select(vec4(0.0, 0.0, 0.0, 1.0), vec4(p, 1.0, 1.0), v < 3u);
return out;
}
out.position = globals.view_proj * vec4(corner(origin, low, high, CORNERS[v]), 1.0);
out.position = globals.view_proj * vec4(corner(origin, low, high, box_triangle_corner(v)), 1.0);
return out;
}
@@ -0,0 +1,214 @@
//! The hook an external shader pipeline fills (#14035, layer plan M6). A shader pack's runtime
//! (a platform crate, later) implements [`ExternalPipeline`]; the renderer calls it at fixed
//! points of a world frame and draws vanilla's way wherever it doesn't answer. With none set
//! (`Renderer::set_external_pipeline`), each point is one `Option` test.
//!
//! Workspace-internal: the trait names the engine's frame, its mesh format and its pass order,
//! has one implementer in this workspace, carries no stability promise and is never exposed to
//! mods. A mesher or pass change updates its implementer in the same PR. HDR output
//! (`output.rs`, `frame_policy`) is not an implementer: it stays the one output stage after the
//! frame, and a pipeline draws into the frame it gives.
//!
//! Shadows are an engine frame point, on request: a pipeline that wants a shadow pass answers
//! [`ShadowView`], the engine culls the sections from it ([`ShadowCull`]) and hands back the
//! terrain seen from the light. Vanilla's path never asks, so it never computes shadow
//! visibility.
use glam::{Mat4, Vec3, Vec4};
use super::{Cull, EffectiveOutput, Frame, Frustum, Sides, facing_runs, frustum};
/// What a world frame gives an external pipeline at its points: the frame's own values, and
/// the display's from the renderer's one output snapshot (`EffectiveOutput`: whether HDR is on,
/// paper white, peak), never worked out again, so each split-screen window keeps its own.
pub struct FrameState<'a> {
pub frame: &'a Frame<'a>,
pub output: &'a EffectiveOutput,
}
/// An external shader pipeline, called by the renderer at fixed points of a world frame (not
/// title frames). Every method has a default that leaves vanilla's way in place.
pub trait ExternalPipeline: Send {
/// A world frame starts, before culling.
fn begin_frame(&mut self, _state: &FrameState<'_>) {}
/// The shadow pass this frame wants; `None` draws none.
fn shadow_request(&self, _state: &FrameState<'_>) -> Option<ShadowView> {
None
}
/// The window's drawable size changed.
fn resize(&mut self, _size: [u32; 2]) {}
/// Forget what was kept from earlier frames: the next is drawn as a fresh pipeline's first.
fn reset_history(&mut self) {}
}
/// What the shadow camera sees of the terrain, for the game's draw lists: its view and
/// projection in wgpu's clip space, the direction toward the light, and how far from the camera
/// terrain is drawn (`shadowDistanceRenderMul`).
pub struct ShadowView {
pub cull: glam::Mat4,
pub light: glam::Vec3,
pub distance: Option<f32>,
/// Draw everything, every face, within this many blocks (`shadow.culling=false|reversed`):
/// packs that voxelize the world in their shadow pass need all of it.
pub unculled: Option<f32>,
/// Every face of the drawn sections, not only those that can face the light. Iris 1.11.7's
/// shadow map holds the faces turned away from the light too (#9033): under a hill at low sun
/// a cave's ceiling, which faces away, is often all that shadows the cave.
pub every_face: bool,
/// Only the sections whose shadow can fall into the camera's view: those the camera's
/// frustum, stretched toward the light, takes in (`shadow_casters`). Our probes' Iris 1.11.7
/// maps fit keeping only those with `shadow.culling` unset (#8464): under a noon sun, only
/// the terrain above the ground the camera sees; with a low sun ahead, none behind the camera.
pub view_casters: bool,
/// Whether the projection's near and far planes in `cull` drop sections too. Our probes'
/// Iris 1.11.7 maps hold the terrain at every depth we put it along the light (from 535 blocks
/// beyond the shadow camera to about 120 before it), whatever `shadowNearPlane` and
/// `shadowFarPlane` the pack sets, or none (#10403): only its sides cull.
pub depth_planes: bool,
}
/// A shader pack's shadow camera's box, and with `casters` only what can shade the camera's view
/// (`shadow_casters`): a box must meet all of them.
#[derive(Clone, Copy, Debug)]
pub struct ShadowCull {
pub light: Frustum,
pub casters: Option<[Frustum; 2]>,
/// `shadowDistance × shadowDistanceRenderMul`: only what lies within this many blocks of the
/// camera along each axis, a cube around it. Our probe's Iris 1.11.7 maps keep the sections
/// whose box, grown by `SHADOW_CASTER_MARGIN` as for the casters, meets that cube (#8464):
/// out to its corners, and a section 1 block past its side but not one 1.5 blocks past.
pub reach: Option<f32>,
}
impl ShadowCull {
/// Whether the camera-relative box `min..max`, grown by the margin, meets (`whole`: lies
/// within) `reach`'s cube.
fn within_reach(&self, min: Vec3, max: Vec3, whole: bool) -> bool {
let (min, max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.reach.is_none_or(|d| {
if whole {
min.cmpge(Vec3::splat(-d)).all() && max.cmple(Vec3::splat(d)).all()
} else {
max.cmpge(Vec3::splat(-d)).all() && min.cmple(Vec3::splat(d)).all()
}
})
}
}
/// How far past a section's 16 blocks the shadow pass looks for what can shade the view: our
/// probes' Iris 1.11.7 maps keep the sections whose box, grown by this much on every side, meets
/// `shadow_casters`' shape. Over 76 scenes at fields of view 30 to 110, Iris keeps every section
/// that needs up to 1.1224 blocks and drops every one that needs 1.1252 or more (#8464): one
/// growth, whatever the field of view, of 9/8 (a fit, not Iris's code). Without it the edges of
/// the wedge lose a column of terrain.
const SHADOW_CASTER_MARGIN: f32 = 1.125;
impl Cull for ShadowCull {
fn intersects(&self, min: Vec3, max: Vec3) -> bool {
let (grown_min, grown_max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.within_reach(min, max, false)
&& self.light.intersects(min, max)
&& self
.casters
.is_none_or(|c| c.iter().all(|f| f.intersects(grown_min, grown_max)))
}
fn contains(&self, min: Vec3, max: Vec3) -> bool {
let (grown_min, grown_max) = (min - SHADOW_CASTER_MARGIN, max + SHADOW_CASTER_MARGIN);
self.within_reach(min, max, true)
&& self.light.contains(min, max)
&& self
.casters
.is_none_or(|c| c.iter().all(|f| f.contains(grown_min, grown_max)))
}
/// Our probe's Iris 1.11.7 maps fit testing the casters' whole sections (a guess that matched).
fn tight(&self) -> bool {
self.casters.is_none()
}
}
/// The shadow camera's box that the shadow pass draws terrain in: the sides of `view.cull`, and
/// its near and far planes only with `depth_planes`.
pub(super) fn shadow_box(view: &ShadowView) -> Frustum {
let mut planes = frustum(view.cull);
if !view.depth_planes {
// `frustum`'s faces at depth 0 and 1 take in everything.
planes[4] = Vec4::W;
planes[5] = Vec4::W;
}
Frustum { planes }
}
/// The runs of a section's solid quads the shadow pass draws: every face within the unculled
/// distance, or everywhere for `every_face`; else the quads that can face the light.
pub(super) fn shadow_runs(
sides: &Sides,
view: &ShadowView,
origin: [f32; 3],
draw: impl FnMut(u32, u32),
) {
let unculled = view.unculled.is_some_and(|d| {
let o = Vec3::from(origin) + 8.0;
o.x.abs().max(o.z.abs()) <= d + 8.0
});
let toward = (!unculled && !view.every_face).then_some(view.light * 1.0e5);
facing_runs(sides, toward, origin, draw);
}
/// The camera's view `view_proj` (wgpu depth, reversed or not) stretched without end toward
/// `light` (a direction): the boxes whose shadow, cast away from the light, can fall into the
/// view. Its planes are the view's faces turned toward the light, and through each edge between
/// such a face and one turned away, the plane along the light; unused ones take in everything.
pub(super) fn shadow_casters(view_proj: Mat4, light: Vec3) -> [Frustum; 2] {
let faces = frustum(view_proj);
let toward = faces.map(|p| p.truncate().dot(light) >= 0.0);
let inverse = view_proj.inverse();
// Corner (x, y, z) of clip space's box; `frustum`'s faces at x -1 and 1 are 0 and 1, at
// y -1 and 1 are 2 and 3, at depth 0 and 1 are 4 and 5.
let corner = |c: [usize; 3]| {
inverse.project_point3(Vec3::new(
c[0] as f32 * 2.0 - 1.0,
c[1] as f32 * 2.0 - 1.0,
c[2] as f32,
))
};
let corners: Vec<[usize; 3]> = (0..8).map(|i| [i & 1, (i >> 1) & 1, i >> 2]).collect();
let centre = corners.iter().map(|&c| corner(c)).sum::<Vec3>() / 8.0;
let mut planes = [Vec4::W; 12];
let mut n = 0;
for (k, &face) in faces.iter().enumerate() {
if toward[k] {
planes[n] = face;
n += 1;
}
}
for a in &corners {
for axis in 0..3 {
if a[axis] == 1 {
continue;
}
let mut b = *a;
b[axis] = 1;
// The edge from a to b lies on the faces of the two other axes.
let [f, g] = [(axis + 1) % 3, (axis + 2) % 3].map(|o| o * 2 + a[o]);
if toward[f] == toward[g] {
continue;
}
let (p, q) = (corner(*a), corner(b));
let normal = (q - p).cross(light);
if normal.length_squared() < 1e-12 {
continue;
}
let normal = normal.normalize();
let side = if normal.dot(centre - p) < 0.0 {
-1.0
} else {
1.0
};
// At most six such edges with at most four faces toward the light: 12 planes.
if let Some(plane) = planes.get_mut(n) {
*plane = (normal * side).extend(-normal.dot(p) * side);
n += 1;
}
}
}
let [a, b] = [0, 6].map(|i| Frustum {
planes: planes[i..i + 6].try_into().expect("six planes"),
});
[a, b]
}
+99 -45
View File
@@ -19,7 +19,10 @@
//! start, and the run is drawn indirectly with the count the copy reached.
use super::SolidPipeline;
use super::arena::GRAIN;
use smallvec::SmallVec;
#[path = "binding_cache.rs"]
mod binding_cache;
use binding_cache::BindingKey;
/// One section draw for `flatten.wgsl`: index count, first sorted index (or
/// `QUADS` for a solid draw; phase 2: its entry in phase 2's draws), base
@@ -85,6 +88,11 @@ pub struct Call {
pub count: u32,
}
struct CachedGroup<const N: usize> {
key: BindingKey<wgpu::Buffer, N>,
group: wgpu::BindGroup,
}
pub struct Flat {
/// The solid draws in one pass (`fs_solid`), where the GPU doesn't hide pixels
/// by tiles (`split_solid` in `Renderer::draw_frame`: elsewhere than Metal).
@@ -109,8 +117,9 @@ pub struct Flat {
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)>,
/// Bindings reused while the range and all GPU buffers are unchanged.
phase2_group: Option<CachedGroup<4>>,
groups: Vec<CachedGroup<3>>,
/// The layout of a page's bind group 1 (shader packs' terrain pipelines share it).
pub(super) draw_layout: wgpu::BindGroupLayout,
blocks_per_page: u64,
@@ -515,6 +524,7 @@ impl Flat {
phase2_call_data: Vec::new(),
indirect_execution,
phase2_group: None,
groups: Vec::new(),
draw_layout,
blocks_per_page: page_vertices.div_ceil(GRAIN),
translucent_blocks_per_page: page_vertices.div_ceil(GRAIN),
@@ -626,6 +636,8 @@ impl Flat {
}
pub fn clear(&mut self) {
self.pages.clear();
self.groups.clear();
self.phase2_group = None;
self.free_ids.clear();
self.next_id = 0;
}
@@ -665,7 +677,6 @@ impl Flat {
sorted_page: impl Fn(u32) -> wgpu::Buffer,
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
@@ -729,6 +740,9 @@ impl Flat {
self.shadow_calls = shadow_calls;
self.pass_calls = pass_calls;
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
// Do not retain bindings for a frame that cannot use flat draws.
self.phase2_group = None;
self.groups.clear();
self.calls.clear();
self.phase1_calls = 0;
self.solid_calls = 0;
@@ -802,39 +816,63 @@ impl Flat {
phase2,
self.segments.iter().find(|(s, ..)| *s == Source::Seen),
) {
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten phase 2 section draws"),
layout: &self.seen_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: ranges_at(first, count),
let buffers = [&self.ranges, &self.indices, phase2, &self.phase2_calls];
if !self
.phase2_group
.as_ref()
.is_some_and(|cached| cached.key.matches(first, count, buffers))
{
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten phase 2 section draws"),
layout: &self.seen_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: ranges_at(first, count),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: phase2.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.phase2_calls.as_entire_binding(),
},
],
});
self.phase2_group = Some(CachedGroup {
key: BindingKey {
first,
count,
buffers: buffers.map(|b| b.clone()),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: phase2.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.phase2_calls.as_entire_binding(),
},
],
});
self.phase2_group = Some((group, count as u32));
group,
});
}
} else {
self.phase2_group = None;
}
let groups: SmallVec<[(wgpu::BindGroup, u32); 8]> = self
.segments
.iter()
.filter_map(|&(source, first, count)| {
let sorted = match source {
Source::Quads => None,
Source::Seen => return None,
Source::Sorted(page) => Some(sorted_page(page)),
};
let mut groups = 0;
for &(source, first, count) in &self.segments {
let sorted = match source {
Source::Quads => None,
Source::Seen => continue,
Source::Sorted(page) => Some(sorted_page(page)),
};
let buffers = [
&self.ranges,
sorted.as_ref().unwrap_or(&self.empty),
&self.indices,
];
if self
.groups
.get(groups)
.is_none_or(|cached| !cached.key.matches(first, count, buffers))
{
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten section draws"),
layout: &self.compute_layout,
@@ -845,7 +883,7 @@ impl Flat {
},
wgpu::BindGroupEntry {
binding: 1,
resource: sorted.as_ref().unwrap_or(&self.empty).as_entire_binding(),
resource: buffers[1].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
@@ -853,17 +891,32 @@ impl Flat {
},
],
});
Some((group, count as u32))
})
.collect();
let cached = CachedGroup {
key: BindingKey {
first,
count,
buffers: buffers.map(|b| b.clone()),
},
group,
};
if groups < self.groups.len() {
self.groups[groups] = cached;
} else {
self.groups.push(cached);
}
}
groups += 1;
}
self.groups.truncate(groups);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Flatten section draws"),
timestamp_writes: timing.and_then(|t| t.compute_writes("Flatten")),
});
pass.set_pipeline(&self.flatten);
for (group, count) in &groups {
pass.set_bind_group(0, group, &[]);
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
for cached in &self.groups {
let count = cached.key.count as u32;
pass.set_bind_group(0, &cached.group, &[]);
pass.dispatch_workgroups(count.min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
}
drop(pass);
true
@@ -919,16 +972,17 @@ impl Flat {
encoder: &mut wgpu::CommandEncoder,
timing: Option<&mut super::pack_timing::PassTiming>,
) {
let Some((group, count)) = &self.phase2_group else {
let Some(cached) = &self.phase2_group else {
return;
};
let count = cached.key.count as u32;
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Flatten phase 2 section draws"),
timestamp_writes: timing.and_then(|t| t.compute_writes("Flatten phase 2")),
});
pass.set_pipeline(&self.flatten_seen);
pass.set_bind_group(0, group, &[]);
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
pass.set_bind_group(0, &cached.group, &[]);
pass.dispatch_workgroups(count.min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
}
/// The camera's translucent calls.
@@ -9,11 +9,20 @@
@group(0) @binding(12) var<storage, read> box_sections: array<Section>;
// The corners (bit 0: x, bit 1: y, bit 2: z) of the box's 12 triangles,
// counter-clockwise seen from outside (cull.wgsl's).
const CORNERS = array<u32, 36>(
0u, 6u, 2u, 0u, 4u, 6u, 1u, 3u, 7u, 1u, 7u, 5u, 0u, 1u, 5u, 0u, 5u, 4u,
2u, 7u, 3u, 2u, 6u, 7u, 0u, 3u, 1u, 0u, 2u, 3u, 4u, 5u, 7u, 4u, 7u, 6u,
);
// counter-clockwise seen from outside (cull.wgsl's `box_triangle_corner`).
// Packed four bits each, eight a word, read through a switch: a constant array indexed by the
// vertex would be a private array, which Adreno's Vulkan compiler (build 0676.41) fails to link.
fn box_triangle_corner(v: u32) -> u32 {
var word: u32;
switch v / 8u {
case 0u: { word = 0x31640260u; }
case 1u: { word = 0x05105717u; }
case 2u: { word = 0x76237245u; }
case 3u: { word = 0x54320130u; }
default: { word = 0x00006747u; }
}
return (word >> (v % 8u * 4u)) & 0xfu;
}
struct BoxOut {
@builtin(position) position: vec4<f32>,
@@ -26,7 +35,7 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box
let o = bitcast<vec3<f32>>(box_origins[id].xyz);
var out: BoxOut;
out.id = id;
out.position = params.view_proj * vec4(box_corner(o, box_sections[id].a.z, CORNERS[v]), 1.0);
out.position = params.view_proj * vec4(box_corner(o, box_sections[id].a.z, box_triangle_corner(v)), 1.0);
return out;
}
+43 -20
View File
@@ -169,7 +169,8 @@ pub struct Hdr {
hand_mark: wgpu::RenderPipeline,
params: wgpu::Buffer,
/// The same pass drawing HDR10 for a screenshot (`capture`), with its own parameters,
/// so it can differ from the swapchain's in one frame.
/// so it can differ from the swapchain's in one frame, and without the swapchain's dither:
/// a screenshot keeps the exact codes.
capture_pipeline: wgpu::RenderPipeline,
capture_params: wgpu::Buffer,
pub output: Output,
@@ -286,8 +287,9 @@ impl Hdr {
entries: &entries,
})
};
// One full-screen pass of hdr.wgsl's `entry` into `format`, reading `layout`.
let pass = |label, layout: &wgpu::BindGroupLayout, entry, format| {
// One full-screen pass of hdr.wgsl's `entry` into `format`, reading `layout`; `dither`
// for the last pass into the HDR10 swapchain (`pq_dither`).
let pass = |label, layout: &wgpu::BindGroupLayout, entry, format, dither: bool| {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(label),
bind_group_layouts: &[Some(layout)],
@@ -308,7 +310,10 @@ impl Hdr {
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(entry),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[("pq_dither", f64::from(u8::from(dither)))],
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
@@ -321,7 +326,8 @@ impl Hdr {
};
let layout_bindings: &[u32] = if coverage { &[0, 3, 4, 5] } else { &[0, 1, 3] };
let display = layout("Horizon HDR bindings", layout_bindings, true);
let pipeline_for = |format| pass("Horizon HDR", &display, entry_point, format);
let pipeline_for =
|format, dither| pass("Horizon HDR", &display, entry_point, format, dither);
let params = || {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon HDR parameters"),
@@ -333,7 +339,7 @@ impl Hdr {
let layered = coverage.then(|| {
let with = |label, textures: &[u32], params, entry, format| {
let layout = layout(label, textures, params);
let pipeline = pass(label, &layout, entry, format);
let pipeline = pass(label, &layout, entry, format, false);
(layout, pipeline)
};
let hud = super::hud_coverage::HUD_FORMAT;
@@ -395,8 +401,8 @@ impl Hdr {
);
Self {
logo: logo_mask(device, queue),
pipeline: pipeline_for(output.format()),
capture_pipeline: pipeline_for(Output::Pq.format()),
pipeline: pipeline_for(output.format(), output == Output::Pq),
capture_pipeline: pipeline_for(Output::Pq.format(), false),
layout: display,
clear_alpha,
hand_mark,
@@ -1709,19 +1715,32 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
super::super::hud_coverage::clear(&mut encoder, &hdr.coverage_view().unwrap());
hdr.begin(&queue, true);
hdr.present(&queue, &mut encoder, &target, true, None);
let got = texel(&device, &queue, encoder, &target);
for c in &got[..3] {
let c = f64::from(*c);
let ok = match output {
// 10-bit codes, a step either way for rounding.
Output::Pq => (c - 1023.0 * pq(want)).abs() <= 1.0,
// 80 nits a unit, in half floats.
Output::ScRgb => (c * 80.0 - want).abs() <= 2e-3 * want + 1e-4,
// HDR10's exact codes are a screenshot's copy: the swapchain's own get a
// code of dither either way.
let exact = (output == Output::Pq)
.then(|| hdr.capture(&device, &queue, &mut encoder, true).unwrap());
let presented = texel(&device, &queue, encoder, &target);
let exact = exact.map(|copy| {
let encoder = device.create_command_encoder(&Default::default());
texel(&device, &queue, encoder, &copy)
});
for (got, codes) in [(Some(presented), 2.0), (exact, 1.0)] {
let Some(got) = got else {
continue;
};
assert!(
ok,
"{output:?} black {black}, light {light}: {got:?}, not {want} nits"
);
for c in &got[..3] {
let c = f64::from(*c);
let ok = match output {
// 10-bit codes, a step either way for rounding.
Output::Pq => (c - 1023.0 * pq(want)).abs() <= codes,
// 80 nits a unit, in half floats.
Output::ScRgb => (c * 80.0 - want).abs() <= 2e-3 * want + 1e-4,
};
assert!(
ok,
"{output:?} black {black}, light {light}: {got:?}, not {want} nits"
);
}
}
}
}
@@ -2078,3 +2097,7 @@ mod lighting_tests {
#[cfg(test)]
#[path = "hdr_written_tests.rs"]
mod written_tests;
#[cfg(test)]
#[path = "hdr_dither_tests.rs"]
mod dither_tests;
@@ -0,0 +1,313 @@
//! HDR10's dither (`hdr.wgsl`, `dithered`): the last pass into the 10-bit swapchain, and what
//! must stay without it.
use super::{
Hdr, Output,
tests::{fill, gpu},
};
use wgpu::TextureFormat as F;
const SIZE: [u32; 2] = [64, 1024];
/// The ramp: grey rising by one half-float step every `ROWS` rows from `FIRST / 2048`. That is
/// three PQ codes down the picture around 91 nits: as slow as a clear sky, and as fine as the
/// float frame holds.
const FIRST: u32 = 1434;
const ROWS: u32 = 52;
/// SMPTE ST 2084: nits as a 10-bit PQ code, before rounding.
fn code(nits: f64) -> f64 {
let y = (nits / 10_000.0).powf(0.1593017578125);
1023.0 * ((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y)).powf(78.84375)
}
/// The ramp's row `y` as a PQ code, at the 200-nit paper white `Hdr` starts with.
fn ramp_code(y: u32) -> f64 {
code(200.0 * (f64::from(FIRST + y / ROWS) / 2048.0).powf(2.2))
}
fn ramp(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture) {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(
format!(
r#"
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {{
return vec4(vec2(f32((i << 1u) & 2u), f32(i & 2u)) * 2.0 - 1.0, 0.0, 1.0);
}}
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {{
return vec4(vec3(f32({FIRST}u + u32(pos.y) / {ROWS}u) / 2048.0), 1.0);
}}
"#
)
.into(),
),
});
let pipeline = device.create_render_pipeline(&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: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[Some(frame.format().into())],
}),
multiview_mask: None,
cache: None,
});
let view = frame.create_view(&Default::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(super::super::hud_coverage::attachment(&view))],
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.draw(0..3, 0..1);
}
/// What `hdr` writes for the float frame `paint` fills, with no HUD over it: its last pass into
/// a swapchain image of its output (`Hdr::present`), or a screenshot's HDR10 copy
/// (`Hdr::capture`). Every pixel's bytes, row by row.
fn shown(
(device, queue): &(wgpu::Device, wgpu::Queue),
hdr: &mut Hdr,
screenshot: bool,
paint: impl Fn(&mut wgpu::CommandEncoder, &wgpu::Texture),
) -> Vec<u8> {
let frame = hdr.frame(device, SIZE);
let mut encoder = device.create_command_encoder(&Default::default());
paint(&mut encoder, &frame);
hdr.keep_world(&mut encoder, None);
super::super::hud_coverage::clear(&mut encoder, &hdr.coverage_view().unwrap());
let image = if screenshot {
hdr.capture(device, queue, &mut encoder, true).unwrap()
} else {
let image = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: frame.size(),
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: hdr.output.format(),
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
hdr.present(queue, &mut encoder, &image, true, None);
image
};
let row = SIZE[0] * image.format().block_copy_size(None).unwrap();
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(row * SIZE[1]),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
image.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(row),
rows_per_image: None,
},
},
image.size(),
);
queue.submit([encoder.finish()]);
buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
buffer.get_mapped_range(..).unwrap().to_vec()
}
fn float_hdr((device, queue): &(wgpu::Device, wgpu::Queue), output: Output) -> Hdr {
Hdr::with_debug(device, queue, F::Rgba16Float, output, true, None)
}
/// An HDR10 picture's 10-bit codes, red, green and blue.
fn codes(bytes: &[u8]) -> Vec<[u32; 3]> {
let pixels = bytes.as_chunks::<4>().0.iter();
pixels
.map(|p| [0, 10, 20].map(|shift| (u32::from_le_bytes(*p) >> shift) & 0x3ff))
.collect()
}
/// Down every column of a channel: the longest run of rows with one code, and the runs' mean
/// length.
fn runs(codes: &[[u32; 3]], channel: usize) -> (u32, f64) {
let (mut longest, mut count) = (0, 0);
for x in 0..SIZE[0] {
let mut run = 0;
for y in 0..SIZE[1] {
let at = |y: u32| codes[(y * SIZE[0] + x) as usize][channel];
if y > 0 && at(y) != at(y - 1) {
(longest, count, run) = (longest.max(run), count + 1, 0);
}
run += 1;
}
(longest, count) = (longest.max(run), count + 1);
}
(longest, f64::from(SIZE[0] * SIZE[1]) / f64::from(count))
}
/// Whether every row of a picture is one value from side to side: no noise in it.
fn rows_are_flat(bytes: &[u8]) -> bool {
let pixel = bytes.len() / (SIZE[0] * SIZE[1]) as usize;
bytes
.chunks(pixel * SIZE[0] as usize)
.all(|row| row.chunks(pixel).all(|p| p == &row[..pixel]))
}
#[test]
fn a_slow_gradient_gets_grain_instead_of_bands_on_hdr10() {
let Some(gpu) = gpu() else {
return;
};
let ramp = |encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture| {
ramp(&gpu.0, encoder, frame);
};
let mut hdr = float_hdr(&gpu, Output::Pq);
// The ramp is what the test says: three codes, top to bottom.
let span = ramp_code(SIZE[1] - 1) - ramp_code(0);
assert!((2.9..3.2).contains(&span), "{span}");
// Without dither, as a screenshot's copy stays: each row its nearest code, in bands hundreds
// of rows tall. A GPU need not round at exactly half a code: an NVIDIA one rounds up from
// 0.55 here, which shows as 0.05 of a code less, so the bounds below leave a quarter code.
let plain = codes(&shown(&gpu, &mut hdr, true, ramp));
let dithered = codes(&shown(&gpu, &mut hdr, false, ramp));
let want = |i: usize| ramp_code(i as u32 / SIZE[0]);
for channel in 0..3 {
for (i, p) in plain.iter().enumerate() {
let off = (f64::from(p[channel]) - want(i)).abs();
assert!(
off <= 0.75,
"plain {channel} at {i}: {p:?}, not {}",
want(i)
);
}
let (longest, _) = runs(&plain, channel);
assert!(longest >= 250, "plain {channel}: bands of {longest} rows");
// With it: each pixel within the noise's one code of its light (and half a code of
// rounding), no column holds a code for long, and a run is a few rows on average.
for (i, d) in dithered.iter().enumerate() {
let off = (f64::from(d[channel]) - want(i)).abs();
assert!(
off <= 1.75,
"dithered {channel} at {i}: {d:?}, not {}",
want(i)
);
}
let (longest, mean) = runs(&dithered, channel);
eprintln!(
"HDR10 dither GPU, channel {channel}: longest run {longest} rows, mean {mean:.2}"
);
assert!(longest <= 64, "dithered {channel}: a run of {longest} rows");
assert!(mean < 4.0, "dithered {channel}: runs of {mean} rows");
// The mean of each 64-row block is the light meant.
let mut worst = 0.0_f64;
for block in 0..SIZE[1] / 64 {
let rows = (block * 64 * SIZE[0]) as usize..((block + 1) * 64 * SIZE[0]) as usize;
let n = rows.len() as f64;
let got = dithered[rows.clone()]
.iter()
.map(|d| f64::from(d[channel]))
.sum::<f64>()
/ n;
let meant = rows.map(want).sum::<f64>() / n;
worst = worst.max((got - meant).abs());
assert!(
(got - meant).abs() < 0.25,
"block {block} of {channel}: {got}, not {meant}"
);
}
eprintln!("HDR10 dither GPU, channel {channel}: block means within {worst:.3} of a code");
}
}
#[test]
fn hdr10s_dither_keeps_both_ends_exact_and_leans_to_them_in_their_last_code() {
let Some(gpu) = gpu() else {
return;
};
let mut hdr = float_hdr(&gpu, Output::Pq);
let grey = |g: f64| {
move |encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture| {
fill(encoder, frame, [g, g, g, 1.0]);
}
};
// How far the picture's mean code is from `end`.
let mean_from = |picture: &[[u32; 3]], end: f64| {
let sum: f64 = picture.iter().flatten().map(|c| f64::from(*c)).sum();
(sum / (picture.len() * 3) as f64 - end).abs()
};
// Within a code of an end the noise shrinks to the distance to it. A third of a code from
// the end, the signal plus that noise passes half a code only where the noise is over half
// its range, an eighth of a triangle: so the picture's mean is an eighth of a code from the
// end, not a third. That lean to the end, in the last code alone, is the price of keeping
// the end itself exact. Bound: a GPU that rounds a tenth of a code off the half (as above)
// shows between 0.02 and 0.32 of a code, always short of the third.
let leans = |mean: f64| (0.015..0.325).contains(&mean);
// Black gets no noise: every pixel stays off.
let black = codes(&shown(&gpu, &mut hdr, false, grey(0.0)));
assert!(black.iter().all(|p| *p == [0; 3]));
// A third of a code above black (this grey is a half float): 0 or 1, never lifted past it.
let dim = 0.00038433074951171875;
let meant = code(200.0 * f64::powf(dim, 2.2));
assert!((meant - 1.0 / 3.0).abs() < 0.001, "{meant}");
let near_black = codes(&shown(&gpu, &mut hdr, false, grey(dim)));
assert!(near_black.iter().flatten().all(|c| *c <= 1));
let mean = mean_from(&near_black, 0.0);
eprintln!("HDR10 dither GPU: a third of a code above black shows as {mean:.3}");
assert!(leans(mean), "{mean} above black");
// The top of the range, PQ's 10 000 nits, stays the top: nothing wraps or dims. Light past
// the peak is held at it, so the Peak setting is the signal here.
hdr.peak = 10_000.0;
let top = codes(&shown(&gpu, &mut hdr, false, grey(20.0)));
assert!(top.iter().all(|p| *p == [1023; 3]));
// A third of a code under the top, mirrored: 1022 or 1023.
let (mut under, mut over) = (9000.0, 10_000.0);
for _ in 0..60 {
let middle = (under + over) / 2.0;
if code(middle) < 1023.0 - 1.0 / 3.0 {
under = middle;
} else {
over = middle;
}
}
hdr.peak = under as f32;
let meant = code(f64::from(hdr.peak));
assert!((1023.0 - meant - 1.0 / 3.0).abs() < 0.001, "{meant}");
let near_top = codes(&shown(&gpu, &mut hdr, false, grey(20.0)));
assert!(near_top.iter().flatten().all(|c| *c >= 1022));
let mean = mean_from(&near_top, 1023.0);
eprintln!("HDR10 dither GPU: a third of a code under the top shows as {mean:.3} under");
assert!(leans(mean), "{mean} under the top");
}
#[test]
fn scrgb_and_screenshots_get_no_dither() {
let Some(gpu) = gpu() else {
return;
};
let ramp = |encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture| {
ramp(&gpu.0, encoder, frame);
};
let (mut hdr10, mut scrgb) = (float_hdr(&gpu, Output::Pq), float_hdr(&gpu, Output::ScRgb));
// scRGB's swapchain is float: every row is one value from side to side.
assert!(rows_are_flat(&shown(&gpu, &mut scrgb, false, ramp)));
// A screenshot's HDR10 copy is the same bytes whichever swapchain is presented, the
// dithered one included, and has no noise in it.
let screenshot = shown(&gpu, &mut hdr10, true, ramp);
assert!(rows_are_flat(&screenshot));
assert_eq!(screenshot, shown(&gpu, &mut scrgb, true, ramp));
// The swapchain's own picture differs from it: the dither is on there.
assert_ne!(screenshot, shown(&gpu, &mut hdr10, false, ramp));
}
@@ -8,7 +8,7 @@
use glam::{Mat4, Vec3};
use horizon_shader_api::{
Api, Frame as FrameInputs, StageKind, check::CheckedStage, stages::GROUP,
Api, Frame as FrameInputs, Primaries, StageKind, check::CheckedStage, stages::GROUP,
};
use super::Frame;
@@ -1596,7 +1596,11 @@ pub fn frame_inputs(
paper_white: 80.0,
peak: 80.0,
black_level: 0.0,
padding: [0; 3],
// No pack is served another space yet (`[frame] primaries`).
primaries: Primaries::Bt709 as u32,
luminance_gap: [0; 2],
luminance: Primaries::Bt709.luminance(),
padding: 0,
}
}
@@ -42,6 +42,8 @@ const DISTANT_SQR: f64 = 3600.0;
const SECTION_DIAGONAL: f64 = 28.0;
/// In `Graph::rays`: the line from this corner stays in reached sections.
const SEES: u8 = u8::MAX;
/// Edits kept before a full resend.
const EDIT_CAP: usize = 1 << 16;
/// VisGraph connectivity per column, one entry per section (bottom first).
/// A missing column or section connects every face.
@@ -611,6 +613,8 @@ pub struct Occlusion {
queue: VecDeque<u32>,
/// Changes whenever `contains` may answer differently (`generation`).
generation: u64,
/// Set when edits were dropped; the next search resends every column.
resync: bool,
}
impl Occlusion {
@@ -631,6 +635,7 @@ impl Occlusion {
vis: Vec::new(),
queue: VecDeque::new(),
generation: next_generation(),
resync: false,
}
}
pub fn set(&mut self, key: SectionKey, vis: u64) {
@@ -639,13 +644,35 @@ impl Occlusion {
}
}
fn changed(&mut self, key: SectionKey, vis: u64) {
self.edits.push(Edit::Set(key, vis));
self.dirty = true;
if self.edits.len() >= EDIT_CAP || self.changed.len() >= EDIT_CAP {
// nobody drains these with cave culling off
self.resync = true;
self.edits.clear();
self.changed.clear();
self.changed_late.clear();
}
if self.resync {
return;
}
self.edits.push(Edit::Set(key, vis));
self.changed.push(key);
if self.running.is_some() {
self.changed_late.push(key);
}
}
fn resync_edits(&mut self) {
self.resync = false;
self.edits.clear();
self.edits.push(Edit::Clear);
for (&(x, z), column) in &self.columns.map {
for (y, &vis) in column.iter().enumerate() {
if vis != ALL_VISIBLE {
self.edits.push(Edit::Set((x, y as i32, z), vis));
}
}
}
}
/// Every section of the column `x`, `z` goes (sees through every face).
pub fn remove_column(&mut self, x: i32, z: i32) {
let Some(column) = self.columns.map.remove(&(x, z)) else {
@@ -674,6 +701,7 @@ impl Occlusion {
self.columns.map.clear();
self.edits.clear();
self.edits.push(Edit::Clear);
self.resync = false;
self.dirty = true;
// Another world: the old graph says nothing about it. Without one, every
// section was visible already, and stays so.
@@ -769,6 +797,9 @@ impl Occlusion {
let from = self.columns.section_of(camera);
self.dirty = false;
self.searched = Some((from, radius));
if self.resync {
self.resync_edits();
}
let graph = std::mem::take(&mut self.spare);
if let Some(worker) = &self.worker {
let job = Job {
@@ -1793,4 +1824,36 @@ mod tests {
assert_ne!(answers(&o, around, spread + radius), walled.1);
assert_ne!(o.generation(), walled.0, "the graph went");
}
#[test]
fn edit_queue_stays_bounded_without_searches() {
let mut o = Occlusion::new(0, 4);
let total = (1usize << 16) + 5000;
for i in 0..total {
o.set(((i % 700) as i32, 1, (i / 700) as i32), 1 + (i as u64 % 5));
}
assert!(o.edits.len() <= 1 << 16, "{} edits queued", o.edits.len());
assert!(
o.changed.len() <= 1 << 16,
"{} changed queued",
o.changed.len()
);
let mut fresh = Occlusion::new(0, 4);
for (&(x, z), column) in &o.columns.map {
for (y, &vis) in column.iter().enumerate() {
fresh.set((x, y as i32, z), vis);
}
}
let camera = at((0, 1, 0));
for _ in 0..2 {
o.settle(camera, 6);
fresh.settle(camera, 6);
}
assert_eq!(
reached(&o),
reached(&fresh),
"the worker saw the same world"
);
}
}
@@ -295,6 +295,22 @@ pub(crate) fn resolve_output(
}
}
/// Whether HDR output lifts the world's light-source marks above paper white. Not on the title
/// screen or the float frame, and not under a pack that lights its world itself: a 0.2 pack is
/// shown at paper white, and a `shaders/` pack's `final` pass leaves its own alpha in the
/// frame, which isn't marks (HDR lighting is off under it too).
pub(crate) fn lifts_world(
title: bool,
float_frame: bool,
shaders_pack: bool,
native_api: Option<horizon_shader_api::Api>,
) -> bool {
!title
&& !float_frame
&& !shaders_pack
&& native_api.is_none_or(|api| api == horizon_shader_api::Api::V0_1)
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
@@ -337,6 +353,29 @@ pub(crate) mod tests {
resolve_output(settings, caps, reading, frame, true)
}
/// HDR output lifts light-source marks only on the 8/16-bit frame's world with no pack or
/// a 0.1 pack: a `shaders/` pack's alpha isn't marks, and a 0.2 pack is shown at paper white.
#[test]
fn only_horizons_own_gamma_world_is_lifted() {
use horizon_shader_api::Api::{V0_1, V0_2};
// (title, float frame, `shaders/` pack, Horizon pack) -> lifts
let cases = [
((false, false, false, None), true),
((false, false, false, Some(V0_1)), true),
((false, false, true, None), false),
((false, false, false, Some(V0_2)), false),
((false, true, false, None), false),
((true, false, false, None), false),
];
for ((title, float, shaders, api), lifts) in cases {
assert_eq!(
lifts_world(title, float, shaders, api),
lifts,
"title {title}, float {float}, shaders/ pack {shaders}, pack {api:?}"
);
}
}
/// Every mode against every offer, system report, pack and device: HDR output only where
/// the mode asks for it and the destination offers it, and the frame each combination
/// draws in, as `Renderer::new` picked it before the snapshot.
@@ -666,34 +666,52 @@ const FACE: &str = " vec3 hz_p0 = uintBitsToFloat(hz_cp0);\n \
}\n \
}\n";
/// `terrain` (`PackAtlas::terrain_inputs`) drawing only solid terrain, then only cutout terrain:
/// each leaves the other part's quads outside the clip volume. Solid: the quads over opaque
/// texels and opaque leaves (`mesher::OPAQUE_LAYER`), as vanilla picks `ChunkSectionLayer.SOLID`
/// per quad (`FaceBakery.computeMaterialTransparency`, `SectionCompiler.compile`), and lava's
/// faces (sprite layers `lava`, its still and flowing sprites), which Iris 1.11.7 drew with
/// `gbuffers_terrain_solid` in our probes, with and without `separateAo`.
/// GLSL: whether a terrain vertex's quad is solid terrain rather than cutout. Solid: the quads
/// over opaque texels and opaque leaves (`mesher::OPAQUE_LAYER`), as vanilla picks
/// `ChunkSectionLayer.SOLID` per quad (`FaceBakery.computeMaterialTransparency`,
/// `SectionCompiler.compile`), and lava's faces (sprite layers `lava`, its still and flowing
/// sprites), which Iris 1.11.7 drew with `gbuffers_terrain_solid` in our probes, with and
/// without `separateAo`.
///
/// The test reads only the vertex's sprite layer, which all four vertices of a quad share: a
/// quad lands whole in one part. The colour's alpha can't decide it, as with `separateAo` it
/// holds each vertex's own ambient occlusion.
pub fn terrain_parts(
terrain: &horizon_shaders::GbuffersInputs,
lava: &[u16],
) -> [horizon_shaders::GbuffersInputs; 2] {
fn solid(lava: &[u16]) -> String {
let opaque = crate::mesher::OPAQUE_LAYER;
let lava: String = lava
.iter()
.map(|l| format!(" || hz_v_layer == {l}u"))
.collect();
let part = |solid: bool| {
format!("(hz_v_layer & {opaque}u) != 0u{lava}")
}
/// The game's `terrain` inputs (`PackAtlas::terrain_inputs`) for a pack: whole; drawing only
/// solid terrain, then only cutout terrain (`solid`), each leaving the other part's quads outside
/// the clip volume; and drawing both in one pass, each quad with its part's alpha test.
pub fn game_terrain(
terrain: Option<horizon_shaders::GbuffersInputs>,
lava: &[u16],
) -> horizon_shaders::GameInputs {
let solid = solid(lava);
let part = |terrain: &horizon_shaders::GbuffersInputs, part: bool| {
let mut inputs = terrain.clone();
inputs.after.push_str(&format!(
" bool hz_solid = (hz_v_layer & {opaque}u) != 0u{lava};\n \
if (hz_solid != {solid}) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);\n"
" if (({solid}) != {part}) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);\n"
));
inputs
};
[part(true), part(false)]
horizon_shaders::GameInputs {
terrain_parts: terrain.as_ref().map(|t| [part(t, true), part(t, false)]),
terrain_one_pass: terrain.as_ref().map(|t| horizon_shaders::GbuffersInputs {
parts: Some(horizon_shaders::Parts {
solid: solid.clone(),
cutout_alpha_test: None,
}),
..t.clone()
}),
terrain,
..Default::default()
}
}
impl PackAtlas {
@@ -852,6 +870,7 @@ impl PackAtlas {
.collect(),
after: String::new(),
alpha_test: None,
parts: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
@@ -125,6 +125,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
op: ">",
reference: 0.1,
}),
parts: None,
item_id_declared: false,
far_depth: false,
// Entities, items and block entities read the shared atlas: its own maps (paged_maps.rs).
@@ -192,6 +193,7 @@ pub fn cloud_inputs() -> horizon_shaders::GbuffersInputs {
.collect(),
after: String::new(),
alpha_test: None,
parts: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
@@ -5,6 +5,7 @@
use std::collections::BTreeMap;
use horizon_shaders::{BufferObject, CustomImage, Format, Kind};
use wgpu::util::DeviceExt;
pub(super) struct PackImage {
pub(super) def: CustomImage,
@@ -468,19 +469,33 @@ impl Buffers {
.iter()
.map(|(binding, o)| {
let least = self.minimums.get(binding).copied().unwrap_or(0);
let wanted = buffer_size(*o, size, least);
let wanted = buffer_size(o, size, least);
if wanted > largest {
log::warn!(
"shader pack: bufferObject.{binding} wants {wanted} bytes, this device \
binds at most {largest}"
);
}
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack buffer"),
size: wanted.min(largest),
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
})
let size = wanted.min(largest);
// A buffer the pack initializes from a file starts with the file's bytes, the
// rest of it zero.
match o.initial_data() {
Some(data) => {
let mut contents = data.to_vec();
contents.resize(size as usize, 0);
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Shader pack buffer"),
contents: &contents,
usage: wgpu::BufferUsages::STORAGE,
})
}
None => device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Shader pack buffer"),
size,
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
}),
}
})
.collect();
let entries: Vec<_> = self
@@ -509,7 +524,7 @@ impl Buffers {
/// The bytes a storage buffer is made with for a render size of `render`: what the pack
/// declares, or more when a shader binds it as a larger block (`least`), which wgpu needs where
/// OpenGL binds the smaller buffer; a multiple of 4.
fn buffer_size(object: BufferObject, render: [u32; 2], least: u64) -> u64 {
fn buffer_size(object: &BufferObject, render: [u32; 2], least: u64) -> u64 {
object.size(render).max(least).next_multiple_of(4)
}
@@ -612,18 +627,18 @@ mod tests {
/// bound as a 48-byte block failed wgpu's validation, #7178); a larger one keeps its size.
#[test]
fn a_buffer_is_at_least_its_shaders_block() {
assert_eq!(buffer_size(BufferObject::Bytes(40), [1, 1], 48), 48);
assert_eq!(buffer_size(&BufferObject::Bytes(40), [1, 1], 48), 48);
assert_eq!(
buffer_size(BufferObject::Bytes(40980), [1, 1], 40992),
buffer_size(&BufferObject::Bytes(40980), [1, 1], 40992),
40992
);
assert_eq!(buffer_size(BufferObject::Bytes(100), [1, 1], 48), 100);
assert_eq!(buffer_size(BufferObject::Bytes(41), [1, 1], 0), 44);
assert_eq!(buffer_size(&BufferObject::Bytes(100), [1, 1], 48), 100);
assert_eq!(buffer_size(&BufferObject::Bytes(41), [1, 1], 0), 44);
let per_pixel = BufferObject::PerPixel {
bytes: 4,
scale: [0.5, 0.5],
};
assert_eq!(buffer_size(per_pixel, [10, 10], 64), 100);
assert_eq!(buffer_size(per_pixel, [4, 4], 64), 64);
assert_eq!(buffer_size(&per_pixel, [10, 10], 64), 100);
assert_eq!(buffer_size(&per_pixel, [4, 4], 64), 64);
}
}
@@ -50,6 +50,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
.collect(),
after,
alpha_test: None,
parts: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
@@ -1201,31 +1201,7 @@ pub(super) type TerrainDraw<'a> = dyn FnMut(
Option<(u32, &wgpu::BindGroupLayout)>,
) + 'a;
/// What the shadow camera sees of the terrain, for the game's draw lists: its view and
/// projection in wgpu's clip space, the direction toward the light, and how far from the camera
/// terrain is drawn (`shadowDistanceRenderMul`).
pub(super) struct ShadowView {
pub cull: glam::Mat4,
pub light: glam::Vec3,
pub distance: Option<f32>,
/// Draw everything, every face, within this many blocks (`shadow.culling=false|reversed`):
/// packs that voxelize the world in their shadow pass need all of it.
pub unculled: Option<f32>,
/// Every face of the drawn sections, not only those that can face the light. Iris 1.11.7's
/// shadow map holds the faces turned away from the light too (#9033): under a hill at low sun
/// a cave's ceiling, which faces away, is often all that shadows the cave.
pub every_face: bool,
/// Only the sections whose shadow can fall into the camera's view: those the camera's
/// frustum, stretched toward the light, takes in (`shadow_casters`). Our probes' Iris 1.11.7
/// maps fit keeping only those with `shadow.culling` unset (#8464): under a noon sun, only
/// the terrain above the ground the camera sees; with a low sun ahead, none behind the camera.
pub view_casters: bool,
/// Whether the projection's near and far planes in `cull` drop sections too. Our probes'
/// Iris 1.11.7 maps hold the terrain at every depth we put it along the light (from 535 blocks
/// beyond the shadow camera to about 120 before it), whatever `shadowNearPlane` and
/// `shadowFarPlane` the pack sets, or none (#10403): only its sides cull.
pub depth_planes: bool,
}
pub(super) use super::external::ShadowView;
/// An arena page's key, native vertices and optional per-quad source records.
pub(super) type TerrainPage = (u32, wgpu::Buffer, Option<wgpu::Buffer>);
@@ -2964,17 +2940,13 @@ impl PackPost {
p.name
));
}
match (&terrain, &mut terrain_cutout) {
match (&terrain, &terrain_cutout) {
(Some(t), None) => notes.push(format!("terrain draws with {}", t.name)),
(t, Some(c)) => {
if let Some(t) = t {
notes.push(format!("solid terrain draws with {}", t.name));
}
notes.push(format!("cutout terrain draws with {}", c.name));
// Timed (and labelled) apart from the solid part when it runs the same program.
if t.as_ref().is_some_and(|t| t.name == c.name) {
c.name.push_str(" (cutout)");
}
}
(None, None) => {}
}
@@ -3835,7 +3807,7 @@ impl PackPost {
timestamp_writes: self
.timing
.as_mut()
.and_then(|t| t.compute_writes(&pass.name)),
.and_then(|t| t.compute_writes(&format!("{} (compute)", pass.name))),
});
cp.set_pipeline(&pipeline);
cp.set_bind_group(0, &group, &[]);
@@ -3911,8 +3883,8 @@ impl PackPost {
}
/// Terrain (or, `translucent`, translucent terrain) with the pack's program; `draw` issues
/// the game's draws. Solid terrain in two parts has its cutout part drawn second, from the
/// same draws.
/// the game's draws. Solid terrain in two parts (a pack's `gbuffers_terrain_solid` and
/// `_cutout`) has its cutout part drawn second, from the same draws.
fn draw_terrain(
&mut self,
device: &wgpu::Device,
@@ -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,paged_maps:false,water_mask:false,water_patches: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,parts:None,item_id_declared:false,far_depth:false,paged_maps:false,water_mask:false,water_patches:false }),
hand:hand.then(crate::gfx::pack_hand::inputs),..Default::default()
};
let mut post = gpu.load(
@@ -717,6 +717,7 @@ fn shadow_depth_map_reads(
attributes: vec![],
after: String::new(),
alpha_test: None,
parts: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
@@ -48,6 +48,7 @@ fn pack(outputs: u32) -> Post {
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
let inputs = horizon_shaders::GameInputs {
terrain: Some(horizon_shaders::GbuffersInputs {
parts: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
@@ -44,6 +44,7 @@ fn pack() -> Post {
let (properties, _) = horizon_shaders::read_properties(&pack, &mut macros);
let inputs = horizon_shaders::GameInputs {
terrain: Some(horizon_shaders::GbuffersInputs {
parts: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
@@ -89,14 +89,7 @@ fn strips_of(
.into(),
..Default::default()
};
let inputs = horizon_shaders::GameInputs {
terrain_parts: Some(super::super::pack_atlas::terrain_parts(
&terrain,
&[LAVA, LAVA + 1],
)),
terrain: Some(terrain),
..Default::default()
};
let inputs = super::super::pack_atlas::game_terrain(Some(terrain), &[LAVA, LAVA + 1]);
const ATTRS: [wgpu::VertexAttribute; 3] =
wgpu::vertex_attr_array![0=>Float32x3,2=>Uint32,3=>Unorm8x4];
let layouts = [Some(wgpu::VertexBufferLayout {
@@ -346,3 +339,64 @@ fn alpha_test_ref_is_0_for_solid_terrain_and_0_5_for_cutout() {
assert_eq!(got, [Some(RED), Some(YELLOW), Some(RED)], "{names:?}");
}
}
/// `alphaTest.gbuffers_terrain` replaces both parts' tests when one program draws them, as it
/// did when they drew in two passes: over `GREATER 0.25`, alpha 0.3 keeps cutout terrain too
/// and 0.2 loses solid terrain too, and `alphaTestRef` reads 0.25 in both.
#[test]
fn a_packs_terrain_alpha_test_applies_to_both_parts() {
let properties = || {
(
"shaders.properties".to_owned(),
"alphaTest.gbuffers_terrain=GREATER 0.25\n".to_owned(),
)
};
for (alpha, kept) in [(0.3, true), (0.2, false)] {
let mut files = program("gbuffers_terrain", RED, alpha).to_vec();
files.push(properties());
let Some((got, _)) = strips_of(files, [255; 4]) else {
return;
};
assert_eq!(got, [kept.then_some(RED); 3], "alpha {alpha}");
}
let files = vec![
(
"gbuffers_terrain.vsh".to_owned(),
"#version 120\nvoid main(){gl_Position=vec4(gl_Vertex.xy,0.0,1.0);}".to_owned(),
),
(
"gbuffers_terrain.fsh".to_owned(),
"#version 120\nuniform float alphaTestRef;\n/* DRAWBUFFERS:0 */\n\
void main(){gl_FragData[0]=vec4(1.0,alphaTestRef*4.0,0.0,1.0);}"
.to_owned(),
),
properties(),
];
let Some((got, _)) = strips_of(files, [255; 4]) else {
return;
};
assert_eq!(got, [Some([255, 255, 0]); 3]);
}
/// The vertex stage reads its own quad's `alphaTestRef` too: 0 for solid, 0.5 for cutout.
#[test]
fn the_vertex_stage_reads_its_parts_alpha_test_ref() {
let files = vec![
(
"gbuffers_terrain.vsh".to_owned(),
"#version 120\nuniform float alphaTestRef;\nvarying float ref;\n\
void main(){ref=alphaTestRef;gl_Position=vec4(gl_Vertex.xy,0.0,1.0);}"
.to_owned(),
),
(
"gbuffers_terrain.fsh".to_owned(),
"#version 120\nvarying float ref;\n/* DRAWBUFFERS:0 */\n\
void main(){gl_FragData[0]=vec4(1.0,ref*2.0,0.0,1.0);}"
.to_owned(),
),
];
let Some((got, _)) = strips_of(files, [255; 4]) else {
return;
};
assert_eq!(got, [Some(RED), Some([255, 255, 0]), Some(RED)]);
}
@@ -102,6 +102,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
// depth. Its fragments read their own depth, as in Iris.
after: String::new(),
alpha_test: None,
parts: None,
item_id_declared: false,
far_depth: true,
paged_maps: false,
@@ -132,6 +133,7 @@ pub fn celestial_inputs() -> horizon_shaders::GbuffersInputs {
],
after: String::new(),
alpha_test: None,
parts: None,
item_id_declared: false,
far_depth: true,
paged_maps: false,
@@ -151,7 +151,9 @@ impl PassTiming {
Some(stamps(&self.queries, i))
}
/// Timestamp writes for the compute pass `name`, in a timed frame.
/// Timestamp writes for the compute pass `name`, in a timed frame. Shader packs' compute
/// passes come as `<program> (compute)`, apart from the fragment program of the same name
/// (`deferred2.csh` beside `deferred2.fsh`), whose time theirs would otherwise add to.
pub fn compute_writes(&mut self, name: &str) -> Option<wgpu::ComputePassTimestampWrites<'_>> {
let i = self.push(name)?;
Some(compute_stamps(&self.queries, i))
@@ -236,23 +238,7 @@ impl PassTiming {
drop(data);
self.read.unmap();
let times = pass_times(&stamps, self.period_ns);
for (name, ms) in self.names.iter().zip(times) {
let Some(ms) = ms.filter(|_| !name.is_empty()) else {
continue;
};
let i = match self.samples.iter().position(|s| s.0 == *name) {
Some(i) => i,
None => {
self.samples.push((name.clone(), VecDeque::new()));
self.samples.len() - 1
}
};
let window = &mut self.samples[i].1;
if window.len() == WINDOW {
window.pop_front();
}
window.push_back(ms);
}
record(&mut self.samples, self.names.iter().zip(times));
self.reports += 1;
if self.log && self.reports.is_multiple_of(REPORT) {
let medians = self.medians();
@@ -283,6 +269,40 @@ impl PassTiming {
}
}
/// Adds one timed frame's pass times to `samples`, each pass's window of its last `WINDOW`
/// frames. Passes of one name in a frame (a program drawn over several render passes) count as
/// one sample, their sum: as separate samples they shared one window, and its median was the
/// time of neither. Unnamed and unstamped passes are left out.
fn record<'a>(
samples: &mut Vec<(String, VecDeque<f32>)>,
frame: impl Iterator<Item = (&'a String, Option<f32>)>,
) {
let mut sums: Vec<(&str, f32)> = Vec::new();
for (name, ms) in frame {
let Some(ms) = ms.filter(|_| !name.is_empty()) else {
continue;
};
match sums.iter_mut().find(|s| s.0 == name) {
Some(s) => s.1 += ms,
None => sums.push((name, ms)),
}
}
for (name, ms) in sums {
let i = match samples.iter().position(|s| s.0 == name) {
Some(i) => i,
None => {
samples.push((name.to_owned(), VecDeque::new()));
samples.len() - 1
}
};
let window = &mut samples[i].1;
if window.len() == WINDOW {
window.pop_front();
}
window.push_back(ms);
}
}
/// Pass `i`'s beginning and end timestamps.
fn stamps(queries: &wgpu::QuerySet, i: u32) -> wgpu::RenderPassTimestampWrites<'_> {
wgpu::RenderPassTimestampWrites {
@@ -323,7 +343,21 @@ fn pass_times(stamps: &[u64], period_ns: f32) -> Vec<Option<f32>> {
#[cfg(test)]
mod tests {
use super::pass_times;
use super::{pass_times, record};
use std::collections::VecDeque;
#[test]
fn passes_of_one_name_count_as_their_sum() {
let names = ["terrain", "sky", "terrain", "", "water"].map(String::from);
let times = [Some(1.0), Some(2.0), Some(3.0), Some(9.0), None];
let mut samples: Vec<(String, VecDeque<f32>)> = Vec::new();
record(&mut samples, names.iter().zip(times));
let got: Vec<(&str, Vec<f32>)> = samples
.iter()
.map(|(n, w)| (n.as_str(), w.iter().copied().collect()))
.collect();
assert_eq!(got, [("terrain", vec![4.0]), ("sky", vec![2.0])]);
}
#[test]
fn overlapping_passes_cost_from_the_previous_end() {
@@ -44,6 +44,7 @@ pub fn inputs() -> horizon_shaders::GbuffersInputs {
op: ">",
reference: 0.1,
}),
parts: None,
item_id_declared: false,
far_depth: false,
paged_maps: false,
@@ -399,6 +399,20 @@ impl Rotation {
#[cfg(test)]
mod tests {
use super::*;
/// CubeMap's cube: its corners' indices, six faces of two triangles.
#[test]
fn the_packed_cube_corners_are_cubemaps_indices() {
let indices = [
4, 7, 6, 4, 6, 5, 5, 6, 2, 5, 2, 1, 1, 2, 3, 1, 3, 0, 0, 3, 7, 0, 7, 4, 7, 3, 2, 7, 2,
6, 0, 4, 5, 0, 5, 1,
];
let source = include_str!("panorama.wgsl");
assert_eq!(
super::super::cull::packed_lookup(source, "cube_corner", 36),
indices
);
}
use std::{
fs,
sync::atomic::{AtomicU32, Ordering},
@@ -8,19 +8,27 @@ struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) direction: vec3<f32>,
}
// The cube's corner of each of its 36 vertices (CubeMap's indices): 4 7 6, 4 6 5, 5 6 2,
// 5 2 1, 1 2 3, 1 3 0, 0 3 7, 0 7 4, 7 3 2, 7 2 6, 0 4 5, 0 5 1.
// Packed four bits each, eight a word, read through a switch: a constant array indexed by the
// vertex would be a private array, which Adreno's Vulkan compiler (build 0676.41) fails to link.
fn cube_corner(v: u32) -> u32 {
var word: u32;
switch v / 8u {
case 0u: { word = 0x65564674u; }
case 1u: { word = 0x13211252u; }
case 2u: { word = 0x47073003u; }
case 3u: { word = 0x40627237u; }
default: { word = 0x00001505u; }
}
return (word >> (v % 8u * 4u)) & 0xfu;
}
@vertex fn vs_panorama(@builtin(vertex_index) index: u32) -> Out {
let corners = array<vec3<f32>, 8>(
vec3(-1.0, -1.0, -1.0), vec3(1.0, -1.0, -1.0),
vec3(1.0, 1.0, -1.0), vec3(-1.0, 1.0, -1.0),
vec3(-1.0, -1.0, 1.0), vec3(1.0, -1.0, 1.0),
vec3(1.0, 1.0, 1.0), vec3(-1.0, 1.0, 1.0),
);
let indices = array<u32, 36>(
4, 7, 6, 4, 6, 5, 5, 6, 2, 5, 2, 1,
1, 2, 3, 1, 3, 0, 0, 3, 7, 0, 7, 4,
7, 3, 2, 7, 2, 6, 0, 4, 5, 0, 5, 1,
);
let position = corners[indices[index]];
// CubeMap's corners: -1 or 1 on each axis, x 1 at corners 1, 2, 5 and 6, y at 2, 3, 6
// and 7, z at 4 to 7.
let c = cube_corner(index);
let high = vec3((c ^ (c >> 1u)) & 1u, c & 2u, c & 4u) != vec3(0u);
let position = select(vec3(-1.0), vec3(1.0), high);
var out: Out;
out.clip = projection.view_proj * vec4(position, 1.0);
out.direction = position;
@@ -221,6 +221,18 @@ pub(super) async fn open_adapter(
configured,
})
}
/// Logs a sprite split below the CPU's (the GPU's limit), and warns when Metal's arrays grew
/// past 512 layers (#12155), so a big pack's texture-corruption report ties to it (#8471).
pub(super) fn log_sprite_split(info: &wgpu::AdapterInfo, split: u32, layers: u32) {
if info.backend == wgpu::Backend::Metal && split > 512 {
log::warn!(
"Horizon: {split}-layer Metal sprite arrays for {layers} on {}",
info.name
);
} else if split < super::sprite_split() {
log::info!("Horizon: {split} block textures per array (the GPU's limit)");
}
}
#[cfg(test)]
mod tests {
use super::{AdapterChoice, pick_adapter};
+5 -3
View File
@@ -1897,10 +1897,12 @@ mod tests {
let g = Graphics::default();
assert_eq!(g.workers, 0);
let cores = horizon_threads::worker_count();
// Vanilla's bound: one core is always left for the render and server threads.
assert!((1..=cores.saturating_sub(1).max(1)).contains(&g.worker_threads()));
if !cfg!(target_vendor = "apple") {
assert_eq!(g.worker_threads(), cores.saturating_sub(1).max(1));
}
// The count itself is `horizon_threads::default_workers`, which is one less than
// the *smaller* of the machine's cores and its performance cores (a Linux hybrid
// CPU reports fewer of the latter), so it is not always `cores - 1`.
assert_eq!(g.worker_threads(), horizon_threads::default_workers());
// A manual count is the player's own choice, kept as asked.
let manual = Graphics { workers: 3, ..g };
assert_eq!(manual.worker_threads(), 3);
+45 -6
View File
@@ -173,13 +173,52 @@ fn calibration_picture(pos: vec4<f32>) -> vec4<f32> {
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> {
// On for the HDR10 swapchain alone (Hdr::new): its 10 bits get dither. A screenshot's HDR10 copy
// (Hdr::capture) keeps the exact codes, and scRGB's floats need none.
override pq_dither: bool = false;
// Three even random values in [0, 1) for `at`: PCG's 3D hash (Jarzynski and Olano, "Hash Functions
// for GPU Rendering", JCGT 2020). Integers only, so it is the same on every GPU and at every
// resolution, where hashes built on `fract(sin())` repeat or streak at 4K's coordinates.
// Copyright 2020 Mark Jarzynski & Marc Olano, MIT (github.com/markjarzynski/PCG3D; the license is in
// THIRD_PARTY_NOTICES.md).
fn hash3(at: vec3<u32>) -> vec3<f32> {
var v = at * 1664525u + 1013904223u;
v.x += v.y * v.z;
v.y += v.z * v.x;
v.z += v.x * v.y;
v ^= v >> vec3(16u);
v.x += v.y * v.z;
v.y += v.z * v.x;
v.z += v.x * v.y;
return vec3<f32>(v >> vec3(8u)) / 16777216.0;
}
// The PQ signal `e` with dither for its 10 bits: triangular noise of one code either way, each
// channel's own, so a slow gradient (a clear sky is a few codes tall) shows as grain a code deep
// instead of bands, and its mean is the light meant. The noise is the pixel's alone: no frame
// counter, so a still picture stays still. Within a code of black or of the top it shrinks to
// what fits: the signal never leaves 0..1, and black stays exactly black (an OLED's pixel off).
// The price is in that last code alone: the smaller noise keeps the signal's mean but not the
// rounded one, which leans to the end (a third of a code from it shows as an eighth). Under
// 0.00004 nits at black, that is the accepted cost of a true 0.
fn dithered(e: vec3<f32>, pixel: vec2<f32>) -> vec3<f32> {
let at = vec2<u32>(pixel);
let noise = hash3(vec3(at, 0u)) + hash3(vec3(at, 1u)) - 1.0;
return e + noise * min(min(e, 1.0 - e), vec3(1.0 / 1023.0));
}
// Light in units of paper white at the pixel `pos`, as the swapchain takes it: HDR10 or scRGB,
// the black level lifted.
fn display(light: vec3<f32>, pos: vec4<f32>) -> vec4<f32> {
let scrgb = light * params.paper;
if params.pq > 0.5 {
let e = pq(BT709_TO_BT2020 * scrgb * 80.0);
return vec4(select(e, lift_black(e), params.black > 0.0), 1.0);
let lifted = select(e, lift_black(e), params.black > 0.0);
if pq_dither {
return vec4(dithered(lifted, pos.xy), 1.0);
}
return vec4(lifted, 1.0);
}
if params.black > 0.0 {
return vec4(pq_nits(lift_black(pq(scrgb * 80.0))) / 80.0, 1.0);
@@ -209,7 +248,7 @@ fn display(light: vec3<f32>) -> vec4<f32> {
// The HUD and menus at their own brightness, by how much they cover, no brighter than the
// peak (as `fs_hdr_layered`): UI Brightness can pass paper white.
light = min(light * mix(1.0, params.ui, ui), vec3(params.peak));
return display(light);
return display(light, pos);
}
// The tone curve's knee: up to it light stays as it is. Where HDR lighting eased into the peak
@@ -328,5 +367,5 @@ override screenshot_shoulder: bool = true;
if calibrating(pos) {
return calibration_picture(pos);
}
return display(min(pow(layered(vec2<i32>(pos.xy)), vec3(2.2)), vec3(params.peak)));
return display(min(pow(layered(vec2<i32>(pos.xy)), vec3(2.2)), vec3(params.peak)), pos);
}
+159 -22
View File
@@ -12,8 +12,11 @@ use std::{
};
use wgpu::util::DeviceExt;
use model_reducing::reducible_model_sprites;
mod animate;
pub mod cit_glint;
mod model_reducing;
mod pack_text;
pub mod pictures;
pub(crate) mod sprite_modifiers;
@@ -52,7 +55,7 @@ pub struct TextureFlags {
impl TextureFlags {
/// The `texture` section of a `.png.mcmeta` file, if it sets either flag.
pub fn from_mcmeta(json: &str) -> Option<Self> {
let meta: serde_json::Value = serde_json::from_str(json).ok()?;
let meta = crate::packs::first_json(json.as_bytes())?;
let section = meta.get("texture")?;
let flag = |key| section.get(key).and_then(serde_json::Value::as_bool) == Some(true);
let flags = Self {
@@ -387,7 +390,7 @@ fn strip_frame(pixels: &[u8], stride: u32, x: u32, y: u32, w: u32, h: u32) -> Ve
}
/// The `animation` section of a texture's `.mcmeta`.
fn animation_of(mcmeta: Option<&str>) -> Option<AnimationMetadata> {
let meta: serde_json::Value = serde_json::from_str(mcmeta?).ok()?;
let meta = crate::packs::first_json(mcmeta?.as_bytes())?;
AnimationMetadata::from_json(&meta.get("animation")?.to_string()).ok()
}
/// An animated strip's first frame: the region the mcmeta's frame size picks
@@ -1057,25 +1060,6 @@ impl HudAtlas {
blinks: Default::default(),
}
}
/// `layout`, but when `extras` (Custom Item Textures) make the images more than `max`
/// holds, without them: they are left out, not the packs.
fn layout_leaving_out(
images: &mut Vec<PackedImage>,
animated: &mut Vec<String>,
extras: &HashSet<String>,
max: u32,
) -> Result<(u32, Vec<(u32, u32)>, u32)> {
match Self::layout(images, max) {
Err(e) if !extras.is_empty() => {
images.retain(|i| !extras.contains(&i.0));
animated.retain(|n| !extras.contains(n));
let layout = Self::layout(images, max)?;
log::warn!("left out the custom item textures: {e}");
Ok(layout)
}
layout => layout,
}
}
/// Shelf placements of `images` (tallest first) in the narrowest atlas
/// width from 4096 up that keeps the atlas, glyph rows included, within
/// `max` texels a side; and the first row free for glyphs. High-resolution
@@ -1460,7 +1444,20 @@ impl HudAtlas {
}
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
let (width, placements, glyph_region) =
Self::layout_leaving_out(&mut images, &mut animated, &cit_names, MAX_ATLAS_SIZE)?;
Self::layout_leaving_out(&mut images, &mut animated, &cit_names, MAX_ATLAS_SIZE)
.or_else(|error| -> Result<_> {
let models = reducible_model_sprites(root, &images, &bordered);
let layout = Self::layout_reducing_models(
&mut images,
&mut gui_sizes,
&models,
MAX_ATLAS_SIZE,
)?;
log::warn!(
"reduced HUD model texture resolution to keep the resource pack: {error}"
);
Ok(layout)
})?;
// A multiple of 1024 rather than a power of two: the default resources
// need 4096x5120 (8192 rows before), Faithful 32x 4096x12288 (16384).
let height = (glyph_region + GLYPH_ROWS).next_multiple_of(1024);
@@ -3110,6 +3107,18 @@ mod coverage_tests;
mod tests {
use super::*;
#[test]
fn animated_texture_metadata_ignores_trailing_pack_signature() {
let meta = r#"{"animation":{"frametime":2,"width":2,"height":2}}
// High Contrast pack signature"#;
let animation = animation_of(Some(meta)).expect("the first JSON value is metadata");
assert_eq!(animation.frame_size(8, 4), [2, 2]);
let pixels = (0..8 * 4).flat_map(|i| [i as u8, 0, 0, 255]).collect();
let (_, height, first) = first_frame((8, 4, pixels), Some(&animation));
assert_eq!(height, 2);
assert_eq!(first.len(), 2 * 2 * 4);
}
#[test]
fn object_skin_revision_tracks_changes_and_capacity_clear() {
let mut atlas = HudAtlas::boot();
@@ -3766,6 +3775,47 @@ mod tests {
assert_eq!(banner.texels((atlas.width, atlas.height)), (16, 32));
}
#[test]
fn a_root_single_sprite_strip_taller_than_the_atlas_packs_one_frame() {
let root = animated_root();
let atlases = root.join("assets/minecraft/atlases");
fs::create_dir_all(&atlases).unwrap();
fs::write(
atlases.join("items.json"),
r#"{"sources":[{"type":"single","resource":"nexo:abc123"},
{"type":"single","resource":"nexo:still"}]}"#,
)
.unwrap();
// Plugin-generated names need no item/ prefix. Keep the production
// strip's height, but use narrow frames to keep this fixture cheap.
let textures = root.join("assets/nexo/textures");
fs::create_dir_all(&textures).unwrap();
write_strip(
&textures.join("abc123.png"),
16,
32768,
&[[255, 0, 0, 255], [0, 0, 255, 255]],
Some(r#"{"animation":{"frames":[1024,0],"frametime":3}}"#),
);
write_strip(&textures.join("still.png"), 16, 32, &[[7, 8, 9, 255]], None);
let atlas = HudAtlas::build(&root).unwrap();
let _ = fs::remove_dir_all(&root);
let rect = atlas.sprites["nexo:abc123"];
assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16));
assert_eq!(texel_at(&atlas, rect, 0, 15), [0, 0, 255, 255]);
let (_, animation) = atlas
.sprite_animations
.iter()
.find(|(r, _)| r.u0 == rect.u0 && r.v0 == rect.v0)
.expect("the root-level single sprite animates");
assert_eq!(animation.frame(0), 1024);
assert_eq!(animation.frame(3), 0);
assert_eq!(animation.frame_count(), 2048);
assert_eq!(
atlas.sprites["nexo:still"].texels((atlas.width, atlas.height)),
(16, 32)
);
}
#[test]
fn an_animated_gui_sprite_packs_its_first_frame_and_animates() {
let root =
std::env::temp_dir().join(format!("horizon-atlas-gui-anim-{}", std::process::id()));
@@ -4172,6 +4222,93 @@ texture=wide",
assert_inside(&images, width, &placements, free);
}
#[test]
fn model_resolution_fallback_protects_font_sources_and_gui_aliases() {
let root = animated_root();
write_png(&root, "item/font_sheet", 32, 32);
write_png(&root, "gui/panel", 32, 32);
write_png(&root, "hash", 32, 32);
let font = root.join("assets/minecraft/font/default.json");
fs::create_dir_all(font.parent().unwrap()).unwrap();
fs::write(
font,
r#"{"providers":[{"type":"bitmap","file":"minecraft:item/font_sheet.png","ascent":7,"chars":["a"]}]}"#,
).unwrap();
let atlases = root.join("assets/minecraft/atlases");
fs::create_dir_all(&atlases).unwrap();
fs::write(
atlases.join("items.json"),
r#"{"sources":[
{"type":"single","resource":"item/font_sheet","sprite":"font_alias"},
{"type":"single","resource":"gui/panel","sprite":"gui_alias"},
{"type":"single","resource":"hash"}
]}"#,
)
.unwrap();
let images = vec![
("item/font_sheet".to_owned(), 32, 32, Vec::new()),
("item/blurred".to_owned(), 32, 32, Vec::new()),
("block/stone".to_owned(), 32, 32, Vec::new()),
];
let models =
reducible_model_sprites(&root, &images, &HashSet::from(["item/blurred".to_owned()]));
let _ = fs::remove_dir_all(root);
assert_eq!(
models,
HashSet::from(["hash".to_owned(), "block/stone".to_owned()])
);
}
#[test]
fn overflowing_model_textures_shrink_without_changing_gui_sizes_or_slots() {
let mut images = vec![
(
"nexo:hash".into(),
1024,
1024,
[10, 20, 30, 255].repeat(1024 * 1024),
),
(
"gui/panel".into(),
32,
32,
[40, 50, 60, 255].repeat(32 * 32),
),
("horizon/map".into(), 128, 128, Vec::new()),
];
let models = HashSet::from(["nexo:hash".to_owned(), "horizon/map".to_owned()]);
let mut sizes = HashMap::new();
assert!(HudAtlas::layout(&images, 1024).is_err());
let (width, placements, free) =
HudAtlas::layout_reducing_models(&mut images, &mut sizes, &models, 1024).unwrap();
assert_inside(&images, width, &placements, free);
assert!(free + GLYPH_ROWS <= 1024);
let model = images.iter().find(|i| i.0 == "nexo:hash").unwrap();
assert_eq!((model.1, model.2), (256, 256));
assert_eq!(model.3, [10, 20, 30, 255].repeat(256 * 256));
assert_eq!(sizes["nexo:hash"], (1024, 1024));
let gui = images.iter().find(|i| i.0 == "gui/panel").unwrap();
assert_eq!((gui.1, gui.2), (32, 32));
assert_eq!(gui.3, [40, 50, 60, 255].repeat(32 * 32));
let slot = images.iter().find(|i| i.0 == "horizon/map").unwrap();
assert_eq!((slot.1, slot.2), (128, 128));
assert!(slot.3.is_empty());
}
#[test]
fn fitting_models_keep_their_pixels_and_existing_logical_sizes() {
let mut images = vec![("item/gem".into(), 32, 32, [1, 2, 3, 255].repeat(32 * 32))];
let original = images.clone();
let mut sizes = HashMap::from([("item/gem".to_owned(), (16, 16))]);
let models = HashSet::from(["item/gem".to_owned()]);
HudAtlas::layout_reducing_models(&mut images, &mut sizes, &models, 1024).unwrap();
assert_eq!(images, original);
assert_eq!(sizes["item/gem"], (16, 16));
// Protected oversized images remain an error; no unbounded retry or
// silent removal of GUI/font resources when shrinking cannot help.
images.push(("font/sheet".into(), 1024, 1024, Vec::new()));
assert!(HudAtlas::layout_reducing_models(&mut images, &mut sizes, &models, 1024).is_err());
assert_eq!((images[0].1, images[0].2), (1024, 1024));
assert_eq!(sizes["item/gem"], (16, 16));
}
#[test]
fn textures_that_cannot_fit_are_an_error_not_a_gpu_panic() {
let error = HudAtlas::layout(&sized(300, 1024, 1024), MAX_ATLAS_SIZE).unwrap_err();
assert!(error.to_string().contains("do not fit a 16384x16384 atlas"));
@@ -0,0 +1,105 @@
//! Resolution fallback for model textures that exceed the shared HUD atlas.
use super::{HashMap, HashSet, HudAtlas, PackedImage, Path, Result, bitmap_font_textures};
/// Only model atlas sprites may lose resolution. Font sheets can also be
/// model textures, so protect both their file names and renamed sources.
pub(super) fn reducible_model_sprites(
root: &Path,
images: &[PackedImage],
bordered: &HashSet<String>,
) -> HashSet<String> {
use crate::atlas_sources::{self, SpriteOrigin};
let fonts: HashSet<_> = bitmap_font_textures(root).into_iter().collect();
let protected = |name: &str| {
let path = name.split_once(':').map_or(name, |(_, path)| path);
path.starts_with("gui/")
|| path.starts_with("font/")
|| fonts.contains(&atlas_sources::texture_path(root, name, "textures"))
};
let mut models: HashSet<String> = images
.iter()
.filter(|(name, ..)| name.starts_with("item/") || name.starts_with("block/"))
.map(|(name, ..)| name.clone())
.collect();
let textures = atlas_sources::list_textures(root);
let mut protected_aliases = HashSet::new();
for (atlas, sources) in atlas_sources::atlases(root) {
if atlas != "minecraft:blocks" && atlas != "minecraft:items" {
continue;
}
for (id, origin) in atlas_sources::list(&sources, &textures) {
let name = id.strip_prefix("minecraft:").unwrap_or(&id).to_owned();
if let SpriteOrigin::File(texture) = origin {
if protected(&texture) {
protected_aliases.insert(name);
} else {
models.insert(name);
}
}
}
}
models.retain(|name| {
!bordered.contains(name) && !protected(name) && !protected_aliases.contains(name)
});
models
}
impl HudAtlas {
/// `layout`, but when `extras` (Custom Item Textures) make the images more than `max`
/// holds, without them: they are left out, not the packs.
pub(super) fn layout_leaving_out(
images: &mut Vec<PackedImage>,
animated: &mut Vec<String>,
extras: &HashSet<String>,
max: u32,
) -> Result<(u32, Vec<(u32, u32)>, u32)> {
match Self::layout(images, max) {
Err(e) if !extras.is_empty() => {
images.retain(|i| !extras.contains(&i.0));
animated.retain(|n| !extras.contains(n));
let layout = Self::layout(images, max)?;
log::warn!("left out the custom item textures: {e}");
Ok(layout)
}
layout => layout,
}
}
/// Last resort for a pack that exceeds the shared atlas: halve model
/// textures until they fit, retaining their logical GUI sizes. Never
/// shrink run-time slots (empty pixels), or below the vanilla 16 texels.
pub(super) fn layout_reducing_models(
images: &mut [PackedImage],
gui_sizes: &mut HashMap<String, (u32, u32)>,
models: &HashSet<String>,
max: u32,
) -> Result<(u32, Vec<(u32, u32)>, u32)> {
loop {
let error = match Self::layout(images, max) {
Ok(layout) => return Ok(layout),
Err(error) => error,
};
let mut changed = false;
for (name, w, h, pixels) in images.iter_mut() {
if !models.contains(name) || pixels.is_empty() || (*w <= 16 && *h <= 16) {
continue;
}
let (nw, nh) = ((*w / 2).max((*w).min(16)), (*h / 2).max((*h).min(16)));
let mut scaled = Vec::with_capacity((nw * nh * 4) as usize);
for y in 0..nh {
for x in 0..nw {
let at = (((y * *h / nh) * *w + x * *w / nw) * 4) as usize;
scaled.extend_from_slice(&pixels[at..at + 4]);
}
}
gui_sizes.entry(name.clone()).or_insert((*w, *h));
*pixels = scaled;
(*w, *h) = (nw, nh);
changed = true;
}
if !changed {
return Err(error);
}
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
}
}
}
@@ -39,11 +39,14 @@ pub fn text_with_backdrop(
background: u32,
) {
if background != 0 {
// Font.PreparedTextBuilder.markBackground: one pixel above and left of
// the glyphs, the glyph advance to the right and nine high: not a
// fixed two-pixel frame.
out.push(fill(
x - 2,
y - 2,
x + w + 2,
y + 9 + 2,
x - 1,
y - 1,
x + w,
y + 9,
multiply(background, color),
));
}
@@ -1484,3 +1487,27 @@ mod boss_bar_room_tests {
}
}
}
#[cfg(test)]
mod backdrop_tests {
use super::*;
/// `markBackground`: the backdrop reaches one pixel above and left of the
/// glyphs, their advance to the right and nine down, not 2 on every side.
#[test]
fn the_backdrop_frames_the_glyphs_by_one_pixel() {
let mut out = Vec::new();
text_with_backdrop(
&mut out,
Text::literal("X"),
10,
20,
6,
u32::MAX,
0xFF00_0000,
);
let Some(GuiDraw::Fill { x0, y0, x1, y1, .. }) = out.first() else {
panic!("a backdrop is a fill first");
};
assert_eq!((*x0, *y0, *x1, *y1), (9, 19, 16, 29));
}
}
+135 -21
View File
@@ -22,6 +22,7 @@ use crate::{
use horizon_core::geometry::{Direction, ShapeOp, VoxelShape};
use horizon_world::registry::{BlockRegistry, BlockStateId};
use std::{
cell::RefCell,
collections::{HashMap, VecDeque},
path::Path,
sync::Arc,
@@ -365,6 +366,48 @@ fn give_scratch(scratch: LightScratch) {
}
}
thread_local! {
static RELIGHT_SCRATCH: RefCell<RelightScratch> = RefCell::new(RelightScratch::new());
}
struct RelightScratch {
decrease: VecDeque<(Pos, u8)>,
cleared: Vec<Pos>,
increase: VecDeque<Pos>,
sources: FxHashMap<(i32, i32), i32>,
}
impl RelightScratch {
fn new() -> Self {
Self {
decrease: VecDeque::new(),
cleared: Vec::new(),
increase: VecDeque::new(),
sources: FxHashMap::default(),
}
}
fn clear(&mut self) {
const MAX_CAPACITY: usize = 16_384;
self.decrease.clear();
if self.decrease.capacity() > MAX_CAPACITY {
self.decrease.shrink_to(MAX_CAPACITY);
}
self.cleared.clear();
if self.cleared.capacity() > MAX_CAPACITY {
self.cleared.shrink_to(MAX_CAPACITY);
}
self.increase.clear();
if self.increase.capacity() > MAX_CAPACITY {
self.increase.shrink_to(MAX_CAPACITY);
}
self.sources.clear();
if self.sources.capacity() > MAX_CAPACITY {
self.sources.shrink_to(MAX_CAPACITY);
}
}
}
/// Where a section sits in the 48-wide region.
#[derive(Clone, Copy)]
struct At {
@@ -880,12 +923,12 @@ impl<'w> Region<'w> {
Self {
layout: world.layout(),
world,
slots: Vec::new(),
slots: Vec::with_capacity(16),
index: FxHashMap::default(),
last: ((i32::MIN, 0, 0), NONE),
}
}
#[inline]
#[inline(always)]
fn slot(&mut self, x: i32, y: i32, z: i32) -> Option<usize> {
let s = self.layout.section_index(y)?;
let key = (x >> 4, s as i32, z >> 4);
@@ -1142,10 +1185,25 @@ pub fn relight(
force: bool,
changed: &mut LightChanges,
) {
let mut region = Region::new(world);
changed.keyed(region.layout);
relight_region(&mut region, tables, sky_light, positions, force, changed);
region.finish();
changed.keyed(world.layout());
if positions.is_empty() {
return;
}
RELIGHT_SCRATCH.with_borrow_mut(|scratch| {
scratch.clear();
let mut region = Region::new(world);
relight_region(
&mut region,
tables,
sky_light,
positions,
force,
scratch,
changed,
);
region.finish();
scratch.clear();
});
}
/// The columns `changed` touched that border a loaded column not lit yet
/// (`unlit`). `relight` reads and writes only lit columns, so an edit's
@@ -1170,10 +1228,11 @@ fn relight_region(
sky_light: bool,
positions: &[Pos],
force: bool,
scratch: &mut RelightScratch,
changed: &mut LightChanges,
) {
crate::spans::time("lt_block", || {
relight_layer(world, tables, false, positions.to_vec(), force, changed)
relight_layer(world, tables, false, positions, force, scratch, changed)
});
if sky_light {
let (min_y, max_y) = (world.layout.min_y(), world.layout.max_y());
@@ -1201,7 +1260,7 @@ fn relight_region(
}
});
crate::spans::time("lt_sky", || {
relight_layer(world, tables, true, seeds, force, changed)
relight_layer(world, tables, true, &seeds, force, scratch, changed)
});
}
}
@@ -1209,14 +1268,30 @@ fn relight_layer(
world: &mut Region,
tables: &LightTables,
sky: bool,
seeds: Vec<Pos>,
seeds: &[Pos],
force: bool,
scratch: &mut RelightScratch,
changed: &mut LightChanges,
) {
let mut decrease: VecDeque<(Pos, u8)> = VecDeque::new();
let mut cleared: Vec<Pos> = Vec::new();
let mut increase: VecDeque<Pos> = VecDeque::new();
for p in seeds {
scratch.decrease.clear();
scratch.cleared.clear();
scratch.increase.clear();
scratch.sources.clear();
if seeds.len() > scratch.decrease.capacity() {
scratch.decrease.reserve(seeds.len());
}
if seeds.len() > scratch.cleared.capacity() {
scratch.cleared.reserve(seeds.len());
}
if seeds.len() > scratch.increase.capacity() {
scratch.increase.reserve(seeds.len());
}
let decrease = &mut scratch.decrease;
let cleared = &mut scratch.cleared;
let increase = &mut scratch.increase;
for &p in seeds {
let Some(old) = level(world, sky, p) else {
continue;
};
@@ -1267,13 +1342,22 @@ fn relight_layer(
}
}
// Sources inside the cleared area light up again.
let mut sources: FxHashMap<(i32, i32), i32> = FxHashMap::default();
let sources = &mut scratch.sources;
let mut last_xz = (i32::MIN, i32::MIN);
let mut last_lowest = 0;
crate::spans::time("lt_sources", || {
for p in cleared {
for &p in cleared.iter() {
let seed = if sky {
let lowest = *sources
.entry((p.0, p.2))
.or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2));
let lowest = if (p.0, p.2) == last_xz {
last_lowest
} else {
let lowest = *sources
.entry((p.0, p.2))
.or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2));
last_xz = (p.0, p.2);
last_lowest = lowest;
lowest
};
if p.1 >= lowest { 15 } else { 0 }
} else {
world
@@ -2119,9 +2203,39 @@ pub(crate) mod tests {
relight(&mut w, &t, true, &positions, false, &mut changed);
}
println!(
"relight_bench: {:?}, {} sections",
start.elapsed(),
changed.sections().count()
"relight_bench (large batch: 400 rounds x 32 blocks): {:?}",
start.elapsed()
);
}
#[test]
#[ignore]
fn relight_single_block_bench() {
let mut w: FxHashMap<_, _> = world(|_| {}).into_iter().collect();
let t = tables();
let mut rng = 0x2545_f491_u32;
let mut next = |n: i32| {
rng ^= rng << 13;
rng ^= rng >> 17;
rng ^= rng << 5;
(rng % n as u32) as i32
};
let start = std::time::Instant::now();
let mut changed = LightChanges::default();
for round in 0..2000 {
let state = [TORCH, SLAB, AIR][round % 3];
let pos = (next(32) - 8, next(12), next(32) - 8);
Arc::make_mut(w.get_mut(&(pos.0 >> 4, pos.2 >> 4)).unwrap()).set(
pos.0 & 15,
pos.1,
pos.2 & 15,
state,
);
relight(&mut w, &t, true, &[pos], false, &mut changed);
}
println!(
"relight_single_block_bench (single block: 2000 rounds): {:?}",
start.elapsed()
);
}
@@ -59,6 +59,16 @@ pub const CULL_BACK: [i8; 4] = [0, 0, 0, 1];
/// `Vertex::normal.w` of a shaded quad of an `entityCutoutCull` model (the bat): shaded by the
/// normal like -127, and `entity.wgsl` also discards its back-facing pixels.
pub const SHADED_CULL_W: i8 = -126;
/// `Vertex::normal` of a quad of an `entitySolid` model, which culls its back faces: a quad
/// the shader shades by its normal keeps it ([`SHADED_CULL_W`]), a baked-colour one (no
/// normal) gets [`CULL_BACK`].
pub fn cull_back(normal: [i8; 4]) -> [i8; 4] {
if normal == [0; 4] {
CULL_BACK
} else {
[normal[0], normal[1], normal[2], SHADED_CULL_W]
}
}
/// A section vertex: vanilla's `DefaultVertexFormat.BLOCK` (position, colour,
/// UV0, UV2) with the sprite's array layer beside the light, in 24 bytes
/// rather than vanilla's 28: the UV is fixed point, which holds model UVs
@@ -145,6 +155,17 @@ impl TerrainVertex {
}
}
#[cfg(test)]
mod cull_back_tests {
use super::{CULL_BACK, SHADED_CULL_W, cull_back};
/// #15322: a shaded `entitySolid` quad keeps its normal and culls; a baked one has
/// no normal and only culls.
#[test]
fn cull_back_keeps_a_shaded_normal() {
assert_eq!(cull_back([0; 4]), CULL_BACK);
assert_eq!(cull_back([0, 127, 0, 127]), [0, 127, 0, SHADED_CULL_W]);
}
}
#[cfg(test)]
mod vertex_tests {
use super::TerrainVertex;
+35 -154
View File
@@ -6,6 +6,8 @@ use std::time::Instant;
pub use crate::settings::Opt;
#[path = "options_ui_widgets.rs"]
mod widgets;
use crate::{
gamepad::{self, GlyphStyle},
hdr_calibration::Picture,
@@ -17,9 +19,18 @@ use crate::{
text::{self, Style, Text},
ui,
};
pub(crate) use widgets::{button, inactive};
#[path = "options_ui_values.rs"]
mod values;
pub(crate) use values::{chat_delay_label, chat_px, generic, on_off, percent};
mod shell_pages;
#[path = "options_ui_wheel.rs"]
mod wheel;
pub(crate) use wheel::slider_unsnapped;
fn tr(key: &str) -> Text {
Text::translate(key, &[])
}
@@ -31,18 +42,6 @@ pub static HORIZON_EXTRAS: std::sync::atomic::AtomicBool = std::sync::atomic::At
fn horizon_extras() -> bool {
HORIZON_EXTRAS.load(std::sync::atomic::Ordering::Relaxed)
}
fn generic(caption: &str, value: Text) -> Text {
Text::translate("options.generic_value", &[tr(caption), value])
}
fn percent(caption: &str, value: f32) -> Text {
Text::translate(
"options.percent_value",
&[
tr(caption),
Text::literal(((f64::from(value) * 100.0) as i32).to_string()),
],
)
}
/// `text` cut into lines of at most `width` characters, at spaces where it has them.
fn wrap(text: &str, width: usize) -> Vec<String> {
let mut lines = Vec::new();
@@ -67,20 +66,11 @@ fn wrap(text: &str, width: usize) -> Vec<String> {
}
lines
}
fn on_off(v: bool) -> Text {
tr(if v { "options.on" } else { "options.off" })
}
/// A music track's name as its row shows it: the file, without its folder
/// (`minecraft:music/game/calm1` -> `calm1`; the group names the situation).
fn track_name(id: &str) -> &str {
id.rsplit('/').next().unwrap_or(id)
}
fn chat_px(caption: &str, px: f32) -> Text {
Text::translate(
"options.pixel_value",
&[tr(caption), Text::literal((px as i32).to_string())],
)
}
pub(crate) enum Kind {
/// Slider position 0..1.
Slider(f32),
@@ -349,6 +339,7 @@ impl Opt {
pub(crate) fn kind(self, s: &Settings) -> Kind {
let unit = |v: f32, lo: f32, hi: f32| Kind::Slider(((v - lo) / (hi - lo)).clamp(0.0, 1.0));
match self {
Opt::ChatDelay => values::kind(s.file.double("chatDelay")),
Opt::FovEffects | Opt::DarknessPulsing => {
Kind::Slider(s.file.double(self.file_key().unwrap()).sqrt() as f32)
}
@@ -365,7 +356,7 @@ impl Opt {
),
Opt::SimulationDistance => unit(s.simulation_distance as f32, 5.0, 32.0),
Opt::Sensitivity => Kind::Slider(s.sensitivity),
Opt::WheelSensitivity => unit(s.mouse_wheel_sensitivity, 0.01, 10.0),
Opt::WheelSensitivity => wheel::kind(s.mouse_wheel_sensitivity),
Opt::Volume(i) => Kind::Slider(if i == 0 {
s.master_volume
} else {
@@ -457,6 +448,7 @@ impl Opt {
/// The discrete step count for stepped sliders, or `None` if continuous.
pub fn slider_steps(self) -> Option<u32> {
match self {
Opt::ChatDelay => Some(60),
Opt::Fov => Some(80),
Opt::RenderDistance => Some((crate::options_file::MAX_RENDER_DISTANCE - 2) as u32),
Opt::SimulationDistance => Some(27),
@@ -507,7 +499,7 @@ impl Opt {
pub fn label(self, s: &Settings) -> Text {
let c = self.caption();
match self {
Opt::ChatDelay => tr("options.chat.delay_none"),
Opt::ChatDelay => chat_delay_label(s),
Opt::FovEffects
| Opt::DarknessPulsing
| Opt::DistortionEffects
@@ -712,7 +704,7 @@ impl Opt {
} else {
"options.narrator.notavailable"
}),
Opt::ChatDelay => tr("options.chat.delay_none"),
Opt::ChatDelay => chat_delay_label(s),
Opt::HideLightningFlashes => on_off(s.file.bool("hideLightningFlashes")),
Opt::MonochromeLogo => on_off(s.file.bool("darkMojangStudiosBackground")),
Opt::HideSplashTexts => on_off(s.file.bool("hideSplashTexts")),
@@ -897,6 +889,7 @@ impl Opt {
let v = v.clamp(0.0, 1.0);
let step = |lo: f32, hi: f32| (lo + v * (hi - lo)).round();
match self {
Opt::ChatDelay => values::set(s, v),
Opt::FovEffects | Opt::DarknessPulsing => s.file.set(
self.file_key().unwrap(),
crate::options_file::V::Double(f64::from(v).powi(2)),
@@ -916,7 +909,7 @@ impl Opt {
}
Opt::SimulationDistance => s.simulation_distance = step(5.0, 32.0) as i32,
Opt::Sensitivity => s.sensitivity = v,
Opt::WheelSensitivity => s.mouse_wheel_sensitivity = 0.01 + v * 9.99,
Opt::WheelSensitivity => s.mouse_wheel_sensitivity = wheel::from_slider(v),
Opt::Volume(0) => s.master_volume = v,
Opt::Volume(i) => s.volumes[i] = v,
Opt::Gamma => s.gamma = v,
@@ -924,7 +917,7 @@ impl Opt {
Opt::CloudRange => s.cloud_range = step(2.0, 128.0) as i32,
Opt::EntityDistance => s.entity_distance = step(2.0, 20.0) / 4.0,
Opt::BiomeBlend => s.biome_blend = step(0.0, 7.0) as i32,
Opt::Preset => s.graphics_preset = PRESETS[step(0.0, 3.0) as usize].into(),
Opt::Preset => s.graphics_preset = PRESETS[preset_from_slider(v)].into(),
Opt::Mipmaps => s.mipmap_levels = step(0.0, 4.0) as i32,
Opt::MaxAnisotropy => s.file.set(
"maxAnisotropyBit",
@@ -1214,92 +1207,6 @@ impl Opt {
}
}
}
const PRESETS: [&str; 4] = ["fast", "fancy", "fabulous", "custom"];
fn preset_index(p: &str) -> usize {
PRESETS.iter().position(|x| *x == p).unwrap_or(1)
}
/// A slider moved to `v` (OptionInstance.set): the graphics preset applies
/// its options when its value changes (`Options.applyGraphicsPreset`).
pub fn set_slider(opt: Opt, s: &mut Settings, v: f32) {
let preset = preset_index(&s.graphics_preset);
opt.set_slider(s, v);
if opt == Opt::Preset && preset_index(&s.graphics_preset) != preset {
apply_preset(s);
}
}
/// A slider pressed or dragged to `v`: apply it live, and tell the game when
/// a category volume changed (`Options.createSoundSliderOptionInstance`'s
/// callback, which `OptionInstance.set` runs only for a new value).
fn drag_slider(opt: Opt, s: &mut Settings, v: f32, events: &mut Vec<Event>) {
let volume = |s: &Settings| match opt {
Opt::Volume(0) => Some(s.master_volume),
Opt::Volume(i) => Some(s.volumes[i]),
_ => None,
};
let before = volume(s);
set_slider(opt, s, v);
events.push(Event::SliderDrag);
if let (Opt::Volume(source), Some(after)) = (opt, volume(s))
&& before != Some(after)
{
events.push(Event::Volume(source, after));
}
}
/// GraphicsPreset.apply: the options Fast, Fancy and Fabulous set.
pub fn apply_preset(s: &mut Settings) {
let fabulous = s.graphics_preset == "fabulous";
match s.graphics_preset.as_str() {
"fast" => {
s.biome_blend = 1;
s.render_distance = 8;
s.prioritize_chunk_updates = 0;
s.simulation_distance = 6;
s.smooth_lighting = false;
s.clouds = "fast".into();
s.particles = 1;
s.mipmap_levels = 2;
s.entity_shadows = false;
s.entity_distance = 0.75;
s.menu_blur = 2;
s.cloud_range = 32;
s.cutout_leaves = false;
s.improved_transparency = false;
s.weather_radius = 5;
set_filtering(s, 1, 0);
}
"fancy" | "fabulous" => {
s.biome_blend = 2;
s.render_distance = if fabulous { 32 } else { 16 };
s.prioritize_chunk_updates = 1;
s.simulation_distance = 12;
s.smooth_lighting = true;
s.clouds = "true".into();
s.particles = 0;
s.mipmap_levels = 4;
s.entity_shadows = true;
s.entity_distance = if fabulous { 1.25 } else { 1.0 };
s.menu_blur = 5;
s.cloud_range = if fabulous { 128 } else { 64 };
s.cutout_leaves = true;
s.improved_transparency = fabulous;
s.weather_radius = 10;
// Fabulous takes anisotropic filtering (RGSS on a device with known issues, which
// wgpu does not report).
set_filtering(
s,
if fabulous { 2 } else { 1 },
if fabulous { 2 } else { 1 },
);
}
_ => {}
}
}
/// The preset's `maxAnisotropyBit` and `textureFiltering` (0 none, 1 RGSS, 2 anisotropic).
fn set_filtering(s: &mut Settings, anisotropy_bit: i32, filtering: i32) {
use crate::options_file::V;
s.file.set("maxAnisotropyBit", V::Int(anisotropy_bit));
s.file.set("textureFiltering", V::Int(filtering));
}
/// `Options.preferredGraphicsBackend`'s tooltip: the restart note once the choice differs from
/// the startup one, the description, and Vulkan's warning.
@@ -1388,7 +1295,7 @@ pub enum Page {
Music,
}
#[derive(Clone, Debug, PartialEq)]
enum Act {
pub(crate) enum Act {
None,
Push(Page),
Done,
@@ -1453,7 +1360,7 @@ enum WKind {
code: String,
},
}
struct Widget {
pub(crate) struct Widget {
x: f32,
y: f32,
w: f32,
@@ -1604,23 +1511,6 @@ pub struct MusicGroup {
/// The rows, in `sounds.json` order.
pub tracks: Vec<MusicTrack>,
}
/// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after
/// the last change (`OptionInstanceSliderButton.delayedApplyAt`).
fn delays_apply(opt: Opt) -> bool {
matches!(
opt,
Opt::RenderDistance | Opt::SimulationDistance | Opt::BiomeBlend | Opt::WheelSensitivity
)
}
/// Whether a slider still shows its own position: while held, or for a
/// delayed one until its value applies (both then `resetValue`).
fn slider_unsnapped(opt: Opt, held: bool, moved: Instant) -> bool {
if delays_apply(opt) {
moved.elapsed().as_millis() < 600
} else {
held
}
}
pub struct OptionsUi {
pub stack: Vec<Page>,
scroll: f32,
@@ -1806,27 +1696,6 @@ impl Default for OptionsUi {
}
}
}
fn button(x: f32, y: f32, w: f32, label: Text, act: Act) -> Widget {
Widget {
x,
y,
w,
h: 20.0,
kind: WKind::Button {
label,
active: true,
act,
},
list: false,
row: 0,
}
}
fn inactive(mut w: Widget) -> Widget {
if let WKind::Button { active, .. } = &mut w.kind {
*active = false;
}
w
}
fn option_widget(s: &Settings, opt: Opt, x: f32, y: f32, w: f32) -> Widget {
// OptionsSubScreen.addContents: the narrator button is active only while
// the narrator is (`narratorButton.active = narrator.isActive()`).
@@ -3193,13 +3062,20 @@ impl OptionsUi {
}
content = y + self.scroll - top + 2.0;
out[list_start..].iter_mut().for_each(|w| w.list = true);
out.push(button(
let reset_all = button(
cx - 154.0,
h - 27.0,
150.0,
tr("controls.resetAll"),
Act::ResetKeys,
));
);
// KeyBindsScreen.extractRenderState: active only while some
// binding differs from its default.
out.push(if s.keys.changed_from_defaults() {
reset_all
} else {
inactive(reset_all)
});
out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done));
}
Page::Language => {
@@ -8297,6 +8173,11 @@ mod tests {
}
}
#[path = "options_ui_preset.rs"]
mod preset;
pub(crate) use preset::{
PRESETS, apply_preset, drag_slider, preset_from_slider, preset_index, set_slider,
};
#[cfg(test)]
#[path = "options_ui_graphics_tests.rs"]
mod graphics_tests;
@@ -174,3 +174,42 @@ fn a_held_hdr_start_shows_as_the_graphics_screen_opens() {
assert_eq!(ui.graphics.screen.output.held, held);
}
}
/// The slider position `Opt::ChatDelay`'s kind() gives the stored seconds.
fn delay_pos(seconds: f64) -> f32 {
match values::kind(seconds) {
Kind::Slider(p) => p,
_ => panic!("the chat delay is a slider"),
}
}
/// `Options.chatDelay`: `IntRange(0, 60)` xmap(v / 10) — a slider in tenths of
/// a second from 0 to 6, not a button with no value behind it.
#[test]
fn the_chat_delay_slider_steps_in_tenths() {
assert_eq!(delay_pos(0.0), 0.0);
assert!((delay_pos(3.0) - 0.5).abs() < 1e-6);
assert_eq!(delay_pos(6.0), 1.0);
// A value past the option's range clamps to its last step.
assert_eq!(delay_pos(6.5), 1.0);
assert_eq!(Opt::ChatDelay.slider_steps(), Some(60));
let mut s = Settings::default();
set_slider(Opt::ChatDelay, &mut s, 0.0);
assert_eq!(s.file.double("chatDelay"), 0.0);
set_slider(Opt::ChatDelay, &mut s, 0.5);
assert!((s.file.double("chatDelay") - 3.0).abs() < 1e-9);
set_slider(Opt::ChatDelay, &mut s, 1.0);
assert!((s.file.double("chatDelay") - 6.0).abs() < 1e-9);
}
/// `Options.chatDelay`'s message: None at zero, else the delay to one decimal.
#[test]
fn the_chat_delay_slider_says_its_delay() {
let mut s = Settings::default();
assert_eq!(chat_delay_label(&s).plain(), "options.chat.delay_none");
s.file.set("chatDelay", crate::options_file::V::Double(2.0));
assert_eq!(chat_delay_label(&s).plain(), "Chat Delay: 2.0 second(s)");
s.file.set("chatDelay", crate::options_file::V::Double(6.0));
assert_eq!(chat_delay_label(&s).plain(), "Chat Delay: 6.0 second(s)");
s.file.set("chatDelay", crate::options_file::V::Double(0.0));
assert_eq!(chat_delay_label(&s).plain(), "options.chat.delay_none");
}
@@ -0,0 +1,121 @@
//! The graphics preset: `Options.graphicsPreset`'s slider position and the
//! options `GraphicsPreset.apply` sets.
use super::*;
pub(crate) const PRESETS: [&str; 4] = ["fast", "fancy", "fabulous", "custom"];
/// `SliderableEnum.fromSliderValue`: the slider's 0..1 position maps by
/// `floor(v * values)` with 1.0 just below it, clamped to the last stop (4
/// graphics presets), not by rounding `v * 3`.
pub(crate) fn preset_from_slider(v: f32) -> usize {
let v = if v >= 1.0 { 0.99999 } else { v };
((v * 4.0).floor() as usize).min(3)
}
pub(crate) fn preset_index(p: &str) -> usize {
PRESETS.iter().position(|x| *x == p).unwrap_or(1)
}
/// A slider moved to `v` (OptionInstance.set): the graphics preset applies
/// its options when its value changes (`Options.applyGraphicsPreset`).
pub(crate) fn set_slider(opt: Opt, s: &mut Settings, v: f32) {
let preset = preset_index(&s.graphics_preset);
opt.set_slider(s, v);
if opt == Opt::Preset && preset_index(&s.graphics_preset) != preset {
apply_preset(s);
}
}
/// A slider pressed or dragged to `v`: apply it live, and tell the game when
/// a category volume changed (`Options.createSoundSliderOptionInstance`'s
/// callback, which `OptionInstance.set` runs only for a new value).
pub(crate) fn drag_slider(opt: Opt, s: &mut Settings, v: f32, events: &mut Vec<Event>) {
let volume = |s: &Settings| match opt {
Opt::Volume(0) => Some(s.master_volume),
Opt::Volume(i) => Some(s.volumes[i]),
_ => None,
};
let before = volume(s);
set_slider(opt, s, v);
events.push(Event::SliderDrag);
if let (Opt::Volume(source), Some(after)) = (opt, volume(s))
&& before != Some(after)
{
events.push(Event::Volume(source, after));
}
}
/// GraphicsPreset.apply: the options Fast, Fancy and Fabulous set.
pub(crate) fn apply_preset(s: &mut Settings) {
let fabulous = s.graphics_preset == "fabulous";
match s.graphics_preset.as_str() {
"fast" => {
s.biome_blend = 1;
s.render_distance = 8;
s.prioritize_chunk_updates = 0;
s.simulation_distance = 6;
s.smooth_lighting = false;
s.clouds = "fast".into();
s.particles = 1;
s.mipmap_levels = 2;
s.entity_shadows = false;
s.entity_distance = 0.75;
s.menu_blur = 2;
s.cloud_range = 32;
s.cutout_leaves = false;
s.improved_transparency = false;
s.weather_radius = 5;
set_filtering(s, 1, 0);
}
"fancy" | "fabulous" => {
s.biome_blend = 2;
s.render_distance = if fabulous { 32 } else { 16 };
s.prioritize_chunk_updates = 1;
s.simulation_distance = 12;
s.smooth_lighting = true;
s.clouds = "true".into();
s.particles = 0;
s.mipmap_levels = 4;
s.entity_shadows = true;
s.entity_distance = if fabulous { 1.25 } else { 1.0 };
s.menu_blur = 5;
s.cloud_range = if fabulous { 128 } else { 64 };
s.cutout_leaves = true;
s.improved_transparency = fabulous;
s.weather_radius = 10;
// Fabulous takes anisotropic filtering (RGSS on a device with known issues, which
// wgpu does not report).
set_filtering(
s,
if fabulous { 2 } else { 1 },
if fabulous { 2 } else { 1 },
);
}
_ => {}
}
}
/// The preset's `maxAnisotropyBit` and `textureFiltering` (0 none, 1 RGSS, 2 anisotropic).
fn set_filtering(s: &mut Settings, anisotropy_bit: i32, filtering: i32) {
use crate::options_file::V;
s.file.set("maxAnisotropyBit", V::Int(anisotropy_bit));
s.file.set("textureFiltering", V::Int(filtering));
}
#[cfg(test)]
mod tests {
use super::*;
/// `SliderableEnum.fromSliderValue`: the graphics preset slider's stops are
/// floor(v * 4), 1.0 landing on the last, and the value setter follows.
#[test]
fn the_graphics_preset_slider_uses_floor_stops() {
assert_eq!(preset_from_slider(0.0), 0);
assert_eq!(preset_from_slider(0.24), 0);
assert_eq!(preset_from_slider(0.25), 1);
assert_eq!(preset_from_slider(0.49), 1);
assert_eq!(preset_from_slider(0.5), 2);
assert_eq!(preset_from_slider(0.74), 2);
assert_eq!(preset_from_slider(0.75), 3);
assert_eq!(preset_from_slider(1.0), 3);
let mut s = Settings::default();
set_slider(Opt::Preset, &mut s, 0.2);
assert_eq!(s.graphics_preset, "fast");
set_slider(Opt::Preset, &mut s, 0.8);
assert_eq!(s.graphics_preset, "custom");
}
}
@@ -0,0 +1,54 @@
//! The small option value labels (`generic`, `percent`, `on_off`, `chat_px`,
//! `chat_delay_label`) and `Options.chatDelay`'s slider mapping.
use super::*;
pub(crate) fn generic(caption: &str, value: Text) -> Text {
Text::translate("options.generic_value", &[tr(caption), value])
}
pub(crate) fn on_off(v: bool) -> Text {
tr(if v { "options.on" } else { "options.off" })
}
pub(crate) fn chat_px(caption: &str, px: f32) -> Text {
Text::translate(
"options.pixel_value",
&[tr(caption), Text::literal((px as i32).to_string())],
)
}
pub(crate) fn percent(caption: &str, value: f32) -> Text {
Text::translate(
"options.percent_value",
&[
tr(caption),
Text::literal(((f64::from(value) * 100.0) as i32).to_string()),
],
)
}
/// `Options.chatDelay`'s message: `options.chat.delay_none` at zero, else
/// `options.chat.delay` with the delay to one decimal (`%.1f` seconds).
pub(crate) fn chat_delay_label(s: &Settings) -> Text {
let value = s.file.double("chatDelay") as f32;
if value <= 0.0 {
Text::translate("options.chat.delay_none", &[])
} else {
Text::translate_with_fallback(
"options.chat.delay",
"Chat Delay: %s second(s)",
&[Text::literal(format!("{value:.1}"))],
)
}
}
/// `IntRange(0, 60).toSliderValue` on the stored seconds (`xmap(v / 10.0)`):
/// the tenth-of-a-second step over the slider's 60.
pub(crate) fn kind(value: f64) -> Kind {
Kind::Slider(((value * 10.0).floor() / 60.0).clamp(0.0, 1.0) as f32)
}
/// `IntRange(0, 60).fromSliderValue` then `xmap`'s `/ 10.0`:
/// floor(map(v, 0, 1, 0, 61)), the last step capped at 60, in tenths.
pub(crate) fn from_slider(v: f32) -> f64 {
f64::from((v.clamp(0.0, 1.0) * 61.0).floor().min(60.0) / 10.0)
}
/// `Options.chatDelay.set`: the slider's value as the stored seconds.
pub(crate) fn set(s: &mut Settings, v: f32) {
s.file
.set("chatDelay", crate::options_file::V::Double(from_slider(v)));
}
@@ -0,0 +1,71 @@
//! `Options.mouseWheelSensitivity`'s logarithmic slider (`logMouse`/`unlogMouse`)
//! and the delayed-apply test the slider buttons share.
use super::*;
use std::time::Instant;
/// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after
/// the last change (`OptionInstanceSliderButton.delayedApplyAt`).
fn delays_apply(opt: Opt) -> bool {
matches!(
opt,
Opt::RenderDistance | Opt::SimulationDistance | Opt::BiomeBlend | Opt::WheelSensitivity
)
}
/// Whether a slider still shows its own position: while held, or for a
/// delayed one until its value applies (both then `resetValue`).
pub(crate) fn slider_unsnapped(opt: Opt, held: bool, moved: Instant) -> bool {
if delays_apply(opt) {
moved.elapsed().as_millis() < 600
} else {
held
}
}
/// `Options.unlogMouse`: the stored sensitivity as its hundredth-log step,
/// -200..=100, which the `IntRange(-200, 100)` slider runs over (0.01 to 10.0).
pub(crate) fn step(value: f32) -> f32 {
(value.max(1.0e-6).log10() * 100.0)
.floor()
.clamp(-200.0, 100.0)
}
/// `IntRange(-200, 100).toSliderValue`: the step over the slider's span.
pub(crate) fn kind(value: f32) -> Kind {
Kind::Slider(((step(value) + 200.0) / 300.0).clamp(0.0, 1.0))
}
/// `IntRange(-200, 100).fromSliderValue` then `Options.logMouse`:
/// floor(map(v, 0, 1, -200, 101)), the last step clamped, as 10^(i/100).
pub(crate) fn from_slider(v: f32) -> f32 {
let i = (v.clamp(0.0, 1.0) * 301.0).floor() - 200.0;
10.0_f32.powf(i.clamp(-200.0, 100.0) / 100.0)
}
#[cfg(test)]
mod tests {
use super::*;
/// The slider position `Opt::WheelSensitivity`'s kind() gives a value.
fn wheel_pos(value: f32) -> f32 {
match kind(value) {
Kind::Slider(p) => p,
_ => panic!("the wheel sensitivity is a slider"),
}
}
/// `Options.mouseWheelSensitivity` runs over `IntRange(-200, 100)` through
/// `logMouse`/`unlogMouse`: 10^(i/100), 0.01 to 10.0, not a straight line.
#[test]
fn the_mouse_wheel_sensitivity_slider_is_logarithmic() {
// 1.0 is step 0: 200 of the 300 slider steps in, not at 0.099.
assert!((wheel_pos(1.0) - 2.0 / 3.0).abs() < 1e-6);
assert!((wheel_pos(0.01) - 0.0).abs() < 1e-6);
assert!((wheel_pos(10.0) - 1.0).abs() < 1e-6);
assert!((from_slider(2.0 / 3.0) - 1.0).abs() < 1e-5);
assert!((from_slider(0.0) - 0.01).abs() < 1e-6);
assert!((from_slider(1.0) - 10.0).abs() < 1e-4);
assert!((from_slider(1.0 / 3.0) - 0.1).abs() < 1e-5);
// The value setter goes through the same mapping.
let mut s = Settings::default();
set_slider(Opt::WheelSensitivity, &mut s, 2.0 / 3.0);
assert!((s.mouse_wheel_sensitivity - 1.0).abs() < 1e-5);
set_slider(Opt::WheelSensitivity, &mut s, 0.0);
assert!((s.mouse_wheel_sensitivity - 0.01).abs() < 1e-6);
}
}
@@ -0,0 +1,25 @@
//! The option screens' widget constructors: a 20-pixel button row and the
//! same widget turned inactive.
use super::*;
pub(crate) fn button(x: f32, y: f32, w: f32, label: Text, act: Act) -> Widget {
Widget {
x,
y,
w,
h: 20.0,
kind: WKind::Button {
label,
active: true,
act,
},
list: false,
row: 0,
}
}
pub(crate) fn inactive(mut w: Widget) -> Widget {
if let WKind::Button { active, .. } = &mut w.kind {
*active = false;
}
w
}
@@ -1718,6 +1718,19 @@ impl PackScreen {
[32, 2],
);
if l.scrollable() {
// AbstractScrollArea.extractScrollbar: over the bar, the pointer
// points, or resizes while the bar is held.
let over_bar = mouse.0 >= l.scroll_bar_x()
&& mouse.0 < l.scroll_bar_x() + 6
&& mouse.1 >= l.y
&& mouse.1 < l.bottom();
if over_bar {
crate::widgets::request_cursor(if l.held.is_some() {
crate::widgets::Cursor::ResizeNs
} else {
crate::widgets::Cursor::PointingHand
});
}
let sh = l.scroller_height().clamp(32, l.height - 8);
let sy = (l.scroll as i32 * (l.height - sh) / l.max_scroll() + l.y).max(l.y);
d::sprite(
@@ -2197,6 +2210,29 @@ mod icon_slot_tests {
/// Only the available list has packs: one row of 36 for each of `count` icons fits in a
/// window `height` high.
/// `AbstractScrollArea.extractScrollbar`: over a held pack list's bar the
/// pointer asks to resize vertically, at rest it points.
#[test]
fn the_pack_scrollbar_asks_for_its_cursor() {
let atlas = atlas();
let m = Measure(&atlas.font);
let mut screen = screen(&m, 30, 200);
let l = &screen.lists[0];
assert!(l.scrollable());
let at = (l.scroll_bar_x() + 2, l.y + 8);
let _ = crate::widgets::take_cursor();
screen.draw(&m, at, 0, 0);
assert_eq!(
crate::widgets::take_cursor(),
crate::widgets::Cursor::PointingHand
);
screen.lists[0].held = Some(f64::from(at.1));
screen.draw(&m, at, 0, 0);
assert_eq!(
crate::widgets::take_cursor(),
crate::widgets::Cursor::ResizeNs
);
}
fn screen(m: &Measure, count: usize, height: i32) -> PackScreen {
PackScreen::new(
m,
@@ -466,6 +466,13 @@ fn read_meta(source: &Source) -> Option<serde_json::Value> {
/// file with a comment after the closing brace. Gson reads past a UTF-8 byte order mark;
/// serde_json rejects it.
pub(crate) fn parse_meta(bytes: &[u8]) -> Option<serde_json::Value> {
first_json(bytes)
}
/// Reads the first JSON value from resource metadata, matching Gson's
/// `JsonReader` (which ignores a trailing signature or comment). Resource
/// packs commonly append such text to texture metadata as well as pack.mcmeta.
pub(crate) fn first_json(bytes: &[u8]) -> Option<serde_json::Value> {
serde_json::Deserializer::from_slice(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes))
.into_iter()
.next()?
+18 -34
View File
@@ -526,6 +526,8 @@ pub struct Particle {
no_render: bool,
/// Ticked once when created (`CritParticle` constructor).
pre_tick: bool,
/// A Polytone particle with physics, which joins only where its box is clear of blocks.
spawn_check: bool,
/// `Particle.random`: the particle's own generator (`RandomSource.create()`).
random: LegacyRandom,
controller: Option<Box<dyn native::Controller>>,
@@ -895,6 +897,7 @@ impl Particle {
behaviour: Behaviour::Base,
no_render: false,
pre_tick: false,
spawn_check: false,
frame_ticks: 0,
random: LegacyRandom::new(0),
controller: None,
@@ -1759,28 +1762,6 @@ impl ParticleEngine {
particle.controller = Some(Box::new(controller));
Some(particle)
}
/// Sets (or clears) the resource packs' Polytone custom particle types.
pub fn set_polytone(&mut self, registry: Option<std::sync::Arc<polytone::Registry>>) {
let registry = registry.filter(|r| !r.is_empty());
let same = match (&self.polytone, &registry) {
(Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
(None, None) => true,
_ => false,
};
if !same {
self.polytone_gpu.clear();
self.polytone_overrides = registry
.iter()
.flat_map(|r| {
ParticleType::ALL.iter().filter_map(|&ty| {
let id = format!("minecraft:{}", ty.name());
r.get(&id).is_some().then_some((ty, id))
})
})
.collect();
}
self.polytone = registry;
}
/// The quads the last render blends additively (`RenderPipelines` additive, src alpha and
/// one), for the frame's additive pass.
pub fn take_additive(&self) -> Vec<Vertex> {
@@ -3621,13 +3602,14 @@ impl ParticleEngine {
self.sprite_from_age(&mut q);
q
}
/// ClientLevel.createFireworks: a Starter (or poofs without explosions).
/// ClientLevel.createFireworks: a Starter (or poofs without explosions) with `playSound`.
pub fn fireworks(
&mut self,
at: [f64; 3],
v: [f64; 3],
explosions: Vec<FireworkExplosion>,
camera: [f64; 3],
play_sound: bool,
) {
if explosions.is_empty() {
for _ in 0..self.random.next_int_bound(3).unwrap_or(0) + 2 {
@@ -3651,17 +3633,17 @@ impl ParticleEngine {
life: 0,
lifetime,
twinkle_delay: twinkle,
far,
sound: play_sound.then_some(far),
});
}
fn tick_starters(&mut self) {
for mut s in std::mem::take(&mut self.starters) {
if s.life == 0 {
if s.life == 0 && s.sound.is_some() {
let large = s.explosions.len() >= 3
|| s.explosions
.iter()
.any(|e| e.shape == FireworkShape::LargeBall);
let sound = match (large, s.far) {
let sound = match (large, s.sound == Some(true)) {
(true, true) => "minecraft:entity.firework_rocket.large_blast_far",
(true, false) => "minecraft:entity.firework_rocket.large_blast",
(false, true) => "minecraft:entity.firework_rocket.blast_far",
@@ -3704,16 +3686,13 @@ impl ParticleEngine {
(c & 255) as f32 / 255.0,
((c >> 24) & 255) as f32 / 255.0,
];
self.create(
&ParticleOptions::colored(ParticleType::Flash, rgba),
s.at,
[0.0; 3],
);
let flash = ParticleOptions::colored(ParticleType::Flash, rgba);
self.create(&flash, s.at, [0.0; 3]);
}
s.life += 1;
if s.life > s.lifetime {
if s.twinkle_delay {
let sound = if s.far {
if s.twinkle_delay && s.sound.is_some() {
let sound = if s.sound == Some(true) {
"minecraft:entity.firework_rocket.twinkle_far"
} else {
"minecraft:entity.firework_rocket.twinkle"
@@ -3846,6 +3825,9 @@ impl ParticleEngine {
}
let pending = std::mem::take(&mut self.pending);
for mut p in pending {
if !self.polytone_joins(&p, level) {
continue;
}
if p.pre_tick {
p.pre_tick = false;
self.tick_particle(&mut p, level);
@@ -5054,7 +5036,9 @@ struct Starter {
life: i32,
lifetime: i32,
twinkle_delay: bool,
far: bool,
/// `FireworkParticles.Starter.playSound`, with `isFarAwayFromCamera` when
/// it plays: `None` for a silent rocket.
sound: Option<bool>,
}
const STAR: [[f64; 2]; 6] = [
[0.0, 1.0],
@@ -1090,6 +1090,40 @@ const INITIALIZED: [&str; 13] = [
"dz",
];
/// Whether no block's collision shape overlaps `bb` (where the query fails, nothing does).
pub(super) fn unobstructed(level: &ParticleLevel<'_>, bb: horizon_core::geometry::Aabb) -> bool {
let mut scene = crate::collisions::SceneCollisions {
world: level.world,
binding: level.collision,
subject: None,
};
scene.cells_without_collision(bb) || scene.unobstructed(bb).unwrap_or(true)
}
impl ParticleEngine {
/// Whether a pending Polytone particle joins the world. One with physics whose box starts
/// inside a block's collision never does, and its type's `limit` is then counted among those
/// that joined, so one that never joins takes no place (measured on the mod: with `limit` 1,
/// one born inside a block and one clear of it in the same tick, the clear one shows).
pub(super) fn polytone_joins(&self, p: &Particle, level: &ParticleLevel<'_>) -> bool {
if !p.spawn_check {
return true;
}
if !unobstructed(level, p.bb) {
return false;
}
let Some(name) = p.polytone_type.as_deref() else {
return true;
};
let def = self.polytone.as_ref().and_then(|r| r.get(name));
let limit = def.and_then(|d| d.limit.filter(|_| d.gpu.is_none()));
limit.is_none_or(|limit| {
let same = |q: &&Particle| !q.removed && q.polytone_type.as_deref() == Some(name);
self.particles.iter().filter(same).count() < limit as usize
})
}
}
impl super::ParticleController for Controller {
fn tick(&mut self, p: &mut Particle, level: &ParticleLevel<'_>) -> ParticleUpdate {
let mut update = ParticleUpdate::default();
@@ -1204,7 +1238,8 @@ pub(super) fn make(
velocity: [f64; 3],
seed: i64,
) -> Option<Particle> {
// `limit`: at most that many of the type alive at once.
// `limit`: at most that many of the type alive at once. A pending one with physics may never
// join (`polytone_joins`), so it takes no place until it does.
// (A GPU particle's `limit` is its ring of records instead.)
if let Some(limit) = def.limit
&& def.gpu.is_none()
@@ -1212,7 +1247,7 @@ pub(super) fn make(
let alive = engine
.particles
.iter()
.chain(&engine.pending)
.chain(engine.pending.iter().filter(|p| !p.spawn_check))
.filter(|p| !p.removed && p.polytone_type.as_deref() == Some(name))
.count();
if alive >= limit as usize {
@@ -1220,10 +1255,11 @@ pub(super) fn make(
}
}
// `exclusion_radius`: none spawns within that distance of a live one of its type (rain
// splashes, one per patch of ground).
// splashes, one per patch of ground from tick to tick). Only those already in the world count: measured on
// the mod, two spawned in the same tick a block apart both show, with or without physics.
if def.exclusion_radius > 0.0 && def.gpu.is_none() {
let r2 = def.exclusion_radius * def.exclusion_radius;
let crowded = engine.particles.iter().chain(&engine.pending).any(|p| {
let crowded = engine.particles.iter().any(|p| {
!p.removed
&& p.polytone_type.as_deref() == Some(name)
&& (0..3)
@@ -1320,6 +1356,10 @@ pub(super) fn make(
particle.polytone_type =
(def.limit.is_some() || def.exclusion_radius > 0.0).then(|| Arc::from(name));
particle.bb = super::aabb_at(position, particle.bb_width, particle.bb_height);
// A particle with physics whose box starts inside a block's collision never joins the world:
// it is not drawn and none of its emitters run (measured on the mod: one spawned just under a
// block, where falling leaves start, never shows; one 0.01 clear of it does).
particle.spawn_check = def.has_physics;
particle.controller = Some(Box::new(Controller {
def: def.clone(),
registry: registry.clone(),
@@ -1531,6 +1571,31 @@ impl ParticleEngine {
}
}
impl ParticleEngine {
/// Sets (or clears) the resource packs' Polytone custom particle types.
pub fn set_polytone(&mut self, registry: Option<Arc<Registry>>) {
let registry = registry.filter(|r| !r.is_empty());
let same = match (&self.polytone, &registry) {
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
(None, None) => true,
_ => false,
};
if !same {
self.polytone_gpu.clear();
self.polytone_overrides = registry
.iter()
.flat_map(|r| {
ParticleType::ALL.iter().filter_map(|&ty| {
let id = format!("minecraft:{}", ty.name());
r.get(&id).is_some().then_some((ty, id))
})
})
.collect();
}
self.polytone = registry;
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1819,7 +1884,8 @@ mod tests {
let root = pack(&[
(
"assets/test/polytone/custom_particles/splash.json",
serde_json::json!({"has_physics": false, "exclusion_radius": 1, "render_type": "invisible"}),
serde_json::json!({"has_physics": false, "exclusion_radius": 1, "render_type": "invisible",
"initializer": {"lifetime": "100"}}),
),
(
"assets/test/polytone/custom_particles/drop.json",
@@ -1829,7 +1895,8 @@ mod tests {
"assets/minecraft/polytone/entity_modifiers/player.json",
serde_json::json!({"emitters": [
{"particle": "test:splash", "x": "0", "chance": "1"},
// 0.5 from the first: excluded.
// 0.5 from the first, in the same tick: the first isn't in the world yet,
// so it spawns (measured on the mod).
{"particle": "test:splash", "x": "0.5", "chance": "1"},
// 3 away: spawns.
{"particle": "test:splash", "x": "3", "chance": "1"},
@@ -1851,7 +1918,15 @@ mod tests {
engine.polytone_entity(&level, "minecraft:player", [1.0, 64.0, 1.0]);
let mut xs: Vec<f64> = engine.pending.iter().map(|p| p.position[0]).collect();
xs.sort_by(f64::total_cmp);
assert_eq!(xs, [1.0, 1.5, 4.0]);
assert_eq!(xs, [1.0, 1.5, 1.5, 4.0]);
// Once they are in the world, the next tick's splashes near them are excluded; ones
// farther than the radius from all of them spawn, again without excluding each other.
engine.tick(&level);
let splashes = |p: &&Particle| p.polytone_type.as_deref() == Some("test:splash");
engine.polytone_entity(&level, "minecraft:player", [1.0, 64.0, 1.0]);
assert_eq!(engine.pending.iter().filter(splashes).count(), 0);
engine.polytone_entity(&level, "minecraft:player", [9.0, 64.0, 1.0]);
assert_eq!(engine.pending.iter().filter(splashes).count(), 3);
std::fs::remove_dir_all(root).unwrap();
}
@@ -2244,6 +2319,208 @@ mod tests {
std::fs::remove_dir_all(root).unwrap();
}
/// `scene`, with the torch a full block of collision: something a particle's box can start in.
fn solid_scene(blocks: &'static BlockRegistry) -> Scene {
use horizon_core::geometry::{Axis, VoxelShape};
let tag = |shape: VoxelShape| {
let sizes = shape.sizes();
let occupied = (0..sizes[2])
.flat_map(|z| {
(0..sizes[1]).flat_map(move |y| (0..sizes[0]).map(move |x| (x, y, z)))
})
.map(|(x, y, z)| u8::from(shape.is_full(x as i32, y as i32, z as i32)))
.collect();
let (min, max) = shape.discrete_bounds();
let axes = shape
.cube_coordinate_axes()
.iter()
.enumerate()
.fold(0, |mask, (i, on)| mask | (i8::from(*on) << i));
let mut fields = vec![
("occupied", Tag::ByteArray(occupied)),
("cube", Tag::Byte(i8::from(shape.is_cube()))),
("cube_axes", Tag::Byte(axes)),
("discrete_min", Tag::IntArray(min.to_vec())),
("discrete_max", Tag::IntArray(max.to_vec())),
];
for (axis, name) in [(Axis::X, "x"), (Axis::Y, "y"), (Axis::Z, "z")] {
let bits = shape.coordinates(axis).iter().map(|v| v.to_bits() as i64);
fields.push((name, Tag::LongArray(bits.collect())));
}
Tag::compound(fields)
};
let names = || Tag::List(STATES.iter().map(|s| Tag::String((*s).into())).collect());
let cached = CachedCollisionRegistry::from_nbt(
&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
("states", names()),
(
"shapes",
Tag::List(vec![tag(VoxelShape::empty()), tag(VoxelShape::block())]),
),
("cached_shapes", Tag::IntArray(vec![0, 1])),
]),
blocks,
)
.unwrap();
Scene {
collision: BlockCollisionRegistry::new(Arc::new(cached)).unwrap(),
..scene(blocks)
}
}
#[test]
fn a_particle_with_physics_born_inside_a_block_never_joins() {
let blocks = blocks();
let leaf = |physics| {
serde_json::json!({"has_physics": physics, "render_type": "invisible",
"initializer": {"lifetime": "20", "hitbox_size": "0.08"},
"particle_emitters": [{"particle": "test:mark", "chance": "1"}]})
};
let root = pack(&[
(
"assets/test/polytone/custom_particles/leaf.json",
leaf(true),
),
(
"assets/test/polytone/custom_particles/ghost.json",
leaf(false),
),
(
"assets/test/polytone/custom_particles/mark.json",
serde_json::json!({"render_type": "invisible", "has_physics": false}),
),
(
"assets/minecraft/polytone/entity_modifiers/player.json",
serde_json::json!({"emitters": [{"particle": "test:leaf", "chance": "1"}]}),
),
(
"assets/test/polytone/custom_particles/wide.json",
serde_json::json!({"has_physics": true, "render_type": "invisible",
"initializer": {"lifetime": "20", "hitbox_size": 10},
"particle_emitters": [{"particle": "test:mark", "chance": "1"}]}),
),
(
"assets/test/polytone/custom_particles/parent.json",
serde_json::json!({"has_physics": true, "render_type": "invisible",
"initializer": {"lifetime": "20", "hitbox_size": "0.08"},
"particle_emitters": [{"particle": "test:wide", "chance": "1", "y": "-0.05"}]}),
),
(
"assets/minecraft/polytone/entity_modifiers/skeleton.json",
serde_json::json!({"emitters": [{"particle": "test:parent", "chance": "1", "x": "-4.5"}]}),
),
(
"assets/minecraft/polytone/entity_modifiers/creeper.json",
serde_json::json!({"emitters": [{"particle": "test:wide", "chance": "1", "x": "-4.5"}]}),
),
(
"assets/minecraft/polytone/entity_modifiers/zombie.json",
serde_json::json!({"emitters": [{"particle": "test:ghost", "chance": "1"}]}),
),
]);
let scene = solid_scene(blocks);
let level = ParticleLevel {
world: &scene.world,
facts: &scene.facts,
collision: &scene.collision,
player: None,
cached_chunk: std::cell::Cell::new(None),
};
let mut engine = engine(Registry::read(&root, Default::default(), blocks));
// The solid block is at (1, 64, 1): its bottom face is y 64.
// Spawns one particle, lets the engine take it in and tick it: whether it joined, and
// how many particles it emitted.
let mut spawn = |entity: &str, y: f64| {
engine.particles.clear();
engine.pending.clear();
engine.polytone_entity(&level, entity, [1.5, y, 1.5]);
engine.tick(&level);
let joined = engine.particles.len();
engine.tick(&level);
(
joined,
engine.particles.len() + engine.pending.len() - joined,
)
};
// The solid block is at (1, 64, 1): its bottom face is y 64.
// 0.05 under the block, a 0.08 box reaches into it: it never joins, nothing emitted.
assert_eq!(spawn("minecraft:player", 63.95), (0, 0));
// 0.01 clear of it, it joins and emits.
assert_eq!(spawn("minecraft:player", 63.91), (1, 1));
// Without physics nothing collides.
assert_eq!(spawn("minecraft:zombie", 63.95), (1, 1));
// A wide box reaching a block from five blocks away does not join either.
assert_eq!(spawn("minecraft:creeper", 60.0), (0, 0));
// Nor does one a clear particle emits there: the small one joins, its wide copy never.
assert_eq!(spawn("minecraft:skeleton", 60.0), (1, 0));
std::fs::remove_dir_all(root).unwrap();
}
/// Measured on the mod: with `limit` 1, one particle born inside a block and one clear of it
/// in the same tick, the clear one shows. The one that never joins takes no place.
#[test]
fn a_particle_that_never_joins_takes_no_place_under_its_limit() {
let blocks = blocks();
let lim = |x: &str| serde_json::json!({"particle": "test:lim", "chance": "1", "x": x});
let root = pack(&[
(
"assets/test/polytone/custom_particles/lim.json",
serde_json::json!({"has_physics": true, "render_type": "invisible", "limit": 1,
"initializer": {"lifetime": "20", "hitbox_size": "0.08"}}),
),
// The first inside the block's reach, the second three blocks clear of it.
(
"assets/minecraft/polytone/entity_modifiers/player.json",
serde_json::json!({"emitters": [lim("0"), lim("3")]}),
),
// Two clear of it: the limit still keeps one.
(
"assets/minecraft/polytone/entity_modifiers/zombie.json",
serde_json::json!({"emitters": [lim("3"), lim("6")]}),
),
// `exclusion_radius` with physics: the one inside the block doesn't keep the clear
// one a block away from spawning.
(
"assets/test/polytone/custom_particles/exc.json",
serde_json::json!({"has_physics": true, "render_type": "invisible",
"exclusion_radius": 2,
"initializer": {"lifetime": "20", "hitbox_size": "0.08"}}),
),
(
"assets/minecraft/polytone/entity_modifiers/skeleton.json",
serde_json::json!({"emitters": [
{"particle": "test:exc", "chance": "1", "x": "0"},
{"particle": "test:exc", "chance": "1", "x": "1"}]}),
),
]);
let scene = solid_scene(blocks);
let level = ParticleLevel {
world: &scene.world,
facts: &scene.facts,
collision: &scene.collision,
player: None,
cached_chunk: std::cell::Cell::new(None),
};
let mut engine = engine(Registry::read(&root, Default::default(), blocks));
let mut joined = |entity: &str| {
engine.particles.clear();
engine.pending.clear();
// The solid block is at (1, 64, 1): 0.05 under it, a 0.08 box reaches into it.
engine.polytone_entity(&level, entity, [1.5, 63.95, 1.5]);
engine.tick(&level);
engine
.particles
.iter()
.map(|p| p.position[0])
.collect::<Vec<_>>()
};
assert_eq!(joined("minecraft:player"), vec![4.5]);
assert_eq!(joined("minecraft:zombie"), vec![4.5]);
assert_eq!(joined("minecraft:skeleton"), vec![2.5]);
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn a_pack_custom_particle_replaces_the_vanilla_type_of_its_id() {
let root = pack(&[(
@@ -43,7 +43,7 @@ fn spawn_tick(engine: &mut ParticleEngine, rng: &mut Lcg, types: &[Emitter], roc
twinkle: false,
};
let at = [-5.5 + rng.next() * 12.0, f64::from(FLOOR_Y + 20), 20.5];
engine.fireworks(at, [0.0, 0.1, 0.0], vec![explosion], engine.camera);
engine.fireworks(at, [0.0, 0.1, 0.0], vec![explosion], engine.camera, true);
}
for &(ty, count, center, delta, speed) in types {
let options = ParticleOptions::simple(ty);
@@ -7,13 +7,16 @@ use horizon_core::{
geometry::{Vec3, traverse_blocks},
position::BlockPos,
};
use horizon_world::collision_context::CollisionContext;
/// `PotentSulfurBlock.ALLOWED_WATER_BLOCKS_ABOVE`.
const ALLOWED_WATER_BLOCKS_ABOVE: i32 = 4;
/// `PotentSulfurBlockEntity.isGeyserPassableBlock`: air, water, or a block
/// with no collision shape.
pub fn is_geyser_passable_block(level: &ParticleLevel, pos: [i32; 3]) -> bool {
/// with no collision shape for `CollisionContext.positionContext(context_y)`.
/// Vanilla passes the height of the block under the column it reads, so
/// scaffolding seen from below lets the gas and the geyser through.
pub fn is_geyser_passable_block(level: &ParticleLevel, pos: [i32; 3], context_y: i32) -> bool {
let state = level.world.block(pos[0], pos[1], pos[2]);
if level.facts.is_air(state) || &*level.facts.get(state).name == "minecraft:water" {
return true;
@@ -23,7 +26,9 @@ pub fn is_geyser_passable_block(level: &ParticleLevel, pos: [i32; 3]) -> bool {
binding: level.collision,
subject: None,
};
match level.collision.collision_shape(&mut scene, state, pos) {
let context = CollisionContext::position(f64::from(context_y));
let position = BlockPos::new(pos[0], pos[1], pos[2]);
match (level.collision).collision_shape_with_context(&mut scene, state, position, &context) {
Ok(shape) => shape.is_empty(),
Err(_) => !level.facts.get(state).full_collision,
}
@@ -46,9 +51,9 @@ pub fn find_noxious_gas_source_block(level: &ParticleLevel, origin: [i32; 3]) ->
let state = level.world.block(pos[0], pos[1], pos[2]);
let is_water_block = &*level.facts.get(state).name == "minecraft:water";
if !is_water_source(level, pos)
|| (!is_water_block && !is_geyser_passable_block(level, pos))
|| (!is_water_block && !is_geyser_passable_block(level, pos, origin[1]))
{
if level.facts.is_air(state) || is_geyser_passable_block(level, pos) {
if level.facts.is_air(state) || is_geyser_passable_block(level, pos, origin[1]) {
return Some(pos);
}
break;
@@ -63,7 +68,7 @@ pub fn find_noxious_gas_source_block(level: &ParticleLevel, origin: [i32; 3]) ->
pub fn unobstructed_block_count(level: &ParticleLevel, pos: [i32; 3], water_blocks: i32) -> i32 {
let geyser_force_height = 6 * water_blocks;
for i in 0..geyser_force_height {
if !is_geyser_passable_block(level, [pos[0], pos[1] + i, pos[2]]) {
if !is_geyser_passable_block(level, [pos[0], pos[1] + i, pos[2]], pos[1] - 1) {
return i;
}
}
@@ -79,7 +84,7 @@ pub fn can_be_reached_by_noxious_gas(
pos: [f64; 3],
) -> bool {
let block = ParticleLevel::block_at(pos);
if !is_geyser_passable_block(level, block) {
if !is_geyser_passable_block(level, block, block[1] - 1) {
return false;
}
let center = source_block.map(|c| f64::from(c) + 0.5);
@@ -277,6 +277,14 @@ pub fn take_text_input_area() -> Option<[f32; 4]> {
mod tests {
use super::*;
/// The tests that change [`STATE`] take turns: it is one for the whole process, and
/// cargo runs tests in parallel, so one test's `reset` or `should_suppress_key` could
/// land in the middle of another (#14577).
static STATE_TESTS: Mutex<()> = Mutex::new(());
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
STATE_TESTS.lock().unwrap_or_else(|e| e.into_inner())
}
#[test]
fn empty_text_is_no_composition() {
assert_eq!(PreeditEvent::from_sdl_text_editing(None, 0, 0), None);
@@ -352,6 +360,7 @@ mod tests {
#[test]
fn set_and_clear_preedit() {
let _turn = one_at_a_time();
reset();
set_preedit(PreeditEvent::from_winit("nihongo", Some((0, 7))));
assert!(composing());
@@ -362,6 +371,7 @@ mod tests {
#[test]
fn empty_preedit_clears_composing_and_suppresses_trailing_enter_once() {
let _turn = one_at_a_time();
reset();
set_preedit(PreeditEvent::from_winit("こんにちは", Some((0, 15))));
assert!(composing());
@@ -385,6 +395,7 @@ mod tests {
#[test]
fn mark_committed_suppresses_single_trailing_key() {
let _turn = one_at_a_time();
reset();
set_preedit(PreeditEvent::from_winit("漢字", Some((0, 6))));
mark_committed();
@@ -681,26 +681,36 @@ impl TextField {
}
/// `setValue`.
pub fn set_value(&mut self, m: &Measure, value: &str) {
self.value = value.chars().take(self.max_length).collect();
self.value = crate::ui::utf16_prefix(value, self.max_length);
self.move_cursor_to(m, chars(&self.value), false);
self.set_highlight(m, self.cursor);
}
/// `insertText`: replaces the selection within the maximum length. True
/// when the value changed (its responder runs).
/// when the value changed (its responder runs). The limit is in UTF-16
/// code units, as Java's `String.length()` counts them.
pub fn insert_text(&mut self, m: &Measure, input: &str) -> bool {
let (start, end) = (
self.cursor.min(self.highlight),
self.cursor.max(self.highlight),
);
let room = self.max_length as isize - chars(&self.value) as isize + (end - start) as isize;
if room <= 0 {
let selected_units: usize = self
.value
.chars()
.skip(start)
.take(end - start)
.map(char::len_utf16)
.sum();
let room = self
.max_length
.saturating_sub(crate::ui::utf16_len(&self.value) - selected_units);
if room == 0 {
return false;
}
let filtered: String = input
.chars()
.filter(|c| *c >= ' ' && *c != '\u{7f}' && *c != '§')
.collect();
let insert: String = filtered.chars().take(room as usize).collect();
let insert = crate::ui::utf16_prefix(&filtered, room);
let n = chars(&insert);
self.value = format!(
"{}{}{}",
@@ -912,7 +922,8 @@ impl TextField {
text_as_typed(out, t, draw_x, ty, color, self.text_shadow);
draw_x += w + 1;
}
let insert = self.cursor < len || len >= self.max_length;
// `value.length() >= maxLength` is Java's length: UTF-16 units.
let insert = self.cursor < len || crate::ui::utf16_len(&self.value) >= self.max_length;
let mut cursor_x = draw_x;
if !on_screen {
cursor_x = if rel_cursor > 0 { tx + self.width } else { tx };
@@ -1427,3 +1438,32 @@ mod scissor_tests {
);
}
}
#[cfg(test)]
mod max_length_tests {
use super::*;
fn atlas() -> HudAtlas {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
/// `EditBox.maxLength` counts Java `String.length()` (UTF-16 code units),
/// and the chat box is this field: ChatScreen's 256 takes 128 emoji, not
/// 256, and a half-fitted emoji is dropped rather than split.
#[test]
fn the_chat_box_maximum_counts_utf16_units() {
let atlas = atlas();
let m = Measure(&atlas.font);
let mut field = TextField::new(0, 0, 200, 20);
field.max_length = 3;
field.insert_text(&m, "ab😀");
assert_eq!(
field.value, "ab",
"three units: a, b and one of the emoji's"
);
field.set_value(&m, "");
field.max_length = 4;
field.insert_text(&m, "ab😀");
assert_eq!(field.value, "ab😀", "four units, both of the emoji's");
}
}
+36 -1
View File
@@ -232,6 +232,8 @@ impl Selector {
pub struct Tick {
/// A vibration was chosen: its travel time (the particle starts).
pub started: Option<(Info, i32)>,
/// A vibration was reloaded from save: particle resumes from interpolated pos.
pub resumed: Option<(Info, i32)>,
/// A vibration arrived.
pub received: Option<Info>,
/// `onDataChanged`.
@@ -261,6 +263,10 @@ impl Data {
self.selector.start_over();
}
if let Some(info) = self.current {
if self.reload_particle {
self.reload_particle = false;
out.resumed = Some((info, self.travel));
}
let mut changed = self.travel > 0;
self.travel = (self.travel - 1).max(0);
if self.travel <= 0 {
@@ -293,8 +299,11 @@ impl Data {
Tag::compound(entries)
}
pub fn from_nbt(tag: &Tag) -> Self {
let current = tag.get("event").and_then(info_from_nbt);
let reload_particle = current.is_some();
let mut data = Self {
current: tag.get("event").and_then(info_from_nbt),
current,
reload_particle,
..Self::default()
};
if let Some(Tag::Int(t)) = tag.get("event_delay") {
@@ -979,4 +988,30 @@ mod tests {
assert_eq!(back.spreader.cursors[0].charge, 1000);
assert_eq!(back.spreader.cursors[1].charge, 500);
}
#[test]
fn vibration_reloads_particle() {
let tag = Tag::compound([
(
"event",
Tag::compound([
("game_event", Tag::String("minecraft:step".into())),
("distance", Tag::Float(4.0f32.to_bits())),
(
"pos",
Tag::List(vec![
Tag::Double(1.0f64.to_bits()),
Tag::Double(0),
Tag::Double(0),
]),
),
]),
),
("event_delay", Tag::Int(3)),
]);
let mut d = Data::from_nbt(&tag);
assert!(d.reload_particle && d.current.is_some());
let tick = d.tick(10, true, true, |dist| dist as i32);
assert!(tick.resumed.is_some() && !d.reload_particle);
}
}
@@ -501,7 +501,12 @@ pub(crate) fn row(batch: &mut HudBatch, atlas: &HudAtlas, cols: &Columns, y: f32
let lit = [rect[0] + 2.0, y + 1.0, rect[2] - 4.0, style::ROW - 2.0];
style::fill(batch, atlas, lit, style::hover());
}
crate::widgets::widget_cursor(hover, live);
// AbstractSliderButton.handleCursor: a dragged slider resizes, buttons point.
if slider.is_some() {
crate::widgets::slider_cursor(hover, live, held);
} else {
crate::widgets::widget_cursor(hover, live);
}
// The control socket's widget tree, the narrator and a controller's focus.
let kind = match slider {
Some(value) => crate::widgets::Kind::Slider {
+10 -343
View File
@@ -12,6 +12,16 @@
//! or an empty answer keeps the cached lists, `Retry-After` sets the poll interval, and
//! `getFriendData` waits out a ten-second cooldown between reads. The presence statuses
//! are `PresenceHandler.getPresenceStatus`'s, supplied by the client each tick.
mod list_updates;
mod model;
use list_updates::{Handler, spawn_updater};
pub use list_updates::{State, set_foreground};
use model::presence_of;
pub use model::{
Friend, FriendData, Presence, PresenceStatus, ResultCode, parse_friends, parse_presence,
};
use crate::auth::{self, AuthSession};
use serde_json::{Value, json};
use std::{
@@ -23,99 +33,6 @@ use std::{
time::{Duration, Instant},
};
/// authlib's `FriendsService.ResultCode`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResultCode {
Success,
Error,
ServiceNotAvailable,
TooManyRequests,
Forbidden,
UpgradeNeeded,
ConnectionIssue,
TemporaryUnavailable,
UnknownProfile,
Unauthorized,
GenericError,
}
/// `FriendDto`: one friend or one pending request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Friend {
pub id: u128,
pub name: String,
}
/// authlib's `FriendData`: the three lists the service answers.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FriendData {
pub friends: Vec<Friend>,
pub incoming: Vec<Friend>,
pub outgoing: Vec<Friend>,
}
/// authlib's `PresenceStatus`, as `updatePresence` stores it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PresenceStatus {
Online,
PlayingOffline,
PlayingRealms,
PlayingServer,
PlayingHostedServer,
Offline,
}
impl PresenceStatus {
/// `PresenceStatus.name()`: the string `updatePresence` sends and
/// `PresenceStatusDto.status` carries.
fn wire(self) -> &'static str {
match self {
Self::Online => "ONLINE",
Self::PlayingOffline => "PLAYING_OFFLINE",
Self::PlayingRealms => "PLAYING_REALMS",
Self::PlayingServer => "PLAYING_SERVER",
Self::PlayingHostedServer => "PLAYING_HOSTED_SERVER",
Self::Offline => "OFFLINE",
}
}
}
/// `PresenceStatusDto`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Presence {
pub id: u128,
pub status: PresenceStatus,
}
/// `RemoteFriendListUpdateHandler.State`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
Loading,
UpgradeNeeded,
ConnectionIssue,
UserMayLackActiveProfile,
Unauthorized,
TemporaryUnavailable,
GenericError,
Success,
}
impl State {
/// `RemoteFriendListUpdateHandler.mapResultCodeToState`.
fn of(code: ResultCode) -> Self {
match code {
ResultCode::Success => Self::Success,
ResultCode::UpgradeNeeded => Self::UpgradeNeeded,
ResultCode::ConnectionIssue => Self::ConnectionIssue,
ResultCode::UnknownProfile => Self::UserMayLackActiveProfile,
ResultCode::Unauthorized => Self::Unauthorized,
ResultCode::TemporaryUnavailable
| ResultCode::Forbidden
| ResultCode::ServiceNotAvailable
| ResultCode::TooManyRequests => Self::TemporaryUnavailable,
ResultCode::Error | ResultCode::GenericError => Self::GenericError,
}
}
}
/// `Options.sharePresence` (`PresenceSharing`): how much of the player the service sees.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SharePresence {
@@ -159,45 +76,6 @@ impl Service {
}
}
/// `RemoteFriendListUpdateHandler`.
struct Handler {
enabled: bool,
state: State,
latest: FriendData,
/// `lastUpdateNanos`: a read at that moment is due; `None` reads at once.
last_update: Option<Instant>,
/// A forced read (`forceUpdate`) is due, whatever the interval.
forced: bool,
/// `getUpdateIntervalNanos`'s foreground: the friends overlay is open.
foreground: bool,
}
impl Default for Handler {
fn default() -> Self {
Self {
enabled: false,
state: State::Loading,
latest: FriendData::default(),
last_update: None,
forced: false,
foreground: false,
}
}
}
impl Handler {
/// `getUpdateIntervalNanos`: the service's interval (a minute when it named none),
/// five times as long in the background.
fn interval(&self, service: &Service) -> Duration {
let foreground = service.friends_poll.unwrap_or(Duration::from_secs(60));
if self.foreground {
foreground
} else {
foreground * 5
}
}
}
/// `PresenceHandler`.
struct PresenceHandler {
latest: Vec<Presence>,
@@ -326,11 +204,6 @@ pub fn latest_presence() -> Vec<Presence> {
lock().presence.latest.clone()
}
/// `RemoteFriendListUpdateHandler`'s foreground interval: the friends overlay is open.
pub fn set_foreground(open: bool) {
lock().handler.foreground = open;
}
/// `Options.sharePresence`: what presence the handler posts.
pub fn set_share_presence(share: SharePresence) {
lock().share = share;
@@ -480,100 +353,6 @@ fn friend_action(body: Value) -> ResultCode {
code
}
/// `RemoteFriendListUpdateHandler.start`'s worker: one read per interval while the list
/// is enabled, the first one as soon as it starts.
fn spawn_updater() {
static STARTED: AtomicBool = AtomicBool::new(false);
if STARTED.swap(true, Ordering::Relaxed) {
return;
}
let _ = thread::Builder::new()
.name("Friends List".into())
.spawn(|| {
loop {
thread::sleep(Duration::from_secs(1));
let due = {
let inner = lock();
if !inner.handler.enabled {
continue;
}
inner.handler.forced
|| inner
.handler
.last_update
.is_none_or(|at| at.elapsed() >= inner.handler.interval(&inner.service))
};
if due {
update_friend_data();
}
}
});
}
/// `RemoteFriendListUpdateHandler.runUpdateFriendDataInternal`.
fn update_friend_data() {
let etag = {
let mut inner = lock();
if inner.service.pending {
// Another read is in flight; its answer is the cache's.
return;
}
if !inner.service.can_make_request() {
inner.handler.forced = false;
inner.handler.state = State::Success;
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.last_update = Some(Instant::now());
return;
}
inner.service.pending = true;
inner.service.cooldown = Some(Instant::now() + Duration::from_secs(10));
inner.service.friends_etag.clone()
};
log::debug!("Performing Friends List update");
let result = match session() {
Some(session) => fetch_friends(&session, etag.as_deref()),
None => Err(Failure {
code: ResultCode::Unauthorized,
}),
};
let mut inner = lock();
inner.service.pending = false;
inner.handler.forced = false;
inner.handler.last_update = Some(Instant::now());
match result {
Ok(answer) => {
if let Some(retry) = answer.retry_after {
inner.service.friends_poll = Some(retry);
}
if let Some(etag) = answer.etag {
inner.service.friends_etag = Some(etag);
}
if answer.status != 304 && !answer.body.is_empty() {
match parse_friends(&answer.body) {
Some(data) => inner.service.friends_cache = data,
None => {
// authlib's parse failure is an ERROR result: the handler keeps
// the cached lists and shows the generic error.
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.state = State::GenericError;
return;
}
}
}
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.state = State::Success;
}
Err(failure) => {
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.state = State::of(failure.code);
log::warn!(
"Friends List update failed with result code: {:?}",
failure.code
);
}
}
}
/// `MinecraftServicesFriendsService.presence`: post one status, cache the answer.
/// `None` means the answer said nothing new (304, an empty body or a failure); the
/// handler keeps its last presence then.
@@ -726,122 +505,10 @@ fn http_error(error: ureq::Error) -> Failure {
Failure { code }
}
/// authlib's `FriendsListResponse` (`getFriends`/`updateFriends` body).
pub fn parse_friends(body: &str) -> Option<FriendData> {
let v: Value = serde_json::from_str(body).ok()?;
Some(FriendData {
friends: parse_friend_list(v.get("friends")),
incoming: parse_friend_list(v.get("incomingRequests")),
outgoing: parse_friend_list(v.get("outgoingRequests")),
})
}
fn parse_friend_list(value: Option<&Value>) -> Vec<Friend> {
value
.and_then(|v| v.as_array())
.into_iter()
.flatten()
.filter_map(|friend| {
Some(Friend {
id: auth::parse_uuid(friend.get("profileId")?.as_str()?)?,
name: friend.get("name")?.as_str()?.to_owned(),
})
})
.collect()
}
/// authlib's `PresenceResponse`.
pub fn parse_presence(body: &str) -> Option<Vec<Presence>> {
let v: Value = serde_json::from_str(body).ok()?;
Some(presence_of(&v))
}
/// `PresenceResponse.presence`: a missing list reads as empty, as Gson's null does.
fn presence_of(v: &Value) -> Vec<Presence> {
v.get("presence")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let status = entry.get("status")?.as_str()?;
let status = match status {
"ONLINE" => PresenceStatus::Online,
"PLAYING_OFFLINE" => PresenceStatus::PlayingOffline,
"PLAYING_REALMS" => PresenceStatus::PlayingRealms,
"PLAYING_SERVER" => PresenceStatus::PlayingServer,
"PLAYING_HOSTED_SERVER" => PresenceStatus::PlayingHostedServer,
_ => PresenceStatus::Offline,
};
Some(Presence {
id: auth::parse_uuid(entry.get("profileId")?.as_str()?)?,
status,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_friends_answer_reads_its_three_lists() {
let data = parse_friends(
r#"{"friends":[{"profileId":"0123456789abcdef0123456789abcdef","name":"Alex"}],
"incomingRequests":[],"outgoingRequests":[{"profileId":"fedcba9876543210fedcba9876543210","name":"Steve"}]}"#,
)
.unwrap();
assert_eq!(
data.friends,
vec![Friend {
id: 0x0123_4567_89ab_cdef_0123_4567_89ab_cdef,
name: "Alex".into()
}]
);
assert!(data.incoming.is_empty());
assert_eq!(data.outgoing[0].name, "Steve");
// The service's answer to an account with no friends, as the live check
// captured it: the three lists plus an `empty` flag the parser ignores.
let empty = parse_friends(
r#"{"empty":true,"friends":[],"incomingRequests":[],"outgoingRequests":[]}"#,
)
.unwrap();
assert_eq!(empty, FriendData::default());
}
#[test]
fn a_presence_answer_reads_each_status() {
let presence = parse_presence(
r#"{"presence":[
{"profileId":"0123456789abcdef0123456789abcdef","pmid":"00000000000000000000000000000000","status":"PLAYING_REALMS","lastUpdated":"2026-11-08T12:00:00Z"},
{"profileId":"fedcba9876543210fedcba9876543210","pmid":"00000000000000000000000000000000","status":"OFFLINE","lastUpdated":"2026-11-08T12:00:00Z"}]}"#,
)
.unwrap();
assert_eq!(presence[0].status, PresenceStatus::PlayingRealms);
assert_eq!(presence[1].status, PresenceStatus::Offline);
// `PresenceResponse` without its list is empty, not missing.
assert_eq!(parse_presence("{}"), Some(Vec::new()));
assert_eq!(parse_presence("not json"), None);
}
#[test]
fn result_codes_map_to_the_handlers_states() {
assert_eq!(State::of(ResultCode::Success), State::Success);
assert_eq!(
State::of(ResultCode::TooManyRequests),
State::TemporaryUnavailable
);
assert_eq!(
State::of(ResultCode::UnknownProfile),
State::UserMayLackActiveProfile
);
assert_eq!(State::of(ResultCode::UpgradeNeeded), State::UpgradeNeeded);
assert_eq!(
State::of(ResultCode::ConnectionIssue),
State::ConnectionIssue
);
}
#[test]
fn the_share_presence_option_maps_to_its_levels() {
assert_eq!(SharePresence::of(0), SharePresence::None);
@@ -0,0 +1,199 @@
use super::{
Failure, FriendData, ResultCode, Service, fetch_friends, lock, parse_friends, session,
};
use std::{
sync::atomic::{AtomicBool, Ordering},
thread,
time::{Duration, Instant},
};
/// `RemoteFriendListUpdateHandler.State`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
Loading,
UpgradeNeeded,
ConnectionIssue,
UserMayLackActiveProfile,
Unauthorized,
TemporaryUnavailable,
GenericError,
Success,
}
impl State {
/// `RemoteFriendListUpdateHandler.mapResultCodeToState`.
fn of(code: ResultCode) -> Self {
match code {
ResultCode::Success => Self::Success,
ResultCode::UpgradeNeeded => Self::UpgradeNeeded,
ResultCode::ConnectionIssue => Self::ConnectionIssue,
ResultCode::UnknownProfile => Self::UserMayLackActiveProfile,
ResultCode::Unauthorized => Self::Unauthorized,
ResultCode::TemporaryUnavailable
| ResultCode::Forbidden
| ResultCode::ServiceNotAvailable
| ResultCode::TooManyRequests => Self::TemporaryUnavailable,
ResultCode::Error | ResultCode::GenericError => Self::GenericError,
}
}
}
/// `RemoteFriendListUpdateHandler`.
pub(super) struct Handler {
pub(super) enabled: bool,
pub(super) state: State,
pub(super) latest: FriendData,
/// `lastUpdateNanos`: a read at that moment is due; `None` reads at once.
pub(super) last_update: Option<Instant>,
/// A forced read (`forceUpdate`) is due, whatever the interval.
pub(super) forced: bool,
/// `getUpdateIntervalNanos`'s foreground: the friends overlay is open.
foreground: bool,
}
impl Default for Handler {
fn default() -> Self {
Self {
enabled: false,
state: State::Loading,
latest: FriendData::default(),
last_update: None,
forced: false,
foreground: false,
}
}
}
impl Handler {
/// `getUpdateIntervalNanos`: the service's interval (a minute when it named none),
/// five times as long in the background.
fn interval(&self, service: &Service) -> Duration {
let foreground = service.friends_poll.unwrap_or(Duration::from_secs(60));
if self.foreground {
foreground
} else {
foreground * 5
}
}
}
/// `RemoteFriendListUpdateHandler`'s foreground interval: the friends overlay is open.
pub fn set_foreground(open: bool) {
lock().handler.foreground = open;
}
/// `RemoteFriendListUpdateHandler.start`'s worker: one read per interval while the list
/// is enabled, the first one as soon as it starts.
pub(super) fn spawn_updater() {
static STARTED: AtomicBool = AtomicBool::new(false);
if STARTED.swap(true, Ordering::Relaxed) {
return;
}
let _ = thread::Builder::new()
.name("Friends List".into())
.spawn(|| {
loop {
thread::sleep(Duration::from_secs(1));
let due = {
let inner = lock();
if !inner.handler.enabled {
continue;
}
inner.handler.forced
|| inner
.handler
.last_update
.is_none_or(|at| at.elapsed() >= inner.handler.interval(&inner.service))
};
if due {
update_friend_data();
}
}
});
}
/// `RemoteFriendListUpdateHandler.runUpdateFriendDataInternal`.
pub(super) fn update_friend_data() {
let etag = {
let mut inner = lock();
if inner.service.pending {
// Another read is in flight; its answer is the cache's.
return;
}
if !inner.service.can_make_request() {
inner.handler.forced = false;
inner.handler.state = State::Success;
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.last_update = Some(Instant::now());
return;
}
inner.service.pending = true;
inner.service.cooldown = Some(Instant::now() + Duration::from_secs(10));
inner.service.friends_etag.clone()
};
log::debug!("Performing Friends List update");
let result = match session() {
Some(session) => fetch_friends(&session, etag.as_deref()),
None => Err(Failure {
code: ResultCode::Unauthorized,
}),
};
let mut inner = lock();
inner.service.pending = false;
inner.handler.forced = false;
inner.handler.last_update = Some(Instant::now());
match result {
Ok(answer) => {
if let Some(retry) = answer.retry_after {
inner.service.friends_poll = Some(retry);
}
if let Some(etag) = answer.etag {
inner.service.friends_etag = Some(etag);
}
if answer.status != 304 && !answer.body.is_empty() {
match parse_friends(&answer.body) {
Some(data) => inner.service.friends_cache = data,
None => {
// authlib's parse failure is an ERROR result: the handler keeps
// the cached lists and shows the generic error.
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.state = State::GenericError;
return;
}
}
}
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.state = State::Success;
}
Err(failure) => {
inner.handler.latest = inner.service.friends_cache.clone();
inner.handler.state = State::of(failure.code);
log::warn!(
"Friends List update failed with result code: {:?}",
failure.code
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn result_codes_map_to_the_handlers_states() {
assert_eq!(State::of(ResultCode::Success), State::Success);
assert_eq!(
State::of(ResultCode::TooManyRequests),
State::TemporaryUnavailable
);
assert_eq!(
State::of(ResultCode::UnknownProfile),
State::UserMayLackActiveProfile
);
assert_eq!(State::of(ResultCode::UpgradeNeeded), State::UpgradeNeeded);
assert_eq!(
State::of(ResultCode::ConnectionIssue),
State::ConnectionIssue
);
}
}
@@ -0,0 +1,164 @@
use crate::auth;
use serde_json::Value;
/// authlib's `FriendsService.ResultCode`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResultCode {
Success,
Error,
ServiceNotAvailable,
TooManyRequests,
Forbidden,
UpgradeNeeded,
ConnectionIssue,
TemporaryUnavailable,
UnknownProfile,
Unauthorized,
GenericError,
}
/// `FriendDto`: one friend or one pending request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Friend {
pub id: u128,
pub name: String,
}
/// authlib's `FriendData`: the three lists the service answers.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FriendData {
pub friends: Vec<Friend>,
pub incoming: Vec<Friend>,
pub outgoing: Vec<Friend>,
}
/// authlib's `PresenceStatus`, as `updatePresence` stores it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PresenceStatus {
Online,
PlayingOffline,
PlayingRealms,
PlayingServer,
PlayingHostedServer,
Offline,
}
impl PresenceStatus {
/// `PresenceStatus.name()`: the string `updatePresence` sends and
/// `PresenceStatusDto.status` carries.
pub(super) fn wire(self) -> &'static str {
match self {
Self::Online => "ONLINE",
Self::PlayingOffline => "PLAYING_OFFLINE",
Self::PlayingRealms => "PLAYING_REALMS",
Self::PlayingServer => "PLAYING_SERVER",
Self::PlayingHostedServer => "PLAYING_HOSTED_SERVER",
Self::Offline => "OFFLINE",
}
}
}
/// `PresenceStatusDto`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Presence {
pub id: u128,
pub status: PresenceStatus,
}
/// authlib's `FriendsListResponse` (`getFriends`/`updateFriends` body).
pub fn parse_friends(body: &str) -> Option<FriendData> {
let v: Value = serde_json::from_str(body).ok()?;
Some(FriendData {
friends: parse_friend_list(v.get("friends")),
incoming: parse_friend_list(v.get("incomingRequests")),
outgoing: parse_friend_list(v.get("outgoingRequests")),
})
}
fn parse_friend_list(value: Option<&Value>) -> Vec<Friend> {
value
.and_then(|v| v.as_array())
.into_iter()
.flatten()
.filter_map(|friend| {
Some(Friend {
id: auth::parse_uuid(friend.get("profileId")?.as_str()?)?,
name: friend.get("name")?.as_str()?.to_owned(),
})
})
.collect()
}
/// authlib's `PresenceResponse`.
pub fn parse_presence(body: &str) -> Option<Vec<Presence>> {
let v: Value = serde_json::from_str(body).ok()?;
Some(presence_of(&v))
}
/// `PresenceResponse.presence`: a missing list reads as empty, as Gson's null does.
pub(super) fn presence_of(v: &Value) -> Vec<Presence> {
v.get("presence")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let status = entry.get("status")?.as_str()?;
let status = match status {
"ONLINE" => PresenceStatus::Online,
"PLAYING_OFFLINE" => PresenceStatus::PlayingOffline,
"PLAYING_REALMS" => PresenceStatus::PlayingRealms,
"PLAYING_SERVER" => PresenceStatus::PlayingServer,
"PLAYING_HOSTED_SERVER" => PresenceStatus::PlayingHostedServer,
_ => PresenceStatus::Offline,
};
Some(Presence {
id: auth::parse_uuid(entry.get("profileId")?.as_str()?)?,
status,
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_friends_answer_reads_its_three_lists() {
let data = parse_friends(
r#"{"friends":[{"profileId":"0123456789abcdef0123456789abcdef","name":"Alex"}],
"incomingRequests":[],"outgoingRequests":[{"profileId":"fedcba9876543210fedcba9876543210","name":"Steve"}]}"#,
)
.unwrap();
assert_eq!(
data.friends,
vec![Friend {
id: 0x0123_4567_89ab_cdef_0123_4567_89ab_cdef,
name: "Alex".into()
}]
);
assert!(data.incoming.is_empty());
assert_eq!(data.outgoing[0].name, "Steve");
// The service's answer to an account with no friends, as the live check
// captured it: the three lists plus an `empty` flag the parser ignores.
let empty = parse_friends(
r#"{"empty":true,"friends":[],"incomingRequests":[],"outgoingRequests":[]}"#,
)
.unwrap();
assert_eq!(empty, FriendData::default());
}
#[test]
fn a_presence_answer_reads_each_status() {
let presence = parse_presence(
r#"{"presence":[
{"profileId":"0123456789abcdef0123456789abcdef","pmid":"00000000000000000000000000000000","status":"PLAYING_REALMS","lastUpdated":"2026-11-08T12:00:00Z"},
{"profileId":"fedcba9876543210fedcba9876543210","pmid":"00000000000000000000000000000000","status":"OFFLINE","lastUpdated":"2026-11-08T12:00:00Z"}]}"#,
)
.unwrap();
assert_eq!(presence[0].status, PresenceStatus::PlayingRealms);
assert_eq!(presence[1].status, PresenceStatus::Offline);
// `PresenceResponse` without its list is empty, not missing.
assert_eq!(parse_presence("{}"), Some(Vec::new()));
assert_eq!(parse_presence("not json"), None);
}
}
+13 -9
View File
@@ -303,8 +303,12 @@ fn faded(code: u32, local: vec3<f32>, dx: vec3<f32>, dy: vec3<f32>) -> bool {
let pixel = max(length(dx), length(dy));
let unit = exp2(ceil(log2(max(pixel * 1.5, 1.0 / 16.0))));
let p = vec2<u32>(bitcast<vec2<u32>>(vec2<i32>(floor(plane / unit)))) & vec2(3u);
let bayer = array<u32, 16>(0u, 8u, 2u, 10u, 12u, 4u, 14u, 6u, 3u, 11u, 1u, 9u, 15u, 7u, 13u, 5u);
return (f32(bayer[p.y * 4u + p.x]) + 0.5) / 16.0 >= shown;
// The 4x4 Bayer matrix by rows, 0 8 2 10, 12 4 14 6, 3 11 1 9, 15 7 13 5: four bits each,
// two rows a word (a constant array indexed by the pixel would be a private array, which
// Adreno's Vulkan compiler, build 0676.41, fails to link).
let rows = select(0x6e4ca280u, 0x5d7f91b3u, p.y >= 2u);
let bayer = (rows >> (((p.y & 1u) * 4u + p.x) * 4u)) & 0xfu;
return (f32(bayer) + 0.5) / 16.0 >= shown;
}
// A fading tile or section is drawn a hair toward the camera (depth is
// reversed: nearer is larger), the newer the more, so it wins where it draws
@@ -965,13 +969,13 @@ const PI: f32 = 3.14159265;
fn disc_distance(d: vec3<f32>, y: f32) -> vec2<f32> {
if d.y * y <= 0.0 { return vec2(-1.0); }
let p = d * (y / d.y);
let h = length(p.xz);
let phi = atan2(p.z, p.x);
let sector = PI / 4.0;
let delta = phi - (floor(phi / sector) * sector + sector * 0.5);
let edge = 512.0 * cos(sector * 0.5) / cos(delta);
if h > edge { return vec2(-1.0); }
let s = h / edge;
// The regular octagon's edge parameter, directly from its half planes.
// max(|x| + tan(pi/8)*|z|, |z| + tan(pi/8)*|x|) / radius
// equals length(p.xz) / edge without atan2, floor or cos per pixel.
let a = abs(p.xz);
let diagonal = 0.41421356237309503;
let s = max(a.x + diagonal * a.y, a.y + diagonal * a.x) / 512.0;
if s > 1.0 { return vec2(-1.0); }
let ay = abs(y);
let rim = sqrt(512.0 * 512.0 + y * y);
return vec2(ay + s * (rim - ay), ay + s * (512.0 - ay));
+65 -6
View File
@@ -1421,7 +1421,7 @@ pub fn append_field(
batch.text(atlas, value, x, y, color, shadow);
cursor_x += HudBatch::text_width(atlas, value) + 1.0;
}
let insert = char_len(value) >= max_chars;
let insert = utf16_len(value) >= max_chars;
if insert {
cursor_x -= 1.0;
}
@@ -1444,6 +1444,29 @@ fn byte_index(s: &str, chars: usize) -> usize {
pub fn char_len(s: &str) -> usize {
s.chars().count()
}
/// Java's `String.length()`: UTF-16 code units, the unit `EditBox.maxLength`
/// counts. A character outside the BMP — an emoji, say — is two of them, so
/// a box with room for one more character takes an `a` and rejects a `😀`.
pub fn utf16_len(s: &str) -> usize {
s.encode_utf16().count()
}
/// The longest prefix of `s` that fits `max` UTF-16 code units without
/// splitting a character. `EditBox.insertText` drops the half surrogate it
/// would otherwise keep, so this is what vanilla inserts; Rust strings cannot
/// hold the lone surrogate that `setValue`'s unguarded `substring` may leave,
/// so a value too long by half a character keeps the whole characters before
/// the cut.
pub fn utf16_prefix(s: &str, max: usize) -> String {
let mut units = 0;
for (i, c) in s.char_indices() {
let n = c.len_utf16();
if units + n > max {
return s[..i].to_owned();
}
units += n;
}
s.to_owned()
}
/// `EditBox.getWordPosition(dir, from)`: the character index `dir` words away
/// from `from`. Forward, past the rest of the word and its spaces; backward,
/// over any spaces to the start of the word.
@@ -1585,7 +1608,7 @@ impl EditBox {
self.focused && (self.focused_at.elapsed().as_millis() / 300).is_multiple_of(2)
}
pub fn set_value(&mut self, value: &str) {
self.value = value.chars().take(self.max_length).collect();
self.value = utf16_prefix(value, self.max_length);
self.move_cursor_to_end(false);
}
fn selected(&self) -> (usize, usize) {
@@ -1598,7 +1621,9 @@ impl EditBox {
let (a, b) = self.selected();
self.value.chars().skip(a).take(b - a).collect()
}
/// EditBox.insertText: replace the selection, respecting the maximum length.
/// EditBox.insertText: replace the selection, respecting the maximum
/// length. The limit is in UTF-16 code units, as Java's `String.length()`
/// counts them.
pub fn insert_text(&mut self, text: &str) {
// `EditBox.charTyped` only inserts through `canConsumeInput`, which a
// read-only box fails; the screens here hand typed text to this method
@@ -1608,10 +1633,17 @@ impl EditBox {
}
let (a, b) = self.selected();
let filtered = crate::clipboard::filter_text(text, self.multiline);
let selected_units: usize = self
.value
.chars()
.skip(a)
.take(b - a)
.map(char::len_utf16)
.sum();
let room = self
.max_length
.saturating_sub(char_len(&self.value) - (b - a));
let insert: String = filtered.chars().take(room).collect();
.saturating_sub(utf16_len(&self.value) - selected_units);
let insert = utf16_prefix(&filtered, room);
let (ba, bb) = (byte_index(&self.value, a), byte_index(&self.value, b));
self.value.replace_range(ba..bb, &insert);
let pos = a + char_len(&insert);
@@ -1889,8 +1921,10 @@ impl EditBox {
batch.text_styled(atlas, &t, draw_x, ty, color, true);
draw_x += atlas.font.width_text(&t) + 1.0;
}
// EditBox.extractWidgetRenderState: `value.length() >= maxLength`
// is Java's length, so the caret turns into a bar at the unit count.
let insert =
self.cursor < char_len(&self.value) || char_len(&self.value) >= self.max_length;
self.cursor < char_len(&self.value) || utf16_len(&self.value) >= self.max_length;
let mut cursor_x = draw_x;
if !on_screen {
cursor_x = if rel_cursor > 0 { tx + self.width } else { tx };
@@ -2636,6 +2670,31 @@ mod tests {
);
}
/// `EditBox.maxLength` counts Java `String.length()`: UTF-16 code units.
/// A pasted emoji takes two of them and is never split (vanilla's
/// `Character.isHighSurrogate` guard drops the half it would keep).
#[test]
fn an_edit_box_maximum_counts_utf16_units() {
assert_eq!(utf16_len("ab😀"), 4);
assert_eq!(utf16_prefix("ab😀", 3), "ab");
assert_eq!(utf16_prefix("ab😀", 4), "ab😀");
let mut edit = EditBox::new(0.0, 0.0, 200.0, 20.0);
edit.max_length = 3;
edit.insert_text("ab😀");
assert_eq!(edit.value, "ab", "three units: a, b and one of the emoji's");
edit.set_value("");
edit.max_length = 4;
edit.insert_text("ab😀");
assert_eq!(edit.value, "ab😀", "four units, both of the emoji's");
// The selection's own units give their room back: with "ab"
// selected there are two units left, enough for the emoji, not
// for the emoji and the x.
edit.set_cursor(0, false);
edit.set_cursor(2, true);
edit.insert_text("😀x");
assert_eq!(edit.value, "😀😀");
}
/// `EditBox.setInvertHighlightedTextColor`: a selection inverts its text
/// unless the box asks it not to (the anvil's rename box).
#[test]
@@ -14,6 +14,10 @@ pub enum Cursor {
Arrow,
PointingHand,
NotAllowed,
/// `CursorTypes.RESIZE_NS`: a scroller held vertically (`MerchantScreen`).
ResizeNs,
/// `CursorTypes.RESIZE_EW`: a slider held horizontally.
ResizeEw,
}
thread_local! {
@@ -37,6 +41,19 @@ pub fn widget_cursor(hovered: bool, active: bool) {
});
}
}
/// `AbstractSliderButton.handleCursor`: a dragged slider resizes, a hovered
/// one points, and an inactive one is not allowed.
pub fn slider_cursor(hovered: bool, active: bool, dragging: bool) {
if hovered {
request_cursor(if !active {
Cursor::NotAllowed
} else if dragging {
Cursor::ResizeEw
} else {
Cursor::PointingHand
});
}
}
/// The cursor the frame asked for, and back to the arrow for the next one
/// (the window shows the arrow unless a widget asks).
@@ -412,6 +429,18 @@ pub fn record_as(label: &str, [x, y, w, h]: [f32; 4], enabled: bool, kind: Kind)
mod cursor_tests {
use super::*;
#[test]
fn a_dragged_slider_asks_for_the_horizontal_resize_cursor() {
let _ = take_cursor();
slider_cursor(false, true, true);
assert_eq!(take_cursor(), Cursor::Arrow);
slider_cursor(true, true, true);
assert_eq!(take_cursor(), Cursor::ResizeEw);
slider_cursor(true, true, false);
assert_eq!(take_cursor(), Cursor::PointingHand);
slider_cursor(true, false, true);
assert_eq!(take_cursor(), Cursor::NotAllowed);
}
#[test]
fn hovered_widgets_ask_for_the_hand_or_not_allowed() {
let _ = take_cursor();
@@ -1,4 +1,13 @@
{
"horizon.no_resources.title": "No prepared game files",
"horizon.no_resources.prepare": "Prepare them with horizon-prepare --prepare, or pass --resources <folder>.",
"horizon.no_resources.looked_in": "No prepared game files in %s",
"horizon.no_resources.quit": "Quit",
"horizon.get_the_game.title": "Start Horizon from the launcher",
"horizon.get_the_game.about": "This is the game the Horizon launcher installs and starts. On its own it has none of Minecraft's files, so it can't start.",
"horizon.get_the_game.minecraft": "Horizon needs your own copy of Minecraft: Java Edition. The launcher signs you in and prepares the game files from it.",
"horizon.get_the_game.download": "Download the launcher at %s, then press Play there.",
"horizon.get_the_game.button": "Download the launcher",
"horizon.extras.header.world": "World",
"horizon.extras.pregen": "Chunk pregeneration",
"horizon.extras.pregen.tooltip": "Enables /pregen in your single-player and LAN worlds. With cheats enabled, use /pregen start to generate an area before exploring it. Does not enable the command on servers you join.",
@@ -1053,5 +1053,100 @@
"horizon.studio.topbar.add_marker": "Додати маркер",
"horizon.studio.topbar.clear_keyframes": "🗑 Очистити ключові кадри",
"horizon.studio.topbar.timeline_hud": "⏱ Шкала часу",
"horizon.studio.topbar.split_scene": "Розділити сцену"
"horizon.studio.topbar.split_scene": "Розділити сцену",
"horizon.options.radial_mode": "Радіальне меню",
"horizon.options.radial_mode.about": "Утримуйте кнопку відкриття радіального меню або натисніть її раз, щоб відкрити, і ще раз, щоб закрити.",
"horizon.options.radial_mode.hold.about": "Утримуйте кнопку відкриття й відпустіть, щоб виконати те, на що вказує стік.",
"horizon.options.radial_mode.toggle.about": "Натисніть кнопку відкриття, щоб відкрити меню; A або повторне натискання кнопки відкриття виконує те, на що вказує стік, B закриває.",
"horizon.options.radial_stick": "Вибір у радіальному меню",
"horizon.options.radial_stick.about": "Стік, яким ви вказуєте на комірки радіального меню.",
"horizon.options.radial_stick.right": "Правий стік",
"horizon.options.radial_stick.left": "Лівий стік",
"horizon.options.radial_stick.either": "Будь-який",
"horizon.options.radial_stick.right.about": "Правий стік вказує на комірки; лівим ви й далі ходите.",
"horizon.options.radial_stick.left.about": "Лівий стік вказує, а ви стоїте на місці. Під тим самим пальцем — хрестовина праворуч, тож оберіть кнопку відкриття на сторінці «Радіальне меню».",
"horizon.options.radial_stick.either.about": "Вказує стік, яким рухали останнім; жоден не рухає вас і не повертає огляд. Відкрити меню можна лише бампером, тригером або кнопкою View.",
"horizon.pages.controller_radial": "Радіальне меню",
"horizon.radial.page.general": "Загальне",
"horizon.radial.page.camera": "Камера",
"horizon.radial.release_stick": "Відпустіть стік",
"horizon.radial.action.key_inventory": "Інвентар",
"horizon.radial.action.key_chat": "Чат",
"horizon.radial.action.key_command": "Команди",
"horizon.radial.action.key_advancements": "Досягнення",
"horizon.radial.action.key_togglePerspective": "Перспектива",
"horizon.radial.action.key_swapOffhand": "Поміняти руки",
"horizon.radial.action.key_drop": "Викинути",
"horizon.radial.action.key_pickItem": "Вибрати блок",
"horizon.radial.action.key_screenshot": "Знімок екрана",
"horizon.radial.action.key_toggleGui": "Сховати HUD",
"horizon.radial.action.key_smoothCamera": "Кінематографічна камера",
"horizon.radial.action.key_socialInteractions": "Соціальне",
"horizon.radial.action.key_emote": "Емоція",
"horizon.radial.action.pad_hotbarPrevious": "Попередня комірка",
"horizon.radial.action.pad_hotbarNext": "Наступна комірка",
"horizon.radial.action.key_fullscreen": "Повний екран",
"horizon.radial.action.key_quickActions": "Швидкі дії",
"horizon.radial.action.key_debug_overlay": "Екран налагодження",
"horizon.radial.missing": "Відсутня",
"horizon.radial.why.missing": "Невідома дія",
"horizon.radial.why.cosmetics": "Потрібна увімкнена косметика",
"horizon.radial.why.quick_actions": "На цьому сервері немає швидких дій",
"horizon.radial.why.social": "Лише на сервері",
"horizon.radial.next": "→ %s",
"horizon.radial.state.first_person": "Від першої особи",
"horizon.radial.state.third_person_back": "Від третьої особи",
"horizon.radial.state.third_person_front": "Вигляд спереду",
"horizon.radial.state.shown": "Показано",
"horizon.radial.state.hidden": "Приховано",
"horizon.radial.state.on": "Увімк.",
"horizon.radial.state.off": "Вимк.",
"horizon.radial.pick_title": "Оберіть дію",
"horizon.radial.group.actions": "Дії",
"horizon.radial.pick.slot": "Комірка «%s» сторінки «%s»",
"horizon.radial.pick.about": "Ставить цю дію в комірку й повертається назад. Поточну дію комірки позначено.",
"horizon.radial.pick.current": "Поточна",
"horizon.radial.missing.about": "Ця гра не знає дії %s: комірка зберігає її, але нічого не виконує. Натисніть або «праворуч», щоб поставити сюди іншу.",
"horizon.radial.page.new": "Нова сторінка",
"horizon.pages.open.controller_radial": "Радіальне меню...",
"horizon.radial.group.slots": "Комірки",
"horizon.radial.group.page": "Сторінка",
"horizon.radial.group.all": "Усі сторінки",
"horizon.radial.empty": "Порожньо",
"horizon.radial.page_of": "Сторінка %s з %s. Кожна комірка — це напрямок стіка вибору, поки кнопку відкриття утримано.",
"horizon.radial.slot.0": "Угору",
"horizon.radial.slot.1": "Угору праворуч",
"horizon.radial.slot.2": "Праворуч",
"horizon.radial.slot.3": "Униз праворуч",
"horizon.radial.slot.4": "Униз",
"horizon.radial.slot.5": "Униз ліворуч",
"horizon.radial.slot.6": "Ліворуч",
"horizon.radial.slot.7": "Угору ліворуч",
"horizon.radial.slot.about": "Дія, яку виконує цей напрямок. Натисніть, щоб побачити список дій; «праворуч» — наступна, «ліворуч» або Shift+клік — попередня.",
"horizon.radial.rename": "Перейменувати сторінку",
"horizon.radial.rename.about": "Дайте цій сторінці власну назву.",
"horizon.radial.name_title": "Назва сторінки",
"horizon.radial.new_page.about": "Додає порожню сторінку після останньої й показує її.",
"horizon.radial.new_page.full": "Меню вміщує щонайбільше %s сторінок.",
"horizon.radial.delete_page": "Видалити сторінку",
"horizon.radial.delete_page.about": "Одразу видаляє цю сторінку та її комірки. «Скасувати» повертає її.",
"horizon.radial.delete_page.last": "У меню лишається щонайменше одна сторінка.",
"horizon.radial.reset": "Скинути всі сторінки",
"horizon.radial.reset.about": "Одразу повертає сторінки «Загальне» й «Камера» та видаляє решту. «Скасувати» повертає їх.",
"horizon.radial.reset.default": "Сторінки вже типові.",
"horizon.radial.opener": "Кнопка відкриття",
"horizon.radial.opener.about": "Кнопка, яку утримують, щоб відкрити меню. Натисніть, потім натисніть кнопку геймпада: бампер або хрестовину, але не A, B, X, Y чи правий стік, якими керують і скасовують.",
"horizon.radial.opener.about.left": "Кнопка, яку утримують, щоб відкрити меню. Натисніть, потім натисніть кнопку геймпада: бампер, A, X або Y, але не хрестовину чи лівий стік, якими керують, і не B, яка скасовує.",
"horizon.radial.opener.about.either": "Кнопка, яку утримують, щоб відкрити меню. Натисніть, потім натисніть кнопку геймпада: бампер, тригер або View; обидва великі пальці керують, а B скасовує.",
"horizon.radial.unbound": "Жодна кнопка не відкриває меню (кнопку під пальцем, яким обирають, звільнено): натисніть, потім натисніть кнопку геймпада.",
"horizon.radial.conflict": "Спільна з іншою дією: у грі цю кнопку забирає меню. Натисніть, щоб обрати іншу.",
"Radial Menu": "Радіальне меню",
"Named pages of eight actions, held open with a button.": "Іменовані сторінки по вісім дій, відкриті, поки утримуєте кнопку.",
"The shader pack lights the world itself.": "Пакет шейдерів сам освітлює світ.",
"How bright the HUD and menus are. Auto: at paper white.": "Яскравість HUD і меню. «Авто»: на рівні білої точки.",
"HDR output stopped the game the last time it started with this graphics driver. Choose a mode to try again.": "Минулого разу з цим графічним драйвером HDR-вивід зупинив гру. Оберіть режим, щоб спробувати знову.",
"horizon.pad.action.radial": "Радіальне меню",
"horizon.recipes.fuel.options": "Утримуйте SHIFT, щоб закріпити цю підказку, потім клацніть інгредієнт, щоб переглянути рецепти.",
"horizon.recipes.fuel.any": "Будь-яке паливо",
"horizon.recipes.fuel.minecraft": "Minecraft"
}
+2 -2
View File
@@ -274,8 +274,8 @@ impl ArrowState {
/// `Arrow.getColor` of the server's own arrow: the colour of the potion on
/// its pickup item, None for a plain arrow (`PotionContents.EMPTY`).
pub fn potion_color(&self) -> Option<u32> {
let potion = self.pickup_item.potion()?;
Some(crate::brewing::potion_color(Some(potion)))
(!crate::brewing::contents_empty(&self.pickup_item))
.then(|| crate::brewing::contents_color(&self.pickup_item))
}
/// The `AbstractArrow` constructor's `pickupItemStack`: the drawn ammo
/// (one item). Ammo drawn without being used up (`INTANGIBLE_PROJECTILE`)
+1
View File
@@ -85,6 +85,7 @@ pub mod join_seq;
pub mod lan;
pub mod landing;
pub mod legacy_combat;
pub mod living_death;
pub mod locator_bar;
pub mod lod_net;
pub mod menu;
+23
View File
@@ -137,6 +137,15 @@ pub struct DebugKeys {
}
impl DebugKeys {
/// Window focus lost, or input reset: clear held modifier state.
pub fn reset(&mut self) {
self.modifier_down = false;
self.used_debug_key_as_modifier = false;
if self.crash_key_time > 0 {
self.crash_key_time = -1;
}
}
/// `keyPress` once the open screen (if any) did not take the key. `key`
/// is the physical key's name (`key.keyboard.f3`); `crash_key_down`
/// whether the crash mapping's key is held (`InputConstants.isKeyDown`).
@@ -487,4 +496,18 @@ mod tests {
press(&mut k, &mut h, &b, "key.keyboard.k", 2);
assert_eq!(h.actions, [(DebugAction::ShowChunkBorders, false)]);
}
#[test]
fn reset_on_focus_loss_clears_held_modifier_and_avoids_spurious_shortcuts() {
let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default());
press(&mut k, &mut h, &b, F3, 0);
assert!(k.modifier_down);
// Window loses focus while F3 was down (e.g. desktop shortcut Ctrl+F3)
k.reset();
assert!(!k.modifier_down);
assert!(!k.used_debug_key_as_modifier);
// User refocuses and presses 'b': it should NOT trigger ShowHitboxes
assert!(press(&mut k, &mut h, &b, "key.keyboard.b", 1));
assert!(h.actions.is_empty());
}
}
+123 -107
View File
@@ -39,6 +39,8 @@ pub fn conversion_tags(raw: Option<&Tag>) -> Option<Tag> {
fn string(s: &str) -> Tag {
Tag::String(s.into())
}
mod refs;
pub use refs::who_by_uuid;
/// Entity type ID (`id`).
pub fn kind(tag: &Tag) -> Option<String> {
horizon_client_core::identifier::normalize_id(&text(tag.get("id"))?)
@@ -284,28 +286,6 @@ pub fn migrate_player_uuid(tag: &mut Tag, old: [i32; 4], new: [i32; 4]) {
_ => {}
}
}
/// The entity a stored UUID names, while it is in the level: `player` (the
/// player's own UUID, when one is in the level), or the mob `uuids` gives that
/// UUID to. `uuids` is the game layer's id -> UUID map, so this is the read half
/// of the pair [`who_uuid`] and `mob_to_nbt`'s `uuid_of` form. A UUID nothing
/// loaded has, or one naming a kind `Who` cannot carry (an item, a projectile, a
/// guest), is `None` - never some other entity as a stand-in.
pub fn who_by_uuid(
uuids: &HashMap<u32, [i32; 4]>,
mobs: &[Mob],
player: Option<[i32; 4]>,
uuid: [i32; 4],
) -> Option<Who> {
if player == Some(uuid) {
return Some(Who::Player);
}
// Only a loaded mob: the map also holds projectiles, vehicles and items,
// whose ids mean nothing to `Who`.
uuids
.iter()
.find(|(id, u)| **u == uuid && mobs.iter().any(|m| m.id == **id))
.map(|(id, _)| Who::Mob(*id))
}
/// `AngerManagement.SUSPECT_ANGER_PAIR`: one suspect's UUID and how angry the
/// warden is at it.
fn suspect_anger(uuid: [i32; 4], anger: i32) -> Tag {
@@ -1257,11 +1237,11 @@ pub fn mob_to_nbt(
));
}
// ITEM_PICKUP_COOLDOWN_TICKS (`Codec.INT`), which a throw sets to 60,
// while it runs.
if m.extra.ints[3] > 0 {
// while the memory is there (its value 0 included).
if let Some(ticks) = crate::mobs::allay::pickup_cooldown(m) {
memories.push((
"minecraft:item_pickup_cooldown_ticks",
Tag::compound([("value", Tag::Int(m.extra.ints[3]))]),
Tag::compound([("value", Tag::Int(ticks))]),
));
}
// Always written, so a forgotten note block does not come back
@@ -2016,7 +1996,7 @@ pub fn mob_from_nbt_with_random(
if crate::mobs::equine::is_equine(m.species()) {
m.health = m.health.min(m.attrs.max_health);
}
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
m.hurt_time = i32::from(number(tag.get("HurtTime")).unwrap_or(0) as i16);
// What it holds (equipment.mainhand / offhand), when saved.
if let Some(eq) = tag.get("equipment") {
m.extra
@@ -2054,7 +2034,7 @@ pub fn mob_from_nbt_with_random(
// vanilla); a loaded mob holds only what its file lists.
m.extra.set_main_hand(None);
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.death_time = i32::from(number(tag.get("DeathTime")).unwrap_or(0) as i16);
m.impulse_grace_time =
number(tag.get("current_impulse_context_reset_grace_time")).unwrap_or(0) as i32;
// Mob.readAdditionalSaveData overrides what the constructor set (copper
@@ -2063,6 +2043,7 @@ pub fn mob_from_nbt_with_random(
m.extra.death_loot_table = text(tag.get("DeathLootTable"))
.and_then(|t| horizon_client_core::identifier::normalize_id(&t));
m.extra.death_loot_seed = number(tag.get("DeathLootTableSeed")).unwrap_or(0);
refs::read_last_hurt_by(&mut m, tag);
// `NeutralMob.readPersistentAngerSaveData`: the anger end time and the
// target come back with the mob.
if persistent_anger(m.species()) {
@@ -2442,7 +2423,7 @@ pub fn mob_from_nbt_with_random(
restore_axolotl_memories(&mut m, tag);
}
read_variant(&mut m, tag);
m.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32;
m.fire_ticks = i32::from(number(tag.get("Fire")).unwrap_or(0) as i16);
// Entity.load: `input.getIntOr("Air", getMaxAirSupply())`, 4800 for a dolphin.
m.air = number(tag.get("Air")).map_or(m.max_air_supply(), |air| air as i32);
if m.species() == crate::mobs::Species::Allay {
@@ -2488,8 +2469,8 @@ pub fn mob_from_nbt_with_random(
};
m.extra.ints[2] =
number(memory("minecraft:liked_noteblock_cooldown_ticks")).unwrap_or(0) as i32;
m.extra.ints[3] =
number(memory("minecraft:item_pickup_cooldown_ticks")).unwrap_or(0) as i32;
let pickup = number(memory("minecraft:item_pickup_cooldown_ticks")).map(|t| t as i32);
crate::mobs::allay::set_pickup_cooldown(&mut m, pickup);
if let Some(st) = m.extra.allay.as_mut()
&& let Some(noteblock) = memory("minecraft:liked_noteblock")
&& let Some(Tag::IntArray(p)) = noteblock.get("pos")
@@ -2628,7 +2609,7 @@ pub fn mob_from_nbt_with_random(
}
// Sheep.readAdditionalSaveData: white and unsheared when absent.
if m.species() == crate::mobs::Species::Sheep {
m.extra.color = number(tag.get("Color")).map_or(0, |c| (c as u8) & 15);
m.extra.color = crate::mobs::farm::saved_color(tag.get("Color"));
m.extra.sheared = flag(tag, "Sheared");
}
// GlowSquid.readAdditionalSaveData: not dimmed when absent.
@@ -2978,7 +2959,8 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option<ItemE
/// `OminousItemSpawner.addAdditionalSaveData`: its item (left out when
/// empty) and `spawn_item_after_ticks`. Its tick count is the entity's
/// `tickCount`, which isn't saved: a reloaded spawner counts from 0 again.
/// It never moves, so the `Motion` it was loaded with is what it saves.
/// It never moves or turns: it saves the Motion, Rotation, OnGround and
/// fall_distance it was loaded with (`Entity.load`).
pub fn ominous_item_spawner_to_nbt(
item: &crate::items::ItemStack,
position: Vec3,
@@ -2991,13 +2973,12 @@ pub fn ominous_item_spawner_to_nbt(
uuid,
position,
motion: raw.map_or(Vec3::ZERO, loaded_motion),
rotation: [0.0, 0.0],
on_ground: false,
fall_distance: 0.0,
rotation: raw.map_or([0.0, 0.0], rotation),
on_ground: raw.is_some_and(|t| flag(t, "OnGround")),
fall_distance: float(raw.and_then(|t| t.get("fall_distance"))).unwrap_or(0.0),
};
let mut tag = base.tag(raw);
// `ItemStack.CODEC` can't encode `ItemStack.EMPTY`, so an empty item
// writes no key.
// `ItemStack.CODEC` can't encode `ItemStack.EMPTY`: an empty item writes no key.
if let Tag::Compound(map) = &mut tag {
map.remove(&"item".into());
}
@@ -3024,59 +3005,8 @@ pub fn ominous_item_spawner_from_nbt(tag: &Tag) -> Option<(crate::items::ItemSta
Some((item, position(tag)?, after))
}
/// `ExperienceOrb`: Health, Age, Value, Count.
pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
let base = Base {
id: "minecraft:experience_orb",
uuid,
position: o.position,
motion: o.velocity,
rotation: o.rotation,
on_ground: o.on_ground,
fall_distance: 0.0,
};
let mut tag = base.tag(None);
for (key, value) in [
("Health", Tag::Short(o.health as i16)),
("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)),
("Value", Tag::Short(o.value as i16)),
("Count", Tag::Int(o.count.min(i32::MAX as u32) as i32)),
] {
put(&mut tag, key, value);
}
// Entity.saveWithoutId writes NoGravity only when set.
if o.no_gravity {
put(&mut tag, "NoGravity", Tag::Byte(1));
}
tag
}
/// One orb with its merged `Count`.
pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
let Some(position) = position(tag) else {
return Vec::new();
};
let count = number(tag.get("Count")).unwrap_or(1).max(1) as u32;
let orb = ExperienceOrb {
rotation: rotation(tag),
join: Default::default(),
no_gravity: flag(tag, "NoGravity"),
id: 0,
position,
previous: position,
velocity: motion(tag),
// `getShortOr("Value", 0)`, unclamped.
value: tag.get("Value").and_then(int_value).unwrap_or(0) as i16 as i32,
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
on_ground: flag(tag, "OnGround"),
count,
ticks: 0,
health: number(tag.get("Health")).unwrap_or(5) as i32,
// ExperienceOrb's followingPlayer is transient: never saved, so a
// loaded orb starts without one.
following: None,
};
vec![orb]
}
mod orb;
pub use orb::{orb_to_nbt, orbs_from_nbt};
/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow;
/// `in_block` is its `inBlockState`, `raw` the compound it was loaded with.
@@ -3868,19 +3798,7 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("current_impulse_context_reset_grace_time", Tag::Int(0)),
// AttributeMap.pack: the movement_speed instance the stand's first
// tick makes (removeFrost), at the registry default.
(
"attributes",
Tag::List(if a.speed_instance {
vec![Tag::compound([
("id", string(SPEED_ATTRIBUTE)),
("base", Tag::Double(0.7f64.to_bits())),
])]
} else {
Vec::new()
}),
),
("attributes", Tag::List(Vec::new())),
(
"Brain",
Tag::compound([("memories", Tag::Compound(Compound::new()))]),
@@ -3890,6 +3808,18 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
] {
map.entry(key.into()).or_insert(value);
}
// `removeFrost`'s first-tick movement_speed, over a saved list without it.
if a.speed_instance
&& let Some(Tag::List(list)) = map.get_mut(&"attributes".into())
&& !list
.iter()
.any(|t| text(t.get("id")).as_deref() == Some(SPEED_ATTRIBUTE))
{
list.push(Tag::compound([
("id", string(SPEED_ATTRIBUTE)),
("base", Tag::Double(0.7f64.to_bits())),
]));
}
}
tag
}
@@ -3903,7 +3833,7 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option<ArmorStand> {
if list.iter().any(|attr| text(attr.get("id")).as_deref() == Some(SPEED_ATTRIBUTE)));
a.velocity = loaded_motion(tag);
a.health = float(tag.get("Health")).unwrap_or(20.0) as f32;
a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32;
a.fire_ticks = i32::from(number(tag.get("Fire")).unwrap_or(0) as i16);
a.custom_name = tag.get("CustomName").map(name_text);
a.name_visible = flag(tag, "CustomNameVisible");
if let Some(eq) = tag.get("equipment") {
@@ -4620,6 +4550,27 @@ mod tests {
}
}
/// `LivingEntity.readAdditionalSaveData` reads `HurtTime` and `DeathTime`
/// with `getShortOr`: an int tag is narrowed (`(short)(value & 65535)`),
/// so 40000 is -25536 and never counts down.
#[test]
fn a_mob_narrows_its_hurt_and_death_time_to_a_short() {
let kind = crate::mobs::sensor_scan_tests::kind();
let types = [(kind.id.to_string(), kind.clone())].into();
let load = |hurt: Tag, death: Tag| {
let raw = Tag::compound([
("id", string(&kind.id)),
("Pos", doubles(&[4.5, 220.0, 4.5])),
("HurtTime", hurt),
("DeathTime", death),
]);
let m = mob_from_nbt(&raw, &types, 1, None).unwrap();
(m.hurt_time, m.death_time)
};
assert_eq!(load(Tag::Int(40000), Tag::Int(65546)), (-25536, 10));
assert_eq!(load(Tag::Short(7), Tag::Short(19)), (7, 19));
}
/// A mount keeps its body armour and a helmet (say
/// `/item replace entity <horse> armor.head with minecraft:iron_helmet`)
/// in their own slots through a save: vanilla holds both (`equipment.body`
@@ -5910,6 +5861,43 @@ mod tests {
assert_eq!(attributes(&armor_stand_from_nbt(&saved, 1).unwrap()), speed);
}
#[test]
fn a_loaded_stand_gains_the_speed_instance_its_first_tick_makes() {
// Vanilla 26.3: `/summon armor_stand ~ ~ ~ {attributes:[]}` saves `[]` until the
// first tick, whose removeFrost makes movement_speed (base 0.7d); a saved
// instance of another attribute stays in front of it.
let ids = |stand: &ArmorStand, raw: &Tag| match armor_stand_to_nbt(stand, [0; 4], Some(raw))
.get("attributes")
{
Some(Tag::List(attrs)) => attrs
.iter()
.map(|a| (text(a.get("id")).unwrap(), a.get("base").cloned()))
.collect::<Vec<_>>(),
other => panic!("attributes: {other:?}"),
};
let health = (
"minecraft:max_health".to_owned(),
Some(Tag::Double(20f64.to_bits())),
);
let speed = (
"minecraft:movement_speed".to_owned(),
Some(Tag::Double(0.7f64.to_bits())),
);
let empty = Tag::compound([("attributes", Tag::List(Vec::new()))]);
let saved = Tag::compound([(
"attributes",
Tag::List(vec![Tag::compound([
("id", string("minecraft:max_health")),
("base", Tag::Double(20f64.to_bits())),
])]),
)]);
let mut stand = ArmorStand::new(1, Vec3::ZERO, 0.0);
assert_eq!(ids(&stand, &empty), []);
assert_eq!(ids(&stand, &saved), std::slice::from_ref(&health));
stand.speed_instance = true;
assert_eq!(ids(&stand, &empty), std::slice::from_ref(&speed));
assert_eq!(ids(&stand, &saved), [health, speed]);
}
#[test]
fn summoned_trident_defaults_are_not_pickable_or_already_shot() {
let raw = Tag::compound([
("Pos", doubles(&[0.0, 0.0, 0.0])),
@@ -7430,11 +7418,11 @@ mod sheep_nbt_tests {
assert_eq!(number(tag.get("InWaterTime")), Some(300));
assert_eq!(number(tag.get("DrownedConversionTime")), Some(-1));
assert_eq!((back.extra.counter, back.extra.counter2), (300, 0));
(zombie.extra.counter, zombie.extra.counter2) = (600, 300);
(zombie.extra.counter, zombie.extra.counter2) = (600, 301);
let (back, tag) = round_trip(&zombie);
assert_eq!(number(tag.get("InWaterTime")), Some(600));
assert_eq!(number(tag.get("DrownedConversionTime")), Some(299));
assert_eq!((back.extra.counter, back.extra.counter2), (600, 300));
assert_eq!(number(tag.get("DrownedConversionTime")), Some(300));
assert_eq!((back.extra.counter, back.extra.counter2), (600, 301));
// A skeleton outside powder snow is not afflicted: -1 whatever the
// counter holds, as with a fresh or NoAI one.
let (_, tag) = round_trip(&new("minecraft:skeleton"));
@@ -9481,6 +9469,34 @@ mod pickup_loot_save_tests {
mod stand_fall_save_tests {
use super::*;
/// `Entity.load` reads `Fire` with `getShortOr`: an int tag is narrowed
/// (`(short)(value & 65535)`), so 40000 is -25536 and the stand or mob
/// does not burn.
#[test]
fn a_stand_and_a_mob_narrow_a_loaded_fire_to_a_short() {
let kind = crate::mobs::sensor_scan_tests::kind();
let types = [(kind.id.to_string(), kind.clone())].into();
for (fire, expected) in [
(Tag::Int(40000), -25536),
(Tag::Int(65546), 10),
(Tag::Short(60), 60),
] {
let input = Tag::compound([
("id", string(&kind.id)),
("Pos", doubles(&[4.5, 205.0, 4.5])),
("Fire", fire),
]);
assert_eq!(
armor_stand_from_nbt(&input, 1).unwrap().fire_ticks,
expected
);
assert_eq!(
mob_from_nbt(&input, &types, 1, None).unwrap().fire_ticks,
expected
);
}
}
#[test]
fn decoded_stand_fall_distance_survives_save_without_raw_or_with_stale_raw() {
let stale = Tag::compound([("fall_distance", Tag::Double(99.0_f64.to_bits()))]);
@@ -39,10 +39,16 @@ fn attached_block_pos(tag: &Tag) -> Option<[i32; 3]> {
}
}
}
/// `Direction.from3DDataValue` / `from2DDataValue`: the byte read by
/// `LEGACY_ID_CODEC` indexes the table as `abs(data % modulus)`, never clamped.
fn wrap_data_value(raw: impl TryInto<i64> + Copy, modulus: i64) -> u8 {
let byte = raw.try_into().unwrap_or(0) as i8;
(i64::from(byte) % modulus).unsigned_abs() as u8
}
/// The block position, facing and variant (if saved) of a painting.
pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, Option<String>)> {
let pos = attached_block_pos(tag)?;
let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8;
let facing = wrap_data_value(number(tag.get("facing")).unwrap_or(0), 4);
Some((pos, facing, text(tag.get("variant"))))
}
/// ItemFrame.addAdditionalSaveData.
@@ -92,7 +98,7 @@ pub fn item_frame_from_nbt(tag: &Tag, id: u32) -> Option<ItemFrame> {
Some(ItemFrame {
id,
pos,
facing: number(tag.get("Facing")).unwrap_or(0).clamp(0, 5) as u8,
facing: wrap_data_value(number(tag.get("Facing")).unwrap_or(0), 6),
glow: kind(tag).as_deref() == Some("minecraft:glow_item_frame"),
item: tag
.get("Item")
@@ -107,3 +113,26 @@ pub fn item_frame_from_nbt(tag: &Tag, id: u32) -> Option<ItemFrame> {
random: crate::random_source::entity(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn negative_facing_wraps_like_vanilla_direction_codecs() {
// from3DDataValue: abs(-1 % 6) = 1 (UP); 7 -> 1; -6 -> 0.
for (raw, want) in [(-1i8, 1u8), (7, 1), (-6, 0), (5, 5), (0, 0)] {
let tag = Tag::compound([
("Facing", Tag::Byte(raw)),
("block_pos", Tag::IntArray(vec![0, 0, 0])),
]);
assert_eq!(item_frame_from_nbt(&tag, 1).unwrap().facing, want);
}
// from2DDataValue: abs(-1 % 4) = 1.
let tag = Tag::compound([
("facing", Tag::Byte(-1)),
("block_pos", Tag::IntArray(vec![0, 0, 0])),
]);
assert_eq!(painting_from_nbt(&tag).unwrap().1, 1);
}
}
@@ -0,0 +1,56 @@
//! Experience orbs: `ExperienceOrb` save data.
use super::{Base, ExperienceOrb, Tag, flag, int_value, motion, number, position, put, rotation};
/// `ExperienceOrb`: Health, Age, Value, Count.
pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
let base = Base {
id: "minecraft:experience_orb",
uuid,
position: o.position,
motion: o.velocity,
rotation: o.rotation,
on_ground: o.on_ground,
fall_distance: 0.0,
};
let mut tag = base.tag(None);
for (key, value) in [
("Health", Tag::Short(o.health as i16)),
("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)),
("Value", Tag::Short(o.value as i16)),
("Count", Tag::Int(o.count.min(i32::MAX as u32) as i32)),
] {
put(&mut tag, key, value);
}
// Entity.saveWithoutId writes NoGravity only when set.
if o.no_gravity {
put(&mut tag, "NoGravity", Tag::Byte(1));
}
tag
}
/// One orb with its merged `Count`.
pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
let Some(position) = position(tag) else {
return Vec::new();
};
let count = number(tag.get("Count")).unwrap_or(1).max(1) as u32;
let orb = ExperienceOrb {
rotation: rotation(tag),
join: Default::default(),
no_gravity: flag(tag, "NoGravity"),
id: 0,
position,
previous: position,
velocity: motion(tag),
// `getShortOr("Value", 0)`, unclamped.
value: tag.get("Value").and_then(int_value).unwrap_or(0) as i16 as i32,
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
on_ground: flag(tag, "OnGround"),
count,
ticks: 0,
health: number(tag.get("Health")).unwrap_or(5) as i32,
// ExperienceOrb's followingPlayer is transient: never saved, so a
// loaded orb starts without one.
following: None,
};
vec![orb]
}
@@ -0,0 +1,85 @@
//! `EntityReference`s a mob's compound holds: a UUID, resolved against what is in
//! the level.
use super::{Who, number, uuid_from_tag};
use crate::mobs::Mob;
use horizon_world::nbt::Tag;
use std::collections::HashMap;
/// `LivingEntity.readAdditionalSaveData`: `last_hurt_by_mob` is a lazy
/// `EntityReference` (the UUID, which the game resolves once the entity is in
/// the level) and its timestamp is `tickCount - ticks_since_last_hurt_by_mob`.
pub(super) fn read_last_hurt_by(m: &mut Mob, tag: &Tag) {
m.ai.last_hurt_by_ref = uuid_from_tag(tag.get("last_hurt_by_mob"));
m.ai.last_hurt_by_time = (m.age as i32)
.wrapping_sub(number(tag.get("ticks_since_last_hurt_by_mob")).unwrap_or(0) as i32);
}
/// The entity a stored UUID names, while it is in the level: `player` (the
/// player's own UUID, when one is in the level), or the mob `uuids` gives that
/// UUID to. `uuids` is the game layer's id -> UUID map, so this is the read half
/// of the pair [`who_uuid`] and `mob_to_nbt`'s `uuid_of` form. A UUID nothing
/// loaded has, or one naming a kind `Who` cannot carry (an item, a projectile, a
/// guest), is `None` - never some other entity as a stand-in.
pub fn who_by_uuid(
uuids: &HashMap<u32, [i32; 4]>,
mobs: &[Mob],
player: Option<[i32; 4]>,
uuid: [i32; 4],
) -> Option<Who> {
if player == Some(uuid) {
return Some(Who::Player);
}
// Only a loaded mob: the map also holds projectiles, vehicles and items,
// whose ids mean nothing to `Who`.
uuids
.iter()
.find(|(id, u)| **u == uuid && mobs.iter().any(|m| m.id == **id))
.map(|(id, _)| Who::Mob(*id))
}
#[cfg(test)]
mod tests {
use super::super::*;
use crate::mobs::{Species, sensor_scan_tests::kind};
fn types() -> HashMap<String, std::sync::Arc<crate::mobs::MobType>> {
let mut pig = (*kind()).clone();
pig.id = "minecraft:pig".into();
pig.species = Species::Pig;
HashMap::from([("minecraft:pig".to_owned(), std::sync::Arc::new(pig))])
}
fn load(snbt: &str) -> Mob {
let tag = horizon_world::nbt::parse_snbt(snbt).unwrap().0;
mob_from_nbt(&tag, &types(), 7, None).unwrap()
}
/// `LivingEntity.readAdditionalSaveData`: `lastHurtByMob` is the UUID,
/// `lastHurtByMobTimestamp = tickCount - ticks_since_last_hurt_by_mob`, and a
/// freshly loaded entity has `tickCount` 0, so 30 saved ticks make -30.
#[test]
fn a_saved_hurt_by_mob_is_read_back_as_a_reference_and_a_timestamp() {
let m = load(
r#"{id:"minecraft:pig",UUID:[I;5,0,0,1],Pos:[2.5d,200d,4.5d],Health:10f,last_hurt_by_mob:[I;5,0,0,2],ticks_since_last_hurt_by_mob:30}"#,
);
assert_eq!(m.age, 0);
assert_eq!(m.ai.last_hurt_by_ref, Some([5, 0, 0, 2]));
assert_eq!(m.ai.last_hurt_by_time, -30);
// Not resolved yet: `getLastHurtByMob` answers nothing.
assert_eq!(m.ai.last_hurt_by, None);
}
/// Missing keys: no reference, and `getIntOr("ticks_since...", 0)` stamps the
/// timestamp at `tickCount`.
#[test]
fn a_save_without_a_hurt_by_mob_has_none() {
let m = load(r#"{id:"minecraft:pig",UUID:[I;5,0,0,1],Pos:[2.5d,200d,4.5d],Health:10f}"#);
assert_eq!(m.ai.last_hurt_by_ref, None);
assert_eq!(m.ai.last_hurt_by_time, 0);
// A key that is not a UUID int array is no reference (the codec fails).
let m = load(
r#"{id:"minecraft:pig",UUID:[I;5,0,0,1],Pos:[2.5d,200d,4.5d],Health:10f,last_hurt_by_mob:"x"}"#,
);
assert_eq!(m.ai.last_hurt_by_ref, None);
}
}
+10
View File
@@ -28,6 +28,8 @@ pub fn main_with(mods: crate::mod_api::Mods) {
// then the Horizon parts still in this crate; none registers after this point.
game::player_hooks::register();
horizon_hooks::engine::seal();
// The text crates ship (`horizon_hooks::lang`), loaded with the game's own languages.
horizon_client::lang::install_crate_files(horizon_hooks::lang::engine::all());
horizon_client::spans::startup::init(std::time::Instant::now());
horizon_client::spans::trace::start_from_env();
let args: Vec<String> = std::env::args().skip(1).collect();
@@ -230,6 +232,14 @@ pub fn main_with(mods: crate::mod_api::Mods) {
living_jump: |entity, kind| {
crate::mod_api::dispatch_living_jump(crate::mod_api::mods(), entity, kind);
},
living_death_message: |entity, kind, message| {
crate::mod_api::dispatch_living_death_message(
crate::mod_api::mods(),
entity,
kind,
message,
);
},
register_goals: |mob| {
crate::mod_api::dispatch_register_goals(crate::mod_api::mods(), mob);
},
+79 -105
View File
@@ -497,7 +497,7 @@ use horizon_client::random_source;
pub use advancements::AdvancementDisplay;
use horizon_client::actions::Action as Mapping;
use horizon_client::held::Source;
use horizon_client::spans::startup;
use horizon_client::spans::{startup, time as span};
use horizon_client::{
Result,
assets::{Assets, RenderAssets},
@@ -758,7 +758,6 @@ enum GuestUse {
/// an entity again from the view.
Entity(Hand, InteractTarget),
}
/// The entity an interact packet names and where its client clicked it (the
/// packet's location, measured from the entity's position): what
/// `ServerGamePacketListenerImpl.handleInteract` takes from
@@ -1505,7 +1504,7 @@ impl LevelAccess for GameLevel<'_> {
{
return signal;
}
machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos)
machines::container_signal(self, pos)
}
fn item_frame_analog_output(&self, pos: BlockPos, facing: Direction) -> Option<i32> {
let mut frames = self
@@ -2328,6 +2327,8 @@ struct Game<'a> {
last_device_recovery: Option<Instant>,
/// CPU geometry storage retained across frames, including empty/title frames.
entity_vertices: Vec<Vertex>,
/// Falling models by state and selected-model address list; cleared on pack/atlas replacement.
falling_vertices: RefCell<HashMap<BlockStateId, Vec<(Vec<usize>, Vec<Vertex>)>>>,
/// Horizon Extras' dynamic lights this frame (`dynamic_lights.rs`), and how brightly each
/// item glows (built the first time the extra is on).
dynamic_lights: Vec<[f32; 4]>,
@@ -3888,6 +3889,7 @@ impl Game<'_> {
golem_chests.extend(self.chest_other_half(key));
}
let native_authoritative = self.native_authoritative();
let environment_type = self.dimension_type();
let mut level = GameLevel {
gateway_servers: &mut self.be_anims.gateway_servers,
border: self.border.geometry(),
@@ -3910,11 +3912,7 @@ impl Game<'_> {
events: &mut self.level_events,
dimension,
darken,
environment: match dimension {
LevelDimension::Overworld => self.res.environment(),
LevelDimension::Nether => self.res.nether_environment(),
LevelDimension::End => self.res.end_environment(),
},
environment: self.res.environment_of(&environment_type.id),
raining: rain > 0.2,
thundering: thunder > 0.9,
player_box,
@@ -5033,8 +5031,8 @@ impl Game<'_> {
self.loot_block_entity(pos, &facts.name)
};
if let Some(entity) = self.world.block_entities.get(&key).cloned() {
let name = self.world.block_names.get(&key).cloned();
self.pending.record(pos, &entity, &facts.name, name);
self.pending
.record_from(&self.world, pos, &entity, &facts.name);
} else if let Some(tag) = spill::saved_entity(&self.world, pos) {
self.pending.record_saved(pos, &tag);
}
@@ -5544,7 +5542,7 @@ impl Game<'_> {
// the activated item counts down.
self.boss_overlay.tick_darken(running);
self.tick_item_activation();
self.native_inventory_ticks();
span("mods_inventory_ticks", || self.native_inventory_ticks());
if running {
// `MinecraftServer.tickChildren`: `commandFunctions` runs before
// any level ticks, so a tick function reads the game time and the
@@ -5552,7 +5550,7 @@ impl Game<'_> {
// long before this point; the lazy scoreboard/storage read has to
// be done by then too, or a load tag writes over what it restores.
self.load_scoreboard();
self.tick_functions();
span("tick_functions", || self.tick_functions());
self.world.game_time += 1;
if self.ui.rules.bool("advance_weather") {
self.world.weather.tick_timers(&mut self.world.random);
@@ -5566,7 +5564,7 @@ impl Game<'_> {
}
// ClientLevel.tick: the sky flash fades in a frozen level too.
self.tick_weather_effects();
let _ = self.finish_player_autosaves(false);
let _ = span("player_autosaves", || self.finish_player_autosaves(false));
// MinecraftServer.tickServer's countdown, then autoSave: three
// hundred seconds of ticks at the rate the server runs at now.
self.ticks_until_autosave -= 1;
@@ -5575,7 +5573,7 @@ impl Game<'_> {
serving.set_saving(self.autosaving);
}
if self.autosaving {
self.save_game_with(false)?;
span("autosave", || self.save_game_with(false))?;
self.ticks_until_autosave = self.next_autosave_interval();
if let Some(serving) = &self.serving {
serving.set_saving(false);
@@ -5584,27 +5582,27 @@ impl Game<'_> {
if running {
self.advance_clock();
// `ServerLevel.tickTime`, once the clock has moved on.
self.run_scheduled_functions();
span("scheduled_functions", || self.run_scheduled_functions());
}
if self.use_delay > 0 {
self.use_delay -= 1;
}
self.tick_totem();
self.update_totem_ready();
self.tick_command_extras();
self.native_tick();
self.tell_native_now();
span("tick_command_extras", || self.tick_command_extras());
span("mods_tick", || self.native_tick());
span("mods_tick", || self.tell_native_now());
self.tick_world(running)
}
/// What the tick runs after the local player's own update: effects, the
/// world's entities and blocks, and the network hub.
fn tick_world(&mut self, running: bool) -> Result<()> {
// Entities added since the last tick join the level before it ticks.
self.native_joins_flush(false, 0);
self.share_spawn_conditions();
span("mods_joins_flush", || self.native_joins_flush(false, 0));
span("share_spawn_conditions", || self.share_spawn_conditions());
horizon_client::mobs::sulfur_cube::set_tnt_explodes(self.ui.rules.bool("tnt_explodes"));
self.update_chunk_tickets();
self.score_destroyed_entities();
span("chunk_tickets", || self.update_chunk_tickets());
span("score_destroyed", || self.score_destroyed_entities());
horizon_client::spans::time("tick_effects", || self.tick_effects(running));
self.tick_sign_editor();
// Player.tick's ItemCooldowns.tick for the window's player (a
@@ -5628,8 +5626,8 @@ impl Game<'_> {
sent = horizon_client::spans::time("tick_blocks", || self.tick_blocks())?;
// What the blocks spawned (a dispensed minecart, a lit TNT, a
// placed boat) joins before the entities tick.
self.native_joins_flush(false, 0);
self.lan_mark_synced();
span("mods_joins_flush", || self.native_joins_flush(false, 0));
span("lan_mark_synced", || self.lan_mark_synced());
// `EntityTickList.forEach`: what joined before the entity pass
// (function summons, dropped or dispensed items) ticks in it;
// what joins during it waits for the next tick
@@ -5639,7 +5637,7 @@ impl Game<'_> {
}
// ChunkMap still ticks while /tick freeze holds block/entity ticks.
if !running {
self.save_chunks_eagerly();
span("save_chunks_eagerly", || self.save_chunks_eagerly());
}
self.begin_ordered_ticks();
if running {
@@ -5653,8 +5651,8 @@ impl Game<'_> {
// ServerLevel.tick: the arrivals of this server tick are in the level
// (`addDuringTeleport`), and each vehicle handles its portal as its
// own tick opens.
self.land_portal_arrivals();
self.handle_vehicle_portals();
span("portal_arrivals", || self.land_portal_arrivals());
span("vehicle_portals", || self.handle_vehicle_portals());
self.ordered_before(ordered_tick::Batch::Boats)?;
horizon_client::spans::time("tick_boats", || self.tick_boats());
self.ordered_before(ordered_tick::Batch::Carts)?;
@@ -5684,11 +5682,11 @@ impl Game<'_> {
self.ordered_before(ordered_tick::Batch::Items)?;
horizon_client::spans::time("tick_items", || self.tick_items());
if self.remote.is_none() {
self.hoppers_catch_items();
span("hoppers_catch_items", || self.hoppers_catch_items());
}
// Merged, burnt, despawned or picked up.
self.native_leaves_flush();
self.native_joins_flush(false, 0);
span("mods_leaves_flush", || self.native_leaves_flush());
span("mods_joins_flush", || self.native_joins_flush(false, 0));
horizon_client::spans::time("touch_arrows", || self.touch_arrows());
}
horizon_client::spans::time("spawn_loaded_entities", || self.spawn_loaded_entities());
@@ -5698,22 +5696,22 @@ impl Game<'_> {
self.ordered_before(ordered_tick::Batch::Mobs)?;
horizon_client::spans::time("tick_mobs", || self.tick_mobs())?;
// Dead, despawned or gone into a hive.
self.native_leaves_flush();
span("mods_leaves_flush", || self.native_leaves_flush());
horizon_client::spans::time("recheck_golem_openers", || self.recheck_golem_openers());
self.tick_mod_container_viewers();
span("mod_viewers", || self.tick_mod_container_viewers());
// Orbs, primed TNT and falling blocks still to tick, in join order.
self.run_ordered_ticks(horizon_client::join_seq::JoinSeq::MAX, false)?;
horizon_client::spans::time("tick_experience", || self.tick_experience());
// Merged, despawned or picked up.
self.native_leaves_flush();
span("mods_leaves_flush", || self.native_leaves_flush());
horizon_client::spans::time("entity_portals", || {
self.find_entity_portals();
self.resolve_arrivals();
});
}
// The rest of the tick's spawns join, and what left is told of.
self.native_joins_flush(false, 0);
self.native_leaves_flush();
span("mods_joins_flush", || self.native_joins_flush(false, 0));
span("mods_leaves_flush", || self.native_leaves_flush());
// ServerLevel.tick broadcasts the changed blocks after the scheduled and
// random ticks (`tick_blocks`), before the block events, the entities
// and the block entities: what those change goes out with the next
@@ -5728,23 +5726,23 @@ impl Game<'_> {
if let Some(log) = self.world.block_log.as_mut() {
log.extend(held);
}
self.tick_friends();
span("tick_friends", || self.tick_friends());
horizon_client::spans::time("tick_hand", || self.tick_hand());
horizon_client::spans::time("tick_sleep", || self.tick_sleep());
self.announce_sleep_status();
self.free_left_beds();
span("sleep_status", || self.announce_sleep_status());
span("sleep_status", || self.free_left_beds());
if running {
horizon_client::spans::time("tick_end", || self.tick_end())?;
horizon_client::spans::time("end_gateways", || {
self.find_end_gateway_portals();
self.resolve_end_gateway_arrivals()
})?;
self.keep_gateway_destinations();
span("end_gateways", || self.keep_gateway_destinations());
}
if running {
// Primed TNT and falling blocks that joined since the spawn packets.
self.run_ordered_ticks(horizon_client::join_seq::JoinSeq::MAX, true)?;
self.apply_late_wind_pushes();
span("late_wind_pushes", || self.apply_late_wind_pushes());
}
// Everything that has joined has had its spawn packet and, if it joined
// before the entity passes (TNT a piston or repeater primed), its first
@@ -5763,21 +5761,21 @@ impl Game<'_> {
self.tick_block_entity_anims()
});
// A conduit's hurt teleports an enderman now (`Enderman.hurtServer`).
self.settle_hurt_teleports()?;
span("settle_hurt_teleports", || self.settle_hurt_teleports())?;
horizon_client::spans::time("tick_particles", || self.tick_particles());
self.tick_client_ambient();
span("tick_client_ambient", || self.tick_client_ambient());
}
// ServerLevel.tick's `entityManager.tick()`, frozen or not, after every
// block entity ticker (the bells, conduits and gateways above too): the
// chunks loaded before this pass have their entities loaded from the next.
self.world.entities_pending.clear();
self.tick_frame_visuals(running);
span("tick_frame_visuals", || self.tick_frame_visuals(running));
if running {
// MinecraftServer.tickServer: GameTestTicker.SINGLETON.tick().
self.tick_game_tests();
span("tick_game_tests", || self.tick_game_tests());
}
// ServerBossEvent broadcasts, after this level's entities have ticked.
self.publish_boss_bars();
span("publish_boss_bars", || self.publish_boss_bars());
// Minecraft.handleKeybinds: held use repeats only while no item is in
// use (a raised shield or a drawn bow places and uses nothing).
if self.right
@@ -6733,19 +6731,14 @@ impl Game<'_> {
// Entity shadows (EntityRenderer.extractShadow); a native pack's sun shadows replace them.
self.mark_translucent_entity(out.len(), "minecraft:entity_shadow");
let pack_shadows = self.renderer.as_ref().is_some_and(|r| {
r.pack_entity_shadows() || (self.dim == Dim::Overworld && r.native_shadow())
r.pack_entity_shadows() || (self.overworld_skybox() && r.native_shadow())
});
let shadows = self.settings.entity_shadows && self.pack.polytone_colors.entity_shadows();
let shadow_sprite = (shadows && !pack_shadows)
.then(|| self.gui.atlas.sprites.get("misc/shadow").copied())
.flatten();
if let Some(sprite) = shadow_sprite {
// DimensionType.ambientLight: the_nether 0.1, the_end 0.25.
let ambient = match self.dim {
Dim::Nether => 0.1,
Dim::End => 0.25,
Dim::Overworld => 0.0,
};
let ambient = self.dimension_type().ambient_light;
let darken = self.sky_darken();
let a = alpha;
let lerp = |p: Vec3, q: Vec3| {
@@ -6908,7 +6901,7 @@ impl Game<'_> {
emissive: &self.gui.atlas.emissive,
translucent_sprites: &self.gui.atlas.translucent,
atlas_revision: self.gui.atlas.revision,
nether: self.dim == Dim::Nether,
nether: self.nether_lighting(),
lid: &lid,
sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) {
Some(BlockEntity::Sign(sign)) => Some(sign),
@@ -7158,14 +7151,7 @@ impl Game<'_> {
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let start = out.len();
self.mark_motion(start, Self::MOTION_OBJECT | u64::from(f.id));
self.block_model_vertices(
f.state,
horizon_core::random::position_seed(f.start_pos),
glam::Mat4::from_translation(o),
packed,
false,
&mut out,
);
self.falling_model_vertices(f.state, f.start_pos, o, packed, &mut out);
let tint = horizon_client::mobs::render::abgr(tint);
for vertex in &mut out[start..] {
vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint);
@@ -7633,8 +7619,10 @@ impl Game<'_> {
r.clear_sections(self.world.layout());
}
self.apply_settings();
self.streaming.sky_light = dim != Dim::Nether;
self.streaming.nether_shading = dim == Dim::Nether;
let facts = self.dimension_type_of(dim);
self.streaming.sky_light = facts.height.has_skylight;
self.streaming.nether_shading =
facts.cardinal_light == horizon_world::dimension_type::CardinalLight::Nether;
self.load_world_state();
// The level the world opens in, before any of its chunks.
self.native_level_opened(dim);
@@ -8211,10 +8199,7 @@ impl Game<'_> {
}
if let Some(kind) = mob {
if let Some(id) = self.spawn_mob_at(kind, (target[0], target[1], target[2]), true) {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
horizon_client::entity_nbt::apply_item_components(m, stack);
}
self.mob_placed(id)?;
self.mob_placed(id, stack)?;
}
self.post_block_game_event(
"minecraft:entity_place",
@@ -8490,6 +8475,7 @@ impl Game<'_> {
None,
self.settings.horizon.api,
self.settings.horizon.translucent_batching,
self.settings.vsync,
&self.settings.horizon,
shader_packs::picked_pack_shape(&self.settings),
display,
@@ -9325,10 +9311,10 @@ impl Game<'_> {
game_time: self.world.game_time,
day_time: self.view_day_time(),
render_distance: self.streaming.radius,
sky_type: match self.dim {
Dim::Overworld => 1,
Dim::End => 2,
Dim::Nether => 0,
sky_type: match self.dimension_type().skybox {
horizon_world::dimension_type::Skybox::Overworld => 1,
horizon_world::dimension_type::Skybox::End => 2,
horizon_world::dimension_type::Skybox::None => 0,
},
dimension: match self.dim {
Dim::Overworld => "minecraft:overworld",
@@ -9670,13 +9656,13 @@ impl Game<'_> {
pr.lap("pr_dragon_bolts");
let (celestial, stars) = if title {
(Vec::new(), None)
} else if self.dim == Dim::Overworld
} else if self.overworld_skybox()
&& self.potions.effects.get("darkness").is_none()
&& self.potions.effects.get("blindness").is_none()
{
// Camera.doesMobEffectBlockSky: no sun, moon or stars.
self.celestial_geometry(&sky, rain)
} else if self.dim == Dim::End && self.settings.horizon.sky {
} else if self.end_skybox() && self.settings.horizon.sky {
(self.end_flash_geometry(), None)
} else {
(Vec::new(), None)
@@ -9750,7 +9736,7 @@ impl Game<'_> {
let frame = Frame {
weather: &weather,
weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32),
nether_lighting: self.dim == Dim::Nether,
nether_lighting: self.nether_lighting(),
camera,
yaw,
pitch,
@@ -9790,8 +9776,8 @@ impl Game<'_> {
|| self.potions.effects.get("darkness").is_some(),
self.boss_overlay.should_create_world_fog(),
),
skybox: self.dim == Dim::Overworld && self.settings.horizon.sky,
end_sky: self.dim == Dim::End && self.settings.horizon.sky,
skybox: self.overworld_skybox() && self.settings.horizon.sky,
end_sky: self.end_skybox() && self.settings.horizon.sky,
end_sky_sprite: self
.gui
.atlas
@@ -9815,7 +9801,7 @@ impl Game<'_> {
glint_alpha: self.glint_frame.alpha,
glint_ticks: self.glint_frame.scroll_ticks(),
clouds: (!title
&& self.dim == Dim::Overworld
&& self.overworld_skybox()
&& horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3]))
.then(|| self.gui.atlas.sprites.get("horizon/white"))
.flatten()
@@ -9863,12 +9849,10 @@ impl Game<'_> {
border,
game_time: self.world.game_time as f32,
shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0,
crumbling_sprite: self
.gui
.atlas
.sprites
.get("block/destroy_stage_0")
.map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]),
crumbling_sprite: frame_geometry::crumbling_sprite(
&self.gui.atlas.sprites,
self.settings.improved_transparency,
),
end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| {
self.gui
.atlas
@@ -9972,20 +9956,10 @@ impl Game<'_> {
self.drag_button = None;
}
if let WindowEvent::ModifiersChanged(m) = &event {
self.modifiers = m.state();
horizon_client_input::modifiers::reconcile(
self.modifiers,
&mut self.physical_keys,
&self.settings.keys,
&mut self.toggles,
[self.settings.toggle_crouch, self.settings.toggle_sprint],
[
self.pad.holds_action("key.sneak"),
self.pad.holds_action("key.sprint"),
],
);
self.sync_toggle(SNEAK);
self.sync_toggle(SPRINT);
self.update_modifiers(m.state());
}
if let WindowEvent::Focused(false) = &event {
self.update_modifiers(winit::keyboard::ModifiersState::empty());
}
// `PackSelectionScreen.onFilesDrop` on the Create New World screen.
if let WindowEvent::DroppedFile(path) = &event
@@ -10391,6 +10365,8 @@ impl Game<'_> {
let held = self.captured;
if self.control.is_none() {
self.keys.clear();
self.modifiers = winit::keyboard::ModifiersState::empty();
self.debug_keys.reset();
// Latched sneak/sprint live in `toggles`, not in the
// physical keys: put them back so a short alt-tab
// (no pause screen) does not drop them. Only a mapping
@@ -10398,21 +10374,18 @@ impl Game<'_> {
// no state to keep, and an unfocused window never gets
// its key release, so leaving it down would keep the
// player sneaking or sprinting until the key is tapped.
for (slot, needs_toggle) in [
let toggles = [
self.settings.toggle_crouch,
self.settings.toggle_sprint,
self.settings.toggle_attack,
self.settings.toggle_use,
]
.into_iter()
.enumerate()
{
];
for (slot, needs_toggle) in toggles.into_iter().enumerate() {
self.toggles.0[slot].set_down(false, needs_toggle);
}
self.sync_toggle(0);
self.sync_toggle(1);
self.left = false;
self.right = false;
(self.left, self.right) = (false, false);
self.capture(false);
}
self.regrab_on_refocus = held;
@@ -11685,6 +11658,7 @@ impl<'a> Game<'a> {
renderer: None,
last_device_recovery: None,
entity_vertices: Vec::new(),
falling_vertices: Default::default(),
dynamic_lights: Vec::new(),
luminance: Default::default(),
see_through_vertices: Vec::new(),
@@ -12480,7 +12454,7 @@ pub fn run_with() -> Result<()> {
horizon_world::datafix::set_resources(
&std::path::absolute(&vanilla_root).unwrap_or_else(|_| vanilla_root.clone()),
);
if let Some(error) = missing_resources(&vanilla_root) {
if let Some(error) = missing_resources(&vanilla_root, horizon_hooks::engine::get_the_game()) {
// The game build started by hand (the release's zip), not by the
// launcher: a window says where to get it. Scripts and servers get
// the error.
@@ -230,15 +230,10 @@ impl adv::World for View<'_, '_> {
_ => None,
}
}
/// `Level.canSeeSky`: sky light 15 at the position, whatever stands
/// above it, as `MobWorld` reads it for the spawn rules.
fn can_see_sky(&self, p: [i32; 3]) -> bool {
(p[1] + 1..p[1] + 200).all(|y| {
!self
.0
.res
.facts()
.get(self.0.world.block(p[0], y, p[2]))
.full_collision
})
self.0.mob_world_base(&[]).can_see_sky(p[0], p[1], p[2])
}
fn light(&self, p: [i32; 3]) -> i32 {
let l = self.0.world.light(p[0], p[1], p[2]);
@@ -4,6 +4,7 @@
//! same on vanilla 26.3).
use super::*;
use horizon_client::chunk::Chunk;
use horizon_client::mobs::allay;
use horizon_core::position::ChunkPos;
use horizon_world::nbt::Tag;
use std::sync::Arc;
@@ -84,7 +85,7 @@ fn an_allay_keeps_its_item_pickup_cooldown_memory() {
let mut game = game();
let i = index(&mut game);
// The supplied memory is loaded into the pickup cooldown and saved back.
assert_eq!(game.mobs[i].extra.ints[3], 30, "loaded");
assert_eq!(allay::pickup_cooldown(&game.mobs[i]), Some(30), "loaded");
assert_eq!(
saved(&mut game, i),
Some(Tag::compound([("value", Tag::Int(30))])),
@@ -100,6 +101,53 @@ fn an_allay_keeps_its_item_pickup_cooldown_memory() {
Some(Tag::compound([("value", Tag::Int(20))])),
"after 10 ticks"
);
// CountDownCooldownTicks: the memory reaches 0 and is erased a tick later
// (`stop`).
step(&mut game, 20);
assert_eq!(
saved(&mut game, i),
Some(Tag::compound([("value", Tag::Int(0))])),
"at 0"
);
step(&mut game, 1);
assert_eq!(saved(&mut game, i), None, "erased the tick after");
}
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn pickup_cooldown_saves_the_full_integer_value() {
let mut game = game();
let i = index(&mut game);
assert!(game.run_command(&format!(
"item replace entity {SUPPLIED} weapon.mainhand with minecraft:diamond 1"
)));
for ticks in [i32::MIN, -1, 0, 1, i32::MAX] {
allay::set_pickup_cooldown(&mut game.mobs[i], Some(ticks));
assert!(
!game.mobs[i].can_pick_up_loot(),
"memory present at {ticks}"
);
assert_eq!(
saved(&mut game, i),
Some(Tag::compound([("value", Tag::Int(ticks))])),
"saved {ticks}"
);
let tag = game.mob_tree_nbt(i);
let loaded = horizon_client::entity_nbt::mob_from_nbt(
&tag,
game.res.mob_types(),
game.mobs[i].id,
None,
)
.unwrap();
assert_eq!(
allay::pickup_cooldown(&loaded),
Some(ticks),
"loaded {ticks}"
);
}
allay::set_pickup_cooldown(&mut game.mobs[i], None);
assert!(game.mobs[i].can_pick_up_loot(), "memory erased");
}
// Added controls (after the frozen baseline above).
@@ -135,10 +183,10 @@ fn the_saved_pickup_cooldown_follows_the_model() {
assert_eq!(saved(&mut game, plain), None, "no raw memory");
// A loaded memory the model has ended: no key (the raw copy is not echoed).
let supplied = index(&mut game);
game.mobs[supplied].extra.ints[3] = 0;
allay::set_pickup_cooldown(&mut game.mobs[supplied], None);
assert_eq!(saved(&mut game, supplied), None, "stale raw memory");
// A model mutation, as a throw does (`allays.rs`): saved with its value.
game.mobs[plain].extra.ints[3] = 60;
allay::set_pickup_cooldown(&mut game.mobs[plain], Some(60));
let tag = saved(&mut game, plain);
assert_eq!(
tag,
@@ -149,7 +197,11 @@ fn the_saved_pickup_cooldown_follows_the_model() {
let whole = game.mob_tree_nbt(plain);
let reloaded =
horizon_client::entity_nbt::mob_from_nbt(&whole, game.res.mob_types(), 99, None).unwrap();
assert_eq!(reloaded.extra.ints[3], 60, "load after save");
assert_eq!(
allay::pickup_cooldown(&reloaded),
Some(60),
"load after save"
);
// NoAI: no Brain tick, the value stays.
let frozen = at(&mut game, 2);
step(&mut game, 5);
+1 -1
View File
@@ -288,7 +288,7 @@ impl Game<'_> {
});
let m = &mut self.mobs[i];
m.extra.allay.as_mut().unwrap().take(1);
m.extra.ints[3] = 60;
allay::set_pickup_cooldown(m, Some(60));
// ItemEntity.setDefaultPickUpDelay.
self.spawn_item(stack, from, v, 10);
// BehaviorUtils.throwItem: ItemEntity.setThrower(the allay).
@@ -1954,8 +1954,7 @@ impl Game<'_> {
mut skin: Option<&mut horizon_client::mobs::skin::Skin>,
out: &mut Vec<Vertex>,
) {
let lights =
horizon_client::block_entity_render::diffuse_lights(self.dim == super::Dim::Nether);
let lights = horizon_client::block_entity_render::diffuse_lights(self.nether_lighting());
let mut submit = |state: &horizon_client::item_render::ItemRenderState,
pose: glam::Mat4,
out: &mut Vec<Vertex>| {
@@ -2028,7 +2027,7 @@ impl Game<'_> {
out,
light,
lights: Some(horizon_client::block_entity_render::diffuse_lights(
self.dim == super::Dim::Nether,
self.nether_lighting(),
)),
glint: self.glint(),
tier: 0,
@@ -801,8 +801,17 @@ impl Game<'_> {
let server = self.be_anims.gateway_servers.entry(key).or_insert(initial);
let triggered = server.portal_tick();
let age = server.age;
if let Some(BlockEntity::EndGateway(g)) = self.world.block_entities.get_mut(&pos) {
let mut aged = false;
if let Some(BlockEntity::EndGateway(g)) = self.world.block_entities.get_mut(&pos)
&& g.age != age
{
g.age = age;
aged = true;
}
if aged {
// `TheEndGatewayBlockEntity.portalTick` ends with `setChanged`: the
// age the beam and the chunk save read moved.
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
}
if triggered {
self.gateway_cooldown_event(key);
@@ -1108,3 +1117,41 @@ mod bell_ownership_tests {
assert!(anims.bells.is_empty());
}
}
#[cfg(test)]
mod gateway_age_tests {
use super::*;
use crate::game::native_machines::tests::server_game;
/// `TheEndGatewayBlockEntity.portalTick`: an age that moved is a change
/// to save.
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn a_gateway_that_ages_marks_the_chunk() {
let mut game = server_game();
let state = game
.pack
.assets
.registry
.default_state("minecraft:end_gateway")
.unwrap();
let pos = (2, 4, 3);
game.world.set(pos.0, pos.1, pos.2, state).unwrap();
game.world.block_entities.insert(
pos,
BlockEntity::EndGateway(horizon_client::containers::EndGateway::default()),
);
game.world.modified.clear();
game.tick_end_gateway(pos);
let Some(BlockEntity::EndGateway(g)) = game.world.block_entities.get(&pos) else {
panic!("no gateway");
};
assert_eq!(g.age, 1, "the tick aged the gateway");
assert!(
game.world.modified.contains(&(0, 0)),
"the aged gateway left the chunk unmarked"
);
}
}
Loaded 100 of 610 files, more files were not shown because too many files have changed in this diff. Show more