Compare commits

...
Author SHA1 Message Date
rdbtCVSandCodex GPT-6.1 Terra fa0e2b01cd Merge updated item and helper work into mob groundwork
Co-Authored-By: Codex GPT-6.1 Terra <[email protected]>
2026-11-11 08:22:25 +00:00
rdbtCVSandCodex GPT-6.1 Terra f663c83f98 Merge updated parallel tick helpers into item moves
Co-Authored-By: Codex GPT-6.1 Terra <[email protected]>
2026-11-11 08:20:28 +00:00
rdbtCVSandCodex GPT-6.1 Terra 4740691c04 Merge origin/main into parallel tick helpers
Co-Authored-By: Codex GPT-6.1 Terra <[email protected]>
2026-11-11 08:18:54 +00:00
rdbt 04a26210e3 Merge pull request #15038 from horizon-rust/fix/main-ci-after-bulk-merge
Fix CEM compilation and scaled mob culling bounds
2026-11-11 02:39:18 +00:00
rdbtCVSandCodex f37bcae92c Scale culling margins with the mob model root
Include the root model scale in the appendage margin so animated elder guardian vertices remain inside the precheck bounds. The existing prepared-model coverage test remains unchanged.

Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
2026-11-10 23:55:39 +00:00
rdbtCVSandCodex 04b53013c8 Fix CEM own-model lookup shadowing
Keep the own-file map available when selecting the layers covered by a model.

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

Repair the existing escape test's baseline chunk fixture and promote vanilla's 0.98F drag to double in its expected value; no production gameplay change.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-10 23:17:06 +00:00
8a4ca5e7de Merge helper verification into dependent item moves
Preserve helper test commit 41a579d428 and the item phase's original history and authors.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-10 23:08:41 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 2160d3e4d1 The firework event tests pass new_rocket its random
#14603 gave new_rocket the rocket's own random as a fourth argument; the
tests added by 188817342 still called it with three, so the client's tests
stopped compiling on main.

Refs #15025

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-11 00:08:01 +01:00
Nikita Maximilian Grimm 4536ec51ca Merge remote-tracking branch 'origin/main' into fix/hold-fullbright-replay 2026-11-11 00:01:35 +01:00
rdbtCVS 5cc88b517b test: cross parallel tick helper thresholds with real resources
Compare deferred and in-place metadata for 2,085 varied mobs, including pack-selected effect particles and switch-off vector reuse. Exercise live climbing, snapshot order and nearest-player invalidation for 293 mobs. Build 132 random-tick section masks ahead and retain exact event, state and random comparisons through edits and reloads.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: GPT 6.1 Sol <[email protected]>
(cherry picked from commit 41a579d428)
2026-11-10 22:55:55 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 72d1238876 hold_fullbright asks the replay whether it plays
#14335 read Game::studio_replay, which the layer split had moved to
Game::replay before it merged, so main stopped compiling.

Fixes #15025

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 23:51:58 +01:00
rdbt 214469a4bf Merge pull request #14737 from ilguerro/fix/sitting-cat-blocks-comparator
Silence a chest's comparator while a cat sits on it
2026-11-10 22:51:41 +00:00
rdbt b2bfa61fb1 Merge pull request #14987 from DUzzL/fix/14856-shulker-armor
A shulker keeps its armor attribute once its lid has moved
2026-11-10 22:49:57 +00:00
rdbt 5f4dbb058b Merge pull request #14969 from vermingov/fix/villager-food-level-14967
A villager narrows a loaded FoodLevel to a byte (#14967)
2026-11-10 22:49:50 +00:00
rdbt 292dfe14e1 Merge pull request #14955 from DUzzL/fix/14832-zombie-villager-cure
A zombie villager starts its cure when it loads a ConversionTime
2026-11-10 22:49:45 +00:00
rdbt 506624b951 Merge pull request #14951 from Web-mc1/fix/biome-get-empty
Fix biome table panic when empty
2026-11-10 22:49:39 +00:00
rdbt e7fb465789 Merge pull request #14935 from TheMrZZ/slot-sources/holder-tag-codec
Slot sources: holder and tag codec, and slot-source tags in DataStore
2026-11-10 22:49:33 +00:00
rdbt 31af1ed8ad Merge pull request #14932 from Detimes/perf-replay-excuse
Perf: the replay excuse tests the distance before the entity kind
2026-11-10 22:49:28 +00:00
rdbt af3a8d235b Merge pull request #14928 from MSedgeMC/fix/crafter-recipe-book
port: a crafter's grid counts for the recipe book
2026-11-10 22:49:22 +00:00
rdbt 3c564f0e2b Merge pull request #14910 from oloion/fix/custom-crafting-recipes-book
client: show custom server crafting recipes in recipe book
2026-11-10 22:49:17 +00:00
rdbt 45c4e0d744 Merge pull request #14900 from MSedgeMC/fix/jukebox-block-change
port: a disc coming or going posts block_change
2026-11-10 22:49:12 +00:00
rdbt 802056c402 Merge pull request #14892 from NikitaMGrimm/shader-api-primaries-key
Shader API 0.2: [frame] primaries, and the rule for new names
2026-11-10 22:49:06 +00:00
rdbt fc604a958a Merge pull request #14785 from MSedgeMC/fix/merchant-scroller-cursor
The merchant's trade scroller shows its cursor
2026-11-10 22:49:01 +00:00
rdbt 8f98a65be5 Merge pull request #14776 from NongTham/fix/14715-modifier-key-handling
input: clear modifiers on focus loss and heal alt and super keys (fixes #14715)
2026-11-10 22:48:56 +00:00
rdbt 75dc9db341 Merge pull request #14772 from foudretbr/fix/attack-speed-attribute-modifiers
fix(game): evaluate attack_speed attribute modifiers for player attack cooldown (#14721)
2026-11-10 22:48:51 +00:00
rdbt eb161b9c99 Merge pull request #14745 from MSedgeMC/fix/feed-never-baby
A mob that cannot be a baby does not take the food that grows it
2026-11-10 22:48:44 +00:00
rdbt 7687b2a619 Merge pull request #14742 from foudretbr/fix/modifier-key-debug-shortcuts-focus-loss
fix(input): reset debug keys modifier state on window focus loss (#14715)
2026-11-10 22:48:39 +00:00
rdbt 1d50e158b9 Merge pull request #14723 from ilguerro/fix/firework-silent-explode-stat
Firework rockets: honour Silent, post EXPLODE, count block launches
2026-11-10 22:48:33 +00:00
rdbt 58b5d93f8f Merge pull request #14710 from glitchsnake/fix/14467-squid-noai-motion
mobs: apply squid sinking velocity on land under NoAI (fixes #14467)
2026-11-10 22:48:28 +00:00
rdbt 9951ef958d Merge pull request #14705 from Skr1zzzz/falling-model-cache
Falling blocks: cache each model's vertices instead of rebuilding them every frame
2026-11-10 22:48:22 +00:00
rdbt 8cb5c02d4b Merge pull request #14703 from ilguerro/fix/horses-do-not-climb
Stop horses, llamas, camels and flying monsters climbing vines and ladders
2026-11-10 22:48:17 +00:00
rdbt b75ffd9554 Merge pull request #14699 from NikitaMGrimm/hdr-pq-dither
HDR10 output: the last pass dithers its 10 bits, so a clear sky doesn't band
2026-11-10 22:48:12 +00:00
rdbt c7552a32e5 Merge pull request #14697 from ilguerro/fix/phantoms-glass-roof
Spawn phantoms under a glass roof
2026-11-10 22:48:07 +00:00
rdbt ff03932fb0 Merge pull request #14693 from ilguerro/fix/turtle-frog-lay-events
Post block_place when turtles and frogs lay eggs, and stop bred turtles bursting hearts
2026-11-10 22:48:02 +00:00
rdbt 6a007e8e02 Merge pull request #14691 from ilguerro/fix/campfire-candle-douse
Sneaking keeps the held food off campfires and candles answer pick-block
2026-11-10 22:47:57 +00:00
rdbt a4b71ca8ba Merge pull request #14689 from ilguerro/fix/shulker-teleport-vibration
Post a shulker teleport's game event for sculk sensors
2026-11-10 22:47:52 +00:00
rdbt 1386a7fd1f Merge pull request #14677 from YourPancakes/perf/skip-full-cube-shape-allocation
perf(world): avoid full-cube allocation in collision checks
2026-11-10 22:47:47 +00:00
rdbt 5f029bb260 Merge pull request #14672 from YourPancakes/perf/cache-flat-compute-bind-groups
perf(render): cache flat compute bind groups
2026-11-10 22:47:42 +00:00
rdbt 23a2b65c29 Merge pull request #14667 from vnsmoreira/fix/dispensed-item-random
A dispensed item draws its constructor's motion from its own random
2026-11-10 22:47:37 +00:00
rdbt 62165d135d Merge pull request #14665 from YourPancakes/perf/sky-octagon-half-planes
perf(render): evaluate sky octagon with half-planes
2026-11-10 22:47:31 +00:00
rdbt 2732d737a1 Merge pull request #14653 from Ragbie/tests/pad-parity-actions
pad::parity_tests: the pad_press helper records the press, so four tests pass again
2026-11-10 22:47:25 +00:00
rdbt a1807b93a1 Merge pull request #14629 from Ragbie/tests/tnt-silence-stack
TNT silence tests run on an 8 MiB stack, so they don't overflow on Windows
2026-11-10 22:47:18 +00:00
rdbt 53c0b0694b Merge pull request #14602 from ilguerro/fix/sniffer-dig-vibration-silence
Keep animal_brain.rs at main's line count
2026-11-10 22:47:13 +00:00
rdbt cc3e92cadd Merge pull request #14600 from ilguerro/fix/bred-wolf-voice
Move the bred offspring's draws and their test out of creatures.rs
2026-11-10 22:47:08 +00:00
rdbt 27e0787a23 Merge pull request #14592 from NikitaMGrimm/parity/bucket-mob-from-bucket
A mob from a bucket is not persistent, a sulfur cube keeps its bucket's age, and tadpoles never despawn
2026-11-10 22:47:02 +00:00
rdbt f312c30454 Merge pull request #14585 from foudretbr/fix/cat-default-variant-black
fix(mobs): default cat variant to black when omitted
2026-11-10 22:46:57 +00:00
rdbt a79db77ac1 Merge pull request #14573 from MSedgeMC/ledger/moved-citations
port map: point citations at the modules they moved to
2026-11-10 22:46:52 +00:00
rdbt 5fde1275b5 Merge pull request #14556 from ilguerro/fix/wall-hanging-sign-click-command
Run a waxed wall hanging sign's click command instead of chaining a sign
2026-11-10 22:46:46 +00:00
rdbt 7ebdfbc3ee Merge pull request #14508 from Ragbie/tests/mob-landing-neighbourhood
mob_landing_support_tests load the chunks a pig needs to tick
2026-11-10 22:46:41 +00:00
rdbt 9e4e43a69b Merge pull request #14496 from horizon-rust/fix/service-images-path-crates
Telemetry and mod registry images copy every crate their lockfile builds
2026-11-10 22:46:35 +00:00
rdbt 78f286e657 Merge pull request #14492 from Ragbie/fix/landing-vibrations
Primed TNT and falling blocks make a vibration when they land
2026-11-10 22:46:28 +00:00
rdbt 71e8f7c8cd Merge pull request #14489 from MSedgeMC/fix/wololo-visibility
An invisible blue sheep is not wololoed from five blocks
2026-11-10 22:46:23 +00:00
rdbt 91429d906a Merge pull request #14488 from MSedgeMC/fix/sulfur-tempt-visibility
A sulfur cube's tempt range shrinks for an invisible player
2026-11-10 22:46:17 +00:00
rdbt 846e34c2eb Merge pull request #14486 from vnsmoreira/fix/golden-horse-armor
A horse draws its golden armour
2026-11-10 22:46:10 +00:00
rdbt a084ad2f35 Merge pull request #14468 from Solenopsisbot/fix/high-contrast-pack-hang
Fix startup hang with High Contrast resource pack
2026-11-10 22:46:05 +00:00
rdbt 10588c9b4c Merge pull request #14448 from ilguerro/fix/frame-vibrations
Let sculk hear item frame changes as vanilla does
2026-11-10 22:46:00 +00:00
rdbt 8ad2bee66a Merge pull request #14434 from MSedgeMC/fix/written-book-resolve
port: a written book resolves its selectors and scores when it is opened
2026-11-10 22:45:54 +00:00
rdbt 3e8dbbc2df Merge pull request #14423 from YourPancakes/perf/skip-swim-below-block-reads
perf(mobs): skip redundant swim block reads
2026-11-10 22:45:49 +00:00
rdbt bbe1ec5372 Merge pull request #14415 from YourPancakes/perf/villager-item-sensing-index
perf(mobs): reuse item cells for villager sensing
2026-11-10 22:45:43 +00:00
rdbt 1f6cf55e1c Merge pull request #14413 from MSedgeMC/fix/shulker-neighbor-updates
port: a shulker box lid updates its neighbours as it moves
2026-11-10 22:45:38 +00:00
rdbt 221d303a90 Merge pull request #14409 from Joansitoh/fix-14407-version-picker-scroll
Launcher: the Home version picker scrolls its list
2026-11-10 22:45:32 +00:00
rdbt 83cb8979be Merge pull request #14399 from Cx188/fix/14338-command-hints-scroll
chat: fix touchpad scrolling in command suggestions
2026-11-10 22:45:26 +00:00
rdbt 1f10f8bbb0 Merge pull request #14398 from MSedgeMC/fix/social-scrollbar
The social player list shows its scrollbar
2026-11-10 22:45:22 +00:00
rdbt 67de3115e2 Merge pull request #14396 from MSedgeMC/fix/creative-tab-tooltip
The creative inventory's tabs say their name on hover
2026-11-10 22:45:17 +00:00
rdbt 53aab90fb5 Merge pull request #14393 from vivescene/perf/vehicle-mob-grid
Server tick: boats and minecarts read the mobs near them, not every mob
2026-11-10 22:45:12 +00:00
rdbt 0e120f96d5 Merge pull request #14392 from YourPancakes/perf/reuse-native-sprite-frames
perf(render): reuse native sprite frames when sizes match
2026-11-10 22:45:06 +00:00
rdbt 1f1fa1fc4d Merge pull request #14386 from vnsmoreira/fix/glide-fall-accumulation
A gliding mob caps its fall at 1 unless it dives
2026-11-10 22:44:59 +00:00
rdbt 8ffe3913ea Merge pull request #14379 from martipops/agent/pack-card-pad-target
Pack screen: a pack card's options button is a pad target
2026-11-10 22:44:54 +00:00
rdbt 87fe5531ed Merge pull request #14378 from ilguerro/fix/mount-feeding-eat
Feeding a horse or camel makes a vibration and a Silent one eats quietly
2026-11-10 22:44:50 +00:00
rdbt 255baf27e3 Merge pull request #14367 from DUzzL/fix/14297-hopper-decorated-pot
Let hoppers pull items out of a decorated pot
2026-11-10 22:44:44 +00:00
rdbt a713ed14e5 Merge pull request #14364 from DUzzL/fix/14298-tab-name-translation
Resolve a creative tab name given as a translation key
2026-11-10 22:44:37 +00:00
rdbt 4973e64a25 Merge pull request #14362 from voduff/map-stale-gaps-005
port map: player, villager, witch, wind and wither skull render rows (client-005, client-007)
2026-11-10 22:44:32 +00:00
rdbt 0a42c8f111 Merge pull request #14359 from ilguerro/fix/breed-partner-range
Move the breed goal tests out of goals.rs
2026-11-10 22:44:27 +00:00
rdbt 8c1118a3cf Merge pull request #14357 from voduff/map-stale-gaps-003
port map: boat wobble, skeleton shake, cat poses, block displays are drawn (client-003)
2026-11-10 22:44:22 +00:00
rdbt 6a88a1335d Merge pull request #14354 from voduff/map-stale-gaps-008
port map: block entity crack overlays are drawn (client-008)
2026-11-10 22:44:17 +00:00
rdbt e02af2c3bf Merge pull request #14347 from Cx188/fix/8406-stage-local-reachability
Drop unreachable graphics-stage GLSL helpers
2026-11-10 22:44:11 +00:00
rdbt a31f9f4763 Merge pull request #14344 from MSedgeMC/fix/test-block-analog-state-gate
A test block reads its block state mode for a comparator
2026-11-10 22:44:03 +00:00
rdbt 50486a59b0 Merge pull request #14337 from voduff/map-particle-anvil
port map: the particle limit and anvil rename box rows name their fns
2026-11-10 22:43:58 +00:00
rdbt e6ab43107a Merge pull request #14330 from yahya-nusseibeh/fix/report-claim-before-filing
Telemetry server: claim a bug report before filing its issue
2026-11-10 22:43:53 +00:00
rdbt 912e18ed0a Merge pull request #14329 from yahya-nusseibeh/fix/text-push-in-place
Text: append siblings in place instead of cloning the tree each time
2026-11-10 22:43:47 +00:00
rdbt eef3c52455 Merge pull request #14328 from yahya-nusseibeh/fix/translation-span-budget
Text: bound what one translation's fallback template expands to
2026-11-10 22:43:42 +00:00
rdbt 0e4511ae40 Merge pull request #14326 from ilguerro/fix/breeze-dust-support
Breeze dust crumbles the fence, wall or gate it stands on
2026-11-10 22:43:36 +00:00
rdbt dfa0603931 Merge pull request #14315 from vnsmoreira/packs/polytone-rnoise
Polytone: r.noise is 1.21's PerlinSimplexNoise, seed 0, octave 1
2026-11-10 22:43:31 +00:00
rdbt cf3d748474 Merge pull request #14312 from ilguerro/fix/enderman-persistent-anger
Keep an enderman's anger after it loses its target
2026-11-10 22:43:25 +00:00
rdbt 865f209838 Merge pull request #14308 from MSedgeMC/fix/named-fish-stays
A named fish or axolotl never despawns
2026-11-10 22:43:20 +00:00
rdbt aefc8c5254 Merge pull request #14307 from Akirabane/fix/jmath-log-windows
jmath: Math.log on Windows rounds like HotSpot's x86-64 stub, as sin and cos do
2026-11-10 22:43:15 +00:00
rdbt b1f72f3449 Merge pull request #14304 from NikitaMGrimm/record-start-copy
record-start no longer fails copying a world the server is saving
2026-11-10 22:43:10 +00:00
rdbt 450a11d633 Merge pull request #14289 from senjinthedragon/ctm-shared-layers
Connected textures: a texture a rule matches keeps a layer of its own
2026-11-10 22:43:05 +00:00
rdbt cb0513691e Merge pull request #14288 from vnsmoreira/fix/vehicle-fall-clip-wait
command_exec: two boat groups wait for their entity-ticking neighbourhood
2026-11-10 22:42:58 +00:00
rdbt b36353a08a Merge pull request #14255 from Cx188/fix/8578-controlled-chunk-acks
Add a controlled fixed-64 chunk ACK mode to horizon-bots
2026-11-10 22:42:53 +00:00
rdbt aeca67e1e7 Merge pull request #13818 from RINNECODER/up12/cem-legacy-textures
OptiFine CEM: a pre-1.21.5 pack's old mob textures paint its models and the climate variants
2026-11-10 22:42:48 +00:00
rdbt 95cfe9ab5c Merge pull request #13816 from RINNECODER/up12/cem-this
OptiFine CEM: `this` is a replacing entry's own bone
2026-11-10 22:42:43 +00:00
rdbt 7b3a3d06fa Merge pull request #13727 from MSedgeMC/fix/dialog-book-pause
A dialog's pause and a lectern's book decide whether the world stops
2026-11-10 22:42:37 +00:00
rdbt d5f9b60203 Merge pull request #12642 from itarqos5/perf/particle-threads
Particles: tick the independent ones on several threads (stacked on #12641)
2026-11-10 22:42:31 +00:00
rdbt fbd69c11f1 Merge pull request #12449 from RINNECODER/up3/pack-compact-terrain
Shader packs: keep solid terrain in the compact layout
2026-11-10 22:42:27 +00:00
rdbt 6ed7be61d9 Merge pull request #11230 from Ragbie/fix/vehicle-item-stack-config
A placed or dispensed minecart or boat takes its item's name, custom data and entity_data
2026-11-10 22:42:01 +00:00
rdbt aff92ca2df Merge pull request #14504 from horizon-rust/ci/runner-watch
runner watch: one issue when jobs wait for self-hosted runners that are offline
2026-11-10 22:36:30 +00:00
rdbt 54ee56ea1c Merge pull request #14303 from NikitaMGrimm/agent-e2e-windows
agent_control_e2e passes on Windows again: screen commands wait for the first frame
2026-11-10 22:36:24 +00:00
rdbt 9221eaf7b5 Merge pull request #14323 from NikitaMGrimm/fix/layer-checks-merge-base
Local layer and address checks no longer fail a branch for entries main dropped after it
2026-11-10 22:36:21 +00:00
rdbt 7b42678bcd Merge pull request #14342 from NikitaMGrimm/prepared-data-stale-tests
Five prepared-data tests run again: datapack fixtures, the gateway test, HORIZON_TEST_RESOURCES
2026-11-10 22:36:17 +00:00
rdbt e7af6c5683 Merge pull request #14372 from Joansitoh/fix/14369-rotate-source
Fix /rotate relative angles to use the command source's rotation
2026-11-10 22:36:13 +00:00
rdbt 26f0f7b710 Merge pull request #14507 from horizon-rust/docs/operations-runbook
docs/operations.md: running Horizon by hand without agents or the maintainer's machines
2026-11-10 22:36:09 +00:00
rdbt 37518b7953 Merge pull request #14429 from rdbtCVS/perf/forced-cover-distance
Streaming: forced chunks by distance, one lookup per column instead of a scan
2026-11-10 22:34:12 +00:00
rdbt c5ebfaad17 Merge pull request #14316 from voduff/team-feedback-names
Scoreboard: /team and /scoreboard name holders and teams with vanilla's hover and insertion
2026-11-10 22:34:09 +00:00
rdbt 1ce50ca842 Merge pull request #13760 from TheMrZZ/fix/allay-jukebox-source-2
An allay dances to the jukebox it heard first
2026-11-10 22:33:43 +00:00
rdbt 03fe63b323 Merge pull request #14336 from voduff/map-moved-fns
port map: rows follow fns split into their own files
2026-11-10 22:33:40 +00:00
rdbt 0e9d4928a1 Merge pull request #14363 from voduff/map-stale-gaps-004
port map: golem, mooshroom, ocelot, phantom, snow golem render rows (client-004)
2026-11-10 22:33:37 +00:00
rdbt 10dd71a575 Merge pull request #14428 from DUzzL/fix/14235-plate-minecart
Fix a fenced minecart not re-triggering the pressure plate above it
2026-11-10 22:33:33 +00:00
rdbt f722c4455a Merge pull request #14453 from AfrobamaYT/parity-shim-loop
Parity: the java shim never starts itself, and stops with a reason if a wrapper loops it back
2026-11-10 22:33:29 +00:00
rdbt ff4dd57b32 Merge pull request #14456 from rdbtCVS/fix/armadillo-baby-follow-box
Armadillo: a baby follows only adults its sensor's box meets
2026-11-10 22:33:25 +00:00
rdbt 6e7600425c Merge pull request #14633 from NikitaMGrimm/parity/projectile-rotation-lerp
Thrown projectiles and llama spit turn a fifth of the way towards their motion each tick
2026-11-10 22:33:22 +00:00
41a579d428 test: cross parallel tick helper thresholds with real resources
Compare deferred and in-place metadata for 2,085 varied mobs, including pack-selected effect particles and switch-off vector reuse. Exercise live climbing, snapshot order and nearest-player invalidation for 293 mobs. Build 132 random-tick section masks ahead and retain exact event, state and random comparisons through edits and reloads.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: GPT 6.1 Sol <[email protected]>
2026-11-10 22:32:11 +00:00
rdbt 9ba4c83c35 Merge pull request #14385 from Akirabane/fix/9370c-skin-loader-bounds
Skin loader: bound its downloads, `states` and `resources`
2026-11-10 22:31:11 +00:00
rdbt 98d56df183 Merge pull request #14952 from masa-masa-0314/audit/realms-26.3-main
Realms: finish world extraction after cancellation
2026-11-10 22:31:07 +00:00
rdbt ec5b969a9c Merge pull request #14272 from NikitaMGrimm/parity-windows-builds
Local parity runs work on Windows: harnesses no longer fail with "Access is denied" rebuilding a running game
2026-11-10 22:31:04 +00:00
rdbt fddebc2c59 Merge pull request #14335 from Akirabane/fix/3823-fullbright-remote
Fullbright is held off on another's server; single player and a LAN host keep it
2026-11-10 22:30:37 +00:00
rdbt d4f99b0b3b Merge pull request #14343 from Akirabane/fix/12820-offline-own-cosmetics
Cosmetics: the own model on an offline-mode server is asked by the signed-in account
2026-11-10 22:30:33 +00:00
rdbt cc3b9703a4 Merge pull request #14346 from Akirabane/fix/9370a-pack-icon-budget
Pack screen: send each pack icon to the atlas once, not every frame
2026-11-10 22:30:30 +00:00
rdbt 85e2eddf52 Merge pull request #14353 from DUzzL/fix/14264-dragon-wing-armour
Charge the host's armour for a dragon wing hit
2026-11-10 22:30:26 +00:00
rdbt d907493401 Merge pull request #14355 from Evan-lhm/split/gfx-section-fade
gfx.rs: the chunk fade-in helpers move to gfx/section_fade.rs
2026-11-10 22:30:23 +00:00
rdbt 09ab1bf799 Merge pull request #14548 from DUzzL/fix/14443-minecart-soul-sand
Minecart: powered rail pushes a resting cart away from soul sand
2026-11-10 22:30:13 +00:00
rdbt c822ad5a5b Merge pull request #14603 from Mayonesu0/up-14475-firework-lifetime
A firework rocket draws its UUID, motion, lifetime and shot from one random
2026-11-10 22:30:08 +00:00
rdbt 550bfa1815 Merge pull request #14797 from foudretbr/fix/launcher-preview-lag-animating-items
fix(cosmetics): permit 60 fps drag pictures while animating items in viewer (#14656)
2026-11-10 22:30:04 +00:00
rdbt 9b6036466e Merge pull request #14854 from lucasmts59/fix/dialog-text-glyph-bounds
A dialog's body text is clicked where its glyphs are drawn
2026-11-10 22:30:00 +00:00
rdbt 9c1241b581 Merge pull request #15003 from MSedgeMC/fix/strider-lava-fall
A strider that lands in lava takes no fall damage
2026-11-10 22:29:57 +00:00
rdbt 9fb79e9ae5 Merge pull request #15005 from MSedgeMC/fix/sulfur-cube-silent-step
A sulfur cube carrying a block walks silently
2026-11-10 22:29:53 +00:00
rdbt ee286fe931 Merge pull request #14842 from foudretbr/perf/shader-water-patch-uniform-reads
perf(shaders): unroll boat water patch checks to avoid local array spilling (#14782)
2026-11-10 22:28:00 +00:00
rdbt 926790a953 Merge pull request #14810 from tarzinio/fix-particle-culling-answers
Keep answers of earlier particle culling jobs
2026-11-10 22:27:57 +00:00
rdbt 5991716f9b Merge pull request #14796 from DUzzL/fix/14753-cube-wasonground
Run AbstractCubeMob.tick for NoAI cubes so wasOnGround updates
2026-11-10 22:27:54 +00:00
rdbt 41bf552edc Merge pull request #14778 from DUzzL/fix/14752-minecart-pitch
Reset a minecart's pitch to 0 every tick like vanilla's old behaviour
2026-11-10 22:27:50 +00:00
rdbt 705826487f Merge pull request #14788 from NongTham/fix/14748-carved-pumpkin-swing
use_item: do not swing non-swappable equippables on empty target (fixes #14748)
2026-11-10 22:27:47 +00:00
rdbt 87327e8228 Merge pull request #14790 from zenith600/fix/hidden-processes-platform-path
Launcher: hidden_processes test names horizon-prepare through horizon-platform
2026-11-10 22:27:44 +00:00
rdbt 743c4af6a8 Merge pull request #14878 from NikitaMGrimm/hdr-calibrate-wording
HDR settings: the Calibrate row no longer says Windows' peak is too high
2026-11-10 22:27:40 +00:00
rdbt 8f761ea16e Merge pull request #14881 from Art34222/fix/full-detail-distance-chunks
Keep vanilla's chunk count on Full Detail Distance
2026-11-10 22:27:37 +00:00
rdbt 50be3bbb80 Merge pull request #15002 from MSedgeMC/fix/shelf-block-activate
port: a container writing a shelf's slot posts block_activate
2026-11-10 22:27:33 +00:00
rdbt d4e561413b Merge pull request #14903 from MSedgeMC/fix/recipe-book-narrow-escape
Escape closes the recipe book, not the screen, when it covers one
2026-11-10 22:27:00 +00:00
rdbt ce94025311 Merge pull request #14906 from MSedgeMC/ledger/lectern-maybuild
port map: the lectern's Take Book row names the build gate it already has
2026-11-10 22:26:57 +00:00
rdbt 885a98f2df Merge pull request #14915 from Detimes/perf-mob-near
Perf: raider companions, shout range and the cat bed check use the mob grid
2026-11-10 22:26:52 +00:00
rdbt a72bf4935b Merge pull request #14913 from Detimes/perf-piston-index
Perf: index moving-piston tickers by position
2026-11-10 22:26:49 +00:00
rdbt 4af062b305 Merge pull request #14912 from Detimes/perf-adv-tick
Perf: no advancement tick view without a listening criterion
2026-11-10 22:26:45 +00:00
rdbt a4b68b5d40 Merge pull request #14953 from Web-mc1/fix/far-tiles-div-zero
Fix div_ceil(0) when HORIZON_FAR_TILES=0
2026-11-10 22:26:42 +00:00
rdbt 14c1840967 Merge pull request #14960 from MSedgeMC/fix/pet-dead-attacker
A pet does not avenge a dead attacker
2026-11-10 22:26:39 +00:00
rdbt 7866f95d80 Merge pull request #14963 from MSedgeMC/fix/fox-sleep-inputs
A fox with movement input does not sleep
2026-11-10 22:26:35 +00:00
rdbt ab98b12b18 Merge pull request #14965 from DUzzL/fix/14833-phantom-pitch
Phantoms keep the pitch their move control sets
2026-11-10 22:26:32 +00:00
rdbt d7b00ddb4b Merge pull request #14966 from RLC248/fix/sulfur-cube-growth-age-crossing
A sulfur cube grows to size 2 only when it grows up
2026-11-10 22:26:28 +00:00
rdbt 9fcedb7da9 Merge pull request #14968 from DUzzL/fix/14908-furnace-neg-cooktime
fix(furnace): saturate idle cooking timer at a negative total instead of panicking
2026-11-10 22:26:25 +00:00
rdbt 2a17e04399 Merge pull request #14985 from MSedgeMC/fix/book-link-cursor
A link in a book asks for the pointing hand
2026-11-10 22:26:22 +00:00
rdbt bbe2b1be3c Merge pull request #14992 from senjinthedragon/vec4-uniforms
Shader packs: horizonDynamicLight* and horizonWaterPatch* are vec4s to the type check, not floats
2026-11-10 22:26:18 +00:00
rdbt 1b30bc56af Merge pull request #14983 from MSedgeMC/fix/suggestion-hand-cursor
The command suggestions ask for the pointing hand
2026-11-10 22:25:36 +00:00
rdbt ee2e56ced0 Merge pull request #14990 from DUzzL/fix/14909-shulker-neg-peek
fix(shulker): a negative Peek no longer panics the lid easing
2026-11-10 22:25:33 +00:00
rdbt 32a7bbc853 Merge pull request #14996 from KBroneZ/claude/fork-14503
Leak each distinct block registry once in Assets::load
2026-11-10 22:25:31 +00:00
rdbt a02e0034cf Merge pull request #15008 from MSedgeMC/fix/spider-vehicle-attachment-note
port_map: the spider's vehicle attachment names its rule
2026-11-10 22:25:19 +00:00
rdbtCVS 0b21fcbf60 Random: preserve the ordered lane and stream when reseeding
Treat LegacyRandom::set_seed as an ordered mutation: acquire the shared stream before replacing its LCG state and clearing the Gaussian cache, without discarding the gate. This also publishes a reseed-only item's state through end_item and keeps finish_lane and LaneDone working.

Add timeout-bounded multi-lane regressions for reseeding before/after draws, reseed-only items, cross-lane Gaussian state and panic cleanup, plus serial cache-reset coverage. The regression rejects the original gate loss, omitted synchronization and retained Gaussian cache.

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

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

The list now reads all or nothing, and the test asserts the empty answer for a
mixed list, a missing field, and that a list of valid layers still reads back
(and round-trips), so an always-empty result cannot pass it.
2026-11-10 21:58:02 +00:00
DUzzL a8a5843f59 Mobs: tick freezing after the move and block effects, like LivingEntity.aiStep 2026-11-10 22:40:06 +01:00
MSedgeMC 4a93a8edcc port_map: the spider's vehicle attachment names its rule
The row pointed at passenger_attachment, which is the seat for riders on the
spider, and claimed the spider always uses its fixed seat. The rule is
vehicle_attachment: 0.3125 of the scale only when the vehicle's box is no wider
than the spider's, and a wider vehicle falls to the type's vehicle attachment,
EntityAttachment.VEHICLE's AT_FEET fallback, which is the feet.
2026-11-10 21:38:43 +00:00
MSedgeMC f09665e100 port_map: the loaded cube's silent step names its arm
SulfurCube.playStepSound had no row; it is the sulfur cube arm of step_sound.
2026-11-10 21:32:44 +00:00
MSedgeMC 41036d79a3 Test the loaded cube that steps silently
ai::step_sound over a stone block: a sulfur cube with a stone body answers
None, and an empty one answers block.stone.step at volume 0.15 and pitch 1.0.
Without the arm the loaded cube reads Some(("block.stone.step", 0.15, 1.0)).
2026-11-10 21:29:37 +00:00
MSedgeMC dba73d15d4 A sulfur cube carrying a block walks silently
SulfurCube.playStepSound returns before its super while the cube has a block
in its body, so a loaded cube makes no footstep at all; an empty one takes the
block's own step at 15%. step_sound had no sulfur cube arm, so a loaded cube
walked with block.stone.step like an empty one.

The arm sits in step_sound, which moves out of ai.rs into mobs/ai/step.rs with
the block sound ids it interns: ai.rs loses 100 lines of code to the move.
2026-11-10 21:29:37 +00:00
MSedgeMC ea6b0327df port_map: the strider's lava landing names its arm
Strider.checkFallDamage had no row; it is the lava guard in check_fall_damage.
2026-11-10 21:16:49 +00:00
MSedgeMC 4c3c5d6dd1 Test the strider that falls into lava
Mob::check_fall_damage with six blocks of fall and the mob standing inside a
lava pool: the strider takes 0.0 and keeps a fall distance of 0.0 with no
LandingDust, a pig in the same lava takes 3.0, and a strider landing on stone
takes 3.0 too. Without the arm the strider in lava reads 3.0.
2026-11-10 21:16:44 +00:00
MSedgeMC 53d72939bc A strider that lands in lava takes no fall damage
Strider.checkFallDamage resets the fall distance and returns while the strider
is in lava, so the base's landing never runs: no fall damage and no dust, and
a strider that drops into a lava sea walks out of it owing nothing. Horizon
ran the base for every species, so a strider that fell six blocks into lava
took the three a pig would.
2026-11-10 21:16:44 +00:00
MSedgeMC e2f5019d91 port_map: ShelfBlockEntity.setChanged posts block_activate
A container's slot write on a shelf posts the no-argument setChanged's
block activation.
2026-11-10 20:58:22 +00:00
MSedgeMC dc468324cf test: a container write on a shelf posts block_activate
`a_container_writing_a_shelf_posts_block_activate` puts a shelf and its
block entity and runs the container-change path on its view: the posted
events hold `("minecraft:block_activate", [2.5, 4.5, 3.5], None)`.
Without the post the same test fails with `Some([])`.
2026-11-10 20:58:22 +00:00
MSedgeMC bffad5a2aa fix: a container writing a shelf's slot posts block_activate
`ShelfBlockEntity.setChanged()` is overridden without arguments and
passes `GameEvent.BLOCK_ACTIVATE` to `setChanged(Holder)`, so any
container write to a shelf (a hopper's or dropper's `setItem`) posts a
block activation at the shelf and syncs it to clients.

Horizon's `Game::view_changed` marked the shelf's chunk and re-read the
comparator, but posted no game event.
2026-11-10 20:58:07 +00:00
CocofireHDandDeepSeek V4.1 Flash 63a2feba79 A zombie villager's profession is the constructor's draw from its own random (#14857)
`ZombieVillager.defineSynchedData` seeds `DATA_VILLAGER_DATA` from
`initializeZombieVillagerData(this.random)`: one `nextInt(15)` on the entity's
own random, made inside `Entity`'s constructor. Horizon built a synthetic
`LegacyRandom` out of the mob's random state and id instead, so the profession
never matched vanilla's and the mob's own random never advanced.

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

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

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

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

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

Co-Authored-By: opencode (DeepSeek V4.1 Flash) <[email protected]>
2026-11-10 21:38:36 +01:00
SenjinandClaude Opus 5.5 db8460de3a Shader packs: horizonDynamicLight* and horizonWaterPatch* are vec4s to the type check: a pack declaring them read 0
The type check (beb30045fd) keeps a built-in only as the type it gives, sized by components(), which
took Horizon's own vec4s for floats: a pack declaring horizonDynamicLight<n> (#12069) or
horizonWaterPatch<n> as vec4 had them switched off and read 0. Their counts stay ints.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 21:14:59 +01:00
DUzzL b228e6bef7 A shulker keeps its armor attribute once its lid has moved 2026-11-10 20:51:41 +01:00
MSedgeMC a1b69de138 port_map: BookViewScreen's link cursor 2026-11-10 19:25:47 +00:00
MSedgeMC 857436a4f7 test: only a clickable book word asks for the hand
An open_url click does; a show_text hover alone leaves the arrow, though it
still shows its tooltip.
2026-11-10 19:25:47 +00:00
MSedgeMC dd415f3cf3 fix: a link in a book asks for the pointing hand
BookViewScreen.extractRenderState visits its pages with
HoveredTextEffects.TOOLTIP_AND_CURSOR, which shows the hover tooltip and
requests the pointing hand over a clickable word. Horizon showed the tooltip
but never asked for the cursor, so links looked like plain text.
2026-11-10 19:25:23 +00:00
MSedgeMC 2f0107b159 port_map: SuggestionsList's pointing hand 2026-11-10 19:24:49 +00:00
MSedgeMC 93831bb101 test: the suggestion list asks for the pointing hand
Inside its rectangle the draw requests Cursor::PointingHand; one pixel left of
it the cursor stays the arrow.
2026-11-10 19:24:49 +00:00
MSedgeMC 404c0d8314 fix: the command suggestions ask for the pointing hand
CommandSuggestions.SuggestionsList.extractRenderState ends with
rect.contains(mouseX, mouseY) -> requestCursor(CursorTypes.POINTING_HAND).
Horizon's draw_list highlighted the hovered row but requested no cursor, so
the pointer stayed an arrow over the suggestion list.
2026-11-10 19:24:27 +00:00
Verm 6a246dd81d A villager narrows a loaded FoodLevel to a byte (#14967)
Villager.readAdditionalSaveData reads it with getByteOr, which narrows
any numeric tag (IntTag.byteValue is (byte)(value & 255)): FoodLevel:300
loads as 44. The loader kept the raw number.
2026-11-10 19:20:30 +00:00
DUzzL 159615221a fix(furnace): saturate idle cooking timer at a negative total instead of panicking 2026-11-10 20:15:26 +01:00
RLC248 4f5fa9c7ed A sulfur cube grows to size 2 only when it grows up (#14916)
The cube's AI step grew every adult of size 1 to size 2 on its second
tick, and shrank every baby above size 1 back to size 1. Vanilla's
SulfurCube.ageBoundaryReached runs only where AgeableMob.setAge crosses
the baby boundary, which finalize::set_age already does. The tick check
is gone: a summoned or loaded adult of size 1 and a split baby of size 2
keep their size.

command_exec gets a "sulfur cube size ticks" group with the cubes' AI on.
2026-11-10 20:14:20 +01:00
DUzzL 50f9032a65 fix(shulker): ease the lid with Mth.clamp semantics so a negative Peek cannot panic 2026-11-10 20:10:44 +01:00
Web-mc1 511921359c Fix div_ceil(0) when HORIZON_FAR_TILES=0 2026-11-11 07:49:33 +13:00
Web-mc1 4c49ec3523 Fix biome table panic when empty 2026-11-11 07:47:48 +13:00
masa-masa-0314andZCode 1158ed5a3a Realms: finish world extraction after cancellation
Match vanilla's cancellation boundary once a world archive starts extracting, and cover cancellation on both sides of that boundary.

Co-Authored-By: ZCode <[email protected]>
2026-11-11 02:44:22 +08:00
MSedgeMC 3eaaf3070c port_map: map FoxSleepGoal.canUse movement inputs 2026-11-10 18:42:21 +00:00
MSedgeMC 74abfb6fa7 test: a fox with movement input does not sleep 2026-11-10 18:42:21 +00:00
MSedgeMC 0990beeb2b fix: a fox needs no movement input to sleep 2026-11-10 18:42:06 +00:00
MSedgeMC 4a73bc0b34 port_map: map OwnerHurtByTargetGoal.canUse target validity 2026-11-10 18:41:04 +00:00
MSedgeMC e631c28418 test: a pet does not avenge a dead attacker 2026-11-10 18:41:04 +00:00
MSedgeMC 4871665711 fix: a pet does not avenge a dead attacker 2026-11-10 18:40:49 +00:00
Oloion 2e6f3cd716 client: show custom server crafting recipes in recipe book (fixes #14608) 2026-11-10 21:32:19 +03:00
DetimesandClaude Opus 5.5 594e8622a7 Merge upstream/main into perf-mob-near
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:29:34 +00:00
DetimesandClaude Opus 5.5 ea212b9152 Merge upstream/main into perf-piston-index
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:25:11 +00:00
DetimesandClaude Opus 5.5 289e90d636 Merge upstream/main into perf-replay-excuse
Brings the branch up to date and lays out the new code and tests as
rustfmt wants them, which the verify job checks.

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

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

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

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

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

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

Refs #14920

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

Refs #14920

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 17:40:37 +00:00
DUzzL a0677225dd Phantom: empty look control keeps the pitch its move control sets 2026-11-10 18:31:53 +01:00
MSedgeMC 7950bfbc6f port map: the lectern's Take Book row names the build gate it already has 2026-11-10 17:29:49 +00:00
MSedgeMC b5a64cf86b port_map: JukeboxBlockEntity.notifyItemChangedInJukebox is a port
A disc coming or going sets `has_record` and posts `block_change` at the
box; the row kept the old gap.
2026-11-10 17:24:58 +00:00
DetimesandClaude Opus 5.5 c9cd62bd5b Keep game.rs from growing: the tick-view gate lives with the criteria helpers
game.rs is over the 3000-line limit, so the gate and its test move into
native_criteria.rs, which already builds the player's advancement views,
instead of a new module declared in game.rs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 17:21:28 +00:00
MSedgeMC 0966aa0d3f test: a disc change posts block_change
`a_disc_change_posts_block_change` places a jukebox, records the posted
game events and calls `set_has_record`: the box posts
`minecraft:block_change` at its centre with no source. Without the post
the recorded list is empty.
2026-11-10 17:15:39 +00:00
Nikita Maximilian GrimmandClaude Fable 5.2 9188926fff Shader API 0.2: [frame] primaries, and the rule for new names
A 0.2 pack can't show a colour outside sRGB today: the contract says every
colour is in BT.709 primaries, forever. This adds the key that will let a
pack ask for more, before 0.2 is on by default and packs are written against
that contract.

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Codex gpt-6.1-sol <[email protected]>
2026-11-10 18:02:03 +01:00
Florian ErnstandClaude Opus 5.5 1aec392a34 Move the allay jukebox harness to its own pull request
The fix and its Rust tests stay here (about 350 lines). The harness,
its transcript and the VanillaProtocolClient mode follow in a stacked
pull request, as asked in review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:01:44 +01:00
arrteandClaude Opus 5.5 dd81778073 Keep vanilla's chunk count on Full Detail Distance
With LOD Distance on, the Render Distance row is relabelled "Full Detail
Distance", and its value came from Horizon's own "%s chunks" key instead
of vanilla's options.chunks, so "12 Chunks" turned into "12 chunks".
Format the value with options.chunks, as the vanilla row does.

Fixes #14880

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 19:57:51 +03:00
Nikita Maximilian GrimmandClaude Fable 5.2 1c93067327 HDR settings: the Calibrate row no longer says Windows' peak is too high
On Windows the HDR page's Calibrate row said "Your display's reported peak is
often too high: calibrate to set it up." That is wrong for a player who ran
Windows HDR Calibration: its profile overrides the display's own figure in the
`MaxLuminance` DXGI reports, so their good value was called too high. Horizon
can't tell which source the number has, and nothing says reported peaks are
too high in general.

The row now reads "Auto uses the peak Windows reports. Calibrate if highlights
look clipped.", true for either source. A new test keeps the row's four
descriptions within the description strip's two lines at vanilla's 427-wide
GUI, where a longer sentence would be cut off.

Nothing else changes: the setup states, the button labels and calibration are
as before. The comments and docs/graphics.md say what is known of the figure.
The old sentence was in en_us.json only.

Part of #12989.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 17:52:40 +01:00
MSedgeMC b47d5104da port_map: RecipeBookComponent's narrow Escape 2026-11-10 16:43:14 +00:00
MSedgeMC 6395c90680 test: Escape closes only a narrow book, not its menu
Under NARROW with the book open it takes the key; at NARROW, or with the book
closed, Escape belongs to the container.
2026-11-10 16:43:10 +00:00
MSedgeMC 43f69a7018 fix: Escape closes the recipe book, not the screen, when it covers one
RecipeBookComponent.keyPressed closes the book when Escape is pressed and
!isOffsetNextToMainGUI (a window narrower than NARROW, where the open book
covers the menu). Horizon's Escape arm went straight to close_container, so
pressing Escape threw away the inventory or crafting table instead of the
book.
2026-11-10 16:43:10 +00:00
DetimesandClaude Haiku 5.5 197aeeeea6 Test grid-backed raider and cat scans against the full scan
Companions, shout range and the cat bed check must give the same ids in
the same order with and without the mob grid. Two lattices of 300 and
200 mobs cover raiders within and beyond 8 and 16 blocks, and lying and
standing cats around four beds.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 16:42:15 +00:00
DetimesandClaude Haiku 5.5 6b7e237730 Scan only the mob grid for raider companions, shout range and cat bed check
companions and shout_range walked every mob to find raiders in a box
around the patrolling raider; the cat's occupied check walked every mob
for cats lying beside a bed. Use others_near with the box each already
computes, one block wider so every accepted mob's bounds meet it. The
filters are unchanged, so results and their order stay the same.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-10 16:41:43 +00:00
DetimesandClaude b6fc1844be Test: the advancement tick view is gated by the trigger's listeners
Covers view_needed: before the advancements load the view is built as
before; after that it is built only for a trigger with a listener in
tree.by_trigger, the same lookup trigger() makes. Needs no resources.

Co-Authored-By: Claude <[email protected]>
2026-11-10 16:41:32 +00:00
DetimesandClaude 9fcdc6481d Perf: skip the advancement tick view when no criterion listens
tick_advancements built the player's EntityView every tick (and every
20 ticks for minecraft:location) even when no loaded criterion listens
to that trigger, and then dropped it. The view is now built only when
the trigger's own lookup (tree.by_trigger) finds listeners, or before
the advancements are loaded, when the tree is not read yet, so the
view is built exactly as before. load_advancements and the early outs
of trigger keep their order.

Co-Authored-By: Claude <[email protected]>
2026-11-10 16:41:28 +00:00
DetimesandClaude 5df2749ffe Test: moving-piston index matches the linear scan
Adds a unit test in level/ticks.rs that loads, replaces and removes
moving pistons, then edits the Vec from outside the index (a direct
push and a reversed Vec), and checks that every lookup equals the old
linear scan, that tickers stay in ascending id order, and that
`moving_piston_has` accepts only the current id.

Co-Authored-By: Claude <[email protected]>
2026-11-10 16:41:16 +00:00
DetimesandClaude 8e942033a2 Perf: index moving-piston tickers by position (no O(N^2) scans per tick)
Ticking moving pistons ran an `any` scan over every moving piston for
each ticker, and the lookups, progress updates and set/remove went
through linear `find`/`retain`/`position`, so a tick with N moving
pistons cost about N^2 comparisons.

`Ticks` now keeps a position-to-id hint next to `moving_pistons`. The
hint is only trusted when the slot it leads to really holds the position
(the Vec is sorted by ascending id, so the slot is a binary search), and
it falls back to the old scan otherwise, so a Vec edited from outside
still gives the same answer. The Vec, its order, and every observable
result are unchanged.

Co-Authored-By: Claude <[email protected]>
2026-11-10 16:41:14 +00:00
lucasmts59andClaude Opus 5.5 da83875ae3 Hit dialog body text where its glyphs are drawn
ActiveTextCollector.ClickableStyleFinder tests each glyph's own area
(BakedSheetGlyph.GlyphInstance: its top and bottom, the shadow, bold
thickness and italic shear), so a glyph a font's ascent moves off its
line is clicked where it is drawn; only empty glyphs cover the line's 9
pixels. The last area with a click event wins, not the first character
under the cursor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 17:10:22 +01:00
levzzz 1405044d09 Merge pull request #14569 from Ragbie/fix/discord-socket-test-cfg
horizon-discord: #[cfg(unix)] back on the socket test, so the tests build on Windows
2026-11-10 21:01:13 +05:00
KBroneZandClaude Opus 5.5 be247b49e0 fix: leak each distinct block registry once in Assets::load
Assets::load leaked a new BlockRegistry (about 11 MB for vanilla) on every
call. The game calls it once, but tests call it once per fixture, and none
of it is freed. Keep the &'static contract and intern by content: equal
registries (same states in order, same defaults) share one leaked copy.

Closes #14503

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 18:00:24 +02:00
foudretbr 55509cffaf perf(shaders): unroll boat water patch checks to avoid local array spilling (#14782) 2026-11-10 16:32:04 +01:00
readerkid 327b811914 Map CEM's armour models to the layers 26.3 draws, and the rabbit's feet
CEM names a humanoid's armour with two models, `<mob>_outer_armor` and
`<mob>_inner_armor`, but 26.3 draws it on four layers of the model: the helmet,
the chestplate, the boots and the thinner leggings. A CEM name gave one layer
key, so no armour file reached any of them, and the 24 armour layers of the
zombie family's baby models were unreachable.

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

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

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

Fixes #8426

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <[email protected]>
2026-11-10 07:16:11 -08:00
tarzinio 58d23e2654 Keep answers of earlier particle culling jobs 2026-11-10 14:25:11 +01:00
foudretbr fc51d09b64 fix(cosmetics): permit 60 fps drag pictures while animating items in viewer (#14656) 2026-11-10 13:11:08 +01:00
NongTham e1848e08a4 input: clear modifiers on focus loss and heal alt and super keys (fixes #14715) 2026-11-10 19:10:27 +07:00
DUzzL b782c0d9b5 Run AbstractCubeMob.tick for NoAI slimes, magma cubes and sulfur cubes 2026-11-10 12:56:20 +01:00
foudretbr 3661bfd7c2 fix(game): evaluate attack_speed attribute modifiers for player attack cooldown (#14721) 2026-11-10 12:55:27 +01:00
NongTham 4264ba0c4e use_item: do not swing non-swappable equippables on empty target (fixes #14748) 2026-11-10 18:50:05 +07:00
MSedgeMC a08205b8ec port_map: MerchantScreen.extractScroller is ported 2026-11-10 11:44:30 +00:00
MSedgeMC 41fdaa3f0c test: the merchant scroller's thumb asks for its cursor
Eight offers put the thumb at the track's top; a hand over it, the vertical
resize while dragged, nothing left of the thumb or past its bottom edge, and
the disabled scroller of seven offers asks for nothing.
2026-11-10 11:44:30 +00:00
MSedgeMC 2398317072 fix: the merchant's trade scroller shows its cursor
MerchantScreen.extractScroller requests CursorTypes.POINTING_HAND over the
scroller's thumb, or RESIZE_NS while it is dragged. Horizon drew the thumb
but asked for no cursor, so the pointer stayed an arrow over it.
2026-11-10 11:44:30 +00:00
DUzzL 36fb430fbc Reset a minecart's pitch to 0 every tick like OldMinecartBehavior 2026-11-10 12:30:47 +01:00
MSedgeMC 669e1a162a Move takes_food into mobs/ai/feeding.rs so ai.rs may not grow 2026-11-10 11:29:46 +00:00
zenith600andClaude Opus 5.5 0ea7d1707c Launcher: hidden_processes test names horizon-prepare through horizon-platform
The Windows-only test still built `horizon_prepare::java::Jdk`, but since
92886cd964 the launcher reaches that crate only through horizon-platform's
`prepare` feature, so `cargo clippy --all-targets` in launcher/ failed on
Windows (Linux CI never compiles this file). Use
`horizon_platform::prepare::java::Jdk`, as backend.rs does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 16:55:46 +05:30
NongTham d645b72e8b test: allow-flight in bed_explosion parity harness (fixes #14664) 2026-11-10 18:05:15 +07:00
Loki 3bc4e3035c Merge remote-tracking branch 'origin/main' into fix/12935-sculk-particle-resume-reload 2026-11-10 19:47:20 +09:00
foudretbr 15183261d9 fix(input): reset debug keys modifier state on window focus loss (#14715) 2026-11-10 11:25:52 +01:00
Ludovic Marie 8933e8c2d8 Merge pull request #14741 from horizon-rust/governance/elections-tiers
🤖 Agent: founder-imposed governance amendment of 2026-11-10 (Ludovic's go, ~09:55Z): three kinds of action, elections by tier, the permissions table checked against the live Discord, panel, ops list and GitHub, and P41 with a 24 h veto; docs only, verify green on this head. The council can overturn it by poll.
2026-11-10 11:25:36 +01:00
MSedgeMC adbc523e5c port_map: the canAgeUp feeding branch
AgeableMob.canAgeUp to ai.rs::can_age_up, and Animal.mobInteract's food
branches to ai.rs::takes_food: an adult at age 0 that canFallInLove, else
canAgeUp.
2026-11-10 10:20:16 +00:00
MSedgeMC 7f5b3462df test: feeding a frog at a baby's age leaves the food in the hand
A frog and a cow, both at Age -24000, through takes_food and feed_animal: the
frog refuses the food and keeps the age, the cow takes it and grows a tenth.

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

takes_food now asks can_age_up(m), the port of canAgeUp, the same predicate
the rest of the feeding code already used.
2026-11-10 10:20:06 +00:00
Horizon agentandClaude Opus 5.5 226a707d0d GOVERNANCE.md: three kinds of action, elections by tier, who may do what, P41
Founder-imposed amendment of 2026-11-10. Free actions need no vote; a role
with power or a body's own decision is a 24-hour body vote with a 24-hour
council veto; everything else stays a council poll (48 h only for this
document, the licence, money and org ownership). Adds the election table,
its hard cases and Kira's reminders (5.3), the permissions table checked
against the live Discord, panel, ops list and GitHub teams (2.2), and P41:
the mods decide moderation matters, council veto 24 h (section 7).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 11:06:36 +01:00
1d9040c05a Silence a chest's comparator while a cat sits on it
ChestBlock.isChestBlockedAt is a redstone conductor above the chest or a
cat sitting in the block above it (ChestBlock.java:318-319, the cat test
at :327-338). getAnalogOutputSignal (:346-348) reads getContainer(..,
false), whose combine(.., false) (:279) uses that predicate, so a blocked
chest combines to nothing and the comparator reads 0.

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 11:14:38 +03:00
LokiandAntigravity 27cded80d5 mobs: apply squid sinking velocity on land under NoAI (fixes #14467)
Co-Authored-By: Antigravity <[email protected]>
2026-11-10 15:36:11 +09:00
masa-masa-0314andZCode 64e74bffd2 docs: propose friends overlay Part 2 spec
Co-Authored-By: ZCode <[email protected]>
2026-11-10 14:19:11 +08:00
Nikita Maximilian GrimmandClaude Fable 5.2 db26868e4f HDR10 output: the last pass dithers its 10 bits
The float frame is smooth, but the last pass rounded it to the HDR10
swapchain's 10 bits as it was. Around 90 nits one PQ code is a 1% step
in light, and a clear noon sky is two or three codes tall, so it showed
as wide flat bands with hard edges (#12989's audit, F3).

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

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

Refs #12989

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

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

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 06:36:40 +01:00
3f1f2fd3a8 Spawn phantoms under a glass roof
PhantomSpawner.tick asks Level.canSeeSky, which is "sky light 15 here"
(BlockAndLightGetter.canSeeSky), not a scan for a full collision cube:
glass and stained glass keep the sky light and spawn phantoms, while
stone, water and a slab roof do not. The advancement location predicate
read the same hand-rolled scan and now reads the sky light too.

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

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

Fixes #14537

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

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

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 04:13:00 +01:00
Evrim CicekandClaude Opus 5.5 03a6255967 pad::parity_tests: pad_press records the press as pad_button does (#14648)
Since the radial menu, Pad::holds_action reads the actions pad_button
records for a pressed button; the helper called pad_action directly, so
four tests read a held action as not held.

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

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

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-10 03:52:09 +01:00
DetimesandClaude Haiku 5.5 7059358371 Catalog test: accept living_death_message as a free function
living_death_message is a free function in horizon_client_lib::living_death,
so the test needs a set for that module like hunger, landing and chat.

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

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

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

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

Harness: tools/test_wind_bursts_all_push_parity.py.

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

Harness: tools/test_projectile_fluid_current_parity.py.

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

Harness: tools/test_piston_cactus_vehicles_parity.py.

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

Harness: tools/test_projectile_hits_tnt_parity.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 02:10:37 +01:00
Mayonesu0andClaude Sonnet 5.5 acd16c9ae8 A firework rocket draws its UUID, motion, lifetime and shot from one random
FireworkRocketItem.asProjectile builds the rocket from Entity.random, then
Projectile.spawnProjectileUsingShoot spreads the shot with that same random.
Horizon made a second random for the constructor's draws, so a dispensed or
crossbow rocket's LifeTime (and the shot's spread) were out of step.

new_rocket now takes the rocket's own random and draws the UUID, motion and
lifetime from it in vanilla's order; launch_angled_rocket makes it and hands it
to the shot. seed_sync gets a dispensed-rocket case (UUID, LifeTime, Motion).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-10 02:07:51 +01:00
Detimes 7a47e7a21f Merge remote-tracking branch 'upstream/main' into gap-line-of-sight 2026-11-10 01:06:25 +00:00
188817342b Firework rockets: honour Silent, post EXPLODE, count block launches
`FireworkRocketEntity.explode` posts `GameEvent.EXPLODE` from `getOwner()` at
the rocket before the damage, and the entity event passes `!isSilent()` to
`createFireworks`, which gates only the blast and the twinkle of
`FireworkParticles.Starter`, so a silent rocket keeps its sparks and flash.
A rocket launched from a block face also counts as a use, as
`ItemStack.useOn` does for `FireworkRocketItem.useOn`'s SUCCESS.

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

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

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

Part of #13007

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 03:50:36 +03:00
Nikita Maximilian GrimmandClaude Opus 5.5 861914b486 Merge origin/main into parity/bucket-mob-from-bucket
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 01:46:34 +01:00
foudretbr d1ca042ab8 fix(mobs): default cat variant to black when omitted (#14540) 2026-11-10 01:45:52 +01:00
Detimes 1e66c75589 Merge remote-tracking branch 'upstream/main' into gap-server-props-read 2026-11-10 00:40:40 +00:00
Detimes bd6bf2422b Merge remote-tracking branch 'upstream/main' into gap-mob-death-message 2026-11-10 00:25:43 +00:00
MSedgeMC 72879fc35b port map: point citations at the modules they moved to
The game, entity_nbt, stations, creatures, minecarts, particles and remote modules were split this week; twenty rows
still named the file a function left.
2026-11-10 00:17:52 +00:00
Evrim CicekandClaude Opus 5.5 5f0ea2347a horizon-discord: #[cfg(unix)] back on the socket test
Fixes #14568: 62e62c21e6 put the switch test between the socket test's
attribute and the test, so the socket test (std::os::unix) compiled on
Windows and the switch test ran only on unix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 03:13:09 +03:00
voidsip 38b2b41791 Name the arrow expiry harness for its actual coverage 2026-11-09 18:12:25 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 5c6f115aa6 Thrown projectiles and llama spit turn a fifth of the way towards their motion each tick
ThrowableProjectile.tick and LlamaSpit.tick call Projectile.updateRotation,
which lerps pitch and yaw 20% from the tick's old rotation towards the
motion's direction (the spit with its motion before drag and gravity).
Horizon set the target angles at once.

Fixes #14544

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 01:09:21 +01:00
Riccardo GuerrieroandClaude Opus 5.5 5f40c762f6 Move the bred offspring's draws and their test out of creatures.rs
creatures.rs is over the 3000-line limit (docs/layers.md#file-size): the
coat coin, the wolf pup's voice and the test of both move to
game/creatures/bred_draws.rs.

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:57:43 +01:00
voduff d68f241a0e Merge remote-tracking branch 'origin/main' into fix/12038-cube-body-item-replace 2026-11-09 23:52:09 +00:00
valuttaandClaude Opus 5.5 176f5b3475 AGENTS.md: review pull requests only when asked, post only findings
An agent asked for some reviews swept about 300 open pull requests, most
reviews saying it found nothing. Agents now review a pull request only
when its author or a maintainer asks for it, post only findings someone
can act on as a real review, and skip reviews that found nothing.
Maintainers' own agents may run wider passes when the maintainer asks.

Closes #14545.

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

Fixes #14538

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:42:55 +01:00
MSedgeMC 9e7fc5f18c Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-09 23:41:45 +00:00
72fe5b13ba Mobs: the mob loop's body moves into a group of mobs, still one thread
The per-mob turn of tick_creatures (its world view, brain, movement, events,
riders, deaths and pushes) moves into creatures/mob_group.rs as Group::tick, on
a Group that owns the mobs it ticks, their snapshot grid, pushes, events and the
level random. tick_creatures builds one group of every mob and runs it in list
order, so nothing changes: whether a mob is loaded and ticking, and the
per-chunk difficulty, are still decided at the mob's own turn. The parallel tick
(#14457) will run several groups. creatures.rs shrinks by 177 lines.

From kacpherek's #13644.

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

Harness: tools/test_geyser_scaffolding_parity.py.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 00:22:30 +01:00
aaf5aa6fcf Mobs: what the parallel mob tick's groups read, behind no switch
MobSlot lets the mob loop's helpers (apply_brain_events, riders, a school's
recruits) work on a group's borrowed mobs as on the list's own; MobWorld.foreign
answers a lookup by id of a mob in another group (ForeignSeen); PendingPushes::
append puts one group's pushes after another's, each mob's in order; and a
SeenGrid of part of a list can answer as the whole list's grid would
(answering_as). Nothing sets them yet: every caller passes the list's own mobs
and foreign: None. For #14457.

From kacpherek's #13644; the grid follows main's scan threshold.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 23:20:15 +00:00
eaa027179b Random: a lane that panics is marked finished, so the others don't wait on it
LaneDone, held by a lane's thread while it runs, marks the lane finished when
dropped, also while a panic unwinds: the other lanes run to their end instead of
waiting forever for its items, and the panic reaches the caller when it joins
them. Review finding 1 on #13644; the test times out without it.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 23:20:15 +00:00
bbaa73ec43 Random: one LegacyRandom stream drawn in list order from several threads
OrderedDraws shares a LegacyRandom among lanes that each run their part of a list
in list order: an item's first draw waits until every other lane has passed it,
so every draw comes out as one thread would make it. A copy of a gated random
draws on its own. For the parallel mob tick (#14457).

Taken from kacpherek's #13644.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 23:20:15 +00:00
d3c8eb00ea Parallel tick: the dropped items' own moves worked out ahead on helpers
While the parallel tick is on, each ticking item's move (ItemEntity.tick up to its
merge) is worked out on a copy on the helper threads before the item loop, and
put in place at its turn. The move reads only the item, the blocks, the obstacle
boxes and the border, none of which the loop changes; an item inside a block
escapes at its own random's speed, which the copy carries. A merge before its turn
that changed its count, age or pickup delay sends it back to the move at its turn,
as do native mods and a mod listening to the round. HORIZON_PARALLEL_TICK=verify
makes each move again at its turn on a copy and logs a difference.

The item's tick reads ItemTables (the blocks, collisions, motion tables, border)
so helpers run the same code the turn runs; ObstacleGrid moves to
entities/obstacles.rs and gains a query with the caller's scratch. A test ticks
307 items (escaping blocks, in water, falling, merging) both ways and checks the
items and the level's random come out the same.

From kacpherek's #13644, redone on main's item tick.

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

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

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

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

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 23:11:58 +00:00
Horizon agentandClaude Opus 5.5 5499eea24e docs/operations.md: running Horizon by hand without agents or the maintainer's machines
A runbook for the Horizon Team and the council: who can do what today, merging by hand, the Nightly
and how to stop or roll it back, what waits when the self-hosted runners are offline and what to do,
the Mojang republish issue, the mods registry (form pull requests, forks, takedowns), Kira, the
official server and security incidents. It points at release-flow.md, ci-runners.md, security.md
and GOVERNANCE.md for the details instead of repeating them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 00:06:25 +01:00
DetimesandClaude Haiku 5.5 9f861b1624 Use contains_key in entity lookup test (clippy unnecessary_get_then_check)
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 23:04:34 +00:00
DUzzL 6a4ea1890f Minecart: resting cart on a powered rail reads the block's redstone-conductor flag (soul sand) 2026-11-10 00:02:53 +01:00
Evrim Cicek bdf33dd2a3 Merge remote-tracking branch 'upstream/main' into tests/mob-landing-neighbourhood 2026-11-10 02:01:58 +03:00
MrCloudy2andClaude Fable 5.2 016630efda Keep creatures.rs from growing: the vehicle re-tick lives in wind.rs
The file-size rule (docs/layers.md#file-size). hurt_vehicle moves with it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-10 00:01:01 +01:00
Horizon agentandClaude Opus 5.5 9dc8b78a8f runner watch: one issue when jobs wait for self-hosted runners that are offline
Jobs that need the maintainer's machines (bots on horizon-light, parity, parity-main, the Mac's
Nightly and launcher builds) wait up to a day when those machines are off, then fail, and nothing
says why. Every 30 minutes, on GitHub's runners, tools/ci/runner_watch.py lists the jobs of queued and
running runs that wait for a self-hosted runner; when one has waited over 2 hours in a pool where no
job runs at all, it opens one issue naming the pools, what stops and what to do, keeps it current,
and closes it once nothing waits. Only the workflow token (actions: read, issues: write).

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

Harness: tools/test_geyser_launch_parity.py.

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

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

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

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

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

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

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

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

Fixes #13826

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:23:28 -03:00
SolenopsisbotandCodex 3a22ba32c2 Fix texture metadata parsing during pack startup
Co-Authored-By: Codex <[email protected]>
2026-11-10 09:17:35 +11:00
0xRinne 20d37726a2 Merge branch 'main' into up12/cem-legacy-textures 2026-11-09 16:16:51 -06:00
0xRinne a95c4653f4 Merge branch 'main' into up12/cem-this 2026-11-09 16:16:48 -06:00
5f61de11d9 Parallel tick: mob entity data and attributes from plain tables, on helpers
mob_meta reads SyncData instead of the hub (SyncData::effect_meta, with main's
shown_color; Hub::effect_meta calls it), and the attribute instances read
AttrSources (the catalog, the items, /attribute's maps) instead of Game. While
the parallel tick is on, the mobs' entity data and attributes are built after
the pass on the pool and put in place (game/lan/mob_states.rs); with it off
they are filled in place as before, with no new Vecs. What is read in order
(idle state, lead, equipment network ids) stays in the pass. A test checks the
states put in place equal those built in place.

From kacpherek's #13644.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 22:14:03 +00:00
1ef6e26dfa Parallel tick: mob prep and random tick masks on the helper threads
Before the mob loop, each mob's climbing check, snapshot entry and nearest
player read only that mob, the blocks and the players, so they are mapped on the
pool from 256 mobs (creatures/prep.rs, out of creatures.rs). A mob that moved
before its turn is asked its nearest player again where it stands. The masks the
random ticks read are built on the pool before the random ticks; the draws and
the ticks stay serial. The random tick test runs a fourth path with its masks
built ahead and checks it gives vanilla's scan's events and random values.

From kacpherek's #13644.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 22:14:03 +00:00
2c9aa0ac86 Parallel tick: one pool of helper threads, behind HORIZON_PARALLEL_TICK
horizon_client::parallel: one rayon pool made once (at most 8 threads, the server
thread takes parts too), par_map that gives every part's results in the items'
order, and the HORIZON_PARALLEL_TICK switch (off by default; 1 or verify turn it
on). With the switch off every phase runs its serial code on the server thread.
Goal is Send + Sync, so mobs can be read from helper threads.

From kacpherek's #13644.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 22:14:03 +00:00
2d79ae6ace Armadillo: a baby follows only adults its sensor's box meets
NearestLivingEntitySensor.doTick finds the living entities whose boxes meet the
baby's box inflated by its FOLLOW_RANGE (16). BabyFollowAdult took every adult
others_near returned, which only narrows to grid cells and, when the grid falls
back to a scan, returns every mob: the baby checked line of sight to, and could
follow, adults anywhere in the level. Found by kacpherek's verify mode in #13644.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 22:13:48 +00:00
MrCloudy2andClaude Fable 5.2 eedbb1717c A wind charge's hit damages a boat or a minecart
AbstractWindCharge.onHitEntity hurts what it hit by one point before the
burst; a vehicle takes it through VehicleEntity.hurtServer and breaks on the
fifth hit of a tick. wind_charge_damage only looked among the mobs.

Harness: tools/test_wind_charge_vehicle_parity.py.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 23:11:56 +01:00
AfrobamaYTandClaude Opus 5.5 dc2b1acd07 Parity: the java shim never starts itself, and stops with a reason if a wrapper loops it back
The oracle cache's shim started the real java with the PATH it got, its own folder first. A java
wrapper that looks java up on PATH (a JDK selector, a build wrapper) then found the shim again,
which found the wrapper again: every round left a python3 alive under Popen, past 5,000 on one
machine, until RAM and swap were full.

real() skips candidates that resolve to the shim; the real program gets PARITY_SHIM_REAL_PATH as
its PATH; and past 4 rounds inside itself (PARITY_SHIM_DEPTH) the shim exits with a reason.
Tests use a wrapper java that stops itself after a few rounds, so a looping shim fails them
rather than the machine: without the fix all three fail, with it they pass.

Fixes #14450

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

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

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

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-09 22:49:34 +01:00
Nikita Maximilian GrimmandClaude Fable 5.2 0f5b71e021 Merge remote-tracking branch 'origin/main' into prepared-data-stale-tests
piston_push.rs: main's version (#13655 made the same correction to the order test's expected push).

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:42:45 +00:00
JoansitohandClaude Sonnet 5.5 2a4d90b9cf Launcher: the Version menu's state lives beside the picker, not in main.rs
main.rs is over 3000 lines and may not grow (docs/layers.md#file-size): the menu's
open flag, scroll and the window height it was opened at become one PickerState in
glass_home.rs, replacing picker_open.

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

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

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

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

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

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

`Behaviours::shulker_neighbor_updates` ports the two calls, and
`tick_shulkers` runs it once per counted update. The box's collision
shape for the same ticks already reaches the world through
`shulker_collision_state`.
2026-11-09 21:04:49 +00:00
JoansitohandClaude Sonnet 5.5 80687d32d1 Launcher: the Home version picker scrolls its list
The Version menu capped its height to the room under the button and its
rows scroll (with the launcher's scrollbar and take_wheel); Manage
versions stays pinned below them.

Fixes #14407

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 21:59:51 +01:00
DUzzL 82d1afa019 Merge remote-tracking branch 'origin/fix/14297-hopper-decorated-pot' into fix/14297-hopper-decorated-pot 2026-11-09 21:59:29 +01:00
DUzzL c7c8dd8f82 Merge upstream/main into fix/14297-hopper-decorated-pot 2026-11-09 21:59:16 +01:00
rdbtCVSandClaude Sonnet 5.5 74a38d29aa Keep ai.rs the same size: inline the one-use creature local
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 20:53:49 +00:00
rdbtCVSandClaude Sonnet 5.5 e10e2144bd Merge main into fix/14297-hopper-decorated-pot
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 20:49:39 +00:00
DUzzL 920e317f53 Make jmath::pow return NaN like Java for NaN exponent and |x|==1 with infinite y 2026-11-09 21:47:25 +01:00
Vinícius MoreiraandClaude Opus 5.5 9286b28e24 Polytone: a particle with physics born inside a block goes at once
A custom particle with has_physics whose box starts inside a block's
collision is dropped before its first tick, so its emitters never run.
Falling leaves start 0.05 under their leaf block, and a pack's leaf with a
0.08 hitbox reaches into it: in Java such a leaf never falls, while here
every one fell, and a leaf that emits a resting copy of itself each tick
left trails of them under every tree until the frame rate collapsed.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:45:54 -03:00
CxandClaude b13153310c chat: fix touchpad scrolling in command suggestions
Round the suggestion list scroll offset instead of truncating f64->i32.
Fractional touchpad/PixelDelta wheel deltas were dropped in one
direction, so command hints scrolled down but not up.

Fixes #14338

Co-Authored-By: Claude <[email protected]>
2026-11-09 23:45:47 +03:00
MSedgeMC 3a642c76c0 port_map: AbstractSelectionList.scrollBarX 2026-11-09 20:45:37 +00:00
MSedgeMC 79551ef835 test: the social list's scrollbar sits right of the rows
Its column, from getRowRight + scrollbarWidth + 2 at two window widths, and
the overflow rule that decides whether it shows.
2026-11-09 20:45:37 +00:00
MSedgeMC d4a019ad08 fix: the social player list shows its scrollbar
AbstractSelectionList.extractRenderState draws its scrollbar at scrollBarX
(getRowRight + scrollbarWidth + 2) whenever the rows overflow. Horizon clipped
and scrolled the rows but drew no bar, so a long list gave no sign of its
position.
2026-11-09 20:45:37 +00:00
MSedgeMC a794f852d7 port_map: CreativeModeInventoryScreen.checkTabHovering is ported 2026-11-09 20:45:23 +00:00
MSedgeMC ff65ebc7fc test: only a tab's inset icon is hovered
The cursor on the 3 pixel border of a tab's slot is outside checkTabHovering's
21x27 icon rectangle; inside it the tab is the hovered one.
2026-11-09 20:45:23 +00:00
MSedgeMC 6767556a09 fix: the creative inventory's tabs say their name on hover
CreativeModeInventoryScreen.checkTabHovering shows a tab's display name when
the cursor is on its icon (3 pixels in from the 26x32 slot). Horizon drew the
tabs without the tooltip, so a tab's name only appeared in a search result's
tooltip.
2026-11-09 20:45:23 +00:00
voidsip df4b2599b4 Load the portal fixture's entity-ticking neighborhood 2026-11-09 14:43:57 -06:00
valuttaandClaude Fable 5.2 0a079cdd75 Server tick: boats and minecarts read the mobs near them, not every mob
Each vehicle walked every mob of the level several times a tick:

- Its box queries (`cart_entity_collisions`, `boat_obstacles`,
  `boat_contacts`) now go through `mobs_meeting`, which reads the mobs
  near the box from a grid of the mobs' boxes. The first query of a
  stretch of vehicle ticks builds it, and the boats' grid serves the
  carts ticking right after them.
- Mob pushes on carts ask that grid once per cart when the mobs
  outnumber the carts, instead of asking the carts' grid once per mob.
- Who rides a vehicle (`boat_mobs`, asked by every boat, and
  `cart_is_vehicle`, asked by every cart on rails) comes from one walk
  per stretch.

The grid and the riders hold until the mob list's next write (its
`ListStamp`): after one, the walk answers until it has cost about as
much as a new grid. With native mods loaded the walks stay. The mobs
found and their order are those of the walk. Refs #14321.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-09 21:40:42 +01:00
Riccardo Guerriero 8aea9cb52b Merge remote-tracking branch 'origin/main' into fix/frame-vibrations 2026-11-09 21:40:02 +01:00
YourPancakes fd70c6aa11 perf(render): reuse native sprite frames when sizes match 2026-11-09 23:36:19 +03:00
c451a0eca5 Streaming: the forced chunks' code in a module of its own, with a test
ForcedCover and the Ranges methods that read the forced chunks (is_forced,
forced_chunks, and in_main_range past the player's circle) go to
streaming/forced_cover.rs, so streaming.rs doesn't grow. A test checks that the
distance map answers every margin as the scan of every forced chunk does, as the
forced chunks change, and that past MOST no map is made.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:31:15 +00:00
dc2a951126 Streaming: forced chunks by distance, one lookup per column instead of a scan
in_main_range went through every forced chunk for each column it was asked about, several times
a tick. While update runs (nothing can change the forced chunks then, as for the extra areas'
cover), a map of each column's distance to the nearest forced chunk answers instead; it is made
again when they change. The same answers. Streaming on the bench: 6.2 ms a tick to 4.7.

Co-Authored-By: Kacper <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:31:14 +00:00
AkirabaneandClaude Sonnet 5.5 722f39f691 Skin loader: bound its downloads, states and resources
`Downloader` kept an entry in `states` for every texture URL asked for and
started a thread (with its own HTTP agent) for each, and an entry in
`resources` for every `texture` id of a profile, none ever dropped. A tab list
of 200 players started about 400 threads at once.

At most 16 downloads now run at once: past that `state` answers `Pending`
without recording the key, and the caller, which asks every frame, starts it
when one has finished. `states` and `resources` keep at most 4096 entries each,
dropping the oldest settled one first (a running download is never dropped); a
dropped texture loads again from the disk cache or the pack. A download thread
that panics before answering now answers "failed" through a drop guard, so its
place is given back and the texture is retried after the wait. The fetch
function and the bounds are fields so a test can set them.

Part of #9370.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 21:23:04 +01:00
JoansitohandClaude Sonnet 5.5 218dc467c4 Fix /rotate relative angles to use the command source's rotation
Fixes #14369

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 21:21:33 +01:00
voidsip 8aaa338f08 Separate Nether portal cooldown handling from gateway changes 2026-11-09 14:20:39 -06:00
voidsip 79b62aaaea Keep witness visibility inputs on seen villagers 2026-11-09 14:17:44 -06:00
Detimes 02b3b03618 Merge remote-tracking branch 'upstream/main' into gap-line-of-sight 2026-11-09 20:17:13 +00:00
DetimesandClaude Haiku 5.5 0acd52bcb5 Work in progress
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 20:17:11 +00:00
Detimes 02f00f9b83 Merge remote-tracking branch 'upstream/main' into gap-riding-getters 2026-11-09 20:17:08 +00:00
Detimes 7d75faab81 Merge remote-tracking branch 'upstream/main' into gap-server-props-read 2026-11-09 20:17:05 +00:00
Detimes 0eddebf75e Merge remote-tracking branch 'upstream/main' into gap-map-colors-read 2026-11-09 20:17:04 +00:00
DetimesandClaude Haiku 5.5 baab01b031 Work in progress
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 20:17:03 +00:00
Detimes 034c4b6e5c Merge remote-tracking branch 'upstream/main' into gap-mob-death-message 2026-11-09 20:16:59 +00:00
Detimes 566027307e Merge remote-tracking branch 'upstream/main' into gap-entity-lookup 2026-11-09 20:16:57 +00:00
voidsip e8dbc42da7 Use the oracle memory constructor entity-list type 2026-11-09 14:13:14 -06:00
voidsip adfc70d2f3 Split custom arrow contents and expiration from potion impacts 2026-11-09 14:10:51 -06:00
voidsip 9da6aa25e5 Split cached villager murder witnesses from hurt attribution 2026-11-09 14:10:25 -06:00
voidsip acf9008e49 Merge commit '38174db59bfd5bf90027bd727f894b141c9e72dc' into split/11536-preserve-live
# Conflicts:
#	.github/workflows/ci.yml
2026-11-09 14:06:12 -06:00
voidsip 7e32b7d0da Merge main before splitting villager reputation fixes 2026-11-09 14:06:08 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 c14ab8d543 Merge remote-tracking branch 'origin/main' into frame-data-count
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:05:56 +01:00
voidsip cd9441f90e Merge commit '38174db59bfd5bf90027bd727f894b141c9e72dc' into split/11484-review 2026-11-09 14:05:52 -06:00
valuttaandClaude Opus 5.5 a79f9c81ba Server tick: skip the per-mob work of idle vehicle and portal passes
- Vehicles: the mobs' BoxReach is worked out by the first box query of a
  stretch of vehicle ticks, not before it, so a level without boats walks
  no mobs for it. Mob pushes on carts work out the box only of the mobs the
  carts' grid puts near a cart.
- Entity portals: the sweep walk stops at once when no loaded section has
  a portal state in its palette, and the pass before it no longer works
  out every mob's size to learn that mobs use portals.

Behaviour is unchanged: each skip turns away only what the full test
would have turned away. Refs #14221.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 21:00:55 +01:00
martipopsandClaude Opus 5.5 222d449920 A pack card's options button is a pad target
The pack screen is a pointer screen: a pad moves a crosshair, which
glides onto the nearest control and hops between controls with the
D-pad. A card's options button registered no target, so the crosshair
never settled on it and the D-pad couldn't reach it; only aiming the
stick by hand opened Pack Options. It registers one now, clipped to the
list's view like its rows.

pad_menu_e2e: pack_card_options, with a fixture pack that has Polytone
config entries, hops onto the button with the D-pad, opens Pack Options
with A and comes back with B.

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

Fixes #14178

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:58:37 +01:00
voduffandClaude Opus 5.5 bd35a34d53 port map: client-005 and client-007 render rows the player can see now
Rows whose 'gap: player:' notes describe things Horizon draws today.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:56:00 +00:00
voduffandClaude Opus 5.5 d6020c9fcc port map: block entity cracks on bells, conduits, lecterns, shulker boxes, skulls
render_breaking redraws these Kinds with the crack overlay now; drop the stale gaps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:56:00 +00:00
voduffandClaude Opus 5.5 bc3893a448 port map: client-003 render rows the player can see now
Rows whose 'gap: player:' notes describe things Horizon draws today.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:55:46 +00:00
voduffandClaude Opus 5.5 79f8b1c258 port map: client-004 render rows the player can see now
Rows whose 'gap: player:' notes describe things Horizon draws today.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:55:46 +00:00
Evan-lhmandClaude Opus 5.5 46b6725e3e gfx.rs: the chunk fade-in helpers move to gfx/section_fade.rs
A pure move (docs/layers.md#file-size): section_instance, chunk_visibility, fade_millis, section_visibility,
FadeInputs and CHUNK_VISIBILITY_THRESHOLD, unchanged but for pub(super). gfx.rs re-imports them, so callers keep
their paths. It makes room for #13780 step 2's few lines of ray tracing glue.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:53:10 +01:00
MSedgeMC b529106e69 port_map: the test block own signal reads the state mode 2026-11-09 19:51:47 +00:00
MSedgeMC 78bfaf571a test: a test block state mode gates the powered entity 2026-11-09 19:51:47 +00:00
MSedgeMC 30e60a02ec fix: a test block reads the block state mode for its own signal 2026-11-09 19:51:47 +00:00
voduffandClaude Opus 5.5 7ae38e4441 port map: the chest minecart save rows follow Minecart's to_nbt/from_nbt to minecarts/nbt.rs
Part of #14327

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:49:54 +00:00
voduff 469ca1d618 Merge remote-tracking branch 'origin/main' into map-moved-fns 2026-11-09 19:49:26 +00:00
Cx188andCodex d18ae680a9 Drop unreachable graphics-stage GLSL helpers (#8406)
Retain calls from each stage main and global declarations, including
referenced overloads and prototypes. Blank unreachable function spans
without moving diagnostic lines. Cover the public translation APIs and
post loader with independent positive and negative GLSL regressions.

Co-Authored-By: Codex (GPT-6) <[email protected]>
2026-11-09 22:49:03 +03:00
DUzzL 51e490f6f9 Let hoppers pull items out of a decorated pot 2026-11-09 20:48:36 +01:00
Vinícius MoreiraandClaude Opus 5.5 cc900e6c6e Polytone: r.noise is 1.21's PerlinSimplexNoise, seed 0, octave 1
r.noise read a single simplex noise of seed 0, which is octave 0 of
Polytone's noise: the mod builds 1.18-1.21's PerlinSimplexNoise (gone
from 26.3) with octaves {1}, whose noise comes from a random seeded by
the first noise's value at its own offsets, read at twice the input with
the noise offsets. So grass and leaves a pack tints with the noise took
other shades than on Java.

Measured on the real mod with a probe pack whose grass colormap encodes
the noise (column the coarse value, row the fine part, calibrated with
ramps): r.noise(x/8, z/8) at 1527 blocks matches this construction to
the decoding's 0.016, and so do polytone/noises definitions with seed 0
or 1 and octaves {0}, {1} and {0, 1} (their weights a third and two
thirds). SimplexNoise gains get2_f64/get3_f64: the mod sums and seeds in
double.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:48:00 -03:00
voduffandClaude Opus 5.5 6b6d099127 port map: the particle limit and anvil rename box rows name their fns
ParticleEngine::create moved to particles/spawn.rs, and the anvil's
50-character unbordered rename box is built by stations/anvil.rs's
rename_box; both rows named fns map-check couldn't find.

Part of #14327

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:45:23 +00:00
AkirabaneandClaude Opus 5.5 a05066c560 Cosmetics: the own model on an offline-mode server is asked by the signed-in account
Fixes #12820, the part kept open there: the player's own model. An
offline-mode server names the player by nameUUIDFromBytes of their name (a
version 3 UUID), which the cosmetics service doesn't know, so their own
cosmetics, name tag style and Horizon's mark were missing. own_uuid now asks
by the signed-in account's UUID for such a profile, as In single player does
for the window's own server; an online profile is kept, and signed out the
profile is kept as before.

No new setting: an offline server behaves as an online one, under My
cosmetics. Other players are still asked by the UUID the server gives them,
since on an offline server anyone can take any name. The service receives
the account's UUID only, no name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:45:06 +01:00
DUzzL 59b4f00696 Share the host's push-and-hurt path 2026-11-09 20:44:59 +01:00
voduffandClaude Opus 5.5 8e8f6ff6fd port map: rows follow fns split out of remote.rs, game.rs, potions.rs, creatures.rs and entity_nbt.rs
Thirteen rows named a fn at the file it was split out of (poll_remote,
tick_world_icon, potion_cloud_to_nbt, the spawn egg fns, the hanging
and trident loaders), so map-check reported "no fn". They now name the
file that holds each fn.

Part of #14327

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:42:13 +00:00
voduffandClaude Opus 5.5 e916d5a66c port map: rows follow mob_geometry to game/creatures/mob_geometry.rs
Game::mob_geometry moved out of game/creatures.rs; 16 rows in
client-003/004/005/007 and client2-002 still named the old file, so
map-check reported "no fn". They now name the new file.

Part of #14327

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:39:25 +00:00
yahya-nusseibehandClaude Opus 5.5 5328ec28b5 Mod registry: bundle SQLite 3.54 through rusqlite 0.41
The registry's own workspace still resolved rusqlite 0.37 ->
libsqlite3-sys 0.35, which bundles a SQLite older than 3.54
(RUSTSEC-2026-0459: uninitialised page-cache memory from a crafted
database opened with a "-wal" file of another page size). The registry
only opens its own database, so this isn't reachable as deployed, but
it is the same upgrade the telemetry server and the root workspace
already made: rusqlite 0.41 resolves libsqlite3-sys 0.39.1, and
fallible_uint keeps the u64/usize conversions working as before (an
error past i64::MAX).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-09 21:36:55 +02:00
yahya-nusseibehandClaude Opus 5.5 1d7c9f150e Telemetry server: claim a bug report before filing its issue
The duplicate check in enqueue stops a double click from filing twice
only once the first issue is recorded. While the first request still
waited on GitHub (up to 20 s) the row's issue was empty, so a second
identical request found the row, got no issue back and filed a second
issue for it; the 10-minute upkeep (file_pending) could likewise file a
report a request was filing at that moment.

Store::claim moves a report from 'new' to 'filing' for exactly one
caller, and Store::release gives it back when GitHub refuses. report()
and file_pending() both claim first; a request that loses the claim is
answered 202 with no issue yet, as when GitHub fails. A report left
'filing' by a server that stopped mid-filing goes back to 'new' when it
starts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-09 21:34:15 +02:00
AkirabaneandClaude Sonnet 5.5 fdd5bac5a8 Pack screen: send each pack icon to the atlas once, not every frame
bind_icons gave every icon drawn in a frame a slot in drawing order and pushed
its 128 by 128 RGBA pixels (64 KiB) every frame, into an atlas that keeps what
it is given. The screen now keeps which slot holds which icon from one frame to
the next: an icon is sent when it takes a slot, the slot of the icon drawn
longest ago is taken when all are in use, changed pixels under the same key are
sent into the same slot, and a new atlas (another revision) empties the table.

Icons past the 64 slots in a single frame still keep unknown_pack, as before.

Part of #9370.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 20:34:12 +01:00
AkirabaneandClaude Opus 5.5 1d60510ba1 Fullbright is held off on another's server; single player and a LAN host keep it
Fixes #3823, as decided there. Fullbright was already off by default; on a
connection that plays no save of the window's own (Remote::save_folder is
None: a multiplayer server, or another player's LAN world) the renderer now
draws the normal lightmap and the graphics screen hides the row. Single
player, a LAN host, a splitscreen seat in P1's world and Replay Studio keep
it, and the saved choice is never changed.

The flag is applied with the settings and again each tick, since joining a
server sets the connection after the settings were applied. The row reads
Settings::fullbright_held, which each game sets for itself (not saved), so a
splitscreen seat does not share it through a process-wide flag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:33:22 +01:00
yahya-nusseibehandClaude Opus 5.5 3e9ac65dba Text: append siblings in place instead of cloning the tree each time
Text::push (MutableComponent.append) cloned the whole JSON component
built so far on every append, then added one sibling, so N siblings
cost N^2. to_text_with pushes once per "extra" entry, and a server's
chat, title or server-list MOTD can carry hundreds of thousands: 20 000
siblings (80 KB) took 76 s on the packet-handling thread.

push now takes the tree out of its Arc and appends in place
(Arc::make_mut, so a Text cloned earlier keeps its own tree). A styled
text is still wrapped once first, including one built from a single
styled span with no saved tree, so its style doesn't reach what is
appended. The JSON produced is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-09 21:31:14 +02:00
Vinícius MoreiraandClaude Opus 5.5 820af79e89 A gliding mob caps its fall at 1 unless it dives
LivingEntity.updateFallFlying starts with checkFallDistanceAccumulation:
a glide whose vertical speed is above -0.5 keeps at most 1 of its fall.
Horizon's update_fall_flying left it out, so a gliding mob kept its whole
fall. The glide code moves to mobs/ai_glide.rs, keeping ai.rs from
growing.

Fixes #13868

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:30:46 -03:00
Nikita Maximilian GrimmandClaude Opus 5.5 c1cf271fbb Layer and address checks read the base's lists at the branch's merge base
Fixes #14317. A local --base origin/main read the lists at main's tip, so entries main dropped after the branch left it counted as the branch's additions. check_file_size.py already compares with the merge base; CI's HEAD^1 is its own merge base.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:29:16 +01:00
yahya-nusseibehandClaude Opus 5.5 96665e3a8e Text: bound what one translation's fallback template expands to
A translatable component a server sends ({"translate", "fallback",
"with"}) falls back to the server's own template when the language has
no such key, and format_translation copied the argument's spans for
every %1$s in it. With the argument being another such component the
copies multiply: 300 references nested three deep is a 4 KB server-list
MOTD or chat message that becomes 27 million spans, and the client ran
out of memory. Vanilla's TranslatableContents.decompose keeps references
to its arguments, so its cost stays linear.

format_translation now shows the template verbatim, as it already does
for a malformed one, when the expansion would pass 32768 spans or 4 MiB
of text. Real translations are nowhere near either.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SJ3stK8iXVDXqoi7midcqd
2026-11-09 21:28:56 +02:00
DUzzL 98ff540d65 Resolve a creative tab name given as a translation key 2026-11-09 20:27:25 +01:00
voduffandClaude Opus 5.5 9d5f89a756 Scoreboard: /team and /scoreboard name holders and teams with vanilla's hover and insertion (#14279)
ScoreHolder.getFeedbackDisplayName replaces the display name's hover
with ShowText of the scoreboard name (an entity's UUID, a player's
name); /team and /scoreboard replies name holders with it. Horizon used
the plain display name. PlayerTeam's displayNameStyle also inserts the
team's name, which Horizon's formatted team name lacked.

test_mob_display_name_parity.py compares the /team and /scoreboard
replies too (10/10; without this commit 5 differ).

Fixes #14279

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:23:28 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 f881b09c67 Merge remote-tracking branch 'origin/main' into prepared-data-stale-tests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 20:23:27 +01:00
DUzzL 624b34b3f9 Charge the host's armour for a dragon wing hit 2026-11-09 20:19:49 +01:00
MSedgeMC 352a141050 port_map: the fish's despawn rule names its port
AbstractFish.removeWhenFarAway and Axolotl.removeWhenFarAway had no row, so
the ledger read the whole pair as unported; named_keeps_it carries it now.
2026-11-09 19:18:10 +00:00
MSedgeMC f6fbdbeebc Test the named fish that stays
Mob::despawn_check on a cod, a salmon and an axolotl 200 blocks from the
player: each with a custom name stays and each without one is removed, and a
zombie's name saves it nothing. Without the name half of removeWhenFarAway the
named cod is discarded like the unnamed one.
2026-11-09 19:18:10 +00:00
MSedgeMC f52894e0dc A named fish or axolotl never despawns
AbstractFish.removeWhenFarAway and Axolotl.removeWhenFarAway answer
`!fromBucket() && !hasCustomName()`, so a cod a player has named stays put
however far it swims, and one let out of a bucket is persistent before it.
Only the bucket half was ported: from_bucket is in
requires_custom_persistence, but check_despawn's removable flag knew nothing
of the name, so a name tag bought a fish nothing and it was discarded past the
128-block despawn distance like any other water mob.

named_keeps_it answers the name half for the fish and the axolotl, and
removable consults it beside the feline rule: a named cod, salmon, tropical
fish, pufferfish, tadpole or axolotl is never removed for distance, and no
other mob's name is persistence.
2026-11-09 19:18:10 +00:00
AkirabaneandClaude Sonnet 5.5 0fb13fa3c8 jmath: Math.log on Windows rounds like HotSpot's x86-64 stub, as sin and cos do
Windows' libm rounds log differently from Java's x86-64 intrinsic for about
0.1% of arguments (299 in 200,000 polar-method radii, #5064 point 1), and
Gaussian draws, density functions and a few block behaviours call it. The
platform's ln is replaced there by exact::log, in the module that already does
this for sin and cos: x split into a power of two and a mantissa in
[sqrt(1/2), sqrt(2)), ln m as 2 atanh((m - 1) / (m + 1)) in double-double with
a quick path checked against an error bound, and the full series with its
terms summed exactly where the bound leaves the rounding open.

exact::log is correctly rounded. HotSpot's stub is not quite (one ulp off for
about 0.002% of arguments), so this matches the JDK on all but those. On
374,043 arguments exact::log was never off from a 70-digit reference; Java's
Math.log was 7 times and the platform ln 331 times. The tests pin ten
arguments where Windows' ln and the JDK differ, the seven where HotSpot
itself is one ulp off, 28 arguments within 2^-65 of a half-way point, the
edges, and that both paths agree.

Part of #5064.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 20:10:34 +01:00
Vinícius MoreiraandClaude Opus 5.5 e5332ab63e command_exec: two boat groups wait for their entity-ticking neighbourhood
vehicle fall clip (#13005) and boat float height (#13022) waited for
their own forced chunk only. Since #13953 an entity ticks once every chunk
within 2 columns is loaded (ChunkMap.prepareEntityTickingChunk), so their
boats and minecarts fell only when an earlier group had left the
neighbours loaded: boat float height failed all 59 reads on main, and
vehicle fall clip failed whenever a group was added before it. Both now
wait for the 5x5 ring, as the other ticking groups do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:05:58 -03:00
DetimesandClaude Haiku 5.5 de6cc998df Native hooks: read the vehicle an entity rides and its passengers
Adds the read-only helpers native_vehicle_of(entity) and
native_passengers_of(entity) for server mods (vanilla Entity.getVehicle
and getPassengers, first = controlling passenger). Helper-only fragment
riding_getters.json; API number is assigned when the fragment is stamped.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 19:00:46 +00:00
DetimesandClaude Haiku 5.5 03b7d245b5 Native hooks: living_death_message (mob death message) (work in progress)
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 18:59:43 +00:00
voduffandClaude Opus 5.5 909d83c284 Commands: a mob's name carries its show_entity hover and UUID insertion (#14220)
Entity.getDisplayName adds a HoverEvent.ShowEntity (type, UUID, name)
and the UUID string as insertion to the team-formatted name. Horizon's
command replies named a mob with the team formatting only, and /summon
without NBT with a bare type name.

mob_command_name (commands/display_names.rs) builds it; target_name's
mob arm and /summon use it. New harness test_mob_display_name_parity.py
(4/4; main: 0/4).

Fixes #14220

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:58:30 +00:00
DetimesandClaude Haiku 5.5 a6204f1f3a Native hooks: read-only entity lookup by UUID and entity data in any level (work in progress)
Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 18:57:08 +00:00
Mik00000 c2dd2d935d perf(light): reuse scratch queues during incremental relight and preserve lazy section loading
- Reuse thread-local scratch queues (`RelightScratch`) across BFS light propagation passes, avoiding reallocation during incremental relighting.
- Pass borrowed slices `&[Pos]` to `relight_layer` to avoid redundant `Vec<Pos>` heap allocations.
- Cache consecutive vertical column lookups in `lt_sources` to avoid redundant map lookups.
- Preserve lazy loading of sections in `Region`, only loading and cloning sections that are actually read or written.
- Add `relight_single_block_bench` and update `relight_bench` to verify timings for both single-block and large batch edits.
2026-11-09 20:55:36 +02:00
itarqos5andClaude Sonnet 5.5 e104190b38 Merge main into particle threads again: both sides add a module line
#14115 moved send_particles and create out of particles.rs into spawn.rs,
and this branch had added `mod simple;` on the same line. Both modules stay.
cargo test -p horizon-client-render --lib particles: 59 passed, including
parallel_tick_matches_serial_tick.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-09 18:54:33 +00:00
Nikita Maximilian GrimmandClaude Opus 5.5 f67f4687a1 Prepared-data tests: give datapack fixtures a pack section, expect TNT's float box, run the gateway test as the console, read HORIZON_TEST_RESOURCES
Six #[ignore]d tests that need prepared vanilla data had gone stale or never
ran (#14261):

- two datapack fixtures lacked the pack section #11576 requires;
- the piston order test expected a push of 0.5, but #12231 gave primed TNT
  vanilla's float box (half width 0.98F / 2, widened);
- the end gateway age test ran /setblock at permission 0 without the command
  registries;
- index_on_vanilla_tree and the_humanoid_mesh_bakes_as_vanillas_zombie read
  HORIZON_RESOURCES and returned early without it.

Fixes #14261

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:52:53 +01:00
Nikita Maximilian Grimm 3e7b3fe7a1 Merge remote-tracking branch 'origin/main' into parity-windows-builds 2026-11-09 19:50:58 +01:00
itarqos5andClaude Sonnet 5.5 2caff14d10 Merge main into particle threads, and give each worker thread its own level
Conflict: particles/tick_bench.rs. Main (c221aa9ec9) adds `cached_chunk` to the
`ParticleLevel` literal of the old benchmark body; this branch had rewritten
that body into `with_scene` and `measure`. Kept this branch's structure and
added the field to the one literal.

That commit also makes the merge fail to build, which no textual conflict
shows: `ParticleLevel::cached_chunk` is a `Cell`, so a `ParticleLevel` is no
longer `Sync`, and `tick_all` shared `&ParticleLevel` between its scoped
threads (E0277). Each worker thread now takes a view of the same world with an
empty one-chunk cache of its own (`thread_view`, in simple.rs, so particles.rs
does not grow), built on the engine thread and moved into the thread. The
thread that runs the first share keeps the caller's level and its cache. A
cache shared between threads could not have held "the last chunk looked up"
for any one of them anyway.

cargo test -p horizon-client-render --lib particles: 59 passed, including
parallel_tick_matches_serial_tick. fmt, clippy on the particle files and
tools/check_file_size.py --base origin/main are clean.

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

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-11-09 18:47:11 +00:00
SenjinandClaude Opus 5.5 dc59cbc710 Connected textures: a texture a rule matches keeps a layer of its own
Identical still textures share one layer (d874278161), and connected-texture rules find their
faces by layer. A rule matching one of them by name (matchTiles, connectTiles) then also took the
faces of the others. Since chained tiles resolve (#13707), a resource pack's rule over its own
transparent tile 19 (`matchTiles=./19.png`, drawing wheat stages) reached every grass block's top
layer, a placeholder with the same pixels, and put plants on the grass.

The rules are read before the models insert their textures, and every name they match keeps a
layer of its own (Sprites::keep_apart). Identical textures no rule names still share.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:45:18 +01:00
Cx188andCodex da831bab1d Add controlled chunk batch ACK rate selection (#8578)
Keep one acknowledgement per completed batch while optionally requesting
64 chunks per tick. Preserve vanilla estimation by default, record the
selected mode, and cover the framed receive path in both modes.

Co-Authored-By: Codex (GPT-6) <[email protected]>
2026-11-09 21:42:56 +03:00
Horizon agentandClaude Opus 5.5 272fcfa34c mace.rs: pass the borrowed stack as it is (clippy needless_borrow)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:27:53 +01:00
Horizon agentandClaude Opus 5.5 997007191a Banner layers: leave out only the layer the codec rejects
TagValueInput.read returns the codec error's partial value, and DFU's list
codec keeps the valid elements as that partial (checked against
datafixerupper 10.0.21): vanilla keeps the other layers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 19:21:03 +01:00
MSedgeMC 9790d9d81c Merge remote-tracking branch 'upstream/main' into fix/weapon-damage-component 2026-11-09 18:02:49 +00:00
MSedgeMC ae0ab270ff Merge remote-tracking branch 'upstream/main' into fix/weapon-damage-component 2026-11-09 17:59:18 +00:00
Nikita Maximilian Grimm f25a5afc00 Merge remote-tracking branch 'origin/main' into record-start-copy 2026-11-09 18:53:46 +01:00
MSedgeMC e865160f46 Merge remote-tracking branch 'upstream/main' into fix/weapon-damage-component 2026-11-09 17:53:42 +00:00
Nikita Maximilian Grimm cc03d693a2 Merge remote-tracking branch 'origin/main' into agent-e2e-windows 2026-11-09 18:53:36 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 d9ef984808 parity.py on Windows: record each harness's builds, and keep conflicting ones apart
The tracer read each command from the subprocess.Popen audit event, which on Windows carries the command line
Popen built, not the list: no harness's cargo build was recognised, so the probe prebuild built nothing and probes'
Rust sources never became dependencies. It now splits the line back (CommandLineToArgvW), and dep_info finds an
.exe's .d file.

Cargo on Windows names a program in deps/ without the hash of its features, so a harness building horizon-client
with another selection (-p horizon-client-lib --bins) relinked the file a running harness's game was using:
"Access is denied", and every later build of the common selection failed too. On Windows a harness now waits while
a running harness built one of its programs differently.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 18:50:07 +01:00
Riccardo GuerrieroandClaude Opus 5.5 d3408a7e1e Keep an enderman's anger after it loses its target
Enderman.aiStep runs NeutralMob.updatePersistentAnger(level, true): holding
a target names it (angry_at) and keeps 20 to 39 seconds of anger running,
so an enderman that lost its player (a daylight teleport, a reload) stays
angry, and EndermanLookForPlayerGoal takes back a player it is angry at on
sight, without a new stare (isAngerInducing). The goal's continue
conditions (forCombat().ignoreLineOfSight()) have no range, so a held
target is no longer dropped past the 64-block follow range.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-09 18:36:52 +01:00
rdbtCVSandClaude Sonnet 5.5 c7a360b9bb Merge main into fix/h194-item-count-predicate-2
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 17:28:42 +00:00
MSedgeMC 9e68efc05b port_map: the destroy-progress stage and the daylight ticker rows are ports
`guest_dig_feedback` sends `(int)(progress * 10)`, the stage
`incrementDestroyProgress` computes, and `tick_daylight_detector` gates on
the dimension type's sky light, so the End is excluded like the Nether.
Both rows still described the old gaps.
2026-11-09 17:19:46 +00:00
rdbtCVSandClaude Sonnet 5.5 b8ceaa3ed4 Merge main into fix/h211-shulker-drop-lock-2
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-09 17:09:21 +00:00
itarqos5 0f23e5e538 Merge remote-tracking branch 'origin/main' into pr/particle-threads 2026-11-09 17:02:25 +00:00
Horizon agentandClaude Opus 5.5 45a2f32631 particles.rs doesn't grow: the threaded tick moves to particles/simple.rs
tick_simple, Simple, sprite_from_age_in, tick_all, finish_simple and the thread
settings move unchanged into a child module; particles.rs keeps the calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 17:04:48 +01:00
MSedgeMC 02a8a61de4 Weapon wear comes from a stack's weapon component
ItemStack.postHurtEnemy uses Weapon.itemDamagePerAttack from the stack's
component. Horizon read the item prototype's weapon damage, so a patched
weapon wore 0 or the prototype's amount instead of its own.

Test: a diamond sword with item_damage_per_attack 3 wears 3 per hit.
2026-11-09 16:00:01 +00:00
MSedgeMC 6a68afa6cc A banner with an invalid layer loads no patterns
BannerPatternLayers.CODEC reads its layer list all or nothing: one layer the
codec rejects leaves the empty layer list. Horizon skipped only the bad layer,
so a banner kept the layers before it.
2026-11-09 15:32:06 +00:00
Horizon agent 3c5c7d6077 Merge remote-tracking branch 'origin/main' into fix-11484
# Conflicts:
#	crates/horizon-client/src/game/nether_portal.rs
2026-11-09 16:31:19 +01:00
Horizon agent ef85f6dd7b Merge main into threaded particle ticks
# Conflicts:
#	crates/horizon-client-render/src/particles.rs
2026-11-09 16:24:19 +01:00
Horizon agent d93a9a4be4 Merge remote-tracking branch 'origin/main' into fix-11536 2026-11-09 16:21:50 +01:00
Horizon agentandClaude Opus 5.5 2b6aed3dc7 Leave the other harnesses' work folders as on main
A run- folder per invocation under .local/<harness>/ is never removed by runner-gc (it only
looks one level down), and these four harnesses aren't this fix's. Main's harness fixes own them.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 16:14:35 +01:00
Horizon agent 6db95ffc1e Merge remote-tracking branch 'origin/main' into fix-11536 2026-11-09 16:14:15 +01:00
Riccardo GuerrieroandClaude Opus 5.5 a3c2a271ef Move the breed goal tests out of goals.rs
goals.rs is over the 3000-line limit and may not grow: the two Breed
goal test modules move to their own files, and the range check uses
Mob::distance_sqr, so goals.rs ends shorter than on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Claude-Session: https://claude.ai/code/session_01WZzq8MxShENtiMj2DMbm5G
2026-11-09 14:37:39 +01:00
Horizon agentandClaude Opus 5.5 cef8682971 Drop the item count fixture nothing runs
Its name matches no harness pattern; test_command_exec_parity.py --only
"item count predicate" already compares the group with vanilla.

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 13:35:18 +01:00
Florian Ernst c2e4f28c3f Start CI again: the previous run stayed queued with no jobs 2026-11-09 13:25:01 +01:00
Florian Ernst 8e26753cda Start CI again: the previous run stayed queued with no jobs 2026-11-09 13:24:59 +01:00
Florian Ernst 8fe0b417be Start CI again: the previous run stayed queued with no jobs 2026-11-09 13:24:57 +01:00
voidsip edfe18495e Keep reputation damage and visibility helpers in focused modules 2026-11-09 05:35:03 -06:00
voidsip 8ede2ff197 Keep potion sound regression in its own module 2026-11-09 05:22:24 -06:00
voidsip f1696089ef Merge commit 'b25a050be818408360d7cf97956350212dda0686' into fix/11329-villager-reputation-events
# Conflicts:
#	crates/horizon-client/src/game/creatures.rs
#	crates/horizon-client/src/game/native_hooks.rs
2026-11-09 05:20:13 -06:00
voidsip a4925a7954 Merge commit 'b25a050be818408360d7cf97956350212dda0686' into fix/11336-potion-contents 2026-11-09 05:19:15 -06:00
voidsip 085b4109e3 Merge commit '3690aa6119b9235be7e3b79680c156da8979479b' into fix/11336-potion-contents 2026-11-09 05:19:05 -06:00
voidsip 4a6942b8e9 Merge commit '3690aa6119b9235be7e3b79680c156da8979479b' into fix/11329-villager-reputation-events 2026-11-09 05:18:51 -06:00
RINNECODERandClaude Opus 5.5 13a8b0c3fe OptiFine CEM: a pre-1.21.5 pack's mob texture paints its old models and the climate variants
A pack made before 1.21.5 ships entity/pig/pig.png, cow.png,
red_mooshroom.png, brown_mooshroom.png and entity/chicken.png in the old
64x32 layout, and its .jem files measure their UVs on them. 26.3 draws
the renamed pig_temperate (64x64) through those UVs: misplaced,
see-through panels. Cold pigs, climate cows and mooshrooms kept
vanilla's textures.

When the packs have an old texture, the adult and its climate variants
draw the adult's model, reshaped by the adult's .jem when it has no
texture of its own, with the vanilla parts' UVs in the old layout (faces
past its bottom, the 1.21.5 cow's muzzle, are dropped). The renderer maps
the 26.3 name (pig_cold, mooshroom_brown) to the old one through
CemLayer::texture_for, so random textures follow it. A variant with a
.jem of its own is left alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 05:04:12 -06:00
RINNECODERandClaude Opus 5.5 7fd4a41cec OptiFine CEM: this is a replacing entry's own bone, not the vanilla part
OptiFine's CEM animation docs: "this" is the current custom model, "part"
the original one. A replacing entry's `this` wrote the vanilla part's
pose instead. Conquest Reforged's pig sets this.tx/ty/tz to its bone's
translate, which flung the head 7 px off the body.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 04:55:41 -06:00
Florian ErnstandClaude Opus 5.5 6ddde6fcde Keep game.rs from growing: declare the allay test module in allays.rs
The file-size check (docs/layers.md#file-size) does not let a file over
3000 lines grow.

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 10:52:21 +01:00
Florian ErnstandClaude Opus 5.5 770f30306a An allay dances to the jukebox it heard first
Squashed and rebased onto main from #12466.

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 10:01:28 +01:00
LokiandAntigravity 6c199da5f6 sculk: resume vibration particle on reload (fixes #12935)
Co-Authored-By: Antigravity <[email protected]>
2026-11-09 17:46:05 +09:00
MSedgeMC 323705ef9b Merge remote-tracking branch 'upstream/main' into fix/dialog-book-pause
# Conflicts:
#	crates/horizon-client/src/game/books.rs
2026-11-09 08:33:49 +00:00
MSedgeMC 94a2f9a782 A dialog's pause and a lectern's book decide whether the world stops
Minecraft.pause asks the screen Minecraft set. A dialog is a DialogScreen of
its own: isPauseScreen returns its CommonDialogData.pause, true by default, so
a server's dialog freezes a single-player world unless the dialog says
otherwise. The warning above it is a ConfirmScreen (true) and the waiting
screen answers false. Horizon parsed `pause` and never read it, so every dialog
kept the world running. A lectern's book is LecternScreen, whose isPauseScreen
overrides BookViewScreen's true to false: reading on a lectern leaves the world
ticking, reading the same book in hand does not. Horizon paused for both.

pauses_game now asks the dialog, then the book, then the screen, the way each
of them is its own screen over the last.
2026-11-09 08:04:10 +00:00
fc4a51753d Feeding a horse or camel makes a vibration and a Silent one eats quietly
`AbstractHorse.handleEating` and `Camel.handleEating` play the eating sound
only when the mount is not Silent, at its feet, with a pitch from the mount's
own random, and then post `GameEvent.EAT` from the mount. A growing baby's
HAPPY_VILLAGER position draws three doubles from that random first (the
server's `Level.addParticle` shows nothing; the client draws its own).
Horizon played the sound for Silent mounts too, at the body's centre with
the level's random, and posted no game event, so sculk sensors and wardens
never heard a mount eat.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
2026-11-09 07:23:49 +01:00
af8fa33bf0 Keep breeding partners within eight blocks
Match BreedGoal.getFreePartner and TargetingConditions.test by rejecting
partners beyond the spherical range while keeping the existing box query
and nearest-first ordering. Keep partners exactly eight blocks away.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
2026-11-09 07:23:49 +01:00
12d3b1f189 Breeze dust crumbles the fence, wall or gate it stands on
`Breeze.emitGroundParticles` and `emitJumpTrailParticles` take
`getInBlockState`, else `getBlockStateOn` (`Entity.getOnPos(1.0E-5F)`), which
keeps the supporting block under the feet. Fences, walls and fence gates
collide 1.5 blocks high, so the cell 0.2 below a breeze standing on one is air
and no dust came out. The ground dust also skips invisible blocks as vanilla
does. The crumbs now go through `ClientLevel.addParticle`, so each particle's
own generator (`Particle.random`) makes its draws and the client level's random
is left alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Codex (gpt-6.1-sol) <[email protected]>
Co-Authored-By: DeepSeek V4.1 Flash <[email protected]>
2026-11-09 07:23:48 +01:00
voidsip 42b04e0238 Update reputation damage and guest fixtures for main 2026-11-08 20:23:13 -06:00
voidsip b37b703f1c Run portal cooldown proof in a scratch game directory 2026-11-08 19:19:22 -06:00
voidsip 94cad99398 Merge commit 'f858ee752f1c0e76b6d200ec846645532536aded' into fix/11336-potion-contents 2026-11-08 18:41:12 -06:00
voidsip d7dc5628e2 Merge commit 'f858ee752f1c0e76b6d200ec846645532536aded' into fix/11329-villager-reputation-events 2026-11-08 18:38:26 -06:00
voidsip 8b45d15486 Merge commit 'f858ee752f1c0e76b6d200ec846645532536aded' into fix/11318-portal-cooldowns 2026-11-08 18:38:26 -06:00
voidsip e8f93ffc67 Merge main into villager reputation fix 2026-11-08 18:38:25 -06:00
voidsip 2e0f86f312 Merge main and preserve entity portal cooldown phases 2026-11-08 18:38:25 -06:00
voidsip 167caf28d0 Merge commit '976346aff5bfa09c6d8e364c347bdf1791618a98' into fix/11336-potion-contents 2026-11-08 18:13:04 -06:00
Nikita Maximilian GrimmandClaude Opus 5.5 d0f851fca9 agent_control_e2e passes again: the screen commands wait for the first frame
- A game answers its control socket before it has drawn a frame: `ui`, `click`, `set`,
  `screen` and `click-button`, which read the last drawn frame, now wait for the first one
  (UiWait), as `ui`, `click` and `set` already wait for a frame after a click.
- The ui scenario expects Create New World's Game tab, the manage scenario a widget the
  Horizon options page still has (ai-agent), and the options scenario takes GUI scale 2 as
  half the GUI of scale 1, so display scaling other than 100 % passes.
- The no-ai check honours HORIZON_E2E_HEADLESS like the other scenarios.

Fixes #12972

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 00:27:31 +01:00
Nikita Maximilian GrimmandClaude Opus 5.5 7a08fd9041 record-start: the server thread holds still while the world is copied
Pausing the integrated server for the copy ran its pause save (IntegratedServer.tickServer's
saveEverything) during the copy, often after the call that saved had returned. That save
renames level.dat and the player files into place and hands region files to the region
writer, so the copy failed with "The system cannot find the file specified", or could read
a region file mid-write. Now the server thread saves, then waits on its own thread until the
copy is done; the pause flag stays as it was.

Fixes #12977

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-09 00:17:50 +01:00
Riccardo GuerrieroandClaude Opus 5.5 2485e58daa Merge origin/main
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 22:50:33 +01:00
itarqos5andClaude Sonnet 5.5 32e184c196 Particles: tick the independent ones on several threads
ParticleEngine::tick ran every live particle one after another. Most of them (flames,
smoke, poofs, dust, crits and a firework spark's own motion) read and write only their
own state, the world and the sprite sets, so tick_simple now ticks them on up to four
scoped threads once there are 2048 particles. A spark's trail child, which takes the next
engine seed, and every other behaviour still run on the engine thread afterwards, in the
order they had, so the particles, the engine's random and the sounds come out as before.

On the stress_particles mix (isolated benchmark, particles/tick_bench.rs): whole-scene
engine tick 1.81 ms on one thread, 1.40 / 1.27 / 1.18 / 1.15 ms on 2 / 3 / 4 / 6 threads.
parallel_tick_matches_serial_tick runs both over 90 ticks with rockets and compares every
particle, the engine's random and the sounds.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011paghWkrnyQRBhJRodZpG2
2026-11-08 16:20:06 +00:00
RINNECODERandClaude Opus 5.5 957ecaff5f Shader packs: keep solid terrain in the compact layout
With a `shaders/` pack, sections uploaded their solid quads as four
`TerrainVertex`es each instead of one 24-byte record (`mesher::packed`): the
pack's terrain and shadow programs read vertex attributes. At render distance
64 that doubled the section arena (5.9 GB of vertices against 2.9 GB) and
BSL and Photon flights stalled under memory pressure.

- Flat pack draws now pull every input from the arena page with a GLSL port of
  terrain.wgsl's `section_corner` (`pack_atlas::PULL_FLAT`): position, UV,
  layer, light and colour bit for bit (the colour as the Unorm8x4 fetch
  converts it), and the quad's four corners for the normal, tangent and
  midpoints. Their pipelines take no vertex buffer.
- Records carry each corner's alpha (3-bit codes in spare bits of words 3 and
  4): with `separateAo` it is the corner's ambient occlusion, and one alpha a
  quad made almost every face fail the exact check.
- Records always end on a whole quad of slots, so the translucent vertices a
  pack's frames keep after them start a quad (their normals were read across
  quads).
- `section-layout compact|wide` (horizon-ctl) switches the layout in a running
  game for A/B checks; `follow_packed_layout` keeps it on for flat packs.

A GPU test draws records and their wide vertices through a pack's terrain
inputs and requires the same bits for every input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 03:46:41 -06:00
voidsip 36bad2c06e Give parity harnesses fresh default capture directories 2026-11-07 20:35:20 -06:00
voidsip 7c7bca2e7b Update potion fixture for silent impact argument 2026-11-07 20:35:19 -06:00
voidsip 58552b8cb9 Merge commit 'bc6016d19d4dd6f11f6b954fc3b121546f069ffb' into fix/11336-potion-contents 2026-11-07 20:25:35 -06:00
Evrim Cicek 3cd63747b9 Merge remote-tracking branch 'upstream/main' into fix/vehicle-item-stack-config
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-08 02:37:22 +03:00
b064c12aca Let sculk hear item frame changes
Post BLOCK_CHANGE at the frame from ItemFrame.interact, hurtServer and
dropItem, after the changes and drops vanilla performs first. Preserve
BlockAttachedEntity.kill ordering and discard unsupported frames without
a spurious ENTITY_DIE.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 17:51:59 +01:00
Evrim Cicek 99f76baf29 Merge remote-tracking branch 'upstream/main' into fix/vehicle-item-stack-config
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-07 16:53:40 +03:00
Horizon agentandClaude Opus 5.5 1cf0e13b61 Merge origin/main into fix/11329-villager-reputation-events
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:05:20 +01:00
Horizon agentandClaude Opus 5.5 37541674a9 Merge origin/main into fix/11336-potion-contents
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 13:04:25 +01:00
Horizon agentandClaude Opus 5.5 18e0854d00 Merge main into fix/11329-villager-reputation-events
Main split projectile_hit into a wrapper and projectile_hit_inner: the
reputation flush now runs in the wrapper after the inner hit. Trident and
wind charge hits keep both the reputation flush and main's absorbed-damage
and post-attack calls.

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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:01:48 +01:00
voidsip 65d35f3261 Initialize configuration history for reputation test guests 2026-11-06 22:02:27 -06:00
voidsip b4dea2a473 Merge commit '77936bf4bee3ec7d641f54b97a3da09f9b72e213' into fix/11329-villager-reputation-events 2026-11-06 21:52:56 -06:00
voidsip bfa20f0413 Initialize upstream native command fields in reputation fixture 2026-11-06 21:31:46 -06:00
voidsip 05c7788a8f Merge commit '41944ed91474c6af28572d2e2273b6b2bd0bcf1e' into fix/11329-villager-reputation-events 2026-11-06 21:22:00 -06:00
voidsip 35ab895667 Validate villager reputation with isolated game and vanilla fixtures 2026-11-06 19:47:29 -06:00
voidsip 178a2bf8b4 Correct isolated potion fixture admission and default invocation 2026-11-06 18:36:13 -06:00
voidsip 673a2515e8 Add stock-compatible accepted-hurt regression fixture 2026-11-06 17:55:03 -06:00
voidsip 93d57cf58c Validate potion components with isolated vanilla methods 2026-11-06 17:52:39 -06:00
Evrim Cicek 52939c99ab Merge remote-tracking branch 'upstream/main' into fix/vehicle-item-stack-config
# Conflicts:
#	tools/command_exec_corpus.py
2026-11-07 02:30:24 +03:00
voidsip 4f935ae226 Use the standard prepared resource path in the focused harness 2026-11-06 17:28:28 -06:00
voidsip 8eba763b33 Keep legacy cooldown fixture type explicit 2026-11-06 17:14:40 -06:00
voidsip 85029c85e5 Verify portal counters without starting a server 2026-11-06 17:14:13 -06:00
voidsip e08699893a Merge current main into villager reputation fix 2026-11-06 16:15:57 -06:00
voidsip b714d73e46 Deliver villager reputation from accepted damage sources 2026-11-06 16:13:29 -06:00
voidsip 72cd6e42ee Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11336-potion-contents 2026-11-06 16:13:16 -06:00
voidsip 9baf83e129 Fix thrown potion stack components and arrow expiration 2026-11-06 16:13:02 -06:00
voidsip 2d04344265 Merge commit '9d11d0c710705ee0901c2186d78641048a6660b0' into fix/11318-portal-cooldowns 2026-11-06 16:12:27 -06:00
voidsip 226e365523 Use entity-specific portal cooldowns and preserve live counters 2026-11-06 16:12:12 -06:00
voidsip bcc1264dff Share identity-aware merchant price refresh helpers 2026-11-06 15:33:49 -06:00
Evrim CicekandClaude Opus 5.5 8590b6e650 A vehicle from an item also takes its custom_data, and a boat keeps its placing yaw
Review: Entity.applyImplicitComponent applies two components, the custom
name and minecraft:custom_data (saved as `data`), and BoatItem.use /
BoatDispenseItemBehavior turn the boat to the player's or dispenser's yaw
after the stack's config, so entity_data's Rotation does not keep it.
Also moves place_minecart's doc line back onto it.

Harness group "vehicle item stack config": the three new cases 24/27
before, 27/27 now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 18:57:18 +03:00
Evrim CicekandClaude Opus 5.5 70f07d8757 A placed or dispensed minecart or boat takes its item's name and entity_data
MinecartItem.useOn, BoatItem.use and the dispenser's
MinecartDispenseItemBehavior / BoatDispenseItemBehavior apply
EntityType.createDefaultStackConfig to the new vehicle: the item's custom
name (applyComponentsFromItemStack), then minecraft:entity_data loaded
over it (updateCustomEntityTag) when it names the vehicle's type, an
op-only type only from an op player and never from a dispenser. Horizon
placed default vehicles. Game::apply_vehicle_stack_config does both,
through the /data merge loader, with the spawn egg's guard.

Command harness group "vehicle item stack config": 12/23 -> 23/23.

Fixes #11195

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 18:36:09 +03:00
407 changed files with 23294 additions and 3109 deletions

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
name: runner watch
# Every 30 minutes: one issue when jobs wait over 2 hours for a self-hosted runner nobody runs (the maintainer's
# machines are off), closed again once nothing waits (tools/ci/runner_watch.py, docs/operations.md). It runs on
# GitHub's runners, never ours: it must work when every self-hosted runner is gone.
# gh workflow run "runner watch" -f dry_run=true
on:
schedule:
- cron: '11,41 * * * *'
workflow_dispatch:
inputs:
dry_run:
description: Only print what it would do with the issue
type: boolean
default: false
permissions:
actions: read
contents: read
issues: write
concurrency:
group: runner-watch
cancel-in-progress: false
jobs:
watch:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Jobs waiting for a self-hosted runner
env:
GH_TOKEN: ${{ github.token }}
run: python3 tools/ci/runner_watch.py ${{ inputs.dry_run && '--dry-run' || '' }}
+7
View File
@@ -20,6 +20,13 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
is the GitHub account the PR is opened from (`gh api user --jq .login`). Issues say "Filed by", reviews
"Review by". Every comment starts with `🤖 Agent:`. Write only as the person you work for: the lines on
this page that name Ludovic are for his own agents (account `ludovic111`), never for anyone else's.
- **Review only when asked, and decide.** Review a pull request only when its author or a maintainer asks.
Asked by a maintainer to review open pull requests in general, take them one at a time, oldest first, skipping
drafts, your person's own and those they already reviewed. Check that the change does what it says (bugs, edge
cases), what it could break, whether tests cover it, and whether its scope and description hold up. Report only
what you can point to with a `file:line`, each point marked Blocker (fix before merge), Important, Nit,
Suggestion, Question or Praise. Submit a decision, never a plain comment: `gh pr review --approve` when nothing
blocks, `--request-changes` when something does.
- **Attribution.** Commits end with a `Co-Authored-By:` line for the agent that wrote them, and PR bodies
with that agent's own "Generated with" line. Example, Ludovic's agents (Claude Code on `ludovic111`):
first line `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, commits
Generated
+46
View File
@@ -706,6 +706,25 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.14"
@@ -926,6 +945,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "either"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "embedded-io"
version = "0.4.0"
@@ -1554,6 +1579,7 @@ dependencies = [
"open",
"png",
"pollster",
"rayon",
"rustix 1.1.5",
"serde",
"serde_json",
@@ -3664,6 +3690,26 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
[[package]]
name = "rayon"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "rc2"
version = "0.8.1"
+145 -45
View File
@@ -2,6 +2,9 @@
> Adopted 2026-11-09 by the founder as his last decision as head of the project. It takes effect when he
> announces that he is stepping down. From then on only the council changes it, by a 2/3 poll (section 15).
>
> Amended 2026-11-10 by the founder (three kinds of action, elections by tier, who may do what, and council poll P41:
> the mods decide moderation matters). The council can overturn this amendment by poll.
Horizon has no boss. A **council of equals** decides by polls. **Theme groups** do the work in their areas, each
with a **lead**. The **Horizon Team** reviews and merges code. **Moderators** keep the Discord server and the
@@ -50,13 +53,13 @@ the Horizon Team, for example.
| Level | What it can do | How you get in | How you leave | 18+ |
| --- | --- | --- | --- | --- |
| **Member** | Play, chat, report bugs, suggest ideas, open issues and pull requests, pick group roles | Join the Discord server or the GitHub repo | Leave, or get banned | No |
| **Contributor** (⛏️ Iron, 🥇 Gold, 💎 Diamond, 🟪 Netherite ranks) | Write in #contributors; `/claim` issues; nominate people for group lead (if active in that group) | One merged pull request in a public horizon-rust repo, linked with `/link-github` and `/verify-github`. Ranks come from merged pull requests: 10, 40, 100 and 200 | Contributor status and ranks stay | No |
| **Group member** | Read and write in the group's channel; get the group's pings; take part in the group's advisory poll on its lead | Pick the group's role in Channels & Roles, or with `/groups` | Remove the role | No |
| **🤝 Support** | Answer and close posts in #horizon-support | `/apply`; vote of the mods and the Team (as today) | Resign, 30 days inactive, or removed by the Chief of Mods or the council | No |
| **🛡️ Moderator** | Time out, delete messages, manage threads, quarantine. No bans | `/apply`, then the selection filter; mods' vote; the council may object within 24 h | Resign, 30 days inactive, suspended by the Chief of Mods, removed by a council poll (simple majority) | **Yes** |
| **🛡️ Chief of Mods** | A moderator's powers, plus bans; leads the mods; suspends a mod at once pending the council | Council poll (simple majority), from the mods with at least 30 days | Resign, 30 days inactive, council poll (simple majority) | **Yes** |
| **🧭 Group lead** | Decides inside the group's topic (section 6); manages the group's channel; triage on the group's GitHub issues | Nomination, the filter, a 24 h public discussion with an advisory group poll, then a council poll (simple majority); 30 days probation | Resign, 30 days inactive (automatic), council poll (simple majority); confirmed again every 6 months | **Yes** |
| **🌌 Horizon Team** | Review and merge pull requests (GitHub `horizon-team`, write access); `/nightly` and triage commands (trusted reviewers); #horizon-team | Nomination, the filter, a 24 h public discussion, then a council poll (2/3); 30 days probation | Resign, 60 days without a merge or review (automatic), council poll (2/3, without the person) | **Yes** |
| **Contributor** (⛏️ Iron, 🥇 Gold, 💎 Diamond, 🟪 Netherite ranks) | Write in #contributors; `/claim` issues; vote in their group's elections (if active in that group) | One merged pull request in a public horizon-rust repo, linked with `/link-github` and `/verify-github`. Ranks come from merged pull requests: 10, 40, 100 and 200 | Contributor status and ranks stay | No |
| **Group member** | Read and write in the group's channel; get the group's pings; vote in the group's elections and votes when active | Pick the group's role in Channels & Roles, or with `/groups` | Remove the role | No |
| **🤝 Support** | Answer and close posts in #horizon-support | Given by any moderator (a free action, section 2.1) | Resign, 30 days inactive, or removed by a moderator, the Chief of Mods or the council | No |
| **🛡️ Moderator** | Time out, delete messages, manage threads, quarantine. No bans | Elected by the mods (section 5.3); council veto within 24 h | Resign, 30 days inactive, suspended by the Chief of Mods, recalled by the mods, removed by a council poll (simple majority) | **Yes** |
| **🛡️ Chief of Mods** | A moderator's powers, plus bans; leads the mods; suspends a mod at once pending the council | Elected by the mods, from the mods with at least 30 days (section 5.3); council veto within 24 h | Resign, 30 days inactive, recalled by the mods, council poll (simple majority) | **Yes** |
| **🧭 Group lead** | Decides inside the group's topic (section 6); manages the group's channel; triage on the group's GitHub issues | Elected by the group's active members and the Team (section 5.3); council veto within 24 h; 30 days probation | Resign, 30 days inactive (automatic), recalled by the same electorate, council poll (simple majority); confirmed again every 6 months | **Yes** |
| **🌌 Horizon Team** | Review and merge pull requests (GitHub `horizon-team`, write access); `/nightly` and triage commands (trusted reviewers); #horizon-team | Elected by the Team, 2/3 (section 5.3); council veto within 24 h; 30 days probation | Resign, 60 days without a merge or review (automatic), recalled by the Team (2/3), council poll (2/3, without the person) | **Yes** |
| **🏛️ Council** | Decides everything else by poll (section 4); bans; emergency actions by any 2 members | Nominated by a council member, the filter, a 24 h public discussion, then a council poll (2/3); 30 days probation | Resign, inactivity (section 5.5), council poll (2/3, without the person) | **Yes** |
**The account holder** isn't a level. The founder (Ludovic) still holds the project's accounts (GitHub organisation
@@ -64,6 +67,55 @@ owner, Discord server owner, the Microsoft app approved by Mojang, the domains,
council's decisions on them and hands them over step by step (section 11). As a council member he has one vote,
like everyone else.
### 2.1 Three kinds of action
Most things need no vote at all. A vote is for power over other people, and for decisions that bind a whole body.
| Kind | What | How |
| --- | --- | --- |
| **Free** | Everyday actions inside your own role (the list below, and anything of the same weight) | Just do it. Kira logs the ones she sees in #staff-log. The tier above can reverse it; if people disagree, the tier above votes. A pattern of abuse is a recall |
| **Body vote** | Giving or taking a role that carries power (an election), or a decision that belongs to one body: the mods, the Team, a group | `/elect` or `/vote body:` in Kira (section 5.3). Any council member can call a veto within 24 hours |
| **Council poll** | Rules, money, accounts and ownership, the council's own members, vetoes, anything that spans several bodies | `/poll` (section 4) |
Free actions, for example:
- a lead gives or removes their group's helper role (🧩 Horizon Modding Team), through Kira;
- a moderator gives or removes 🤝 Support, through Kira;
- a moderator times out, deletes, quarantines, or changes a channel's slowmode or topic; the Chief of Mods bans and
unbans;
- the Team merges and labels;
- a server operator restarts the official server, or prunes backups and chunks by the written rule;
- a lead pins, renames or creates threads in their group's channels;
- Kira's automatic actions.
**The 24-hour rule.** Every vote lasts 24 hours at most, and closes earlier once its result can't change. Only council
polls on this document, the licence, money and the GitHub organisation's ownership last 48 hours. A veto is called
within 24 hours of a result.
### 2.2 Who may do what
What each post decides, and what it holds on Discord, on the official server and on GitHub. Anything not listed is a
council matter.
| Post | Decides | Discord | Official server | GitHub |
| --- | --- | --- | --- | --- |
| **Member** | — | Chat, threads, picks group roles | Play | Issues, pull requests, `/claim` |
| **Group helper** (🧩 Horizon Modding Team) | — | Writes in the group's team channel | — | — |
| **🤝 Support** | Closes support posts | Manages threads in #horizon-support | — | — |
| **🛡️ Moderator** | Moderation matters, by the mods' vote (section 7) | Time out, delete messages, manage threads and nicknames, audit log, voice mute and move; quarantine through Kira; the staff channels | In-game op if also elected operator | — |
| **🛡️ Chief of Mods** | A moderator's, plus bans and unbans; suspends a mod at once; breaks ties in the mods' votes | Plus Ban | As a moderator | — |
| **Server operator** | In-game moderation by the server rules | — | Op (the server's ops list); no panel, no `server.toml` | — |
| **🧭 Server & SMP lead** | The server's settings, by the written rules (backup first, warning in game) | As every lead | A panel sub-user once a council accounts poll gives one | As every lead |
| **🧭 Group lead** | The group's free actions; gives and removes its helper role | In the group's channels: delete messages, manage and pin threads, ping the group; the helper role through Kira | — | Triage on the group's labels through Kira (no repository role) |
| **🌌 Horizon Team** | Merges; elects Team members | #horizon-team and the staff channels. The role still carries timeout and delete; whether it keeps them is a mod matter | — | `horizon-team`: write on horizon, horizon-mods, horizon-mixins, horizon-native-mod-template and horizon-server; also kira and horizon-site if P37 passes |
| **🔧 Server Manager** | — | Manage Channels and Manage Roles (the server's layout); given by council poll | — | — |
| **🏛️ Council** | Council polls, vetoes, emergencies (any 2) | A moderator's permissions plus Ban, mention @everyone and pin; #council | Panel sub-users for two members if P38 passes | The `council` team: code-owner reviews and the release tools' owner powers if P35 passes, security managers if P36 passes; a second organisation owner if P28 passes |
| **Account holder** (the founder) | Carries out decisions on his accounts (section 11) | Server owner | The panel's owner account | Organisation owner |
Kira applies a passed election everywhere she can: Discord roles herself, GitHub team membership when the council has
given her a token for it. Whatever she can't do (a panel sub-user, the ops list, a GitHub team without a token) she
posts as a list of clicks for a named person.
## 3. Each level in detail
### Member
@@ -84,13 +136,13 @@ an issue or a pull request on GitHub, or a request for a council poll (any counc
Each theme group (section 6) has a role that anyone can pick and drop. It opens the group's channel and receives the
group's pings. Picking a role grants no power. A group member counts as **active in the group** when Kira has seen at
least one counted action in the group's area (section 5.1) in the last 60 days. Only active group members can
nominate a lead or vote in the group's advisory poll.
least one counted action in the group's area (section 5.1) in the last 60 days. Active group members vote in the
group's elections and decisions (section 5.3).
### 🤝 Support
Unchanged: Support members help players in #horizon-support. They answer every post there and mark posts solved.
The role carries no permission, so it has no age rule. They join through `/apply`, and the mods and the Team vote.
The role carries no permission, so it has no age rule. A moderator gives it, and takes it back, through Kira.
### 🛡️ Moderators and the Chief of Mods
@@ -151,7 +203,7 @@ don't go through the filter or a probation. They do make the 18+ declaration (se
| --- | --- |
| Who starts one | Any council member, with `/poll` (Kira). Anyone else asks a council member to start it |
| Where | #polls-and-decisions, in public. Polls about a person (removal, appeals, the age rule) run in #council, and only their result is public |
| How long | 24 hours. It closes early only if every council member has voted |
| How long | 24 hours; 48 hours for this document, the licence, money and the GitHub organisation's ownership. It closes early only if every council member has voted |
| Ballot | Yes, No or Abstain. You can change it until the poll closes |
| Quorum | At least half of the council votes (Abstain counts). With 6 members, 3 votes |
| Simple majority | More Yes than No |
@@ -165,20 +217,20 @@ don't go through the filter or a probation. They do make the 18+ declaration (se
| Simple majority | Two-thirds |
| --- | --- |
| Day-to-day project decisions: direction, priorities, settling disputes between groups, a public statement | Adding council members and Horizon Team members |
| Group leads and co-leads: appointing, removing, confirming every 6 months | Removing a council member or a Team member (without the person concerned) |
| Moderators, the Chief of Mods, Support: confirming, removing | Rules: this document, the server rules, the contributing policy, the licence |
| Day-to-day project decisions: direction, priorities, settling disputes between groups, a public statement | Adding council members |
| Vetoing a body's vote or election (section 5.3) | Removing a council member or a Team member (without the person concerned) |
| Removing a group lead, a moderator, the Chief of Mods or Support (their bodies can also recall them) | Rules: this document, the server rules, the contributing policy, the licence |
| Ending a probation early | Money (section 12) |
| Confirming an emergency action | Account handover steps (section 11) |
| Second-level moderation appeals | Waiving part of the selection filter (section 5.4) |
| Deciding for a body that has fewer than 3 voters | Waiving part of the selection filter (section 5.4) |
| Bringing back someone who stepped down for inactivity, within 6 months | Changing the council's size |
**When in doubt, two-thirds.** Any council member can say a poll needs 2/3, and Kira then counts it at 2/3.
### 4.4 Discussion
Polls that add someone to the council, the Team or a lead post start with a **24-hour public discussion** (section
5.3). Other polls are discussed in their own thread while they run. A member who wants more time votes No and says
Polls that add someone to the council start with a **24-hour public discussion**. Other polls, and elections, are
discussed in their own thread while they run. A member who wants more time votes No and says
why. A failed poll can come back after 7 days.
### 4.5 Conflicts of interest
@@ -220,7 +272,7 @@ false age declaration (section 9).
## 5. The selection filter
Nobody becomes a lead, a Team member or a council member just because they are well liked or talk a lot. Kira
measures the work, and only people above a floor can be nominated. The council then decides among them.
measures the work, and only people above a floor can be nominated. Their body then elects them (section 5.3).
### 5.1 What Kira measures
@@ -254,25 +306,63 @@ A nomination is refused below these floors.
The numbers are checked again once a year (section 15). They should stay reachable for people who really work on
Horizon and out of reach for people who don't.
### 5.3 The path to a role
### 5.3 Elections
1. **Nomination.** Run `/nominate member: role: [group:]` in Kira.
- A **group lead** can be nominated by an active member of that group or by a council member. A self-nomination
needs a second from another active group member or a council member.
- A **Team member** can be nominated by a council or Team member. Someone can also nominate themselves with
`/apply`, if a council or Team member sponsors them.
- A **council member** can only be nominated by a council member.
- **Moderators** apply with `/apply`.
2. **The filter.** Kira checks the floor and the 18+ declaration. Below the floor, Kira refuses and says which line
is short.
3. **Public discussion, 24 hours.** Kira posts the nomination and the evidence card in a thread of
#polls-and-decisions. Contributors and the council can comment. For a lead, Kira also runs an **advisory poll** in
the group's channel for the same 24 hours. Only active group members vote in it, and the council sees the result.
4. **Council poll, 24 hours.** Simple majority for a lead, 2/3 for the Team and the council. For moderators, the mods'
vote replaces this step, and any two council members can object within 24 hours; the council then decides by poll.
5. **Probation, 30 days.** The role is held in full, except for the Team limits in section 3. At day 25, Kira asks the
council in #council whether anything is wrong. Probation ends by itself at day 30, unless a council poll (simple
majority) ended it earlier.
The body that works with a person elects them. Kira runs it: `/elect post: member: [group:]`, and `action: remove`
for a recall.
| Post | Who votes | Passes with | Who can start it |
| --- | --- | --- | --- |
| **🛡️ Moderator** | The mods (🛡️ Mod and 🛡️ Chief of Mods) | Simple majority; the Chief of Mods breaks a tie | Any mod, a council member |
| **🛡️ Chief of Mods** | The mods; candidates are mods for 30 days or more | Simple majority | Any mod, a council member |
| **Server operator** | The mods and the 🧭 Server lead | Simple majority | The Server lead, the Chief of Mods, a council member |
| **🧭 Group lead** (a co-lead once the group has 8 active members) | The group's active members, and the Team | Simple majority | The current lead, a Team member, a council member |
| **🌌 Horizon Team** | The Team | Two thirds, and at least 3 Yes | A Team member, a council member |
| **🏛️ Council** | The council, by poll after a 24-hour discussion (section 4) | Two thirds, and at least 3 Yes | A council member |
| 🤝 Support, a group's helper role | Nobody: a free action (section 2.1) | — | A moderator; the group's lead |
An **active group member** has held the group's role for 14 days or more (Kira counts from when she first saw it)
and has at least one merged pull request or review with the group's label in the last 60 days.
1. **Start.** Kira checks the floor (5.2) and the 18+ declaration. If the candidate falls short, the person starting
gets a private "not now", and the candidate a private message saying what is missing. Nothing is posted and no
reason is ever shown to anyone else. Kira checks what she can measure (verified GitHub, merged pull requests and
reviews, overall and by the group's label, rank, days in the server, Kira level, clean record, the declaration);
the voters judge the rest.
2. **Vote, 24 hours,** in the body's channel, discussed in the vote's thread. Yes, No or Abstain, changeable while it
runs. Kira shows how many voted, never who. It closes early once the result can't change.
3. **Result,** applied at once. Kira gives or takes the Discord role and, with a token, the GitHub team; she lists the
rest as clicks for a named person. Only the result is published, never the ballots.
4. **Veto, 24 hours.** Any council member can call it with the button under the result. A council poll (simple
majority, without the people involved) decides; if it passes, Kira undoes the result.
5. **Probation, 30 days,** for leads and Team members. It ends by itself unless someone who can vote starts a recall.
The council can always remove someone by its own poll. **Body votes** work the same way for a body's own decisions:
`/vote body:mods`, `body:team` or `body:group`, simple majority, 24 hours, the same veto.
#### Hard cases
| Case | What happens |
| --- | --- |
| Fewer than 3 can vote | The council decides by poll |
| Quorum | A third of the electorate, and at least 3 ballots (Abstain counts). Without it, nothing changes |
| Tie | Fails, and nothing changes. In the mods' votes, the Chief of Mods' ballot breaks it |
| The candidate | Doesn't vote on themselves, and can decline (the election ends). The person who started it votes normally |
| Conflicts | Whoever the vote is about, or who gave or received the moderation action in question, doesn't vote |
| Several candidates for one seat | Nominations within the first 12 hours join one approval ballot. The seat goes to the most approvals if that is at least half of the voters; otherwise a 24-hour run-off between the top two |
| A seat that is held | Changes only by a recall or by the 6-month confirmation |
| The council is already voting on it | No election starts for the same person and post |
| Cooldown | A failed or vetoed election can't be started again for the same person and post for 30 days. At most 3 elections run at once in a body |
| Vacancy | When a lead or the Chief of Mods leaves, Kira opens the seat's election herself: 24 hours of nominations, then the vote with everyone nominated. Nobody nominated: the seat stays open, and the tier above acts meanwhile. Kira never picks a candidate |
| Abuse of a free action | The tier above reverses it; a disagreement goes to its vote. A pattern is a recall |
| Emergency | Section 4.6. The Chief of Mods can still suspend a mod at once |
| Kira is down | The body may run the same vote as a Discord poll in its channel for 24 hours; Kira records the result when she is back |
#### Reminders, not nominations
Once a month in a group's channel, Kira says how to propose someone, only when the group has no lead or someone in it
meets a post's floor. When a seat opens, she posts once in the electorate's channel. Once a month in #council, she
lists privately the people who meet a floor. These are suggestions: only people start elections.
### 5.4 Exceptions
@@ -299,8 +389,8 @@ holder or an org owner removes GitHub access when the Team role ends.
### 5.6 Terms
- **Group leads** are confirmed every 6 months by a simple-majority poll. If someone else in the group passes the
floor and is nominated, both go on the same poll.
- **Group leads** are confirmed every 6 months by an election in their group. If someone else in the group passes the
floor and is nominated within its first 12 hours, both go on the same ballot.
- **Council and Team** have no fixed term. They stay as long as they are active and keep the council's trust. Removal
is always possible (section 4.7).
@@ -339,8 +429,9 @@ the design system:
- technical and design direction inside the area, when vanilla behaviour and the default look don't change;
- accepting or declining an idea or a proposal in the area. Any two active group members or one council member can
take that decision to the council;
- giving and removing the group's helper role, through Kira (a free action);
- how the group organises itself (threads, meetings, the channel's rules on top of the server's);
- asking the Team for reviews, adding `needs-proof`, and nominating people.
- asking the Team for reviews, adding `needs-proof`, and starting elections in the group.
### 6.4 What goes to the council
@@ -356,21 +447,28 @@ the design system:
The work goes on. The Team reviews and merges, and Kira still routes the group's issues and questions to its
channel. Until a lead is chosen, any council member may take a lead's decision for that group and says so in the
channel. Kira pins a "lead wanted" note with the floor. **No lead is better than a lead who doesn't do the work:**
channel. Kira posts once that the seat is open and how to start its election (section 5.3). **No lead is better than a lead who doesn't do the work:**
nobody is appointed just to fill the seat.
## 7. Moderation and appeals
- **The mods decide moderation matters** (council poll P41, imposed by the founder on 2026-11-10): who joins or
leaves the mod team, the mods' permissions and the staff channels, bans and unbans, and channel settings for
moderation. Everyday actions are free (section 2.1). Anything bigger is a mods' vote (`/vote body:mods`, simple
majority, 24 hours), and the Chief of Mods breaks ties. **The council keeps a veto:** within 24 hours of a mods'
decision, any council member can call a council poll, and a simple majority overturns it.
- **The server rules** are in #rules. Moderators enforce them, the Chief of Mods leads the mods, and the council can
change the rules (2/3).
- **Every action has a mod case**: who acted, what they did, and why. Kira keeps the cases.
- **First appeal:** within 14 days, through #appeal (for a quarantine) or mod mail. A moderator who wasn't involved,
or the Chief of Mods, answers within 72 hours.
- **Second appeal:** for bans, timeouts over 24 hours and quarantines, a council poll in #council (simple majority).
Members who were involved don't vote. The answer is final for 90 days.
- **Second appeal:** for bans, timeouts over 24 hours and quarantines, a mods' vote in #mod-chat. Mods who were
involved don't vote, and the council's veto applies. The answer is final for 90 days.
- **Not appealable here:** actions that Discord's rules or the law require. Those are reported where the law says.
- **Removing a moderator:** the Chief of Mods can suspend a moderator at once, and the council decides within 72 hours
(simple majority). The council removes the Chief of Mods the same way.
- **Removing a moderator:** the Chief of Mods can suspend a moderator at once, and the mods decide within 72 hours by
a recall vote. The mods recall the Chief of Mods the same way. The council can also remove either by poll.
- **Council members keep the ban permission** for emergencies and when no moderator is around. They log the ban like
any other, and the mods can reverse it by vote.
- **Staff are moderated like everyone.** When a council member is involved, the council decides without them.
## 8. Conflicts and hard cases
@@ -458,7 +556,9 @@ and the founder carries it out.
## 13. Transparency
- **#polls-and-decisions:** every poll and every result, posted by Kira, and the 24-hour discussions of nominations.
For polls that aren't about a person, each member's vote is shown once the poll closes.
For polls that aren't about a person, each member's vote is shown once the poll closes. The results of elections
and body votes are posted there too; for elections, only the result.
- **#staff-log:** the free actions Kira sees (roles given or taken, bans, unbans), so the tier above can check them.
- **The decisions log:** Kira keeps an append-only record of every poll, emergency action, appointment and
step-down, with its date and result. It is public and machine-readable, so the agents can check a decision there.
- **This document** lives in horizon-rust/horizon as `GOVERNANCE.md`. A short summary is pinned in #rules and in
+26
View File
@@ -358,3 +358,29 @@ state of Starling's `crates/horizon-client-render/src/touch.rs` at the same comm
`crates/horizon-client-render/src/android_runtime.rs` and `android_runtime/tests/` are adapted from the
input part of Starling's `crates/horizon-client-render/src/android_runtime.rs` at the same commit.
## PCG3D hash
`hash3` in `crates/horizon-client-render/src/hdr.wgsl`, the noise HDR10 output's dither is made from, is the
`pcg3d` hash of Mark Jarzynski and Marc Olano ("Hash Functions for GPU Rendering", Journal of Computer Graphics
Techniques 9(3), 2020), from <https://github.com/markjarzynski/PCG3D>. Copyright 2020 Mark Jarzynski & Marc Olano,
licensed under MIT:
```
Copyright 2020 Mark Jarzynski & Marc Olano
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
+95 -2
View File
@@ -70,6 +70,8 @@ horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline m
other one 30 000 characters long), flood-book (100 pages of 1024 characters
into a writable book), flood-sign (four 384-character lines on the block
below), flood-recipe (recipe book placements)
--ack-mode MODE chunk batch feedback: vanilla (default) or 64 (fixed chunks per tick);
one ACK per completed batch; use explore for a controlled pacing test
--flood N packets a tick for the flood behaviours; default 100
--attack NAME attack the player NAME twice a second, from wherever the bot is (a reach test),
swinging after each attack as vanilla's client does. NAME,NAME...: each of them
@@ -171,6 +173,8 @@ struct Options {
/// --crits: fight bots alternate jumped critical hits and sweeps at a sword's cooldown.
crits: bool,
flood: usize,
/// None uses vanilla estimation; --ack-mode 64 requests a fixed rate.
ack_rate: Option<f32>,
no_read: bool,
no_loaded: bool,
height: f64,
@@ -209,6 +213,7 @@ fn options() -> Result<Options, String> {
no_swing: false,
crits: false,
flood: 100,
ack_rate: None,
no_read: false,
no_loaded: false,
height: 24.0,
@@ -266,6 +271,13 @@ fn options() -> Result<Options, String> {
o.explore_speed = value.parse().map_err(|_| number("blocks a second"))?;
}
"--pvp" => o.pvp = value.parse().map_err(|_| number("true or false"))?,
"--ack-mode" => {
o.ack_rate = match value.as_str() {
"vanilla" => None,
"64" => Some(64.0),
_ => return Err(format!("--ack-mode {value}: use vanilla or 64")),
};
}
"--flood" => o.flood = value.parse().map_err(|_| number("packets a tick"))?,
"--attack" => o.attack = Some(value),
"--attack-after" => o.attack_after = value.parse().map_err(|_| number("seconds"))?,
@@ -950,6 +962,7 @@ fn read(
writer: Arc<Mutex<ConnWriter>>,
bot: Arc<Bot>,
track: bool,
ack_rate: Option<f32>,
mut capture: Option<Capture>,
) {
use ids::play::clientbound as cb;
@@ -1035,7 +1048,8 @@ fn read(
batch.finished(r.varint().unwrap_or(0));
send(
play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived {
chunks_per_tick: batch.desired_chunks_per_tick(),
chunks_per_tick: ack_rate
.unwrap_or_else(|| batch.desired_chunks_per_tick()),
})
.encode(),
)
@@ -1139,7 +1153,8 @@ fn run_bot(
let capture = (index == 0)
.then(|| o.capture.as_deref().and_then(Capture::create))
.flatten();
thread::spawn(move || read(reader, writer, bot, track, capture));
let ack_rate = o.ack_rate;
thread::spawn(move || read(reader, writer, bot, track, ack_rate, capture));
}
use ids::play::serverbound as sb;
// Wait for the spawn position.
@@ -1519,6 +1534,7 @@ fn main() {
"behaviour": o.behaviour,
"seed": o.seed,
"explore_speed": o.explore_speed,
"ack_mode": o.ack_rate.map_or("vanilla", |_| "64"),
"pvp": o.pvp,
"view_distance": o.view_distance,
"seconds": o.seconds,
@@ -1584,6 +1600,83 @@ mod tests {
AddEntity, Clientbound, MoveEntity, MoveEntityPos, RemoveEntities, SetEntityData, VecDelta,
};
/// Exercise the production reader over framed connections. Pings are barriers
/// so extra ACKs are observable without sleeps or timing guesses.
fn check_chunk_acks(ack_rate: Option<f32>) {
use horizon_protocol::connection::Pipe;
let (client, server) = Pipe::pair();
let (reader, writer) = Connection::local(client).split();
let mut server = Connection::local(server);
server
.reader
.set_read_timeout(Some(Duration::from_secs(2)))
.unwrap();
let bot = Arc::new(Bot::default());
bot.online.store(true, Ordering::SeqCst);
let handle = thread::spawn(move || {
read(
reader,
Arc::new(Mutex::new(writer)),
bot,
false,
ack_rate,
None,
)
});
for (nonce, size) in [0, 1, 5].into_iter().enumerate() {
server
.send(&raw(ids::play::clientbound::CHUNK_BATCH_START, |_| {}))
.unwrap();
server
.send(&raw(ids::play::clientbound::PING, |w| w.i32(nonce as i32)))
.unwrap();
let (id, body) = server.recv().unwrap();
assert_eq!(
id,
ids::play::serverbound::PONG,
"batch start must not send an ACK"
);
assert_eq!(Reader::new(&body).i32().unwrap(), nonce as i32);
server
.send(&raw(ids::play::clientbound::CHUNK_BATCH_FINISHED, |w| {
w.varint(size)
}))
.unwrap();
server
.send(&raw(ids::play::clientbound::PING, |w| w.i32(nonce as i32)))
.unwrap();
let (id, body) = server.recv().unwrap();
assert_eq!(id, ids::play::serverbound::CHUNK_BATCH_RECEIVED);
let rate = Reader::new(&body).f32().unwrap();
if let Some(fixed) = ack_rate {
assert_eq!(rate, fixed);
} else if size == 0 {
assert_eq!(rate, 3.5, "vanilla initial rate must remain the default");
} else {
assert!(rate.is_finite() && rate > 0.0);
}
let (id, body) = server.recv().unwrap();
assert_eq!(
id,
ids::play::serverbound::PONG,
"exactly one ACK per finished batch"
);
assert_eq!(Reader::new(&body).i32().unwrap(), nonce as i32);
}
server.writer.shutdown();
handle.join().unwrap();
}
#[test]
fn fixed_64_ack_is_sent_once_per_finished_batch() {
check_chunk_acks(Some(64.0));
}
#[test]
fn vanilla_acks_remain_once_per_finished_batch() {
check_chunk_acks(None);
}
fn feed(entities: &mut Entities, packet: &Clientbound) {
let bytes = packet.encode();
let mut r = Reader::new(&bytes);
@@ -514,6 +514,34 @@ pub fn name_text(tag: &Tag) -> Text {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nested_fallback_references_stay_bounded() {
// 300 references to the argument, nested three deep: 27 million copies of "A" from a
// 4 KB component, which ran a client out of memory.
let bomb = |depth: usize, text: &str| {
let pattern = "%1$s".repeat(300);
let mut v = serde_json::json!({ "text": text });
for _ in 0..depth {
v = serde_json::json!({"translate": "x.unknown", "fallback": pattern, "with": [v]});
}
v
};
let started = std::time::Instant::now();
let text = to_text(&bomb(3, "A"), &mut |s| Text::literal(s));
assert!(text.spans.len() < 1 << 15, "{} spans", text.spans.len());
// One long argument referenced many times multiplies bytes, not spans.
let long = "B".repeat(64 << 10);
let text = to_text(&bomb(1, &long), &mut |s| Text::literal(s));
let bytes: usize = text.spans.iter().map(|s| s.text.len()).sum();
assert!(bytes <= 4 << 20, "{bytes} bytes");
assert!(started.elapsed() < std::time::Duration::from_secs(5));
// A real fallback still formats.
let ok = serde_json::json!({
"translate": "x.unknown", "fallback": "%1$s and %1$s", "with": [{"text": "A"}]
});
assert_eq!(to_text(&ok, &mut |s| Text::literal(s)).plain(), "A and A");
}
use crate::lang::{self, Language, ResourceSource};
struct Mem(std::collections::HashMap<String, Vec<u8>>);
+172 -37
View File
@@ -74,11 +74,70 @@ pub trait ResourceSource {
vec!["minecraft".into()]
}
}
/// The bundled file a language reads, and whether it drops `ß`: a regional variant reads its
/// language's file (Swiss German writes "ss" for "ß", as vanilla's de_ch does).
fn bundled_code(code: &str) -> (&str, bool) {
match code {
"ko" => ("ko_kr", false),
"hr" => ("hr_hr", false),
"de_at" => ("de_de", false),
"de_ch" => ("de_de", true),
"fr_ca" | "fr_ch" => ("fr_fr", false),
"es_ar" | "es_cl" | "es_ec" | "es_mx" | "es_uy" | "es_ve" => ("es_es", false),
code => (code, false),
}
}
/// Lang files crates above the engine ship (`horizon_hooks::lang`), each a list of
/// (code, JSON) pairs. The game's entry installs them once, before any language loads.
static CRATE_FILES: std::sync::OnceLock<&'static [&'static [(&'static str, &'static str)]]> =
std::sync::OnceLock::new();
/// Installs the crates' lang files (`horizon_hooks::lang::engine::all()`). Only the first call
/// counts.
pub fn install_crate_files(files: &'static [&'static [(&'static str, &'static str)]]) {
let _ = CRATE_FILES.set(files);
}
/// The crates' entries for language `code` (through [`bundled_code`]'s variants) that the
/// engine's own `horizon` file for it doesn't have: on a key both have, the engine wins.
fn read_crate_files(files: &[&[(&str, &str)]], code: &str, map: &mut HashMap<String, String>) {
if files.is_empty() {
return;
}
let (file, swiss) = bundled_code(code);
let mut own = HashMap::new();
if let Some(bytes) = Bundled.read(&format!("assets/horizon/lang/{code}.json")) {
read_lang_file(&bytes, &mut own);
}
for (c, json) in files.iter().flat_map(|f| f.iter()) {
if *c != file {
continue;
}
let mut theirs = HashMap::new();
if swiss {
read_lang_file(json.replace('ß', "ss").as_bytes(), &mut theirs);
} else {
read_lang_file(json.as_bytes(), &mut theirs);
}
for (key, value) in theirs {
if !own.contains_key(&key) {
map.insert(key, value);
}
}
}
}
/// Horizon's own strings, compiled in so they need no prepared resources.
struct Bundled;
impl ResourceSource for Bundled {
fn read(&self, path: &str) -> Option<Vec<u8>> {
let body = match path {
let code = path
.strip_prefix("assets/horizon/lang/")?
.strip_suffix(".json")?;
let (file, swiss) = bundled_code(code);
let path = format!("assets/horizon/lang/{file}.json");
let body = match path.as_str() {
"assets/horizon/lang/en_us.json" => {
include_str!("../../horizon-client/assets/horizon/lang/en_us.json")
}
@@ -103,10 +162,10 @@ impl ResourceSource for Bundled {
"assets/horizon/lang/tr_tr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/tr_tr.json")
}
"assets/horizon/lang/ko_kr.json" | "assets/horizon/lang/ko.json" => {
"assets/horizon/lang/ko_kr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/ko_kr.json")
}
"assets/horizon/lang/hr_hr.json" | "assets/horizon/lang/hr.json" => {
"assets/horizon/lang/hr_hr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/hr_hr.json")
}
"assets/horizon/lang/pt_pt.json" => {
@@ -331,30 +390,20 @@ impl ResourceSource for Bundled {
"assets/horizon/lang/vec_it.json" => {
include_str!("../../horizon-client/assets/horizon/lang/vec_it.json")
}
"assets/horizon/lang/de_de.json" | "assets/horizon/lang/de_at.json" => {
"assets/horizon/lang/de_de.json" => {
include_str!("../../horizon-client/assets/horizon/lang/de_de.json")
}
// Swiss German writes "ss" for "ß", as vanilla's de_ch does.
"assets/horizon/lang/de_ch.json" => {
let de = include_str!("../../horizon-client/assets/horizon/lang/de_de.json");
return Some(de.replace('ß', "ss").into_bytes());
}
"assets/horizon/lang/fr_fr.json"
| "assets/horizon/lang/fr_ca.json"
| "assets/horizon/lang/fr_ch.json" => {
"assets/horizon/lang/fr_fr.json" => {
include_str!("../../horizon-client/assets/horizon/lang/fr_fr.json")
}
"assets/horizon/lang/es_es.json"
| "assets/horizon/lang/es_ar.json"
| "assets/horizon/lang/es_cl.json"
| "assets/horizon/lang/es_ec.json"
| "assets/horizon/lang/es_mx.json"
| "assets/horizon/lang/es_uy.json"
| "assets/horizon/lang/es_ve.json" => {
"assets/horizon/lang/es_es.json" => {
include_str!("../../horizon-client/assets/horizon/lang/es_es.json")
}
_ => return None,
};
if swiss {
return Some(body.replace('ß', "ss").into_bytes());
}
Some(body.as_bytes().to_vec())
}
fn namespaces(&self) -> Vec<String> {
@@ -438,6 +487,16 @@ impl Language {
/// from every namespace and every source in priority order (later sources
/// override).
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
let crate_files = CRATE_FILES.get().copied().unwrap_or_default();
Self::load_with(sources, code, crate_files)
}
/// [`Language::load`] with these crates' lang files.
fn load_with(
sources: &[&dyn ResourceSource],
code: &str,
crate_files: &[&[(&str, &str)]],
) -> Self {
let mut map = HashMap::new();
let mut codes = vec![DEFAULT];
if code != DEFAULT {
@@ -453,12 +512,14 @@ impl Language {
sources.iter().flat_map(|s| s.namespaces()).collect();
for c in codes {
for namespace in &namespaces {
for source in sources {
let Some(bytes) = source.read(&format!("assets/{namespace}/lang/{c}.json"))
else {
continue;
};
read_lang_file(&bytes, &mut map);
for (i, source) in sources.iter().enumerate() {
if let Some(bytes) = source.read(&format!("assets/{namespace}/lang/{c}.json")) {
read_lang_file(&bytes, &mut map);
}
// The crates' text right after the engine's own (`Bundled`, the first source).
if i == 0 && namespace == "horizon" {
read_crate_files(crate_files, c, &mut map);
}
}
}
}
@@ -688,6 +749,43 @@ mod tests {
);
}
#[test]
fn a_crates_text_loads_after_the_engines_and_before_packs() {
static CRATE: &[(&str, &str)] = &[
(
"en_us",
r#"{"test.crate.hello": "Hello", "horizon.osk.close": "Shut", "test.crate.packed": "Crate"}"#,
),
(
"de_de",
r#"{"test.crate.hello": "Grüß dich", "horizon.osk.close": "Zu"}"#,
),
("fr_fr", r#"{"test.crate.hello": "Bonjour"}"#),
];
let pack = Mem(HashMap::from([(
"assets/horizon/lang/en_us.json".to_owned(),
br#"{"test.crate.packed": "Pack"}"#.to_vec(),
)]));
let load = |code| Language::load_with(&[&pack], code, &[CRATE]);
let en = load("en_us");
assert_eq!(en.get("test.crate.hello"), Some("Hello"));
// The engine's own file wins on a key both have; a pack wins over both.
assert_eq!(en.get("horizon.osk.close"), Some("Close"));
assert_eq!(en.get("test.crate.packed"), Some("Pack"));
let de = load("de_de");
assert_eq!(de.get("test.crate.hello"), Some("Grüß dich"));
assert_eq!(de.get("horizon.osk.close"), Some("Schließen"));
// Regional variants read their language's file, as the engine's do.
assert_eq!(load("de_ch").get("test.crate.hello"), Some("Grüss dich"));
assert_eq!(load("fr_ca").get("test.crate.hello"), Some("Bonjour"));
// A language the crate lacks falls back to its English.
assert_eq!(load("pl_pl").get("test.crate.hello"), Some("Hello"));
// Without crate files, nothing changes.
let plain = Language::load_with(&[&pack], "de_de", &[]);
assert_eq!(plain.get("test.crate.hello"), None);
assert_eq!(plain.len() + 1, de.len());
}
#[test]
fn a_scoped_language_is_the_calling_threads_and_reports_what_it_lacks() {
let empty = Mem(HashMap::new());
@@ -739,6 +837,20 @@ mod tests {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../horizon-client/assets/horizon/lang")
}
/// The crates whose own lang files the game loads (`crates/<name>/assets/lang`,
/// registered through `horizon_hooks::lang`), with that folder.
fn crate_lang_dirs() -> Vec<(String, std::path::PathBuf)> {
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut dirs: Vec<_> = std::fs::read_dir(&crates)
.unwrap()
.flatten()
.map(|e| (e.file_name().into_string().unwrap(), e.path()))
.map(|(name, path)| (name, path.join("assets/lang")))
.filter(|(_, dir)| dir.join("en_us.json").is_file())
.collect();
dirs.sort();
dirs
}
/// The keys of a flat bundled file in file order, duplicates included (a map
/// would keep only the last of two equal keys). One `"key": "value"` per line.
fn file_keys(body: &str) -> Vec<String> {
@@ -776,11 +888,33 @@ mod tests {
#[test]
fn bundled_files_are_served_and_have_no_stale_or_repeated_keys() {
let dir = bundled_dir();
let engine = check_lang_dir(&bundled_dir(), true);
assert!(
engine.1 >= 7,
"found {} bundled lang files in {}",
engine.1,
bundled_dir().display()
);
// A crate's files pass the same checks. Its keys are its own: on a key the engine's
// files also have, the engine's text would win and hide the crate's.
for (name, dir) in crate_lang_dirs() {
let (en, _) = check_lang_dir(&dir, false);
for key in en.keys() {
assert!(
!engine.0.contains_key(key),
"{name}: {key} is also the engine's"
);
}
}
}
/// The checks every lang folder passes: flat maps, no repeated key, no key en_us lacks, the
/// same placeholders as English, no empty text. Its en_us and how many files it has.
fn check_lang_dir(dir: &std::path::Path, bundled: bool) -> (HashMap<String, String>, usize) {
let en_body = std::fs::read_to_string(dir.join("en_us.json")).unwrap();
let en: HashMap<String, String> = serde_json::from_str(&en_body).unwrap();
let mut seen = 0;
for entry in std::fs::read_dir(&dir).unwrap().flatten() {
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let name = entry.file_name().into_string().unwrap();
let Some(code) = name.strip_suffix(".json") else {
continue;
@@ -789,7 +923,7 @@ mod tests {
// A file that Bundled::read does not name is never loaded.
let path = format!("assets/horizon/lang/{name}");
assert!(
Bundled.read(&path).is_some(),
!bundled || Bundled.read(&path).is_some(),
"{name} is not served by Bundled"
);
let body = std::fs::read_to_string(entry.path()).unwrap();
@@ -815,11 +949,7 @@ mod tests {
assert!(!value.trim().is_empty(), "{code}: {key} is empty");
}
}
assert!(
seen >= 7,
"found {seen} bundled lang files in {}",
dir.display()
);
(en, seen)
}
#[test]
@@ -834,10 +964,10 @@ mod tests {
}
}
}
let en: HashMap<String, String> = serde_json::from_str(
&std::fs::read_to_string(bundled_dir().join("en_us.json")).unwrap(),
)
.unwrap();
let english = |dir: &std::path::Path| -> HashMap<String, String> {
serde_json::from_str(&std::fs::read_to_string(dir.join("en_us.json")).unwrap()).unwrap()
};
let mut en = english(&bundled_dir());
let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut files = Vec::new();
for krate in [
@@ -847,6 +977,11 @@ mod tests {
] {
rust_files(&crates.join(krate).join("src"), &mut files);
}
// A crate that ships lang files names its keys in its own sources.
for (name, dir) in crate_lang_dirs() {
en.extend(english(&dir));
rust_files(&crates.join(name).join("src"), &mut files);
}
assert!(files.len() > 100, "found only {} sources", files.len());
let mut found = 0;
for file in files {
+19 -1
View File
@@ -529,10 +529,13 @@ impl Team {
None => t,
}
}
/// `PlayerTeam.getFormattedDisplayName`.
/// `PlayerTeam.getFormattedDisplayName`: the display name in the team's
/// `displayNameStyle`, which its constructor makes the team's name on hover
/// (`ShowText`) and as insertion.
pub fn formatted_display_name(&self) -> Text {
let inner = hover_name(comp_text(&self.display_name), &self.name).with_style(&Style {
click: None,
insertion: Some(self.name.clone()),
..Style::default()
});
self.apply_color(bracketed(inner))
@@ -1411,6 +1414,21 @@ fn finish(node: &mut serde_json::Map<String, Value>, extra: Vec<Comp>) -> Comp {
#[cfg(test)]
mod tests {
use super::*;
/// #14279: `PlayerTeam`'s `displayNameStyle` puts the team's name on hover
/// and as insertion; `getFormattedDisplayName` brackets the name in it.
#[test]
fn a_teams_formatted_name_inserts_the_team_name() {
let team = Team::new("reds");
let c = team.formatted_display_name().component();
assert_eq!(c["translate"], "chat.square_brackets");
let inner = &c["with"][0];
assert_eq!(inner["text"], "reds");
assert_eq!(inner["insertion"], "reds");
assert_eq!(inner["hover_event"]["action"], "show_text");
// `{"text":"reds"}` or its short form `"reds"`: the same component.
let value = &inner["hover_event"]["value"];
assert!(value == "reds" || value["text"] == "reds", "{value}");
}
fn board() -> Scoreboard {
let mut sb = Scoreboard::default();
+70 -12
View File
@@ -282,17 +282,20 @@ impl Text {
pub fn push(&mut self, other: impl Into<Text>) {
let other = other.into();
let sibling = other.component();
let mut root = if self.spans.is_empty() && self.source.is_none() {
json!({ "text": "" })
} else {
let c = self.component();
if STYLE_KEYS.iter().any(|k| c.get(*k).is_some()) {
json!({ "text": "", "extra": [c] })
} else {
c
}
// The tree is appended to in place: cloning all of it on every append made a component
// with N siblings (a server's chat or MOTD "extra") cost N^2.
let root = match self.source.take() {
None if self.spans.is_empty() => std::sync::Arc::new(json!({ "text": "" })),
None => std::sync::Arc::new(self.component()),
Some(c) => c,
};
if let Value::Object(o) = &mut root {
let mut root = if STYLE_KEYS.iter().any(|k| root.get(*k).is_some()) {
let c = std::sync::Arc::try_unwrap(root).unwrap_or_else(|c| (*c).clone());
std::sync::Arc::new(json!({ "text": "", "extra": [c] }))
} else {
root
};
if let Value::Object(o) = std::sync::Arc::make_mut(&mut root) {
match o.get_mut("extra") {
Some(Value::Array(a)) => a.push(sibling),
_ => {
@@ -300,7 +303,7 @@ impl Text {
}
}
}
self.source = Some(root.into());
self.source = Some(root);
self.spans.extend(other.spans);
}
/// Apply `style` underneath every span (MutableComponent.withStyle on a parent).
@@ -671,11 +674,22 @@ pub fn legacy_format(style: &Style, code: char, reset: &Style) -> Style {
s
}
/// The most spans one translation expands to. Vanilla's `TranslatableContents.decompose` keeps
/// references to its arguments, so its cost stays linear in the input; copying them here makes
/// nested `%1$s` templates multiply (`k` references nested `D` deep: `k^D` copies), and a server's
/// `fallback` template is any text it likes.
const MAX_TRANSLATION_SPANS: usize = 1 << 15;
/// The most text one translation expands to: one long argument referenced many times multiplies
/// bytes, not spans.
const MAX_TRANSLATION_BYTES: usize = 1 << 22;
/// TranslatableContents.decomposeTemplate: `%s` takes the next argument,
/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are
/// shown verbatim.
/// shown verbatim, and so is one that would expand past [`MAX_TRANSLATION_SPANS`] or
/// [`MAX_TRANSLATION_BYTES`].
pub fn format_translation(template: &str, args: &[Text]) -> Text {
let mut out = Text::default();
let mut bytes = 0usize;
let mut literal = String::new();
let mut next = 0usize;
let chars: Vec<char> = template.chars().collect();
@@ -725,6 +739,14 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text {
let Some(arg) = args.get(index) else {
return Text::literal(template);
};
bytes = bytes
.saturating_add(literal.len())
.saturating_add(arg.spans.iter().map(|s| s.text.len()).sum());
if out.spans.len().saturating_add(arg.spans.len()) >= MAX_TRANSLATION_SPANS
|| bytes > MAX_TRANSLATION_BYTES
{
return Text::literal(template);
}
if !literal.is_empty() {
out.spans.push(Span {
text: std::mem::take(&mut literal),
@@ -750,6 +772,42 @@ pub fn format_translation(template: &str, args: &[Text]) -> Text {
mod tests {
use super::*;
#[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.
let mut styled = Text::literal("a").with_style(&Style {
bold: Some(true),
..Style::default()
});
styled.push(Text::literal("b"));
let before = styled.clone();
styled.push(Text::literal("c"));
assert_eq!(
styled.component(),
json!({"text": "", "extra": [{"text": "a", "bold": true}, {"text": "b"}, {"text": "c"}]})
);
assert_eq!(
before.component(),
json!({"text": "", "extra": [{"text": "a", "bold": true}, {"text": "b"}]})
);
let mut plain = Text::default();
plain.push(Text::literal("x"));
plain.push(Text::literal("y"));
assert_eq!(
plain.component(),
json!({"text": "", "extra": [{"text": "x"}, {"text": "y"}]})
);
// 20 000 siblings, as a server's chat may carry: 76 s before, as each append cloned the
// whole tree.
let started = std::time::Instant::now();
let mut long = Text::default();
for _ in 0..20_000 {
long.push(Text::literal("a"));
}
assert_eq!(long.spans.len(), 20_000);
assert!(started.elapsed() < std::time::Duration::from_secs(5));
}
#[test]
fn click_events_serialize_and_inherit_as_one_style_field() {
for (event, json) in [
(
+3
View File
@@ -27,6 +27,9 @@ 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" }
# 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"
horizon-hdr = { path = "../horizon-hdr" }
horizon-world = { path = "../horizon-world" }
horizon-protocol = { path = "../horizon-protocol" }
+58 -2
View File
@@ -6,7 +6,12 @@ use horizon_world::{
worldgen::{tags::TagDefinitions, terrain::TerrainBlockStates},
};
use serde_json::Value;
use std::{collections::BTreeSet, io, path::Path, sync::Arc};
use std::{
collections::BTreeSet,
io,
path::Path,
sync::{Arc, Mutex},
};
pub const MATERIALS: [&str; 6] = ["bedrock", "dirt", "stone", "sand", "oak_planks", "bricks"];
#[derive(Clone, Copy)]
@@ -182,6 +187,23 @@ static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
/// Every block registry [`Assets::load`] has handed out, one per distinct
/// content. Callers keep `&'static` references, so a registry is never freed;
/// loading equal data again (tests load the same root once per fixture)
/// returns the one already leaked instead of leaking another (about 11 MB for
/// vanilla).
static REGISTRIES: Mutex<Vec<&'static BlockRegistry>> = Mutex::new(Vec::new());
/// `registry` leaked, or the equal one leaked before it.
fn intern_registry(registry: BlockRegistry) -> &'static BlockRegistry {
let mut leaked = REGISTRIES.lock().unwrap_or_else(|e| e.into_inner());
if let Some(&same) = leaked.iter().find(|&&known| *known == registry) {
return same;
}
let registry: &'static BlockRegistry = Box::leak(Box::new(registry));
leaked.push(registry);
registry
}
impl Assets {
pub fn load(root: &Path) -> Result<Self> {
let manifest: Value = horizon_world::json_file::read(&root.join("horizon-resources.json"))?;
@@ -256,7 +278,7 @@ impl Assets {
// Chunks hold every state of this registry: content mods can take it
// past vanilla's 16-bit global palette.
crate::chunk::set_block_states(registry.len());
let registry: &'static BlockRegistry = Box::leak(Box::new(registry));
let registry = intern_registry(registry);
Ok(Self {
registry,
properties,
@@ -320,6 +342,16 @@ impl RenderAssets {
}
None => crate::model_library::ParsedModels::default(),
};
// Connected-texture rules find their faces by sprite layer: what they match by name keeps a
// layer of its own, decided before the models insert their textures.
let ctm_rules = if draws {
horizon_optifine::ctm::load(root)
} else {
Vec::new()
};
sprites.keep_apart(crate::connected::ConnectedTextures::matched_sprites(
&ctm_rules,
));
let mut models = if draws {
let _step = crate::spans::startup::step("core.models_bake");
crate::models::prepare_with_models(root, registry, &mut sprites, &parsed)?
@@ -359,6 +391,7 @@ impl RenderAssets {
let mut found = Vec::new();
crate::connected::ConnectedTextures::load(
root,
ctm_rules,
registry,
&mut sprites,
|state, face| {
@@ -496,6 +529,29 @@ mod tests {
));
}
#[test]
fn equal_registries_are_leaked_once() {
use horizon_world::registry::BlockRegistry;
let registry = |extra: &str| {
let facts = format!(
r#"{{"defaults":{{"minecraft:air":0,"fixture:{extra}":1}},"states":[
["air",true,false,"","minecraft:air"],
["{extra}",false,false,"","fixture:{extra}"]
]}}"#
);
BlockRegistry::from_facts_json(facts.as_bytes()).unwrap()
};
let first = super::intern_registry(registry("interned_once"));
let again = super::intern_registry(registry("interned_once"));
let other = super::intern_registry(registry("interned_other"));
assert!(std::ptr::eq(first, again), "equal content leaked twice");
assert!(!std::ptr::eq(first, other), "different content shared");
assert_eq!(
other.default_state("fixture:interned_other"),
Some(horizon_world::registry::BlockStateId(1))
);
}
#[test]
fn sprite_pixels_come_back_the_same_once_packed() {
// Two layers of 16x16 RGBA with some structure, as sprites have.
+61 -1
View File
@@ -7,7 +7,7 @@ use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
path::Path,
sync::Arc,
sync::{Arc, OnceLock},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -398,7 +398,37 @@ impl Biomes {
pub fn contains(&self, name: &str) -> bool {
self.index.contains_key(name)
}
/// The biome at `id`, clamped to the last entry when `id` is past the
/// table (a stale column from an older registry keeps its id).
///
/// When the table is empty (a resource pack with no biome files), returns
/// a shared default plains biome instead of panicking on `list.len() - 1`.
pub fn get(&self, id: u16) -> &BiomeInfo {
if self.list.is_empty() {
static DEFAULT: OnceLock<BiomeInfo> = OnceLock::new();
return DEFAULT.get_or_init(|| BiomeInfo {
spawns: HashMap::new(),
spawn_costs: HashMap::new(),
creature_probability: 0.0,
increased_fire_burnout: false,
name: "minecraft:plains".to_owned(),
temperature: 0.8,
frozen: false,
downfall: 0.4,
precipitation: false,
grass: 0x7f_c0_55,
modifier: GrassModifier::None,
foliage: 0x6a_ab_37,
dry_foliage: 0x79_75_54,
water: 0x3f_76_e4,
sky: None,
fog: None,
water_fog: 0x3f_76_e4,
ambient_particles: Vec::new(),
features: Vec::new(),
attributes: Default::default(),
});
}
&self.list[usize::from(id).min(self.list.len() - 1)]
}
/// The name of biome `id`, plains (as for an unknown name) when the id is
@@ -795,4 +825,34 @@ mod blend_tests {
}
assert!(at(-2.0) > 0.0 && at(-2.0) < 0.5);
}
/// An empty biome table (a resource pack with no biome files) must not
/// panic on `get`: before the fix, `list.len() - 1` underflowed.
#[test]
fn get_on_empty_biome_table_returns_default_instead_of_panicking() {
use std::sync::Arc;
let empty = Biomes {
builtin: Arc::new(Vec::new()),
index: HashMap::new(),
list: Vec::new(),
info_noise: SimplexNoise::with_skipped_offsets(&mut LegacyRandom::new(2345), true),
colormaps: Arc::new(Colormaps {
grass: Vec::new(),
foliage: Vec::new(),
dry: Vec::new(),
}),
packs: BTreeMap::new(),
};
// Any id returns the shared default plains biome, no panic.
let b = empty.get(0);
assert_eq!(b.name, "minecraft:plains");
let b = empty.get(65535);
assert_eq!(b.name, "minecraft:plains");
// Colours and temperature come from the default.
assert_eq!(b.temperature, 0.8);
assert_eq!(b.grass, 0x7f_c0_55);
assert_eq!(b.foliage, 0x6a_ab_37);
assert_eq!(b.water, 0x3f_76_e4);
}
}
+100
View File
@@ -84,6 +84,71 @@ pub fn contents_effects(stack: &ItemStack) -> Vec<(&'static str, i32, i32)> {
)
.collect()
}
/// `PotionContents.getAllEffects`, retaining each custom instance's flags.
pub fn contents_instances(stack: &ItemStack) -> Vec<crate::effects::EffectInstance> {
use horizon_client_core::nbt_value::{number, text};
use horizon_world::nbt::Tag;
let mut effects: Vec<_> = stack
.potion()
.and_then(potion)
.map_or(&[][..], |p| p.effects)
.iter()
.map(|(id, duration, amp)| crate::effects::EffectInstance::new(id, *duration, *amp))
.collect();
if let Some((_, Tag::List(custom))) = stack
.data()
.and_then(|d| d.potion_extra.iter().find(|(k, _)| k == "custom_effects"))
{
for e in custom {
let Some(def) = text(e.get("id")).and_then(|id| effect(&id)) else {
continue;
};
let mut instance = crate::effects::EffectInstance::new(
def.id,
number(e.get("duration")).unwrap_or(0) as i32,
number(e.get("amplifier")).unwrap_or(0).clamp(0, 255) as i32,
);
instance.ambient = number(e.get("ambient")).unwrap_or(0) != 0;
instance.visible = number(e.get("show_particles")) != Some(0);
effects.push(instance);
}
}
effects
}
/// `PotionContents.getColor`: an explicit colour wins; otherwise mix only
/// visible base and custom effects, with their amplifier weights.
pub fn contents_color(stack: &ItemStack) -> u32 {
use horizon_client_core::nbt_value::number;
if let Some(color) = stack
.data()
.and_then(|d| d.potion_extra.iter().find(|(k, _)| k == "custom_color"))
.and_then(|(_, v)| number(Some(v)))
{
return color as u32;
}
0xFF00_0000
| horizon_client_core::potions::effects_color(
contents_instances(stack)
.iter()
.filter(|e| e.visible)
.map(|e| (e.id, e.amplifier)),
)
}
/// `PotionContents.equals(EMPTY)`: colour and custom name also make contents
/// nonempty, even when there is no registered potion or custom effect.
pub fn contents_empty(stack: &ItemStack) -> bool {
use horizon_world::nbt::Tag;
stack.potion().is_none()
&& stack.data().is_none_or(|d| {
d.potion_extra
.iter()
.all(|(key, value)| match key.as_str() {
"custom_effects" => matches!(value, Tag::List(list) if list.is_empty()),
"custom_color" | "custom_name" => false,
_ => true,
})
})
}
/// Roman amplifier suffix (`potion.potency.N`) and duration lines of a potion.
pub fn tooltip(
potion: Option<&str>,
@@ -706,4 +771,39 @@ mod tests {
let lines = effect_lines([("minecraft:resistance", 15, 0)], 1.0, &translate);
assert_eq!(lines[0].0, "resistance");
}
#[test]
fn custom_contents_color_and_empty_semantics() {
use horizon_world::nbt::Tag;
let mut stack = ItemStack::new("minecraft:tipped_arrow", 1);
assert!(contents_empty(&stack));
stack
.data_mut()
.potion_extra
.push(("custom_effects".into(), Tag::List(Vec::new())));
assert!(contents_empty(&stack));
stack.data_mut().potion_extra = vec![(
"custom_effects".into(),
Tag::List(vec![
Tag::compound([
("id", Tag::String("minecraft:glowing".into())),
("amplifier", Tag::Int(1)),
]),
Tag::compound([
("id", Tag::String("minecraft:poison".into())),
("show_particles", Tag::Byte(0)),
]),
]),
)];
assert!(!contents_empty(&stack));
// Glowing's colour; hidden poison contributes no weight.
assert_eq!(contents_color(&stack), 0xFF94_A061);
stack
.data_mut()
.potion_extra
.push(("custom_color".into(), Tag::Int(123456)));
assert_eq!(contents_color(&stack), 123456);
stack.data_mut().potion_extra = vec![("custom_name".into(), Tag::String("test".into()))];
assert!(!contents_empty(&stack));
assert_eq!(contents_color(&stack), 0xFF38_5DC6);
}
}
+10 -1
View File
@@ -1974,7 +1974,11 @@ impl ChatScreen {
return false;
}
let max = l.list.len().saturating_sub(self.layout.line_limit) as i32;
l.offset = ((l.offset as f64 - amount.clamp(-1.0, 1.0)) as i32).clamp(0, max) as usize;
// Round instead of truncating: touchpad/PixelDelta produces fractional
// amounts and truncation drops movement in one direction (#14338).
l.offset = (l.offset as f64 - amount.clamp(-1.0, 1.0))
.round()
.clamp(0.0, max as f64) as usize;
true
}
/// `CommandSuggestions.formatText`: argument colours over the input. The
@@ -2086,6 +2090,11 @@ impl ChatScreen {
) {
let limit = l.list.len().min(self.layout.line_limit);
let [rx, ry, rw, rh] = l.rect;
// SuggestionsList.extractRenderState: the whole list asks for the
// pointing hand while the pointer is inside its rectangle.
if mouse.0 >= rx && mouse.0 < rx + rw && mouse.1 >= ry && mouse.1 < ry + rh {
crate::widgets::request_cursor(crate::widgets::Cursor::PointingHand);
}
let has_prev = l.offset > 0;
let has_next = l.list.len() > l.offset + limit;
let moved = l.last_mouse != mouse;
@@ -1066,3 +1066,32 @@ fn a_server_filter_mask_hides_or_masks_the_message() {
.all(|s| s.style.color.is_none())
);
}
/// `SuggestionsList.extractRenderState`: the list's rectangle asks for the
/// pointing hand; outside it the cursor stays the arrow.
#[test]
fn the_suggestion_list_asks_for_the_pointing_hand() {
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, "/");
let rect = screen
.suggestions
.as_ref()
.expect("the root commands are a suggestion list")
.rect;
let _ = crate::widgets::take_cursor();
screen.draw(&m, (rect[0] + 2, rect[1] + 2), 0, 0);
assert_eq!(
crate::widgets::take_cursor(),
crate::widgets::Cursor::PointingHand
);
let _ = crate::widgets::take_cursor();
screen.draw(&m, (rect[0] - 1, rect[1] + 2), 0, 0);
assert_eq!(crate::widgets::take_cursor(), crate::widgets::Cursor::Arrow);
}
@@ -539,6 +539,7 @@ pub struct Data {
pub current: Option<Info>,
pub travel: i32,
pub selector: Selector,
pub reload_particle: bool,
}
/// Which sculk block entity this is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+48 -3
View File
@@ -124,15 +124,25 @@ fn sprite_name(resource: &str) -> String {
}
impl ConnectedTextures {
/// The rules under `root`, with their tiles inserted into `sprites` (before it finishes).
/// `face_layer` answers a block state's sprite on a side, for rules that connect by tile.
/// The sprites `rules` match by name (`matchTiles`, `connectTiles`), for
/// [`Sprites::keep_apart`]: before the models insert theirs.
pub fn matched_sprites(rules: &[Rule]) -> Vec<String> {
(rules.iter())
.flat_map(|r| r.match_tiles.iter().chain(&r.connect_tiles))
.map(|t| sprite_name(t))
.collect()
}
/// `rules` (`ctm::load` under `root`), with their tiles inserted into `sprites` (before it
/// finishes). `face_layer` answers a block state's sprite on a side, for rules that connect
/// by tile.
pub fn load(
root: &Path,
mut rules: Vec<Rule>,
registry: &BlockRegistry,
sprites: &mut Sprites,
mut face_layer: impl FnMut(BlockStateId, Face) -> Option<u32>,
) -> Self {
let mut rules = ctm::load(root);
// Rules with a custom name load no tiles: section meshes see no block entity.
rules.retain(|r| r.name.is_none());
// Rule indices are `u16`.
@@ -1270,6 +1280,41 @@ mod tests {
assert!(!ctm.stacked_pane_hides(3, 3, post));
}
#[test]
fn rules_name_the_sprites_they_match() {
// `matchTiles` among the textures and beside the file (a chain onto another rule's
// tile), and `connectTiles`: each as the sprite name the textures and tiles are inserted
// under.
let dir = "assets/minecraft/optifine/ctm/pack/crops";
let rule = |file: &str, text: &str| {
Rule::parse(
&format!("{dir}/{file}"),
&horizon_optifine::properties::Properties::parse(text),
)
.unwrap()
.unwrap()
};
let rules = [
rule(
"1.properties",
"matchTiles=./19.png\nmethod=random\ntiles=5-6",
),
rule(
"2.properties",
"matchTiles=textures/block/extra/placeholder.png\nmethod=overlay\n\
connectTiles=textures/block/stone.png\ntiles=0-16",
),
];
assert_eq!(
ConnectedTextures::matched_sprites(&rules),
[
format!("{dir}/19.png"),
"minecraft:block/extra/placeholder".to_owned(),
"minecraft:block/stone".to_owned(),
]
);
}
#[test]
fn sprite_names() {
assert_eq!(
@@ -1,6 +1,7 @@
//! Data packs (`<world>/datapacks`: folders and zips with `pack.mcmeta`) and
//! the parts of them commands use: `.mcfunction` functions (with macros and
//! line continuation), function tags and predicates.
mod slot_sources;
use crate::zip::Zip;
use horizon_world::{
nbt::Tag,
@@ -663,6 +664,8 @@ pub struct DataStore {
pub item_modifiers: BTreeMap<String, serde_json::Value>,
/// `slot_source` definitions, evaluated against a command's live accessor.
pub slot_sources: BTreeMap<String, serde_json::Value>,
/// Slot-source tags belong to the same loaded snapshot as their definitions.
pub slot_source_tags: BTreeMap<String, Vec<(String, bool)>>,
/// The content tables' raw files from the packs after the built-in one:
/// `recipe/`, `recipe_filter/`, `loot_table/`, `advancement/`, `dialog/`, `damage_type/`, `data_maps/`, `enchantment/` and `tags/…/` files, by
/// `<kind-dir>/<ns>:<path>`, each id's files in pack order. The tables
@@ -759,6 +762,16 @@ impl DataStore {
&& let Ok(v) = serde_json::from_slice(&bytes)
{
s.item_modifiers.insert(id, v);
} else if let Some(id) = resource_id(&f, "tags/slot_source", ".json")
&& let Some(bytes) = pack.read(&f)
&& let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes)
{
let entries = tag_entries(&v);
let slot = s.slot_source_tags.entry(id).or_default();
if v["replace"].as_bool() == Some(true) {
slot.clear();
}
slot.extend(entries);
} else if let Some(id) = resource_id(&f, "slot_source", ".json")
&& let Some(bytes) = pack.read(&f)
&& let Ok(v) = serde_json::from_slice(&bytes)
@@ -0,0 +1,86 @@
//! Slot-source holder-set tags share DataStore's pack ordering and snapshot.
use super::DataStore;
use std::collections::BTreeSet;
impl DataStore {
/// TagLoader's required-member validation and first-seen membership order.
pub fn slot_source_tag(&self, id: &str) -> Result<Vec<String>, String> {
fn visit(
store: &DataStore,
id: &str,
active: &mut BTreeSet<String>,
) -> Result<Vec<String>, String> {
if !active.insert(id.to_owned()) {
return Err(format!("Recursive slot-source tag #{id}"));
}
let result = (|| {
let entries = store
.slot_source_tags
.get(id)
.ok_or_else(|| format!("Unknown slot-source tag #{id}"))?;
let mut out = Vec::new();
for (entry, required) in entries {
let values = if let Some(tag) = entry.strip_prefix('#') {
visit(store, tag, active)
} else if store.slot_sources.contains_key(entry) {
Ok(vec![entry.clone()])
} else {
Err(format!("Unknown slot source {entry}"))
};
match values {
Ok(values) => {
for value in values {
if !out.contains(&value) {
out.push(value);
}
}
}
Err(error) if *required => return Err(error),
Err(_) => {}
}
}
Ok(out)
})();
active.remove(id);
result
}
visit(self, id, &mut BTreeSet::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn holder_set_tags_keep_order_required_members_and_snapshot_authority() {
let mut store = DataStore::default();
for name in ["t:a", "t:b"] {
store.slot_sources.insert(
name.into(),
serde_json::json!({"type":"slot_range","slots":"container.0"}),
);
}
store.slot_source_tags.insert(
"t:child".into(),
vec![("t:b".into(), true), ("t:a".into(), true)],
);
store.slot_source_tags.insert(
"t:all".into(),
vec![
("t:a".into(), true),
("#t:child".into(), true),
("t:absent".into(), false),
],
);
assert_eq!(store.slot_source_tag("t:all").unwrap(), ["t:a", "t:b"]);
store
.slot_source_tags
.get_mut("t:all")
.unwrap()
.push(("t:absent".into(), true));
assert!(store.slot_source_tag("t:all").is_err());
store
.slot_source_tags
.insert("t:cycle".into(), vec![("#t:cycle".into(), true)]);
assert!(store.slot_source_tag("t:cycle").is_err());
}
}
@@ -12,6 +12,8 @@ use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, RwLock};
mod noise;
pub struct Environment {
system: System,
/// What the packs' expressions read; the frame sets it before sampling.
@@ -559,13 +561,9 @@ impl<'a> BlockHost<'a> {
}
}
/// The simplex noise `r.noise(x, y)` reads, the same for blocks and particles.
pub(crate) fn polytone_noise() -> &'static horizon_core::noise::SimplexNoise {
static NOISE: std::sync::OnceLock<horizon_core::noise::SimplexNoise> =
std::sync::OnceLock::new();
NOISE.get_or_init(|| {
horizon_core::noise::SimplexNoise::new(&mut horizon_core::random::LegacyRandom::new(0))
})
/// The noise `r.noise(x, y)` reads, the same for blocks and particles.
pub(crate) fn polytone_noise() -> &'static noise::PerlinSimplex {
noise::builtin()
}
impl horizon_polytone::expr::Host for BlockHost<'_> {
@@ -615,7 +613,7 @@ impl horizon_polytone::expr::Host for BlockHost<'_> {
(V::Object(2), "noise") => {
let mut coords = args.iter().filter(|v| !matches!(v, V::Str(_))).map(V::num);
let (x, y) = (coords.next().unwrap_or(0.0), coords.next().unwrap_or(0.0));
num(f64::from(polytone_noise().get2(x, y)))
num(polytone_noise().get(x, y))
}
_ => Err(format!("{name} is not available to block colormaps")),
}
@@ -0,0 +1,116 @@
//! Polytone's `r.noise(x, y)`: 1.18-1.21's `PerlinSimplexNoise` over simplex noises, which 26.3 no
//! longer has. Measured on the real mod (Polytone 26.3-6.8.6) with a pack whose grass colormap encodes
//! the noise: the built-in noise is seed 0 with octaves `{1}`, read with the noise offsets
//! (`getValue(x, y, true)`), and a `polytone/noises` definition with seed 0 or 1 and octaves `{0}`,
//! `{1}` or `{0, 1}` matches this construction too.
use horizon_core::noise::SimplexNoise;
use horizon_core::random::{LegacyRandom, RandomSource};
/// `PerlinSimplexNoise(random, octaves)`: one simplex noise per octave, the highest octave first.
pub(crate) struct PerlinSimplex {
levels: Vec<Option<SimplexNoise>>,
input_factor: f64,
value_factor: f64,
}
impl PerlinSimplex {
/// The construction of `PerlinSimplexNoise(new LegacyRandomSource(seed), octaves)`: octave 0 takes
/// the first noise of `seed`'s random; the positive octaves come from a random seeded by that
/// noise's value at its own offsets, the negative ones from `seed`'s random after it.
pub(crate) fn new(seed: i64, octaves: &[i32]) -> Self {
let mut random = LegacyRandom::new(seed);
let lowest = octaves.iter().copied().min().unwrap_or(0);
let highest = octaves.iter().copied().max().unwrap_or(0);
let count = (highest - lowest + 1) as usize;
let first = SimplexNoise::new(&mut random);
let top = highest;
let wanted = |index: i32| octaves.contains(&(top - index));
let mut levels: Vec<Option<SimplexNoise>> = (0..count).map(|_| None).collect();
for index in top + 1..count as i32 {
if index >= 0 && wanted(index) {
levels[index as usize] = Some(SimplexNoise::new(&mut random));
} else {
random.consume_count(262);
}
}
if highest > 0 {
// `(long)(getValue(xo, yo, zo) * 9.223372E18F)`: the noise at its own offsets, which
// 26.3's get3 reads at (0, 0, 0). The float constant is 2^63.
let value = first.get3_f64(0.0, 0.0, 0.0) * 9.223_372e18_f32 as f64;
let mut upper = LegacyRandom::new(value as i64);
for index in (0..top).rev() {
if (index as usize) < count && wanted(index) {
levels[index as usize] = Some(SimplexNoise::new(&mut upper));
} else {
upper.consume_count(262);
}
}
}
if (0..count as i32).contains(&top) && octaves.contains(&0) {
levels[top as usize] = Some(first);
}
Self {
levels,
input_factor: 2f64.powi(highest),
value_factor: 1.0 / (2f64.powi(count as i32) - 1.0),
}
}
/// `getValue(x, y, true)`: each octave read with its offsets, which 26.3's simplex adds itself.
pub(crate) fn get(&self, x: f64, y: f64) -> f64 {
let (mut input, mut value, mut sum) = (self.input_factor, self.value_factor, 0.0);
for level in &self.levels {
if let Some(noise) = level {
sum += noise.get2_f64(x * input, y * input) * value;
}
input /= 2.0;
value *= 2.0;
}
sum
}
}
/// The built-in `r.noise(x, y)`: seed 0, octaves `{1}`.
pub(crate) fn builtin() -> &'static PerlinSimplex {
static NOISE: std::sync::OnceLock<PerlinSimplex> = std::sync::OnceLock::new();
NOISE.get_or_init(|| PerlinSimplex::new(0, &[1]))
}
#[cfg(test)]
mod tests {
use super::*;
/// `r.noise(x/8, z/8)` read on the real mod (Polytone 26.3-6.8.6): a grass colormap whose pixel
/// encodes the value, decoded to about 0.01 (polytone-work/rnoise in the measurement notes).
#[test]
fn the_builtin_noise_reads_what_the_mod_draws() {
for (x, z, mod_value) in [
(0, 10, -0.28373),
(3, 10, -0.14683),
(10, 0, 0.31833),
(24, 14, -0.55941),
(40, 25, -0.48358),
(7, 3, -0.68202),
] {
let value = builtin().get(f64::from(x) / 8.0, f64::from(z) / 8.0);
assert!(
(value - mod_value).abs() < 0.02,
"({x}, {z}): {value} against {mod_value}"
);
}
}
/// The octaves add as `PerlinSimplexNoise`'s do: `{0, 1}` is a third of `{1}` and two thirds of
/// `{0}` (measured: 0.067 = 0.33 x -0.284 + 0.67 x 0.247 at (0, 10) / 8).
#[test]
fn two_octaves_weigh_a_third_and_two_thirds() {
let both = PerlinSimplex::new(0, &[0, 1]);
let (low, high) = (PerlinSimplex::new(0, &[0]), PerlinSimplex::new(0, &[1]));
for (x, y) in [(0.0, 1.25), (2.5, -3.0), (17.1, 4.4)] {
let mixed = high.get(x, y) / 3.0 + low.get(x, y) * 2.0 / 3.0;
assert!((both.get(x, y) - mixed).abs() < 1e-12);
}
assert!((both.get(0.0, 1.25) - 0.067).abs() < 0.02);
}
}
+42 -68
View File
@@ -60,6 +60,7 @@ mod entity_outline;
mod fluid;
#[cfg(test)]
mod inter_stage_tests;
mod section_fade;
mod terrain_model;
#[cfg(test)]
pub(crate) mod test_gpu;
@@ -74,6 +75,10 @@ pub use entity_batch::{
WATER_MASK_OVERLAY, WORLD_TEXT_OVERLAY, WORLD_TEXT_POLYGON_OFFSET_OVERLAY, is_native_terrain,
mark_oit,
};
use section_fade::{
CHUNK_VISIBILITY_THRESHOLD, FadeInputs, chunk_visibility, fade_millis, section_instance,
section_visibility,
};
pub use view::{View, ViewSet};
/// Window.getAppropriateLineWidth, in framebuffer pixels.
@@ -365,62 +370,6 @@ fn pack_terrain_camera(camera: DVec3) -> DVec3 {
let whole = camera.floor();
whole + ((camera - whole) * 65536.0).round() / 65536.0
}
/// A section's instance: its camera-relative origin and its UV step, negated
/// past its fade code while it fades in over far terrain (`lod::instance`).
fn section_instance(origin: [f32; 3], fade: u32, visibility: f32) -> [f32; 4] {
let step = 1.0 / crate::mesher::UV_STEPS;
[
origin[0],
origin[1],
origin[2],
if fade == 0 {
// The step is a power of two, so its mantissa is free: it holds the vanilla
// chunk fade-in's `1 - visibility` in 23 bits (terrain.wgsl's `instance_step` and
// `instance_visibility` read it back). A whole section is the bare step.
let faded = ((1.0 - visibility) * 8_388_608.0)
.round()
.clamp(0.0, 8_388_607.0) as u32;
f32::from_bits(step.to_bits() | faded)
} else {
-(fade as f32 + step)
},
]
}
/// `SectionRenderDispatcher.RenderSection.getVisibility`: how far through its fade-in a section
/// uploaded `elapsed_ms` ago is.
fn chunk_visibility(elapsed_ms: u64, fade_ms: u64) -> f32 {
if elapsed_ms >= fade_ms {
1.0
} else {
elapsed_ms as f32 / fade_ms as f32
}
}
/// `Util.toMillis`: `Mth.floor(seconds * 1000.0)`.
fn fade_millis(seconds: f32) -> u64 {
(f64::from(seconds) * 1000.0).floor().max(0.0) as u64
}
/// `chunk_visibility` at `now` of a section first uploaded at `uploaded`
/// (`Renderer::section_uploaded`; none: one that fades in over far terrain, or
/// whose column left), with the chunk fade-in `fade_ms`.
fn section_visibility(uploaded: Option<&Instant>, fade_ms: u64, now: Instant) -> f32 {
uploaded.map_or(1.0, |&t| {
let elapsed = now.saturating_duration_since(t).as_millis() as u64;
chunk_visibility(elapsed, fade_ms)
})
}
/// What a section's fade depends on besides the section itself
/// (`SectionGpu::drawn_faded`): the time, the chunk fade-in time, the sections'
/// first uploads (`Renderer::section_uploaded`) and those held while far
/// terrain comes in (`Renderer::lod_retiring`).
#[derive(Clone, Copy)]
struct FadeInputs<'a> {
now: Instant,
fade_ms: u64,
uploaded: &'a FxHashMap<SectionKey, Instant>,
retiring: &'a crate::fast_hash::FxHashSet<SectionKey>,
}
/// `LevelRenderer.CHUNK_VISIBILITY_THRESHOLD`: a section's block entities wait for it.
const CHUNK_VISIBILITY_THRESHOLD: f32 = 0.3;
/// A new value for `Renderer::block_entity_revision`.
fn next_block_entity_revision() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
@@ -1176,6 +1125,8 @@ pub struct Renderer {
/// Sections upload their solid quads in the compact layout (`mesher::packed`): the solid
/// passes read the arena themselves (`flat`) and no shader pack reads it as vertices.
packed_quads: bool,
/// The compact layout is allowed (`HORIZON_PACKED_QUADS`, `set_packed_layout`).
packed_on: bool,
/// The visibility buffer for flat frames' solid terrain (`visbuffer`,
/// `HORIZON_VISBUFFER=1`).
visbuf: Option<visbuffer::Visbuffer>,
@@ -4953,8 +4904,8 @@ impl Renderer {
}
None => (solid, solid_opaque, solid_cutout, solid_mirror),
};
// The solid quads in the compact layout, while no shader pack reads the arena
// (`follow_packed_layout`).
// The solid quads in the compact layout where every pass reads it; the first world
// frames settle it for the picked pack (`follow_packed_layout`).
let packed_quads = flat.is_some() && !shader_pack && packed_wanted();
packed::pack_quads(packed_quads);
// A native mod's world warp builds its pipelines with these layouts once it is given one.
@@ -5122,6 +5073,7 @@ impl Renderer {
world_warps,
flat_on: flat.is_some(),
packed_quads,
packed_on: packed_wanted(),
cull_on: cull.is_some(),
sides_on: true,
gpu_culling: None,
@@ -6758,13 +6710,17 @@ impl Renderer {
flat.set_translucent_page_vertices(arena.page_vertices());
}
}
/// Uploads solid quads in the compact layout (`packed_quads`) while no shader pack runs:
/// a pack's terrain and shadow programs, and Horizon's own packs' stages, read the
/// arena's vertices as `TerrainVertex`es. Leaving it drops every section and far tile
/// for the game to mesh again, as `follow_translucent_layout` does.
/// Uploads solid quads in the compact layout (`packed_quads`) unless a pack reads the
/// arena's vertices as `TerrainVertex`es: Horizon's own packs' stages, and a `shaders/`
/// pack's terrain and shadow programs outside flat draws (flat ones unpack the records,
/// `pack_atlas::PULL_FLAT`). Leaving it drops every section and far tile for the game to
/// mesh again, as `follow_translucent_layout` does.
fn follow_packed_layout(&mut self) {
let pack = self.pack_post.as_ref().and_then(|p| p.1.as_ref()).is_some();
let want = self.flat.is_some() && !pack && self.native.is_none() && packed_wanted();
let want = self.flat.is_some()
&& (!pack || self.pack_terrain_flat)
&& self.native.is_none()
&& self.packed_on;
if want == self.packed_quads {
return;
}
@@ -6775,6 +6731,10 @@ impl Renderer {
let waiting = self.hold.take_all();
self.place_held(waiting);
}
log::info!(
"Horizon: compact solid terrain {}",
if want { "on" } else { "off" }
);
self.packed_quads = want;
packed::pack_quads(want);
let laid_out = self.sections.values().any(|s| s.packed)
@@ -6784,6 +6744,17 @@ impl Renderer {
self.clear_sections(self.layout);
}
}
/// Allows the compact layout of solid quads or not, for A/B checks: every section and far
/// tile is meshed again in the layout that follows. Replies whether sections now use it.
pub fn set_packed_layout(&mut self, on: bool) -> bool {
if on != self.packed_on {
self.packed_on = on;
self.follow_packed_layout();
self.sections_dropped = true;
self.clear_sections(self.layout);
}
self.packed_quads
}
/// Whether every section and far tile was dropped since the last call, to be
/// laid out again (`follow_translucent_layout`): the game meshes them again,
/// as for a new renderer.
@@ -7226,7 +7197,8 @@ impl Renderer {
.as_ref()
.map_or([1, 1], |t| [t.width(), t.height()]),
terrain: self.pack_atlas.as_ref().map(|_| pack_post::Geometry {
buffers: if flat { &buffers[..1] } else { &buffers },
// Flat terrain programs pull their vertices (`pack_atlas::PULL_FLAT`).
buffers: if flat { &[] } else { &buffers },
table: self.flat.as_ref().filter(|_| flat).map(|f| &f.draw_layout),
depth_write: true,
atlas: None,
@@ -7396,7 +7368,8 @@ impl Renderer {
lightmap,
gui_size,
terrain: terrain.then(|| pack_post::Geometry {
buffers: if flat { &buffers[..1] } else { &buffers },
// Flat terrain programs pull their vertices (`pack_atlas::PULL_FLAT`).
buffers: if flat { &[] } else { &buffers },
table: table.as_ref(),
depth_write: true,
atlas: None,
@@ -7561,7 +7534,8 @@ impl Renderer {
);
horizon_shaders::GeometryInputs {
inputs,
pull: pack_atlas::PULL.to_owned(),
// Flat terrain inputs pull their own vertex (`PULL_FLAT`, `gl_VertexIndex` → `hz_vertex_index`).
pull: String::new(),
index: "hz_indices[@]".to_owned(),
}
});
@@ -15306,8 +15280,8 @@ fn log_os_reported(reported: Option<crate::graphics::Reported>) {
});
}
/// What the OS reports in absolute nits, HDR output's scale (Windows: DXGI's SDR white level,
/// the brightness slider's, as Paper White, and its `MaxLuminance`, mostly the display's EDID
/// guess, as Peak Brightness), kept within the settings' ranges. The player's values win.
/// the brightness slider's, as Paper White, and its `MaxLuminance`, the display's or a calibration
/// profile's, as Peak Brightness), kept within the settings' ranges. The player's values win.
fn os_reported(info: &wgpu::DisplayHdrInfo) -> Option<crate::graphics::Reported> {
let luminance = info.luminance?;
let usable = |n: f32| n.is_finite() && n > 0.0;
@@ -0,0 +1,42 @@
//! A bind group's validity depends on the identity of its buffers and the
//! bound slice, not on the bytes written into those buffers.
pub(super) struct BindingKey<B, const N: usize> {
pub first: u64,
pub count: u64,
pub buffers: [B; N],
}
impl<B: PartialEq, const N: usize> BindingKey<B, N> {
pub fn matches(&self, first: u64, count: u64, buffers: [&B; N]) -> bool {
self.first == first
&& self.count == count
&& self
.buffers
.iter()
.zip(buffers)
.all(|(old, new)| old == new)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn changes_to_any_resource_or_range_invalidate_the_binding() {
let key = BindingKey {
first: 16,
count: 8,
buffers: [1u64, 2, 3, 4],
};
assert!(key.matches(16, 8, [&1, &2, &3, &4]));
assert!(!key.matches(0, 8, [&1, &2, &3, &4]));
assert!(!key.matches(16, 9, [&1, &2, &3, &4]));
for i in 0..4 {
let mut resources = [1u64, 2, 3, 4];
resources[i] += 100;
assert!(!key.matches(16, 8, resources.each_ref()));
}
}
}
+99 -45
View File
@@ -19,7 +19,10 @@
//! start, and the run is drawn indirectly with the count the copy reached.
use super::SolidPipeline;
use super::arena::GRAIN;
use smallvec::SmallVec;
#[path = "binding_cache.rs"]
mod binding_cache;
use binding_cache::BindingKey;
/// One section draw for `flatten.wgsl`: index count, first sorted index (or
/// `QUADS` for a solid draw; phase 2: its entry in phase 2's draws), base
@@ -85,6 +88,11 @@ pub struct Call {
pub count: u32,
}
struct CachedGroup<const N: usize> {
key: BindingKey<wgpu::Buffer, N>,
group: wgpu::BindGroup,
}
pub struct Flat {
/// The solid draws in one pass (`fs_solid`), where the GPU doesn't hide pixels
/// by tiles (`split_solid` in `Renderer::draw_frame`: elsewhere than Metal).
@@ -109,8 +117,9 @@ pub struct Flat {
phase2_call_data: Vec<[u32; 5]>,
/// GPU culling's phase 2 uses indirect draws; flat draws without culling do not.
indirect_execution: bool,
/// The copy of phase 2's draws, and its ranges.
phase2_group: Option<(wgpu::BindGroup, u32)>,
/// Bindings reused while the range and all GPU buffers are unchanged.
phase2_group: Option<CachedGroup<4>>,
groups: Vec<CachedGroup<3>>,
/// The layout of a page's bind group 1 (shader packs' terrain pipelines share it).
pub(super) draw_layout: wgpu::BindGroupLayout,
blocks_per_page: u64,
@@ -515,6 +524,7 @@ impl Flat {
phase2_call_data: Vec::new(),
indirect_execution,
phase2_group: None,
groups: Vec::new(),
draw_layout,
blocks_per_page: page_vertices.div_ceil(GRAIN),
translucent_blocks_per_page: page_vertices.div_ceil(GRAIN),
@@ -626,6 +636,8 @@ impl Flat {
}
pub fn clear(&mut self) {
self.pages.clear();
self.groups.clear();
self.phase2_group = None;
self.free_ids.clear();
self.next_id = 0;
}
@@ -665,7 +677,6 @@ impl Flat {
sorted_page: impl Fn(u32) -> wgpu::Buffer,
timing: Option<&mut super::pack_timing::PassTiming>,
) -> bool {
self.phase2_group = None;
let phase2 = phase2.filter(|_| self.indirect_execution);
let phase1_draws = if phase2.is_some() {
phase1_draws
@@ -729,6 +740,9 @@ impl Flat {
self.shadow_calls = shadow_calls;
self.pass_calls = pass_calls;
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
// Do not retain bindings for a frame that cannot use flat draws.
self.phase2_group = None;
self.groups.clear();
self.calls.clear();
self.phase1_calls = 0;
self.solid_calls = 0;
@@ -802,39 +816,63 @@ impl Flat {
phase2,
self.segments.iter().find(|(s, ..)| *s == Source::Seen),
) {
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten phase 2 section draws"),
layout: &self.seen_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: ranges_at(first, count),
let buffers = [&self.ranges, &self.indices, phase2, &self.phase2_calls];
if !self
.phase2_group
.as_ref()
.is_some_and(|cached| cached.key.matches(first, count, buffers))
{
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten phase 2 section draws"),
layout: &self.seen_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: ranges_at(first, count),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: phase2.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.phase2_calls.as_entire_binding(),
},
],
});
self.phase2_group = Some(CachedGroup {
key: BindingKey {
first,
count,
buffers: buffers.map(|b| b.clone()),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: phase2.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.phase2_calls.as_entire_binding(),
},
],
});
self.phase2_group = Some((group, count as u32));
group,
});
}
} else {
self.phase2_group = None;
}
let groups: SmallVec<[(wgpu::BindGroup, u32); 8]> = self
.segments
.iter()
.filter_map(|&(source, first, count)| {
let sorted = match source {
Source::Quads => None,
Source::Seen => return None,
Source::Sorted(page) => Some(sorted_page(page)),
};
let mut groups = 0;
for &(source, first, count) in &self.segments {
let sorted = match source {
Source::Quads => None,
Source::Seen => continue,
Source::Sorted(page) => Some(sorted_page(page)),
};
let buffers = [
&self.ranges,
sorted.as_ref().unwrap_or(&self.empty),
&self.indices,
];
if self
.groups
.get(groups)
.is_none_or(|cached| !cached.key.matches(first, count, buffers))
{
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Flatten section draws"),
layout: &self.compute_layout,
@@ -845,7 +883,7 @@ impl Flat {
},
wgpu::BindGroupEntry {
binding: 1,
resource: sorted.as_ref().unwrap_or(&self.empty).as_entire_binding(),
resource: buffers[1].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
@@ -853,17 +891,32 @@ impl Flat {
},
],
});
Some((group, count as u32))
})
.collect();
let cached = CachedGroup {
key: BindingKey {
first,
count,
buffers: buffers.map(|b| b.clone()),
},
group,
};
if groups < self.groups.len() {
self.groups[groups] = cached;
} else {
self.groups.push(cached);
}
}
groups += 1;
}
self.groups.truncate(groups);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Flatten section draws"),
timestamp_writes: timing.and_then(|t| t.compute_writes("Flatten")),
});
pass.set_pipeline(&self.flatten);
for (group, count) in &groups {
pass.set_bind_group(0, group, &[]);
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
for cached in &self.groups {
let count = cached.key.count as u32;
pass.set_bind_group(0, &cached.group, &[]);
pass.dispatch_workgroups(count.min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
}
drop(pass);
true
@@ -919,16 +972,17 @@ impl Flat {
encoder: &mut wgpu::CommandEncoder,
timing: Option<&mut super::pack_timing::PassTiming>,
) {
let Some((group, count)) = &self.phase2_group else {
let Some(cached) = &self.phase2_group else {
return;
};
let count = cached.key.count as u32;
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Flatten phase 2 section draws"),
timestamp_writes: timing.and_then(|t| t.compute_writes("Flatten phase 2")),
});
pass.set_pipeline(&self.flatten_seen);
pass.set_bind_group(0, group, &[]);
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
pass.set_bind_group(0, &cached.group, &[]);
pass.dispatch_workgroups(count.min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
}
/// The camera's translucent calls.
+43 -20
View File
@@ -169,7 +169,8 @@ pub struct Hdr {
hand_mark: wgpu::RenderPipeline,
params: wgpu::Buffer,
/// The same pass drawing HDR10 for a screenshot (`capture`), with its own parameters,
/// so it can differ from the swapchain's in one frame.
/// so it can differ from the swapchain's in one frame, and without the swapchain's dither:
/// a screenshot keeps the exact codes.
capture_pipeline: wgpu::RenderPipeline,
capture_params: wgpu::Buffer,
pub output: Output,
@@ -286,8 +287,9 @@ impl Hdr {
entries: &entries,
})
};
// One full-screen pass of hdr.wgsl's `entry` into `format`, reading `layout`.
let pass = |label, layout: &wgpu::BindGroupLayout, entry, format| {
// One full-screen pass of hdr.wgsl's `entry` into `format`, reading `layout`; `dither`
// for the last pass into the HDR10 swapchain (`pq_dither`).
let pass = |label, layout: &wgpu::BindGroupLayout, entry, format, dither: bool| {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(label),
bind_group_layouts: &[Some(layout)],
@@ -308,7 +310,10 @@ impl Hdr {
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(entry),
compilation_options: Default::default(),
compilation_options: wgpu::PipelineCompilationOptions {
constants: &[("pq_dither", f64::from(u8::from(dither)))],
..Default::default()
},
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
@@ -321,7 +326,8 @@ impl Hdr {
};
let layout_bindings: &[u32] = if coverage { &[0, 3, 4, 5] } else { &[0, 1, 3] };
let display = layout("Horizon HDR bindings", layout_bindings, true);
let pipeline_for = |format| pass("Horizon HDR", &display, entry_point, format);
let pipeline_for =
|format, dither| pass("Horizon HDR", &display, entry_point, format, dither);
let params = || {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon HDR parameters"),
@@ -333,7 +339,7 @@ impl Hdr {
let layered = coverage.then(|| {
let with = |label, textures: &[u32], params, entry, format| {
let layout = layout(label, textures, params);
let pipeline = pass(label, &layout, entry, format);
let pipeline = pass(label, &layout, entry, format, false);
(layout, pipeline)
};
let hud = super::hud_coverage::HUD_FORMAT;
@@ -395,8 +401,8 @@ impl Hdr {
);
Self {
logo: logo_mask(device, queue),
pipeline: pipeline_for(output.format()),
capture_pipeline: pipeline_for(Output::Pq.format()),
pipeline: pipeline_for(output.format(), output == Output::Pq),
capture_pipeline: pipeline_for(Output::Pq.format(), false),
layout: display,
clear_alpha,
hand_mark,
@@ -1709,19 +1715,32 @@ struct ReferenceParams { peak: f32, scene: f32, world: f32, debug: f32, share: v
super::super::hud_coverage::clear(&mut encoder, &hdr.coverage_view().unwrap());
hdr.begin(&queue, true);
hdr.present(&queue, &mut encoder, &target, true, None);
let got = texel(&device, &queue, encoder, &target);
for c in &got[..3] {
let c = f64::from(*c);
let ok = match output {
// 10-bit codes, a step either way for rounding.
Output::Pq => (c - 1023.0 * pq(want)).abs() <= 1.0,
// 80 nits a unit, in half floats.
Output::ScRgb => (c * 80.0 - want).abs() <= 2e-3 * want + 1e-4,
// HDR10's exact codes are a screenshot's copy: the swapchain's own get a
// code of dither either way.
let exact = (output == Output::Pq)
.then(|| hdr.capture(&device, &queue, &mut encoder, true).unwrap());
let presented = texel(&device, &queue, encoder, &target);
let exact = exact.map(|copy| {
let encoder = device.create_command_encoder(&Default::default());
texel(&device, &queue, encoder, &copy)
});
for (got, codes) in [(Some(presented), 2.0), (exact, 1.0)] {
let Some(got) = got else {
continue;
};
assert!(
ok,
"{output:?} black {black}, light {light}: {got:?}, not {want} nits"
);
for c in &got[..3] {
let c = f64::from(*c);
let ok = match output {
// 10-bit codes, a step either way for rounding.
Output::Pq => (c - 1023.0 * pq(want)).abs() <= codes,
// 80 nits a unit, in half floats.
Output::ScRgb => (c * 80.0 - want).abs() <= 2e-3 * want + 1e-4,
};
assert!(
ok,
"{output:?} black {black}, light {light}: {got:?}, not {want} nits"
);
}
}
}
}
@@ -2078,3 +2097,7 @@ mod lighting_tests {
#[cfg(test)]
#[path = "hdr_written_tests.rs"]
mod written_tests;
#[cfg(test)]
#[path = "hdr_dither_tests.rs"]
mod dither_tests;
@@ -0,0 +1,313 @@
//! HDR10's dither (`hdr.wgsl`, `dithered`): the last pass into the 10-bit swapchain, and what
//! must stay without it.
use super::{
Hdr, Output,
tests::{fill, gpu},
};
use wgpu::TextureFormat as F;
const SIZE: [u32; 2] = [64, 1024];
/// The ramp: grey rising by one half-float step every `ROWS` rows from `FIRST / 2048`. That is
/// three PQ codes down the picture around 91 nits: as slow as a clear sky, and as fine as the
/// float frame holds.
const FIRST: u32 = 1434;
const ROWS: u32 = 52;
/// SMPTE ST 2084: nits as a 10-bit PQ code, before rounding.
fn code(nits: f64) -> f64 {
let y = (nits / 10_000.0).powf(0.1593017578125);
1023.0 * ((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y)).powf(78.84375)
}
/// The ramp's row `y` as a PQ code, at the 200-nit paper white `Hdr` starts with.
fn ramp_code(y: u32) -> f64 {
code(200.0 * (f64::from(FIRST + y / ROWS) / 2048.0).powf(2.2))
}
fn ramp(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture) {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(
format!(
r#"
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {{
return vec4(vec2(f32((i << 1u) & 2u), f32(i & 2u)) * 2.0 - 1.0, 0.0, 1.0);
}}
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {{
return vec4(vec3(f32({FIRST}u + u32(pos.y) / {ROWS}u) / 2048.0), 1.0);
}}
"#
)
.into(),
),
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[Some(frame.format().into())],
}),
multiview_mask: None,
cache: None,
});
let view = frame.create_view(&Default::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(super::super::hud_coverage::attachment(&view))],
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.draw(0..3, 0..1);
}
/// What `hdr` writes for the float frame `paint` fills, with no HUD over it: its last pass into
/// a swapchain image of its output (`Hdr::present`), or a screenshot's HDR10 copy
/// (`Hdr::capture`). Every pixel's bytes, row by row.
fn shown(
(device, queue): &(wgpu::Device, wgpu::Queue),
hdr: &mut Hdr,
screenshot: bool,
paint: impl Fn(&mut wgpu::CommandEncoder, &wgpu::Texture),
) -> Vec<u8> {
let frame = hdr.frame(device, SIZE);
let mut encoder = device.create_command_encoder(&Default::default());
paint(&mut encoder, &frame);
hdr.keep_world(&mut encoder, None);
super::super::hud_coverage::clear(&mut encoder, &hdr.coverage_view().unwrap());
let image = if screenshot {
hdr.capture(device, queue, &mut encoder, true).unwrap()
} else {
let image = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: frame.size(),
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: hdr.output.format(),
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
hdr.present(queue, &mut encoder, &image, true, None);
image
};
let row = SIZE[0] * image.format().block_copy_size(None).unwrap();
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(row * SIZE[1]),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
image.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(row),
rows_per_image: None,
},
},
image.size(),
);
queue.submit([encoder.finish()]);
buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
buffer.get_mapped_range(..).unwrap().to_vec()
}
fn float_hdr((device, queue): &(wgpu::Device, wgpu::Queue), output: Output) -> Hdr {
Hdr::with_debug(device, queue, F::Rgba16Float, output, true, None)
}
/// An HDR10 picture's 10-bit codes, red, green and blue.
fn codes(bytes: &[u8]) -> Vec<[u32; 3]> {
let pixels = bytes.as_chunks::<4>().0.iter();
pixels
.map(|p| [0, 10, 20].map(|shift| (u32::from_le_bytes(*p) >> shift) & 0x3ff))
.collect()
}
/// Down every column of a channel: the longest run of rows with one code, and the runs' mean
/// length.
fn runs(codes: &[[u32; 3]], channel: usize) -> (u32, f64) {
let (mut longest, mut count) = (0, 0);
for x in 0..SIZE[0] {
let mut run = 0;
for y in 0..SIZE[1] {
let at = |y: u32| codes[(y * SIZE[0] + x) as usize][channel];
if y > 0 && at(y) != at(y - 1) {
(longest, count, run) = (longest.max(run), count + 1, 0);
}
run += 1;
}
(longest, count) = (longest.max(run), count + 1);
}
(longest, f64::from(SIZE[0] * SIZE[1]) / f64::from(count))
}
/// Whether every row of a picture is one value from side to side: no noise in it.
fn rows_are_flat(bytes: &[u8]) -> bool {
let pixel = bytes.len() / (SIZE[0] * SIZE[1]) as usize;
bytes
.chunks(pixel * SIZE[0] as usize)
.all(|row| row.chunks(pixel).all(|p| p == &row[..pixel]))
}
#[test]
fn a_slow_gradient_gets_grain_instead_of_bands_on_hdr10() {
let Some(gpu) = gpu() else {
return;
};
let ramp = |encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture| {
ramp(&gpu.0, encoder, frame);
};
let mut hdr = float_hdr(&gpu, Output::Pq);
// The ramp is what the test says: three codes, top to bottom.
let span = ramp_code(SIZE[1] - 1) - ramp_code(0);
assert!((2.9..3.2).contains(&span), "{span}");
// Without dither, as a screenshot's copy stays: each row its nearest code, in bands hundreds
// of rows tall. A GPU need not round at exactly half a code: an NVIDIA one rounds up from
// 0.55 here, which shows as 0.05 of a code less, so the bounds below leave a quarter code.
let plain = codes(&shown(&gpu, &mut hdr, true, ramp));
let dithered = codes(&shown(&gpu, &mut hdr, false, ramp));
let want = |i: usize| ramp_code(i as u32 / SIZE[0]);
for channel in 0..3 {
for (i, p) in plain.iter().enumerate() {
let off = (f64::from(p[channel]) - want(i)).abs();
assert!(
off <= 0.75,
"plain {channel} at {i}: {p:?}, not {}",
want(i)
);
}
let (longest, _) = runs(&plain, channel);
assert!(longest >= 250, "plain {channel}: bands of {longest} rows");
// With it: each pixel within the noise's one code of its light (and half a code of
// rounding), no column holds a code for long, and a run is a few rows on average.
for (i, d) in dithered.iter().enumerate() {
let off = (f64::from(d[channel]) - want(i)).abs();
assert!(
off <= 1.75,
"dithered {channel} at {i}: {d:?}, not {}",
want(i)
);
}
let (longest, mean) = runs(&dithered, channel);
eprintln!(
"HDR10 dither GPU, channel {channel}: longest run {longest} rows, mean {mean:.2}"
);
assert!(longest <= 64, "dithered {channel}: a run of {longest} rows");
assert!(mean < 4.0, "dithered {channel}: runs of {mean} rows");
// The mean of each 64-row block is the light meant.
let mut worst = 0.0_f64;
for block in 0..SIZE[1] / 64 {
let rows = (block * 64 * SIZE[0]) as usize..((block + 1) * 64 * SIZE[0]) as usize;
let n = rows.len() as f64;
let got = dithered[rows.clone()]
.iter()
.map(|d| f64::from(d[channel]))
.sum::<f64>()
/ n;
let meant = rows.map(want).sum::<f64>() / n;
worst = worst.max((got - meant).abs());
assert!(
(got - meant).abs() < 0.25,
"block {block} of {channel}: {got}, not {meant}"
);
}
eprintln!("HDR10 dither GPU, channel {channel}: block means within {worst:.3} of a code");
}
}
#[test]
fn hdr10s_dither_keeps_both_ends_exact_and_leans_to_them_in_their_last_code() {
let Some(gpu) = gpu() else {
return;
};
let mut hdr = float_hdr(&gpu, Output::Pq);
let grey = |g: f64| {
move |encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture| {
fill(encoder, frame, [g, g, g, 1.0]);
}
};
// How far the picture's mean code is from `end`.
let mean_from = |picture: &[[u32; 3]], end: f64| {
let sum: f64 = picture.iter().flatten().map(|c| f64::from(*c)).sum();
(sum / (picture.len() * 3) as f64 - end).abs()
};
// Within a code of an end the noise shrinks to the distance to it. A third of a code from
// the end, the signal plus that noise passes half a code only where the noise is over half
// its range, an eighth of a triangle: so the picture's mean is an eighth of a code from the
// end, not a third. That lean to the end, in the last code alone, is the price of keeping
// the end itself exact. Bound: a GPU that rounds a tenth of a code off the half (as above)
// shows between 0.02 and 0.32 of a code, always short of the third.
let leans = |mean: f64| (0.015..0.325).contains(&mean);
// Black gets no noise: every pixel stays off.
let black = codes(&shown(&gpu, &mut hdr, false, grey(0.0)));
assert!(black.iter().all(|p| *p == [0; 3]));
// A third of a code above black (this grey is a half float): 0 or 1, never lifted past it.
let dim = 0.00038433074951171875;
let meant = code(200.0 * f64::powf(dim, 2.2));
assert!((meant - 1.0 / 3.0).abs() < 0.001, "{meant}");
let near_black = codes(&shown(&gpu, &mut hdr, false, grey(dim)));
assert!(near_black.iter().flatten().all(|c| *c <= 1));
let mean = mean_from(&near_black, 0.0);
eprintln!("HDR10 dither GPU: a third of a code above black shows as {mean:.3}");
assert!(leans(mean), "{mean} above black");
// The top of the range, PQ's 10 000 nits, stays the top: nothing wraps or dims. Light past
// the peak is held at it, so the Peak setting is the signal here.
hdr.peak = 10_000.0;
let top = codes(&shown(&gpu, &mut hdr, false, grey(20.0)));
assert!(top.iter().all(|p| *p == [1023; 3]));
// A third of a code under the top, mirrored: 1022 or 1023.
let (mut under, mut over) = (9000.0, 10_000.0);
for _ in 0..60 {
let middle = (under + over) / 2.0;
if code(middle) < 1023.0 - 1.0 / 3.0 {
under = middle;
} else {
over = middle;
}
}
hdr.peak = under as f32;
let meant = code(f64::from(hdr.peak));
assert!((1023.0 - meant - 1.0 / 3.0).abs() < 0.001, "{meant}");
let near_top = codes(&shown(&gpu, &mut hdr, false, grey(20.0)));
assert!(near_top.iter().flatten().all(|c| *c >= 1022));
let mean = mean_from(&near_top, 1023.0);
eprintln!("HDR10 dither GPU: a third of a code under the top shows as {mean:.3} under");
assert!(leans(mean), "{mean} under the top");
}
#[test]
fn scrgb_and_screenshots_get_no_dither() {
let Some(gpu) = gpu() else {
return;
};
let ramp = |encoder: &mut wgpu::CommandEncoder, frame: &wgpu::Texture| {
ramp(&gpu.0, encoder, frame);
};
let (mut hdr10, mut scrgb) = (float_hdr(&gpu, Output::Pq), float_hdr(&gpu, Output::ScRgb));
// scRGB's swapchain is float: every row is one value from side to side.
assert!(rows_are_flat(&shown(&gpu, &mut scrgb, false, ramp)));
// A screenshot's HDR10 copy is the same bytes whichever swapchain is presented, the
// dithered one included, and has no noise in it.
let screenshot = shown(&gpu, &mut hdr10, true, ramp);
assert!(rows_are_flat(&screenshot));
assert_eq!(screenshot, shown(&gpu, &mut scrgb, true, ramp));
// The swapchain's own picture differs from it: the dither is on there.
assert_ne!(screenshot, shown(&gpu, &mut hdr10, false, ramp));
}
@@ -8,7 +8,7 @@
use glam::{Mat4, Vec3};
use horizon_shader_api::{
Api, Frame as FrameInputs, StageKind, check::CheckedStage, stages::GROUP,
Api, Frame as FrameInputs, Primaries, StageKind, check::CheckedStage, stages::GROUP,
};
use super::Frame;
@@ -1596,7 +1596,11 @@ pub fn frame_inputs(
paper_white: 80.0,
peak: 80.0,
black_level: 0.0,
padding: [0; 3],
// No pack is served another space yet (`[frame] primaries`).
primaries: Primaries::Bt709 as u32,
luminance_gap: [0; 2],
luminance: Primaries::Bt709.luminance(),
padding: 0,
}
}
@@ -548,27 +548,107 @@ impl PackAtlas {
}
}
/// A `TerrainVertex` of flat draws' arena page (`hz_vertices`, six words each) into the vertex
/// inputs, for vertex `hz_vertex_index`.
pub const PULL: &str = " uint hz_pw = hz_vertex_index * 6u;\n \
hz_v_pos = uintBitsToFloat(uvec3(hz_vertices[hz_pw], hz_vertices[hz_pw + 1u], hz_vertices[hz_pw + 2u]));\n \
hz_v_uv = uvec2(hz_vertices[hz_pw + 3u] & 65535u, hz_vertices[hz_pw + 3u] >> 16u);\n \
hz_v_layer = hz_vertices[hz_pw + 4u] & 65535u;\n \
uint hz_pl = hz_vertices[hz_pw + 4u] >> 16u;\n \
hz_v_light = uvec2(hz_pl & 255u, hz_pl >> 8u);\n \
hz_v_color = unpackUnorm4x8(hz_vertices[hz_pw + 5u]);\n";
/// GLSL: terrain.wgsl's `section_corner` over the arena page (`hz_vertices`), by quad: a
/// vertex's words as `TerrainVertex` holds them (position, then UV, layer with light, colour),
/// from vertices below `PACKED_BASE` or a compact record (`mesher/packed.rs`) past it. Records
/// give back their quad's vertices bit for bit, so packs read either layout alike.
/// `hz_arena_corner`: a vertex's position and UV words; `hz_record_corner`: corner `k`'s of the
/// record `lo`, `hi`; `hz_record_rest`: its layer-with-light and colour words.
const CORNER_FN: &str = "void hz_arena_corner(uint hz_av, out uvec3 hz_p, out uint hz_uv) {\n \
uint hz_w = hz_av * 6u;\n \
hz_p = uvec3(hz_vertices[hz_w], hz_vertices[hz_w + 1u], hz_vertices[hz_w + 2u]);\n \
hz_uv = hz_vertices[hz_w + 3u];\n\
}\n\
uint hz_corner_offset(uint hz_rel, uint hz_side, uint hz_du, uint hz_dw) {\n \
return hz_rel == 0u ? hz_side : (hz_rel == 1u ? hz_du : hz_dw);\n\
}\n\
void hz_record_corner(uvec3 hz_lo, uvec3 hz_hi, uint hz_k, out uvec3 hz_p, out uint hz_uv) {\n \
uint hz_o = (hz_hi.z >> 12u) & 0x3ffffu;\n \
uvec3 hz_block = uvec3(hz_o & 15u, (hz_o >> 4u) & 15u, (hz_o >> 8u) & 15u);\n \
uint hz_axis = (hz_o >> 12u) & 3u;\n \
uint hz_side = (hz_o >> 14u) & 1u;\n \
uint hz_step = (((hz_o >> 15u) & 3u) + (((hz_o >> 17u) & 1u) == 1u ? 4u - hz_k : hz_k)) & 3u;\n \
uint hz_du = (hz_step == 1u || hz_step == 2u) ? 1u : 0u;\n \
uint hz_dw = hz_step >= 2u ? 1u : 0u;\n \
uvec3 hz_pos = hz_block + uvec3(hz_corner_offset((3u - hz_axis) % 3u, hz_side, hz_du, hz_dw),\n \
hz_corner_offset((4u - hz_axis) % 3u, hz_side, hz_du, hz_dw),\n \
hz_corner_offset((5u - hz_axis) % 3u, hz_side, hz_du, hz_dw));\n \
uint hz_sel = hz_lo.z >> 24u;\n \
uint hz_u = (hz_lo.z >> (6u * ((hz_sel >> (2u * hz_k)) & 1u))) & 63u;\n \
uint hz_v = (hz_lo.z >> (12u + 6u * ((hz_sel >> (2u * hz_k + 1u)) & 1u))) & 63u;\n \
hz_p = floatBitsToUint(vec3(hz_pos));\n \
hz_uv = (hz_u << 10u) | (hz_v << 26u);\n\
}\n\
uvec2 hz_record_rest(uvec3 hz_lo, uvec3 hz_hi, uint hz_k) {\n \
uint hz_l = hz_k == 0u ? hz_hi.x >> 16u : (hz_k == 1u ? hz_hi.y : (hz_k == 2u ? hz_hi.y >> 12u : hz_hi.z));\n \
hz_l &= 0xfffu;\n \
uint hz_pl = ((hz_l & 63u) << 2u) | (((hz_l >> 6u) & 63u) << 10u);\n \
uint hz_g = (hz_lo.y >> (8u * hz_k)) & 255u;\n \
uint hz_t = hz_lo.x;\n \
uint hz_code = hz_k == 1u ? (hz_hi.x >> 28u) & 7u : (hz_k == 2u ? (hz_hi.y >> 24u) & 7u\n \
: (hz_k == 3u ? (hz_hi.y >> 27u) & 7u : 0u));\n \
uint hz_alpha = hz_code == 0u ? hz_t & 0xff000000u : (hz_code * 51u) << 24u;\n \
uint hz_c = (hz_g * ((hz_t >> 16u) & 255u) / 255u) | ((hz_g * ((hz_t >> 8u) & 255u) / 255u) << 8u)\n \
| ((hz_g * (hz_t & 255u) / 255u) << 16u) | hz_alpha;\n \
return uvec2((hz_hi.x & 0xffffu) | (hz_pl << 16u), hz_c);\n\
}\n";
/// GLSL: a flat-drawn vertex's inputs, and its quad's four corners' positions (`hz_cp0`..) and
/// UV words (`hz_uv0`..), pulled from the arena page as terrain.wgsl's `vs_section_flat` pulls
/// them (`CORNER_FN`): a record is read once for all four, and only the vertex's own light and
/// colour are worked out. `hz_slot`: the slot its block is found by (`hz_block_slots`, 256 a
/// block). The colour as the vertex fetch converts a Unorm8x4 (terrain.wgsl's `unorm8x4`).
const PULL_FLAT: &str = " uint hz_qv = uint(gl_VertexIndex);\n \
uint hz_own = hz_qv & 3u;\n \
uint hz_av = hz_qv & ~3u;\n \
uint hz_slot = hz_qv;\n \
bool hz_rec = false;\n \
uvec3 hz_lo = uvec3(0u);\n \
uvec3 hz_hi = uvec3(0u);\n \
if (hz_av >= 0x10000000u) {\n \
hz_slot = (hz_av - 0x10000000u) >> 2u;\n \
uint hz_rw = hz_slot * 6u;\n \
hz_lo = uvec3(hz_vertices[hz_rw], hz_vertices[hz_rw + 1u], hz_vertices[hz_rw + 2u]);\n \
hz_hi = uvec3(hz_vertices[hz_rw + 3u], hz_vertices[hz_rw + 4u], hz_vertices[hz_rw + 5u]);\n \
hz_rec = (hz_hi.z & 0x80000000u) == 0u;\n \
hz_av = hz_slot + hz_lo.x;\n \
}\n \
uvec3 hz_cp0; uvec3 hz_cp1; uvec3 hz_cp2; uvec3 hz_cp3;\n \
uint hz_uv0; uint hz_uv1; uint hz_uv2; uint hz_uv3;\n \
uvec2 hz_rest;\n \
if (hz_rec) {\n \
hz_record_corner(hz_lo, hz_hi, 0u, hz_cp0, hz_uv0);\n \
hz_record_corner(hz_lo, hz_hi, 1u, hz_cp1, hz_uv1);\n \
hz_record_corner(hz_lo, hz_hi, 2u, hz_cp2, hz_uv2);\n \
hz_record_corner(hz_lo, hz_hi, 3u, hz_cp3, hz_uv3);\n \
hz_rest = hz_record_rest(hz_lo, hz_hi, hz_own);\n \
} else {\n \
hz_arena_corner(hz_av, hz_cp0, hz_uv0);\n \
hz_arena_corner(hz_av + 1u, hz_cp1, hz_uv1);\n \
hz_arena_corner(hz_av + 2u, hz_cp2, hz_uv2);\n \
hz_arena_corner(hz_av + 3u, hz_cp3, hz_uv3);\n \
uint hz_ow = (hz_av + hz_own) * 6u;\n \
hz_rest = uvec2(hz_vertices[hz_ow + 4u], hz_vertices[hz_ow + 5u]);\n \
}\n \
uvec3 hz_vp = hz_own == 0u ? hz_cp0 : (hz_own == 1u ? hz_cp1 : (hz_own == 2u ? hz_cp2 : hz_cp3));\n \
uvec3 hz_vr = uvec3(hz_own == 0u ? hz_uv0 : (hz_own == 1u ? hz_uv1 : (hz_own == 2u ? hz_uv2 : hz_uv3)), hz_rest);\n \
hz_v_pos = uintBitsToFloat(hz_vp);\n \
hz_v_uv = uvec2(hz_vr.x & 65535u, hz_vr.x >> 16u);\n \
hz_v_layer = hz_vr.y & 65535u;\n \
hz_v_light = uvec2((hz_vr.y >> 16u) & 255u, hz_vr.y >> 24u);\n \
hz_v_color = vec4(float(hz_vr.z & 255u), float((hz_vr.z >> 8u) & 255u), float((hz_vr.z >> 16u) & 255u),\n \
float(hz_vr.z >> 24u)) * (1.0 / 255.0);\n";
/// GLSL: the face normal and tangent of a flat-drawn vertex, from its quad's first three corners
/// (quads are four consecutive vertices of the page; position words 0-2, UV word 3).
const FACE: &str = " uint hz_q = (uint(gl_VertexIndex) & ~3u) * 6u;\n \
vec3 hz_p0 = uintBitsToFloat(uvec3(hz_vertices[hz_q], hz_vertices[hz_q + 1u], hz_vertices[hz_q + 2u]));\n \
vec3 hz_p1 = uintBitsToFloat(uvec3(hz_vertices[hz_q + 6u], hz_vertices[hz_q + 7u], hz_vertices[hz_q + 8u]));\n \
vec3 hz_p2 = uintBitsToFloat(uvec3(hz_vertices[hz_q + 12u], hz_vertices[hz_q + 13u], hz_vertices[hz_q + 14u]));\n \
uvec3 hz_w = uvec3(hz_vertices[hz_q + 3u], hz_vertices[hz_q + 9u], hz_vertices[hz_q + 15u]);\n \
/// (`PULL_FLAT`'s corners: four consecutive vertex indices, in either layout).
const FACE: &str = " vec3 hz_p0 = uintBitsToFloat(hz_cp0);\n \
vec3 hz_p1 = uintBitsToFloat(hz_cp1);\n \
vec3 hz_p2 = uintBitsToFloat(hz_cp2);\n \
uvec3 hz_w = uvec3(hz_uv0, hz_uv1, hz_uv2);\n \
vec2 hz_t0 = vec2(hz_w.x & 65535u, hz_w.x >> 16u);\n \
vec2 hz_d1 = vec2(hz_w.y & 65535u, hz_w.y >> 16u) - hz_t0;\n \
vec2 hz_d2 = vec2(hz_w.z & 65535u, hz_w.z >> 16u) - hz_t0;\n \
uint hz_w3 = hz_vertices[hz_q + 21u];\n \
uint hz_w3 = hz_uv3;\n \
vec2 hz_t3 = vec2(hz_w3 & 65535u, hz_w3 >> 16u);\n \
hz_mid = (clamp(hz_t0 * hz_uv_scale, 0.0, 1.0) + clamp((hz_t0 + hz_d1) * hz_uv_scale, 0.0, 1.0)\n \
+ clamp((hz_t0 + hz_d2) * hz_uv_scale, 0.0, 1.0) + clamp(hz_t3 * hz_uv_scale, 0.0, 1.0)) * 0.25;\n \
@@ -620,11 +700,19 @@ impl PackAtlas {
/// The vertex inputs of a gbuffers program drawing terrain (`TerrainVertex`, terrain.wgsl's
/// `vs_terrain` or, for `flat` draws, `vs_terrain_flat`), in atlas coordinates.
pub fn terrain_inputs(&self, flat: bool) -> horizon_shaders::GbuffersInputs {
let mut declarations = String::from(
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in uvec2 hz_v_uv;\n\
layout(location = 2) in uint hz_v_layer;\nlayout(location = 3) in vec4 hz_v_color;\n\
layout(location = 4) in uvec2 hz_v_light;\n",
);
// Flat draws pull their vertices from the arena page (`PULL_FLAT`), which may hold
// solid quads in the compact layout; others read them as vertex attributes.
let mut declarations = if flat {
String::from(
"vec3 hz_v_pos; uvec2 hz_v_uv; uint hz_v_layer; vec4 hz_v_color; uvec2 hz_v_light;\n",
)
} else {
String::from(
"layout(location = 0) in vec3 hz_v_pos;\nlayout(location = 1) in uvec2 hz_v_uv;\n\
layout(location = 2) in uint hz_v_layer;\nlayout(location = 3) in vec4 hz_v_color;\n\
layout(location = 4) in uvec2 hz_v_light;\n",
)
};
let origin = if flat {
declarations.push_str(
"layout(set = 1, binding = 0) readonly buffer HzBlockSlots { uint hz_block_slots[]; };\n\
@@ -637,7 +725,8 @@ impl PackAtlas {
layout(set = 3, binding = 1) readonly buffer HzVertices { uint hz_vertices[]; };\n\
layout(set = 3, binding = 2) readonly buffer HzTerrainTables { int hz_tables[]; };\n",
);
"hz_slot_origins[hz_block_slots[uint(gl_VertexIndex) >> 8u]]"
declarations.push_str(CORNER_FN);
"hz_slot_origins[hz_block_slots[hz_slot >> 8u]]"
} else {
declarations.push_str("layout(location = 5) in vec4 hz_v_origin;\n");
"hz_v_origin"
@@ -700,6 +789,7 @@ impl PackAtlas {
);
let mut body = body;
if flat {
body.insert_str(0, PULL_FLAT);
body.push_str(FACE);
body.push_str(
" uint hz_quad = uint(gl_VertexIndex) / 4u;\n \
@@ -125,7 +125,7 @@ fn terrain_fade_reaches_pack_pixels_through_real_instances() {
terrain: Some(atlas.terrain_inputs(flat)),
terrain_geometry: geometry.then(|| horizon_shaders::GeometryInputs {
inputs: atlas.terrain_inputs(true),
pull: super::PULL.to_owned(),
pull: String::new(),
index: "@".to_owned(),
}),
..Default::default()
@@ -245,6 +245,135 @@ fn terrain_vertices_go_down_to_the_32768th_below_them() {
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
/// A shader pack's flat terrain inputs read a compact record (`mesher::packed`) as the four
/// vertices it holds: a whole tinted face with its own ambient occlusion per corner
/// (`separateAo`), two more, and a slab's top kept as its vertices (`packed::FULL`).
#[test]
fn compact_records_feed_a_pack_the_vertices_they_hold() {
use crate::mesher::packed;
let instance = crate::gfx::test_gpu::instance();
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
return;
};
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).unwrap();
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 16,
height: 16,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let mut encoder = device.create_command_encoder(&Default::default());
let mut atlas = PackAtlas::new(&device, &mut encoder, &[texture], 1, 1, 16).unwrap();
queue.submit([encoder.finish()]);
atlas.separate_ao = true;
let tint = 0x7F_B238u32;
let ao = [255u32, 153, 102, 204];
let face = |x: f32, y: f32| {
let pos = [
[x, y, 5.0],
[x, y, 6.0],
[x + 1.0, y, 6.0],
[x + 1.0, y, 5.0],
];
let uv = [[0, 0], [16 << 10, 0], [16 << 10, 16 << 10], [0, 16 << 10]];
(0..4).map(move |i| {
let [r, g, b] = [16, 8, 0].map(|s| 200 * (tint >> s & 255) / 255);
TerrainVertex {
pos: pos[i],
uv: uv[i],
layer: 0x8000,
light: 0xF0 | 0x40 << 8,
color: r | g << 8 | b << 16 | ao[i] << 24,
}
})
};
let solid: Vec<_> = [(3.0, 16.0), (5.0, 16.0), (7.0, 16.0), (3.0, 8.5)]
.into_iter()
.flat_map(|(x, y)| face(x, y))
.collect();
let records = packed::layout(&solid, &[tint; 4]);
assert_eq!(
packed::packed_quads(&records, 4),
3,
"whole faces pack, the slab doesn't"
);
let page = bytemuck::cast_slice(&records);
let packed_range = packed::PACKED_BASE..packed::PACKED_BASE + 16;
let origin = f32::from_bits((1. / UV_STEPS).to_bits());
let mut failures = Vec::new();
for expression in [
"gl_Vertex",
"gl_Color",
"vec4(gl_MultiTexCoord0.xy, gl_MultiTexCoord1.xy)",
"vec4(gl_Normal, 0.0)",
"at_tangent",
"at_midBlock",
"vec4(mc_midTexCoord, mc_Entity.xy)",
] {
for shadow in [false, true] {
let flags = [true, shadow];
let wide = sample_probe(&device, &queue, &atlas, &solid, origin, flags, expression);
let compact = sample_page(
&device,
&queue,
&atlas,
page,
packed_range.clone(),
origin,
flags,
expression,
);
let bits = |v: &[[f32; 4]]| v.iter().flatten().map(|f| f.to_bits()).collect::<Vec<_>>();
if bits(&wide) != bits(&compact) {
failures.push(format!(
"{expression} shadow={shadow}: {wide:?} != {compact:?}"
));
}
if expression == "gl_Color" {
for (corner, want) in ao.iter().enumerate() {
let got = compact[corner][3];
if (got - *want as f32 / 255.0).abs() > 1e-6 {
failures.push(format!("corner {corner}'s alpha {got} != {want}/255"));
}
}
}
}
}
// A pack's frames keep the translucent quads in the section arena after the solid range: three
// records and no `FULL` quad, then a water quad, whose corners must read as its own.
let mut page: Vec<[u32; 6]> = packed::layout(&solid[..12], &[tint; 3]);
let water: Vec<_> = face(9.0, 15.0).collect();
let at = page.len() as u32;
page.extend(water.iter().map(|v| bytemuck::cast::<_, [u32; 6]>(*v)));
for expression in ["vec4(gl_Normal, 0.0)", "at_tangent", "at_midBlock"] {
let flags = [true, false];
let wide = sample_probe(&device, &queue, &atlas, &water, origin, flags, expression);
let page = bytemuck::cast_slice(&page);
let after = sample_page(
&device,
&queue,
&atlas,
page,
at..at + 4,
origin,
flags,
expression,
);
if wide != after {
failures.push(format!("water {expression}: {wide:?} != {after:?}"));
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
fn sample(
device: &wgpu::Device,
queue: &wgpu::Queue,
@@ -271,18 +400,38 @@ fn sample_probe(
atlas: &PackAtlas,
vertices: &[TerrainVertex],
scale: f32,
flags: [bool; 2],
expression: &str,
) -> Vec<[f32; 4]> {
let page = bytemuck::cast_slice(vertices);
let drawn = 0..vertices.len() as u32;
sample_page(device, queue, atlas, page, drawn, scale, flags, expression)
}
/// `sample_probe` of the vertex indices `drawn` of an arena page holding `page`.
#[allow(clippy::too_many_arguments)]
fn sample_page(
device: &wgpu::Device,
queue: &wgpu::Queue,
atlas: &PackAtlas,
page: &[u8],
drawn: std::ops::Range<u32>,
scale: f32,
[flat, shadow]: [bool; 2],
expression: &str,
) -> Vec<[f32; 4]> {
let count = drawn.len() as u32;
let pp = |code| horizon_shaders::Preprocessed {
code,
..Default::default()
};
let vertex = pp(format!(
"attribute vec2 mc_midTexCoord;\nvarying vec4 probe;\nvoid main() {{\n\
"attribute vec2 mc_midTexCoord;\nattribute vec4 at_tangent;\n\
attribute vec4 at_midBlock;\nattribute vec4 mc_Entity;\nvarying vec4 probe;\nvoid main() {{\n\
probe = {expression};\n\
gl_Position = vec4((float(gl_VertexID) + 0.5) * {} - 1.0, 0.0, 0.0, 1.0);\n}}",
2. / vertices.len() as f32,
gl_Position = vec4((float(gl_VertexID - {}) + 0.5) * {} - 1.0, 0.0, 0.0, 1.0);\n}}",
drawn.start,
2. / count as f32,
));
// Integer attachments retain the float bits without requiring float-render-target
// capabilities on the adapter that the test runner picks.
@@ -369,7 +518,8 @@ fn sample_probe(
module: &vs,
entry_point: Some("main"),
compilation_options: Default::default(),
buffers: &vertex_layouts[..if flat { 1 } else { 2 }],
// Flat draws pull their vertices from the page (`PULL_FLAT`), as in the game.
buffers: if flat { &[] } else { &vertex_layouts[..] },
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::PointList,
@@ -408,7 +558,7 @@ fn sample_probe(
);
let ids = buffer(bytemuck::bytes_of(&[0u32; 2]), wgpu::BufferUsages::STORAGE);
let data = buffer(
bytemuck::cast_slice(vertices),
page,
wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::VERTEX,
);
let rects = buffer(
@@ -444,7 +594,7 @@ fn sample_probe(
let output = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: vertices.len() as u32,
width: count,
height: 1,
depth_or_array_layers: 1,
},
@@ -457,7 +607,7 @@ fn sample_probe(
});
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: vertices.len() as u64 * 16,
size: u64::from(count) * 16,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -481,11 +631,11 @@ fn sample_probe(
for (k, group) in groups.iter().enumerate() {
pass.set_bind_group(k as u32, group, &[]);
}
pass.set_vertex_buffer(0, data.slice(..));
if !flat {
pass.set_vertex_buffer(0, data.slice(..));
pass.set_vertex_buffer(1, origin.slice(..));
}
pass.draw(0..vertices.len() as u32, 0..1);
pass.draw(drawn, 0..1);
}
encoder.copy_texture_to_buffer(
output.as_image_copy(),
@@ -1137,6 +1137,10 @@ fn components(name: &str) -> usize {
| "endFlashPosition" => 3,
"eyeBrightness" | "eyeBrightnessSmooth" | "atlasSize" => 2,
"entityColor" => 4,
// Horizon's own vec4s, a dynamic light and half a boat's water patch box; their counts
// are ints.
n if n.starts_with("horizonDynamicLight") && n != "horizonDynamicLightCount" => 4,
n if n.starts_with("horizonWaterPatch") && n != "horizonWaterPatchCount" => 4,
n if n.starts_with("gbuffer") || n.starts_with("shadow") && n != "shadowAngle" => 16,
_ => 1,
}
@@ -1208,6 +1212,28 @@ mod tests {
(&matrix, "gbufferModelView", "mat4", true),
(&matrix, "gbufferModelView", "mat3", false),
(&Value::i(&[1]), GBUFFERS_FOG_MODE, "int", true),
// Horizon's own: a dynamic light and a water patch box half are vec4s, their counts
// ints.
(
&Value::f(&[1.0, 64.0, 2.0, 14.0]),
"horizonDynamicLight0",
"vec4",
true,
),
(
&Value::f(&[1.0, 64.0, 2.0, 14.0]),
"horizonDynamicLight0",
"float",
false,
),
(
&Value::f(&[0.5, -1.0, 62.0, 62.5]),
"horizonWaterPatch0",
"vec4",
true,
),
(&Value::i(&[3]), "horizonDynamicLightCount", "int", true),
(&Value::i(&[1]), "horizonWaterPatchCount", "int", true),
] {
assert_eq!(value.read_as(name, ty), kept, "{ty} {name}");
}
@@ -0,0 +1,60 @@
//! How far through vanilla's chunk fade-in a section is, and the instance that carries it to `terrain.wgsl`.
use crate::fast_hash::FxHashMap;
use std::time::Instant;
/// A section's instance: its camera-relative origin and its UV step, negated
/// past its fade code while it fades in over far terrain (`lod::instance`).
pub(super) fn section_instance(origin: [f32; 3], fade: u32, visibility: f32) -> [f32; 4] {
let step = 1.0 / crate::mesher::UV_STEPS;
[
origin[0],
origin[1],
origin[2],
if fade == 0 {
// The step is a power of two, so its mantissa is free: it holds the vanilla
// chunk fade-in's `1 - visibility` in 23 bits (terrain.wgsl's `instance_step` and
// `instance_visibility` read it back). A whole section is the bare step.
let faded = ((1.0 - visibility) * 8_388_608.0)
.round()
.clamp(0.0, 8_388_607.0) as u32;
f32::from_bits(step.to_bits() | faded)
} else {
-(fade as f32 + step)
},
]
}
/// `SectionRenderDispatcher.RenderSection.getVisibility`: how far through its fade-in a section
/// uploaded `elapsed_ms` ago is.
pub(super) fn chunk_visibility(elapsed_ms: u64, fade_ms: u64) -> f32 {
if elapsed_ms >= fade_ms {
1.0
} else {
elapsed_ms as f32 / fade_ms as f32
}
}
/// `Util.toMillis`: `Mth.floor(seconds * 1000.0)`.
pub(super) fn fade_millis(seconds: f32) -> u64 {
(f64::from(seconds) * 1000.0).floor().max(0.0) as u64
}
/// `chunk_visibility` at `now` of a section first uploaded at `uploaded`
/// (`Renderer::section_uploaded`; none: one that fades in over far terrain, or
/// whose column left), with the chunk fade-in `fade_ms`.
pub(super) fn section_visibility(uploaded: Option<&Instant>, fade_ms: u64, now: Instant) -> f32 {
uploaded.map_or(1.0, |&t| {
let elapsed = now.saturating_duration_since(t).as_millis() as u64;
chunk_visibility(elapsed, fade_ms)
})
}
/// What a section's fade depends on besides the section itself
/// (`SectionGpu::drawn_faded`): the time, the chunk fade-in time, the sections'
/// first uploads (`Renderer::section_uploaded`) and those held while far
/// terrain comes in (`Renderer::lod_retiring`).
#[derive(Clone, Copy)]
pub(super) struct FadeInputs<'a> {
pub(super) now: Instant,
pub(super) fade_ms: u64,
pub(super) uploaded: &'a FxHashMap<super::SectionKey, Instant>,
pub(super) retiring: &'a crate::fast_hash::FxHashSet<super::SectionKey>,
}
/// `LevelRenderer.CHUNK_VISIBILITY_THRESHOLD`: a section's block entities wait for it.
pub(super) const CHUNK_VISIBILITY_THRESHOLD: f32 = 0.3;
+6 -5
View File
@@ -30,8 +30,9 @@ fn marker_driver(text: &str) -> &str {
pub struct Reported {
pub paper_white: u32,
pub peak: u32,
/// The peak is the display's own claim (DXGI's `MaxLuminance`, mostly its EDID figure),
/// which often runs high: Auto still uses it, but the HDR page asks to calibrate.
/// The peak is the system's own figure (DXGI's `MaxLuminance`): the display's, or a
/// calibration profile's (Windows HDR Calibration), which Horizon can't tell apart. Auto
/// uses it, and the HDR page offers calibration.
pub peak_guessed: bool,
}
@@ -40,7 +41,7 @@ pub struct Reported {
pub enum HdrSetup {
/// The system says nothing: the player calibrates.
Unknown,
/// The system says, but only guesses the peak: the player calibrates.
/// The system says, but not where its peak comes from: the page offers calibration.
Guessed,
/// Peak Brightness and Paper White follow the system.
Automatic,
@@ -1355,7 +1356,7 @@ mod tests {
}
#[test]
fn hdr_setup_asks_to_calibrate_where_the_peak_is_guessed() {
fn hdr_setup_offers_calibration_where_the_peaks_source_is_unknown() {
let wayland = Reported {
paper_white: 203,
peak: 1015,
@@ -1370,7 +1371,7 @@ mod tests {
assert_eq!(g.hdr_setup(None), HdrSetup::Unknown);
assert_eq!(g.hdr_setup(Some(wayland)), HdrSetup::Automatic);
assert_eq!(g.hdr_setup(Some(windows)), HdrSetup::Guessed);
// Auto still takes the guess, over the 1000-nit default.
// Auto still takes the reported peak, over the 1000-nit default.
assert_eq!(g.peak_nits(Some(windows)), 1000);
assert_eq!(g.paper_white_nits(Some(windows)), 400);
for (peak, paper_white) in [(800, 0), (0, 240)] {
+70 -12
View File
@@ -697,7 +697,7 @@ fn description(
"Your display didn't say how bright it gets: calibrate to set it up."
}
(Item::Horizon(H::HdrCalibrate), Setup::Guessed) => {
"Your display's reported peak is often too high: calibrate to set it up."
"Auto uses the peak Windows reports. Calibrate if highlights look clipped."
}
(Item::Horizon(H::HdrCalibrate), Setup::Automatic) => {
"Already set up for your display. Only calibrate if HDR looks wrong."
@@ -705,7 +705,7 @@ fn description(
(Item::Horizon(H::HdrCalibrate), Setup::Changed) => {
"Puts Peak Brightness and Paper White back to your display's setup."
}
// A guessed peak's Auto is what calibration replaced; paper white is the player's own.
// A peak of unknown source isn't said to be set up; paper white is the player's own.
(Item::Horizon(h @ (H::HdrPeak | H::HdrPaperWhite)), Setup::Automatic | Setup::Changed)
if h == H::HdrPaperWhite || out.reported.is_some_and(|r| !r.peak_guessed) =>
{
@@ -1219,10 +1219,13 @@ impl Item {
}
pub fn label(self, s: &Settings, out: &EffectiveOutput) -> Text {
match self {
Item::Vanilla(Opt::RenderDistance) if s.horizon.lod_distance > 0 => labelled(
"Full Detail Distance",
lang::tr("%s chunks", &[&s.render_distance]),
),
// Far terrain renames the row; its value stays vanilla's `options.chunks`.
Item::Vanilla(Opt::RenderDistance) if s.horizon.lod_distance > 0 => {
Text::option_name_value(
Text::literal(lang::get("Full Detail Distance")),
Text::tr("options.chunks", &[&s.render_distance]),
)
}
Item::Vanilla(o) => o.label(s),
Item::Horizon(h) => h.label(s, out),
Item::Extra(e) => Text::option_name_value(
@@ -1318,7 +1321,11 @@ impl Item {
/// Whether a setting is on the screen now: Upscaling only while TAA is, which does it.
fn shown(item: Item, s: &Settings) -> bool {
item != Item::Horizon(H::Upscaling) || s.horizon.taa
match item {
Item::Horizon(H::Upscaling) => s.horizon.taa,
Item::Extra(crate::extras::Item::Fullbright) => !s.fullbright_held,
_ => true,
}
}
/// A control's label as its name and its value ("Render Distance" and "12 chunks").
fn parts(item: Item, s: &Settings, out: &EffectiveOutput) -> (String, Option<String>) {
@@ -1430,7 +1437,7 @@ impl Screen for GraphicsScreen {
g::gpu_culling_offer(),
g::reduced_far_detail_suggested(),
);
shell::stamp_of(&(read(s), offers))
shell::stamp_of(&(read(s), s.fullbright_held, offers))
}
fn sheets(&self, s: &Settings) -> Vec<Sheet<Page, Item>> {
let sheet = |(page, groups): (Page, Vec<(&'static str, Vec<Setting>)>)| Sheet {
@@ -1990,6 +1997,31 @@ mod tests {
assert_eq!(key(&mut ui, &mut s, K::Escape), [Output::Done]);
}
/// On another's server Fullbright's row is gone and the screen draws again; its choice is
/// kept for the next world that allows it (#3823).
#[test]
fn fullbright_row_is_hidden_while_held_and_keeps_its_choice() {
let mut s = Settings::default();
s.extras.fullbright = true;
let screen = GraphicsScreen::default();
let listed = |s: &Settings, item| {
let sheets = screen.sheets(s);
let groups = sheets.into_iter().flat_map(|sheet| sheet.groups);
groups.flat_map(|group| group.rows).any(|r| r.id == item)
};
let fullbright = Item::Extra(crate::extras::Item::Fullbright);
let lights = Item::Extra(crate::extras::Item::DynamicLights);
assert!(listed(&s, fullbright));
let free = screen.stamp(&s);
s.fullbright_held = true;
assert!(!listed(&s, fullbright));
assert!(listed(&s, lights));
assert_ne!(screen.stamp(&s), free);
assert!(s.extras.fullbright);
s.fullbright_held = false;
assert!(listed(&s, fullbright));
}
/// The strip says what a row does, what its chosen value does where that differs, and why a
/// greyed row can't be used; the search finds a row by what it does.
#[test]
@@ -2110,10 +2142,36 @@ mod tests {
assert_eq!(item.slider(&s), Some(13.0 / 23.0));
s.horizon.lod_distance = 12;
assert_eq!(item.slider(&s), Some(1.0 / 23.0));
assert_eq!(
Item::Vanilla(Opt::RenderDistance).label(&s, &NONE).plain(),
format!("Full Detail Distance: {near} chunks")
);
}
/// With far terrain on, Render Distance reads "Full Detail Distance" but keeps vanilla's
/// `options.chunks` value: it was Horizon's "%s chunks", so "12 Chunks" became "12 chunks"
/// (#14880).
#[test]
fn full_detail_distance_keeps_the_vanilla_chunk_count() {
struct Vanilla;
impl lang::ResourceSource for Vanilla {
fn read(&self, path: &str) -> Option<Vec<u8>> {
(path == "assets/minecraft/lang/en_us.json").then(|| {
serde_json::to_vec(&serde_json::json!({
"options.renderDistance": "Render Distance",
"options.chunks": "%s Chunks",
"options.generic_value": "%s: %s"
}))
.unwrap()
})
}
}
let mut s = Settings::default();
let near = s.render_distance;
let render = Item::Vanilla(Opt::RenderDistance);
let ((off, on), _) = lang::scoped(lang::Language::load(&[&Vanilla], "en_us"), || {
let off = render.label(&s, &NONE).plain();
s.horizon.lod_distance = 256;
(off, render.label(&s, &NONE).plain())
});
assert_eq!(off, format!("Render Distance: {near} Chunks"));
assert_eq!(on, format!("Full Detail Distance: {near} Chunks"));
}
#[test]
@@ -164,7 +164,7 @@ fn auto_levels_and_setup_read_their_own_renderers_report() {
}
/// The setup rows' label and description for each kind of report: none, a compositor's
/// (Wayland), and Windows', whose peak is the display's own guess.
/// (Wayland), and Windows', whose peak may be the display's or a calibration profile's.
#[test]
fn the_setup_rows_ask_to_calibrate_unless_the_system_set_the_display_up() {
let trusted = offering(true, Some(true));
@@ -200,7 +200,7 @@ fn the_setup_rows_ask_to_calibrate_unless_the_system_set_the_display_up() {
[
(
calibrate.into(),
"Your display's reported peak is often too high: calibrate to set it up."
"Auto uses the peak Windows reports. Calibrate if highlights look clipped."
),
("Peak Brightness: Auto (1000)".into(), "-"),
("Paper White: Auto (400)".into(), "-"),
@@ -219,7 +219,7 @@ fn the_setup_rows_ask_to_calibrate_unless_the_system_set_the_display_up() {
);
// Calibrated or set by hand, either report offers its automatic setup back.
s.horizon.hdr_peak = 800;
// Peak's Auto stays a guess on Windows: only Paper White is said to be set up there.
// Peak's Auto has no known source on Windows: only Paper White is said to be set up there.
let changed = |peak| {
[
(
@@ -348,3 +348,30 @@ fn undo_never_restores_a_held_hdr_start() {
screen.undo(&mut s, &opened);
assert_eq!(s.horizon, opened.horizon);
}
/// The Calibrate row's descriptions fit the strip's two lines at vanilla's 427-wide GUI (a
/// 1080p window at scale 4 is wider): a longer one would end in "…".
#[test]
fn the_calibrate_descriptions_fit_the_strip() {
let atlas = crate::hud::HudAtlas::build(std::path::Path::new("/nonexistent")).unwrap();
let mut guessed = offering(true, Some(true));
guessed.reported = guessed.reported.map(|r| crate::graphics::Reported {
peak_guessed: true,
..r
});
let mut changed = Settings::default();
changed.horizon.hdr_peak = 800;
let item = Item::Horizon(H::HdrCalibrate);
let width = Columns::of(427.0, 240.0).dock[2] - 24.0;
for (s, out) in [
(Settings::default(), NONE),
(Settings::default(), guessed),
(Settings::default(), offering(true, Some(true))),
(changed, guessed),
] {
let text = description(item, &s, &out, "-");
assert_ne!(text, "-");
let lines = atlas.font.split(&Text::literal(text.to_owned()), width);
assert!(lines.len() <= 2, "{text}");
}
}
+45 -6
View File
@@ -173,13 +173,52 @@ fn calibration_picture(pos: vec4<f32>) -> vec4<f32> {
return vec4(nits / 80.0, 1.0);
}
// Light in units of paper white, as the swapchain takes it: HDR10 or scRGB, the black level
// lifted.
fn display(light: vec3<f32>) -> vec4<f32> {
// On for the HDR10 swapchain alone (Hdr::new): its 10 bits get dither. A screenshot's HDR10 copy
// (Hdr::capture) keeps the exact codes, and scRGB's floats need none.
override pq_dither: bool = false;
// Three even random values in [0, 1) for `at`: PCG's 3D hash (Jarzynski and Olano, "Hash Functions
// for GPU Rendering", JCGT 2020). Integers only, so it is the same on every GPU and at every
// resolution, where hashes built on `fract(sin())` repeat or streak at 4K's coordinates.
// Copyright 2020 Mark Jarzynski & Marc Olano, MIT (github.com/markjarzynski/PCG3D; the license is in
// THIRD_PARTY_NOTICES.md).
fn hash3(at: vec3<u32>) -> vec3<f32> {
var v = at * 1664525u + 1013904223u;
v.x += v.y * v.z;
v.y += v.z * v.x;
v.z += v.x * v.y;
v ^= v >> vec3(16u);
v.x += v.y * v.z;
v.y += v.z * v.x;
v.z += v.x * v.y;
return vec3<f32>(v >> vec3(8u)) / 16777216.0;
}
// The PQ signal `e` with dither for its 10 bits: triangular noise of one code either way, each
// channel's own, so a slow gradient (a clear sky is a few codes tall) shows as grain a code deep
// instead of bands, and its mean is the light meant. The noise is the pixel's alone: no frame
// counter, so a still picture stays still. Within a code of black or of the top it shrinks to
// what fits: the signal never leaves 0..1, and black stays exactly black (an OLED's pixel off).
// The price is in that last code alone: the smaller noise keeps the signal's mean but not the
// rounded one, which leans to the end (a third of a code from it shows as an eighth). Under
// 0.00004 nits at black, that is the accepted cost of a true 0.
fn dithered(e: vec3<f32>, pixel: vec2<f32>) -> vec3<f32> {
let at = vec2<u32>(pixel);
let noise = hash3(vec3(at, 0u)) + hash3(vec3(at, 1u)) - 1.0;
return e + noise * min(min(e, 1.0 - e), vec3(1.0 / 1023.0));
}
// Light in units of paper white at the pixel `pos`, as the swapchain takes it: HDR10 or scRGB,
// the black level lifted.
fn display(light: vec3<f32>, pos: vec4<f32>) -> vec4<f32> {
let scrgb = light * params.paper;
if params.pq > 0.5 {
let e = pq(BT709_TO_BT2020 * scrgb * 80.0);
return vec4(select(e, lift_black(e), params.black > 0.0), 1.0);
let lifted = select(e, lift_black(e), params.black > 0.0);
if pq_dither {
return vec4(dithered(lifted, pos.xy), 1.0);
}
return vec4(lifted, 1.0);
}
if params.black > 0.0 {
return vec4(pq_nits(lift_black(pq(scrgb * 80.0))) / 80.0, 1.0);
@@ -209,7 +248,7 @@ fn display(light: vec3<f32>) -> vec4<f32> {
// The HUD and menus at their own brightness, by how much they cover, no brighter than the
// peak (as `fs_hdr_layered`): UI Brightness can pass paper white.
light = min(light * mix(1.0, params.ui, ui), vec3(params.peak));
return display(light);
return display(light, pos);
}
// The tone curve's knee: up to it light stays as it is. Where HDR lighting eased into the peak
@@ -328,5 +367,5 @@ override screenshot_shoulder: bool = true;
if calibrating(pos) {
return calibration_picture(pos);
}
return display(min(pow(layered(vec2<i32>(pos.xy)), vec3(2.2)), vec3(params.peak)));
return display(min(pow(layered(vec2<i32>(pos.xy)), vec3(2.2)), vec3(params.peak)), pos);
}
+14 -2
View File
@@ -52,7 +52,7 @@ pub struct TextureFlags {
impl TextureFlags {
/// The `texture` section of a `.png.mcmeta` file, if it sets either flag.
pub fn from_mcmeta(json: &str) -> Option<Self> {
let meta: serde_json::Value = serde_json::from_str(json).ok()?;
let meta = crate::packs::first_json(json.as_bytes())?;
let section = meta.get("texture")?;
let flag = |key| section.get(key).and_then(serde_json::Value::as_bool) == Some(true);
let flags = Self {
@@ -387,7 +387,7 @@ fn strip_frame(pixels: &[u8], stride: u32, x: u32, y: u32, w: u32, h: u32) -> Ve
}
/// The `animation` section of a texture's `.mcmeta`.
fn animation_of(mcmeta: Option<&str>) -> Option<AnimationMetadata> {
let meta: serde_json::Value = serde_json::from_str(mcmeta?).ok()?;
let meta = crate::packs::first_json(mcmeta?.as_bytes())?;
AnimationMetadata::from_json(&meta.get("animation")?.to_string()).ok()
}
/// An animated strip's first frame: the region the mcmeta's frame size picks
@@ -3110,6 +3110,18 @@ mod coverage_tests;
mod tests {
use super::*;
#[test]
fn animated_texture_metadata_ignores_trailing_pack_signature() {
let meta = r#"{"animation":{"frametime":2,"width":2,"height":2}}
// High Contrast pack signature"#;
let animation = animation_of(Some(meta)).expect("the first JSON value is metadata");
assert_eq!(animation.frame_size(8, 4), [2, 2]);
let pixels = (0..8 * 4).flat_map(|i| [i as u8, 0, 0, 255]).collect();
let (_, height, first) = first_frame((8, 4, pixels), Some(&animation));
assert_eq!(height, 2);
assert_eq!(first.len(), 2 * 2 * 4);
}
#[test]
fn object_skin_revision_tracks_changes_and_capacity_clear() {
let mut atlas = HudAtlas::boot();
+135 -21
View File
@@ -22,6 +22,7 @@ use crate::{
use horizon_core::geometry::{Direction, ShapeOp, VoxelShape};
use horizon_world::registry::{BlockRegistry, BlockStateId};
use std::{
cell::RefCell,
collections::{HashMap, VecDeque},
path::Path,
sync::Arc,
@@ -365,6 +366,48 @@ fn give_scratch(scratch: LightScratch) {
}
}
thread_local! {
static RELIGHT_SCRATCH: RefCell<RelightScratch> = RefCell::new(RelightScratch::new());
}
struct RelightScratch {
decrease: VecDeque<(Pos, u8)>,
cleared: Vec<Pos>,
increase: VecDeque<Pos>,
sources: FxHashMap<(i32, i32), i32>,
}
impl RelightScratch {
fn new() -> Self {
Self {
decrease: VecDeque::new(),
cleared: Vec::new(),
increase: VecDeque::new(),
sources: FxHashMap::default(),
}
}
fn clear(&mut self) {
const MAX_CAPACITY: usize = 16_384;
self.decrease.clear();
if self.decrease.capacity() > MAX_CAPACITY {
self.decrease.shrink_to(MAX_CAPACITY);
}
self.cleared.clear();
if self.cleared.capacity() > MAX_CAPACITY {
self.cleared.shrink_to(MAX_CAPACITY);
}
self.increase.clear();
if self.increase.capacity() > MAX_CAPACITY {
self.increase.shrink_to(MAX_CAPACITY);
}
self.sources.clear();
if self.sources.capacity() > MAX_CAPACITY {
self.sources.shrink_to(MAX_CAPACITY);
}
}
}
/// Where a section sits in the 48-wide region.
#[derive(Clone, Copy)]
struct At {
@@ -880,12 +923,12 @@ impl<'w> Region<'w> {
Self {
layout: world.layout(),
world,
slots: Vec::new(),
slots: Vec::with_capacity(16),
index: FxHashMap::default(),
last: ((i32::MIN, 0, 0), NONE),
}
}
#[inline]
#[inline(always)]
fn slot(&mut self, x: i32, y: i32, z: i32) -> Option<usize> {
let s = self.layout.section_index(y)?;
let key = (x >> 4, s as i32, z >> 4);
@@ -1142,10 +1185,25 @@ pub fn relight(
force: bool,
changed: &mut LightChanges,
) {
let mut region = Region::new(world);
changed.keyed(region.layout);
relight_region(&mut region, tables, sky_light, positions, force, changed);
region.finish();
changed.keyed(world.layout());
if positions.is_empty() {
return;
}
RELIGHT_SCRATCH.with_borrow_mut(|scratch| {
scratch.clear();
let mut region = Region::new(world);
relight_region(
&mut region,
tables,
sky_light,
positions,
force,
scratch,
changed,
);
region.finish();
scratch.clear();
});
}
/// The columns `changed` touched that border a loaded column not lit yet
/// (`unlit`). `relight` reads and writes only lit columns, so an edit's
@@ -1170,10 +1228,11 @@ fn relight_region(
sky_light: bool,
positions: &[Pos],
force: bool,
scratch: &mut RelightScratch,
changed: &mut LightChanges,
) {
crate::spans::time("lt_block", || {
relight_layer(world, tables, false, positions.to_vec(), force, changed)
relight_layer(world, tables, false, positions, force, scratch, changed)
});
if sky_light {
let (min_y, max_y) = (world.layout.min_y(), world.layout.max_y());
@@ -1201,7 +1260,7 @@ fn relight_region(
}
});
crate::spans::time("lt_sky", || {
relight_layer(world, tables, true, seeds, force, changed)
relight_layer(world, tables, true, &seeds, force, scratch, changed)
});
}
}
@@ -1209,14 +1268,30 @@ fn relight_layer(
world: &mut Region,
tables: &LightTables,
sky: bool,
seeds: Vec<Pos>,
seeds: &[Pos],
force: bool,
scratch: &mut RelightScratch,
changed: &mut LightChanges,
) {
let mut decrease: VecDeque<(Pos, u8)> = VecDeque::new();
let mut cleared: Vec<Pos> = Vec::new();
let mut increase: VecDeque<Pos> = VecDeque::new();
for p in seeds {
scratch.decrease.clear();
scratch.cleared.clear();
scratch.increase.clear();
scratch.sources.clear();
if seeds.len() > scratch.decrease.capacity() {
scratch.decrease.reserve(seeds.len());
}
if seeds.len() > scratch.cleared.capacity() {
scratch.cleared.reserve(seeds.len());
}
if seeds.len() > scratch.increase.capacity() {
scratch.increase.reserve(seeds.len());
}
let decrease = &mut scratch.decrease;
let cleared = &mut scratch.cleared;
let increase = &mut scratch.increase;
for &p in seeds {
let Some(old) = level(world, sky, p) else {
continue;
};
@@ -1267,13 +1342,22 @@ fn relight_layer(
}
}
// Sources inside the cleared area light up again.
let mut sources: FxHashMap<(i32, i32), i32> = FxHashMap::default();
let sources = &mut scratch.sources;
let mut last_xz = (i32::MIN, i32::MIN);
let mut last_lowest = 0;
crate::spans::time("lt_sources", || {
for p in cleared {
for &p in cleared.iter() {
let seed = if sky {
let lowest = *sources
.entry((p.0, p.2))
.or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2));
let lowest = if (p.0, p.2) == last_xz {
last_lowest
} else {
let lowest = *sources
.entry((p.0, p.2))
.or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2));
last_xz = (p.0, p.2);
last_lowest = lowest;
lowest
};
if p.1 >= lowest { 15 } else { 0 }
} else {
world
@@ -2119,9 +2203,39 @@ pub(crate) mod tests {
relight(&mut w, &t, true, &positions, false, &mut changed);
}
println!(
"relight_bench: {:?}, {} sections",
start.elapsed(),
changed.sections().count()
"relight_bench (large batch: 400 rounds x 32 blocks): {:?}",
start.elapsed()
);
}
#[test]
#[ignore]
fn relight_single_block_bench() {
let mut w: FxHashMap<_, _> = world(|_| {}).into_iter().collect();
let t = tables();
let mut rng = 0x2545_f491_u32;
let mut next = |n: i32| {
rng ^= rng << 13;
rng ^= rng >> 17;
rng ^= rng << 5;
(rng % n as u32) as i32
};
let start = std::time::Instant::now();
let mut changed = LightChanges::default();
for round in 0..2000 {
let state = [TORCH, SLAB, AIR][round % 3];
let pos = (next(32) - 8, next(12), next(32) - 8);
Arc::make_mut(w.get_mut(&(pos.0 >> 4, pos.2 >> 4)).unwrap()).set(
pos.0 & 15,
pos.1,
pos.2 & 15,
state,
);
relight(&mut w, &t, true, &[pos], false, &mut changed);
}
println!(
"relight_single_block_bench (single block: 2000 rounds): {:?}",
start.elapsed()
);
}
@@ -13,8 +13,9 @@
//! - word 1: each corner's grey level before the tint;
//! - word 2: the UV rectangle in 1/32 of the sprite (u0, u1, v0, v1, 6 bits each) and, per
//! corner, which edge of it its u and v take;
//! - word 3: the layer, and corner 0's light (sky and block light over 4, 6 bits each);
//! - word 4: corners 1 and 2's light;
//! - word 3: the layer, corner 0's light (sky and block light over 4, 6 bits each), and
//! corner 1's alpha code (`ALPHA_STEP` times it; 0: word 0's alpha);
//! - word 4: corners 1 and 2's light, and corners 2 and 3's alpha codes;
//! - word 5: corner 3's light, the face (block x, y, z, the axis it faces along, which side
//! of the block, and where and which way its corners go round), and `FULL` clear.
use super::TerrainVertex;
@@ -27,6 +28,8 @@ pub const WHITE: u32 = 0xFF_FFFF;
/// Word 5's bit of a quad kept as four vertices; word 0 is then the slots from the record
/// to its first vertex.
pub const FULL: u32 = 1 << 31;
/// The step of a corner's own alpha (words 3 and 4's codes): 255 / 5.
pub const ALPHA_STEP: u32 = 51;
/// The draws' base vertex of a compact mesh: `PACKED_BASE + 4 * slot + corner` is a corner of
/// the quad whose record is at `slot`; below it, vertex indices name vertices.
pub const PACKED_BASE: u32 = 1 << 28;
@@ -133,12 +136,24 @@ pub fn pack_quad(quad: &[TerrainVertex; 4], tint: u32) -> Option<[u32; 6]> {
for (i, v) in quad.iter().enumerate() {
grays |= gray_of(v.color, tint)? << (8 * i);
}
// Corners 1 to 3's alpha (a shader pack's `separateAo`: each corner's ambient occlusion,
// multiples of 51 on a whole face): `ALPHA_STEP` times the code, 0 for corner 0's.
let mut codes = [0u32; 3];
for (code, v) in codes.iter_mut().zip(&quad[1..]) {
let a = v.color >> 24;
if v.color & 0xFF00_0000 != alpha {
if a == 0 || a % ALPHA_STEP != 0 {
return None;
}
*code = a / ALPHA_STEP;
}
}
let words = [
tint | alpha,
grays,
rect | select << 24,
u32::from(quad[0].layer) | light[0] << 16,
light[1] | light[2] << 12,
u32::from(quad[0].layer) | light[0] << 16 | codes[0] << 28,
light[1] | light[2] << 12 | codes[1] << 24 | codes[2] << 27,
light[3] | orient << 12,
];
let exact = (0..4).all(|c| {
@@ -190,12 +205,18 @@ pub fn packed_vertex(words: &[u32; 6], corner: usize) -> TerrainVertex {
let light = ((light & 63) << 2 | (light >> 6 & 63) << 10) as u16;
let g = w1 >> (8 * i) & 255;
let [r, gr, b] = channels(w0).map(|t| g * t / 255);
let code = [0, w3 >> 28 & 7, w4 >> 24 & 7, w4 >> 27 & 7][corner];
let alpha = if code == 0 {
w0 & 0xFF00_0000
} else {
(code * ALPHA_STEP) << 24
};
TerrainVertex {
pos: pos.map(|c| c as f32),
uv,
layer: (w3 & 0xFFFF) as u16,
light,
color: r | gr << 8 | b << 16 | (w0 & 0xFF00_0000),
color: r | gr << 8 | b << 16 | alpha,
}
}
@@ -247,11 +268,10 @@ pub fn place_into(
let n = quads.len();
let packed = records.iter().filter(|r| r.is_some()).count();
let full = n - packed;
let pad = if full > 0 {
n.next_multiple_of(4) - n
} else {
0
};
// Whole quads of slots: what follows (a quad's own vertices, the translucent ones after
// the solid range) then starts a quad, as a shader pack's vertex stage reads its quad's
// corners from the vertex index (`pack_atlas::PULL_FLAT`).
let pad = n.next_multiple_of(4) - n;
if n + pad + 4 * full >= 4 * n {
return;
}
@@ -334,6 +354,22 @@ mod tests {
}
}
#[test]
fn each_corners_ambient_occlusion_alpha_packs_on_its_steps() {
// A shader pack's `separateAo`: the alpha byte is each corner's occlusion.
let mut quad = top([0, 1, 2, 3]);
for (v, a) in quad.iter_mut().zip([153u32, 255, 51, 204]) {
v.color = v.color & 0x00FF_FFFF | a << 24;
}
let words = pack_quad(&quad, TINT).expect("occlusion on the 51 steps packs");
for (corner, v) in quad.iter().enumerate() {
assert!(same(&packed_vertex(&words, corner), v), "corner {corner}");
}
// A partial face's blended occlusion falls between the steps.
quad[2].color = quad[2].color & 0x00FF_FFFF | 140 << 24;
assert!(pack_quad(&quad, TINT).is_none());
}
#[test]
fn quads_off_the_grid_or_the_steps_keep_their_vertices() {
// Half a block up: a slab's top.
@@ -375,4 +411,13 @@ mod tests {
// Nothing smaller to gain: no layout at all.
assert!(layout(&odd, &[TINT]).is_empty());
}
#[test]
fn the_records_end_on_a_whole_quad_of_slots() {
// Five whole faces, every one a record: the translucent vertices after them start a quad.
let solid: Vec<TerrainVertex> = (0..5).flat_map(|_| top([0, 1, 2, 3])).collect();
let out = layout(&solid, &[TINT; 5]);
assert_eq!(packed_quads(&out, 5), 5);
assert_eq!(out.len(), 8);
}
}
+256 -13
View File
@@ -368,6 +368,57 @@ pub struct PackScreen {
browser_search: TextField,
/// The browser's search box has the keyboard.
browser_focus: bool,
/// Which atlas slot holds which icon, kept from one frame to the next
/// ([`PackScreen::bind_icons`]).
icon_slots: std::cell::RefCell<IconSlots>,
}
/// The atlas's pack icon slots and the icon each holds. The atlas keeps what is
/// written into a slot, so an icon is sent once, when it takes a slot, and not
/// again every frame it is drawn.
#[derive(Clone, Debug, Default)]
struct IconSlots {
/// The atlas the pixels went into ([`HudAtlas::revision`]); a new atlas holds none of them.
revision: u64,
/// Frames bound so far: an icon drawn in this one keeps its slot.
frame: u64,
/// Least recently drawn first: the icon's texture key, its slot, its pixels, and the
/// frame it was last drawn in.
held: Vec<(String, usize, Arc<[u8]>, u64)>,
}
impl IconSlots {
/// Starts a frame on `atlas`; an atlas that is not the one the slots were filled in empties them.
fn begin(&mut self, atlas: &HudAtlas) {
if self.revision != atlas.revision {
self.held.clear();
self.revision = atlas.revision;
}
self.frame += 1;
}
/// The slot for the icon drawn under `texture`, and whether its pixels have to be sent. A new
/// icon takes a free slot, else the slot of the icon drawn longest ago; none when every slot
/// holds an icon drawn in this frame, and that icon keeps `unknown_pack`.
fn slot_for(&mut self, texture: &str, icon: &Arc<[u8]>) -> Option<(usize, bool)> {
if let Some(at) = self.held.iter().position(|h| h.0 == texture) {
let mut kept = self.held.remove(at);
let same = Arc::ptr_eq(&kept.2, icon);
kept.2 = icon.clone();
kept.3 = self.frame;
let slot = kept.1;
self.held.push(kept);
return Some((slot, !same));
}
let slot = match (0..PACK_ICON_SLOTS).find(|i| !self.held.iter().any(|h| h.1 == *i)) {
Some(free) => free,
None if self.held.first().is_some_and(|h| h.3 < self.frame) => self.held.remove(0).1,
None => return None,
};
self.held
.push((texture.to_owned(), slot, icon.clone(), self.frame));
Some((slot, true))
}
}
fn tr(key: &str) -> Text {
@@ -459,6 +510,7 @@ impl PackScreen {
field
},
browser_focus: false,
icon_slots: Default::default(),
changed: false,
};
s.reposition(m);
@@ -931,10 +983,13 @@ impl PackScreen {
self.model.commit()
}
/// Points the icon blits of `draws` at the atlas's pack icon slots and
/// writes the icons into them, one slot per icon drawn (vanilla registers a
/// texture per pack). Icons past the last slot keep `unknown_pack`.
/// writes the icons into them (vanilla registers a texture per pack). An
/// icon keeps its slot from one frame to the next and is sent when it takes
/// the slot, not every frame; the slot of the icon drawn longest ago is
/// taken first. Icons past the last slot in one frame keep `unknown_pack`.
pub fn bind_icons(&self, draws: &mut [Draw], atlas: &HudAtlas, patches: &mut Vec<Patch>) {
let mut slots = 0..PACK_ICON_SLOTS;
let mut slots = self.icon_slots.borrow_mut();
slots.begin(atlas);
for draw in draws {
let Draw::Blit { texture, .. } = draw else {
continue;
@@ -942,20 +997,23 @@ impl PackScreen {
let Some(icon) = self.icons.get(texture.as_str()) else {
continue;
};
let Some(slot) = slots.next() else {
return;
let Some((slot, send)) = slots.slot_for(texture, icon) else {
continue;
};
let sprite = format!("horizon/pack-icon{slot}");
let Some(rect) = atlas.sprites.get(&sprite) else {
slots.held.pop();
return;
};
patches.push(Patch {
x: (rect.u0 * atlas.width as f32).round() as u32,
y: (rect.v0 * atlas.height as f32).round() as u32,
width: PACK_ICON_SIZE,
height: PACK_ICON_SIZE,
rgba: icon.to_vec(),
});
if send {
patches.push(Patch {
x: (rect.u0 * atlas.width as f32).round() as u32,
y: (rect.v0 * atlas.height as f32).round() as u32,
width: PACK_ICON_SIZE,
height: PACK_ICON_SIZE,
rgba: icon.to_vec(),
});
}
*texture = sprite;
}
}
@@ -1618,6 +1676,12 @@ impl PackScreen {
let hover = hovered == Some(i)
&& d::inside(mouse, bx, by, OPTIONS_SIZE, OPTIONS_SIZE);
Self::draw_options_button(out, bx, by, hover);
// A control for a pad's crosshair to glide onto and its D-pad to hop to,
// while the list shows it whole.
let mark = crate::widgets::targets_mark();
let size = OPTIONS_SIZE as f32;
crate::widgets::target([bx as f32, by as f32, size, size]);
crate::widgets::clip_targets(mark, l.y as f32, l.bottom() as f32);
if hover {
tooltip = Some(tr("horizon.pack.optionsInfo"));
}
@@ -1745,9 +1809,14 @@ mod icon_tests {
.unwrap();
assert_eq!(id, "file/Configurable");
let (cx, cy) = (bx + OPTIONS_SIZE / 2, by + OPTIONS_SIZE / 2);
// Hovered, it explains itself.
// Hovered, it explains itself; a pad's crosshair reaches it as a control.
let draws = screen.draw(&m, (cx, cy), 0, 0);
assert!(draws.iter().any(|d| matches!(d, Draw::Tooltip { .. })));
crate::widgets::end_frame(crate::widgets::generation() + 1);
let size = OPTIONS_SIZE as f32;
let button = [bx as f32, by as f32, size, size];
let targets = crate::widgets::last_targets();
assert!(targets.iter().any(|t| t.rect == button), "{targets:?}");
assert_eq!(
screen.click(&m, cx as f64, cy as f64),
Action::Options("file/Configurable".into())
@@ -2070,3 +2139,177 @@ mod footer_label_tests {
assert_eq!(lang::code(), before, "the global language was left alone");
}
}
#[cfg(test)]
mod icon_slot_tests {
use super::*;
fn atlas() -> HudAtlas {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
/// `count` packs with an icon each, the pixels of icon `i` all `i`.
fn packs(count: usize) -> Vec<PackInfo> {
let side = PACK_ICON_SIZE as usize;
(0..count)
.map(|i| PackInfo {
id: format!("file/pack{i:03}"),
title: Text::literal(format!("pack{i:03}")),
description: Text::literal(""),
description_style: Style::default(),
source: Source::BuiltIn,
compat: Compat::Compatible,
icon: Some(vec![i as u8; side * side * 4].into()),
required: false,
position: Position::Top,
fixed: false,
})
.collect()
}
/// One frame as `options_ui` draws it: the calls, then the icons bound. The icons drawn
/// (their texture keys before binding), the textures after, and the patches sent.
fn frame(screen: &PackScreen, atlas: &HudAtlas) -> (Vec<String>, Vec<String>, Vec<Patch>) {
let m = Measure(&atlas.font);
let mut draws = screen.draw(&m, (0, 0), 0, 0);
let drawn: Vec<String> = draws
.iter()
.filter_map(|d| match d {
Draw::Blit { texture, .. } if screen.icons.contains_key(texture) => {
Some(texture.clone())
}
_ => None,
})
.collect();
let mut patches = Vec::new();
screen.bind_icons(&mut draws, atlas, &mut patches);
let bound = draws
.iter()
.filter_map(|d| match d {
Draw::Blit { texture, .. } if texture.contains("pack-icon") => {
Some(texture.clone())
}
_ => None,
})
.collect();
(drawn, bound, patches)
}
/// Only the available list has packs: one row of 36 for each of `count` icons fits in a
/// window `height` high.
fn screen(m: &Measure, count: usize, height: i32) -> PackScreen {
PackScreen::new(
m,
tr("resourcePack.title"),
480,
height,
false,
packs(count),
&[],
)
}
/// Every frame sent every drawn icon again (a 128 by 128 RGBA copy each) into the same
/// atlas, which keeps what it is given: an icon is sent when it takes a slot, once.
#[test]
fn an_icon_is_sent_once_and_not_every_frame() {
let atlas = atlas();
let screen = screen(&Measure(&atlas.font), 5, 400);
let (drawn, bound, patches) = frame(&screen, &atlas);
assert_eq!((drawn.len(), bound.len(), patches.len()), (5, 5, 5));
for again in 0..3 {
let (_, rebound, resent) = frame(&screen, &atlas);
assert_eq!(rebound, bound, "frame {again}");
assert_eq!(resent.len(), 0, "frame {again}");
}
}
/// More icons drawn in one frame than there are slots: the first 64 get one, the rest keep
/// `unknown_pack`, and the next frame does not move them or send anything.
#[test]
fn past_the_slots_in_one_frame_the_rest_keep_unknown_pack() {
let atlas = atlas();
let screen = screen(&Measure(&atlas.font), PACK_ICON_SLOTS + 6, 4000);
let (drawn, bound, patches) = frame(&screen, &atlas);
assert_eq!(
drawn.len(),
PACK_ICON_SLOTS + 6,
"the window shows every row"
);
assert_eq!(
(bound.len(), patches.len()),
(PACK_ICON_SLOTS, PACK_ICON_SLOTS)
);
let (_, rebound, resent) = frame(&screen, &atlas);
assert_eq!((rebound, resent.len()), (bound, 0));
}
/// Scrolling through more packs than slots: every icon drawn gets a slot, each one is sent
/// once on the way down, and a frame that draws what the last one drew sends nothing.
#[test]
fn scrolling_sends_only_the_icons_that_come_into_view() {
let atlas = atlas();
let m = Measure(&atlas.font);
let mut screen = screen(&m, 70, 330);
let mut seen = std::collections::HashSet::new();
let mut sent = 0;
// 150 wheel steps of 18 are more than the 2520 high list.
for step in 0..150 {
let (drawn, bound, patches) = frame(&screen, &atlas);
assert_eq!(bound.len(), drawn.len(), "step {step}: none falls back");
let new = drawn.iter().filter(|t| seen.insert((*t).clone())).count();
assert_eq!(patches.len(), new, "step {step}");
sent += patches.len();
assert_eq!(frame(&screen, &atlas).2.len(), 0, "step {step}: same view");
screen.scroll(100.0, 200.0, -1.0);
}
assert_eq!((seen.len(), sent), (70, 70));
}
/// The slot of the icon drawn longest ago is the one taken, and the icon that left it is
/// sent again when it comes back.
#[test]
fn the_icon_drawn_longest_ago_gives_up_its_slot() {
let icons: Vec<Arc<[u8]>> = packs(PACK_ICON_SLOTS + 1)
.into_iter()
.map(|p| p.icon.unwrap())
.collect();
let mut slots = IconSlots::default();
let key = |i: usize| format!("k{i}");
slots.begin(&atlas());
for i in 0..PACK_ICON_SLOTS {
assert_eq!(slots.slot_for(&key(i), &icons[i]), Some((i, true)));
}
// The next frame draws icon 0 first, then a new one: slot 1, the oldest left, is taken.
slots.frame += 1;
assert_eq!(slots.slot_for(&key(0), &icons[0]), Some((0, false)));
assert_eq!(
slots.slot_for("new", &icons[PACK_ICON_SLOTS]),
Some((1, true))
);
// Icon 1 comes back: it is sent again, into the slot of the next oldest.
assert_eq!(slots.slot_for(&key(1), &icons[1]), Some((2, true)));
}
/// New pixels under the same key take the same slot and are sent; a new atlas holds none
/// of the icons, so all are sent again.
#[test]
fn changed_pixels_and_a_new_atlas_send_again() {
let atlas = atlas();
let mut screen = screen(&Measure(&atlas.font), 3, 400);
let (_, bound, patches) = frame(&screen, &atlas);
assert_eq!(patches.len(), 3);
let key = icon_texture("file/pack001");
screen
.icons
.insert(key, vec![200; patches[1].rgba.len()].into());
let (_, rebound, resent) = frame(&screen, &atlas);
assert_eq!(rebound, bound);
assert_eq!(resent.len(), 1);
assert_eq!((resent[0].x, resent[0].y), (patches[1].x, patches[1].y));
assert_eq!(resent[0].rgba[0], 200);
let other = self::atlas();
assert_ne!(other.revision, atlas.revision);
assert_eq!(frame(&screen, &other).2.len(), 3);
}
}
@@ -466,6 +466,13 @@ fn read_meta(source: &Source) -> Option<serde_json::Value> {
/// file with a comment after the closing brace. Gson reads past a UTF-8 byte order mark;
/// serde_json rejects it.
pub(crate) fn parse_meta(bytes: &[u8]) -> Option<serde_json::Value> {
first_json(bytes)
}
/// Reads the first JSON value from resource metadata, matching Gson's
/// `JsonReader` (which ignores a trailing signature or comment). Resource
/// packs commonly append such text to texture metadata as well as pack.mcmeta.
pub(crate) fn first_json(bytes: &[u8]) -> Option<serde_json::Value> {
serde_json::Deserializer::from_slice(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes))
.into_iter()
.next()?
+36 -98
View File
@@ -31,8 +31,10 @@ mod native;
pub mod polytone;
mod polytone_gpu;
mod polytone_model;
mod simple;
mod spawn;
pub use native::{ParticleController, ParticleUpdate};
use simple::{PARALLEL_MIN, parallel_threads, sprite_from_age_in, tick_simple};
/// `ParticleOptions` with the parameters of the option classes used here.
#[derive(Clone, Debug)]
@@ -524,6 +526,8 @@ pub struct Particle {
no_render: bool,
/// Ticked once when created (`CritParticle` constructor).
pre_tick: bool,
/// A Polytone particle with physics, which joins only where its box is clear of blocks.
spawn_check: bool,
/// `Particle.random`: the particle's own generator (`RandomSource.create()`).
random: LegacyRandom,
controller: Option<Box<dyn native::Controller>>,
@@ -893,6 +897,7 @@ impl Particle {
behaviour: Behaviour::Base,
no_render: false,
pre_tick: false,
spawn_check: false,
frame_ticks: 0,
random: LegacyRandom::new(0),
controller: None,
@@ -1325,6 +1330,9 @@ pub struct ParticleEngine {
/// A native mod's sprite sets, by namespaced particle name.
mod_sets: HashMap<String, (u32, Option<ModBehaviour>)>,
set_sprites: Vec<Vec<u32>>,
/// How many live particles it takes to tick them on several threads (`tick_all`), and how many threads.
parallel_min: usize,
parallel_threads: usize,
/// Resource packs' Polytone custom particle types (#11486).
polytone: Option<std::sync::Arc<polytone::Registry>>,
/// Vanilla particle types a pack replaces with a custom one of the same id
@@ -1527,6 +1535,8 @@ impl ParticleEngine {
sets: HashMap::new(),
mod_sets: HashMap::new(),
set_sprites: Vec::new(),
parallel_min: PARALLEL_MIN,
parallel_threads: parallel_threads(),
polytone: None,
polytone_overrides: HashMap::new(),
polytone_gpu: Vec::new(),
@@ -1752,28 +1762,6 @@ impl ParticleEngine {
particle.controller = Some(Box::new(controller));
Some(particle)
}
/// Sets (or clears) the resource packs' Polytone custom particle types.
pub fn set_polytone(&mut self, registry: Option<std::sync::Arc<polytone::Registry>>) {
let registry = registry.filter(|r| !r.is_empty());
let same = match (&self.polytone, &registry) {
(Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
(None, None) => true,
_ => false,
};
if !same {
self.polytone_gpu.clear();
self.polytone_overrides = registry
.iter()
.flat_map(|r| {
ParticleType::ALL.iter().filter_map(|&ty| {
let id = format!("minecraft:{}", ty.name());
r.get(&id).is_some().then_some((ty, id))
})
})
.collect();
}
self.polytone = registry;
}
/// The quads the last render blends additively (`RenderPipelines` additive, src alpha and
/// one), for the frame's additive pass.
pub fn take_additive(&self) -> Vec<Vertex> {
@@ -2121,23 +2109,7 @@ impl ParticleEngine {
}
/// `SingleQuadParticle.setSpriteFromAge`.
fn sprite_from_age(&self, p: &mut Particle) {
if p.removed {
return;
}
if let Some(set) = p.set {
// A sprite set's index can outlive the reload that rebuilt them.
let Some(sprites) = self.set_sprites.get(set as usize) else {
return;
};
let lifetime = p.lifetime.max(1);
let index = if p.frame_ticks > 0 {
(p.age.max(0) as i64 / i64::from(p.frame_ticks)) % sprites.len() as i64
} else {
(p.age.max(0) as i64 * (sprites.len() as i64 - 1) / i64::from(lifetime))
.clamp(0, sprites.len() as i64 - 1)
};
p.sprite = Sprite::Index(sprites[index as usize]);
}
sprite_from_age_in(&self.set_sprites, p);
}
#[allow(clippy::too_many_lines)]
/// `ParticleProvider.createParticle`: provider draws use the engine's
@@ -3630,13 +3602,14 @@ impl ParticleEngine {
self.sprite_from_age(&mut q);
q
}
/// ClientLevel.createFireworks: a Starter (or poofs without explosions).
/// ClientLevel.createFireworks: a Starter (or poofs without explosions) with `playSound`.
pub fn fireworks(
&mut self,
at: [f64; 3],
v: [f64; 3],
explosions: Vec<FireworkExplosion>,
camera: [f64; 3],
play_sound: bool,
) {
if explosions.is_empty() {
for _ in 0..self.random.next_int_bound(3).unwrap_or(0) + 2 {
@@ -3660,17 +3633,17 @@ impl ParticleEngine {
life: 0,
lifetime,
twinkle_delay: twinkle,
far,
sound: play_sound.then_some(far),
});
}
fn tick_starters(&mut self) {
for mut s in std::mem::take(&mut self.starters) {
if s.life == 0 {
if s.life == 0 && s.sound.is_some() {
let large = s.explosions.len() >= 3
|| s.explosions
.iter()
.any(|e| e.shape == FireworkShape::LargeBall);
let sound = match (large, s.far) {
let sound = match (large, s.sound == Some(true)) {
(true, true) => "minecraft:entity.firework_rocket.large_blast_far",
(true, false) => "minecraft:entity.firework_rocket.large_blast",
(false, true) => "minecraft:entity.firework_rocket.blast_far",
@@ -3713,16 +3686,13 @@ impl ParticleEngine {
(c & 255) as f32 / 255.0,
((c >> 24) & 255) as f32 / 255.0,
];
self.create(
&ParticleOptions::colored(ParticleType::Flash, rgba),
s.at,
[0.0; 3],
);
let flash = ParticleOptions::colored(ParticleType::Flash, rgba);
self.create(&flash, s.at, [0.0; 3]);
}
s.life += 1;
if s.life > s.lifetime {
if s.twinkle_delay {
let sound = if s.far {
if s.twinkle_delay && s.sound.is_some() {
let sound = if s.sound == Some(true) {
"minecraft:entity.firework_rocket.twinkle_far"
} else {
"minecraft:entity.firework_rocket.twinkle"
@@ -3847,9 +3817,7 @@ impl ParticleEngine {
self.emitters = emitters;
let mut particles = std::mem::take(&mut self.particles);
self.spawned_in_tick = Some(Vec::new());
for p in &mut particles {
self.tick_particle(p, level);
}
self.tick_all(&mut particles, level);
particles.retain(|p| !p.removed);
self.particles = particles;
for (options, pos, velocity) in self.spawned_in_tick.take().unwrap_or_default() {
@@ -3857,6 +3825,9 @@ impl ParticleEngine {
}
let pending = std::mem::take(&mut self.pending);
for mut p in pending {
if p.spawn_check && !polytone::unobstructed(level, p.bb) {
continue;
}
if p.pre_tick {
p.pre_tick = false;
self.tick_particle(&mut p, level);
@@ -3954,7 +3925,15 @@ impl ParticleEngine {
#[allow(clippy::too_many_lines)]
fn tick_particle(&mut self, p: &mut Particle, level: &ParticleLevel) {
match p.behaviour {
Behaviour::Base => p.base_tick(level),
Behaviour::Base
| Behaviour::Mod { .. }
| Behaviour::Animated
| Behaviour::Snowflake
| Behaviour::Crit
| Behaviour::Spark { .. } => {
let simple = tick_simple(&self.set_sprites, p, level);
self.finish_simple(p, simple);
}
Behaviour::Controlled { .. } => {
if let Some(mut controller) = p.controller.take() {
let update = controller.tick(p, level);
@@ -3973,23 +3952,6 @@ impl ParticleEngine {
p.remove();
}
}
Behaviour::Mod { size, alpha } => {
p.base_tick(level);
p.size = mod_curve(size, p.age, p.lifetime);
p.rgba[3] = mod_curve(alpha, p.age, p.lifetime);
self.sprite_from_age(p);
}
Behaviour::Animated => {
p.base_tick(level);
self.sprite_from_age(p);
}
Behaviour::Snowflake => {
p.base_tick(level);
self.sprite_from_age(p);
p.velocity[0] *= f64::from(0.95f32);
p.velocity[1] *= f64::from(0.9f32);
p.velocity[2] *= f64::from(0.95f32);
}
Behaviour::Lava => {
p.base_tick(level);
if !p.removed && p.random.next_float() > p.age as f32 / p.lifetime as f32 {
@@ -4000,11 +3962,6 @@ impl ParticleEngine {
);
}
}
Behaviour::Crit => {
p.base_tick(level);
p.rgba[1] *= 0.96;
p.rgba[2] *= 0.9;
}
Behaviour::Drip {
fluid,
stage,
@@ -4475,27 +4432,6 @@ impl ParticleEngine {
}
}
}
Behaviour::Spark {
fade,
trail,
twinkle,
} => {
p.base_tick(level);
self.sprite_from_age(p);
if p.age > p.lifetime / 2 {
p.rgba[3] = 1.0 - (p.age as f32 - (p.lifetime / 2) as f32) / p.lifetime as f32;
if let Some(f) = fade {
for i in 0..3 {
p.rgba[i] += (f[i] - p.rgba[i]) * 0.2;
}
}
}
if trail && p.age < p.lifetime / 2 && (p.age + p.lifetime) % 2 == 0 {
let mut child = self.spark(p.position, [0.0; 3], p.rgba, fade, false, twinkle);
child.age = child.lifetime / 2;
self.pending.push(child);
}
}
Behaviour::Spell { original_alpha } => {
p.base_tick(level);
self.sprite_from_age(p);
@@ -5100,7 +5036,9 @@ struct Starter {
life: i32,
lifetime: i32,
twinkle_delay: bool,
far: bool,
/// `FireworkParticles.Starter.playSound`, with `isFarAwayFromCamera` when
/// it plays: `None` for a silent rocket.
sound: Option<bool>,
}
const STAR: [[f64; 2]; 6] = [
[0.0, 1.0],
@@ -774,7 +774,7 @@ impl Host for Ctx<'_, '_> {
// `r.noise(x, y)`: one simplex noise (named noises aren't read yet).
let mut coords = args.iter().filter(|v| !matches!(v, V::Str(_))).map(V::num);
let (x, y) = (coords.next().unwrap_or(0.0), coords.next().unwrap_or(0.0));
num(f64::from(crate::environment::polytone_noise().get2(x, y)))
num(crate::environment::polytone_noise().get(x, y))
}
(id, _) if id >= BLOCKS => {
let at = *self
@@ -1090,6 +1090,16 @@ const INITIALIZED: [&str; 13] = [
"dz",
];
/// Whether no block's collision shape overlaps `bb` (where the query fails, nothing does).
pub(super) fn unobstructed(level: &ParticleLevel<'_>, bb: horizon_core::geometry::Aabb) -> bool {
let mut scene = crate::collisions::SceneCollisions {
world: level.world,
binding: level.collision,
subject: None,
};
scene.cells_without_collision(bb) || scene.unobstructed(bb).unwrap_or(true)
}
impl super::ParticleController for Controller {
fn tick(&mut self, p: &mut Particle, level: &ParticleLevel<'_>) -> ParticleUpdate {
let mut update = ParticleUpdate::default();
@@ -1320,6 +1330,10 @@ pub(super) fn make(
particle.polytone_type =
(def.limit.is_some() || def.exclusion_radius > 0.0).then(|| Arc::from(name));
particle.bb = super::aabb_at(position, particle.bb_width, particle.bb_height);
// A particle with physics whose box starts inside a block's collision never joins the world:
// it is not drawn and none of its emitters run (measured on the mod: one spawned just under a
// block, where falling leaves start, never shows; one 0.01 clear of it does).
particle.spawn_check = def.has_physics;
particle.controller = Some(Box::new(Controller {
def: def.clone(),
registry: registry.clone(),
@@ -1531,6 +1545,31 @@ impl ParticleEngine {
}
}
impl ParticleEngine {
/// Sets (or clears) the resource packs' Polytone custom particle types.
pub fn set_polytone(&mut self, registry: Option<Arc<Registry>>) {
let registry = registry.filter(|r| !r.is_empty());
let same = match (&self.polytone, &registry) {
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
(None, None) => true,
_ => false,
};
if !same {
self.polytone_gpu.clear();
self.polytone_overrides = registry
.iter()
.flat_map(|r| {
ParticleType::ALL.iter().filter_map(|&ty| {
let id = format!("minecraft:{}", ty.name());
r.get(&id).is_some().then_some((ty, id))
})
})
.collect();
}
self.polytone = registry;
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2244,6 +2283,144 @@ mod tests {
std::fs::remove_dir_all(root).unwrap();
}
/// `scene`, with the torch a full block of collision: something a particle's box can start in.
fn solid_scene(blocks: &'static BlockRegistry) -> Scene {
use horizon_core::geometry::{Axis, VoxelShape};
let tag = |shape: VoxelShape| {
let sizes = shape.sizes();
let occupied = (0..sizes[2])
.flat_map(|z| {
(0..sizes[1]).flat_map(move |y| (0..sizes[0]).map(move |x| (x, y, z)))
})
.map(|(x, y, z)| u8::from(shape.is_full(x as i32, y as i32, z as i32)))
.collect();
let (min, max) = shape.discrete_bounds();
let axes = shape
.cube_coordinate_axes()
.iter()
.enumerate()
.fold(0, |mask, (i, on)| mask | (i8::from(*on) << i));
let mut fields = vec![
("occupied", Tag::ByteArray(occupied)),
("cube", Tag::Byte(i8::from(shape.is_cube()))),
("cube_axes", Tag::Byte(axes)),
("discrete_min", Tag::IntArray(min.to_vec())),
("discrete_max", Tag::IntArray(max.to_vec())),
];
for (axis, name) in [(Axis::X, "x"), (Axis::Y, "y"), (Axis::Z, "z")] {
let bits = shape.coordinates(axis).iter().map(|v| v.to_bits() as i64);
fields.push((name, Tag::LongArray(bits.collect())));
}
Tag::compound(fields)
};
let names = || Tag::List(STATES.iter().map(|s| Tag::String((*s).into())).collect());
let cached = CachedCollisionRegistry::from_nbt(
&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
("states", names()),
(
"shapes",
Tag::List(vec![tag(VoxelShape::empty()), tag(VoxelShape::block())]),
),
("cached_shapes", Tag::IntArray(vec![0, 1])),
]),
blocks,
)
.unwrap();
Scene {
collision: BlockCollisionRegistry::new(Arc::new(cached)).unwrap(),
..scene(blocks)
}
}
#[test]
fn a_particle_with_physics_born_inside_a_block_never_joins() {
let blocks = blocks();
let leaf = |physics| {
serde_json::json!({"has_physics": physics, "render_type": "invisible",
"initializer": {"lifetime": "20", "hitbox_size": "0.08"},
"particle_emitters": [{"particle": "test:mark", "chance": "1"}]})
};
let root = pack(&[
(
"assets/test/polytone/custom_particles/leaf.json",
leaf(true),
),
(
"assets/test/polytone/custom_particles/ghost.json",
leaf(false),
),
(
"assets/test/polytone/custom_particles/mark.json",
serde_json::json!({"render_type": "invisible", "has_physics": false}),
),
(
"assets/minecraft/polytone/entity_modifiers/player.json",
serde_json::json!({"emitters": [{"particle": "test:leaf", "chance": "1"}]}),
),
(
"assets/test/polytone/custom_particles/wide.json",
serde_json::json!({"has_physics": true, "render_type": "invisible",
"initializer": {"lifetime": "20", "hitbox_size": 10},
"particle_emitters": [{"particle": "test:mark", "chance": "1"}]}),
),
(
"assets/test/polytone/custom_particles/parent.json",
serde_json::json!({"has_physics": true, "render_type": "invisible",
"initializer": {"lifetime": "20", "hitbox_size": "0.08"},
"particle_emitters": [{"particle": "test:wide", "chance": "1", "y": "-0.05"}]}),
),
(
"assets/minecraft/polytone/entity_modifiers/skeleton.json",
serde_json::json!({"emitters": [{"particle": "test:parent", "chance": "1", "x": "-4.5"}]}),
),
(
"assets/minecraft/polytone/entity_modifiers/creeper.json",
serde_json::json!({"emitters": [{"particle": "test:wide", "chance": "1", "x": "-4.5"}]}),
),
(
"assets/minecraft/polytone/entity_modifiers/zombie.json",
serde_json::json!({"emitters": [{"particle": "test:ghost", "chance": "1"}]}),
),
]);
let scene = solid_scene(blocks);
let level = ParticleLevel {
world: &scene.world,
facts: &scene.facts,
collision: &scene.collision,
player: None,
cached_chunk: std::cell::Cell::new(None),
};
let mut engine = engine(Registry::read(&root, Default::default(), blocks));
// The solid block is at (1, 64, 1): its bottom face is y 64.
// Spawns one particle, lets the engine take it in and tick it: whether it joined, and
// how many particles it emitted.
let mut spawn = |entity: &str, y: f64| {
engine.particles.clear();
engine.pending.clear();
engine.polytone_entity(&level, entity, [1.5, y, 1.5]);
engine.tick(&level);
let joined = engine.particles.len();
engine.tick(&level);
(
joined,
engine.particles.len() + engine.pending.len() - joined,
)
};
// The solid block is at (1, 64, 1): its bottom face is y 64.
// 0.05 under the block, a 0.08 box reaches into it: it never joins, nothing emitted.
assert_eq!(spawn("minecraft:player", 63.95), (0, 0));
// 0.01 clear of it, it joins and emits.
assert_eq!(spawn("minecraft:player", 63.91), (1, 1));
// Without physics nothing collides.
assert_eq!(spawn("minecraft:zombie", 63.95), (1, 1));
// A wide box reaching a block from five blocks away does not join either.
assert_eq!(spawn("minecraft:creeper", 60.0), (0, 0));
// Nor does one a clear particle emits there: the small one joins, its wide copy never.
assert_eq!(spawn("minecraft:skeleton", 60.0), (1, 0));
std::fs::remove_dir_all(root).unwrap();
}
#[test]
fn a_pack_custom_particle_replaces_the_vanilla_type_of_its_id() {
let root = pack(&[(
@@ -0,0 +1,161 @@
//! The particles that tick on their own (`tick_simple`): the behaviours that read and write only
//! their own particle, the world and the sprite sets, which `ParticleEngine::tick_all` runs on several
//! threads in a busy scene.
use super::{Behaviour, Particle, ParticleEngine, ParticleLevel, Sprite, mod_curve};
/// The live particles it takes before `tick_all` uses more than one thread: a scoped thread costs
/// tens of microseconds to start and join, and a simple particle about a tenth of one.
pub(super) const PARALLEL_MIN: usize = 2048;
/// Threads for ticking particles: half the machine's workers, at most four (the chunk workers and
/// the render thread need cores too); `HORIZON_WORKER_THREADS` caps them as it does every pool.
pub(super) fn parallel_threads() -> usize {
(horizon_threads::worker_count() / 2).clamp(1, 4)
}
pub(super) fn sprite_from_age_in(set_sprites: &[Vec<u32>], p: &mut Particle) {
if p.removed {
return;
}
if let Some(set) = p.set {
// A sprite set's index can outlive the reload that rebuilt them.
let Some(sprites) = set_sprites.get(set as usize) else {
return;
};
let lifetime = p.lifetime.max(1);
let index = if p.frame_ticks > 0 {
(p.age.max(0) as i64 / i64::from(p.frame_ticks)) % sprites.len() as i64
} else {
(p.age.max(0) as i64 * (sprites.len() as i64 - 1) / i64::from(lifetime))
.clamp(0, sprites.len() as i64 - 1)
};
p.sprite = Sprite::Index(sprites[index as usize]);
}
}
/// The tick of the behaviours that read and write only their own particle, the world and the engine's
/// sprite sets: no particle spawned, no sound, nothing drawn from the engine's random. Those are the
/// bulk of a busy scene (flames, smoke, poofs, dust, crits), and `ParticleEngine::tick` runs them on
/// several threads. Any other behaviour is left alone, for `ParticleEngine::tick_particle`.
pub(super) fn tick_simple(
set_sprites: &[Vec<u32>],
p: &mut Particle,
level: &ParticleLevel,
) -> Simple {
match p.behaviour {
Behaviour::Base => p.base_tick(level),
Behaviour::Mod { size, alpha } => {
p.base_tick(level);
p.size = mod_curve(size, p.age, p.lifetime);
p.rgba[3] = mod_curve(alpha, p.age, p.lifetime);
sprite_from_age_in(set_sprites, p);
}
Behaviour::Animated => {
p.base_tick(level);
sprite_from_age_in(set_sprites, p);
}
Behaviour::Snowflake => {
p.base_tick(level);
sprite_from_age_in(set_sprites, p);
p.velocity[0] *= f64::from(0.95f32);
p.velocity[1] *= f64::from(0.9f32);
p.velocity[2] *= f64::from(0.95f32);
}
Behaviour::Crit => {
p.base_tick(level);
p.rgba[1] *= 0.96;
p.rgba[2] *= 0.9;
}
Behaviour::Spark { fade, trail, .. } => {
p.base_tick(level);
sprite_from_age_in(set_sprites, p);
if p.age > p.lifetime / 2 {
p.rgba[3] = 1.0 - (p.age as f32 - (p.lifetime / 2) as f32) / p.lifetime as f32;
if let Some(f) = fade {
for i in 0..3 {
p.rgba[i] += (f[i] - p.rgba[i]) * 0.2;
}
}
}
if trail && p.age < p.lifetime / 2 && (p.age + p.lifetime) % 2 == 0 {
return Simple::SparkTrail;
}
}
_ => return Simple::No,
}
Simple::Done
}
/// The same world with a one-chunk lookup cache of its own, for a worker thread.
///
/// `ParticleLevel::cached_chunk` is a `Cell`, which a level shared between threads may not hold:
/// each thread gets a view with an empty cache, built here on the engine thread and moved in. A
/// cache they shared could not hold "the last chunk looked up" for any one of them in any case.
fn thread_view<'a>(level: &ParticleLevel<'a>) -> ParticleLevel<'a> {
ParticleLevel {
world: level.world,
facts: level.facts,
collision: level.collision,
player: level.player,
cached_chunk: std::cell::Cell::new(None),
}
}
/// What `tick_simple` did with a particle.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Simple {
/// Not one of its behaviours: the engine ticks it.
No,
/// Ticked completely.
Done,
/// Ticked, except that a firework spark's trail wants a child. Only the engine can make one:
/// it takes the next seed, so the children come in the order the sparks have.
SparkTrail,
}
impl ParticleEngine {
/// What `tick_simple` leaves to the engine: a spark's trail child.
pub(super) fn finish_simple(&mut self, p: &Particle, simple: Simple) {
if simple != Simple::SparkTrail {
return;
}
if let Behaviour::Spark { fade, twinkle, .. } = p.behaviour {
let mut child = self.spark(p.position, [0.0; 3], p.rgba, fade, false, twinkle);
child.age = child.lifetime / 2;
self.pending.push(child);
}
}
/// One tick of every live particle. The ones `tick_simple` covers are independent of each
/// other and of the engine, so with enough of them they tick on several threads; every other
/// one then ticks here, in the order it had, so the particles, the engine's random and what
/// is spawned come out as when all of them ticked one after another.
pub(super) fn tick_all(&mut self, particles: &mut [Particle], level: &ParticleLevel) {
if particles.is_empty() || particles.len() < self.parallel_min || self.parallel_threads < 2
{
for p in particles {
self.tick_particle(p, level);
}
return;
}
let sets = &self.set_sprites;
let per = particles.len().div_ceil(self.parallel_threads);
let mut handled = vec![Simple::No; particles.len()];
std::thread::scope(|scope| {
let run = |part: &mut [Particle], done: &mut [Simple], level: &ParticleLevel| {
for (p, done) in part.iter_mut().zip(done) {
*done = tick_simple(sets, p, level);
}
};
let mut parts = particles.chunks_mut(per).zip(handled.chunks_mut(per));
let own = parts.next();
for (part, done) in parts {
let view = thread_view(level);
scope.spawn(move || run(part, done, &view));
}
// This thread takes the first share, instead of waiting for the others.
if let Some((part, done)) = own {
run(part, done, level);
}
});
for (p, done) in particles.iter_mut().zip(handled) {
match done {
Simple::No => self.tick_particle(p, level),
simple => self.finish_simple(p, simple),
}
}
}
}
@@ -1,8 +1,12 @@
//! The particle stress scene's load on `ParticleEngine`, outside the game: `cargo test --profile fast
//! -p horizon-client-render --lib particle_tick_cost -- --ignored --nocapture` (prepared resources;
//! `PARTICLE_BENCH_SECS` sets the run, default 5). It spawns what tools/stress_scenes.py's `particles`
//! scene makes each tick (flames, cosy smoke, end rods, TNT debris) over its stone floor and times the
//! spawns and the engine tick apart, once the engine holds as many particles as it will.
//! The particle stress scene's load on `ParticleEngine`, outside the game.
//!
//! - `parallel_tick_matches_serial_tick`: the engine ticking on several threads (`tick_all`) leaves
//! every particle, the engine's random and its sounds exactly as ticking them one after another.
//! - `particle_tick_cost` (`cargo test --profile fast -p horizon-client-render --lib
//! particle_tick_cost -- --ignored --nocapture`, prepared resources; `PARTICLE_BENCH_SECS` sets
//! the run, default 2): spawns what tools/stress_scenes.py's `particles` scene makes each tick
//! (flames, cosy smoke, end rods, TNT debris, rockets) over its stone floor and times the spawns
//! and the engine tick apart, once the engine holds as many particles as it will.
use super::*;
use crate::{blocks::BlockFacts, chunk::Chunk, collisions, world::World};
use std::sync::Arc;
@@ -25,6 +29,7 @@ impl Lcg {
}
}
/// What to spawn each tick: a type, how many, around where, how far, how fast.
type Emitter = (ParticleType, usize, [f64; 3], [f64; 3], f64);
fn spawn_tick(engine: &mut ParticleEngine, rng: &mut Lcg, types: &[Emitter], rockets: usize) {
@@ -38,7 +43,7 @@ fn spawn_tick(engine: &mut ParticleEngine, rng: &mut Lcg, types: &[Emitter], roc
twinkle: false,
};
let at = [-5.5 + rng.next() * 12.0, f64::from(FLOOR_Y + 20), 20.5];
engine.fireworks(at, [0.0, 0.1, 0.0], vec![explosion], engine.camera);
engine.fireworks(at, [0.0, 0.1, 0.0], vec![explosion], engine.camera, true);
}
for &(ty, count, center, delta, speed) in types {
let options = ParticleOptions::simple(ty);
@@ -58,9 +63,29 @@ fn spawn_tick(engine: &mut ParticleEngine, rng: &mut Lcg, types: &[Emitter], roc
}
}
#[test]
#[ignore = "a measurement, not a check"]
fn particle_tick_cost() {
/// The scene's emitters, per tick: flames, cosy smoke, end rods, and TNT's debris (poof and smoke).
fn emitters() -> [Emitter; 5] {
let ty = |name: &str| ParticleType::from_name(name).unwrap();
let (fx, fy, fz) = (0.5, f64::from(FLOOR_Y + 5), 20.5);
let tnt = [0.5, f64::from(FLOOR_Y + 24), 26.5];
[
(ty("flame"), 320, [fx, fy, fz], [8.0, 4.0, 8.0], 0.01),
(
ty("campfire_cosy_smoke"),
8,
[fx, fy, fz],
[8.0, 4.0, 8.0],
0.0,
),
(ty("end_rod"), 80, [fx, fy, fz], [8.0, 4.0, 8.0], 0.05),
(ty("poof"), 258, tnt, [3.0, 3.0, 3.0], 0.4),
(ty("smoke"), 238, tnt, [3.0, 3.0, 3.0], 0.4),
]
}
/// Runs `f` over the stress scene's world (a stone floor at y 289 under the particles). Skipped
/// without prepared resources.
fn with_scene(f: impl FnOnce(&ParticleLevel)) {
let root = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
@@ -88,69 +113,127 @@ fn particle_tick_cost() {
world.set(x, FLOOR_Y, z, floor).unwrap();
}
}
let level = ParticleLevel {
f(&ParticleLevel {
world: &world,
facts: &facts,
collision: &collision,
player: None,
cached_chunk: std::cell::Cell::new(None),
};
let ty = |name: &str| ParticleType::from_name(name).unwrap();
let (fx, fy, fz) = (0.5, f64::from(FLOOR_Y + 5), 20.5);
let tnt = [0.5, f64::from(FLOOR_Y + 24), 26.5];
// The scene's emitters, per tick, and TNT's debris (poof and smoke).
let flame: Emitter = (ty("flame"), 320, [fx, fy, fz], [8.0, 4.0, 8.0], 0.01);
let cosy: Emitter = (
ty("campfire_cosy_smoke"),
8,
[fx, fy, fz],
[8.0, 4.0, 8.0],
0.0,
});
}
fn engine(parallel_min: usize, threads: usize) -> ParticleEngine {
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
engine.camera = [0.5, 298.0, 0.5];
engine.parallel_min = parallel_min;
engine.parallel_threads = threads;
engine
}
/// Every live particle's fields, as text.
fn state(engine: &ParticleEngine) -> Vec<String> {
engine
.particles
.iter()
.map(|p| format!("{:?}", engine.snapshot(p)))
.collect()
}
#[test]
fn parallel_tick_matches_serial_tick() {
with_scene(|level| {
let types = emitters();
// One engine ticks every particle in turn; the other on three threads. Same seeds, same spawns.
let mut serial = engine(usize::MAX, 1);
let mut threaded = engine(0, 3);
for e in [&mut serial, &mut threaded] {
e.seed_randoms(7, 8, 9);
}
let (mut a, mut b) = (Lcg(99), Lcg(99));
for tick in 0..90 {
spawn_tick(&mut serial, &mut a, &types, 3);
spawn_tick(&mut threaded, &mut b, &types, 3);
serial.tick(level);
threaded.tick(level);
assert_eq!(serial.len(), threaded.len(), "tick {tick}");
if tick % 10 == 9 {
assert_eq!(state(&serial), state(&threaded), "tick {tick}");
}
}
assert!(serial.len() > 1000, "{} particles", serial.len());
assert_eq!(serial.sounds.len(), threaded.sounds.len());
assert_eq!(serial.next_randoms(), threaded.next_randoms());
});
}
/// Spawns and ticks `types` once the engine is full, for `secs`, and prints the cost per tick.
fn measure(
level: &ParticleLevel,
name: &str,
(types, rockets): (&[Emitter], usize),
(parallel_min, threads): (usize, usize),
secs: f64,
) {
let mut engine = engine(parallel_min, threads);
let mut rng = Lcg(1234);
for _ in 0..600 {
spawn_tick(&mut engine, &mut rng, types, rockets);
engine.tick(level);
}
let (mut spawn, mut tick, mut ticks, mut alive) =
(Duration::ZERO, Duration::ZERO, 0u64, 0usize);
let end = Instant::now() + Duration::from_secs_f64(secs);
while Instant::now() < end {
let t = Instant::now();
spawn_tick(&mut engine, &mut rng, types, rockets);
spawn += t.elapsed();
let t = Instant::now();
engine.tick(level);
tick += t.elapsed();
alive += engine.len();
ticks += 1;
}
let per = |d: Duration| d.as_secs_f64() * 1000.0 / ticks as f64;
let alive = alive / ticks as usize;
eprintln!(
"{name:24} alive {alive:6} | per tick: spawn {:6.3} ms, engine tick {:6.3} ms | {:5.0} ns per particle",
per(spawn),
per(tick),
per(tick) * 1.0e6 / alive.max(1) as f64
);
let rod: Emitter = (ty("end_rod"), 80, [fx, fy, fz], [8.0, 4.0, 8.0], 0.05);
let poof: Emitter = (ty("poof"), 258, tnt, [3.0, 3.0, 3.0], 0.4);
let smoke: Emitter = (ty("smoke"), 238, tnt, [3.0, 3.0, 3.0], 0.4);
let cases: [(&str, Vec<Emitter>, usize); 7] = [
("flame 320/tick", vec![flame], 0),
("cosy smoke 8/tick", vec![cosy], 0),
("end rod 80/tick", vec![rod], 0),
("poof 258/tick", vec![poof], 0),
("smoke 238/tick", vec![smoke], 0),
("3 rockets/tick", vec![], 3),
("the whole scene", vec![flame, cosy, rod, poof, smoke], 3),
];
let secs: f64 = std::env::var("PARTICLE_BENCH_SECS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(2.0);
for (name, types, rockets) in cases {
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new());
engine.camera = [0.5, 298.0, 0.5];
let mut rng = Lcg(1234);
for _ in 0..600 {
spawn_tick(&mut engine, &mut rng, &types, rockets);
engine.tick(&level);
}
#[test]
#[ignore = "a measurement, not a check"]
fn particle_tick_cost() {
with_scene(|level| {
let [flame, cosy, rod, poof, smoke] = emitters();
let all = [flame, cosy, rod, poof, smoke];
let secs: f64 = std::env::var("PARTICLE_BENCH_SECS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(2.0);
let one = (usize::MAX, 1);
eprintln!("default threads: {}", parallel_threads());
for (name, types, rockets) in [
("flame 320/tick", vec![flame], 0),
("cosy smoke 8/tick", vec![cosy], 0),
("end rod 80/tick", vec![rod], 0),
("poof 258/tick", vec![poof], 0),
("smoke 238/tick", vec![smoke], 0),
("3 rockets/tick", vec![], 3),
] {
measure(level, name, (&types, rockets), one, secs);
}
let (mut spawn, mut tick, mut ticks, mut alive) =
(Duration::ZERO, Duration::ZERO, 0u64, 0usize);
let end = Instant::now() + Duration::from_secs_f64(secs);
while Instant::now() < end {
let t = Instant::now();
spawn_tick(&mut engine, &mut rng, &types, rockets);
spawn += t.elapsed();
let t = Instant::now();
engine.tick(&level);
tick += t.elapsed();
alive += engine.len();
ticks += 1;
measure(level, "whole scene, 1 thread", (&all, 3), one, secs);
for threads in [2, 3, 4, 6] {
measure(
level,
&format!("whole scene, {threads} threads"),
(&all, 3),
(PARALLEL_MIN, threads),
secs,
);
}
let per = |d: Duration| d.as_secs_f64() * 1000.0 / ticks as f64;
let alive = alive / ticks as usize;
eprintln!(
"{name:20} alive {alive:6} | per tick: spawn {:6.3} ms, engine tick {:6.3} ms | {:5.0} ns per particle",
per(spawn),
per(tick),
per(tick) * 1.0e6 / alive.max(1) as f64
);
}
});
}
@@ -7,13 +7,16 @@ use horizon_core::{
geometry::{Vec3, traverse_blocks},
position::BlockPos,
};
use horizon_world::collision_context::CollisionContext;
/// `PotentSulfurBlock.ALLOWED_WATER_BLOCKS_ABOVE`.
const ALLOWED_WATER_BLOCKS_ABOVE: i32 = 4;
/// `PotentSulfurBlockEntity.isGeyserPassableBlock`: air, water, or a block
/// with no collision shape.
pub fn is_geyser_passable_block(level: &ParticleLevel, pos: [i32; 3]) -> bool {
/// with no collision shape for `CollisionContext.positionContext(context_y)`.
/// Vanilla passes the height of the block under the column it reads, so
/// scaffolding seen from below lets the gas and the geyser through.
pub fn is_geyser_passable_block(level: &ParticleLevel, pos: [i32; 3], context_y: i32) -> bool {
let state = level.world.block(pos[0], pos[1], pos[2]);
if level.facts.is_air(state) || &*level.facts.get(state).name == "minecraft:water" {
return true;
@@ -23,7 +26,9 @@ pub fn is_geyser_passable_block(level: &ParticleLevel, pos: [i32; 3]) -> bool {
binding: level.collision,
subject: None,
};
match level.collision.collision_shape(&mut scene, state, pos) {
let context = CollisionContext::position(f64::from(context_y));
let position = BlockPos::new(pos[0], pos[1], pos[2]);
match (level.collision).collision_shape_with_context(&mut scene, state, position, &context) {
Ok(shape) => shape.is_empty(),
Err(_) => !level.facts.get(state).full_collision,
}
@@ -46,9 +51,9 @@ pub fn find_noxious_gas_source_block(level: &ParticleLevel, origin: [i32; 3]) ->
let state = level.world.block(pos[0], pos[1], pos[2]);
let is_water_block = &*level.facts.get(state).name == "minecraft:water";
if !is_water_source(level, pos)
|| (!is_water_block && !is_geyser_passable_block(level, pos))
|| (!is_water_block && !is_geyser_passable_block(level, pos, origin[1]))
{
if level.facts.is_air(state) || is_geyser_passable_block(level, pos) {
if level.facts.is_air(state) || is_geyser_passable_block(level, pos, origin[1]) {
return Some(pos);
}
break;
@@ -63,7 +68,7 @@ pub fn find_noxious_gas_source_block(level: &ParticleLevel, origin: [i32; 3]) ->
pub fn unobstructed_block_count(level: &ParticleLevel, pos: [i32; 3], water_blocks: i32) -> i32 {
let geyser_force_height = 6 * water_blocks;
for i in 0..geyser_force_height {
if !is_geyser_passable_block(level, [pos[0], pos[1] + i, pos[2]]) {
if !is_geyser_passable_block(level, [pos[0], pos[1] + i, pos[2]], pos[1] - 1) {
return i;
}
}
@@ -79,7 +84,7 @@ pub fn can_be_reached_by_noxious_gas(
pos: [f64; 3],
) -> bool {
let block = ParticleLevel::block_at(pos);
if !is_geyser_passable_block(level, block) {
if !is_geyser_passable_block(level, block, block[1] - 1) {
return false;
}
let center = source_block.map(|c| f64::from(c) + 0.5);
+36 -1
View File
@@ -232,6 +232,8 @@ impl Selector {
pub struct Tick {
/// A vibration was chosen: its travel time (the particle starts).
pub started: Option<(Info, i32)>,
/// A vibration was reloaded from save: particle resumes from interpolated pos.
pub resumed: Option<(Info, i32)>,
/// A vibration arrived.
pub received: Option<Info>,
/// `onDataChanged`.
@@ -261,6 +263,10 @@ impl Data {
self.selector.start_over();
}
if let Some(info) = self.current {
if self.reload_particle {
self.reload_particle = false;
out.resumed = Some((info, self.travel));
}
let mut changed = self.travel > 0;
self.travel = (self.travel - 1).max(0);
if self.travel <= 0 {
@@ -293,8 +299,11 @@ impl Data {
Tag::compound(entries)
}
pub fn from_nbt(tag: &Tag) -> Self {
let current = tag.get("event").and_then(info_from_nbt);
let reload_particle = current.is_some();
let mut data = Self {
current: tag.get("event").and_then(info_from_nbt),
current,
reload_particle,
..Self::default()
};
if let Some(Tag::Int(t)) = tag.get("event_delay") {
@@ -979,4 +988,30 @@ mod tests {
assert_eq!(back.spreader.cursors[0].charge, 1000);
assert_eq!(back.spreader.cursors[1].charge, 500);
}
#[test]
fn vibration_reloads_particle() {
let tag = Tag::compound([
(
"event",
Tag::compound([
("game_event", Tag::String("minecraft:step".into())),
("distance", Tag::Float(4.0f32.to_bits())),
(
"pos",
Tag::List(vec![
Tag::Double(1.0f64.to_bits()),
Tag::Double(0),
Tag::Double(0),
]),
),
]),
),
("event_delay", Tag::Int(3)),
]);
let mut d = Data::from_nbt(&tag);
assert!(d.reload_particle && d.current.is_some());
let tick = d.tick(10, true, true, |dist| dist as i32);
assert!(tick.resumed.is_some() && !d.reload_particle);
}
}
@@ -203,6 +203,9 @@ pub struct Settings {
pub startup_api: crate::graphics::GraphicsApi,
/// `Monitor.videoModes` of the window's monitor, for the Video page (set by the game).
pub video_modes: Vec<crate::window::VideoMode>,
/// Fullbright is held off: this window plays on another's server (set by the game, not
/// saved). The graphics screen hides its row; `extras.fullbright` keeps the choice.
pub fullbright_held: bool,
/// Controller settings (`horizon-controller.txt`, Horizon's own).
pub controller: crate::gamepad::PadSettings,
/// Horizon's optional extras (`horizon-extras.txt`), all off by default.
@@ -293,6 +296,7 @@ impl Default for Settings {
horizon: Default::default(),
startup_api: Default::default(),
video_modes: Vec::new(),
fullbright_held: false,
controller: Default::default(),
extras: Default::default(),
mods: Default::default(),
@@ -514,6 +518,7 @@ impl Settings {
horizon: Default::default(),
startup_api: Default::default(),
video_modes: Vec::new(),
fullbright_held: false,
controller: Default::default(),
extras: Default::default(),
mods: Default::default(),
+332 -7
View File
@@ -932,7 +932,56 @@ pub struct Downloader {
failed: std::collections::HashMap<(Kind, String), std::time::Instant>,
/// How long a failed texture download waits before it is tried again.
retry_after: std::time::Duration,
/// The `states` keys, oldest first, so the oldest settled one can go ([`Bounds::states`]).
state_order: std::collections::VecDeque<(Kind, String)>,
/// The `resources` keys, oldest first ([`Bounds::resources`]).
resource_order: std::collections::VecDeque<String>,
/// Downloads started whose answer `state` has not taken yet: one thread each.
in_flight: usize,
/// Fetches a texture's body; the HTTP GET, but for a test.
fetch: fn(&str) -> Option<Vec<u8>>,
bounds: Bounds,
}
/// A download thread's answer to `state`. If the thread panics before giving it (a body that
/// breaks the decoder, say), dropping this answers "failed" instead: the download's place in
/// `in_flight` is given back and the texture is retried after the wait, where an answer that never
/// came kept the key `Pending` for good and, with the bound, the place taken for the session.
struct Answer {
send: std::sync::mpsc::Sender<((Kind, String), Option<Vec<u8>>)>,
key: Option<(Kind, String)>,
}
impl Answer {
fn give(&mut self, image: Option<Vec<u8>>) {
if let Some(key) = self.key.take() {
let _ = self.send.send((key, image));
}
}
}
impl Drop for Answer {
fn drop(&mut self) {
self.give(None);
}
}
/// What the downloader keeps and runs at most. Every texture URL a server (or a tab list of
/// hundreds of players) names used to add a `states` entry and a thread of its own, and every
/// `texture` id a `resources` entry, none of them ever dropped.
#[derive(Clone, Copy, Debug)]
struct Bounds {
/// Entries of `states`; the oldest settled (ready or failed) one is dropped past this. A
/// dropped texture is loaded again from the disk cache when it is asked for.
states: usize,
/// Entries of `resources`; the oldest is dropped past this, and read from the packs again.
resources: usize,
/// Downloads running at once. Past this `state` says `Pending` and starts nothing, so the
/// caller, which asks again every frame, starts it when one has finished.
downloads: usize,
}
const BOUNDS: Bounds = Bounds {
states: 4096,
resources: 4096,
downloads: 16,
};
/// `images` is bounded only so a long session on a busy server does not grow
/// without end; the disk cache holds everything it drops.
const MAX_SKIN_IMAGES: usize = 1024;
@@ -964,6 +1013,11 @@ impl Downloader {
resources: Default::default(),
failed: Default::default(),
retry_after: std::time::Duration::from_secs(60),
state_order: Default::default(),
resource_order: Default::default(),
in_flight: 0,
fetch: http_get,
bounds: BOUNDS,
}
}
/// The resource packs changed (or were first loaded) at `root`: patch
@@ -973,6 +1027,7 @@ impl Downloader {
self.images.remove(&location);
self.image_order.retain(|l| *l != location);
}
self.resource_order.clear();
self.resource_root = root;
}
/// `ClientAsset.ResourceTexture`: loads `<namespace>:textures/<path>.png`
@@ -1002,12 +1057,47 @@ impl Downloader {
}
None => Download::Failed,
};
self.resources.insert(location.to_owned(), state);
if self.resources.insert(location.to_owned(), state).is_none() {
self.resource_order.push_back(location.to_owned());
while self.resources.len() > self.bounds.resources
&& let Some(old) = self.resource_order.pop_front()
{
self.resources.remove(&old);
}
}
}
/// Forgets how `location` loaded, so `resource` reads it again.
fn forget_resource(&mut self, location: &str) {
if self.resources.remove(location).is_some() {
self.resource_order.retain(|l| l != location);
}
}
/// Records how `key` stands. A new key may push the oldest settled one out of `states`;
/// downloads running are never dropped, so their answer has a key to land on.
fn set_state(&mut self, key: (Kind, String), state: Download) {
if self.states.insert(key.clone(), state).is_some() {
return;
}
self.state_order.push_back(key);
while self.states.len() > self.bounds.states {
let Some(at) = self
.state_order
.iter()
.position(|k| self.states.get(k) != Some(&Download::Pending))
else {
break;
};
if let Some(old) = self.state_order.remove(at) {
self.states.remove(&old);
self.failed.remove(&old);
}
}
}
/// How the download of `url` stands, starting it the first time. A
/// failure is permanent for `retry_after`, then tried again.
pub fn state(&mut self, kind: Kind, url: &str) -> Download {
while let Ok((key, image)) = self.done.try_recv() {
self.in_flight = self.in_flight.saturating_sub(1);
let state = match image {
Some(rgba) => {
match key.0 {
@@ -1023,29 +1113,42 @@ impl Downloader {
Download::Failed
}
};
self.states.insert(key, state);
self.set_state(key, state);
}
let Some(hash) = texture_hash(url) else {
return Download::Failed;
};
let key = (kind, hash);
let full = self.in_flight >= self.bounds.downloads;
if let Some(state) = self.states.get(&key).copied() {
let due = self
.failed
.get(&key)
.is_none_or(|at| at.elapsed() >= self.retry_after);
if state != Download::Failed || !due {
// A failure that is due waits for a free download like a new texture does.
if state != Download::Failed || !due || full {
return state;
}
self.states.remove(&key);
self.failed.remove(&key);
self.state_order.retain(|k| *k != key);
}
self.states.insert(key.clone(), Download::Pending);
if full {
// Not recorded: the next call asks again, and starts it once one has finished.
return Download::Pending;
}
self.in_flight += 1;
self.set_state(key.clone(), Download::Pending);
let digest: String = skin_location(&key.1)["skins/".len()..].to_owned();
let (url, send, root) = (url.to_owned(), self.send.clone(), self.root.clone());
let fetch = self.fetch;
std::thread::spawn(move || {
let image = Self::load_texture(&root, kind, &digest, &url, http_get);
let _ = send.send((key, image));
let mut answer = Answer {
send,
key: Some(key),
};
let image = Self::load_texture(&root, kind, &digest, &url, fetch);
answer.give(image);
});
Download::Pending
}
@@ -1108,7 +1211,7 @@ impl Downloader {
if location.starts_with("patch/") {
let Some(image) = self.images.get(location).cloned() else {
// Dropped from memory: read from the packs again.
self.resources.remove(location);
self.forget_resource(location);
return false;
};
self.queue(location.to_owned(), image);
@@ -1925,3 +2028,225 @@ mod tests {
assert_eq!(served.load(Ordering::SeqCst), 2);
}
}
#[cfg(test)]
mod download_bound_tests {
use super::{Bounds, Download, Downloader, Kind};
use std::sync::atomic::{AtomicUsize, Ordering};
fn downloader(name: &str, bounds: Bounds, fetch: fn(&str) -> Option<Vec<u8>>) -> Downloader {
let root =
std::env::temp_dir().join(format!("horizon-test-skin-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let mut d = Downloader::new(root);
d.fetch = fetch;
d.bounds = bounds;
d
}
fn url(i: usize) -> String {
format!("https://textures.example/texture/skin{i:05}")
}
/// Asks again until the texture's download has settled.
fn wait(d: &mut Downloader, url: &str) -> Download {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let state = d.state(Kind::Skin, url);
if state != Download::Pending || std::time::Instant::now() > deadline {
return state;
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
static RUNNING: AtomicUsize = AtomicUsize::new(0);
static PEAK: AtomicUsize = AtomicUsize::new(0);
/// A fetch that is slow enough for the others to pile up behind it, and counts how many run.
fn slow_failure(_: &str) -> Option<Vec<u8>> {
let now = RUNNING.fetch_add(1, Ordering::SeqCst) + 1;
PEAK.fetch_max(now, Ordering::SeqCst);
std::thread::sleep(std::time::Duration::from_millis(20));
RUNNING.fetch_sub(1, Ordering::SeqCst);
None
}
/// The same, not counted: tests run side by side, and the count is another test's.
fn sleepy_failure(_: &str) -> Option<Vec<u8>> {
std::thread::sleep(std::time::Duration::from_millis(20));
None
}
/// A tab list of 60 players names 60 textures at once: no more than the bound run together,
/// the ones that waited start as the others finish, and every one ends. Every frame asks again.
#[test]
fn downloads_run_a_few_at_a_time_and_the_late_ones_start_later() {
let bounds = Bounds {
states: 4096,
resources: 4096,
downloads: 4,
};
let mut d = downloader("threads", bounds, slow_failure);
let urls: Vec<String> = (0..60).map(url).collect();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
let mut first = true;
loop {
let states: Vec<Download> = urls.iter().map(|u| d.state(Kind::Skin, u)).collect();
if first {
// Asked all at once: four started, and the others were not even recorded.
assert_eq!(d.in_flight, 4);
assert_eq!(d.states.len(), 4);
assert!(states.iter().all(|s| *s == Download::Pending));
first = false;
}
if states.iter().all(|s| *s == Download::Failed) {
break;
}
assert!(
std::time::Instant::now() < deadline,
"{} still pending",
states.len()
);
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert!(
PEAK.load(Ordering::SeqCst) <= 4,
"{}",
PEAK.load(Ordering::SeqCst)
);
assert_eq!(d.states.len(), 60);
assert_eq!(d.in_flight, 0);
}
/// More textures than `states` holds: the map keeps to its bound, the oldest settled ones go
/// (and their failure time with them), and one that went is asked again as a new texture.
#[test]
fn the_states_keep_to_their_bound_and_drop_the_oldest() {
let bounds = Bounds {
states: 8,
resources: 4096,
downloads: 16,
};
let mut d = downloader("states", bounds, |_| None);
for i in 0..40 {
let u = url(i);
assert_eq!(wait(&mut d, &u), Download::Failed, "{i}");
assert!(d.states.len() <= 8 && d.state_order.len() == d.states.len());
assert!(d.failed.len() <= 8);
}
let kept: Vec<usize> = (0..40)
.filter(|i| {
d.states
.contains_key(&(Kind::Skin, super::texture_hash(&url(*i)).unwrap()))
})
.collect();
assert_eq!(kept, (32..40).collect::<Vec<_>>());
// The first one went: asked again, it starts again (and fails again).
assert_eq!(d.state(Kind::Skin, &url(0)), Download::Pending);
assert_eq!(d.in_flight, 1);
}
/// A fetch that panics, as a decoder can on a body a server chose.
fn panicking(_: &str) -> Option<Vec<u8>> {
panic!("a fetch that panics, on purpose");
}
/// A thread that panics before it answers still gives its place back: with two places and six
/// textures whose fetch panics, every one settles as failed instead of the places staying
/// taken for good.
#[test]
fn a_download_that_panics_gives_its_place_back() {
let bounds = Bounds {
states: 4096,
resources: 4096,
downloads: 2,
};
let mut d = downloader("panics", bounds, panicking);
for i in 0..6 {
assert_eq!(wait(&mut d, &url(i)), Download::Failed, "{i}");
}
assert_eq!(d.in_flight, 0);
assert_eq!(d.states.len(), 6);
}
/// A fetch long enough for a test to ask between its start and its end.
fn slowish_failure(_: &str) -> Option<Vec<u8>> {
std::thread::sleep(std::time::Duration::from_millis(150));
None
}
/// A failure whose wait is over is retried like a new texture: not while every place is taken
/// (it keeps answering `Failed`, and starts nothing), and as soon as one is free.
#[test]
fn a_failure_that_is_due_waits_for_a_free_place() {
let bounds = Bounds {
states: 4096,
resources: 4096,
downloads: 1,
};
let mut d = downloader("due", bounds, slowish_failure);
let wait_time = d.retry_after;
assert_eq!(wait(&mut d, &url(0)), Download::Failed);
// Another texture takes the only place; the first one's retry becomes due but has to wait.
assert_eq!(d.state(Kind::Skin, &url(1)), Download::Pending);
d.retry_after = std::time::Duration::ZERO;
assert_eq!(d.state(Kind::Skin, &url(0)), Download::Failed);
assert_eq!(d.in_flight, 1);
d.retry_after = wait_time;
assert_eq!(wait(&mut d, &url(1)), Download::Failed);
// The place is free: the retry starts.
d.retry_after = std::time::Duration::ZERO;
assert_eq!(d.state(Kind::Skin, &url(0)), Download::Pending);
assert_eq!(d.in_flight, 1);
}
/// A texture that is running is never the one dropped, however many settle behind it.
#[test]
fn a_running_download_keeps_its_place_in_the_states() {
let bounds = Bounds {
states: 2,
resources: 4096,
downloads: 16,
};
let mut d = downloader("running", bounds, sleepy_failure);
assert_eq!(d.state(Kind::Skin, &url(0)), Download::Pending);
for i in 1..6 {
d.set_state((Kind::Cape, format!("settled{i}")), Download::Ready);
}
assert_eq!(
d.states
.get(&(Kind::Skin, super::texture_hash(&url(0)).unwrap())),
Some(&Download::Pending)
);
assert!(d.states.len() <= 3);
assert_eq!(wait(&mut d, &url(0)), Download::Failed);
}
/// `resources` keeps to its bound too: a server's `texture` ids, one for each unique one, no
/// longer pile up, and one that was dropped is read from the packs again.
#[test]
fn the_resource_textures_keep_to_their_bound() {
let bounds = Bounds {
states: 4096,
resources: 8,
downloads: 16,
};
let mut d = downloader("resources", bounds, |_| None);
for i in 0..40 {
d.resource(&format!("patch/n/{i}"), "n", &format!("t{i}"));
assert!(d.resources.len() <= 8 && d.resource_order.len() == d.resources.len());
}
let kept: Vec<usize> = (0..40)
.filter(|i| d.resources.contains_key(&format!("patch/n/{i}")))
.collect();
assert_eq!(kept, (32..40).collect::<Vec<_>>());
// Forgetting one by hand (as `again` does) leaves no stale key behind.
d.forget_resource("patch/n/35");
assert_eq!(d.resource_order.len(), d.resources.len());
assert!(!d.resource_order.iter().any(|l| l == "patch/n/35"));
// New packs start the count over.
d.set_resource_root(std::env::temp_dir());
assert!(d.resources.is_empty() && d.resource_order.is_empty());
}
}
+98 -19
View File
@@ -127,6 +127,9 @@ pub struct Sprites {
/// textures under their own names, and one layer serves them all (the GPU's array may
/// hold as few as 2048).
still: std::collections::HashMap<StillKey, u32>,
/// Names a connected-texture rule matches by name (`matchTiles`, `connectTiles`): each keeps a
/// layer of its own ([`Sprites::keep_apart`]).
apart: std::collections::HashSet<String>,
/// Decoded textures kept on disk between launches ([`Sprites::with_disk_cache`]).
disk: Option<crate::sprite_cache::SpriteCache>,
/// Textures [`Sprites::prefetch`] decoded ahead of their insert, by sprite name or
@@ -218,6 +221,13 @@ impl Sprites {
..Self::default()
}
}
/// Keeps each of `names` on a layer of its own, never shared with an identical texture: the
/// connected-texture rules that name them find their faces by layer, so a texture sharing it
/// would be matched too (a tile a rule chains onto, and a model's transparent placeholder
/// with the same pixels). Before the textures that bear these names are inserted.
pub fn keep_apart(&mut self, names: impl IntoIterator<Item = String>) {
self.apart.extend(names);
}
/// Write what this run decoded to the cache file.
pub fn save_disk_cache(&mut self) {
if let Some(disk) = &mut self.disk {
@@ -287,8 +297,13 @@ impl Sprites {
let mut resized = Vec::with_capacity(self.native.len());
self.pixels.clear();
for (from, frames, initial) in &self.native {
let frames: Arc<Vec<Vec<u8>>> =
Arc::new(frames.iter().map(|f| resample(f, *from, size)).collect());
// Native frames already match the atlas size: share the immutable
// buffers with animations rather than copying every frame again.
let frames: Arc<Vec<Vec<u8>>> = if *from == size {
Arc::clone(frames)
} else {
Arc::new(frames.iter().map(|f| resample(f, *from, size)).collect())
};
self.pixels.extend_from_slice(&frames[*initial]);
resized.push(frames);
}
@@ -686,23 +701,24 @@ impl Sprites {
.is_some_and(|(_, p)| p.starts_with("item/")),
dither_cutouts: crate::mipmap::dither_cutouts(),
};
let still = (animation.is_none() && frames.len() == 1).then(|| {
use std::hash::{Hash, Hasher};
let mut frame = std::collections::hash_map::DefaultHasher::new();
frames[0].hash(&mut frame);
let mut maps = std::collections::hash_map::DefaultHasher::new();
pbr.hash(&mut maps);
StillKey {
frame: frame.finish(),
pbr: maps.finish(),
side,
settings: [
settings.strategy as u32,
settings.alpha_cutoff_bias.to_bits(),
],
flags: [settings.has_transparent, settings.item, opaque, translucent],
}
});
let still =
(animation.is_none() && frames.len() == 1 && !self.apart.contains(name)).then(|| {
use std::hash::{Hash, Hasher};
let mut frame = std::collections::hash_map::DefaultHasher::new();
frames[0].hash(&mut frame);
let mut maps = std::collections::hash_map::DefaultHasher::new();
pbr.hash(&mut maps);
StillKey {
frame: frame.finish(),
pbr: maps.finish(),
side,
settings: [
settings.strategy as u32,
settings.alpha_cutoff_bias.to_bits(),
],
flags: [settings.has_transparent, settings.item, opaque, translucent],
}
});
if let Some(&same) = still.as_ref().and_then(|k| self.still.get(k)) {
self.layers.insert(name.to_owned(), same);
return Ok(same);
@@ -872,6 +888,35 @@ mod tests {
use super::*;
use std::fs::{self, File};
#[test]
fn native_frames_at_atlas_size_are_shared_without_resampling() {
let pixels = vec![
[10, 20, 30, 255].repeat((SPRITE_SIZE * SPRITE_SIZE) as usize),
[40, 50, 60, 255].repeat((SPRITE_SIZE * SPRITE_SIZE) as usize),
];
let native = Arc::new(pixels.clone());
let smaller = Arc::new(vec![vec![12; 8 * 8 * 4], vec![34; 8 * 8 * 4]]);
let metadata = r#"{"frametime":2}"#;
let mut sprites = Sprites {
native: vec![
(SPRITE_SIZE, Arc::clone(&native), 1),
(8, Arc::clone(&smaller), 0),
],
pbr: vec![[None, None], [None, None]],
animations: vec![
test_frames(0, pixels.clone(), metadata),
test_frames(1, smaller.as_ref().clone(), metadata),
],
..Default::default()
};
sprites.finish();
assert!(Arc::ptr_eq(&sprites.animations[0].frames, &native));
assert!(!Arc::ptr_eq(&sprites.animations[1].frames, &smaller));
assert_eq!(sprites.animations[0].pixels(1), pixels[1].as_slice());
let resized = resample(&smaller[0], 8, SPRITE_SIZE);
assert_eq!(sprites.animations[1].pixels(0), resized.as_slice());
assert_eq!(&sprites.pixels[..pixels[1].len()], pixels[1].as_slice());
}
#[test]
fn the_texture_budget_picks_the_largest_side_that_fits() {
// 1300 layers: vanilla's count, about.
assert_eq!(side_within(512, 1300, DEFAULT_TEXTURE_BUDGET), 128);
@@ -1282,6 +1327,40 @@ mod tests {
assert_eq!(sprites.pixels.len(), 3 * 16 * 16 * 4);
}
#[test]
fn a_texture_a_connected_rule_matches_keeps_a_layer_of_its_own() {
// A resource pack's transparent placeholders: a model's layer and a tile another
// connected-texture rule chains onto (`matchTiles=./19.png`) have the same pixels. The
// rule finds its faces by layer, so the one it names can't share the others'.
let root =
std::env::temp_dir().join(format!("horizon-sprite-apart-{}", std::process::id()));
let directory = root.join("assets/a/textures/block");
fs::create_dir_all(&directory).unwrap();
let write = |name: &str| {
let mut encoder =
png::Encoder::new(File::create(directory.join(name)).unwrap(), 16, 16);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(&[0; 16 * 16 * 4])
.unwrap();
};
for name in ["placeholder.png", "named.png", "again.png"] {
write(name);
}
let mut sprites = Sprites::default();
sprites.keep_apart(["a:block/named".to_owned()]);
let placeholder = sprites.insert(&root, "a:block/placeholder").unwrap();
let named = sprites.insert(&root, "a:block/named").unwrap();
let again = sprites.insert(&root, "a:block/again").unwrap();
fs::remove_dir_all(&root).unwrap();
// The named one alone; the others still share.
assert_ne!(named, placeholder);
assert_eq!(again, placeholder);
assert_eq!(sprites.count(), 2);
}
#[test]
fn a_32px_only_atlas_does_not_add_an_extra_mipmap() {
let mut sprites = Sprites {
native: vec![
+26 -22
View File
@@ -605,6 +605,9 @@ pub struct Streaming {
/// Set while `update` runs, after it refreshed `cover`: nothing else can
/// change `extra` meanwhile, so `cover` answers without comparing them.
cover_current: bool,
/// `forced` and `mod_forced` as each column's distance to the nearest one, made again when
/// they change; read like `cover`, while `cover_current`.
forced_cover: Option<ForcedCover>,
/// Mesh the sections for drawing (false on a server thread).
pub mesh: bool,
/// The pregeneration band (`set_band`).
@@ -806,6 +809,7 @@ impl GenerationScan {
forced: input.ranges.forced,
mod_forced: input.ranges.mod_forced,
cover: input.ranges.cover,
forced_cover: None,
band: input.ranges.band,
};
self.remember(ranges, input.world);
@@ -1066,8 +1070,10 @@ pub struct WorkerContext {
pub light: Arc<LightTables>,
}
mod bounded;
mod forced_cover;
mod relight_now;
use bounded::nearest_first;
use forced_cover::ForcedCover;
impl Streaming {
pub fn new<G: ChunkGenerator>(
generator: Arc<G>,
@@ -1176,6 +1182,7 @@ impl Streaming {
extra: Vec::new(),
cover: None,
cover_current: false,
forced_cover: None,
mesh: true,
band: None,
band_ranked: None,
@@ -1691,6 +1698,7 @@ impl Streaming {
let mut columns = std::mem::take(&mut self.mesh_columns_scratch);
columns.clear();
ExtraCover::refresh(&mut self.cover, &self.extra);
ForcedCover::refresh(&mut self.forced_cover, &self.forced, &self.mod_forced);
self.cover_current = true;
// The sweeps below walk every loaded column and proto chunk. Run them
// at once when the view moves and every eighth tick otherwise: a
@@ -1870,6 +1878,7 @@ impl Streaming {
forced: &self.forced,
mod_forced: &self.mod_forced,
cover: ExtraCover::current(&self.cover, &self.extra, self.cover_current),
forced_cover: self.forced_cover.as_ref().filter(|_| self.cover_current),
band: self.band.as_ref(),
};
let (protos, generating) = (&self.protos, &self.generating);
@@ -2040,6 +2049,7 @@ impl Streaming {
forced: &self.forced,
mod_forced: &self.mod_forced,
cover: ExtraCover::current(&self.cover, &self.extra, self.cover_current),
forced_cover: self.forced_cover.as_ref().filter(|_| self.cover_current),
band: self.band.as_ref(),
};
self.waiting.retain(|&(x, sy, z)| {
@@ -2145,6 +2155,7 @@ impl Streaming {
forced: &self.forced,
mod_forced: &self.mod_forced,
cover: ExtraCover::current(&self.cover, &self.extra, self.cover_current),
forced_cover: self.forced_cover.as_ref().filter(|_| self.cover_current),
band: self.band.as_ref(),
},
world,
@@ -2283,6 +2294,7 @@ impl Streaming {
forced: &self.forced,
mod_forced: &self.mod_forced,
cover: ExtraCover::current(&self.cover, &self.extra, self.cover_current),
forced_cover: self.forced_cover.as_ref().filter(|_| self.cover_current),
band: self.band.as_ref(),
}
}
@@ -2563,6 +2575,8 @@ struct Ranges<'a> {
/// `extra` indexed by a grid or buckets: coverage queries without a
/// scan of every area.
cover: Option<&'a ExtraCover>,
/// `forced` and `mod_forced` by distance (`Streaming::forced_cover`), while they match it.
forced_cover: Option<&'a ForcedCover>,
band: Option<&'a Band>,
}
/// The chunks a pregeneration task (`/pregen`) wants lit now: rows `z0..=z1`
@@ -2611,6 +2625,7 @@ impl Band {
+ i64::from(x - self.x0 + 8).max(0)
}
}
/// For every column near the extra areas, how far it lies outside the
/// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every
/// loaded and wanted column whether one reaches it, several times a tick:
@@ -2918,16 +2933,6 @@ impl Ranges<'_> {
.iter()
.any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin)
}
/// Whether a `/forceload` or a native mod's ticket holds the chunk.
fn is_forced(&self, x: i32, z: i32) -> bool {
self.forced.contains(&(x, z)) || self.mod_forced.contains(&(x, z))
}
/// Every chunk a `/forceload` or a native mod's ticket holds, once each.
fn forced_chunks(&self) -> impl Iterator<Item = &(i32, i32)> + '_ {
self.forced
.iter()
.chain(self.mod_forced.iter().filter(|c| !self.forced.contains(c)))
}
/// The columns meshed for drawing: those vanilla draws around the
/// player (`in_view_distance`), and forced ones.
fn in_view(&self, x: i32, z: i32) -> bool {
@@ -2939,18 +2944,7 @@ impl Ranges<'_> {
if self.radius >= 0 && dx * dx + dz * dz <= r * r {
return true;
}
// A forced chunk holds a FORCED ticket at level 31
// (`ChunkMap.FORCED_TICKET_LEVEL`), and the level rises one per ring
// (`ChunkTracker.computeLevelFromNeighbor`): the margin is the
// vanilla status ring the caller asks for.
let reach = match margin {
1 => FORCED_FULL_RING,
2 => FORCED_FEATURES_RING,
3 => FORCED_TERRAIN_RING,
_ => margin + 1,
};
self.forced_chunks()
.any(|f| (x - f.0).abs() <= reach && (z - f.1).abs() <= reach)
self.near_forced(x, z, margin)
}
}
impl Drop for Streaming {
@@ -3484,6 +3478,7 @@ mod tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover: None,
forced_cover: None,
band: None,
};
let generate = |x, z, priority, order| Queued {
@@ -3724,6 +3719,7 @@ mod tests {
forced: &self.forced,
mod_forced: &NO_CHUNKS,
cover: None,
forced_cover: None,
band: None,
},
world: &self.world,
@@ -4107,6 +4103,7 @@ mod tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover: None,
forced_cover: None,
band: None,
};
let square = |x: i32, z: i32, n: i32| {
@@ -4164,6 +4161,7 @@ mod tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover: None,
forced_cover: None,
band: None,
};
let span = radius * 3 + 20;
@@ -4201,6 +4199,7 @@ mod tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover: None,
forced_cover: None,
band: None,
};
for x in -5i32..=15 {
@@ -4235,6 +4234,7 @@ mod tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover: None,
forced_cover: None,
band: None,
};
let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0);
@@ -4290,6 +4290,7 @@ mod tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover: None,
forced_cover: None,
band: None,
};
let level = |x: i32, z: i32| 31 + (x - 40).abs().max((z + 40).abs());
@@ -4430,6 +4431,7 @@ mod cover_tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover,
forced_cover: None,
band: None,
};
let (scan, grid) = (ranges(None), ranges(Some(&cover)));
@@ -4473,6 +4475,7 @@ mod cover_tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover,
forced_cover: None,
band: None,
};
let (scan, buckets) = (ranges(None), ranges(Some(&cover)));
@@ -4539,6 +4542,7 @@ mod cover_tests {
forced: &forced,
mod_forced: &NO_CHUNKS,
cover,
forced_cover: None,
band: None,
};
// The columns streaming asks about: everything kept, and the
@@ -0,0 +1,165 @@
//! The chunks a `/forceload` or a native mod's ticket holds, as `Ranges` reads them, and their
//! distance map.
use super::{FORCED_FEATURES_RING, FORCED_FULL_RING, FORCED_TERRAIN_RING, Ranges};
use crate::fast_hash::FxHashMap;
use std::collections::HashSet;
/// `Streaming::forced` and `mod_forced` as the Chebyshev distance from each column within
/// `REACH` of one to the nearest: `Ranges::in_main_range` answers by one lookup instead of going
/// through every forced chunk (it is asked for every column, several times a tick).
pub(super) struct ForcedCover {
forced: HashSet<(i32, i32)>,
mod_forced: HashSet<(i32, i32)>,
near: FxHashMap<(i32, i32), u8>,
}
impl ForcedCover {
/// The widest ring `in_main_range` asks of a forced chunk (margins 1 to 4).
const REACH: i32 = FORCED_TERRAIN_RING + 1;
/// Past this many forced chunks the cover is not made: the scan answers.
const MOST: usize = 4096;
pub(super) fn refresh(
cover: &mut Option<Self>,
forced: &HashSet<(i32, i32)>,
mod_forced: &HashSet<(i32, i32)>,
) {
if cover
.as_ref()
.is_some_and(|c| c.forced == *forced && c.mod_forced == *mod_forced)
{
return;
}
if forced.len() + mod_forced.len() > Self::MOST {
*cover = None;
return;
}
let mut near = FxHashMap::default();
for &(fx, fz) in forced.iter().chain(mod_forced) {
for dx in -Self::REACH..=Self::REACH {
for dz in -Self::REACH..=Self::REACH {
let d = dx.abs().max(dz.abs()) as u8;
near.entry((fx + dx, fz + dz))
.and_modify(|e: &mut u8| *e = (*e).min(d))
.or_insert(d);
}
}
}
*cover = Some(Self {
forced: forced.clone(),
mod_forced: mod_forced.clone(),
near,
});
}
/// Whether a forced chunk lies within `reach` of `(x, z)`, or `None` past `REACH`.
pub(super) fn within(&self, x: i32, z: i32, reach: i32) -> Option<bool> {
(reach <= Self::REACH).then(|| {
self.near
.get(&(x, z))
.is_some_and(|&d| i32::from(d) <= reach)
})
}
}
impl Ranges<'_> {
/// Whether a `/forceload` or a native mod's ticket holds the chunk.
pub(super) fn is_forced(&self, x: i32, z: i32) -> bool {
self.forced.contains(&(x, z)) || self.mod_forced.contains(&(x, z))
}
/// Every chunk a `/forceload` or a native mod's ticket holds, once each.
pub(super) fn forced_chunks(&self) -> impl Iterator<Item = &(i32, i32)> + '_ {
self.forced
.iter()
.chain(self.mod_forced.iter().filter(|c| !self.forced.contains(c)))
}
/// `in_main_range` past the player's circle: whether a forced chunk lies within the ring
/// `margin` asks for.
pub(super) fn near_forced(&self, x: i32, z: i32, margin: i32) -> bool {
// A forced chunk holds a FORCED ticket at level 31
// (`ChunkMap.FORCED_TICKET_LEVEL`), and the level rises one per ring
// (`ChunkTracker.computeLevelFromNeighbor`): the margin is the
// vanilla status ring the caller asks for.
let reach = match margin {
1 => FORCED_FULL_RING,
2 => FORCED_FEATURES_RING,
3 => FORCED_TERRAIN_RING,
_ => margin + 1,
};
if let Some(hit) = self.forced_cover.and_then(|c| c.within(x, z, reach)) {
return hit;
}
self.forced_chunks()
.any(|f| (x - f.0).abs() <= reach && (z - f.1).abs() <= reach)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn chunks(seed: &mut u64, n: usize, spread: i32) -> HashSet<(i32, i32)> {
let mut next = |m: i32| {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
(*seed % (2 * m as u64 + 1)) as i32 - m
};
(0..n).map(|_| (next(spread), next(spread))).collect()
}
/// With the forced chunks by distance, every column gets the answer the scan of every forced
/// chunk gives, at every margin streaming asks (and those past the map's reach), after the
/// forced chunks change too.
#[test]
fn the_distances_answer_as_the_scan() {
let mut seed = 0x2545_F491_4F6C_DD1Du64;
let mut cover = None;
for case in 0..24 {
let spread = [3, 12, 40][case % 3];
let forced = chunks(&mut seed, 1 + case % 9, spread);
// Some mod tickets on forced chunks, some apart.
let mut mod_forced = chunks(&mut seed, case % 4, spread);
mod_forced.extend(forced.iter().take(case % 2));
ForcedCover::refresh(&mut cover, &forced, &mod_forced);
let made = cover.as_ref().expect("a few forced chunks get a map");
let ranges = |forced_cover| Ranges {
// The player's circle far away: only the forced chunks answer.
center: (10_000, 10_000),
radius: 2,
extra: &[],
forced: &forced,
mod_forced: &mod_forced,
cover: None,
forced_cover,
band: None,
};
let (scan, map) = (ranges(None), ranges(Some(made)));
let span = spread + 10;
for z in -span..=span {
for x in -span..=span {
for margin in 0..=7 {
assert_eq!(
map.in_main_range(x, z, margin),
scan.in_main_range(x, z, margin),
"case {case} ({x}, {z}) margin {margin}"
);
}
for d in [false, true] {
assert_eq!(map.requested(x, z, d), scan.requested(x, z, d));
assert_eq!(map.chunk_kept(x, z, d), scan.chunk_kept(x, z, d));
assert_eq!(map.unloaded(x, z, d), scan.unloaded(x, z, d));
}
}
}
}
}
/// Too many forced chunks for a map: none is made, and the scan answers.
#[test]
fn past_the_most_no_map_is_made() {
let forced: HashSet<(i32, i32)> = (0..=ForcedCover::MOST as i32).map(|x| (x, 0)).collect();
let mut cover = None;
ForcedCover::refresh(&mut cover, &HashSet::new(), &HashSet::from([(0, 0)]));
assert!(cover.is_some());
ForcedCover::refresh(&mut cover, &forced, &HashSet::new());
assert!(cover.is_none());
}
}
+18 -8
View File
@@ -524,8 +524,18 @@ fn packed_corner(lo: vec3<u32>, hi: vec3<u32>, corner: u32) -> ArenaCorner {
let packed_light = ((light & 63u) << 2u) | (((light >> 6u) & 63u) << 10u);
let g = (lo.y >> (8u * corner)) & 255u;
let t = lo.x;
// Corners 1 to 3's own alpha (`packed::ALPHA_STEP` times the code; 0: word 0's).
var code = 0u;
if corner == 1u {
code = (hi.x >> 28u) & 7u;
} else if corner == 2u {
code = (hi.y >> 24u) & 7u;
} else if corner == 3u {
code = (hi.y >> 27u) & 7u;
}
let alpha = select((code * 51u) << 24u, t & 0xff000000u, code == 0u);
let color = (g * ((t >> 16u) & 255u) / 255u) | ((g * ((t >> 8u) & 255u) / 255u) << 8u)
| ((g * (t & 255u) / 255u) << 16u) | (t & 0xff000000u);
| ((g * (t & 255u) / 255u) << 16u) | alpha;
return ArenaCorner(bitcast<vec3<u32>>(vec3<f32>(pos)),
vec3((u << 10u) | (v << 26u), (hi.x & 0xffffu) | (packed_light << 16u), color));
}
@@ -955,13 +965,13 @@ const PI: f32 = 3.14159265;
fn disc_distance(d: vec3<f32>, y: f32) -> vec2<f32> {
if d.y * y <= 0.0 { return vec2(-1.0); }
let p = d * (y / d.y);
let h = length(p.xz);
let phi = atan2(p.z, p.x);
let sector = PI / 4.0;
let delta = phi - (floor(phi / sector) * sector + sector * 0.5);
let edge = 512.0 * cos(sector * 0.5) / cos(delta);
if h > edge { return vec2(-1.0); }
let s = h / edge;
// The regular octagon's edge parameter, directly from its half planes.
// max(|x| + tan(pi/8)*|z|, |z| + tan(pi/8)*|x|) / radius
// equals length(p.xz) / edge without atan2, floor or cos per pixel.
let a = abs(p.xz);
let diagonal = 0.41421356237309503;
let s = max(a.x + diagonal * a.y, a.y + diagonal * a.x) / 512.0;
if s > 1.0 { return vec2(-1.0); }
let ay = abs(y);
let rim = sqrt(512.0 * 512.0 + y * y);
return vec2(ay + s * (rim - ay), ay + s * (512.0 - ay));
@@ -14,6 +14,8 @@ pub enum Cursor {
Arrow,
PointingHand,
NotAllowed,
/// `CursorTypes.RESIZE_NS`: a scroller held vertically (`MerchantScreen`).
ResizeNs,
}
thread_local! {
@@ -530,7 +530,7 @@
"HDR Calibration %s/%s: %s": "HDR Calibration %s/%s: %s",
"Sets the three below full screen, one test picture at a time.": "Sets the three below full screen, one test picture at a time.",
"Your display didn't say how bright it gets: calibrate to set it up.": "Your display didn't say how bright it gets: calibrate to set it up.",
"Your display's reported peak is often too high: calibrate to set it up.": "Your display's reported peak is often too high: calibrate to set it up.",
"Auto uses the peak Windows reports. Calibrate if highlights look clipped.": "Auto uses the peak Windows reports. Calibrate if highlights look clipped.",
"Already set up for your display. Only calibrate if HDR looks wrong.": "Already set up for your display. Only calibrate if HDR looks wrong.",
"Puts Peak Brightness and Paper White back to your display's setup.": "Puts Peak Brightness and Paper White back to your display's setup.",
"Set up for your display. Leave on Auto unless it looks wrong.": "Set up for your display. Leave on Auto unless it looks wrong.",
@@ -1208,6 +1208,7 @@ pub fn main() -> horizon_client::Result<()> {
dragon: None,
leash_boats: &[],
who_lookup: None,
foreign: None,
others_grid: $grid,
others_index: None,
others_villagers: None,
+5 -5
View File
@@ -1989,13 +1989,13 @@ mod tests {
}
/// The criteria an inventory change and a recipe unlock test, on vanilla's tree:
/// `cargo test -p horizon-client --lib -- --ignored --nocapture index_on_vanilla_tree`
/// with HORIZON_RESOURCES set to the prepared resources.
/// with HORIZON_TEST_RESOURCES set to the prepared resources.
#[test]
#[ignore = "needs the prepared resources"]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn index_on_vanilla_tree() {
let Some(root) = std::env::var_os("HORIZON_RESOURCES").map(std::path::PathBuf::from) else {
return;
};
let root = std::path::PathBuf::from(
std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"),
);
let data = root.join("data");
let t = std::time::Instant::now();
let tree = Tree::load(&data);
+2 -2
View File
@@ -274,8 +274,8 @@ impl ArrowState {
/// `Arrow.getColor` of the server's own arrow: the colour of the potion on
/// its pickup item, None for a plain arrow (`PotionContents.EMPTY`).
pub fn potion_color(&self) -> Option<u32> {
let potion = self.pickup_item.potion()?;
Some(crate::brewing::potion_color(Some(potion)))
(!crate::brewing::contents_empty(&self.pickup_item))
.then(|| crate::brewing::contents_color(&self.pickup_item))
}
/// The `AbstractArrow` constructor's `pickupItemStack`: the drawn ammo
/// (one item). Ammo drawn without being used up (`INTANGIBLE_PROJECTILE`)
+2
View File
@@ -8,6 +8,7 @@ pub mod animate_tick;
pub mod arrows;
pub mod bed_geometry;
pub mod block_contact;
pub mod parallel;
pub mod powder_snow;
pub use horizon_client_render::{
assets, atlas_sources, audio, auth, autotune, ban_notice, bidi, biome, block_edit,
@@ -85,6 +86,7 @@ pub mod join_seq;
pub mod lan;
pub mod landing;
pub mod legacy_combat;
pub mod living_death;
pub mod locator_bar;
pub mod lod_net;
pub mod menu;
+39 -8
View File
@@ -26,8 +26,9 @@ pub struct Tab {
/// The page of tabs it is on: vanilla's are 0, mods' after, as NeoForge
/// pages them.
pub page: u32,
/// A Polytone creative tab modifier's `name`: its text and colour, over the tab's own.
pub name: Option<(String, Option<u32>)>,
/// A Polytone creative tab modifier's `name`: its text (a translation key when
/// the flag is set) and colour, over the tab's own.
pub name: Option<(String, Option<u32>, bool)>,
}
impl Tab {
/// The tab without its stacks.
@@ -103,25 +104,28 @@ pub struct Creative {
/// The packs' Polytone creative tab modifiers, applied by `rebuild`.
pack: Vec<crate::polytone_creative_tabs::TabModifier>,
}
/// A text component's plain text and its colour (a name, or `#rrggbb`).
fn component_text(json: &Value) -> (String, Option<u32>) {
/// A text component's text, its colour (a name, or `#rrggbb`) and whether the
/// text is a `translate` key, to be resolved when drawn.
fn component_text(json: &Value) -> (String, Option<u32>, bool) {
match json {
Value::String(s) => (s.clone(), None),
Value::String(s) => (s.clone(), None, false),
Value::Object(o) => {
let translate = o.get("translate").and_then(Value::as_str);
let text = o
.get("text")
.or_else(|| o.get("translate"))
.and_then(Value::as_str)
.or(translate)
.unwrap_or("")
.to_owned();
let translate = o.get("text").is_none() && translate.is_some();
let color = o.get("color").and_then(Value::as_str).and_then(|c| {
c.strip_prefix('#')
.and_then(|hex| u32::from_str_radix(hex, 16).ok())
.or_else(|| crate::text::named_color(c))
});
(text, color)
(text, color, translate)
}
_ => (String::new(), None),
_ => (String::new(), None, false),
}
}
/// The grid's stacks for one tab, search text and language.
@@ -912,6 +916,16 @@ impl Creative {
let y = if tab.top { -28.0 } else { Self::HEIGHT - 4.0 };
(x, y)
}
/// `CreativeModeInventoryScreen.checkTabHovering`: the tab whose icon
/// rectangle, 3 pixels in from its 26x32 slot (`isHovering(x + 3, y + 3,
/// 21, 27)`), holds the cursor. The screen draws its display name.
pub fn hovered_tab(tabs: &[Tab], origin: (f32, f32), cursor: (f32, f32)) -> Option<usize> {
tabs.iter().position(|tab| {
let (x, y) = Self::tab_position(tab);
let (x, y) = (origin.0 + x + 3.0, origin.1 + y + 3.0);
cursor.0 >= x && cursor.0 < x + 21.0 && cursor.1 >= y && cursor.1 < y + 27.0
})
}
/// `CreativeModeInventoryScreen.extractTabButton`'s cursor: an unselected
/// tab asks for the pointing hand when the whole-pixel mouse, relative to
/// the screen origin, is strictly inside its 26x32 button.
@@ -1789,4 +1803,21 @@ mod tests {
assert!(c.tab_headers().is_empty());
assert_eq!(c.search_tab(), None);
}
/// `CreativeModeInventoryScreen.checkTabHovering`: the 3-pixel inset of a
/// tab's 26x32 slot (21x27) is the hover area whose name the screen shows.
#[test]
fn only_a_tabs_inset_icon_is_hovered() {
let screen = tooltip_tabs();
let tab = &screen.tabs[0];
let (x, y) = Creative::tab_position(tab);
let at =
|dx: f32, dy: f32| Creative::hovered_tab(&screen.tabs, (0.0, 0.0), (x + dx, y + dy));
assert_eq!(at(4.0, 4.0), Some(0));
assert_eq!(at(23.5, 4.0), Some(0));
assert_eq!(at(2.0, 4.0), None);
assert_eq!(at(24.0, 4.0), None);
assert_eq!(at(4.0, 2.0), None);
assert_eq!(at(4.0, 30.0), None);
}
}
+23
View File
@@ -137,6 +137,15 @@ pub struct DebugKeys {
}
impl DebugKeys {
/// Window focus lost, or input reset: clear held modifier state.
pub fn reset(&mut self) {
self.modifier_down = false;
self.used_debug_key_as_modifier = false;
if self.crash_key_time > 0 {
self.crash_key_time = -1;
}
}
/// `keyPress` once the open screen (if any) did not take the key. `key`
/// is the physical key's name (`key.keyboard.f3`); `crash_key_down`
/// whether the crash mapping's key is held (`InputConstants.isKeyDown`).
@@ -487,4 +496,18 @@ mod tests {
press(&mut k, &mut h, &b, "key.keyboard.k", 2);
assert_eq!(h.actions, [(DebugAction::ShowChunkBorders, false)]);
}
#[test]
fn reset_on_focus_loss_clears_held_modifier_and_avoids_spurious_shortcuts() {
let (mut k, mut h, b) = (DebugKeys::default(), Host::default(), KeyBinds::default());
press(&mut k, &mut h, &b, F3, 0);
assert!(k.modifier_down);
// Window loses focus while F3 was down (e.g. desktop shortcut Ctrl+F3)
k.reset();
assert!(!k.modifier_down);
assert!(!k.used_debug_key_as_modifier);
// User refocuses and presses 'b': it should NOT trigger ShowHitboxes
assert!(press(&mut k, &mut h, &b, "key.keyboard.b", 1));
assert!(h.actions.is_empty());
}
}
+105 -11
View File
@@ -8,28 +8,51 @@ use crate::{
text::{Style, Text},
};
/// `ActiveTextCollector.ClickableStyleFinder.accept`: the style under a drawn
/// message glyph, using the same visual order and advances as rendering.
/// `ActiveTextCollector.ClickableStyleFinder.accept`: the last style `wanted`
/// under the cursor, in the same visual order and advances as rendering.
/// A drawn glyph is hit where it is drawn (`BakedSheetGlyph.GlyphInstance`),
/// even far below the line when its font's `ascent` moves it; an empty one
/// covers the line's 9 pixels (`EmptyArea`).
pub fn line_style_at(
font: &Font,
text: &Text,
x: f32,
y: f32,
cursor: (f32, f32),
wanted: impl Fn(&Style) -> bool,
) -> Option<Style> {
let mut left = cursor.0 - x;
if left < 0.0 || !(0.0..9.0).contains(&(cursor.1 - y)) {
return None;
}
let text = text.resolve_legacy();
let visual = crate::bidi::visual(&text);
let mut pen = x;
let mut found = None;
for (c, style) in visual.chars() {
left -= font.advance(c, style);
if left < 0.0 {
return Some(style.clone());
let advance = font.advance(c, style);
let object = c == '\u{fffc}' && style.inline_object.is_some();
let glyph = (!object).then(|| font.glyph_styled(c, style));
let (left, top, bottom) = match glyph {
Some(g) if g.rect.is_some() => {
let thick = if style.is_bold() { 0.1 } else { 0.0 };
let shear = if style.is_italic() {
1.0 - 0.25 * g.bottom
} else {
0.0
};
// Dialog text is drawn with a shadow, which extends the bottom.
(
pen + g.left + shear - thick,
y + g.top - thick,
y + g.bottom + g.offset + thick,
)
}
_ => (pen, y, y + 9.0),
};
let inside = (left..pen + advance).contains(&cursor.0) && (top..bottom).contains(&cursor.1);
if inside && wanted(style) {
found = Some(style.clone());
}
pen += advance;
}
None
found
}
/// `HeaderAndFooterLayout.DEFAULT_HEADER_AND_FOOTER_HEIGHT`.
@@ -485,7 +508,7 @@ mod tests {
]),
&mut |_| Text::empty(),
);
let style = |x, y| line_style_at(&font, &text, 10.0, 20.0, (x, y));
let style = |x, y| line_style_at(&font, &text, 10.0, 20.0, (x, y), |_| true);
assert!(style(9.9, 20.0).is_none());
assert_eq!(style(17.9, 20.0).unwrap().click, None);
for x in [18.0, 21.0, 25.9] {
@@ -503,6 +526,77 @@ mod tests {
assert!(style(21.0, 29.0).is_none());
}
#[test]
fn a_glyph_moved_down_by_its_ascent_is_clicked_where_it_is_drawn() {
use crate::{component, hud::Rect, text::ClickEvent};
let root =
std::env::temp_dir().join(format!("horizon-dialog-ascent-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let mut sheet = Vec::new();
{
let mut encoder = png::Encoder::new(&mut sheet, 8, 8);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(&[255; 8 * 8 * 4])
.unwrap();
}
for (path, bytes) in [
(
"assets/minecraft/font/low.json",
br#"{"providers":[{"type":"bitmap","file":"minecraft:font/box.png","height":8,"ascent":-28,"chars":["a"]}]}"#
.as_slice(),
),
("assets/minecraft/textures/font/box.png", sheet.as_slice()),
] {
let path = root.join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, bytes).unwrap();
}
let font = Font::load(
&root,
&std::collections::HashMap::new(),
&[],
(4096, 1024),
(512, 512),
Rect {
u0: 0.0,
v0: 0.0,
u1: 0.0,
v1: 0.0,
w: 1,
h: 1,
},
);
let _ = std::fs::remove_dir_all(&root);
let text = component::to_text(
&serde_json::json!([
{"text": "a", "font": "minecraft:low"},
{"text": "a", "font": "minecraft:low", "click_event": {
"action": "custom", "id": "test:requests"
}},
]),
&mut |_| Text::empty(),
);
let click = |x, y| {
line_style_at(&font, &text, 10.0, 20.0, (x, y), |s| s.click.is_some())
.and_then(|s| s.click)
};
let requests = Some(ClickEvent::Custom {
id: "test:requests".into(),
payload: None,
});
for (x, y) in [(19.0, 55.0), (22.0, 60.0), (27.9, 63.9)] {
assert_eq!(click(x, y), requests, "drawn 35 below the line at {x}, {y}");
}
assert_eq!(click(22.0, 24.0), None, "the line's own row holds nothing");
assert_eq!(click(22.0, 54.9), None, "above the glyph");
assert_eq!(click(22.0, 65.0), None, "below the glyph and its shadow");
assert_eq!(click(15.0, 60.0), None, "the plain glyph left of it");
}
#[test]
fn grids_pack_full_rows_and_centre_the_rest() {
// AuthMe's two buttons: one row, 2 apart.
+2 -104
View File
@@ -84,7 +84,9 @@ fn slime_at(world: &World, facts: &BlockFacts, position: BlockPos) -> bool {
mod fluids;
mod item_fall;
mod item_no_physics;
mod obstacles;
pub use fluids::{fall_reset_hit, fluid_flow, update_entity_fluids, water_clip};
pub use obstacles::ObstacleGrid;
#[cfg(test)]
mod drop_motion_tests {
@@ -1111,110 +1113,6 @@ fn lava_cauldron_contacts(
}
contacts
}
/// The boxes that stop a dropped item (boats, minecarts, shulkers, a held-still happy ghast),
/// binned by 8-block cell, so an item looks only at the ones near it: a farm with many drops and
/// many vehicles checks a handful of boxes per item, not every box in the level.
#[derive(Default)]
pub struct ObstacleGrid {
cells: crate::fast_hash::FxHashMap<(i32, i32, i32), Vec<u32>>,
boxes: Vec<Aabb>,
/// Each box's entity's `getRootVehicle` when it rides something; empty
/// when none was given.
roots: Vec<Option<u32>>,
found: Vec<u32>,
}
impl ObstacleGrid {
const CELL: f64 = 8.0;
pub fn new(boxes: Vec<Aabb>) -> Self {
Self::with_roots(boxes, Vec::new())
}
/// [`Self::new`] with the vehicle at the bottom of what each box's entity
/// rides (`roots[i]` for `boxes[i]`), so [`Self::near_except`] can leave a
/// mover's own riders out.
pub fn with_roots(boxes: Vec<Aabb>, roots: Vec<Option<u32>>) -> Self {
let mut cells: crate::fast_hash::FxHashMap<(i32, i32, i32), Vec<u32>> = Default::default();
for (i, b) in boxes.iter().enumerate() {
let (lo, hi) = Self::span(*b);
for x in lo.0..=hi.0 {
for y in lo.1..=hi.1 {
for z in lo.2..=hi.2 {
cells.entry((x, y, z)).or_default().push(i as u32);
}
}
}
}
Self {
cells,
boxes,
roots,
found: Vec::new(),
}
}
fn span(b: Aabb) -> ((i32, i32, i32), (i32, i32, i32)) {
let cell = |v: Vec3| {
(
(v.x / Self::CELL).floor() as i32,
(v.y / Self::CELL).floor() as i32,
(v.z / Self::CELL).floor() as i32,
)
};
(cell(b.min_position()), cell(b.max_position()))
}
pub fn is_empty(&self) -> bool {
self.boxes.is_empty()
}
/// The boxes meeting `area` (`getEntityCollisions`'s query box), in the order they were given.
pub fn near(&mut self, area: Aabb, out: &mut Vec<Aabb>) {
self.near_except(area, None, out);
}
/// [`Self::near`] without the boxes of what rides `vehicle` (given with
/// [`Self::with_roots`]): `Entity.canCollideWith` leaves out
/// `isPassengerOfSameVehicle`, so a stand's riders do not stop it.
pub fn near_except(&mut self, area: Aabb, vehicle: Option<u32>, out: &mut Vec<Aabb>) {
out.clear();
if self.boxes.is_empty() {
return;
}
let kept = |i: usize| vehicle.is_none() || self.roots.get(i).copied().flatten() != vehicle;
let (lo, hi) = Self::span(area);
let side = |lo: i32, hi: i32| (i64::from(hi) - i64::from(lo) + 1).max(0);
let cells = side(lo.0, hi.0)
.saturating_mul(side(lo.1, hi.1))
.saturating_mul(side(lo.2, hi.2));
// An area over more cells than there are boxes (a stand loaded with a
// huge Motion asks for one millions of blocks long): test each box
// once rather than walk the cells.
if cells > self.boxes.len() as i64 {
out.extend(
self.boxes
.iter()
.enumerate()
.filter(|&(i, b)| kept(i) && b.intersects(area))
.map(|(_, b)| *b),
);
return;
}
self.found.clear();
for x in lo.0..=hi.0 {
for y in lo.1..=hi.1 {
for z in lo.2..=hi.2 {
if let Some(list) = self.cells.get(&(x, y, z)) {
self.found.extend(list);
}
}
}
}
self.found.sort_unstable();
self.found.dedup();
for &i in &self.found {
let b = self.boxes[i as usize];
if kept(i as usize) && b.intersects(area) {
out.push(b);
}
}
}
}
/// Dropped items by block cell, for `ItemEntity.mergeWithNeighbours`'s
/// search around an item. Holds indexes into the tick's item list.
#[derive(Default)]
@@ -0,0 +1,122 @@
//! The boxes that stop a dropped item, by cell (`ObstacleGrid`).
use crate::fast_hash::FxHashMap;
use horizon_core::geometry::{Aabb, Vec3};
/// The boxes that stop a dropped item (boats, minecarts, shulkers, a held-still happy ghast),
/// binned by 8-block cell, so an item looks only at the ones near it: a farm with many drops and
/// many vehicles checks a handful of boxes per item, not every box in the level.
#[derive(Default)]
pub struct ObstacleGrid {
cells: FxHashMap<(i32, i32, i32), Vec<u32>>,
boxes: Vec<Aabb>,
/// Each box's entity's `getRootVehicle` when it rides something; empty
/// when none was given.
roots: Vec<Option<u32>>,
found: Vec<u32>,
}
impl ObstacleGrid {
const CELL: f64 = 8.0;
pub fn new(boxes: Vec<Aabb>) -> Self {
Self::with_roots(boxes, Vec::new())
}
/// [`Self::new`] with the vehicle at the bottom of what each box's entity
/// rides (`roots[i]` for `boxes[i]`), so [`Self::near_except`] can leave a
/// mover's own riders out.
pub fn with_roots(boxes: Vec<Aabb>, roots: Vec<Option<u32>>) -> Self {
let mut cells: FxHashMap<(i32, i32, i32), Vec<u32>> = Default::default();
for (i, b) in boxes.iter().enumerate() {
let (lo, hi) = Self::span(*b);
for x in lo.0..=hi.0 {
for y in lo.1..=hi.1 {
for z in lo.2..=hi.2 {
cells.entry((x, y, z)).or_default().push(i as u32);
}
}
}
}
Self {
cells,
boxes,
roots,
found: Vec::new(),
}
}
fn span(b: Aabb) -> ((i32, i32, i32), (i32, i32, i32)) {
let cell = |v: Vec3| {
(
(v.x / Self::CELL).floor() as i32,
(v.y / Self::CELL).floor() as i32,
(v.z / Self::CELL).floor() as i32,
)
};
(cell(b.min_position()), cell(b.max_position()))
}
pub fn is_empty(&self) -> bool {
self.boxes.is_empty()
}
/// The boxes meeting `area` (`getEntityCollisions`'s query box), in the order they were given.
pub fn near(&mut self, area: Aabb, out: &mut Vec<Aabb>) {
self.near_except(area, None, out);
}
/// [`Self::near`] without the boxes of what rides `vehicle` (given with
/// [`Self::with_roots`]): `Entity.canCollideWith` leaves out
/// `isPassengerOfSameVehicle`, so a stand's riders do not stop it.
pub fn near_except(&mut self, area: Aabb, vehicle: Option<u32>, out: &mut Vec<Aabb>) {
let mut found = std::mem::take(&mut self.found);
self.near_with(area, vehicle, &mut found, out);
self.found = found;
}
/// [`Self::near`] with the caller's scratch, so several threads can ask one grid.
pub fn near_shared(&self, area: Aabb, found: &mut Vec<u32>, out: &mut Vec<Aabb>) {
self.near_with(area, None, found, out);
}
fn near_with(
&self,
area: Aabb,
vehicle: Option<u32>,
found: &mut Vec<u32>,
out: &mut Vec<Aabb>,
) {
out.clear();
if self.boxes.is_empty() {
return;
}
let kept = |i: usize| vehicle.is_none() || self.roots.get(i).copied().flatten() != vehicle;
let (lo, hi) = Self::span(area);
let side = |lo: i32, hi: i32| (i64::from(hi) - i64::from(lo) + 1).max(0);
let cells = side(lo.0, hi.0)
.saturating_mul(side(lo.1, hi.1))
.saturating_mul(side(lo.2, hi.2));
// An area over more cells than there are boxes (a stand loaded with a
// huge Motion asks for one millions of blocks long): test each box
// once rather than walk the cells.
if cells > self.boxes.len() as i64 {
out.extend(
self.boxes
.iter()
.enumerate()
.filter(|&(i, b)| kept(i) && b.intersects(area))
.map(|(_, b)| *b),
);
return;
}
found.clear();
for x in lo.0..=hi.0 {
for y in lo.1..=hi.1 {
for z in lo.2..=hi.2 {
if let Some(list) = self.cells.get(&(x, y, z)) {
found.extend(list);
}
}
}
}
found.sort_unstable();
found.dedup();
for &i in found.iter() {
let b = self.boxes[i as usize];
if kept(i as usize) && b.intersects(area) {
out.push(b);
}
}
}
}
+10
View File
@@ -28,6 +28,8 @@ pub fn main_with(mods: crate::mod_api::Mods) {
// then the Horizon parts still in this crate; none registers after this point.
game::player_hooks::register();
horizon_hooks::engine::seal();
// The text crates ship (`horizon_hooks::lang`), loaded with the game's own languages.
horizon_client::lang::install_crate_files(horizon_hooks::lang::engine::all());
horizon_client::spans::startup::init(std::time::Instant::now());
horizon_client::spans::trace::start_from_env();
let args: Vec<String> = std::env::args().skip(1).collect();
@@ -230,6 +232,14 @@ pub fn main_with(mods: crate::mod_api::Mods) {
living_jump: |entity, kind| {
crate::mod_api::dispatch_living_jump(crate::mod_api::mods(), entity, kind);
},
living_death_message: |entity, kind, message| {
crate::mod_api::dispatch_living_death_message(
crate::mod_api::mods(),
entity,
kind,
message,
);
},
register_goals: |mob| {
crate::mod_api::dispatch_register_goals(crate::mod_api::mods(), mob);
},
+2 -1
View File
@@ -166,7 +166,8 @@ impl FurnaceCooking for Furnace {
self.cooking_timer = 0;
}
} else if self.cooking_timer > 0 {
self.cooking_timer = (self.cooking_timer - 2).clamp(0, self.cooking_total);
// Vanilla Mth.clamp is min(max(v, 0), max): saturates at a negative total instead of panicking.
self.cooking_timer = (self.cooking_timer - 2).max(0).min(self.cooking_total);
}
(was_lit != lit).then_some(lit)
}
+25 -43
View File
@@ -1505,7 +1505,7 @@ impl LevelAccess for GameLevel<'_> {
{
return signal;
}
machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos)
machines::container_signal(self, pos)
}
fn item_frame_analog_output(&self, pos: BlockPos, facing: Direction) -> Option<i32> {
let mut frames = self
@@ -1524,14 +1524,14 @@ impl LevelAccess for GameLevel<'_> {
fn block_entity_signal(
&self,
pos: BlockPos,
_state: BlockStateId,
state: BlockStateId,
_direction: Direction,
) -> i32 {
// TestBlock.ownSignal.
// TestBlock.ownSignal: the block state's mode gates the entity.
if let Some(BlockEntity::TestBlock(b)) =
self.world.block_entities.get(&(pos.x, pos.y, pos.z))
{
return b.own_signal();
return crate::game::test_blocks::own_signal(self.registry, state, b.powered);
}
// TrappedChestBlock.getSignal: the players with it open, at most 15.
if let Some(count) = self.lid_openers.get(&(pos.x, pos.y, pos.z)) {
@@ -2328,6 +2328,8 @@ struct Game<'a> {
last_device_recovery: Option<Instant>,
/// CPU geometry storage retained across frames, including empty/title frames.
entity_vertices: Vec<Vertex>,
/// Falling models by state and selected-model address list; cleared on pack/atlas replacement.
falling_vertices: RefCell<HashMap<BlockStateId, Vec<(Vec<usize>, Vec<Vertex>)>>>,
/// Horizon Extras' dynamic lights this frame (`dynamic_lights.rs`), and how brightly each
/// item glows (built the first time the extra is on).
dynamic_lights: Vec<[f32; 4]>,
@@ -2873,9 +2875,9 @@ struct Game<'a> {
water_plane_memo: std::cell::Cell<Option<f32>>,
/// The camera's block and the second `water_plane` last scanned at.
water_plane_scan: std::cell::Cell<Option<([i32; 3], i64)>>,
/// The mobs' box reach while the boats and minecarts tick, with the mob count it was
/// worked out for (`vehicle_mob_reach`).
vehicle_mob_reach: std::cell::Cell<Option<(usize, horizon_client::mobs::BoxReach)>>,
/// What the boats' and minecarts' ticks know about the mobs: their box reach
/// (`vehicle_mob_reach`) and a grid of their boxes (`mobs_meeting`).
vehicle_mobs: boat_passengers::VehicleMobs,
persist: persist::EntityMemory,
entity_attachments: HashMap<[i32; 4], horizon_world::attachments::Attachments>,
/// Connected to a server: the world comes from the network (game/remote.rs).
@@ -5033,8 +5035,8 @@ impl Game<'_> {
self.loot_block_entity(pos, &facts.name)
};
if let Some(entity) = self.world.block_entities.get(&key).cloned() {
let name = self.world.block_names.get(&key).cloned();
self.pending.record(pos, &entity, &facts.name, name);
self.pending
.record_from(&self.world, pos, &entity, &facts.name);
} else if let Some(tag) = spill::saved_entity(&self.world, pos) {
self.pending.record_saved(pos, &tag);
}
@@ -7158,14 +7160,7 @@ impl Game<'_> {
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let start = out.len();
self.mark_motion(start, Self::MOTION_OBJECT | u64::from(f.id));
self.block_model_vertices(
f.state,
horizon_core::random::position_seed(f.start_pos),
glam::Mat4::from_translation(o),
packed,
false,
&mut out,
);
self.falling_model_vertices(f.state, f.start_pos, o, packed, &mut out);
let tint = horizon_client::mobs::render::abgr(tint);
for vertex in &mut out[start..] {
vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint);
@@ -8211,10 +8206,7 @@ impl Game<'_> {
}
if let Some(kind) = mob {
if let Some(id) = self.spawn_mob_at(kind, (target[0], target[1], target[2]), true) {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
horizon_client::entity_nbt::apply_item_components(m, stack);
}
self.mob_placed(id)?;
self.mob_placed(id, stack)?;
}
self.post_block_game_event(
"minecraft:entity_place",
@@ -9972,20 +9964,10 @@ impl Game<'_> {
self.drag_button = None;
}
if let WindowEvent::ModifiersChanged(m) = &event {
self.modifiers = m.state();
horizon_client_input::modifiers::reconcile(
self.modifiers,
&mut self.physical_keys,
&self.settings.keys,
&mut self.toggles,
[self.settings.toggle_crouch, self.settings.toggle_sprint],
[
self.pad.holds_action("key.sneak"),
self.pad.holds_action("key.sprint"),
],
);
self.sync_toggle(SNEAK);
self.sync_toggle(SPRINT);
self.update_modifiers(m.state());
}
if let WindowEvent::Focused(false) = &event {
self.update_modifiers(winit::keyboard::ModifiersState::empty());
}
// `PackSelectionScreen.onFilesDrop` on the Create New World screen.
if let WindowEvent::DroppedFile(path) = &event
@@ -10391,6 +10373,8 @@ impl Game<'_> {
let held = self.captured;
if self.control.is_none() {
self.keys.clear();
self.modifiers = winit::keyboard::ModifiersState::empty();
self.debug_keys.reset();
// Latched sneak/sprint live in `toggles`, not in the
// physical keys: put them back so a short alt-tab
// (no pause screen) does not drop them. Only a mapping
@@ -10398,21 +10382,18 @@ impl Game<'_> {
// no state to keep, and an unfocused window never gets
// its key release, so leaving it down would keep the
// player sneaking or sprinting until the key is tapped.
for (slot, needs_toggle) in [
let toggles = [
self.settings.toggle_crouch,
self.settings.toggle_sprint,
self.settings.toggle_attack,
self.settings.toggle_use,
]
.into_iter()
.enumerate()
{
];
for (slot, needs_toggle) in toggles.into_iter().enumerate() {
self.toggles.0[slot].set_down(false, needs_toggle);
}
self.sync_toggle(0);
self.sync_toggle(1);
self.left = false;
self.right = false;
(self.left, self.right) = (false, false);
self.capture(false);
}
self.regrab_on_refocus = held;
@@ -11685,6 +11666,7 @@ impl<'a> Game<'a> {
renderer: None,
last_device_recovery: None,
entity_vertices: Vec::new(),
falling_vertices: Default::default(),
dynamic_lights: Vec::new(),
luminance: Default::default(),
see_through_vertices: Vec::new(),
@@ -11992,7 +11974,7 @@ impl<'a> Game<'a> {
sky_darken_memo: Default::default(),
water_plane_memo: Default::default(),
water_plane_scan: Default::default(),
vehicle_mob_reach: Default::default(),
vehicle_mobs: Default::default(),
persist: Default::default(),
entity_attachments: Default::default(),
remote: None,
+5 -10
View File
@@ -230,15 +230,10 @@ impl adv::World for View<'_, '_> {
_ => None,
}
}
/// `Level.canSeeSky`: sky light 15 at the position, whatever stands
/// above it, as `MobWorld` reads it for the spawn rules.
fn can_see_sky(&self, p: [i32; 3]) -> bool {
(p[1] + 1..p[1] + 200).all(|y| {
!self
.0
.res
.facts()
.get(self.0.world.block(p[0], y, p[2]))
.full_collision
})
self.0.mob_world_base(&[]).can_see_sky(p[0], p[1], p[2])
}
fn light(&self, p: [i32; 3]) -> i32 {
let l = self.0.world.light(p[0], p[1], p[2]);
@@ -1255,7 +1250,7 @@ impl Game<'_> {
}
self.check_inventory_trigger();
// ServerPlayer.tick: PlayerTrigger.TICK every tick.
let me = self.player_entity_for("minecraft:tick");
let me = self.player_entity_if_listened("minecraft:tick");
self.trigger("minecraft:tick", |c, w| {
let ctx = adv::Entities {
this: Some(&me),
@@ -1289,7 +1284,7 @@ impl Game<'_> {
}
self.tick_marks();
if self.ticks.is_multiple_of(20) {
let me = self.player_entity_for("minecraft:location");
let me = self.player_entity_if_listened("minecraft:location");
self.trigger("minecraft:location", |c, w| {
let ctx = adv::Entities {
this: Some(&me),
@@ -0,0 +1,158 @@
//! An allay dances to the jukebox it heard first: `Allay.setJukeboxPlaying`
//! keeps that jukebox's position while it dances, and only a stop from there
//! ends the dance; another jukebox's `jukebox_play` (every 20 ticks of its
//! song) starts it again (tools/test_allay_jukebox_source_parity.py measures
//! the same on vanilla 26.3).
use crate::game::*;
use horizon_client::chunk::Chunk;
use horizon_core::position::ChunkPos;
use std::sync::Arc;
fn game() -> Game<'static> {
let root = std::path::PathBuf::from(
std::env::var_os("HORIZON_TEST_RESOURCES")
.expect("set HORIZON_TEST_RESOURCES to prepared resources"),
);
let settings = Settings::default();
let loaded = load_resources(
root.clone(),
None,
&root,
&settings,
std::time::Instant::now(),
false,
true,
&Progress::new(),
&mut |_, _| unreachable!(),
)
.unwrap();
let mut options = Options::parse(std::iter::empty()).unwrap().unwrap();
options.resources = root.clone();
options.execution_role = execution_role::ExecutionRole::IntegratedServer;
let res: &'static _ = Box::leak(Box::new(loaded.resources));
let mut game = Game::new(
res,
loaded.pack,
loaded.gui.unwrap(),
options,
settings,
Audio::silent(&root),
None,
)
.unwrap();
game.build_registries();
game.set_allow_commands(true);
game.world
.chunks
.insert((0, 0), Arc::new(Chunk::empty(0, 0)));
game.block_ticks
.add_empty_chunk(ChunkPos::new(0, 0))
.unwrap();
for command in [
"tick freeze",
"forceload add 0 0",
"fill 0 99 0 15 99 15 stone",
"fill 7 99 7 9 102 9 glass",
"fill 8 100 8 8 101 8 air",
"setblock 5 100 8 jukebox",
"setblock 12 100 8 jukebox",
"summon allay 8.5 100 8.5 {PersistenceRequired:1b,UUID:[I;2577,0,0,1]}",
] {
assert!(game.run_command(command), "{command}");
}
step(&mut game, 12);
game
}
fn step(game: &mut Game<'_>, ticks: usize) {
for _ in 0..ticks {
assert!(game.run_command("tick step 1"));
game.tick_server(false).unwrap();
}
}
fn dancing(game: &Game<'_>) -> bool {
game.mobs
.iter()
.find(|m| m.species() == horizon_client::mobs::Species::Allay)
.expect("the allay")
.extra
.flag
}
fn play(game: &mut Game<'_>, x: i32, item: &str) {
assert!(game.run_command(&format!(
"item replace block {x} 100 8 container.0 with {item}"
)));
}
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn stopping_the_first_jukebox_stops_the_dance_until_the_other_plays_again() {
let mut game = game();
assert!(!dancing(&game));
play(&mut game, 5, "minecraft:music_disc_cat");
step(&mut game, 5);
assert!(dancing(&game), "jukebox A starts the dance");
play(&mut game, 12, "minecraft:music_disc_cat");
step(&mut game, 25);
assert!(dancing(&game));
// B has played for 25 ticks: its next jukebox_play is 15 ticks away.
play(&mut game, 5, "minecraft:air");
step(&mut game, 1);
assert!(
!dancing(&game),
"the stop of A, the dance's jukebox, ends it though B still plays"
);
step(&mut game, 20);
assert!(dancing(&game), "B's next jukebox_play starts it again");
}
// Controls added after the baseline: the source through an in-place load, a
// NoAI allay, and the out-of-reach check of `aiStep`.
const ALLAY: &str = "00000a11-0000-0000-0000-000000000001";
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn control_data_merge_keeps_the_dance_and_its_jukebox() {
let mut game = game();
play(&mut game, 5, "minecraft:music_disc_cat");
step(&mut game, 5);
play(&mut game, 12, "minecraft:music_disc_cat");
step(&mut game, 5);
assert!(game.run_command(&format!("data merge entity {ALLAY} {{CustomName:\"x\"}}")));
step(&mut game, 1);
assert!(dancing(&game), "Entity.load keeps DATA_DANCING");
// The kept jukebox is still A: B's stop does not end the dance, A's does.
play(&mut game, 12, "minecraft:air");
step(&mut game, 1);
assert!(dancing(&game));
play(&mut game, 5, "minecraft:air");
step(&mut game, 1);
assert!(!dancing(&game));
}
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn control_a_no_ai_allay_never_dances() {
let mut game = game();
assert!(game.run_command(&format!("data merge entity {ALLAY} {{NoAI:1b}}")));
play(&mut game, 5, "minecraft:music_disc_cat");
step(&mut game, 25);
assert!(!dancing(&game));
}
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn control_an_allay_out_of_reach_stops_on_a_twentieth_tick() {
let mut game = game();
play(&mut game, 5, "minecraft:music_disc_cat");
step(&mut game, 2);
assert!(dancing(&game));
assert!(game.run_command("fill 7 99 7 9 102 9 air"));
assert!(game.run_command(&format!("tp {ALLAY} 5.5 112 8.5")));
// Farther than 10 blocks from A's centre: stopped by the next tickCount % 20.
step(&mut game, 20);
assert!(!dancing(&game));
}
+6 -24
View File
@@ -3,7 +3,6 @@
//! and the hand-over interaction (`Allay.mobInteract`).
use super::Game;
use horizon_client::{
containers::BlockEntity,
first_person::Hand,
items::ItemStack,
mobs::{Species, allay},
@@ -74,9 +73,6 @@ impl Game<'_> {
pub(super) fn tick_allays(&mut self) {
let griefing = self.ui.rules.bool("mob_griefing");
// The playing jukeboxes, found at the first allay: no allay starts
// or stops one, and the block entities run into the thousands.
let mut jukeboxes: Option<Vec<(i32, i32, i32)>> = None;
for i in 0..self.mobs.len() {
if self.mobs[i].species() != Species::Allay
|| !self.mobs[i].alive()
@@ -85,26 +81,8 @@ impl Game<'_> {
continue;
}
let pos = self.mobs[i].position;
// Dancing: a playing jukebox within 10 blocks.
let jukeboxes = jukeboxes.get_or_insert_with(|| {
self.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Jukebox(j) if j.playing))
.map(|(k, _)| *k)
.collect()
});
let nearest = jukeboxes
.iter()
.map(|k| {
(f64::from(k.0) + 0.5 - pos.x).powi(2)
+ (f64::from(k.1) + 0.5 - pos.y).powi(2)
+ (f64::from(k.2) + 0.5 - pos.z).powi(2)
})
.fold(f64::INFINITY, f64::min);
// `Allay.setDancing` wants effective AI: a `NoAI` allay never dances.
let panicking = horizon_client::mobs::goals::should_panic(&self.mobs[i]);
self.mobs[i].extra.flag = allay::dances(self.mobs[i].no_ai, panicking, nearest);
// The dance follows the jukebox events the allay hears
// (`mob_listen`), `Allay.tick` and `aiStep`.
let Some(held) = self.mobs[i].extra.main_hand_stack().cloned() else {
self.mobs[i].extra.point = None;
continue;
@@ -425,3 +403,7 @@ impl Game<'_> {
false
}
}
#[cfg(test)]
#[path = "allay_jukebox_source_tests.rs"]
mod allay_jukebox_source_tests;
@@ -153,7 +153,18 @@ impl Game<'_> {
.shulkers
.get_mut(&pos)
.map(|shulker| shulker.tick(pos, facing));
if let Some(push) = tick.and_then(|tick| tick.push) {
let Some(tick) = tick else { continue };
// `ShulkerBoxBlockEntity.doNeighborUpdates` at the start and the
// end of an opening or closing lid: the box's collision shape
// moved, so the neighbours' shapes and their redstone updates run.
for _ in 0..tick.neighbor_updates {
let state = self.world.block(pos[0], pos[1], pos[2]);
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| {
b.shulker_neighbor_updates(level, ticks, at, state)
});
}
if let Some(push) = tick.push {
pushes.push((pos, facing, push));
}
}
@@ -47,8 +47,9 @@ fn clone_item<'a>(name: &str, block_item: &'a str) -> &'a str {
"minecraft:kelp_plant" => "minecraft:kelp",
"minecraft:twisting_vines_plant" => "minecraft:twisting_vines",
"minecraft:weeping_vines_plant" => "minecraft:weeping_vines",
// CandleCakeBlock: new ItemStack(Blocks.CAKE), for every colour.
_ if name.ends_with("_candle_cake") => "minecraft:cake",
// CandleCakeBlock: new ItemStack(Blocks.CAKE), for every colour and
// the plain `minecraft:candle_cake`, whose own item is air.
_ if name == "minecraft:candle_cake" || name.ends_with("_candle_cake") => "minecraft:cake",
_ => block_item,
}
}
@@ -424,6 +425,7 @@ mod tests {
("minecraft:kelp_plant", "minecraft:kelp"),
("minecraft:twisting_vines_plant", "minecraft:twisting_vines"),
("minecraft:weeping_vines_plant", "minecraft:weeping_vines"),
("minecraft:candle_cake", "minecraft:cake"),
("minecraft:white_candle_cake", "minecraft:cake"),
("minecraft:light_blue_candle_cake", "minecraft:cake"),
] {
@@ -239,6 +239,19 @@ impl Game<'_> {
self.tick_scheduled()?;
}
self.with_level(|b, level, ticks| {
// The masks the random ticks will read, built on helper threads first while the
// parallel tick is on (`HORIZON_PARALLEL_TICK`): the draws and ticks don't depend on them.
if !debug && horizon_client::parallel::lanes() > 1 {
horizon_client::spans::time("random_tick_masks", || {
let chunks = &level.world.chunks;
level.random_tick_sections.prepare_masks(
&scratch.ticking,
|key| chunks.get(&key).cloned(),
level.facts,
&|id| b.random_tick_candidate(BlockStateId(id)),
);
});
}
horizon_client::spans::time("random_ticks", || {
for (x, z) in scratch.ticking.drain(..).filter(|_| !debug) {
// The last answer, asked from Y `from` at a world revision:
+313 -42
View File
@@ -7,10 +7,13 @@
use super::{Game, boats::Boat, lan_mobs::guest_bounds};
use horizon_client::{
camera::wrap_degrees,
mobs::{BoxReach, Mob, Species, Who, drops::is_animal, equine, riders},
fast_hash::FxHashMap,
join_seq::ListStamp,
mobs::{BoxReach, Mob, Species, Who, drops::is_animal, equine, riders, seen_grid::SeenGrid},
scoreboard::pushable_by,
};
use horizon_core::geometry::{Aabb, Vec3};
use std::cell::{Cell, RefCell};
/// `Entity.boardingCooldown` once a mob leaves its boat.
pub(super) const BOARDING_COOLDOWN: i32 = 60;
@@ -18,6 +21,35 @@ pub(super) const BOARDING_COOLDOWN: i32 = 60;
/// feet are.
const PLAYER_RIDING_OFFSET: f64 = 0.6;
/// How many box queries the walk over every mob answers, once a write to the mob list has
/// made the grid stale, before a new grid is built: about what building one costs (with
/// 25,000 mobs, six to eight walks). It doubles with each grid of a stretch, so vehicles
/// that each write a mob (a boat pushing the pig beside it) never pay more for grids than
/// for their walks.
const WALKS_BEFORE_GRID: u32 = 8;
/// What a stretch of vehicle ticks knows about the mobs, so a boat or a minecart reads the
/// mobs near it and not every mob of the level ([`Game::mobs_meeting`]).
#[derive(Default)]
pub(super) struct VehicleMobs {
/// The mobs' [`BoxReach`] with the mob count it was worked out for; None outside a stretch.
reach: Cell<Option<(usize, BoxReach)>>,
grid: RefCell<MobGrid>,
/// The last query's candidates, kept for their allocation.
near: Cell<Vec<u32>>,
/// Each ridden vehicle's mobs by slot, for the mob list as it stood ([`Game::vehicle_riders`]).
riders: RefCell<Option<(ListStamp, FxHashMap<u32, Vec<usize>>)>>,
}
#[derive(Default)]
struct MobGrid {
/// The mobs' boxes by column and the list they were read from: they hold until that
/// list's next write ([`ListStamp`]), which every push, pick-up, death and join is.
built: Option<(ListStamp, SeenGrid)>,
/// The queries walked since the grid went stale, and how many are before the next grid.
walked: u32,
patience: u32,
}
/// `Entity.canRide` for a mob species: `Warden` and `WitherBoss` override it
/// to return false, so no vehicle ever takes them aboard.
pub(super) fn species_can_ride(species: Species) -> bool {
@@ -66,32 +98,165 @@ pub(super) fn boat_pushes(boat: Aabb, other: Aabb, other_is_boat: bool) -> bool
}
impl Game<'_> {
/// The players in boat `id`: the window's player (or the server player
/// acting as it) and the server's other players.
/// Starts or ends a stretch of vehicle ticks (`tick_boats`, `tick_carts`): while one runs,
/// a vehicle's box query tests the mobs' positions against their [`BoxReach`] first.
/// A mob joining or leaving works it out again, and so does [`Self::vehicle_picked_up`].
/// a vehicle's box query ([`Self::mobs_meeting`]) reads the mobs near it from a grid of
/// their boxes, or tests the mobs' positions against their [`BoxReach`] first. A mob
/// joining or leaving works the reach out again, and so does [`Self::vehicle_picked_up`].
/// The first query that needs one works it out (the reach's count is one no list has), so
/// a level without boats or carts never walks its mobs for them.
pub(super) fn vehicles_ticking(&self, on: bool) {
self.vehicle_mob_reach
.set(on.then(|| (self.mobs.len(), BoxReach::of(&self.mobs))));
let reach = on.then(|| (usize::MAX, BoxReach::default()));
self.vehicle_mobs.reach.set(reach);
// The boats' grid serves the carts ticking right after them; an older one goes.
let mut grid = self.vehicle_mobs.grid.borrow_mut();
let stamp = self.mobs.stamp();
let built = grid.built.take().filter(|(s, _)| *s == stamp);
*grid = MobGrid {
built,
..Default::default()
};
}
/// A vehicle picked a mob up: a shulker turns its lid up (`Shulker.startRiding`), which
/// changes its box, so the next query works the [`BoxReach`] out again.
pub(super) fn vehicle_picked_up(&self) {
if let Some((_, reach)) = self.vehicle_mob_reach.get() {
self.vehicle_mob_reach.set(Some((usize::MAX, reach)));
if let Some((_, reach)) = self.vehicle_mobs.reach.get() {
self.vehicle_mobs.reach.set(Some((usize::MAX, reach)));
}
}
/// The mobs' [`BoxReach`] while vehicles tick, none otherwise.
pub(super) fn vehicle_mob_reach(&self) -> Option<BoxReach> {
let (count, reach) = self.vehicle_mob_reach.get()?;
let (count, reach) = self.vehicle_mobs.reach.get()?;
if count == self.mobs.len() {
return Some(reach);
}
let reach = BoxReach::of(&self.mobs);
self.vehicle_mob_reach.set(Some((self.mobs.len(), reach)));
self.vehicle_mobs.reach.set(Some((self.mobs.len(), reach)));
Some(reach)
}
/// The slots, ascending, of the mobs whose vehicle is `id`, whatever their state. While
/// vehicles tick, one walk over the mobs answers for every vehicle until the mob list is
/// next written: each boat asks for its passengers and each cart on rails whether it is
/// ridden, and each one walked every mob of the level.
fn vehicle_riders(&self, id: u32) -> Vec<usize> {
let rides = |v: u32| move |&j: &usize| self.mobs[j].extra.mount == Some(v);
if !self.vehicle_mobs_indexed() {
return (0..self.mobs.len()).filter(rides(id)).collect();
}
let stamp = self.mobs.stamp();
let mut riders = self.vehicle_mobs.riders.borrow_mut();
if riders.as_ref().is_none_or(|(s, _)| *s != stamp) {
let mut by_vehicle = FxHashMap::<u32, Vec<usize>>::default();
for (j, m) in self.mobs.iter().enumerate() {
if let Some(v) = m.extra.mount {
by_vehicle.entry(v).or_default().push(j);
}
}
*riders = Some((stamp, by_vehicle));
}
let of = riders
.as_ref()
.and_then(|(_, by_vehicle)| by_vehicle.get(&id));
of.cloned().unwrap_or_default()
}
/// Whether a mob (one not removed) rides vehicle `id`: `Entity.isVehicle` for a cart.
pub(super) fn mob_rides(&self, id: u32) -> bool {
let riders = self.vehicle_riders(id);
riders.iter().any(|&j| !self.mobs[j].removed)
}
/// Whether what a stretch of vehicle ticks reads from the mob list may stand in for a walk
/// over it: a stretch runs, and no native mod is loaded (a hook can move a mob unseen, as
/// for the carts' `CartIndex`).
fn vehicle_mobs_indexed(&self) -> bool {
self.vehicle_mobs.reach.get().is_some() && horizon_client::mod_api::mods().is_empty()
}
/// The slots, ascending, of the mobs whose box may meet `area` into `out` (a superset: the
/// caller still tests each box), from a grid of the mobs' boxes that the first query of a
/// stretch of vehicle ticks builds. False: walk them all. That is outside a stretch or with
/// native mods loaded ([`Self::vehicle_mobs_indexed`]), when the grid cannot say, and for
/// a while after a write to the mob list ([`MobGrid`]).
fn vehicle_mobs_near(&self, area: Aabb, out: &mut Vec<u32>) -> bool {
if !self.vehicle_mobs_indexed() {
return false;
}
let stamp = self.mobs.stamp();
let mut grid = self.vehicle_mobs.grid.borrow_mut();
if grid.built.as_ref().is_none_or(|(s, _)| *s != stamp) {
if grid.walked < grid.patience {
grid.walked += 1;
return false;
}
grid.built = Some((stamp, SeenGrid::new(self.mobs.iter().map(Mob::bounds))));
grid.walked = 0;
grid.patience = (grid.patience * 2).max(WALKS_BEFORE_GRID);
}
let built = grid.built.as_ref();
built.is_some_and(|(_, cells)| cells.candidates(area, out))
}
/// A vehicle's box query: `each` gets every mob whose box meets `area`, in slot order,
/// with its slot and its box. While vehicles tick it reads the mobs near the area
/// ([`Self::vehicle_mobs_near`]) or, walking them all, tests each position against the
/// [`BoxReach`] before working the box out. The mobs and their order are those of a walk
/// that tests every box.
pub(super) fn mobs_meeting(&self, area: Aabb, mut each: impl FnMut(usize, &Mob, Aabb)) {
let mut near = self.vehicle_mobs.near.take();
if self.vehicle_mobs_near(area, &mut near) {
for &j in &near {
let m = &self.mobs[j as usize];
let b = m.bounds();
if b.intersects(area) {
each(j as usize, m, b);
}
}
} else {
let reach = self.vehicle_mob_reach();
for (j, m) in self.mobs.iter().enumerate() {
if reach.is_some_and(|r| !r.may_meet(m, area)) {
continue;
}
let b = m.bounds();
if b.intersects(area) {
each(j, m, b);
}
}
}
self.vehicle_mobs.near.set(near);
}
/// The slots, ascending, of the mobs whose box may meet a cart, read from the mobs' grid
/// once per cart. None when the mobs are the fewer (asking the carts' grid once per mob
/// is then the shorter way) or the grid does not answer.
pub(super) fn mobs_near_carts(&self) -> Option<Vec<u32>> {
if self.mobs.len() <= self.carts.len() {
return None;
}
let (mut slots, mut near) = (Vec::new(), Vec::new());
for c in self.carts.iter() {
if !self.vehicle_mobs_near(c.bounds(), &mut near) {
return None;
}
slots.extend_from_slice(&near);
}
slots.sort_unstable();
slots.dedup();
Some(slots)
}
/// Whether mob `m`, whose box `reach` bounds, may touch a cart: the carts' grid (`cells`)
/// names the carts near it, or every cart when the grid cannot (a superset either way).
pub(super) fn mob_may_meet_cart(
&self,
reach: BoxReach,
m: &Mob,
cells: &SeenGrid,
near: &mut Vec<u32>,
) -> bool {
if !cells.candidates(reach.around(m.position), near) {
near.clear();
near.extend(0..self.carts.len() as u32);
}
near.iter()
.any(|&k| reach.may_meet(m, self.carts[k as usize].bounds()))
}
/// The players in boat `id`: the window's player (or the server player
/// acting as it) and the server's other players.
pub(super) fn boat_players(&self, id: u32) -> usize {
let guests = self.lan.as_ref().map_or(0, |h| {
h.hub
@@ -105,12 +270,9 @@ impl Game<'_> {
/// The mobs in boat `id`, in their seat order after the players
/// (`Entity.addPassenger` puts a player first).
pub(super) fn boat_mobs(&self, id: u32) -> Vec<usize> {
(0..self.mobs.len())
.filter(|&j| {
let m = &self.mobs[j];
m.extra.mount == Some(id) && !m.removed && m.alive()
})
.collect()
let mut riders = self.vehicle_riders(id);
riders.retain(|&j| !self.mobs[j].removed && self.mobs[j].alive());
riders
}
/// `getPassengers().size()` of boat `id`.
pub(super) fn boat_passengers(&self, id: u32) -> usize {
@@ -174,18 +336,12 @@ impl Game<'_> {
/// `AbstractBoat.canVehicleCollide`: the other boats, minecarts,
/// shulkers and pushable mobs and players, but not its own passengers.
pub(super) fn boat_obstacles(&self, id: u32, area: Aabb) -> Vec<Aabb> {
let reach = self.vehicle_mob_reach();
let mut out: Vec<Aabb> = (0..self.mobs.len())
.filter(|&j| {
let m = &self.mobs[j];
// The box first: it turns away nearly every mob of the level.
reach.is_none_or(|r| r.may_meet(m, area))
&& m.bounds().intersects(area)
&& pushable(m)
&& (m.extra.mount.is_none() || self.mob_root_vehicle(j) != Some(id))
})
.map(|j| self.mobs[j].bounds())
.collect();
let mut out = Vec::new();
self.mobs_meeting(area, |j, m, b| {
if pushable(m) && (m.extra.mount.is_none() || self.mob_root_vehicle(j) != Some(id)) {
out.push(b);
}
});
out.extend(
self.boats
.iter()
@@ -230,19 +386,14 @@ impl Game<'_> {
let pick_up = self.boat_players(id) == 0;
// canAddPassenger, which startRiding asks after the checks below.
let room = !self.boats[i].under_water();
// The box first: it turns away nearly every mob of the level, and the
// teams are only worked out when something touches the boat.
let reach = self.vehicle_mob_reach();
let sweep = area.union_bounds(bb);
let near: Vec<usize> = (0..self.mobs.len())
.filter(|&j| {
if reach.is_some_and(|r| !r.may_meet(&self.mobs[j], sweep)) {
return false;
}
let mb = self.mobs[j].bounds();
mb.intersects(area) || mb.intersects(bb)
})
.collect();
// The mobs near the two boxes: the teams are only worked out when something
// touches the boat.
let mut near = Vec::new();
self.mobs_meeting(area.union_bounds(bb), |j, _, mb| {
if mb.intersects(area) || mb.intersects(bb) {
near.push(j);
}
});
let outside = self.players_outside(id);
let touching = !near.is_empty()
|| outside
@@ -531,4 +682,124 @@ mod tests {
assert!(boat_pushes(boat, at(64.5), true));
assert!(!boat_pushes(boat, at(64.5625), true));
}
/// A mob pushes the cart its box touches while a mob far from every cart pushes none and
/// is not pushed, whichever grid finds them: the carts' (four carts in four of its columns,
/// asked once per mob while the mobs are the fewer) or, in a crowd, the mobs' (asked once
/// per cart).
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn only_the_mob_touching_a_cart_pushes_it() {
use super::super::minecarts::{CartKind, Minecart};
let pushed = [0, 12].map(|crowd: u32| {
let mut game = super::super::native_machines::tests::server_game();
let pig = game.res.mob_types().get("minecraft:pig").unwrap().clone();
for (i, (x, z)) in [(0.5, 0.5), (20.5, 0.5), (0.5, 20.5), (20.5, 20.5)]
.into_iter()
.enumerate()
{
let at = Vec3::new(x, 64.0, z);
game.carts
.push(Minecart::new(100 + i as u32, CartKind::Chest, at));
}
// 0.5 west of the second cart (boxes 0.9 and 0.98 wide), in the middle of them
// all, and the crowd well away.
let spots = [(20.0, 0.5), (10.5, 10.5)].into_iter();
let crowd = (0..crowd).map(|i| (40.5 + 3.0 * f64::from(i), 40.5));
for (i, (x, z)) in spots.chain(crowd).enumerate() {
let at = Vec3::new(x, 64.0, z);
game.mobs.push(Mob::new(1 + i as u32, pig.clone(), at, 0.0));
}
game.tick_carts();
let velocity = |id| game.mobs.iter().find(|m| m.id == id).unwrap().velocity;
assert!(velocity(1).x < 0.0, "pushed back west: {:?}", velocity(1));
let idle = game.mobs.iter().filter(|m| m.velocity == Vec3::ZERO);
assert_eq!(idle.count(), game.mobs.len() - 1);
velocity(1)
});
assert_eq!(pushed[0], pushed[1]);
}
/// A vehicle's box query during a stretch of vehicle ticks names the mobs a walk over
/// every box names, in the same order, also right after a mob moved into the box (a
/// push or a pick-up writes the mob list in the middle of a stretch).
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn a_vehicles_box_query_matches_a_walk_over_every_mob() {
let mut game = super::super::native_machines::tests::server_game();
let pig = game.res.mob_types().get("minecraft:pig").unwrap().clone();
// A small LCG keeps the scene the same on every run.
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut next = |range: f64| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
(seed >> 11) as f64 / (1u64 << 53) as f64 * range
};
for id in 1..=400 {
let at = Vec3::new(next(48.0), 64.0 + next(3.0), next(48.0));
game.mobs.push(Mob::new(id, pig.clone(), at, 0.0));
}
let mut met = 0;
for round in 0..300 {
// Three stretches, each with two writes to the mob list.
if round % 100 == 0 {
game.vehicles_ticking(true);
}
let corner = Vec3::new(next(46.0), 63.0 + next(3.0), next(46.0));
let size = Vec3::new(0.5 + next(2.5), 0.5 + next(1.5), 0.5 + next(2.5));
let area = Aabb::new(corner, corner.add_vector(size));
if round % 40 == 20 {
let j = round % game.mobs.len();
game.mobs[j].position = area.center();
}
let walked: Vec<Aabb> = game
.mobs
.iter()
.map(Mob::bounds)
.filter(|b| b.intersects(area))
.collect();
met += walked.len();
assert_eq!(game.boat_obstacles(u32::MAX, area), walked, "round {round}");
if round % 100 == 99 {
// The last comparisons ran against the grid: it stands, for the list as it is.
let fresh = |(stamp, _): &(ListStamp, SeenGrid)| *stamp == game.mobs.stamp();
assert!(
game.vehicle_mobs
.grid
.borrow()
.built
.as_ref()
.is_some_and(fresh)
);
game.vehicles_ticking(false);
}
}
assert!(met > 100, "the boxes met {met} mobs");
}
/// Who rides a vehicle follows the mob list through a stretch of vehicle ticks: a mob that
/// boards counts from then on, one removed no longer does, and a dead one still makes
/// its cart a vehicle but is no passenger of a boat.
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn a_vehicle_knows_its_mob_riders_as_soon_as_they_board() {
let mut game = super::super::native_machines::tests::server_game();
let pig = game.res.mob_types().get("minecraft:pig").unwrap().clone();
for id in 1..=4 {
game.mobs.push(Mob::new(id, pig.clone(), Vec3::ZERO, 0.0));
}
let riders =
|game: &Game| [100, 101, 102].map(|id| (game.mob_rides(id), game.boat_mobs(id)));
game.mobs[0].extra.mount = Some(100);
game.vehicles_ticking(true);
let none = (false, vec![]);
assert_eq!(riders(&game), [(true, vec![0]), none.clone(), none.clone()]);
game.mobs[0].removed = true;
game.mobs[1].extra.mount = Some(101);
game.mobs[3].extra.mount = Some(102);
game.mobs[3].health = 0.0;
let after = [none, (true, vec![1]), (true, vec![])];
assert_eq!(riders(&game), after);
game.vehicles_ticking(false);
assert_eq!(riders(&game), after);
}
}
+39 -10
View File
@@ -682,19 +682,14 @@ impl Game<'_> {
/// of it (`ClipContext.Block.FALLDAMAGE_RESETTING`, `ClipContext.Fluid.WATER`)
/// and a hit resets the fall, before the move's own drop counts.
pub(super) fn vehicle_fall_reset(&self, fall: f64, from: Vec3, moved: Vec3) -> f64 {
let length = moved.length_squared();
if fall == 0.0 || length < 1.0 {
return fall;
}
let reset = &self.res.motion().fall_reset;
let hit = horizon_client::entities::fall_reset_hit(
fall_reset(
&self.world,
&self.res.motion().fluids,
|p| reset.contains(&*self.res.facts().get(self.world.block(p.x, p.y, p.z)).name),
self.res.motion(),
self.res.facts(),
fall,
from,
moved,
);
if hit { 0.0 } else { fall }
)
}
/// `AbstractBoat.checkFallDamage` after a move that went `moved_y` (with
/// `b` already where it landed): on the ground the fall resets; a move
@@ -1467,6 +1462,13 @@ impl Game<'_> {
}
}
/// `BoatItem.use`: aim at a block or the water surface.
/// `Entity.setYRot` on a boat just made (its old rotation moves with it).
pub(super) fn set_boat_yaw(&mut self, id: u32, yaw: f32) {
if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
b.yaw = yaw;
b.previous_yaw = yaw;
}
}
pub(super) fn place_boat(&mut self, stack: &ItemStack) -> bool {
let Some(boat) = self.boat_to_place(stack) else {
return false;
@@ -1477,7 +1479,11 @@ impl Game<'_> {
boat.position.z.floor() as i32 >> 4,
);
self.world.modified.insert(key);
let (id, kind, yaw) = (boat.id, boat.entity_type(), boat.yaw);
self.boats.push(boat);
self.apply_vehicle_stack_config(super::commands::Target::Boat(id), &kind, stack, true);
// BoatItem.use: setYRot(player.getYRot()) after the stack's config.
self.set_boat_yaw(id, yaw);
if self.serving.is_some() || self.options.dedicated.is_some() {
self.native_vehicle_create(
self.boats.last().unwrap().entity_type().as_str(),
@@ -2071,3 +2077,26 @@ mod tests {
}
}
horizon_client::impl_joined!(Boat);
/// [`Game::vehicle_fall_reset`] from the tables it reads.
pub(super) fn fall_reset(
world: &horizon_client::world::World,
motion: &horizon_client::motion::MotionResources,
facts: &horizon_client::blocks::BlockFacts,
fall: f64,
from: Vec3,
moved: Vec3,
) -> f64 {
if fall == 0.0 || moved.length_squared() < 1.0 {
return fall;
}
let reset = &motion.fall_reset;
let hit = horizon_client::entities::fall_reset_hit(
world,
&motion.fluids,
|p| reset.contains(&*facts.get(world.block(p.x, p.y, p.z)).name),
from,
moved,
);
if hit { 0.0 } else { fall }
}
+160 -10
View File
@@ -3,7 +3,7 @@
//! pixels, 1024 characters, 100 pages), signing it into a written book,
//! reading written books, and lecterns (placing a book, turning its pages
//! with a redstone pulse, the comparator output and taking the book).
use super::{Game, lan::LanHost, screen_info};
use super::{Game, chat::PLAYER_NAME, lan::LanHost, screen_info};
use horizon_client::{
containers::{BlockEntity, Lectern},
first_person::Hand,
@@ -18,6 +18,7 @@ use horizon_client::{
use horizon_core::position::BlockPos;
use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S};
use horizon_world::level::flags as level_flags;
use horizon_world::nbt::Tag;
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
@@ -213,6 +214,15 @@ impl Game<'_> {
"minecraft:written_book" => true,
_ => return false,
};
// `ServerPlayer.openItemGui` resolves a written book for the player
// opening it before the screen reads it.
let held;
let stack = if written && self.resolve_held_book() {
held = self.held().cloned();
held.as_ref().unwrap_or(stack)
} else {
stack
};
if self.lan_acting.is_some() {
if written {
let hand = i32::from(self.hand == Hand::Off);
@@ -227,6 +237,56 @@ impl Game<'_> {
self.swing_arm();
true
}
/// `ServerPlayer.openItemGui` -> `WrittenBookContent.resolveForItem`: the
/// selectors and scores of the written book in the acting hand become
/// their text for the player opening it, and the book is marked resolved
/// (so it is never resolved again). True when the pages were rewritten.
fn resolve_held_book(&mut self) -> bool {
let Some(mut book) = self
.held()
.and_then(|s| s.data())
.and_then(|d| d.written.clone())
else {
return false;
};
if book.resolved {
return false;
}
let string = |v: &Tag| match v {
Tag::String(s) => Some(s.to_string_lossy()),
_ => None,
};
let changed = book.resolve(|tag| {
let Tag::Compound(c) = tag else { return None };
if let Some(Tag::String(selector)) = c.get(&"selector".into()) {
let selector = selector.to_string_lossy();
return Some(self.resolve_selector_text(&selector));
}
let score = c.get(&"score".into())?;
let name = score.get("name").and_then(string).unwrap_or_default();
let objective = score.get("objective").and_then(string).unwrap_or_default();
let name = if name == "*" {
PLAYER_NAME
} else {
name.as_str()
};
Some(
self.score
.board
.score(name, &objective)
.map_or_else(String::new, |s| s.value.to_string()),
)
});
if let Some(stack) = self.held_mut() {
stack.data_mut().written = Some(book);
}
// A guest's copy of the book lives in its mirrored inventory: the
// host sends the resolved slot back with the rest of the inventory.
if self.lan_acting.is_some() {
self.guest_inventory_resend = true;
}
changed
}
/// The screen a book in hand opens: `BookEditScreen` for a book and
/// quill, `BookViewScreen` for a written book.
fn book_screen(&self, stack: &ItemStack) -> Option<BookScreen> {
@@ -349,6 +409,7 @@ impl Game<'_> {
generation: 0,
pages,
page_tags: Vec::new(),
resolved: false,
});
*stack = written;
} else {
@@ -1594,15 +1655,17 @@ impl Game<'_> {
&tr("gui.done", "Done"),
);
}
// HoveredTextEffects.TOOLTIP_AND_CURSOR: the hovered words'
// show_text hover event, as the chat shows it.
if let Some(hover) = pages
.get(*page)
.and_then(|t| self.book_style_at(t, left))
.and_then(|s| s.hover)
{
let lines = self.wrapped_rows(&hover, (w as i32 / 2).max(200));
self.draw_tooltip_lines(batch, &lines, mx, my);
// HoveredTextEffects.TOOLTIP_AND_CURSOR: a clickable word
// asks for the hand, and a show_text hover shows its tooltip,
// as the chat does.
if let Some(style) = pages.get(*page).and_then(|t| self.book_style_at(t, left)) {
if let Some(cursor) = link_cursor(&style) {
horizon_client::widgets::request_cursor(cursor);
}
if let Some(hover) = style.hover {
let lines = self.wrapped_rows(&hover, (w as i32 / 2).max(200));
self.draw_tooltip_lines(batch, &lines, mx, my);
}
}
}
}
@@ -1647,6 +1710,16 @@ pub(super) fn lectern_signal(world: &horizon_client::world::World, pos: BlockPos
}
}
/// `HoveredTextEffects.TOOLTIP_AND_CURSOR`: only a word with a click event asks
/// for the pointing hand over a book's page; a hover event alone shows its
/// tooltip.
fn link_cursor(style: &horizon_client::text::Style) -> Option<horizon_client::widgets::Cursor> {
style
.click
.is_some()
.then_some(horizon_client::widgets::Cursor::PointingHand)
}
#[cfg(test)]
mod title_box_tests {
use super::book_title_box;
@@ -1836,6 +1909,60 @@ mod lectern_signal_tests {
assert_eq!(signal(&mut game, Some(written), 1), 15, "last page");
}
}
impl BookScreen {
/// `BookViewScreen.isPauseScreen`: the class inherits `Screen`'s true, so
/// a book read in hand stops a single-player world. `LecternScreen`
/// overrides it false, so the same pages read on a lectern leave the
/// world ticking (its menu is an `AbstractContainerScreen`, which does
/// not pause either).
pub(super) fn pauses_world(&self) -> bool {
!matches!(
self,
Self::View {
lectern: Some(_),
..
}
)
}
}
#[cfg(test)]
mod pause_tests {
use super::BookScreen;
use horizon_client::{text::Text, ui};
fn view(lectern: Option<(i32, i32, i32)>) -> BookScreen {
BookScreen::View {
pages: Vec::<Text>::new(),
page: 0,
lectern,
}
}
#[test]
fn a_lecterns_book_does_not_pause_the_world() {
// BookViewScreen keeps Screen.isPauseScreen's true; LecternScreen
// overrides it false although both read the same pages.
assert!(view(None).pauses_world());
assert!(!view(Some((10, 64, -3))).pauses_world());
}
#[test]
fn a_book_being_edited_or_signed_pauses() {
// BookEditScreen and BookSignScreen do not override isPauseScreen.
let edit = |signing| BookScreen::Edit {
slot: 0,
pages: Vec::new(),
page: 0,
signing,
title: String::new(),
title_edit: ui::EditBox::new(0.0, 0.0, 0.0, 0.0),
page_edit: ui::EditBox::new(0.0, 0.0, 0.0, 0.0),
};
assert!(edit(false).pauses_world());
assert!(edit(true).pauses_world());
}
}
#[cfg(test)]
mod lectern_reach_tests {
@@ -1929,3 +2056,26 @@ mod sign_tests {
}
}
}
#[cfg(test)]
mod link_cursor_tests {
use super::link_cursor;
use horizon_client::text::{ClickEvent, Style, Text};
use horizon_client::widgets::Cursor;
/// `HoveredTextEffects.TOOLTIP_AND_CURSOR`: a clickable word asks for the
/// pointing hand; a hover event alone only shows its tooltip.
#[test]
fn only_a_clickable_book_word_asks_for_the_hand() {
let link = Style {
click: Some(ClickEvent::OpenUrl("https://example.com".into())),
..Style::default()
};
let hover_only = Style {
hover: Some(Box::new(Text::literal("tip"))),
..Style::default()
};
assert_eq!(link_cursor(&link), Some(Cursor::PointingHand));
assert_eq!(link_cursor(&hover_only), None);
}
}
@@ -23,3 +23,34 @@ fn breeding_drops_one_orb_of_the_whole_roll() {
}
assert!(values.iter().any(|v| matches!(v, 4..=6)), "{values:?}");
}
/// `Turtle.TurtleBreedGoal.breed` overrides `Animal.breed`, so a bred turtle
/// never runs `finalizeSpawnChildFromBreeding`'s heart burst (entity event
/// 18); `Frog.spawnChildFromBreeding` still does.
#[test]
#[ignore = "needs prepared resources (HORIZON_TEST_RESOURCES)"]
fn a_bred_turtle_posts_no_heart_burst_but_a_bred_frog_does() {
let mut game = super::super::native_machines::tests::server_game();
game.audio.capture = Some(Vec::new());
for (kind_id, hearts) in [("minecraft:turtle", 0), ("minecraft:frog", 1)] {
let kind = game.res.mob_types().get(kind_id).unwrap().clone();
game.mobs
.push(Mob::new(1, kind.clone(), Vec3::new(8.5, 64.0, 8.5), 0.0));
game.mobs
.push(Mob::new(2, kind, Vec3::new(9.5, 64.0, 8.5), 0.0));
game.lan_entity_events.clear();
game.breed(1, 2, None);
let burst = game
.lan_entity_events
.iter()
.filter(|(id, event, _)| *id == 1 && *event == 18)
.count();
assert_eq!(
burst, hearts,
"{kind_id} heartbeat events: {:?}",
game.lan_entity_events
);
game.mobs.clear();
game.orbs.clear();
}
}
+201 -18
View File
@@ -1,9 +1,10 @@
//! Breeze particles (`Breeze.tick`): block dust at its feet while it stands,
//! a burst of twenty while it slides and a short trail along a long jump.
use super::Game;
use super::{BlockStateId, Game};
use horizon_client::{
mobs::{Species, breeze},
particles::Particle,
blocks::RenderShape,
mobs::{Mob, Species, breeze},
particles::{ParticleOptions, ParticleType},
};
impl Game<'_> {
@@ -33,21 +34,16 @@ impl Game<'_> {
} else {
self.mobs[i].extra.scratch[1] = 0;
}
let m = &self.mobs[i];
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let mut at = [x, y, z];
let mut state = self.world.block(x, y, z);
if self.res.facts().is_air(state) {
at[1] = (m.position.y - 0.2).floor() as i32;
state = self.world.block(x, at[1], z);
let (block, state) = self.breeze_ground(&self.mobs[i]);
// `emitGroundParticles` skips an invisible block; the jump trail
// (`emitJumpTrailParticles`) does not ask.
if !jump_trail && self.res.facts().get(state).render_shape == RenderShape::Invisible {
continue;
}
let Some((sprite, tint)) = self.particle_sprite(state, at) else {
let Some((sprite, tint)) = self.particle_sprite(state, block) else {
continue;
};
let m = &self.mobs[i];
let at = if jump_trail {
[
m.position.x + m.velocity.x,
@@ -57,11 +53,198 @@ impl Game<'_> {
} else {
[m.position.x, m.position.y, m.position.z]
};
// `ClientLevel.addParticle` with no speed: each crumb's own
// generator draws its lifetime, its little push and the quarter of
// the block's sprite it shows, never the level's random.
let options = ParticleOptions::block(ParticleType::Block, sprite, tint);
for _ in 0..amount {
let particle =
Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint);
self.particles.push(particle);
self.particles.add(&options, at, [0.0; 3]);
}
}
}
/// `Breeze.emitGroundParticles`'s block: `getInBlockState`, else
/// `getBlockStateOn`, which is `Entity.getOnPos(1.0E-5F)` — the supporting
/// block the feet rest on, or the cell just below them. A fence, a wall and
/// a fence gate have a 1.5-block collision, so a breeze on one has its feet
/// half a block above that block's own cell, where the cell below them is
/// air and only the supporting block has the material.
pub(super) fn breeze_ground(&self, m: &Mob) -> ([i32; 3], BlockStateId) {
let feet = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let in_block = self.world.block(feet[0], feet[1], feet[2]);
if !self.res.facts().is_air(in_block) {
return (feet, in_block);
}
let on_ground = m
.on_ground
.then(|| self.supporting_block(m.position, m.bounds()));
let at = on_ground.flatten().map_or(
[
feet[0],
(m.position.y - f64::from(1.0e-5_f32)).floor() as i32,
feet[2],
],
|p| [p.x, p.y, p.z],
);
(at, self.world.block(at[0], at[1], at[2]))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::game::{Audio, Options, Progress, Settings, load_resources};
use horizon_client::chunk::Chunk;
use horizon_client::mobs::Mob;
use horizon_core::geometry::Vec3;
use horizon_core::random::LegacyRandom;
use std::sync::Arc;
/// A game on the prepared resources with an empty chunk at (0, 0), the
/// window's player (the camera the dust needs) and one breeze standing
/// with its feet at `feet`.
fn game_with_breeze(feet: Vec3) -> Game<'static> {
let root = std::path::PathBuf::from(
std::env::var_os("HORIZON_TEST_RESOURCES")
.expect("set HORIZON_TEST_RESOURCES to prepared resources"),
);
let settings = Settings::default();
let loaded = load_resources(
root.clone(),
None,
&root,
&settings,
std::time::Instant::now(),
false,
false,
&Progress::new(),
&mut |_, _| unreachable!(),
)
.unwrap();
let mut options = Options::parse(std::iter::empty()).unwrap().unwrap();
options.resources = root.clone();
options.execution_role = crate::game::execution_role::ExecutionRole::IntegratedServer;
let res: &'static _ = Box::leak(Box::new(loaded.resources));
let mut game = Game::new(
res,
loaded.pack,
loaded.gui.unwrap(),
options,
settings,
Audio::silent(&root),
None,
)
.unwrap();
game.world
.chunks
.insert((0, 0), Arc::new(Chunk::empty(0, 0)));
// Eight blocks south of the breeze: inside the 32 blocks the dust needs.
game.player = Some(
horizon_client::motion::PlayerMotion::new(game.motion, Vec3::new(8.5, 66.0, 16.5))
.unwrap(),
);
game.particles.camera = [8.5, 66.0, 16.5];
let kind = game.res.mob_types()["minecraft:breeze"].clone();
game.mobs.push(Mob::new(13001, kind, feet, 0.0));
game
}
/// A breeze standing on a fence rests its feet at 64 + 1.5, where its own
/// cell is air: `Breeze.emitGroundParticles` asks `getBlockStateOn` for the
/// supporting block, so the crumbs are the fence's. Every one of them is
/// made by the particle's own generator (`Particle.random`), so the
/// client level's random is where it was before the tick.
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn the_dust_of_a_breeze_on_a_fence_keeps_the_client_level_random() {
let mut game = game_with_breeze(Vec3::new(8.5, 65.5, 8.5));
let registry = &game.pack.assets.registry;
let stone = registry.default_state("minecraft:stone").unwrap();
let fence = registry.default_state("minecraft:oak_fence").unwrap();
game.world.set(8, 63, 8, stone).unwrap();
game.world.set(8, 64, 8, fence).unwrap();
game.mobs[0].on_ground = true;
assert_eq!(
game.breeze_ground(&game.mobs[0]),
([8, 64, 8], fence),
"the feet's own cell is air; the fence is what holds them up"
);
game.world.random = LegacyRandom::new(1234);
let level = game.world.random.state();
game.tick_breeze_effects();
assert_eq!(
game.particles.made().get("block").copied().unwrap_or(0),
1,
"vanilla emits one crumb of the fence the breeze stands on"
);
assert_eq!(
game.world.random.state(),
level,
"the crumb's constructor draws belong to the particle, not the level"
);
}
/// The control: a breeze standing on a full block's top also crumbles it,
/// and its constructor's draws still leave the client level's random alone.
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn the_dust_of_a_breeze_on_a_full_block_keeps_the_client_level_random() {
let mut game = game_with_breeze(Vec3::new(8.5, 64.0, 8.5));
let stone = game
.pack
.assets
.registry
.default_state("minecraft:stone")
.unwrap();
game.world.set(8, 63, 8, stone).unwrap();
game.mobs[0].on_ground = true;
game.world.random = LegacyRandom::new(1234);
let level = game.world.random.state();
game.tick_breeze_effects();
assert_eq!(
game.world.random.state(),
level,
"the crumb's constructor draws belong to the particle, not the level"
);
assert_eq!(game.particles.made().get("block").copied().unwrap_or(0), 1);
}
/// `Entity.getOnPos(1.0E-5F)` keeps a fence's, a wall's or a fence gate's
/// own cell while the feet rest on its 1.5-block collision; on a full block
/// it is the block below the feet. Reading 0.2 below the feet, as the dust
/// used to, lands in air on all three.
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn the_ground_of_a_breeze_is_the_fence_wall_or_gate_it_stands_on() {
let mut game = game_with_breeze(Vec3::new(8.5, 65.5, 8.5));
let registry = &game.pack.assets.registry;
let stone = registry.default_state("minecraft:stone").unwrap();
game.world.set(8, 63, 8, stone).unwrap();
game.mobs[0].on_ground = true;
for name in [
"minecraft:oak_fence",
"minecraft:cobblestone_wall",
"minecraft:oak_fence_gate",
] {
let state = registry.default_state(name).unwrap();
game.world.set(8, 64, 8, state).unwrap();
assert_eq!(
game.breeze_ground(&game.mobs[0]),
([8, 64, 8], state),
"{name}"
);
}
// The same breeze on the full block's top reads that block.
game.world.set(8, 64, 8, stone).unwrap();
game.mobs[0].position = Vec3::new(8.5, 65.0, 8.5);
assert_eq!(game.breeze_ground(&game.mobs[0]), ([8, 64, 8], stone));
}
}
+18 -2
View File
@@ -5,8 +5,8 @@
use super::Game;
use horizon_assets::item_model::DisplayContext;
use horizon_client::{
Result, block_entities::Pos, block_entity_render::vertex_light, containers::BlockEntity,
items::ItemStack, mesher::Vertex, mobs::Who,
Result, actions::Action, block_entities::Pos, block_entity_render::vertex_light,
containers::BlockEntity, items::ItemStack, mesher::Vertex, mobs::Who,
};
use horizon_core::position::BlockPos;
@@ -25,6 +25,13 @@ impl Game<'_> {
/// to the server. Whether the food went in; None when this isn't a
/// campfire use, so the item's own use runs.
pub(super) fn use_on_campfire(&mut self, pos: [i32; 3]) -> Result<Option<bool>> {
// `ServerPlayerGameMode.useItemOn`'s `suppressUsingBlock`: sneaking
// with a stack in either hand never reaches the block's `useItemOn`,
// so the food stays in the hand and the item's own use (eating)
// runs instead.
if self.keys.held(Action::Sneak) {
return Ok(None);
}
let state = self.world.block(pos[0], pos[1], pos[2]);
if !is_campfire(&self.res.facts().get(state).name) {
return Ok(None);
@@ -60,6 +67,11 @@ impl Game<'_> {
);
self.mark_block_entity_updated(key);
}
// `ServerPlayerGameMode.useItemOn` triggers ITEM_USED_ON_BLOCK with
// the stack before the use once `useItemOn` consumed the click, both
// when the food went in (SUCCESS_SERVER) and on a full campfire
// (CONSUME).
self.trigger_block("minecraft:item_used_on_block", pos, &held);
Ok(Some(placed))
}
@@ -198,3 +210,7 @@ impl Game<'_> {
}
}
}
#[cfg(test)]
#[path = "campfire_tests.rs"]
mod campfire_tests;
@@ -0,0 +1,125 @@
//! Campfire food placement's gate and criterion: `CampfireBlock.useItemOn`
//! reached through `ServerPlayerGameMode.useItemOn`, which skips the block
//! while sneaking with something in hand and then triggers
//! ITEM_USED_ON_BLOCK for the use it consumed.
use super::*;
use crate::game::{Hit, native_machines::tests::server_game};
use horizon_client::{
advancements::{Advancement, Criterion, Rewards, Tree},
held::Source,
items::ItemStack,
motion::PlayerMotion,
};
use horizon_core::geometry::Vec3;
use horizon_world::lazy_json::LazyJson;
use std::sync::Arc;
use winit::keyboard::KeyCode;
/// A server game with a campfire at `pos` (its block entity too) and beef in
/// the main hand, the click forced onto that block.
fn campfire_game(pos: [i32; 3]) -> Game<'static> {
let mut game = server_game();
// A local player, not a dedicated server's silent world: criteria and
// statistics apply to them.
game.options.dedicated = None;
let state = game
.pack
.assets
.registry
.default_state("minecraft:campfire")
.unwrap();
game.world.set(pos[0], pos[1], pos[2], state).unwrap();
game.world.block_entities.put(
(pos[0], pos[1], pos[2]),
BlockEntity::Campfire(Box::default()),
);
let mut player = PlayerMotion::new(
game.motion,
Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 2.5,
),
)
.unwrap();
// `Player.canEat`: hungry, so the beef's own use can start.
player.health.food.food = 6;
game.player = Some(player);
game.creative = false;
*game.held_mut() = Some(ItemStack::new("minecraft:beef", 4));
game.forced_hit = Some(Hit {
pos,
face: [0, 1, 0],
point: [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 1.0,
f64::from(pos[2]) + 0.5,
],
});
game
}
/// The campfire's four cooking slots.
fn slots(game: &Game<'_>, pos: [i32; 3]) -> usize {
match game.world.block_entities.get(&(pos[0], pos[1], pos[2])) {
Some(BlockEntity::Campfire(c)) => c.items.iter().filter(|i| i.is_some()).count(),
_ => panic!("no campfire block entity at {pos:?}"),
}
}
/// `ServerPlayerGameMode.useItemOn`: with something in hand, sneaking skips
/// `state.useItemOn` entirely (`suppressUsingBlock`), so the beef is neither
/// placed nor consumed; the item's own use, eating, starts instead. Without
/// the sneak the campfire takes the beef, and the use it consumed triggers
/// ITEM_USED_ON_BLOCK with the stack before the use.
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn a_sneak_keeps_the_food_and_placing_it_fires_item_used_on_block() {
const POS: [i32; 3] = [2, 4, 3];
let mut game = campfire_game(POS);
// The tree a data pack with one `item_used_on_block` criterion on this
// campfire would be indexed into.
let mut tree = Tree::default();
tree.list.push(Advancement {
id: "horizon:test/campfire".into(),
parent: None,
display: None,
criteria: vec![Criterion {
name: "food".into(),
trigger: "minecraft:item_used_on_block".into(),
conditions: LazyJson::from(serde_json::json!({
"location": {
"type": "minecraft:location_check",
"predicate": {"block": {"blocks": "minecraft:campfire"}}
}
})),
}],
requirements: vec![vec!["food".into()]],
rewards: Rewards::default(),
});
tree.by_id.insert("horizon:test/campfire".into(), 0);
tree.by_trigger
.insert("minecraft:item_used_on_block".into(), vec![(0, 0)]);
game.adv.tree = Arc::new(tree);
let hit = game.forced_hit.unwrap();
game.keys.press(KeyCode::ShiftLeft, Source::Keyboard);
assert!(game.use_hand(Some(&hit)).unwrap());
assert_eq!(slots(&game, POS), 0, "the sneak put no beef on the fire");
assert_eq!(game.held().unwrap().count, 4, "the beef stayed in hand");
assert!(game.using.is_some(), "the beef is being eaten");
assert!(
!game.adv.progress.has("horizon:test/campfire", "food"),
"the skipped block use triggers nothing"
);
// Stop eating, let go of the sneak: the same click now feeds the fire.
game.using = None;
game.keys.release(&KeyCode::ShiftLeft, Source::Keyboard);
assert!(game.use_hand(Some(&hit)).unwrap());
assert_eq!(slots(&game, POS), 1, "the beef went on the fire");
assert_eq!(game.held().unwrap().count, 3, "one beef was used");
assert!(game.using.is_none(), "the click was consumed");
assert!(
game.adv.progress.has("horizon:test/campfire", "food"),
"the placed food fired item_used_on_block"
);
}
+1 -1
View File
@@ -2694,7 +2694,7 @@ mod damage_type_registry_tests {
let pack = dir.join("datapacks/model");
let types = pack.join("data/example/damage_type");
std::fs::create_dir_all(&types).unwrap();
std::fs::write(pack.join("pack.mcmeta"), "{}").unwrap();
std::fs::write(pack.join("pack.mcmeta"), r#"{"pack":{"description":""}}"#).unwrap();
std::fs::write(
types.join("test.json"),
r#"{"message_id":"example.test","scaling":"never","exhaustion":0.0}"#,
+7 -1
View File
@@ -608,7 +608,13 @@ impl Game<'_> {
if !host && !guest {
return;
}
let message = self.mob_death_message(m, killer);
let mut built = Some(self.mob_death_message(m, killer));
let kind = super::native_hooks::mob_kind(m);
horizon_client::living_death::native_living_death_message(m.id, &kind, &mut built);
// A native mod may have changed the message, or set it to None to tell the owner nothing.
let Some(message) = built else {
return;
};
if host {
self.system_message(message);
} else if let Some(lan) = &self.lan {
@@ -380,7 +380,7 @@ impl Game<'_> {
let (mut meta, mut defaults) = (Vec::new(), Vec::new());
super::lan::mob_meta(
m,
hub,
hub.sync_data(),
None,
g.world.game_time,
&mut meta,
+17 -27
View File
@@ -3,10 +3,12 @@
mod admin;
pub(super) mod compute;
mod data;
mod display_names;
pub(super) use data::place_summoned;
mod effects;
pub(super) mod execute;
pub(super) mod extra;
mod item_count;
pub(in crate::game) mod items;
mod misc;
mod place;
@@ -782,13 +784,7 @@ impl Game<'_> {
let block = Text::translate(&format!("block.{block}"), &[]);
Text::translate("entity.minecraft.falling_block_type", &[block])
}
Target::Mob(id) => self.mobs.iter().find(|m| m.id == id).map_or_else(
|| Text::translate("entity.", &[]),
|m| match self.mob_team_of(m) {
Some(team) => team.formatted_name(m.command_name()),
None => m.command_name(),
},
),
Target::Mob(id) => self.mob_command_name(id),
other => {
// Entity.getDisplayName: the CustomName component, else the type.
let custom = super::native_entities::target_id(other)
@@ -2618,9 +2614,10 @@ impl Game<'_> {
if self.res.mob_types().contains_key(&kind) {
// SummonCommand.createEntity loads the mob from `{id:..}`: its yaw
// is the compound's (none, so 0), with no level-random draw.
self.spawn_mob_spawned(&short, pos, super::creatures::SpawnYaw::Fixed(0.0))
let id = self
.spawn_mob_spawned(&short, pos, super::creatures::SpawnYaw::Fixed(0.0))
.ok_or_else(|| err("commands.summon.failed.uuid", &[]))?;
name = Text::translate(&entity_name_key(&kind), &[]);
name = self.target_name(Target::Mob(id));
} else {
match short.as_str() {
"item" => {
@@ -3955,6 +3952,12 @@ impl Game<'_> {
};
let present = components.get(&id.as_str().into());
let result = match term[split..].chars().next() {
// Both count wrappers in `ItemPredicateArgument` use the live
// stack count and the same integer bounds matcher.
Some('=' | '~') if id == "minecraft:count" => {
let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim());
value.is_ok_and(|(v, _)| item_count::matches(stack.count, &v))
}
Some('=') => {
let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim())
.ok()
@@ -3968,28 +3971,11 @@ impl Game<'_> {
}
}
Some('~') => {
// Sub-predicates: `count` and component predicates.
// Component sub-predicates.
let value = horizon_world::nbt::parse_snbt(term[split + 1..].trim())
.ok()
.map(|(t, _)| t);
match (id.as_str(), value) {
("minecraft:count", Some(v)) => {
let n = i64::from(stack.count);
match &v {
horizon_world::nbt::Tag::Compound(_) => {
let get = |k: &str| match v.get(k) {
Some(horizon_world::nbt::Tag::Int(i)) => {
Some(i64::from(*i))
}
_ => None,
};
get("min").is_none_or(|m| n >= m)
&& get("max").is_none_or(|m| n <= m)
}
horizon_world::nbt::Tag::Int(i) => n == i64::from(*i),
_ => false,
}
}
// `MinMaxBounds.Ints.matches`: DamagePredicate's damage-only
// Int bounds shape; effective DAMAGE presence is required.
// Other fields keep the entire existing predicate path.
@@ -6048,3 +6034,7 @@ mod global_selector_order_tests {
);
}
}
#[cfg(test)]
#[path = "item_count_predicate_tests.rs"]
mod item_count_predicate_tests;
@@ -421,6 +421,16 @@ impl Game<'_> {
// random (Entity.random) goes on, as a spawn egg's entity
// data finds it.
slot.random = old.random.clone();
// Entity.load keeps the unsaved Allay.jukeboxPos and
// DATA_DANCING of the entity it loads into.
if slot.species() == horizon_client::mobs::Species::Allay {
slot.extra.flag = old.extra.flag;
if let (Some(st), Some(was)) =
(slot.extra.allay.as_mut(), old.extra.allay.as_ref())
{
st.jukebox = was.jukebox;
}
}
if keep_liked_player {
slot.extra.tame = old.extra.tame;
slot.extra.owner = old.extra.owner;
@@ -506,9 +516,11 @@ impl Game<'_> {
new.glow = old.glow;
// ItemFrame.readAdditionalSaveData: ItemStack.matches includes
// count, item and components, before adopting the new stack.
// It compares the stack as read; setItem keeps one of it
// only after, as `new.item` already does.
let read = tag.get("Item").and_then(save::item_from_nbt);
if old.item.as_ref().is_some_and(|a| {
new.item
.as_ref()
read.as_ref()
.is_none_or(|b| a.count != b.count || !a.same_item_same_components(b))
}) {
let old = old.clone();
@@ -0,0 +1,34 @@
//! `Entity.getDisplayName` for the mobs command replies name: the name as its
//! team shows it, with the `show_entity` hover and the UUID insertion.
use super::super::Game;
use horizon_client::text::Text;
impl Game<'_> {
/// `Entity.getDisplayName` for the mob `id`: `PlayerTeam.formatNameForTeam`
/// of `getName()`, then `withHoverEvent(createHoverEvent())` (a `ShowEntity`
/// of the type, UUID and name) and `withInsertion(getStringUUID())`. A mob
/// gets its UUID when it joins the level; one without keeps the bare name.
pub(in crate::game) fn mob_command_name(&self, id: u32) -> Text {
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return Text::translate("entity.", &[]);
};
let name = m.command_name();
let shown = match self.mob_team_of(m) {
Some(team) => team.formatted_name(name.clone()),
None => name.clone(),
};
let Some(uuid) = self.persist.uuid_of(id) else {
return shown;
};
let uuid = horizon_client::save::uuid_text(uuid);
let kind = horizon_client::command::args::normalize(&m.kind.id);
shown.with_component_fields(vec![
(
"hover_event".into(),
serde_json::json!({"action": "show_entity", "id": kind, "uuid": uuid,
"name": name.component()}),
),
("insertion".into(), uuid.into()),
])
}
}
@@ -0,0 +1,21 @@
//! The `count` wrapper of an item predicate (`ItemPredicateArgument`): both
//! `count=` and `count~` read the live stack count.
use horizon_world::nbt::Tag;
/// `MinMaxBounds.Ints.matches` on the stack count: an exact Int, or a
/// compound with optional Int `min` and `max`.
pub(super) fn matches(count: impl Into<i64>, want: &Tag) -> bool {
let n = count.into();
match want {
Tag::Compound(_) => {
let get = |k: &str| match want.get(k) {
Some(Tag::Int(i)) => Some(i64::from(*i)),
_ => None,
};
get("min").is_none_or(|m| n >= m) && get("max").is_none_or(|m| n <= m)
}
Tag::Int(i) => n == i64::from(*i),
_ => false,
}
}
@@ -535,6 +535,15 @@ impl Game<'_> {
let Some(stack) = stack.filter(|s| &*s.item != "minecraft:air" && s.count > 0) else {
return true;
};
// SulfurCube.getEquipmentSlotForItem: a swallowable item is a body item.
if let Slot::Mob(id, "body") = s
&& self.mobs.iter().find(|m| m.id == *id).is_some_and(|m| {
m.species() == horizon_client::mobs::Species::SulfurCube
&& horizon_client::mobs::sulfur_cube::swallowable(m, &stack.item)
})
{
return true;
}
self.items()
.get(&stack.item)
.is_some_and(|info| info.equip_slot.as_deref() == Some(name))
@@ -1979,6 +1988,31 @@ mod mob_equipment_command_tests {
}
});
}
/// `SulfurCube.getEquipmentSlotForItem`: a `#sulfur_cube_swallowable`
/// item is a body item, so the body's `SlotAccess` takes it (#12038).
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn a_sulfur_cubes_body_takes_a_swallowable_block() {
with_game(|game| {
assert!(game.run_command("summon sulfur_cube 4.5 200 4.5 {NoAI:1b,Tags:[\"cube\"]}"));
let body = |game: &Game<'_>| {
let m = game
.mobs
.iter()
.find(|m| m.kind.id == "minecraft:sulfur_cube");
m.and_then(|m| m.extra.body.clone())
};
let replace = "item replace entity @e[tag=cube,limit=1] armor.body with";
assert!(game.run_command(&format!("{replace} white_wool")));
assert_eq!(body(game).as_deref(), Some("minecraft:white_wool"));
// An item outside the tag stays out, and the body stays on.
assert!(!game.run_command(&format!("{replace} diamond")));
assert_eq!(body(game).as_deref(), Some("minecraft:white_wool"));
// An empty stack always fits: the body comes off.
assert!(game.run_command(&format!("{replace} air")));
assert_eq!(body(game), None);
});
}
#[test]
#[ignore = "needs prepared resources in HORIZON_TEST_RESOURCES"]
fn effective_item_composition_rejects_before_destination_mutation() {
@@ -770,7 +770,13 @@ impl Game<'_> {
let mut pending = crate::game::spill::Pending::default();
let key = (p[0], p[1], p[2]);
let has_block_entity = if let Some(entity) = self.world.block_entities.get(&key) {
pending.record(p, entity, &name, self.world.block_names.get(&key).cloned());
pending.record(
p,
entity,
&name,
self.world.block_names.get(&key).cloned(),
self.world.block_lock(key),
);
true
} else if let Some(saved) = self.block_entity_nbt(p) {
pending.record_saved(p, &saved);
@@ -520,11 +520,12 @@ impl Game<'_> {
let Some(pos) = self.target_position(t) else {
return Ok(0);
};
let current = self.target_rotation(t);
let mut look_at_target = None;
let rot = if let Some(Arg::Coords(c)) = ctx.get("rotation") {
// Relative parts are offsets from the entity's own rotation.
c.rotation(current)
// RotateCommand.rotate: relative parts are offsets from the command
// source's rotation (WorldCoordinates.getRotation); the entity's own
// rotation cancels out in Entity.forceSetRotation.
c.rotation(self.source_rotation())
} else {
let mut faced_entity = None;
let to = if ctx.has("entity") {
@@ -441,6 +441,15 @@ impl Game<'_> {
}
Ok(Some(json!({ "ok": true, "flat": r.flat_draws() })))
}
"section-layout" => {
let r = self.renderer.as_mut().ok_or("no renderer")?;
let compact = match words.get(1).copied() {
Some("compact") => r.set_packed_layout(true),
Some("wide") => r.set_packed_layout(false),
_ => return Err("section-layout compact|wide".into()),
};
Ok(Some(json!({ "ok": true, "compact": compact })))
}
"section-cull" => {
let r = self.renderer.as_mut().ok_or("no renderer")?;
match words.get(1).copied() {
@@ -325,6 +325,8 @@ fn an_interact_packet_cannot_name_a_mob_the_pick_would_refuse() {
assert!(named_mob_pickable(true, 17, Some(23), Some(29)));
}
#[path = "mob_display_name_tests.rs"]
mod mob_display_name_tests;
#[path = "pet_order_tests.rs"]
mod pet_order_tests;
/// The packet's location is `EntityHitResult.getLocation() -
+37 -3
View File
@@ -261,9 +261,11 @@ fn worn_of(
}
/// The UUID the service knows the player's own model by. On a server, the profile it gave
/// (`profile`). In single player the window's own server (`solo`) names the player by their
/// offline profile, which the service doesn't know: the signed-in account's (`account`) then, only
/// with *Cosmetics in single player* on (`shown`); off, nothing is asked or drawn.
/// (`profile`), but an offline-mode server's is `nameUUIDFromBytes` of the name (version 3), which
/// the service doesn't know: the signed-in account's (`account`) then, as an online server's would
/// be (#12820). Only the own model: another player's name can be anyone's there. In single player
/// the window's own server (`solo`) names the player by their offline profile too: the account's
/// then, only with *Cosmetics in single player* on (`shown`); off, nothing is asked or drawn.
fn own_uuid(
profile: Option<u128>,
solo: bool,
@@ -271,6 +273,7 @@ fn own_uuid(
account: impl FnOnce() -> Option<u128>,
) -> Option<u128> {
match solo {
false if profile.is_some_and(|p| (p >> 76) & 0xf == 3) => account().or(profile),
false => profile,
true if shown && profile.is_some() => account(),
true => None,
@@ -1060,6 +1063,37 @@ mod tests {
assert!(worn.is_none() && asked.is_empty());
}
#[test]
fn an_offline_servers_profile_asks_by_my_account_and_an_online_one_by_its_own() {
const ACCOUNT: u128 = 0x1f2e_3d4c_5b6a_4978_8695_a4b3_c2d1_e0ff;
let offline = horizon_protocol::crypto::offline_uuid("Steve");
let online = 0x069a_79f4_44e9_4726_a5be_fca9_0e38_aaf5;
let signed_in = || Some(ACCOUNT);
// An offline-mode server's profile: the service knows the account, so the account's.
assert_eq!(
own_uuid(Some(offline), false, false, signed_in),
Some(ACCOUNT)
);
// An online server's profile is the account's own already: kept as it is.
assert_eq!(
own_uuid(Some(online), false, false, signed_in),
Some(online)
);
// Signed out: the profile, as before.
assert_eq!(
own_uuid(Some(offline), false, false, || None),
Some(offline)
);
// No profile yet: nothing to ask by.
assert_eq!(own_uuid(None, false, false, signed_in), None);
// Single player still follows its own setting.
assert_eq!(own_uuid(Some(offline), true, false, signed_in), None);
assert_eq!(
own_uuid(Some(offline), true, true, signed_in),
Some(ACCOUNT)
);
}
#[test]
fn single_player_shows_my_cosmetics_only_with_its_setting_and_asks_by_my_account() {
// The window's own server names the player by their offline profile.
@@ -28,8 +28,12 @@ impl Game<'_> {
/// `itemGroup.<mod>.<name>`, else its `title` as a lang key (a mod's own
/// `itemGroup.<mod>`), else `title` as English text.
pub(super) fn creative_tab_title(&self, tab: &horizon_client::creative::Tab) -> String {
if let Some((name, _)) = &tab.name {
return name.clone();
if let Some((name, _, translate)) = &tab.name {
return if *translate {
self.translate(name, name)
} else {
name.clone()
};
}
match horizon_client::creative::item_group_key(&tab.id) {
Some(key) => self.translate(key, &tab.title),
@@ -291,6 +295,13 @@ impl Game<'_> {
if let Some(lines) = effect_tip {
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
}
// CreativeModeInventoryScreen.checkTabHovering: a tab says its name.
if let Some(i) = Creative::hovered_tab(&tabs, (ox, oy), self.cursor)
&& let Some(t) = tabs.get(i)
{
let title = self.creative_tab_title(t);
self.tooltip(batch, &title, self.cursor.0, self.cursor.1);
}
}
pub(super) fn creative_trash_hovered(batch: &HudBatch, cursor: (f32, f32)) -> bool {
let (ox, oy) = Self::creative_origin(batch);
+104 -308
View File
@@ -2,7 +2,10 @@
//! chunk-generation spawning (`NaturalSpawner`), mob events (attacks,
//! breeding, conversions, drops), projectiles, player interactions
//! (feeding, shearing, milking, spawn eggs, throwing) and rendering.
mod bred_draws;
mod mob_geometry;
mod mob_group;
mod prep;
mod projectile_world;
mod pufferfish_player;
mod spawn_eggs;
@@ -1048,18 +1051,11 @@ impl Game<'_> {
teams: std::sync::Arc::new(self.mob_teams()),
items: Some(self.items()),
lid_openers: &self.lid_openers,
mod_effects: if self.remote.is_none() {
Some(self)
} else {
None
},
mod_effects: self.remote.is_none().then_some(self as _),
// A warden's away suspects are UUIDs: on the server side, where the
// entity UUIDs live, they resolve back to the mobs that are here.
who_lookup: if self.remote.is_none() {
Some(self)
} else {
None
},
who_lookup: self.remote.is_none().then_some(self as _),
foreign: None,
border: Some(self.border.geometry()),
// The first player in the level: a server has no player of its own.
difficulty: self.local_difficulty(
@@ -1187,50 +1183,32 @@ impl Game<'_> {
self.init_sulfur_attribute_maps();
let uuid = self.level.player_uuid;
let level_id = self.dim.id();
// LivingEntity.isPushable reads onClimbable live; a mob's cached one
// is only refreshed by its own push step, so one that has not ticked
// yet (the first tick after a load, a fresh spawn) or has moved since
// would be pushed out of a ladder or scaffolding. Refreshed here, from
// where each mob stands now, before the snapshot others push it by.
let climbing: Vec<bool> = {
let w = self.mob_world_base(&[]);
self.mobs.iter().map(|m| m.on_climbable(&w)).collect()
};
for (m, climbing) in self.mobs.iter_mut().zip(climbing) {
m.on_climbable = climbing;
}
// Each mob's climbing, refreshed, and its snapshot entry (creatures/prep.rs).
let mut snapshot = std::mem::take(&mut self.creatures.seen_buf);
snapshot.extend(self.mobs.iter().map(|m| seen(m, uuid)));
self.prepare_mobs(uuid, &mut snapshot);
let mut events = std::mem::take(&mut self.creatures.event_buf);
events.clear();
// SulfurCube.primeWhenOnPoweredPosition runs before super.tick adopts
// the body: the cubes whose adopted body explodes, as this tick starts.
let primable = self.sulfur_cubes_adopted_explosive();
let mut mobs = std::mem::take(&mut self.mobs);
let mobs = std::mem::take(&mut self.mobs);
// Each mob's target as the mods last heard it, by its place in `mobs`
// (`native_living_change_target`).
let mut targets = std::mem::take(&mut self.creatures.target_buf);
targets.clear();
targets.extend(mobs.iter().map(|m| m.ai.target));
let mut dead = Vec::new();
let mut corpses = Vec::new();
let mut died = std::mem::take(&mut self.died);
let died = std::mem::take(&mut self.died);
let mut ticked = std::mem::take(&mut self.creatures.ticked);
ticked.clear();
let ticking = self.entity_ticking_area();
// With guests on, each mob sees its nearest player (game/lan_mobs.rs).
let mut guests = self.lan_guest_views();
// What stands in a guest's slot while a mob holds that guest's view for
// its tick (see `lent` below).
let mut spare = guests.first().map(|g| g.1.clone());
let players = self.level_players();
let nearest = super::natural_spawning::NearestPlayers::new(&players);
let mut bindings = match self.lan.as_mut() {
// With guests on, each mob sees its nearest player (game/lan_mobs.rs).
let guests = self.lan_guest_views();
let bindings = match self.lan.as_mut() {
Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players),
_ => Default::default(),
};
// The guests' entity ids by connection, for the shulker bullets fired
// at the guest a mob sees.
let guest_ids: Vec<(u32, u32)> = match self.lan.as_ref() {
Some(host) if !guests.is_empty() => host
.hub
@@ -1240,23 +1218,9 @@ impl Game<'_> {
.collect(),
_ => Vec::new(),
};
let mut guest_events = Vec::new();
// The block writes since the last tick: mobs re-path around them.
let path_writes = std::mem::take(self.world.path_writes.get_or_insert_with(Vec::new));
// The mobs whose bodies go this tick: (id, feet, width, height, split).
// 🤖 Agent: the last field is the grown slime, magma cube or sulfur
// cube the body leaves behind (`AbstractCubeMob.remove`), captured as
// the body goes because it has left the list by the time it splits.
let mut gone = Vec::new();
let level_random;
{
// The level random, lent to the mobs (brain behaviours draw from
// it) and taken back after their ticks.
let mut scratch = self.world.random.clone();
let mut pushes = horizon_client::mobs::PendingPushes::default();
let mut keep = Vec::with_capacity(mobs.len());
let mut grid =
horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds));
let group = {
// All but the snapshot is the same for every mob of the tick, so
// build it once: the player view and the teams scan every UUID.
self.leash_boats = self
@@ -1266,87 +1230,52 @@ impl Game<'_> {
.collect();
let mut base = self.mob_world_base(&[]);
let path_changes = horizon_client::mobs::collision_changes(&base, &path_writes);
// Each mob keeps its snapshot slot all tick; the first slot of an
// id answers, as a scan would.
let mut index = horizon_client::fast_hash::FxHashMap::with_capacity_and_hasher(
snapshot.len(),
Default::default(),
);
let mut villager_slots = Vec::new();
let mut solid_slots = Vec::new();
for (i, s) in snapshot.iter().enumerate() {
index.entry(s.id).or_insert(i as u32);
if s.species == horizon_client::mobs::Species::Villager {
villager_slots.push(i as u32);
}
if s.may_block_mobs() {
solid_slots.push(i as u32);
}
}
laps.lap("creature_prepare");
let single_player = horizon_client::mobs::single_player_pos(
players.iter().map(|p| (p.position, p.spectator)),
);
let nearest = prep::MobsNearest::new(&nearest, &mobs, single_player.is_none());
let mut despawn_w = base.despawn_view();
let mut cached_difficulty: Option<((i32, i32), spawning::LocalDifficulty)> = None;
for i in 0..mobs.len() {
let m = &mut mobs[i];
let (bx, bz) = (m.position.x.floor() as i32, m.position.z.floor() as i32);
let seen_guest = if guests.is_empty() {
None
} else {
let bound = bindings.get(&m.id).copied();
let conn = super::lan_mobs::player_for(m, base.player.as_ref(), &guests, bound);
match conn {
Some(conn) => {
bindings.insert(m.id, conn);
}
None => {
bindings.remove(&m.id);
}
}
conn
};
let shared = mob_group::Shared {
uuid,
level_id,
path_changes: &path_changes,
guest_ids: &guest_ids,
};
let start = mob_group::Start {
events,
// The level random, lent to the mobs and taken back after their ticks.
random: self.world.random.clone(),
guests,
player: base.player.take(),
bindings,
died,
ticked,
targets,
};
let mut group = mob_group::Group::new(mobs.into(), snapshot, start);
for i in 0..group.mobs.len() {
let position = group.mobs[i].position;
let (bx, bz) = (position.x.floor() as i32, position.z.floor() as i32);
let seen_guest = group.bind_guest(i);
if !base.world.loaded(bx, bz) {
keep.push(!m.hostile() || m.persistent);
group.unloaded(i);
continue;
}
let nearest_player = single_player.unwrap_or_else(|| {
nearest
.nearest(m.position.x, m.position.y, m.position.z)
.map(|p| p.position)
});
let nearest_player = single_player.unwrap_or_else(|| nearest.at(i, position));
// ServerLevel.tick: every loaded entity checks despawning, but
// only those in entity-ticking chunks (within the simulation
// distance) tick. The despawn check reads the nearest player
// and the difficulty, not the player the mob sees.
// distance) tick.
if !ticking(bx, bz) {
despawn_w.nearest_player = nearest_player;
let kept = horizon_client::mobs::ai::despawn_check(m, &despawn_w);
if !kept {
died.remove(&m.id);
snapshot[i].alive = false;
}
keep.push(kept);
group.rest(i, &despawn_w);
continue;
}
let controlling_player_movement = horizon_client::mobs::equine::controlled(m)
.then(|| {
base.player
.as_ref()
.filter(|p| p.riding_vehicle == Some(m.id))
.map(|p| p.velocity)
.or_else(|| {
guests
.iter()
.find(|(_, p)| p.riding_vehicle == Some(m.id))
.map(|(_, p)| p.velocity)
})
})
.flatten();
let controlling = group.controlling(i);
// A mod canceled its tick: it stays as it is.
if round.canceled(m.id) {
keep.push(true);
if round.canceled(group.mobs[i].id) {
group.keep.push(true);
continue;
}
// getCurrentDifficultyAt(blockPosition()): the mob's own chunk,
@@ -1356,175 +1285,34 @@ impl Game<'_> {
Some((key, difficulty)) if key == chunk_key => difficulty,
_ => {
let difficulty =
self.local_difficulty([m.position.x, m.position.y, m.position.z]);
self.local_difficulty([position.x, position.y, position.z]);
cached_difficulty = Some((chunk_key, difficulty));
difficulty
}
};
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
horizon_client::mobs::blocks_changed(m, &path_changes);
let from = events.len();
// The guest's view is lent to the mob for its tick, not copied:
// the tick only reads it (`&MobWorld`), and it goes back to the
// guest's slot straight after.
let lent = seen_guest.and_then(|conn| guests.iter().position(|g| g.0 == conn));
let active_player = match (seen_guest, lent) {
(None, _) => base.player.take(),
(Some(_), Some(k)) => spare
.take()
.map(|stand_in| std::mem::replace(&mut guests[k].1, stand_in)),
(Some(_), None) => None,
};
let mut w = MobWorld {
others: &snapshot,
others_grid: Some(&grid),
others_index: Some(&index),
others_villagers: Some(&villager_slots),
others_solid: Some(&solid_slots),
difficulty,
nearest_player,
player: active_player,
teams: std::sync::Arc::clone(&base.teams),
..base
};
w.controlling_player_movement = controlling_player_movement;
ticked.insert(mobs[i].id);
// `horizon-report`'s cost by mob type (tick_profile.rs).
let sampled = super::tick_profile::start().map(|t| (t, mobs[i].kind.clone()));
let kept =
horizon_client::mobs::riders::tick(&mut mobs, i, &w, &mut scratch, &mut events);
if let Some((started, kind)) = sampled {
super::tick_profile::add(level_id, &kind, started);
}
let m = &mut mobs[i];
if seen_guest.is_none() {
base.player = w.player;
} else if let Some(k) = lent {
spare = w.player.map(|v| std::mem::replace(&mut guests[k].1, v));
}
// Its tick changed its target: the mods may keep the one it had
// (`native_living_change_target`), and then what the tick did to
// the new one is not dealt.
if let Some(&before) = targets.get(i)
&& m.ai.target != before
{
let named = target_named(
m.ai.target,
seen_guest,
&guests,
&guest_ids,
base.player.as_ref(),
);
if let Some((player, mob)) = named {
let kind = super::native_hooks::mob_kind(m);
let mut cancel = false;
Self::native_living_change_target(
level_id,
m.id,
&kind,
player,
mob,
&mut cancel,
);
if cancel {
if let Some(new) = m.ai.target {
let mut k = from;
while k < events.len() {
if hits_target(&events[k], new) {
events.remove(k);
} else {
k += 1;
}
}
}
m.ai.target = before;
}
}
targets[i] = m.ai.target;
}
// A killed mob's body is removed: its effects that act on
// death run (`LivingEntity.remove` with KILLED).
if !kept && !m.alive() && !m.removed && !m.extra.effects.is_empty() {
corpses.push(m.clone());
}
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
// LivingEntity.tickDeath: after twenty ticks the body is removed.
if !kept && !m.removed && !m.alive() && m.death_time >= 20 {
let (width, height) = (f64::from(m.width()), f64::from(m.height()));
// 🤖 Agent: `AbstractCubeMob.remove` splits a grown cube into
// its smaller halves when it is removed, twenty ticks after
// the death. The parent leaves the list before the split
// runs, so its size, position, kind and persistence are
// captured here, as they are at the removal.
let split = if matches!(
m.species(),
Species::Slime | Species::MagmaCube | Species::SulfurCube
) && m.extra.size > 1
{
Some(m.clone())
} else {
None
};
gone.push((m.id, m.position, width, height, split));
}
if let Some(conn) = seen_guest {
// ShulkerBullet.finalTarget is the guest's entity: the
// bullet homes on it while the projectiles tick, where
// `Who::Player` is the host's own player.
if let Some(&(_, id)) = guest_ids.iter().find(|g| g.0 == conn) {
for e in &mut events[from..] {
if let MobEvent::Projectile(p) = e
&& let ProjectileKind::ShulkerBullet { target, .. } = &mut p.kind
&& *target == Some(Who::Player)
{
*target = Some(Who::Mob(id));
}
}
}
let mut k = from;
while k < events.len() {
if super::lan_mobs::acts_on_player(&events[k]) {
guest_events.push((conn, m.id, events.remove(k)));
} else {
k += 1;
}
}
}
// Killed during its own tick (drowning, burning, falling...).
if !m.alive() && !m.removed && died.insert(m.id) {
dead.push(m.clone());
}
if !kept {
died.remove(&m.id);
}
keep.push(kept);
// ServerLevel ticks entities one after another: the ones
// after this mob see it as it is now.
snapshot[i] = seen(m, uuid);
snapshot[i].alive &= kept;
grid.update(i, snapshot[i].bounds);
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
let player = (seen_guest, nearest_player, controlling);
group.tick(i, player, difficulty, &base, &shared);
}
// Targets changed after the mob's own tick (another mob's alert):
// heard now, and a cancel puts the old one back before its next tick.
for (i, m) in mobs.iter_mut().enumerate() {
let Some(&before) = targets.get(i) else {
for (i, m) in group.mobs.iter_mut().enumerate() {
let Some(&before) = group.targets.get(i) else {
break;
};
if m.ai.target == before {
continue;
}
let seen_guest = if guests.is_empty() {
let seen_guest = if group.guests.is_empty() {
None
} else {
bindings.get(&m.id).copied()
group.bindings.get(&m.id).copied()
};
let named = target_named(
m.ai.target,
seen_guest,
&guests,
&group.guests,
&guest_ids,
base.player.as_ref(),
group.player.as_ref(),
);
if let Some((player, mob)) = named {
let kind = super::native_hooks::mob_kind(m);
@@ -1543,13 +1331,29 @@ impl Game<'_> {
}
}
laps.lap("creature_loop");
let mut flags = keep.into_iter();
mobs.retain(|_| flags.next().unwrap_or(true));
for m in &mut mobs {
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
let mut flags = std::mem::take(&mut group.keep).into_iter();
group.mobs.retain(|_| flags.next().unwrap_or(true));
for m in &mut group.mobs {
horizon_client::mobs::apply_mob_pushes(m, &mut group.pushes);
}
level_random = scratch;
}
group
};
let mob_group::Group {
mut mobs,
mut snapshot,
mut events,
random: level_random,
guests,
mut bindings,
died,
ticked,
mut targets,
dead,
corpses,
gone,
guest_events,
..
} = group;
self.world.random = level_random;
if let Some(host) = self.lan.as_mut()
&& !guests.is_empty()
@@ -1565,7 +1369,7 @@ impl Game<'_> {
// first, as `append` put them; with none, the ticked list goes back
// as it is instead of being copied into a new one, every mob a tick.
if self.mobs.is_empty() {
self.mobs = mobs;
self.mobs = mobs.into();
} else {
self.mobs.append(&mut mobs);
}
@@ -3059,7 +2863,7 @@ impl Game<'_> {
// `CrossbowItem.createProjectile`: a rocket, from 0.15 under the eyes.
let mut at = arrow.position;
at.y -= f64::from(0.15f32) - 0.1;
self.launch_angled_rocket(at, arrow.velocity, &ammo, arrow.owner);
self.launch_angled_rocket(at, &ammo, arrow.owner, |_| arrow.velocity);
} else {
Self::arrow_from_ammo(&ammo, &mut arrow);
self.launch_mob_projectile(arrow);
@@ -3869,18 +3673,18 @@ impl Game<'_> {
q.extra.in_love = 0;
}
let q = self.mobs.iter().find(|m| m.id == partner).cloned();
// Animal.finalizeSpawnChildFromBreeding: entity event 18 for the parent.
self.mob_event_particles(parent, 18);
// Animal.finalizeSpawnChildFromBreeding's heart burst, not a turtle's.
if p.species() != Species::Turtle {
self.mob_event_particles(parent, 18);
}
// Sniffer.spawnChildFromBreeding: an egg instead of a baby.
if p.species() == Species::Sniffer {
self.lay_sniffer_egg(&p);
return;
}
// TurtleBreedGoal.breed: the goal gave the mother her egg; only the
// experience is left, and only with mob loot on.
// TurtleBreedGoal.breed and Frog.spawnChildFromBreeding: only experience.
if matches!(p.species(), Species::Turtle | Species::Frog) {
// One `new ExperienceOrb` of 1 to 7 from the mother's random (not
// split up as `ExperienceOrb.award` does).
// One `new ExperienceOrb` of 1 to 7 from the mother's random.
if self.ui.rules.bool("mob_drops")
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent)
{
@@ -3889,9 +3693,7 @@ impl Game<'_> {
}
return;
}
// (Mooshroom draws its own coin in getOffspringVariant.)
let coin = p.species() != Species::Mooshroom
&& self.world.random.next_int_bound(2).unwrap_or(0) == 0;
let coin = self.bred_coat_coin(parent, p.species());
// Axolotl.getBreedOffspring: useRareVariant (one in 1200) makes it blue,
// else either parent's variant. The draws come from the mother's random.
let axolotl = if p.species() == Species::Axolotl {
@@ -3943,7 +3745,7 @@ impl Game<'_> {
// No Mob.finalizeSpawn either: no follow range bonus, right-handed.
spawning::bred_offspring(child);
// getBreedOffspring creates the baby without finalizeSpawn: it keeps
// the default (`classic`) sound variant.
// the default (`classic`) sound variant (a wolf picks its own below).
child.extra.sound_variant = None;
// Fox.getBreedOffspring runs no finalizeSpawn: nothing in the
// baby fox's mouth.
@@ -4058,6 +3860,7 @@ impl Game<'_> {
c.extra.color = mixed;
}
}
self.pick_bred_wolf_voice(parent, id);
self.breeding_orb(parent, [p.position.x, p.position.y, p.position.z]);
return;
}
@@ -4546,6 +4349,7 @@ impl Game<'_> {
// The impacts the mods may cancel (`native_projectile_impact`), on a server.
let hear = self.native_hears_impacts();
let mut impacts: Vec<Impact> = Vec::new();
let mut vehicle_winds = self.vehicle_winds();
{
let targets = self.projectile_targets();
let breezes: Vec<u32> = self
@@ -4653,6 +4457,7 @@ impl Game<'_> {
};
// The projectile as it was, to fly on if a mod cancels its impact.
let before = (hear && !p.stuck).then(|| p.clone());
let wind_before = vehicle_winds.before(p);
let mob_shot = !matches!(p.owner, Some(Who::Player));
// A player's arrows, snowballs and eggs meet every player; a
// guest's flies from that guest (Projectile.getOwner), not
@@ -4787,6 +4592,7 @@ impl Game<'_> {
keep_flags[i] = false;
continue;
}
vehicle_winds.met(wind_before, hit);
if hit != Hit::None {
if let Some(before) = before {
impacts.push(Impact {
@@ -4859,6 +4665,9 @@ impl Game<'_> {
}
self.creatures.projectiles.append(&mut projectiles);
for (p, hit) in hits {
let Some((p, hit)) = self.broken_vehicle_retick(p, hit, &mut vehicle_winds) else {
continue;
};
// A player's arrow on another player lands as the victim's hurt.
if let Some(victim) = self.projectile_pvp_victim(&p, hit) {
self.projectile_hits_player(&p, hit, victim)?;
@@ -4973,17 +4782,6 @@ impl Game<'_> {
8.0,
)
}
/// A projectile's hurt of `amount` on the boat or minecart `id`
/// (`VehicleEntity.hurtServer`): even 0 shakes it (`Snowball`, `ThrownEgg`,
/// `ThrownEnderpearl` `.onHitEntity`), 5 from a small fireball destroys it.
fn hurt_vehicle(&mut self, p: &Projectile, id: u32, amount: f32) {
let creative = p.owner == Some(Who::Player) && self.creative;
if let Some(i) = self.boats.iter().position(|b| b.id == id) {
self.hurt_boat(i, amount, creative);
} else if let Some(i) = self.carts.iter().position(|c| c.id == id) {
self.hurt_cart(i, amount, creative, false);
}
}
/// `BellBlock.onProjectileHit`: a projectile that strikes the bell proper
/// rings it, and a player's shot counts as the player's ring.
fn bell_projectile_hit(
@@ -5168,19 +4966,16 @@ impl Game<'_> {
ArrowEvent::ShootEvent | ArrowEvent::Drop => {}
}
}
/// `Level.isRainingAt` for arrows.
/// The boats, minecarts and primed TNT a projectile can strike
/// (`VehicleEntity.isPickable`, `PrimedTnt.isPickable`).
pub(super) fn pickable_object_targets(&self) -> Vec<(Who, Aabb)> {
let boats = self.boats.iter().map(|b| (Who::Mob(b.id), b.bounds()));
let carts = self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds()));
let tnts = self.tnts.iter().map(|t| (Who::Mob(t.id), t.bounds()));
boats.chain(carts).chain(tnts).collect()
}
/// What a projectile can hit: the mobs, the player, the dragon's parts and
/// the End crystals (under reserved ids, game/dragon.rs).
/// The boats and minecarts a projectile can strike.
pub(super) fn vehicle_targets(&self) -> Vec<(Who, Aabb)> {
let mut targets: Vec<(Who, Aabb)> = self
.boats
.iter()
.map(|b| (Who::Mob(b.id), b.bounds()))
.collect();
targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds())));
targets
}
pub(super) fn projectile_targets(&self) -> Vec<(Who, Aabb)> {
let mut targets: Vec<(Who, Aabb)> = self
.mobs
@@ -5198,9 +4993,9 @@ impl Game<'_> {
.into_iter()
.map(|(id, b)| (Who::Mob(id), b)),
);
// Boats and minecarts are pickable for every projectile
// (`VehicleEntity.isPickable`), so every kind shares this one list.
targets.extend(self.vehicle_targets());
// Boats, minecarts and primed TNT are pickable for every projectile,
// so every kind shares this one list.
targets.extend(self.pickable_object_targets());
targets
}
pub(super) fn arrow_rain(&self) -> impl Fn(BlockPos) -> bool + '_ {
@@ -8376,6 +8171,7 @@ mod pearl_tests {
dragon: None,
leash_boats: &[],
who_lookup: None,
foreign: None,
others_grid: None,
others_index: None,
others_villagers: None,
@@ -0,0 +1,148 @@
//! The breeding parent's own random in `getBreedOffspring`: the offspring's
//! coat coin and a wolf pup's voice.
use super::super::Game;
use horizon_client::mobs::Species;
use horizon_core::random::RandomSource;
impl Game<'_> {
/// Cow, Pig, Chicken, Fox, Cat and Wolf.getBreedOffspring: the offspring's
/// variant coin is the breeding parent's own first draw, not the level's.
/// (Mooshroom draws its own coin in getOffspringVariant.)
pub(super) fn bred_coat_coin(&mut self, parent: u32, species: Species) -> bool {
matches!(
species,
Species::Cow
| Species::Pig
| Species::Chicken
| Species::Fox
| Species::Cat
| Species::Wolf
) && self
.mobs
.iter_mut()
.find(|m| m.id == parent)
.is_some_and(|m| m.random.next_boolean())
}
/// WolfSoundVariants.pickRandomSoundVariant: Registry.getRandom over the
/// wolf voice registry, from the parent's own random, after the collar
/// colour's mix.
pub(super) fn pick_bred_wolf_voice(&mut self, parent: u32, child: u32) {
let voices = horizon_client::mobs::finalize::sound_variants(Species::Wolf);
let voice = self.mobs.iter_mut().find(|m| m.id == parent).and_then(|m| {
let i = m.random.next_int_bound(voices.len() as i32).ok()?;
Some(i as u8)
});
if let Some(c) = self.mobs.iter_mut().find(|m| m.id == child) {
c.extra.sound_variant = voice;
}
}
}
#[cfg(test)]
mod tests {
use super::super::*;
/// `Cow`, `Pig`, `Chicken`, `Fox`, `Cat` and `Wolf.getBreedOffspring` draw
/// the offspring's coat from the breeding parent's own random, and only a
/// wolf picks a voice there (`WolfSoundVariants.pickRandomSoundVariant`,
/// that same random, after the collar colour's mix). The level's random
/// answers neither: two runs that differ only in the level's seed must
/// agree, and the parent's stream must read as vanilla's own draws in
/// vanilla's order.
#[test]
#[ignore = "needs prepared resources (HORIZON_TEST_RESOURCES)"]
fn a_pup_takes_its_coat_and_voice_from_the_parents_own_random() {
use horizon_core::random::{LegacyRandom, RandomSource};
// The voice registry, not a hardcoded count of wolf voices.
let voices = horizon_client::mobs::finalize::sound_variants(Species::Wolf).len() as i32;
assert!(voices > 1, "a wolf has several voices");
let cases = [
("minecraft:wolf", 2u8, 8u8),
("minecraft:wolf", 6, 0),
("minecraft:cow", 1, 0),
("minecraft:pig", 2, 0),
("minecraft:chicken", 0, 1),
("minecraft:fox", 1, 0),
("minecraft:cat", 4, 0),
];
let mut heard = std::collections::BTreeSet::new();
// One server game: its resources load once, and only the level's seed
// and the pair change between runs.
let mut game = super::super::super::native_machines::tests::server_game();
for (n, &(kind, own, mate)) in cases.iter().enumerate() {
// Independent entity randoms, kept clear of the ids the spawner
// hands out: the parent is `part`, the partner `mate_id`.
let parent_seed = 4_242 + 1_009 * n as i64;
let mut outcomes = Vec::new();
for (r, level_seed) in [11i64, 2_000_003].into_iter().enumerate() {
game.world.random = LegacyRandom::new(level_seed);
game.mobs.clear();
let (part, mate_id) = (7u32, 8u32);
// Ids the spawner hands out stay clear of the pair's.
game.next_entity = 1_000 + 10 * n as u32 + 2 * r as u32;
let t = game
.res
.mob_types()
.get(kind)
.unwrap_or_else(|| panic!("a {kind}"))
.clone();
for (id, variant) in [(part, own), (mate_id, mate)] {
let mut m = Mob::new(id, t.clone(), Vec3::new(8.5, 64.0, 8.5), 0.0);
m.random = LegacyRandom::new(parent_seed + i64::from(id));
m.extra.variant = variant;
m.extra.in_love = 600;
game.mobs.push(m);
}
game.breed(part, mate_id, None);
let child = game
.mobs
.iter()
.find(|m| m.id != part && m.id != mate_id)
.unwrap_or_else(|| panic!("{kind}: a pup"));
assert_eq!(child.extra.age, -24000, "{kind}: a baby");
// What the parent's own stream answers, draw for draw.
let mut expected = LegacyRandom::new(parent_seed + i64::from(part));
let coin = expected.next_boolean();
let coat = if coin { own } else { mate };
let voice = (kind == "minecraft:wolf").then(|| {
let i = expected.next_int_bound(voices).unwrap() as u8;
heard.insert(i);
i
});
assert_eq!(
child.extra.variant, coat,
"{kind}: the parent's coin picks the coat (level seed {level_seed})"
);
assert_eq!(
child.extra.sound_variant, voice,
"{kind}: the parent's next draw picks the voice (level seed {level_seed})"
);
// The stream ends where vanilla's does: the coin, a wolf's
// voice, then finalizeSpawnChildFromBreeding's 1-to-7 roll.
if game.ui.rules.bool("mob_drops") {
let _ = expected.next_int_bound(7);
}
let mut parent = game
.mobs
.iter()
.find(|m| m.id == part)
.unwrap()
.random
.clone();
for _ in 0..4 {
assert_eq!(
parent.next_int(),
expected.next_int(),
"{kind}: the parent's stream goes on where vanilla leaves it"
);
}
outcomes.push((child.extra.variant, child.extra.sound_variant));
}
assert_eq!(
outcomes[0], outcomes[1],
"{kind}: the level's seed does not decide the pup"
);
}
assert!(heard.len() > 1, "the wolf's voices vary: {heard:?}");
}
}
@@ -0,0 +1,338 @@
//! The mob loop of `tick_creature_entities` over a group of mobs, in their list order, with
//! everything the loop keeps for them: their snapshot and its indexes, the pushes and events
//! their ticks give, the level random they draw from, the players they see and what dies. The
//! serial loop is one group holding every mob; a group of the parallel mob tick (#14457) holds
//! the mobs no mob outside it can reach this tick.
use super::*;
use horizon_client::{
fast_hash::{FxHashMap, FxHashSet},
mobs::{MobSlot, PendingPushes, seen_grid::SeenGrid, spawning::LocalDifficulty},
};
use horizon_core::random::LegacyRandom;
/// What every mob of the loop reads and none writes.
pub(super) struct Shared<'a> {
pub uuid: Option<[i32; 4]>,
pub level_id: &'static str,
/// The blocks whose collision changed since the last tick: mobs re-path around them.
pub path_changes: &'a [[i32; 3]],
/// The guests' entity ids by connection, for the shulker bullets fired at the guest a mob
/// sees.
pub guest_ids: &'a [(u32, u32)],
}
/// A mob whose body goes this tick: (id, feet, width, height, the grown cube it splits into).
/// The last field is the grown slime, magma cube or sulfur cube the body leaves behind
/// (`AbstractCubeMob.remove`), captured as the body goes because it has left the list by the
/// time it splits.
pub(super) type Gone = (u32, Vec3, f64, f64, Option<Mob>);
/// A group's mobs and everything the loop keeps for them, in their list order.
pub(super) struct Group<M: MobSlot> {
pub mobs: Vec<M>,
/// Each mob's snapshot entry: as it was before the tick until its turn, as its turn left it
/// after.
pub snapshot: Vec<Seen>,
grid: SeenGrid,
/// The first slot of each id, as a scan would find it.
index: FxHashMap<u32, u32>,
villager_slots: Vec<u32>,
solid_slots: Vec<u32>,
pub pushes: PendingPushes,
pub events: Vec<MobEvent>,
/// The level random, lent to the mobs (brain behaviours draw from it).
pub random: LegacyRandom,
pub guests: super::super::lan_mobs::GuestViews,
/// What stands in a guest's slot while a mob holds that guest's view for its tick.
spare: Option<PlayerView>,
/// The host's own player, lent to each mob that sees it for its tick.
pub player: Option<PlayerView>,
/// The guest each mob sees, by mob id.
pub bindings: FxHashMap<u32, u32>,
pub died: FxHashSet<u32>,
pub ticked: FxHashSet<u32>,
/// Each mob's target as the mods last heard it (`native_living_change_target`).
pub targets: Vec<Option<Who>>,
/// Whether each mob stays in the list, pushed at its turn.
pub keep: Vec<bool>,
pub dead: Vec<Mob>,
pub corpses: Vec<Mob>,
pub gone: Vec<Gone>,
pub guest_events: Vec<(u32, u32, MobEvent)>,
}
/// What a group starts from besides its mobs and their snapshot.
pub(super) struct Start {
pub events: Vec<MobEvent>,
pub random: LegacyRandom,
pub guests: super::super::lan_mobs::GuestViews,
pub player: Option<PlayerView>,
pub bindings: FxHashMap<u32, u32>,
pub died: FxHashSet<u32>,
pub ticked: FxHashSet<u32>,
pub targets: Vec<Option<Who>>,
}
impl<M: MobSlot> Group<M> {
/// A group of `mobs`, whose snapshot entries are `snapshot`.
pub(super) fn new(mobs: Vec<M>, snapshot: Vec<Seen>, start: Start) -> Self {
let grid = SeenGrid::new(snapshot.iter().map(|s| s.bounds));
let mut index = FxHashMap::with_capacity_and_hasher(snapshot.len(), Default::default());
let (mut villager_slots, mut solid_slots) = (Vec::new(), Vec::new());
for (i, s) in snapshot.iter().enumerate() {
index.entry(s.id).or_insert(i as u32);
if s.species == Species::Villager {
villager_slots.push(i as u32);
}
if s.may_block_mobs() {
solid_slots.push(i as u32);
}
}
let n = mobs.len();
Self {
spare: start.guests.first().map(|g| g.1.clone()),
mobs,
snapshot,
grid,
index,
villager_slots,
solid_slots,
pushes: PendingPushes::default(),
events: start.events,
random: start.random,
guests: start.guests,
player: start.player,
bindings: start.bindings,
died: start.died,
ticked: start.ticked,
targets: start.targets,
keep: Vec::with_capacity(n),
dead: Vec::new(),
corpses: Vec::new(),
gone: Vec::new(),
guest_events: Vec::new(),
}
}
/// The guest mob `i` sees now, kept in the bindings: none while no guest is on.
pub(super) fn bind_guest(&mut self, i: usize) -> Option<u32> {
if self.guests.is_empty() {
return None;
}
let m = self.mobs[i].mob();
let bound = self.bindings.get(&m.id).copied();
let conn = super::super::lan_mobs::player_for(m, self.player.as_ref(), &self.guests, bound);
match conn {
Some(conn) => self.bindings.insert(m.id, conn),
None => self.bindings.remove(&m.id),
};
conn
}
/// Mob `i`'s turn when its chunk isn't loaded: it is kept as it is, unless it would despawn.
pub(super) fn unloaded(&mut self, i: usize) {
let m = self.mobs[i].mob();
self.keep.push(!m.hostile() || m.persistent);
}
/// Mob `i`'s turn outside the entity-ticking area: only its despawn check, which reads the
/// nearest player and the difficulty, not the player the mob sees.
pub(super) fn rest(&mut self, i: usize, despawn_w: &MobWorld) {
let m = self.mobs[i].mob_mut();
let kept = horizon_client::mobs::ai::despawn_check(m, despawn_w);
if !kept {
self.died.remove(&m.id);
self.snapshot[i].alive = false;
}
self.keep.push(kept);
}
/// Who controls mob `i`'s moves this tick: the velocity of the player riding it, when it is
/// a controlled mount.
pub(super) fn controlling(&self, i: usize) -> Option<Vec3> {
let m = self.mobs[i].mob();
horizon_client::mobs::equine::controlled(m)
.then(|| {
self.player
.as_ref()
.filter(|p| p.riding_vehicle == Some(m.id))
.map(|p| p.velocity)
.or_else(|| {
self.guests
.iter()
.find(|(_, p)| p.riding_vehicle == Some(m.id))
.map(|(_, p)| p.velocity)
})
})
.flatten()
}
/// Mob `i`'s own tick, then what the loop does with what it did. `players`: the guest it
/// sees (none: the host's player), its nearest player, and the velocity of the player
/// controlling it as a mount ([`Self::controlling`]).
pub(super) fn tick(
&mut self,
i: usize,
(seen_guest, nearest_player, controlling_player_movement): (
Option<u32>,
Option<Vec3>,
Option<Vec3>,
),
difficulty: LocalDifficulty,
base: &MobWorld,
shared: &Shared,
) {
let m = self.mobs[i].mob_mut();
horizon_client::mobs::apply_mob_pushes(m, &mut self.pushes);
horizon_client::mobs::blocks_changed(m, shared.path_changes);
let from = self.events.len();
// The guest's view is lent to the mob for its tick, not copied:
// the tick only reads it (`&MobWorld`), and it goes back to the
// guest's slot straight after.
let lent = seen_guest.and_then(|conn| self.guests.iter().position(|g| g.0 == conn));
let active_player = match (seen_guest, lent) {
(None, _) => self.player.take(),
(Some(_), Some(k)) => self
.spare
.take()
.map(|stand_in| std::mem::replace(&mut self.guests[k].1, stand_in)),
(Some(_), None) => None,
};
let mut w = MobWorld {
others: &self.snapshot,
others_grid: Some(&self.grid),
others_index: Some(&self.index),
others_villagers: Some(&self.villager_slots),
others_solid: Some(&self.solid_slots),
difficulty,
nearest_player,
player: active_player,
teams: std::sync::Arc::clone(&base.teams),
..*base
};
w.controlling_player_movement = controlling_player_movement;
self.ticked.insert(self.mobs[i].mob().id);
// `horizon-report`'s cost by mob type (tick_profile.rs).
let sampled =
super::super::tick_profile::start().map(|t| (t, self.mobs[i].mob().kind.clone()));
let kept = horizon_client::mobs::riders::tick(
&mut self.mobs,
i,
&w,
&mut self.random,
&mut self.events,
);
if let Some((started, kind)) = sampled {
super::super::tick_profile::add(shared.level_id, &kind, started);
}
let m = self.mobs[i].mob_mut();
if seen_guest.is_none() {
self.player = w.player;
} else if let Some(k) = lent {
self.spare = w
.player
.map(|v| std::mem::replace(&mut self.guests[k].1, v));
}
// Its tick changed its target: the mods may keep the one it had
// (`native_living_change_target`), and then what the tick did to
// the new one is not dealt.
if let Some(&before) = self.targets.get(i)
&& m.ai.target != before
{
let named = target_named(
m.ai.target,
seen_guest,
&self.guests,
shared.guest_ids,
self.player.as_ref(),
);
if let Some((player, mob)) = named {
let kind = super::super::native_hooks::mob_kind(m);
let mut cancel = false;
Game::native_living_change_target(
shared.level_id,
m.id,
&kind,
player,
mob,
&mut cancel,
);
if cancel {
if let Some(new) = m.ai.target {
let mut k = from;
while k < self.events.len() {
if hits_target(&self.events[k], new) {
self.events.remove(k);
} else {
k += 1;
}
}
}
m.ai.target = before;
}
}
self.targets[i] = m.ai.target;
}
// A killed mob's body is removed: its effects that act on
// death run (`LivingEntity.remove` with KILLED).
if !kept && !m.alive() && !m.removed && !m.extra.effects.is_empty() {
self.corpses.push(m.clone());
}
horizon_client::mobs::take_mob_pushes(&mut self.events, from, &mut self.pushes);
// LivingEntity.tickDeath: after twenty ticks the body is removed.
if !kept && !m.removed && !m.alive() && m.death_time >= 20 {
let (width, height) = (f64::from(m.width()), f64::from(m.height()));
// `AbstractCubeMob.remove` splits a grown cube into its smaller halves when it is
// removed, twenty ticks after the death. The parent leaves the list before the split
// runs, so its size, position, kind and persistence are captured here, as they are
// at the removal.
let split = if matches!(
m.species(),
Species::Slime | Species::MagmaCube | Species::SulfurCube
) && m.extra.size > 1
{
Some(m.clone())
} else {
None
};
self.gone.push((m.id, m.position, width, height, split));
}
if let Some(conn) = seen_guest {
// ShulkerBullet.finalTarget is the guest's entity: the
// bullet homes on it while the projectiles tick, where
// `Who::Player` is the host's own player.
if let Some(&(_, id)) = shared.guest_ids.iter().find(|g| g.0 == conn) {
for e in &mut self.events[from..] {
if let MobEvent::Projectile(p) = e
&& let ProjectileKind::ShulkerBullet { target, .. } = &mut p.kind
&& *target == Some(Who::Player)
{
*target = Some(Who::Mob(id));
}
}
}
let mut k = from;
while k < self.events.len() {
if super::super::lan_mobs::acts_on_player(&self.events[k]) {
self.guest_events.push((conn, m.id, self.events.remove(k)));
} else {
k += 1;
}
}
}
// Killed during its own tick (drowning, burning, falling...).
if !m.alive() && !m.removed && self.died.insert(m.id) {
self.dead.push(m.clone());
}
if !kept {
self.died.remove(&m.id);
}
self.keep.push(kept);
// ServerLevel ticks entities one after another: the ones
// after this mob see it as it is now.
self.snapshot[i] = seen(m, shared.uuid);
self.snapshot[i].alive &= kept;
self.grid.update(i, self.snapshot[i].bounds);
horizon_client::mobs::apply_brain_events(&mut self.mobs, &mut self.events, from);
}
}
@@ -0,0 +1,247 @@
//! What the mob loop (`tick_creature_entities`) prepares for every mob before it runs, on the tick's
//! helper threads while the parallel tick is on (`horizon_client::parallel`): each answer reads only
//! that mob, the blocks and the players, so the helpers give what one thread gives.
use super::super::{Game, natural_spawning::NearestPlayers};
use horizon_client::mobs::{Mob, MobWorld, Seen};
use horizon_client::parallel::par_map;
use horizon_core::geometry::Vec3;
/// From this many mobs a preparation goes to the helper threads.
const MIN_MOBS: usize = 256;
impl Game<'_> {
/// `LivingEntity.isPushable` reads onClimbable live; a mob's cached one is only refreshed by its
/// own push step, so one that has not ticked yet (the first tick after a load, a fresh spawn) or
/// has moved since would be pushed out of a ladder or scaffolding. Refreshed here, from where
/// each mob stands now; then each mob's entry of the snapshot others push it by goes in
/// `snapshot`.
pub(super) fn prepare_mobs(&mut self, player: Option<[i32; 4]>, snapshot: &mut Vec<Seen>) {
let climbing: Vec<bool> = {
let w = self.mob_world_base(&[]);
let rebuild = hookless(&w);
par_map(&self.mobs, MIN_MOBS, |part, out| {
let w = rebuild();
out.extend(part.iter().map(|m| m.on_climbable(&w)));
})
};
for (m, climbing) in self.mobs.iter_mut().zip(climbing) {
m.on_climbable = climbing;
}
snapshot.extend(par_map(&self.mobs, MIN_MOBS, |part, out| {
out.extend(part.iter().map(|m| super::seen(m, player)));
}));
}
}
/// The nearest player each mob's despawn check reads (`Mob.checkDespawn`), found for every mob before
/// the loop. A mob that moved before its turn is asked again where it stands.
pub(super) struct MobsNearest<'p> {
players: &'p NearestPlayers<'p>,
/// Each mob's position as the loop started and its nearest player there; empty while the
/// parallel tick is off (every mob asks at its turn).
found: Vec<(Vec3, Option<Vec3>)>,
}
impl<'p> MobsNearest<'p> {
/// `wanted`: whether the loop asks (not with one player, whose position answers).
pub(super) fn new(players: &'p NearestPlayers<'p>, mobs: &[Mob], wanted: bool) -> Self {
let found = if wanted && horizon_client::parallel::lanes() > 1 {
par_map(mobs, MIN_MOBS, |part, out| {
out.extend(
part.iter()
.map(|m| (m.position, Self::ask(players, m.position))),
);
})
} else {
Vec::new()
};
Self { players, found }
}
fn ask(players: &NearestPlayers, at: Vec3) -> Option<Vec3> {
players.nearest(at.x, at.y, at.z).map(|p| p.position)
}
/// The nearest player to mob `i` of the loop, standing at `at`.
pub(super) fn at(&self, i: usize, at: Vec3) -> Option<Vec3> {
match self.found.get(i) {
Some(&(was, nearest)) if was == at => nearest,
_ => Self::ask(self.players, at),
}
}
}
/// `base` without its hooks into the game, which can't leave the server thread, as a recipe a
/// helper thread builds its own world from: native mod effects (the phases on helpers don't run
/// them) and the UUID lookup.
fn hookless<'w>(base: &MobWorld<'w>) -> impl Fn() -> MobWorld<'w> + Sync + use<'w> {
// Every field but the two hooks, named, so that a field added to `MobWorld` is decided here.
let MobWorld {
world,
registry,
facts,
fluid_tables,
movement,
collision,
suffocation,
data,
player,
controlling_player_movement,
nearest_player,
others,
dragon,
leash_boats,
others_grid,
others_index,
others_villagers,
others_solid,
daylight,
monsters_burn,
game_time,
day_time,
raining,
thundering,
level,
block_tags,
landing,
biomes,
mob_griefing,
universal_anger,
mob_drops,
max_entity_cramming,
difficulty,
dimension_type,
world_seed,
sea_level,
teams,
items,
lid_openers,
mod_effects: _,
who_lookup: _,
foreign: _,
border,
} = base.clone();
move || MobWorld {
world,
registry,
facts,
fluid_tables,
movement,
collision,
suffocation,
data,
player: player.clone(),
controlling_player_movement,
nearest_player,
others,
dragon,
leash_boats,
others_grid,
others_index,
others_villagers,
others_solid,
daylight,
monsters_burn,
game_time,
day_time,
raining,
thundering,
level,
block_tags,
landing,
biomes,
mob_griefing,
universal_anger,
mob_drops,
max_entity_cramming,
difficulty,
dimension_type,
world_seed,
sea_level,
teams: std::sync::Arc::clone(&teams),
items,
lid_openers,
mod_effects: None,
who_lookup: None,
foreign: None,
border,
}
}
#[cfg(test)]
mod tests {
use super::super::super::natural_spawning::LevelPlayer;
use super::*;
use horizon_core::geometry::Aabb;
#[test]
#[ignore = "needs prepared resources and scratch homes/cwd"]
fn preparation_refreshes_climbing_and_nearest_after_a_move() {
let mut game = super::super::super::native_machines::tests::server_game();
game.build_registries();
game.set_allow_commands(true);
for command in [
"setblock 8 80 9 stone",
"setblock 8 80 8 ladder[facing=north]",
"summon pig 8.5 80 8.5 {NoAI:1b}",
"summon pig 9.5 80 8.5 {NoAI:1b}",
] {
assert!(game.run_command(command), "{command}");
}
assert_eq!(game.mobs.len(), 2);
let examples = game.mobs.clone();
game.mobs = (0..MIN_MOBS + 37)
.map(|i| {
let mut mob = examples[i % 2].clone();
mob.id = 10_000 + i as u32;
mob.on_climbable = i % 2 != 0; // deliberately stale in both cases
mob
})
.collect::<Vec<_>>()
.into();
let mut snapshot = Vec::new();
game.prepare_mobs(None, &mut snapshot);
assert_eq!(snapshot.len(), game.mobs.len());
for (i, (m, seen)) in game.mobs.iter().zip(&snapshot).enumerate() {
assert_eq!(m.on_climbable, i % 2 == 0, "mob {i}");
assert_eq!(seen.id, m.id);
assert_eq!(seen.position, m.position);
assert_eq!(seen.pushable, i % 2 != 0, "snapshot {i}");
}
let player = |x, spectator| {
let position = Vec3::new(x, 80.0, 8.5);
LevelPlayer {
uuid: 0,
position,
bounds: Aabb::new(position, position),
alive: false, // dead players still count for checkDespawn
creative: false,
spectator,
}
};
let players = [player(8.5, true), player(7.5, false), player(9.5, false)];
let index = NearestPlayers::new(&players);
let nearest = MobsNearest::new(&index, &game.mobs, true);
for (i, mob) in game.mobs.iter().enumerate() {
let expected = if i % 2 == 0 {
players[1].position
} else {
players[2].position
};
assert_eq!(nearest.at(i, mob.position), Some(expected));
// A previous mob's push moved this mob across the nearest-player tie.
assert_eq!(
nearest.at(i, Vec3::new(10.0, 80.0, 8.5)),
Some(players[2].position)
);
}
let no_cache = MobsNearest::new(&index, &game.mobs, false);
assert_eq!(
no_cache.at(0, game.mobs[0].position),
Some(players[1].position)
);
let spectators = [player(8.5, true)];
let index = NearestPlayers::new(&spectators);
let nearest = MobsNearest::new(&index, &game.mobs, true);
assert_eq!(nearest.at(0, game.mobs[0].position), None);
}
}
@@ -47,6 +47,9 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
fn in_water(&self, bounds: Aabb) -> bool {
self.w.fluids(bounds, bounds.max_position().y).in_water
}
fn pushed_by_currents(&self, bounds: Aabb, velocity: Vec3) -> Vec3 {
self.w.pushed_by_currents(bounds, velocity)
}
fn targets(&self) -> &[(Who, Aabb)] {
&self.targets
}
Loaded 100 of 407 files, more files were not shown because too many files have changed in this diff. Show more