Compare commits

...
Author SHA1 Message Date
rdbtCVSandCodex gpt-6.1-sol 5fee5e0bb2 Clarify the scope of benchmark load control
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-13 04:16:29 +00:00
rdbtCVSandCodex gpt-6.1-sol 699d717db1 Merge main before final tracker send proof
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-13 04:14:50 +00:00
rdbtCVSandCodex gpt-6.1-sol 7fcb694da1 Gate parallel tracker sends on measured crowd sizes
Two- and four-core isolated runs regress at 16/64 and 120/120, while the whole tracker improves in every paired round at 400/400 and 600/600. Raise both cutoffs to 400 and retain the measurements and limitations.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-13 04:14:49 +00:00
rdbt a30ed9e44d Merge pull request #15746 from Joansitoh/fix/prediction-history-gap-rebase
Anticheat prediction: a history gap rebases the replay instead of dropping it
2026-11-13 02:55:01 +00:00
rdbt 1a6885f931 Merge pull request #15700 from kacpherek/feat/graphics-presets
Graphics: a Full Performance preset, and every preset a fixed table
2026-11-13 02:54:57 +00:00
rdbt ea50823946 Merge pull request #15695 from NikitaMGrimm/docs/pr-size-what-counts
Docs: say what counts towards the 500-line pull request size
2026-11-13 02:54:52 +00:00
rdbt 98d7a0ce3c Merge pull request #15637 from kacpherek/fix/vanilla-glider-wear
Wear a glider held in a hand like a worn one
2026-11-13 02:54:48 +00:00
rdbt b6db19caad Merge pull request #15636 from kacpherek/fix/vanilla-mob-equipment-compass
Tick the compasses mobs hold or wear so a gone lodestone clears their target
2026-11-13 02:54:44 +00:00
rdbt fce155af99 Merge pull request #15634 from kacpherek/fix/vanilla-player-fall-block-sound
Play the block fall sound after a player's damaging fall
2026-11-13 02:54:40 +00:00
rdbt f0d82fdfd4 Merge pull request #15630 from kacpherek/fix/vanilla-item-damage
Hurt dropped items by lightning and explosions through damage_resistant, as vanilla does
2026-11-13 02:54:36 +00:00
rdbt 532f398264 Merge pull request #15629 from kacpherek/fix/vanilla-mending-effect
Pick Mending repair slots by the repair_with_xp effect, as vanilla does
2026-11-13 02:54:31 +00:00
rdbt e8ce5ad796 Merge pull request #15626 from kacpherek/fix/vanilla-powder-snow
Give every mob and a LAN guest's prediction powder snow's contextual collision
2026-11-13 02:54:27 +00:00
rdbt f88e4141b3 Merge pull request #15625 from kacpherek/fix/vanilla-item-use
End item use the way vanilla does: bundle completion, a changed hand item, stopUsingItem paths
2026-11-13 02:54:23 +00:00
rdbt eb17be4d56 Merge pull request #15513 from yahya-nusseibeh/fix/websocket-control-frames
WebSocket: control frames must come whole and short
2026-11-13 02:54:19 +00:00
rdbt cf0ed1d1ad Merge pull request #15442 from Ragbie/fix/windows-open-folder-shell
Windows: open the pack, world and backup folders in the default file manager
2026-11-13 02:54:15 +00:00
rdbt 7f469386ae Merge pull request #15440 from kacpherek/revert/13737-boat-fire
Revert #13737: boats fail the boat_fire harness
2026-11-13 02:54:10 +00:00
rdbt f1fe19a41e Merge pull request #15431 from Detimes/oc-equipment-ids
Older clients through 1.21.6: read equipment in the client's ids
2026-11-13 02:54:06 +00:00
rdbt 3f25aa9af4 Merge pull request #15430 from Detimes/oc-entity-data
Older clients: entity data in their own serializer ids
2026-11-13 02:54:01 +00:00
rdbt 77f66c55e5 Merge pull request #15428 from lucasmts59/fix/core-shader-int-constant-arrays
Core shaders: an array sized by a local int constant takes its expression
2026-11-13 02:53:57 +00:00
rdbt 07244d141b Merge pull request #15426 from kacpherek/fix/13648-crossbow-arrow-hit-sound
A crossbow arrow switches to the arrow hit sound after its first block hit
2026-11-13 02:53:52 +00:00
rdbt 0d83e5950c Merge pull request #15425 from kacpherek/fix/12320-debug-world-type
Offer Debug Mode on the world type button while Alt is held
2026-11-13 02:53:48 +00:00
rdbt 0ffa0ca457 Merge pull request #15203 from darkliro/perf/upload-budget-follows-frame
perf: adapt chunk mesh upload budget to frame pace
2026-11-13 02:53:40 +00:00
rdbt 4a63b64a17 Merge pull request #15128 from MSedgeMC/fix/wololo-visibility-percent
An invisible flag shrinks the wololo range
2026-11-13 02:53:32 +00:00
rdbt d19eb22735 Merge pull request #14901 from MSedgeMC/fix/chat-double-click-word
Double-clicking the chat box selects the word
2026-11-13 02:53:22 +00:00
rdbt d68f973fab Merge pull request #14811 from tarzinio/fix-far-detail-resample
Sample LOD tiles again when Far detail changes
2026-11-13 02:53:15 +00:00
rdbt fe56b24a49 Merge pull request #14642 from JustKarkat/fix/crafting-book-non-craftable-retry
fix: allow retry-clicking non-craftable recipes in the recipe book
2026-11-13 02:53:09 +00:00
rdbt 824b351d69 Merge pull request #14395 from oloion/perf/label-layout-no-alloc
ui: eliminate heap allocations in label layout and measurement
2026-11-13 02:53:05 +00:00
rdbt 3ccb74b6c1 Merge pull request #14294 from MSedgeMC/fix/piglin-cannot-hunt
A piglin keeps its saved CannotHunt flag
2026-11-13 02:53:01 +00:00
rdbt 7b5114bb29 Merge pull request #14268 from Joansitoh/fix/13632-atlas-sprites
Resolve inline atlas sprites in their named atlas
2026-11-13 02:52:55 +00:00
rdbt b7bf1c97c6 Merge pull request #14257 from vnsmoreira/fix/crafter-triggered-int
A crafter keeps its triggered int and triggers only at 1
2026-11-13 02:52:51 +00:00
rdbt d3723c53b5 Merge pull request #13831 from RINNECODER/up13/lang-dead-keys
Game translations: drop 8 keys no code asks for, and check en_us against the code
2026-11-13 02:52:47 +00:00
rdbt 9f42064c11 Merge pull request #15867 from rdbtCVS/fix/pet-owner-teleport-stroll
pet_owner_teleport: a wolf that came may stroll off; count 16 blocks as near
2026-11-13 02:39:12 +00:00
rdbtCVSandClaude Opus 5.5 a13a21c522 pet_owner_teleport: count a wolf within 16 blocks as come to its owner
A tame wolf that teleported to Alice keeps strolling (WaterAvoidingRandomStrollGoal,
up to 10 blocks) and only walks back from 10 blocks, so a few seconds later it can
be 6 to 12 blocks from her, in vanilla as in Horizon. The 6-block check failed on
that at random (#15483; parity-main 43332620951 bisected it to unrelated merges).
Wolves left behind stay 28 blocks or more away.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 02:35:07 +00:00
rdbtCVSandCodex gpt-6.1-sol 06a4eabbc7 Use the game allocator for opted-in tracker measurements
Gate the benchmark allocator behind a dev-only feature so ordinary tests are unaffected, and reject benchmark binaries built without it.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-13 01:57:23 +00:00
rdbtCVSandCodex gpt-6.1-sol e7ab13bd4e Reject serial benchmark environments consistently
Check the serial-all flag case-insensitively and keep the optimized-build guard usable under Clippy.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-13 01:54:29 +00:00
rdbtCVSandCodex gpt-6.1-sol fde6503ca0 Add an opt-in isolated tracker send benchmark
Measure serial and parallel sending on identical threshold and crowd workloads, with packet and event checks outside the timed region. Require an explicit opt-in as well as --ignored so routine tests do not measure performance.

Refs #15858

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-13 01:50:08 +00:00
rdbtCVSandCodex gpt-6.1-sol a5c5c73ef0 Merge main to refresh entity send validation
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-13 01:42:02 +00:00
rdbt 36eb98b6f6 Merge pull request #15815 from rdbtCVS/t3/fix-nightly-parity-regressions
Fix seven parity regressions blocking nightly builds
2026-11-12 23:53:35 +00:00
rdbtCVSandCodex GPT-6.1 a884525213 Align the head cache test with whole-payload texture rejection
Co-Authored-By: Codex GPT-6.1 <[email protected]>
2026-11-12 23:23:18 +00:00
rdbtCVSandCodex GPT-6.1 c35f0ba323 Clarify the authlib reference outside the game port ledger
Co-Authored-By: Codex GPT-6.1 <[email protected]>
2026-11-12 23:04:01 +00:00
rdbtCVSandCodex GPT-6.1 7e6b2db114 Merge main with the manual-proof parity fix
Co-Authored-By: Codex GPT-6.1 <[email protected]>
2026-11-12 22:55:36 +00:00
rdbtCVSandCodex GPT-6.1 768f0ddb83 Fix seven parity regressions blocking nightly builds
Restore vanilla void thresholds, HUD backdrops and profile texture validation; repair the block-event, AI-label, display-name and save-timer harness contracts.

Co-Authored-By: Codex GPT-6.1 <[email protected]>
2026-11-12 22:55:15 +00:00
rdbt 7c1a43138c Merge pull request #15570 from ilguerro/fix/parity-manual-proof-scripts
Leave the six hand-run proof scripts out of parity runs
2026-11-12 22:43:08 +00:00
rdbt 1a62ef7eb8 Merge pull request #15501 from rdbtCVS/t3/mob-turn-hooks-at-build
Mob islands: find mods that hook a mob's turn at build time
2026-11-12 19:45:27 +00:00
rdbtCVSandClaude Opus 5.5 fd448c5dc3 Mob islands: a mod hooking trample or a block contact keeps the mob tick serial
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 19:23:16 +00:00
rdbtCVSandClaude Opus 5.5 e0d0e34ba3 Mob islands: find mods that hook a mob's turn at build time
Replaces the opt-in native_mob_phase_quiet hook, which every existing mod
leaves unanswered, so any native mod kept the mob tick serial. The build
script now looks itself (horizon_mod_api_gen::mob_turn) and tells the
game through HORIZON_MOB_TURN:

- Mixins: the stage record names each injection's target. One into a
  hook a mob's turn calls, or into anything but a native_* hook point,
  keeps the loop serial.
- Trait mods: a staged trait package or its crates defining a function
  named for a hook the turn waits on keeps it serial. Jump and damage
  post are heard at the join, so overriding them doesn't.

A build without that finding but with trait mods stays serial, as before.
This also covers mixin-only bundles, which the opt-in hook never asked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 19:23:16 +00:00
rdbt 4e459bf8e7 Merge pull request #15497 from rdbtCVS/t3/mob-island-bounded-reach
Mob islands: bounded reaches instead of serial fallbacks
2026-11-12 19:23:05 +00:00
rdbt 15f090e126 Merge pull request #15627 from senjinthedragon/cem-rot-radians
Custom entity models read rot_x, rot_y and player_rot_x/y in radians
2026-11-12 19:17:38 +00:00
rdbt f21b83c8b2 Merge pull request #15752 from rdbtCVS/fix/launcher-needless-bool
Launcher: fix Rust 1.100's needless_bool lint that fails main's launcher check
2026-11-12 19:16:28 +00:00
rdbt b929bea501 Merge pull request #15514 from yahya-nusseibeh/fix/launcher-safe-name-devices
Launcher: no Windows device names or disguising marks in downloaded file names
2026-11-12 19:12:32 +00:00
rdbtCVSandClaude Opus 5.5 ed2d455bf1 Launcher: Rust 1.100's needless_bool in is_link_or_junction
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 19:12:27 +00:00
rdbt 6dd6357962 Merge pull request #15555 from KBroneZ/claude/up-12038b
A sulfur cube's emptied body slot is not saved from its earlier NBT (#12038)
2026-11-12 19:11:27 +00:00
rdbt 6416121902 Merge pull request #15614 from Akirabane/fix/management-player-id-whole-uuid
Management protocol: a player id is a whole 8-4-4-4-12 UUID, as vanilla's PlayerDto reads it
2026-11-12 19:11:21 +00:00
rdbt eb8b298f9e Merge pull request #14195 from RLC248/fix/predicate-terms-holder-forms
A predicate's terms may be one holder alone or a tag (part of #12711)
2026-11-12 19:11:13 +00:00
rdbt c5127a8777 Merge pull request #15603 from Akirabane/fix/init-validates-config
horizon-server init: refuse a port or world name that server.toml would refuse
2026-11-12 19:10:06 +00:00
rdbt 911bbf054b Merge pull request #15605 from Akirabane/fix/backup-find-whole-label
horizon-server: restore and backups find a backup by its whole label
2026-11-12 19:10:01 +00:00
rdbt f646074830 Merge pull request #14712 from Skr1zzzz/falling-spawn-lookup
Client: spawning a falling block or TNT no longer walks the whole list
2026-11-12 19:09:56 +00:00
rdbt 5e3b0f03b6 Merge pull request #15599 from Akirabane/fix/idle-kick-not-during-end-credits
Dedicated server: no idle kick while the End poem is showing, as vanilla
2026-11-12 19:09:50 +00:00
rdbt bb64b215fe Merge pull request #15720 from angel2rider/fix/15494-glsl-feature
fix(shaders): compile the GLSL frontend independently
2026-11-12 19:08:36 +00:00
rdbt 779ea29839 Merge pull request #15670 from ilguerro/fix/stonecutter-scroll-reset
Stonecutter: the recipe list goes back to the top when its input changes
2026-11-12 19:08:32 +00:00
rdbt 74fd49ced0 Merge pull request #15596 from Akirabane/test/anticheat-e2e-log-off
anticheat_e2e: log = "" writes no flag log and the checks still act (log-off)
2026-11-12 19:07:21 +00:00
rdbt 8cf76b5ced Merge pull request #15669 from ilguerro/fix/fish-sounds-voice-sting
Fish play their sounds at their voice pitch, and silent fish play none
2026-11-12 19:06:03 +00:00
rdbt 53759e036a Merge pull request #15616 from Akirabane/fix/console-ban-already-banned
Dedicated console: /ban and /ban-ip of someone banned already change nothing, as vanilla
2026-11-12 19:05:57 +00:00
rdbt 950b9fed63 Merge pull request #15655 from TiggerTakkyTTT/fix/flint-steel-double-sound
Fix duplicate flint and steel sounds for guests
2026-11-12 19:05:47 +00:00
rdbtCVSandClaude Opus 5.5 01f8706d10 Mob islands: grouped turns reach no trample or block contact hook
A mob's turn calls native_trample (farmland) and the native_block_* contacts (a content mod's
blocks) from the movement code, on the group's own thread. Like the other hooks that hand a value
back, they are skipped in a grouped turn, and a quiet mod must not hook them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 19:00:49 +00:00
rdbtCVSandClaude Opus 5.5 ba4e4cf377 Mob islands: bounded reaches instead of serial fallbacks
The parallel mob tick (#14457) no longer falls back to serial for pets,
raids, changed speeds, teleporting meals, withers, wardens, the tick
profiler or quiet native mods. Each case gets a bounded reach or joins
the mobs involved into one island:

- Pets: the owner's teleport destination box is a second place of the
  pet's island, so it joins the mobs near its owner and none between.
- Raids: islands() already joins a raid's raiders; verify compares
  mobs without the process-wide hurt counter.
- Speed, jump and flying speed: a per-mob locomotion bound from the
  attributes and effects at their highest, derived in docs/mob-islands.md.
- Teleport consumables: half the item's TeleportRandomly diameter, and
  the body reaches down as far as the mob can fall.
- Wither and warden: the ids they keep are links.
- Native mods: a new opt-in hook, native_mob_phase_quiet; while every
  mod says it is quiet, grouped turns skip the hooks that hand a value
  back and replay living_jump and damage_post at the join, in order.
- Tick profiler: each island thread samples into its own sums, merged
  at the join.

native_hooks.rs may not grow, so mod_sound_ok, mod_particles_ok and
sound_id move unchanged to native_level_effects.rs, their main user.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 19:00:49 +00:00
rdbt c442809fa7 Merge pull request #13970 from horizon-rust/fix/sprite-mcmeta-trailing-text
Read a sprite's .mcmeta up to its first value, as vanilla does
2026-11-12 18:55:59 +00:00
JoansitohandClaude Sonnet 5.5 7528ca15ff Anticheat prediction: a history gap rebases the replay instead of dropping it
When the record no longer kept the ticks or changes the replay hadn't
played (a server that stalled for seconds), or a tick couldn't be played,
guest_replay dropped the replay and the check stayed off until the player's
next teleport. It now starts again from the server's own position for the
guest, excused until the moves agree with the client's again (at most 40
ticks), so the check resumes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 19:49:41 +01:00
rdbtCVSandClaude Sonnet 5.5 af682746e0 Merge main into branch
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 18:40:53 +00:00
rdbtCVSandClaude Sonnet 5.5 f34daa1a75 Merge main into branch
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 18:40:53 +00:00
rdbtCVSandClaude Sonnet 5.5 130d3ce7b6 Merge main into branch
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 18:40:53 +00:00
rdbt 4acdda54f2 Merge pull request #15690 from Akirabane/fix/console-runs-as-server-source
The dedicated console and RCON run as the server's own source, named Server or Rcon, as vanilla's do
2026-11-12 18:40:47 +00:00
rdbt a1c4de50b1 Merge pull request #15607 from Akirabane/fix/management-permission-level-clamp
Management protocol: a permission level is clamped as vanilla's codec reads it
2026-11-12 18:40:41 +00:00
rdbt 3b48fdf7c4 Merge branch 'main' into claude/up-12038b 2026-11-12 18:38:52 +00:00
rdbt 02b94e5b12 Merge branch 'main' into falling-spawn-lookup 2026-11-12 18:38:48 +00:00
rdbt 51a4fe79e6 Merge branch 'main' into fix/fish-sounds-voice-sting 2026-11-12 18:38:44 +00:00
rdbt cd0f850c12 Merge branch 'main' into fix/idle-kick-not-during-end-credits 2026-11-12 18:38:41 +00:00
rdbt 97fc687ceb Merge branch 'main' into fix/console-ban-already-banned 2026-11-12 18:38:38 +00:00
rdbt f7fce57158 Merge branch 'main' into fix/15494-glsl-feature 2026-11-12 18:38:35 +00:00
rdbt fb50a7ad88 Merge branch 'main' into fix/stonecutter-scroll-reset 2026-11-12 18:38:33 +00:00
rdbt db82ec5ba0 Merge branch 'main' into cem-rot-radians 2026-11-12 18:38:30 +00:00
rdbt 0f93711e13 Merge branch 'main' into fix/management-player-id-whole-uuid 2026-11-12 18:38:27 +00:00
rdbt 2524bc9ea2 Merge branch 'main' into fix/sprite-mcmeta-trailing-text 2026-11-12 18:38:24 +00:00
rdbt fcfa91e598 Merge branch 'main' into fix/predicate-terms-holder-forms 2026-11-12 18:38:17 +00:00
rdbt deb3b4fec3 Merge branch 'main' into fix/flint-steel-double-sound 2026-11-12 18:38:15 +00:00
rdbt 3fd1593ca6 Merge branch 'main' into fix/launcher-safe-name-devices 2026-11-12 18:38:09 +00:00
rdbt db7c87c6b5 Merge branch 'main' into fix/websocket-control-frames 2026-11-12 18:38:06 +00:00
rdbt 95d99935ea Merge pull request #15745 from rdbtCVS/fix/studio-needless-bool
CI: fix two Rust 1.100 lints that fail main's verify
2026-11-12 18:37:35 +00:00
rdbtCVSandClaude Opus 5.5 31fc9ce21d CI: two Rust 1.100 lints on main (needless_bool in studio.rs, unreachable_code without audio)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 18:35:26 +00:00
rdbt 72f92a5ef7 Merge pull request #15594 from Akirabane/test/anticheat-timer-tick-rates
Anticheat timer: test the balance at tick rates other than 20
2026-11-12 18:35:11 +00:00
rdbt 914d5e664d Merge pull request #15644 from Akirabane/fix/server-perf-block-s-linux-only
server_perf: build block_s only on Linux, where its only users are
2026-11-12 18:31:55 +00:00
rdbt 23b4c9c411 Merge pull request #15671 from Akirabane/fix/relay-host-ping-schedule
relay: a host is pinged every 20 s whatever joins arrive, so join traffic cannot end a live host
2026-11-12 18:23:58 +00:00
rdbt 95e346c9ad Merge pull request #15586 from Akirabane/test/anticheat-e2e-combat-restart
anticheat_e2e: a player's kicks are kept across a restart (combat-restart)
2026-11-12 18:23:43 +00:00
rdbt 6f478a6cad Merge pull request #13981 from horizon-rust/fix/feed-particles-tadpole-panda-dolphin
Feeding shows its particles: tadpole slime ball, panda love hearts, dolphin treasure
2026-11-12 18:22:36 +00:00
rdbt 737f81c32d Merge pull request #15656 from Akirabane/fix/ban-date-format-as-simpledateformat
Ban and user cache dates are read as vanilla's SimpleDateFormat reads them
2026-11-12 18:22:28 +00:00
rdbt 408c08e029 Merge pull request #15646 from Akirabane/fix/play-cookie-response-disconnects
LAN and dedicated: a cookie response in play disconnects the player, as vanilla
2026-11-12 18:22:22 +00:00
rdbt 44c7007125 Merge pull request #15601 from Akirabane/fix/stopped-op-permission-level
horizon-server: a stopped op and init --op use op-permission-level, as vanilla's op does
2026-11-12 18:22:13 +00:00
rdbt 551cb3a741 Merge pull request #15592 from Akirabane/fix/pause-when-empty-sprint
Dedicated server: a /tick sprint does not count toward pause-when-empty, as vanilla counts it
2026-11-12 18:22:08 +00:00
rdbt 683603fe21 Merge pull request #15564 from Akirabane/fix/login-unexpected-query-answer
LAN and dedicated login: a query answer or cookie response nobody asked for is refused, as vanilla refuses it
2026-11-12 18:22:02 +00:00
rdbt 5b29177859 Merge pull request #15512 from yahya-nusseibeh/fix/query-challenge-cap
Query: cap the challenges held between prunes
2026-11-12 18:21:55 +00:00
rdbt 3d6224deb4 Merge pull request #15503 from Mayonesu0/up-harness-windows
wire_stream harness runs on Windows: natives, console encoding, .exe
2026-11-12 18:21:49 +00:00
rdbt d1613f705f Merge pull request #15674 from Akirabane/fix/negative-block-sequence-dropped
LAN and dedicated: a block use with a negative sequence is dropped, as vanilla's throw drops it
2026-11-12 18:21:41 +00:00
rdbt e78022f152 Merge pull request #15664 from Akirabane/fix/backup-hand-name-not-auto
horizon-server: a backup made by hand cannot take the name auto, which prune deletes
2026-11-12 18:21:36 +00:00
rdbt 5c4cdb41f6 Merge pull request #15580 from Akirabane/test/anticheat-e2e-off-acting-checks
anticheat_e2e: off also covers the checks that act by default
2026-11-12 18:21:27 +00:00
rdbt 3cac36d0f1 Merge pull request #15577 from Akirabane/fix/anticheat-timer-settings-check
Anticheat: refuse a negative or non-finite timer tolerance_ms or max_lag_ms
2026-11-12 18:21:22 +00:00
rdbt 50d2c4f3e8 Merge pull request #15666 from ilguerro/fix/grindstone-damage-component
Refuse grindstone and anvil inputs without a damage component
2026-11-12 18:14:31 +00:00
rdbt 5e89bcee59 Merge pull request #15661 from ilguerro/fix/happy-ghast-cloud-heal
heal a happy ghast in the clouds every second
2026-11-12 18:14:27 +00:00
rdbt 97aa3cf252 Merge pull request #15590 from TiggerTakkyTTT/fix/flat-light-view
Stop flat and debug worlds retrying light views
2026-11-12 18:14:21 +00:00
rdbt 0ae3420fd5 Merge pull request #15509 from yahya-nusseibeh/fix/panel-login-lockout
Panel: wrong login codes no longer lock out the right one
2026-11-12 18:14:15 +00:00
rdbt 20b1949dbd Merge pull request #15498 from Mayonesu0/up-14807-wire-stream-dig-teleport
wire stream: a teleport's answer ticks keep the position reminder on the script's clock
2026-11-12 18:14:10 +00:00
rdbt 5db98af340 Merge pull request #14387 from martipops/agent/pack-options-shell
Pack Options on the settings shell
2026-11-12 18:14:05 +00:00
rdbt 00b3fa3db7 Merge pull request #14168 from MSedgeMC/fix/block-entity-pos-from-tag
A block entity saved in another chunk moves into the chunk that holds it
2026-11-12 18:14:00 +00:00
rdbt 9b2f425f42 Merge pull request #15618 from Bl4ckspell7/refactor/gfx-in-flight-module
Renderer: frames in flight move out of gfx.rs into gfx/in_flight.rs
2026-11-12 18:13:54 +00:00
rdbt a0a2a53279 Merge pull request #15510 from yahya-nusseibeh/fix/prune-spawn-radius-bound
Prune: a spawn radius past i32 keeps everything instead of nothing
2026-11-12 18:13:49 +00:00
rdbt 13d6ba09ad Merge pull request #15460 from Mayonesu0/up-relbinary-save-reload
entity_save_reload: resolve a relative --binary against the caller's directory
2026-11-12 18:13:45 +00:00
rdbt 1352566ab3 Merge pull request #15452 from Ragbie/tests/world-test-lifecycle-forced-chunk
world_test_def_lifecycle reads a chunk only /forceload holds, and runs automatically again
2026-11-12 18:13:40 +00:00
rdbt ca80643fda Merge pull request #14837 from Xmilon/xmilon/dim-sea
Sea level follows the level's generator
2026-11-12 18:13:36 +00:00
rdbt e9faef471e Merge pull request #14595 from martipops/fix/horizon-preset-name
Graphics: Horizon's own preset row is named Horizon Preset
2026-11-12 18:13:30 +00:00
rdbt 7beafea5e1 Merge pull request #15589 from Akirabane/docs/anticheat-three-sentences
docs/anticheat.md: three sentences that disagreed with the code
2026-11-12 18:13:24 +00:00
rdbt 9e840cecfd Merge pull request #15525 from Mayonesu0/up-15484-pufferfish-contact
Sync randoms before each pufferfish mob contact case
2026-11-12 18:13:18 +00:00
rdbt 78f6ac5536 Merge pull request #14930 from Detimes/perf-effect-meta
Perf: memoise the effect particle lookup in the hub
2026-11-12 17:58:06 +00:00
rdbt 5ca5e36230 Merge pull request #14780 from malithedeveloper/fix/atlas-single-sprite-renames
Resource packs: a renamed atlas sprite reads its resource's texture
2026-11-12 17:58:02 +00:00
rdbt 3e5a89b088 Merge pull request #14580 from DUzzL/fix/14454-minecart-shulker
Let rideable minecarts pick up shulkers beside the rail
2026-11-12 17:57:58 +00:00
rdbt 0609305694 Merge pull request #15511 from yahya-nusseibeh/fix/service-unit-paths
Service: refuse paths a systemd unit would misread
2026-11-12 17:57:53 +00:00
rdbt b723023664 Merge pull request #15445 from AlfaRojo/parity/allay-pickup-cooldown-back
allay_pickup_cooldown back in parity runs; the allay healing test reads the pickup cooldown where it lives
2026-11-12 17:57:47 +00:00
rdbt a5f6b3ba0e Merge pull request #14973 from vermingov/fix/goat-horn-byte-14970
A goat's horn flags are read as bytes (#14970)
2026-11-12 17:57:43 +00:00
rdbt 66129b4902 Merge pull request #14590 from DUzzL/fix/14370-fixture-neighbourhood
Load the 5x5 neighbourhood in prepared-data test fixtures
2026-11-12 17:57:38 +00:00
rdbt ac2603ed41 Merge pull request #15529 from rdbtCVS/t3/explosion-detonate-entities
Native mods: native_explosion_entities spares entities from a blast
2026-11-12 17:51:00 +00:00
rdbt 58d42c41ed Merge branch 'main' into fix/feed-particles-tadpole-panda-dolphin 2026-11-12 17:49:13 +00:00
rdbtandCodex gpt-6.1-sol dffce9c48d Merge pull request #15635 from kacpherek/fix/vanilla-baby-piglin-keeps-ingot
Merge #15635 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:47:04 +00:00
rdbtandCodex gpt-6.1-sol 42e897cc73 Merge pull request #15632 from kacpherek/fix/vanilla-enchant-stack
Merge #15632 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:59 +00:00
rdbtandCodex gpt-6.1-sol ebd4205ea6 Merge pull request #15628 from kacpherek/fix/vanilla-gaze-disguise
Merge #15628 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:55 +00:00
rdbtandCodex gpt-6.1-sol 14859c67b7 Merge pull request #15499 from kacpherek/fix/7922-tessellation-fallback
Merge #15499 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:50 +00:00
rdbtandCodex gpt-6.1-sol 542c7c239e Merge pull request #15344 from Web-mc1/fix/item-count-max-stack
Merge #15344 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:45 +00:00
rdbtandCodex gpt-6.1-sol 93d98006a8 Merge pull request #14961 from SamB440/fix/player-rotation-packet-parity
Merge #14961 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:41 +00:00
rdbtandCodex gpt-6.1-sol 12b96b27c3 Merge pull request #14899 from NikitaMGrimm/shader-api-entity-stage
Merge #14899 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:35 +00:00
rdbtandCodex gpt-6.1-sol 5b912979d4 Merge pull request #14758 from ilguerro/perf/worldgen-noise-masks
Merge #14758 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:30 +00:00
rdbtandCodex gpt-6.1-sol e518cb868d Merge pull request #14687 from Mayonesu0/up-14641-stack-components
Merge #14687 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:25 +00:00
rdbtandCodex gpt-6.1-sol 3c1027d1e1 Merge pull request #14684 from vnsmoreira/fix/end-crystal-saved-fall
Merge #14684 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:20 +00:00
rdbtandCodex gpt-6.1-sol ae8e375feb Merge pull request #14578 from ilguerro/fix/jukebox-song-reload
Merge #14578 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:15 +00:00
rdbtandCodex gpt-6.1-sol 7e8805bb61 Merge pull request #14558 from voidsipp/split/11535-pending-entity-provenance-20261109
Merge #14558 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:11 +00:00
rdbtandCodex gpt-6.1-sol fb089da76c Merge pull request #14459 from ilguerro/fix/wither-star-lifetime
Merge #14459 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:06 +00:00
rdbtandCodex gpt-6.1-sol d162b9f5e5 Merge pull request #14349 from Akirabane/feat/7255-particle-frustum
Merge #14349 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:46:02 +00:00
rdbtandCodex gpt-6.1-sol 748c6ba3d5 Merge pull request #14150 from RLC248/fix/thrown-potion-level-entity
Merge #14150 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:45:57 +00:00
rdbtandCodex gpt-6.1-sol 3665978732 Merge pull request #14149 from horizon-rust/layers/extras-tweaks
Merge #14149 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:45:52 +00:00
rdbtandCodex gpt-6.1-sol 5364cb4ebc Merge pull request #14839 from DUzzL/fix/14804-frame-motion
Merge #14839 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:45:45 +00:00
rdbt 855e215c43 Merge branch 'main' into fix/sprite-mcmeta-trailing-text 2026-11-12 17:45:43 +00:00
rdbtandCodex gpt-6.1-sol 7c8f5e38a6 Merge pull request #14663 from vnsmoreira/fix/painting-on-ground
Merge #14663 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:45:39 +00:00
rdbtandCodex gpt-6.1-sol 108bf1dd93 Merge pull request #14258 from vnsmoreira/fix/raw-entity-flags
Merge #14258 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:45:33 +00:00
rdbtandCodex gpt-6.1-sol 3fc31df485 Merge pull request #11261 from Ragbie/fix/hanging-item-stack-config
Merge #11261 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:45:28 +00:00
rdbtandCodex gpt-6.1-sol 633d28079b Merge pull request #14852 from vermingov/fix/evoker-fangs-fall-distance-14847
Merge #14852 after current verify, review, and discussion checks.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-12 17:44:41 +00:00
rdbt e5efe9dc8d Merge pull request #14301 from Ragbie/tools/fall-clip-wait-neighbourhood
vehicle/mob fall clip wait for the forced chunk's 2-column neighbourhood
2026-11-12 17:44:03 +00:00
rdbtCVSandClaude Opus 5.5 2b8ce785e1 Explosions: list the entities for mods only while native mods are loaded
The spared ids are a set, so a blast over many entities stays linear.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 17:27:10 +00:00
rdbt d52edf0341 Merge pull request #15489 from kacpherek/fix/stack-dump-test-race
Fix the stack dump test that fails one verify run in three
2026-11-12 17:22:19 +00:00
Kacper 9925dccf60 Merge branch 'main' into fix/crafter-triggered-int 2026-11-12 18:18:15 +01:00
Kacper 852dcc5416 Merge pull request #14476 from vnsmoreira/fix/vex-no-gravity
A vex turns its gravity off every tick
2026-11-12 18:18:06 +01:00
Kacper 62d8085479 Merge branch 'main' into fix/vex-no-gravity 2026-11-12 17:56:51 +01:00
angel2riderandGPT 6.1 Sol 72627408bc fix(shaders): compile the GLSL frontend independently
Fixes #15494.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-12 16:42:31 +00:00
Kacpherek a660afd3a1 Add a Full Performance graphics preset and make every preset a fixed table
Full Performance sits before Performance: the lowest settings, far terrain off,
opaque ice and a 75% resolution scale. Every preset is now a fixed table, so
picking one after another leaves nothing of the first behind, and every one of
them turns on the optimizations that leave the picture as it is: asynchronous
entity and particle culling, the block-entity caches and GPU Culling's Auto.
2026-11-12 16:35:00 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 9de182a265 docs: say what counts towards the 500-line pull request size
Fixes #15692.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-12 16:00:19 +01:00
AkirabaneandClaude Opus 5.5 91c0bf1f42 Dedicated console and RCON: commands run as the server's source, as vanilla
The console ran each command with no source, so it ran as the player in
place: `/me waves` said "* Player waves", `teammsg` looked for that player's
team, and relative coordinates (`~ ~ ~`) were that player's position. Vanilla's
console source (MinecraftServer.createCommandSourceStack) has no entity, is
at the world spawn's lower corner and is named "Server"; an RCON client's
(RconConsoleSource) is named "Rcon". as_console_in_overworld now runs the line
with the server's source (feedback heard, as command_harness's console does),
and say, me and the operators' line name it "Server" or "Rcon".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:32:55 +01:00
AkirabaneandClaude Sonnet 5.5 c26187a6f0 A use packet with a negative block sequence is dropped before the hub, as in vanilla
ServerGamePacketListenerImpl.handleUseItemOn and handleUseItem call
ackBlockChangesUpTo(sequence) right after the client-loaded check, and it
throws IllegalArgumentException("Expected packet sequence nr >= 0") for a
negative number. The packet processor catches it and only logs "Failed to
handle packet ..., suppressing error": nothing else in the handler runs, the
idle timer is not reset and the player stays. Horizon passed such a packet to
the hub and the game, which used the item or the block. PlayConn::packet now
drops a UseItem or UseItemOn whose sequence is negative.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 14:46:02 +01:00
TiggerTakkyTTTandCodex 5a135748c8 Fix duplicate flint and steel sounds for guests
Co-Authored-By: Codex <[email protected]>
2026-11-12 20:39:38 +07:00
AkirabaneandClaude Sonnet 5.5 5208a5385b Relay: guest joins no longer hold back a host's pings
The relay pinged a host only after ping_every of quiet: every join line it
sent to the host restarted that wait. The host speaks on its control
connection only to answer a ping, so joins arriving less than ping_every
apart for host_timeout left it silent and the relay dropped a host that was
alive, retiring its code (later guests got `ended`). A ping now goes out
every ping_every whatever else is sent meanwhile.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 14:39:32 +01:00
AkirabaneandClaude Sonnet 5.5 d3c30ae2b0 Server: a hand backup cannot take the automatic backups' name
`horizon-server backup auto` wrote `<time>-auto.zip`, byte for byte the name
of an automatic backup, so the next automatic backup's prune deleted it once
it was beyond `keep`, although backups made by hand are never deleted. `auto`
is now refused as a name for a hand backup, with a message saying why; the
automatic backups are named by auto_name, which no longer goes through that
check.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 14:31:33 +01:00
AkirabaneandClaude Opus 5.5 eb44631ea7 Server files: read a ban or cache date's zone as SimpleDateFormat does
BanListEntry and CachedUserNameToIdResolver parse their dates with
SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ROOT). Its zone field
takes +hhmm with hours to 23 and minutes to 59, GMT alone or
GMT+h:mm / GMT-hh:mm, and UTC, in any case, and leaves what follows
unread. parse_date took any four digits after a sign and nothing else,
so "+2400" was a date and "... UTC" was not: an expiry written with UTC
or GMT became a permanent ban.

zone_offset reads the zone that way; the test's values are those
vanilla's own format gave.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 14:30:24 +01:00
Kacpherek eadd0a9b5e Wear a glider held in a hand like a worn one
LivingEntity.updateFallFlying picks at random among every slot (mainhand,
offhand, feet, legs, chest, head) whose stack can glide, not just armor.
2026-11-12 13:57:06 +01:00
Kacpherek a022ef2e01 End an item use through stopUsingItem on shield disable, swap, slot, spectator and portal
Vanilla BlocksAttacks.disable, handlePlayerAction SWAP_ITEM_WITH_OFFHAND,
handleSetCarriedItem (main hand use), ServerPlayer.setGameMode (spectator)
and ServerPlayer.teleport (another dimension) call stopUsingItem, which
posts the item_interact_finish vibration. These paths only cleared the use.
2026-11-12 13:45:46 +01:00
Kacpherek c0def62a4e Stop an item use when the hand holds another item
Vanilla LivingEntity.updatingUsingItem calls stopUsingItem when the
hand's item is no longer the item the use began with, and
releaseUsingItem runs releaseUsing only for the same item (then
stopUsingItem). Remember the starting stack and do the same for the
host's and the guests' uses.
2026-11-12 13:45:46 +01:00
Kacpherek 7c4be249c2 Tick the compasses mobs hold or wear
LivingEntity.aiStep ticks EntityEquipment, which calls
CompassItem.inventoryTick on each equipment stack: a tracker whose
lodestone is gone loses its target. Only the player and armor stands did
this; a mob keeps a compass pointing at a broken lodestone.
2026-11-12 13:45:05 +01:00
Kacpherek 53209c8800 Keep a hit baby piglin's admired gold ingot
PiglinAi.stopHoldingOffHandItem deletes the off-hand gold ingot (without
bartering) only for an adult. A baby tries to equip it, then holds it in
its main hand. stop_admiring dropped it for any age.
2026-11-12 13:43:50 +01:00
Kacpherek 5700ead75f Enchant loot and trade stacks by their own enchantable component
EnchantmentHelper.enchantItem asks the stack for DataComponents.ENCHANTABLE, so
a stack that changed or removed it is not enchanted as the plain item.
2026-11-12 13:43:37 +01:00
Kacpherek e3b03d4adc Read the gaze disguise from the item tag
LivingEntity.PLAYER_NOT_WEARING_DISGUISE_ITEM checks the helmet against
#gaze_disguise_equipment, which Enderman.isBeingStaredBy and the creaking
both use, not the carved pumpkin by name.
2026-11-12 13:43:29 +01:00
Kacpherek 417e700f73 Play the block fall sound after a player's damaging fall
LivingEntity.causeFallDamage calls playBlockFallSound after the fall
sound: the block at floor(y - 0.2F) plays its fall sound at half volume
and three quarters pitch, unless it is air. The event was queued but no
one played it. Carry the block state and play it where the small and big
fall sounds already play: every other player on the server, and the
landing player's own client.
2026-11-12 13:43:24 +01:00
Kacpherek 8801c809a6 Pick Mending repair slots by the repair_with_xp effect
ExperienceOrb.repairPlayerItems takes EnchantmentHelper.getRandomItemWith
(REPAIR_WITH_XP, ...): one entry per enchantment that has that effect and
applies in the slot, not any item with the minecraft:mending id. A data
pack enchantment with the effect now repairs too.
2026-11-12 13:43:09 +01:00
Kacpherek 779cb6ce5e Decide an item's explosion resistance from its damage_resistant
ItemStack.canBeHurtBy reads the stack's damage_resistant component. The nether
star's #is_explosion came from a hard-coded item name, so other stacks with
the component (or a stack that removed it) were handled wrongly.
2026-11-12 13:43:03 +01:00
Kacpherek 720cee852f Hurt dropped items struck by lightning instead of deleting them
Entity.thunderHit calls ItemEntity.hurtServer for 5: the item loses health,
is destroyed at zero (onDestroyed spills contents), and is spared when its
damage_resistant covers lightning_bolt (ItemStack.canBeHurtBy). Share the
stack-aware resistance check the damage command already used.
2026-11-12 13:42:56 +01:00
SenjinandClaude Opus 5.5 387fc29cb8 Custom entity models read rot_x, rot_y and player_rot_x/y in radians
EMF gives them in radians, the entity ones lerped within the tick
(EMFMath.getEntityRX/RY, getPlayerRX/RY). Degrees made a pack's
turn-in-place counter-rotation spin mobs round several times.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 13:42:46 +01:00
Kacpherek 49a1fcfec0 Predict a guest's leather boots on powder snow
The server copy of a guest's body never learned about leather boots, so its
movement check made a guest wearing them sink in powder snow
(PowderSnowBlock.canEntityWalkOnPowderSnow). Set the flag each tick like
the freeze-immune one.
2026-11-12 13:42:02 +01:00
Kacpherek f7cccbd700 Give every mob powder snow's contextual collision
PowderSnowBlock.getCollisionShape asks any entity for its fall distance,
the powder_snow_walkable_mobs tag and leather boots on its feet. Mob moves
passed that only for striders, so foxes, rabbits, endermites, silverfish
and mobs in leather boots sank in powder snow.
2026-11-12 13:41:24 +01:00
Kacpherek e4f3225d7f Complete a bundle's use on its 200th tick
Vanilla LivingEntity.updateUsingItem calls completeUsingItem when the
remaining ticks reach 0 (BundleItem.getUseDuration is 200, no
useOnRelease), so the use sends entity event 9, runs the finish hook and
ends with stopUsingItem's interact vibration. The bundle only cleared the
use.
2026-11-12 13:40:53 +01:00
Bl4ckspellandClaude Opus 5.5 16448c5ff1 refactor(gfx): move frames in flight into gfx/in_flight.rs
gfx.rs is over the 3000-line limit and may not grow, and the 4x terrain MSAA (#15479) adds to it. The impl block from after_submit to take_readback moves unchanged; the five private methods gfx.rs still calls become pub(super).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 13:10:16 +01:00
AkirabaneandClaude Sonnet 5.5 38f23d16e4 A cookie response in the play state disconnects the player, as vanilla does
ServerCommonPacketListenerImpl.handleCookieResponse disconnects with
multiplayer.disconnect.unexpected_query_response, and the vanilla server asks
for no cookie, so every response is unexpected. Horizon decoded the packet and
let the game drop it. PlayConn::packet now answers it with that disconnect, for
the singleplayer owner too (a keep-alive has an owner exemption, this has none).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 13:01:32 +01:00
AkirabaneandClaude Opus 5.5 5b4d583209 Management protocol: a PlayerDto id of 32 undashed digits is refused, as vanilla's codec does
PlayerDto reads its id with UUIDUtil.STRING_CODEC (UUID.fromString):
vanilla answers "Invalid UUID string" for
0123456789abcdef0123456789abcdef (UUIDUtil.LENIENT_CODEC, an int array
or that same string codec, refuses it too). Horizon's parse_uuid also
took the 32 undashed digits; now only the 8-4-4-4-12 form parses.

The test's 32-digit case moves to the refused ones. UUID.fromString's
other forms (five shorter dashed groups, a sign) stay refused here; that
is not in this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 12:55:40 +01:00
AkirabaneandClaude Sonnet 5.5 ebf8069c57 server_perf: build block_s only on Linux, where its only users are
block_s (the sampler's seconds per time block) is called only from the Linux
sampler, `mod linux` of server_perf/samples.rs, which is built for
target_os = "linux". On every other platform clippy with warnings denied
stopped on `function block_s is never used`. It now carries the same cfg as
its users, so Linux builds exactly what it built before.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 12:53:07 +01:00
AkirabaneandClaude Opus 5.5 1751960d36 Dedicated console: /ban and /ban-ip of someone banned already change nothing
BanPlayerCommands.banPlayers skips a player who isBanned, and
BanIpCommands.banIp refuses an address that is, so a second ban keeps the
first one and answers "Nothing changed". The console's own /ban and /ban-ip
relied on UserList::add, which replaces an entry whose reason differs: a
second ban with another reason replaced the first and said "Banned". They now
check isBanned first (Lists::ban and Lists::ban_ip), as the game's /ban does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 12:42:10 +01:00
AkirabaneandClaude Opus 5.5 35e7459102 Management protocol: a permission level is clamped as vanilla's codec reads it
An OperatorDto's permissionLevel and the value of
serversettings/operator_user_permission_level/set are decoded by
PermissionLevel.INT_CODEC: Codec.INT, then PermissionLevel.byId, whose
ByIdMap clamps. So 5 is 4, -1 is 0 and 2.7 is 2; only a non-number is
refused. Horizon answered invalid params for operators/add|set and an
error for the setter.

permission_level() reads it that way for both; the old test that
expected 5 to be refused now expects 4.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 12:41:14 +01:00
AkirabaneandClaude Sonnet 5.5 b942e89cd6 Server: restore and backups find a backup by its whole label
`restore NAME` takes "the name given to `backup` (the newest with it)", but
find matched any file name that ends with `-NAME.zip`, so `restore test`
took a newer `<stamp>-my-test.zip` over the `<stamp>-test.zip` it named, and
`restore auto` or `restore update` could take a hand-made `nightly-auto` or
a `before-update` backup. The label is the whole text between the time
stamp and `.zip`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 12:28:59 +01:00
AkirabaneandClaude Sonnet 5.5 f117ec604a Server: init refuses a port or world name that server.toml would refuse
horizon-server init took its port and world name from a flag or answer and
wrote server.toml without checking them, so `--port 0` or `--world a/b`
gave "Wrote server.toml" and then every run failed to load it (Config::check
refuses port 0 and a world name with a slash, `..`, backups, logs or
.horizon). init now runs Config::check on what it will write, right after
the port is set and before anything else is written, and stops with that
message.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 12:23:22 +01:00
AkirabaneandClaude Sonnet 5.5 34dcda27f0 Server: a stopped op and init --op use op-permission-level
PlayerList.op writes ServerOpListEntry(MinecraftServer.operatorUserPermissions()),
and DedicatedServer.operatorUserPermissions() is the op-permission-level
property. horizon-server's stopped `op` and `init --op` wrote level 4 whatever
the property said; they now write its level (0 to 4, 4 when unset), read as
the game reads it at its next start: server.properties with server.toml's
keys written over it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 12:19:35 +01:00
AkirabaneandClaude Opus 5.5 ee8b7b891a Dedicated server: no idle kick while the End poem is showing
ServerGamePacketListenerImpl.tick kicks an idle player only when
!player.wonGame: a client showing the credits sends no action until it
asks to respawn. Horizon's kick_idle kicked such a player once
player-idle-timeout passed.

The decision moves into idles_out, which also takes the guest's
won_game, so it is tested without a running server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 12:19:16 +01:00
Ludovic Marie f24ee1accf Merge pull request #15361 from UMCEKO/perf-platform
🤖 Agent: queued for merge at Ludovic's request.
2026-11-12 12:12:30 +01:00
9a314a0b5a Fish play their sounds at their voice pitch, and silent fish play none
`Pufferfish.tick` and `AbstractFish.aiStep` go through
`LivingEntity.makeSound`, which plays `Entity.playSound(sound,
getSoundVolume(), getVoicePitch())`: two random draws for the pitch, at the
entity's feet, and nothing when the entity is silent. The raw `Mob::sound`
helper played at eye height, at pitch 1.0, and ignored `Silent`, so a
`{Silent:1b}` pufferfish still blew up and out and a flop never varied.

`Pufferfish.playerTouch` sends `ClientboundGameEventPacket.PUFFER_FISH_STING`
only inside the `hurtServer` branch and only when the fish is not silent; the
sting for the player now comes from there, as a game event for a guest and as
the local play for the host, instead of the fish's AI tick playing it every
tenth tick whether or not any damage landed.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 12:09:41 +01:00
TiggerTakkyTTTandCodex 68ac8880d3 Fix light views for flat and debug worlds
Flat and debug generator protos already contain their decorated columns, so expose a copy for lighting neighbours outside the kept area. This prevents the chunk pump from retrying impossible light-view jobs indefinitely.

Co-Authored-By: Codex <[email protected]>
2026-11-12 18:03:39 +07:00
AkirabaneandClaude Opus 5.5 717b8d192f anticheat_e2e: log = "" writes no flag log and the checks still act (log-off)
docs/anticheat.md says an empty `log` writes no file, and no e2e case set
it. The new log-off case runs a survival server with `[anticheat] log = ""`
and a bot attacking without swinging: it is still kicked, the console still
has the [Anticheat] warning of the kick, and logs/anticheat.log is never
written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 12:02:36 +01:00
AkirabaneandClaude Opus 5.5 7cd92e310d Dedicated server: a /tick sprint does not count toward pause-when-empty
MinecraftServer.tickServer counts a tick as empty only with no player
and no sprint running (ServerTickRateManager.isSprinting), and sets the
count back to 0 otherwise. Horizon counted sprinting ticks, so a sprint
on an empty server reached the pause almost at once and then stayed
stuck: the paused tick does not advance it.

The count moves into count_empty_tick, which also takes the sprint, so
the decision is tested without a running server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:56:24 +01:00
AkirabaneandClaude Opus 5.5 541ef4e5fa Anticheat timer: test the balance at tick rates other than 20
Every timer test ran at 20 ticks a second, although Balance::tick_end takes
1000 / rate ms per client tick and the hub passes the server's rate. The new
test runs a client on time at /tick rate 10 and 60 for ten minutes (never
flagged), 1.5 times as fast (flagged again and again), and 20 ticks a second
on a server at 10 (flagged).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:56:23 +01:00
AkirabaneandClaude Opus 5.5 baa43ddf05 docs/anticheat.md: three sentences that disagreed with the code
- A wrong [anticheat] section makes horizon-server start and run refuse to
  start (the error names the key); it is the game, reading server.toml
  itself, that turns the anticheat off with an error.
- ground bans by default too (ban_after = 2), not only combat.
- A kick or a ban always reaches the console; the log line needs a log file
  (log = "" writes none) and the operators' line needs alerts = true.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:54:45 +01:00
AkirabaneandClaude Opus 5.5 337b8a751c anticheat_e2e: a player's kicks are kept across a restart (combat-restart)
docs/anticheat.md says a check's kicks are counted across sessions and
restarts, but check_combat bans on a second session of the same running
server. The new combat-restart case kicks a no-swing bot once, checks that
anticheat-strikes.json holds one combat strike, stops the server and starts
it again on the same folder, and expects the same bot, cheating again, to be
banned with the count back at 0. start() reuses a folder that is already
there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:44:37 +01:00
AkirabaneandClaude Opus 5.5 f31921a9a3 Anticheat: refuse a negative or non-finite timer tolerance_ms or max_lag_ms
Config::check refused negative thresholds and a prediction tolerance of 0 or
less, but let any [anticheat.timer] tolerance_ms and max_lag_ms through. A
negative tolerance_ms flags a client on time every tick; a max_lag_ms below
-tolerance_ms does too, as the balance rests at the cap; NaN never flags, or
never caps the balance. Both are now numbers of milliseconds from 0 up,
checked by horizon-server before a start and by the game when it reads
server.toml.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:22:56 +01:00
AkirabaneandClaude Opus 5.5 1aa472967f anticheat_e2e: off also covers the checks that act by default
check_off ran only the timer check's 1.5x bot, so nothing showed that
`enabled = false` silences combat and ground, the two checks that drop, kick
and ban by default. It now also runs, on a survival server with allow-flight on
(vanilla's floating kick would end the no-fall bot on its own), the no-swing,
two-target and no-fall bots of check_combat and check_ground: none is flagged,
kicked or banned, no anticheat log is written, and their hits land.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 11:15:04 +01:00
umcekoandClaude Opus 5.5 327daa3899 Merge origin/main into perf-platform
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 13:12:23 +03:00
Riccardo GuerrieroandClaude Opus 5.5 cc1fea2714 Leave the six hand-run proof scripts out of parity runs
tools/parity.py runs every tools/test_*_parity.py with no arguments. Six of
them are two-step proofs that need arguments (a Java side, then a native
side against its reference): builtin_component_delivery,
entity_movement_predicate, guest_close_event, machine_recipe_placement,
predicate_reference_startup and self_pose_metadata. Run bare, each exits
in 0 s with a usage error, so every parity-main run since they landed
(11-07 to 11-09) has failed on them, and the Nightly waits for a green
parity-main.

A script can now declare PARITY_MANUAL = "<how to run it>": parity.py
leaves it out of every run (--changed and parity-main included) and,
asked for it by name, says how to run it. The six declare it; nothing
else about them changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Fekd42tRMKJk8JighAmETj
2026-11-12 11:08:41 +01:00
Kacper f25ac92565 Merge branch 'main' into fix/crafter-triggered-int 2026-11-12 11:08:39 +01:00
Kacper ba91f75cb2 Merge pull request #13731 from TheApple05/fix/13666-chest-boat-loot
Fix chest boat loot for hopper transfers and destruction
2026-11-12 11:08:09 +01:00
AkirabaneandClaude Sonnet 5.5 40ca777682 LAN and dedicated login: refuse a query answer or cookie response nobody asked for
In login_and_configure, while the server waits for LoginAcknowledged, a
CustomQueryAnswer or a CookieResponse was skipped and the login went on to
configuration. Vanilla's ServerLoginPacketListenerImpl.handleCustomQueryPacket
and handleCookieResponse both disconnect with
ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY
(multiplayer.disconnect.unexpected_query_response). The server sends no query
or cookie request at that point (its one query, the proxy forwarding request,
is sent and answered in forward() before LoginFinished), so any answer is
unexpected. It now sends the login disconnect through refuse(), logs the loss
of the connection and ends the login. Those two packets were the only ones the
wait skipped, so it no longer loops: it reads one packet.

Tests: a query answer and a cookie response each get the disconnect and the two
log lines; a login with nothing stray still reaches configuration.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 10:41:16 +01:00
036dc77592 Stonecutter: the recipe list goes back to the top when its input changes
`StonecutterScreen.containerChanged` (StonecutterScreen.java:205-209) resets
`scrollOffs` and `startIndex`, and the screen hangs it on the input container's
listener (StonecutterMenu.java:37-44), so it runs on any change of the input
slot: adding to the stack, a shift-click into it, and taking a result, which
uses one up (StonecutterMenu.java:66). Picking a recipe or clicking in the
player's inventory is not such a change.

Horizon reset only when the input was empty or there were no recipes, and ran
that after every menu session, so a cut left the list scrolled to its last row.
The reset now follows the input slot having changed, as the enchanting table
does, and a server's slot packet for the input runs it too
(AbstractContainerMenu.setItem -> Slot.set -> setChanged).

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 10:40:01 +01:00
Kacper 2a3b142012 Merge branch 'main' into fix/vex-no-gravity 2026-11-12 10:36:57 +01:00
Kacper a2534b622b Merge branch 'main' into fix/crafter-triggered-int 2026-11-12 10:36:49 +01:00
Kacper 5164ada2a6 Merge branch 'main' into fix/13666-chest-boat-loot 2026-11-12 10:36:41 +01:00
Kacper a21f8a3947 Merge pull request #14047 from MrCloudy2/fix/wind-charge-no-deflect-ticks
A player's wind charge can't be turned in its first five ticks
2026-11-12 10:36:19 +01:00
rdbtCVSandClaude Sonnet 5.5 6d3692c673 Keep the geometry-stage note and add a tessellation note
The merged note broke the two tests that read the geometry note; give
tessellation its own note and cover it in the post loader test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 09:26:02 +00:00
AkirabaneandClaude Sonnet 5.5 383b68b576 port map: the frustum rows follow the move and the particle frustum test
Frustum.offset and Frustum.pointInFrustum are now ported (Frustum::pulled_back,
Frustum::contains_point), Frustum.isVisible and Frustum.cubeInFrustum cite the
file Frustum moved to (gfx/view_frustum.rs), and QuadParticleGroup.extractRenderState
names ParticleEngine::render_in_view, which does its frustum point test, so its
"no frustum point test" gap is gone.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 10:22:19 +01:00
KBroneZandClaude Sonnet 5.5 69fdcefa2a fix: a sulfur cube's emptied body slot is not saved from its earlier NBT
mob_to_nbt starts from the entity's earlier saved equipment and only
inserted the body; a body taken off (/item replace ... armor.body with air)
kept its old entry, so /data get still read it. Vanilla writes
equipment.body only while the slot holds something.

Fixes #12038

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 11:22:08 +02:00
rdbtCVSandClaude Sonnet 5.5 59493f4837 Format the block entity order test with rustfmt
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 09:20:12 +00:00
AkirabaneandClaude Sonnet 5.5 0a80c3d42f Test that a particle is culled at its position this tick
kacpherek's commit 061ba23407 made the frustum test read the particle's
position this tick instead of an interpolated one, but no test told the two
apart: the tests' particles all had previous equal to position.

The new test draws at partial 0.5 a particle that is ahead now and was far
behind a tick ago (kept) and one that is behind now and was ahead a tick ago
(dropped). With the test using the interpolated point instead, the first is
dropped and the test fails (left 0, right 4).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 10:17:43 +01:00
Kacper f0811d3363 Merge pull request #14598 from ilguerro/perf/faster-client-lib-tests
Load the prepared test resources once per test process
2026-11-12 09:50:51 +01:00
Kacper c543cb8689 Merge pull request #14596 from Ragbie/fix/orb-fall-distance
Experience orbs keep their fall distance and make a vibration when they land
2026-11-12 09:50:34 +01:00
Kacper 4b65ec8a0d Merge pull request #13578 from NikitaMGrimm/hdr-one-peak
HDR float frame: one peak, the world mastered for 1000 nits
2026-11-12 09:49:46 +01:00
Kacper bb8a15db1e Merge pull request #15359 from Akirabane/fix/guest-invalid-entity-attack-kick
A guest who attacks an item, an orb, themselves or an arrow is disconnected, as handleAttack does
2026-11-12 09:39:18 +01:00
Kacper 555b885429 Merge pull request #14860 from vermingov/fix/cloud-fall-distance-14853
An area effect cloud keeps the fall_distance it was loaded with (#14853)
2026-11-12 09:38:57 +01:00
Kacper 722e63500a Merge pull request #14848 from vermingov/fix/trident-fall-distance-14846
A trident keeps the fall_distance it was loaded with (#14846)
2026-11-12 09:38:40 +01:00
Kacper f1708966d5 Merge pull request #14612 from Solenopsisbot/t3/nameplate-distance-attributes
Client: honor synced nameplate distances
2026-11-12 09:38:23 +01:00
Kacper 7b45eb9614 Merge pull request #13962 from horizon-rust/split/telemetry-probes
horizon-system: the process probes leave horizon-bench (layer plan M5)
2026-11-12 09:33:41 +01:00
805f69c8a9 Refuse grindstone and anvil inputs without a damage component
ItemStack.isDamageableItem needs MAX_DAMAGE, DAMAGE and no UNBREAKABLE
(ItemStack.java:421-423); GrindstoneMenu's two input slots (GrindstoneMenu.java:50-52,
:56-58) and AnvilMenu's repair branches (AnvilMenu.java:133, :151, :157) use it. A
stick patched with max_damage but neither the item's durability default nor an
explicit damage is therefore not damageable, so it can no longer enter the
grindstone, nor merge into a "repaired" copy, nor combine its enchantments with another
such stack on the anvil.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 09:28:59 +01:00
Kacper 911aa6ddc6 Merge pull request #14904 from vermingov/fix/collar-colour-14897
A wolf's or cat's CollarColor outside 0..15 reads white (#14897)
2026-11-12 09:27:07 +01:00
Kacper 5816e84e56 Merge pull request #14822 from DUzzL/fix/14800-arrow-air
An arrow loads and keeps its saved Air
2026-11-12 09:26:50 +01:00
Kacper 1cd6c70899 Merge pull request #14771 from zenith600/launcher/version-file-without-game
Launcher: a folder with 26.3's version file but not its game says to play 26.3 once
2026-11-12 09:26:32 +01:00
Kacpherek d78f0c49c9 Merge main into fix/evoker-fangs-fall-distance-14847 2026-11-12 09:21:51 +01:00
Kacper eb084c5152 Merge pull request #15058 from ilguerro/fix/fox-village-shade-defend-trusted
Keep foxes out of the shade in villages and defending the players they trust
2026-11-12 09:20:15 +01:00
Kacper aa3483bf5a Merge branch 'main' into perf/faster-client-lib-tests 2026-11-12 09:15:37 +01:00
Kacper 23678db4f7 Merge branch 'main' into fix/orb-fall-distance 2026-11-12 09:15:28 +01:00
Kacper 663ba1239c Merge branch 'main' into fix/crafter-triggered-int 2026-11-12 09:15:18 +01:00
Kacper a97725d63c Merge branch 'main' into fix/wind-charge-no-deflect-ticks 2026-11-12 09:15:09 +01:00
Kacper 0ce3cf8624 Merge branch 'main' into hdr-one-peak 2026-11-12 09:14:54 +01:00
Kacper aa548b0a41 Merge branch 'main' into fix/guest-invalid-entity-attack-kick 2026-11-12 09:04:15 +01:00
Kacper cd4e73e270 Merge branch 'main' into fix/collar-colour-14897 2026-11-12 09:04:06 +01:00
Kacper d946b838fe Merge branch 'main' into fix/cloud-fall-distance-14853 2026-11-12 09:03:57 +01:00
Kacper b2d30693b8 Merge branch 'main' into fix/trident-fall-distance-14846 2026-11-12 09:03:48 +01:00
Kacper 8b13f108ef Merge branch 'main' into fix/14800-arrow-air 2026-11-12 09:03:38 +01:00
Kacper a15a3ea50c Merge branch 'main' into launcher/version-file-without-game 2026-11-12 09:03:29 +01:00
Kacper 5ddbaaab62 Merge branch 'main' into t3/nameplate-distance-attributes 2026-11-12 09:03:19 +01:00
Kacper 6c34352b0f Merge pull request #14931 from Detimes/perf-equipment-cache
Perf: convert a guest's equipment only when a stack changed
2026-11-12 08:52:49 +01:00
Kacper 52540d4ff2 Merge pull request #13830 from RINNECODER/up13/camera-armor-stand
Spectator camera: a server's camera on an armor stand holds the view
2026-11-12 08:52:32 +01:00
Kacper f671c935c2 Merge pull request #11190 from Ragbie/fix/tnt-minecart-explosion-power
TNT minecarts keep explosion_power and explosion_speed_factor, and blow with them
2026-11-12 08:52:14 +01:00
Kacper d0c091ae1d Merge branch 'main' into fix/13666-chest-boat-loot 2026-11-12 08:52:13 +01:00
Kacper 11e85c0411 Merge pull request #14784 from MSedgeMC/fix/port-error-tooltip
The LAN port box says why its number is wrong
2026-11-12 08:51:57 +01:00
Kacpherek 2dabcba7dc Merge main into fix/fox-village-shade-defend-trusted 2026-11-12 08:44:32 +01:00
Kacper c94cdb0c76 Merge pull request #14131 from MSedgeMC/fix/component-can_eat
Food and consumable components come from the stack
2026-11-12 08:41:33 +01:00
9303b88c79 heal a happy ghast in the clouds every second
HappyGhast.continuousHeal heals every 20 ticks when
`isInClouds() || precipitationAt(blockPosition()) != NONE`, but Horizon
only asked the precipitation, so a hurt ghast in clear air at the cloud
height healed on the 600-tick interval.

Entity.isInClouds reads the dimension's `visual/cloud_color` alpha (0:
no clouds at all) and `visual/cloud_height` (192.33 in the overworld)
and tests the entity's box against the four blocks above that height.
DimensionFacts now carries both, parsed from the dimension type's
attributes, and MobWorld::in_clouds ports the check; ai_step asks it
before the precipitation, in vanilla's order.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 08:41:23 +01:00
Kacper ecc1570388 Merge branch 'main' into fix/vex-no-gravity 2026-11-12 08:35:38 +01:00
Kacper 8182a33000 Merge pull request #14943 from vermingov/fix/shulker-attach-face-14940
A shulker's AttachFace is narrowed to a byte before the face is picked (#14940)
2026-11-12 08:30:45 +01:00
Kacper dd90805814 Merge branch 'main' into fix/tnt-minecart-explosion-power 2026-11-12 08:30:16 +01:00
rdbtCVSandClaude Opus 5.5 050e90b150 Native mods: native_explosion_entities spares entities from a blast
A new server hook, after native_explosion_detonate: an explosion is about
to hurt and push the entities in its reach, and a mod takes out the ids
to spare (NeoForge's ExplosionEvent.Detonate entity list). Spared
entities are neither hurt nor pushed. Players aren't listed; they keep
native_living_incoming_damage.

native_hooks.rs may not grow, so viewer_changes moves unchanged to
native_menus.rs, beside the menus.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 06:06:39 +00:00
rdbtCVSandClaude Sonnet 5.5 87be63d40a Merge origin/main into portal TNT provenance branch
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 05:57:11 +00:00
Mayonesu0andClaude Opus 5.5 278d0355e9 Sync randoms before each pufferfish mob contact case
The ordinary-AI pufferfish rolls FishSwimGoal on its own random, which
both engines seed from the clock. About one run in ten it started
swimming in one engine only, and its position read failed (#15484).
A sync_randoms step before each fish's summon makes the roll repeat.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 06:52:05 +01:00
Kacper 0c1a839a02 Merge pull request #15192 from MSedgeMC/fix/ibeam
A hovered text field shows the I-beam cursor
2026-11-12 06:49:20 +01:00
Kacper 00f230d640 Merge pull request #13843 from v0ntr3n/fix/thunder-trap-random-streams
Use Level.randValue for thunder strike columns and trap horse RNG for scatter
2026-11-12 06:48:52 +01:00
Kacper 535211eb7e Merge pull request #13966 from horizon-rust/fix/warden-silent-unmount-wither-easy
Wardens: silent ones make no sound, forced riders get off to dig; withers' idle volleys wait for Normal
2026-11-12 06:47:41 +01:00
martipopsandClaude Opus 5.5 83e0929684 Merge upstream main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:47:21 -05:00
rdbtCVSandClaude Sonnet 5.5 e3e866eb41 Merge main into layers/extras-tweaks
Resolves the docs/forking.md and docs/layers.md conflicts: main's rows kept, with game/extras/ in place of game/tweaks.rs.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 05:35:15 +00:00
Kacper d4c59f8c7a Merge pull request #15021 from DUzzL/fix/15013-launcher-ipv4-fallback
launcher: fall back to IPv4 when IPv6 to Microsoft sign-in is dead
2026-11-12 06:34:08 +01:00
Kacpherek a4a529a565 Keep save.rs from growing: the order position comes from save/block_entity_order.rs 2026-11-12 06:31:48 +01:00
Kacper 82f042de20 Merge branch 'main' into split/telemetry-probes 2026-11-12 06:27:32 +01:00
Kacper c351efbab6 Merge branch 'main' into fix/warden-silent-unmount-wither-easy 2026-11-12 06:27:20 +01:00
Kacper 3054963dec Merge pull request #15289 from DUzzL/fix/15276-set-custom-data
Remove empty custom_data after set_custom_data item modifier
2026-11-12 06:27:02 +01:00
Kacper 25a8fab320 Merge branch 'main' into fix/ibeam 2026-11-12 06:26:03 +01:00
Kacper 194c5c2c6c Merge pull request #15217 from GIGABAIT93/docs/index-updated
docs: the index's `updated`, and the fields a reader may rely on (#10562)
2026-11-12 06:25:38 +01:00
Kacper bab03f04db Merge pull request #15170 from MSedgeMC/fix/loot-set-enchantments
Set Enchantments replaces the levels
2026-11-12 06:25:24 +01:00
Kacper 9a71098242 Merge pull request #15061 from DUzzL/fix/15057-egg-breed
Thrown eggs hatch the chicken variant of their item
2026-11-12 06:25:11 +01:00
Kacper 6d76e89de2 Merge pull request #15053 from ilguerro/fix/fox-eat-effects-panda-pickup
Give a fox that eats its food its effects, and credit a panda's pickup
2026-11-12 06:24:20 +01:00
Kacper 609981c352 Merge pull request #14740 from TiggerTakkyTTT/fix/wind-burst-ender-dragon
Fix Wind Burst knockback for the Ender Dragon
2026-11-12 06:24:05 +01:00
Kacper 3aeb206813 Merge pull request #14587 from MSedgeMC/fix/skeleton-never-freezes
A skeleton and a loaded sulfur cube never freeze
2026-11-12 06:23:52 +01:00
Kacper 9bd670d3d3 Merge pull request #14574 from voidsipp/split/11535-sulfur-portal-compile-fix-20261109
Preserve portal blocks in sulfur cube explosions
2026-11-12 06:23:39 +01:00
Kacper 63bd6c914d Merge pull request #14561 from ilguerro/fix/lectern-book-state
Lecterns take a placed book into has_book, gate the comparator on it and post block_change
2026-11-12 06:23:26 +01:00
Kacper ea787a658c Merge pull request #14553 from ilguerro/fix/adventure-sign-place-on
Place a can_place_on block against a sign in adventure mode
2026-11-12 06:23:14 +01:00
Kacper 14e27946ca Merge pull request #15410 from Web-mc1/fix/item-set-count-overflow
Guard item count arithmetic against i32 overflow
2026-11-12 06:20:31 +01:00
Kacper 9639526d6b Merge pull request #15360 from Web-mc1/fix/pvp-held-count-overflow
Guard held item count against u32 overflow
2026-11-12 06:20:18 +01:00
rdbtCVSandClaude Sonnet 5.5 a77e616a14 Merge main into fix/wololo-visibility-percent
Main's Seen already carries invisible (flag or effect) and moved Mob::seen to
mobs/seen.rs; drop the duplicate field and put visibility_percent beside it so
mobs.rs does not grow.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 04:53:29 +00:00
yahya-nusseibehandClaude Opus 5.5 336b647f63 Launcher: no Windows device names or disguising marks in downloaded file names
safe_name let a mod or pack file named CON, NUL.jar or COM1.zip through: on Windows the
joined path names a device, and the rename from its .part file fails or acts on it. It
also let bidirectional and zero-width marks through, so a shown name could read as
another. Both are now refused, like a path separator.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-12 06:43:22 +02:00
yahya-nusseibehandClaude Opus 5.5 65676a7dbd WebSocket: control frames must come whole and short
RFC 6455 5.5 has control frames unfragmented with at most 125 bytes, and Netty's decoder
that vanilla uses fails the connection otherwise. Here a 64 KiB ping was accepted and
echoed, and a fragmented one answered. Both now end the connection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-12 06:35:46 +02:00
yahya-nusseibehandClaude Opus 5.5 f181472b63 Query: cap the challenges held between prunes
Every handshake from a new address added a token, and the map was cleared only every 30 s,
so spoofed UDP handshakes grew it with the packet rate. At 65,536 addresses a new one gets no
answer until the next prune; an address already holding a token still gets a new one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-12 06:33:31 +02:00
yahya-nusseibehandClaude Opus 5.5 875b98b71f Service: refuse paths a systemd unit would misread
service install wrote the server folder and the program path into the unit as they were. A %
in a folder name is a systemd specifier, a line break adds a directive, and a quote or a
backslash changes ExecStart's quoting. Such a path is now refused with a plain message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-12 06:31:43 +02:00
yahya-nusseibehandClaude Opus 5.5 5e177afe1d Prune: a spawn radius past i32 keeps everything instead of nothing
prune_chunks.spawn_radius is a u32 cast to i32, so a value above i32::MAX wrapped negative,
no chunk counted as near spawn and a delete run pruned the spawn area. The radius now
saturates at i32::MAX: as large a radius as asked for, keeping every chunk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-12 06:29:59 +02:00
yahya-nusseibehandClaude Opus 5.5 59972a243d Panel: wrong login codes no longer lock out the right one
Failed logins were counted for everyone and checked before the code, so ten bad /login
requests a minute from anyone who could reach the panel made the owner's own link fail with
429. The limit now applies only to wrong codes; a valid link always signs in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-12 06:28:11 +02:00
Kacper d9b9996a4d Merge pull request #14850 from DUzzL/fix/14806-fire-reset
A mob's negative Fire is reset to 0 on its first tick
2026-11-12 04:54:06 +01:00
Kacper a71f9d3bd3 Merge pull request #11507 from voidsipp/fix/shield-blocking-11338
Fix built-in shield piercing, use statistics and durability
2026-11-12 04:53:39 +01:00
Kacpherek 91e8f91fee Skeleton trap test: the horse's random is an EntityRandom 2026-11-12 04:52:33 +01:00
rdbtCVSandClaude Sonnet 5.5 92eb621473 Merge main into fix/goat-horn-byte-14970
Goat horn flags now read in mobs::goat::read_nbt with the byte-valued rule.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 03:51:12 +00:00
Kacpherek c6544a2311 Foxes do not flee wolves and polar bears while defending
Vanilla gates both avoidance goals on !isDefending(); a defending fox now goes on to the melee attack.
2026-11-12 04:49:41 +01:00
Kacpherek 63ad77a1da Send the drink game event for a fox's drinkable food
A consumable with the DRINK animation posts minecraft:drink instead of minecraft:eat, and the mob game-event forwarding now passes minecraft:drink on.
2026-11-12 04:48:53 +01:00
rdbtCVSandClaude Sonnet 5.5 440a7f0144 Format the held-count fold with rustfmt
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 03:47:32 +00:00
rdbtCVSandClaude Sonnet 5.5 96bb424a7f Format saturating item count arithmetic
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 03:47:18 +00:00
Kacpherek 5cdcbf9812 Accept libtest's singular banner for a one-test parity run 2026-11-12 04:47:15 +01:00
Kacpherek 3cc15c8ba0 Keep enchantments that set_enchantments does not name
Only the supplied enchantments are set, as vanilla does; the others on the stack stay.
2026-11-12 04:44:31 +01:00
Kacpherek 061ba23407 Cull particles by their current position instead of an interpolated one 2026-11-12 04:41:02 +01:00
Kacpherek e983ba70a5 Limit the never-freeze override to Skeleton; the bogged, parched and wither skeleton freeze 2026-11-12 04:39:52 +01:00
Mayonesu0andClaude Opus 5.5 80eca9b7e2 wire_stream harness: run on Windows (natives, console encoding, .exe)
vanilla_client picks the natives jar the launcher's rules keep for this
OS and architecture (natives-windows, natives-windows-arm64, ...) from the
version JSON instead of knowing only macOS and Linux. The JVM writes UTF-8
and the reader replaces stray bytes, so a cp1252/cp850 console no longer
kills it; the log is UTF-8. lab.binary finds horizon-client.exe.

Fixes #15500

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 04:37:34 +01:00
Kacpherek 1a5bea076d Set a placed lectern's has_book before the item's block_state is applied 2026-11-12 04:35:28 +01:00
Kacpherek 672b1cae9a Test that an empty set_custom_data merge adds no custom_data component 2026-11-12 04:33:33 +01:00
Kacpherek af9e445fbd Reject an item template whose count is outside 1 to 99, as vanilla does 2026-11-12 04:33:16 +01:00
Kacpherek 745274bee2 Skip shader programs with a tessellation stage so their fallback is used
A program with a .tcs or .tes stage was loaded as a plain vertex and
fragment program, silently dropping the tessellation stage. Horizon has
no tessellation backend, so skip such a program with a note, as an
unsupported geometry stage already is, and let the fallback chain pick
the next program.

Fixes #7922
2026-11-12 04:33:15 +01:00
Kacpherek f85db126cc Move the player rotation packet handling out of remote.rs so the file shrinks 2026-11-12 04:32:59 +01:00
Kacpherek 9a2135d7b2 Decide whether a sign consumes the click before its commands run 2026-11-12 04:32:31 +01:00
Kacpherek 5ca6902528 Fix the two clippy warnings in the text layout pass 2026-11-12 04:32:28 +01:00
Kacpherek beb77a48e0 Wrap the invalid-port tooltip to 170 pixels like vanilla 2026-11-12 04:31:33 +01:00
Kacpherek 8286150240 Record a moved block entity's load order under its corrected position 2026-11-12 04:31:30 +01:00
Kacper 2abe71ca92 Merge pull request #14589 from MSedgeMC/fix/drowned-fluid-push
A swimming drowned is not pushed by the current
2026-11-12 04:29:17 +01:00
Kacpherek d7a25b8aec Merge commit '571ef142c5' into unstick/14574
# Conflicts:
#	crates/horizon-client/src/game/creatures.rs
#	crates/horizon-client/src/game/explosion.rs
#	crates/horizon-client/src/game/nether_portal.rs
2026-11-12 04:28:26 +01:00
Mayonesu0andClaude Opus 5.5 62eb25aa1d wire stream: a teleport's answer ticks keep the position reminder on the script's clock
compare_answered compared the two clients' answer ticks whole. In dig_teleport
(`tp @s ~ ~ ~`) the answer moves nobody, and LocalPlayer.sendPosition's 20-tick
position reminder stays on the script's clock (ClientPacketListener.handleMovePlayer
resets neither positionReminder nor xLast): it falls on tick 27 in both clients.
When the server answers Horizon a tick later than vanilla (26 vs 27), Horizon's
answer tick carries the reminder and vanilla's doesn't, which the nightly reported
as an extra move_player_pos (#14807).

The answer ticks now compare without their moves, and their moves compare tick for
tick, on the script's clock.

Fixes #14807

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 04:26:06 +01:00
Detimes c6683ed9a2 Merge branch 'perf-equipment-cache' of https://github.com/Detimes/horizon into perf-equipment-cache 2026-11-12 03:21:14 +00:00
DetimesandClaude Opus 5.5 0a484606c9 Merge upstream/main into perf-equipment-cache
Keeps both new tests at the end of hub_tests.rs (main's teleport accept test and the equipment cache test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 03:21:12 +00:00
Kacpherek c497ba5279 Test that an item frame keeps its loaded Motion, OnGround and fall_distance 2026-11-12 04:20:15 +01:00
Kacpherek 98961ccd14 Merge commit '571ef142c5' into unstick/15061
# Conflicts:
#	crates/horizon-client/src/game/creatures.rs
#	crates/horizon-client/src/projectiles.rs
2026-11-12 04:16:58 +01:00
Kacper f787306fce Merge pull request #15457 from svetch/fix/26.3-seventh-republish
Prepare: accept Mojang's seventh 26.3 republish (9f67e10e, index e99f9973)
2026-11-12 04:16:20 +01:00
Kacper d8bf54d1e6 Merge pull request #14494 from vnsmoreira/fix/explosion-creaking-heart-xp
A player's blast awards a natural creaking heart's experience
2026-11-12 04:16:11 +01:00
Kacper f165e7fa29 Merge pull request #15419 from yahya-nusseibeh/fix/launcher-sign-in-bounds
Launcher: bound the sign-in services' interval and lifetimes
2026-11-12 04:16:01 +01:00
Kacper 9d73f6a26a Merge pull request #15151 from MSedgeMC/fix/chiseled-shelf-can-take
fix: a chiseled bookshelf only gives a book to a hopper with room
2026-11-12 04:15:48 +01:00
Kacpherek c2bead90c4 Workflow files as on main: this pull request changes the item count only 2026-11-12 04:14:31 +01:00
Kacpherek e470dac100 Merge remote-tracking branch 'origin/main' into takeover/15410 2026-11-12 04:14:20 +01:00
Kacpherek 6f2a39f578 Merge commit '571ef142c5' into unstick/14642
# Conflicts:
#	crates/horizon-client/src/game/recipe_book.rs
2026-11-12 04:12:33 +01:00
Kacpherek 22bfbbd417 Merge commit '571ef142c5' into unstick/14459
# Conflicts:
#	crates/horizon-client/src/game/item_entities.rs
2026-11-12 04:11:50 +01:00
Kacpherek 523f142977 Merge commit '571ef142c5' into unstick/15428
# Conflicts:
#	crates/horizon-client-render/src/core_shader/glsl_fixups.rs
#	crates/horizon-client-render/src/core_shader/glsl_fixups/tests/mod.rs
2026-11-12 04:10:52 +01:00
Kacper 4a60f12112 Merge pull request #13630 from MSedgeMC/fix/goat-long-jump
A goat keeps its long-jump cooldown in its chunk save
2026-11-12 04:09:39 +01:00
DetimesandClaude Opus 5.5 c950a3dafe Merge the branch's main update from GitHub
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 03:09:32 +00:00
Kacpherek f92b723265 Merge commit '571ef142c5' into unstick/14349
# Conflicts:
#	crates/horizon-client-render/src/particles.rs
2026-11-12 04:06:39 +01:00
Kacpherek fdf5a402aa Merge commit '571ef142c5' into unstick/14901
# Conflicts:
#	crates/horizon-client-render/src/chat_tests.rs
2026-11-12 04:06:31 +01:00
DetimesandClaude Opus 5.5 784eb9f185 Merge upstream/main into perf-effect-meta
Keeps main's new cave_air_tests module next to effect_meta_tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 03:06:17 +00:00
Kacpherek aa71621cae Merge commit '571ef142c5' into unstick/14684
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-12 04:02:32 +01:00
Kacpherek e829142877 Merge commit '571ef142c5' into unstick/14476
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-12 04:02:07 +01:00
Kacper 192be7194f Merge pull request #15120 from MSedgeMC/port_map/farmland-is-near-water
port_map: FarmlandBlock.isNearWater is the water fluid search
2026-11-12 04:01:45 +01:00
Kacpherek 4ae80fa5ea Merge commit '571ef142c5' into unstick/14258
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-12 04:01:23 +01:00
Kacper 5f3caf9be4 Merge pull request #13881 from Skr1zzzz/split-renderer
Move building and adopting the renderer out of game.rs into game/render_settings.rs
2026-11-12 04:00:55 +01:00
Kacper 571ef142c5 Merge pull request #15477 from Ragbie/fix/stack-dump-windows-unused
horizon-threads: stack_dump's Unix-only code no longer fails clippy on Windows
2026-11-12 03:48:06 +01:00
Kacper 21845f7949 Merge pull request #14376 from Joansitoh/fix/14371-rod-neighbours
Lightning rod: a strike updates the front block's neighbours without redstone experiments
2026-11-12 03:46:31 +01:00
Kacper 27a4dc65c9 Merge pull request #14365 from oloion/perf/range-dispatch-binary-search
assets: avoid heap allocation in item model range dispatch binary search
2026-11-12 03:46:19 +01:00
Kacper deaab60ba9 Merge pull request #15418 from yahya-nusseibeh/fix/protocol-inflate-growth
Protocol: grow the inflate buffer instead of reserving the declared size
2026-11-12 03:38:58 +01:00
DetimesandClaude Opus 5.5 4484d84eed Effect particles: cache only the particle type ids, not the colour
An effect's colour comes from the resource packs (set_pack_colors) and a
pack reload replaces it without replacing the hub's SyncData, so a cached
particle kept the old colour. The cache now holds only the registry id of
each particle type; the colour is read on every call. New test: a pack
colour change shows although the id is cached.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 02:37:06 +00:00
Kacper c2c3cea8e3 Merge pull request #15478 from Bl4ckspell7/refactor/gfx-census-module
Renderer: residency and memory figures move out of gfx.rs into gfx/census.rs
2026-11-12 03:33:14 +01:00
umcekoandClaude Opus 5.5 7798130a18 Merge origin/main into perf-platform
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 05:24:24 +03:00
Kacpherek fcf7c70c83 Merge commit '24b778c3b4' into unstick/14131
# Conflicts:
#	crates/horizon-client/src/item_sync.rs
2026-11-12 02:58:34 +01:00
Kacpherek be34bdfd3c Merge commit '24b778c3b4' into unstick/14589
# Conflicts:
#	crates/horizon-client/src/mobs/living_tests.rs
2026-11-12 02:57:18 +01:00
Kacper 09d748f19c Merge branch 'main' into fix/shulker-attach-face-14940 2026-11-12 02:55:48 +01:00
Kacpherek 0cc70624e2 Merge commit '24b778c3b4' into unstick/14663
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-12 02:55:10 +01:00
Kacpherek e72b69caca Merge commit '24b778c3b4' into unstick/14494
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-12 02:54:54 +01:00
Kacpherek 2f113e476a Merge commit '24b778c3b4' into unstick/14257
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-12 02:54:34 +01:00
Kacpherek 166e09f55e Merge commit '24b778c3b4' into unstick/14587
# Conflicts:
#	tools/port_map/game-006.tsv
2026-11-12 02:52:49 +01:00
Kacpherek f48bf07992 Merge commit '24b778c3b4' into unstick/14899
# Conflicts:
#	crates/horizon-client/src/game/native_shaders.rs
#	docs/api/shaders.md
2026-11-12 02:52:46 +01:00
Kacpherek 61c43e5109 Merge commit 'aab654d4e8' into unstick/11507
# Conflicts:
#	crates/horizon-client/src/game/dispense_fixture.rs
#	crates/horizon-client/src/game/shield.rs
2026-11-12 02:19:15 +01:00
Kacpherek 10721b288e Merge commit 'aab654d4e8' into unstick/14848
# Conflicts:
#	crates/horizon-client/src/entity_nbt/trident.rs
#	crates/horizon-client/src/game/trident.rs
2026-11-12 02:17:22 +01:00
Kacpherek 19fa5d003a Merge commit 'aab654d4e8' into unstick/14590
# Conflicts:
#	crates/horizon-client/src/game/item_entities.rs
2026-11-12 02:16:48 +01:00
Kacpherek be9a3c000f Merge commit 'aab654d4e8' into unstick/14822
# Conflicts:
#	crates/horizon-client/src/entity_nbt/projectile_fields.rs
2026-11-12 02:16:25 +01:00
Kacpherek bad917dea7 Merge commit 'aab654d4e8' into unstick/14663
# Conflicts:
#	crates/horizon-client/src/entity_nbt/hanging.rs
2026-11-12 02:14:00 +01:00
Kacpherek bb9d4c2467 Merge commit 'aab654d4e8' into unstick/14860
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-12 02:13:03 +01:00
Kacpherek d9d89df9d8 Merge commit 'aab654d4e8' into unstick/14494
# Conflicts:
#	crates/horizon-client/src/game/explosion.rs
2026-11-12 02:12:20 +01:00
Kacpherek 8604af23c4 Merge commit 'aab654d4e8' into unstick/14294
# Conflicts:
#	crates/horizon-client/src/mobs/piglin.rs
2026-11-12 02:11:45 +01:00
Kacpherek cd1c3ad784 Merge commit 'aab654d4e8' into unstick/14852
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-12 02:10:43 +01:00
Kacpherek 5a5d9f780c Merge commit 'aab654d4e8' into unstick/14131
# Conflicts:
#	crates/horizon-client/src/game/using_item.rs
2026-11-12 02:10:09 +01:00
Kacpherek 344bcdec9a Merge commit 'aab654d4e8' into unstick/15021
# Conflicts:
#	launcher/src/account/tests.rs
2026-11-12 02:07:33 +01:00
Kacpherek 18415b2fbd Merge commit 'aab654d4e8' into unstick/11190
# Conflicts:
#	crates/horizon-client/src/game/minecarts/nbt.rs
2026-11-12 02:05:06 +01:00
Kacper 018f221041 Merge branch 'main' into revert/13737-boat-fire 2026-11-12 02:01:23 +01:00
Kacpherek 9d9edcc5c7 Ask for the busy thread's stack only once it is in the busy frame
The stack dump test asked for the worker's stack as soon as the worker's
handle arrived. The worker could still be inside the channel send that
woke the test thread, so the sample sometimes held no busy frame and the
test failed about one verify run in three.
2026-11-12 02:00:36 +01:00
umcekoandClaude Opus 5.5 474e9eb4c8 Perf: the entity context lines live in the per-mob and per-projectile helpers
creatures.rs may not grow after main moved the mob loop out; end_mob clears the mob's context, Projectile::tick sets its own, and the fangs start with none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 03:59:29 +03:00
Kacpherek b808a25d4b chat_tests: the double click test and the suggestion list test stand apart again 2026-11-12 01:58:33 +01:00
Kacpherek 2b35f4bfc6 Merge remote-tracking branch 'origin/main' into unstick/14901 2026-11-12 01:57:08 +01:00
umcekoandClaude Opus 5.5 9fd3efbf81 Merge origin/main into perf-platform-clean
The mob loop moved into creatures/mob_group.rs; its per-mob sample takes start_mob/end_mob there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 03:53:38 +03:00
Kacpherek 45f36d84e1 Keep reset_unlit_fire before control.rs's test module 2026-11-12 01:36:18 +01:00
Solenopsisbot 8368def6fa Merge remote-tracking branch 'origin/main' into t3/nameplate-distance-attributes
# Conflicts:
#	crates/horizon-client/src/entities.rs
2026-11-12 11:35:51 +11:00
Kacpherek 10004fcd77 Merge remote-tracking branch 'origin/main' into unstick/14850 2026-11-12 01:35:00 +01:00
Joansitoh f8e59c3e3b Merge upstream main into fix/14371-rod-neighbours 2026-11-12 01:31:16 +01:00
Kacpherek 2106fb21d8 Camel pose test: saved entities go back in as pending entities 2026-11-12 01:30:39 +01:00
Kacpherek 4752a44392 Merge remote-tracking branch 'origin/main' into unstick/14558 2026-11-12 01:29:04 +01:00
Kacper 94077f9e66 Merge branch 'main' into launcher/version-file-without-game 2026-11-12 01:15:59 +01:00
Kacper 869df6be8e Merge branch 'main' into fix/atlas-single-sprite-renames 2026-11-12 01:15:51 +01:00
Kacper 10ea380a42 Merge branch 'main' into xmilon/dim-sea 2026-11-12 01:15:08 +01:00
Kacper da19583b0e Merge branch 'main' into fix/14804-frame-motion 2026-11-12 01:14:59 +01:00
Kacper a4bf39fccf Merge branch 'main' into parity/allay-pickup-cooldown-back 2026-11-12 01:13:23 +01:00
Kacper a856c936d6 Merge branch 'main' into tests/world-test-lifecycle-forced-chunk 2026-11-12 01:13:05 +01:00
Kacper 1dcb48e1ec Merge branch 'main' into fix/26.3-seventh-republish 2026-11-12 01:12:39 +01:00
Kacper 79b225758e Merge branch 'main' into up-relbinary-save-reload 2026-11-12 01:12:21 +01:00
Kacper 80570541d0 Merge branch 'main' into fix/goat-long-jump 2026-11-12 01:11:14 +01:00
Kacper 475ea2f6a7 Merge branch 'main' into fix/thunder-trap-random-streams 2026-11-12 01:11:06 +01:00
Kacper f26c009854 Merge branch 'main' into fix/block-entity-pos-from-tag 2026-11-12 01:10:41 +01:00
Kacper 783c5d4bd5 Merge branch 'main' into fix/predicate-terms-holder-forms 2026-11-12 01:10:32 +01:00
Kacper 9108c8ea68 Merge branch 'main' into fix/crafter-triggered-int 2026-11-12 01:10:23 +01:00
Kacper 8c2241221b Merge branch 'main' into agent/pack-options-shell 2026-11-12 01:10:05 +01:00
Kacper fb003e9b48 Merge branch 'main' into fix/horizon-preset-name 2026-11-12 01:08:43 +01:00
Kacper e243b417ec Merge branch 'main' into falling-spawn-lookup 2026-11-12 01:08:27 +01:00
Kacper b0918fb06c Merge branch 'main' into fix/loot-set-enchantments 2026-11-12 01:07:18 +01:00
Kacper 0539295b59 Merge branch 'main' into fix/wololo-visibility-percent 2026-11-12 01:07:08 +01:00
Kacper 702b9e5a6e Merge branch 'main' into docs/index-updated 2026-11-12 01:07:03 +01:00
Kacper 0bdbffccf7 Merge branch 'main' into fix/fox-village-shade-defend-trusted 2026-11-12 01:06:24 +01:00
Kacper e3d11137f6 Merge branch 'main' into fix/fox-eat-effects-panda-pickup 2026-11-12 01:06:15 +01:00
Kacper 783c053601 Merge branch 'main' into fix/15276-set-custom-data 2026-11-12 01:05:54 +01:00
Kacper 1416eb94b9 Merge branch 'main' into fix/pvp-held-count-overflow 2026-11-12 01:05:46 +01:00
Kacper 76a0ded489 Merge branch 'main' into fix/item-set-count-overflow 2026-11-12 01:05:37 +01:00
Kacper 0e06fcffe8 Merge branch 'main' into fix/player-rotation-packet-parity 2026-11-12 01:05:30 +01:00
Kacper d340ac54e6 Merge branch 'main' into fix/chat-double-click-word 2026-11-12 01:05:20 +01:00
Kacper 44699b4c51 Merge branch 'main' into fix/protocol-inflate-growth 2026-11-12 01:05:19 +01:00
Kacper 22b2093962 Merge branch 'main' into fix/14806-fire-reset 2026-11-12 01:05:11 +01:00
Kacper 30aa7c3cd9 Merge branch 'main' into fix-far-detail-resample 2026-11-12 01:04:52 +01:00
Kacper 7a67cce201 Merge branch 'main' into t3/nameplate-distance-attributes 2026-11-12 01:04:46 +01:00
Kacper 11bda3ecc3 Merge branch 'main' into fix/port-error-tooltip 2026-11-12 01:04:43 +01:00
Kacper c187167717 Merge branch 'main' into perf/worldgen-noise-masks 2026-11-12 01:04:34 +01:00
Kacper c26677ed47 Merge branch 'main' into fix/13666-chest-boat-loot 2026-11-12 01:04:14 +01:00
Kacper 7a725b44e8 Merge branch 'main' into fix/wind-burst-ender-dragon 2026-11-12 01:04:06 +01:00
Kacper 09449b8b5a Merge branch 'main' into up-14641-stack-components 2026-11-12 01:03:49 +01:00
Kacper c9fbcbc9c0 Merge branch 'main' into fix/orb-fall-distance 2026-11-12 01:03:41 +01:00
Kacper 3a44c61b5c Merge branch 'main' into fix/jukebox-song-reload 2026-11-12 01:03:26 +01:00
Kacper d1617aa506 Merge branch 'main' into perf/upload-budget-follows-frame 2026-11-12 01:03:24 +01:00
Kacper e3d38ae5bd Merge branch 'main' into fix/lectern-book-state 2026-11-12 01:03:08 +01:00
Kacper adf711981d Merge branch 'main' into split/11535-pending-entity-provenance-20261109 2026-11-12 01:02:59 +01:00
Kacper 58cdf1b551 Merge branch 'main' into fix/adventure-sign-place-on 2026-11-12 01:02:51 +01:00
Kacper b140490175 Merge branch 'main' into fix/vex-no-gravity 2026-11-12 01:02:37 +01:00
Kacper 7244070cdf Merge branch 'main' into fix/end-crystal-saved-fall 2026-11-12 01:02:28 +01:00
Kacper 0c03fe844b Merge branch 'main' into perf-equipment-cache 2026-11-12 01:02:19 +01:00
Kacper 05ed4ff36f Merge branch 'main' into tools/fall-clip-wait-neighbourhood 2026-11-12 01:02:15 +01:00
Kacper e554afd5a3 Merge branch 'main' into fix/13632-atlas-sprites 2026-11-12 01:02:06 +01:00
Kacper ede16abf28 Merge branch 'main' into fix/guest-invalid-entity-attack-kick 2026-11-12 01:01:56 +01:00
Kacper 765595fc00 Merge branch 'main' into fix/thrown-potion-level-entity 2026-11-12 01:01:39 +01:00
Kacper 02b5729038 Merge branch 'main' into fix/wind-charge-no-deflect-ticks 2026-11-12 01:00:51 +01:00
Kacper 071685a3cf Merge branch 'main' into fix/raw-entity-flags 2026-11-12 01:00:35 +01:00
Kacper 54a7673ecc Merge branch 'main' into fix/piglin-cannot-hunt 2026-11-12 01:00:25 +01:00
Kacper 370854a657 Merge branch 'main' into fix/explosion-creaking-heart-xp 2026-11-12 01:00:16 +01:00
Kacper 2e23fd1dd1 Merge branch 'main' into perf/faster-client-lib-tests 2026-11-12 00:59:58 +01:00
Kacper 6d01f74e39 Merge branch 'main' into oc-entity-data 2026-11-12 00:59:01 +01:00
Kacper 44cb065704 Merge branch 'main' into fix/windows-open-folder-shell 2026-11-12 00:58:43 +01:00
Kacper 90827741ae Merge branch 'main' into up13/camera-armor-stand 2026-11-12 00:58:39 +01:00
Kacper 1aef29fada Merge branch 'main' into perf-effect-meta 2026-11-12 00:57:32 +01:00
Bl4ckspellandClaude Opus 5.5 83703c28b2 refactor(gfx): move residency and memory figures into gfx/census.rs
gfx.rs is over the 3000-line limit and may not grow, and the 4x terrain MSAA work adds to it. The impl block from resident_sections to cpu_census moves unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:57:12 +01:00
Kacper f701cc7e5a Merge branch 'main' into oc-equipment-ids 2026-11-12 00:56:57 +01:00
Kacper 80ef919e40 Merge branch 'main' into fix/14454-minecart-shulker 2026-11-12 00:56:26 +01:00
Kacper 1b016ba22e Merge branch 'main' into fix/chiseled-shelf-can-take 2026-11-12 00:55:44 +01:00
Kacper 023cef202f Merge branch 'main' into fix/launcher-sign-in-bounds 2026-11-12 00:55:27 +01:00
Kacper a4c81b629b Merge branch 'main' into up13/lang-dead-keys 2026-11-12 00:55:18 +01:00
Kacper fdc97df507 Merge branch 'main' into split-renderer 2026-11-12 00:55:09 +01:00
Kacper fd7c423476 Merge branch 'main' into perf/range-dispatch-binary-search 2026-11-12 00:54:10 +01:00
Kacper 731699144c Merge branch 'main' into port_map/farmland-is-near-water 2026-11-12 00:54:01 +01:00
Evrim CicekandClaude Opus 5.5 1fc67d4d10 stack_dump: the Unix-only code is unused on Windows without failing clippy
after_handler is only called on the signal path (Linux, Android, Apple),
and the tests' busy thread only serves the test that reads another
thread's stack there: on Windows clippy -D warnings stopped in
horizon-threads, and every build warned about after_handler. The function
takes the same cfg_attr(.., allow(dead_code)) as Watched::thread, and the
test helpers and their imports the test's cfg.

Fixes #15476.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 02:45:58 +03:00
Your Name 59f63a251a Merge remote-tracking branch 'origin/main' into fix/pvp-held-count-overflow 2026-11-12 12:40:48 +13:00
Your Name e745db772e Fix held item count overflow: use saturating_add; drop unrelated CI changes 2026-11-12 12:40:14 +13:00
Your Name ad8e395f3c Merge main into fix/item-count-max-stack 2026-11-12 12:40:00 +13:00
Evrim Cicek 7573ae6a3e Merge remote-tracking branch 'upstream/main' into fix/orb-fall-distance
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
#	crates/horizon-client/src/game/commands.rs
#	crates/horizon-client/src/game/loaded_arrow_shot_tests.rs
#	crates/horizon-client/src/game/remote.rs
#	tools/command_exec_corpus.py
2026-11-12 02:28:46 +03:00
Evrim Cicek f071ffe84b Merge remote-tracking branch 'upstream/main' into tools/fall-clip-wait-neighbourhood 2026-11-12 02:18:39 +03:00
AkirabaneandClaude Sonnet 5.5 525c1c9834 Merge origin/main into feat/7255-particle-frustum
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 00:15:44 +01:00
DetimesandClaude Opus 5.5 627864a666 Merge upstream/main: the effect particle cache moves into SyncData
Main moved Hub::effect_meta into SyncData::effect_meta (read by helper
threads since #14506). The per-(effect, ambient) particle cache follows it:
lan/effect_meta.rs keeps ParticleCache and particle_of, SyncData holds the
cache behind a Mutex and Hub::effect_meta delegates as on main. hub.rs
loses the field and module line instead of growing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 23:08:54 +00:00
umcekoandClaude Opus 5.5 47b40ecd35 Merge remote-tracking branch 'origin/main' into perf-platform-clean
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 02:03:21 +03:00
AkirabaneandClaude Sonnet 5.5 efaac3cdc0 Merge origin/main into feat/7255-particle-frustum
crates/horizon-client-render/src/gfx.rs: this branch moved Frustum into
gfx/view_frustum.rs (kept, with its mod and pub use); main left Frustum as it was
but moved shadow_box into gfx/external.rs, so the old shadow_box beside Frustum
here is dropped.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 00:00:00 +01:00
Kacper 014462436f Merge branch 'main' into docs/index-updated 2026-11-11 23:59:38 +01:00
Kacper 7dffe8983b Merge branch 'main' into fix/15276-set-custom-data 2026-11-11 23:58:31 +01:00
Kacper 789be0131d Merge branch 'main' into fix/item-set-count-overflow 2026-11-11 23:58:07 +01:00
Kacper 54ea398de4 Merge branch 'main' into fix/protocol-inflate-growth 2026-11-11 23:57:50 +01:00
Kacper cccf79f63a Merge branch 'main' into fix/13666-chest-boat-loot 2026-11-11 23:56:45 +01:00
Kacpherek 6c090eb39d Merge commit '3298a6dcd5' into unstick/14590
# Conflicts:
#	crates/horizon-client/src/game/persist.rs
2026-11-11 23:56:32 +01:00
Kacper 4e44044828 Merge branch 'main' into fix/thrown-potion-level-entity 2026-11-11 23:56:20 +01:00
Kacper 0788a51320 Merge branch 'main' into perf/upload-budget-follows-frame 2026-11-11 23:55:46 +01:00
Kacper 59319a8e2d Merge branch 'main' into fix/vex-no-gravity 2026-11-11 23:54:59 +01:00
Kacper 3086bc8910 Merge branch 'main' into fix/end-crystal-saved-fall 2026-11-11 23:54:50 +01:00
Kacper 0c07b18c76 Merge branch 'main' into perf-equipment-cache 2026-11-11 23:54:41 +01:00
Kacpherek 71d150b028 Read the redstone experiments flag from the enabled features in the lightning rod test 2026-11-11 23:54:20 +01:00
Kacper f8cf08849e Merge branch 'main' into fix/guest-invalid-entity-attack-kick 2026-11-11 23:54:18 +01:00
Kacper d78f353156 Merge branch 'main' into fix/wind-charge-no-deflect-ticks 2026-11-11 23:53:15 +01:00
Kacper 632b455a88 Merge branch 'main' into fix/raw-entity-flags 2026-11-11 23:52:59 +01:00
Kacper 4339a77eae Merge branch 'main' into fix/piglin-cannot-hunt 2026-11-11 23:52:50 +01:00
Kacper 6c58b77fed Merge branch 'main' into fix/explosion-creaking-heart-xp 2026-11-11 23:52:41 +01:00
Kacper 0bd65042f2 Merge branch 'main' into perf/faster-client-lib-tests 2026-11-11 23:52:23 +01:00
Kacpherek 4a33f95d69 Merge commit '3298a6dcd5' into unstick/14973
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-11 23:52:10 +01:00
Kacpherek 245d97a312 Close the drowned current test in living_tests 2026-11-11 23:51:47 +01:00
Kacper 0ede61c00a Merge branch 'main' into oc-entity-data 2026-11-11 23:51:27 +01:00
Kacper ba53cff558 Merge branch 'main' into fix/windows-open-folder-shell 2026-11-11 23:51:09 +01:00
Kacpherek eb1fbb151d Merge commit '3298a6dcd5' into unstick/14943
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-11 23:50:58 +01:00
Kacpherek 9aae4a6671 Merge commit '3298a6dcd5' into unstick/14376 2026-11-11 23:50:18 +01:00
Kacpherek 2497c21f48 Merge commit '3298a6dcd5' into unstick/14589 2026-11-11 23:50:17 +01:00
Kacpherek 5cbded2bd9 Merge commit '3298a6dcd5' into unstick/14904
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-11 23:50:15 +01:00
Kacper f8f3d2e043 Merge branch 'main' into oc-equipment-ids 2026-11-11 23:49:23 +01:00
Kacper 4347efb700 Merge branch 'main' into fix/14454-minecart-shulker 2026-11-11 23:48:50 +01:00
Kacper d07604cd8e Merge branch 'main' into up13/camera-armor-stand 2026-11-11 23:48:15 +01:00
Kacper 195dceeb94 Merge branch 'main' into fix/chiseled-shelf-can-take 2026-11-11 23:48:07 +01:00
Kacper 8dc176f4e6 Merge branch 'main' into fix/launcher-sign-in-bounds 2026-11-11 23:47:50 +01:00
Kacper 43685602fc Merge branch 'main' into up13/lang-dead-keys 2026-11-11 23:47:41 +01:00
Kacper 13fe0905ba Merge branch 'main' into split-renderer 2026-11-11 23:47:32 +01:00
Kacper 7d7fa98a44 Merge branch 'main' into perf/range-dispatch-binary-search 2026-11-11 23:46:17 +01:00
Kacper fd2f881a32 Merge branch 'main' into port_map/farmland-is-near-water 2026-11-11 23:46:08 +01:00
SolenopsisbotandCodex c3325b01f3 Client: honor synced nameplate distances
Co-Authored-By: Codex (GPT-6.1 Sol) <[email protected]>
2026-11-12 09:45:10 +11:00
umcekoandClaude Opus 5.5 77b12a46b1 server_profile_e2e: the disconnect step starts once the timed capture's file has arrived
The client refuses a server start while the last file is still coming in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 01:40:12 +03:00
DetimesandClaude Opus 5.5 73e29da806 Merge upstream/main into perf-effect-meta
Resolves the conflict with main (new hub modules chunk_batch and far_tests next to effect_meta).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 22:35:24 +00:00
Kacpherek 59dbb4703d Merge commit '8d44c49cd3' into unstick/14561
# Conflicts:
#	crates/horizon-client/src/game/books.rs
#	crates/horizon-client/src/game/use_hand.rs
2026-11-11 23:31:04 +01:00
Kacpherek fe78b81e88 Merge commit '8d44c49cd3' into unstick/14740
# Conflicts:
#	crates/horizon-client/src/game/dragon.rs
2026-11-11 23:27:19 +01:00
Kacpherek 463855a17c Merge commit '8d44c49cd301632618c5cbe08a792a53b405fbdf' into unstick/14268
# Conflicts:
#	crates/horizon-client-render/src/hud.rs
2026-11-11 23:26:07 +01:00
Mayonesu0andClaude Sonnet 5.5 eb0605533b Resolve the save/reload harness's --binary against the caller's directory
Each server runs with its temporary world as the working directory, so a relative
`--binary target/fast/horizon-client` was looked up under the world and failed even when the
binary existed. Make the path absolute before starting the servers, with a unit test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 23:24:31 +01:00
Kacper 4e86da4a7a Merge branch 'main' into fix/loot-set-enchantments 2026-11-11 23:23:18 +01:00
Kacper e56aceb38a Merge branch 'main' into fix/wololo-visibility-percent 2026-11-11 23:23:09 +01:00
Kacper 98df3549d2 Merge branch 'main' into fix/fox-village-shade-defend-trusted 2026-11-11 23:22:23 +01:00
Kacper 7d256e1766 Merge branch 'main' into fix/fox-eat-effects-panda-pickup 2026-11-11 23:22:14 +01:00
Kacper 1db662da23 Merge branch 'main' into fix/player-rotation-packet-parity 2026-11-11 23:21:29 +01:00
Kacper cf98445e8f Merge branch 'main' into fix/chat-double-click-word 2026-11-11 23:21:11 +01:00
Kacper 012f70508a Merge branch 'main' into fix/14806-fire-reset 2026-11-11 23:21:02 +01:00
Kacper d83dac2429 Merge branch 'main' into fix-far-detail-resample 2026-11-11 23:20:44 +01:00
Kacper 40a5a99ca8 Merge branch 'main' into fix/port-error-tooltip 2026-11-11 23:20:26 +01:00
Kacper ece1d80195 Merge branch 'main' into up-14641-stack-components 2026-11-11 23:19:42 +01:00
Kacper 4a90452d73 Merge branch 'main' into fix/drowned-fluid-push 2026-11-11 23:19:17 +01:00
Kacper 858de11740 Merge branch 'main' into fix/jukebox-song-reload 2026-11-11 23:19:00 +01:00
Kacper 3528b8ce41 Merge branch 'main' into split/11535-pending-entity-provenance-20261109 2026-11-11 23:18:34 +01:00
Kacper b1fb8a4048 Merge branch 'main' into fix/adventure-sign-place-on 2026-11-11 23:18:25 +01:00
Kacper b9abf293aa Merge branch 'main' into fix/14371-rod-neighbours 2026-11-11 23:17:47 +01:00
Kacper 2525ab8ff8 Merge branch 'main' into tools/fall-clip-wait-neighbourhood 2026-11-11 23:17:29 +01:00
Akirabane 54909bf033 Merge remote-tracking branch 'origin/main' into local/W3-02-invalid-attack-kick 2026-11-11 23:13:48 +01:00
Román BenjáminandClaude Opus 5.5 f5a3990fbf Prepare: accept Mojang's seventh 26.3 republish (9f67e10e, index e99f9973)
Fixes #15456.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 23:12:02 +01:00
umcekoandClaude Opus 5.5 3da49d7a02 Perf: the inflation-cap test checks the bomb against the announced cap
Its gzip size depends on the flate2 backend that feature unification picks
(3.7 MB alone, 5.2 MB in a workspace test run); what matters is that the
announced-size cap lets it through, so the inflated cap is what stops it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:58:35 +03:00
umcekoandClaude Opus 5.5 eae9be3b4f Perf: rustfmt the sampler's ring attribute
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:51:16 +03:00
umcekoandClaude Opus 5.5 f21daf7263 Perf: horizon-server report prints a short summary again
On main `horizon-server report` printed the report's text summary; with the
capture it printed only the file's path, and the text form moved to
horizon-perf, which no release ships, so a host on a VPS could not read the
result there. horizon-perf-format, already shipped through the platform,
gets server_brief: the kind and length, TPS and MSPT, CPU, RSS, players,
chunks and entities, and the five heaviest tick phases. The report prints
it before the path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:47:34 +03:00
umcekoandClaude Opus 5.5 21a8b3bff1 Perf: the one-shot Open server retries a failed accept until its deadline
Any accept() error other than WouldBlock ended the server that offers a
capture to the viewer, before the viewer had fetched it: an aborted
connection (ECONNABORTED, common on BSDs and macOS, WSAECONNRESET on
Windows) or a full file table (EMFILE) left Open broken for that click.
Errors now wait 10 ms and try again until the offer's deadline or a cancel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:45:29 +03:00
umcekoandClaude Opus 5.5 1979dc6dc2 Perf: a thread's sampler ring grows when a session needs more
A thread's ring was sized at its first session and kept, but the size a
session needs depends on its Hz, --wall (twice the entries) and the unwind
mode (about 16 KiB per stack copy), so a later capture with --wall or a
higher --hz lost most of its samples to `dropped` (95 of 99 in the new
test). A session now gets a new, larger ring when the thread's is smaller
than it needs. A replaced ring stays allocated for the thread's life, since
a late signal's handler may still hold it; rings only ever grow, so this is
at most a few per thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:44:51 +03:00
darkliro a67a4b9f4b Merge remote-tracking branch 'upstream/main' into perf/upload-budget-follows-frame 2026-11-11 22:44:24 +01:00
umcekoandClaude Opus 5.5 b2df8cee34 Perf: a server profile stops when the guest who asked for it leaves
The requester was keyed by connection id and never cleared on disconnect,
so after the admin's client dropped during an open-ended `profile server
start` everyone got AlreadyRunning until the 600 s window ended, and the
same admin, reconnected under a new id, got NotRunning when stopping. Each
tick's requests now include a stop (reason DISCONNECTED) once the
requester's connection is gone; the file stays in the server's reports/ and
its path is logged, and the slot frees as soon as it is saved, so anyone
(the same admin included) can start again. server_profile_e2e covers the
disconnect and the start after reconnecting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:43:06 +03:00
umcekoandClaude Opus 5.5 ec1fb9a182 Perf: Share uploads again when the receipt's upload is gone
share_saved always reused an existing .hzperf.share.json and only re-pinned
it, so once the upload expired (a temporary one after an hour, a shared one
after 30 days) or was deleted, Share failed for that capture until the
receipt was removed by hand. A 404 or 410 on the pin of a reused receipt now
uploads the capture again, replaces the receipt (still 0600, written beside
and renamed over) and pins the new upload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:40:09 +03:00
umcekoandClaude Opus 5.5 cec503f33e Perf: a typed /profiler goes where its completion came from
with_profiler keeps a server's or mod's own `profiler` node, so the chat
completed the server's command while handle_chat_input still answered
/profiler locally, and the server's command could not be reached. Horizon's
nodes now carry their own command id; a typed /profiler runs locally only
when the chat tree's `profiler` is Horizon's (or there is no server), and
otherwise goes to the server or mod that owns the name. The client's own
buttons keep running locally.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:36:22 +03:00
Kacpherek 8a205c4d53 Merge commit '6cc36c6f3a' into unstick/14758
# Conflicts:
#	crates/horizon-core/src/density/selection.rs
2026-11-11 22:30:33 +01:00
Evrim CicekandClaude Opus 5.5 6980c84dfc parity_hosts: world_test_def_lifecycle runs automatically again
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:29:48 +03:00
Kacpherek 6d72da27f6 Merge commit '6cc36c6f3a' into unstick/14150
# Conflicts:
#	crates/horizon-client/src/game/dispenser.rs
2026-11-11 22:29:30 +01:00
Evrim Cicek 18e01a3ba2 Merge remote-tracking branch 'upstream/main' into tests/world-test-lifecycle-forced-chunk 2026-11-12 00:28:49 +03:00
Kacpherek 68b16245aa Merge commit '6cc36c6f3a' into unstick/14904
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-11 22:27:17 +01:00
umcekoandClaude Opus 5.5 5ccb6cd15b Perf: a server's click can no longer run /profiler on the client
click_command answered any clicked /profiler line itself, so a server's
chat component, book or dialog with run_command "/profiler share" uploaded
the player's last capture after one click. The client's own [Open],
[Share], [Start], [Stop] and retry buttons now carry a client-only click
action that no server text decodes to (as [Folder]'s open_file already
was); a clicked run_command is a plain command again, sent to the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:27:09 +03:00
Kacpherek c994a813ec Merge commit '6cc36c6f3a' into unstick/14590
# Conflicts:
#	crates/horizon-client/src/game/persist.rs
2026-11-11 22:26:54 +01:00
Kacpherek ee18d85a3d Merge commit '6cc36c6f3a' into unstick/14973
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-11 22:26:47 +01:00
Kacpherek 1c7ff0f82d Merge commit '6cc36c6f3a' into unstick/11261
# Conflicts:
#	crates/horizon-client/src/entity_nbt/hanging.rs
2026-11-11 22:26:34 +01:00
Kacpherek 32a43ad647 Merge commit '6cc36c6f3a' into unstick/14943
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-11 22:25:32 +01:00
Evrim CicekandClaude Opus 5.5 8be0fd72d2 world_test_def_lifecycle reads a chunk only /forceload holds
The step's /execute if loaded read the spot's own chunk. The Java oracle's
player isn't ticked, so its tickets stay on the 5x5 chunks around its
spawn, while Horizon's player loads the chunks around wherever it stands:
once GameTestRunner's batch listener released the forced chunks, spots 56
to 104 were unloaded in Java only (4 of 99 records, #15158). The read is
now of chunk x 11, which only /forceload holds and neither player reaches;
both sides see the release at the same step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:25:03 +03:00
Kacpherek 46179fd42e Pack screen: no I-beam on the filter while the Add-pack browser covers it 2026-11-11 22:23:34 +01:00
umcekoandClaude Opus 5.5 91491459d5 Perf: a server part whose last chunk fails to finish still gets its Stop
The merger was taken out before finish(), so when finish() failed the
abandoned part was closed with a fresh merger that had yielded nothing,
and no Stop{DISCONNECTED} was written for a part that began. finish() now
borrows the merger, which keeps what it yielded for cut_short.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:14:36 +03:00
umcekoandClaude Opus 5.5 4cce8f8484 Perf: cap the server's part and take only its own side's fields
A client took whatever size a server announced and inflated every chunk
without limit, and appended fields of any side into the player's capture.
The announced size is now capped at 64 MiB (the share endpoint's own cap),
the inflated part at 512 MiB (the timeline's 256 MiB cap plus the rest of
a 600 s capture; real captures inflate about 3x from 130-230 KB a minute),
and one field at 64 MiB, which also bounds what waits half-arrived. A field
whose message is not side = SERVER, or has no side (an attachment), refuses
the part; what arrived stays with the incomplete warning, as for any part
that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 00:12:29 +03:00
Kacpherek 6e6c114701 Merge commit 'a5df8273bb' into unstick/14558
# Conflicts:
#	crates/horizon-client/src/game/commands.rs
2026-11-11 22:11:36 +01:00
Vinícius Moreira c482d207f0 Merge commit 'c8e1eb66199f696d1a6218fbbaeef1863ce5cc00' into HEAD
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-11 18:08:07 -03:00
umceko c7227eb3f7 Merge remote-tracking branch 'origin/main' into perf-platform-clean
# Conflicts:
#	crates/horizon-client-render/src/gfx/pack_timing.rs
#	crates/horizon-platform/src/lib.rs
2026-11-12 00:03:27 +03:00
Vinícius Moreira 66493ad0a4 Merge commit 'c8e1eb66199f696d1a6218fbbaeef1863ce5cc00' into fix/raw-entity-flags
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-11 17:57:12 -03:00
Vinícius Moreira c3f130ec76 Merge commit 'c8e1eb66199f696d1a6218fbbaeef1863ce5cc00' into fix/vex-no-gravity
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-11 17:57:11 -03:00
Vinícius Moreira 190aa00a63 Merge commit 'c8e1eb66199f696d1a6218fbbaeef1863ce5cc00' into fix/explosion-creaking-heart-xp
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-11 17:57:10 -03:00
Vinícius Moreira 03ed9279f2 Merge commit 'c8e1eb66199f696d1a6218fbbaeef1863ce5cc00' into fix/painting-on-ground
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-11 17:57:08 -03:00
Vinícius Moreira ceb22dff50 Merge commit 'c8e1eb66199f696d1a6218fbbaeef1863ce5cc00' into fix/end-crystal-saved-fall
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-11 17:57:07 -03:00
rdbtCVSandOpenCode 986616a581 test: cover crafter triggered double decoding
Address Akirabane's small follow-up suggestion on PR #14257: pin floor and saturation when a crafter's triggered value loads from a double NBT tag. No production behavior changes.

Co-Authored-By: OpenCode (GPT 6.1 Sol) <[email protected]>
2026-11-11 20:56:41 +00:00
Kacpherek a4e2314c0b Move set_reduced_detail out of lod.rs so the big file does not grow 2026-11-11 21:55:19 +01:00
Kacpherek 2f763d92f6 Merge commit 'd0f5bccf60' into unstick/14811 2026-11-11 21:54:41 +01:00
Kevin RamirezandClaude Opus 5.5 d025af8ef1 allay_pickup_cooldown back in parity runs; the healing test reads the pickup cooldown where it lives
- allay_pickup_cooldown passes on main now (twice locally with prepared
  resources), so it leaves named_only in parity_hosts.json (#15158).
- allays_heal_on_tenth_ticks_without_enabling_noai_work still set and
  read extra.ints[3], which held ITEM_PICKUP_COOLDOWN_TICKS until it
  moved to AllayState::pickup_cooldown: the test fails on main whenever
  prepared resources are present (CI has none, so it skips). It now
  sets and reads the cooldown through allay::set_pickup_cooldown and
  pickup_cooldown.

Part of #15158

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:53:54 -06:00
Kacpherek 4ac7e4ed1c Move the inline atlas sprite lookup out of hud.rs so the big file does not grow 2026-11-11 21:53:16 +01:00
Kacpherek 59f9d5cc79 Merge commit 'd0f5bccf60' into unstick/14268 2026-11-11 21:52:06 +01:00
Kacper b2258c35e7 Merge branch 'main' into fix/loot-set-enchantments 2026-11-11 21:51:09 +01:00
Kacper 852dc6da3e Merge branch 'main' into fix/wololo-visibility-percent 2026-11-11 21:51:06 +01:00
Kacper 90fed51ab1 Merge branch 'main' into fix/fox-village-shade-defend-trusted 2026-11-11 21:50:47 +01:00
Kacper 5de4e1ee74 Merge branch 'main' into fix/fox-eat-effects-panda-pickup 2026-11-11 21:50:43 +01:00
Kacper 682d70268a Merge branch 'main' into fix/player-rotation-packet-parity 2026-11-11 21:50:24 +01:00
Kacper 601d2e24ad Merge branch 'main' into fix/chat-double-click-word 2026-11-11 21:50:16 +01:00
Kacper 6b1f808b13 Merge branch 'main' into fix/14806-fire-reset 2026-11-11 21:50:12 +01:00
Kacper 81336ce7a9 Merge branch 'main' into fix/wind-burst-ender-dragon 2026-11-11 21:50:02 +01:00
Kacper 47e22facbb Merge branch 'main' into fix/drowned-fluid-push 2026-11-11 21:49:56 +01:00
Kacper f2a97a7329 Merge branch 'main' into fix/skeleton-never-freezes 2026-11-11 21:49:52 +01:00
Kacper 1d2b14b01d Merge branch 'main' into fix/14371-rod-neighbours 2026-11-11 21:49:49 +01:00
Kacpherek fdd210261e Revert "Boats: Mth's sine table for steering, dismounts and minecart pushes; lastYd for water entry" (#13737)
Its parity run failed boat_fire (781 of 789 commands): after a boat burns, Horizon leaves an item where vanilla leaves none. The harness does not fail on main without it. Merged by mistake before the author answered; it can come back once boat_fire passes.
2026-11-11 21:47:09 +01:00
Kacpherek fc67e09538 Merge commit 'a5df8273bb' into unstick/14301
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-11 21:46:22 +01:00
Kacpherek 9ccd03e15c Merge commit 'a5df8273bb' into unstick/14687
# Conflicts:
#	crates/horizon-client/src/game/player_equip.rs
#	crates/horizon-items/src/items.rs
2026-11-11 21:43:23 +01:00
Kacpherek b6a22b4d5d Keep the Alt state and the extended preset list out of the big files
game.rs, title.rs and save.rs are over 3000 lines and may not grow: the Alt state lives in
WorldOptions, set from update_modifiers, and WorldPreset::step sits in create_world.rs.
2026-11-11 21:42:49 +01:00
Kacpherek d38f369ade Keep the arrow sound save and load out of entity_nbt.rs
entity_nbt.rs is over 3000 lines and may not grow: the SoundEvent save and load move into
ArrowState methods in arrows.rs.
2026-11-11 21:42:29 +01:00
Kacpherek a45820d34e Merge commit 'a5df8273bb' into unstick/14578
# Conflicts:
#	crates/horizon-client/src/game/jukebox.rs
2026-11-11 21:41:09 +01:00
Kacpherek 4c2306d61d Merge commit 'a5df8273bb' into unstick/14561
# Conflicts:
#	crates/horizon-client/src/game.rs
#	crates/horizon-client/src/game/books.rs
2026-11-11 21:39:53 +01:00
Kacpherek ff08319e96 Merge commit 'a5df8273bb' into unstick/15192
# Conflicts:
#	crates/horizon-client-render/src/widgets.rs
2026-11-11 21:39:52 +01:00
Kacpherek 194ddaa041 Merge commit 'a5df8273bb' into unstick/14553
# Conflicts:
#	crates/horizon-client/src/game/use_hand.rs
2026-11-11 21:39:07 +01:00
Kacpherek 289674508b Merge commit 'a5df8273bb' into unstick/14784
# Conflicts:
#	tools/port_map/client2-015.tsv
2026-11-11 21:36:54 +01:00
Akirabane f2ea985b8d Merge remote-tracking branch 'origin/main' into local/W3-02-invalid-attack-kick 2026-11-11 21:33:47 +01:00
rdbtCVSandGPT 6.1 Sol 1bcc5ec3f9 assets: preserve vanilla range-dispatch binary-search hits
Address kacpherek's request on PR #14365: remove the post-hit tie scan while keeping slice-based search and the short-list upper bound. Extend the existing regression test with 16-entry duplicate and signed-zero lists; expected indices were observed on the JVM and the pinned vanilla method was checked with javap.

Validation: cargo check -p horizon-assets --locked; cargo test -p horizon-assets --locked (53 passed); cargo fmt -p horizon-assets -- --check; cargo clippy -p horizon-assets --all-targets --locked -- -D warnings.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 20:31:36 +00:00
rdbtCVSandGPT 6.1 Sol b9b53a6b06 Remove committed clippy build log
Address the explicit request in review 5863588800. No gameplay or test code changes.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 20:29:11 +00:00
rdbtCVSandOpenAI GPT-6.1 Sol 83583196d4 Merge main into sprite metadata fix
Resolve the shared first_json helper conflict by retaining the generic parser while preserving main's metadata behavior and animation regression test.

Co-Authored-By: OpenAI GPT-6.1 Sol <[email protected]>
2026-11-11 20:23:44 +00:00
rdbtCVSandGPT 6.1 Sol 1c5f7c2d3c Merge main into fix/thunder-trap-random-streams
Address the reviewer request by retaining main's invulnerable_time field rename alongside the PR's RNG changes.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 20:23:21 +00:00
AkirabaneandClaude Opus 5.5 e7922700f0 Check that the guest's attack on the pig hurts it
The attack-checks test only asserted that attacking a pig does not
disconnect the guest. It now also asserts that the pig lost health,
so a normal attack on a mob is shown to still land.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 21:21:23 +01:00
DetimesandClaude Opus 5.5 b11f2ea604 Merge upstream/main into perf-effect-meta
Brings the branch up to date with main for review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 20:20:15 +00:00
DetimesandClaude Opus 5.5 7ad2c3b0bc Merge upstream/main into perf-equipment-cache
Brings the branch up to date with main for review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 20:11:47 +00:00
Evrim CicekandClaude Opus 5.5 80726b9127 desktop: links keep their own opener; a verbatim path gives its plain URI
open_uri on Linux and macOS went through open_folder, which now resolves
the path first, so a link would fail as a missing file: desktop::open_uri
hands it to open / xdg-open as it is. dunce leaves a share (a mapped drive
too) or a path past MAX_PATH as \?\ (UNC); file_uri gave file://%3F/...
for those, which the shell can't open. dunce and open leave horizon-client,
which no longer uses them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 23:07:18 +03:00
LucasandClaude Opus 5.5 b886a382d8 Core shaders: an array sized by a local int constant takes its expression
Vanilla 26.3's oit_sample.glsl sizes an array by a constant declared in
its function (const int targetCount = OIT_COEFF_COUNT / 4;
vec4 coeffSamples[targetCount];), which naga's GLSL front end refuses.
Each such array size takes the constant's expression, from the
innermost scope that declares it. A guarded include pasted twice
declares the same constant twice and still sizes its arrays; two
different expressions for one name in a scope, or more than 256
constants, leave the text as it was.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 21:06:33 +01:00
Evrim CicekandClaude Opus 5.5 2160ff3fe7 Windows: open folders through the shell's file association, not explorer
Blaze3D.openPath hands path.toUri() to SDL_OpenURL, which on Windows is
ShellExecute's open verb, so a folder opens in the default file manager.
The pack folders (packs::open_folder) and the world and backup folders
(world_management::open_folder) started explorer instead. Both now go
through desktop::open_path: a file: URI to ShellExecute on Windows (the
open crate's folder shortcut, SHOpenFolderAndSelectItems, is Explorer's
own), open / xdg-open elsewhere.

Fixes #15259.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 23:00:08 +03:00
Kacpherek 18b0590437 Offer Debug Mode on the world type button while Alt is held
The Create World type button never reached Debug Mode. Vanilla cycles WorldPresetTags.EXTENDED (normal list plus Debug) while Alt is held, and the normal list otherwise.
2026-11-11 20:57:24 +01:00
Kacpherek 14999a6bda Switch a crossbow arrow to the arrow hit sound after its first block
The sound was picked from the weapon on every hit and saved as item.crossbow.hit forever. Vanilla's soundEvent is the crossbow's only until onHitBlock sets entity.arrow.hit.
2026-11-11 20:57:11 +01:00
Kacpherek c52976236b Merge main into pr-14580
# Conflicts:
#	crates/horizon-client/src/game/minecarts.rs
2026-11-11 20:56:50 +01:00
DetimesandClaude Opus 5.5 d72fab3a55 Older clients: the Writer import of step_1_21_6 is test-only
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 19:56:02 +00:00
Kacpherek 8ec11feda8 Merge main into pr-14590
# Conflicts:
#	crates/horizon-client/src/game/last_hurt_by_mob_tests.rs
2026-11-11 20:55:11 +01:00
Kacpherek 983bd56fb5 Merge main into pr-14598
# Conflicts:
#	crates/horizon-client/src/lan/prediction.rs
2026-11-11 20:54:52 +01:00
martipopsandClaude Opus 5.5 3e3ed99fde Merge upstream main into Pack Options on the settings shell
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 14:46:38 -05:00
Kacpherek b61cff5625 Merge main into fix/chiseled-shelf-can-take 2026-11-11 20:44:41 +01:00
Kacpherek 37f6d169d7 Merge main into port_map/farmland-is-near-water 2026-11-11 20:44:26 +01:00
Kacpherek 7b98f70c85 Merge main into fix/15013-launcher-ipv4-fallback 2026-11-11 20:43:13 +01:00
Kacpherek 56b3fbab8c Merge main into agent/pack-options-shell 2026-11-11 20:42:37 +01:00
Kacpherek ac4204f395 Merge main into split-renderer 2026-11-11 20:42:09 +01:00
Kacpherek 1a44550fc8 Merge main into up13/lang-dead-keys 2026-11-11 20:42:01 +01:00
Kacpherek 7714b1d37a Merge main into fix/goat-long-jump 2026-11-11 20:41:46 +01:00
Kacpherek dfcfa1a0db Merge main into fix/hanging-item-stack-config 2026-11-11 20:41:38 +01:00
Kacpherek b045dddfa1 Merge main into fix/tnt-minecart-explosion-power 2026-11-11 20:41:30 +01:00
yahya-nusseibehandClaude Opus 5.5 5f61926401 Launcher: bound the sign-in services' interval and lifetimes
The device-code interval, its expiry and the Minecraft token lifetime came from the services
unchecked; Instant + a huge interval panicked the sign-in thread and left the window on the
code. The interval is clamped to 1-60 s (slow-down too), the device code's expiry to an hour
and the token lifetime to a week, all added with saturating_add.

Split out of #15247 at review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 21:31:24 +02:00
Detimes 09fdcaf8db Older clients: entity data in their serializer ids
(cherry picked from commit 159e992cd6, without the local recipe drop)
2026-11-11 19:24:03 +00:00
Detimes 277f388e26 Older clients through 1.21.6: read equipment in the client's ids
1.21.6's step (the saddle slot) read set_equipment, already in the client's item and component ids, as pinned
ids, so the first equipment with a component disconnected every client through 1.21.6 ("NBT at byte 1: unknown
tag type"). It reads and writes the stacks in the client's ids now; a session test sends equipment with
components to every older release.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 2dc378ce5b05a6dbb8dad635490e0fc86d73d183)
2026-11-11 19:24:03 +00:00
yahya-nusseibehandClaude Opus 5.5 98b40e8e5e protocol: grow the inflate buffer instead of reserving the declared size
A compressed frame declares its uncompressed size up front, and the inflater reserved that
much at once: a few bytes declaring 8 MiB made the reader allocate 8 MiB per frame. The
buffer now grows as output arrives (capped by DEFLATE's ~1032:1 ratio), so a lying frame
is refused after a small allocation and a real large body still inflates whole.

Split out of #15249 at review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-11 21:16:47 +02:00
RLC248 1759cc1565 Merge remote-tracking branch 'upstream/main' into fix/thrown-potion-level-entity 2026-11-11 19:55:13 +01:00
Web-mc1 c93c23248a Guard item count arithmetic against i32 overflow 2026-11-12 07:45:27 +13:00
Web-mc1 fbfa055eff Guard item count arithmetic against i32 overflow 2026-11-12 07:40:58 +13:00
umceko fb85eb77e0 Merge remote-tracking branch 'origin/main' into perf-platform-clean
# Conflicts:
#	crates/horizon-client/src/game/creatures.rs
2026-11-11 21:18:57 +03:00
umcekoandClaude Opus 5.5 a3efbe017d profile_client_e2e: the stop line reads "Profile saved" since the chat redesign
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 21:18:38 +03:00
Web-mc1 b610bc7618 Guard held item count against u32 overflow 2026-11-12 07:15:10 +13:00
Web-mc1 b082e400c6 Guard held item count against u32 overflow 2026-11-12 07:09:38 +13:00
AkirabaneandClaude Opus 5.5 9a267cf4bf Disconnect a player who attacks an item, an orb, themselves or an arrow
ServerGamePacketListenerImpl.handleAttack disconnects a player whose
attack names an ItemEntity, an ExperienceOrb, the player itself or an
AbstractArrow that is not isAttackable, with
multiplayer.disconnect.invalid_entity_attacked, after the world border,
attack range and PIERCING_WEAPON checks. A hosted or dedicated Horizon
server let the attack end without a word.

handleAttack's checks before Player.attack move to
game/lan_actions/attack_checks.rs: the border and range checks
guest_attack already did, then that test. An arrow's isAttackable reads
#minecraft:redirectable_projectile from the tags the players were sent,
so a data pack that adds arrows to it keeps them attackable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 18:56:15 +01:00
Web-mc1 b7414749eb Clamp NBT item count to prevent oversized stacks 2026-11-12 06:35:15 +13:00
Oloion d1d6b41685 ui: avoid heap allocations in design-system label layout 2026-11-11 19:58:16 +03:00
umcekoandClaude Opus 5.5 239b96621a Performance platform: files over 3000 lines don't grow
The pass timing switches and readings and the world pass helpers move
from gfx.rs to gfx/pass_timing_api.rs, the streamer's queue census and
job_stats to streaming/, Horizon's mark sprite to mark_sprite.rs, and
`horizon-ctl lan op` to game/lan_op.rs. A guest's plugin channel
routing moves beside horizon_channel, the client takes the profile
channel's replies before handle_packet, and tick_profile starts and
ends a mob's tick for both the sampler and the mob costs. The server
bench test reads the saved line the server prints now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 19:53:39 +03:00
RLC248 ffb455858e Merge remote-tracking branch 'upstream/main' into fix/thrown-potion-level-entity
# Conflicts:
#	crates/horizon-client/src/game/tnt.rs
2026-11-11 17:21:25 +01:00
umcekoandClaude Opus 5.5 08b55819b1 Performance platform: leave out what is not the profiler
Removes the fork's review and claim tooling and its docs, and the scene
corpus, which the design keeps separate (an input fixture, not a
measurement). The design doc describes the viewer and upload API in
horizon-rust/horizon-site and drops the planning sections; tests and
doc comments point at playhorizon.dev and horizon-site. The debug keys'
comment is upstream's again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 18:21:33 +03:00
umcekoandClaude Opus 5.5 d27e19390d Merge upstream main into the performance platform
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 18:18:28 +03:00
Umut Cevdet Koçak ad491915a5 Merge pull request #280 from sunrise-org/perf-idle-cost
Profiler docs: idle hooks' cost within the margin of error
2026-11-11 18:16:50 +03:00
umcekoandClaude Opus 5.5 f356ceda41 Profiler docs: the idle hooks' cost is within the margin of error
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 18:14:56 +03:00
Riccardo Guerriero 09b8b5b94b Merge origin/main into perf/faster-client-lib-tests 2026-11-11 15:57:05 +01:00
GIGABAIT93andClaude Opus 5.5 dc064e4bb1 docs: broken_on picks a version, it isn't only shown
A reader skips a version broken on the player's Horizon commit for an
older one that builds; only downloads, stars and updated are for show and
sort. None of the four is checked against a downloaded file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 16:21:50 +02:00
DUzzL c741fd4d39 Remove empty custom_data after set_custom_data item modifier 2026-11-11 15:04:13 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 ca1c65d957 Shader API 0.2: an entity-only pack may ask for its shadow map and lights
`[shadow]`, `[[lights]]` and `[[particle_lights]]` were refused without a
`[material]` (or, for the shadow, a `[[post]]`), though the entity stage reads
the shadow maps and the coloured lights too. A 0.2 pack with only `[entity]`
had to add a stage it didn't want. The three checks now take `[entity]` as a
stage that reads them; 0.1 keeps its rules, and its two light messages are
reworded with the same meaning.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 14:41:12 +01:00
DUzzL 64fc971ebc Honor an egg's explicit chicken variant removal before the item default 2026-11-11 14:39:38 +01:00
Nikita Maximilian Grimm d580bddaec Merge remote-tracking branch 'origin/main' into shader-api-entity-stage 2026-11-11 14:39:22 +01:00
GIGABAIT93andClaude Opus 5.5 c6e83d5f09 docs: the index's updated, and the fields a reader may rely on
`projects[].updated` is the date of a project's newest version, set by the
registry's publish job (horizon-rust/horizon-mods#683). While the index is
preview, a reader may rely on every field but the publish job's four
(`downloads`, `stars`, `updated`, `broken_on`), which may be absent at any
time. Point (3) of #10562.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 15:10:46 +02:00
rdbtCVSandGPT 6.1 Sol 8c893c55f0 Merge main into split-renderer to pick up deterministic CI fixture
Preserve the contributor's renderer extraction unchanged while including main's fix for the Git maintenance race in test_git_slim. The diff against main remains the same four moved methods and port-map citation.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 11:59:51 +00:00
rdbtCVSandGPT 6.1 Sol caf5e9b7d6 Merge main to pick up the upstream CEM compile fix
Includes main fix 04b53013c8 without unrelated local code edits; preserves the contributor history and translation-only PR diff.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 11:42:22 +00:00
Ludovic MarieandClaude Opus 5.5 7fd46c83e5 perf: adapt chunk mesh upload budget to frame pace
High-framerate gameplay (e.g. 144Hz - 300+ FPS) suffers from micro-stutters
when chunk mesh uploads are capped by a flat 2 ms time budget, because 2 ms
can represent 30% to 60% of an entire frame interval (which is ~3.3 ms to
~6.9 ms).

This commit introduces dynamic frame-paced upload budgeting:
- Computes an exponentially smoothed frame time.
- Budgets mesh uploads dynamically to at most 25% of recent frame time.
- Enforces a 250 µs floor and scales up to a 2 ms ceiling when a backlog
  of pending uploads accumulates.
- Preserves the higher 6 ms allocation during initial terrain arrival
  (world open or teleportation).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 12:27:15 +01:00
MSedgeMC 08e01dc3da port_map: EditBox.handleCursor's I-beam 2026-11-11 10:37:18 +00:00
MSedgeMC c289d208e6 test: a hovered text field asks for the I-beam cursor
Not hovered asks nothing; hovered asks Ibeam; a read-only one asks NotAllowed.
2026-11-11 10:37:18 +00:00
MSedgeMC 84d6e3d97a fix: a hovered text field shows the I-beam cursor
EditBox.handleCursor requests CursorTypes.IBEAM while hovered and editable, and
NOT_ALLOWED when it takes no text. Horizon's cursor set had no I-beam, and the
pack screen's search boxes and the settings shell's search never asked for one.
widgets::text_cursor adds it, the two screens call it where their fields are
drawn, and the client maps Cursor::Ibeam to CursorIcon::Text.
2026-11-11 10:36:57 +00:00
MSedgeMC 7f0f9337f3 port_map: Set Enchantments replaces the levels 2026-11-11 09:52:12 +00:00
MSedgeMC 7d011d64aa test: Set Enchantments replaces the levels 2026-11-11 09:52:12 +00:00
MSedgeMC 4ea481cb2f fix: Set Enchantments replaces the levels 2026-11-11 09:52:12 +00:00
rdbtCVSandGPT 6.1 Sol 2962f1172d Merge main into #11261, preserving hanging stack-config coverage
Resolve the corpus registration conflict without changing any main group or hanging-config operation. Restore the BoatItem.use documentation to place_boat.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 08:49:19 +00:00
MSedgeMC 30e4e488b2 port_map: ChiseledBookShelfBlockEntity.canTakeItem asks the target's room
The hopper's path applies the `hasAnyMatching` rule through
`can_take_into`.
2026-11-11 08:49:01 +00:00
rdbtCVSandGPT 6.1 Sol b2095cc1ca Merge current main into TNT minecart explosion fix
Preserve the contributor's TNT power change and the minecart extraction already on main. Git resolved both touched files without manual conflict edits. The net change against main is three files (+82/-2).

Validation: rustfmt, public-tree, layer/file-size checks and three command-fixture Python tests pass. The focused Rust test attempt failed in sccache before compiling Horizon; vanilla resources and the port ledger are unavailable, so gameplay proof remains outstanding.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-11 08:42:36 +00:00
MSedgeMC e2ee8ad7d9 test: a full hopper cannot take a book from a chiseled shelf
`a_full_hopper_cannot_take_a_book_from_a_chiseled_shelf` asks the rule
with a hopper full of stone (false) and an empty one (true). Without the
shelf rule both answer true.
2026-11-11 08:40:34 +00:00
MSedgeMC c59a4d6ffd fix: a chiseled bookshelf only gives a book to a hopper with room
`ChiseledBookShelfBlockEntity.canTakeItem` is
`target.hasAnyMatching(other -> other.isEmpty() || (same item and
components && other.count + stack.count <= target.getMaxStackSize(other)))`:
a hopper may take a book only when it has a free slot or a matching stack
with room.

Horizon's `Containers::can_take` had no shelf rule, so a full hopper
still pulled a book out (and put it back). The hopper's path now asks
`can_take_into`, which applies the shelf rule before the existing checks.
2026-11-11 08:40:13 +00:00
TiggerTakkyTTTandCodex 866057db34 Merge upstream/main into fix/wind-burst-ender-dragon
Co-Authored-By: Codex <[email protected]>
2026-11-11 15:30:28 +07:00
MSedgeMC 2d216e9c78 port_map: the wololo row names the visibility it scales by
The row said "scaled by visibility" while the code used the two extremes of
the invisibility effect; it now names `getVisibilityPercent`, the flag or the
effect, and the 0.07 factor.
2026-11-11 06:30:32 +00:00
MSedgeMC 182cbc1a5c test: a flagged invisible blue sheep is out of wololo range at fourteen
Two evoker wololo casts in a real goal selector, with a blue sheep 14 blocks
away: the visible sheep starts `UseSpell`, the same sheep with `invisible: true`
does not. Without the visibility-scaled range both are picked, `[true, true]`
against `[true, false]`.

The existing five-block test with the invisibility effect still passes: the
effect counts beside the flag.
2026-11-11 06:30:25 +00:00
MSedgeMC ea783f5db0 fix: a wololoed sheep's range scales by its visibility
`Evoker$EvokerWololoSpellGoal` finds its blue sheep with
`TargetingConditions.forNonCombat().range(16)`, and `TargetingConditions.test`
scales that range by `LivingEntity.getVisibilityPercent` with a floor of 2.
Horizon asked `has_effect("invisibility")` and used the two extremes, so a
sheep with the `invisible` entity flag and no effect stayed in range at
sixteen blocks where vanilla's percent is 0.07 and the range 1.12, floored to
2.

`Seen` now carries `invisible` (`Entity.isInvisible`) and answers
`visibility_percent`, the mob half of `getVisibilityPercent`: 1, or
0.7 x armor cover (at least 0.1) while invisible - a mob does not sneak and its
`getArmorCoverPercentage` is 0, so 0.07. The effect counts beside the flag
because vanilla's `updateInvisibilityStatus` copies it into the flag each tick
and Horizon has no port of that yet. The wololo filter uses it.

`Seen.invisible` is the same field #13755 adds for follow-mob goals; whichever
lands second takes the other's line.
2026-11-11 06:29:14 +00:00
MSedgeMC fb05c1acfc port_map: FarmlandBlock.isNearWater is the water fluid search
Vanilla's predicate is `state.getFluidState().is(FluidTags.WATER)`, which
the inline 9x2x9 search already matches; the row's `canBeHydrated` gap
was wrong.
2026-11-11 05:02:45 +00:00
MSedgeMC a2cdad2a10 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:17 +00:00
MSedgeMC 53e8715d83 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:53:14 +00:00
MSedgeMC 31bf00a458 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-11 03:52:55 +00:00
Vinícius Moreira 306dca0a21 Merge remote-tracking branch 'upstream/main' into fix/explosion-creaking-heart-xp 2026-11-11 00:03:46 -03:00
Vinícius Moreira ac68d5ae04 Merge remote-tracking branch 'upstream/main' into fix/end-crystal-saved-fall 2026-11-11 00:03:46 -03:00
Vinícius Moreira b5ae68c8b7 Merge remote-tracking branch 'upstream/main' into fix/crafter-triggered-int 2026-11-11 00:03:46 -03:00
Vinícius MoreiraandClaude Opus 5.5 76a8f27085 Merge main into fix/raw-entity-flags: main compiles again (#15038)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:57:45 -03:00
Vinícius MoreiraandClaude Opus 5.5 0ba2a84306 Merge main into fix/vex-no-gravity: main compiles again (#15038)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:56:36 -03:00
Vinícius MoreiraandClaude Opus 5.5 40b2f16229 Merge main into fix/painting-on-ground: main compiles again (#15038)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:56:02 -03:00
Vinícius MoreiraandClaude Opus 5.5 023a57e557 rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:48:53 -03:00
DUzzL 6352b7468c Thrown eggs hatch the chicken variant of their item
ThrownEgg.onHit sets the chicken's variant from the item's CHICKEN_VARIANT component (egg temperate, blue_egg cold, brown_egg warm); a thrown or dispensed egg now carries it.
2026-11-11 03:37:51 +01:00
Vinícius MoreiraandClaude Opus 5.5 26d32147ea Wrap the zombie owner's summon
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:43:53 -03:00
Vinícius MoreiraandClaude Opus 5.5 0b2ed50a68 A nested blast drops the TNT owner; the zombie owner stays and leaves no drops
A native explosion inside a TNT blast is Level.explode(null, ...): it
now takes blast_owner, blast_guest and blast_owner_player aside with
the rest of the blast's state. The group keeps its zombie persistent
and clears the zombie's drops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:43:46 -03:00
Vinícius MoreiraandClaude Opus 5.5 08fba7506e A block entity's ints load as getIntOr does; the crafter group moves apart
decode_block_entity reads every int through nbt_path::int_value
(NumericTag.intValue: a float or double floored and saturated), so the
crafter's triggered keeps rustfmt's single line and save.rs does not
grow. The crafter group moves to a chunk no other group forces within
five columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:43:08 -03:00
Vinícius MoreiraandClaude Opus 5.5 a15fb9d167 An end crystal reads its fall with ground_from_nbt; /tp grounds it; powder snow's shape counts
ground_from_nbt on main already reads OnGround and fall_distance, so the
helper this pull request added goes. TeleportCommand.performTeleport
sets onGround. Powder snow's inside shape for a fall over 2.5 is 0.9
tall, so a crystal above it keeps its fall. The deflate is 1.0E-5F.
The group adds both powder snow cases and a teleported crystal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:42:25 -03:00
Vinícius MoreiraandClaude Opus 5.5 947aae2b5b A crafter's screen draws its arrow from the int; a double triggered floors
CrafterScreen asks menu.isPowered(), data slot 9 == 1, not the block
state, so a crafter[triggered=true]{triggered:5} shows the unpowered
arrow. getIntOr reads a double through DoubleTag.intValue, floored and
saturated: -0.5d is -1 and 4294967297d is 2147483647, where the cast
truncated and wrapped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:37:15 -03:00
Vinícius MoreiraandClaude Opus 5.5 b1499e6662 An end crystal carries its own loaded fall; a cobweb resets it
The loaded OnGround and fall_distance now live on the crystal, so a
crystal summoned where a loaded one was killed starts from nothing and
a teleported crystal keeps its own (the position-keyed compound found
neither). EndCrystal.tick's applyEffectsFromBlocks resets the fall in
a cobweb or powder snow (makeStuckInBlock). Crystal::new builds the
fresh crystal its five call sites wrote out; start_time moves beside it
in dragon/crystal.rs, keeping dragon.rs from growing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:35:59 -03:00
Vinícius MoreiraandClaude Opus 5.5 386d0560a1 A mob-owned TNT awards no creaking heart experience; block_drops off pops none
PrimedTnt.getOwner names the mob a saved owner UUID points at, so its
blast's indirect source is no player and tryAwardExperience awards
nothing. Keep whether the owner is a player beside blast_owner (a chain
reaction hands a mob owner on as a mob). Block.popExperience draws the
amount, then pops nothing with block_drops off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 22:32:56 -03:00
f90e164b4b Give a fox that eats its food its effects, and credit a panda's pickup
`Fox.aiStep` finishes the item in the mouth with `ItemStack.finishUsingItem`
(`Consumable.onConsume`), which ran only the chorus fruit's teleport here: run
the whole consume in vanilla's order — `emitParticlesAndSounds` (the
consumable's sound, and the four draws a crumb of `spawnItemParticles` costs,
though `Level.addParticle` is empty on a server), `FoodProperties.onConsume`'s
own sound, the `on_consume_effects` through `LivingEntity.addEffect` (so a
golden apple's regeneration and absorption land) and `GameEvent.EAT` at the
fox's feet with the fox as its source.

`Panda.pickUpItem` calls `onItemPickup` before it takes the item, so
`CriteriaTriggers.THROWN_ITEM_PICKED_UP_BY_ENTITY` fires for whoever threw it,
as it already did for the fox (`LivingEntity.onItemPickup`).

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 02:32:32 +01:00
RINNECODERandClaude Opus 5.5 adb0766fe6 Merge main: #14430's crate lang files in the key check
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 19:24:39 -06:00
MSedgeMC 49873c3371 Merge main; keep both sides' tests and module declarations 2026-11-11 01:03:02 +00:00
MSedgeMC 359388eea7 Merge main; keep both sides' tests and module declarations 2026-11-11 01:03:00 +00:00
MSedgeMC fcbbd1f556 Merge main; keep both sides' tests and module declarations 2026-11-11 01:02:55 +00:00
Vinícius MoreiraandClaude Opus 5.5 07e165137f The crafter's whole-int test builds its crafter in one expression
clippy's field_reassign_with_default refused the field set after Default::default().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:59:39 -03:00
Vinícius MoreiraandClaude Opus 5.5 cf0566a27d A leash knot or marker saves its flags as booleans
Entity.load reads NoGravity, Silent, Glowing and the other flags with
getBooleanOr and Entity.saveWithoutId writes each back as 1b only when
true. Horizon saved a leash knot's, a marker's or an eye of ender's raw
compound, keeping bytes like -1b and false flags; other_to_nbt now
normalizes them as the other entities' saves do.

Fixes #13853

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:59:38 -03:00
Vinícius MoreiraandClaude Opus 5.5 bdbf33939c A vex turns its gravity off every tick
Vex.tick calls setNoGravity(true) on every tick, AI or not, so a vex that
ticked once saves NoGravity: 1b. Horizon's vex flew through its own
travel without the flag and left it out of the save.

Fixes #13849

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:59:36 -03:00
Vinícius MoreiraandClaude Opus 5.5 4d6923514e A player's blast awards a natural creaking heart's experience
CreakingHeartBlock.onExplosionHit awards the heart's experience
(tryAwardExperience) when the explosion's indirect source is a player, a
primed TNT's owner, unless that player is in creative or spectator
(preventsBlockDrops). Horizon always broke the heart as if no player
caused it.

Part of #11330

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:59:34 -03:00
Vinícius MoreiraandClaude Opus 5.5 d0314e8f25 A painting keeps its saved OnGround and fall_distance
Entity.load reads OnGround and fall_distance and Entity.saveWithoutId
writes them back. BlockAttachedEntity.tick never moves a painting nor runs
baseTick, so both stay what was loaded. painting_to_nbt wrote OnGround 0b
and fall_distance 0; it now writes the loaded values from the painting's
saved compound.

Fixes #14543

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:59:32 -03:00
Vinícius MoreiraandClaude Opus 5.5 03c750245c An end crystal keeps its saved OnGround and fall_distance
Entity.load reads OnGround and fall_distance and Entity.saveWithoutId
writes them back. EndCrystal.tick never moves the crystal nor runs
baseTick, so both stay what was loaded. Crystal::to_nbt wrote OnGround 0b
and fall_distance 0; it now writes the values from the crystal's loaded
compound.

Fixes #14671

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:59:31 -03:00
Vinícius MoreiraandClaude Opus 5.5 814e31a935 A crafter's triggered int round-trips at 5, -1 and 65537 too
The round trip at 1 passed with the old bool as well; values other than 1 come back
unchanged and untriggered, as vanilla saves and reads them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:57:01 -03:00
Vinícius MoreiraandClaude Opus 5.5 89b756de50 A crafter keeps its triggered int and triggers only at 1
CrafterBlockEntity keeps triggered as the int it read (containerData
slot 9), writes it back and is triggered only when it is 1. Horizon held
a bool read as != 0, so -1 or 5 became triggered and saved as 1. The
field is the raw int now, with is_triggered() for the bool.

Fixes #13851

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:57:01 -03:00
Umut Cevdet Koçak add317d016 Merge pull request #277 from sunrise-org/perf-m1-heap
Sampled heap profiling: allocations and live memory by call stack
2026-11-11 03:39:28 +03:00
umcekoandClaude Opus 5.5 b944c970c3 Heap samples leave out the profiler's own threads
The e2e capture's live heap was all on horizon-profile: the CPU
sampler's drain thread copies the binary's unwind sections (~9 MB,
framehop's Module::new from StackUnwinder::refresh) at the start of the
capture and holds them to the end, so the heap sampler profiled the
profiler. Samples were already tagged with the allocating thread.

heap_sample::ignore_this_thread() stops sampling a thread's allocations
(its frees still leave the live set). The sampler's drain thread, the
capture writer (WriterThread::spawn_with), the finishing thread and
the gauges thread call it.

server_perf_e2e checks live bytes over every thread, none on a profiler
thread, and that the top live function is not the profiler's; it
samples every 64 KiB so its 4 s capture holds some. It now passes: 1.0
MiB live on tick, workers and chunk threads, 19,453 samples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 03:39:05 +03:00
umceko 3030aa3652 Merge remote-tracking branch 'fork/perf-platform-upstream' into perf-m1-heap
# Conflicts:
#	tools/server_perf_e2e.py
2026-11-11 03:20:39 +03:00
Umut Cevdet Koçak f65b2574e1 Merge pull request #279 from sunrise-org/perf-chat-calm
Profiler chat: calm lines, action bar progress, and the mark sprite fixed
2026-11-11 03:03:02 +03:00
umcekoandClaude Sonnet 5.5 f80e0cfbf0 Profiler chat: one calm line per outcome, progress on the action bar, and the mark sprite drawn
Chat keeps the lines with a next step (started, saved, shared, failures); saving,
uploading, opened and marked go to the action bar; the saved line carries the
capture's length from when stop was asked; [Retry] names its profile.

Text::styled dropped the style's inline object (Style::inherit never passes one
on), so the profiler tag drew the font's [OBJ] box instead of horizon:gui/mark.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 03:02:11 +03:00
TiggerTakkyTTTandCodex 15e02ce312 fix(cem): preserve layer ownership map
Avoid shadowing the ownership map with the layer-key list so the latest main branch compiles after the CEM armour-layer merge.

Co-Authored-By: Codex <[email protected]>
2026-11-11 07:00:19 +07:00
TiggerTakkyTTT 1c15680e9a Merge remote-tracking branch 'upstream/main' into fix/wind-burst-ender-dragon 2026-11-11 06:57:15 +07:00
rdbtCVSandGPT 6.1 Sol 7cdd21f24d Merge repaired main into PR #15021 to refresh CI
By rdbtCVS's AI agent (OpenCode, GPT 6.1 Sol). Preserve the contributor and maintainer history while including main's merged #15027 repair for the inherited studio_replay and rocket RNG compilation failures. No PR-specific code changes.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-10 23:52:38 +00:00
TiggerTakkyTTTandCodex 61d8dea2a7 fix(combat): scale dragon wind burst knockback
Apply the burst damage-calculator multiplier to the Ender Dragon impulse before native knockback hooks, and cover the behavior with a regression test.

Co-Authored-By: Codex <[email protected]>
2026-11-11 06:39:34 +07:00
DUzzL c9544070f8 Merge remote-tracking branch 'upstream/main' into cf/14590 2026-11-11 00:26:48 +01:00
DUzzL 361923c262 Merge remote-tracking branch 'upstream/main' into cf/14590
# Conflicts:
#	crates/horizon-client/src/game/mob_landing_support_tests.rs
2026-11-11 00:26:25 +01:00
martipopsandClaude Opus 5.5 adbf42ffb9 Merge upstream main (#14379) into Pack Options on the settings shell
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:22:03 -05:00
rdbtCVSandGPT 6.1 Sol 0afcabe0ec test(launcher): exercise sign-in builder in IPv4 fallback test
Use the production timeout builder rather than an unrelated test agent, and
cover IPv4-first multi-address and IPv6-only resolver ordering.

Fixup by rdbtCVS's AI agent (OpenCode, GPT 6.1 Sol), not by rdbtCVS personally.

Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-10 23:07:38 +00:00
Umut Cevdet Koçak b97a7d0dec Merge pull request #278 from sunrise-org/perf-m2-reader-memory
Perf platform M2: finer sample blocks, memory_labels/counters ops, samples in tick, complete server memory report
2026-11-11 01:48:42 +03:00
Umut Cevdet Koçak b6832dc940 Merge pull request #276 from sunrise-org/perf-l1-layers
Profiler on upstream's layers: Open and Share through a hook, no built-in address
2026-11-11 01:48:38 +03:00
umcekoandClaude Sonnet 5.5 7942b6d4c3 Memory report: a typed, complete server report with entities, players, chunk send caches, queues and unattributed_mb
`horizon-ctl memory` and a capture's memory snapshots are built from `#[derive(Serialize)]` structs instead
of `json!`; existing keys keep their shape. A dedicated server (no window) names its columns `columns`;
single player keeps `client_columns` and `server_columns`.

New, all estimated from capacities:
- `entities`: count and bytes by entity type (top 30), across every level
- `players`: count and, per player by name, the send queue (packets and bytes), chunks waiting, chunks sent
  and tracked entities
- `chunk_send`: the encoded section and heightmap caches and the shared compressed frames
- `light_queue`, `generation_queue`: lengths and the bytes of their tables
- `allocator`: `live_heap_mb` (mimalloc's statistics), `commit_mb`, `peak_commit_mb`, `overhead_mb`
- `named_mb` and `unattributed_mb` (resident minus the named parts) on every side

The server e2e asserts a stop snapshot has `players`, `entities` and `unattributed_mb`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 01:47:31 +03:00
umcekoandClaude Sonnet 5.5 c7a26889ff horizon-perf: tick carries the top functions of the samples around the tick
`hot` is the top 30 functions (the `hot` op's row) of the main thread's samples in the time blocks
overlapping the tick, only the slow samples when the tick is slow, and `samples_from`/`samples_to` say the
window those blocks cover. With 1 s blocks that is the second around the tick, not the tick's own samples.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 01:47:31 +03:00
umcekoandClaude Sonnet 5.5 46b588e72a horizon-perf: memory_labels lists a capture's memory snapshots and counters its counters
`memory_labels` (CLI `query memory-labels`, MCP and wasm through the shared op list) gives one row per
snapshot, `{label, t, side, rows}`, in time order. `counters` gives one row per counter definition,
`{id, name, unit, kind, labels, side, samples}`. Each has a golden reply. `memory` also ranks a negative
megabyte row by its size, so `unattributed_mb` can show.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 01:47:31 +03:00
umcekoandClaude Sonnet 5.5 2843049551 Profiler: CPU sample time blocks are 1 s, up to 1800, and a time range selects the blocks it overlaps
`block_s` defaults to 1.0 and `MAX_TIME_BLOCKS` is 1800 (30 minutes, the block index a `u16`); a longer
session keeps the rest in the last block, as before. The reader selects every block a `--from`/`--to`
range overlaps, a range inside one block picks that block, and the reply's `selection.from`/`to` name the
blocks the weights cover, so a 2 s range no longer leaves Functions and the flame graph empty.

Capture size before and after on the 200-bot benchmark and a client capture is not measured yet: pending a
quiet machine. If growth is over 2x, blocks older than 5 minutes get merged at write time.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 01:47:31 +03:00
umcekoandClaude Opus 5.5 9e7925e2e9 Sampled heap profiling: allocations and live memory by call stack
horizon-threads' heap_sample wraps mimalloc and is the game's allocator
on Linux (alloc-count and alloc-census still replace it). While a
capture runs it samples about one allocation per 512 KiB
(HORIZON_HEAP_SAMPLE_KIB; 0 turns it off) with an exponential countdown
per thread, records the stack, thread and span context, and weighs
each sample interval / (1 - exp(-size / interval)) bytes. Frees look a
pointer up in a 1 MiB table of per-bucket counts and only take the lock
on a hit. One session per process: the first capture to start owns it,
so the integrated server's joined side does not start another.

Captures write two more kinds, alloc and live (bytes, period 1), into
the same tables as the CPU samples, without the allocator's own frames
at the leaf end.

Measured (fast profile, Linux x86_64, 24 threads, machine at load ~50
from other builds):
- Off: alloc_count_bench 64 B alloc+free pairs, +0.4-0.6 ns a pair
  (+9-11% of mimalloc's 5 ns on 1 thread; +1-14% on 8, noisy): one
  relaxed load and branch on each side, as designed.
- On, 200 walking bots with a capture: the sampler is 1.2% of the
  tick thread's CPU samples (1.24 and 0.77 ms a tick), about 70% of it
  .eh_frame unwinding, at ~40-70 us a sample; 63k and 100k samples in
  ~2 min. MSPT avg on 89/148/224/97 vs off 108/69/217/65 ms: the
  overloaded server (TPS 5-14) and the machine load swamp the A/B.
- Capture size: 209 and 231 KB on vs 171 and 171 KB off (+22-35%).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 01:40:00 +03:00
umcekoandClaude Opus 5.5 81b07fb2d6 Profiler format and reader: live heap samples
SampleSource gains LIVE (sampled heap bytes still allocated when the
capture stopped, at their allocation's time block), and Overhead gains
heap_samples and heap_sample_ns.

horizon-perf reads them: --select live works in query hot/tree/callers
and in the folded and pprof exports, in bytes (a total, not a rate per
tick); the summary prints a heap line (live and allocated MiB, the
functions holding the most) and the heap sampler's cost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 01:40:00 +03:00
DUzzL d13e35bb8f launcher: fall back to IPv4 when IPv6 to Microsoft is dead
Interleave the address families of resolved sign-in hosts and bound the
connect time, so a broken IPv6 route no longer fails sign-in with
'Could not reach Microsoft'. Fixes #15013.
2026-11-10 23:27:51 +01:00
e24554895d Keep foxes out of the shade in villages and defending the players they trust
Fox.SeekShelterGoal.canUse no longer looks for shade when the fox stands in a
village (ServerLevel.isVillage: within one section of a village POI), so a
village fox keeps strolling in the sun as vanilla's does.

Fox.DefendTrustedTargetGoal is now registered at target priority 3: the fox
takes whoever last hurt a trusted entity as its target, plays FOX_AGGRO at its
feet, sets DEFENDING (the growl and the avoid/stroll guards were dead code) and
drops the flag through Fox.setTarget(null) when the goal stops.

Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 23:13:12 +01:00
umcekoandClaude Sonnet 5.5 bd94713fdd /profiler: stop only saves; [Open] and [Share] are the player's to click
`/profiler stop` prints the saved file and never uploads. Where a captures part is
registered (the official build) the line carries [Open] and [Share] buttons that run
`/profiler open <id>` and `/profiler share <id>` (no id: the last capture saved);
a build without the part answers both "not available in this build". horizon-ctl
gains `profile open FILE` and `profile share FILE`. The profiler harnesses read the
new saved line, and `profile_client_e2e.py --official` checks the buttons and open_at.
Docs: saving, Open and Share are independent of telemetry; Share is the only upload.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 00:28:07 +03:00
umcekoandClaude Sonnet 5.5 a86ab9d4bc Layers: the profiler crates have layers, and benchmarks sit on horizon-system
The benchmark report format reads its hardware through `horizon-system`, not
`horizon-telemetry`, so `horizon-bench` is an engine crate and the two `-> horizon-bench`
exceptions go. `horizon-perf-format` is engine, `horizon-perf` a tool, `horizon-perf-share`
Horizon. The launcher and `horizon-server` reach the report format and the capture files
through `horizon_platform::{bench, perf_format}`. `horizon-threads` joins the portable
crates, which `horizon-world` already used.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 00:28:07 +03:00
umcekoandClaude Sonnet 5.5 ccf6b2c913 Perf captures: Open and Share go through a hook, not a built-in address
Saving a capture is local. A registered `Hooks::captures` offers the viewer page,
Open (serve the file once on 127.0.0.1 and open the viewer on it) and Share (the
upload). `horizon-perf-share`, a Horizon crate in `horizon-official`'s parts, holds
both, with the addresses in `horizon-addresses` and their env overrides; the upload
code moves there from `horizon-perf`, which gains `horizon-perf open`.

The saved line and the `profile stop` reply carry no address: `open_at` is present
only when a build has the hook. `horizon-client` keeps `horizon-perf` for tests only.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-11 00:28:07 +03:00
Verm fadace66a0 A goat's horn flags are read as bytes (#14970)
Goat reads HasLeftHorn and HasRightHorn with getBooleanOr(key, true): a
number is true when its byte value is not 0, so an int 256 is a lost
horn. The loader tested the whole number; it now uses flag_or, as every
other boolean there does.
2026-11-10 19:33:20 +00:00
Umut Cevdet Koçak e301d92133 Merge branch 'horizon-rust:main' into perf-platform-upstream 2026-11-10 22:13:29 +03:00
RLC248 7c384cd6ae Merge remote-tracking branch 'upstream/main' into fix/thrown-potion-level-entity 2026-11-10 19:31:50 +01:00
DetimesandClaude Opus 5.5 e61bf50d60 Merge upstream/main into perf-effect-meta
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:17:50 +00:00
Mayonesu0andClaude Sonnet 5.5 d1190a4dc7 A bare attribute name saves and applies as minecraft:'s; delivery harness covers tool and attribute_modifiers
Review of #14687.

Vanilla reads Attribute.CODEC and Identifier.CODEC with `minecraft:` as the
default namespace and writes them back whole, so `/item replace ... with
iron_pickaxe[attribute_modifiers=[{type:"attack_damage",id:"x",...}]]` saves
`minecraft:attack_damage` / `minecraft:x`. Horizon kept the strings as given:
the wire writer namespaced them, but the host passed the bare name to
`set_modifier_unclamped`, which skips an attribute it cannot find.

- `Items::attribute_modifiers` namespaces the stack's `type` and `id`, so the
  host applies what the client shows.
- The saved form (`item_to_nbt`) namespaces them as vanilla does.
- `test_builtin_component_delivery_parity.py`: a `tool` and an
  `attribute_modifiers` case (with bare names), run against the 26.3 server.
- Tests: a bare name on the host and across the wire, the saved form, and the
  writers' silent-drop path for a tool or modifier they cannot encode.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 19:10:54 +01:00
Verm 7d37a291c2 A shulker's AttachFace is narrowed to a byte before the face is picked (#14940)
Shulker reads AttachFace with Direction.LEGACY_ID_CODEC: a byte through
from3DDataValue (abs(data % 6)). The loader took the remainder of the
whole number, so an int 258 was face 0 where vanilla's byte 2 is face 2.
The shulker bullet's Dir already narrowed first.
2026-11-10 18:02:13 +00:00
MSedgeMC b968ef5726 Keep entity_nbt.rs at its size: two-line write, no extra comment 2026-11-10 18:00:54 +00:00
MSedgeMC fce0b893f8 Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-10 17:52:57 +00:00
DetimesandClaude Opus 5.5 bcb0d01d9e Test the effect particle cache against the uncached lookup
Every (effect, ambient) pair, known or not, gives the same particle
through the cache as through the plain lookup, and the second pass
over the same pairs makes no registry lookup at all.

Refs #14921

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 17:42:42 +00:00
DetimesandClaude Opus 5.5 6ece267eb9 Memoise effect particle lookups in the hub
effect_meta looked up the particle of every visible effect for every
placed guest on every tick: a linear search over the effect table, a
formatted name and a String-keyed registry lookup. The result depends
only on (effect, ambient), so the hub now keeps it per pair. Output is
unchanged. The function moves out of hub.rs into hub/effect_meta.rs,
which keeps hub.rs from growing.

Refs #14921

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 17:42:39 +00:00
DetimesandClaude Haiku 5.5 d2bc41cd4e Test: equipment conversion repeats only for changed stacks
Compares the cached equipment with a direct conversion of every equipped
slot over static ticks, after a count change and after a slot is cleared.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 17:42:31 +00:00
DetimesandClaude Haiku 5.5 61ffa23382 Perf: cache converted equipment per guest
Held, offhand and armor stacks were converted to network stacks for every
guest on every tick. Each guest now keeps the converted stack of each
equipment slot together with the ItemStack it came from, and converts
again only when that stack differs by full equality. The /reload path
clears the cache, since conversions depend on the registries.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 17:42:28 +00:00
Verm c44aa01ebb A wolf's or cat's CollarColor outside 0..15 reads white (#14897)
Wolf and Cat read CollarColor with DyeColor.LEGACY_ID_CODEC: a byte
through DyeColor.byId, whose out-of-range answer is the first colour
(OutOfBoundsStrategy.ZERO). The loader masked the id with & 15, so 17b
was orange and -1b black where vanilla's collar is white.
2026-11-10 17:26:10 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 eb06abefe2 Shader API 0.2: the [entity] stage, checked and not yet drawn
A 0.2 pack lights block terrain and nothing else: mobs, chests, dropped
items and particles keep vanilla's lighting, and no stage lets a pack light
them. This adds the API for that stage, so packs can be written and checked
against it before the game draws it.

- `[entity]` in the manifest and `fn entity(input: EntityInput) -> Surface`:
  the texture, the tint apart from vanilla's shade, the hurt flash, the
  light, a normal, the position and what is drawn (`kind`). It returns the
  material stage's `Surface`, so one function can light both.
- Its resources are the material stage's shadow maps and coloured-light
  grid, at the same bindings, so one bind group can serve both. No block
  texture helpers, `reflection`, `opaque_*` or `set_surface`.
- The reference gives vanilla's own as the stage's function, read from
  `entity_color`: the flash is mixed in vanilla's gamma, before the light.
- `horizon-shader check` takes the stage with the material's limits and
  refuses a wrong signature or a constructed `EntityInput`. The game refuses
  a pack that has it until it draws the stage.

A pack without `[entity]` is unchanged and sees none of the stage's names:
every other stage's prelude and entries are the same text as before, held by
the names lists. 0.1 refuses the key.

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

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 18:22:04 +01:00
[email protected]andClaude Sonnet 5.5 5fcd41ad3c Leave the recording's login sea level as it was
A recording is made on a remote connection, where the process-wide table
may still hold the sea level of a world opened earlier.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 18:00:36 +01:00
MSedgeMC 7fed2549d7 port_map: EditBox and MultiLineEditBox onClick double clicks 2026-11-10 17:00:33 +00:00
MSedgeMC 86cc476eff test: a double click in the chat box selects the word
Two clicks on the last letter of "hello world": the first places the caret
at the word's end, the second selects world, not the space before it.
2026-11-10 17:00:33 +00:00
MSedgeMC 65bce70f7a fix: double-clicking the chat box selects the word
EditBox.onClick selects the word under the pointer on a double click
(EditBox.selectWord: getWordPosition(-1)..getWordPosition(1)) and places the
caret otherwise; MouseHandler calls a click within 250 ms on the same screen a
double click. Horizon's chat input only ever placed the caret.
2026-11-10 17:00:33 +00:00
malithedeveloperandClaude Opus 5.5 c1b56cea13 Resource packs: a sprite alias never replaces a texture that is there
An alias written over an existing texture changed what every other reader
of that file sees: an unstitched or paletted sprite built from it, another
source's resource, anything that reads the texture as itself. Aliases now
only fill sprite paths that have no texture of their own, which is what
ItemsAdder and Nexo packs rename to; a rename over an existing texture
draws that texture, as before aliases. With that, vanilla's atlases never
list an alias's sprite, so they are no longer read for it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 19:57:46 +03:00
Verm 935faca944 An area effect cloud keeps the fall_distance it was loaded with (#14853)
AreaEffectCloud extends Entity and never moves, so Entity.saveWithoutId
writes the fall_distance Entity.load read. entity_base_tag, which the
cloud's save uses, took OnGround from the loaded compound but wrote
fall_distance 0.0; it now takes that from the compound too.
2026-11-10 16:18:38 +00:00
malithedeveloperandClaude Opus 5.5 fac0918973 Resource packs: a renamed sprite leaves a filtered .mcmeta out
A rename whose resource is vanilla's texture copied vanilla's `.mcmeta`
under the sprite even when a pack's filter hid that `.mcmeta`. Vanilla's
`createStackMetadataFinder` stops at a pack that filters the metadata, so
the alias now takes vanilla's `.mcmeta` only where no filter blocks it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 19:17:14 +03:00
Verm cfa85f016f Evoker fangs keep the fall_distance they were loaded with (#14847)
EvokerFangs extends Entity and never moves, so Entity.saveWithoutId
writes the fall_distance Entity.load read. Their save took Motion, the
pitch and OnGround from the loaded compound but wrote fall_distance 0.0;
it now takes that from the compound too.
2026-11-10 16:05:16 +00:00
Verm 70ee24e9ef A trident keeps the fall_distance it was loaded with (#14846)
Entity.saveWithoutId writes fall_distance from fallDistance and
Entity.load reads it back. AbstractArrow.tick never calls Entity.move,
so a trident keeps the loaded value until water resets it. The trident's
save wrote 0.0 and its load ignored the key; it now reads, keeps and
saves it as the arrow does, and water resets it in the ticks that reach
Entity.baseTick. Lava's halving is not modelled for a trident.
2026-11-10 15:58:46 +00:00
DUzzL 615735e12c Keep shulkers that are not picked up out of the cart push fallback 2026-11-10 16:57:33 +01:00
SamB440 c46fd6f944 parity: Respond with acknowledgement packet when receiving PlayerRotation packet 2026-11-10 15:55:17 +00:00
[email protected]andClaude Sonnet 5.5 18bb5b3b1d Keep the files over 3000 lines from growing
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 16:31:11 +01:00
[email protected]andClaude Sonnet 5.5 dc3fe491e3 Sea level follows the level's generator
Fixes #14835

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 16:16:45 +01:00
malithedeveloperandClaude Opus 5.5 d1619f89b3 Resource packs: a renamed sprite keeps a later source's texture
The overlay gave every `single` rename's sprite its resource's file, even
when a later source of the atlas (a plain `single` or a `directory` of a
higher pack) listed that sprite from its own texture again. It now resolves
each atlas's whole source list in order with `atlas_sources::list`
(`SpriteSourceList.list`) over the textures the packs and vanilla leave
visible, and gives a sprite its resource's file only when that final
listing is the rename. Both atlases read the same file, so a sprite the
other atlas lists any other way keeps it. An atlas no pack provides is
vanilla's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:09:48 +03:00
DUzzL 267c3838b6 Reset a negative mob Fire to 0 on its first tick 2026-11-10 16:06:42 +01:00
DUzzL 4068a09887 Keep an item frame's saved Motion, OnGround and fall_distance 2026-11-10 16:03:09 +01:00
DUzzL dfbdf94740 An arrow loads and keeps its saved Air 2026-11-10 15:10:23 +01:00
Oloion afb34764ec assets: eliminate heap allocations in RangeSelectItemModel binary search 2026-11-10 17:00:17 +03:00
tarzinio f291526b1f Sample LOD tiles again when Far detail changes 2026-11-10 14:25:13 +01:00
umcekoandClaude Opus 5.5 fc9eb64042 Captures name players: the privacy section and its harness say so
A server owner has to know which connection floods or lags, so net rows carry each player's name, client
brand and view distance. server_perf_e2e still checks that the world, seed, MOTD, mob and sign names and the
IP stay out, and now checks that net names both bots.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 16:22:22 +03:00
umcekoandClaude Opus 5.5 fc9acc4a74 Profiler: a client capture records its connection, and a server-thread start waits for the last file
The window now hands its server connection's byte counters to the capture each frame, so a client capture's
network tab has data. A server-thread capture asked for while the previous one is still being written waits
for that file instead of refusing, which the window had already reported as started.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 16:22:22 +03:00
umcekoandClaude Sonnet 5.5 79b1df4051 Golden net replies carry each connection's name, brand and view distance
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 15:58:46 +03:00
umcekoandClaude Sonnet 5.5 31ae839a81 Format the ported profiler work
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 15:18:40 +03:00
umcekoandClaude Sonnet 5.5 226fb118f8 Captures name each connection: player, client brand and view distance; a client records its own server traffic
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 15:17:58 +03:00
umcekoandClaude Sonnet 5.5 4390baae27 Profiler chat: Horizon's mark as the line's tag
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 15:15:50 +03:00
umcekoandClaude Sonnet 5.5 aa3df3b4f7 Read a single-player capture's GPU frames without naming the side
The profile e2e checks the GPU summary and frame series too.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 15:01:15 +03:00
umcekoandClaude Sonnet 5.5 51fa349fe4 Record every GPU-timed frame in captures and split the world pass into draw groups
A capture made with --gpu now writes each timed frame (gpu_frames = 24: its
start on the capture clock, first-to-last timestamp total, every pass and part)
in blocks about once a second, with the CPU ms of every drawn frame. GpuPasses
ms becomes the median over the whole capture instead of the last 15 frames.

Where the device stamps inside passes, every timed frame splits the world
passes into their draw groups (sky, solid terrain, occlusion boxes, entities,
translucent terrain, clouds, weather, hand...) and compute passes into their
dispatches, so GPU culling's parts show without detail mode; Metal keeps pass
boundaries, recorded as GpuDevice.pass_split.

query gpu gains per-pass and per-part samples, p50/p95/p99/max and share of the
GPU frame p50, plus a summary row with GPU and CPU frame percentiles and a
gpu/cpu/mixed bound verdict; query gpu_frames gives the series with slow frames
flagged. Older captures read with empty statistics.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 14:44:54 +03:00
MSedgeMC 479276f66d port_map: WorldOptionsScreen.setPortError is ported 2026-11-10 11:44:22 +00:00
MSedgeMC 17cdf49055 test: a rejected port says why in its tooltip
Above 65535, below 1024, not a number and negative all read the invalid-port
reason; 1024, 25565 and 65535 keep the Port Number label, and an empty box
takes the suggestion.
2026-11-10 11:44:22 +00:00
MSedgeMC b49f625199 fix: the LAN port box says why its number is wrong
WorldOptionsScreen.setPortError swaps the port box's tooltip from
PORT_INFO_TEXT to INVALID_PORT when tryParsePort rejects the value. Horizon
always showed Port Number, so a red box never said what was wrong.
2026-11-10 11:44:22 +00:00
umcekoandClaude Sonnet 5.5 034ffdbfef Parse /profiler through its command tree, with gpu literals and spark-style chat lines
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 14:35:00 +03:00
MSedgeMC c1fad2fb18 port_map: the loaded cube's freeze immunity
SulfurCube.canFreeze had no row; it is the cube's arm of freezing.rs::can_freeze.
2026-11-10 11:28:57 +00:00
MSedgeMC 9b087a4560 A sulfur cube holding a block does not freeze
SulfurCube.canFreeze answers `!hasBodyItem() && super`, so a cube carrying a
block in its body takes no frozen ticks from powder snow and no freeze damage,
while one without a body freezes like the cube mobs do. can_freeze answered
the tag and the skeleton's refusal and nothing else, so a loaded cube shook and
took the 1 a fully frozen mob takes.

The test puts a sulfur cube with a stone body at 0 and at 140 frozen ticks: it
stays at 0 with no damage and melts to 138, where the cube without a body gains
a tick (1) and takes the 1 at 140. Without the arm the loaded cube reads (1,
0.0) like the empty one.
2026-11-10 11:17:11 +00:00
umcekoandClaude Sonnet 5.5 28fa20f13d Share in-game profiler captures through direct viewer links
Upload completed chat-started captures on a background worker and show a clickable capture URL. Preserve the local file and an owner-only receipt before pinning, so /profiler share can retry without uploading twice. Use an application user agent accepted by the deployed API. Keep control-socket and environment captures local.

Validated timed and manual in-game completion against the live API with byte-identical download, plus retry/ownership regression, command completion and Clippy. Test uploads removed after validation.

Fixes sunrise-org/horizon#267

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 14:11:21 +03:00
umcekoandClaude Sonnet 5.5 ac784c6832 Record complete 1% and 0.1% timing lows for performance captures
Keep bounded raw unit timings during recording and expose exact slow-tail means through meta. Tick rates express work capacity capped at 20 TPS; old or incomplete captures omit lows. Related: sunrise-org/horizon#264.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 14:08:24 +03:00
zenith600andClaude Opus 5.5 4d3d579464 launcher: say when a folder has the version file but not the game (#14286)
A folder where the official launcher wrote versions/26.3/26.3.json but not
26.3.jar (a version picked but never played, or a download that stopped)
said "no Minecraft 26.3 client jar", the same as a folder that never had
26.3. It now says the version file is there and to play 26.3 once in that
launcher. A wrong jar and a folder without the version file keep their
messages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 16:29:39 +05:30
umcekoandClaude Sonnet 5.5 9cddcfb071 Carry the remaining profiler and benchmark work onto upstream's layout
Benchmark A/B runs and --benchmark-set/--profile, the memory section, span
laps through streaming and the world update, the server report and the
/profiler command tree, ported from the original patches onto the files
upstream split out of game.rs.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 13:48:22 +03:00
malithedeveloperandClaude Opus 5.5 09cfb0197c Resource packs: a renamed atlas sprite reads its resource's texture
A `single` atlas source with a `sprite` puts its resource's pixels under
another id (SingleFile.run). ItemsAdder and Nexo server packs name their
models' textures only through these renames ("ia:1199" for
minecraft:block/sea_lantern), and every loader reads a model's sprite
from textures/<sprite>.png, which those packs never ship: their models
drew the missing texture or nothing.

The overlay now gives each renamed sprite of the blocks and items
atlases its resource's file and .mcmeta, as SpriteResourceLoader reads
the resource's metadata. A rename over an existing texture replaces it
in the overlay only. Overlay cache version 9 rebuilds cached overlays.

Part of #14485.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 13:39:06 +03:00
umcekoandClaude Sonnet 5.5 4039f0eeb6 Merge origin/main into perf-platform-upstream
Conflicts kept both sides: the platform's pass timing feature moves into the
device search's new open_adapter, its Options fields and work-attribution
calls follow the code upstream moved out of game.rs, and the perf channel
joins upstream's list of Horizon channels.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 13:37:36 +03:00
TiggerTakkyTTTandCodex 01731db683 fix(combat): make Wind Burst affect the Ender Dragon
Fixes #14724.

Co-Authored-By: Codex <[email protected]>
2026-11-10 17:03:22 +07:00
MSedgeMC 7b9fca2a49 Move the freezing helpers into mobs/ai/freezing.rs
ai.rs is over the 3000-line limit and may not grow, so in_powder_snow and can_freeze move out; the skeleton rule stays
the same.
2026-11-10 09:51:34 +00:00
MSedgeMC 868ff0f305 Read CannotHunt in the piglin helper and write it on one line
Keeps entity_nbt.rs, over the 3000-line limit, from growing by the read.
2026-11-10 09:31:09 +00:00
Riccardo GuerrieroandClaude Fable 5.2 e8578c2e47 Worldgen: choices sample a branch only where they read it
Vanilla's bulk range choice and interval select sample every branch over the
whole volume and then pick one value per position, and so did the port. In
the Overworld's final density that is the underground caves (cave layer,
cave cheese, 2D spaghetti) on the two thirds of a chunk's 5x49x5 lattice
above the stone, and four or five scales of each spaghetti noise where one
is read.

The noise samplers can already skip the Ys a caller does not read
(sample_needed, a bit per Y per column), but only the lerp asked. The range
choice now asks its out-of-range branch for the positions whose selector is
out of range, the interval select asks each branch for the positions that
select it, and lerp, unary and binary samplers pass a caller's mask on.

Every sampler is still called, in vanilla's order, and a cache still fills
its whole volume (its buffer is read by later scalar queries), so only noise
that nothing reads is skipped. A test spoils every value a noise was not
asked for and checks the result bit for bit against the choices spelled out
per value.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 09:59:38 +01:00
Skr1zzzzandClaude Opus 5.5 8c9c801232 Keep game/remote.rs from growing: the AddEntity projectile choice moves out
The new-or-reused id check and the choice between the two spawn paths move
into `tracks_remote_entity` and `spawn_added_projectile` in
remote_projectiles.rs, so the AddEntity handler calls one function and
remote.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:25:49 +03:00
Skr1zzzzandClaude Opus 5.5 1fd78941bd Client: spawning a falling block or TNT no longer walks the whole list
Each AddEntity made two passes over `falling` with thousands of blocks in
the air: `spawn_remote_projectile` first removed any entity under the same
id (ClientLevel.addEntity's removeEntity), and `remote_motion` then looked
the new block up from the front of the list, where it is last.

The handler now checks whether the id is already tracked before
`spawn_entity` tracks it. Only then are `falling` and `tnts` filtered for
it; the crystals and the small projectile lists are still filtered every
time, since the client can add to those itself. `remote_motion` and
`move_entity` search `falling` and `tnts` from the back.

8,000 falling blocks, 256 AddEntity packets (debug test build):
10.6 -> 0.9 ms.

Part of #13007

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 10:31:31 +03:00
Mayonesu0andClaude Opus 5.5 28584b59bf A stack's own tool and attribute modifiers reach the client and the hit
The server now sends a stack's minecraft:tool and
minecraft:attribute_modifiers (Tool.STREAM_CODEC,
ItemAttributeModifiers.STREAM_CODEC), and the client reads them back as
their codecs save them. Single player's client and LAN guests now predict
mining from the stack's tool and show its own modifiers in the tooltip.

Equipment modifiers (detectEquipmentUpdates, ItemStack.forEachModifier)
come from the stack's ATTRIBUTE_MODIFIERS, not the item type's, so
Player.attack's getAttributeValue(ATTACK_DAMAGE) honours them: +20
attack_damage on an iron pickaxe hits for 21.

Fixes #14641

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 05:25:59 +01:00
JustKarkat 6705307882 fix: don't deplete stacked contents when checking recipe craftability
Stacked::try_pick with output=None was a destructive check: it ran the
augmenting-path match and deducted matched items from self. Menu::place_recipe
called it as a pre-check before Menu::place, which then tried to pick again on
the already-depleted stacked contents. With exactly enough ingredients for one
craft (e.g. 3 sugar cane for paper), the second pick failed and nothing was
placed — no ghost, no items moved.

Make try_pick non-destructive when output is None (work on a clone). Only the
actual pick (output=Some) mutates self. This also fixes try_pick_all's binary
search, which called try_pick(mid, None) and depleted stacked before finding
the answer.
2026-11-09 20:56:36 -06:00
JustKarkat c6e670c7d0 fix: allow retry-clicking non-craftable recipes in the recipe book
Clicking a recipe whose ingredients are missing (e.g. paper without sugar
cane) showed the ghost once, but a second click did nothing because
try_place's last_placed guard blocked re-clicking any entry marked
non-craftable. Vanilla always shows the ghost for an uncraftable recipe,
so remove the retry guard. last_placed is still recorded for remote ghost
recipe handling.

Fixes #14616
2026-11-09 20:42:28 -06:00
Riccardo GuerrieroandClaude Fable 5.1 1258ec339a Load the prepared test resources once per test process
horizon-client-lib's unit tests spent 71% of their time in the 708 mobs::
tests and 7% in lan::prediction, and nearly all of that was each test
reading the whole prepared root again in a debug build: Assets (block
registry, tags), BlockFacts, MotionResources, MobData, MobTypes, Biomes,
Items and the collision registry, about 7 s a call under load. A test
calling the fixture 16 times paid 16 times (157 s).

The tests only read those tables and build their own World over them, so
mobs/world.rs keeps the vanilla root's bundle (TestResources) in a OnceLock
and run_test_world builds the per-test World on it as before. A mod root
in a test's scratch folder is still loaded fresh each call, since the same
path can hold different content between tests. test_fixtures::vanilla()
does the same for Assets, RenderAssets, collisions and MotionResources;
lan::prediction's steps_in uses it, and motion.rs and entities.rs can
follow.

Same tests, same cases, same assertions; nothing new is #[ignore]d.
cargo test -p horizon-client-lib --lib on an 8-core laptop at 8 threads:
388 s -> 99 s wall (three interleaved runs each), 3061 s -> 770 s summed.

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

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 01:58:51 +01:00
MSedgeMC b0aeefebe9 port map: the CannotHunt row no longer claims it is unread 2026-11-10 00:55:20 +00:00
MSedgeMC 7cbe3d49b0 port_map: the drowned's fluid push names its arm
Drowned.isPushedByFluid had no row; it is the drowned arm of
living.rs::Mob::pushed_by_fluid now.
2026-11-10 00:50:48 +00:00
MSedgeMC 83122825e5 Test the drowned that a current leaves alone
Mob::pushed_by_fluid, the predicate both push sites of
LivingEntity.updateFluidInteraction read: a drowned with its swimming flag set
answers false, the same drowned with the flag cleared answers true, the water
mobs that never take a push (a cod, a squid, a turtle, a nautilus) answer
false either way, and a zombie answers true. Without the drowned arm the
swimming one answers true too.
2026-11-10 00:50:42 +00:00
MSedgeMC c3af4fadeb A swimming drowned is not pushed by the current
Drowned.isPushedByFluid answers `!isSwimming()`: a drowned swimming after its
target holds its line in a stream, while one walking the bottom is carried
along like any other mob. Horizon answered the plain LivingEntity rule for
every drowned, so a drowned chasing a player through flowing water was swept
off its path, and the current was applied even while its own move control was
driving it.

pushed_by_fluid now answers the drowned with its swimming flag, which
Drowned.updateSwimming keeps on the mob (`extra.flag`) and the clients read
from the shared flags, and the rest of the table stays as it was.
2026-11-10 00:50:42 +00:00
martipopsandClaude Opus 5.5 2f8540be63 Graphics: Horizon's own preset row is named Horizon Preset
The General page showed two rows named Preset: Horizon's own preset, which sets the
options below together, and vanilla's options.graphics.preset. Horizon's is now
Horizon Preset (a new en_us entry; other languages fall back to English until
translated), so the two read apart. The group keeps its name. The search finds both
for "preset", and Horizon's alone for "horizon preset"; the shell_choice_step case
looks for the new name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:48:56 -05:00
MSedgeMC fbf4ddd296 port_map: the freeze immunity names its port
canFreeze had no row in either place: LivingEntity's tag-and-wearables half
and the Skeleton override are both ai.rs::can_freeze.
2026-11-10 00:47:14 +00:00
MSedgeMC a8c16eb5db Test the skeleton that powder snow leaves alone
LivingEntity.aiStep's freezing, through freeze_tick, in a world with a powder
snow block at the mob's feet: a skeleton, a stray, a bogged, a parched and a
wither skeleton gain no frozen tick (0) where a zombie gains one (1), and one
of them put at 140 frozen ticks melts to 138 with no damage where the zombie
takes its 1. Without the skeleton arm the skeleton freezes like the zombie.
2026-11-10 00:47:14 +00:00
MSedgeMC ce66fd40bd A skeleton never freezes
Skeleton.canFreeze answers false, so powder snow builds no frozen ticks on a
skeleton and never deals it the 1 a fully frozen mob takes, and a skeleton
already frozen melts out of it at two ticks a tick. The stray, the bogged, the
parched and the wither skeleton inherit the same false. Horizon only asked the
freeze_immune_entity_types tag — which lists the stray, the polar bear, the
snow golem and the wither — and the worn freeze_immune_wearables, so a plain
skeleton standing in powder snow froze like a zombie.

can_freeze now answers the five skeletons before the tag, which is where
vanilla puts the class override.
2026-11-10 00:47:13 +00:00
Evrim CicekandClaude Opus 5.5 22e92450e4 ExperienceOrb::new builds a fresh orb
The summon and remote-spawn sites build their orb with it, so the new
fall_distance field doesn't grow commands.rs and remote.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 03:37:25 +03:00
Evrim CicekandClaude Opus 5.5 ee1dfabaa6 An orb's first tick doesn't halve its fall in lava
Entity.isInLava is false while firstTick holds, so Entity.baseTick halves
the fall only from the second tick. Review finding on #14440; the
`orb fall distance` group gains an orb summoned inside lava.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 03:22:21 +03:00
RINNECODERandClaude Opus 5.5 7dcca26230 lang: keep the ru_ru check on the layered lookup, as main now adds strings in English first
A ru_ru.json completeness check failed on main's 95 English-only keys (docs/translations.md).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:14:07 -06:00
RINNECODER 1d8865acdf Merge main into #13831 2026-11-09 18:12:52 -06:00
Evrim CicekandClaude Opus 5.5 5e1eab0e05 Experience orbs keep their fall distance and post hit_ground on landing
Part of #14440: an orb's Entity.fallDistance builds up as it falls and is
saved and loaded (and taken by /data merge). Entity.baseTick's fluid step
resets it in water and halves it in lava; Entity.move's long-move ray
resets it past a fall-resetting block or water, and checkFallDamage adds
the drop and, landing after a fall, posts HIT_GROUND. Adds the
`orb fall distance` command-exec group.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 03:07:01 +03:00
voidsip 7f8e095514 Keep ordinary explosion reference tests on the default calculator 2026-11-09 18:04:34 -06:00
MSedgeMC 47b8e5c51d Merge main: keep the guarded anger read beside CannotHunt 2026-11-10 00:03:41 +00:00
91e62194e8 Jukeboxes keep a finished song stopped after a reload and vibrate when a disc goes in or out
`JukeboxBlockEntity.loadAdditional` -> `JukeboxSongPlayer.setSongWithoutPlaying` brings a song
back only from a saved clock, only under its length, and never starts it (level event 1010 comes
from `play` alone): a record saved without a clock, or with one past its song's end, loads silent
at signal 0. `notifyItemChangedInJukebox` posts `BLOCK_CHANGE` for the block's `has_record` — and
`JukeboxPlayable.tryInsertIntoJukebox` posts a second one with the player as its source, against
the state the click found. `JukeboxBlock` decides both clicks by that state, not by the slot, and
`popOutTheItem` pops nothing from an empty slot.

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:58:01 +01:00
DUzzL 9094309407 Let rideable minecarts pick up shulkers beside the rail 2026-11-10 00:48:39 +01:00
martipopsandClaude Opus 5.5 4888b73428 Merge upstream main (#13606) into Pack Options on the settings shell
Pack Options joins the shells pad_clicks_step resets, and its shell arms and
open_pack_options move to options_ui/shell_pages.rs, where main put shell and shell_mut.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:10:04 -05:00
DUzzL d6fb844de4 Load the 5x5 neighbourhood in the prepared-data test fixtures that tick entities
Entity ticking waits for every chunk within 2 columns (ChunkMap.prepareEntityTickingChunk), as of #13953. Add Game::load_ticking_neighbourhood for tests and call it from the fixtures of the 51 prepared-data tests that failed since, and correct the item escape test's drag to 0.98F widened to double.
2026-11-09 23:57:19 +01:00
793565a33f Lecterns take a placed book into has_book, gate the comparator on it and post block_change
`LecternBlock.getStateForPlacement` sets HAS_BOOK from the item's
`block_entity_data.Book` when the placer may use game-master blocks, so a
lectern placed from a book-carrying item draws its book.

`LecternBlock.getAnalogOutputSignal` reads the state's HAS_BOOK before asking
`LecternBlockEntity.getRedstoneSignal`, so `/setblock ... lectern[has_book=true]`
with no book now reads 14 instead of 0, and `has_book=false` reads 0.

`LecternBlock.resetBookState` sets POWERED and HAS_BOOK in one write, then posts
`minecraft:block_change` (the player who put the book on, none when
`LecternBlockEntity.onBookItemRemove` takes it off) and updates below, so a
sculk sensor hears both.

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:49:04 +01:00
voidsip 4bed23dc4c Leave portal placement helpers in their existing module 2026-11-09 16:29:08 -06:00
b820331574 Place a can_place_on block against a sign in adventure mode
SignBlock.useWithoutItem answers PASS when the player may not build and
the sign is not waxed and has no click action to run (SignBlock.java:139-146),
so ServerPlayerGameMode.useItemOn goes on to the item phase
(ServerPlayerGameMode.java:411-427) and ItemStack.useOn's canPlaceOn test
lets a `can_place_on` block place against the sign (ItemStack.java:358-362).
Horizon's sim's sign arm answered SUCCESS, which `use_hand` consumed before
the item was used. `sign_consumes_click` now asks the sign's block entity
the question vanilla asks it, and use_hand only ends the click when it says
a waxed sign, a click-command side or a player who may build takes 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-09 23:20:28 +01:00
81f336b814 Give the wither's nether star its ten-minute lifetime
WitherBoss.dropCustomDeathLoot spawns the star and then calls
ItemEntity.setExtendedLifetime, which sets age to -6000, so the
age >= 6000 discard takes it at tick 12000 instead of 6000. Horizon
spawned it like any other death drop, at age 0, and lost it after
five minutes.

Fixes #13937.

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:48:11 +01:00
Umut Cevdet Koçak 18c2782391 Merge pull request #259 from sunrise-org/fix/perf-upload-public-check
Fix the capture upload E2E driver for the public CDN
2026-11-10 00:47:14 +03:00
umcekoandCodex gpt-6.1-sol eb150b0297 Make the capture upload check work through the public CDN
Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-10 00:29:46 +03:00
Umut Cevdet Koçak 88cc456f65 Merge pull request #258 from sunrise-org/feat/perf-sharing
Move the perf viewer to the site and implement capture sharing in the CLI
2026-11-10 00:25:02 +03:00
umcekoandCodex gpt-6.1-sol b2d4f65e77 Move the perf viewer to the site and add capture uploads and share links
Keep Rust reader artifacts in the game repository, move the viewer source into sunrise-org/horizon-site, and add CLI uploads and remote capture reads. Update fork automation for the organization transfer.

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-10 00:03:48 +03:00
voidsip d42af058e8 Preserve TNT transfer state without trusting saved NBT 2026-11-09 14:58:58 -06:00
voidsip b4b9d03ed5 Keep pending entity load context separate from saved NBT 2026-11-09 14:47:59 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 9f1fb2c77c HDR tone curve test: the scene's peak itself may come back one half-float step off
S's gamma rounds up in half float, to light just above S that the curve holds at S. Whether that comes back to the same half float depends on the GPU's rounding: on an Apple M4 Pro (Metal) it lands one step lower, so the exact check at S failed there. Every stored value below S still comes back bit-identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:45:09 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 46fe2c7f3d Merge main into #13578; graphics.md's HDR paragraph is main's plus this PR's sentences
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:28:40 +01:00
martipopsandClaude Opus 5.5 467d045271 Pack Options on the settings shell
Pack Options (#11486) becomes a screen on the settings shell, as Shaders
is: each Polytone config section is a page, numbers are sliders that stop
at the entry's step, value lists are choices, booleans switch and free
text reads. The first page starts with the pack-wide presets and Reset
all. The shell gives it keyboard and controller focus, Left/Right
stepping, the search (an entry's tooltip included), descriptions with
the performance-impact line in the strip, and Undo from a snapshot taken
when the screen opens. Leaving sends the pack's choices only when they
differ from that snapshot, so an Undo sends nothing.

options_ui's special cases for the page go, with Lines::titled and the
shell list's branch for it. foot_button takes the glyph room itself
rather than through a wrapper. A pad_menu_e2e case, pack_options, runs
the fixture pack through RB, Right, Undo, Left and B.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:25:04 -05:00
JoansitohandClaude Sonnet 5.5 f23a03f6c7 Lightning rod: update the front block's neighbours without redstone experiments
Fixes #14371

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 21:23:34 +01:00
voidsip fa7424ca31 Protect sulfur cube blasts while portal cooldown is positive 2026-11-09 14:15:30 -06:00
Horizon agent 2b3729188a Merge origin/main (brings #14090's test_git_slim fix) 2026-11-09 21:05:33 +01:00
Ludovic Marie 4cea8c2ee6 Merge remote-tracking branch 'origin/main' into split/telemetry-probes 2026-11-09 21:00:24 +01:00
AkirabaneandClaude Sonnet 5.5 45eb484b85 Particles: cull against the camera frustum pulled back 3 blocks, like vanilla
Vanilla tests every particle's point against the camera frustum moved back
3 blocks (ParticleEngine.extract, QuadParticleGroup, Frustum.pointInFrustum).
Horizon only did it behind the opt-in Particle Culling setting, so by default
ParticleEngine::render built a quad for every live particle.

Frustum::pulled_back moves the camera back along its view direction and
Frustum::contains_point is the point test. ParticleEngine::render_in_view
skips a particle outside that frustum before any sprite, light or quad work;
render_culled applies it too, whatever the setting says. render is unchanged.
game.rs passes the camera's frustum on the default path.

Written from the issue's description of the rule; there is no vanilla oracle.

Fixes #7255

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 20:33:25 +01:00
MSedgeMC 0e02985f36 fix: a piglin keeps the guarded anger its brain saved
`PiglinAi` sets `ANGRY_AT` with an expiry when a player breaks a guarded block
near a piglin, and `Brain.Packed` saves every memory with a codec under
`Brain.memories`: the value is the player's UUID and the TTL is the ticks left.
`LivingEntity.readAdditionalSaveData` reads that brain back.

Horizon wrote `minecraft:angry_at` in `mob_to_nbt` but `mob_from_nbt` never read
it: a piglin that a player had angered unloaded with its chunk and came back
with `extra.anger` 0 and no actor UUID, so it stopped attacking and the guarded
event was forgotten.

The load now reads the memory back: a four-int UUID into
`extra.piglin.guarded_angry_at` and the `ttl` into the existing `extra.anger`
counter, with no TTL read as the longest counter there is. The writer moves to
`mobs/piglin.rs` beside it, which also keeps `entity_nbt.rs` from growing.
2026-11-09 19:10:28 +00:00
MSedgeMC 89314c8f13 port_map: the piglin's CannotHunt flag is saved and read
`tools/port_map/game2-004.tsv` now answers `Piglin.addAdditionalSaveData`:
`CannotHunt` is written from the live flag, and `mob_from_nbt` reads it back.
2026-11-09 19:10:28 +00:00
MSedgeMC 0b2072a874 test: a saved CannotHunt reads and writes back
`mob_from_nbt`/`mob_to_nbt` are the pair `Game::load_mob` and `Game::mob_tree_nbt`
go through. `CannotHunt: 1b` loads `cannot_hunt` true and `can_hunt` false, and
the next save writes 1. `0b` and a missing key load false and save 0.

Without the read the flag stays false and the save writes 0: `left: false`,
`right: true` for the loaded flag.
2026-11-09 19:10:28 +00:00
MSedgeMC 8c28931f1d fix: a piglin keeps its saved CannotHunt flag
`Piglin.readAdditionalSaveData` reads `CannotHunt` with
`getBooleanOr("CannotHunt", false)` and `setCannotHunt`, and
`addAdditionalSaveData` always writes it. `AbstractPiglin.canHunt` is false
while the flag is set, and `PiglinAi` asks it before starting a hoglin hunt.

Horizon wrote a hardcoded `CannotHunt: 0` and never read the field, so a
piglin saved with the flag set hunted hoglins again after its chunk reloaded.
The flag now lives in `piglin::Memories`, the save writes it, the load reads
it, and the hunt goal checks `can_hunt`.
2026-11-09 19:10:28 +00:00
Ludovic Marie 0694db7dcb Merge pull request #14152 from horizon-rust/split/telemetry-scrub
🤖 Agent: scrub.rs moved unchanged to horizon-system; horizon-telemetry re-exports it, so the launcher and the ingest server keep their paths.
2026-11-09 20:00:36 +01:00
JoansitohandClaude Sonnet 5.5 31a4a5ea65 Resolve inline atlas sprites in their named atlas
AtlasGlyphProvider looks the sprite up in the atlas the component names;
the GUI atlas keeps its sprites under gui/sprites/, so boss_bar/*, widget/*,
server_list/* and icon/* drew nothing. Draw the missing sprite when absent.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 19:56:25 +01:00
Horizon agentandClaude Opus 5.5 b21058f361 deflect tests: the turned wind charge is past its no-deflect ticks
The two redirect tests built a fresh wind charge, which this PR now (as
WindCharge.deflect) refuses for its first five ticks; their fixture clears
no_deflect_ticks, and a new test checks a fresh one keeps its course and owner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:51:31 +01:00
Evrim CicekandClaude Opus 5.5 0dace8ff46 vehicle/mob fall clip: wait for the forced chunk's 2-column neighbourhood
Since #13953 an entity ticks only once every chunk within 2 columns is
loaded (ChunkMap.prepareEntityTickingChunk). Horizon has that
neighbourhood ready a few ticks after vanilla, so these groups, which
waited for the forced chunk alone, read vehicles and mobs that hadn't
moved yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:50:30 +03:00
Horizon agent 58f80819d9 Merge remote-tracking branch 'rv3n/14131' into rv3-comp 2026-11-09 19:21:19 +01:00
MSedgeMC f606efbf36 Merge remote-tracking branch 'upstream/main' into fix/component-can_eat 2026-11-09 18:03:15 +00:00
Evrim Cicek 5054ffc2ab Merge branch 'refactor/minecarts-split' into fix/hanging-item-stack-config 2026-11-09 21:03:03 +03:00
MSedgeMC 96a7044c15 Merge remote-tracking branch 'upstream/main' into fix/block-entity-pos-from-tag 2026-11-09 18:00:54 +00:00
MSedgeMC e8397cd8eb Merge remote-tracking branch 'upstream/main' into fix/component-can_eat 2026-11-09 17:55:10 +00:00
RLC248 182994edc8 A predicate's terms may be one holder alone or a tag
HolderSetCodec reads an all_of or any_of terms as a list of holders, one
holder alone (at .terms[0]) or a #tag. The dedicated server's startup check
now follows a lone holder like the list's first element, and refuses a world
whose terms names a predicate tag no pack defines (Unbound tags in registry).
The evaluation reads a lone holder too, so a lone any_of term is true when
its predicate is.

Part of #12711
2026-11-09 18:54:27 +01:00
Evrim Cicek dd2d560901 Merge branch 'refactor/minecarts-split' into fix/tnt-minecart-explosion-power 2026-11-09 20:51:09 +03:00
Evrim Cicek 0a48f1eade Merge remote-tracking branch 'upstream/main' into fix/hanging-item-stack-config 2026-11-09 20:44:56 +03:00
MSedgeMC 9f51db9b40 port_map: BlockEntity.getPosFromTag is a port
The row said a block entity saved in the wrong chunk keeps its saved
x/z; `chunk::block_entity_pos` now moves it into the chunk that saved it,
so the row cites it.
2026-11-09 17:44:04 +00:00
MSedgeMC 301fc5fc05 test: a wrongly chunked block entity is read into its chunk
`chunk::block_entity_pos`'s test pins the arithmetic: (37, 70, -3) in
chunk (0, 0) is (5, 70, 13) after vanilla's `sectionRelative`, an
already-correct position is untouched, and another chunk moves its own
corner.

`a_block_entity_saved_under_another_chunks_coordinates_moves_here`
decodes a chunk whose `block_entities` list names x=37, z=-3 at chunk
(0, 0) and expects the chest at (5, 70, 13). Without the fix it stays at
(37, 70, -3).
2026-11-09 17:44:04 +00:00
MSedgeMC 74db568335 fix: a block entity saved in another chunk moves into the chunk that holds it
`BlockEntity.getPosFromTag` reads the tag's `x`, `y`, `z`, and when they
name another chunk it warns and keeps only the low four bits of `x` and
`z`, so the entity stays in the chunk whose save wrote it. Horizon's
`decode_block_entity` returned the saved coordinates as they were, so a
block entity saved under the wrong chunk's coordinates landed at a
position that chunk may not even hold, instead of where vanilla puts it.

`chunk::block_entity_pos` does the clamp, and the chunk decoder uses it
for every block entity it reads. No line growth in `save.rs` (the size
gate's 3000-line rule).
2026-11-09 17:44:04 +00:00
Horizon agentandClaude Opus 5.5 a03902b64d Use the stack's whole consumable component, finish the merged series
The eight component branches (#14131-#14138) each edited the same spots and
three of them left an unclosed block in finish_consuming. Merged here:

- item_sync::stack_consumable builds the component a use reads once: the
  stack's own when it has one, with Consumable.CODEC's defaults for the
  fields it leaves out (1.6 s, eat, entity.generic.eat, particles), else the
  item's. finish_consuming, the per-tick particles and sounds and the
  instant-consume check use it.
- Consumable.canConsume's food check asks the stack's food component.
- A direct sound reads SoundEvent.DIRECT_CODEC's `sound_id`, and every
  ItemUseAnimation name maps (trident, crossbow and spyglass were eat).
- The glider test's doc comment is back on its test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:42:09 +01:00
Horizon agent 30637c0820 Merge remote-tracking branch 'rv3/14136' into comp
# Conflicts:
#	crates/horizon-client/src/game/consume.rs
#	crates/horizon-client/src/item_sync.rs
2026-11-09 18:37:24 +01:00
Horizon agent b63d7491d2 Merge remote-tracking branch 'rv3/14135' into comp
# Conflicts:
#	crates/horizon-client/src/game/consume.rs
#	crates/horizon-client/src/item_sync.rs
2026-11-09 18:37:21 +01:00
Horizon agent e64e477126 Merge remote-tracking branch 'rv3/14133' into comp
# Conflicts:
#	crates/horizon-client/src/item_sync.rs
2026-11-09 18:37:14 +01:00
Horizon agent dc94adc898 Merge remote-tracking branch 'rv3/14134' into comp
# Conflicts:
#	crates/horizon-client/src/item_sync.rs
2026-11-09 18:37:05 +01:00
Horizon agent f914bcd4a9 Merge remote-tracking branch 'rv3/14138' into comp
# Conflicts:
#	crates/horizon-client/src/item_sync.rs
2026-11-09 18:36:53 +01:00
Horizon agent 0a6d0dd257 Merge remote-tracking branch 'rv3/14137' into comp
# Conflicts:
#	crates/horizon-client/src/item_sync.rs
2026-11-09 18:36:51 +01:00
Horizon agent c719e4ac0e Merge remote-tracking branch 'rv3/14132' into comp
# Conflicts:
#	crates/horizon-client/src/item_sync.rs
2026-11-09 18:36:50 +01:00
Nikita Maximilian Grimm 7049d0e811 Merge remote-tracking branch 'origin/main' into hdr-one-peak
# Conflicts:
#	docs/graphics.md
2026-11-09 18:34:01 +01:00
rdbtCVSandClaude Sonnet 5.5 78e094e614 Merge main into fix/tnt-minecart-explosion-power
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 17:29:33 +00:00
rdbtCVSandClaude Sonnet 5.5 f81f6de46b cargo fmt
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 17:23:28 +00:00
RLC248 f64da572af A thrown potion or bottle is a level entity
A splash or lingering potion or experience bottle that a player throws
or a dispenser shoots went into a side list that is not part of the
level, so @e, /data get entity, /execute if entity and /kill never found
it. Vanilla adds it with level.addFreshEntity like any entity.

Throws and dispensers now make the same level projectile /summon does
(ProjectileKind::Potion / ExperienceBottle); the player's throw uses
Projectile.shoot_from_rotation (#13201).
2026-11-09 18:22:49 +01:00
Horizon agentandClaude Opus 5.5 fe0a4d80bf Mouse Tweaks: rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:22:34 +01:00
MSedgeMC ff42a99d98 port_map: Dispensable comes from the stack 2026-11-09 17:20:59 +00:00
MSedgeMC aced4bb6b9 test: Dispensable comes from the stack 2026-11-09 17:20:59 +00:00
MSedgeMC 97a323b499 fix: Dispensable comes from the stack 2026-11-09 17:20:59 +00:00
MSedgeMC 227333eacd port_map: Use remainder comes from the stack 2026-11-09 17:20:53 +00:00
MSedgeMC 9367ed7710 test: Use remainder comes from the stack 2026-11-09 17:20:53 +00:00
MSedgeMC e15589bbbb fix: Use remainder comes from the stack 2026-11-09 17:20:53 +00:00
MSedgeMC 84fe5b4f12 port_map: Consumable particles come from the stack 2026-11-09 17:20:47 +00:00
MSedgeMC 7ee566f6b7 test: Consumable particles come from the stack 2026-11-09 17:20:47 +00:00
MSedgeMC 3774ca6edd fix: Consumable particles come from the stack 2026-11-09 17:20:47 +00:00
MSedgeMC c73321876c port_map: Consumable sound comes from the stack 2026-11-09 17:20:41 +00:00
MSedgeMC 19d083fa26 test: Consumable sound comes from the stack 2026-11-09 17:20:41 +00:00
MSedgeMC 8d35e7fc0a fix: Consumable sound comes from the stack 2026-11-09 17:20:41 +00:00
MSedgeMC 46f0546de6 port_map: Consumable animation comes from the stack 2026-11-09 17:20:13 +00:00
MSedgeMC 7c173c30b1 test: Consumable animation comes from the stack 2026-11-09 17:20:13 +00:00
MSedgeMC 715a969071 fix: Consumable animation comes from the stack 2026-11-09 17:20:13 +00:00
MSedgeMC 5097c53509 port_map: Consumable seconds come from the stack 2026-11-09 17:20:08 +00:00
MSedgeMC a89477a4b9 test: Consumable seconds come from the stack 2026-11-09 17:20:08 +00:00
MSedgeMC 430b6dc4c5 fix: Consumable seconds come from the stack 2026-11-09 17:20:07 +00:00
MSedgeMC e591b36a8d port_map: Food can_always_eat comes from the stack 2026-11-09 17:20:01 +00:00
MSedgeMC 701eaa6f9c test: Food can_always_eat comes from the stack 2026-11-09 17:20:01 +00:00
MSedgeMC 018a51c27f fix: Food can_always_eat comes from the stack 2026-11-09 17:20:01 +00:00
MSedgeMC 4db980e5de port_map: Food nutrition and saturation come from the stack 2026-11-09 17:19:53 +00:00
MSedgeMC d40ab7df1a test: Food nutrition and saturation come from the stack 2026-11-09 17:19:53 +00:00
MSedgeMC 54578041bc fix: Food nutrition and saturation come from the stack 2026-11-09 17:19:52 +00:00
Horizon agentandClaude Opus 5.5 adc454cfc9 Mouse Tweaks and sorting move to game/extras/, one module each (layer plan M5)
A pure move: game/tweaks.rs becomes game/extras/mouse_tweaks.rs, and
the sort buttons and key leave it for game/extras/sorting.rs. Paths,
visibility (pub(in crate::game)) and imports only; game.rs loses its
mod line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:19:15 +01:00
Horizon agent 2cdecbf069 Merge remote-tracking branch 'origin/pr-13893' into layers/extras-tweaks 2026-11-09 18:19:15 +01:00
Horizon agentandClaude Opus 5.5 bdec76846e Merge main: keep main's blocking_item_max_damage
main's 3b34446f84 added the same helper with the fuller ItemStack.isDamageableItem rule (an
explicit DAMAGE component on a non-damageable prototype); this branch keeps that one and its own
ItemDamageFunction.apply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:08:04 +01:00
Horizon agentandClaude Opus 5.5 93ebb80b92 Carry blocking_item_used through the staged equipment hurt
main's health/equipment.rs (3cdf31772f) runs a hurt in stages and copies the block results
between them; it now copies blocking_item_used too, so a staged hit reports the shield use as
the one-shot hurt does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:58:51 +01:00
Evrim Cicek 345041401e Merge branch 'refactor/minecarts-split' into fix/tnt-minecart-explosion-power
# Conflicts:
#	crates/horizon-client/src/game/minecarts.rs
2026-11-09 19:36:49 +03:00
Evrim Cicek 72dff2d5b7 Merge branch 'refactor/entity-nbt-hanging' into fix/hanging-item-stack-config 2026-11-09 19:24:22 +03:00
Evrim Cicek 194a86eff3 Merge branch 'refactor/entity-nbt-hanging' into fix/hanging-item-stack-config
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
2026-11-09 19:24:21 +03:00
Nikita Maximilian Grimm 18c03d23d8 Merge remote-tracking branch 'fork/hdr-one-peak' into hdr-one-peak 2026-11-09 17:14:50 +01:00
Horizon agentandClaude Opus 5.5 b8faec92f1 perf(hub): the entity tracker's send pass on several threads
With a crowd, the tracker's send pass (each active entity's changes and new
pairings, to each viewer) ran on one thread. Each entity's packets are now
made once on several threads, then each viewer's are handed over in entity
order on several threads. Every viewer gets the same packets in the same
order; a test compares both paths byte by byte.

Ideas from HorizonsX (MIT, by cantoptp-bit), commits 091bb8e1c6 and
34e43cef96; code written fresh against main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:08:58 +01:00
Horizon agent dceee849cb Merge remote-tracking branch 'origin/main' into r-13578
# Conflicts:
#	crates/horizon-client-render/src/gfx/native_post.rs
2026-11-09 17:08:54 +01:00
Horizon agentandClaude Opus 5.5 10b318cd6b Merge main into split-renderer
main moved more of game.rs out (#13877, #13878, #13880...): the conflict is only the
neighbours of the moved functions; game.rs takes main and drops the four functions
this branch moves to game/render_settings.rs, unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:08:14 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 79cfecbdb9 HDR float frame: main's encoding-switch test tunes a tier's gain, as one peak has no share
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:05:29 +01:00
MrCloudy2andClaude Opus 5.5 298d3f12e9 A player's wind charge can't be turned in its first five ticks
WindCharge.deflect refuses while noDeflectTicks (5, one less after each tick,
not saved) lasts: a projectile hitting a young wind charge doesn't redirect it
(Projectile.onRedirectProjectile), and a player's blow goes on as an attack
that hurts nothing. A breeze's wind charge has no such wait.
Harness: tools/test_wind_charge_no_deflect_ticks_parity.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:02:39 +01:00
Horizon agentandClaude Opus 5.5 73a745339e Carry an arrow's piercing in a combat flag so creatures.rs doesn't grow
creatures.rs is over 3000 lines (docs/layers.md#file-size). The arrow's hit on the player goes
through shield.rs's arrow_hits_player, which sets combat.piercing_hit; hurt_player_from takes it
as it takes rocket_hit and hands it to player_blocking. Same behaviour as hurt_player_with_pierce.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:00:58 +01:00
Horizon agent 70287510ab Merge remote-tracking branch 'origin/main' into fix-11507 2026-11-09 16:59:46 +01:00
Horizon agentandClaude Opus 5.5 321b0c5a98 Lang: the dead-key check reads every crate's sources
A sentence key is alive when any crate names it: the layer split is moving
client code into crates of its own, and the strings move with it. The
horizon. key check keeps the four client crates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:50:26 +01:00
Horizon agentandClaude Opus 5.5 3089267e7c Dolphin treasure: read the found position without moving it
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:50:01 +01:00
Horizon agentandClaude Opus 5.5 721d5c6fda Merge origin/main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:50:00 +01:00
Horizon agentandClaude Opus 5.5 895726d381 rustfmt
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:39:41 +01:00
Horizon agentandClaude Opus 5.5 3877ae52d8 Merge origin/main into the branch
The verify job compared big files against this branch's old base, so main's own growth of options_ui.rs since then failed the size check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:35:03 +01:00
Nikita Maximilian Grimm 8e46f3971d Merge remote-tracking branch 'origin/main' into hdr-one-peak
# Conflicts:
#	crates/horizon-client-render/src/gfx/native_post.rs
2026-11-09 16:30:19 +01:00
Horizon agentandClaude Opus 5.5 1f96d244f9 Read a sprite's .mcmeta up to its first value, as vanilla does
ResourceMetadata.fromJsonStream reads one JSON value with Gson and never looks
past it, so packs leave notes after the closing brace. CozyUI+'s highlighted
button ends its .mcmeta with `//` lines: Horizon's strict serde_json read
rejected the file, so the sprite lost its nine slice and animation and drew
as its whole 16-frame strip (#3046).

The nine-slice, GUI animation, texture-flag and atlas sprite readers now share
packs::first_json with pack.mcmeta's reader.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:22:17 +01:00
Horizon agentandClaude Opus 5.5 ebe1a5d52b Wardens: silent ones make no sound, forced riders get off to dig; withers' idle volleys wait for Normal
- A Silent:1b warden played its emerge, dig, roar, sniff, tendril, attack and sonic boom sounds:
  both warden sound helpers now check `silent`, as Entity.playSound does (#8835).
- ForceUnmount was stubbed out: a warden put on a vehicle with /ride or a summon's Passengers
  never got off, so it could never dig. It now runs vanilla's unRide (passengers ejected, the warden
  set down where its vehicle lets it off) and stops in the tick it starts (#8833).
- WitherBoss.customServerAiStep counts the side heads' idle updates only on Normal and Hard: on Easy
  a wither fired its random blue skulls all the same (#8840).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:17:45 +01:00
Horizon agentandClaude Opus 5.5 27979c816b Feeding particles: tadpole slime ball, panda love hearts, dolphin treasure
- Tadpole.feed draws its happy_villager particle on the client too; a tadpole
  is never isBaby, so the client's feed prediction skipped it (#8554).
- Panda.mobInteract's setInLove broadcasts entity event 18, the love hearts
  (#8555).
- DolphinSwimToTreasureGoal.start broadcasts entity event 38 once it finds a
  treasure, and Dolphin.mobInteract answers a #minecraft:fishes item with
  SUCCESS on the client, so the hand swings and the fish isn't eaten (#8567).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:16:35 +01:00
Horizon agent 61a0362859 Merge remote-tracking branch 'origin/main' into fix-11507 2026-11-09 16:14:13 +01:00
MSedgeMC 166073d4bc Re-run checks: the previous run failed in an unrelated fixture / harness 2026-11-09 14:52:23 +00:00
Horizon agentandClaude Opus 5.5 92742bef1b horizon-system: the scrubber leaves horizon-telemetry (layer plan M5)
scrub.rs moves unchanged from horizon-telemetry to horizon-system (engine);
horizon-telemetry re-exports it at horizon_telemetry::scrub for the launcher.
The repro export (agent control) reads it there, so gameplay no longer uses
horizon-telemetry for it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:36:00 +01:00
Horizon agentandClaude Opus 5.5 bb29b70b32 Cargo.lock: horizon-system for horizon-client and horizon-optifine
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:23:16 +01:00
Horizon agentandClaude Opus 5.5 3ad8a18a7b horizon-system: the process probes leave horizon-bench (layer plan M5)
rss_bytes, cpu_seconds and load_average move to horizon-system (engine);
horizon-bench re-exports them for the launcher. horizon-system's cpu() and
ram_bytes() become public and replace horizon-bench's identical copies.
The dedicated server's performance report and cem_expr_bench read them
there, so gameplay no longer uses horizon-bench for them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 15:14:20 +01:00
Evrim Cicek 16237bb2b7 Merge remote-tracking branch 'upstream/main' into fix/tnt-minecart-explosion-power
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-09 16:47:50 +03:00
Evrim Cicek 0a11f464a3 Merge remote-tracking branch 'upstream/main' into fix/hanging-item-stack-config
# Conflicts:
#	crates/horizon-client/src/entity_nbt.rs
#	crates/horizon-client/src/game/dispenser.rs
2026-11-09 16:42:23 +03:00
Skr1zzzzandClaude Opus 5.5 71e2401edc Move building and adopting the renderer out of game.rs into game/render_settings.rs
Part of #11857. new_renderer, adopt_renderer, forget_atlas_slots and all_sections_changed join game/render_settings.rs. Methods that were private in game.rs become
pub(super), the same reach.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:29:00 +03:00
RINNECODERandClaude Opus 5.5 b7bb1d0c53 Game translations: drop 8 keys no code asks for, and check en_us against the code
A sentence key is the English text itself, so rewording a setting's text left
the old sentence, and its translations, in all 87 lang files. Eight of them
are no longer named anywhere in the code: the five old descriptions #13802
lists (FOV, HDR output, view bobbing, the two entity culling modes) and three
nits labels. They are removed from every file.

every_sentence_key_in_en_us_is_one_the_code_names fails on a sentence key
that no client crate names as a string literal, so the next rewording can't
leave one behind. The source walk it shares with
every_horizon_key_the_code_names_is_in_en_us now also reads
horizon-client-input, which asks for the gamepad's "Hotbar: Next Slot".

bundled_horizon_strings_follow_the_language checked ru_ru through
Language::load, whose en_us layer fills every gap, so it could not fail. It
now reads ru_ru.json's own keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 05:30:49 -06:00
RINNECODERandClaude Opus 5.5 6c5f62af35 Spectator camera: a server's camera on an armor stand holds the view
ClientPacketListener.handleSetCamera takes any entity the level holds, but
remote_set_camera only looked among the mobs, so a camera on an armor stand
(the usual target of a server's cutscene or menu scene) was dropped: the
view stayed on the player, who kept moving and turning. The stand now holds
the camera like a mob does: the view looks out of its eyes along its yaw,
the player sends no moves, the crosshair skips the stand and first person
does not draw it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 05:25:24 -06:00
Tran Anh Van d029364bd4 Use Level.randValue for thunder strike columns and trap horse RNG for scatter
ServerLevel.tickThunder picks its strike column via Level.getBlockRandomPos(minX, 0, minZ, 15), which advances Level.randValue (Ticks::block_random_pos) and extracts bits 2..=5 for X and 10..=13 for Z instead of drawing from Level.random.

SkeletonTrapGoal.tick draws each additional trap horse's horizontal push (two triangle(0.0, 1.1485) draws) from the original trap horse's own random after creating and mounting its skeleton rider, rather than drawing from Level.random before rider creation.
2026-11-09 18:19:33 +07:00
AppaandCodex aac293db9b Keep the boat identity across loot advancement rewards
Co-Authored-By: Codex (GPT-6) <[email protected]>
2026-11-09 00:25:43 -08:00
AppaandCodex a328e9c5db Keep chest boat loot handling in the boat module
Respect the repository size limit on commands and LAN action modules.

Co-Authored-By: Codex (GPT-6) <[email protected]>
2026-11-09 00:24:50 -08:00
AppaandCodex 4272268cbc Guard chest boat loot fixtures with a fresh hopper cooldown
Co-Authored-By: Codex (GPT-6) <[email protected]>
2026-11-09 00:21:18 -08:00
AppaandCodex 3ef0ebf52f Fix chest boat loot unpacking for hopper access and destruction
Roll pending loot before automation accesses chest-boat slots or destroying
removals spill them. Keep occupied slots, synchronize open-menu copies, and
award container loot only for the player opening a pending table.

Co-Authored-By: Codex (GPT-6) <[email protected]>
2026-11-09 00:17:30 -08:00
MSedgeMC 35fc116bd3 fix: drop the goat's old call and pass the memory value to number 2026-11-09 06:41:45 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 cc100b4470 Merge origin/main into hdr-one-peak
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 07:20:47 +01:00
MSedgeMC 2a95475e8f refactor: keep the goat's save code in goat.rs
`entity_nbt.rs` is over the 3000-line limit and may not grow (docs/layers.md
#file-size), so the goat's save pair moves into `mobs/goat.rs`: the screaming
and horn fields `Goat.addAdditionalSaveData` writes plus the long jump
cooldown memory, and their read side. `entity_nbt` keeps a one-line call.
2026-11-09 05:52:47 +00:00
MSedgeMC 47894e831f port_map: a goat's long-jump cooldown is saved and read
`Goat.addAdditionalSaveData`'s row in `tools/port_map/game-012.tsv` names the
three own fields; it now also names the `GoatAi` `LONG_JUMP_COOLDOWN_TICKS`
brain memory that the save covers.
2026-11-09 05:18:42 +00:00
MSedgeMC 5e735bd030 test: a goat's long-jump cooldown through the chunk save
`mob_to_nbt`/`mob_from_nbt` are the pair `Game::mob_tree_nbt` and
`Game::load_mob` go through. A goat with 57 ticks of long-jump cooldown saves
`Brain.memories."minecraft:long_jump_cooling_down"` as `{value: 57}` and the
reloaded goat's `frog::jump_cooldown` is 57 again. A goat with no cooldown
writes no memory, even over a compound that still names one.

Without the write the save has no memory (left `None`, right `Some(Compound({"value": Int(57)}))`), and the
reloaded goat has no cooldown (left `None`, right `Some(57)`).
2026-11-09 05:18:42 +00:00
MSedgeMC da4591bc88 fix: a goat keeps its long-jump cooldown in its chunk save
`GoatAi` sets `LONG_JUMP_COOLDOWN_TICKS` when a goat long jumps, and
`CountDownCooldownTicks` counts it down; `Brain.Packed` saves every brain
memory with `LivingEntity.addAdditionalSaveData` and reads it back.

Horizon kept the cooldown in the goat's `extra.memories` (the shared
`frog::jump_cooldown` the long jump goal asks) and wrote no `Brain`, so a goat
that had just long jumped unloaded with its chunk and came back ready to jump
again. The save now writes `minecraft:long_jump_cooling_down` as the integer
memory it is and the load puts it back in the goat's memories.
2026-11-09 05:18:42 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 dbcbe4fe87 HDR one peak docs: the identity holds where Peak reaches 1000/203 Paper White
The design note and graphics.md said a display at 1000 nits or more shows
the scene as written. That holds at a paper white of 203; in general the
curve is the identity where Peak Brightness is at least 1000/203 times
Paper White, so say that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 05:05:05 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 8423eabc57 HDR float frame: pin one peak's identity at the settings' extremes
Paper White now runs from 10 to 480 nits and Peak up to 10 000 (#12881): the tone curve
test checks that the world shows exactly as written wherever the display's peak reaches
the scene's, at 480/10 000 and 10/200 nits too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 04:30:47 +01:00
Nikita Maximilian Grimm fd46aa03c5 Merge remote-tracking branch 'origin/main' into hdr-one-peak 2026-11-09 04:29:46 +01:00
Nikita Maximilian Grimm 87f2c1314e Merge branch 'hdr-step5-gates' into hdr-one-peak 2026-11-09 04:12:22 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 4c2a2c42d2 HDR float frame: one peak, the world mastered for 1000 nits
On the float frame the world's light no longer depends on the display. Light sources
multiply their brightest pixels by fixed gains in multiples of paper white (1.6, 2.4,
2.8 and 4 from faint glowers to the sun), and HDR lighting's strongest light by 3. The
tone curve alone fits that scene to the display: light above the scene's peak (1000/203
of paper white, a 1000-nit display at BT.2408's 203-nit white) is held at it, keeping
its hue, then BT.2390's EETF maps the scene's peak onto the display's.

For players: on a 1000-nit display the world shows exactly as written; a 1500-nit or
brighter one shows the same picture, the sun included, instead of a brighter sun and
lava; a dimmer one keeps its midtones and rolls the highlights off below its peak.
Before, the gains scaled with the display's headroom and the curve then compressed
that light again from a peak it derived from the same headroom, so the look changed
with the Peak setting.

Light Horizon doesn't lift (HDR Lighting off, the title, a 0.2 pack's own) has no
known peak, so there the curve keeps the source that follows the display, as the 0.2
contract describes. HDR off, HDR Lighting off, the HUD, the black lift, the SDR
screenshot's shoulder and the 16-bit or 8-bit compatibility frame (HDR's default until
step 5, which changes the look once) are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 03:26:04 +01:00
umcekoandClaude Opus 5.5 3d11f0b6c6 Merge upstream main into perf-platform
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 21:15:53 +03:00
umcekoandClaude Opus 5.5 db571535c2 Merge perf-platform web work into the upstream sync
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 21:07:08 +03:00
Umut Cevdet Koçak 7d9d35c729 Merge pull request #257 from UMCEKO/plat/web-finish
Perf web: call tree, flame graph, info points, copy id, bench and compare in every view
2026-11-08 21:03:37 +03:00
umcekoandClaude Opus 5.5 6354608451 Merge perf-platform into the finished web viewer
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 20:47:45 +03:00
umcekoandClaude Sonnet 5.5 1fc4ccd439 Perf web: UI review fixes (numbers from the wasm, no file name, no duplicated views, units and labels)
- Summary tiles read the wasm's own series stats (new optional `stats` on series rows, asked for with filters.stats); the old browser-side statistics disagreed with the CLI summary (MSPT 8.9 against 10.7, CPU 8.47 against 6.6).
- Queries no longer carry the real file name, so the Query tab never shows it.
- Slow ticks: every kept tick opens into its full span tree; the meaningless min/median/p95 of the slowest 16, the histogram and the sparkline are gone. The summary no longer repeats the worst ticks and lists only the top steps of the tick.
- Metadata: tabs that only repeated Memory, Network and World are gone, rows without data are left out, empty tabs are hidden, enum values read as words, and the mod crate column reads the `crate` field the wasm sends.
- Units on every number, frame figures say frames, warnings are worded from their codes, compare rows have readable names and drop an all-"not enough data" verdict column, network packet columns hide when nothing was counted, TPS windows longer than the capture are not shown.
- Keyboard focus is no longer hidden under the sticky tab bar, and rows that open show a chevron.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 20:42:38 +03:00
umcekoandClaude Sonnet 5.5 ce9fdee6d4 Perf web: offer only the exports the capture can fill, group by thread ignores the picked thread, one verdict colour scheme, strings through t()
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 20:33:14 +03:00
umcekoandClaude Sonnet 5.5 8d1b4c8cca Perf web: every row view shows the change and verdict against a second capture
The diff gains opt-in function and call-path rows (--calls, calls in hp_diff), matched by stable id. One comparison state feeds Summary, Spans, Functions and the Call tree; rows only the second capture has are listed apart.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 20:22:47 +03:00
umcekoandClaude Sonnet 5.5 fee41659bd Perf web: hide the sample picker when there is one choice, drop an unsafe cast in export
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 20:04:27 +03:00
Evrim Cicek 4c246e24f2 Merge remote-tracking branch 'upstream/main' into fix/tnt-minecart-explosion-power
# Conflicts:
#	crates/horizon-client/src/game/minecarts.rs
2026-11-08 20:02:17 +03:00
umcekoandClaude Sonnet 5.5 b0154fc77d Merge plat/web-bench
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 19:57:30 +03:00
umceko 2dbff9aefe Merge plat/web-points 2026-11-08 19:57:16 +03:00
umceko dee8aecd7a Merge plat/web-flame 2026-11-08 19:57:15 +03:00
umceko 3a0a7390bf Merge plat/web-tree 2026-11-08 19:57:13 +03:00
umcekoandClaude Sonnet 5.5 e434d37311 Perf web: info points on well-known spans and functions, and a copy-id control on every row
Spans and functions the profiler meets most (tick_blocks, tick_lan, streaming,
tick_mobs, lan_chunks, random_ticks, allocator and memory calls...) get a short
explanation keyed by stable id in the translation file, shown as an accessible
hover and focus tooltip. Every row of the Summary, Spans, Functions, Call tree
and Slow ticks views copies its stable id from a control that appears on row
hover or keyboard focus, so rows stay clean at rest.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 19:56:27 +03:00
umcekoandClaude Sonnet 5.5 544600c10a Perf web: flame graph view for the call tree
A List / Flame graph toggle in the Call tree tab draws the current side, thread,
selection, grouping, merge mode and focus as a canvas flame graph: widths are time,
colours are the tree's crate groups, hover shows name, time and share, a click zooms
in with a trail back, and arrow keys, Enter and Escape do the same from the keyboard.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 19:49:44 +03:00
umcekoandClaude Sonnet 5.5 75e0f7387b Perf web: call tree with colour by crate, group by, selections, detail panel and search
The tree rows carry their crate, and a request can ask for each row's own time as a percent.
The tree tab is split into focused components; chains of single-child functions share a line.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 19:41:38 +03:00
Umut Cevdet Koçak 285846c5ee Merge pull request #256 from UMCEKO/perf/w1-web-ui
Web UI for horizon-perf
2026-11-08 19:33:32 +03:00
umcekoandClaude Sonnet 5.5 9df9c5bde2 Perf web: Bench tab with frame times per phase, repeat statistics and A/B verdicts
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 19:29:59 +03:00
umcekoandClaude Opus 5.5 28561fd634 Launcher: a native mod's generated main uses the game's current allocator
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 19:19:52 +03:00
umcekoandClaude Opus 5.5 f3613a539d Perf web: landing page, tabs only where there is data, and no duplicated views
The no-capture screen is now a landing page: what the viewer reads and how to get a capture. A tab appears only when its query answers with rows for the side on show, so GPU is gone from a server and empty tabs are gone everywhere; Metadata's sub-tabs follow the same rule.

Health, and Summary's network and dimension cards, repeated other views and are gone. So are the file name and size, the report box, New profile, the sort direction and row limit, the placeholder flame graph, and id chips.

Fixes: slow ticks say they cover only the slowest kept, in time order; query errors show their real message; Compare is a table of real rows for the side on show; table headers line up with their columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 19:18:46 +03:00
umcekoandClaude Opus 5.5 04a9f56511 Perf web: review fixes, design-system polish and no upload path
Removes sharing entirely: the Share button, share links, the upload API, its S3 storage and the CLI's `share` and `upload`. A capture stays on the machine.

Fixes:
- ureq and the snapshot files are gone, so the wasm builds and the tree is 7,600 lines lighter
- merge mode hides wrappers and merges a function across its callers
- `group --by mod` backs the mods view, charging a sample to its innermost mod frame
- a failed compare shows its error, and the compared capture is closed when replaced
- Hot shows milliseconds rather than calling them percent; Tree bars share one scale
- tick details line up; wasm replies are typed structs; launcher lock is current

Polish follows docs/design-system.md: Geist, list rows with aligned number columns, one accent, one sticky tab row, a real opening screen, focus states and reduced motion. Panels share one query hook, and dead icons, strings and exports are removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 19:00:20 +03:00
Claude 5ea2d3c0fb Perf web UI: host-machine tab, new profile button, drop filename/top drop title
Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-11-08 16:20:42 +01:00
Claude be3db9da27 Perf platform web UI: complete UI1-UI7 client and U1/U2 upload API
Fan out implementation of the remaining perf-platform web UI pieces and upload API:
health/metadata, call tree/group-by/select/detail/search, flat/mods/merge/info,
flame graph and ticks tab, compare/GPU/export/copy/share/open links, and
upload route handlers, S3 storage, validation, share pin, sweep, rate limit.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-11-08 16:12:05 +01:00
Claude 0d6d1f1f66 Perf platform wasm + web UI updates
Co-Authored-By: Claude Code <[email protected]>
2026-11-08 15:43:10 +01:00
Claude bc4559b024 Improve web/perf UI: tabs, paste, panels, theme, typography
Co-Authored-By: Claude Code <[email protected]>
2026-11-08 15:42:48 +01:00
FryedCheese b4733ffec0 Merge branch 'horizon-rust:main' into main 2026-11-08 23:19:56 +13:00
FryedCheese 1b8e661146 Merge pull request #1 from Web-mc1/studio-screen-bridge
Add Screen::Studio so script windows stop borrowing the chat slot
2026-11-08 21:09:44 +13:00
Web-mc1 95b6b28fcb Add Screen::Studio so Studio windows don't borrow the chat slot 2026-11-08 20:52:29 +13:00
umcekoandClaude Opus 5.5 993525d333 Merge upstream main into perf-platform
Upstream moved Game::shut_down and idle to game/window_handler.rs and loading_frame and start_game to game/loading_window.rs; finish_profile and the benchmark set and profile fields move with them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 10:14:49 +03:00
Umut Cevdet Koçak 3bd70dbc06 Merge pull request #255 from UMCEKO/plat/L1
Perf platform L1: retire the slow-tick span log lines; docs point to captures
2026-11-08 07:59:40 +03:00
umcekoandClaude Sonnet 5.5 0b4c261d0c Perf platform L1: keep per-event attribution as a log line, pacing_bench drops pre-capture frames
The slow ring no longer shows up as span lists in the log, but whose packets or events took a tick
stay in the server owner's log as a separate line. pacing_bench keeps only frames over the threshold
recorded during the capture.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 07:53:56 +03:00
umcekoandClaude Sonnet 5.5 caac772100 Perf platform L1: slow-tick and slow-frame span lists leave the log; pacing_bench reads captures; docs point to captures
The slow ring and the captures keep the steps of slow ticks and frames; the notes channel that only fed the log line (event timings, packet notes, spawn counters) goes, and the spawn counters move to the counter registry.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 07:36:33 +03:00
Umut Cevdet Koçak 1d7e15c969 Merge pull request #254 from UMCEKO/plat/R1b
Perf platform R1b: rate-limited transfer of the server's capture into the client's file
2026-11-08 07:12:22 +03:00
umcekoandClaude Sonnet 5.5 68685775d9 Perf platform R1b: rate-limited transfer of the server's capture into the client's file
The server sends its finished file in 32 KiB chunks over horizon:perf, at most 256 KiB/s and not while the guest has a backlog. The client merges it field by field into its own stream (PartMerger, no decode), or saves it unchanged for profile server alone; a cut transfer ends the file with SERVER_PART_INCOMPLETE.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 07:07:33 +03:00
Umut Cevdet Koçak e87894a81d Merge pull request #253 from UMCEKO/plat/R1a
Perf platform R1a: profile a remote Horizon server from a client (channel, level 4, server copy)
2026-11-08 06:42:23 +03:00
umcekoandClaude Sonnet 5.5 35d8ee793f Perf platform R1a: profile a remote Horizon server from a client over horizon:perf
A client asks a Horizon server (LAN host, dedicated server) to capture its side: operator level 4, one capture at a time, the server logs who profiled and keeps its copy in reports/. profile server start|stop work on a joined server; a bare profile also asks and a refusal is a warning in the client file.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 06:35:26 +03:00
Umut Cevdet Koçak 78caa5b352 Merge pull request #252 from UMCEKO/plat/C2
Perf platform C2: single player captures both sides; horizon-ctl profile server
2026-11-08 06:05:14 +03:00
umcekoandClaude Sonnet 5.5 3597945405 Perf platform C2: the gpu e2e checks read the client side's options
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 06:05:00 +03:00
umcekoandClaude Sonnet 5.5 87623d9714 Perf platform C2: fit the server capture options and tests to the gpu and timeline pieces after the rebase
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 06:00:17 +03:00
umcekoandClaude Sonnet 5.5 71a09a89c0 Perf platform C2: every mark reply is on the game clock; start lists the sides asked for
A server-only mark replied capture-relative and a joined one on the game clock; both now use the game clock.
The e2e checks the server mark against the client mark's game-clock t.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:54:54 +03:00
umcekoandClaude Sonnet 5.5 18c344ff3c Fix profile mark and status routing for joined and finished server captures
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:54:54 +03:00
umcekoandClaude Sonnet 5.5 1b28cc6feb Perf platform C2: e2e reads the client side by name, docs say what stop and mark do per side
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:54:41 +03:00
umcekoandClaude Sonnet 5.5 af837708aa Perf platform C2: single player captures both sides; profile server
The integrated server thread writes its side (kind INTEGRATED) into the window's capture file, on the same clock, and a bare profile means both. profile server writes the server thread's own file.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:54:41 +03:00
Umut Cevdet Koçak ba04e6991d Merge pull request #251 from UMCEKO/plat/E1
Perf platform E1: horizon-perf export to pprof, folded and Perfetto
2026-11-08 05:47:20 +03:00
umcekoandClaude Sonnet 5.5 56cf9c3301 Perf platform E1: typed pprof labels and sample states, finer pprof period, two-side export tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:46:48 +03:00
umcekoandClaude Sonnet 5.5 05925da3cd Perf platform E1: horizon-perf export to pprof, folded stacks and a Perfetto trace
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:46:48 +03:00
Umut Cevdet Koçak a072c2275f Merge pull request #250 from UMCEKO/plat/B1
Perf platform B1: benchmark reports in the capture, horizon-perf attach, server_bench --profile
2026-11-08 05:42:43 +03:00
umcekoandClaude Sonnet 5.5 4e27118c3b Perf platform B1: fit the bench op and stop_with to the gpu piece after the rebase
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:41:55 +03:00
umcekoandClaude Sonnet 5.5 415797f30a perf: keep local paths, label and bot errors out of captures
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:37:05 +03:00
umcekoandClaude Sonnet 5.5 c283f0ce85 Perf platform B1: benchmark reports in the capture, horizon-perf attach, --benchmark --profile, server_bench --profile
Adds BenchResult (field 21) and Attachment (field 22) to the capture contract. horizon-perf reads bare benchmarks/*.json as one-sided captures, answers query bench and prints bench lines in the summary, and attach appends an attachment on the wire bytes so unknown fields survive. The game's --benchmark --profile records a capture and embeds the report through profile stop --bench; server_bench.py --profile records Horizon's measure window with horizon-report and attaches the run record.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:37:03 +03:00
Umut Cevdet Koçak 5bc42b54cf Merge pull request #249 from UMCEKO/plat/T1
Perf platform T1: timeline in the capture; HORIZON_TRACE and trace write .hzperf
2026-11-08 05:35:15 +03:00
umcekoandClaude Sonnet 5.5 980844073d Merge fix: drop the needless options update after rebasing T1 onto G1
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:35:00 +03:00
umcekoandClaude Sonnet 5.5 780a965ae2 Fix T1 review findings: trace seconds range, TLS-safe span, docs
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:29:27 +03:00
umcekoandClaude Sonnet 5.5 7b7afe9a8f Perf platform T1: timeline chunks in the capture; HORIZON_TRACE, trace and horizon-trace write .hzperf
The Chrome-trace writer in spans.rs is replaced by per-thread buffers drained once a second into
TimelineChunk (field 15), capped at 60 s or 256 MiB with timeline_stopped_t and a warning.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:29:18 +03:00
Umut Cevdet Koçak dc191e58df Merge pull request #248 from UMCEKO/plat/G1
Perf platform G1: GPU pass timings and counters in the capture
2026-11-08 05:09:48 +03:00
umcekoandClaude Sonnet 5.5 9f08382773 Perf platform G1: GPU pass timings and counters in the capture
Adds the gpu field (GpuPasses per timer) to the contract, written from the
renderer's PassTiming readings at stop; profile start --gpu[=detail], the
HORIZON_SHADER_PACK_TIMING and HORIZON_GPU_PASS_DETAIL aliases, horizon-perf
query gpu with fragments_per_pixel, a summary line and a meta count.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 05:01:54 +03:00
Umut Cevdet Koçak b787473097 Merge pull request #247 from UMCEKO/plat/C1
Perf platform C1: client captures: horizon-ctl profile client, F3+O, HORIZON_PROFILE
2026-11-08 04:31:55 +03:00
umcekoandClaude Sonnet 5.5 89feab9f8f Perf platform C1: adapt the client capture to the span, world and net recorders
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 04:31:42 +03:00
umcekoandClaude Sonnet 5.5 dd5fd7e80d Perf platform C1: fix review findings
One-line docstring and debug-key comment, F3+O feedback decided by who pressed stop, hardware described off the render thread, and the gauge probe spawned on the first frame with this second's counts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 04:25:38 +03:00
umcekoandClaude Sonnet 5.5 e715b5b743 Perf platform C1: client captures with horizon-ctl profile, F3+O and HORIZON_PROFILE
The window's frames feed an always-on client health history and slow ring.
profile start|stop|status|mark (and F3+O, HORIZON_PROFILE=DIR) write a .hzperf
into reports/ in the game home, with the render thread's samples, retention and
the translated saved message. The capture session is shared with the dedicated
server's through a Role; the gauge probes run off the frame thread.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 04:25:38 +03:00
Umut Cevdet Koçak 4dbc406616 Merge pull request #246 from UMCEKO/plat/S1b
Perf platform S1b: spans, workers, net and world move from report.rs into the capture
2026-11-08 03:56:40 +03:00
umcekoandClaude Sonnet 5.5 c5a342f764 Fix S1b review: rustfmt the rule asserts, check only the report's span bit in the drop test
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 03:52:19 +03:00
umcekoandClaude Sonnet 5.5 6efe76a432 Fix S1b review: spans and job stats off when a recording drops, rule and option tests, far ring 0 when off
A Recording now turns spans and job stats off when it is dropped, so a capture that failed
to start or a shutdown no longer leaves them on. A leaver's unread bytes are lost (noted on
TrafficRecorder). The e2e script's docstring is one line and its build command is in
docs/perf-platform.md, which also says the privacy checks' split and the dropped between-tick spans.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 03:52:18 +03:00
umcekoandClaude Sonnet 5.5 958af813dd Perf platform S1b: spans, workers, net and world move from report.rs into the capture
The dedicated server's capture now carries span_blocks (5 s blocks with parents), the spans
summary (totals, histogram, 16 worst ticks with their trees), workers, per-player net bytes by
join order and the world at start and stop with sampled mob costs. perf-*.json and .txt are no
longer written. capture.proto gains the game_rules and horizon_options allowlists and the mob
timing overhead fields. Spans recorded between ticks no longer count in a tick.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 03:52:18 +03:00
Umut Cevdet Koçak da474503d8 Merge pull request #245 from UMCEKO/plat/M1
Perf platform M1: horizon-perf mcp server
2026-11-08 03:38:50 +03:00
umcekoandClaude Sonnet 5.5 50386e55df horizon-perf: mcp server with perf_summary, perf_query, perf_diff, perf_list and perf_follow (M1)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 03:36:48 +03:00
Umut Cevdet Koçak fc1972ffe7 Merge pull request #244 from UMCEKO/plat/Q2
Perf platform Q2: sample queries hot, tree, callers, callees, split, group, frames
2026-11-08 03:28:49 +03:00
umcekoandClaude Sonnet 5.5 05b2a7afee perf Q2: split t:<thread> uses that thread's units; frames warns on mixed threads; real-writer smoke test
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 03:24:19 +03:00
umcekoandClaude Sonnet 5.5 4e71e99f98 Perf platform Q2: sample queries hot, tree, callers, callees, split, group, frames; hot functions in the summary
Reads the samples section: functions merged by normalized name, ids over the
normalized name and call path, filters (thread, select, slow, where, window),
several captures for frames, meta counts samples, summary gains hot functions
and the entity/block/chunk splits.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 03:15:17 +03:00
Umut Cevdet Koçak 8fc4c27855 Merge pull request #243 from UMCEKO/plat/S2
Perf platform S2: sampler call trees in the capture; horizon-report samples by default
2026-11-08 02:58:17 +03:00
Evrim Cicek 3ff75a8ecb Merge remote-tracking branch 'upstream/main' into fix/tnt-minecart-explosion-power 2026-11-08 02:38:26 +03:00
Evrim Cicek 2f07a64084 Merge remote-tracking branch 'upstream/main' into fix/hanging-item-stack-config
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-08 02:38:03 +03:00
umcekoandClaude Sonnet 5.5 35ddec5e9e Fix S2 review findings: one sample node per (parent, function), one-line doc, sampler share test, design doc notes
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 02:30:00 +03:00
umcekoandClaude Sonnet 5.5 9102edfb56 Perf platform S2: sampler call trees in the capture; horizon-report samples by default
The samples field (SampleProfile) is built from horizon_threads::Profile in
horizon-client-render: a deduplicated function table, a call-node chain per
stack, a context table and weights per thread, state, slow flag and time block.
The sampler's aggregate gains time blocks. horizon-report samples the tick
thread on Linux unless --no-samples, and finishes the file off the tick thread.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 02:04:12 +03:00
Umut Cevdet Koçak be4be0ce6b Merge pull request #242 from UMCEKO/plat/S1a
Perf platform S1a: dedicated servers: horizon-report writes .hzperf
2026-11-08 01:00:06 +03:00
umcekoandClaude Sonnet 5.5 d7b9e267e0 Fix S1a review: PERF_UI_URL points at /perf, note report output in hosting docs
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 00:53:36 +03:00
umcekoandClaude Sonnet 5.5 769cdcd232 Fix S1a review findings: one-line comments, unknown slow-tick cpu is 0, empty capture is incomplete, report checks completion only after the window, record files exception in the design doc
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 00:53:35 +03:00
umcekoandClaude Sonnet 5.5 3d9ef21f68 Perf platform S1a: horizon-report writes a .hzperf on the dedicated server
The always-on server health history and slow ring feed a capture file
(Start, history, slow_history, health, counters, slow, Stop) in reports/,
with retention of 30 files or 1 GiB that never touches renamed files.
horizon-report accepts --no-samples and --profile; horizon-server report
prints the saved path and the web UI address.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-08 00:53:35 +03:00
Umut Cevdet Koçak 6634e4ba98 Merge pull request #241 from UMCEKO/plat/typed
horizon-perf: every request, reply and vocabulary is typed
2026-11-08 00:33:32 +03:00
umceko ad01e692c9 horizon-perf: every request, reply and vocabulary is typed
Replies are serde structs (one Envelope<R>, a row struct per op, typed meta, watch events, diff and bench diff) and
closed vocabularies are enums (Op, Select, ContextKey, GroupBy, Unit, Verdict, HealthField, Flag, the proto name enums).
The CLI parses strings into them at the edge; no serde_json::Value, json! or string-keyed match is left in the library.

The JSON is the same as before as parsed JSON (tests/golden holds 49 cases captured from the old code). Intentional
differences, each visible in the golden diff:
- --where dimension=X is now the key dim, so dim and dimension merge in selection.where
- follow --json spells a stop reason window_cap (it said "window cap"), like query meta
- an unknown --by is a usage error at the edge instead of a world-only query error
- JSON object keys now come out in declaration order, not alphabetical
2026-11-08 00:32:47 +03:00
umceko 1547313299 horizon-perf: the golden follow case includes a window-cap stop 2026-11-08 00:28:45 +03:00
umceko 9874954fd0 horizon-perf: golden outputs of every query, diff and follow --json case, from before the typing refactor 2026-11-08 00:18:35 +03:00
Umut Cevdet Koçak 2e68167379 Merge pull request #240 from UMCEKO/plat/D1
Perf platform D1: horizon-perf diff with block statistics, and summary --baseline
2026-11-07 23:57:34 +03:00
umcekoandClaude Sonnet 5.5 14f833917a horizon-perf: diff with two-sample block statistics, drift warning, summary --baseline, benchmark report ab (D1)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:54:36 +03:00
Umut Cevdet Koçak 9ca66bdb02 Merge pull request #239 from UMCEKO/plat/Q1
Perf platform Q1: horizon-perf queries without samples, stable ids and filters
2026-11-07 23:44:15 +03:00
umcekoandClaude Sonnet 5.5 0da566c2ed horizon-perf: summary sections, filters and tests for the span queries (Q1)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:43:16 +03:00
umcekoandClaude Sonnet 5.5 8883d77504 horizon-perf: span, tick, series, world, net, meta, memory, mark and warning queries with stable ids (Q1)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:43:16 +03:00
Umut Cevdet Koçak 838d140cbc Merge pull request #238 from UMCEKO/plat/F2
Perf platform F2: health recorder, slow ring and counter registry
2026-11-07 23:37:30 +03:00
umcekoandClaude Sonnet 5.5 d2825d34f8 Perf platform F2: health recorder tiers, slow ring and counter registry
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:35:06 +03:00
Umut Cevdet Koçak e6f80a4ee4 Merge pull request #237 from UMCEKO/plat/D
Perf platform D: alloc-count, per-thread allocation counts in the frame stats
2026-11-07 23:30:32 +03:00
umcekoandClaude Sonnet 5.5 1d4d4feaf5 alloc-count: ON is false with system-allocator; rustfmt
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:25:49 +03:00
umcekoandClaude Sonnet 5.5 ff458a358d alloc-count: one-line comments, rustfmt
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:25:49 +03:00
umcekoandClaude Sonnet 5.5 c61ca75ca4 Add alloc-count: per-thread allocation counts, and alloc in the frame stats
horizon-threads gets a feature alloc-count (alloc-census implies it) with
CountingAllocator: each thread owns a cache-line slot of four counters, so a
block costs two plain load/store bumps. GameAllocator picks the census, the
counting mimalloc or plain mimalloc, and main.rs and the scene_replay example
declare it; without the feature the allocator is unchanged. The census counts
the same way.

In a counting build stats, bench and fly reply with alloc (window-thread
allocations and KiB per frame, all-thread rates, net growth), and stats raw and
fly raw add alloc_count and alloc_bytes beside frame_ms. Other builds reply
null. docs/memory.md gets the section with the measured cost.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:25:49 +03:00
umcekoandClaude Sonnet 5.5 cc52c95887 Docs: memory.md says what holds the game's memory and what the heap census costs
Describes only what exists: horizon-ctl memory and what each number means, the
alloc-census build (how tags are chosen, what it costs: +1.8% resident, frame
CPU time within the run-to-run spread, measured with --benchmark standard),
spans/trace/stats, resident memory in benchmark reports, scene_replay --memory
and the system-allocator feature for heaptrack on small probes.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:25:40 +03:00
Umut Cevdet Koçak e0f6c4f5e8 Merge pull request #236 from UMCEKO/plat/H
Perf platform H: in-process sampling profiler with symbolized function trees
2026-11-07 23:19:38 +03:00
umcekoandClaude Sonnet 5.5 91813c5ae0 horizon-threads: in-process symbolization and merged function trees for the sampler's aggregates
symbols.rs resolves addresses against this process's own binaries (DWARF through addr2line, the ELF symbol table for full paths), keeping base file names only. tree.rs names the aggregate's trie, merges it into a function tree and ranks functions by own and total samples. The pprof, folded and HTML writers stay out; the capture's samples field replaces them. Also fixes the spans test's work:: path and a clippy as_chunks lint.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:16:34 +03:00
umcekoandClaude Sonnet 5.5 a8a0d2cc25 horizon-threads: a profile session drains the sampler into bounded aggregates, with wall-clock samples
`profile::start` runs a writer thread that drains the sampler's rings every 100 ms, unwinds the stack copies there and folds each record
into a call-stack trie (131k nodes at most) plus counters per stack and context (span, entity type, chunk, block, dimension, slow tick).
A tick marker decides afterwards whether the samples of that tick count as slow, so the report can keep only the ticks over a threshold.
Tick durations go to a fixed log-bucket histogram per thread with the ten worst ticks. `Session::status` reads progress while it runs.

`Config::wall` arms a second timer per thread on the monotonic clock, signalling SIGRTMIN so it queues instead of merging with the
CPU-time SIGPROF; each handler blocks the other, so they never nest on one ring. A wall sample is marked running when the thread's CPU
clock advanced by more than half the period since its previous wall sample (the handlers' own microseconds don't count).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:16:33 +03:00
umcekoandClaude Sonnet 5.5 8e88e778a6 Profiler: the game loops store what they are doing in the sampler's context
The innermost span (spans::guard), the entity type before each mob, item,
cart, projectile and block entity tick, the chunk and block of random and
scheduled block ticks, the chunk in natural spawning, the level's dimension,
and a tick marker with its duration at the end of each server tick and each
client frame. Plain stores into the sampler's thread-local; the new
horizon_threads::profile module makes them no-ops where the sampler does not
run and interns the names behind the ids.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:16:33 +03:00
umcekoandClaude Sonnet 5.5 7b5cf13614 horizon-threads: the sampler unwinds copies of the stack with .eh_frame when frame pointers are off
Frame pointers cost 29-34% world load in release builds, so the release build keeps them off and the SIGPROF handler now copies
the interrupted registers and the top 16 KiB of the thread's stack (clamped to its bounds) into a byte ring, memcpy only.
`Session::drain`, on the caller's thread, unwinds each copy with the loaded objects' `.eh_frame` tables. The frame-pointer walk
stays in the handler as the fast path when this build keeps frame pointers (`Unwind::Auto`, decided at start from a probe).
Ring entries are variable length; a ring holds two seconds of samples by default, and a full one drops and counts as before.

New dependencies (Linux only): `framehop` 0.16 (MIT/Apache-2.0, samply's unwinder; default features off, so no Mach-O/PE
parsers) unwinds from `.eh_frame`, and `object` 0.39 locates the sections in each loaded ELF. There is no in-tree unwinder, and
writing a CFI interpreter is the alternative. Both share one `gimli` 0.33, which was not in the lock before.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:16:33 +03:00
umcekoandClaude Sonnet 5.5 1514d3d16a horizon-threads: a frame-pointer unwinder and a Linux CPU-time stack sampler
`unwind` walks frame pointers within a thread's stack bounds (shared with the allocation profiler). `sampler` arms a per-thread
CPU-time POSIX timer that signals SIGPROF to its own thread; the async-signal-safe handler copies the thread's context and
stack into a preallocated ring, and `tick_end` writes tick-duration markers so a report can keep only slow ticks.
Nothing is installed or armed until `sampler::start`. Frame pointers stay off in `.cargo/config.toml`: the benchmark
shows world load +29% (7 of 8 pairs) with `-C force-frame-pointers=yes`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:16:32 +03:00
Umut Cevdet Koçak 3e093c2c6f Merge pull request #235 from UMCEKO/plat/C
Perf platform C: GPU pass timing
2026-11-07 23:16:19 +03:00
umcekoandClaude Sonnet 5.5 e9db26a19a Shorten the detail test doc to one line
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:10:35 +03:00
umcekoandClaude Sonnet 5.5 267d39c511 GPU pass timing: fix review findings (docs on tables, uploads entry, phase 2 test)
step moves above tables' doc comment. The docs now say GPU culling uploads is a pass entry of its
own, only in detail frames on devices with encoder timestamps, not a part of GPU culling. A new
GPU test times both phases and the uploads and checks detail leaves the counts and draws as an
untimed frame's; the test device now asks for SHADER_EARLY_DEPTH_TEST so phase 2 can run.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:10:35 +03:00
umcekoandClaude Sonnet 5.5 3b3de54fa3 GPU pass timing: where detail shows (gpu-passes detail, F3, scene_replay)
`horizon-ctl gpu-passes detail` turns on dispatch times and, on Vulkan, per-pass counters;
stats and bench add `gpu_pass_detail`, `gpu_pass_parts` and `gpu_counters`, F3 lists the parts
and the six passes with the most fragments, and `scene_replay --gpu-detail on` reports both per
view after the timed frames. RADV counts fragments per 2x2 quad, so a calibration draw at setup
finds each device's `fragment_unit` and `fragments_per_pixel` is computed from it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:10:35 +03:00
umcekoandClaude Sonnet 5.5 a1cf28d100 GPU pass timing: pipeline statistics on the world passes
`gpu-passes detail` frames now alternate between a parts frame (times) and a counters frame
(vertex, clipper and fragment shader invocations per world pass, split into segments such as
before translucent, occlusion boxes and translucent terrain). A counters frame throws its times
away, and CountedPass ends its query on drop, so none stays open at the end of a pass. Vulkan
only; a device without pipeline statistics keeps parts frames.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:10:35 +03:00
umcekoandClaude Sonnet 5.5 517546d1af GPU pass timing: dispatch parts inside a pass, and GPU culling's dispatches and uploads
`gpu-passes detail` (the renderer's `set_pass_detail`, or HORIZON_GPU_PASS_DETAIL) times each
dispatch of GPU culling (apply, cull, scan, scatter; count2, scan2, scatter2) and its uploads
plus clear_buffer, so a slow pass can be split. A timestamp pair brackets each part inside one
compute pass where the device has TIMESTAMP_QUERY_INSIDE_PASSES, else each part gets a pass of
its own. Off by default; `on` records the same queries and passes as before.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:10:35 +03:00
umcekoandClaude Opus 5.5 cb7a5c204e gpu-passes: time the frames the submit thread submits too
land_frame told the GPU timer and a shader pack's pass timer that their frame
was submitted, but not Horizon's own pass timer: with the submit thread on, its
first timed frame was read and every later one waited forever, so gpu-passes,
F3 and scene_replay showed the first frame's pass times only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 23:10:35 +03:00
Umut Cevdet Koçak 7833ed6c05 Merge pull request #234 from UMCEKO/plat/P1
Perf platform P1: horizon-perf readers, latest/list/follow and a health-only summary
2026-11-07 23:07:48 +03:00
umcekoandClaude Sonnet 5.5 8b7cc25b66 perf: stream captures in 64 KiB slices, one-line doc, pin gzip trailer and header paths
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:05:29 +03:00
umcekoandClaude Sonnet 5.5 0689bc6505 horizon-perf: whole-file and follow readers, latest, list, follow and a health-only summary (P1)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 23:01:49 +03:00
Umut Cevdet Koçak e9e7050f32 Merge pull request #233 from UMCEKO/plat/A
Perf platform A: paired A/B statistics and the travel benchmark scenario
2026-11-07 22:51:54 +03:00
umcekoandClaude Sonnet 5.5 afdac528fc Benchmark A/B: drop the references to the removed bench_stats.py
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 22:42:49 +03:00
umcekoandClaude Sonnet 5.5 875c7d7a2b Benchmark: the travel scenario, --benchmark-set and bench raw
horizon-client --benchmark travel flies 512 blocks at 16 blocks/s with the time
and weather frozen, then holds at the end for four blocks: the renderer after
travel, where GPU culling's slowdown shows. Scenario::parse replaces scenes();
--benchmark-set SWITCH=VALUE sets one of the SWITCHES (defaults as gfx has them)
before the world opens, and a refused switch ends the run with the game's
reason. The bench control word takes raw like stats and fly, and the report gets
gpu.<phase>.p50_ms and cpu.<phase>.p50_ms for the trip and hold phases.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 22:30:08 +03:00
umcekoandClaude Sonnet 5.5 9a2931de68 Benchmark report: paired A/B statistics and the optional ab field
horizon_bench::compare pairs the ab.a/ab.b blocks (B A A B order) and gives the
Hodges-Lehmann effect, the exact Wilcoxon signed-rank interval, a verdict, the
blocks' noise and the first-block flag. tools/bench_stats.py computes the same
numbers in Python and checks a report's stored result against its frames.
Report gains an optional ab field; the format stays version 1.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-07 22:30:08 +03:00
umcekoandClaude Opus 5.5 52128e9f79 docs: perf platform's gzip writer goes through flate2 (pure Rust), as F1 built it
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:17:42 +03:00
Umut Cevdet Koçak e635a9b0b4 horizon-perf-format: the .hzperf capture contract (F1) (#232)
horizon-perf-format: the .hzperf capture contract (F1)
2026-11-07 22:17:18 +03:00
umcekoandClaude Opus 5.5 0d21d07827 horizon-perf-format: the .hzperf capture contract (F1)
The new crate holds piece F1 of docs/perf-platform.md: capture.proto (Capture's
top level with Start, Stop, strings, marks, warnings, health, history, the slow
ring and counters), compiled by protox + prost-build in build.rs, and the gzip
writer (flate2, rust_backend) that appends whole top-level fields with a sync
flush after each, on a horizon-perf-writer thread fed by a 4,096-field bounded
channel that drops and counts instead of waiting.

Tests: the frozen tests/fixtures/v1.hzperf decodes to its listed values; after
every flush the file on disk inflates to exactly the fields written; a file cut
at random points yields only whole fields, in order; unknown field numbers are
skipped; the descriptor lint passes capture.proto and rejects a missing
_UNSPECIFIED, a JSON-name collision and a group; a full channel drops, counts
and never waits, and Stop records the drops.

Fixes #2

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 22:16:46 +03:00
umcekoandClaude Opus 5.5 b91b5516f3 fork: /claim bot and review batches for the perf platform fork
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:31:53 +03:00
umceko be1de92536 Merge branch 'docs/perf-platform-spec' into perf-platform 2026-11-07 20:28:31 +03:00
umcekoandClaude Opus 5.5 b3be633edf docs: perf platform tracker lives on UMCEKO/horizon#1
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:22:26 +03:00
umcekoandClaude Opus 5.5 ae1555ab94 docs: perf platform pieces have no PR size limit; tracker #11902
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:17:03 +03:00
umcekoandClaude Opus 5.5 ee3a790501 docs: design spec for one performance platform (.hzperf, horizon-perf, web UI)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 20:10:46 +03:00
Horizon agentandClaude Opus 5.5 6ca76d9e9c Merge origin/main into #11507
dispense_fixture.rs: chains this branch's shield_hit fixture op and
main's wind_burst op.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:50:23 +01:00
Evrim Cicek c58a3eef6f Merge remote-tracking branch 'origin/fix/tnt-fuse-any-number' into fix/tnt-minecart-explosion-power
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-07 16:54:08 +03:00
Evrim Cicek ca57097ae8 Merge remote-tracking branch 'upstream/main' into fix/tnt-minecart-explosion-power
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-07 16:53:53 +03:00
Horizon agentandClaude Opus 5.5 bb6e18b94d Merge origin/main into #11261 (main builds again after #11767)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:10:29 +01:00
Horizon agentandClaude Opus 5.5 b28069d08e rustfmt spawner.rs (verify's fmt step failed on this hunk)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:00:50 +01:00
Horizon agentandClaude Opus 5.5 2f4a142e8b Merge origin/main into #11261 (keep both command_exec corpus groups)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 14:00:39 +01:00
Horizon agentandClaude Opus 5.5 83df38c895 Drop an unreachable return after components()
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 09:44:10 +01:00
voidsip b98cb1a611 Give each shield fixture run a fresh game directory 2026-11-06 18:07:05 -06:00
Evrim Cicek d70f2fdb20 Merge upstream/main: build on #11268's stack config; the item's name loads too
Upstream #11268 configures a placed frame, painting or armor stand through
stack_configured_entity. Keep its placement code, add the item's custom name
there (a painting took none, an armor stand's lost its style), and route
apply_item_stack_config through the same helper.
2026-11-07 02:40:03 +03:00
Evrim Cicek b7eb967776 Merge remote-tracking branch 'upstream/main' into fix/tnt-minecart-explosion-power
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-07 02:30:21 +03:00
voidsip c74851a64b Initialize starvation blocking state and bound fixture startup 2026-11-06 17:25:24 -06:00
voidsip 6b6a9577c7 Merge current upstream for shield blocking validation 2026-11-06 16:13:01 -06:00
voidsip 316f9680d5 Fix built-in shield blocking inputs and item wear 2026-11-06 16:12:41 -06:00
Evrim CicekandClaude Opus 5.5 d8a86b2454 Dispensed armor stand config, block_pos range, unreadable painting variant
ArmorStandDispenseItemBehavior applies the same stack config with no user
after the dispenser's yaw. BlockAttachedEntity.readAdditionalSaveData keeps
the Pos block for a block_pos 16 blocks or more away, and a painting with an
unreadable variant still loads the rest of its data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 19:44:48 +03:00
Evrim CicekandClaude Opus 5.5 d4cfdeab5c A placed painting, item frame or armor stand takes its item's stack config
HangingEntityItem.useOn and ArmorStandItem.useOn apply
EntityType.createDefaultStackConfig: the item's custom name and custom data,
then minecraft:entity_data merged over the entity. The hanging entity's
survives() runs on the configured entity; the stand turns to the player's
yaw, pitch 0, afterwards. The vehicle helper becomes apply_item_stack_config,
and /data merge entity now loads a painting (facing, block, known variant).

Fixes #11242

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 19:32:10 +03:00
Evrim CicekandClaude Opus 5.5 5a60e2252b TNT minecarts keep explosion_power and explosion_speed_factor, and blow with them
MinecartTNT reads explosion_power and explosion_speed_factor with
getFloatOr (4 and 1), clamped to 0..128, writes each only off its
default, and explode() blows with explosionPowerBase +
explosionSpeedFactor * nextDouble() * 1.5 * min(speed, 5). Horizon blew
every cart at 4 + 1.5 * speed * r and kept whatever the loaded compound
had for the fields, unclamped.

Command harness group "tnt minecart explosion power": 13/18 -> 18/18.

Fixes #11167

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 17:28:56 +03:00
807 changed files with 72128 additions and 6611 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
# `cargo xtask …` runs the repository's task crate, so the commands in docs/perf-platform.md and
# web/perf/README.md work as written. `cargo run -p xtask -- …` stays equivalent.
[alias]
xtask = "run --package xtask --"
+3 -2
View File
@@ -2,8 +2,9 @@
## What and why
<!-- What this changes, and why. Link the issue it fixes ("Fixes #123"). Over about 500 lines: link the issue with its
approved spec too ("Spec: #123"), CONTRIBUTING.md "Large pull requests". -->
<!-- What this changes, and why. Link the issue it fixes ("Fixes #123"). Over about 500 lines of code
(docs and test files don't count): link the issue with its approved spec too ("Spec: #123"), CONTRIBUTING.md
"Large pull requests". -->
## Kind
+56
View File
@@ -0,0 +1,56 @@
name: perf-wasm
# The site consumes this reader bundle from horizon-rust/horizon-site.
on:
push:
branches: [main]
paths:
- 'crates/horizon-perf/**'
- 'crates/horizon-perf-format/**'
- 'crates/horizon-bench/**'
- 'xtask/**'
- 'Cargo.lock'
- 'Cargo.toml'
- '.github/workflows/perf-wasm.yml'
pull_request:
types: [opened, synchronize, reopened]
paths:
- 'crates/horizon-perf/**'
- 'crates/horizon-perf-format/**'
- 'crates/horizon-bench/**'
- 'xtask/**'
- 'Cargo.lock'
- 'Cargo.toml'
- '.github/workflows/perf-wasm.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: perf-wasm-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
HORIZON_TELEMETRY_URL: "off"
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
with:
key: perf-wasm
# The agreement test: the C ABI, called natively, must print the bytes the CLI prints.
- name: The wasm ABI agrees with the CLI
run: cargo test -p horizon-perf --features wasm --test wasm
- name: Build the wasm the page loads
run: cargo run -p xtask -- perf-wasm
- uses: actions/upload-artifact@v4
with:
name: perf-wasm
path: target/perf-wasm
if-no-files-found: error
+5 -3
View File
@@ -34,8 +34,9 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
- Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`.
- Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where
they would change the vanilla look.
- 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
- Small PRs (< ~500 lines of code; docs and test files don't count:
[CONTRIBUTING.md](CONTRIBUTING.md#pull-requests)). 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)).
- **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
@@ -102,6 +103,7 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
| `horizon-shader-api` | Horizon's own WGSL shader packs ([docs/api/shaders.md](docs/api/shaders.md)): `horizon-shaders.toml`, the `.hshader` package; shared by the game, the launcher and the registry |
| `horizon-shaders` | Shader packs (the `shaders/` folder format), rebuilt clean-room from a written spec of the format; no wgpu |
| `horizon-theme` | Design tokens and fonts for the launcher, the game's own menus and the website |
| `horizon-perf-format` | The `.hzperf` capture contract ([docs/perf-platform.md](docs/perf-platform.md) §3): `proto/horizon/perf/v1/capture.proto`, its generated types, the gzip writer and its thread. No Horizon dependencies; nothing in the game reads a capture |
| `horizon-telemetry`, `horizon-telemetry-server`, `horizon-bench` | Opt-in data collection, its ingest server, the benchmark report format |
| `horizon-system` | The machine the game runs on (OS, CPU, memory, drive, power, GPU maker and memory), for the crash report, the renderer's GPU info and telemetry |
| `horizon-platform` | The platform's public API: what the Horizon layer may use of the engine ([docs/layers.md](docs/layers.md)); re-exports `horizon-system` today |
@@ -213,7 +215,7 @@ state stays separate from the library tests. This compiles gameplay twice for ex
| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `mobs/cem.rs` + `mobs/cem_anim.rs` (OptiFine/EMF entity models and their animations); `horizon-client-core/src/lang.rs`; crates `horizon-assets`, `horizon-optifine`; G: `packs.rs` |
| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) |
| Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` |
| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` |
| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs` + `extras/` (each extra's glue: `mouse_tweaks.rs`, `sorting.rs`, `pvp.rs`, `reconnect.rs`), `options.rs` |
## How `Game` is organised
+5 -2
View File
@@ -144,7 +144,9 @@ it (edited on every push, never repeated): talk to its author in the thread befo
- **Small.** One change per pull request, under about 500 lines of code where you can; split bigger work into
pieces that each make sense alone. Small pull requests get reviewed and merged the same day. Bigger than that:
[large pull requests](#large-pull-requests).
[large pull requests](#large-pull-requests). What counts: lines added plus lines removed, outside Markdown (`.md`)
files and test files (any `tests/` or `test/` folder, and `test_*.py`). Tests written inside a source file do count.
pr_ready counts it the same way and warns when a pull request is over.
- **Fill in the template**: what and why, the vanilla reference, the pr_ready block, screenshots for anything you
can see.
- **Tick "Allow edits by maintainers".** When something small is left (a lint, a rebase, a nit) we push the fixup
@@ -169,7 +171,8 @@ How agents, checks, releases and signed updates keep this safe: [security](docs/
### Large pull requests
500 lines stays the default. A pull request that can't be split below it starts from a spec:
500 lines of code ([what counts](#pull-requests)) stays the default. A pull request that can't be split below it
starts from a spec:
1. **Open an issue with the spec** before the code: what changes, the files it touches, the behaviour players and
other code will see, and the tests or harnesses that prove it.
Generated
+344 -6
View File
@@ -18,6 +18,15 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"
[[package]]
name = "addr2line"
version = "0.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59317f77929f0e679d39364702289274de2f0f0b22cbf50b2b8cff2169a0b27a"
dependencies = [
"gimli",
]
[[package]]
name = "adler2"
version = "2.0.1"
@@ -129,6 +138,12 @@ dependencies = [
"libc",
]
[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "arboard"
version = "3.7.0"
@@ -264,6 +279,12 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "beef"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -559,7 +580,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width",
"unicode-width 0.2.2",
]
[[package]]
@@ -1011,6 +1032,12 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -1109,6 +1136,18 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "framehop"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f54fe4785e899d4d6f43793b151c63c5647240fc630b005509d2614a939f693"
dependencies = [
"arrayvec",
"cfg-if",
"fallible-iterator",
"gimli",
]
[[package]]
name = "fs4"
version = "1.1.0"
@@ -1246,6 +1285,15 @@ dependencies = [
"windows 0.62.2",
]
[[package]]
name = "gimli"
version = "0.33.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c"
dependencies = [
"stable_deref_trait",
]
[[package]]
name = "gl_generator"
version = "0.14.0"
@@ -1426,7 +1474,7 @@ dependencies = [
name = "horizon-bench"
version = "0.1.0"
dependencies = [
"horizon-telemetry",
"horizon-system",
"serde",
"serde_json",
]
@@ -1457,7 +1505,6 @@ dependencies = [
"bytemuck",
"chrono",
"crc32fast",
"dunce",
"flate2",
"fs4",
"gilrs",
@@ -1482,10 +1529,13 @@ dependencies = [
"horizon-mods",
"horizon-narrator",
"horizon-optifine",
"horizon-perf",
"horizon-perf-format",
"horizon-protocol",
"horizon-server-files",
"horizon-shader-api",
"horizon-shaders",
"horizon-system",
"horizon-telemetry",
"horizon-theme",
"horizon-threads",
@@ -1496,7 +1546,6 @@ dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"open",
"png",
"pollster",
"rustix 1.1.5",
@@ -1540,6 +1589,7 @@ dependencies = [
"bytemuck",
"chrono",
"crc32fast",
"dunce",
"flate2",
"fs4",
"getrandom 0.3.4",
@@ -1560,6 +1610,8 @@ dependencies = [
"horizon-mods",
"horizon-narrator",
"horizon-optifine",
"horizon-perf",
"horizon-perf-format",
"horizon-protocol",
"horizon-server-files",
"horizon-shader-api",
@@ -1614,6 +1666,8 @@ dependencies = [
"horizon-items",
"horizon-narrator",
"horizon-optifine",
"horizon-perf",
"horizon-perf-format",
"horizon-polytone",
"horizon-protocol",
"horizon-shader-api",
@@ -1831,6 +1885,7 @@ dependencies = [
"horizon-game",
"horizon-heartbeat",
"horizon-official-servers",
"horizon-perf-share",
"horizon-platform",
"log",
"winresource",
@@ -1849,18 +1904,60 @@ dependencies = [
name = "horizon-optifine"
version = "0.1.0"
dependencies = [
"horizon-bench",
"horizon-core",
"horizon-system",
"log",
"regex",
]
[[package]]
name = "horizon-perf"
version = "0.1.0"
dependencies = [
"flate2",
"horizon-bench",
"horizon-perf-format",
"horizon-perf-share",
"prost",
"regex",
"serde",
"serde_json",
]
[[package]]
name = "horizon-perf-format"
version = "0.1.0"
dependencies = [
"flate2",
"prost",
"prost-build",
"prost-types",
"protox",
]
[[package]]
name = "horizon-perf-share"
version = "0.1.0"
dependencies = [
"getrandom 0.3.4",
"horizon-addresses",
"horizon-platform",
"log",
"open",
"serde",
"serde_json",
"ureq",
"url",
]
[[package]]
name = "horizon-platform"
version = "0.1.0"
dependencies = [
"horizon-bench",
"horizon-core",
"horizon-hooks",
"horizon-perf-format",
"horizon-prepare",
"horizon-protocol",
"horizon-server-files",
@@ -1945,7 +2042,6 @@ dependencies = [
"chrono",
"getrandom 0.3.4",
"horizon-anticheat",
"horizon-bench",
"horizon-chat-filter",
"horizon-mcp",
"horizon-platform",
@@ -2029,9 +2125,14 @@ version = "0.1.0"
name = "horizon-threads"
version = "0.1.0"
dependencies = [
"addr2line",
"framehop",
"libc",
"libmimalloc-sys",
"memmap2",
"mimalloc",
"object",
"rustc-demangle",
"windows-sys 0.61.2",
]
@@ -2041,6 +2142,7 @@ version = "0.1.0"
dependencies = [
"flate2",
"horizon-core",
"horizon-threads",
"libm",
"log",
"lz4_flex",
@@ -2282,6 +2384,15 @@ dependencies = [
"once_cell",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -2508,6 +2619,72 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "logos"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff472f899b4ec2d99161c51f60ff7075eeb3097069a36050d8037a6325eb8154"
dependencies = [
"logos-derive 0.15.1",
]
[[package]]
name = "logos"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f"
dependencies = [
"logos-derive 0.16.1",
]
[[package]]
name = "logos-codegen"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "192a3a2b90b0c05b27a0b2c43eecdb7c415e29243acc3f89cc8247a5b693045c"
dependencies = [
"beef",
"fnv",
"lazy_static",
"proc-macro2",
"quote",
"regex-syntax",
"rustc_version",
"syn 2.0.119",
]
[[package]]
name = "logos-codegen"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970"
dependencies = [
"fnv",
"proc-macro2",
"quote",
"regex-automata",
"regex-syntax",
"syn 2.0.119",
]
[[package]]
name = "logos-derive"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "605d9697bcd5ef3a42d38efc51541aa3d6a4a25f7ab6d1ed0da5ac632a26b470"
dependencies = [
"logos-codegen 0.15.1",
]
[[package]]
name = "logos-derive"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31"
dependencies = [
"logos-codegen 0.16.1",
]
[[package]]
name = "lru"
version = "0.18.5"
@@ -2550,6 +2727,28 @@ dependencies = [
"libc",
]
[[package]]
name = "miette"
version = "7.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"
dependencies = [
"cfg-if",
"miette-derive",
"unicode-width 0.1.14",
]
[[package]]
name = "miette-derive"
version = "7.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "mimalloc"
version = "0.1.52"
@@ -2603,6 +2802,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multimap"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
@@ -3183,6 +3388,15 @@ dependencies = [
"objc2-foundation 0.2.2",
]
[[package]]
name = "object"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
dependencies = [
"memchr",
]
[[package]]
name = "oid-registry"
version = "0.8.1"
@@ -3514,6 +3728,16 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn 2.0.119",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@@ -3538,6 +3762,96 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
[[package]]
name = "prost"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-build"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
dependencies = [
"heck",
"itertools",
"log",
"multimap",
"petgraph",
"prettyplease",
"prost",
"prost-types",
"regex",
"syn 2.0.119",
"tempfile",
]
[[package]]
name = "prost-derive"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
dependencies = [
"anyhow",
"itertools",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "prost-reflect"
version = "0.16.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1"
dependencies = [
"logos 0.16.1",
"miette",
"prost",
"prost-types",
]
[[package]]
name = "prost-types"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
dependencies = [
"prost",
]
[[package]]
name = "protox"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1"
dependencies = [
"bytes",
"miette",
"prost",
"prost-reflect",
"prost-types",
"protox-parse",
"thiserror 2.0.21",
]
[[package]]
name = "protox-parse"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "072eee358134396a4643dff81cfff1c255c9fbd3fb296be14bdb6a26f9156366"
dependencies = [
"logos 0.15.1",
"miette",
"prost-types",
"thiserror 2.0.21",
]
[[package]]
name = "quick-error"
version = "2.0.1"
@@ -3837,6 +4151,12 @@ dependencies = [
"smallvec",
]
[[package]]
name = "rustc-demangle"
version = "0.1.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb"
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -4395,6 +4715,18 @@ dependencies = [
"syn 3.0.6",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
]
[[package]]
name = "termcolor"
version = "1.4.1"
@@ -4664,6 +4996,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "unicode-width"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "unicode-width"
version = "0.2.2"
+3
View File
@@ -37,6 +37,9 @@ members = [
"crates/horizon-discord",
"crates/horizon-official-servers",
"crates/horizon-bench",
"crates/horizon-perf-format",
"crates/horizon-perf",
"crates/horizon-perf-share",
"crates/horizon-friends",
"crates/horizon-relay",
"crates/horizon-mods",
+2
View File
@@ -62,6 +62,8 @@ The GLSL frontend also resets the common type for each comma-separated declarato
variable's array specifier does not change later variables.
It also reads a struct member outside a constant expression through a pointer to the member,
not out of a loaded copy of the whole struct, so a member an atomic function uses can be read.
The shared interpolation defaults also compile with `glsl-in` alone, without needing the
SPIR-V or WGSL frontend to enable them.
## DirectX Shader Compiler
+6
View File
@@ -35,6 +35,12 @@ pub const COSMETICS_API: &str = "https://cosmetics.playhorizon.dev";
/// "I'm playing" ping, benchmark uploads (`HORIZON_TELEMETRY_URL` overrides it).
pub const TELEMETRY: &str = "https://telemetry.playhorizon.dev";
/// The performance viewer page a saved capture opens in (`HORIZON_PERF_VIEWER` overrides it).
pub const PERF_VIEWER: &str = "https://playhorizon.dev/perf";
/// The capture upload API behind Share (`HORIZON_PERF_CAPTURES` overrides it).
pub const PERF_CAPTURES: &str = "https://playhorizon.dev/api/perf/captures";
/// Public STUN servers for Play with Friends' NAT discovery: two independent operators, so one
/// outage doesn't break discovery (`HORIZON_STUN_SERVERS` overrides them).
pub const STUN_SERVERS: &[&str] = &["stun.cloudflare.com:3478", "stun.l.google.com:19302"];
+33 -1
View File
@@ -206,7 +206,7 @@ impl Config {
Ok(file.anticheat)
}
/// Thresholds can't be negative.
/// Thresholds can't be negative, and neither can the timer's milliseconds.
pub fn check(&self) -> Result<(), String> {
for &c in Check::ALL {
let a = self.actions(c);
@@ -220,6 +220,18 @@ impl Config {
));
}
}
// A negative tolerance flags a client on time every tick, and so does a cap below minus the
// tolerance (the balance rests at the cap); NaN never flags, or never caps the balance. No
// negative number of milliseconds means anything, so all are refused.
if [self.timer.tolerance_ms, self.timer.max_lag_ms]
.iter()
.any(|v| !v.is_finite() || *v < 0.0)
{
return Err(
"anticheat.timer: tolerance_ms and max_lag_ms are numbers of milliseconds from 0 up"
.into(),
);
}
let tolerance = self.prediction.tolerance;
if !tolerance.is_finite() || tolerance <= 0.0 {
return Err("anticheat.prediction: tolerance is a number of blocks above 0".into());
@@ -361,6 +373,26 @@ mod tests {
assert!(Config::from_server_toml("[anticheat.timer]\nkick = -1\n").is_err());
}
/// A negative `tolerance_ms` flags a client on time every tick, and so does a `max_lag_ms` below
/// `-tolerance_ms` (the balance rests at the cap); a NaN turns the check (or its cap) off without a
/// word. Every negative or non-finite value is refused, as a negative threshold is.
#[test]
fn refuses_timer_settings_that_are_not_milliseconds_from_0_up() {
for bad in [
"tolerance_ms = -1",
"tolerance_ms = nan",
"tolerance_ms = inf",
"max_lag_ms = -1",
"max_lag_ms = nan",
] {
let text = format!("[anticheat.timer]\n{bad}\n");
let e = Config::from_server_toml(&text).expect_err(bad);
assert!(e.starts_with("anticheat.timer:"), "{bad}: {e}");
}
let edge = "[anticheat.timer]\ntolerance_ms = 0\nmax_lag_ms = 0\n";
assert!(Config::from_server_toml(edge).is_ok());
}
#[test]
fn levels_rise_decay_and_act_in_order() {
let mut c = on();
+25 -1
View File
@@ -45,6 +45,11 @@ mod tests {
/// `seconds` of server ticks of `server_ms` each, with `per_tick` client ticks handled in each.
fn run(b: &mut Balance, server_ms: f64, per_tick: f64, seconds: f64) -> usize {
run_at(b, 20.0, server_ms, per_tick, seconds)
}
/// [`run`] at the tick rate `rate` (`/tick rate`), which the client's ticks follow.
fn run_at(b: &mut Balance, rate: f32, server_ms: f64, per_tick: f64, seconds: f64) -> usize {
let c = TimerConfig::default();
let mut owed = 0.0;
let mut flags = 0;
@@ -53,12 +58,31 @@ mod tests {
owed += per_tick;
while owed >= 1.0 {
owed -= 1.0;
flags += usize::from(b.tick_end(20.0, &c).is_some());
flags += usize::from(b.tick_end(rate, &c).is_some());
}
}
flags
}
/// At another tick rate a vanilla client ticks at the rate the server sent it, and each of its
/// ticks is worth `1000 / rate` ms: never flagged on time, flagged again and again 1.5 times as fast.
#[test]
fn the_balance_follows_the_tick_rate() {
for rate in [10.0_f32, 60.0] {
let tick_ms = 1000.0 / f64::from(rate);
assert_eq!(
run_at(&mut Balance::default(), rate, tick_ms, 1.0, 600.0),
0,
"on time at {rate}"
);
// Half a tick ahead every server tick: 75 flags in a minute at 10 a second, 94 at 60.
let flags = run_at(&mut Balance::default(), rate, tick_ms, 1.5, 60.0);
assert!(flags >= 50, "1.5 times as fast at {rate}: {flags} flags");
}
// The rate counts: at 10 a second, a client sending 20 ticks a second is twice as fast.
assert!(run_at(&mut Balance::default(), 10.0, 100.0, 2.0, 60.0) >= 50);
}
#[test]
fn a_vanilla_client_is_never_flagged() {
let mut b = Balance::default();
+8 -9
View File
@@ -1764,14 +1764,13 @@ fn stack_from_template(template: &Value) -> Option<StackView> {
/// `RangeSelectItemModel.lastIndexLessOrEqual`.
fn last_index_less_or_equal(entries: &[(f32, ItemModelNode)], needle: f32) -> Option<usize> {
let haystack: Vec<f32> = entries.iter().map(|e| e.0).collect();
let found = if haystack.len() < 16 {
haystack
let found = if entries.len() < 16 {
entries
.iter()
.position(|h| *h > needle)
.map_or(haystack.len() as i64 - 1, |i| i as i64 - 1)
.position(|e| e.0 > needle)
.map_or(entries.len() as i64 - 1, |i| i as i64 - 1)
} else {
match binary_search(&haystack, needle) {
match binary_search(entries, needle) {
Ok(index) => index as i64,
Err(insertion) => insertion as i64 - 1,
}
@@ -1780,8 +1779,8 @@ fn last_index_less_or_equal(entries: &[(f32, ItemModelNode)], needle: f32) -> Op
}
/// `Arrays.binarySearch(float[], float)`, including its handling of equal
/// values (-0.0 below 0.0, NaN above everything).
fn binary_search(a: &[f32], key: f32) -> std::result::Result<usize, usize> {
let (mut low, mut high) = (0i64, a.len() as i64 - 1);
fn binary_search(entries: &[(f32, ItemModelNode)], key: f32) -> std::result::Result<usize, usize> {
let (mut low, mut high) = (0i64, entries.len() as i64 - 1);
let bits = |v: f32| -> i32 {
if v.is_nan() {
0x7fc0_0000
@@ -1791,7 +1790,7 @@ fn binary_search(a: &[f32], key: f32) -> std::result::Result<usize, usize> {
};
while low <= high {
let mid = (low + high) >> 1;
let value = a[mid as usize];
let value = entries[mid as usize].0;
if value < key {
low = mid + 1;
} else if value > key {
@@ -158,3 +158,61 @@ fn a_patched_stack_reads_its_patch_over_its_items_defaults() {
}
assert_eq!(view.to_map(), *merged);
}
#[test]
fn last_index_less_or_equal_linear_and_binary() {
use super::last_index_less_or_equal;
let make = |thresholds: &[f32]| -> Vec<(f32, ItemModelNode)> {
thresholds
.iter()
.map(|&t| (t, ItemModelNode::Empty))
.collect()
};
// Empty
assert_eq!(last_index_less_or_equal(&[], 0.0), None);
// Short (< 16): linear search
let short = make(&[-1.0, 0.0, 1.0, 2.5, 5.0]);
assert_eq!(last_index_less_or_equal(&short, -2.0), None);
assert_eq!(last_index_less_or_equal(&short, -1.0), Some(0));
assert_eq!(last_index_less_or_equal(&short, -0.5), Some(0));
assert_eq!(last_index_less_or_equal(&short, 0.0), Some(1));
assert_eq!(last_index_less_or_equal(&short, 2.5), Some(3));
assert_eq!(last_index_less_or_equal(&short, 3.0), Some(3));
assert_eq!(last_index_less_or_equal(&short, 5.0), Some(4));
assert_eq!(last_index_less_or_equal(&short, 10.0), Some(4));
// Long (>= 16): binary search
let thresholds: Vec<f32> = (0..32).map(|i| i as f32 * 10.0).collect();
let long = make(&thresholds);
assert_eq!(last_index_less_or_equal(&long, -5.0), None);
assert_eq!(last_index_less_or_equal(&long, 0.0), Some(0));
assert_eq!(last_index_less_or_equal(&long, 5.0), Some(0));
assert_eq!(last_index_less_or_equal(&long, 10.0), Some(1));
assert_eq!(last_index_less_or_equal(&long, 150.0), Some(15));
assert_eq!(last_index_less_or_equal(&long, 155.0), Some(15));
assert_eq!(last_index_less_or_equal(&long, 310.0), Some(31));
assert_eq!(last_index_less_or_equal(&long, 1000.0), Some(31));
// Short lists use upper-bound tie behavior, including signed zero.
let duplicates = make(&[1.0, 1.0, 2.0]);
assert_eq!(last_index_less_or_equal(&duplicates, 1.0), Some(1));
let zeroes = make(&[-0.0, 0.0]);
assert_eq!(last_index_less_or_equal(&zeroes, -0.0), Some(1));
assert_eq!(last_index_less_or_equal(&zeroes, 0.0), Some(1));
// At 16 entries, vanilla returns Arrays.binarySearch's hit, not the last tie.
// Expected indices were checked on the JVM.
let duplicates = make(&[
0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 7.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0,
]);
assert_eq!(last_index_less_or_equal(&duplicates, 7.0), Some(7));
let zeroes = make(&[
-8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -0.0, -0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0,
]);
assert_eq!(last_index_less_or_equal(&zeroes, -0.0), Some(7));
assert_eq!(last_index_less_or_equal(&zeroes, 0.0), Some(9));
}
+4 -2
View File
@@ -9,5 +9,7 @@ description = "The benchmark report format (docs/benchmark-report.md), shared by
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# The hardware probes shared with telemetry (cores, clocks, drive, VRAM, power, form).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
# The hardware probes (cores, clocks, drive, VRAM, power, form); a reader of reports (the wasm
# build of horizon-perf) needs the types below, never the probes.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
horizon-system = { path = "../horizon-system" }
+434
View File
@@ -0,0 +1,434 @@
//! Paired A/B comparison of benchmark blocks (docs/benchmark-report.md, "A/B runs").
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::{round, Frames};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
TooFewPairs,
WithinNoise,
Negligible,
Slower,
Faster,
}
/// B against A over paired blocks; lower milliseconds are better.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Paired {
pub pairs: usize,
pub a: f64,
pub b: f64,
/// Hodges-Lehmann estimate of b - a.
pub diff: f64,
/// Absent when `a` is zero.
pub diff_pct: Option<f64>,
/// Exact Wilcoxon signed-rank interval; absent below 6 pairs.
pub ci95: Option<[f64; 2]>,
pub confidence: Option<f64>,
/// Median distance between neighbouring blocks of the same arm.
pub noise: Option<f64>,
pub verdict: Verdict,
}
type Getter = fn(&Frames) -> Option<f64>;
fn median(values: &[f64]) -> f64 {
let mut v = values.to_vec();
v.sort_by(f64::total_cmp);
match v.len() {
0 => 0.0,
n if n % 2 == 1 => v[n / 2],
n => (v[n / 2 - 1] + v[n / 2]) / 2.0,
}
}
fn round4(v: f64) -> f64 {
(v * 10_000.0).round() / 10_000.0
}
/// `(a, b)` per pair, `noise` left for the caller.
pub fn paired(pairs: &[(f64, f64)]) -> Paired {
let n = pairs.len();
let a = median(&pairs.iter().map(|p| p.0).collect::<Vec<_>>());
let b = median(&pairs.iter().map(|p| p.1).collect::<Vec<_>>());
let d: Vec<f64> = pairs.iter().map(|p| p.1 - p.0).collect();
let mut walsh = Vec::with_capacity(n * (n + 1) / 2);
for i in 0..n {
for j in i..n {
walsh.push((d[i] + d[j]) / 2.0);
}
}
walsh.sort_by(f64::total_cmp);
let diff = median(&walsh);
let interval = interval(n, &walsh);
let verdict = match interval {
None => Verdict::TooFewPairs,
Some(([lo, hi], _)) if lo <= 0.0 && 0.0 <= hi => Verdict::WithinNoise,
Some(_) if diff.abs() < 0.05_f64.max(0.02 * a) => Verdict::Negligible,
Some(([lo, _], _)) if lo > 0.0 => Verdict::Slower,
Some(_) => Verdict::Faster,
};
Paired {
pairs: n,
a: round(a) + 0.0,
b: round(b) + 0.0,
diff: round(diff) + 0.0,
diff_pct: (a != 0.0).then(|| round(100.0 * diff / a) + 0.0),
ci95: interval.map(|([lo, hi], _)| [round(lo) + 0.0, round(hi) + 0.0]),
confidence: interval.map(|(_, c)| round4(c)),
noise: None,
verdict,
}
}
/// The widest symmetric interval of the sorted Walsh averages whose tails hold at most 2.5% each, and its confidence.
fn interval(n: usize, walsh: &[f64]) -> Option<([f64; 2], f64)> {
let m = walsh.len();
// Null probabilities of T+ (halving is exact in binary, so these are the counts over 2^n).
let mut p = vec![0.0f64; m + 1];
p[0] = 1.0;
for r in 1..=n {
for t in (0..=m).rev() {
p[t] = (p[t] + if t >= r { p[t - r] } else { 0.0 }) / 2.0;
}
}
let (mut k, mut tail, mut best) = (0, 0.0, 0.0);
while k < m {
tail += p[k];
if tail > 0.025 {
break;
}
k += 1;
best = tail;
}
(k >= 1).then(|| ([walsh[k - 1], walsh[m - k]], 1.0 - 2.0 * best))
}
/// The result of an A/B run: pairs of blocks in B A A B order, recomputable from the report's `frames`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Ab {
pub switch: String,
pub a: String,
pub b: String,
pub pairs: u32,
pub block_s: f64,
pub warmup_s: f64,
/// Block 0 (measured before any switch) lies outside the later B blocks.
pub first_block_outside_range: bool,
/// By `gpu_p50_ms`, `cpu_p50_ms`, `frame_p50_ms`; a metric missing from any block is left out.
pub result: BTreeMap<String, Paired>,
}
impl Ab {
/// Pairs the `ab.a`/`ab.b` entries of `frames` by `repeat` (0, 1, 2...): pair k is blocks 2k and 2k+1.
pub fn from_frames(
switch: &str,
a: &str,
b: &str,
block_s: f64,
warmup_s: f64,
frames: &[Frames],
) -> Result<Ab, String> {
let mut blocks: Vec<&Frames> = frames
.iter()
.filter(|f| f.phase == "ab.a" || f.phase == "ab.b")
.collect();
blocks.sort_by_key(|f| f.repeat);
if blocks.is_empty()
|| !blocks.len().is_multiple_of(2)
|| blocks
.iter()
.enumerate()
.any(|(i, f)| f.repeat as usize != i)
{
return Err("A/B blocks must be numbered 0..N with N even".to_owned());
}
if blocks.chunks(2).any(|p| p[0].phase == p[1].phase) {
return Err("each pair needs one ab.a and one ab.b block".to_owned());
}
let pairs = blocks.len() / 2;
let metrics: [(&str, Getter); 3] = [
("gpu_p50_ms", |f| f.gpu_p50_ms),
("cpu_p50_ms", |f| f.cpu_p50_ms),
("frame_p50_ms", |f| Some(f.p50_ms)),
];
let mut result = BTreeMap::new();
let mut series: BTreeMap<&str, Vec<f64>> = BTreeMap::new();
for (name, get) in metrics {
let Some(values) = blocks.iter().map(|f| get(f)).collect::<Option<Vec<f64>>>() else {
continue;
};
let by_arm: Vec<(f64, f64)> = blocks
.chunks(2)
.zip(values.chunks(2))
.map(|(p, v)| {
if p[0].phase == "ab.a" {
(v[0], v[1])
} else {
(v[1], v[0])
}
})
.collect();
let mut stat = paired(&by_arm);
let gaps: Vec<f64> = (1..values.len().saturating_sub(1))
.step_by(2)
.filter(|&i| blocks[i].phase == blocks[i + 1].phase)
.map(|i| (values[i] - values[i + 1]).abs())
.collect();
stat.noise = (!gaps.is_empty()).then(|| round(median(&gaps)) + 0.0);
result.insert(name.to_owned(), stat);
series.insert(name, values);
}
let first_block_outside_range = series
.get("gpu_p50_ms")
.or_else(|| series.get("frame_p50_ms"))
.is_some_and(|values| {
let later: Vec<f64> = (1..values.len())
.filter(|&i| blocks[i].phase == "ab.b")
.map(|i| values[i])
.collect();
blocks[0].phase == "ab.b"
&& !later.is_empty()
&& (values[0] < later.iter().copied().fold(f64::INFINITY, f64::min)
|| values[0] > later.iter().copied().fold(f64::NEG_INFINITY, f64::max))
});
Ok(Ab {
switch: switch.to_owned(),
a: a.to_owned(),
b: b.to_owned(),
pairs: pairs as u32,
block_s,
warmup_s,
first_block_outside_range,
result,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{App, Kind, Report};
// Expected values: exact-rational Walsh averages and a brute-force sign enumeration, run once outside this code.
fn check(
a: &[f64],
b: &[f64],
diff: f64,
ci: Option<[f64; 2]>,
conf: Option<f64>,
verdict: Verdict,
) {
let pairs: Vec<(f64, f64)> = a.iter().copied().zip(b.iter().copied()).collect();
let p = paired(&pairs);
assert_eq!(
(p.pairs, p.diff, p.ci95, p.confidence, p.verdict),
(a.len(), diff, ci, conf, verdict),
"{b:?}"
);
}
#[test]
fn the_decided_vectors() {
use Verdict::*;
let z = |n: usize| vec![0.0; n];
let up = |n: usize| (1..=n).map(|v| v as f64).collect::<Vec<_>>();
check(&z(8), &up(8), 4.5, Some([2.0, 7.0]), Some(0.9609), Slower);
let wobble = [-0.3, 0.2, -0.1, 0.4, -0.2, 0.1, 0.3, -0.4];
check(
&z(8),
&wobble,
0.0,
Some([-0.3, 0.3]),
Some(0.9609),
WithinNoise,
);
check(&z(6), &up(6), 3.5, Some([1.0, 6.0]), Some(0.9688), Slower);
check(&z(5), &up(5), 3.0, None, None, TooFewPairs);
let a = [3.65, 3.70, 3.62, 3.68, 3.66, 3.71, 3.63, 3.69];
let b = [5.63, 5.60, 5.70, 5.58, 5.65, 5.62, 5.66, 5.61];
check(&a, &b, 1.96, Some([1.905, 2.03]), Some(0.9609), Slower);
let tiny: Vec<f64> = (1..=8).map(|v| 10.0 + v as f64 / 100.0).collect();
check(
&[10.0; 8],
&tiny,
0.045,
Some([0.02, 0.07]),
Some(0.9609),
Negligible,
);
let down: Vec<f64> = up(8).iter().map(|_| 0.0).collect();
check(
&up(8),
&down,
-4.5,
Some([-7.0, -2.0]),
Some(0.9609),
Faster,
);
let mixed = [0.5, -0.2, 0.0, 0.3, 0.9, -0.1, 0.4];
check(
&z(7),
&mixed,
0.225,
Some([-0.1, 0.65]),
Some(0.9531),
WithinNoise,
);
let ten = [0.3, -0.1, 0.8, 0.2, -0.5, 0.6, 0.1, 0.4, 0.7, 0.05];
check(
&z(10),
&ten,
0.25,
Some([-0.025, 0.55]),
Some(0.9512),
WithinNoise,
);
}
#[test]
fn medians_percent_and_empty_input() {
let a = [3.65, 3.70, 3.62, 3.68, 3.66, 3.71, 3.63, 3.69];
let b = [5.63, 5.60, 5.70, 5.58, 5.65, 5.62, 5.66, 5.61];
let p = paired(&a.iter().copied().zip(b).collect::<Vec<_>>());
assert_eq!(
(p.a, p.b, p.diff_pct, p.noise),
(3.67, 5.625, Some(53.406), None)
);
assert_eq!(
paired(&[(0.0, 1.0); 8]).diff_pct,
None,
"no percent of zero"
);
assert_eq!(paired(&[]).verdict, Verdict::TooFewPairs);
}
fn block(phase: &str, repeat: u32, frame: f64, cpu: Option<f64>, gpu: Option<f64>) -> Frames {
Frames {
phase: phase.into(),
repeat,
frames: 100,
seconds: 4.0,
avg_fps: 250.0,
low_1pct_fps: 100.0,
low_01pct_fps: 90.0,
p50_ms: frame,
p95_ms: frame + 1.0,
p99_ms: frame + 2.0,
p999_ms: frame + 3.0,
max_ms: frame + 4.0,
cpu_p50_ms: cpu,
gpu_p50_ms: gpu,
histogram: vec![0; crate::HISTOGRAM_EDGES_MS.len()],
}
}
// B A A B B A A B B A A B, as gpu milliseconds; frame time is gpu + 1.
fn twelve(first_b: f64) -> Vec<Frames> {
let gpu = [
first_b, 3.0, 3.2, 5.0, 5.2, 3.1, 3.1, 5.1, 5.4, 3.4, 3.3, 5.3,
];
gpu.iter()
.enumerate()
.map(|(i, &g)| {
block(
if matches!(i % 4, 0 | 3) {
"ab.b"
} else {
"ab.a"
},
i as u32,
g + 1.0,
Some(g / 2.0),
Some(g),
)
})
.collect()
}
fn from(frames: &[Frames]) -> Result<Ab, String> {
Ab::from_frames("gpu-culling", "off", "on", 4.0, 2.0, frames)
}
#[test]
fn noise_and_the_first_block_flag() {
let ab = from(&twelve(6.4)).unwrap();
assert!(
ab.first_block_outside_range,
"6.4 is 1 ms above the other B blocks"
);
let gpu = &ab.result["gpu_p50_ms"];
// Neighbours (1,2) (3,4) (5,6) (7,8) (9,10): 0.2 0.2 0 0.3 0.1.
assert_eq!(
(gpu.pairs, gpu.a, gpu.b, gpu.noise),
(6, 3.15, 5.25, Some(0.2))
);
assert_eq!(
(gpu.ci95, gpu.verdict),
(Some([1.8, 3.4]), Verdict::Slower),
"every d is positive: min and max Walsh averages"
);
assert_eq!(ab.result["cpu_p50_ms"].noise, Some(0.1));
assert_eq!(
(ab.pairs, ab.switch.as_str(), ab.a.as_str(), ab.b.as_str()),
(6, "gpu-culling", "off", "on")
);
assert!(!from(&twelve(5.2)).unwrap().first_block_outside_range);
}
#[test]
fn a_metric_missing_from_one_block_is_left_out() {
let mut frames = twelve(5.2);
frames[7].gpu_p50_ms = None;
let ab = from(&frames).unwrap();
assert_eq!(
ab.result.keys().collect::<Vec<_>>(),
["cpu_p50_ms", "frame_p50_ms"]
);
let mut frames = twelve(6.4);
frames[0].gpu_p50_ms = None;
frames[0].p50_ms = 6.0;
assert!(
!from(&frames).unwrap().first_block_outside_range,
"frame time 6.0 is inside 6.0..6.4 of the later B blocks"
);
}
#[test]
fn blocks_that_do_not_pair_are_refused() {
assert!(from(&[]).is_err());
assert!(from(&twelve(5.2)[..11]).is_err(), "odd number of blocks");
let mut frames = twelve(5.2);
frames[1].phase = "ab.b".into();
assert!(from(&frames).is_err(), "a pair of two B blocks");
let mut frames = twelve(5.2);
frames[3].repeat = 9;
assert!(from(&frames).is_err(), "a gap in the numbering");
}
#[test]
fn a_report_with_ab_round_trips_and_old_ones_still_parse() {
let mut r = Report::new(Kind::Game, App::default());
let old = r.to_json();
assert!(!old.contains("\"ab\""));
assert_eq!(Report::parse(&old).unwrap().ab, None);
r.frames = twelve(5.2);
r.ab = Some(from(&r.frames).unwrap());
let json = r.to_json();
assert_eq!(Report::parse(&json).unwrap(), r);
assert!(
json.contains("\"first_block_outside_range\": false")
&& json.contains("\"verdict\": \"slower\"")
);
assert_eq!(r.for_upload().ab, r.ab);
let mut few = paired(&[(1.0, 2.0); 3]);
few.noise = None;
assert!(serde_json::to_string(&few)
.unwrap()
.contains("\"ci95\":null,\"confidence\":null"));
}
}
+20 -125
View File
@@ -1,7 +1,8 @@
//! The machine a report was measured on. CPU, RAM and OS are detected here; the GPU and the display
//! come from the program that rendered (the game knows its adapter, the launcher its window).
use horizon_telemetry::system::command_output as output;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use horizon_system::command_output as output;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -61,6 +62,7 @@ pub struct Display {
pub refresh_hz: Option<u32>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Hardware {
pub fn detect() -> Hardware {
let probes = probes();
@@ -68,12 +70,12 @@ impl Hardware {
os: std::env::consts::OS.to_owned(),
os_version: os_version(),
arch: std::env::consts::ARCH.to_owned(),
cpu: cpu(),
cpu: horizon_system::cpu(),
cpu_threads: std::thread::available_parallelism().ok().map(|n| n.get()),
cpu_cores: probes.cores,
cpu_base_mhz: probes.base,
cpu_boost_mhz: probes.boost,
ram_mb: ram_bytes().map(|b| b >> 20),
ram_mb: horizon_system::ram_bytes().map(|b| b >> 20),
storage: None,
form: probes.form,
gpu: None,
@@ -84,13 +86,14 @@ impl Hardware {
/// [`Hardware::detect`] with the kind of drive `game_dir` is on.
pub fn detect_in(game_dir: &std::path::Path) -> Hardware {
Hardware {
storage: horizon_telemetry::system::storage(game_dir).map(str::to_owned),
storage: horizon_system::storage(game_dir).map(str::to_owned),
..Hardware::detect()
}
}
}
/// What the telemetry probes read (`horizon_telemetry::system`).
#[cfg(not(target_arch = "wasm32"))]
/// What `horizon_system::Machine` reads.
struct Probes {
cores: Option<u16>,
base: Option<u32>,
@@ -98,95 +101,31 @@ struct Probes {
form: Option<String>,
}
#[cfg(not(target_arch = "wasm32"))]
fn probes() -> Probes {
let s = horizon_telemetry::payload::System::detect();
let s = horizon_system::Machine::detect();
let some = |n: u32| (n > 0).then_some(n);
Probes {
cores: (s.cores > 0).then_some(s.cores),
base: some(s.cpu_base_mhz),
boost: some(s.cpu_boost_mhz),
form: (!s.form.is_empty()).then_some(s.form),
}
}
/// The one-minute load average: above about the number of threads the machine was busy.
pub fn load_average() -> Option<f64> {
if cfg!(target_os = "macos") {
// "{ 1.23 1.10 1.00 }"
output("sysctl", &["-n", "vm.loadavg"])?
.trim_start_matches('{')
.split_whitespace()
.next()?
.parse()
.ok()
} else {
std::fs::read_to_string("/proc/loadavg")
.ok()?
.split_whitespace()
.next()?
.parse()
.ok()
form: (!s.form.is_empty()).then(|| s.form.to_owned()),
}
}
#[cfg(not(target_arch = "wasm32"))]
/// `ac` or `battery`; `None` where it can't be read (and on machines without a battery on Linux).
pub fn power_source() -> Option<&'static str> {
horizon_telemetry::system::power()
}
/// Resident memory of a process, in bytes (macOS, Linux).
pub fn rss_bytes(pid: u32) -> Option<u64> {
if cfg!(target_os = "macos") {
return output("ps", &["-o", "rss=", "-p", &pid.to_string()])?
.parse::<u64>()
.ok()
.map(|kb| kb * 1024);
}
let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
let line = status.lines().find(|l| l.starts_with("VmRSS:"))?;
line.split_whitespace()
.nth(1)?
.parse::<u64>()
.ok()
.map(|kb| kb * 1024)
}
/// CPU time a process has used, user and system, in seconds (macOS, Linux).
pub fn cpu_seconds(pid: u32) -> Option<f64> {
if cfg!(target_os = "macos") {
// "[[dd-]hh:]mm:ss.cc"
let time = output("ps", &["-o", "time=", "-p", &pid.to_string()])?;
let (rest, days) = match time.split_once('-') {
Some((d, rest)) => (rest.to_owned(), d.parse::<f64>().ok()?),
None => (time, 0.0),
};
let seconds = rest.split(':').try_fold(0.0, |acc, part| {
part.parse::<f64>().ok().map(|v| acc * 60.0 + v)
})?;
return Some(days * 86_400.0 + seconds);
}
// utime and stime, fields 14 and 15, in clock ticks (100 per second on Linux).
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let fields: Vec<&str> = stat.rsplit_once(')')?.1.split_whitespace().collect();
let ticks: f64 = fields.get(11)?.parse::<f64>().ok()? + fields.get(12)?.parse::<f64>().ok()?;
Some(ticks / 100.0)
horizon_system::power()
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(target_os = "macos")]
fn os_version() -> Option<String> {
output("sw_vers", &["-productVersion"])
}
#[cfg(target_os = "macos")]
fn cpu() -> Option<String> {
output("sysctl", &["-n", "machdep.cpu.brand_string"])
}
#[cfg(target_os = "macos")]
fn ram_bytes() -> Option<u64> {
output("sysctl", &["-n", "hw.memsize"])?.parse().ok()
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(target_os = "linux")]
fn os_version() -> Option<String> {
let release = std::fs::read_to_string("/etc/os-release").ok()?;
@@ -199,22 +138,7 @@ fn os_version() -> Option<String> {
})
}
#[cfg(target_os = "linux")]
fn cpu() -> Option<String> {
let info = std::fs::read_to_string("/proc/cpuinfo").ok()?;
// x86 names the CPU per core; arm64 only gives the core's implementer and part.
horizon_telemetry::system::linux_cpu_name(&info)
}
#[cfg(target_os = "linux")]
fn ram_bytes() -> Option<u64> {
let info = std::fs::read_to_string("/proc/meminfo").ok()?;
let kb = key_value(&info, "MemTotal", ':')?
.trim_end_matches("kB")
.trim();
kb.parse::<u64>().ok().map(|kb| kb * 1024)
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(target_os = "linux")]
fn key_value<'a>(text: &'a str, key: &str, sep: char) -> Option<&'a str> {
text.lines().find_map(|line| {
@@ -223,45 +147,19 @@ fn key_value<'a>(text: &'a str, key: &str, sep: char) -> Option<&'a str> {
})
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(target_os = "windows")]
fn os_version() -> Option<String> {
horizon_telemetry::system::windows_version()
}
#[cfg(target_os = "windows")]
fn cpu() -> Option<String> {
horizon_telemetry::system::windows_cpu()
}
#[cfg(target_os = "windows")]
fn ram_bytes() -> Option<u64> {
let out = output(
"powershell",
&[
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory",
],
)?;
out.parse().ok()
horizon_system::windows_version()
}
#[cfg(not(target_arch = "wasm32"))]
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn os_version() -> Option<String> {
None
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn cpu() -> Option<String> {
None
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn ram_bytes() -> Option<u64> {
None
}
#[cfg(test)]
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
@@ -274,9 +172,6 @@ mod tests {
assert!(hw.cpu.is_some(), "{hw:?}");
assert!(hw.ram_mb.unwrap() > 256, "{hw:?}");
assert!(hw.os_version.is_some(), "{hw:?}");
assert!(load_average().is_some());
assert!(rss_bytes(std::process::id()).unwrap() > 1 << 20);
assert!(cpu_seconds(std::process::id()).unwrap() >= 0.0);
}
}
+12 -1
View File
@@ -11,9 +11,15 @@ use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
pub mod compare;
mod hardware;
pub use hardware::{cpu_seconds, load_average, power_source, rss_bytes, Display, Gpu, Hardware};
#[cfg(not(target_arch = "wasm32"))]
pub use hardware::power_source;
pub use hardware::{Display, Gpu, Hardware};
/// The process probes, from the platform (`horizon-system`).
#[cfg(not(target_arch = "wasm32"))]
pub use horizon_system::{cpu_seconds, load_average, rss_bytes};
pub const FORMAT: &str = "horizon-benchmark-report";
pub const VERSION: u32 = 1;
@@ -234,6 +240,9 @@ pub struct Report {
pub metrics: BTreeMap<String, Summary>,
#[serde(default)]
pub frames: Vec<Frames>,
/// Present in A/B runs only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ab: Option<compare::Ab>,
/// Local only: a name the person running it chose.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
@@ -244,6 +253,7 @@ pub struct Report {
impl Report {
/// An empty report for this machine, created now.
#[cfg(not(target_arch = "wasm32"))]
pub fn new(kind: Kind, app: App) -> Report {
Self::with_hardware(kind, app, Hardware::detect())
}
@@ -261,6 +271,7 @@ impl Report {
conditions: Conditions::default(),
metrics: BTreeMap::new(),
frames: Vec::new(),
ab: None,
label: None,
local: Vec::new(),
}
+65 -16
View File
@@ -952,8 +952,16 @@ mod tests {
(en, seen)
}
#[test]
fn every_horizon_key_the_code_names_is_in_en_us() {
/// The crates whose `horizon.` keys must be in en_us.json.
const CLIENT_CRATES: [&str; 4] = [
"horizon-client",
"horizon-client-render",
"horizon-client-core",
"horizon-client-input",
];
/// The Rust sources of `krates`, or of every crate under `crates/` when it is empty.
fn crate_sources(krates: &[&str]) -> Vec<std::path::PathBuf> {
fn rust_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
@@ -964,27 +972,68 @@ mod tests {
}
}
}
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut files = Vec::new();
if krates.is_empty() {
for entry in std::fs::read_dir(&crates).unwrap().flatten() {
rust_files(&entry.path().join("src"), &mut files);
}
}
for krate in krates {
rust_files(&crates.join(krate).join("src"), &mut files);
}
assert!(files.len() > 100, "found only {} sources", files.len());
files
}
/// A sentence key (the English text itself, not a `horizon.` id) that no
/// source names as a string literal is text the game no longer shows: its
/// rewording left it behind in every language (#13802).
#[test]
fn every_sentence_key_in_en_us_is_one_the_code_names() {
let en: HashMap<String, String> = serde_json::from_str(
&std::fs::read_to_string(bundled_dir().join("en_us.json")).unwrap(),
)
.unwrap();
// Every crate: a feature moved out of the client crates keeps its strings.
let code: String = crate_sources(&[])
.iter()
.map(|file| std::fs::read_to_string(file).unwrap())
.collect();
let sentences: Vec<&String> = en.keys().filter(|k| !k.starts_with("horizon.")).collect();
assert!(
sentences.len() > 100,
"found only {} sentence keys",
sentences.len()
);
// A JSON string literal escapes `"` and `\` as Rust's does.
let mut dead: Vec<&str> = sentences
.into_iter()
.filter(|key| !code.contains(&serde_json::to_string(key).unwrap()))
.map(String::as_str)
.collect();
dead.sort_unstable();
assert!(
dead.is_empty(),
"en_us.json keys no code asks for: {dead:#?}"
);
}
#[test]
fn every_horizon_key_the_code_names_is_in_en_us() {
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 [
"horizon-client",
"horizon-client-render",
"horizon-client-core",
] {
rust_files(&crates.join(krate).join("src"), &mut files);
}
let mut krates = CLIENT_CRATES.to_vec();
// 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);
let lang_dirs = crate_lang_dirs();
for (name, dir) in &lang_dirs {
en.extend(english(dir));
krates.push(name);
}
assert!(files.len() > 100, "found only {} sources", files.len());
let mut found = 0;
for file in files {
for file in crate_sources(&krates) {
let text = std::fs::read_to_string(&file).unwrap();
for (at, _) in text.match_indices("\"horizon.") {
let rest = &text[at + 1..];
+32 -1
View File
@@ -61,6 +61,8 @@ pub enum ClickEvent {
/// A local file to open with the system handler.
/// Only allow this in locally constructed messages, never server/LAN text.
OpenFile(String),
/// A `/profiler` line the client's own buttons run; never decoded from a server's text, so only they reach the local profiler.
Profiler(String),
}
/// A non-character `minecraft:object` embedded in a text component.
@@ -202,7 +204,12 @@ impl Text {
}
}
pub fn styled(s: impl Into<String>, style: Style) -> Self {
Self::literal(s).with_style(&style)
let mut text = Self::literal(s).with_style(&style);
// `inherit` never passes an object on, but a styled span's own style carries it.
for span in &mut text.spans {
span.style.inline_object.clone_from(&style.inline_object);
}
text
}
pub fn colored(s: impl Into<String>, color: u32) -> Self {
Self::styled(s, Style::color(color))
@@ -619,6 +626,9 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
event
}
ClickEvent::OpenFile(path) => json!({ "action": "open_file", "path": path }),
ClickEvent::Profiler(command) => {
json!({ "action": "run_command", "command": command })
}
};
out.push(("click_event".to_owned(), event));
}
@@ -772,6 +782,27 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text {
mod tests {
use super::*;
#[test]
fn a_styled_object_span_keeps_its_object_through_append_and_slice() {
let object = InlineObject::Atlas {
atlas: "minecraft:gui".into(),
sprite: "horizon:gui/mark".into(),
fallback: "H".into(),
};
let sprite = Text::styled(
"\u{fffc}",
Style {
inline_object: Some(object.clone()),
..Style::color(WHITE)
},
);
let line = Text::colored("[", DARK_GRAY)
.append(sprite)
.append(Text::colored("] ", DARK_GRAY));
let line = line.slice(0, 3);
assert_eq!(line.spans[1].style.inline_object, Some(object));
assert_eq!(line.plain(), "[H]");
}
#[test]
fn appending_builds_the_same_tree_in_linear_time() {
// A styled text is wrapped once, so its style doesn't reach what follows; a plain one
// takes the siblings itself; a copy taken before an append keeps its own tree.
+8
View File
@@ -27,6 +27,8 @@ horizon-mcp = { path = "../horizon-mcp" }
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
horizon-optifine = { path = "../horizon-optifine" }
horizon-threads = { path = "../horizon-threads" }
# The .hzperf capture format and writer (docs/perf-platform.md).
horizon-perf-format = { path = "../horizon-perf-format" }
# One pool of helper threads for the server tick's parallel phases (`parallel.rs`): threads made
# once, not for every phase of every tick.
rayon = "1.10"
@@ -91,6 +93,8 @@ rustix = { version = "1", default-features = false, features = ["std", "time", "
[target.'cfg(windows)'.dependencies]
# Use the registered URI handler without routing links through Explorer/cmd.
open = { version = "5.4.5", features = ["shellexecute-on-windows"] }
# Resolve virtualized folders to shell-compatible physical paths (desktop.rs).
dunce = "1.0.5"
# DirectX 12, where Vulkan has no adapter or device, or by choice (`graphicsApi`, graphics.rs).
# Shaders compile with FXC (d3dcompiler_47.dll, part of Windows), or on integrated GPUs with DXC
# (dxcompiler.dll beside the game, gfx/dx12_compiler.rs).
@@ -110,6 +114,8 @@ wgpu = { version = "30.0.1", default-features = false, features = ["gles"] }
[features]
default = ["audio", "controllers"]
# Dev-only: the ignored tracker-send benchmark uses the executable's allocator.
tracker-send-bench = []
# Sound output. Without it (and `controllers`) the program links neither libasound nor libudev on
# Linux: the server build (`--no-default-features`, released as horizon-engine; docs/server.md).
audio = ["horizon-client-render/audio"]
@@ -130,6 +136,8 @@ workspace = true
horizon-theme = { path = "../horizon-theme" }
horizon-client-render = { path = "../horizon-client-render", features = ["test-support"] }
horizon-items = { path = "../horizon-items", features = ["test-support"] }
# Reads back the captures the server_perf tests write.
horizon-perf = { path = "../horizon-perf" }
# Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests).
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] }
+5
View File
@@ -23,6 +23,7 @@ horizon-narrator = { path = "../horizon-narrator" }
# OptiFine-format pack files: random entity textures (hud.rs), connected textures
# (connected.rs) and custom item texture rules (cit.rs).
horizon-optifine = { path = "../horizon-optifine" }
horizon-perf-format = { path = "../horizon-perf-format" }
horizon-polytone = { path = "../horizon-polytone" }
horizon-protocol = { path = "../horizon-protocol" }
horizon-shader-api = { path = "../horizon-shader-api" }
@@ -74,6 +75,9 @@ wgpu = { version = "30.0.1", default-features = false, features = ["gles"] }
audio = ["dep:cpal"]
# Helpers horizon-client's tests build their fixtures with.
test-support = []
# The `scene_replay` example's allocator counts allocations (horizon-threads' `alloc-count`).
alloc-count = ["horizon-threads/alloc-count"]
# horizon-client's `horizon-extras`: asking the device for hardware ray tracing on request
# (`gfx/ray_query.rs`, `HORIZON_RAY_TRACING=1`). Without it the device is requested as without
# the variable.
@@ -83,6 +87,7 @@ horizon-extras = []
workspace = true
[dev-dependencies]
horizon-perf = { path = "../horizon-perf" }
# Tests: a TrueType font to load, and the design system the menus' motion curves match.
horizon-theme = { path = "../horizon-theme" }
horizon-items = { path = "../horizon-items", features = ["test-support"] }
@@ -6,13 +6,14 @@
//! [--mipmaps N] [--lod-distance CHUNKS] [--render-distance CHUNKS] [--size WxH]
//! [--section-draws flat|indirect] [--section-cull on|off] [--section-sides on|off]
//! [--gpu-culling on|off] [--root RESOURCES] [--screenshot PNG]
//! [--world SAVE --leaf-culling MODE] [--memory on]`
//! [--world SAVE --leaf-culling MODE] [--memory on] [--gpu-detail on|off]`
//! `--screenshot` saves the first view's last frame, after the timed frames.
//! `--world` meshes the captured sections again from that save's region files
//! (blocks, biomes and saved light; `ao`, `biomeBlendRadius` and `cutoutLeaves`
//! from `./options.txt`) with `--leaf-culling` (default `off`), so a mesher
//! change can be measured on the captured view. A section whose 3x3 columns are
//! not all saved keeps its captured mesh.
//! `--gpu-detail on` adds GPU culling's dispatch times and, on Vulkan, the world passes' counters.
//! `--memory on` adds the renderer's largest GPU resources and, on macOS, the process's
//! physical footprint by category (`footprint`), taken after the timed frames.
use horizon_client_render::{
@@ -24,6 +25,7 @@ use horizon_client_render::{
gfx::{
PreparedTextures, Renderer, ScreenshotRequest,
capture::{self, AtlasCheck, Scene},
pack_timing,
panorama::Faces,
},
graphics::LeafCullingMode,
@@ -61,7 +63,10 @@ use winit::{
// The game's allocator, so that `--memory`'s footprint is the game's: the system heap kept
// gigabytes of the meshes `--world` frees dirty.
#[global_allocator]
static ALLOCATOR: horizon_threads::Allocator = horizon_threads::ALLOCATOR;
static ALLOCATOR: horizon_threads::GameAllocator = horizon_threads::GAME_ALLOCATOR;
/// Frames drawn with detail on, enough for a few timed frames of each kind.
const DETAIL_FRAMES: usize = 60;
#[derive(Default)]
struct Options {
@@ -84,6 +89,7 @@ struct Options {
world: Option<PathBuf>,
leaf_culling: LeafCullingMode,
memory: bool,
gpu_detail: bool,
}
fn on_off(value: &str) -> Result<bool, String> {
@@ -136,6 +142,7 @@ fn options() -> Result<Options, String> {
"--screenshot" => o.screenshot = Some(value.into()),
"--world" => o.world = Some(value.into()),
"--memory" => o.memory = on_off(&value)?,
"--gpu-detail" => o.gpu_detail = on_off(&value)?,
"--leaf-culling" => {
o.leaf_culling = LeafCullingMode::ALL
.into_iter()
@@ -400,6 +407,23 @@ fn replay(window: Arc<Window>) -> Result<(), Box<dyn std::error::Error>> {
None => notes.push("screenshot: not saved".into()),
}
}
let mut detail = serde_json::Map::new();
if o.gpu_detail {
renderer.set_pass_detail(true);
for _ in 0..DETAIL_FRAMES {
draw(&mut renderer)?;
}
detail.insert(
"gpu_pass_parts_median_ms".into(),
pack_timing::parts_json(&renderer.own_pass_parts()),
);
let unit = renderer.pass_detail_support().and_then(|s| s.fragment_unit);
detail.insert(
"gpu_counters_median".into(),
pack_timing::counters_by_pass_json(&renderer.own_pass_counters(), unit),
);
renderer.set_pass_detail(false);
}
views.push(json!({
"yaw_offset": offset,
"gpu_ms": summary(&gpu),
@@ -417,6 +441,9 @@ fn replay(window: Arc<Window>) -> Result<(), Box<dyn std::error::Error>> {
// indices hidden.
"culled": renderer.culled_sections(),
}));
if let Some(Value::Object(view)) = views.last_mut() {
view.extend(detail);
}
}
let section_draws = if renderer.flat_draws() {
"flat"
@@ -424,6 +451,11 @@ fn replay(window: Arc<Window>) -> Result<(), Box<dyn std::error::Error>> {
"indirect"
};
let memory = o.memory.then(|| memory_report(&renderer));
let gpu_detail = o
.gpu_detail
.then(|| renderer.pass_detail_support())
.flatten()
.map(pack_timing::support_json);
let report = json!({
"capture": o.dir.display().to_string(),
"adapter": renderer.info.name,
@@ -454,6 +486,7 @@ fn replay(window: Arc<Window>) -> Result<(), Box<dyn std::error::Error>> {
"notes": notes,
"views": views,
"memory": memory,
"gpu_detail": gpu_detail,
});
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
@@ -1442,6 +1442,8 @@ impl Audio {
} else {
Err("no output on a dedicated server".into())
};
// Without `audio` a stream can't exist (`Infallible`), so the `Ok` arm never runs.
#[cfg_attr(not(feature = "audio"), allow(unreachable_code))]
let (stream, live) = match opened {
Ok(v) => (Some(v), true),
Err(e) => {
+13 -1
View File
@@ -1279,6 +1279,9 @@ pub struct ChatScreen {
/// `CommandSuggestions.setRestrictions`: what the Chat option allows.
pub abilities: ChatAbilities,
pub layout: SuggestLayout,
/// `MouseHandler.lastClick`: a click within 250 ms of the last one on
/// this screen is a double click.
last_click: Option<std::time::Instant>,
}
/// Local completions waiting for the server's reply to request `id`.
struct Awaiting {
@@ -1401,6 +1404,7 @@ impl ChatScreen {
auto_suggestions: true,
abilities,
layout: SuggestLayout::CHAT,
last_click: None,
};
s.update_command_info(m, c);
s
@@ -1439,6 +1443,7 @@ impl ChatScreen {
auto_suggestions: true,
abilities: ChatAbilities::new(ChatVisibility::Full),
layout: SuggestLayout::COMMAND_BLOCK,
last_click: None,
};
s.update_command_info(m, c);
s
@@ -1966,8 +1971,15 @@ impl ChatScreen {
}
self.suggestions = Some(l);
}
// MouseHandler: the same screen's click within 250 ms is a double
// click, which selects the word under the pointer.
let now = std::time::Instant::now();
let double = self
.last_click
.is_some_and(|at| now.duration_since(at).as_millis() < 250);
self.last_click = Some(now);
if self.input.contains(x, y) {
self.input.click(m, x, false);
self.input.click(m, x, false, double);
return true;
}
false
@@ -305,6 +305,31 @@ fn locate_coordinates_fill_chat_with_teleport_without_submitting() {
}
}
/// `EditBox.onClick`: a double click selects the word under the pointer; a
/// single click only places the caret there.
#[test]
fn a_double_click_in_the_chat_box_selects_the_word() {
let font = font();
let m = Measure(&font);
let registries = Registries::default();
let c = Commands {
dispatcher: crate::command::vanilla::game_dispatcher(),
registries: &registries,
};
let mut screen = ChatScreen::new(&m, &c, "", false, 0, 640, 360, full());
screen.type_text(&m, &c, "hello world");
// The pointer on the last letter: the first click places the caret there,
// the second takes the word.
let x = f64::from(screen.input.x) + f64::from(font.width("hello world")) - 1.0;
let y = f64::from(screen.input.y) + 2.0;
assert!(screen.click(&m, &c, x, y));
assert!((10..=11).contains(&screen.input.cursor));
assert_eq!(screen.input.highlight, screen.input.cursor);
assert!(screen.click(&m, &c, x, y));
assert_eq!((screen.input.highlight, screen.input.cursor), (6, 11));
assert_eq!(screen.input.selected_text(), "world");
}
#[test]
fn history_arrows_recall_messages_and_restore_the_draft() {
use winit::keyboard::KeyCode::{ArrowDown, ArrowUp};
@@ -413,12 +413,20 @@ pub enum NameOrId {
pub struct Crafter {
pub items: [Option<ItemStack>; 9],
pub disabled: [bool; 9],
pub triggered: bool,
/// `containerData` slot 9 as saved (`triggered`): any int, triggered
/// only at 1 ([`Crafter::is_triggered`]).
pub triggered: i32,
pub crafting_ticks: i32,
/// The block state's `triggered` when last ticked (not saved): the block
/// entity flag follows it only when it changes (`CrafterBlock.neighborChanged`).
pub state_triggered: Option<bool>,
}
impl Crafter {
/// `CrafterBlockEntity.isTriggered`: `containerData.get(9) == 1`.
pub fn is_triggered(&self) -> bool {
self.triggered == 1
}
}
#[derive(Clone, Debug, Default)]
pub struct Banner {
pub layers: Vec<BannerLayer>,
@@ -465,6 +473,9 @@ pub struct Jukebox {
/// reference exists. Keep this separate from legacy playback adoption.
pub song_clock_present: bool,
pub playing: bool,
/// A clock a save brought back, not playing yet: `setSongWithoutPlaying`
/// keeps the song and its clock without the sound's level event 1010.
pub loaded_clock: bool,
}
impl Jukebox {
/// `JukeboxBlockEntity.getTheItem`: the disc it holds.
@@ -291,10 +291,15 @@ impl SceneCollisions<'_, '_> {
}
fn context(&self, bounds: Aabb) -> CollisionContext<'static> {
let y = bounds.min_position().y;
if !self
.subject
.is_some_and(|s| s.lava_walker || s.leather_boots)
{
// An entity context is needed wherever PowderSnowBlock or a strider
// reads the entity: boots, the walkable tag, a long fall.
if !self.subject.is_some_and(|s| {
s.lava_walker
|| s.leather_boots
|| s.walkable_type
|| s.falling_block
|| s.fall_distance > 2.5
}) {
return CollisionContext::position(y);
}
CollisionContext::for_entity(
@@ -3,7 +3,8 @@
//! - 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.
//! initializer gives;
//! - an array declared with a `const int`'s size takes the constant's expression.
/// The longest shader rewritten (vanilla's, includes expanded, are a few KiB).
const MAX_LEN: usize = 64 * 1024;
@@ -17,7 +18,115 @@ pub(super) fn fixups(text: &str) -> String {
if text.len() > MAX_LEN {
return text.to_owned();
}
size_unsized_arrays(&specialize_sampler_params(text))
size_by_int_constants(&size_unsized_arrays(&specialize_sampler_params(text)))
}
/// The most `const int`s a shader's arrays are sized by.
const MAX_INT_CONSTANTS: usize = 256;
/// `type name[n]` becomes `type name[(expression)]` where `const int n = expression;` is in scope;
/// accesses (`name[n]`) are left as they are. Two constants of one name and different values in
/// one scope, which only exclusive `#if` branches allow, leave the text as it was; the same one
/// twice is a guarded include pasted twice.
fn size_by_int_constants(text: &str) -> String {
struct Constant<'a> {
name: &'a str,
expression: &'a str,
from: usize,
to: usize,
}
let bytes = text.as_bytes();
let mut constants: Vec<Constant> = Vec::new();
let mut scopes: Vec<Vec<usize>> = vec![Vec::new()];
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'{' => scopes.push(Vec::new()),
b'}' => {
for c in scopes.pop().unwrap_or_default() {
constants[c].to = i;
}
if scopes.is_empty() {
return text.to_owned();
}
}
b'c' if text[i..].starts_with("const int ")
&& (i == 0 || !is_ident(char::from(bytes[i - 1]))) =>
{
let start = i + "const int ".len();
let Some(end) = text[start..].find([';', '{', '}']).map(|e| start + e) else {
break;
};
if bytes[end] == b';'
&& let Some((name, expression)) = text[start..end].split_once('=')
{
let (name, expression) = (name.trim(), expression.trim());
if is_name(name) && !expression.is_empty() {
let scope = scopes.last_mut().expect("the global scope stays");
let same = scope.iter().find(|&&c| constants[c].name == name);
match same {
Some(&c) if constants[c].expression == expression => {}
Some(_) => return text.to_owned(),
None if constants.len() == MAX_INT_CONSTANTS => {
return text.to_owned();
}
None => {
scope.push(constants.len());
constants.push(Constant {
name,
expression,
from: end,
to: text.len(),
});
}
}
}
}
i = end;
continue;
}
_ => {}
}
i += 1;
}
if constants.is_empty() {
return text.to_owned();
}
let mut out = String::with_capacity(text.len());
let mut copied = 0;
let mut at = 0;
while let Some(found) = text[at..].find('[') {
let open = at + found;
at = open + 1;
let Some(close) = text[open..].find(']').map(|c| open + c) else {
break;
};
let size = text[open + 1..close].trim();
let Some(constant) = constants
.iter()
.filter(|c| c.name == size && c.from < open && open < c.to)
.max_by_key(|c| c.from)
else {
continue;
};
if !declares_an_array(text, open) {
continue;
}
out.push_str(&text[copied..=open]);
out.push('(');
out.push_str(constant.expression);
out.push(')');
copied = close;
}
out.push_str(&text[copied..]);
out
}
/// Whether the `[` at `open` follows `type name`, so it sizes a declaration.
fn declares_an_array(text: &str, open: usize) -> bool {
ident_before(text, open)
.and_then(|(start, _)| ident_before(text, start))
.is_some_and(|(_, ty)| !matches!(ty, "return" | "else" | "case"))
}
fn is_ident(c: char) -> bool {
@@ -245,6 +245,72 @@ fn thousands_of_calls_are_left_as_they_were() {
);
}
#[test]
fn an_array_sized_by_a_local_int_constant_takes_its_expression() {
let text =
"void main() {\n const int n = COUNT / 4;\n vec4 s[n];\n s[0] = vec4(n);\n}\n";
let out = size_by_int_constants(text);
assert!(out.contains("vec4 s[(COUNT / 4)];"), "{out}");
assert!(out.contains("s[0] = vec4(n);"), "{out}");
}
#[test]
fn each_function_sizes_by_its_own_constant_and_accesses_are_kept() {
let text = "float f() {\n const int n = 2;\n float a[n];\n a[1] = 1.0;\n return a[n - 1];\n}\n\
float g() {\n const int n = 4;\n float b[n];\n b[3] = 1.0;\n float c = b[n];\n return c;\n}\n";
let out = size_by_int_constants(text);
assert!(out.contains("float a[(2)];"), "{out}");
assert!(out.contains("float b[(4)];"), "{out}");
assert!(out.contains("b[3] = 1.0;"), "{out}");
assert!(out.contains("float c = b[n];"), "{out}");
assert!(out.contains("return a[n - 1];"), "{out}");
}
#[test]
fn an_inner_constant_shadows_the_outer_one_only_inside_its_block() {
let text = "void main() {\n const int n = 2;\n {\n const int n = 4;\n float inner[n];\n }\n\
float outer[n];\n}\n";
let out = size_by_int_constants(text);
assert!(out.contains("float inner[(4)];"), "{out}");
assert!(out.contains("float outer[(2)];"), "{out}");
}
#[test]
fn constants_of_exclusive_branches_leave_the_text_as_it_was() {
let text = "void main() {\n#ifdef A\n const int n = 2;\n#else\n const int n = 4;\n#endif\n float a[n];\n}\n";
assert_eq!(size_by_int_constants(text), text);
}
#[test]
fn a_guarded_include_pasted_twice_still_sizes_its_arrays() {
let include = "#ifndef I\n#define I\nconst int bins = 2;\n#endif\n";
let text = format!("{include}{include}void main() {{\n float a[bins];\n}}\n");
assert!(size_by_int_constants(&text).contains("float a[(2)];"));
}
#[test]
fn arrays_sized_by_two_functions_constants_translate_to_their_own_sizes() {
let fsh = "#version 330\nout vec4 fragColor;\n\
float f() {\n const int n = 2;\n float a[n];\n a[1] = 1.0;\n return a[1];\n}\n\
float g() {\n const int n = 4;\n float b[n];\n b[3] = 1.0;\n return b[3];\n}\n\
void main() {\n fragColor = vec4(f() + g());\n}\n";
let program = translate(fsh).unwrap();
let mut sizes: Vec<u32> = program
.fragment
.types
.iter()
.filter_map(|(_, ty)| match ty.inner {
naga::TypeInner::Array {
size: naga::ArraySize::Constant(n),
..
} => Some(n.get()),
_ => None,
})
.collect();
sizes.sort_unstable();
assert_eq!(sizes, [2, 4]);
}
#[test]
fn unsized_arrays_take_their_initializers_size() {
let text = "const float[] w = float[](0.25, 0.5, 0.25);\n\
+4 -4
View File
@@ -36,7 +36,7 @@ struct Globals {
// w: apply the no-pack HDR gain; HDR_WRITE_LIGHT independently keeps float alpha as coverage.
hdr_light: vec4<f32>,
hdr_settings: vec4<f32>,
hdr_shares: vec4<f32>,
hdr_gains: vec4<f32>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@@ -292,7 +292,7 @@ fn entity_written_color(in: Out, color: vec4<f32>) -> vec4<f32> {
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 && in.overlay != 11u && in.overlay != 12u {
var mark = hdr_entity_mark(in);
if in.overlay == 4u { mark = hdr_scene_alpha(globals.hdr_light.y); }
return vec4(hdr_written(color.rgb, mark, globals.hdr_settings, globals.hdr_shares), color.a);
return vec4(hdr_written(color.rgb, mark, globals.hdr_settings, globals.hdr_gains), color.a);
}
if FRAME_LINEAR && (in.overlay == 11u || in.overlay == 12u) {
// The cracks scale what is under them by twice their colour (CRUMBLING_BLEND). Vanilla's
@@ -451,7 +451,7 @@ fn celestial_color(in: Out) -> vec4<f32> {
@fragment fn fs_celestial(in: Out) -> @location(0) vec4<f32> {
let color = celestial_color(in);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
return vec4(hdr_written(color.rgb, hdr_entity_mark(in), globals.hdr_settings, globals.hdr_shares), color.a);
return vec4(hdr_written(color.rgb, hdr_entity_mark(in), globals.hdr_settings, globals.hdr_gains), color.a);
}
return frame_stored(color);
}
@@ -472,7 +472,7 @@ fn celestial_color(in: Out) -> vec4<f32> {
// or it would come out darker than the sky around it.
let full = y >= globals.hdr_windows[1][clamp(tier, 1u, 4u) - 1u];
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
return vec4(hdr_written(added, select(1.0, hdr_mark(tier, y), full), globals.hdr_settings, globals.hdr_shares), color.a);
return vec4(hdr_written(added, select(1.0, hdr_mark(tier, y), full), globals.hdr_settings, globals.hdr_gains), color.a);
}
// Premultiplied after the decode: the light the texel adds, at its coverage.
if HDR_WRITE_LIGHT { return vec4(frame_stored(color).rgb * color.a, color.a); }
+88 -423
View File
@@ -192,6 +192,7 @@ fn packed_wanted() -> bool {
pub(crate) mod animate;
mod arena;
pub mod capture;
mod census;
pub mod compositor;
pub(crate) mod core_lines;
pub(crate) mod core_sky;
@@ -209,6 +210,7 @@ mod hdr_icc;
mod hdr_start;
mod hdr_stats;
pub(crate) mod hud_coverage;
mod in_flight;
pub use hdr::{Calibration as HdrCalibration, Output as HdrOutput};
mod hold;
pub use hold::WorldHold;
@@ -246,9 +248,11 @@ mod pack_post;
mod pack_shadow;
mod pack_sky;
mod pack_textures;
pub(crate) mod pack_timing;
pub mod pack_timing;
pub mod pack_uniforms;
mod pack_weather;
mod pass_timing_api;
use pass_timing_api::{after_culling_pass, pixel_count, world_pass_after_culling};
mod page_runs;
pub mod panorama;
mod readback;
@@ -337,42 +341,6 @@ fn surface_pass<'e>(
..Default::default()
})
}
fn world_pass_after_culling<'e>(
encoder: &'e mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
depth: &wgpu::TextureView,
keep_depth: bool,
timing: Option<&mut pack_timing::PassTiming>,
name: &str,
) -> wgpu::RenderPass<'e> {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon world, after culling"),
timestamp_writes: timing.and_then(|t| t.writes(name)),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
// A shader pack reads it as depthtex0.
store: if keep_depth {
wgpu::StoreOp::Store
} else {
wgpu::StoreOp::Discard
},
}),
stencil_ops: None,
}),
..Default::default()
})
}
/// The point a `shaders/` pack's terrain is drawn relative to: the camera with the fraction of
/// each coordinate rounded to the nearest 1/65536 block. Read back with a probe pack of ours,
/// Iris 1.11.7's terrain `gl_Vertex` is the block's position minus this, for cameras from 13
@@ -427,10 +395,10 @@ struct Globals {
/// full (`hdr::Hdr::windows`); zero without HDR.
hdr_windows: [[f32; 4]; 2],
hdr_light: [f32; 4],
/// Headroom, effective scene gain, world/look and debug, as HDR output's pass has them
/// The scene's peak, HDR lighting's gain, world/look and debug; then the tiers' gains
/// (`Hdr::draw_params`).
hdr_settings: [f32; 4],
hdr_shares: [f32; 4],
hdr_gains: [f32; 4],
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
@@ -1473,10 +1441,14 @@ pub struct Renderer {
pack_loading: Option<PackLoading>,
/// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s.
native: Option<native_pack::NativePack>,
/// Time the shader pack's passes on the GPU (F3, or `HORIZON_SHADER_PACK_TIMING`).
/// Time the shader pack's passes on the GPU (F3, or a capture made with `--gpu`).
pass_timing: bool,
/// Times the parts of passes too (`set_pass_detail`).
pass_detail: bool,
/// Least time between timed frames (`set_pass_timing_gap`).
pass_timing_gap: std::time::Duration,
/// Whether the timers keep every timed frame for `take_timed_frames`.
keep_timed_frames: bool,
/// Times Horizon's own passes on the GPU, as `pass_timing` does (`own_pass_times`).
own_timing: Option<pack_timing::PassTiming>,
/// The entity vertices Horizon draws itself while a shader pack draws the others.
@@ -2547,160 +2519,6 @@ enum FirstFrame {
fn on_off(on: bool) -> &'static str {
if on { "on" } else { "off" }
}
impl Renderer {
/// Sections with GPU buffers, for soak tests watching residency.
pub fn resident_sections(&self) -> usize {
self.sections.len()
}
/// Quads of the far terrain tiles with GPU buffers.
pub fn lod_quads(&self) -> u64 {
self.lods
.values()
.map(|tile| u64::from(tile.mesh.solid + tile.mesh.translucent))
.sum()
}
/// Tiles and quads of the far terrain tiles with GPU buffers, by level.
pub fn lod_levels(&self) -> Vec<[u64; 2]> {
let mut levels = Vec::new();
for (key, tile) in &self.lods {
let level = usize::from(key.level);
if levels.len() <= level {
levels.resize(level + 1, [0, 0]);
}
levels[level][0] += 1;
levels[level][1] += u64::from(tile.mesh.solid + tile.mesh.translucent);
}
levels
}
/// Whether solid quads go to the arena in the compact layout
/// (`packed_quads`), and whether far tiles' own records are on
/// (`lod::packed::far_packing`).
pub fn packed_layout(&self) -> [bool; 2] {
[self.packed_quads, crate::lod::packed::far_packing()]
}
/// Bytes of the arena the resident chunk sections hold, and of the one far
/// tiles hold: the same split `gpu_census` reports, for `status`, so the
/// compact layouts can be seen working.
pub fn vertex_bytes_split(&self) -> [u64; 2] {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let used = |s: &SectionGpu| (s.solid_slots + u64::from(s.translucent) * 4) * stride;
[
self.sections.values().map(used).sum(),
self.lods.values().map(|tile| used(&tile.mesh)).sum(),
]
}
/// Bytes of the section vertex arenas' buffers, and of the vertices
/// resident sections hold in them.
pub fn section_vertex_bytes(&self) -> [u64; 2] {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let vertices: u64 = self
.sections
.values()
.chain(self.lods.values().map(|tile| &*tile.mesh))
.map(|s| s.solid_slots + u64::from(s.translucent) * 4)
.sum();
let translucent = self.translucent_arena.as_ref();
let arenas = self.arena.bytes() + translucent.map_or(0, arena::Arena::bytes);
[arenas, vertices * stride]
}
/// Bytes of the renderer's largest GPU resources, by name (`scene_replay --memory`):
/// the terrain arenas (their pages, and what resident sections and far tiles use of
/// them), the quad indices, the block sprites with their mips, the LabPBR maps, flat
/// draws' buffers and the visibility buffer's.
pub fn gpu_census(&self) -> Vec<(&'static str, u64)> {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let used = |s: &SectionGpu| (s.solid_slots + u64::from(s.translucent) * 4) * stride;
let textures = |t: &[wgpu::Texture]| t.iter().map(texture_bytes).sum::<u64>();
let translucent = self.translucent_arena.as_ref();
vec![
("section_arena_pages", self.arena.bytes()),
(
"translucent_arena_pages",
translucent.map_or(0, arena::Arena::bytes),
),
("sorted_index_pages", self.sorted_indices.bytes()),
(
"near_section_vertices",
self.sections.values().map(used).sum(),
),
(
"held_section_vertices",
self.hold
.sections()
.filter_map(|held| held.gpu.as_ref())
.map(used)
.sum(),
),
(
"far_tile_vertices",
self.lods.values().map(|tile| used(&tile.mesh)).sum(),
),
("quad_indices", self.indices.size()),
("block_sprites", textures(&self.sprite_textures)),
(
"pbr_maps",
self.pbr_maps
.as_ref()
.map_or(0, |maps| maps.iter().flatten().map(texture_bytes).sum()),
),
(
"flat_draws",
self.flat.as_ref().map_or(0, flat::Flat::bytes),
),
(
"visibility_buffer",
self.visbuf.as_ref().map_or(0, visbuffer::Visbuffer::bytes),
),
]
}
/// Device memory the backend's allocator holds, by the label of what holds
/// it, largest first, with its allocated and reserved totals (Vulkan and
/// DirectX 12; none on Metal and OpenGL) (`horizon-ctl memory`).
pub fn gpu_memory_by_label(&self) -> Option<(u64, u64, Vec<(String, u64)>)> {
let report = self.device.generate_allocator_report()?;
let mut by_label: HashMap<String, u64> = HashMap::new();
for a in report.allocations {
*by_label.entry(a.name).or_default() += a.size;
}
let mut labels: Vec<_> = by_label.into_iter().collect();
labels.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
Some((
report.total_allocated_bytes,
report.total_reserved_bytes,
labels,
))
}
/// Heap bytes of the renderer's per-section bookkeeping (`horizon-ctl memory`):
/// resident sections, far tiles, block entities and light sources by section.
pub fn cpu_census(&self) -> [(&'static str, usize); 4] {
use std::mem::size_of;
let per_section = |map_len: usize, lists: usize| {
map_len * (size_of::<SectionKey>() + size_of::<Vec<([i32; 3], u32)>>() + 1)
+ lists * size_of::<([i32; 3], u32)>()
};
let lists = |map: &crate::fast_hash::FxHashMap<SectionKey, Vec<([i32; 3], u32)>>| {
per_section(
map.capacity(),
map.values().map(Vec::capacity).sum::<usize>(),
)
};
let animated: usize = self
.sections
.values()
.map(|s| s.animated_layers.len() * size_of::<u16>())
.sum();
[
("resident_sections", self.sections.heap_bytes() + animated),
(
"far_tiles",
self.lods.capacity()
* (size_of::<crate::lod::TileKey>() + size_of::<lod::Tile>() + 1),
),
("block_entities", lists(&self.block_entities)),
("light_sources", lists(&self.light_blocks)),
]
}
}
impl Renderer {
pub async fn new(
window: Arc<Window>,
@@ -5239,8 +5057,10 @@ impl Renderer {
pack_post: None,
pack_loading: None,
native: None,
pass_timing: pack_timing::PassTiming::logging(),
pass_timing: false,
pass_detail: false,
pass_timing_gap: std::time::Duration::ZERO,
keep_timed_frames: false,
own_timing: None,
pack_entity_rest: Vec::new(),
cloud_bindings,
@@ -7602,51 +7422,6 @@ impl Renderer {
.terrain_inputs(self.pack_terrain_flat),
)
}
/// Times the shader pack's passes on the GPU while `on` (the F3 overlay is open), or always
/// with `HORIZON_SHADER_PACK_TIMING`.
pub fn set_pass_timing(&mut self, on: bool) {
self.pass_timing = on || pack_timing::PassTiming::logging();
}
/// Times a frame at most once per `gap` while passes are timed (the F3 overlay needs far fewer
/// samples than a measurement). `HORIZON_SHADER_PACK_TIMING` keeps every sample.
pub fn set_pass_timing_gap(&mut self, gap: std::time::Duration) {
self.pass_timing_gap = if pack_timing::PassTiming::logging() {
std::time::Duration::ZERO
} else {
gap
};
}
/// The running shader pack's timer, of either kind.
fn pass_timer<'a>(
pack: &'a mut Option<(i32, Option<pack_post::PackPost>)>,
native: &'a mut Option<native_pack::NativePack>,
) -> Option<&'a mut Option<pack_timing::PassTiming>> {
match (pack, native) {
(Some((_, Some(post))), _) => Some(&mut post.timing),
(_, Some(native)) => Some(&mut native.timing),
_ => None,
}
}
/// Each pass of the running shader pack with its median GPU time in milliseconds, while
/// they are timed (`set_pass_timing`).
pub fn shader_pass_times(&self) -> Vec<(String, f32)> {
let timer = match (&self.pack_post, &self.native) {
(Some((_, Some(post))), _) => post.timing.as_ref(),
(_, Some(native)) => native.timing.as_ref(),
_ => None,
};
timer
.map(pack_timing::PassTiming::medians)
.unwrap_or_default()
}
/// Each of Horizon's own passes with its median GPU time in milliseconds, while they are
/// timed (`set_pass_timing`).
pub fn own_pass_times(&self) -> Vec<(String, f32)> {
self.own_timing
.as_ref()
.map(pack_timing::PassTiming::medians)
.unwrap_or_default()
}
/// The macros this renderer gives shader packs: the GL extensions this device has
/// (subgroups, when it has them), and the vendor, renderer and mipmap levels
/// (`Macros::define_renderer`).
@@ -8255,6 +8030,8 @@ impl Renderer {
}
if let Some(t) = &mut self.own_timing {
t.gap = self.pass_timing_gap;
t.keep_frames(self.keep_timed_frames);
t.set_detail(self.pass_detail);
t.begin(&self.device, &self.queue);
}
if self.animated_textures {
@@ -8291,14 +8068,14 @@ impl Renderer {
self.shader_pack_kind().is_some(),
!frame.title,
);
let (hdr_settings, hdr_shares) = self
let (hdr_settings, hdr_gains) = self
.hdr
.as_ref()
.map_or(([0.0; 4], [0.0; 4]), |h| h.draw_params(!frame.title));
self.world_post.baked_light(
hdr_gain,
hdr_settings,
hdr_shares,
hdr_gains,
self.hdr.as_ref().map_or([[0.0; 4]; 2], hdr::Hdr::windows),
);
let jitter = self.world_post.jitter(
@@ -8458,7 +8235,7 @@ impl Renderer {
f32::from(u8::from(hdr_gain)),
],
hdr_settings,
hdr_shares,
hdr_gains,
};
self.uploads
.buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals));
@@ -8674,6 +8451,7 @@ impl Renderer {
&mut self.uploads,
&mut encoder,
&input,
self.own_timing.as_mut(),
)
});
// A frame whose planes leave the test's integers (the camera millions of blocks
@@ -10022,6 +9800,7 @@ impl Renderer {
}
if let Some(Some(t)) = Self::pass_timer(&mut self.pack_post, &mut self.native) {
t.gap = self.pass_timing_gap;
t.keep_frames(self.keep_timed_frames);
}
let pack_reads_world = pack_post || native_post;
laps.lap("r_uploads");
@@ -10546,7 +10325,8 @@ impl Renderer {
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
let world_pixels = pixel_count(world_depth);
let first_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon world"),
timestamp_writes: self.own_timing.as_mut().and_then(|t| t.writes("World")),
color_attachments: &attachments,
@@ -10566,9 +10346,16 @@ impl Renderer {
}),
..Default::default()
});
let mut pass = pack_timing::counted(
self.own_timing.as_mut(),
first_pass,
world_pixels,
"before translucent",
);
pass.set_bind_group(0, &self.group, &[]);
pack_frame(&mut pass);
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
pass.stage(self.own_timing.as_mut(), "sky");
if !frame.title && frame.skybox && !pack_draws_sky && !native_sky_pass {
match self
.native
@@ -10655,16 +10442,15 @@ impl Renderer {
.forget_lifetime();
pass.set_bind_group(0, &self.group, &[]);
pack_frame(&mut pass);
pass
pack_timing::CountedPass::plain(pass)
};
// The occlusion test's pipeline draws into the world's colour alone.
let plain_pass = |encoder: &mut wgpu::CommandEncoder| {
let mut pass =
world_pass_after_culling(encoder, world_view, world_depth, true, None, "")
.forget_lifetime();
let mut pass = after_culling_pass(encoder, world_view, world_depth, true, None)
.forget_lifetime();
pass.set_bind_group(0, &self.group, &[]);
pack_frame(&mut pass);
pass
pack_timing::CountedPass::plain(pass)
};
if let Some(surface) = &surface {
drop(pass);
@@ -10718,6 +10504,7 @@ impl Renderer {
keep_depth,
self.own_timing.as_mut(),
"World after visibility buffer",
world_pixels,
);
pass.set_bind_group(0, &self.group, &[]);
pack_frame(&mut pass);
@@ -10750,6 +10537,7 @@ impl Renderer {
flat.draw(pass, &flat.calls[calls.clone()], vertices);
}
};
pass.stage(self.own_timing.as_mut(), "solid terrain");
match cull {
// As below: phase 1, the test, then phase 2's draws
// that the test saw, copied after it.
@@ -10759,6 +10547,8 @@ impl Renderer {
drop(pass);
pass = plain_pass(&mut encoder);
}
pass.split(self.own_timing.as_mut(), "occlusion boxes");
pass.stage(self.own_timing.as_mut(), "occlusion boxes");
cull.test(&mut pass);
drop(pass);
cull.test_pass(&mut encoder, self.own_timing.as_mut());
@@ -10772,10 +10562,12 @@ impl Renderer {
keep_depth,
self.own_timing.as_mut(),
"World after culling",
world_pixels,
),
};
pass.set_bind_group(0, &self.group, &[]);
pack_frame(&mut pass);
pass.stage(self.own_timing.as_mut(), "solid terrain phase 2");
for (pipeline, _, calls) in passes {
pass.set_pipeline(pipeline);
flat.draw_phase2(&mut pass, calls.clone(), vertices);
@@ -10813,6 +10605,7 @@ impl Renderer {
let pulled = material.is_none() && self.flat.is_some();
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(1, self.instances.slice(..));
pass.stage(self.own_timing.as_mut(), "solid terrain");
if let Some(group) = warp_group {
pass.set_bind_group(2, group, &[]);
}
@@ -10837,6 +10630,8 @@ impl Renderer {
drop(pass);
pass = plain_pass(&mut encoder);
}
pass.split(self.own_timing.as_mut(), "occlusion boxes");
pass.stage(self.own_timing.as_mut(), "occlusion boxes");
cull.test(&mut pass);
drop(pass);
cull.test_pass(&mut encoder, self.own_timing.as_mut());
@@ -10849,6 +10644,7 @@ impl Renderer {
keep_depth,
self.own_timing.as_mut(),
"World after culling",
world_pixels,
),
};
pass.set_bind_group(0, &self.group, &[]);
@@ -10858,6 +10654,7 @@ impl Renderer {
wgpu::IndexFormat::Uint32,
);
pass.set_vertex_buffer(1, self.instances.slice(..));
pass.stage(self.own_timing.as_mut(), "solid terrain phase 2");
for (pipeline, _, draws) in passes {
pass.set_pipeline(pipeline);
self.draw_sections_from(
@@ -10905,6 +10702,8 @@ impl Renderer {
drop(pass);
pass = plain_pass(&mut encoder);
}
pass.split(self.own_timing.as_mut(), "occlusion boxes");
pass.stage(self.own_timing.as_mut(), "occlusion boxes");
gpu.test(&mut pass);
drop(pass);
gpu.compact(&mut encoder, self.own_timing.as_mut());
@@ -10917,6 +10716,7 @@ impl Renderer {
keep_depth,
self.own_timing.as_mut(),
"World after culling",
world_pixels,
),
};
pass.set_bind_group(0, &self.group, &[]);
@@ -10925,6 +10725,7 @@ impl Renderer {
self.indices.slice(..),
wgpu::IndexFormat::Uint32,
);
pass.stage(self.own_timing.as_mut(), "solid terrain phase 2");
for (pipeline, draws, _) in passes {
pass.set_pipeline(pipeline);
gpu.draw(&mut pass, &self.arena, page_group, 1);
@@ -10951,6 +10752,7 @@ impl Renderer {
&& let Some(d) = &n.displacement
&& let Some(pipeline) = n.material.as_ref().and_then(|m| m.displaced.as_ref())
{
pass.stage(self.own_timing.as_mut(), "displacement");
pass.set_bind_group(0, &self.group, &[]);
pack_frame(&mut pass);
d.draw(&mut pass, &d.view, pipeline);
@@ -10967,6 +10769,7 @@ impl Renderer {
let hdr_entity_mark =
warped.map_or(&self.hdr_entity_mark_pipeline, |w| &w.hdr_entity_mark);
if static_entity_quads > 0 {
pass.stage(self.own_timing.as_mut(), "static block entities");
pass.set_pipeline(
warped.map_or(&self.static_entity_pipeline, |w| &w.static_entities),
);
@@ -10992,6 +10795,7 @@ impl Renderer {
}
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
if entity_quads > 0 {
pass.stage(self.own_timing.as_mut(), "entities");
pass.set_pipeline(warped.map_or(&self.entity_pipeline, |w| &w.entities));
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11003,6 +10807,7 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
}
if text_quads > 0 && !oit_on {
pass.stage(self.own_timing.as_mut(), "entity text");
pass.set_pipeline(warped.map_or(&self.text_polygon_offset_pipeline, |w| &w.text));
self.bind_world_text(&mut pass, warped.is_none(), false);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11012,6 +10817,7 @@ impl Renderer {
// FeatureRenderDispatcher.PreparedFrame.executeTranslucent: the shadows
// come before the translucent items, which then cover them (#7026).
if shadow_quads > 0 && !oit_on {
pass.stage(self.own_timing.as_mut(), "shadows");
pass.set_pipeline(warped.map_or(&self.shadow_blob_pipeline, |w| &w.entity_shadows));
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11027,6 +10833,7 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
}
if translucent_item_quads > 0 && !oit_on {
pass.stage(self.own_timing.as_mut(), "translucent items");
pass.set_pipeline(
warped.map_or(&self.translucent_item_pipeline, |w| &w.translucent_items),
);
@@ -11062,6 +10869,7 @@ impl Renderer {
.enumerate()
{
if count > 0 {
pass.stage(self.own_timing.as_mut(), "terrain models");
pass.set_pipeline(&self.terrain_model_pipelines[i]);
pass.set_bind_group(
0,
@@ -11082,6 +10890,7 @@ impl Renderer {
// translucent material, before terrain transparency. This material
// always writes depth and never joins the improved-transparency queues.
if fluid_quads > 0 {
pass.stage(self.own_timing.as_mut(), "fluid block entities");
pass.set_pipeline(&self.fluid_pipeline);
pass.set_bind_group(0, &self.fluid_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11094,6 +10903,7 @@ impl Renderer {
}
// Cracks multiply the existing light; scalar OIT coverage cannot carry that factor.
if crumbling_quads > 0 && (!oit_on || hdr_gain) {
pass.stage(self.own_timing.as_mut(), "block breaking");
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11107,6 +10917,7 @@ impl Renderer {
// BoatRenderer's water patch (RenderTypes.waterMask): depth only,
// before translucent terrain, so no water shows inside the boat.
if water_mask_quads > 0 && !oit_on {
pass.stage(self.own_timing.as_mut(), "boat water mask");
pass.set_pipeline(&self.water_mask_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11119,6 +10930,7 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
}
if !frame.lightning.bolts.is_empty() && !oit_on {
pass.stage(self.own_timing.as_mut(), "lightning");
pass.set_pipeline(&self.lightning_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
self.lightning.draw(&mut pass, &frame.lightning);
@@ -11129,6 +10941,7 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
}
if swirl_quads > 0 && !oit_on {
pass.stage(self.own_timing.as_mut(), "energy swirl");
pass.set_pipeline(&self.energy_swirl_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11145,6 +10958,7 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
}
if additive_quads > 0 && !oit_on {
pass.stage(self.own_timing.as_mut(), "additive entities");
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
let mut first = 0;
@@ -11170,20 +10984,24 @@ impl Renderer {
pass.set_bind_group(0, &self.group, &[]);
}
if outline_edges > 0 && !frame.outline_after_terrain && !pack_draws_outline {
pass.stage(self.own_timing.as_mut(), "block outline");
self.draw_outline(&mut pass, outline_edges as u32, frame.outline_high_contrast);
}
// DrawableGizmoPrimitives' opaque group writes depth, the translucent one does not.
if debug_opaque > 0 {
pass.stage(self.own_timing.as_mut(), "debug lines");
pass.set_pipeline(&self.debug_lines_opaque);
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
pass.draw(0..4, 0..debug_opaque);
}
if debug_depth > debug_opaque {
pass.stage(self.own_timing.as_mut(), "debug lines");
pass.set_pipeline(&self.debug_lines);
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
pass.draw(0..4, debug_opaque..debug_depth);
}
if debug_top > 0 {
pass.stage(self.own_timing.as_mut(), "debug lines");
pass.set_pipeline(&self.debug_lines_on_top);
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
pass.draw(0..4, debug_depth..debug_depth + debug_top);
@@ -11211,6 +11029,7 @@ impl Renderer {
keep_depth,
self.own_timing.as_mut(),
"World after copy",
world_pixels,
);
pass.set_bind_group(0, &self.group, &[]);
pack_frame(&mut pass);
@@ -11384,9 +11203,11 @@ impl Renderer {
true,
self.own_timing.as_mut(),
"World after OIT",
world_pixels,
);
pass.set_bind_group(0, &self.group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.stage(self.own_timing.as_mut(), "OIT marks");
if cloud_quads > 0 && !pack_draws_clouds {
self.mark_clouds(&mut pass, cloud_quads);
}
@@ -11419,6 +11240,8 @@ impl Renderer {
self.mark_translucent_terrain(&mut pass, flat, solid_draws, translucent_draws);
}
Some(flat) => {
pass.split(self.own_timing.as_mut(), "translucent terrain");
pass.stage(self.own_timing.as_mut(), "translucent terrain");
pass.set_pipeline(pack_flat.map_or(&flat.translucent, |p| &p.1));
flat.draw(
&mut pass,
@@ -11433,8 +11256,11 @@ impl Renderer {
solid_draws,
translucent_draws,
);
pass.split(self.own_timing.as_mut(), "after translucent");
}
None => {
pass.split(self.own_timing.as_mut(), "translucent terrain");
pass.stage(self.own_timing.as_mut(), "translucent terrain");
pass.set_pipeline(translucent_pipeline);
if let Some(group) = warp_group {
pass.set_bind_group(2, group, &[]);
@@ -11457,6 +11283,7 @@ impl Renderer {
translucent_draws,
);
}
pass.split(self.own_timing.as_mut(), "after translucent");
}
}
// LevelRenderer.executeTranslucentAfterTerrain: vanilla's
@@ -11464,6 +11291,7 @@ impl Renderer {
// the quads write depth, so before it they would hide the glass
// or water behind them.
if translucent_particle_quads > 0 && !oit_on {
pass.stage(self.own_timing.as_mut(), "translucent particles");
pass.set_pipeline(warped.map_or(&self.entity_pipeline, |w| &w.entities));
if let Some(group) = warp_group {
pass.set_bind_group(2, group, &[]);
@@ -11492,6 +11320,7 @@ impl Renderer {
// particles (also after the OIT composite) and before the hand.
// Its own geometry is independent of block-entity lifetime.
if world_text_quads + world_text_offset_quads > 0 {
pass.stage(self.own_timing.as_mut(), "world text");
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11514,9 +11343,11 @@ impl Renderer {
// LevelRenderer.executeClassicTransparency: translucent targets'
// outlines follow terrain, so its blending cannot wash them out.
if outline_edges > 0 && frame.outline_after_terrain && !pack_draws_outline {
pass.stage(self.own_timing.as_mut(), "block outline");
self.draw_outline(&mut pass, outline_edges as u32, frame.outline_high_contrast);
}
if translucent_crumbling_quads > 0 && (!oit_on || hdr_gain) {
pass.stage(self.own_timing.as_mut(), "block breaking");
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11527,6 +11358,7 @@ impl Renderer {
);
}
if cloud_quads > 0 && !pack_draws_clouds && !oit_on {
pass.stage(self.own_timing.as_mut(), "clouds");
pass.set_pipeline(&self.cloud_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_bind_group(1, &self.cloud_group, &[]);
@@ -11538,6 +11370,7 @@ impl Renderer {
// terrain and clouds, so the water behind the rain is drawn first.
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
if !pack_draws_weather && !oit_on {
pass.stage(self.own_timing.as_mut(), "weather");
let native_weather = self
.native
.as_ref()
@@ -11549,6 +11382,7 @@ impl Renderer {
}
// LevelRenderer: the world border after translucent terrain and weather.
if let Some(b) = frame.border.as_ref().filter(|_| !frame.title && !oit_on) {
pass.stage(self.own_timing.as_mut(), "world border");
pass.set_pipeline(&self.border_pipeline);
pass.set_bind_group(0, &self.border_group, &[]);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
@@ -11561,6 +11395,7 @@ impl Renderer {
}
// LevelRenderer.executeSeeThrough, after the rest of the world.
if see_through_quads > 0 {
pass.stage(self.own_timing.as_mut(), "see-through");
pass.set_pipeline(&self.see_through_pipeline);
self.bind_world_text(&mut pass, true, true);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
@@ -11573,9 +11408,11 @@ impl Renderer {
// Native mods' primitives: after the entities and the rest of the world, into its
// targets (its resolution, reversed depth and TAA), before the hand.
if world_primitives {
pass.stage(self.own_timing.as_mut(), "mod primitives");
self.world_primitives.draw(&mut pass);
}
if hand_in_world {
pass.stage(self.own_timing.as_mut(), "hand");
pass.set_pipeline(&self.depth_reset);
pass.set_bind_group(0, &self.group, &[]);
pass.draw(0..3, 0..1);
@@ -12515,130 +12352,6 @@ pub(crate) fn copy_frame(
);
buffer
}
impl Renderer {
/// The frame's readbacks to start right after its submission (on the submit thread when
/// the frame goes there): occlusion culling's results (`cull`) and GPU culling's
/// statistics. GPU frames leave occlusion culling off, so a frame has one at most.
fn after_submit(&mut self) -> Option<submit::AfterSubmit> {
let cull = self.cull.as_mut().and_then(|c| c.submitted());
let gpu = self.gpu_culling.as_mut().and_then(|g| g.submitted());
match (cull, gpu) {
(Some(c), Some(g)) => Some(Box::new(move || {
c();
g();
})),
(Some(c), None) => Some(Box::new(c)),
(None, Some(g)) => Some(Box::new(g)),
(None, None) => None,
}
}
/// Frame `frame`'s statistics shown, unless a newer frame's are: a CPU frame's as it is
/// drawn, a GPU frame's when its counts come back (`GpuCulling::collect`).
fn show_stats(&mut self, frame: u64, [sections, draws, calls]: [usize; 3]) {
if frame > self.stats_frame {
self.stats_frame = frame;
(
self.drawn_sections,
self.section_draws,
self.section_draw_calls,
) = (sections, draws, calls);
}
}
/// Frames between the last one drawn and the one whose statistics are shown: 0 after a
/// CPU frame, one to three in GPU frames, while their counts are on their way back.
pub fn stats_lag(&self) -> u64 {
self.frame_serial - self.stats_frame
}
/// Take in the frame the submit thread submitted: start its readbacks and, offscreen,
/// keep at most two frames ahead of the GPU, as a frame submitted in place does.
fn land_frame(&mut self) {
let Some(offscreen) = self.deferred.take() else {
return;
};
let submission = self.queue.landed();
if let Some(timer) = &mut self.gpu_timer {
timer.submitted(&self.queue);
timer.collect(&self.device, &mut self.gpu_times);
}
if let Some(Some(timer)) = Self::pass_timer(&mut self.pack_post, &mut self.native) {
timer.submitted(&self.queue);
}
if offscreen && let Some(submission) = submission {
self.in_flight.push_back(submission);
if !self.paced_elsewhere {
self.wait_frames();
}
}
}
/// No swapchain paces offscreen frames: keep two on the GPU at most.
pub fn wait_in_flight(&mut self) {
self.land_frame();
self.wait_frames();
}
/// The frame on the submit thread submitted: a surface reconfigure waits for the
/// device and breaks if a frame is submitted while it waits, and the compositor
/// copies views after them. (The end of a frame already lands the frames of the
/// turn before; this is the turn's own.)
pub fn wait_submissions(&mut self) {
self.queue.wait();
}
fn wait_frames(&mut self) {
while self.in_flight.len() > 2 {
let index = self.in_flight.pop_front();
let _ = self.device.poll(wgpu::PollType::Wait {
submission_index: index,
timeout: Some(std::time::Duration::from_secs(5)),
});
}
}
/// Take a screenshot request: queue the frame's copy, or report why the
/// frame cannot be read back.
fn take_readback(
&mut self,
request: ScreenshotRequest,
encoder: &mut wgpu::CommandEncoder,
texture: &wgpu::Texture,
) -> Option<(ScreenshotRequest, wgpu::Buffer)> {
// The copy and PNG writer both assume 8-bit pixels; a float surface would make
// the row stride too small for the copy and abort in validation.
if self.config.format.block_copy_size(None) == Some(4) {
let size = [self.config.width, self.config.height];
let format = self.config.format.remove_srgb_suffix();
// The layered float frame maps the world to SDR, then adds the HUD as drawn.
// Other 16-bit frames keep their clipped 8-bit copy.
let copy = self
.hdr
.as_mut()
.and_then(|hdr| {
hdr.sdr_screenshot(&self.device, encoder, format, request.size.is_some())
})
.or_else(|| {
(texture.format() != format && texture.format() == self.output.frame.format)
.then(|| {
self.readback
.unorm_copy(&self.device, encoder, texture, format)
})
});
let texture = copy.as_ref().unwrap_or(texture);
Some((request, copy_frame(&self.device, encoder, texture, size)))
} else {
let error = format!(
"screenshots need a 32-bit surface format, not {:?}",
self.config.format
);
if request.background {
self.saved_screenshots.push(screenshot_save::Saved {
path: request.path,
result: Err(error),
hdr: None,
});
} else {
self.screenshot_result = Some(Err(error));
}
None
}
}
}
/// `screenshots/2026-10-28_12.00.00.png` -> `screenshots/2026-10-28_12.00.00-hdr.png`.
fn hdr_screenshot_path(path: &std::path::Path) -> PathBuf {
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
@@ -12744,56 +12457,8 @@ fn block_entities_within_reach<'a>(
})
.flatten()
}
/// Camera-relative clip planes (`Frustum`).
#[derive(Clone, Copy, Debug)]
pub struct Frustum {
planes: [Vec4; 6],
}
impl Frustum {
/// Whether the camera-relative box `min..max` is at least partly inside.
pub fn intersects(&self, min: Vec3, max: Vec3) -> bool {
!self.planes.iter().any(|p| {
let sign = p.truncate().cmpge(Vec3::ZERO);
let v = Vec3::select(sign, max, min);
p.truncate().dot(v) + p.w < 0.0
})
}
/// Whether a camera-relative sphere is at least partly inside. Frustum
/// planes are normalized, so each test needs only one dot product and a
/// radius comparison.
pub fn intersects_sphere(&self, center: Vec3, radius: f32) -> bool {
if !center.is_finite() || !radius.is_finite() || radius < 0.0 {
return true;
}
!self
.planes
.iter()
.any(|plane| plane.truncate().dot(center) + plane.w < -radius)
}
/// Depth clip planes alone: X/Y projection jitter cannot change this test.
/// Retaining side-of-screen geometry makes this safe before TAA selects a phase.
pub fn intersects_depth(&self, min: Vec3, max: Vec3) -> bool {
if !min.is_finite() || !max.is_finite() || !min.cmple(max).all() {
return true;
}
!self.planes[4..].iter().any(|p| {
let sign = p.truncate().cmpge(Vec3::ZERO);
let v = Vec3::select(sign, max, min);
p.truncate().dot(v) + p.w < 0.0
})
}
/// Whether the camera-relative box `min..max` is entirely inside. Then
/// `intersects` accepts every box within it: each plane's distance only
/// grows from this box's nearest corner to the inner box's farthest, and
/// rounding keeps that order.
pub fn contains(&self, min: Vec3, max: Vec3) -> bool {
self.planes.iter().all(|p| {
let sign = p.truncate().cmpge(Vec3::ZERO);
let v = Vec3::select(sign, min, max);
p.truncate().dot(v) + p.w >= 0.0
})
}
}
mod view_frustum;
pub use view_frustum::Frustum;
/// Vanilla's `Projection`: reversed depth (near maps to 1, far to 0, tests
/// are GREATER_THAN_OR_EQUAL), which keeps far faces a hair apart, like
/// fire_side's 0.01 pixel in front of its block, from z-fighting.
@@ -0,0 +1,164 @@
//! What the renderer holds, for status, soak tests and memory reports (`horizon-ctl memory`,
//! `scene_replay --memory`): resident sections and far tiles, and the bytes of its largest
//! GPU resources and of its per-section bookkeeping.
use std::collections::HashMap;
use super::{
Renderer, SectionGpu, SectionKey, TerrainVertex, arena, flat, lod, texture_bytes, visbuffer,
};
impl Renderer {
/// Sections with GPU buffers, for soak tests watching residency.
pub fn resident_sections(&self) -> usize {
self.sections.len()
}
/// Quads of the far terrain tiles with GPU buffers.
pub fn lod_quads(&self) -> u64 {
self.lods
.values()
.map(|tile| u64::from(tile.mesh.solid + tile.mesh.translucent))
.sum()
}
/// Tiles and quads of the far terrain tiles with GPU buffers, by level.
pub fn lod_levels(&self) -> Vec<[u64; 2]> {
let mut levels = Vec::new();
for (key, tile) in &self.lods {
let level = usize::from(key.level);
if levels.len() <= level {
levels.resize(level + 1, [0, 0]);
}
levels[level][0] += 1;
levels[level][1] += u64::from(tile.mesh.solid + tile.mesh.translucent);
}
levels
}
/// Whether solid quads go to the arena in the compact layout
/// (`packed_quads`), and whether far tiles' own records are on
/// (`lod::packed::far_packing`).
pub fn packed_layout(&self) -> [bool; 2] {
[self.packed_quads, crate::lod::packed::far_packing()]
}
/// Bytes of the arena the resident chunk sections hold, and of the one far
/// tiles hold: the same split `gpu_census` reports, for `status`, so the
/// compact layouts can be seen working.
pub fn vertex_bytes_split(&self) -> [u64; 2] {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let used = |s: &SectionGpu| (s.solid_slots + u64::from(s.translucent) * 4) * stride;
[
self.sections.values().map(used).sum(),
self.lods.values().map(|tile| used(&tile.mesh)).sum(),
]
}
/// Bytes of the section vertex arenas' buffers, and of the vertices
/// resident sections hold in them.
pub fn section_vertex_bytes(&self) -> [u64; 2] {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let vertices: u64 = self
.sections
.values()
.chain(self.lods.values().map(|tile| &*tile.mesh))
.map(|s| s.solid_slots + u64::from(s.translucent) * 4)
.sum();
let translucent = self.translucent_arena.as_ref();
let arenas = self.arena.bytes() + translucent.map_or(0, arena::Arena::bytes);
[arenas, vertices * stride]
}
/// Bytes of the renderer's largest GPU resources, by name (`scene_replay --memory`):
/// the terrain arenas (their pages, and what resident sections and far tiles use of
/// them), the quad indices, the block sprites with their mips, the LabPBR maps, flat
/// draws' buffers and the visibility buffer's.
pub fn gpu_census(&self) -> Vec<(&'static str, u64)> {
let stride = std::mem::size_of::<TerrainVertex>() as u64;
let used = |s: &SectionGpu| (s.solid_slots + u64::from(s.translucent) * 4) * stride;
let textures = |t: &[wgpu::Texture]| t.iter().map(texture_bytes).sum::<u64>();
let translucent = self.translucent_arena.as_ref();
vec![
("section_arena_pages", self.arena.bytes()),
(
"translucent_arena_pages",
translucent.map_or(0, arena::Arena::bytes),
),
("sorted_index_pages", self.sorted_indices.bytes()),
(
"near_section_vertices",
self.sections.values().map(used).sum(),
),
(
"held_section_vertices",
self.hold
.sections()
.filter_map(|held| held.gpu.as_ref())
.map(used)
.sum(),
),
(
"far_tile_vertices",
self.lods.values().map(|tile| used(&tile.mesh)).sum(),
),
("quad_indices", self.indices.size()),
("block_sprites", textures(&self.sprite_textures)),
(
"pbr_maps",
self.pbr_maps
.as_ref()
.map_or(0, |maps| maps.iter().flatten().map(texture_bytes).sum()),
),
(
"flat_draws",
self.flat.as_ref().map_or(0, flat::Flat::bytes),
),
(
"visibility_buffer",
self.visbuf.as_ref().map_or(0, visbuffer::Visbuffer::bytes),
),
]
}
/// Device memory the backend's allocator holds, by the label of what holds
/// it, largest first, with its allocated and reserved totals (Vulkan and
/// DirectX 12; none on Metal and OpenGL) (`horizon-ctl memory`).
pub fn gpu_memory_by_label(&self) -> Option<(u64, u64, Vec<(String, u64)>)> {
let report = self.device.generate_allocator_report()?;
let mut by_label: HashMap<String, u64> = HashMap::new();
for a in report.allocations {
*by_label.entry(a.name).or_default() += a.size;
}
let mut labels: Vec<_> = by_label.into_iter().collect();
labels.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
Some((
report.total_allocated_bytes,
report.total_reserved_bytes,
labels,
))
}
/// Heap bytes of the renderer's per-section bookkeeping (`horizon-ctl memory`):
/// resident sections, far tiles, block entities and light sources by section.
pub fn cpu_census(&self) -> [(&'static str, usize); 4] {
use std::mem::size_of;
let per_section = |map_len: usize, lists: usize| {
map_len * (size_of::<SectionKey>() + size_of::<Vec<([i32; 3], u32)>>() + 1)
+ lists * size_of::<([i32; 3], u32)>()
};
let lists = |map: &crate::fast_hash::FxHashMap<SectionKey, Vec<([i32; 3], u32)>>| {
per_section(
map.capacity(),
map.values().map(Vec::capacity).sum::<usize>(),
)
};
let animated: usize = self
.sections
.values()
.map(|s| s.animated_layers.len() * size_of::<u16>())
.sum();
[
("resident_sections", self.sections.heap_bytes() + animated),
(
"far_tiles",
self.lods.capacity()
* (size_of::<crate::lod::TileKey>() + size_of::<lod::Tile>() + 1),
),
("block_entities", lists(&self.block_entities)),
("light_sources", lists(&self.light_blocks)),
]
}
}
@@ -33,7 +33,7 @@ struct Uniform {
mode: u32,
pad: [u32; 2],
hdr_settings: [f32; 4],
hdr_shares: [f32; 4],
hdr_gains: [f32; 4],
hdr_light: [f32; 4],
}
@@ -407,7 +407,7 @@ impl CustomSky {
self.written_gain = (globals.hdr_light[3] != 0.0).then(|| {
let mark =
((1.0 - 0.24 * globals.hdr_light[1]).clamp(0.0, 1.0) * 255.0).round() / 255.0;
if globals.hdr_settings[2] > 0.5 && globals.hdr_settings[0] > 1.0 {
if globals.hdr_settings[2] > 0.5 {
(1.0 + (globals.hdr_settings[1] - 1.0) * (1.0 - mark) / 0.24).powf(1.0 / 2.2)
} else {
1.0
@@ -428,7 +428,7 @@ impl CustomSky {
mode: mode as u32,
pad: [0; 2],
hdr_settings: globals.hdr_settings,
hdr_shares: globals.hdr_shares,
hdr_gains: globals.hdr_gains,
hdr_light: globals.hdr_light,
};
let offset = STRIDE * self.frame.len() as u64;
@@ -702,7 +702,7 @@ mod tests {
mode: mode_index as u32,
pad: [0; 2],
hdr_settings: [5.0, 4.0, 1.0, f32::from(u8::from(debug))],
hdr_shares: [0.2, 0.5, 0.6, 1.0],
hdr_gains: [1.6, 2.4, 2.8, 4.0],
hdr_light: [0.8, 0.8, 1.0, f32::from(u8::from(written))],
};
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
@@ -10,7 +10,7 @@ struct Layer {
mode: u32,
pad: vec2<u32>,
hdr_settings: vec4<f32>,
hdr_shares: vec4<f32>,
hdr_gains: vec4<f32>,
hdr_light: vec4<f32>,
}
@group(0) @binding(0) var<uniform> layer: Layer;
@@ -54,7 +54,7 @@ fn custom_sky_color(in: Out) -> vec4<f32> {
var color = t.rgb;
if HDR_WRITE_LIGHT && layer.hdr_light.w != 0.0 &&
(layer.mode == ADD || layer.mode == SUBTRACT || layer.mode == REPLACE || layer.mode == ALPHA) {
color = hdr_written(color, 1.0 - 0.24 * layer.hdr_light.y, layer.hdr_settings, layer.hdr_shares);
color = hdr_written(color, 1.0 - 0.24 * layer.hdr_light.y, layer.hdr_settings, layer.hdr_gains);
}
// On a frame of linear light (`FRAME_LINEAR`) the layer's colour is decoded as it is stored.
switch layer.mode {
@@ -84,5 +84,5 @@ fn custom_sky_color(in: Out) -> vec4<f32> {
@fragment fn fs_custom_sky_screen_light(in: Out) -> @location(0) vec4<f32> {
let color = custom_sky_color(in);
return vec4(hdr_written(color.rgb, 1.0 - 0.24 * layer.hdr_light.y, layer.hdr_settings, layer.hdr_shares), color.a);
return vec4(hdr_written(color.rgb, 1.0 - 0.24 * layer.hdr_light.y, layer.hdr_settings, layer.hdr_gains), color.a);
}
@@ -71,7 +71,7 @@ use super::{
Frustum, SectionKey,
arena::{Arena, try_create},
occlusion::Reach,
pack_timing::PassTiming,
pack_timing::{PassTiming, compute_parts},
resident,
submit::Queue,
upload::Uploads,
@@ -374,6 +374,21 @@ pub(super) enum Prepared {
OutOfMemory,
}
/// A part of a compute pass: `pipeline` over `[x, y]` workgroups, nothing when `x` is 0.
fn step<'a>(
group: &'a wgpu::BindGroup,
pipeline: &'a wgpu::ComputePipeline,
[x, y]: [u32; 2],
) -> impl FnMut(&mut wgpu::ComputePass<'_>) + 'a {
move |pass| {
if x > 0 {
pass.set_bind_group(0, group, &[]);
pass.set_pipeline(pipeline);
pass.dispatch_workgroups(x, y, 1);
}
}
}
/// The frame's `tables` before the regions, into `words`, and the parameters
/// the frustum test and facing read with them; `None` when the CPU draws the
/// frame (`Prepared::Cpu`): a sum of a plane's terms could leave i32
@@ -1190,12 +1205,13 @@ impl GpuCulling {
uploads: &mut Uploads,
encoder: &mut wgpu::CommandEncoder,
input: &FrameInputs<'_>,
timing: Option<&mut PassTiming>,
) -> Prepared {
self.pages.clear();
self.ids = 0;
self.n_updates = 0;
self.occluding = false;
self.prepare_buffers(device, queue, uploads, encoder, input)
self.prepare_buffers(device, queue, uploads, encoder, input, timing)
.unwrap_or(Prepared::OutOfMemory)
}
@@ -1206,6 +1222,7 @@ impl GpuCulling {
uploads: &mut Uploads,
encoder: &mut wgpu::CommandEncoder,
input: &FrameInputs<'_>,
mut timing: Option<&mut PassTiming>,
) -> Option<Prepared> {
// Every buffer grows before anything is written. One made anew drops
// the bind group at once, and a new section table needs every record:
@@ -1287,6 +1304,9 @@ impl GpuCulling {
occl = OCCLUDE | if probe { PROBE } else { 0 };
}
}
let uploading = timing
.as_mut()
.and_then(|t| t.encoder_begin(encoder, "GPU culling uploads"));
if self.records.all_dirty {
// The whole table, after it grew or more records changed than
// updates take (GPU culling switched on in a loaded world, a
@@ -1352,6 +1372,9 @@ impl GpuCulling {
// are written before they are read.
let cleared = if self.occluding { tests_at } else { phase1_end };
encoder.clear_buffer(&self.counts.buffer, 0, Some(cleared * 4));
if let Some(t) = timing {
t.encoder_end(encoder, uploading);
}
if self.group.is_none() {
self.group = Some(self.bind(device));
if let Some(test) = &mut self.test {
@@ -1403,23 +1426,24 @@ impl GpuCulling {
let Some(group) = self.group.as_ref().filter(|_| self.ids > 0) else {
return;
};
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("GPU culling"),
timestamp_writes: timing.and_then(|t| t.compute_writes("GPU culling")),
});
pass.set_bind_group(0, group, &[]);
let [apply, cull, scan, scatter] = &self.pipelines;
if self.n_updates > 0 {
pass.set_pipeline(apply);
pass.dispatch_workgroups(self.n_updates.div_ceil(WORKGROUP), 1, 1);
}
let blocks = self.ids.div_ceil(WORKGROUP);
pass.set_pipeline(cull);
pass.dispatch_workgroups(blocks.min(ROW), blocks.div_ceil(ROW), 1);
pass.set_pipeline(scan);
pass.dispatch_workgroups(self.pass_pages, 1, 1);
pass.set_pipeline(scatter);
pass.dispatch_workgroups(blocks.min(ROW), blocks.div_ceil(ROW), 1);
let rows = [blocks.min(ROW), blocks.div_ceil(ROW)];
let updates = [self.n_updates.div_ceil(WORKGROUP), 1];
let (mut apply, mut cull) = (step(group, apply, updates), step(group, cull, rows));
let pages = [self.pass_pages, 1];
let (mut scan, mut scatter) = (step(group, scan, pages), step(group, scatter, rows));
compute_parts(
encoder,
timing,
"GPU culling",
&mut [
("apply", &mut apply),
("cull", &mut cull),
("scan", &mut scan),
("scatter", &mut scatter),
],
);
}
/// The kept sections' solid draws, a count draw per page, with the quad
@@ -1494,19 +1518,22 @@ impl GpuCulling {
if !self.occluding {
return;
}
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("GPU culling phase 2"),
timestamp_writes: timing.and_then(|t| t.compute_writes("GPU culling phase 2")),
});
pass.set_bind_group(0, group, &[]);
let [count2, scan2, scatter2] = &test.phase2;
let blocks = self.ids.div_ceil(WORKGROUP);
pass.set_pipeline(count2);
pass.dispatch_workgroups(blocks.min(ROW), blocks.div_ceil(ROW), 1);
pass.set_pipeline(scan2);
pass.dispatch_workgroups(self.pass_pages, 1, 1);
pass.set_pipeline(scatter2);
pass.dispatch_workgroups(blocks.min(ROW), blocks.div_ceil(ROW), 1);
let rows = [blocks.min(ROW), blocks.div_ceil(ROW)];
let pages = [self.pass_pages, 1];
let (mut count, mut scatter) = (step(group, count2, rows), step(group, scatter2, rows));
let mut scan = step(group, scan2, pages);
compute_parts(
encoder,
timing,
"GPU culling phase 2",
&mut [
("count2", &mut count),
("scan2", &mut scan),
("scatter2", &mut scatter),
],
);
}
/// After the frame's world passes (phase 2's counts too), in the same
@@ -2720,6 +2747,11 @@ mod tests {
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
let needed =
wgpu::Features::MULTI_DRAW_INDIRECT_COUNT | wgpu::Features::INDIRECT_FIRST_INSTANCE;
let timing = adapter.features()
& (wgpu::Features::TIMESTAMP_QUERY
| wgpu::Features::TIMESTAMP_QUERY_INSIDE_PASSES
| wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS
| wgpu::Features::SHADER_EARLY_DEPTH_TEST);
if !adapter.features().contains(needed)
|| super::super::flat::is_broken_intel_vulkan(&adapter.get_info())
{
@@ -2727,7 +2759,7 @@ mod tests {
}
eprintln!("GPU culling on {} ({name})", adapter.get_info().name);
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_features: needed,
required_features: needed | timing,
..Default::default()
}))
.ok()
@@ -2834,6 +2866,11 @@ mod tests {
// was drawn.
let (mut eyed, mut hidden, mut several) = (0, 0, 0);
let (mut edge, mut edge_drawn) = (None, false);
// Timed in detail as the renderer does: the commands, and so the draws, stay the same.
let mut timing = PassTiming::new(device, queue);
if let Some(t) = &mut timing {
t.set_detail(true);
}
for case in 0..25 {
let radius = [2, 5, 9][case % 3];
let at_edge = case == 24;
@@ -2981,6 +3018,9 @@ mod tests {
edge = Some(id);
}
let whole = gpu.records.all_dirty;
if let Some(t) = &mut timing {
t.begin(device, queue);
}
let mut encoder = device.create_command_encoder(&Default::default());
let input = FrameInputs {
camera,
@@ -3000,11 +3040,18 @@ mod tests {
camera: camera + DVec3::Y * 2.0e7,
..input
};
let prepared = gpu.prepare(device, queue, &mut uploads, &mut encoder, &up);
let prepared = gpu.prepare(device, queue, &mut uploads, &mut encoder, &up, None);
assert_eq!(prepared, Prepared::Cpu, "case 7");
assert!(gpu.records.all_dirty || !gpu.records.dirty.is_empty());
}
let prepared = gpu.prepare(device, queue, &mut uploads, &mut encoder, &input);
let prepared = gpu.prepare(
device,
queue,
&mut uploads,
&mut encoder,
&input,
timing.as_mut(),
);
assert_eq!(prepared, Prepared::Gpu, "case {case}");
match case {
4 => assert!(
@@ -3060,12 +3107,15 @@ mod tests {
culled += 1;
}
}
gpu.dispatch(&mut encoder, None);
gpu.dispatch(&mut encoder, timing.as_mut());
// Its statistics come back with a CPU part of the case's own.
let cpu = [case * 7, case * 3, case];
gpu.copy_stats(&mut encoder, case as u64, cpu);
uploads.finish(&encoder);
queue.submit([encoder.finish()]);
if let Some(t) = &mut timing {
t.submitted(queue);
}
gpu.submitted().expect("a readback free")();
let pages = u64::from(gpu.pass_pages);
let counts = read(device, queue, &gpu.counts.buffer, (STATS + pages) * 4);
@@ -3124,6 +3174,18 @@ mod tests {
"of {eyed} from an eye, {hidden} with a bucket left out, {several} in three runs"
);
assert!(edge_drawn, "the bucket at the section's edge");
if let Some(t) = &timing {
let parts = t.part_medians();
let names = |pass: &str| {
let parts = parts.iter().find(|p| p.0 == pass)?;
Some(parts.1.iter().map(|p| p.0.as_str()).collect::<Vec<_>>())
};
assert_eq!(
names("GPU culling"),
Some(vec!["apply", "cull", "scan", "scatter"]),
"{parts:?}"
);
}
assert!(culled > 2_000, "{culled} within the distance left out");
assert!(faded * 10 > compared, "{faded} fading of {compared} drawn");
assert!(
@@ -3136,6 +3198,113 @@ mod tests {
);
}
/// Detail times both phases and the uploads and leaves counts and draws as an untimed frame's.
#[test]
fn detail_times_both_phases_and_leaves_the_draws_alone() {
on_each_device(|device, queue| {
let mut rng = Rng(0x1F83_D9AB_FB41_BD6B);
let (frustum, _) = view(&mut rng);
let records: Vec<Record> = (0..400)
.map(|i| {
let key = (rng.range(-6, 6), rng.range(0, 23), rng.range(-6, 6));
Record::new(
key,
i % 3,
u64::from(i) * 1024,
1 + rng.below(500),
UNBOUNDED,
)
})
.collect();
let mut timing = PassTiming::new(device, queue);
let early = device
.features()
.contains(wgpu::Features::SHADER_EARLY_DEPTH_TEST);
let Some(t) = timing.as_mut().filter(|_| early) else {
eprintln!("no timestamps or early depth test: skipped");
return;
};
t.set_detail(true);
let run = |timing: &mut Option<PassTiming>| {
let mut gpu = GpuCulling::new(device, Some(wgpu::TextureFormat::Rgba8Unorm))
.expect("the pass");
let mut uploads = Uploads::new(device);
for r in &records {
gpu.records.insert(*r);
}
let mut out = Vec::new();
for frame in 0..12 {
if let Some(t) = timing {
t.begin(device, queue);
}
let mut encoder = device.create_command_encoder(&Default::default());
let input = FrameInputs {
camera: DVec3::new(0.5, 70.0, 0.5),
min_y: -64,
sections: 24,
radius: 5,
frustum: &frustum,
reach: None,
eye: None,
view_proj: Mat4::IDENTITY,
occlude: true,
};
let prepared = gpu.prepare(
device,
queue,
&mut uploads,
&mut encoder,
&input,
timing.as_mut(),
);
assert_eq!(prepared, Prepared::Gpu, "frame {frame}");
assert!(gpu.occluding(), "frame {frame}: phase 2 runs");
gpu.dispatch(&mut encoder, timing.as_mut());
gpu.compact(&mut encoder, timing.as_mut());
uploads.finish(&encoder);
queue.submit([encoder.finish()]);
if let Some(t) = timing {
t.submitted(queue);
}
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let pages = u64::from(gpu.pass_pages);
out.push((
read(device, queue, &gpu.counts.buffer, (STATS + 2 * pages) * 4),
read(device, queue, &gpu.draws.buffer, gpu.draws.bytes),
));
}
out
};
let timed = run(&mut timing);
let plain = run(&mut None);
assert_eq!(timed, plain, "detail changes what is drawn");
let t = timing.as_ref().expect("the timer");
let parts = t.part_medians();
let names = |pass: &str| {
let parts = parts.iter().find(|p| p.0 == pass)?;
Some(parts.1.iter().map(|p| p.0.as_str()).collect::<Vec<_>>())
};
assert_eq!(
names("GPU culling"),
Some(vec!["apply", "cull", "scan", "scatter"]),
"{parts:?}"
);
assert_eq!(
names("GPU culling phase 2"),
Some(vec!["count2", "scan2", "scatter2"]),
"{parts:?}"
);
// The uploads are a pass of their own, never a part of one.
assert_eq!(names("GPU culling uploads"), None, "{parts:?}");
let passes = t.medians();
assert_eq!(
passes.iter().any(|p| p.0 == "GPU culling uploads"),
t.detail_support().encoder_stamps,
"{passes:?}"
);
});
}
/// The statistics come back with their frame, in place and from the submit
/// thread, submitted as gfx.rs submits frames (`submit_later`, or in place
/// with its `after` handed back): three frames on their way fill the ring, a
@@ -3377,7 +3546,7 @@ struct Quad {
view_proj: Mat4::IDENTITY,
occlude: false,
};
let prepared = gpu.prepare(device, queue, &mut uploads, &mut encoder, &input);
let prepared = gpu.prepare(device, queue, &mut uploads, &mut encoder, &input, None);
assert_eq!(prepared, Prepared::Gpu, "frame {frame}");
let mut params = tables(&input, &mut words).expect("the planes fit");
params.pages = gpu.pass_pages;
+270 -90
View File
@@ -5,6 +5,10 @@
//! or scRGB swapchain at the player's paper white, expanding the world's
//! highlights towards their peak brightness. The world is copied aside before
//! the hand and HUD so only it is expanded.
//!
//! On the float frame Horizon's world light is the same on every display (`TIERS`,
//! `SUNLIT_GAIN`, up to `SCENE_PEAK`), and the tone curve alone fits it to the display's
//! peak (docs/design/hdr-linear-light.md, step 6a).
/// The swapchain HDR output presents to.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -99,38 +103,53 @@ struct Layered {
params: wgpu::Buffer,
}
/// How one tier of light sources (`mesher::hdr_tier`) shines: `share` of the headroom for
/// its brightest pixels, lifted from brightness `start` (none) to `full` (all of it), the
/// texel's own brightness before lighting.
/// How one tier of light sources (`mesher::hdr_tier`) shines: its brightest pixels are
/// multiplied by `gain`, in multiples of paper white, lifted from brightness `start` (none) to
/// `full` (all of it), the texel's own brightness before lighting.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tier {
pub share: f32,
pub gain: f32,
pub start: f32,
pub full: f32,
}
/// Low, incandescent, bright and very bright.
/// Low, incandescent, bright and very bright: faint glowers such as magma, flames and lava,
/// glowstone and campfires, the sun.
pub const TIERS: [Tier; 4] = [
Tier {
share: 0.2,
gain: 1.6,
start: 0.08,
full: 0.09,
},
Tier {
share: 0.5,
gain: 2.4,
start: 0.14,
full: 0.38,
},
Tier {
share: 0.6,
gain: 2.8,
start: 0.14,
full: 0.38,
},
Tier {
share: 1.0,
gain: 4.0,
start: 0.14,
full: 0.38,
},
];
/// The scene's peak, in multiples of paper white: just above the brightest light the world
/// writes (the sun's disc, white at the very bright tier's 4), and what the tone curve maps
/// onto the display's peak; light past it (where the sky adds onto the sun) is held at it. The
/// world is mastered for a 1000-nit display at ITU-R BT.2408's 203-nit reference white, as
/// HDR10 content usually is: there it shows as written, a dimmer display eases its highlights
/// into its peak (BT.2390's EETF), and a brighter one shows it as at 1000.
pub const SCENE_PEAK: f32 = 1000.0 / 203.0;
/// HDR lighting: what the strongest light multiplies a surface by (`hdr_light.wgsl`).
pub const SUNLIT_GAIN: f32 = 3.0;
/// The compatibility frame's tiers (the 16-bit or 8-bit frame, until step 5 removes it): each
/// one's share of the display's headroom, as before one peak, so the look HDR has by default
/// changes once, when the float frame replaces it.
const COMPAT_SHARES: [f32; 4] = [0.2, 0.5, 0.6, 1.0];
/// Which pixels of a light source's sprite may shine (`hdr_stats.wgsl`), as a fraction of
/// the way from its darkest to its brightest opaque pixel: `parts` for one whose bright parts
/// shine (a torch's flame, not its handle), `whole` for one that shines all over
@@ -331,7 +350,7 @@ impl Hdr {
let params = || {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon HDR parameters"),
size: 64,
size: 80,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
@@ -944,16 +963,19 @@ impl Hdr {
})
}
/// What the world's writers read (`hdr_written`): the scene's peak, HDR lighting's gain,
/// world/look and debug, then the tiers' gains. No part of the display reaches them.
pub(super) fn draw_params(&self, world: bool) -> ([f32; 4], [f32; 4]) {
let p = self.params(world, false);
([p[1], p[7], p[2], p[3]], p[8..12].try_into().unwrap())
let sunlit = if self.lighting { SUNLIT_GAIN } else { 1.0 };
([SCENE_PEAK, sunlit, p[2], p[3]], self.tiers.map(|t| t.gain))
}
/// hdr.wgsl's `Params`.
fn params(&self, world: bool, pq: bool) -> [f32; 16] {
fn params(&self, world: bool, pq: bool) -> [f32; 20] {
let paper = self.paper_white.max(1.0);
let c = self.calibration;
let mut params = [0.0; 16];
let mut params = [0.0; 20];
params[..5].copy_from_slice(&[
paper / 80.0,
(self.peak / paper).max(1.0),
@@ -968,12 +990,17 @@ impl Hdr {
} else {
1.0
};
for (i, t) in self.tiers.iter().enumerate() {
params[8 + i] = t.share;
}
params[8..12].copy_from_slice(&COMPAT_SHARES);
params[12] = c.map_or(0.0, |c| c.step as f32);
params[13] = c.map_or(0.0, |c| c.nits);
params[14] = c.map_or(0.0, |c| c.band);
// Only Horizon's lifted world is known to end at the scene's peak; elsewhere (HDR
// Lighting off, a pack's own light, the title) the curve's source follows the display.
params[16] = if world && self.lighting {
SCENE_PEAK
} else {
0.0
};
params
}
@@ -1050,8 +1077,9 @@ fn logo_mask(device: &wgpu::Device, queue: &wgpu::Queue) -> wgpu::TextureView {
.create_view(&Default::default())
}
/// What the strongest light multiplies a surface by, in HDR lighting: 4, which looked right
/// across biomes; less only where there is little headroom to ease into (`hdr.wgsl`).
/// The compatibility frame's HDR lighting (`fs_hdr`): what the strongest light multiplies a
/// surface by, 4, which looked right across biomes; less only where there is little headroom
/// to ease into. The float frame's is `SUNLIT_GAIN`.
fn scene_gain(peak: f32, paper_white: f32) -> f32 {
(peak / paper_white.max(1.0) * 1.75).clamp(1.0, 4.0)
}
@@ -1069,7 +1097,8 @@ mod tests {
return;
};
// All 8-bit marks, both easing policies, non-grey and over-white colours, look,
// debug, headroom and tier shares; half-float neighbours straddle mark boundaries.
// debug, headroom and tier shares; half-float neighbours straddle mark boundaries. The
// writers take the gain that a share gives.
let source = include_str!("../hdr_light.wgsl").to_owned()
+ r#"
struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: vec4<f32> }
@@ -1088,19 +1117,20 @@ var<private> params: ReferenceParams;
select(0.0, 1.0, (mode & 32u) != 0u), vec4(0.2, 0.5, 0.6, 1.0));
let color = select(vec3(0.9, 0.4, 0.02), vec3(1.4, 0.8, 0.2), (mode & 64u) != 0u);
let expected = reference_lit(color, mark, shows, eased);
let gains = 1.0 + (params.peak - 1.0) * params.share;
let actual = hdr_mark_light(color, mark, shows, eased,
vec4(params.peak, params.scene, params.world, params.debug), params.share);
vec4(params.peak, params.scene, params.world, params.debug), (params.peak - 1.0) * params.share);
errors[i] = select(0u, 1u, any(abs(expected.light - actual.light) > vec3(1e-6)) || expected.lifted != actual.lifted);
// Gain stays above the tone knee until the separate tone curve runs.
let gain = 1.0 + 3.0 * (1.0 - 194.0 / 255.0) / 0.24;
let white = hdr_written(vec3(1.0), 0.76, vec4(5.0, 4.0, 1.0, 0.0), params.share);
let white = hdr_written(vec3(1.0), 0.76, vec4(5.0, 4.0, 1.0, 0.0), gains);
errors[i] |= select(0u, 4u, any(abs(pow(white, vec3(2.2)) - vec3(gain)) > vec3(1e-5)));
let boundary = (f32(i % 255u) + 0.5) / 255.0;
for (var step = -1; step <= 1; step++) {
let stored = unpack2x16float(pack2x16float(vec2(boundary + f32(step) / 65536.0))).x;
let quantized = round(saturate(stored) * 255.0) / 255.0;
let want = pow(reference_lit(color, quantized, params.world > 0.5 && params.peak > 1.0, false).light, vec3(1.0 / 2.2));
let got = hdr_written(color, stored, vec4(params.peak, params.scene, params.world, params.debug), params.share);
let want = pow(reference_lit(color, quantized, params.world > 0.5, false).light, vec3(1.0 / 2.2));
let got = hdr_written(color, stored, vec4(params.peak, params.scene, params.world, params.debug), gains);
errors[i] |= select(0u, 2u, any(abs(want - got) > vec3(1e-6)));
}
}
@@ -1319,10 +1349,12 @@ var<private> params: ReferenceParams;
// Independent pre-refactor light arithmetic applied to a compatibility attachment.
// Float targets in these tests only receive the resulting colour and coverage.
// `lift`: the reference's peak, HDR lighting gain, world and debug, then the tiers' shares
// of the headroom up to that peak (`writers_lift`, `display_lift`).
pub(super) fn legacy_light(
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
hdr: &Hdr,
lift: [[f32; 4]; 2],
source: &wgpu::Texture,
target: &wgpu::Texture,
) {
@@ -1345,7 +1377,7 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
@fragment fn fs() -> @location(0) vec4<f32> {
let c = textureLoad(source, vec2(0), 0);
let mark = round(saturate(c.a) * 255.0) / 255.0;
let light = reference_lit(c.rgb, mark, params.world > 0.5 && params.peak > 1.0, false).light;
let light = reference_lit(c.rgb, mark, params.world > 0.5, false).light;
return vec4(pow(light, vec3(1.0 / 2.2)), 1.0);
}
"#)
@@ -1373,10 +1405,9 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
multiview_mask: None,
cache: None,
});
let (settings, shares) = hdr.draw_params(true);
let params = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
contents: bytemuck::cast_slice(&[settings, shares]),
contents: bytemuck::cast_slice(&lift),
usage: wgpu::BufferUsages::UNIFORM,
});
let view = source.create_view(&Default::default());
@@ -1404,6 +1435,19 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
);
}
/// The float frame's writers' light as `legacy_light` takes it: each tier's gain as a share
/// of the headroom up to the scene's peak.
pub(super) fn writers_lift(hdr: &Hdr) -> [[f32; 4]; 2] {
let (settings, gains) = hdr.draw_params(true);
[settings, gains.map(|g| (g - 1.0) / (settings[0] - 1.0))]
}
/// The compatibility frame's display pass's light (`fs_hdr`) as `legacy_light` takes it.
fn display_lift(hdr: &Hdr) -> [[f32; 4]; 2] {
let p = hdr.params(true, false);
[[p[1], p[7], p[2], p[3]], p[8..12].try_into().unwrap()]
}
#[test]
fn direct_light_matches_the_legacy_non_float_display_below_the_tone_knee() {
let Some((device, queue)) = gpu() else {
@@ -1416,8 +1460,9 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
eprintln!("legacy display GPU skipped: 16-bit UNORM unavailable");
return;
}
// Compare the compatibility display lift with direct colour under the layered HUD.
// The frozen oracle supplies the writer's light from a non-float attachment.
// Compare the compatibility display lift with direct colour under the layered HUD:
// the frozen oracle turns the marks into the light that display gives them, and the
// layered display, whose curve is the identity at 1000 nits, must show it the same.
let shown = |layered: bool, world: [f64; 4]| {
let mut hdr = Hdr::with_debug(
&device,
@@ -1441,7 +1486,14 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
if world[3] == 1.0 {
fill(&mut encoder, &frame, world);
} else {
legacy_light(&device, &mut encoder, &hdr, &marked, &frame);
// The light the compatibility frame shows: its own lift, not the writers'.
legacy_light(
&device,
&mut encoder,
display_lift(&legacy),
&marked,
&frame,
);
}
hdr.begin(&queue, true);
hdr.tonemap(&mut encoder, None);
@@ -1480,78 +1532,206 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
assert!(above[0] > white[0] && above[1] > white[1]);
}
/// The world's writers read nothing of the display: the same gains and the same scene peak
/// at any paper white and peak (docs/design/hdr-linear-light.md, step 6a).
#[test]
fn the_tone_curve_eases_light_into_the_peak() {
fn the_writers_light_is_the_same_on_every_display() {
let Some((device, queue)) = gpu() else {
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
(hdr.paper_white, hdr.peak) = (203.0, 1000.0);
let headroom = 1000.0 / 203.0;
// The frame holding `color` (in gamma, as it stores light) after `passes` ran on it.
let after =
|hdr: &mut Hdr, color: [f64; 4], passes: &dyn Fn(&Hdr, &mut wgpu::CommandEncoder)| {
let frame = hdr.frame(&device, [1, 1]);
let mut encoder = device.create_command_encoder(&Default::default());
fill(&mut encoder, &frame, color);
hdr.begin(&queue, true);
passes(hdr, &mut encoder);
texel(&device, &queue, encoder, &frame)
};
let tonemap = |hdr: &Hdr, encoder: &mut wgpu::CommandEncoder| hdr.tonemap(encoder, None);
let written = hdr.draw_params(true);
assert_eq!(
written,
(
[super::SCENE_PEAK, super::SUNLIT_GAIN, 1.0, 0.0],
[1.6, 2.4, 2.8, 4.0]
)
);
for (paper, peak) in [
(203.0, 300.0),
(203.0, 600.0),
(203.0, 1500.0),
(400.0, 600.0),
(480.0, 200.0),
(80.0, 10000.0),
] {
(hdr.paper_white, hdr.peak) = (paper, peak);
assert_eq!(hdr.draw_params(true), written, "{paper}/{peak}");
assert_eq!(
hdr.params(true, false)[16],
super::SCENE_PEAK,
"{paper}/{peak}"
);
}
// The title, and frames Horizon doesn't light (HDR Lighting off, a pack drawing):
// nothing says where their light ends, so the curve's source follows the display.
assert_eq!(hdr.params(false, false)[16], 0.0);
hdr.lighting = false;
assert_eq!(hdr.draw_params(true).0[1], 1.0);
assert_eq!(hdr.params(true, false)[16], 0.0);
}
/// The tone curve maps the scene's peak S onto the display's peak T with ITU-R BT.2390's
/// EETF, keeping hue, after holding light above S at S. Checkpoints are worked out apart
/// from the shader, in f64 from SMPTE ST 2084 and BT.2390.
#[test]
fn the_tone_curve_maps_the_scene_peak_onto_the_display() {
let Some((device, queue)) = gpu() else {
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let scene_peak = super::SCENE_PEAK;
// The frame holding `color` (in gamma, as it stores light), after the curve if `curve`.
let through = |hdr: &mut Hdr, color: [f64; 4], curve: bool| {
let frame = hdr.frame(&device, [1, 1]);
let mut encoder = device.create_command_encoder(&Default::default());
fill(&mut encoder, &frame, color);
hdr.begin(&queue, true);
if curve {
hdr.tonemap(&mut encoder, None);
}
texel(&device, &queue, encoder, &frame)
};
// `exact`, or within one half-float step: S's own gamma rounds up in half float, to
// light just above S that the curve holds at S, and whether that comes back to the same
// half float depends on the GPU's rounding (one step lower on an Apple M4 Pro).
let unchanged = |hdr: &mut Hdr, color: [f64; 4], exact: bool| {
let (got, stored) = (through(hdr, color, true), through(hdr, color, false));
(0..4).all(|c| {
got[c] == stored[c] || !exact && (got[c] - stored[c]).abs() <= stored[c] / 1024.0
})
};
// Linear light in and out, in units of paper white.
let eased = |hdr: &mut Hdr, light: [f32; 3]| {
let mapped = |hdr: &mut Hdr, light: [f32; 3]| {
let [r, g, b] = light.map(|c| f64::from(c.powf(1.0 / 2.2)));
let [r, g, b, a] = after(hdr, [r, g, b, 1.0], &tonemap);
let [r, g, b, a] = through(hdr, [r, g, b, 1.0], true);
assert_eq!(a, 1.0);
[r, g, b].map(|c| c.powf(2.2))
};
let near = |got: f32, want: f32| (got - want).abs() <= 0.005 * want.max(1.0);
// Up to the knee (60% of the peak) the light stays exactly as stored.
for light in [0.0f32, 0.5, 1.0, 2.0, 2.9] {
let g = f64::from(light.powf(1.0 / 2.2));
let stored = after(&mut hdr, [g, g * 0.5, 0.0, 1.0], &|_, _| {});
assert_eq!(
after(&mut hdr, [g, g * 0.5, 0.0, 1.0], &tonemap),
stored,
"{light}"
);
}
// Past it, BT.2390's EETF in PQ at 203 and 1000 nits, with the source's peak at 2771
// nits (13.7 times paper white), worked out apart from the shader.
for (light, want) in [
(3.5, 3.43791),
(4.0, 3.78351),
(headroom, 4.23556),
(8.0, 4.82043),
(12.0, 4.92462),
(50.0, headroom),
// A display at or above the mastering one (T >= S): every stored value up to S comes
// out exactly as it went in, grey or coloured, and light above S is held at S with its
// hue, so 1500 and 10 000 nits show what 1000 does; so do the settings' extremes (Paper
// White 10 to 480 nits, Peak up to 10 000) wherever T reaches S.
for (paper, peak) in [
(203.0, 1000.0),
(203.0, 1500.0),
(203.0, 10000.0),
(480.0, 10000.0),
(10.0, 200.0),
] {
let [r, ..] = eased(&mut hdr, [light; 3]);
assert!(near(r, want), "{light}: {r}, not {want}");
(hdr.paper_white, hdr.peak) = (paper, peak);
for i in 0..=64 {
let g = f64::from((scene_peak * i as f32 / 64.0).powf(1.0 / 2.2));
let exact = i < 64;
assert!(unchanged(&mut hdr, [g, g, g, 1.0], exact), "{peak}: {i}");
assert!(
unchanged(&mut hdr, [g, g * 0.6, g * 0.1, 1.0], exact),
"{peak}: {i}"
);
}
for light in [8.0f32, 50.0] {
let [r, g, b] = mapped(&mut hdr, [light, light / 4.0, 0.0]);
assert!(
near(r, scene_peak) && near(g * 4.0, r) && b == 0.0,
"{peak}: {light}: {r} {g} {b}"
);
}
}
// It rises, stays under the peak, and the brightest channel scales the others: the
// light keeps its hue.
let mut last = 0.0;
for i in 0..40 {
let light = 2.5 * 1.08f32.powi(i);
let [r, g, b] = eased(&mut hdr, [light, light / 4.0, 0.0]);
assert!(r >= last - 0.001 && r <= headroom * 1.002, "{light}: {r}");
assert!(near(g * 4.0, r) && b == 0.0, "{light}: {r} {g} {b}");
last = r;
// Dimmer displays: unchanged up to the knee, then the EETF into T, T at S and past it.
// At 300 nits the knee falls just below white (161 nits): white shows at 198 nits
// where the gates' curve, whose source followed the display, kept it at 203; the
// highlights above it keep more of their steps.
for (paper, peak, knee, checkpoints) in [
(
203.0,
600.0,
2.0,
&[
(2.5, 2.47516),
(3.0, 2.75699),
(4.0, 2.9404),
(scene_peak, 600.0 / 203.0),
(8.0, 600.0 / 203.0),
][..],
),
(
203.0,
300.0,
0.75,
&[
(0.9, 0.89289),
(1.0, 0.97365),
(1.2, 1.10406),
(1.4, 1.20134),
(2.0, 1.36833),
(4.0, 1.47641),
(8.0, 300.0 / 203.0),
],
),
(
400.0,
600.0,
0.8,
&[
(1.0, 0.97973),
(1.2, 1.11501),
(1.5, 1.25607),
(2.0, 1.38818),
(scene_peak, 1.5),
],
),
// No headroom (a peak under paper white): the scene is compressed into white.
(
203.0,
150.0,
0.4,
&[
(1.0, 0.78346),
(1.5, 0.90244),
(2.0, 0.95589),
(4.0, 0.99944),
(scene_peak, 1.0),
],
),
] {
(hdr.paper_white, hdr.peak) = (paper, peak);
for light in [0.0f32, 0.3, knee] {
let g = f64::from(light.powf(1.0 / 2.2));
assert!(
unchanged(&mut hdr, [g, g * 0.5, 0.0, 1.0], true),
"{paper}/{peak}: {light}"
);
}
for &(light, want) in checkpoints {
let [r, ..] = mapped(&mut hdr, [light; 3]);
assert!(near(r, want), "{paper}/{peak}: {light}: {r}, not {want}");
}
// It rises, stays under the peak, and the brightest channel scales the others; a
// half float's step in gamma is 0.1% of the light near white.
let headroom = (peak / paper).max(1.0);
let mut last = 0.0;
for i in 0..40 {
let light = 0.5 * 1.08f32.powi(i);
let [r, g, b] = mapped(&mut hdr, [light, light / 4.0, 0.0]);
assert!(
r >= last * 0.998 && r <= headroom * 1.002,
"{peak}: {light}: {r}"
);
assert!(near(g * 4.0, r) && b == 0.0, "{peak}: {light}: {r} {g} {b}");
last = r;
}
}
// A display with little headroom, 300 nits at a paper white of 203: the knee sits at
// white, so all that SDR shows stays as it is, and the source's peak is 645 nits.
hdr.peak = 300.0;
// Light Horizon doesn't lift (HDR Lighting off, a 0.2 pack's own) has no known peak:
// the curve's source follows the display, the knee at 60% of its peak and at least
// white, as before one peak. At 300 nits the source's peak is 645 nits.
hdr.lighting = false;
(hdr.paper_white, hdr.peak) = (203.0, 300.0);
let headroom = 300.0 / 203.0;
for light in [0.5f32, 0.9, 1.0] {
for light in [0.0f32, 0.5, 0.9, 1.0] {
let g = f64::from(light.powf(1.0 / 2.2));
let stored = after(&mut hdr, [g, g * 0.5, 0.0, 1.0], &|_, _| {});
assert_eq!(
after(&mut hdr, [g, g * 0.5, 0.0, 1.0], &tonemap),
stored,
"{light}"
);
assert!(unchanged(&mut hdr, [g, g * 0.5, 0.0, 1.0], true), "{light}");
}
for (light, want) in [
(1.2, 1.16839),
@@ -1560,12 +1740,12 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
(2.0, 1.44024),
(4.0, headroom),
] {
let [r, ..] = eased(&mut hdr, [light; 3]);
let [r, ..] = mapped(&mut hdr, [light; 3]);
assert!(near(r, want), "{light}: {r}, not {want}");
}
// No headroom (a peak below paper white): a clip at white, channel by channel.
// With no headroom there, a clip at white, channel by channel.
hdr.peak = 150.0;
let [r, g, b] = eased(&mut hdr, [1.5, 0.5, 0.2]);
let [r, g, b] = mapped(&mut hdr, [1.5, 0.5, 0.2]);
assert!(r == 1.0 && near(g, 0.5) && near(b, 0.2), "{r} {g} {b}");
}
@@ -1582,7 +1762,7 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
(hdr.paper_white, hdr.peak, hdr.black) = (250.0, 800.0, 0.0);
(hdr.ui, hdr.look, hdr.lighting) = (0.5, false, false);
hdr.masks.parts = 0.4;
hdr.tiers[1].share = 0.7;
hdr.tiers[1].gain = 3.0;
hdr.debug = true;
hdr.calibration = Some(super::Calibration {
step: 2,
@@ -1,6 +1,6 @@
use super::{
Hdr, Output,
tests::{gpu, legacy_light, texel},
tests::{gpu, legacy_light, texel, writers_lift},
};
use wgpu::TextureFormat as F;
use wgpu::util::DeviceExt;
@@ -648,7 +648,7 @@ impl<'a> Draw<'a> {
}
if !written && !self.raw {
let light = hdr.frame(self.device, [1, 1]);
legacy_light(self.device, &mut encoder, hdr, &frame, &light);
legacy_light(self.device, &mut encoder, writers_lift(hdr), &frame, &light);
return texel(self.device, self.queue, encoder, &light);
}
texel(self.device, self.queue, encoder, &frame)
@@ -662,7 +662,7 @@ fn float_plain_fragments_keep_rgb_and_write_only_coverage() {
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let (settings, gains) = hdr.draw_params(true);
let mut cases = 0;
for hdr_on in [false, true] {
let globals = super::super::Globals {
@@ -677,7 +677,7 @@ fn float_plain_fragments_keep_rgb_and_write_only_coverage() {
hdr_windows: hdr.windows(),
hdr_light: [0.8, 0.8, f32::from(u8::from(hdr_on)), 0.0],
hdr_settings: settings,
hdr_shares: shares,
hdr_gains: gains,
..bytemuck::Zeroable::zeroed()
};
for terrain in [true, false] {
@@ -739,7 +739,7 @@ fn float_stars_keep_the_original_rgb_with_brightness_as_coverage() {
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let (settings, gains) = hdr.draw_params(true);
// Frozen f030d9c80 fragment: the original written branch and its marked fallback.
let source = include_str!("../hdr_light.wgsl").to_owned()
+ include_str!("stars.wgsl")
@@ -750,7 +750,7 @@ fn float_stars_keep_the_original_rgb_with_brightness_as_coverage() {
@fragment fn reference() -> @location(0) vec4<f32> {
let b = stars.color.a;
if HDR_WRITE_LIGHT && stars.hdr_light.w != 0.0 {
return vec4(hdr_written(stars.color.rgb * b, 0.175, stars.hdr_settings, stars.hdr_shares), b);
return vec4(hdr_written(stars.color.rgb * b, 0.175, stars.hdr_settings, stars.hdr_gains), b);
}
return vec4(stars.color.rgb * b, 0.175);
}
@@ -763,7 +763,7 @@ fn float_stars_keep_the_original_rgb_with_brightness_as_coverage() {
let mut data = [0.0_f32; 32];
data[16..20].copy_from_slice(&[0.7, 0.8, 0.9, 0.35]);
data[20..24].copy_from_slice(&settings);
data[24..28].copy_from_slice(&shares);
data[24..28].copy_from_slice(&gains);
data[31] = gain;
let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: None,
@@ -908,7 +908,7 @@ fn actual_opaque_writers_match_the_legacy_non_float_oracle() {
}
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
(hdr.paper_white, hdr.peak) = (203.0, 1000.0);
let (settings, shares) = hdr.draw_params(true);
let (settings, gains) = hdr.draw_params(true);
let mut count = 0;
for fog in [0.0, 0.5, 1.0] {
for visibility in [1.0, 0.4] {
@@ -921,7 +921,7 @@ fn actual_opaque_writers_match_the_legacy_non_float_oracle() {
hdr_windows: hdr.windows(),
hdr_light: [0.8, 0.8, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
hdr_gains: gains,
..bytemuck::Zeroable::zeroed()
};
for terrain in [true, false] {
@@ -968,7 +968,7 @@ fn actual_translucent_writers_blend_their_own_light() {
return;
};
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let (settings, gains) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
fog_ends: [100.0, 100.0, 0.0, 0.0],
@@ -977,7 +977,7 @@ fn actual_translucent_writers_blend_their_own_light() {
hdr_windows: hdr.windows(),
hdr_light: [0.8, 0.8, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
hdr_gains: gains,
..bytemuck::Zeroable::zeroed()
};
// Texel alpha 100 is clear glass's kind of texel, below the 0.6 the marked frame's
@@ -1035,14 +1035,14 @@ fn unmarked_entity_users_keep_their_source_gain() {
return;
}
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let (settings, gains) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
fog_ends: [100.0, 100.0, 0.0, 0.0],
hdr_windows: hdr.windows(),
hdr_light: [1.0, 1.0, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
hdr_gains: gains,
..bytemuck::Zeroable::zeroed()
};
let draw = Draw::new(&device, &queue, false, &globals, 255);
@@ -1079,13 +1079,13 @@ fn additive_texels_below_the_mark_cutoff_keep_their_gain() {
return;
}
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let (settings, gains) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
hdr_windows: hdr.windows(),
hdr_light: [1.0, 1.0, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
hdr_gains: gains,
..bytemuck::Zeroable::zeroed()
};
let draw = Draw::new(&device, &queue, false, &globals, 16);
@@ -1129,7 +1129,7 @@ fn check_oit_writer(terrain: bool, kind: &str, overlay: u32, tier: u32, alphas:
}))
.unwrap();
let mut hdr = Hdr::with_debug(&device, &queue, F::Rgba16Float, Output::Pq, true, None);
let (settings, shares) = hdr.draw_params(true);
let (settings, gains) = hdr.draw_params(true);
let globals = super::super::Globals {
fog: [0.0, 100.0, 0.0, 100.0],
fog_ends: [100.0, 100.0, 0.0, 0.0],
@@ -1138,7 +1138,7 @@ fn check_oit_writer(terrain: bool, kind: &str, overlay: u32, tier: u32, alphas:
hdr_windows: hdr.windows(),
hdr_light: [0.8, 0.8, 1.0, 1.0],
hdr_settings: settings,
hdr_shares: shares,
hdr_gains: gains,
..bytemuck::Zeroable::zeroed()
};
for &alpha in alphas {
@@ -0,0 +1,132 @@
//! Frames in flight: the readbacks a submission starts, landing frames the submit thread
//! submitted, keeping offscreen frames at most two ahead of the GPU, and a screenshot's copy.
use super::{Renderer, ScreenshotRequest, copy_frame, screenshot_save, submit};
impl Renderer {
/// The frame's readbacks to start right after its submission (on the submit thread when
/// the frame goes there): occlusion culling's results (`cull`) and GPU culling's
/// statistics. GPU frames leave occlusion culling off, so a frame has one at most.
pub(super) fn after_submit(&mut self) -> Option<submit::AfterSubmit> {
let cull = self.cull.as_mut().and_then(|c| c.submitted());
let gpu = self.gpu_culling.as_mut().and_then(|g| g.submitted());
match (cull, gpu) {
(Some(c), Some(g)) => Some(Box::new(move || {
c();
g();
})),
(Some(c), None) => Some(Box::new(c)),
(None, Some(g)) => Some(Box::new(g)),
(None, None) => None,
}
}
/// Frame `frame`'s statistics shown, unless a newer frame's are: a CPU frame's as it is
/// drawn, a GPU frame's when its counts come back (`GpuCulling::collect`).
pub(super) fn show_stats(&mut self, frame: u64, [sections, draws, calls]: [usize; 3]) {
if frame > self.stats_frame {
self.stats_frame = frame;
(
self.drawn_sections,
self.section_draws,
self.section_draw_calls,
) = (sections, draws, calls);
}
}
/// Frames between the last one drawn and the one whose statistics are shown: 0 after a
/// CPU frame, one to three in GPU frames, while their counts are on their way back.
pub fn stats_lag(&self) -> u64 {
self.frame_serial - self.stats_frame
}
/// Take in the frame the submit thread submitted: start its readbacks and, offscreen,
/// keep at most two frames ahead of the GPU, as a frame submitted in place does.
pub(super) fn land_frame(&mut self) {
let Some(offscreen) = self.deferred.take() else {
return;
};
let submission = self.queue.landed();
if let Some(timer) = &mut self.gpu_timer {
timer.submitted(&self.queue);
timer.collect(&self.device, &mut self.gpu_times);
}
if let Some(Some(timer)) = Self::pass_timer(&mut self.pack_post, &mut self.native) {
timer.submitted(&self.queue);
}
if let Some(timer) = &mut self.own_timing {
timer.submitted(&self.queue);
}
if offscreen && let Some(submission) = submission {
self.in_flight.push_back(submission);
if !self.paced_elsewhere {
self.wait_frames();
}
}
}
/// No swapchain paces offscreen frames: keep two on the GPU at most.
pub fn wait_in_flight(&mut self) {
self.land_frame();
self.wait_frames();
}
/// The frame on the submit thread submitted: a surface reconfigure waits for the
/// device and breaks if a frame is submitted while it waits, and the compositor
/// copies views after them. (The end of a frame already lands the frames of the
/// turn before; this is the turn's own.)
pub fn wait_submissions(&mut self) {
self.queue.wait();
}
pub(super) fn wait_frames(&mut self) {
while self.in_flight.len() > 2 {
let index = self.in_flight.pop_front();
let _ = self.device.poll(wgpu::PollType::Wait {
submission_index: index,
timeout: Some(std::time::Duration::from_secs(5)),
});
}
}
/// Take a screenshot request: queue the frame's copy, or report why the
/// frame cannot be read back.
pub(super) fn take_readback(
&mut self,
request: ScreenshotRequest,
encoder: &mut wgpu::CommandEncoder,
texture: &wgpu::Texture,
) -> Option<(ScreenshotRequest, wgpu::Buffer)> {
// The copy and PNG writer both assume 8-bit pixels; a float surface would make
// the row stride too small for the copy and abort in validation.
if self.config.format.block_copy_size(None) == Some(4) {
let size = [self.config.width, self.config.height];
let format = self.config.format.remove_srgb_suffix();
// The layered float frame maps the world to SDR, then adds the HUD as drawn.
// Other 16-bit frames keep their clipped 8-bit copy.
let copy = self
.hdr
.as_mut()
.and_then(|hdr| {
hdr.sdr_screenshot(&self.device, encoder, format, request.size.is_some())
})
.or_else(|| {
(texture.format() != format && texture.format() == self.output.frame.format)
.then(|| {
self.readback
.unorm_copy(&self.device, encoder, texture, format)
})
});
let texture = copy.as_ref().unwrap_or(texture);
Some((request, copy_frame(&self.device, encoder, texture, size)))
} else {
let error = format!(
"screenshots need a 32-bit surface format, not {:?}",
self.config.format
);
if request.background {
self.saved_screenshots.push(screenshot_save::Saved {
path: request.path,
result: Err(error),
hdr: None,
});
} else {
self.screenshot_result = Some(Err(error));
}
None
}
}
}
@@ -2770,6 +2770,8 @@ file = \"b.wgsl\"
true,
);
(display.paper_white, display.peak) = (paper, peak);
// As the renderer has it under a pack that draws: Horizon lights none of it.
display.lighting = false;
if switched {
use super::super::hdr::Output::{Pq, ScRgb};
display = display.retargeted(&device, &queue, ScRgb);
+4 -1
View File
@@ -696,13 +696,16 @@ impl Oit {
),
] {
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
let pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(label),
timestamp_writes: timing.as_deref_mut().and_then(|t| t.writes(label)),
color_attachments: &first,
depth_stencil_attachment: read_only(terrain_depth),
..Default::default()
});
let pixels = super::pixel_count(terrain_depth);
let mut pass =
super::pack_timing::counted(timing.as_deref_mut(), pass, pixels, label);
pass.set_bind_group(GROUP, group, &[]);
draw(&mut pass, stage);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,169 @@
//! The world pass after culling, and the renderer's GPU pass timing switches and readings.
use super::{Renderer, native_pack, pack_post, pack_timing};
pub(super) fn world_pass_after_culling<'e>(
encoder: &'e mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
depth: &wgpu::TextureView,
keep_depth: bool,
mut timing: Option<&mut pack_timing::PassTiming>,
name: &str,
pixels: u64,
) -> pack_timing::CountedPass<'e> {
let pass = after_culling_pass(
encoder,
view,
depth,
keep_depth,
timing.as_deref_mut().and_then(|t| t.writes(name)),
);
pack_timing::counted(timing, pass, pixels, "before translucent")
}
/// The pixels of a depth attachment, for `fragments_per_pixel`.
pub(super) fn pixel_count(depth: &wgpu::TextureView) -> u64 {
let texture = depth.texture();
u64::from(texture.width()) * u64::from(texture.height())
}
pub(super) fn after_culling_pass<'e>(
encoder: &'e mut wgpu::CommandEncoder,
view: &wgpu::TextureView,
depth: &wgpu::TextureView,
keep_depth: bool,
timestamp_writes: Option<wgpu::RenderPassTimestampWrites<'_>>,
) -> wgpu::RenderPass<'e> {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon world, after culling"),
timestamp_writes,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Load,
// A shader pack reads it as depthtex0.
store: if keep_depth {
wgpu::StoreOp::Store
} else {
wgpu::StoreOp::Discard
},
}),
stencil_ops: None,
}),
..Default::default()
})
}
impl Renderer {
/// Times the shader pack's passes on the GPU while `on` (the F3 overlay is open or a capture records them).
pub fn set_pass_timing(&mut self, on: bool) {
self.pass_timing = on;
}
/// Times the parts of Horizon's own passes while `on`.
pub fn set_pass_detail(&mut self, on: bool) {
self.pass_detail = on;
}
/// Times a frame at most once per `gap` while passes are timed (the F3 overlay needs far fewer
/// samples than a measurement).
pub fn set_pass_timing_gap(&mut self, gap: std::time::Duration) {
self.pass_timing_gap = gap;
}
/// Keeps each timed frame's pass times for `take_timed_frames` while `on` (a capture records them).
pub fn set_keep_timed_frames(&mut self, on: bool) {
self.keep_timed_frames = on;
}
/// The frames both timers timed since the last call, without waiting on the GPU.
pub fn take_timed_frames(&mut self) -> pack_timing::TimedFrames {
let own = self
.own_timing
.as_mut()
.map(pack_timing::PassTiming::take_frames)
.unwrap_or_default();
let pack = match Self::pass_timer(&mut self.pack_post, &mut self.native) {
Some(Some(t)) => t.take_frames(),
_ => Vec::new(),
};
pack_timing::TimedFrames { own, pack }
}
/// The running shader pack's timer, of either kind.
pub(super) fn pass_timer<'a>(
pack: &'a mut Option<(i32, Option<pack_post::PackPost>)>,
native: &'a mut Option<native_pack::NativePack>,
) -> Option<&'a mut Option<pack_timing::PassTiming>> {
match (pack, native) {
(Some((_, Some(post))), _) => Some(&mut post.timing),
(_, Some(native)) => Some(&mut native.timing),
_ => None,
}
}
/// Each pass of the running shader pack with its median GPU time in milliseconds, while
/// they are timed (`set_pass_timing`).
pub fn shader_pass_times(&self) -> Vec<(String, f32)> {
let timer = match (&self.pack_post, &self.native) {
(Some((_, Some(post))), _) => post.timing.as_ref(),
(_, Some(native)) => native.timing.as_ref(),
_ => None,
};
timer
.map(pack_timing::PassTiming::medians)
.unwrap_or_default()
}
/// Each of Horizon's own passes with its median GPU time in milliseconds, while they are
/// timed (`set_pass_timing`).
pub fn own_pass_times(&self) -> Vec<(String, f32)> {
self.own_timing
.as_ref()
.map(pack_timing::PassTiming::medians)
.unwrap_or_default()
}
/// Each of Horizon's own passes with its parts' median GPU times in milliseconds.
pub fn own_pass_parts(&self) -> Vec<(String, Vec<(String, f32)>)> {
self.own_timing
.as_ref()
.map(pack_timing::PassTiming::part_medians)
.unwrap_or_default()
}
/// Each counted pass's counters (medians), while detail is on and the device has them.
pub fn own_pass_counters(&self) -> Vec<(String, pack_timing::PassCounters)> {
self.own_timing
.as_ref()
.map(pack_timing::PassTiming::counter_medians)
.unwrap_or_default()
}
/// Both timers' readings and this adapter, for a capture; `None` when neither has timed a pass.
pub fn gpu_readout(&self) -> Option<pack_timing::GpuReadout> {
let own = self
.own_timing
.as_ref()
.map(pack_timing::PassTiming::readings)
.filter(|r| !r.is_empty());
let pack = match (&self.pack_post, &self.native) {
(Some((_, Some(post))), _) => post.timing.as_ref(),
(_, Some(native)) => native.timing.as_ref(),
_ => None,
}
.map(pack_timing::PassTiming::readings)
.filter(|r| !r.is_empty());
(own.is_some() || pack.is_some()).then(|| pack_timing::GpuReadout {
adapter: self.info.clone(),
own,
pack,
})
}
/// Whether dispatch parts and counters are being asked for (`set_pass_detail`).
pub fn pass_detail(&self) -> bool {
self.pass_detail
}
/// What detail timing can show on this device; `None` without pass timing.
pub fn pass_detail_support(&self) -> Option<pack_timing::DetailSupport> {
self.own_timing
.as_ref()
.map(pack_timing::PassTiming::detail_support)
}
}
@@ -47,7 +47,7 @@ struct Uniform {
clip_from_sky: [[f32; 4]; 4],
color: [f32; 4],
hdr_settings: [f32; 4],
hdr_shares: [f32; 4],
hdr_gains: [f32; 4],
hdr_light: [f32; 4],
}
@@ -184,7 +184,7 @@ impl Stars {
clip_from_sky: clip_from_sky.to_cols_array_2d(),
color: [b; 4],
hdr_settings: globals.hdr_settings,
hdr_shares: globals.hdr_shares,
hdr_gains: globals.hdr_gains,
hdr_light: globals.hdr_light,
};
uploads.buffer(encoder, &self.uniform, 0, bytemuck::bytes_of(&uniform));
@@ -5,7 +5,7 @@ struct Stars {
// starBrightness in every channel (RenderSystem.setShaderColor).
color: vec4<f32>,
hdr_settings: vec4<f32>,
hdr_shares: vec4<f32>,
hdr_gains: vec4<f32>,
hdr_light: vec4<f32>,
}
@group(0) @binding(0) var<uniform> stars: Stars;
@@ -20,7 +20,7 @@ struct Stars {
@fragment fn fs_stars() -> @location(0) vec4<f32> {
let b = stars.color.a;
if HDR_WRITE_LIGHT && stars.hdr_light.w != 0.0 {
return vec4(hdr_written(stars.color.rgb * b, 0.175, stars.hdr_settings, stars.hdr_shares), b);
return vec4(hdr_written(stars.color.rgb * b, 0.175, stars.hdr_settings, stars.hdr_gains), b);
}
if HDR_WRITE_LIGHT { return vec4(frame_stored(stars.color).rgb * b, b); }
return vec4(stars.color.rgb * b, 0.175);
@@ -2,8 +2,8 @@
//! an adapter that can't present to the window gives way to another of its backend
//! (#13493).
use super::{
Renderer, check_layers, cull, describe_adapter, is_software, oit, startup_step, surface_format,
timing,
Renderer, check_layers, cull, describe_adapter, is_software, oit, pack_timing, startup_step,
surface_format, timing,
};
// Ray tracing on request, which the device needs from its creation (gfx.rs may not grow).
#[path = "ray_query.rs"]
@@ -135,6 +135,7 @@ pub(super) async fn open_adapter(
// atomics on images: their buffers and images. Filtering 32-bit float textures: shader
// packs' RGBA32F buffers, which GL filters and mipmaps. Count draws: GPU culling's (`gpu_culling`).
let features = timing::GpuTimer::features(adapter)
| pack_timing::PassTiming::features(adapter)
| cull::Cull::features(adapter)
| oit::features(adapter)
| ray_query::features(adapter)
@@ -0,0 +1,252 @@
//! The camera's view frustum, as camera-relative clip planes.
use glam::{Vec3, Vec4};
/// Camera-relative clip planes (`Frustum`).
#[derive(Clone, Copy, Debug)]
pub struct Frustum {
pub(super) planes: [Vec4; 6],
}
impl Frustum {
/// Whether the camera-relative box `min..max` is at least partly inside.
pub fn intersects(&self, min: Vec3, max: Vec3) -> bool {
!self.planes.iter().any(|p| {
let sign = p.truncate().cmpge(Vec3::ZERO);
let v = Vec3::select(sign, max, min);
p.truncate().dot(v) + p.w < 0.0
})
}
/// Whether a camera-relative sphere is at least partly inside. Frustum
/// planes are normalized, so each test needs only one dot product and a
/// radius comparison.
pub fn intersects_sphere(&self, center: Vec3, radius: f32) -> bool {
if !center.is_finite() || !radius.is_finite() || radius < 0.0 {
return true;
}
!self
.planes
.iter()
.any(|plane| plane.truncate().dot(center) + plane.w < -radius)
}
/// Depth clip planes alone: X/Y projection jitter cannot change this test.
/// Retaining side-of-screen geometry makes this safe before TAA selects a phase.
pub fn intersects_depth(&self, min: Vec3, max: Vec3) -> bool {
if !min.is_finite() || !max.is_finite() || !min.cmple(max).all() {
return true;
}
!self.planes[4..].iter().any(|p| {
let sign = p.truncate().cmpge(Vec3::ZERO);
let v = Vec3::select(sign, max, min);
p.truncate().dot(v) + p.w < 0.0
})
}
/// Whether the camera-relative box `min..max` is entirely inside. Then
/// `intersects` accepts every box within it: each plane's distance only
/// grows from this box's nearest corner to the inner box's farthest, and
/// rounding keeps that order.
pub fn contains(&self, min: Vec3, max: Vec3) -> bool {
self.planes.iter().all(|p| {
let sign = p.truncate().cmpge(Vec3::ZERO);
let v = Vec3::select(sign, min, max);
p.truncate().dot(v) + p.w >= 0.0
})
}
/// Whether the camera-relative `point` is on or inside every plane (vanilla's
/// `Frustum.pointInFrustum`). A point that is not finite is kept: a test that cannot
/// tell must not hide the particle.
pub fn contains_point(&self, point: Vec3) -> bool {
if !point.is_finite() {
return true;
}
self.planes
.iter()
.all(|plane| plane.truncate().dot(point) + plane.w >= 0.0)
}
/// The same frustum seen from a camera moved `blocks` back along the view direction
/// (vanilla's `Frustum.offset`): the sides open up near the camera and the near plane
/// moves behind it, so what sits just behind or beside the camera stays inside.
///
/// The view direction is the normal of the depth planes (the two are opposite), signed
/// towards where the side planes point. A frustum that has no direction to pull along
/// comes back unchanged: a box with no depth planes (the shadow pass's), and a box whose
/// sides are parallel to the view direction (an orthographic projection), where the side
/// normals cancel and say nothing about which way is forward.
pub fn pulled_back(&self, blocks: f32) -> Frustum {
let sides: Vec3 = self.planes[..4].iter().map(|p| p.truncate()).sum();
let depth = self.planes[4].truncate();
let along = depth.dot(sides);
// A perspective frustum's four side normals each lean forward, so this is well above 1.
if along.abs() < 1.0e-3 {
return *self;
}
let toward_sides = if along > 0.0 { depth } else { -depth };
let axis = toward_sides.normalize_or_zero();
let mut planes = self.planes;
for plane in &mut planes {
plane.w += blocks * plane.truncate().dot(axis);
}
Frustum { planes }
}
/// The frustum of a camera-relative `view_proj`, for tests outside this module.
#[cfg(test)]
pub(crate) fn from_view_projection(view_proj: glam::Mat4) -> Frustum {
Frustum {
planes: super::frustum(view_proj),
}
}
}
#[cfg(test)]
mod tests {
use super::{Frustum, Vec3};
use crate::gfx::world_projection;
use glam::Mat4;
const FOV: f32 = 70.0;
const ASPECT: f32 = 16.0 / 9.0;
const FAR: f32 = 512.0;
const EPS: f32 = 0.01;
fn looking_down_minus_z() -> Frustum {
Frustum::from_view_projection(world_projection(FOV, ASPECT, FAR))
}
fn tangents() -> (f32, f32) {
let up = (FOV / 2.0).to_radians().tan();
(up * ASPECT, up)
}
/// Each of the six planes of the unmoved frustum, a point just inside and one just outside,
/// from the field of view worked out by hand.
#[test]
fn a_point_is_inside_only_within_all_six_planes() {
let view = looking_down_minus_z();
let (tan_x, tan_y) = tangents();
let depth = 10.0;
let inside = [
Vec3::new(0.0, 0.0, -depth),
Vec3::new(depth * tan_x - EPS, 0.0, -depth),
Vec3::new(-(depth * tan_x - EPS), 0.0, -depth),
Vec3::new(0.0, depth * tan_y - EPS, -depth),
Vec3::new(0.0, -(depth * tan_y - EPS), -depth),
Vec3::new(0.0, 0.0, -0.06),
Vec3::new(0.0, 0.0, -(FAR - 0.1)),
];
let outside = [
Vec3::new(depth * tan_x + EPS, 0.0, -depth),
Vec3::new(-(depth * tan_x + EPS), 0.0, -depth),
Vec3::new(0.0, depth * tan_y + EPS, -depth),
Vec3::new(0.0, -(depth * tan_y + EPS), -depth),
Vec3::new(0.0, 0.0, -0.04),
Vec3::new(0.0, 0.0, -(FAR + 0.1)),
Vec3::new(0.0, 0.0, 1.0),
Vec3::new(0.0, 0.0, 0.0),
];
for p in inside {
assert!(view.contains_point(p), "{p} should be inside");
}
for p in outside {
assert!(!view.contains_point(p), "{p} should be outside");
}
assert!(view.contains_point(Vec3::NAN), "an unknown point is kept");
}
/// Camera 3 blocks back: its apex is at z = 3, so the sides open by 3 * tan, the near
/// plane is at z = 3 - 0.05 and the far plane at z = 3 - FAR.
#[test]
fn pulling_the_camera_back_moves_every_plane() {
let (tan_x, tan_y) = tangents();
let back = looking_down_minus_z().pulled_back(3.0);
let inside = [
Vec3::new(0.0, 0.0, 2.9),
Vec3::new(3.0 * tan_x - EPS, 0.0, 0.0),
Vec3::new(-(3.0 * tan_x - EPS), 0.0, 0.0),
Vec3::new(0.0, 3.0 * tan_y - EPS, 0.0),
Vec3::new(0.0, -(3.0 * tan_y - EPS), 0.0),
Vec3::new(0.0, 0.0, 3.0 - FAR + 0.1),
];
let outside = [
Vec3::new(0.0, 0.0, 3.0),
Vec3::new(3.0 * tan_x + EPS, 0.0, 0.0),
Vec3::new(-(3.0 * tan_x + EPS), 0.0, 0.0),
Vec3::new(0.0, 3.0 * tan_y + EPS, 0.0),
Vec3::new(0.0, -(3.0 * tan_y + EPS), 0.0),
Vec3::new(0.0, 0.0, 3.0 - FAR - 0.1),
];
for p in inside {
assert!(back.contains_point(p), "{p} should be inside");
}
for p in outside {
assert!(!back.contains_point(p), "{p} should be outside");
}
// The unmoved frustum does not have the point that only the offset one has.
assert!(!looking_down_minus_z().contains_point(Vec3::new(0.0, 0.0, 2.9)));
// An offset of nothing changes no verdict.
let same = looking_down_minus_z();
let unmoved = same.pulled_back(0.0);
for p in [
Vec3::new(1.0, 2.0, -3.0),
Vec3::new(0.0, 0.0, 1.0),
Vec3::new(40.0, 0.0, -5.0),
] {
assert_eq!(same.contains_point(p), unmoved.contains_point(p));
}
}
/// The offset follows the camera's own view direction, whatever way it looks.
#[test]
fn the_offset_is_along_the_view_direction() {
for (yaw, pitch) in [(0.3_f32, 0.0_f32), (2.0, -0.5), (-1.2, 0.9), (3.0, 1.2)] {
let pose = Mat4::from_rotation_x(pitch) * Mat4::from_rotation_y(yaw);
let view = Frustum::from_view_projection(world_projection(FOV, ASPECT, FAR) * pose);
let forward = pose.inverse().transform_vector3(-Vec3::Z);
let back = view.pulled_back(3.0);
assert!(
back.contains_point(forward * -2.9),
"{yaw} {pitch}: 2.9 behind"
);
assert!(
!back.contains_point(forward * -3.0),
"{yaw} {pitch}: 3 behind"
);
assert!(
!view.contains_point(forward * -2.9),
"{yaw} {pitch}: unmoved"
);
assert!(back.contains_point(forward * 20.0) && view.contains_point(forward * 20.0));
}
}
/// An orthographic box has no apex to pull back from: its side normals cancel, so there is
/// no direction, and the frustum must come back as it was.
#[test]
fn an_orthographic_frustum_stays_where_it_is() {
let ortho =
Frustum::from_view_projection(Mat4::orthographic_rh(-8.0, 8.0, -4.5, 4.5, 100.0, 0.05));
let moved = ortho.pulled_back(3.0);
for p in [
Vec3::new(0.0, 0.0, 2.0),
Vec3::new(0.0, 0.0, -9.0),
Vec3::new(7.9, 4.4, -9.0),
Vec3::new(8.1, 0.0, -9.0),
Vec3::new(0.0, 0.0, -101.0),
] {
assert_eq!(ortho.contains_point(p), moved.contains_point(p), "{p}");
}
}
/// The shadow pass's box has no depth planes, so no direction: it must not move.
#[test]
fn a_frustum_without_depth_planes_stays_where_it_is() {
let mut flat = looking_down_minus_z();
flat.planes[4] = glam::Vec4::W;
flat.planes[5] = glam::Vec4::W;
let moved = flat.pulled_back(3.0);
for p in [
Vec3::new(0.0, 0.0, 2.0),
Vec3::new(0.0, 0.0, -9.0),
Vec3::new(80.0, 0.0, -9.0),
] {
assert_eq!(flat.contains_point(p), moved.contains_point(p));
}
}
}
@@ -239,17 +239,17 @@ impl Visbuffer {
encoder: &'e mut wgpu::CommandEncoder,
depth: &wgpu::TextureView,
clear: bool,
timing: Option<&mut PassTiming>,
) -> wgpu::RenderPass<'e> {
mut timing: Option<&mut PassTiming>,
) -> super::pack_timing::CountedPass<'e> {
let (ids, _) = self.ids.as_ref().expect("fitted before the world pass");
let name = if clear {
"Visibility IDs"
} else {
"Visibility IDs after culling"
};
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
let pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon visibility buffer"),
timestamp_writes: timing.and_then(|t| t.writes(name)),
timestamp_writes: timing.as_deref_mut().and_then(|t| t.writes(name)),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: ids,
resolve_target: None,
@@ -272,7 +272,8 @@ impl Visbuffer {
stencil_ops: None,
}),
..Default::default()
})
});
super::pack_timing::counted(timing, pass, super::pixel_count(depth), name)
}
/// Phase 1's solid calls into the IDs, as the normal passes draw them: the opaque
@@ -360,13 +360,13 @@ impl Post {
&mut self,
gain: bool,
settings: [f32; 4],
shares: [f32; 4],
gains: [f32; 4],
windows: [[f32; 4]; 2],
) {
// These uniforms do not change baked colour without gain. Keep compatibility
// history stable when only its final display settings change.
let key = Some(if gain {
(true, settings, shares, windows)
(true, settings, gains, windows)
} else {
(false, [0.0; 4], [0.0; 4], [[0.0; 4]; 2])
});
@@ -887,7 +887,7 @@ mod tests {
post.jitter([32, 32], true, Mat4::IDENTITY, DVec3::ZERO);
assert_eq!(post.taa_this_frame.jitter[2], 0.0);
eprintln!(
"TAA baked-light GPU checked gain, all settings/shares/windows and the first frame after a pack"
"TAA baked-light GPU checked gain, all settings/gains/windows and the first frame after a pack"
);
}
@@ -64,7 +64,7 @@ fn warp_fragment(in: TerrainOut, front: bool) -> Fragment {
let fog = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)) * globals.fog_color.a;
let mark = hdr_scene_alpha(mix(hdr_scene(in.scene.x, in.scene.y, hdr_facing()), globals.hdr_light.y, fog));
return vec4(hdr_written(finished.rgb, mark, globals.hdr_settings, globals.hdr_shares), finished.a);
return vec4(hdr_written(finished.rgb, mark, globals.hdr_settings, globals.hdr_gains), finished.a);
}
return frame_stored(finished);
}
+12 -35
View File
@@ -90,6 +90,8 @@ fn nits_setting(nits: u32) -> u32 {
/// Simple-level presets. `Custom` leaves every option as the player set it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Preset {
/// Every saving on, over the lowest settings (`preset::table`).
FullPerformance,
Performance,
Balanced,
Quality,
@@ -98,7 +100,8 @@ pub enum Preset {
Custom,
}
impl Preset {
pub const ALL: [Preset; 5] = [
pub const ALL: [Preset; 6] = [
Preset::FullPerformance,
Preset::Performance,
Preset::Balanced,
Preset::Quality,
@@ -107,6 +110,7 @@ impl Preset {
];
pub fn name(self) -> &'static str {
match self {
Preset::FullPerformance => "full_performance",
Preset::Performance => "performance",
Preset::Balanced => "balanced",
Preset::Quality => "quality",
@@ -116,6 +120,7 @@ impl Preset {
}
pub fn label(self) -> &'static str {
match self {
Preset::FullPerformance => "Full Performance",
Preset::Performance => "Performance",
Preset::Balanced => "Balanced",
Preset::Quality => "Quality",
@@ -773,9 +778,9 @@ pub struct Graphics {
pub cave_culling: bool,
/// Near solid terrain culled, and its draws listed, on the GPU (`gfx::gpu_culling`), where it
/// is offered (`gpu_culling_offer`). Off by default (GPU Culling, Performance graphics); it
/// applies at once, and no preset sets it. Every save writes it, so a default turned on later
/// needs a new key, as `batchTranslucent` did. Auto turns it on only where the CPU limits the
/// frame and it makes the frame faster (`autotune`).
/// applies at once, and every preset sets it to Auto. Every save writes it, so a default
/// turned on later needs a new key, as `batchTranslucent` did. Auto turns it on only where
/// the CPU limits the frame and it makes the frame faster (`autotune`).
pub gpu_culling: GpuCullingMode,
/// Skip drawing entities hidden behind opaque terrain, synchronously or asynchronously.
pub entity_culling: EntityCullingMode,
@@ -1280,37 +1285,9 @@ impl Graphics {
}
}
/// A preset's values for vanilla's options and Horizon's own.
pub fn apply_preset(preset: Preset, s: &mut crate::settings::Settings) {
let (rd, sim, clouds, particles, shadows, blend, mipmaps, entity, leaves, weather_r) =
match preset {
Preset::Performance => (8, 6, "false", 2, false, 0, 0, 0.5, false, 3),
Preset::Balanced => (12, 8, "fast", 1, true, 1, 2, 0.75, true, 5),
Preset::Quality => (16, 12, "true", 0, true, 2, 4, 1.0, true, 10),
Preset::Ultra => (24, 12, "true", 0, true, 3, 4, 1.5, true, 10),
Preset::Custom => return,
};
s.render_distance = rd;
s.simulation_distance = sim;
s.clouds = clouds.into();
s.particles = particles;
s.entity_shadows = shadows;
s.biome_blend = blend;
s.mipmap_levels = mipmaps;
s.entity_distance = entity;
s.cutout_leaves = leaves;
s.weather_radius = weather_r;
s.graphics_preset = "custom".into();
let g = &mut s.horizon;
g.preset = preset;
g.cave_culling = true;
g.animated_textures = true;
g.chunk_updates = 0;
g.upload_budget_kib = 0;
g.sky = true;
g.fog = true;
g.weather = true;
}
#[path = "graphics_preset.rs"]
mod preset;
pub use preset::apply_preset;
#[cfg(test)]
mod tests {
@@ -0,0 +1,169 @@
//! The graphics presets: each one a fixed table of the options it sets, vanilla's and
//! Horizon's own, so that picking one gives the same settings whatever was set before.
//! Every preset turns on the optimizations that leave the picture as it is; Full
//! Performance adds the ones that change it. What no table names keeps the player's
//! choice: the display preferences (`graphics_ui`'s `touched`), Far Detail and Leaf
//! Culling, which follow the machine and the look the player picked, and Translucent
//! Batching, on unless the player turned it off.
use super::{EntityCullingMode, GpuCullingMode, ParticleCullingMode, Preset, Upscaling};
use crate::settings::Settings;
/// What differs between the presets. Every one of them also turns on entity and particle
/// culling on a worker, the block-entity caches and GPU Culling's Auto (which tries it only
/// where it makes frames faster), keeps cave culling, the sky, the fog, the weather and the
/// animated textures on, uploads meshes unthrottled and draws at a fixed resolution without
/// TAA.
struct Table {
render_distance: i32,
simulation_distance: i32,
/// `options.txt`'s `renderClouds`: `false`, `fast` or `true`.
clouds: &'static str,
/// 0 all, 1 decreased, 2 minimal.
particles: u8,
entity_shadows: bool,
biome_blend: i32,
mipmap_levels: i32,
entity_distance: f32,
cutout_leaves: bool,
weather_radius: i32,
/// Far terrain's range in chunks; 0 is off.
lod_distance: u32,
opaque_ice: bool,
resolution_scale: u32,
fxaa: bool,
dither_cutout_mips: bool,
}
fn table(preset: Preset) -> Option<Table> {
Some(match preset {
Preset::FullPerformance => Table {
render_distance: 6,
simulation_distance: 5,
clouds: "false",
particles: 2,
entity_shadows: false,
biome_blend: 0,
mipmap_levels: 0,
entity_distance: 0.5,
cutout_leaves: false,
weather_radius: 3,
lod_distance: 0,
opaque_ice: true,
resolution_scale: 75,
fxaa: false,
dither_cutout_mips: false,
},
Preset::Performance => Table {
render_distance: 8,
simulation_distance: 6,
clouds: "false",
particles: 2,
entity_shadows: false,
biome_blend: 0,
mipmap_levels: 0,
entity_distance: 0.5,
cutout_leaves: false,
weather_radius: 3,
lod_distance: 0,
opaque_ice: false,
resolution_scale: 100,
fxaa: false,
dither_cutout_mips: false,
},
Preset::Balanced => Table {
render_distance: 12,
simulation_distance: 8,
clouds: "fast",
particles: 1,
entity_shadows: true,
biome_blend: 1,
mipmap_levels: 2,
entity_distance: 0.75,
cutout_leaves: true,
weather_radius: 5,
lod_distance: 0,
opaque_ice: false,
resolution_scale: 100,
fxaa: false,
dither_cutout_mips: false,
},
Preset::Quality => Table {
render_distance: 16,
simulation_distance: 12,
clouds: "true",
particles: 0,
entity_shadows: true,
biome_blend: 2,
mipmap_levels: 4,
entity_distance: 1.0,
cutout_leaves: true,
weather_radius: 10,
lod_distance: 64,
opaque_ice: false,
resolution_scale: 100,
fxaa: true,
dither_cutout_mips: false,
},
Preset::Ultra => Table {
render_distance: 24,
simulation_distance: 12,
clouds: "true",
particles: 0,
entity_shadows: true,
biome_blend: 3,
mipmap_levels: 4,
entity_distance: 1.5,
cutout_leaves: true,
weather_radius: 10,
lod_distance: 128,
opaque_ice: false,
resolution_scale: 100,
fxaa: true,
dither_cutout_mips: true,
},
Preset::Custom => return None,
})
}
/// Sets what `preset`'s table names, in vanilla's options and Horizon's own.
pub fn apply_preset(preset: Preset, s: &mut Settings) {
let Some(t) = table(preset) else { return };
s.render_distance = t.render_distance;
s.simulation_distance = t.simulation_distance;
s.clouds = t.clouds.into();
s.particles = t.particles;
s.entity_shadows = t.entity_shadows;
s.biome_blend = t.biome_blend;
s.mipmap_levels = t.mipmap_levels;
s.entity_distance = t.entity_distance;
s.cutout_leaves = t.cutout_leaves;
s.weather_radius = t.weather_radius;
s.graphics_preset = "custom".into();
let g = &mut s.horizon;
g.preset = preset;
g.lod_distance = t.lod_distance;
g.cave_culling = true;
g.gpu_culling = GpuCullingMode::Auto;
g.entity_culling = EntityCullingMode::Asynchronous;
g.particle_culling = ParticleCullingMode::Asynchronous;
g.opaque_ice = t.opaque_ice;
g.cache_shulker_boxes = true;
g.cache_signs = true;
g.cache_decorated_pots = true;
g.cache_bells = true;
g.cache_chests = true;
g.cache_banners = true;
g.cache_copper_golem_statues = true;
g.chunk_updates = 0;
g.upload_budget_kib = 0;
g.sky = true;
g.fog = true;
g.weather = true;
g.animated_textures = true;
g.dither_cutout_mips = t.dither_cutout_mips;
g.resolution_scale = t.resolution_scale;
g.dynamic_resolution = false;
g.fxaa = t.fxaa;
g.taa = false;
g.upscaling = Upscaling::Native;
}
+32 -28
View File
@@ -853,7 +853,7 @@ impl H {
fn label(self, s: &Settings, out: &EffectiveOutput) -> Text {
let g = &s.horizon;
match self {
H::Preset => labelled("Preset", g.preset.label()),
H::Preset => labelled("Horizon Preset", g.preset.label()),
H::LodDistance => match g.lod_distance {
0 => labelled("LOD Distance", "Off"),
n => labelled("LOD Distance", lang::tr("%s chunks", &[&n])),
@@ -1296,7 +1296,6 @@ impl Item {
| H::GraphicsApi
| H::TranslucentBatching
| H::HdrSmoothGradients
| H::GpuCulling
)
| Item::Vanilla(
Opt::GuiScale
@@ -1753,6 +1752,14 @@ mod tests {
ui.set_search("tearing");
let found = ui.listed(&s, SIZE);
assert!(found.iter().any(|(_, i)| *i == Item::Vanilla(Opt::Vsync)));
// Both presets answer "preset"; Horizon's own, named apart from vanilla's, answers its name.
ui.set_search("preset");
let found = ui.listed(&s, SIZE);
let general = |item| (Page::General, item);
assert!(found.contains(&general(Item::Horizon(H::Preset))));
assert!(found.contains(&general(Item::Vanilla(Opt::Preset))));
ui.set_search("horizon preset");
assert_eq!(ui.listed(&s, SIZE), [general(Item::Horizon(H::Preset))]);
ui.set_search("hdr");
let [x, y, w, h] = cols.page(Page::ALL.len() - 1);
press(&mut ui, &mut s, (x + w / 2.0, y + h / 2.0));
@@ -2225,9 +2232,18 @@ mod tests {
fn presets_set_vanilla_and_horizon_options() {
let mut s = Settings::default();
Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480], &NONE);
assert_eq!(s.horizon.preset, Preset::FullPerformance);
assert_eq!(s.render_distance, 6);
assert_eq!(s.clouds, "false");
assert_eq!(s.horizon.resolution_scale, 75);
assert_eq!(s.horizon.entity_culling, EntityCullingMode::Asynchronous);
assert!(s.horizon.opaque_ice && s.horizon.cache_chests);
// The next one puts back what only Full Performance lowers.
Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480], &NONE);
assert_eq!(s.horizon.preset, Preset::Performance);
assert_eq!(s.render_distance, 8);
assert_eq!(s.clouds, "false");
assert_eq!(s.horizon.resolution_scale, 100);
assert!(!s.horizon.opaque_ice && s.horizon.cache_chests);
// Any quality change leaves the preset.
Item::Vanilla(Opt::Clouds).cycle(&mut s, false, [854, 480], &NONE);
assert_eq!(s.horizon.preset, Preset::Custom);
@@ -2235,6 +2251,14 @@ mod tests {
Item::Horizon(H::Preset).cycle(&mut s, true, [854, 480], &NONE);
Item::Vanilla(Opt::Vsync).cycle(&mut s, false, [854, 480], &NONE);
assert_eq!(s.horizon.preset, Preset::Ultra);
// Ultra keeps the optimizations that leave the picture as it is, and no others.
assert_eq!(s.horizon.entity_culling, EntityCullingMode::Asynchronous);
assert_eq!(s.horizon.gpu_culling, GpuCullingMode::Auto);
assert_eq!((s.horizon.lod_distance, s.horizon.fxaa), (128, true));
assert_eq!(
(s.horizon.resolution_scale, s.horizon.opaque_ice),
(100, false)
);
}
#[test]
@@ -2249,7 +2273,7 @@ mod tests {
assert_eq!(seen, [2, 4, 8, 1]);
Item::Horizon(H::ScreenshotQuality).cycle(&mut s, true, [854, 480], &NONE);
assert_eq!(s.horizon.screenshot_quality, 8);
assert_eq!(s.horizon.preset, Preset::Performance);
assert_eq!(s.horizon.preset, Preset::FullPerformance);
}
#[test]
@@ -2297,14 +2321,6 @@ mod tests {
let item = Item::Horizon(H::EntityCulling);
assert_eq!(s.horizon.entity_culling, EntityCullingMode::Off);
assert_eq!(item.label(&s, &NONE).plain(), "Entity Culling: Off");
for mode in EntityCullingMode::ALL {
s.horizon.entity_culling = mode;
for preset in Preset::ALL {
crate::graphics::apply_preset(preset, &mut s);
assert_eq!(s.horizon.entity_culling, mode);
}
}
s.horizon.entity_culling = EntityCullingMode::Off;
let mut ui = ui();
let r = row(&mut ui, &s, item);
for mode in [
@@ -2333,10 +2349,6 @@ mod tests {
assert_eq!(item.label(&s, &NONE).plain(), "Particle Culling: Off");
for mode in ParticleCullingMode::ALL {
s.horizon.particle_culling = mode;
for preset in Preset::ALL {
crate::graphics::apply_preset(preset, &mut s);
assert_eq!(s.horizon.particle_culling, mode);
}
assert_eq!(
crate::graphics::Graphics::parse(&s.horizon.serialize()).particle_culling,
mode
@@ -2530,8 +2542,8 @@ mod tests {
}
}
/// GPU Culling: Off, On or Auto right after Cave Culling, off by default, no part of a
/// preset, and greyed out with its reason, reading Off, wherever it isn't offered.
/// GPU Culling: Off, On or Auto right after Cave Culling, off by default, and greyed out
/// with its reason, reading Off, wherever it isn't offered.
#[test]
fn gpu_culling_steps_off_on_auto_where_it_is_offered() {
use crate::graphics::GpuCullingOffer;
@@ -2570,7 +2582,7 @@ mod tests {
assert!(key(&mut ui, &mut s, K::Enter).is_empty());
assert_eq!(s.horizon.gpu_culling, GpuCullingMode::On, "{offer:?}");
}
// Where it is, it steps through its three values and keeps the preset.
// Where it is, it steps through its three values and leaves the preset.
crate::graphics::offer_gpu_culling(GpuCullingOffer::Offered);
assert_eq!(item.blocked(&s, &NONE), None);
for label in ["Auto", "Off", "On"] {
@@ -2586,18 +2598,10 @@ mod tests {
}
item.cycle(&mut s, true, FB, &NONE);
assert_eq!(s.horizon.gpu_culling, GpuCullingMode::Off);
assert_eq!(s.horizon.preset, Preset::Balanced);
assert_eq!(s.horizon.preset, Preset::Custom);
// Auto says what it does.
s.horizon.gpu_culling = GpuCullingMode::Auto;
assert!(description(item, &s, &NONE, "").starts_with("Auto: "));
// No preset sets it.
for mode in GpuCullingMode::ALL {
s.horizon.gpu_culling = mode;
for preset in Preset::ALL {
crate::graphics::apply_preset(preset, &mut s);
assert_eq!(s.horizon.gpu_culling, mode, "{preset:?}");
}
}
}
#[test]
+50 -26
View File
@@ -20,15 +20,20 @@ struct Params {
black: f32,
// The HUD and menus' brightness as a share of paper white.
ui: f32,
// HDR lighting: what the strongest light multiplies a surface by, 1 for none.
// The compatibility frame's lift (`lit`; the float frame's writers have theirs from
// Hdr::draw_params). HDR lighting: what the strongest light multiplies a surface by, 1 for
// none.
scene: f32,
// Per tier, low to very bright (hdr.rs `Tier`): the share of the headroom
// Per tier, low to very bright (hdr.rs `COMPAT_SHARES`): the share of the headroom
// its fully lifted pixels get.
share: vec4<f32>,
// HDR calibration (hdr_calibration.rs): x its step (0 none, 1 black level,
// 2 peak, 3 paper white), y the slider in nits, z where its controls start,
// a share of the height.
calibration: vec4<f32>,
// The scene's peak in units of paper white where Horizon lifts the world (hdr.rs
// `SCENE_PEAK`), else 0: what the tone curve maps onto the display's peak (`tone_scale`).
scene_peak: f32,
};
@group(0) @binding(2) var<uniform> params: Params;
// Horizon's logo, 1 inside, 0 outside, for calibration's test pictures.
@@ -155,7 +160,7 @@ fn calibration_nits(p: vec2<f32>, size: vec2<f32>) -> f32 {
}
fn lit(f: vec3<f32>, a: f32, shows: bool, eased: bool) -> Lit {
return hdr_mark_light(f, a, shows, eased, vec4(params.peak, params.scene, params.world, params.debug), params.share);
return hdr_mark_light(f, a, shows, eased, vec4(params.peak, params.scene, params.world, params.debug), (params.peak - 1.0) * params.share);
}
// Calibration: above its controls the test picture, straight in nits, past
@@ -251,33 +256,52 @@ fn display(light: vec3<f32>, pos: vec4<f32>) -> vec4<f32> {
return display(light, pos);
}
// The tone curve's knee: up to it light stays as it is. Where HDR lighting eased into the peak
// before the curve (`lit`), 60% of it, so bright textures keep their detail; at least paper white.
// Where the scene's peak is unknown (`tone_scale`), the curve's knee: up to it light stays as it
// is. Where HDR lighting eased into the peak before the curve (`lit`), 60% of it, so bright
// textures keep their detail; at least paper white.
fn tone_knee(headroom: f32) -> f32 {
return max(0.6 * headroom, 1.0);
}
// The tone curve on light whose brightest channel is `top`, in units of paper white `paper`
// nits: what to scale the light by, so it ends at most `headroom` (above 1). ITU-R BT.2390's
// EETF in PQ, without the black level lift (`display` does that): the same up to its knee, then
// a Hermite spline that reaches the peak level, at the source's peak. That peak is where the knee
// lands at `tone_knee`, PQ's 10 000 nits at most; light past it shows at the peak. The brightest
// channel sets the scale for all three, so light keeps its hue as it eases (lava stays orange)
// and no channel passes the peak.
fn tone_scale(top: f32, headroom: f32, paper: f32) -> f32 {
if top <= tone_knee(headroom) {
return 1.0;
}
// The tone curve on light whose brightest channel is `top`, in units of paper white `paper` nits:
// what to scale the light by, so it ends at most `headroom` (T). ITU-R BT.2390's EETF in PQ,
// without the black level lift (`display` does that): the same up to its knee, then a Hermite
// spline reaching T at the source's peak, past which light shows at T. The brightest channel sets
// the scale for all three, so light keeps its hue (lava stays orange) and no channel passes T.
//
// The source is the scene's peak S where Horizon lifts the world (`scene_peak`, hdr.rs
// `SCENE_PEAK`): the world's light is the same on every display, light past S is held at S, and
// where T reaches S that is all, so a display above S shows the world as one at S. Where the
// scene's range is unknown (`scene_peak` 0: a 0.2 pack's own light, HDR Lighting off), the
// source follows the display, as the 0.2 contract has it: the peak that puts the EETF's knee at
// `tone_knee`, PQ's 10 000 nits at most.
fn tone_scale(top: f32, scene_peak: f32, headroom: f32, paper: f32) -> f32 {
let peak = pq(vec3(headroom * paper)).x;
let source = min(3.0 * peak - 2.0 * pq(vec3(tone_knee(headroom) * paper)).x, 1.0);
let e = pq(vec3(top * paper)).x / source;
var source: f32;
var e: f32;
var held = 1.0;
if scene_peak > 0.0 {
held = min(1.0, scene_peak / max(top, 1e-6));
if scene_peak <= headroom {
return held;
}
source = pq(vec3(scene_peak * paper)).x;
e = pq(vec3(min(top, scene_peak) * paper)).x / source;
} else {
if top <= tone_knee(headroom) {
return 1.0;
}
source = min(3.0 * peak - 2.0 * pq(vec3(tone_knee(headroom) * paper)).x, 1.0);
e = pq(vec3(top * paper)).x / source;
}
let max_lum = peak / source;
let ks = 1.5 * max_lum - 0.5;
// At least 0: past 3 to 1 in PQ the knee would leave the source's range.
let ks = max(1.5 * max_lum - 0.5, 0.0);
if e >= 1.0 {
return headroom / top;
}
if e <= ks {
return 1.0;
return held;
}
let t = (e - ks) / (1.0 - ks);
let t2 = t * t;
@@ -287,16 +311,16 @@ fn tone_scale(top: f32, headroom: f32, paper: f32) -> f32 {
}
// Hdr::tonemap, after the post effects and before the camera overlays (docs/design/
// hdr-linear-light.md, `[tonemap]`): the light (`world` holds the frame) eased into the peak, in
// gamma, where scaling the light by s scales the stored colour by s^(1/2.2). Light up to the
// knee stays exactly as stored. With no headroom, a clip at white.
// hdr-linear-light.md, `[tonemap]`): the light (`world` holds the frame) fitted to the display, in
// gamma, where scaling the light by s scales the stored colour by s^(1/2.2). Light the curve
// leaves alone stays exactly as stored. With no headroom and no scene peak, a clip at white.
@fragment fn fs_tonemap(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let g = textureLoad(world, vec2<i32>(pos.xy), 0).rgb;
if params.peak <= 1.0 {
if params.scene_peak == 0.0 && params.peak <= 1.0 {
return vec4(min(g, vec3(1.0)), 1.0);
}
let top = pow(max(max(g.r, max(g.g, g.b)), 0.0), 2.2);
let s = tone_scale(top, params.peak, params.paper * 80.0);
let s = tone_scale(top, params.scene_peak, params.peak, params.paper * 80.0);
return vec4(select(g * pow(s, 1.0 / 2.2), g, s == 1.0), 1.0);
}
@@ -331,7 +355,7 @@ fn layered(at: vec2<i32>) -> vec3<f32> {
}
// Screenshots keep midtones at their drawn brightness, with a shoulder starting at 0.6
// paper white in linear light. Unlike the display curve (whose knee is at least white),
// paper white in linear light. Unlike the display curve (which ends at the display's peak),
// this has an unbounded source range: k + (1-k)*(top-k)/(top+1-2*k) approaches SDR
// white smoothly, with slope 1 at k. One scale keeps the world's linear RGB ratios.
fn screenshot_world(w: vec3<f32>) -> vec3<f32> {
@@ -27,7 +27,8 @@ struct Lit {
lifted: bool,
};
fn hdr_mark_light(f: vec3<f32>, a: f32, shows: bool, eased: bool, settings: vec4<f32>, shares: vec4<f32>) -> Lit {
// `lifts`, per tier: how much its fully lifted pixels gain over their own light (their gain - 1).
fn hdr_mark_light(f: vec3<f32>, a: f32, shows: bool, eased: bool, settings: vec4<f32>, lifts: vec4<f32>) -> Lit {
var lifted = false;
// Light over 1 (a float frame's) shows only where the world does and carries
// no mark (alpha 1), up to the peak: light written as light. Marked pixels clip
@@ -60,7 +61,7 @@ fn hdr_mark_light(f: vec3<f32>, a: f32, shows: bool, eased: bool, settings: vec4
let lift = 1.0 - clamp((a - 0.175 * f32(band)) / 0.165, 0.0, 1.0);
if lift > 0.0 {
let top = max(light.r, max(light.g, light.b));
var gain = 1.0 + (settings.x - 1.0) * shares[tier] * lift;
var gain = 1.0 + lifts[tier] * lift;
if eased {
gain = min(gain, settings.x / max(top, 1e-4));
}
@@ -88,7 +89,8 @@ fn hdr_quantized_mark(mark: f32) -> f32 {
return round(saturate(mark) * 255.0) / 255.0;
}
fn hdr_written(color: vec3<f32>, mark: f32, settings: vec4<f32>, shares: vec4<f32>) -> vec3<f32> {
let shows = settings.z > 0.5 && settings.x > 1.0;
return pow(hdr_mark_light(max(color, vec3(0.0)), hdr_quantized_mark(mark), shows, false, settings, shares).light, vec3(1.0 / 2.2));
// The world's writers' light, from the tiers' `gains` (Hdr::draw_params): the same on every
// display; the tone curve fits it to the display afterwards (fs_tonemap).
fn hdr_written(color: vec3<f32>, mark: f32, settings: vec4<f32>, gains: vec4<f32>) -> vec3<f32> {
return pow(hdr_mark_light(max(color, vec3(0.0)), hdr_quantized_mark(mark), settings.z > 0.5, false, settings, gains - vec4(1.0)).light, vec3(1.0 / 2.2));
}
+34 -8
View File
@@ -16,6 +16,7 @@ use model_reducing::reducible_model_sprites;
mod animate;
pub mod cit_glint;
mod gui_sprite;
mod model_reducing;
mod pack_text;
pub mod pictures;
@@ -55,7 +56,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 = crate::packs::first_json(json.as_bytes())?;
let meta: serde_json::Value = crate::packs::first_json(json.as_bytes()).ok()?;
let section = meta.get("texture")?;
let flag = |key| section.get(key).and_then(serde_json::Value::as_bool) == Some(true);
let flags = Self {
@@ -388,7 +389,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 = crate::packs::first_json(mcmeta?.as_bytes())?;
let meta: serde_json::Value = crate::packs::first_json(mcmeta?.as_bytes()).ok()?;
AnimationMetadata::from_json(&meta.get("animation")?.to_string()).ok()
}
/// An animated strip's first frame: the region the mcmeta's frame size picks
@@ -1401,9 +1402,9 @@ impl HudAtlas {
edition.3 = pixels;
}
images.push(("horizon/white".into(), 4, 4, vec![255; 64]));
// The controller's art, unless a pack brought its own (walked above, as a mod's GUI
// textures are).
for image in crate::pad_glyph::images() {
// The controller's art and Horizon's mark, unless a pack brought its own (walked above, as a
// mod's GUI textures are).
for image in crate::pad_glyph::images().chain(crate::mark_sprite::image()) {
if !images.iter().any(|i| i.0 == image.0) {
images.push(image);
}
@@ -2466,9 +2467,8 @@ impl HudBatch {
);
}
}
InlineObject::Atlas { sprite, .. } => {
let key = sprite.strip_prefix("minecraft:").unwrap_or(sprite);
if let Some(rect) = atlas.sprites.get(key).copied() {
InlineObject::Atlas { .. } => {
if let Some(rect) = atlas.inline_object_sprite(object) {
self.rect_uv(x, y, 8.0, 8.0, rect, tint);
}
}
@@ -3773,6 +3773,32 @@ mod tests {
assert_eq!(banner.texels((atlas.width, atlas.height)), (16, 32));
}
#[test]
fn an_inline_atlas_sprite_resolves_in_its_named_atlas() {
let root =
std::env::temp_dir().join(format!("horizon-atlas-inline-{}", std::process::id()));
let gui = root.join("assets/minecraft/textures/gui/sprites/boss_bar");
fs::create_dir_all(&gui).unwrap();
write_strip(
&gui.join("pink_background.png"),
16,
16,
&[[1, 2, 3, 255]],
None,
);
let atlas = HudAtlas::build(&root).unwrap();
let _ = fs::remove_dir_all(&root);
let packed = atlas.sprites["gui/sprites/boss_bar/pink_background"];
let missing = atlas.sprites[MISSING_SPRITE];
let found = atlas
.inline_sprite("minecraft:gui", "minecraft:boss_bar/pink_background")
.unwrap();
assert_eq!((found.u0, found.v0), (packed.u0, packed.v0));
let none = atlas
.inline_sprite("minecraft:gui", "minecraft:boss_bar/nope")
.unwrap();
assert_eq!((none.u0, none.v0), (missing.u0, missing.v0));
}
#[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");
@@ -0,0 +1,41 @@
use super::{HudAtlas, MISSING_SPRITE, Rect};
/// The packed key of a GUI sprite id: `minecraft:boss_bar/pink_background` is
/// `gui/sprites/boss_bar/pink_background`, another namespace's `ns:gui/sprites/...`.
fn atlas_key_of_gui_sprite(id: &str) -> String {
match id.split_once(':') {
Some(("minecraft", path)) => format!("gui/sprites/{path}"),
Some((namespace, path)) => format!("{namespace}:gui/sprites/{path}"),
None => format!("gui/sprites/{id}"),
}
}
impl HudAtlas {
/// `AtlasGlyphProvider`: the sprite `sprite` of the atlas named `atlas`
/// (`minecraft:gui` keeps its sprites under `gui/sprites/`), or the missing
/// sprite when that atlas has none by that name.
pub fn inline_sprite(&self, atlas: &str, sprite: &str) -> Option<Rect> {
let plain = sprite.strip_prefix("minecraft:").unwrap_or(sprite);
let gui = atlas_key_of_gui_sprite(sprite);
let gui_atlas = atlas.strip_prefix("minecraft:").unwrap_or(atlas) == "gui";
let (first, second) = if gui_atlas {
(gui.as_str(), plain)
} else {
(plain, gui.as_str())
};
self.sprites
.get(first)
.or_else(|| self.sprites.get(second))
.or_else(|| self.sprites.get(MISSING_SPRITE))
.copied()
}
/// `inline_sprite` for an inline atlas object; `None` for any other object.
pub(super) fn inline_object_sprite(&self, object: &crate::text::InlineObject) -> Option<Rect> {
match object {
crate::text::InlineObject::Atlas { atlas, sprite, .. } => {
self.inline_sprite(atlas, sprite)
}
_ => None,
}
}
}
@@ -39,14 +39,13 @@ 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.
// GuiGraphicsExtractor.textWithBackdrop adds two pixels around the
// text's advance and the font's nine-pixel line height.
out.push(fill(
x - 1,
y - 1,
x + w,
y + 9,
x - 2,
y - 2,
x + w + 2,
y + 11,
multiply(background, color),
));
}
@@ -1491,10 +1490,10 @@ mod boss_bar_room_tests {
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.
/// `GuiGraphicsExtractor.textWithBackdrop`: two pixels around the advance
/// and the nine-pixel font line, independently of glyph-background drawing.
#[test]
fn the_backdrop_frames_the_glyphs_by_one_pixel() {
fn the_backdrop_frames_the_text_by_two_pixels() {
let mut out = Vec::new();
text_with_backdrop(
&mut out,
@@ -1508,6 +1507,6 @@ mod backdrop_tests {
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));
assert_eq!((*x0, *y0, *x1, *y1), (8, 18, 18, 31));
}
}
+4
View File
@@ -74,6 +74,7 @@ pub mod level_loading;
pub mod light;
pub mod lod;
pub mod logging;
pub mod mark_sprite;
pub mod menu_blur;
pub mod menu_style;
pub mod mesher;
@@ -102,6 +103,9 @@ pub mod pad_glyph;
pub mod paged_maps;
pub mod par;
pub mod particles;
#[cfg(target_os = "linux")]
pub mod perf_capture;
pub mod perf_gpu;
pub mod poi_sections;
pub mod polytone_post;
pub mod post_chain;
+31 -7
View File
@@ -9,6 +9,7 @@ use crate::{
};
pub mod bake;
pub mod cache;
mod detail;
mod kept;
mod mesh;
pub mod packed;
@@ -2387,13 +2388,6 @@ impl Lod {
self.shared.mesh_wake.notify_all();
}
}
/// Reduced far detail (`graphics::FarDetail::Reduced`): the next update
/// replans when it changes, and tiles sampled from then on approximate
/// wide cells (`GeneratorWorker::lod_grid`).
pub fn set_reduced_detail(&mut self, reduced: bool) {
self.reduced_detail = reduced;
self.shared.approximate.store(reduced, Ordering::Relaxed);
}
fn held(&self) -> bool {
self.small && self.near_loading
}
@@ -6115,4 +6109,34 @@ mod tests {
assert!(lod.stale.contains(&key));
assert_eq!(queued(&mut lod), [key]);
}
#[test]
fn changing_far_detail_samples_tiles_again() {
for level in [0, 1, 2, 3, 5] {
let mut lod = Lod::scheduler_for_test();
let key = TileKey { x: 0, z: 0, level };
lod.plan.nodes.insert(key);
lod.active.insert(key);
lod.ready.insert(key, Arc::new(samples(70)));
assert!(
queued(&mut lod).is_empty(),
"level {level}: sampled tile is not asked again"
);
lod.set_reduced_detail(true);
assert!(
lod.ready.contains_key(&key),
"level {level}: old samples stay"
);
assert_eq!(queued(&mut lod), [key], "level {level}: not sampled again");
lod.finish_sample(key, samples(70));
lod.set_reduced_detail(true);
assert!(queued(&mut lod).is_empty(), "level {level}: same value");
lod.set_reduced_detail(false);
assert_eq!(
queued(&mut lod),
[key],
"level {level}: not sampled again on the way back"
);
}
}
}
@@ -0,0 +1,23 @@
//! Reduced far detail.
use super::*;
impl Lod {
/// Reduced far detail (`graphics::FarDetail::Reduced`): the next update
/// replans when it changes, and tiles sampled from then on approximate
/// wide cells (`GeneratorWorker::lod_grid`).
pub fn set_reduced_detail(&mut self, reduced: bool) {
if self.reduced_detail != reduced {
let keys: Vec<_> = self
.ready
.keys()
.chain(self.pending.iter())
.copied()
.collect();
for key in keys {
self.mark_stale(key);
}
}
self.reduced_detail = reduced;
self.shared.approximate.store(reduced, Ordering::Relaxed);
}
}
@@ -0,0 +1,11 @@
//! Horizon's mark (`docs/media/brand/mark-dark.svg`) on the text grid, for an inline text sprite.
/// The mark's name in the HUD atlas.
pub const SPRITE: &str = "horizon:gui/mark";
const PNG: &[u8] = include_bytes!("../../horizon-client/assets/horizon/textures/gui/mark.png");
/// The mark as the HUD atlas takes an image.
pub fn image() -> std::iter::Once<(String, u32, u32, Vec<u8>)> {
let (width, height, rgba) = crate::hud::decode_bytes(PNG).expect("Horizon's mark is PNG");
std::iter::once((SPRITE.to_owned(), width, height, rgba))
}
@@ -24,7 +24,7 @@ fn oit_cloud_color(in: Out, front: bool, fade: bool) -> vec4<f32> {
var color = oit_cloud_color(in, front, true);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
color = vec4(hdr_written(color.rgb, hdr_scene_alpha(globals.hdr_light.y),
globals.hdr_settings, globals.hdr_shares), color.a);
globals.hdr_settings, globals.hdr_gains), color.a);
}
let seen = oit_sample_transmittance(vec2<i32>(in.clip.xy),
oit_normalize_depth(in.clip.z, in.clip.xy), 1.0 - color.a);
@@ -62,7 +62,7 @@
@fragment fn fs_oit_lightning_accumulate(in: Out) -> @location(0) vec4<f32> {
var color = celestial_color(in);
if HDR_WRITE_LIGHT && globals.hdr_light.w != 0.0 {
color = vec4(hdr_written(color.rgb, hdr_entity_mark(in), globals.hdr_settings, globals.hdr_shares), color.a);
color = vec4(hdr_written(color.rgb, hdr_entity_mark(in), globals.hdr_settings, globals.hdr_gains), color.a);
}
return oit_accumulate_additive(vec4(color.rgb, min(0.99, color.a)), 0.0, in.clip);
}
@@ -41,7 +41,7 @@ fn oit_terrain_color(in: TerrainOut) -> vec4<f32> {
globals.hdr_light.y, f * globals.fog_color.a));
// Convert the surface before weighting; its mark never belongs to the light behind it.
let fogged = mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a);
return vec4(hdr_written(fogged, mark, globals.hdr_settings, globals.hdr_shares) * weighted.a, weighted.a);
return vec4(hdr_written(fogged, mark, globals.hdr_settings, globals.hdr_gains) * weighted.a, weighted.a);
}
return vec4(rgb, weighted.a);
}
+34 -46
View File
@@ -1594,9 +1594,9 @@ pub struct OptionsUi {
radial_pick: shell::Shell<crate::radial_editor::PickScreen>,
/// Shaders: the shader packs and the picked one's options, on the settings shell.
shader: shell::Shell<crate::shader_ui::ShaderScreen>,
/// The Pack Options page, and the packs' Polytone config entries by pack id (the game
/// fills them beside `pack_infos`).
pub pack_options: crate::pack_options_ui::PackOptionsUi,
/// Pack Options, on the settings shell, and the packs' Polytone config entries by pack id
/// (the game fills them beside `pack_infos`).
pack_options: shell::Shell<crate::pack_options_ui::PackOptionsScreen>,
pub pack_configs: std::collections::BTreeMap<String, horizon_polytone::pack::Configs>,
pub split_profiles: crate::split_profiles::SplitProfiles,
/// HDR calibration while its page is open.
@@ -3401,10 +3401,6 @@ impl OptionsUi {
c.draw(batch, atlas, cursor);
return;
}
if self.page() == Page::PackOptions {
self.pack_options.draw(batch, atlas, cursor, self.in_world);
return;
}
let waiting = self.waiting();
let in_world = self.in_world;
if self.draw_radial_name(batch, atlas, cursor, in_world) {
@@ -3786,20 +3782,6 @@ impl OptionsUi {
});
return self.shell_events(s, outputs);
}
if self.page() == Page::PackOptions {
let mut events = Vec::new();
for action in self
.pack_options
.click((x, y), size, drag, right || self.shift)
{
match action {
crate::pack_options_ui::Action::ButtonClick => events.push(Event::ButtonClick),
crate::pack_options_ui::Action::SliderDrag => {}
crate::pack_options_ui::Action::Done => events.extend(self.back(s)),
}
}
return events;
}
if self.page() == Page::Packs {
let mut events = Vec::new();
if drag {
@@ -3829,14 +3811,7 @@ impl OptionsUi {
crate::pack_screen::Action::BrowsePick(i) => {
events.push(Event::DownloadPack(i));
}
crate::pack_screen::Action::Options(id) => {
let mut configs = horizon_polytone::pack::Configs::default();
if let Some(own) = self.pack_configs.get(&id) {
configs.merge(own);
}
self.pack_options = crate::pack_options_ui::PackOptionsUi::open(configs);
self.push(Page::PackOptions);
}
crate::pack_screen::Action::Options(id) => self.open_pack_options(&id),
crate::pack_screen::Action::None => {}
}
return events;
@@ -4074,7 +4049,6 @@ impl OptionsUi {
// release, even if the pointer has left the widget or its value stayed.
let slider = self.dragging.take().is_some();
let shell_slider = self.shell_mut().and_then(|shell| shell.release());
self.pack_options.release();
let calibration_slider = self.calibration.as_mut().is_some_and(|c| c.release());
let split_drop = self.split_setup.release();
if slider || shell_slider.is_some() || calibration_slider {
@@ -4168,10 +4142,6 @@ impl OptionsUi {
self.studio.wheel(amount);
return Vec::new();
}
if self.page() == Page::PackOptions {
self.pack_options.scroll(size, amount);
return Vec::new();
}
let plain = self.resource_error.is_none()
&& !(self.pack_screen.is_some() && self.stack.last() == Some(&Page::Packs));
if !plain {
@@ -4255,10 +4225,6 @@ impl OptionsUi {
self.studio.wheel(amount);
return;
}
if self.page() == Page::PackOptions {
self.pack_options.scroll(size, amount);
return;
}
match &mut self.pack_screen {
Some(p) if self.stack.last() == Some(&Page::Packs) => {
p.scroll(cursor.0 as f64, cursor.1 as f64, amount as f64)
@@ -4393,14 +4359,8 @@ impl OptionsUi {
self.can_change_value = false;
match page {
Page::PackOptions => {
let ui = std::mem::take(&mut self.pack_options);
if ui.changed {
let entries = ui.configs.entries().keys().cloned().collect();
events.push(Event::PackOptions {
entries,
chosen: ui.configs.chosen(),
});
}
let screen = std::mem::take(&mut self.pack_options.screen);
events.extend(screen.finished());
}
Page::ShaderOptions | Page::ShaderPacks => {
if s.shader_options.as_ref().is_some_and(|o| o.changed) {
@@ -4960,6 +4920,34 @@ mod tests {
/// A renderer whose destination offers nothing and whose display reports nothing.
const NONE: EffectiveOutput = EffectiveOutput::NONE;
#[test]
fn pack_options_leave_with_a_change_and_with_nothing_after_its_undo() {
use crate::settings_shell::Screen as _;
let mut s = Settings::default();
let atlas = HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets"));
let atlas = atlas.unwrap();
let mut ui = OptionsUi::default();
let mut configs = horizon_polytone::pack::Configs::default();
let birds = serde_json::json!({"default_value": true});
configs.add_entry("p:birds".into(), &birds);
ui.pack_configs.insert("pack".into(), configs);
for undone in [false, true] {
ui.open_pack_options("pack");
assert!(ui.shell().is_some(), "Pack Options is on the shell");
let birds = crate::pack_options_ui::Item::Entry(0);
ui.pack_options.screen.press(&mut s, birds, false);
if undone {
let before = s.clone();
ui.pack_options.screen.undo(&mut s, &before);
}
let events = ui.key(&mut s, &atlas, winit::keyboard::KeyCode::Escape, None);
let sent = events
.iter()
.any(|e| matches!(e, Event::PackOptions { .. }));
assert_eq!(sent, !undone, "undone: {undone}");
}
}
/// The window allows the input method only while `typing` says a search
/// box has the focus (`Game::text_field_focused`), so a page without one
/// must not claim the keys: the movement and menu keys keep working there.
@@ -23,6 +23,7 @@ impl OptionsUi {
Page::ControllerRadialPick => Some(&self.radial_pick),
page if Self::controller_page(page).is_some() => Some(&self.controller),
page if Self::shader_page(page).is_some() => Some(&self.shader),
Page::PackOptions => Some(&self.pack_options),
_ => None,
}
}
@@ -35,9 +36,20 @@ impl OptionsUi {
Page::ControllerRadialPick => Some(&mut self.radial_pick),
page if Self::controller_page(page).is_some() => Some(&mut self.controller),
page if Self::shader_page(page).is_some() => Some(&mut self.shader),
Page::PackOptions => Some(&mut self.pack_options),
_ => None,
}
}
/// Pack Options for the pack `id`, from the pack screen: its Polytone config entries.
pub(super) fn open_pack_options(&mut self, id: &str) {
let mut configs = horizon_polytone::pack::Configs::default();
if let Some(own) = self.pack_configs.get(id) {
configs.merge(own);
}
// Opening a shell starts it afresh: the entries go in after.
self.push(Page::PackOptions);
self.pack_options.screen = crate::pack_options_ui::PackOptionsScreen::open(configs);
}
/// Where the open shell screen asked the focus to open (a radial slot's list, on the slot's
/// action), for a controller's focus to land there.
pub fn shell_opened_focus(&self) -> Option<[f32; 4]> {
@@ -53,13 +65,14 @@ impl OptionsUi {
return;
}
// Every shell: the click may have changed the page.
let shells: [&mut dyn shell::Hosted; 6] = [
let shells: [&mut dyn shell::Hosted; 7] = [
&mut self.extras,
&mut self.graphics,
&mut self.controller,
&mut self.radial,
&mut self.radial_pick,
&mut self.shader,
&mut self.pack_options,
];
for shell in shells {
shell.clicks_step(false);
@@ -1,45 +1,36 @@
//! The Pack Options page (#11486): the config entries of the selected resource packs' Polytone
//! `config_entries` (wiki "Polytone Configs"), in the frame of Horizon's settings screens
//! (`settings_shell`). Numbers are sliders, texts cycle, booleans switch; the entries sit in
//! their `section`s, named by the packs' own translations. Leaving with Done keeps what changed,
//! and the packs load again with it.
use crate::widgets::Action as Declared;
//! The Pack Options screen (#11486), on the settings shell (`settings_shell`): the config entries
//! of the selected resource packs' Polytone `config_entries` (wiki "Polytone Configs"). Each
//! `section` is a page, named by the packs' own translations; numbers are sliders that stop at
//! the entry's `step`, value lists are choices, booleans switch and free text reads. The first
//! page starts with the pack-wide presets and Reset all. The shell gives it the keyboard, a
//! controller's focus, the search, the strip's descriptions and Undo; leaving keeps what differs
//! from how the screen opened, and the packs load again with it.
use crate::{
graphics_style as style,
hud::{HudAtlas, HudBatch},
lang,
settings_shell::{self as shell, Columns, Line, Lines},
text::Text,
ui,
settings::Settings,
settings_shell::{self as shell, Group, Output, Row, Sheet, Value},
};
use horizon_polytone::pack::{ConfigKind, ConfigValue, Configs};
/// What a click asks of the options screen.
/// A row: the pack-wide presets, Reset all, or the entry at an index of `ids`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
ButtonClick,
SliderDrag,
/// Done: leave, keeping what changed.
Done,
pub(crate) enum Item {
Presets,
ResetAll,
Entry(u16),
}
/// The page's state: the entries being edited, how they are listed, and the pointer's hold.
#[derive(Default)]
pub struct PackOptionsUi {
/// The selected packs' entries and the values being picked.
pub configs: Configs,
/// Entry ids, by the row index the list uses.
ids: Vec<String>,
/// The sections in order: the `section` id (none for entries without one) and its rows.
sections: Vec<(Option<String>, Vec<u16>)>,
scroll: ui::Scroll,
dragging: Option<u16>,
/// A value changed since the page opened.
pub changed: bool,
}
/// The presets' row (and its section): past every entry's index.
const PRESETS: u16 = u16::MAX;
const TITLE: &str = "horizon.pack.options.title";
/// The first page's group of rows for the whole pack, and every page's group of entries.
const WHOLE_PACK: &str = "Whole pack";
const PACK_OPTIONS: &str = "Pack settings";
const RESET_ALL: &str = "Reset all";
const RESET_ABOUT: &str = "Puts every option of this pack back to its default.";
const AT_DEFAULTS: &str = "Every option is at its default already.";
const PRESETS_ABOUT: &str = "Sets many options at once, as the pack groups them.";
const PACK_SETTINGS: &str = "Settings made by the pack's author: they change only this pack.";
/// A pack's tooltips, with the performance line after them, run longer than Horizon's own.
const NOTE_LINES: usize = 3;
/// A translation, or `fallback` where no language has the key.
fn translated(key: &str, fallback: impl FnOnce() -> String) -> String {
@@ -65,9 +56,34 @@ fn readable(path: &str) -> String {
.unwrap_or_default()
}
impl PackOptionsUi {
/// The page opens on `configs`, the selected packs' entries with the player's values.
pub fn open(configs: Configs) -> Self {
/// A number as its entry shows it: whole with a whole step, else up to two decimals.
fn number_text(n: f64, step: f64) -> String {
if step >= 1.0 && step.fract() == 0.0 {
format!("{n:.0}")
} else {
let text = format!("{n:.2}");
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
}
/// The screen: the entries being edited, as they were when it opened (for Undo and for whether
/// leaving changes anything), and how they are paged.
#[derive(Default)]
pub(crate) struct PackOptionsScreen {
/// The selected packs' entries and the values being picked.
pub(crate) configs: Configs,
opened: Configs,
/// Entry ids, by `Item::Entry`'s index.
ids: Vec<String>,
/// The sections in order: the `section` id (none for entries without one) and its entries.
sections: Vec<(Option<String>, Vec<u16>)>,
/// Bumped on every change, for `stamp`: the values are floats, which don't hash.
revision: u64,
}
impl PackOptionsScreen {
/// The screen opens on `configs`, the selected packs' entries with the player's values.
pub(crate) fn open(configs: Configs) -> Self {
let mut ids: Vec<(String, Option<String>, i64)> = configs
.entries()
.iter()
@@ -96,25 +112,21 @@ impl PackOptionsUi {
(None, None) => a.0.cmp(&b.0),
});
Self {
opened: configs.clone(),
configs,
ids: ids.into_iter().map(|(id, ..)| id).collect(),
sections: sections.into_iter().map(|(s, _, rows)| (s, rows)).collect(),
..Self::default()
revision: 0,
}
}
fn layout(&self, w: f32, h: f32) -> (Columns, Vec<Line<u16, u16>>, f32) {
let cols = Columns::of(w, h);
let mut lines = Lines::new();
// The pack-wide presets first, when the entries have some.
if !self.configs.presets().is_empty() {
lines.titled(PRESETS, vec![PRESETS]);
}
for (i, (_, rows)) in self.sections.iter().enumerate() {
lines.titled(i as u16, rows.clone());
}
let (lines, content) = lines.finish();
(cols, lines, content)
/// What leaving sends: the entries and the player's choices, if they differ from how the
/// screen opened (an Undo, or a value stepped back, leaves nothing to send).
pub(crate) fn finished(&self) -> Option<crate::options_ui::Event> {
(self.configs != self.opened).then(|| crate::options_ui::Event::PackOptions {
entries: self.configs.entries().keys().cloned().collect(),
chosen: self.configs.chosen(),
})
}
/// The namespace the presets' translations are under: of the first entry with presets.
@@ -166,21 +178,14 @@ impl PackOptionsUi {
None if back => n - 1,
None => 0,
};
let before = self.configs.clone();
self.configs.apply_preset(&presets[next]);
if self.configs != before {
self.changed = true;
}
self.revision += 1;
}
/// A section's heading: `config.<namespace>.section.<id>`, by its first entry's namespace.
fn section_name(&self, section: u16) -> String {
if section == PRESETS {
let key = format!("{}.presets", self.presets_namespace());
return translated(&key, || lang::get("horizon.pack.options.presets"));
}
let Some((id, rows)) = self.sections.get(usize::from(section)) else {
return String::new();
/// A section's page name: `config.<namespace>.section.<id>`, by its first entry's namespace.
fn section_name(&self, section: usize) -> String {
let Some((id, rows)) = self.sections.get(section) else {
return lang::get("horizon.pack.options.general");
};
let Some(id) = id else {
return lang::get("horizon.pack.options.general");
@@ -192,367 +197,218 @@ impl PackOptionsUi {
translated(&format!("config.{namespace}.section.{id}"), || readable(id))
}
/// An entry's name (`config.<namespace>.<name>`) and its value's label.
fn parts(&self, row: u16) -> (String, Option<String>) {
if row == PRESETS {
let label = self.preset_label(self.current_preset().as_deref());
return (self.section_name(PRESETS), Some(label));
}
let Some(id) = self.ids.get(usize::from(row)) else {
return (String::new(), None);
};
let (namespace, path) = split(id);
let name = translated(&format!("config.{namespace}.{path}"), || readable(path));
let entry = &self.configs.entries()[id];
let value = match self.configs.get(id) {
Some(ConfigValue::Number(n)) => {
let step = match entry.kind {
ConfigKind::Number { step, .. } => step,
_ => 1.0,
};
let text = if step >= 1.0 && step.fract() == 0.0 {
format!("{n:.0}")
} else {
format!("{n:.2}")
.trim_end_matches('0')
.trim_end_matches('.')
.to_owned()
};
Some(text)
}
Some(ConfigValue::Text(t)) => Some(t.clone()),
Some(ConfigValue::Bool(_)) | None => None,
};
let value = value.map(|v| match &entry.value_translation {
Some(key) if lang::has(key) => lang::tr(key, &[&v]),
_ => v,
});
(name, value)
}
/// The tooltip (`config.<namespace>.<name>.tooltip`) and the performance hint.
fn description(&self, row: u16) -> String {
let Some(id) = self.ids.get(usize::from(row)) else {
return String::new();
};
/// The tooltip (`config.<namespace>.<name>.tooltip`) and the performance line after it.
fn description(&self, id: &str) -> String {
let (namespace, path) = split(id);
let key = format!("config.{namespace}.{path}.tooltip");
let mut text = if lang::has(&key) {
let tooltip = if lang::has(&key) {
lang::get(&key)
} else {
String::new()
};
if let Some(impact) = &self.configs.entries()[id].performance_impact {
let level = lang::get(&format!("horizon.pack.options.impact.{impact}"));
let line = lang::tr("horizon.pack.options.impact", &[&level]);
text = if text.is_empty() {
line
} else {
format!("{text} {line}")
};
}
text
}
/// A slider's place (0 to 1) for a number entry.
fn slider(&self, row: u16) -> Option<f32> {
let id = self.ids.get(usize::from(row))?;
let ConfigKind::Number { min, max, .. } = self.configs.entries()[id].kind else {
return None;
};
let Some(ConfigValue::Number(n)) = self.configs.get(id) else {
return None;
};
Some(if max > min {
((n - min) / (max - min)) as f32
} else {
0.0
})
}
fn switch(&self, row: u16) -> Option<bool> {
match self.configs.get(self.ids.get(usize::from(row))?)? {
ConfigValue::Bool(b) => Some(*b),
_ => None,
let impact = self.configs.entries()[id]
.performance_impact
.as_ref()
.map(|impact| {
let level = lang::get(&format!("horizon.pack.options.impact.{impact}"));
lang::tr("horizon.pack.options.impact", &[&level])
});
match impact {
Some(line) if tooltip.is_empty() => line,
Some(line) => format!("{tooltip} {line}"),
None => tooltip,
}
}
pub fn draw(
&mut self,
batch: &mut HudBatch,
atlas: &HudAtlas,
cursor: (f32, f32),
in_world: bool,
) {
let (w, h) = (batch.width, batch.height);
let (cols, lines, content) = self.layout(w, h);
self.scroll.clamp(cols.top, cols.bottom, content);
shell::backdrop(batch, atlas, in_world);
shell::mark(
batch,
atlas,
&cols,
&lang::get("horizon.pack.options.title"),
);
shell::plate(
batch,
atlas,
&cols,
&lang::get("horizon.pack.options.title"),
);
let over_list = cursor.1 >= cols.top && cursor.1 < cols.bottom;
let mut described = None;
shell::list(
batch,
atlas,
&cols,
&lines,
self.scroll.amount,
|section| self.section_name(section),
|batch, row: u16, y| {
let [rx, ry, rw, rh] = cols.row(y);
let hover = over_list && ui::hovered(cursor, rx, ry, rw, rh);
if hover || self.dragging == Some(row) {
described = Some(row);
/// Entry `i`'s row: a switch, a slider in its steps, a choice, or text to read.
fn entry_row(&self, i: u16) -> Option<Row<Item>> {
let id = self.ids.get(usize::from(i))?;
let (namespace, path) = split(id);
let name = translated(&format!("config.{namespace}.{path}"), || readable(path));
let entry = &self.configs.entries()[id];
let shown = |text: String| match &entry.value_translation {
Some(key) if lang::has(key) => lang::tr(key, &[&text]),
_ => text,
};
let value = match (&entry.kind, self.configs.get(id)?) {
(_, ConfigValue::Bool(on)) => Value::Switch(*on),
(&ConfigKind::Number { min, max, step }, &ConfigValue::Number(n)) => {
let span = max - min;
let stops = if step > 0.0 {
(span / step).round()
} else {
0.0
};
Value::Slider {
position: if span > 0.0 {
((n - min) / span) as f32
} else {
0.0
},
steps: (stops >= 1.0).then_some(stops as u32),
text: shown(number_text(n, step)),
}
let (name, value) = self.parts(row);
let label = match &value {
Some(v) => format!("{name}: {v}"),
None => name.clone(),
};
let view = shell::RowView {
label: &label,
name: &name,
value: value.as_deref(),
switch: self.switch(row),
slider: self.slider(row),
live: true,
hover,
focused: false,
held: self.dragging == Some(row),
key: None,
};
shell::row(batch, atlas, &cols, y, &view);
},
);
shell::scroller(batch, atlas, &cols, content, self.scroll.amount);
// The strip: the pointed-at entry's tooltip.
let [x, y, ..] = cols.dock;
style::panel(batch, atlas, cols.dock);
if let Some(row) = described {
let name = Text::literal(self.parts(row).0);
batch.text_styled(atlas, &name, x + 12.0, y + 8.0, style::WHITE, true);
shell::dock_note(batch, atlas, &cols, self.description(row), style::GREY);
}
let mut foot = vec![(cols.button(0), "gui.done", Some(Declared::Done))];
if self
.configs
.chosen()
.iter()
.any(|(id, _)| self.ids.contains(id))
{
foot.push((cols.button(1), "controls.reset", None));
}
for (rect, key, declared) in foot {
if let Some(declared) = declared {
crate::widgets::declare_action(declared, rect, true);
}
let label = Text::literal(lang::get(key));
shell::foot_button(batch, atlas, rect, &label, cursor, (false, true));
}
(ConfigKind::Text { allowed }, ConfigValue::Text(t)) if !allowed.is_empty() => {
Value::Choice(shown(t.clone()))
}
(_, value) => Value::Read(shown(match value {
ConfigValue::Number(n) => number_text(*n, 1.0),
ConfigValue::Text(t) => t.clone(),
ConfigValue::Bool(b) => b.to_string(),
})),
};
Some(Row::new(Item::Entry(i), name, value).about(self.description(id)))
}
/// A press (or a drag with `drag`) at `(x, y)`; `back` turns a cycle backwards.
pub fn click(
&mut self,
(x, y): (f32, f32),
(w, h): (f32, f32),
drag: bool,
back: bool,
) -> Vec<Action> {
let (cols, lines, content) = self.layout(w, h);
let at = |[rx, ry, rw, rh]: [f32; 4]| ui::hovered((x, y), rx, ry, rw, rh);
if drag {
if self.scroll.held() {
self.scroll.drag(y, cols.top, cols.bottom, content);
} else if let Some(row) = self.dragging {
self.set_slider(row, cols.slider_at(x));
return vec![Action::SliderDrag];
}
return Vec::new();
/// The rows for the whole pack: its presets, when it has some, and Reset all.
fn whole_pack(&self) -> Group<Item> {
let mut rows = Vec::new();
if !self.configs.presets().is_empty() {
let key = format!("{}.presets", self.presets_namespace());
let name = translated(&key, || lang::get("horizon.pack.options.presets"));
let label = self.preset_label(self.current_preset().as_deref());
rows.push(
Row::new(Item::Presets, name, Value::Choice(label)).about(lang::get(PRESETS_ABOUT)),
);
}
if cols.scrolls()
&& self
.scroll
.press((x, y), cols.bar_x(), cols.top, cols.bottom, content)
{
return Vec::new();
let at_defaults = self.configs.chosen().is_empty();
let reset = Row::new(Item::ResetAll, lang::get(RESET_ALL), Value::Press)
.about(lang::get(RESET_ABOUT))
.blocked(at_defaults.then(|| lang::get(AT_DEFAULTS)));
rows.push(reset);
Group {
name: WHOLE_PACK,
rows,
}
if at(cols.button(0)) {
return vec![Action::ButtonClick, Action::Done];
}
if at(cols.button(1)) {
self.reset();
return vec![Action::ButtonClick];
}
if y < cols.top || y >= cols.bottom {
return Vec::new();
}
let Some(row) = lines.iter().find_map(|line| {
let row = line.setting?;
at(cols.row(cols.top + line.y - self.scroll.amount)).then_some(row)
}) else {
return Vec::new();
};
if row == PRESETS {
self.cycle_preset(back);
return vec![Action::ButtonClick];
}
let Some(id) = self.ids.get(usize::from(row)).cloned() else {
return Vec::new();
};
let entry = self.configs.entries()[&id].clone();
match (&entry.kind, self.configs.get(&id).cloned()) {
(ConfigKind::Number { .. }, _) => {
self.dragging = Some(row);
self.set_slider(row, cols.slider_at(x));
return vec![Action::SliderDrag];
}
(ConfigKind::Bool, Some(ConfigValue::Bool(b))) => {
self.set(&id, ConfigValue::Bool(!b));
}
(ConfigKind::Text { allowed }, Some(ConfigValue::Text(t))) if !allowed.is_empty() => {
let i = allowed.iter().position(|a| *a == t).unwrap_or(0);
let n = allowed.len();
let next = if back { (i + n - 1) % n } else { (i + 1) % n };
self.set(&id, ConfigValue::Text(allowed[next].clone()));
}
_ => return Vec::new(),
}
vec![Action::ButtonClick]
}
fn set(&mut self, id: &str, value: ConfigValue) {
let before = self.configs.get(id).cloned();
self.configs.set(id, value);
if self.configs.get(id).cloned() != before {
self.changed = true;
}
}
/// Number entry `row` at slider place `at` (0 to 1).
fn set_slider(&mut self, row: u16, at: f32) {
let Some(id) = self.ids.get(usize::from(row)).cloned() else {
return;
};
if let ConfigKind::Number { min, max, .. } = self.configs.entries()[&id].kind {
self.set(&id, ConfigValue::Number(min + f64::from(at) * (max - min)));
}
self.revision += 1;
}
/// Every entry back to its default.
fn reset(&mut self) {
let defaults: Vec<_> = self
.configs
.entries()
.iter()
let defaults: Vec<_> = (self.configs.entries().iter())
.map(|(id, e)| (id.clone(), e.default.clone()))
.collect();
for (id, value) in defaults {
self.set(&id, value);
}
}
}
/// The pointer lets go.
pub fn release(&mut self) {
self.scroll.release();
self.dragging = None;
impl shell::Screen for PackOptionsScreen {
type Page = u16;
type Row = Item;
fn title(&self) -> &'static str {
TITLE
}
/// The mouse wheel scrolls the list.
pub fn scroll(&mut self, (w, h): (f32, f32), amount: f32) {
let (cols, _, content) = self.layout(w, h);
self.scroll
.wheel(amount, 18.0, cols.top, cols.bottom, content);
fn note_lines(&self) -> usize {
NOTE_LINES
}
/// The rows read only the screen's own entries, which change through it alone.
fn stamp(&self, _s: &Settings) -> u64 {
self.revision
}
/// A page per section; the first starts with the rows for the whole pack.
fn sheets(&self, _s: &Settings) -> Vec<Sheet<u16, Item>> {
let about = lang::get(PACK_SETTINGS);
let mut sheets = Vec::new();
for (i, (_, entries)) in self.sections.iter().enumerate() {
let rows = entries.iter().filter_map(|&e| self.entry_row(e)).collect();
let mut groups = vec![Group {
name: PACK_OPTIONS,
rows,
}];
if i == 0 {
groups.insert(0, self.whole_pack());
}
sheets.push(Sheet::new(
i as u16,
self.section_name(i),
about.clone(),
groups,
));
}
if sheets.is_empty() {
let groups = vec![self.whole_pack()];
sheets.push(Sheet::new(0, self.section_name(0), about, groups));
}
sheets
}
/// A switch flips, a choice and the presets step (back with Shift, or Left), Reset all
/// resets.
fn press(&mut self, _s: &mut Settings, item: Item, back: bool) -> Vec<Output> {
let i = match item {
Item::Presets => {
self.cycle_preset(back);
return Vec::new();
}
Item::ResetAll => {
self.reset();
return Vec::new();
}
Item::Entry(i) => i,
};
let Some(id) = self.ids.get(usize::from(i)).cloned() else {
return Vec::new();
};
let kind = self.configs.entries()[&id].kind.clone();
match (kind, self.configs.get(&id).cloned()) {
(_, Some(ConfigValue::Bool(on))) => self.set(&id, ConfigValue::Bool(!on)),
(ConfigKind::Text { allowed }, Some(ConfigValue::Text(t))) if !allowed.is_empty() => {
let at = allowed.iter().position(|a| *a == t).unwrap_or(0);
let n = allowed.len();
let next = if back { (at + n - 1) % n } else { (at + 1) % n };
self.set(&id, ConfigValue::Text(allowed[next].clone()));
}
_ => {}
}
Vec::new()
}
/// A slider moves its entry to the step nearest it (`Configs::set` snaps it).
fn slide(&mut self, _s: &mut Settings, item: Item, position: f32) {
let Item::Entry(i) = item else { return };
let Some(id) = self.ids.get(usize::from(i)).cloned() else {
return;
};
if let ConfigKind::Number { min, max, .. } = self.configs.entries()[&id].kind {
let value = min + f64::from(position.clamp(0.0, 1.0)) * (max - min);
self.set(&id, ConfigValue::Number(value));
}
}
/// With the "Scroll wheel changes settings" extra, the wheel steps a choice and the presets.
fn wheel_step(&mut self, s: &mut Settings, item: Item, back: bool) -> Option<Vec<Output>> {
let steps = match item {
Item::Presets => true,
Item::Entry(i) => self
.entry_row(i)
.is_some_and(|row| matches!(row.value, Value::Choice(_))),
Item::ResetAll => false,
};
if !steps {
return None;
}
let mut outputs = vec![Output::Event(crate::options_ui::Event::ButtonClick)];
outputs.extend(self.press(s, item, back));
Some(outputs)
}
fn undoes(&self) -> bool {
true
}
/// The entries as the screen opened with them.
fn undo(&mut self, _s: &mut Settings, _before: &Settings) -> Vec<Output> {
self.configs = self.opened.clone();
self.revision += 1;
Vec::new()
}
/// Undo shows exactly while an entry differs from how the screen opened.
fn differs(&self, _s: &Settings, _before: &Settings) -> Option<bool> {
Some(self.configs != self.opened)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn configs() -> Configs {
let mut c = Configs::default();
c.add_entry(
"p:fog".into(),
&serde_json::json!({"default_value": 0.5, "section": "sky", "section_order": 2}),
);
c.add_entry("p:rain".into(), &serde_json::json!({"default_value": "drops", "allowed_values": ["drops", "streaks"], "section": "weather", "section_order": 1}));
c.add_entry(
"p:birds".into(),
&serde_json::json!({"default_value": true}),
);
c
}
#[test]
fn sections_sort_by_their_order_and_the_unsectioned_last() {
let ui = PackOptionsUi::open(configs());
let order: Vec<_> = ui.sections.iter().map(|(s, _)| s.as_deref()).collect();
assert_eq!(order, [Some("weather"), Some("sky"), None]);
}
#[test]
fn rows_switch_cycle_and_slide() {
let mut ui = PackOptionsUi::open(configs());
let size = (480.0, 270.0);
let (cols, lines, _) = ui.layout(size.0, size.1);
let ids = ui.ids.clone();
let point = |id: &str| {
let row = ids.iter().position(|i| i == id).unwrap() as u16;
let line = lines.iter().find(|l| l.setting == Some(row)).unwrap();
let [x, y, w, h] = cols.row(cols.top + line.y);
(x + w - 4.0, y + h / 2.0)
};
let (birds, rain) = (point("p:birds"), point("p:rain"));
ui.click(birds, size, false, false);
assert_eq!(ui.configs.get("p:birds"), Some(&ConfigValue::Bool(false)));
ui.click(rain, size, false, false);
assert_eq!(
ui.configs.get("p:rain"),
Some(&ConfigValue::Text("streaks".into()))
);
// The slider's far right end is its maximum.
let fog = point("p:fog");
let (tx, tw) = cols.track();
ui.click((tx + tw, fog.1), size, false, false);
ui.release();
assert_eq!(ui.configs.get("p:fog"), Some(&ConfigValue::Number(1.0)));
assert!(ui.changed);
assert_eq!(ui.configs.chosen().len(), 3);
ui.reset();
assert!(ui.configs.chosen().is_empty());
}
#[test]
fn the_presets_row_cycles_the_pack_wide_presets_and_shows_custom_otherwise() {
let mut c = Configs::default();
let entry = |default: f64, fast: f64, pretty: f64| serde_json::json!({"default_value": default, "presets": {"fast": fast, "pretty": pretty}});
c.add_entry("p:fog".into(), &entry(0.5, 0.0, 1.0));
c.add_entry("p:dust".into(), &entry(0.5, 0.0, 0.8));
let mut ui = PackOptionsUi::open(c);
// The defaults are no preset.
assert_eq!(ui.current_preset(), None);
ui.cycle_preset(false);
assert_eq!(ui.current_preset().as_deref(), Some("fast"));
assert_eq!(ui.configs.get("p:fog"), Some(&ConfigValue::Number(0.0)));
ui.cycle_preset(false);
assert_eq!(ui.current_preset().as_deref(), Some("pretty"));
ui.cycle_preset(true);
assert_eq!(ui.current_preset().as_deref(), Some("fast"));
// One value off the preset: custom again.
ui.set("p:dust", ConfigValue::Number(0.3));
assert_eq!(ui.current_preset(), None);
assert!(ui.changed);
}
}
mod tests;
@@ -0,0 +1,281 @@
use super::*;
use crate::options_ui::Event;
use crate::settings_shell::{Columns, Hosted, Screen as _, Shell, Target};
use winit::keyboard::KeyCode as K;
const SIZE: (f32, f32) = (854.0, 480.0);
/// Fog (a number) under Sky, rain (a list of values) under Weather, birds (a boolean) in no
/// section.
fn configs() -> Configs {
let mut c = Configs::default();
c.add_entry(
"p:fog".into(),
&serde_json::json!({"default_value": 0.5, "section": "sky", "section_order": 2}),
);
c.add_entry("p:rain".into(), &serde_json::json!({"default_value": "drops", "allowed_values": ["drops", "streaks"], "section": "weather", "section_order": 1}));
c.add_entry(
"p:birds".into(),
&serde_json::json!({"default_value": true}),
);
c
}
/// Two entries with the pack-wide presets `fast` and `pretty`.
fn with_presets() -> Configs {
let mut c = Configs::default();
let entry = |default: f64, fast: f64, pretty: f64| serde_json::json!({"default_value": default, "presets": {"fast": fast, "pretty": pretty}});
c.add_entry("p:fog".into(), &entry(0.5, 0.0, 1.0));
c.add_entry("p:dust".into(), &entry(0.5, 0.0, 0.8));
c
}
fn shell_of(configs: Configs) -> Shell<PackOptionsScreen> {
let mut shell = Shell::default();
shell.screen = PackOptionsScreen::open(configs);
shell
}
/// The row of entry `id`, and the page it is on.
fn entry(shell: &Shell<PackOptionsScreen>, id: &str) -> (u16, Item) {
let i = shell.screen.ids.iter().position(|e| e == id).unwrap() as u16;
let page = shell.screen.sections.iter().position(|s| s.1.contains(&i));
(page.unwrap() as u16, Item::Entry(i))
}
fn press(shell: &mut Shell<PackOptionsScreen>, s: &mut Settings, item: Item) -> Vec<Output> {
let at = shell.point_at(s, SIZE, item);
shell.click(s, at, SIZE, false, false, false)
}
fn value<'a>(shell: &'a Shell<PackOptionsScreen>, id: &str) -> Option<&'a ConfigValue> {
shell.screen.configs.get(id)
}
#[test]
fn sections_sort_by_their_order_and_the_unsectioned_last() {
let screen = PackOptionsScreen::open(configs());
let order: Vec<_> = screen.sections.iter().map(|(s, _)| s.as_deref()).collect();
assert_eq!(order, [Some("weather"), Some("sky"), None]);
// Each section is a page, the first one holding Reset all before its entries.
let sheets = screen.sheets(&Settings::default());
let names: Vec<_> = sheets.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["Weather", "Sky", "horizon.pack.options.general"]);
let first: Vec<Vec<Item>> = (sheets[0].groups.iter())
.map(|g| g.rows.iter().map(|r| r.id).collect())
.collect();
let rain = screen.ids.iter().position(|e| e == "p:rain").unwrap() as u16;
assert_eq!(first, [vec![Item::ResetAll], vec![Item::Entry(rain)]]);
}
#[test]
fn rows_switch_cycle_and_slide() {
let mut s = Settings::default();
let mut shell = shell_of(configs());
let (page, birds) = entry(&shell, "p:birds");
shell.show(page);
assert_eq!(
press(&mut shell, &mut s, birds)[0],
Output::Event(Event::ButtonClick)
);
assert_eq!(value(&shell, "p:birds"), Some(&ConfigValue::Bool(false)));
let (page, rain) = entry(&shell, "p:rain");
shell.show(page);
press(&mut shell, &mut s, rain);
let streaks = ConfigValue::Text("streaks".into());
assert_eq!(value(&shell, "p:rain"), Some(&streaks));
// The slider's far right end is its maximum.
let (page, fog) = entry(&shell, "p:fog");
shell.show(page);
let at = shell.point_at(&s, SIZE, fog);
let (track, width) = Columns::of(SIZE.0, SIZE.1).track();
shell.click(&mut s, (track + width, at.1), SIZE, false, false, false);
shell.release();
assert_eq!(value(&shell, "p:fog"), Some(&ConfigValue::Number(1.0)));
assert_eq!(shell.screen.configs.chosen().len(), 3);
// Reset all, on the first page, puts them all back, and is greyed once they are.
shell.show(0);
press(&mut shell, &mut s, Item::ResetAll);
assert!(shell.screen.configs.chosen().is_empty());
let sheets = shell.screen.sheets(&s);
assert!(!sheets[0].groups[0].rows[0].live);
}
#[test]
fn the_presets_row_cycles_the_pack_wide_presets_and_shows_custom_otherwise() {
let mut screen = PackOptionsScreen::open(with_presets());
// The defaults are no preset.
assert_eq!(screen.current_preset(), None);
screen.cycle_preset(false);
assert_eq!(screen.current_preset().as_deref(), Some("fast"));
assert_eq!(screen.configs.get("p:fog"), Some(&ConfigValue::Number(0.0)));
screen.cycle_preset(false);
assert_eq!(screen.current_preset().as_deref(), Some("pretty"));
screen.cycle_preset(true);
assert_eq!(screen.current_preset().as_deref(), Some("fast"));
// One value off the preset: custom again.
screen.set("p:dust", ConfigValue::Number(0.3));
assert_eq!(screen.current_preset(), None);
let presets = &screen.sheets(&Settings::default())[0].groups[0].rows[0];
assert_eq!(presets.id, Item::Presets);
let custom = lang::get("horizon.pack.options.presets.custom");
assert_eq!(presets.value, Value::Choice(custom));
}
#[test]
fn left_and_right_step_the_presets() {
let mut s = Settings::default();
let mut shell = shell_of(with_presets());
shell.set_focus(Some(Target::Row(Item::Presets)));
shell.key(&mut s, K::ArrowRight, None, false, SIZE);
assert_eq!(shell.screen.current_preset().as_deref(), Some("fast"));
shell.key(&mut s, K::ArrowRight, None, false, SIZE);
assert_eq!(shell.screen.current_preset().as_deref(), Some("pretty"));
shell.key(&mut s, K::ArrowLeft, None, false, SIZE);
assert_eq!(shell.screen.current_preset().as_deref(), Some("fast"));
assert_eq!(shell.focused_row(), Some(Item::Presets));
}
#[test]
fn sliders_stop_at_the_entrys_step() {
let mut c = Configs::default();
let json = serde_json::json!({"default_value": 4.0, "min": 0.0, "max": 10.0, "step": 2.0});
c.add_entry("p:clouds".into(), &json);
let mut s = Settings::default();
let mut shell = shell_of(c);
let row = &shell.screen.sheets(&s)[0].groups[1].rows[0];
let stops = Value::Slider {
position: 0.4,
steps: Some(5),
text: "4".into(),
};
assert_eq!(row.value, stops);
// A press a little past the middle of the track lands on the step nearest it.
let at = shell.point_at(&s, SIZE, Item::Entry(0));
let (track, width) = Columns::of(SIZE.0, SIZE.1).track();
shell.click(
&mut s,
(track + width * 0.55, at.1),
SIZE,
false,
false,
false,
);
shell.release();
assert_eq!(value(&shell, "p:clouds"), Some(&ConfigValue::Number(6.0)));
// Held by the press, Right goes one step on and Left one back.
shell.set_focus(Some(Target::Row(Item::Entry(0))));
shell.key(&mut s, K::ArrowRight, None, false, SIZE);
assert_eq!(value(&shell, "p:clouds"), Some(&ConfigValue::Number(8.0)));
shell.key(&mut s, K::ArrowLeft, None, false, SIZE);
shell.key(&mut s, K::ArrowLeft, None, false, SIZE);
assert_eq!(value(&shell, "p:clouds"), Some(&ConfigValue::Number(4.0)));
}
/// A language with the pack's own strings: a name, a section and a tooltip.
struct PackLang;
impl lang::ResourceSource for PackLang {
fn read(&self, path: &str) -> Option<Vec<u8>> {
(path == "assets/minecraft/lang/en_us.json").then(|| {
let strings = serde_json::json!({
"config.minecraft.haze": "Haze",
"config.minecraft.haze.tooltip": "Thickens the distant air.",
"config.minecraft.section.sky": "Sky and fog",
});
serde_json::to_vec(&strings).unwrap()
})
}
}
fn haze() -> Configs {
let mut c = configs();
let json =
serde_json::json!({"default_value": false, "section": "sky", "performance_impact": "high"});
c.add_entry("minecraft:haze".into(), &json);
c
}
#[test]
fn the_search_finds_an_entry_by_its_tooltip_and_the_strip_has_its_impact() {
let language = lang::Language::load(&[&PackLang], "en_us");
lang::scoped(language, || {
let s = Settings::default();
let mut shell = shell_of(haze());
let (page, haze) = entry(&shell, "minecraft:haze");
shell.set_search("distant air");
assert_eq!(shell.listed(&s, SIZE), [(page, haze)]);
let sheets = shell.screen.sheets(&s);
assert_eq!(sheets[usize::from(page)].name, "Sky and fog");
let row = sheets.iter().flat_map(|p| &p.groups).flat_map(|g| &g.rows);
let row = row.into_iter().find(|r| r.id == haze).unwrap();
assert_eq!(row.name, "Haze");
assert_eq!(
row.about,
"Thickens the distant air. Performance impact: high"
);
});
}
#[test]
fn tab_reaches_every_row_of_every_page() {
let mut s = Settings::default();
let mut shell = shell_of(haze());
let pages = shell.screen.sheets(&s).len() as u16;
let mut seen = Vec::new();
for page in 0..pages {
shell.show(page);
shell.set_focus(None);
for _ in 0..8 {
shell.key(&mut s, K::Tab, None, false, SIZE);
if let Some(row) = shell.focused_row()
&& !seen.contains(&row)
{
seen.push(row);
}
}
}
// Reset all is greyed at the defaults; every entry is reached.
let mut entries: Vec<Item> = (0..shell.screen.ids.len() as u16)
.map(Item::Entry)
.collect();
seen.sort_by_key(|item| format!("{item:?}"));
entries.sort_by_key(|item| format!("{item:?}"));
assert_eq!(seen, entries);
}
#[test]
fn undo_puts_the_entries_back_and_then_leaving_sends_nothing() {
let mut s = Settings::default();
let mut shell = shell_of(configs());
let (page, birds) = entry(&shell, "p:birds");
shell.show(page);
press(&mut shell, &mut s, birds);
assert!(shell.foot_at(&s, SIZE).iter().any(|f| f.0 == Target::Undo));
assert!(shell.screen.finished().is_some());
let undo = shell
.foot_at(&s, SIZE)
.into_iter()
.find(|f| f.0 == Target::Undo);
let [x, y, w, h] = undo.unwrap().1;
shell.click(
&mut s,
(x + w / 2.0, y + h / 2.0),
SIZE,
false,
false,
false,
);
assert_eq!(value(&shell, "p:birds"), Some(&ConfigValue::Bool(true)));
assert!(!shell.foot_at(&s, SIZE).iter().any(|f| f.0 == Target::Undo));
assert_eq!(shell.screen.finished(), None);
// Stepped there and back by hand, it sends nothing either.
press(&mut shell, &mut s, birds);
press(&mut shell, &mut s, birds);
assert_eq!(shell.screen.finished(), None);
press(&mut shell, &mut s, birds);
let Some(Event::PackOptions { entries, chosen }) = shell.screen.finished() else {
panic!("a change is sent");
};
assert_eq!(entries.len(), 3);
assert_eq!(chosen.get("p:birds"), Some(&ConfigValue::Bool(false)));
}
@@ -677,7 +677,7 @@ impl PackScreen {
return action;
}
if self.search.contains(x, y) {
self.search.click(m, x, false);
self.search.click(m, x, false, false);
self.set_focus(Focus::Search);
return Action::None;
}
@@ -1100,6 +1100,9 @@ impl PackScreen {
0,
);
self.search.draw(&mut out, m, blink_ms, None);
if self.browser.is_none() && self.search.contains(f64::from(mouse.0), f64::from(mouse.1)) {
crate::widgets::text_cursor(true, true);
}
for side in 0..2 {
self.draw_list(&mut out, m, side, mouse);
}
@@ -1134,7 +1137,7 @@ impl PackScreen {
if d::inside(point, qx, qy, BROWSER_SEARCH_W, 18) {
self.browser_search.x = qx;
self.browser_search.y = qy;
self.browser_search.click(m, x, false);
self.browser_search.click(m, x, false, false);
self.browser_focus = true;
return Some(Action::None);
}
@@ -1302,6 +1305,9 @@ impl PackScreen {
field.x = qx;
field.y = qy;
field.draw(out, m, 0, None);
if field.contains(f64::from(mouse.0), f64::from(mouse.1)) {
crate::widgets::text_cursor(true, true);
}
let (sbx, sby) = self.browser_search_button();
d::button(
out,
+232 -16
View File
@@ -468,17 +468,20 @@ 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)
first_json(bytes).ok()
}
/// 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))
/// The first JSON value of a `.mcmeta` file, as `ResourceMetadata.fromJsonStream` reads it:
/// Gson's `TypeAdapter.read` stops after the value, so text after it (packs leave `//` notes
/// there) is never read, and a UTF-8 byte order mark is skipped.
pub(crate) fn first_json<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> serde_json::Result<T> {
let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
match serde_json::Deserializer::from_slice(bytes)
.into_iter()
.next()?
.ok()
.next()
{
Some(value) => value,
None => Err(serde::de::Error::custom("empty metadata")),
}
}
/// A pack's Polytone config entries (`assets/<namespace>/polytone/config_entries/<name>.json`,
/// in the pack's base, not its overlays) at their default values.
@@ -827,13 +830,6 @@ fn build_overlay_uncached(
}
// Vanilla sits below every pack, so filters hide its files too.
let filters: Vec<&Filter> = packs.iter().flat_map(|p| &p.filter).collect();
let touched_dirs: BTreeSet<String> = files
.keys()
.flat_map(|f| {
let parts: Vec<&str> = f.split('/').collect();
(1..parts.len()).map(move |n| parts[..n].join("/"))
})
.collect();
let zips: Vec<Option<Zip>> = packs
.iter()
.map(|p| {
@@ -882,6 +878,21 @@ fn build_overlay_uncached(
merged.insert(name.clone(), bytes);
}
}
add_sprite_renames(
vanilla,
&merged,
&filters,
&mut files,
&mut hidden,
dependencies,
);
let touched_dirs: BTreeSet<String> = files
.keys()
.flat_map(|f| {
let parts: Vec<&str> = f.split('/').collect();
(1..parts.len()).map(move |n| parts[..n].join("/"))
})
.collect();
/// A zip entry to write: its pack, its name in the zip and where it goes.
type Extract<'a> = (usize, &'a str, PathBuf);
#[allow(clippy::too_many_arguments)]
@@ -1032,6 +1043,123 @@ fn build_overlay_uncached(
}
extracted
}
/// `SingleFile` with a `sprite`: the atlas holds the resource's pixels, and the resource's
/// `.mcmeta`, under the sprite's id. Every other sprite of the blocks and items atlases is its
/// texture's own id, and the loaders read a model's sprite from `textures/<sprite>.png`, so the
/// overlay gives a renamed sprite that file. ItemsAdder and Nexo packs name their models'
/// textures only through these renames (#14485).
///
/// A sprite gets its resource's file only when the whole source list, in order, ends on the
/// rename (`SpriteSourceList.list`: a later source of the same id replaces it), when the other
/// atlas, which reads the same file, lists it from that resource too or not at all, and when it
/// has no texture of its own. A texture that is there may be read as itself (another source's
/// resource, an unstitched or paletted sprite's input), so no alias ever replaces one; such a
/// sprite draws its own texture, as before aliases.
fn add_sprite_renames(
vanilla: &Path,
merged: &BTreeMap<String, Vec<u8>>,
filters: &[&Filter],
files: &mut BTreeMap<String, (usize, Provided)>,
hidden: &mut BTreeSet<String>,
dependencies: &mut cache::Dependencies,
) {
use crate::atlas_sources::{
SpriteOrigin, SpriteSource, decode, list, list_textures, texture_path,
};
let png = |id: &str| {
texture_path(Path::new(""), id, "textures")
.to_string_lossy()
.replace('\\', "/")
};
let atlases: Vec<_> = ["blocks", "items"]
.into_iter()
.filter_map(|atlas| merged.get(&format!("assets/minecraft/atlases/{atlas}.json")))
.filter_map(|bytes| decode(std::str::from_utf8(bytes).ok()?))
.collect();
let renamed = |source: &SpriteSource| matches!(source, SpriteSource::Single { resource, sprite: Some(sprite) } if sprite != resource);
if !atlases.iter().flatten().any(renamed) {
return;
}
// The textures a source can list: the packs' and vanilla's the packs leave visible.
let mut textures: Vec<String> = list_textures(vanilla)
.into_iter()
.filter(|id| {
let name = png(id);
!hidden.contains(&name) && !filters.iter().any(|f| f.blocks(&name))
})
.chain(files.keys().filter_map(|name| {
let (namespace, rest) = name.strip_prefix("assets/")?.split_once('/')?;
let path = rest.strip_prefix("textures/")?.strip_suffix(".png")?;
Some(format!("{namespace}:{path}"))
}))
.collect();
textures.sort();
textures.dedup();
// Each sprite's resource, `None` where an atlas lists it any other way.
let mut renames: BTreeMap<String, Option<String>> = BTreeMap::new();
for sources in &atlases {
for (sprite, origin) in list(sources, &textures) {
let from = match origin {
SpriteOrigin::File(resource) if resource != sprite => Some(resource),
_ => None,
};
renames
.entry(sprite)
.and_modify(|seen| {
if *seen != from {
*seen = None;
}
})
.or_insert(from);
}
}
let renames = renames
.into_iter()
.filter(|(sprite, _)| textures.binary_search(sprite).is_err())
.filter_map(|(sprite, resource)| Some((png(&resource?), png(&sprite))));
// Each resource is the file the packs give, never another rename's sprite.
let mut found = Vec::new();
for (from, to) in renames {
// `texture_path` names an id that would leave the root as a file that is never there.
if !stays_inside(&from) || !stays_inside(&to) {
continue;
}
let from_meta = format!("{from}.mcmeta");
// A pack's texture with its own `.mcmeta`, or vanilla's below every pack.
let (file, meta) = match files.get(&from) {
Some(file) => (file.clone(), files.get(&from_meta).cloned()),
None => {
let (path, meta_path) = (vanilla.join(&from), vanilla.join(&from_meta));
dependencies.file(&path);
dependencies.file(&meta_path);
if !path.is_file() || filters.iter().any(|f| f.blocks(&from)) {
continue;
}
// `createStackMetadataFinder`: a pack's filter hides vanilla's `.mcmeta` too.
let meta = files.get(&from_meta).cloned().or_else(|| {
(meta_path.is_file() && !filters.iter().any(|f| f.blocks(&from_meta)))
.then(|| (0, (Some(meta_path), from_meta.clone())))
});
((0, (Some(path), from.clone())), meta)
}
};
found.push((to, file, meta));
}
for (to, file, meta) in found {
let to_meta = format!("{to}.mcmeta");
files.insert(to, file);
match meta {
Some(meta) => {
hidden.remove(&to_meta);
files.insert(to_meta, meta);
}
None => {
files.remove(&to_meta);
hidden.insert(to_meta);
}
}
}
}
/// The most the zip packs in `packs` may unpack to in one overlay: 16 times their size on disk
/// (real packs are mostly PNGs and JSON, a few times smaller zipped at most), at least 64 MiB
/// for a small pack of text, and never past 8 GiB.
@@ -1906,6 +2034,94 @@ mod tests {
let _ = fs::remove_dir_all(base);
}
#[test]
fn a_renamed_atlas_sprite_reads_its_resource() {
let base =
std::env::temp_dir().join(format!("horizon-sprite-rename-{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
let write = |path: PathBuf, bytes: &[u8]| {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, bytes).unwrap();
};
let vanilla = base.join("vanilla");
let textures = vanilla.join("assets/minecraft/textures");
let animation = b"{\"animation\":{}}";
write(textures.join("block/sea_lantern.png"), b"lantern");
write(textures.join("block/sea_lantern.png.mcmeta"), animation);
write(textures.join("item/stick.png"), b"vanilla stick");
write(textures.join("item/stick.png.mcmeta"), animation);
let meta = br#"{"pack":{"description":"d","pack_format":97}}"#;
let pack = base.join("packs/IA");
write(pack.join("pack.mcmeta"), meta);
write(pack.join("assets/iageneric/textures/item/box.png"), b"box");
// An ItemsAdder pack's items atlas: its models name only the `ia:` sprites.
write(
pack.join("assets/minecraft/atlases/items.json"),
br#"{"sources":[
{"type":"single","resource":"iageneric:item/box","sprite":"ia:0"},
{"type":"single","resource":"minecraft:block/sea_lantern","sprite":"ia:1199"},
{"type":"single","resource":"iageneric:item/box","sprite":"minecraft:item/stick"},
{"type":"single","resource":"minecraft:item/stick","sprite":"ia:3"},
{"type":"single","resource":"iageneric:item/gone","sprite":"ia:2"},
{"type":"single","resource":"iageneric:item/box","sprite":"ia:../../../escape"},
{"type":"single","resource":"iageneric:item/box","sprite":"ia:7"},
{"type":"single","resource":"iageneric:item/box","sprite":"ia:8"},
{"type":"single","resource":"iageneric:item/box","sprite":"ia:9"}
]}"#,
);
// A pack above it: later sources of three of those sprites, a blocks atlas that
// disagrees about another, and a filter hiding vanilla's animation of the stick.
let higher = base.join("packs/Top");
write(
higher.join("pack.mcmeta"),
br#"{"pack":{"description":"d","pack_format":97},
"filter":{"block":[{"path":"textures/item/stick\\.png\\.mcmeta"}]}}"#,
);
write(
higher.join("assets/minecraft/atlases/items.json"),
br#"{"sources":[
{"type":"single","resource":"minecraft:block/sea_lantern","sprite":"ia:8"},
{"type":"filter","pattern":{"namespace":"ia","path":"7"}}
]}"#,
);
write(
higher.join("assets/minecraft/atlases/blocks.json"),
br#"{"sources":[
{"type":"single","resource":"minecraft:block/sea_lantern","sprite":"ia:9"}
]}"#,
);
let packs = discover(&vanilla, &base.join("packs"));
let out = base.join("overlay");
build_overlay(&vanilla, &packs, &out).unwrap();
let read = |rel: &str| fs::read(out.join(rel)).ok();
let texture = |id: &str| read(&format!("assets/ia/textures/{id}.png"));
assert_eq!(texture("0").as_deref(), Some(&b"box"[..]));
assert_eq!(read("assets/ia/textures/0.png.mcmeta"), None);
// A vanilla resource comes with its animation.
assert_eq!(texture("1199").as_deref(), Some(&b"lantern"[..]));
assert_eq!(
read("assets/ia/textures/1199.png.mcmeta").as_deref(),
Some(&animation[..])
);
// A texture that is there stays itself: other sources may read it (here as `ia:3`'s
// resource; an unstitched or paletted sprite's input alike).
assert_eq!(
read("assets/minecraft/textures/item/stick.png").as_deref(),
Some(&b"vanilla stick"[..])
);
// ...with its `.mcmeta` only where no filter hides it.
assert_eq!(texture("3").as_deref(), Some(&b"vanilla stick"[..]));
assert_eq!(read("assets/ia/textures/3.png.mcmeta"), None);
// A missing resource adds nothing, and no rename leaves the overlay.
assert_eq!(texture("2"), None);
assert!(!out.join("escape.png").exists());
// The last source of a sprite wins: a filter drops it, a later rename replaces it.
assert_eq!(texture("7"), None);
assert_eq!(texture("8").as_deref(), Some(&b"lantern"[..]));
// The two atlases read one file, and disagree about `ia:9`: it gets neither.
assert_eq!(texture("9"), None);
let _ = fs::remove_dir_all(base);
}
#[test]
fn every_file_of_a_big_stack_comes_from_its_top_pack() {
use std::io::Write as _;
let base = std::env::temp_dir().join(format!("horizon-pack-stack-{}", std::process::id()));
@@ -13,7 +13,8 @@ use std::{collections::BTreeSet, fs, io, path::Path, path::PathBuf};
// Version 5 read every vanilla file to stamp it on Windows.
// Version 6 stamps vanilla's files by their metadata on Windows too.
// Version 7 stacks blockstate files (every pack's definition, bottom first).
const VERSION: u32 = 8;
// Version 8 left an atlas `single` source's renamed sprite without its texture file (#14485).
const VERSION: u32 = 9;
#[derive(Default, Serialize, Deserialize)]
pub(super) struct Dependencies {
+119 -105
View File
@@ -1402,100 +1402,8 @@ impl ParticleLightCache {
}
}
const PARTICLE_SECTION_CACHE_SIZE: usize = 128;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SectionFrustumResult {
Outside,
Intersects,
Inside,
}
#[derive(Clone, Copy)]
struct CachedSectionFrustum {
section: [i32; 3],
radius_quarters: i32,
result: SectionFrustumResult,
}
struct ParticleSectionFrustumCache {
entries: [Option<CachedSectionFrustum>; PARTICLE_SECTION_CACHE_SIZE],
}
impl Default for ParticleSectionFrustumCache {
fn default() -> Self {
Self {
entries: [None; PARTICLE_SECTION_CACHE_SIZE],
}
}
}
impl ParticleSectionFrustumCache {
fn result(
&mut self,
world: [f64; 3],
camera: DVec3,
radius: f64,
frustum: &crate::gfx::Frustum,
) -> SectionFrustumResult {
let Some(section) = world_section(world) else {
return SectionFrustumResult::Intersects;
};
if !radius.is_finite() || radius < 0.0 || radius * 4.0 > f64::from(i32::MAX) {
return SectionFrustumResult::Intersects;
}
let radius_quarters = (radius * 4.0).ceil() as i32;
let hash = (section[0] as u32).wrapping_mul(73_856_093)
^ (section[1] as u32).wrapping_mul(19_349_663)
^ (section[2] as u32).wrapping_mul(83_492_791)
^ (radius_quarters as u32).wrapping_mul(2_654_435_761);
let slot = hash as usize & (PARTICLE_SECTION_CACHE_SIZE - 1);
if let Some(entry) = self.entries[slot]
&& entry.section == section
&& entry.radius_quarters == radius_quarters
{
return entry.result;
}
let pad = f64::from(radius_quarters) * 0.25;
let camera = camera.to_array();
let min = array::from_fn(|axis| f64::from(section[axis]) * 16.0 - pad - camera[axis]);
let max = array::from_fn(|axis| min[axis] + 16.0 + 2.0 * pad);
let result = if min.into_iter().chain(max).any(|v| !v.is_finite()) {
SectionFrustumResult::Intersects
} else {
let min = FVec3::from_array(min.map(|v| v as f32));
let max = FVec3::from_array(max.map(|v| v as f32));
if !min.is_finite() || !max.is_finite() {
SectionFrustumResult::Intersects
} else if frustum.contains(min, max) {
SectionFrustumResult::Inside
} else if frustum.intersects(min, max) {
SectionFrustumResult::Intersects
} else {
SectionFrustumResult::Outside
}
};
self.entries[slot] = Some(CachedSectionFrustum {
section,
radius_quarters,
result,
});
result
}
}
fn world_section(position: [f64; 3]) -> Option<[i32; 3]> {
let mut block = [0; 3];
for axis in 0..3 {
let value = position[axis].floor();
if !value.is_finite() || value < f64::from(i32::MIN) || value > f64::from(i32::MAX) {
return None;
}
block[axis] = value as i32;
}
Some([block[0] >> 4, block[1] >> 4, block[2] >> 4])
}
mod view_cull;
use view_cull::{PARTICLE_FRUSTUM_OFFSET, ParticleSectionFrustumCache, SectionFrustumResult};
fn below_half_pixel(radius: f64, distance_squared: f64, pixel_focal_length: f32) -> bool {
let projected_limit = 4.0 * radius * f64::from(pixel_focal_length);
@@ -4703,16 +4611,7 @@ impl ParticleEngine {
light_at: &dyn Fn([i32; 3]) -> u8,
out: &mut Vec<Vertex>,
) {
self.render_inner::<false>(
camera,
base,
partial,
0.0,
None,
&mut |_, _| false,
light_at,
out,
);
self.render_in_view(camera, base, partial, None, light_at, out);
}
/// Render particles after rejecting view-frustum misses and any particles
@@ -4730,7 +4629,7 @@ impl ParticleEngine {
out: &mut Vec<Vertex>,
) {
if !culling_enabled {
self.render(camera, base, partial, light_at, out);
self.render_in_view(camera, base, partial, frustum, light_at, out);
return;
}
self.render_inner::<true>(
@@ -4761,10 +4660,16 @@ impl ParticleEngine {
additive.clear();
let mut section_cache =
(CULL && frustum.is_some()).then(ParticleSectionFrustumCache::default);
let view = frustum.map(|f| f.pulled_back(PARTICLE_FRUSTUM_OFFSET));
for p in &self.particles {
if p.no_render {
continue;
}
if let Some(view) = &view
&& !view_cull::in_view(view, p, camera)
{
continue;
}
// SparkParticle.extract: twinkling sparks blink after a third of their life.
if let Behaviour::Spark { twinkle: true, .. } = p.behaviour
&& p.age >= p.lifetime / 3
@@ -5199,6 +5104,115 @@ mod tests {
assert_eq!(attributes(&disabled), attributes(&regular));
}
/// An engine whose smoke particles stand at `positions`, camera-relative (the camera is at
/// the origin looking down -z, like `Mat4::IDENTITY` as a view).
fn smoke_at(positions: &[[f64; 3]]) -> ParticleEngine {
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
let sprite = "test:smoke".to_owned();
engine.atlas.insert(
sprite.clone(),
(
Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 16,
h: 16,
},
false,
),
);
let mut random = LegacyRandom::new(7);
for &at in positions {
let mut particle = Particle::moving(&mut random, ParticleType::Smoke, at, [0.0; 3]);
particle.sprite = Sprite::Named(sprite.clone());
engine.particles.push(particle);
}
engine
}
fn quad_vertices(engine: &ParticleEngine, view: Option<&crate::gfx::Frustum>) -> usize {
let mut out = Vec::new();
engine.render_in_view(DVec3::ZERO, Quat::IDENTITY, 0.5, view, &|_| 0xf0, &mut out);
out.len()
}
#[test]
fn particles_outside_the_pulled_back_frustum_make_no_quads() {
use crate::gfx::{Frustum, world_projection};
let view = Frustum::from_view_projection(world_projection(70.0, 16.0 / 9.0, 512.0));
let kept = [
[0.0, 0.0, -5.0], // straight ahead
[0.0, 0.0, 2.5], // behind the camera, inside the 3 blocks of offset
[0.0, 0.0, -300.0], // far, inside the far plane
];
let dropped = [
[0.0, 0.0, 10.0], // well behind the camera
[0.0, 0.0, 3.5], // just past the offset
[100.0, 0.0, -5.0], // far to the side
[0.0, 60.0, -5.0], // far above
[0.0, 0.0, -600.0], // beyond the far plane
];
let all: Vec<_> = kept.iter().chain(&dropped).copied().collect();
let engine = smoke_at(&all);
let only_kept = quad_vertices(&smoke_at(&kept), None);
assert!(only_kept > 0);
assert_eq!(quad_vertices(&engine, Some(&view)), only_kept);
// Without a view every particle is drawn, as before.
assert_eq!(
quad_vertices(&engine, None),
only_kept * all.len() / kept.len()
);
// `render` is the same as no view.
let mut regular = Vec::new();
engine.render(DVec3::ZERO, Quat::IDENTITY, 0.5, &|_| 0xf0, &mut regular);
assert_eq!(regular.len(), quad_vertices(&engine, None));
}
#[test]
fn the_culled_path_applies_the_same_frustum_test() {
use crate::gfx::{Frustum, world_projection};
let view = Frustum::from_view_projection(world_projection(70.0, 16.0 / 9.0, 512.0));
let engine = smoke_at(&[[0.0, 0.0, -5.0], [0.0, 0.0, 10.0]]);
let mut out = Vec::new();
// The disabled setting still keeps vanilla's always-on test.
engine.render_culled(
DVec3::ZERO,
Quat::IDENTITY,
0.5,
900.0,
false,
Some(&view),
|_, _| panic!("disabled culling must not query particle visibility"),
&|_| 0xf0,
&mut out,
);
assert_eq!(
out.len(),
quad_vertices(&smoke_at(&[[0.0, 0.0, -5.0]]), None)
);
}
#[test]
fn a_particle_is_tested_at_its_position_this_tick_not_an_interpolated_one() {
use crate::gfx::{Frustum, world_projection};
let view = Frustum::from_view_projection(world_projection(70.0, 16.0 / 9.0, 512.0));
// The frame is drawn half way (0.5) between `previous` and `position`.
// Ahead now, far behind a tick ago (half way: 12.5 behind, outside): kept.
let mut coming = smoke_at(&[[0.0, 0.0, -5.0]]);
coming.particles[0].previous = [0.0, 0.0, 30.0];
assert!(quad_vertices(&coming, None) > 0);
assert_eq!(
quad_vertices(&coming, Some(&view)),
quad_vertices(&coming, None)
);
// Behind now, ahead a tick ago (half way: 5 ahead, inside): dropped.
let mut going = smoke_at(&[[0.0, 0.0, 10.0]]);
going.particles[0].previous = [0.0, 0.0, -20.0];
assert_eq!(quad_vertices(&going, Some(&view)), 0);
}
#[test]
fn quads_face_the_rotation_they_are_given() {
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
@@ -0,0 +1,138 @@
//! The camera's view frustum for particles: vanilla's always-on point test, and the section
//! cache behind the opt-in Particle Culling setting.
use super::{Particle, ParticleEngine, Vertex};
use glam::{DVec3, Quat, Vec3 as FVec3};
use std::array;
const PARTICLE_SECTION_CACHE_SIZE: usize = 128;
/// How far back, in blocks, the camera's frustum is pulled for the particle test (vanilla's
/// `Frustum.offset` in `ParticleEngine.extract`).
pub(super) const PARTICLE_FRUSTUM_OFFSET: f32 = 3.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SectionFrustumResult {
Outside,
Intersects,
Inside,
}
#[derive(Clone, Copy)]
struct CachedSectionFrustum {
section: [i32; 3],
radius_quarters: i32,
result: SectionFrustumResult,
}
pub(super) struct ParticleSectionFrustumCache {
entries: [Option<CachedSectionFrustum>; PARTICLE_SECTION_CACHE_SIZE],
}
impl Default for ParticleSectionFrustumCache {
fn default() -> Self {
Self {
entries: [None; PARTICLE_SECTION_CACHE_SIZE],
}
}
}
impl ParticleSectionFrustumCache {
pub(super) fn result(
&mut self,
world: [f64; 3],
camera: DVec3,
radius: f64,
frustum: &crate::gfx::Frustum,
) -> SectionFrustumResult {
let Some(section) = world_section(world) else {
return SectionFrustumResult::Intersects;
};
if !radius.is_finite() || radius < 0.0 || radius * 4.0 > f64::from(i32::MAX) {
return SectionFrustumResult::Intersects;
}
let radius_quarters = (radius * 4.0).ceil() as i32;
let hash = (section[0] as u32).wrapping_mul(73_856_093)
^ (section[1] as u32).wrapping_mul(19_349_663)
^ (section[2] as u32).wrapping_mul(83_492_791)
^ (radius_quarters as u32).wrapping_mul(2_654_435_761);
let slot = hash as usize & (PARTICLE_SECTION_CACHE_SIZE - 1);
if let Some(entry) = self.entries[slot]
&& entry.section == section
&& entry.radius_quarters == radius_quarters
{
return entry.result;
}
let pad = f64::from(radius_quarters) * 0.25;
let camera = camera.to_array();
let min = array::from_fn(|axis| f64::from(section[axis]) * 16.0 - pad - camera[axis]);
let max = array::from_fn(|axis| min[axis] + 16.0 + 2.0 * pad);
let result = if min.into_iter().chain(max).any(|v| !v.is_finite()) {
SectionFrustumResult::Intersects
} else {
let min = FVec3::from_array(min.map(|v| v as f32));
let max = FVec3::from_array(max.map(|v| v as f32));
if !min.is_finite() || !max.is_finite() {
SectionFrustumResult::Intersects
} else if frustum.contains(min, max) {
SectionFrustumResult::Inside
} else if frustum.intersects(min, max) {
SectionFrustumResult::Intersects
} else {
SectionFrustumResult::Outside
}
};
self.entries[slot] = Some(CachedSectionFrustum {
section,
radius_quarters,
result,
});
result
}
}
fn world_section(position: [f64; 3]) -> Option<[i32; 3]> {
let mut block = [0; 3];
for axis in 0..3 {
let value = position[axis].floor();
if !value.is_finite() || value < f64::from(i32::MIN) || value > f64::from(i32::MAX) {
return None;
}
block[axis] = value as i32;
}
Some([block[0] >> 4, block[1] >> 4, block[2] >> 4])
}
/// Whether `QuadParticleGroup`'s test keeps `particle`: its position this tick (camera-relative, not
/// interpolated) is on or inside `view`, the camera's frustum pulled back [`PARTICLE_FRUSTUM_OFFSET`] blocks.
pub(super) fn in_view(view: &crate::gfx::Frustum, particle: &Particle, camera: DVec3) -> bool {
let at = DVec3::from_array(particle.position) - camera;
view.contains_point(at.as_vec3())
}
impl ParticleEngine {
/// [`Self::render`], keeping only the particles inside `view`, the camera's frustum pulled
/// back [`PARTICLE_FRUSTUM_OFFSET`] blocks (vanilla's `ParticleEngine.extract` and
/// `QuadParticleGroup`): the test runs whatever the Particle Culling setting says. With
/// `None`, every particle is drawn.
pub fn render_in_view(
&self,
camera: DVec3,
base: Quat,
partial: f32,
view: Option<&crate::gfx::Frustum>,
light_at: &dyn Fn([i32; 3]) -> u8,
out: &mut Vec<Vertex>,
) {
self.render_inner::<false>(
camera,
base,
partial,
0.0,
view,
&mut |_, _| false,
light_at,
out,
);
}
}
@@ -0,0 +1,406 @@
//! A stopped sampler session as the capture's `samples` message (docs/perf-platform.md §3.5).
use std::collections::HashMap;
use horizon_perf_format::Interner;
use horizon_perf_format::v1::{
BlockUnits, Contexts, Functions, Nodes, Overhead, SampleKind, SampleProfile, SampleSource,
SampleUnit, SampledThread, Side, Unit, Weights,
};
use horizon_threads::heap_sample::HeapProfile;
use horizon_threads::profile::{Aggregate, Frame, Profile, State, Symbols, symbolize};
use horizon_threads::work::{self, Space};
#[cfg(test)]
mod tests;
const UNKNOWN: &str = "[unknown]";
/// The name `work::set_dim` ids stand for: 1 overworld, 2 the nether, 3 the end.
fn dimension_name(id: u8) -> Option<&'static str> {
match id {
1 => Some("overworld"),
2 => Some("the_nether"),
3 => Some("the_end"),
_ => None,
}
}
/// The crate a demangled function name belongs to, or "" when it names none.
fn crate_of(name: &str) -> &str {
if let Some(inner) = name.strip_prefix('[') {
let module = inner.split([' ', ']']).next().unwrap_or("");
return if module == "unmapped" { "" } else { module };
}
let name = name.trim_start_matches(['<', '&', '*']);
let name = name.strip_prefix("dyn ").unwrap_or(name);
match name.split_once("::") {
Some((krate, _)) if krate.chars().all(|c| c.is_alphanumeric() || c == '_') => krate,
_ => "",
}
}
#[derive(Default)]
struct FunctionTable {
rows: Functions,
index: HashMap<(u32, u32), u32>,
allocator: Vec<bool>,
}
impl FunctionTable {
fn id(
&mut self,
strings: &mut Interner,
name: &str,
file: Option<&str>,
line: u32,
addr: u64,
) -> u32 {
let (name_id, file_id) = (
strings.intern(name),
file.map_or(0, |file| strings.intern(file)),
);
if let Some(&row) = self.index.get(&(name_id, file_id)) {
return row;
}
let row = self.rows.name.len() as u32;
self.rows.name.push(name_id);
self.rows.file.push(file_id);
self.rows.line.push(line);
self.rows.crate_.push(match crate_of(name) {
"" => 0,
krate => strings.intern(krate),
});
self.rows.addr.push(addr);
self.allocator.push(allocator_frame(name));
self.index.insert((name_id, file_id), row);
row
}
}
/// The thread each trie node belongs to; node 0 is the root.
fn thread_of(agg: &Aggregate) -> Vec<u16> {
let mut of = vec![0u16; agg.nodes()];
for n in 1..agg.nodes() {
of[n] = match agg.frame(n as u32) {
Frame::Thread(i) => i,
_ => of[agg.parent(n as u32) as usize],
};
}
of
}
/// The trie nodes some counted sample passes through.
fn live_nodes(agg: &Aggregate) -> Vec<bool> {
let mut live = vec![false; agg.nodes()];
for key in agg.counts.keys() {
let mut n = key.node as usize;
while n != 0 && !live[n] {
live[n] = true;
n = agg.parent(n as u32) as usize;
}
}
live
}
#[derive(Default)]
struct NodeTable {
rows: Nodes,
index: HashMap<(Option<u32>, u32, u16), u32>,
}
impl NodeTable {
fn id(&mut self, parent: Option<u32>, function: u32, thread: u16) -> u32 {
let key = (parent, function, if parent.is_none() { thread } else { 0 });
if let Some(&row) = self.index.get(&key) {
return row;
}
let nodes = &mut self.rows;
nodes.parent.push(parent.unwrap_or(0));
nodes.function.push(function);
nodes.thread_root.push(match parent {
None => u32::from(thread) + 1,
Some(_) => 0,
});
let row = nodes.parent.len() as u32 - 1;
self.index.insert(key, row);
row
}
}
fn named(strings: &mut Interner, space: Space, id: u16) -> u32 {
match id {
0 => 0,
id => match work::name(space, id) {
Some(name) => strings.intern(name),
None => strings.intern(&format!("#{id}")),
},
}
}
/// Whether `name` is the allocator's own frame, which a heap sample's stack drops from its leaf end.
fn allocator_frame(name: &str) -> bool {
let name = name.trim_start_matches('<');
name.starts_with("horizon_threads::heap_sample::")
|| name.starts_with("__rust")
|| name.starts_with("__rg_")
|| name.starts_with("__rdl_")
|| name.starts_with("alloc::alloc::")
|| name.starts_with("alloc::raw_vec::")
|| name.starts_with("mimalloc::")
}
/// One aggregate's trie nodes as rows of the shared tables: `last[n]` is the output node of trie node `n`.
fn add_tree(
agg: &Aggregate,
threads: &[u16],
symbols: &Symbols,
functions: &mut FunctionTable,
nodes: &mut NodeTable,
strings: &mut Interner,
) -> (Vec<u16>, Vec<Option<u32>>) {
let (local, live) = (thread_of(agg), live_nodes(agg));
let thread_of: Vec<u16> = local
.iter()
.map(|&t| threads.get(usize::from(t)).copied().unwrap_or(0))
.collect();
let mut last: Vec<Option<u32>> = vec![None; agg.nodes()];
for n in (1..agg.nodes()).filter(|&n| live[n]) {
let inherited = last[agg.parent(n as u32) as usize];
last[n] = match agg.frame(n as u32) {
Frame::Thread(_) => None,
Frame::Wall(_) => inherited,
Frame::Addr(addr) => {
let offset = symbols.module_offset(addr);
let mut at = inherited;
for sym in symbols.frames(addr).iter().rev() {
let f = functions.id(strings, &sym.name, sym.file.as_deref(), sym.line, offset);
at = Some(nodes.id(at, f, thread_of[n]));
}
if at == inherited {
let f = functions.id(strings, UNKNOWN, None, 0, offset);
at = Some(nodes.id(at, f, thread_of[n]));
}
at
}
};
}
(thread_of, last)
}
fn trie_addrs(agg: &Aggregate) -> impl Iterator<Item = u64> + '_ {
let live = live_nodes(agg);
(1..agg.nodes())
.filter(move |&n| live[n])
.filter_map(|n| match agg.frame(n as u32) {
Frame::Addr(a) => Some(a),
_ => None,
})
}
/// `profile` (and the heap session's `heap`) as a `SampleProfile` of `side`; strings go through `strings`, whose new entries the caller appends first.
pub fn sample_profile(
profile: &Profile,
heap: Option<&HeapProfile>,
side: Side,
unit: Unit,
block_name: &dyn Fn(u16) -> Option<String>,
strings: &mut Interner,
) -> SampleProfile {
let agg = &profile.agg;
let addrs: Vec<u64> = trie_addrs(agg)
.chain(heap.into_iter().flat_map(|h| trie_addrs(&h.agg)))
.collect();
let symbols = symbolize(addrs);
let mut names: Vec<String> = agg.threads.clone();
let cpu_threads: Vec<u16> = (0..agg.threads.len() as u16).collect();
let heap_threads: Vec<u16> = heap.map_or_else(Vec::new, |h| {
h.agg
.threads
.iter()
.map(|name| match names.iter().position(|n| n == name) {
Some(at) => at as u16,
None => {
names.push(name.clone());
names.len() as u16 - 1
}
})
.collect()
});
let mut functions = FunctionTable::default();
let mut nodes = NodeTable::default();
let mut trees = vec![(
agg,
add_tree(
agg,
&cpu_threads,
&symbols,
&mut functions,
&mut nodes,
strings,
),
)];
if let Some(h) = heap {
let tree = add_tree(
&h.agg,
&heap_threads,
&symbols,
&mut functions,
&mut nodes,
strings,
);
trees.push((&h.agg, tree));
}
let wall = agg.counts.keys().any(|k| k.state != State::Cpu);
let period_ms = 1000.0 / f64::from(profile.config.sampler.hz.max(1));
let kind = |source: SampleSource, unit: SampleUnit, period: f64| SampleKind {
source: source as i32,
unit: unit as i32,
period,
};
let mut kinds = vec![kind(SampleSource::Cpu, SampleUnit::Ms, period_ms)];
if wall {
kinds.push(kind(SampleSource::Wall, SampleUnit::Ms, period_ms));
}
if heap.is_some() {
kinds.push(kind(SampleSource::Alloc, SampleUnit::Bytes, 1.0));
kinds.push(kind(SampleSource::Live, SampleUnit::Bytes, 1.0));
}
let kind_of = |state: State| -> u32 {
let source = match state {
State::Cpu => SampleSource::Cpu,
State::Running | State::Waiting => SampleSource::Wall,
State::Alloc => SampleSource::Alloc,
State::Live => SampleSource::Live,
};
kinds
.iter()
.position(|k| k.source == source as i32)
.unwrap_or(0) as u32
};
let mut contexts = Contexts::default();
let mut context_ids: HashMap<[u32; 6], u32> = HashMap::new();
let mut weights = Weights::default();
let mut unknown_roots: HashMap<u16, u32> = HashMap::new();
for (agg, (thread_of, last)) in &trees {
let mut counted: Vec<_> = agg.counts.iter().collect();
counted.sort_by_key(|(k, _)| {
(
thread_of[k.node as usize],
k.node,
k.state as u8,
k.slow,
k.time_block,
(k.span, k.entity, k.block, k.dim, k.chunk),
)
});
for (key, &count) in counted {
let thread = thread_of[key.node as usize];
let mut node = match last[key.node as usize] {
Some(node) => node,
None => *unknown_roots.entry(thread).or_insert_with(|| {
let f = functions.id(strings, UNKNOWN, None, 0, 0);
nodes.id(None, f, thread)
}),
};
if matches!(key.state, State::Alloc | State::Live) {
while nodes.rows.thread_root[node as usize] == 0
&& functions.allocator[nodes.rows.function[node as usize] as usize]
{
node = nodes.rows.parent[node as usize];
}
}
let row = [
named(strings, Space::Span, key.span),
named(strings, Space::Entity, key.entity),
match key.block {
0 => 0,
id => match block_name(id) {
Some(name) => strings.intern(&name),
None => strings.intern(&format!("#{id}")),
},
},
dimension_name(key.dim).map_or(0, |name| strings.intern(name)),
key.chunk.0 as u32,
key.chunk.1 as u32,
];
let context = *context_ids.entry(row).or_insert_with(|| {
contexts.span.push(row[0]);
contexts.entity.push(row[1]);
contexts.block.push(row[2]);
contexts.dim.push(row[3]);
contexts.chunk_x.push(key.chunk.0);
contexts.chunk_z.push(key.chunk.1);
contexts.span.len() as u32 - 1
});
weights.node.push(node);
weights.thread.push(u32::from(thread));
weights.kind.push(kind_of(key.state));
weights.state.push(match key.state {
State::Running => 1,
State::Waiting => 2,
State::Cpu | State::Alloc | State::Live => 0,
});
weights.slow.push(key.slow);
weights.context.push(context);
weights.block.push(u32::from(key.time_block));
weights.count.push(count);
}
}
let blocks = agg.time_blocks();
let mut threads = Vec::new();
let mut block_units = Vec::new();
for (i, name) in names.iter().enumerate() {
let ticks = agg.ticks.get(&(i as u16)).filter(|_| i < agg.threads.len());
threads.push(SampledThread {
name: strings.intern(name),
units: ticks.map_or(0, |t| t.count),
slow_units: ticks.map_or(0, |t| t.slow),
unit: unit as i32,
});
if i >= agg.threads.len() {
continue;
}
let mut units = agg
.block_ticks
.get(&(i as u16))
.cloned()
.unwrap_or_default();
units.resize(blocks, 0);
block_units.push(BlockUnits {
thread: i as u32,
units,
});
}
SampleProfile {
side: side as i32,
kinds,
threads,
block_s: profile.config.block_s,
block_units,
functions: Some(functions.rows),
nodes: Some(nodes.rows),
contexts: Some(contexts),
weights: Some(weights),
slow_over_ms: profile.config.ticks_over_ms as f32,
}
}
/// What the sampler and its writer thread cost during the session.
pub fn overhead(profile: &Profile, heap: Option<&HeapProfile>) -> Overhead {
let wall_ns = profile.elapsed.as_nanos().max(1) as f64;
let handler_ns = profile.stats.handler_ns.unwrap_or(0.0) * profile.stats.samples as f64;
Overhead {
sampler_share_of_thread: (handler_ns / wall_ns) as f32,
writer_core_share: (profile.writer_cpu_ns as f64 / wall_ns) as f32,
dropped_samples: profile.stats.dropped + profile.agg.lost + heap.map_or(0, |h| h.agg.lost),
heap_samples: heap.map_or(0, |h| h.samples),
heap_sample_ns: heap.map_or(0, |h| h.sample_ns),
..Overhead::default()
}
}
@@ -0,0 +1,649 @@
use std::collections::HashMap;
use std::hint::black_box;
use std::sync::mpsc;
use std::thread;
use std::time::{Duration, SystemTime};
use horizon_perf_format::v1::{
Kind as CaptureKind, SampleProfile, Side, Start, Stop, StringEntry, Unit,
};
use horizon_perf_format::{CaptureWriter, Field};
use horizon_threads::profile::{self, Aggregate, Config, Profile};
use horizon_threads::sampler::{self, Context, Kind, Record, Stats};
use horizon_threads::unwind::MAX_FRAMES;
use horizon_threads::work;
use super::*;
#[inline(never)]
fn alpha() {
black_box(1);
}
#[inline(never)]
fn beta() {
black_box(2);
}
#[inline(never)]
fn gamma() {
black_box(3);
}
fn at(f: fn(), offset: usize) -> usize {
f as *const () as usize + offset
}
fn record(kind: Kind, ctx: Context, value: u64, stack: &[usize]) -> Record {
let mut frames = [0; MAX_FRAMES];
frames[..stack.len()].copy_from_slice(stack);
Record {
kind,
depth: stack.len() as u8,
ctx,
value,
frames,
}
}
fn profile_of(agg: Aggregate, config: Config) -> Profile {
Profile {
agg,
config,
stats: Stats::default(),
elapsed: Duration::from_secs(10),
started: SystemTime::now(),
writer_cpu_ns: 0,
}
}
struct Converted {
samples: SampleProfile,
strings: Vec<StringEntry>,
}
impl Converted {
fn text(&self, id: u32) -> &str {
match id {
0 => "",
id => &self.strings.iter().find(|s| s.id == id).unwrap().text,
}
}
fn function(&self, row: u32) -> &str {
self.text(self.samples.functions.as_ref().unwrap().name[row as usize])
}
/// Function names from the root down to `node`.
fn path(&self, node: u32) -> Vec<&str> {
let nodes = self.samples.nodes.as_ref().unwrap();
let mut path = vec![self.function(nodes.function[node as usize])];
let mut at = node as usize;
while nodes.thread_root[at] == 0 {
at = nodes.parent[at] as usize;
path.push(self.function(nodes.function[at]));
}
path.reverse();
path
}
/// Samples per entity name, optionally only the slow ones.
fn by_entity(&self, slow_only: bool) -> HashMap<String, u64> {
let (w, c) = (
self.samples.weights.as_ref().unwrap(),
self.samples.contexts.as_ref().unwrap(),
);
let mut by = HashMap::new();
for i in 0..w.node.len() {
if slow_only && !w.slow[i] {
continue;
}
let entity = self.text(c.entity[w.context[i] as usize]).to_owned();
*by.entry(entity).or_default() += w.count[i];
}
by
}
}
fn convert(profile: &Profile) -> Converted {
let mut interner = Interner::default();
let samples = sample_profile(
profile,
None,
Side::Server,
Unit::Tick,
&|id| (id == 7).then(|| "minecraft:hopper".to_owned()),
&mut interner,
);
Converted {
samples,
strings: interner.take_new(Side::Server),
}
}
fn short(name: &str) -> &str {
name.rsplit("::").next().unwrap()
}
#[test]
fn a_stack_becomes_a_root_to_leaf_chain_with_its_context() {
let entity = work::entity_id("test:zombie");
let ctx = Context {
tick: 1,
entity_type: entity,
block: 7,
dim: 2,
chunk: (-3, 9),
..Context::default()
};
let mut agg = Aggregate::new(50_000_000);
for _ in 0..5 {
agg.add(
"tick",
&record(Kind::Cpu, ctx, 0, &[at(alpha, 4), at(gamma, 3)]),
);
}
agg.add("tick", &record(Kind::Tick, ctx, 9_000_000, &[]));
agg.finish();
let c = convert(&profile_of(agg, Config::default()));
let w = c.samples.weights.as_ref().unwrap();
assert_eq!(
(w.node.len(), w.count[0], w.state[0], w.slow[0]),
(1, 5, 0, false)
);
let path: Vec<_> = c.path(w.node[0]).into_iter().map(short).collect();
assert_eq!(path, ["gamma", "alpha"]);
let nodes = c.samples.nodes.as_ref().unwrap();
assert_eq!(nodes.thread_root, [1, 0]);
let ctxs = c.samples.contexts.as_ref().unwrap();
let row = w.context[0] as usize;
assert_eq!(c.text(ctxs.entity[row]), "test:zombie");
assert_eq!(c.text(ctxs.block[row]), "minecraft:hopper");
assert_eq!(c.text(ctxs.dim[row]), "the_nether");
assert_eq!((ctxs.chunk_x[row], ctxs.chunk_z[row]), (-3, 9));
assert_eq!(c.text(c.samples.threads[0].name), "tick");
assert_eq!(
(c.samples.threads[0].units, c.samples.threads[0].slow_units),
(1, 0)
);
}
#[test]
fn addresses_of_one_function_share_one_row() {
let ctx = Context::default();
let mut agg = Aggregate::new(50_000_000);
for (inner, count) in [(4, 2), (8, 3)] {
for _ in 0..count {
agg.add(
"tick",
&record(Kind::Cpu, ctx, 0, &[at(alpha, inner), at(gamma, 3)]),
);
}
}
agg.add(
"tick",
&record(Kind::Cpu, ctx, 0, &[at(beta, 4), at(gamma, 3)]),
);
agg.finish();
let c = convert(&profile_of(agg, Config::default()));
let f = c.samples.functions.as_ref().unwrap();
let names: Vec<_> = (0..f.name.len() as u32)
.map(|row| short(c.function(row)))
.collect();
let mut sorted = names.clone();
sorted.sort_unstable();
assert_eq!(sorted, ["alpha", "beta", "gamma"]);
let w = c.samples.weights.as_ref().unwrap();
let on_alpha: u64 = (0..w.node.len())
.filter(|&i| short(c.path(w.node[i]).last().unwrap()) == "alpha")
.map(|i| w.count[i])
.sum();
assert_eq!(on_alpha, 5);
let n = c.samples.nodes.as_ref().unwrap();
let alphas: Vec<usize> = (0..n.function.len())
.filter(|&i| short(c.function(n.function[i])) == "alpha")
.collect();
assert_eq!(alphas.len(), 1, "one node per (parent, function)");
assert_eq!(
short(c.function(n.function[n.parent[alphas[0]] as usize])),
"gamma"
);
let weight_on_alpha: u64 = (0..w.node.len())
.filter(|&i| w.node[i] as usize == alphas[0])
.map(|i| w.count[i])
.sum();
assert_eq!(weight_on_alpha, 5);
let alpha_row = names.iter().position(|n| *n == "alpha").unwrap();
assert!(f.addr[alpha_row] > 0, "a module-relative address is kept");
}
#[test]
fn time_blocks_and_ticks_per_block_follow_when_they_were_added() {
let ctx = |tick| Context {
tick,
..Context::default()
};
let mut agg = Aggregate::new(50_000_000);
for (block, tick, samples) in [(0, 1, 2u64), (1, 2, 3), (1, 3, 1), (3, 4, 4)] {
agg.set_time_block(block);
for _ in 0..samples {
agg.add("tick", &record(Kind::Cpu, ctx(tick), 0, &[at(alpha, 1)]));
}
agg.add("tick", &record(Kind::Tick, ctx(tick), 1_000_000, &[]));
}
agg.finish();
let config = Config {
block_s: 2.5,
..Config::default()
};
let c = convert(&profile_of(agg, config));
let w = c.samples.weights.as_ref().unwrap();
let mut per_block = [0u64; 4];
for i in 0..w.node.len() {
per_block[w.block[i] as usize] += w.count[i];
}
assert_eq!(per_block, [2, 4, 0, 4]);
assert_eq!(c.samples.block_s, 2.5);
assert_eq!(c.samples.block_units[0].units, [1, 2, 0, 1]);
assert_eq!(c.samples.threads[0].units, 4);
}
#[test]
fn a_sample_with_no_stack_hangs_off_an_unknown_root() {
let mut agg = Aggregate::new(50_000_000);
agg.add("tick", &record(Kind::Cpu, Context::default(), 0, &[]));
agg.finish();
let c = convert(&profile_of(agg, Config::default()));
let w = c.samples.weights.as_ref().unwrap();
assert_eq!(c.path(w.node[0]), ["[unknown]"]);
}
#[test]
fn wall_samples_carry_their_state_and_a_second_kind() {
let mut agg = Aggregate::new(50_000_000);
let ctx = Context::default();
agg.add("tick", &record(Kind::Cpu, ctx, 0, &[at(alpha, 1)]));
agg.add("tick", &record(Kind::Wall, ctx, 1, &[at(alpha, 1)]));
agg.add("tick", &record(Kind::Wall, ctx, 0, &[at(beta, 1)]));
agg.finish();
let config = Config {
sampler: sampler::Config {
hz: 200,
..sampler::Config::default()
},
..Config::default()
};
let c = convert(&profile_of(agg, config));
assert_eq!(c.samples.kinds.len(), 2);
assert_eq!(c.samples.kinds[0].period, 5.0);
let w = c.samples.weights.as_ref().unwrap();
let mut seen: Vec<_> = (0..w.node.len())
.map(|i| {
(
short(c.path(w.node[i]).last().unwrap()).to_owned(),
w.kind[i],
w.state[i],
)
})
.collect();
seen.sort();
assert_eq!(
seen,
[
("alpha".into(), 0, 0),
("alpha".into(), 1, 1),
("beta".into(), 1, 2)
]
);
}
#[inline(never)]
fn spin_fast() {
spin(8);
black_box(0);
}
#[inline(never)]
fn spin_slow() {
spin(120);
black_box(1);
}
fn spin(cpu_ms: u64) {
let until = sampler::thread_cpu_ns() + cpu_ms * 1_000_000;
let mut x = 1u64;
while sampler::thread_cpu_ns() < until {
for _ in 0..1 << 14 {
x = black_box(x.wrapping_mul(6364136223846793005).wrapping_add(1));
}
}
black_box(x);
}
fn live_config() -> Config {
Config {
sampler: sampler::Config {
hz: 1000,
ring_samples: 512,
unwind: sampler::Unwind::StackCopy,
stack_copy_kib: 16,
wall: false,
},
ticks_over_ms: 50.0,
..Config::default()
}
}
/// Runs `body` on a thread opted in as `name`, profiled for exactly its duration.
fn profiled(name: &'static str, body: fn()) -> Profile {
let (ready, wait) = mpsc::channel();
let (go, start) = mpsc::channel::<()>();
let worker = thread::spawn(move || {
assert!(sampler::sampled_thread(name));
ready.send(()).unwrap();
start.recv().unwrap();
body();
});
wait.recv().unwrap();
let session = profile::start(Config {
threads: vec![name.into()],
..live_config()
})
.expect("start profiling");
go.send(()).unwrap();
worker.join().unwrap();
session.stop().expect("stop profiling")
}
fn entity_units() {
let (a, b) = (work::entity_id("test:a"), work::entity_id("test:b"));
for unit in 0..4 {
work::tick_start();
work::set_entity(if unit < 3 { a } else { b });
let started = sampler::thread_cpu_ns();
spin(40);
work::clear_work();
work::tick_end(sampler::thread_cpu_ns() - started);
}
}
#[test]
fn three_units_of_a_and_one_of_b_split_the_samples_three_to_one() {
let c = convert(&profiled("perf-capture-entities", entity_units));
let by = c.by_entity(false);
let total = (by["test:a"] + by["test:b"]) as f64;
let (a, b) = (by["test:a"] as f64 / total, by["test:b"] as f64 / total);
assert!((a - 0.75).abs() < 0.1 && (b - 0.25).abs() < 0.1, "{by:?}");
assert!(total > 100.0, "{total} samples");
assert_eq!(c.samples.threads[0].units, 4);
}
fn ticks_with_one_slow() {
for tick in 0..6 {
work::tick_start();
let started = sampler::thread_cpu_ns();
if tick == 3 {
spin_slow();
} else {
spin_fast();
}
work::tick_end(sampler::thread_cpu_ns() - started);
}
}
#[test]
fn only_the_slow_ticks_function_is_in_the_slow_weights() {
let c = convert(&profiled("perf-capture-slow", ticks_with_one_slow));
let w = c.samples.weights.as_ref().unwrap();
let (mut slow, mut fast) = (0, 0);
for i in 0..w.node.len() {
let names: Vec<_> = c.path(w.node[i]).into_iter().map(short).collect();
if w.slow[i] {
slow += w.count[i];
assert!(
names.contains(&"spin_slow") && !names.contains(&"spin_fast"),
"{names:?}"
);
} else {
fast += w.count[i];
assert!(!names.contains(&"spin_slow"), "{names:?}");
}
}
assert!(slow > 60 && fast > 20, "{slow} slow, {fast} other");
assert_eq!(
(c.samples.threads[0].units, c.samples.threads[0].slow_units),
(6, 1)
);
}
#[test]
fn overhead_counts_lost_samples_and_the_writers_share_of_a_core() {
let mut agg = Aggregate::new(1);
agg.lost = 4;
let mut profile = profile_of(agg, Config::default());
profile.stats.dropped = 3;
profile.stats.samples = 1000;
profile.stats.handler_ns = Some(2_000.0);
profile.writer_cpu_ns = 50_000_000;
let o = overhead(&profile, None);
assert_eq!(o.dropped_samples, 7);
assert!((o.sampler_share_of_thread - 0.0002).abs() < 1e-7);
assert!((o.writer_core_share - 0.005).abs() < 1e-6);
}
#[test]
fn crates_come_from_the_first_path_segment() {
for (name, krate) in [
(
"horizon_world::level::tick::random_tick_at",
"horizon_world",
),
(
"<horizon_world::X as core::ops::Drop>::drop",
"horizon_world",
),
("core::ptr::drop_in_place<alloc::vec::Vec<u8>>", "core"),
("clone3", ""),
("[horizon-server 0x4f2a]", "horizon-server"),
("[unmapped 0x7ffd]", ""),
] {
assert_eq!(crate_of(name), krate, "{name}");
}
}
fn ask(
file: &std::path::Path,
parts: &[&str],
) -> horizon_perf::wire::Envelope<horizon_perf::query::Row> {
let env = horizon_perf::cli::Env {
horizon_home: None,
poll: Duration::from_millis(2),
};
let mut args = vec!["query".to_owned()];
args.extend(parts.iter().map(|p| (*p).to_owned()));
args.push(file.to_string_lossy().into_owned());
let mut out = Vec::new();
if let Err(e) = horizon_perf::cli::run(&args, &env, &mut out) {
panic!("{e:?}");
}
serde_json::from_slice(&out)
.unwrap_or_else(|e| panic!("{e}: {}", String::from_utf8_lossy(&out)))
}
#[test]
fn a_converted_profile_written_to_a_file_reads_back_through_the_queries() {
let ctx = Context::default();
let mut agg = Aggregate::new(50_000_000);
for _ in 0..5 {
agg.add(
"tick",
&record(Kind::Cpu, ctx, 0, &[at(alpha, 4), at(gamma, 3)]),
);
}
for _ in 0..2 {
agg.add(
"tick",
&record(Kind::Cpu, ctx, 0, &[at(beta, 4), at(gamma, 3)]),
);
}
for _ in 0..2 {
agg.add("tick", &record(Kind::Tick, ctx, 9_000_000, &[]));
}
for _ in 0..3 {
agg.add("worker", &record(Kind::Cpu, ctx, 0, &[at(beta, 4)]));
}
agg.add("worker", &record(Kind::Tick, ctx, 9_000_000, &[]));
agg.finish();
let config = Config {
sampler: sampler::Config {
hz: 100,
..sampler::Config::default()
},
..Config::default()
};
let c = convert(&profile_of(agg, config));
let mut fields = vec![Field::Start(Start {
side: Side::Server as i32,
kind: CaptureKind::Dedicated as i32,
..Default::default()
})];
fields.extend(c.strings.into_iter().map(Field::String));
fields.push(Field::Samples(c.samples));
fields.push(Field::Stop(Stop {
side: Side::Server as i32,
t: 10.0,
..Default::default()
}));
let dir = std::env::temp_dir().join(format!("horizon-render-perf-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("real.hzperf");
let mut writer = CaptureWriter::new(std::fs::File::create(&file).unwrap()).unwrap();
for field in fields {
writer.write(field).unwrap();
}
writer.finish().unwrap();
// 10 ms samples: alpha has 5 over the tick thread's 2 ticks.
let hot = ask(&file, &["hot"]);
let alpha = hot.rows().iter().find_map(|r| match r {
horizon_perf::query::Row::Hot(h) if h.full.ends_with("alpha") => Some(h),
_ => None,
});
assert_eq!(alpha.map(|h| (h.self_ms, h.samples)), Some((25.0, 5)));
let worker = ask(&file, &["split", "t:worker", "--by", "thread"]);
let sel = worker.selection.as_ref().unwrap();
assert_eq!(
(sel.thread.as_deref(), sel.ticks, sel.samples),
(Some("worker"), Some(1), Some(3))
);
let values: Vec<_> = worker
.rows()
.iter()
.map(|r| match r {
horizon_perf::query::Row::Split(s) => (s.key.clone(), s.value),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(values, [(Some("t:worker".to_owned()), 30.0)]);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn heap_samples_share_the_tables_without_the_allocators_own_frames() {
let mut cpu = Aggregate::new(50_000_000);
cpu.add(
"tick",
&record(
Kind::Cpu,
Context::default(),
0,
&[at(alpha, 4), at(gamma, 3)],
),
);
cpu.finish();
let mut heap = Aggregate::new(0);
let inside = HeapProfile::bytes as *const () as usize + 4;
let on_tick = heap.thread_index("tick");
let key = heap.stack_key(
on_tick,
profile::State::Alloc,
&Context::default(),
&[inside, at(beta, 4), at(gamma, 3)],
);
heap.add_weight(key, 3000);
heap.add_weight(
profile::Key {
state: profile::State::Live,
..key
},
1000,
);
let on_worker = heap.thread_index("worker");
let key = heap.stack_key(
on_worker,
profile::State::Live,
&Context::default(),
&[inside, at(alpha, 4)],
);
heap.add_weight(key, 500);
let heap = HeapProfile {
agg: heap,
interval: 4096,
samples: 3,
live_samples: 2,
sample_ns: 0,
freed: 2000,
elapsed: Duration::from_secs(10),
};
let mut interner = Interner::default();
let samples = sample_profile(
&profile_of(cpu, Config::default()),
Some(&heap),
Side::Server,
Unit::Tick,
&|_| None,
&mut interner,
);
let c = Converted {
samples,
strings: interner.take_new(Side::Server),
};
let sources: Vec<_> = c
.samples
.kinds
.iter()
.map(|k| (k.source(), k.period))
.collect();
assert_eq!(
sources,
[
(SampleSource::Cpu, 4.0),
(SampleSource::Alloc, 1.0),
(SampleSource::Live, 1.0)
]
);
let names: Vec<_> = c.samples.threads.iter().map(|t| c.text(t.name)).collect();
assert_eq!(names, ["tick", "worker"]);
let w = c.samples.weights.as_ref().unwrap();
let mut rows: Vec<_> = (0..w.node.len())
.map(|i| {
let path: Vec<_> = c.path(w.node[i]).into_iter().map(short).collect();
(w.kind[i], w.thread[i], path.join(">"), w.count[i])
})
.collect();
rows.sort();
assert_eq!(
rows,
[
(0, 0, "gamma>alpha".to_owned(), 1),
(1, 0, "gamma>beta".to_owned(), 3000),
(2, 0, "gamma>beta".to_owned(), 1000),
(2, 1, "alpha".to_owned(), 500),
]
);
let o = overhead(
&profile_of(Aggregate::new(0), Config::default()),
Some(&heap),
);
assert_eq!(o.heap_samples, 3);
}
@@ -0,0 +1,484 @@
//! The GPU pass timers' readings as the capture's `gpu` messages (docs/perf-platform.md §3.5); apart from `perf_capture`, which only Linux has.
use horizon_perf_format::Interner;
use horizon_perf_format::v1::{
GpuBackend, GpuCounter, GpuCounts, GpuDevice, GpuFragmentUnit, GpuFrame, GpuFrames, GpuPart,
GpuPartCounts, GpuPartsMode, GpuPass, GpuPassSplit, GpuPasses, GpuSource, Side,
};
use std::time::Instant;
use crate::gfx::pack_timing::{
Counters, FragmentUnit, GpuReadout, PartsMode, PassCounters, Readings, TimedFrame, TimedFrames,
};
/// Every time one timer's frames gave a pass or a part during a capture.
#[derive(Default)]
struct Times {
passes: Vec<(String, Vec<f32>)>,
parts: Vec<(String, Vec<(String, Vec<f32>)>)>,
}
fn times_of<'a>(list: &'a mut Vec<(String, Vec<f32>)>, name: &str) -> &'a mut Vec<f32> {
let i = match list.iter().position(|e| e.0 == name) {
Some(i) => i,
None => {
list.push((name.to_owned(), Vec::new()));
list.len() - 1
}
};
&mut list[i].1
}
impl Times {
fn add(&mut self, frame: &TimedFrame) {
for (pass, ms) in &frame.passes {
times_of(&mut self.passes, pass).push(*ms);
}
for (pass, parts) in &frame.parts {
let i = match self.parts.iter().position(|e| e.0 == *pass) {
Some(i) => i,
None => {
self.parts.push((pass.clone(), Vec::new()));
self.parts.len() - 1
}
};
for (part, ms) in parts {
times_of(&mut self.parts[i].1, part).push(*ms);
}
}
}
fn is_empty(&self) -> bool {
self.passes.is_empty() && self.parts.is_empty()
}
/// `readings` with its times the medians over the whole capture instead of its last frames.
fn medians_into(&self, readings: &Readings) -> Readings {
let median = |v: &[f32]| {
let mut v = v.to_vec();
v.sort_by(f32::total_cmp);
v[v.len() / 2]
};
Readings {
passes: self
.passes
.iter()
.map(|(name, v)| (name.clone(), median(v)))
.collect(),
parts: self
.parts
.iter()
.map(|(pass, parts)| {
let parts = parts.iter().map(|(n, v)| (n.clone(), median(v))).collect();
(pass.clone(), parts)
})
.collect(),
..readings.clone()
}
}
}
/// A capture's timed frames on their way into `GpuFrames` blocks, every time kept for the whole capture's medians.
#[derive(Default)]
pub struct FrameLog {
pending: Vec<GpuFrame>,
cpu_frame_ms: Vec<f32>,
own: Times,
pack: Times,
}
impl FrameLog {
/// The CPU's own ms of one frame the window drew.
pub fn cpu_frame(&mut self, ms: f32) {
self.cpu_frame_ms.push(ms);
}
/// The frames timed since the last call; `t_of` puts a frame's start on the capture clock.
pub fn add(
&mut self,
frames: &TimedFrames,
t_of: impl Fn(Instant) -> f64,
strings: &mut Interner,
) {
for (source, list, times) in [
(GpuSource::Horizon, &frames.own, &mut self.own),
(GpuSource::ShaderPack, &frames.pack, &mut self.pack),
] {
for frame in list {
times.add(frame);
self.pending
.push(frame_message(frame, source, t_of(frame.at), strings));
}
}
}
/// The frames and CPU frame times since the last block; none when there are neither.
pub fn take_block(&mut self, side: Side) -> Option<GpuFrames> {
if self.pending.is_empty() && self.cpu_frame_ms.is_empty() {
return None;
}
Some(GpuFrames {
side: side as i32,
frames: std::mem::take(&mut self.pending),
cpu_frame_ms: std::mem::take(&mut self.cpu_frame_ms),
})
}
}
fn frame_message(
frame: &TimedFrame,
source: GpuSource,
t: f64,
strings: &mut Interner,
) -> GpuFrame {
let mut passes: Vec<GpuPass> = frame
.passes
.iter()
.map(|(name, ms)| GpuPass {
name: strings.intern(name),
ms: Some(*ms),
parts: Vec::new(),
})
.collect();
for (pass, parts) in &frame.parts {
let parts = parts
.iter()
.map(|(part, ms)| GpuPart {
name: strings.intern(part),
ms: *ms,
})
.collect();
let name = strings.intern(pass);
match passes.iter_mut().find(|p| p.name == name) {
Some(p) => p.parts = parts,
None => passes.push(GpuPass {
name,
ms: None,
parts,
}),
}
}
GpuFrame {
source: source as i32,
t,
total_ms: frame.total_ms,
passes,
}
}
fn backend(backend: wgpu::Backend) -> GpuBackend {
match backend {
wgpu::Backend::Vulkan => GpuBackend::Vulkan,
wgpu::Backend::Metal => GpuBackend::Metal,
wgpu::Backend::Dx12 => GpuBackend::Dx12,
wgpu::Backend::Gl => GpuBackend::Gl,
_ => GpuBackend::Other,
}
}
fn counts(c: Counters) -> GpuCounts {
GpuCounts {
vertex_shader_invocations: c.vertex_shader_invocations,
clipper_invocations: c.clipper_invocations,
clipper_primitives_out: c.clipper_primitives_out,
fragment_shader_invocations: c.fragment_shader_invocations,
}
}
fn counter(strings: &mut Interner, pass: &str, c: &PassCounters) -> GpuCounter {
GpuCounter {
pass: strings.intern(pass),
total: Some(counts(c.total)),
pixels: c.pixels,
parts: c
.parts
.iter()
.map(|(name, part)| GpuPartCounts {
name: strings.intern(name),
counts: Some(counts(*part)),
})
.collect(),
}
}
fn device(adapter: &wgpu::AdapterInfo, readings: &Readings) -> GpuDevice {
let driver = format!("{} {}", adapter.driver, adapter.driver_info);
GpuDevice {
adapter: adapter.name.clone(),
backend: backend(adapter.backend) as i32,
driver: driver.trim().to_owned(),
parts_mode: match readings.support.parts {
PartsMode::InsidePasses => GpuPartsMode::InsidePasses,
PartsMode::SeparatePasses => GpuPartsMode::SeparatePasses,
} as i32,
pass_split: match readings.support.parts {
PartsMode::InsidePasses => GpuPassSplit::DrawGroups,
PartsMode::SeparatePasses => GpuPassSplit::PassesOnly,
} as i32,
counters: readings.support.counters,
fragment_unit: match readings.support.fragment_unit {
None => GpuFragmentUnit::Unspecified,
Some(FragmentUnit::Pixel) => GpuFragmentUnit::Pixel,
Some(FragmentUnit::Quad) => GpuFragmentUnit::Quad,
} as i32,
}
}
fn section(
adapter: &wgpu::AdapterInfo,
side: Side,
source: GpuSource,
readings: &Readings,
strings: &mut Interner,
) -> GpuPasses {
let mut passes: Vec<GpuPass> = readings
.passes
.iter()
.map(|(name, ms)| GpuPass {
name: strings.intern(name),
ms: Some(*ms),
parts: Vec::new(),
})
.collect();
for (pass, parts) in &readings.parts {
let name = strings.intern(pass);
let at = passes
.iter()
.position(|p| p.name == name)
.unwrap_or_else(|| {
passes.push(GpuPass {
name,
ms: None,
parts: Vec::new(),
});
passes.len() - 1
});
passes[at].parts = parts
.iter()
.map(|(part, ms)| GpuPart {
name: strings.intern(part),
ms: *ms,
})
.collect();
}
GpuPasses {
side: side as i32,
device: Some(device(adapter, readings)),
passes,
counters: readings
.counters
.iter()
.map(|(pass, c)| counter(strings, pass, c))
.collect(),
source: source as i32,
}
}
/// One `GpuPasses` per timer that has timed something, its times the medians of `log` where it has them; the caller appends `strings`' new entries first.
pub fn gpu_passes(
readout: &GpuReadout,
log: &FrameLog,
side: Side,
strings: &mut Interner,
) -> Vec<GpuPasses> {
[
(GpuSource::Horizon, &readout.own, &log.own),
(GpuSource::ShaderPack, &readout.pack, &log.pack),
]
.into_iter()
.filter_map(|(source, readings, times)| {
let readings = readings.as_ref().filter(|r| !r.is_empty())?;
let whole = (!times.is_empty()).then(|| times.medians_into(readings));
let readings = whole.as_ref().unwrap_or(readings);
Some(section(&readout.adapter, side, source, readings, strings))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gfx::pack_timing::DetailSupport;
fn adapter() -> wgpu::AdapterInfo {
wgpu::AdapterInfo {
name: "Test GPU".into(),
vendor: 0x10de,
device: 1,
device_type: wgpu::DeviceType::DiscreteGpu,
device_pci_bus_id: String::new(),
driver: "NVIDIA".into(),
driver_info: "570.1".into(),
backend: wgpu::Backend::Vulkan,
subgroup_min_size: 0,
subgroup_max_size: 0,
transient_saves_memory: None,
limit_bucket: None,
}
}
fn support(unit: Option<FragmentUnit>) -> DetailSupport {
DetailSupport {
parts: PartsMode::InsidePasses,
encoder_stamps: true,
counters: true,
fragment_unit: unit,
}
}
#[test]
fn known_medians_parts_and_counters_come_through_with_their_names() {
let c = |v, f| Counters {
vertex_shader_invocations: v,
clipper_invocations: 2_050_000,
clipper_primitives_out: 1_200_000,
fragment_shader_invocations: f,
};
let own = Readings {
passes: vec![("World".into(), 1.5), ("HUD".into(), 0.25)],
parts: vec![("GPU culling".into(), vec![("cull".into(), 0.125)])],
counters: vec![(
"World".into(),
PassCounters {
total: c(4_100_000, 6_300_000),
pixels: 2_073_600,
parts: vec![
("before translucent".into(), c(3_000_000, 5_100_000)),
("translucent terrain".into(), c(1_100_000, 1_200_000)),
],
},
)],
support: support(Some(FragmentUnit::Quad)),
};
let readout = GpuReadout {
adapter: adapter(),
own: Some(own),
pack: None,
};
let mut strings = Interner::default();
let got = gpu_passes(&readout, &FrameLog::default(), Side::Client, &mut strings);
assert_eq!(got.len(), 1);
let g = &got[0];
assert_eq!((g.side(), g.source()), (Side::Client, GpuSource::Horizon));
let d = g.device.as_ref().unwrap();
assert_eq!(d.adapter, "Test GPU");
assert_eq!(d.backend(), GpuBackend::Vulkan);
assert_eq!(d.driver, "NVIDIA 570.1");
assert_eq!(d.parts_mode(), GpuPartsMode::InsidePasses);
assert!(d.counters);
assert_eq!(d.fragment_unit(), GpuFragmentUnit::Quad);
// World, HUD, then the pass known only through its parts.
let entries = strings.take_new(Side::Client);
let name = |id: u32| entries.iter().find(|e| e.id == id).unwrap().text.as_str();
let named: Vec<_> = g.passes.iter().map(|p| name(p.name)).collect();
assert_eq!(named, ["World", "HUD", "GPU culling"]);
let shown: Vec<_> = g.passes.iter().map(|p| p.ms).collect();
assert_eq!(shown, [Some(1.5), Some(0.25), None]);
assert_eq!(name(g.passes[2].parts[0].name), "cull");
assert_eq!(g.passes[2].parts[0].ms, 0.125);
let counted = &g.counters[0];
assert_eq!(counted.pixels, 2_073_600);
assert_eq!(
counted.total.as_ref().unwrap().fragment_shader_invocations,
6_300_000
);
assert_eq!(counted.parts.len(), 2);
assert_eq!(
counted.parts[1]
.counts
.as_ref()
.unwrap()
.vertex_shader_invocations,
1_100_000
);
// The pass's counters and its time name the same string.
assert_eq!(counted.pass, g.passes[0].name);
}
#[test]
fn a_timer_that_timed_nothing_adds_no_section() {
let idle = Readings {
passes: Vec::new(),
parts: Vec::new(),
counters: Vec::new(),
support: support(None),
};
let pack = Readings {
passes: vec![("composite".into(), 0.75)],
..idle.clone()
};
let readout = GpuReadout {
adapter: adapter(),
own: Some(idle),
pack: Some(pack),
};
let got = gpu_passes(
&readout,
&FrameLog::default(),
Side::Client,
&mut Interner::default(),
);
assert_eq!(got.len(), 1);
assert_eq!(got[0].source(), GpuSource::ShaderPack);
assert_eq!(
got[0].device.as_ref().unwrap().fragment_unit(),
GpuFragmentUnit::Unspecified
);
}
#[test]
fn the_end_section_takes_the_whole_capture_median_and_each_block_its_frames() {
let start = Instant::now();
let frame = |i: u32, world: f32| TimedFrame {
at: start + std::time::Duration::from_millis(u64::from(i) * 10),
total_ms: Some(world + 1.0),
passes: vec![("World".into(), world), ("HUD".into(), 0.5)],
parts: vec![("World".into(), vec![("sky".into(), world / 4.0)])],
};
let mut log = FrameLog::default();
let mut strings = Interner::default();
let worlds = [1.0, 2.0, 3.0, 4.0, 100.0];
let frames = TimedFrames {
own: worlds
.iter()
.enumerate()
.map(|(i, &w)| frame(i as u32, w))
.collect(),
pack: Vec::new(),
};
log.add(
&frames,
|at| at.duration_since(start).as_secs_f64(),
&mut strings,
);
log.cpu_frame(6.0);
let block = log.take_block(Side::Client).expect("a block");
assert_eq!(block.frames.len(), 5);
assert_eq!(block.cpu_frame_ms, [6.0]);
assert!((block.frames[4].t - 0.04).abs() < 1e-9);
assert_eq!(block.frames[4].total_ms, Some(101.0));
assert_eq!(block.frames[4].passes[0].parts[0].ms, 25.0);
assert!(log.take_block(Side::Client).is_none());
// The timer's own median (9.0) is of its last frames; the capture's is the third of five sorted.
let own = Readings {
passes: vec![("World".into(), 9.0)],
parts: Vec::new(),
counters: Vec::new(),
support: support(None),
};
let readout = GpuReadout {
adapter: adapter(),
own: Some(own),
pack: None,
};
let got = gpu_passes(&readout, &log, Side::Client, &mut strings);
let world = &got[0].passes[0];
assert_eq!(world.ms, Some(3.0));
assert_eq!(world.parts[0].ms, 0.75);
assert_eq!(
got[0].device.as_ref().unwrap().pass_split(),
GpuPassSplit::DrawGroups
);
}
}
@@ -864,11 +864,21 @@ impl TextField {
self.set_highlight(m, pos);
}
/// `onClick`: the cursor where the mouse is (`findClickedPositionInText`).
pub fn click(&mut self, m: &Measure, x: f64, extend: bool) {
/// `EditBox.onClick` / `MultiLineEditBox.onClick`: a double click selects
/// the word the pointer is in (`EditBox.selectWord`), any other click
/// places the caret there.
pub fn click(&mut self, m: &Measure, x: f64, extend: bool, double: bool) {
let pos = (x.floor() as i32 - self.text_x()).min(self.inner_width());
let rest = sub(&self.value, self.display, chars(&self.value));
let at = self.display + m.plain(&rest, pos, false);
self.move_cursor_to(m, at, extend);
if double {
let start = crate::ui::word_position(&self.value, -1, at);
let end = crate::ui::word_position(&self.value, 1, at);
self.move_cursor_to(m, start, false);
self.move_cursor_to(m, end, true);
} else {
self.move_cursor_to(m, at, extend);
}
}
pub fn contains(&self, x: f64, y: f64) -> bool {
x >= self.x as f64
@@ -222,11 +222,6 @@ impl<P: Copy, S: Copy> Lines<P, S> {
}
self.y += style::GROUP_GAP;
}
/// A group of rows under its page's own name (`list`'s `page_name`), for pages named at run
/// time, such as a resource pack's config entries (`pack_options_ui`).
pub(crate) fn titled(&mut self, page: P, rows: Vec<S>) {
self.group(page, "", rows);
}
/// The lines and the content's height.
pub(crate) fn finish(self) -> (Vec<Line<P, S>>, f32) {
(self.lines, (self.y - style::GROUP_GAP).max(0.0))
@@ -310,6 +305,9 @@ pub(crate) fn search_field(
let frame = [x, y, clear[0] - x, h];
search.frame = Some(frame);
search.draw(batch, atlas, None);
if ui::hovered(cursor, x, y, frame[2], h) {
crate::widgets::text_cursor(true, true);
}
if search.value.is_empty() && !focused {
let hint = Text::literal(search.message.clone());
batch.text_styled(atlas, &hint, x + 5.0, search.y, style::muted(), true);
@@ -349,8 +347,7 @@ pub(crate) fn plate(batch: &mut HudBatch, atlas: &HudAtlas, cols: &Columns, head
}
/// The list, clipped to its view: each group's panel, then its names and rows on it. `row`
/// draws a setting at its `y`; `page_name` names a page, and a group without a name of its own
/// (`Lines::titled`), in the player's language.
/// draws a setting at its `y`; `page_name` names a page, in the player's language.
pub(crate) fn list<P: Copy, S: Copy>(
batch: &mut HudBatch,
atlas: &HudAtlas,
@@ -383,7 +380,6 @@ pub(crate) fn list<P: Copy, S: Copy>(
}
let Some(setting) = line.setting else {
let (name, color, dy) = match line.group {
Some(("", _)) => (page_name(line.page), style::muted(), 3.0),
Some((name, _)) => (lang::get(name), style::muted(), 3.0),
None => (page_name(line.page), style::accent(), 4.0),
};
@@ -949,22 +945,10 @@ pub(crate) fn dock_note(
}
}
/// Done or Undo at the foot of the page list.
/// Done, Undo or Apply at the foot of the page list, registered for a controller. Its label
/// leaves `room` at its left for a controller's glyph: a button that declared its job gets one,
/// as vanilla's do (`ui::action_button`), which a half-width Undo or Apply needs.
pub(crate) fn foot_button(
batch: &mut HudBatch,
atlas: &HudAtlas,
rect: [f32; 4],
label: &Text,
cursor: (f32, f32),
flags: (bool, bool),
) {
foot_button_with_room(batch, atlas, rect, label, cursor, flags, 0.0);
}
/// A foot button whose label leaves `room` at its left for a controller's glyph: a button that
/// declared its job gets one, as vanilla's do (`ui::action_button`), which a half-width Undo or
/// Apply needs.
fn foot_button_with_room(
batch: &mut HudBatch,
atlas: &HudAtlas,
rect: [f32; 4],
@@ -2411,7 +2395,7 @@ impl<S: Screen + Default> Hosted for Shell<S> {
}
None => 0.0,
};
foot_button_with_room(batch, atlas, rect, &label, cursor, flags, room);
foot_button(batch, atlas, rect, &label, cursor, flags, room);
}
}
fn click(
+11 -17
View File
@@ -93,18 +93,17 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[impl AsRef<str>])
signed: signature == Signature::Signed,
..empty.clone()
};
// Each texture is loaded independently: an invalid or disallowed URL for one
// texture (cape, elytra) must not drop another (the skin). Vanilla's
// SkinManager works the same way.
// Authlib's MinecraftServicesSessionService validates every URL in
// unpackTextures before returning any textures. A bad cape rejects the skin too.
for (kind, texture) in textures {
let Some(url) = texture.get("url").and_then(|u| u.as_str()) else {
continue;
return empty;
};
let allowed = valid_uris
.iter()
.any(|u| url.starts_with(&u.as_ref().replace("{textureId}", "")));
if !allowed {
continue;
return empty;
}
if kind == "SKIN" {
out.slim = texture
@@ -1388,10 +1387,9 @@ mod tests {
&super::TEXTURE_URIS,
);
assert_eq!(textures.slim, slim && !url.contains("evil"));
// Textures are judged per URL (vanilla's SkinManager): the
// cape's URL is always allowed here, so it is kept even when
// the skin's URL is not.
assert!(textures.cape.is_some());
// Authlib rejects the whole payload if any URL is invalid,
// including the allowed cape when the skin is disallowed.
assert_eq!(textures.cape.is_some(), !url.contains("evil"));
assert_eq!(parsed.skin.is_some(), !url.contains("evil"));
assert!(std::sync::Arc::ptr_eq(&parsed, &cache.get(&profile)));
}
@@ -1544,18 +1542,14 @@ mod tests {
assert!(t.slim);
assert!(!unpack(wide, Signature::Signed, &TEXTURE_URIS).slim);
}
/// `unpack` keeps each texture independently: a cape from another origin
/// must not drop the skin.
/// Authlib's `MinecraftServicesSessionService` rejects the whole profile in
/// `unpackTextures` when any texture URL is outside the allowed origins.
#[test]
fn unpack_keeps_the_skin_when_another_texture_is_rejected() {
fn unpack_rejects_the_skin_when_another_texture_is_rejected() {
use super::{Signature, TEXTURE_URIS, unpack};
let mixed = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL3NraW4xIn0sICJDQVBFIjogeyJ1cmwiOiAiaHR0cHM6Ly9ldmlsLmV4YW1wbGUvdGV4dHVyZS9jYXBlMSJ9fX0=";
let t = unpack(mixed, Signature::Unsigned, &TEXTURE_URIS);
assert_eq!(
t.skin.as_deref(),
Some("https://textures.minecraft.net/texture/skin1")
);
assert_eq!(t.cape, None);
assert_eq!(t, super::Textures::default());
}
#[test]
fn profiles_parse_like_resolvable_profiles() {
+304 -171
View File
@@ -1,10 +1,4 @@
//! Named timings within a frame, for finding what makes a frame slow:
//! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time
//! exceeds MS milliseconds, and of every server tick (dedicated or
//! integrated) longer than MS. Each span keeps its wall time and the
//! thread's CPU time inside it, so a span that waited (for a lock, the GPU
//! or a core on a busy machine) shows apart from one that worked. Costs two
//! clock reads per span when enabled and a relaxed load otherwise.
//! Named timings (wall and thread CPU) of a frame or tick, on with `HORIZON_SPIKES` or while a capture records; the slow ones go to the slow ring, not as span lists to the log.
use std::{
cell::{Cell, RefCell},
sync::atomic::{AtomicBool, Ordering},
@@ -58,10 +52,10 @@ pub fn record_here(on: bool) {
/// Whether this thread records spans: all of them on, or [`record_here`].
#[inline]
pub fn recording_here() -> bool {
ENABLED.load(Ordering::Relaxed) || HERE.with(Cell::get) || trace::on()
ENABLED.load(Ordering::Relaxed) || HERE.with(Cell::get) || timeline::on()
}
/// The thread's CPU time when spans are on for every thread (`HORIZON_SPIKES`): only they
/// print it.
/// The thread's CPU time when spans are on for every thread (`HORIZON_SPIKES`): spans recorded
/// by `record_here` alone keep wall time only.
#[inline]
fn cpu_if_enabled() -> Option<Duration> {
if ENABLED.load(Ordering::Relaxed) {
@@ -82,31 +76,41 @@ pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T {
pub struct Guard {
open: Option<(&'static str, Instant, Option<Duration>, u8)>,
_heap: Option<horizon_threads::heap_census::Tag>,
/// The sampler's span before this one.
outer: u16,
}
/// Start a span named `name` that ends when the returned [`Guard`] is dropped.
#[inline]
pub fn guard(name: &'static str) -> Guard {
let _heap = horizon_threads::heap_tag(name);
let outer = horizon_threads::work::enter_span(name);
if !recording_here() {
return Guard { open: None, _heap };
return Guard {
open: None,
_heap,
outer,
};
}
let depth = DEPTH.with(|d| d.replace(d.get().saturating_add(1)));
Guard {
open: Some((name, Instant::now(), cpu_if_enabled(), depth)),
_heap,
outer,
}
}
impl Drop for Guard {
fn drop(&mut self) {
horizon_threads::work::leave_span(self.outer);
let Some((name, started, cpu, depth)) = self.open.take() else {
return;
};
let ms = started.elapsed().as_secs_f32() * 1000.0;
let elapsed = started.elapsed();
let ms = elapsed.as_secs_f32() * 1000.0;
let cpu_ms = cpu
.and_then(|start| Some((thread_cpu()?, start)))
.map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0);
DEPTH.with(|d| d.set(depth));
trace::span(name, started, ms);
timeline::span(name, started, elapsed, depth);
push(Span {
name,
ms,
@@ -115,6 +119,22 @@ impl Drop for Guard {
});
}
}
/// How many spans this thread holds.
fn recorded() -> usize {
SPANS.with(|s| s.borrow().len())
}
/// Moves the spans recorded since `mark` one level in: they ran inside the lap now ending.
fn nest_since(mark: usize, depth: u8) {
SPANS.with(|s| {
let mut s = s.borrow_mut();
let start = mark.min(s.len());
for span in &mut s[start..] {
if span.depth >= depth {
span.depth = span.depth.saturating_add(1);
}
}
});
}
/// Keeps a finished span for the thread's next [`take_raw`].
fn push(span: Span) {
SPANS.with(|s| {
@@ -125,22 +145,6 @@ fn push(span: Span) {
s.push(span);
});
}
/// Attach per-tick counts without interpreting them as durations.
pub fn counters(counts: &[(&str, u64)]) {
if !enabled() {
return;
}
NOTES.with(|n| {
n.borrow_mut().push((
0.0,
counts
.iter()
.map(|(name, count)| format!("{name}={count}"))
.collect::<Vec<_>>()
.join(", "),
))
});
}
/// Notes that one step inside a span took `ms` milliseconds doing `what` (one player's
/// packets, say), when this thread records spans and the step took at least [`NOTE_MS`]: a
/// span says where a slow tick went, its notes whose doing it was. Only the slowest few are
@@ -173,34 +177,36 @@ pub fn take_notes() -> Vec<(f32, String)> {
}
/// Consecutive steps of one function timed as spans: each [`Laps::lap`] records the time since
/// the previous one (or since [`laps`]) under its name. Nothing is read while spans are off.
pub struct Laps(Option<(Instant, Option<Duration>)>);
pub struct Laps(Option<(Instant, Option<Duration>, usize)>);
/// Start timing the steps of a function (see [`Laps`]).
#[inline]
pub fn laps() -> Laps {
Laps(recording_here().then(|| (Instant::now(), cpu_if_enabled())))
Laps(recording_here().then(|| (Instant::now(), cpu_if_enabled(), recorded())))
}
impl Laps {
/// Record the step that just ended under `name`, and start the next.
#[inline]
pub fn lap(&mut self, name: &'static str) {
let Some((started, cpu)) = &mut self.0 else {
let Some((started, cpu, mark)) = &mut self.0 else {
return;
};
let now = Instant::now();
let now_cpu = cpu.and_then(|_| thread_cpu());
let ms = (now - *started).as_secs_f32() * 1000.0;
let elapsed = now - *started;
let ms = elapsed.as_secs_f32() * 1000.0;
let cpu_ms = now_cpu
.zip(*cpu)
.map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0);
let depth = DEPTH.with(Cell::get);
trace::span(name, *started, ms);
timeline::span(name, *started, elapsed, depth);
nest_since(*mark, depth);
push(Span {
name,
ms,
cpu_ms,
depth,
});
(*started, *cpu) = (now, now_cpu);
(*started, *cpu, *mark) = (now, now_cpu, recorded());
}
}
/// The CPU time this thread has used, where the platform tells it: a tick
@@ -283,173 +289,176 @@ pub fn merge(spans: &[Span]) -> Vec<Span> {
sums.sort_by(|a, b| b.ms.total_cmp(&a.ms));
sums
}
/// `name wall` for spans of at least 0.5 ms, with `/cpu` when the thread
/// worked for less than nine tenths of it: the slow-frame and slow-tick lines.
pub fn describe(spans: &[Span]) -> String {
let list: Vec<String> = spans
.iter()
.filter(|s| s.ms >= 0.5)
.map(|s| {
if s.cpu_ms < s.ms * 0.9 {
format!("{} {:.1}/{:.1}", s.name, s.ms, s.cpu_ms)
} else {
format!("{} {:.1}", s.name, s.ms)
}
})
.collect();
list.join(", ")
}
/// The run's timeline: every span ([`time`], [`guard`], [`Laps::lap`]) on every thread, as
/// Chrome trace events that Perfetto (ui.perfetto.dev) opens as they are. `HORIZON_TRACE=FILE`
/// writes it from the start; [`start`](trace::start) and [`stop`](trace::stop) write one for a
/// while (`horizon-trace` on a dedicated server's console, `trace` on the control socket). Spans
/// show on their threads where they ran, nested by time, so what ran beside what, and what a
/// thread waited for, can be read off. Off, a span costs one relaxed load more.
pub mod trace {
/// The run's timeline: every span on every thread, kept in per-thread buffers until a capture drains them as `timeline` chunks.
pub mod timeline {
use std::{
cell::Cell,
fs::File,
io::{BufWriter, Write as _},
path::Path,
cell::RefCell,
sync::{
Mutex, PoisonError,
Arc, Mutex, PoisonError,
atomic::{AtomicBool, AtomicU32, Ordering},
},
time::Instant,
time::{Duration, Instant},
};
/// The most spans a thread holds between two drains; a thread that records more drops them.
const THREAD_EVENTS_MAX: usize = 1 << 18;
static ON: AtomicBool = AtomicBool::new(false);
static SINK: Mutex<Option<Sink>> = Mutex::new(None);
/// Counts the traces started: a thread names itself again in each one.
static TRACES: AtomicU32 = AtomicU32::new(0);
static NEXT_THREAD: AtomicU32 = AtomicU32::new(1);
thread_local! {
/// This thread's id in traces (0: none yet).
static THREAD: Cell<u32> = const { Cell::new(0) };
/// The trace this thread last named itself in.
static NAMED_IN: Cell<u32> = const { Cell::new(0) };
}
/// How often a trace's buffer goes to the file, at most: a run that ends without
/// [`stop`] loses no more than this.
const FLUSH_EVERY: std::time::Duration = std::time::Duration::from_secs(1);
static GENERATION: AtomicU32 = AtomicU32::new(0);
static RUN: Mutex<Option<Run>> = Mutex::new(None);
struct Sink {
file: BufWriter<File>,
struct Run {
origin: Instant,
/// Until when it records ([`start`]'s `seconds`).
until: Option<Instant>,
flushed: Instant,
/// Events written: the next one is preceded by a comma.
events: u64,
}
impl Sink {
fn event(&mut self, event: std::fmt::Arguments) {
let comma = if self.events == 0 { "" } else { ",\n" };
let _ = write!(self.file, "{comma}{{\"pid\":1,{event}}}");
self.events += 1;
}
threads: Vec<Arc<Mutex<Thread>>>,
}
/// Whether a trace is being written.
struct Thread {
name: String,
label: String,
events: Vec<Event>,
}
/// This thread's buffer in the timeline it last joined.
struct Mine {
generation: u32,
origin: Instant,
thread: Arc<Mutex<Thread>>,
}
thread_local! {
static MINE: RefCell<Option<Mine>> = const { RefCell::new(None) };
}
/// One finished span.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Event {
pub name: &'static str,
/// Microseconds from the timeline's start.
pub start_us: u64,
pub dur_us: u32,
/// How many spans it ran inside on its thread.
pub depth: u8,
}
/// The spans one thread finished since the last drain, in the order they finished.
#[derive(Debug, PartialEq, Eq)]
pub struct ThreadEvents {
/// The thread's name; threads alive together under one name get `#2`, `#3`... after it.
pub thread: String,
pub events: Vec<Event>,
}
/// Whether a timeline is being recorded.
#[inline]
pub fn on() -> bool {
ON.load(Ordering::Relaxed)
}
/// Starts a trace written to `path` (replacing a trace being written), for `seconds` or
/// until [`stop`].
pub fn start(path: &Path, seconds: Option<u32>) -> std::io::Result<()> {
let mut file = BufWriter::with_capacity(1 << 18, File::create(path)?);
file.write_all(b"[\n")?;
let now = Instant::now();
let sink = Sink {
file,
origin: now,
until: seconds.map(|s| now + std::time::Duration::from_secs(u64::from(s))),
flushed: now,
events: 0,
};
let mut slot = SINK.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(old) = slot.take() {
close(old);
/// Starts recording, timed from `origin`; false when a timeline already runs (the process has one).
pub fn start(origin: Instant) -> bool {
let mut run = RUN.lock().unwrap_or_else(PoisonError::into_inner);
if run.is_some() {
return false;
}
*slot = Some(sink);
TRACES.fetch_add(1, Ordering::Relaxed);
*run = Some(Run {
origin,
threads: Vec::new(),
});
GENERATION.fetch_add(1, Ordering::Relaxed);
ON.store(true, Ordering::Relaxed);
Ok(())
true
}
/// Starts the trace `HORIZON_TRACE` names, if it names one.
pub fn start_from_env() {
if let Some(path) = std::env::var_os("HORIZON_TRACE")
&& let Err(e) = start(Path::new(&path), None)
{
log::warn!("Horizon: HORIZON_TRACE: {e}");
}
/// Takes what the threads finished since the last call.
pub fn drain() -> Vec<ThreadEvents> {
let run = RUN.lock().unwrap_or_else(PoisonError::into_inner);
run.as_ref().map_or_else(Vec::new, take_all)
}
/// Ends the trace being written: the file is complete JSON. The events written so far
/// and whether one was being written.
pub fn stop() -> Option<u64> {
/// Stops recording and returns what the threads finished since the last drain.
pub fn finish() -> Vec<ThreadEvents> {
ON.store(false, Ordering::Relaxed);
let sink = SINK.lock().unwrap_or_else(PoisonError::into_inner).take()?;
let events = sink.events;
close(sink);
Some(events)
let run = RUN.lock().unwrap_or_else(PoisonError::into_inner).take();
run.as_ref().map_or_else(Vec::new, take_all)
}
/// Whether the trace being written has run its time ([`start`]'s `seconds`): the caller
/// then [`stop`]s it.
pub fn due() -> bool {
on() && SINK
.lock()
.unwrap_or_else(PoisonError::into_inner)
.as_ref()
.and_then(|s| s.until)
.is_some_and(|until| Instant::now() >= until)
fn take_all(run: &Run) -> Vec<ThreadEvents> {
run.threads
.iter()
.filter_map(|thread| {
let mut thread = thread.lock().unwrap_or_else(PoisonError::into_inner);
(!thread.events.is_empty()).then(|| ThreadEvents {
thread: thread.label.clone(),
events: std::mem::take(&mut thread.events),
})
})
.collect()
}
fn close(mut sink: Sink) {
let _ = sink.file.write_all(b"\n]\n");
let _ = sink.file.flush();
/// Takes a buffer for this thread: the one of an exited thread of the same name, else a new one.
fn join() -> Option<Mine> {
let mut slot = RUN.lock().unwrap_or_else(PoisonError::into_inner);
let run = slot.as_mut()?;
let name = std::thread::current()
.name()
.unwrap_or("unnamed")
.to_owned();
let of_name =
|t: &Arc<Mutex<Thread>>| t.lock().unwrap_or_else(PoisonError::into_inner).name == name;
let thread = match run
.threads
.iter()
.find(|t| Arc::strong_count(t) == 1 && of_name(t))
{
Some(exited) => Arc::clone(exited),
None => {
let same = run.threads.iter().filter(|t| of_name(t)).count();
let label = if same == 0 {
name.clone()
} else {
format!("{name} #{}", same + 1)
};
let thread = Arc::new(Mutex::new(Thread {
name,
label,
events: Vec::new(),
}));
run.threads.push(Arc::clone(&thread));
thread
}
};
Some(Mine {
generation: GENERATION.load(Ordering::Relaxed),
origin: run.origin,
thread,
})
}
/// A span of this thread from `started`, `ms` long.
pub(super) fn span(name: &'static str, started: Instant, ms: f32) {
/// A span of this thread from `started`, `elapsed` long, inside `depth` others.
pub(super) fn span(name: &'static str, started: Instant, elapsed: Duration, depth: u8) {
if !on() {
return;
}
let tid = THREAD.with(|t| {
if t.get() == 0 {
t.set(NEXT_THREAD.fetch_add(1, Ordering::Relaxed));
let generation = GENERATION.load(Ordering::Relaxed);
let _ = MINE.try_with(|mine| {
let mut mine = mine.borrow_mut();
if mine.as_ref().is_none_or(|m| m.generation != generation) {
*mine = join();
}
let Some(mine) = mine.as_ref() else {
return;
};
let event = Event {
name,
start_us: started.saturating_duration_since(mine.origin).as_micros() as u64,
dur_us: elapsed.as_micros().min(u128::from(u32::MAX)) as u32,
depth,
};
let mut thread = mine.thread.lock().unwrap_or_else(PoisonError::into_inner);
if thread.events.len() < THREAD_EVENTS_MAX {
thread.events.push(event);
}
t.get()
});
let trace = TRACES.load(Ordering::Relaxed);
let mut slot = SINK.lock().unwrap_or_else(PoisonError::into_inner);
let Some(sink) = slot.as_mut() else {
return;
};
if NAMED_IN.with(|n| n.replace(trace)) != trace {
let name = std::thread::current()
.name()
.unwrap_or("unnamed")
.replace(['"', '\\'], "_");
sink.event(format_args!(
r#""ph":"M","name":"thread_name","tid":{tid},"args":{{"name":"{name}"}}"#
));
}
let ts = started.saturating_duration_since(sink.origin).as_secs_f64() * 1e6;
sink.event(format_args!(
r#""ph":"X","name":"{name}","tid":{tid},"ts":{ts:.3},"dur":{:.3}"#,
f64::from(ms) * 1e3
));
let now = Instant::now();
if now.duration_since(sink.flushed) >= FLUSH_EVERY {
let _ = sink.file.flush();
sink.flushed = now;
}
}
}
@@ -654,6 +663,46 @@ mod tests {
SWITCH.lock().unwrap_or_else(|e| e.into_inner())
}
/// Samples taken inside a named span carry its id, with spans off, and the span is left after it.
#[cfg(target_os = "linux")]
#[test]
fn samples_inside_a_span_carry_its_id() {
use horizon_threads::{sampler, work};
use std::time::{Duration, Instant};
let worker = std::thread::spawn(|| {
assert!(sampler::sampled_thread("spans-id-test"));
let config = sampler::Config {
hz: 1000,
..Default::default()
};
let session = sampler::start(config, |n| n == "spans-id-test").unwrap();
let busy = |ms| {
let until = Instant::now() + Duration::from_millis(ms);
while Instant::now() < until {
std::hint::black_box(0);
}
};
super::time("spans_id_test_named", || busy(60));
assert_eq!(sampler::span(), 0);
busy(60);
let mut spans = Vec::new();
session.stop(|_, r| spans.push(r.ctx.span));
spans
});
let spans = worker.join().unwrap();
let inside = |s: &u16| work::name(work::Space::Span, *s) == Some("spans_id_test_named");
let (named, plain) = (
spans.iter().filter(|s| inside(s)).count(),
spans.iter().filter(|s| **s == 0).count(),
);
assert!(
named > 30 && plain > 30,
"{named} named, {plain} outside of {} samples",
spans.len()
);
assert_eq!(named + plain, spans.len(), "no other span id");
}
/// A slow tick's notes are its slowest steps, slowest first; short steps and steps on a
/// thread that records no spans leave none.
#[test]
@@ -680,8 +729,7 @@ mod tests {
assert!(super::take_notes().is_empty(), "taking them clears them");
}
/// Spans of one name add up; a span the thread spent mostly waiting
/// shows its CPU time after the wall time, short ones are left out.
/// Spans of one name add up, the slowest first; a span that waited keeps its small CPU time.
#[test]
fn spans_sum_by_name_and_show_waits() {
super::SPANS.with(|s| {
@@ -723,7 +771,6 @@ mod tests {
}
);
assert_eq!((spans[1].name, spans[1].ms), ("tick", 5.0));
assert_eq!(super::describe(&spans), "submit 30.0/0.2, tick 5.0");
assert!(super::take().is_empty());
}
@@ -843,6 +890,22 @@ mod tests {
assert!(spans[0].ms >= 2.0);
}
/// A span that ran during a lap belongs inside that lap, and not inside the next one.
#[test]
fn a_span_during_a_lap_nests_under_that_lap() {
let _switch = spans_switch();
let _ = super::take_raw();
super::enable(true);
let mut laps = super::laps();
super::time("inner", || {});
laps.lap("first");
laps.lap("second");
super::enable(false);
let spans = super::take_raw();
let depths: Vec<_> = spans.iter().map(|s| (s.name, s.depth)).collect();
assert_eq!(depths, [("inner", 1), ("first", 0), ("second", 0)]);
}
/// The thread's CPU clock moves with work done on it, not with time
/// spent asleep.
#[cfg(any(unix, all(windows, target_arch = "x86_64")))]
@@ -865,4 +928,74 @@ mod tests {
assert!(slept.as_millis() < 25, "{slept:?} while asleep");
assert!(worked.as_millis() >= 10, "{worked:?} while busy");
}
/// Each thread's finished spans reach the timeline with their depth and nesting in time; threads alive together under one name get labels of their own, ones after another share a lane.
#[test]
fn the_timeline_keeps_each_threads_spans_with_their_depth_and_place_in_time() {
use super::timeline;
use std::sync::{Arc, Barrier};
use std::time::{Duration, Instant};
let _switch = spans_switch();
assert!(timeline::start(Instant::now()));
assert!(
!timeline::start(Instant::now()),
"the process has one timeline"
);
let spawn = |name: &str, alive_with: Option<Arc<Barrier>>| {
std::thread::Builder::new()
.name(name.into())
.spawn(move || {
super::time("outer", || {
std::thread::sleep(Duration::from_millis(4));
super::time("inner", || std::thread::sleep(Duration::from_millis(3)));
});
if let Some(barrier) = alive_with {
barrier.wait();
}
})
.unwrap()
};
spawn("tl-solo", None).join().unwrap();
let together = Arc::new(Barrier::new(2));
let twins = [
spawn("tl-twin", Some(together.clone())),
spawn("tl-twin", Some(together)),
];
for twin in twins {
twin.join().unwrap();
}
spawn("tl-seq", None).join().unwrap();
spawn("tl-seq", None).join().unwrap();
let mut threads = timeline::finish();
threads.retain(|t| t.thread.starts_with("tl-"));
threads.sort_by(|a, b| a.thread.cmp(&b.thread));
let labels: Vec<_> = threads.iter().map(|t| t.thread.as_str()).collect();
assert_eq!(labels, ["tl-seq", "tl-solo", "tl-twin", "tl-twin #2"]);
for thread in &threads {
let runs = if thread.thread == "tl-seq" { 2 } else { 1 };
assert_eq!(thread.events.len(), 2 * runs, "{thread:?}");
for pair in thread.events.chunks(2) {
let [inner, outer] = pair else { unreachable!() };
assert_eq!((inner.name, inner.depth), ("inner", 1));
assert_eq!((outer.name, outer.depth), ("outer", 0));
assert!(
inner.dur_us >= 3_000 && outer.dur_us >= 7_000,
"{inner:?} {outer:?}"
);
assert!(inner.start_us >= outer.start_us + 4_000);
assert!(
inner.start_us + u64::from(inner.dur_us)
<= outer.start_us + u64::from(outer.dur_us)
);
}
}
let seq = threads.iter().find(|t| t.thread == "tl-seq").unwrap();
assert!(seq.events[2].start_us >= seq.events[1].start_us + u64::from(seq.events[1].dur_us));
spawn("tl-after", None).join().unwrap();
assert!(
timeline::drain().is_empty(),
"a stopped timeline records nothing"
);
}
}
+4 -4
View File
@@ -478,9 +478,9 @@ impl Sprites {
let metadata = match horizon_core::prepared_files::read_to_string(
&path.with_extension("png.mcmeta"),
) {
Ok(text) => Some(serde_json::from_str::<
Ok(text) => Some(crate::packs::first_json::<
BTreeMap<String, Box<serde_json::value::RawValue>>,
>(&text)?),
>(text.as_bytes())?),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
@@ -589,9 +589,9 @@ impl Sprites {
let metadata = match horizon_core::prepared_files::read_to_string(
&path.with_extension("png.mcmeta"),
) {
Ok(text) => Some(serde_json::from_str::<
Ok(text) => Some(crate::packs::first_json::<
BTreeMap<String, Box<serde_json::value::RawValue>>,
>(&text)?),
>(text.as_bytes())?),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
+14 -32
View File
@@ -28,37 +28,7 @@ pub const IDLE_RELEASE: std::time::Duration = std::time::Duration::from_secs(5);
/// Worker CPU time and job counts by kind, for benchmarks
/// (`examples/gen_light_bench.rs`). Off unless enabled: a relaxed load per
/// job then.
pub mod job_stats {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
pub const KINDS: [&str; 7] = [
"load", "generate", "decorate", "finish", "light", "mesh", "other",
];
static ENABLED: AtomicBool = AtomicBool::new(false);
static NANOS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
static COUNT: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
pub fn enable(on: bool) {
ENABLED.store(on, Ordering::Relaxed);
}
pub(super) fn enabled() -> bool {
ENABLED.load(Ordering::Relaxed)
}
pub(super) fn add(kind: usize, nanos: u64) {
NANOS[kind].fetch_add(nanos, Ordering::Relaxed);
COUNT[kind].fetch_add(1, Ordering::Relaxed);
}
/// (kind, nanoseconds, count) since the last call; resets them.
pub fn take() -> Vec<(&'static str, u64, u64)> {
(0..KINDS.len())
.map(|i| {
(
KINDS[i],
NANOS[i].swap(0, Ordering::Relaxed),
COUNT[i].swap(0, Ordering::Relaxed),
)
})
.collect()
}
}
pub mod job_stats;
/// A chunk under generation, opaque to the streamer.
pub type Proto = Box<dyn std::any::Any + Send>;
/// Chunk generation in vanilla's stages: a neighbour-independent proto chunk
@@ -1070,6 +1040,8 @@ pub struct WorkerContext {
pub light: Arc<LightTables>,
}
mod bounded;
mod queue_census;
pub use queue_census::QueueCensus;
mod forced_cover;
mod forced_ring;
mod relight_now;
@@ -1466,7 +1438,7 @@ impl Streaming {
let entities = std::mem::take(&mut chunk.entities);
world.entities_pending.insert((chunk.x, chunk.z));
if !entities.is_empty() {
world.loaded_entities.push(((chunk.x, chunk.z), entities));
world.queue_entity_nbt((chunk.x, chunk.z), entities);
}
self.generated_total += 1;
// A chunk saved with its light needs no light job; its unlit
@@ -1683,6 +1655,7 @@ impl Streaming {
&mut self,
world: &mut World,
) -> (Vec<((i32, i32, i32), SectionMesh)>, Vec<Arc<Chunk>>) {
let mut hz_laps = crate::spans::laps();
let mut uploads = Vec::new();
if self.paused {
return (uploads, Vec::new());
@@ -1708,6 +1681,7 @@ impl Streaming {
self.scan_age = if sweep { 0 } else { self.scan_age + 1 };
self.requeue();
self.relight_edits(world);
hz_laps.lap("st_relight_edits");
let deferred = std::mem::take(&mut self.deferred);
let received = self.shared.done.take();
// Meshes made stale meanwhile, freed with the uploaded ones (`free`).
@@ -1757,6 +1731,7 @@ impl Streaming {
}
}
}
hz_laps.lap("st_results");
self.free(stale);
let mut removed = Vec::new();
if sweep {
@@ -1827,6 +1802,7 @@ impl Streaming {
}
self.save_checked_out(written);
}
hz_laps.lap("st_sweep");
let (protos, finishing) = (&self.protos, &self.finishing);
self.decorated.retain(|k| {
protos.contains_key(k) || finishing.contains(k) || world.chunks.contains_key(k)
@@ -1858,6 +1834,7 @@ impl Streaming {
self.submit(Some((x, z)), 0, Job::Finish(proto));
}
}
hz_laps.lap("st_finalize");
// Decorate chunks whose 3x3 proto neighbourhood is available, in
// vanilla's order: decoration is order dependent where write regions
// overlap (see `DecorationOrder`).
@@ -1983,7 +1960,9 @@ impl Streaming {
self.submit(Some((x, z)), 1, Job::Decorate(x, z, region, finals));
}
}
hz_laps.lap("st_decorate");
self.schedule_generation(world, workers);
hz_laps.lap("st_generate");
// Lighting once all neighbours exist, nearest first and only as
// much of it as the workers can chew. Vanilla's light engine also
// hands a bounded queue to its workers and reschedules what did
@@ -2019,6 +1998,7 @@ impl Streaming {
Job::Light(x, z, region, self.sequence, self.sky_light),
);
}
hz_laps.lap("st_light");
// A server draws nothing: its sections are never meshed.
if !self.mesh {
world.dirty_sections.clear();
@@ -2059,6 +2039,7 @@ impl Streaming {
!back
});
}
hz_laps.lap("st_waiting");
// Column by column: the checks below hold for all of a column's
// sections, and columns waiting for light cost one look per frame.
columns.extend(world.dirty_sections.columns());
@@ -2091,6 +2072,7 @@ impl Streaming {
}
candidates.push((self.distance(x, z), x, z, sections));
}
hz_laps.lap("st_candidates");
// Nearest first, and only as many sections as the workers can chew.
// Every ready column used to be submitted at once, so at a wide
// render distance the queue — and `meshing`, and each job's 3x3
@@ -0,0 +1,29 @@
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
pub const KINDS: [&str; 7] = [
"load", "generate", "decorate", "finish", "light", "mesh", "other",
];
static ENABLED: AtomicBool = AtomicBool::new(false);
static NANOS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
static COUNT: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7];
pub fn enable(on: bool) {
ENABLED.store(on, Ordering::Relaxed);
}
pub(super) fn enabled() -> bool {
ENABLED.load(Ordering::Relaxed)
}
pub(super) fn add(kind: usize, nanos: u64) {
NANOS[kind].fetch_add(nanos, Ordering::Relaxed);
COUNT[kind].fetch_add(1, Ordering::Relaxed);
}
/// (kind, nanoseconds, count) since the last call; resets them.
pub fn take() -> Vec<(&'static str, u64, u64)> {
(0..KINDS.len())
.map(|i| {
(
KINDS[i],
NANOS[i].swap(0, Ordering::Relaxed),
COUNT[i].swap(0, Ordering::Relaxed),
)
})
.collect()
}
@@ -0,0 +1,39 @@
//! What the streamer's queues hold, for `horizon-ctl memory` and captures.
use super::{Queued, Streaming};
/// What the streamer's work queues hold, each as (entries, estimated bytes).
#[derive(Debug, Default)]
pub struct QueueCensus {
/// Jobs queued and chunks generating.
pub generation: (usize, usize),
/// Chunks being lit and the edit log their jobs replay.
pub light: (usize, usize),
}
impl Streaming {
/// The queues' lengths and the bytes of their tables, from capacities. For `horizon-ctl memory`.
pub fn queue_census(&self) -> QueueCensus {
use std::mem::size_of;
let table = |capacity: usize, entry: usize| capacity * (entry + 1);
let queued = {
let queue = self.shared.queue.lock().unwrap();
(queue.len(), queue.capacity() * size_of::<Queued>())
};
QueueCensus {
generation: (
queued.0 + self.generating.len(),
queued.1 + table(self.generating.capacity(), size_of::<(i32, i32)>()),
),
light: (
self.lighting.len(),
table(self.lighting.capacity(), size_of::<((i32, i32), u64)>())
+ table(
self.light_snapshots.capacity(),
size_of::<((i32, i32), u64)>(),
)
+ self.light_log.capacity() * size_of::<(u64, (i32, i32, i32))>()
+ self.light_scratch.capacity() * size_of::<(i64, i32, i32)>(),
),
}
}
}
@@ -43,7 +43,7 @@ struct Globals {
// w: apply the no-pack HDR gain; HDR_WRITE_LIGHT independently keeps float alpha as coverage.
hdr_light: vec4<f32>,
hdr_settings: vec4<f32>,
hdr_shares: vec4<f32>,
hdr_gains: vec4<f32>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
@@ -788,7 +788,7 @@ fn solid_finish(in: TerrainOut, texel: vec4<f32>, color: vec4<f32>) -> vec4<f32>
fn solid_light(finished: vec4<f32>) -> vec4<f32> {
if HDR_WRITE_LIGHT {
if globals.hdr_light.w != 0.0 {
return vec4(hdr_written(finished.rgb, finished.a, globals.hdr_settings, globals.hdr_shares), 1.0);
return vec4(hdr_written(finished.rgb, finished.a, globals.hdr_settings, globals.hdr_gains), 1.0);
}
return frame_stored(vec4(finished.rgb, 1.0));
}
@@ -870,7 +870,7 @@ fn solid_finish_at(in: TerrainOut, texel: vec4<f32>, color: vec4<f32>, du: vec2<
let fogged = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)) * globals.fog_color.a;
let mark = hdr_scene_alpha(mix(hdr_scene(in.scene.x, in.scene.y, hdr_facing()), globals.hdr_light.y, fogged));
return vec4(hdr_written(finished.rgb, mark, globals.hdr_settings, globals.hdr_shares), finished.a);
return vec4(hdr_written(finished.rgb, mark, globals.hdr_settings, globals.hdr_gains), finished.a);
}
return frame_stored(finished);
}
@@ -1076,7 +1076,7 @@ fn sky_finished(color: vec3<f32>) -> vec4<f32> {
let mark = 1.0 - 0.24 * globals.hdr_light.y;
if HDR_WRITE_LIGHT {
if globals.hdr_light.w != 0.0 {
return vec4(hdr_written(color, mark, globals.hdr_settings, globals.hdr_shares), 1.0);
return vec4(hdr_written(color, mark, globals.hdr_settings, globals.hdr_gains), 1.0);
}
return frame_stored(vec4(color, 1.0));
}
+23 -1
View File
@@ -104,7 +104,7 @@ pub fn read_metadata(root: &Path) -> UiMetadata {
let Ok(text) = horizon_core::prepared_files::read_to_string(&p) else {
continue;
};
let Some(nine_slice) = serde_json::from_str(&text)
let Some(nine_slice) = crate::packs::first_json(text.as_bytes())
.ok()
.as_ref()
.and_then(parse_nine_slice)
@@ -2025,6 +2025,28 @@ impl EditBox {
mod tests {
use super::*;
#[test]
fn notes_after_a_sprites_metadata_keep_its_nine_slice() {
// Gson stops reading after the first value, so vanilla keeps this nine slice
// (CozyUI+'s highlighted button, #3046).
let root = std::env::temp_dir().join(format!("horizon-ui-meta-{}", std::process::id()));
let widget = root.join("assets/minecraft/textures/gui/sprites/widget");
std::fs::create_dir_all(&widget).unwrap();
std::fs::write(
widget.join("button_highlighted.png.mcmeta"),
"{\"gui\": {\"scaling\": {\"type\": \"nine_slice\", \"width\": 80, \"height\": 20,\n\
\"border\": {\"left\": 34, \"top\": 8, \"right\": 34, \"bottom\": 8}}}}\n\n// 0 10\n// 1 8\n",
)
.unwrap();
let metadata = read_metadata(&root);
std::fs::remove_dir_all(&root).unwrap();
let slice = metadata.0["gui/sprites/widget/button_highlighted"];
assert_eq!(
(slice.width, slice.height, slice.border),
(80, 20, [34, 8, 34, 8])
);
}
/// The quads' destination rectangles and their UVs.
fn quads(batch: &HudBatch) -> Vec<([f32; 4], [f32; 4])> {
batch
@@ -13,6 +13,8 @@ pub enum Cursor {
#[default]
Arrow,
PointingHand,
/// `CursorTypes.IBEAM`: over a text field that takes input.
Ibeam,
NotAllowed,
/// `CursorTypes.RESIZE_NS`: a scroller held vertically (`MerchantScreen`).
ResizeNs,
@@ -55,6 +57,18 @@ pub fn slider_cursor(hovered: bool, active: bool, dragging: bool) {
}
}
/// `EditBox.handleCursor`: a hovered text field shows the I-beam, or the
/// forbidden sign when it takes no input.
pub fn text_cursor(hovered: bool, editable: bool) {
if hovered {
request_cursor(if editable {
Cursor::Ibeam
} else {
Cursor::NotAllowed
});
}
}
/// The cursor the frame asked for, and back to the arrow for the next one
/// (the window shows the arrow unless a widget asks).
pub fn take_cursor() -> Cursor {
@@ -429,6 +443,16 @@ pub fn record_as(label: &str, [x, y, w, h]: [f32; 4], enabled: bool, kind: Kind)
mod cursor_tests {
use super::*;
#[test]
fn a_hovered_text_field_asks_for_the_i_beam() {
let _ = take_cursor();
text_cursor(false, true);
assert_eq!(take_cursor(), Cursor::Arrow);
text_cursor(true, true);
assert_eq!(take_cursor(), Cursor::Ibeam);
text_cursor(true, false);
assert_eq!(take_cursor(), Cursor::NotAllowed);
}
#[test]
fn a_dragged_slider_asks_for_the_horizontal_resize_cursor() {
let _ = take_cursor();
+10 -1
View File
@@ -9,6 +9,9 @@ use horizon_core::random::{LegacyRandom, LevelRandom};
use horizon_world::registry::BlockStateId;
use std::sync::Arc;
mod pending_entity;
pub use pending_entity::{EntityLoadReason, PendingEntity};
mod modified;
pub use modified::ModifiedChunks;
@@ -81,7 +84,7 @@ pub struct World {
/// incrementally by streaming.
pub light_edits: Vec<((i32, i32, i32), u32, u32)>,
/// Saved entities of chunks that just loaded, spawned by the game.
pub loaded_entities: Vec<((i32, i32), Vec<horizon_world::nbt::Tag>)>,
pub loaded_entities: Vec<((i32, i32), Vec<PendingEntity>)>,
/// Chunks loaded since the level's last pass, their entity sections not
/// ready yet (`PersistentEntitySectionManager`'s PENDING), empty ones too:
/// the pass ends by readying them (`processPendingLoads`).
@@ -215,6 +218,12 @@ impl Weather {
}
}
impl World {
/// Queue ordinary NBT; transient transfer state is never decoded from it.
pub fn queue_entity_nbt(&mut self, key: (i32, i32), tags: Vec<horizon_world::nbt::Tag>) {
self.loaded_entities
.push((key, tags.into_iter().map(PendingEntity::from).collect()));
}
pub fn new(air: BlockStateId, seed: i64) -> Self {
Self {
shape: LevelShape::OVERWORLD,
@@ -0,0 +1,89 @@
//! Pending entity NBT and the runtime context that must not be stored inside it.
use horizon_world::nbt::Tag;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntityLoadReason {
Ordinary,
TeleportedTnt,
}
#[derive(Clone, Debug)]
pub struct PendingEntity {
tag: Tag,
reason: EntityLoadReason,
}
impl From<Tag> for PendingEntity {
fn from(tag: Tag) -> Self {
Self {
tag,
reason: EntityLoadReason::Ordinary,
}
}
}
impl PendingEntity {
/// Only an in-memory TNT transfer supplies this context, never saved NBT.
pub fn after_tnt_portal(tag: Tag) -> Self {
Self {
tag,
reason: EntityLoadReason::TeleportedTnt,
}
}
pub fn into_parts(self) -> (Tag, EntityLoadReason) {
(self.tag, self.reason)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ordinary_nbt_cannot_request_transient_portal_state() {
for marker in [0, 1] {
let tag = Tag::compound([("horizon:tnt_used_portal", Tag::Byte(marker))]);
let (loaded, reason) = PendingEntity::from(tag.clone()).into_parts();
assert_eq!(loaded, tag);
assert_eq!(reason, EntityLoadReason::Ordinary);
}
}
#[test]
fn queue_swaps_and_appends_keep_each_entitys_context_and_order() {
let ordinary = Tag::compound([("id", Tag::String("ordinary".into()))]);
let transfer = Tag::compound([("id", Tag::String("transfer".into()))]);
let mut batches = vec![(
(1, 2),
vec![
ordinary.clone().into(),
PendingEntity::after_tnt_portal(transfer.clone()),
],
)];
let mut waiting = std::mem::take(&mut batches);
batches.push(((3, 4), vec![ordinary.clone().into()]));
waiting.append(&mut batches);
assert!(batches.is_empty());
let mut batches = waiting.into_iter();
let (key, entities) = batches.next().unwrap();
assert_eq!(key, (1, 2));
let mut entities = entities.into_iter();
assert_eq!(
entities.next().unwrap().into_parts(),
(ordinary.clone(), EntityLoadReason::Ordinary)
);
assert_eq!(
entities.next().unwrap().into_parts(),
(transfer, EntityLoadReason::TeleportedTnt)
);
assert!(entities.next().is_none());
let (key, entities) = batches.next().unwrap();
assert_eq!(key, (3, 4));
assert_eq!(
entities.into_iter().next().unwrap().into_parts(),
(ordinary, EntityLoadReason::Ordinary)
);
assert!(batches.next().is_none());
}
}
+7 -5
View File
@@ -26,6 +26,7 @@ horizon-hooks = { path = "../horizon-hooks" }
horizon-optifine = { path = "../horizon-optifine" }
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
horizon-threads = { path = "../horizon-threads" }
horizon-perf-format = { path = "../horizon-perf-format" }
horizon-hdr = { path = "../horizon-hdr" }
horizon-world = { path = "../horizon-world" }
horizon-protocol = { path = "../horizon-protocol" }
@@ -73,6 +74,8 @@ horizon-theme = { path = "../horizon-theme" }
# anonymous "I'm playing" ping is the Horizon layer's (`horizon-heartbeat`, in the official executable).
horizon-telemetry = { path = "../horizon-telemetry", default-features = false }
horizon-bench = { path = "../horizon-bench" }
# The machine and process probes (the dedicated server's performance report).
horizon-system = { path = "../horizon-system" }
crc32fast = "1"
zip = { version = "9.1.3", default-features = false, features = ["deflate"] }
# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input); the `controllers` feature.
@@ -90,10 +93,6 @@ fs4 = { version = "1.1.0", default-features = false, features = ["sync"] }
rustix = { version = "1", default-features = false, features = ["std", "time", "process", "fs"] }
[target.'cfg(windows)'.dependencies]
# Resolve virtualized folders to shell-compatible physical paths.
dunce = "1.0.5"
# Use the registered URI handler without routing links through Explorer/cmd.
open = { version = "5.4.5", features = ["shellexecute-on-windows"] }
# DirectX 12, where Vulkan has no adapter or device, or by choice (`graphicsApi`, graphics.rs).
# Shaders compile with FXC (d3dcompiler_47.dll, part of Windows), or on integrated GPUs with DXC
# (dxcompiler.dll beside the game, gfx/dx12_compiler.rs).
@@ -132,7 +131,9 @@ friends = ["dep:horizon-friends"]
rng-trace = ["horizon-core/rng-trace", "horizon-client-lib/rng-trace"]
# Rust's allocations go to the system heap instead of mimalloc, where heap profilers that replace
# malloc (heaptrack, valgrind's massif) see them. For profiling only: mimalloc is faster.
system-allocator = []
system-allocator = ["horizon-threads/system-allocator"]
# mimalloc that counts each thread's allocations and frees (`stats` replies with `alloc`).
alloc-count = ["horizon-threads/alloc-count"]
# mimalloc with a tag on each block: `horizon-ctl memory` lists the live heap by startup step and
# thread (`heap_by_tag_mb`). For measuring only: each block costs 16 bytes more.
alloc-census = ["horizon-threads/alloc-census"]
@@ -176,5 +177,6 @@ workspace = true
[dev-dependencies]
horizon-client-render = { path = "../horizon-client-render", features = ["test-support"] }
horizon-items = { path = "../horizon-items", features = ["test-support"] }
horizon-perf = { path = "../horizon-perf" }
# Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests).
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] }
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Growwe verre terrein in plaaslike wêrelde. Geïntegreerde GPU's stop by 128 stukke.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Verminder trek veel terrein growwer: vinniger op hierdie geïntegreerde GPU.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Verminder trek veel terrein growwer, vir GPU's word dit stadiger.",
"Field of view. Wider shows more terrain at once.": "Gesigsveld. Wyer wys meer terrein op een slag.",
"Caps frames per second; a cap saves power and heat.": "Caps rame per sekonde; 'n pet spaar krag en hitte.",
"Waits for the display's refresh: no tearing, a little latency.": "Wag vir die verversing van die skerm: geen skeur nie, 'n bietjie vertraging.",
"Size of menus and the HUD.": "Grootte van spyskaarte en die HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Maak gekartelde rande glad. FXAA: sagter. TAA: gladste, bewegende dinge kan loop.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Maak die wêreld kleiner en herbou dit met TAA. Vinniger, sagter.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Verskerp die opgeskaalde beeld. Hoër: skerper rande, meer flikkering.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "HDR-uitset op 'n HDR-skerm: lawa, vuur en sonlig skyn helderder.",
"How frames reach the screen while VSync is off.": "Hoe rame die skerm bereik terwyl VSync af is.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Doeltreffende slaap tot die volgende raam; Presiese draaie, soos vanielje.",
"Fills the screen (borderless).": "Vul die skerm (randloos).",
"Brightens dark places.": "Verhelder donker plekke.",
"Lowers the frame rate when minimised, or idle too.": "Verlaag die raamtempo wanneer dit geminimaliseer word, of ook ledig.",
"Sways the view while walking.": "Swaai die uitsig terwyl jy stap.",
"Fades newly loaded chunks in.": "Vervaag nuutgelaaide stukke in.",
"Darkens the screen's edges.": "Maak die skerm se rande donkerder.",
"Shows when the world saves.": "Wys wanneer die wêreld red.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Hierdie bediener is in aanlynmodus: vanlyn profiele kan nie daarby aansluit nie; elke speler het sy eie Minecraft-rekening nodig.",
"horizon.splitscreen.own_account": "Hierdie bediener vereis elke speler se eie Minecraft-rekening",
"horizon.splitscreen.local_only": "Ander spelers kan slegs met hul eie Minecraft-rekening by hierdie bediener aansluit: vanlyn profiele speel in jou wêreld, op LAN of op 'n bediener op jou plaaslike netwerk.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Versteek modelle agter ondeursigtige blokke. Async kontroleer af-draad; entiteite merk.",
"Block Entities": "Blok Entiteite",
"Shulker Boxes": "Shulkerbokse",
"Reuses settled boxes; lid movement stays animated.": "Hergebruik afgewikkelde bokse; dekselbeweging bly geanimeerd.",
@@ -621,10 +617,6 @@
"horizon.agent.session_opened": "Geopen vir hierdie sessie deur die program wat die speletjie begin het.",
"horizon.agent.socket": "Sok: %s (kopieer die besonderhede vir sy volledige pad)",
"horizon.agent.local_only": "Slegs plaaslik: agente op hierdie rekenaar, nooit die netwerk nie.",
"%s nits": "%s nete",
"Auto (%s nits)": "Outo (%s nete)",
"%.2f nits": "%.2f nete",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Versteek modelle agter ondeursigtige blokke. Entiteite-opdatering. Af met pasgemaakte pakke.",
"Entity Culling Precheck": "Entiteit-uitdunning-voorafkontrole",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Voer die skare-AABB-voorafkontrole uit ná hierdie aantal gelaaide skare. Nul skakel dit af.",
"%s mobs": "%s skares",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "التضاريس البعيدة الخشنة في العوالم المحلية. تتوقف وحدات معالجة الرسومات المدمجة عند 128 قطعة.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "تم تقليل الرسم على التضاريس البعيدة: بشكل أسرع على وحدة معالجة الرسومات المدمجة هذه.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "يتم تقليل الرسوم على التضاريس البعيدة بشكل أكثر خشونة، أما بالنسبة لوحدات معالجة الرسومات فإنها تبطئ.",
"Field of view. Wider shows more terrain at once.": "مجال الرؤية. يُظهر العرض الأوسع المزيد من التضاريس في وقت واحد.",
"Caps frames per second; a cap saves power and heat.": "قبعات الإطارات في الثانية الواحدة؛ غطاء يوفر الطاقة والحرارة.",
"Waits for the display's refresh: no tearing, a little latency.": "في انتظار تحديث الشاشة: بدون تمزق، وقليل من زمن الوصول.",
"Size of menus and the HUD.": "حجم القوائم وHUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "ينعم الحواف الخشنة. FXAA: أكثر ليونة. TAA: قد تتبع الأشياء الأكثر سلاسة وتحريكًا.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "يجعل العالم أصغر حجمًا ويعيد بنائه باستخدام TAA. أسرع وأكثر ليونة.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "يزيد حدة الصورة المرتقاة. أعلى: حواف أوضح ووميض أكثر.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "إخراج HDR على شاشة HDR: تتألق الحمم البركانية والنار وأشعة الشمس بشكل أكثر سطوعًا.",
"How frames reach the screen while VSync is off.": "كيفية وصول الإطارات إلى الشاشة أثناء إيقاف تشغيل VSync.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "ينام بكفاءة حتى الإطار التالي؛ يدور بدقة، مثل الفانيليا.",
"Fills the screen (borderless).": "يملأ الشاشة (بلا حدود).",
"Brightens dark places.": "يضيء الأماكن الداكنة.",
"Lowers the frame rate when minimised, or idle too.": "يخفض معدل الإطارات عند تصغيره أو في وضع الخمول أيضًا.",
"Sways the view while walking.": "يتأرجح المنظر أثناء المشي.",
"Fades newly loaded chunks in.": "يتلاشى القطع المحملة حديثًا.",
"Darkens the screen's edges.": "لتغميق حواف الشاشة.",
"Shows when the world saves.": "يظهر عندما ينقذ العالم.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "هذا الخادم في وضع الاتصال: لا يمكن للملفات الشخصية غير المتصلة الانضمام إليه، وكل لاعب يحتاج حساب Minecraft خاصًا به.",
"horizon.splitscreen.own_account": "يحتاج هذا الخادم حساب Minecraft خاصًا بكل لاعب",
"horizon.splitscreen.local_only": "يمكن للاعبين الآخرين الانضمام إلى هذا الخادم فقط بحساب Minecraft خاص بهم: أما الملفات الشخصية غير المتصلة فتلعب في عالمك، على LAN أو على خادم في شبكتك المحلية.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "يخفي النماذج خلف الكتل المعتمة. غير متزامن يتحقق من خارج الموضوع؛ علامة الكيانات.",
"Block Entities": "حظر الكيانات",
"Shulker Boxes": "صناديق شوكر",
"Reuses settled boxes; lid movement stays animated.": "إعادة استخدام الصناديق المستقرة؛ تبقى حركة الغطاء متحركة.",
@@ -621,10 +617,6 @@
"horizon.agent.session_opened": "تم فتحه لهذه الجلسة بواسطة البرنامج الذي بدأ اللعبة.",
"horizon.agent.socket": "المقبس: %s (انسخ التفاصيل لمساره الكامل)",
"horizon.agent.local_only": "محلي فقط: الوكلاء على هذا الكمبيوتر، وليس الشبكة أبدًا.",
"%s nits": "%s القمل",
"Auto (%s nits)": "تلقائي (%s شمعة في المتر المربع)",
"%.2f nits": "%.2f القمل",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "يخفي النماذج خلف الكتل المعتمة. تحديث الكيانات مع حزم مخصصة.",
"Entity Culling Precheck": "فحص استبعاد الكيانات المسبق",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "يشغّل فحص AABB للغوغاء بعد هذا العدد من الغوغاء المحمّلين. صفر يعطّله.",
"%s mobs": "%s غوغاء",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Yerli dünyalarda kobud uzaq ərazi. İnteqrasiya edilmiş GPU-lar 128 hissədə dayanır.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Azaldılmış ərazini daha qaba çəkir: bu inteqrasiya olunmuş GPU-da daha sürətli.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Azaldılmış ərazini daha qaba çəkir, GPU-lar üçün isə yavaşlayır.",
"Field of view. Wider shows more terrain at once.": "Baxış sahəsi. Daha geniş bir anda daha çox ərazini göstərir.",
"Caps frames per second; a cap saves power and heat.": "Saniyədə kadrların sayı; qapaq enerjiyə və istiliyə qənaət edir.",
"Waits for the display's refresh: no tearing, a little latency.": "Ekranın təzələnməsini gözləyir: cırılma, bir az gecikmə.",
"Size of menus and the HUD.": "Menyuların ölçüsü və HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Kəsik kənarları hamarlayır. FXAA: daha yumşaq. TAA: ən hamar, hərəkətli şeylər cığır çəkə bilər.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Dünyanı daha kiçik edir və TAA ilə yenidən qurur. Daha sürətli, daha yumşaq.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Böyüdülmüş təsviri kəskinləşdirir. Daha yüksək: daha aydın kənarlar, daha çox parıltı.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "HDR displeydə HDR çıxışı: lava, yanğın və günəş işığı daha parlaq parlayır.",
"How frames reach the screen while VSync is off.": "VSync söndürüldükdə çərçivələr ekrana necə çatır.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Növbəti kadra qədər səmərəli yuxular; Vanil kimi dəqiq spinlər.",
"Fills the screen (borderless).": "Ekranı doldurur (sərhədsiz).",
"Brightens dark places.": "Qaranlıq yerləri işıqlandırır.",
"Lowers the frame rate when minimised, or idle too.": "Minimumlaşdırıldıqda və ya boş olduqda kadr sürətini azaldır.",
"Sways the view while walking.": "Gəzərkən mənzərəni yelləyir.",
"Fades newly loaded chunks in.": "Yeni yüklənmiş parçaları sönür.",
"Darkens the screen's edges.": "Ekranın kənarlarını qaraldır.",
"Shows when the world saves.": "Dünyanın nə vaxt xilas etdiyini göstərir.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Bu server onlayn rejimdədir: oflayn profillər ona qoşula bilməz, hər oyunçunun öz Minecraft hesabı lazımdır.",
"horizon.splitscreen.own_account": "Bu server hər oyunçunun öz Minecraft hesabını tələb edir",
"horizon.splitscreen.local_only": "Digər oyunçular bu serverə yalnız öz Minecraft hesabları ilə qoşula bilər: oflayn profillər sizin dünyanızda, LAN-da və ya yerli şəbəkənizdəki serverdə oynayır.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Modelləri qeyri-şəffaf blokların arxasında gizlədir. Async-dən kənar yoxlayır; qurumlar işarələyir.",
"Block Entities": "Blok obyektləri",
"Shulker Boxes": "Shulker qutuları",
"Reuses settled boxes; lid movement stays animated.": "Yerləşmiş qutuları təkrar istifadə edir; qapaq hərəkəti canlı qalır.",
@@ -621,10 +617,6 @@
"horizon.agent.session_opened": "Oyuna başlayan proqram tərəfindən bu sessiya üçün açıldı.",
"horizon.agent.socket": "Soket: %s (tam yolu üçün təfərrüatları kopyalayın)",
"horizon.agent.local_only": "Yalnız yerli: bu kompüterdəki agentlər, heç vaxt şəbəkə.",
"%s nits": "%s nit",
"Auto (%s nits)": "Avtomatik (%s nits)",
"%.2f nits": "%.2f nit",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Modelləri qeyri-şəffaf blokların arxasında gizlədir. Müəssisələrin yenilənməsi. Fərdi paketlərlə endirim.",
"Entity Culling Precheck": "Obyekt kəsmə ön yoxlaması",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Yüklənmiş mob sayı bu həddə çatanda mob AABB ön yoxlamasını işlədir. Sıfır onu söndürür.",
"%s mobs": "%s mob",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Урындағы донъяларҙа ҡырыҫ алыҫ ерҙәр. Интеграцияланған график процессорҙар 128 өлөштә туҡтай.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Ҡыҫҡартылған тарта алыҫ ер ҡырыҫ: тиҙерәк был интеграцияланған GPU.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Кәметелгән тарта алыҫ ер ҡырыҫыраҡ, GPUs өсөн ул яйлатып.",
"Field of view. Wider shows more terrain at once.": "Күренеш өлкәһе. Киңерәк бер юлы күберәк ерҙе күрһәтә.",
"Caps frames per second; a cap saves power and heat.": "Ҡапҡастар кадрҙар секундына; ҡапҡас энергияны һәм йылылыҡты һаҡлай.",
"Waits for the display's refresh: no tearing, a little latency.": "Дисплейҙы яңыртыуҙы көтә: йыртыу юҡ, бер аҙ тотҡарлыҡ.",
"Size of menus and the HUD.": "Размер меню һәм HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Тешле ситтәрен тигеҙләй. ФХАА: йомшағыраҡ. ТАА: иң шыма, хәрәкәт итеүсе әйберҙәр эҙҙәре булыуы мөмкин.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Донъяны бәләкәйерәк итә һәм уны ТАА менән яңынан төҙөй. Тиҙерәк, йомшағыраҡ.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Масштабланған һүрәтте үткерләндерә. Юғарыраҡ: ситтәр асығыраҡ, ялтырау күберәк.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "HDR дисплейында HDR сығышы: лава, ут һәм ҡояш нурҙары сағыуыраҡ балҡый.",
"How frames reach the screen while VSync is off.": "Нисек кадрҙар экранға етә, ә VSync өҙөлгән.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Һөҙөмтәле йоҡлай сираттағы кадрға тиклем; Теүәл әйләнештәр, ваниль кеүек.",
"Fills the screen (borderless).": "Экранды тултыра (сикһеҙ).",
"Brightens dark places.": "Ҡараңғы урындарҙы яҡтырта.",
"Lowers the frame rate when minimised, or idle too.": "Кадрҙар йышлығын түбәнәйтә, ҡасан минималь, йәки буш ла.",
"Sways the view while walking.": "Йөрөгәндә ҡарашты һелкетә.",
"Fades newly loaded chunks in.": "Яңы тейәлгән өлөштәрҙе һүнә.",
"Darkens the screen's edges.": "Экрандың ситтәрен ҡарайта.",
"Shows when the world saves.": "Донъя ҡотҡарғанда күрһәтә.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Был сервер онлайн режимда: офлайн профилдәр уға ҡушыла алмай, һәр уйынсыға үҙ Minecraft иҫәбе кәрәк.",
"horizon.splitscreen.own_account": "Был серверға һәр уйынсының үҙ Minecraft иҫәбе кәрәк",
"horizon.splitscreen.local_only": "Башҡа уйынсылар был серверға үҙҙәренең Minecraft иҫәбенә генә ҡушыла ала: офлайн профилдәр һеҙҙең донъяла, LAN йәки һеҙҙең урындағы селтәрҙәге серверҙа уйнай.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Моделдәрҙе асыҡ булмаған блоктар артында йәшерә. Ассинхрон тикшерә тышҡы еп; субъекттар галочкой.",
"Block Entities": "Блок субъекттары",
"Shulker Boxes": "Шулкер йәшниктәре",
"Reuses settled boxes; lid movement stays animated.": "Ҡабаттан ҡуллана урынлаштырылған йәшниктәр; ҡапҡас хәрәкәте йәнле ҡала.",
@@ -621,10 +617,6 @@
"horizon.agent.session_opened": "Был сессия өсөн уйынды башлаған программа асты.",
"horizon.agent.socket": "Розетка: %s (уның тулы юлы өсөн реквизиттарҙы күсерергә)",
"horizon.agent.local_only": "Урындағы ғына: был компьютерҙа агенттар, бер ҡасан да селтәр.",
"%s nits": "%s нит",
"Auto (%s nits)": "Авто (%s нит)",
"%.2f nits": "%.2f нит",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Моделдәрҙе асыҡ булмаған блоктар артында йәшерә. Яңыртыу субъекттары. Ҡулланыусылар пакеттары менән өҙөлгән.",
"Entity Culling Precheck": "Субъекттарҙы ҡырҡыуҙы алдан тикшереү",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Моб AABB алдан тикшереүен был һандағы тейәлгән мобтан һуң башҡара. Ноль уны һүндерә.",
"%s mobs": "%s моб",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Грубая аддаленая мясцовасць у лакальных мірах. Убудаваныя графічныя працэсары спыняюцца на 128 кавалках.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Паменшанае малюнак больш грубай мясцовасці: хутчэй на гэтым убудаваным графічным працэсары.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Зніжэнне малюе больш грубую мясцовасць, для графічных працэсараў гэта запавольваецца.",
"Field of view. Wider shows more terrain at once.": "Поле зроку. Шырэй паказвае адразу больш мясцовасці.",
"Caps frames per second; a cap saves power and heat.": "Колькасць кадраў у секунду; шапка эканоміць энергію і цяпло.",
"Waits for the display's refresh: no tearing, a little latency.": "Чакае абнаўлення дысплея: без разрыву, з невялікай затрымкай.",
"Size of menus and the HUD.": "Памер меню і HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Згладжвае няроўныя краю. FXAA: мякчэй. TAA: самыя гладкія рэчы, якія рухаюцца, могуць цягнуцца.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Памяншае свет і перабудоўвае яго з TAA. Хутчэй, мякчэй.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Павялічвае рэзкасць павялічанай выявы. Вышэй: больш рэзкія краі, больш мігацення.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "Вывад HDR на дысплеі HDR: лава, агонь і сонечнае святло ззяюць ярчэй.",
"How frames reach the screen while VSync is off.": "Як кадры трапляюць на экран, калі VSync выключаны.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Эфектыўнае спіць да наступнага кадра; Дакладныя спіны, як ваніль.",
"Fills the screen (borderless).": "Запаўняе экран (без палёў).",
"Brightens dark places.": "Асвятляе цёмныя месцы.",
"Lowers the frame rate when minimised, or idle too.": "Зніжае частату кадраў пры згортванні або ў рэжыме чакання.",
"Sways the view while walking.": "Качае погляд падчас хады.",
"Fades newly loaded chunks in.": "Змяншае толькі што загружаныя кавалкі.",
"Darkens the screen's edges.": "Зацямняе краю экрана.",
"Shows when the world saves.": "Паказвае, калі свет ратуе.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Гэты сервер у анлайн-рэжыме: афлайн-профілі не могуць далучыцца, кожнаму гульцу патрэбны ўласны ўліковы запіс Minecraft.",
"horizon.splitscreen.own_account": "Гэтаму серверу патрэбны ўласны ўліковы запіс Minecraft для кожнага гульца",
"horizon.splitscreen.local_only": "Іншыя гульцы могуць далучыцца да гэтага сервера толькі са сваім уліковым запісам Minecraft: афлайн-профілі гуляюць у вашым свеце, па LAN або на серверы ў вашай лакальнай сетцы.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Хавае мадэлі за непразрыстымі блокамі. Async правярае па-за патокам; суб'ектаў цік.",
"Block Entities": "Блокавыя аб'екты",
"Shulker Boxes": "Скрынкі Шулкера",
"Reuses settled boxes; lid movement stays animated.": "Паўторна выкарыстоўвае адстойнікі; рух вечка застаецца ажыўленым.",
@@ -621,10 +617,6 @@
"horizon.agent.session_opened": "Адкрыты для гэтай сесіі праграмай, якая запусціла гульню.",
"horizon.agent.socket": "Сокет: %s (скапіруйце дэталі для поўнага шляху)",
"horizon.agent.local_only": "Толькі лакальна: агенты на гэтым кампутары, ніколі ў сетцы.",
"%s nits": "%s ніт",
"Auto (%s nits)": "Аўта (%s ніт)",
"%.2f nits": "%.2f ніт",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Хавае мадэлі за непразрыстымі блокамі. Абнаўленне суб'ектаў. Выключыце спецыяльныя пакеты.",
"Entity Culling Precheck": "Папярэдняя праверка адсячэння сутнасцей",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Выконвае папярэднюю праверку AABB мабаў пасля гэтай колькасці загружаных мабаў. Нуль адключае яе.",
"%s mobs": "%s мабаў",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Груб далечен терен в местните светове. Интегрираните графични процесори спират на 128 парчета.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Намалено чертане на по-груб терен: по-бързо с този интегриран GPU.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Намалено рисува далеч по-груб терен, за GPU се забавя.",
"Field of view. Wider shows more terrain at once.": "Зрително поле. По-широко показва повече терен наведнъж.",
"Caps frames per second; a cap saves power and heat.": "Максимални кадри в секунда; капачката спестява енергия и топлина.",
"Waits for the display's refresh: no tearing, a little latency.": "Изчаква опресняване на дисплея: без разкъсване, малко забавяне.",
"Size of menus and the HUD.": "Размер на менютата и HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Изглажда назъбените ръбове. FXAA: по-мек. TAA: най-плавните, движещи се неща могат да се проточат.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Прави света по-малък и го възстановява с TAA. По-бързо, по-меко.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Изостря премащабираната картина. По-високо: по-ясни ръбове, повече трептене.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "HDR изход на HDR дисплей: лава, огън и слънчева светлина блестят по-ярко.",
"How frames reach the screen while VSync is off.": "Как кадрите достигат до екрана, докато VSync е изключен.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Ефективно заспиване до следващия кадър; Прецизни завъртания, като ванилия.",
"Fills the screen (borderless).": "Запълва екрана (без граници).",
"Brightens dark places.": "Осветява тъмните места.",
"Lowers the frame rate when minimised, or idle too.": "Намалява честотата на кадрите, когато е минимизирана или неактивна.",
"Sways the view while walking.": "Люлее гледката по време на ходене.",
"Fades newly loaded chunks in.": "Избледнява новозаредените парчета.",
"Darkens the screen's edges.": "Затъмнява ръбовете на екрана.",
"Shows when the world saves.": "Показва кога светът спасява.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Този сървър е в онлайн режим: офлайн профилите не могат да се присъединят, всеки играч се нуждае от собствен акаунт в Minecraft.",
"horizon.splitscreen.own_account": "Този сървър изисква собствен акаунт в Minecraft за всеки играч",
"horizon.splitscreen.local_only": "Другите играчи могат да се присъединят към този сървър само със свой акаунт в Minecraft: офлайн профилите играят във вашия свят, в LAN или на сървър в локалната ви мрежа.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Скрива модели зад непрозрачни блокове. Async проверява извън нишката; субекти отметка.",
"Block Entities": "Блокиране на обекти",
"Shulker Boxes": "Кутии Шулкер",
"Reuses settled boxes; lid movement stays animated.": "Повторно използване на утаени кутии; движението на капака остава анимирано.",
@@ -620,10 +616,6 @@
"horizon.agent.session_opened": "Отворено за тази сесия от програмата, която стартира играта.",
"horizon.agent.socket": "Сокет: %s (копирайте подробностите за пълния му път)",
"horizon.agent.local_only": "Само локално: агенти на този компютър, никога в мрежата.",
"%s nits": "%s нита",
"Auto (%s nits)": "Автоматично (%s нита)",
"%.2f nits": "%.2f нита",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Скрива модели зад непрозрачни блокове. Актуализация на обекти. Изключване с персонализирани пакети.",
"Entity Culling Precheck": "Предварителна проверка на отстраняването",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Изпълнява предварителната проверка на AABB за тълпите след толкова заредени тълпи. Нула я изключва.",
"%s mobs": "%s тълпи",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Douaroù pell gros e bedoù lec'hel. Paouez a ra ar GPUoù kevredet da 128 tamm.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Digreskiñ a ra an douaroù kalz grosoc'h : buanoc'h war ar GPU kevredet-mañ.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Ar reduset a denn an douaroù kalz grosoc'h, evit ar GPUoù e vez gorrekaet.",
"Field of view. Wider shows more terrain at once.": "Tachenn gwel. Ledanoc'h a ziskouez muioc'h a zouaroù war un dro.",
"Caps frames per second; a cap saves power and heat.": "Bep frammoù dre eilenn; ur c'hasketenn a espern energiezh ha tommder.",
"Waits for the display's refresh: no tearing, a little latency.": "Gortoz a ra freskaat ar skramm : tamm torr ebet, un tamm dale.",
"Size of menus and the HUD.": "Ment ar mennozhioù hag an HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Eeunaat a ra ar c'hornioù ruz. FXAA: dousoc'h. TAA: an traoù eeunañ, o fiñval a c'hell heuliañ.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Bihanaat a ra ar bed hag adsevel anezhañ gant TAA. Buanoc'h, dousoc'h.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Lemmaat a ra ar skeudenn gresket. Uheloc'h : bordoù lemmoc'h, muioc'h a sked.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "Disoc'h HDR war ur skramm HDR : lava, tan ha gouloù an heol a lugern muioc'h.",
"How frames reach the screen while VSync is off.": "Penaos e tistro ar frammoù war ar skramm pa vez diweredekaet VSync.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Kousket a ra efedus betek ar framm da heul; Troioù resis, evel ar vanilha.",
"Fills the screen (borderless).": "Leuniañ ar skramm (hep bevennoù).",
"Brightens dark places.": "Sklaeraat a ra al lec'hioù teñval.",
"Lowers the frame rate when minimised, or idle too.": "Digreskiñ a ra ar feur framm pa vez bihanaet, pe pa vez didalvoud ivez.",
"Sways the view while walking.": "Heñchañ a ra ar gwel e-pad ma kerzher.",
"Fades newly loaded chunks in.": "Diverkañ a ra an tammoù nevez karget.",
"Darkens the screen's edges.": "Teñvalaat a ra ribloù ar skramm.",
"Shows when the world saves.": "Diskouez a ra pa savete ar bed.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "E mod enlinenn emañ ar servijer-mañ : n'hall ket ar profiloù ezlinenn mont e-barzh, pep c'hoarier en deus ezhomm eus e gont Minecraft.",
"horizon.splitscreen.own_account": "Ezhomm en deus ar servijer-mañ eus ur gont Minecraft evit pep c'hoarier",
"horizon.splitscreen.local_only": "Ar c'hoarierien all ne c'hallont mont e-barzh ar servijer-mañ nemet gant o c'hont Minecraft o-unan : ar profiloù ezlinenn a c'hoari en ho bed, war LAN pe war ur servijer war ho rouedad lec'hel.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Kuzhat a ra ar patromoù a-dreñv bloc'hoù dister. Gwiriañ a ra an async e-maez an neudennad; tik an entiteoù.",
"Block Entities": "Entiteoù stankañ",
"Shulker Boxes": "Boestoù Shulker",
"Reuses settled boxes; lid movement stays animated.": "Adimplij a ra ar voestoù staliet; fiñv ar golo a chom bev.",
@@ -621,10 +617,6 @@
"horizon.agent.session_opened": "Digoret evit ar prantad-mañ gant ar programm en deus kroget ar c'hoari.",
"horizon.agent.socket": "Socket: %s (eilañ ar munudoù evit e hent klok)",
"horizon.agent.local_only": "Lec'hel hepken : an ajañsoù war an urzhiataer-mañ, biskoazh ar rouedad.",
"%s nits": "%s nits",
"Auto (%s nits)": "Emgefre (%s nits)",
"%.2f nits": "%.2f nits",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Kuzhat a ra ar patromoù a-dreñv bloc'hoù dister. Hizivaat an ensavadurioù. Dilezet gant pakadoù personelaet.",
"Entity Culling Precheck": "Rakwiriañ distruj an entiteoù",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Kas a ra rakwiriad AABB ar moboù goude kement-mañ a voboù karget. Zero a ziweredeka anezhañ.",
"%s mobs": "%s mob",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Grubi udaljeni teren u lokalnim svjetovima. Integrisani GPU-ovi se zaustavljaju na 128 komada.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Smanjeno crtanje dalekog terena grublje: brže na ovom integrisanom GPU-u.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Smanjeno crtanje dalekog terena je grublje, za GPU-ove usporava.",
"Field of view. Wider shows more terrain at once.": "Vidno polje. Šire prikazuje više terena odjednom.",
"Caps frames per second; a cap saves power and heat.": "Caps okvira u sekundi; kapa štedi energiju i toplotu.",
"Waits for the display's refresh: no tearing, a little latency.": "Čeka osvježavanje ekrana: nema kidanja, malo kašnjenja.",
"Size of menus and the HUD.": "Veličina menija i HUD-a.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Zaglađuje nazubljene ivice. FXAA: mekše. TAA: najglađe, pokretne stvari mogu zaostajati.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Čini svijet manjim i obnavlja ga pomoću TAA. Brže, mekše.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Izoštrava uvećanu sliku. Više: oštrije ivice, više treperenja.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "HDR izlaz na HDR displeju: lava, vatra i sunčeva svetlost sijaju jače.",
"How frames reach the screen while VSync is off.": "Kako okviri dolaze do ekrana dok je VSync isključen.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Efikasno spavanje do sljedećeg kadra; Precizno okretanje, poput vanile.",
"Fills the screen (borderless).": "Ispunjava ekran (bez ivica).",
"Brightens dark places.": "Osvjetljava tamna mjesta.",
"Lowers the frame rate when minimised, or idle too.": "Smanjuje brzinu kadrova kada je minimizirana ili u stanju mirovanja.",
"Sways the view while walking.": "Ljulja pogled dok hodate.",
"Fades newly loaded chunks in.": "Uklanja novoučitane komade.",
"Darkens the screen's edges.": "Zatamnjuje ivice ekrana.",
"Shows when the world saves.": "Prikazuje kada svijet spašava.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Ovaj server je u online modu: offline profili mu se ne mogu pridružiti, svaki igrač treba vlastiti Minecraft nalog.",
"horizon.splitscreen.own_account": "Ovaj server zahtijeva vlastiti Minecraft nalog za svakog igrača",
"horizon.splitscreen.local_only": "Drugi igrači se mogu pridružiti ovom serveru samo sa svojim Minecraft nalogom: offline profili igraju u vašem svijetu, na LAN-u ili na serveru na vašoj lokalnoj mreži.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Skriva modele iza neprozirnih blokova. Async provjerava off-thread; entiteti otkucaju.",
"Block Entities": "Blokirajte entitete",
"Shulker Boxes": "Kutije za šulkere",
"Reuses settled boxes; lid movement stays animated.": "Ponovno koristi postavljene kutije; pokreti poklopca ostaju animirani.",
@@ -620,10 +616,6 @@
"horizon.agent.session_opened": "Otvoreno za ovu sesiju od strane programa koji je pokrenuo igru.",
"horizon.agent.socket": "Socket: %s (kopirajte detalje za njegovu punu putanju)",
"horizon.agent.local_only": "Samo lokalno: agenti na ovom računaru, nikada mreža.",
"%s nits": "%s gnjida",
"Auto (%s nits)": "automatski (%s gnjida)",
"%.2f nits": "%.2f gnjida",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Skriva modele iza neprozirnih blokova. Ažuriranje entiteta. Isključeno sa prilagođenim paketima.",
"Entity Culling Precheck": "Prethodna provjera odbijanja entiteta",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Pokreće AABB prethodnu provjeru mobova nakon ovoliko učitanih mobova. Nula je isključuje.",
"%s mobs": "%s mobova",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Terreny llunyà gruixut en mons locals. Les GPU integrades s'aturen a 128 fragments.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Dibuixos reduïts molt llunyans més gruixuts: més ràpid en aquesta GPU integrada.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Els dibuixos reduïts són molt més gruixuts, per a les GPU s'alenteix.",
"Field of view. Wider shows more terrain at once.": "Camp de visió. Més ample mostra més terreny alhora.",
"Caps frames per second; a cap saves power and heat.": "Caps fotogrames per segon; una tapa estalvia energia i calor.",
"Waits for the display's refresh: no tearing, a little latency.": "Espera que la pantalla s'actualitzi: sense trencament, una mica de latència.",
"Size of menus and the HUD.": "Mida dels menús i l'HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Allisa les vores dentades. FXAA: més suau. TAA: més suau, les coses en moviment poden seguir.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Redueix el món i el reconstrueix amb TAA. Més ràpid, més suau.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Fa més nítida la imatge ampliada. Més alt: vores més nítides, més tremolor.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "Sortida HDR en una pantalla HDR: la lava, el foc i la llum del sol brillen més.",
"How frames reach the screen while VSync is off.": "Com arriben els fotogrames a la pantalla mentre VSync està desactivat.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Dors eficients fins al següent fotograma; Girades precises, com la vainilla.",
"Fills the screen (borderless).": "Omple la pantalla (sense vores).",
"Brightens dark places.": "Il·lumina els llocs foscos.",
"Lowers the frame rate when minimised, or idle too.": "Redueix la velocitat de fotogrames quan es minimitza o també està inactiva.",
"Sways the view while walking.": "Oblida la vista mentre camina.",
"Fades newly loaded chunks in.": "Esvaeix els fragments que s'han carregat recentment.",
"Darkens the screen's edges.": "Enfosqueix les vores de la pantalla.",
"Shows when the world saves.": "Mostra quan el món salva.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Aquest servidor està en mode en línia: els perfils fora de línia no s'hi poden unir, cada jugador necessita el seu propi compte de Minecraft.",
"horizon.splitscreen.own_account": "Aquest servidor necessita el compte de Minecraft propi de cada jugador",
"horizon.splitscreen.local_only": "Els altres jugadors només s'hi poden unir amb el seu propi compte de Minecraft: els perfils fora de línia juguen al teu món, a la LAN o en un servidor de la teva xarxa local.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Amaga models darrere de blocs opacs. Async comprova fora de fil; les entitats marquen.",
"Block Entities": "Bloquejar entitats",
"Shulker Boxes": "Caixes Shulker",
"Reuses settled boxes; lid movement stays animated.": "Reutilitza caixes assentades; el moviment de la tapa es manté animat.",
@@ -620,10 +616,6 @@
"horizon.agent.session_opened": "Obert per a aquesta sessió pel programa que va iniciar el joc.",
"horizon.agent.socket": "Socket: %s (copieu els detalls del camí complet)",
"horizon.agent.local_only": "Només local: agents en aquest ordinador, mai la xarxa.",
"%s nits": "%s nits",
"Auto (%s nits)": "Automàtic (%s nits)",
"%.2f nits": "%.2f nits",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Amaga models darrere de blocs opacs. Actualització d'entitats. Apaga amb paquets personalitzats.",
"Entity Culling Precheck": "Comprovació prèvia del culling d'entitats",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Executa la comprovació prèvia d'AABB dels mobs després d'aquest nombre de mobs carregats. Zero la desactiva.",
"%s mobs": "%s mobs",
@@ -301,7 +301,6 @@
"Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.": "Hrubý vzdálený terén v místních světech. Integrované GPU se zastaví na 128 blocích.",
"Reduced draws far terrain coarser: faster on this integrated GPU.": "Snížené vykreslování daleko hrubšího terénu: rychlejší na tomto integrovaném GPU.",
"Reduced draws far terrain coarser, for GPUs it slows down.": "Snížené vykresluje daleko hrubší terén, u GPU se zpomaluje.",
"Field of view. Wider shows more terrain at once.": "Zorné pole. Širší zobrazuje více terénu najednou.",
"Caps frames per second; a cap saves power and heat.": "Počet snímků za sekundu; čepice šetří energii a teplo.",
"Waits for the display's refresh: no tearing, a little latency.": "Čeká na obnovení displeje: žádné trhání, malá latence.",
"Size of menus and the HUD.": "Velikost menu a HUD.",
@@ -339,13 +338,11 @@
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.": "Vyhlazuje zubaté okraje. FXAA: měkčí. TAA: nejhladší, pohyblivé věci se mohou táhnout.",
"Renders the world smaller and rebuilds it with TAA. Faster, softer.": "Zmenší svět a přestaví ho pomocí TAA. Rychlejší, měkčí.",
"Sharpens the upscaled picture. Higher: crisper edges, more shimmer.": "Zaostří zvětšený obraz. Vyšší: ostřejší hrany, více třpytu.",
"HDR output on an HDR display: lava, fire and sunlight shine brighter.": "Výstup HDR na displeji HDR: láva, oheň a sluneční světlo září jasněji.",
"How frames reach the screen while VSync is off.": "Jak se snímky dostanou na obrazovku, když je VSync vypnutá.",
"Efficient sleeps until the next frame; Precise spins, like vanilla.": "Efektivní režim spánku až do dalšího snímku; Přesná rotace, jako vanilka.",
"Fills the screen (borderless).": "Vyplní obrazovku (bez okrajů).",
"Brightens dark places.": "Rozjasňuje tmavá místa.",
"Lowers the frame rate when minimised, or idle too.": "Při minimalizaci nebo nečinnosti sníží snímkovou frekvenci.",
"Sways the view while walking.": "Při chůzi kývá výhled.",
"Fades newly loaded chunks in.": "Nově načtené kousky zmizí.",
"Darkens the screen's edges.": "Ztmaví okraje obrazovky.",
"Shows when the world saves.": "Ukazuje, kdy svět zachraňuje.",
@@ -556,7 +553,6 @@
"horizon.splitscreen.online_only": "Tento server je v online režimu: offline profily se k němu nemohou připojit, každý hráč potřebuje vlastní účet Minecraft.",
"horizon.splitscreen.own_account": "Tento server vyžaduje vlastní účet Minecraft pro každého hráče",
"horizon.splitscreen.local_only": "Ostatní hráči se k tomuto serveru mohou připojit jen s vlastním účtem Minecraft: offline profily hrají ve vašem světě, na LAN nebo na serveru ve vaší místní síti.",
"Hides models behind opaque blocks. Async checks off-thread; entities tick.": "Skryje modely za neprůhledné bloky. Async kontroluje off-thread; entity klíštěte.",
"Block Entities": "Blokovat entity",
"Shulker Boxes": "Krabice Shulker",
"Reuses settled boxes; lid movement stays animated.": "Znovu používá usazené krabice; pohyb víka zůstává animovaný.",
@@ -621,10 +617,6 @@
"horizon.agent.session_opened": "Otevřeno pro tuto relaci programem, který spustil hru.",
"horizon.agent.socket": "Socket: %s (zkopírujte podrobnosti pro jeho úplnou cestu)",
"horizon.agent.local_only": "Pouze místní: agenti na tomto počítači, nikdy v síti.",
"%s nits": "%s hnid",
"Auto (%s nits)": "Auto (%s nitů)",
"%.2f nits": "%.2f hnid",
"Hides models behind opaque blocks. Entities update. Off with custom packs.": "Skryje modely za neprůhledné bloky. Aktualizace entit. Vypnuto s vlastními balíčky.",
"Entity Culling Precheck": "Předkontrola vyřazování entit",
"Runs the mob AABB precheck after this many loaded mobs. Zero disables it.": "Spustí předkontrolu AABB mobů po tomto počtu načtených mobů. Nula ji vypne.",
"%s mobs": "%s mobů",
Loaded 100 of 807 files, more files were not shown because too many files have changed in this diff. Show more