Merge remote-tracking branch 'origin/fix/st2-entity-hands' into mm1-1420
# Conflicts: # tools/lan_e2e.py
This commit is contained in:
@@ -6,7 +6,6 @@
|
||||
/.github/ @ludovic111
|
||||
/tools/ci/ @ludovic111
|
||||
/tools/release_train.py @ludovic111
|
||||
/tools/release_channels.py @ludovic111
|
||||
/crates/horizon-release-sign/ @ludovic111
|
||||
/crates/horizon-server/src/update.rs @ludovic111
|
||||
/crates/horizon-server/Cargo.toml @ludovic111
|
||||
|
||||
@@ -64,9 +64,13 @@ jobs:
|
||||
cargo +stable clippy --workspace --all-targets -- -D warnings
|
||||
# The server build (released as horizon-engine): the game without sound or controllers.
|
||||
cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings
|
||||
# Libraries, binaries and integration tests, then doc tests: not the ~275 examples, which clippy above already
|
||||
# type-checks and the parity job builds and runs (they were most of this step's build and link time).
|
||||
- name: Test Rust core and voxel kernel correctness
|
||||
if: steps.rust.outputs.required != 'false'
|
||||
run: cargo +stable test --workspace
|
||||
run: |
|
||||
cargo +stable test --workspace --lib --bins --tests
|
||||
cargo +stable test --workspace --doc
|
||||
parity:
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: ./.github/workflows/parity.yml
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
name: promote
|
||||
# Beta game releases become stable once a day (docs/release-flow.md, "Channels"): at 20:00 UTC (21:00 in Paris in
|
||||
# winter time, 22:00 in summer) tools/release_channels.py promotes the newest beta that had been out 6 hours by then,
|
||||
# passed its release smoke test and isn't covered by an issue labelled release-blocker. Launchers on the Alpha
|
||||
# channel install every beta when it is published; Stable gets the day's promotion. The later runs of the evening are
|
||||
# retries for a run GitHub starts late or skips: they promote the same beta, so stable still moves once.
|
||||
# By hand, from GitHub's app too (Actions > promote > Run workflow):
|
||||
# gh workflow run promote -f tag=v0.2.3 # that beta now, without waiting for 20:00
|
||||
# gh workflow run promote -f tag=v0.2.3 -f force=true # even blocked or without its smoke test
|
||||
# gh workflow run promote -f dry_run=true # say what would be promoted
|
||||
# Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it
|
||||
# still holds the betas published before it closed. The issue's text is never read (its author could edit it).
|
||||
# When the oldest waiting beta is 30 hours old (it missed a promotion it was due for), an issue "Promotion to stable
|
||||
# has stalled" says so; it closes itself after the next promotion.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '7,37 20-21 * * *'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: The beta to promote now (empty = the newest beta that is due)
|
||||
type: string
|
||||
default: ''
|
||||
force:
|
||||
description: Promote that tag even if a release-blocker covers it or its smoke test didn't run
|
||||
type: boolean
|
||||
default: false
|
||||
dry_run:
|
||||
description: Say what would be promoted, change nothing
|
||||
type: boolean
|
||||
default: false
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
concurrency:
|
||||
group: promote
|
||||
cancel-in-progress: false
|
||||
jobs:
|
||||
promote:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
# The notes of a promoted release cover every pull request since the last stable one.
|
||||
fetch-depth: 0
|
||||
# gh uses GH_TOKEN below; nothing needs git credentials on disk.
|
||||
persist-credentials: false
|
||||
- name: Promote
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
FORCE: ${{ inputs.force && 'yes' || '' }}
|
||||
DRY_RUN: ${{ (inputs.dry_run || github.ref != 'refs/heads/main') && 'yes' || '' }}
|
||||
run: python3 tools/release_channels.py promote ${TAG:+--tag "$TAG"} ${FORCE:+--force} ${DRY_RUN:+--dry-run}
|
||||
@@ -3,12 +3,15 @@ name: release
|
||||
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides:
|
||||
# a release when pull requests merged since the last one changed what players run and the newest merged 5 minutes
|
||||
# ago (the oldest 20 minutes ago, if merges never pause), or at once for a pull request labelled release-now.
|
||||
# RELEASES_PAUSED=1 (repository variable) stops them.
|
||||
# RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too.
|
||||
# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and
|
||||
# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then
|
||||
# publishes vX.Y.Z on the release line in .github/release-line.txt (docs/versioning.md; without it, the dated
|
||||
# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes
|
||||
# stable in its daily promotion. macOS: with the repository variable MACOS_SIGN_IDENTITY set, the programs are signed with
|
||||
# vYYYY.MM.DD[.N] from before 0.2) with notes from the merged pull requests, as the release and GitHub's latest: one
|
||||
# channel, which launchers, `horizon-server update` and install.sh follow at once. So it is published only after the
|
||||
# checks that used to gate a promotion pass in this run: the Mac mini's smoke test drew a world, and no release-blocker
|
||||
# is open (tools/release_train.py gate); otherwise nothing is published. macOS: with the repository variable
|
||||
# MACOS_SIGN_IDENTITY set, the programs are signed with
|
||||
# Developer ID and the hardened runtime and the zip is notarized, from the runner's signing keychain
|
||||
# (packaging/macos/README.md); unset (forks), ad hoc.
|
||||
# gh workflow run release --ref <branch> # dry run: builds and notes, publishes nothing
|
||||
@@ -32,6 +35,8 @@ on:
|
||||
default: false
|
||||
permissions:
|
||||
contents: read
|
||||
# The open release-blocker issues (decide).
|
||||
issues: read
|
||||
concurrency:
|
||||
group: game-release
|
||||
cancel-in-progress: false
|
||||
@@ -203,7 +208,7 @@ jobs:
|
||||
or not report.get("meshed_sections") or not report.get("player"):
|
||||
sys.exit("the smoke run did not draw a world")
|
||||
EOF
|
||||
# Published with the release: a beta becomes stable only with it (tools/release_channels.py).
|
||||
# Published with the release; the publish job checks it again before it publishes anything.
|
||||
cp "$home/smoke.json" "$RUNNER_TEMP/smoke-test.json"
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: runner.environment == 'self-hosted'
|
||||
@@ -319,6 +324,7 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: write
|
||||
issues: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -341,6 +347,17 @@ jobs:
|
||||
run: |
|
||||
key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)")
|
||||
cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist
|
||||
- name: Ready to publish (the smoke test passed, no release-blocker is open)
|
||||
# Right before publishing: an issue labelled while the builds ran still holds this release. A dry run only
|
||||
# reports what a real run would do.
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
DRY_RUN: ${{ needs.decide.outputs.dry_run }}
|
||||
run: |
|
||||
if ! python3 tools/release_train.py gate --kind game --smoke dist/smoke-test.json --blockers; then
|
||||
[[ "$DRY_RUN" == true ]] || { echo "::error::Nothing published"; exit 1; }
|
||||
echo "::warning::A real run would publish nothing"
|
||||
fi
|
||||
- name: Publish ${{ needs.decide.outputs.tag }}
|
||||
if: needs.decide.outputs.dry_run != 'true'
|
||||
env:
|
||||
@@ -348,17 +365,15 @@ jobs:
|
||||
TAG: ${{ needs.decide.outputs.tag }}
|
||||
run: |
|
||||
signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig)
|
||||
smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json)
|
||||
# A beta (pre-release), the Alpha channel's: promote.yml makes it stable and latest in its daily promotion
|
||||
# (docs/release-flow.md).
|
||||
# The release and the latest at once: there is one channel (docs/release-flow.md).
|
||||
gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \
|
||||
--notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \
|
||||
--notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz \
|
||||
dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \
|
||||
dist/SHA256SUMS "${signature[@]}" "${smoke[@]}"
|
||||
dist/SHA256SUMS "${signature[@]}" dist/smoke-test.json
|
||||
- name: Dry run, the release that would be published
|
||||
if: needs.decide.outputs.dry_run == 'true'
|
||||
run: |
|
||||
echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)"
|
||||
echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }} as the release and latest: $(cat notes/title.txt)"
|
||||
ls -l dist
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
# Horizon: a map for agents
|
||||
|
||||
Minecraft: Java Edition 26.3 rewritten in Rust (wgpu). Vanilla is the specification wherever it has the
|
||||
feature. Read [CONTRIBUTING.md](CONTRIBUTING.md) once; this page tells you where things are.
|
||||
Feature → files → harness for the most-changed areas: [docs/architecture.md](docs/architecture.md).
|
||||
|
||||
## Rules that bite
|
||||
|
||||
- **Never commit Mojang's files**: game jars, assets, decompiled source, prepared resources (`.local/`).
|
||||
`tools/check_public_tree.py` rejects them; `git config core.hooksPath .githooks` runs it on commit.
|
||||
- **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d`
|
||||
folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and
|
||||
`XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`. Never write to
|
||||
`~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`.
|
||||
- **Mark what an agent posts.** A PR body starts with
|
||||
`> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.` (issues: "Filed by", reviews:
|
||||
"Review by"); every comment starts with `🤖 Agent:`. Never write as Ludovic.
|
||||
- **Attribution.** Commits end with `Co-Authored-By: Claude <model> <noreply@anthropic.com>`; PR bodies end
|
||||
with `🤖 Generated with [Claude Code](https://claude.com/claude-code)`.
|
||||
- Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`.
|
||||
- Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where
|
||||
they would change the vanilla look.
|
||||
- Small PRs (< ~500 lines). Labels: `feature` (players get something new), `skip-release` (they see no
|
||||
change), none for a fix. Agents never add `release-now`: the maintainer decides it. Every merge to main ships
|
||||
([docs/release-flow.md](docs/release-flow.md)).
|
||||
- Contributors first: `gh pr list --state open --search <area>` before you start; never duplicate theirs.
|
||||
|
||||
## Crates
|
||||
|
||||
Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-server` are separate workspaces.
|
||||
|
||||
| Crate | Owns |
|
||||
|---|---|
|
||||
| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) |
|
||||
| `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage |
|
||||
| `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) |
|
||||
| `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` |
|
||||
| `horizon-assets` | Resource decoding: block-state and item models, baking, atlases |
|
||||
| `horizon-prepare` | Builds `.local/horizon-client/26.3` from the player's own Minecraft install (runs the Java exporters) |
|
||||
| `horizon-server` | `horizon-server`: `server.toml`, CLI, supervisor of the headless game ([docs/hosting.md](docs/hosting.md)) |
|
||||
| `horizon-server-files` | `server.properties`, eula, ops/whitelist/bans, usercache |
|
||||
| `horizon-friends`, `horizon-relay` | Play with Friends: invite codes, encrypted tunnel, the relay ([docs/play-with-friends.md](docs/play-with-friends.md)) |
|
||||
| `horizon-shaderpack` | OptiFine/Iris packs: preprocessor, GLSL → WGSL ([docs/shader-packs.md](docs/shader-packs.md)) |
|
||||
| `horizon-mods`, `horizon-mod-sdk`, `cargo-horizon-mod` | Sandboxed WebAssembly mods: runtime, SDK + WIT, `cargo horizon-mod` ([docs/mods.md](docs/mods.md)) |
|
||||
| `horizon-port-pack` | Porting Java modpacks ([docs/modpacks.md](docs/modpacks.md)) |
|
||||
| `horizon-theme` | Design tokens and fonts for the launcher, the game's own menus and the website |
|
||||
| `horizon-telemetry`, `horizon-telemetry-server`, `horizon-bench` | Opt-in data collection, its ingest server, the benchmark report format |
|
||||
| `horizon-dualsense`, `horizon-threads`, `horizon-release-sign`, `horizon-bots`, `voxel-kernels`, `xtask` | DualSense output, thread priorities, signed release checksums, load-test bots, occupancy kernels, repo tasks |
|
||||
| `launcher/` | GPUI launcher: `main.rs` (UI), `backend.rs` (installs, updates), `cli.rs`, `mcp.rs`, `*_page.rs` |
|
||||
|
||||
Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m
|
||||
unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles),
|
||||
`website/` (playhorizon.dev; its paths are relative to `website/`), `docs/`, `.github/workflows/`.
|
||||
|
||||
## Build and test fast
|
||||
|
||||
```sh
|
||||
python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR
|
||||
python3 tools/pr_ready.py --quick # same without harnesses
|
||||
cargo test -p horizon-client --lib --bins --tests # skips the 104 examples (pr_ready does this); `--doc` separately
|
||||
cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e
|
||||
python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job)
|
||||
python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them
|
||||
python3 tools/parity.py mob_ai sculk # named harnesses
|
||||
python3 tools/lan_e2e.py --check chest # two real games over LAN (host in-frame); --server-thread for the host on its server thread
|
||||
python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
|
||||
```
|
||||
|
||||
- Harnesses and the game need the vanilla data in `.local/` (`minecraft/`, `horizon-client/26.3`, `datagen/`,
|
||||
`tools/`): see [docs/parity-workflow.md](docs/parity-workflow.md). Without it, pr_ready lists the
|
||||
harnesses for CI.
|
||||
- A harness = `tools/test_<name>_parity.py` (324 of them) + a Java oracle (`mods/horizon/src/test/java/dev/horizonlab/parity/Vanilla*Oracle.java`)
|
||||
+ a Rust probe: `crates/<crate>/examples/<name>_{probe,fixture}.rs` (horizon-world 175, horizon-client 104),
|
||||
or the game binary with a fixture env var (`game/dispense_fixture.rs`, `game/sculk_fixture.rs`,
|
||||
`game/command_harness.rs`, `game/net_harness.rs`). Copy a nearby harness for a new one.
|
||||
- Probes build into `.local/parity-target/`; harnesses find binaries via `lab.cargo_target()`, never `target/`.
|
||||
- What a change reruns (of 329 harnesses, measured 2026-10-23): a file of the game binary (`game.rs`, `game/`)
|
||||
~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it.
|
||||
- Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`).
|
||||
- **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined
|
||||
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude horizon-mods-test-guest`.
|
||||
Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`).
|
||||
- Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build).
|
||||
- Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game):
|
||||
`target/fast/horizon-ctl --socket $PWD/ctl.sock launch --world W --creative --offscreen --wait --resources $PWD/.local/horizon-client/26.3`,
|
||||
then `horizon-ctl --socket … state|keys|turn|command|screenshot|quit`
|
||||
([docs/horizon-ctl-commands.md](docs/horizon-ctl-commands.md)).
|
||||
|
||||
## Vanilla reference
|
||||
|
||||
- Decompiled sources: `.local/minecraft/26.3/sources/{client,server}/` (`python3 tools/lab.py decompile`).
|
||||
- Bytecode queries (callers through lambdas, every overload):
|
||||
`python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom`
|
||||
([docs/decompilation-status.md](docs/decompilation-status.md)).
|
||||
- A harness runs the oracle against the real 26.3 jars and the Rust probe on the same inputs, then compares
|
||||
their JSON. Oracle runs are cached by `tools/parity_shim.py`; `--fresh` reruns them.
|
||||
- Mirror vanilla's `Math` calls with `horizon_core::jmath`, and vanilla's RNG with `horizon_core::random`:
|
||||
random draws must happen in vanilla's order.
|
||||
|
||||
## horizon-client: where things live
|
||||
|
||||
`L:` = lib (`crates/horizon-client/src/`), `G:` = bin (`crates/horizon-client/src/game/`). The lib can't see
|
||||
`Game`; bin code reaches the lib as `horizon_client::<module>`.
|
||||
|
||||
| Subsystem | Files |
|
||||
|---|---|
|
||||
| Game loop, tick, frame | `game.rs`: `fn run`, `impl ApplicationHandler for Game` (`window_event`, `about_to_wait`), `fn tick`, `fn tick_world`, `fn render`; L: `clock.rs`, `window.rs`, `spans.rs` |
|
||||
| Rendering | L: `gfx.rs` (`Renderer::new`, `Renderer::render`), `gfx/` (cull, occlusion, translucency, upload, timing, lod, weather, stars, end_sky), `*.wgsl`, `particles.rs`, `block_entity_render.rs`, `item_render.rs`, `fog.rs`, `clouds.rs`, `camera.rs`, `first_person.rs`; G: `render_tick.rs`, `item_draw.rs` |
|
||||
| Chunks, streaming, light | L: `streaming.rs` (worker pool: generate, light, mesh), `world.rs`, `chunk.rs`, `chunk_map.rs`, `light.rs`, `mesher.rs` + `mesher/`, `vanillagen.rs` (binds horizon-world's generator), `lod.rs` + `lod/`, `ticket_levels.rs`; G: `world_loading.rs`, `postprocess.rs`; game.rs `fn update_world` |
|
||||
| World generation | `crates/horizon-world/src/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `carver/`) |
|
||||
| Block behaviour | `crates/horizon-world/src/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `redstone.rs`, `place.rs`, `interact.rs`); game.rs `fn tick_blocks`, `fn process_level_events` |
|
||||
| Mobs | L: `mobs.rs` (types), `mobs/` (`ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `species.rs`, `spawning.rs`, `render.rs`, `anim.rs`); G: `creatures.rs` (ticking, spawning, mob events), one file per mob family (`dragon.rs`, `wither.rs`, `villagers.rs`, `piglins.rs`, `golems.rs`...), `natural_spawning.rs` |
|
||||
| Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` |
|
||||
| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` |
|
||||
| Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` |
|
||||
| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` |
|
||||
| UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` |
|
||||
| Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) |
|
||||
| LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) |
|
||||
| Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` |
|
||||
| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` |
|
||||
| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` |
|
||||
| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` |
|
||||
| Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` |
|
||||
| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` |
|
||||
| Shader packs | L: `shader_pack.rs` (Horizon WGSL packs), `java_pack.rs` + crate `horizon-shaderpack` (Iris/OptiFine), `gfx/pack_stages.rs`, `gfx/java_stages.rs`; G: `shader_packs.rs` |
|
||||
| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) |
|
||||
| Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` |
|
||||
| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` |
|
||||
|
||||
## How `Game` is organised
|
||||
|
||||
- `struct Game` (game.rs, ~290 fields) holds everything. Its methods are spread over ~180 files: game.rs keeps
|
||||
the core (tick, render, input, inventory, world open/close) and each `game/<feature>.rs` adds an
|
||||
`impl Game<'_>` block for one feature, with its own state types. Fields are private to the bin.
|
||||
- Find a feature's code: `grep -rn "fn tick_<thing>\|fn <verb>_<thing>" crates/horizon-client/src/game*`;
|
||||
the file is usually `game/<thing>s.rs`. Who calls it: grep the name in game.rs's `fn tick` / `fn tick_world`.
|
||||
- Fields that say which mode runs: `remote` (this window is a client of a server: multiplayer, LAN guest, or
|
||||
single player on its server thread), `lan` (`LanHost`: this world is open to the network), `integrated`
|
||||
(the window's own server thread), `serving` (this `Game` *is* that server thread), `options.dedicated`.
|
||||
`fn tick` returns `tick_remote()` when `remote` is set; nothing else of the local simulation runs.
|
||||
- A server's players run through the same gameplay code as the local player: `as_guest` swaps the guest's
|
||||
state (position, inventory, mode, mining, item use) into `Game` for one call (`game/lan_actions.rs`), and
|
||||
`levels.rs` swaps whole dimensions in the same way. Changes reach clients through the block log, level
|
||||
events and the entity tracker (`lan/tracking.rs`, `game/lan_entities.rs`).
|
||||
- Shared read-only data: `Resources` (`res`: blocks, items, recipes, mob types, biomes) and `PackResources`
|
||||
(`pack`), both in game.rs.
|
||||
|
||||
## The two single-player paths
|
||||
|
||||
1. **In-frame (default since #1428):** the window's `Game` ticks the world itself, one level that follows
|
||||
the player (`fn enter_dimension`). This is what Stable players run and what harnesses test.
|
||||
2. **Server thread (`--server-thread` or `HORIZON_SERVER_THREAD=1`):** `game/integrated.rs` runs a second
|
||||
`Game` (`serving`) on a "Server thread" with one level per dimension; the window joins it as a client
|
||||
through memory (`remote`), exactly as a LAN guest or a dedicated server's player does. Not at parity yet:
|
||||
open `[server-thread]` issues list the gaps.
|
||||
|
||||
LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths
|
||||
when you touch player-facing gameplay:
|
||||
|
||||
```sh
|
||||
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # in-frame
|
||||
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --server-thread # server thread
|
||||
python3 tools/lan_e2e.py --check <name> # host in-frame, guest is a server client
|
||||
python3 tools/lan_e2e.py --server-thread --check <name> # host on its server thread (portals, levels, distance, lava need it)
|
||||
python3 tools/parity.py dedicated_server server_entities server_player_damage
|
||||
```
|
||||
|
||||
## Docs worth knowing
|
||||
|
||||
[docs/parity-workflow.md](docs/parity-workflow.md) (runner, gate, shards, scopes) ·
|
||||
[docs/native-client.md](docs/native-client.md) (options, controls, horizon-ctl) ·
|
||||
[docs/server-levels.md](docs/server-levels.md) (levels per dimension) ·
|
||||
[docs/rust-parity.md](docs/rust-parity.md) (what is ported) · [docs/known-issues.md](docs/known-issues.md) ·
|
||||
[docs/release-flow.md](docs/release-flow.md) · [docs/README.md](docs/README.md) (index).
|
||||
@@ -30,7 +30,9 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1.0.151", features = ["raw_value"] }
|
||||
# Shader packs: pack.toml, and WGSL checked before it reaches wgpu.
|
||||
toml = "1.1"
|
||||
naga = { version = "30.0.1", features = ["wgsl-in"] }
|
||||
# hlsl-out: the gfx.rs tests translate every shader as wgpu's DirectX 12 backend does. A normal feature,
|
||||
# not a dev-dependency's, so builds, tests and examples share one build of naga, wgpu and this crate.
|
||||
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] }
|
||||
# Java (OptiFine/Iris) shader packs, translated to WGSL.
|
||||
horizon-shaderpack = { path = "../horizon-shaderpack" }
|
||||
# Sound (ALSA on Linux); the `audio` feature.
|
||||
@@ -81,7 +83,3 @@ rng-trace = ["horizon-core/rng-trace"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
# Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests).
|
||||
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! `banner_patterns` layers carried by banner items, shields and placed
|
||||
//! banners, and the loom rules of `LoomMenu` (selectable patterns, the
|
||||
//! six-layer limit and the result stack).
|
||||
use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items};
|
||||
use crate::{block_entity_render::DYES, items::ItemStack, items::Items};
|
||||
use horizon_world::nbt::Tag;
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, fs, path::Path, sync::Arc};
|
||||
@@ -261,12 +261,6 @@ pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec<BannerLayer> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// Keeps `item_data` linked: the `StackData` fields the banner code reads.
|
||||
pub fn set_layers(stack: &mut ItemStack, layers: Vec<BannerLayer>) {
|
||||
let data: &mut item_data::StackData = stack.data_mut();
|
||||
data.banner_patterns = layers;
|
||||
stack.tidy();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
@@ -144,9 +144,6 @@ impl BlockEntities {
|
||||
pub fn set_states(&mut self, states: Vec<Ticking>) {
|
||||
self.states = states;
|
||||
}
|
||||
pub fn take_states(&mut self) -> Vec<Ticking> {
|
||||
std::mem::take(&mut self.states)
|
||||
}
|
||||
pub fn ticking(&self, state: u32) -> Ticking {
|
||||
self.states.get(state as usize).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -382,10 +382,6 @@ impl Shulker {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`.
|
||||
pub fn get_progress(&self, a: f32) -> f32 {
|
||||
self.progress_old + a * (self.progress - self.progress_old)
|
||||
}
|
||||
/// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room
|
||||
/// (`level.noCollision` of the half-block lid box, deflated by 1e-6).
|
||||
pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] {
|
||||
@@ -668,14 +664,6 @@ impl Skull {
|
||||
self.animating = false;
|
||||
}
|
||||
}
|
||||
/// `getAnimation(a)`.
|
||||
pub fn get_animation(&self, a: f32) -> f32 {
|
||||
if self.animating {
|
||||
self.tick_count as f32 + a
|
||||
} else {
|
||||
self.tick_count as f32
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `DecoratedPotBlockEntity.WobbleStyle`.
|
||||
|
||||
@@ -875,13 +875,6 @@ impl BlockEntityRenderer {
|
||||
visibility: None,
|
||||
}
|
||||
}
|
||||
/// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`).
|
||||
pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> {
|
||||
Some((
|
||||
self.models.get("standing_banner")?,
|
||||
self.models.get("standing_banner_flag")?,
|
||||
))
|
||||
}
|
||||
fn kind(&self, state: u32) -> &Kind {
|
||||
self.kinds.get(state as usize).unwrap_or(&Kind::None)
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ impl BossBar {
|
||||
style: "progress".into(),
|
||||
value: 0,
|
||||
max: 100,
|
||||
visible: false,
|
||||
visible: true,
|
||||
player: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,10 +169,6 @@ impl TickRateManager {
|
||||
self.frozen_ticks_to_run -= 1;
|
||||
}
|
||||
}
|
||||
/// `isEntityFrozen` for an entity that is not (and does not carry) a player.
|
||||
pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool {
|
||||
!self.runs_normally() && !is_player_or_carries_player
|
||||
}
|
||||
}
|
||||
|
||||
/// What `/tick sprint` reports when it ends.
|
||||
|
||||
@@ -812,14 +812,6 @@ pub fn java_parse_int(s: &str) -> Option<i32> {
|
||||
}
|
||||
s.parse().ok()
|
||||
}
|
||||
/// Long.parseLong.
|
||||
pub fn java_parse_long(s: &str) -> Option<i64> {
|
||||
let digits = s.strip_prefix(['-', '+']).unwrap_or(s);
|
||||
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
s.parse().ok()
|
||||
}
|
||||
/// Double.parseDouble over the characters StringReader reads as a number.
|
||||
pub fn java_parse_double(s: &str) -> Option<f64> {
|
||||
let t = s.trim_matches(|c: char| c <= ' ');
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of
|
||||
//! SNBT text components, with the data-fixer-upper error messages
|
||||
//! (ComponentArgument, StyleArgument and component-valued item data).
|
||||
use super::codec::{get, no_key, not_list, not_map, snbt};
|
||||
use super::codec::{get, no_key, not_list, not_map};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
/// A DataResult error: its message and whether it carries a partial result.
|
||||
@@ -362,7 +362,3 @@ pub fn decode_style(t: &Tag) -> Result<(), String> {
|
||||
_ => Err(not_map(t)),
|
||||
}
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn _keep(t: &Tag) -> String {
|
||||
snbt(t)
|
||||
}
|
||||
|
||||
@@ -632,10 +632,6 @@ pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemI
|
||||
pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) {
|
||||
PREDICATE.with(|g| g.parse_for_suggestions_with(builder, Some(reg)));
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn _unused(t: &Tag) -> String {
|
||||
snbt(t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
@@ -183,9 +183,6 @@ impl<'a> Reader<'a> {
|
||||
pub fn read_int(&mut self) -> CmdResult<i32> {
|
||||
self.number("int")
|
||||
}
|
||||
pub fn read_long(&mut self) -> CmdResult<i64> {
|
||||
self.number("long")
|
||||
}
|
||||
pub fn read_double(&mut self) -> CmdResult<f64> {
|
||||
self.number("double")
|
||||
}
|
||||
@@ -222,21 +219,6 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
Err(CommandError::tr_at("parsing.quote.expected.end", &[], self))
|
||||
}
|
||||
pub fn read_quoted_string(&mut self) -> CmdResult<String> {
|
||||
if !self.can_read() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let next = self.peek();
|
||||
if next != '"' && next != '\'' {
|
||||
return Err(CommandError::tr_at(
|
||||
"parsing.quote.expected.start",
|
||||
&[],
|
||||
self,
|
||||
));
|
||||
}
|
||||
self.skip();
|
||||
self.read_string_until(next)
|
||||
}
|
||||
pub fn read_string(&mut self) -> CmdResult<String> {
|
||||
if !self.can_read() {
|
||||
return Ok(String::new());
|
||||
@@ -539,18 +521,6 @@ impl<'a> SuggestionsBuilder<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The same with a tooltip per candidate.
|
||||
pub fn suggest_matching_tooltip<'b>(
|
||||
&mut self,
|
||||
candidates: impl IntoIterator<Item = (&'b str, String)>,
|
||||
) {
|
||||
let lower = self.remaining_lower();
|
||||
for (c, tip) in candidates {
|
||||
if args::matches_sub_str(&lower, &c.to_lowercase()) {
|
||||
self.suggest_tooltip(c, tip);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// String.compareToIgnoreCase.
|
||||
pub fn compare_ignore_case(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its
|
||||
//! error messages and completion suggestions, producing NBT tags.
|
||||
use super::packrat::{
|
||||
Grammar, Reason, Rule, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq,
|
||||
};
|
||||
use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq};
|
||||
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag};
|
||||
use std::rc::Rc;
|
||||
@@ -981,5 +979,3 @@ pub fn rule_in<V: super::packrat::Value>(
|
||||
}
|
||||
}
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn _rule_kind(_: Rule<SV>) {}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! mode keywords are read back from the parsed literals.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, GameMode, Resource, integer},
|
||||
args::{ArgType, Resource, integer},
|
||||
};
|
||||
use crate::gamerules::{RULES, Value};
|
||||
|
||||
@@ -509,10 +509,6 @@ fn clone_mode(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(l, "clone");
|
||||
}
|
||||
}
|
||||
/// Game mode names for selector `gamemode=` and the argument.
|
||||
pub fn game_modes() -> [&'static str; 4] {
|
||||
GameMode::ALL.map(GameMode::name)
|
||||
}
|
||||
/// The shared vanilla tree.
|
||||
/// Reorder node children as vanilla registers them (Brigadier keeps
|
||||
/// children in registration order; smart usage lists them that way).
|
||||
@@ -559,5 +555,3 @@ pub fn release_dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(|| build_with(false))
|
||||
}
|
||||
#[allow(unused)]
|
||||
const _: (u8, u8) = (ALL, GAMEMASTERS);
|
||||
|
||||
@@ -252,24 +252,6 @@ impl BlockEntity {
|
||||
};
|
||||
Some(Self::Chest(vec![None; size]))
|
||||
}
|
||||
/// The vanilla block entity type id of a container block.
|
||||
pub fn id_for_block(name: &str) -> Option<&'static str> {
|
||||
Some(match name {
|
||||
"minecraft:chest" => "minecraft:chest",
|
||||
n if n.ends_with("copper_chest") => "minecraft:chest",
|
||||
"minecraft:trapped_chest" => "minecraft:trapped_chest",
|
||||
"minecraft:barrel" => "minecraft:barrel",
|
||||
"minecraft:hopper" => "minecraft:hopper",
|
||||
"minecraft:dispenser" => "minecraft:dispenser",
|
||||
"minecraft:dropper" => "minecraft:dropper",
|
||||
"minecraft:furnace" => "minecraft:furnace",
|
||||
"minecraft:blast_furnace" => "minecraft:blast_furnace",
|
||||
"minecraft:smoker" => "minecraft:smoker",
|
||||
n if n.ends_with("shulker_box") => "minecraft:shulker_box",
|
||||
"minecraft:crafter" => "minecraft:crafter",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Chest(items) => match items.len() {
|
||||
|
||||
@@ -17,8 +17,6 @@ use std::{
|
||||
pub const CAPACITY: usize = 240;
|
||||
/// `AbstractDebugChart.CHART_HEIGHT`.
|
||||
pub const CHART_HEIGHT: i32 = 60;
|
||||
/// `TpsDebugDimensions`: a tick sample's values.
|
||||
pub const FULL_TICK: usize = 0;
|
||||
pub const TICK_SERVER_METHOD: usize = 1;
|
||||
pub const SCHEDULED_TASKS: usize = 2;
|
||||
pub const IDLE: usize = 3;
|
||||
@@ -252,10 +250,6 @@ impl Chart {
|
||||
pub fn width(max_width: i32) -> i32 {
|
||||
(CAPACITY as i32 + 2).min(max_width)
|
||||
}
|
||||
/// `getFullHeight`: the box and the min/avg/max line above it.
|
||||
pub fn full_height() -> i32 {
|
||||
CHART_HEIGHT + 9
|
||||
}
|
||||
/// `AbstractDebugChart.extractRenderState`.
|
||||
pub fn draw(
|
||||
self,
|
||||
|
||||
@@ -359,10 +359,6 @@ impl Enchantments {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Whether a stack draws the enchantment glint.
|
||||
pub fn has_glint(&self, stack: &ItemStack) -> bool {
|
||||
stack.has_any_enchantments() || self.props(&stack.item).is_some_and(|p| p.glint)
|
||||
}
|
||||
|
||||
// ---- Enchanting table (EnchantmentHelper) ----
|
||||
|
||||
@@ -514,19 +510,6 @@ impl Enchantments {
|
||||
.is_some_and(|e| e.effects.get(component).is_some())
|
||||
})
|
||||
}
|
||||
/// The highest level among enchantments on `stack` that have `component`.
|
||||
pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 {
|
||||
stack
|
||||
.enchantments()
|
||||
.iter()
|
||||
.filter(|(id, _)| {
|
||||
self.get(id)
|
||||
.is_some_and(|e| e.effects.get(component).is_some())
|
||||
})
|
||||
.map(|(_, l)| *l)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
/// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation).
|
||||
pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -89,6 +89,47 @@ impl Base<'_> {
|
||||
}
|
||||
|
||||
/// `LivingEntity` + `Mob` (+ `AgeableMob`, creeper and skeleton specifics).
|
||||
/// The mobs whose class extends vanilla's `Animal` (and so save `InLove`):
|
||||
/// not allays, villagers, golems, dolphins or fish.
|
||||
fn is_animal(id: &str) -> bool {
|
||||
matches!(
|
||||
id.strip_prefix("minecraft:").unwrap_or(id),
|
||||
"pig"
|
||||
| "cow"
|
||||
| "mooshroom"
|
||||
| "sheep"
|
||||
| "chicken"
|
||||
| "rabbit"
|
||||
| "horse"
|
||||
| "donkey"
|
||||
| "mule"
|
||||
| "zombie_horse"
|
||||
| "skeleton_horse"
|
||||
| "llama"
|
||||
| "trader_llama"
|
||||
| "goat"
|
||||
| "panda"
|
||||
| "polar_bear"
|
||||
| "fox"
|
||||
| "wolf"
|
||||
| "cat"
|
||||
| "ocelot"
|
||||
| "parrot"
|
||||
| "bee"
|
||||
| "turtle"
|
||||
| "armadillo"
|
||||
| "frog"
|
||||
| "axolotl"
|
||||
| "hoglin"
|
||||
| "strider"
|
||||
| "camel"
|
||||
| "camel_husk"
|
||||
| "sniffer"
|
||||
| "happy_ghast"
|
||||
| "nautilus"
|
||||
| "zombie_nautilus"
|
||||
)
|
||||
}
|
||||
pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
let base = Base {
|
||||
id: &m.kind.id,
|
||||
@@ -175,12 +216,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
for (key, value) in [
|
||||
("Age", Tag::Int(0)),
|
||||
("ForcedAge", Tag::Int(0)),
|
||||
("InLove", Tag::Int(0)),
|
||||
("AgeLocked", Tag::Byte(0)),
|
||||
] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
// Animal.addAdditionalSaveData: the love ticks left, whatever the save had.
|
||||
if is_animal(id) {
|
||||
map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0)));
|
||||
}
|
||||
match id {
|
||||
"minecraft:creeper" => {
|
||||
for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] {
|
||||
@@ -445,10 +489,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
}
|
||||
// Sheep.addAdditionalSaveData: its wool as it is now.
|
||||
"minecraft:sheep" => {
|
||||
for (key, value) in [("Color", Tag::Byte(0)), ("Sheared", Tag::Byte(0))] {
|
||||
map.entry(key.into()).or_insert(value);
|
||||
}
|
||||
map.insert("Color".into(), Tag::Byte((m.extra.color & 15) as i8));
|
||||
map.insert("Sheared".into(), Tag::Byte(i8::from(m.extra.sheared)));
|
||||
}
|
||||
// CopperGolem.addAdditionalSaveData.
|
||||
"minecraft:copper_golem" => {
|
||||
@@ -621,6 +665,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32;
|
||||
m.extra.age_locked = flag(tag, "AgeLocked");
|
||||
}
|
||||
if is_animal(&m.kind.id) {
|
||||
m.extra.in_love = number(tag.get("InLove")).unwrap_or(0) as i32;
|
||||
}
|
||||
m.name_visible = flag(tag, "CustomNameVisible");
|
||||
m.no_ai = flag(tag, "NoAI");
|
||||
m.no_gravity = flag(tag, "NoGravity");
|
||||
@@ -832,6 +879,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
}
|
||||
m.extra.egg_time = number(tag.get("life_ticks")).map_or(-1, |v| v as i32);
|
||||
}
|
||||
// Sheep.readAdditionalSaveData: white and unsheared when absent.
|
||||
if m.species() == crate::mobs::Species::Sheep {
|
||||
m.extra.color = number(tag.get("Color")).map_or(0, |c| (c as u8) & 15);
|
||||
m.extra.sheared = flag(tag, "Sheared");
|
||||
}
|
||||
if m.species() == crate::mobs::Species::Shulker {
|
||||
m.extra.variant3 = number(tag.get("AttachFace")).unwrap_or(0).clamp(0, 5) as u8;
|
||||
m.extra.counter = number(tag.get("Peek")).unwrap_or(0).clamp(0, 100) as i32;
|
||||
@@ -2051,3 +2103,39 @@ mod axolotl_nbt_tests {
|
||||
assert_eq!(mm.temptation_cooldown_ticks.value(), Some(42));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sheep_nbt_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn a_sheep_keeps_its_dyed_and_sheared_wool() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("items.json").exists() {
|
||||
return;
|
||||
}
|
||||
let data = crate::mobs::MobTypes::load(&root).unwrap();
|
||||
let mut m = Mob::new(
|
||||
1,
|
||||
Arc::new(data.types["minecraft:sheep"].clone()),
|
||||
Vec3::new(0.0, 4.0, 0.0),
|
||||
0.0,
|
||||
);
|
||||
// Summoned white, then dyed red and sheared: the save has it now.
|
||||
let raw = Tag::compound([("Color", Tag::Byte(0)), ("Sheared", Tag::Byte(0))]);
|
||||
(m.extra.color, m.extra.sheared) = (14, true);
|
||||
let tag = mob_to_nbt(&m, [1, 2, 3, 4], Some(&raw));
|
||||
assert_eq!(
|
||||
(number(tag.get("Color")), number(tag.get("Sheared"))),
|
||||
(Some(14), Some(1))
|
||||
);
|
||||
let types: HashMap<String, Arc<MobType>> = data
|
||||
.types
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), Arc::new(v.clone())))
|
||||
.collect();
|
||||
let back = mob_from_nbt(&tag, &types, 2).unwrap();
|
||||
assert_eq!((back.extra.color, back.extra.sheared), (14, true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,15 +289,6 @@ impl Default for HandHeights {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// What `FirstPersonHandsAndItems.tick` decides about a hand's visible item.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct HandChange {
|
||||
/// The visible item is not the hand's item after the instant replacement
|
||||
/// (`mainHandItem != nextMainHand`): the hand lowers.
|
||||
pub changed: bool,
|
||||
/// The visible item becomes the hand's item this tick.
|
||||
pub replace: bool,
|
||||
}
|
||||
impl HandHeights {
|
||||
/// `FirstPersonHandsAndItems.tick`'s heights. `changed` says per hand
|
||||
/// whether the visible item differs from the held one once
|
||||
|
||||
@@ -271,7 +271,10 @@ fn load_bitmap(
|
||||
.flatten();
|
||||
// The sheet: its size, and its pixels when they are not in the atlas.
|
||||
let (sw, sh, sheet) = match in_atlas {
|
||||
Some(rect) => (rect.w, rect.h, None),
|
||||
Some(rect) => {
|
||||
let (w, h) = rect.texels(atlas);
|
||||
(w, h, None)
|
||||
}
|
||||
None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) {
|
||||
Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))),
|
||||
Err(_) => {
|
||||
|
||||
@@ -121,6 +121,7 @@ mod pumpkin;
|
||||
mod raids;
|
||||
mod recipe_book;
|
||||
mod remote;
|
||||
mod remote_mob_data;
|
||||
mod remote_mob_use;
|
||||
mod remote_objects;
|
||||
mod remote_projectiles;
|
||||
@@ -283,9 +284,11 @@ struct Options {
|
||||
benchmark: Option<String>,
|
||||
/// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt.
|
||||
dev_mods: Vec<PathBuf>,
|
||||
/// Single player runs on an integrated server thread (game/integrated.rs),
|
||||
/// as vanilla's does: the default. `--no-server-thread` or
|
||||
/// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead.
|
||||
/// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on an
|
||||
/// integrated server thread (game/integrated.rs), as vanilla's does. Off by
|
||||
/// default again until a server's players reach parity with the in-frame
|
||||
/// world (signs, books, totems, keep_inventory...); `--no-server-thread`
|
||||
/// keeps it off.
|
||||
server_thread: bool,
|
||||
/// Set on the integrated server's own options: it draws nothing, so it skips meshing.
|
||||
integrated: bool,
|
||||
@@ -343,7 +346,7 @@ impl Options {
|
||||
dev_mods: Vec::new(),
|
||||
// The command harness (HORIZON_COMMAND_SCRIPT) drives the world
|
||||
// itself, without the event loop: it stays in the frame.
|
||||
server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0")
|
||||
server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1")
|
||||
&& std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(),
|
||||
integrated: false,
|
||||
};
|
||||
@@ -353,7 +356,7 @@ impl Options {
|
||||
match arg.as_str() {
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
|
||||
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --server-thread Run single player's world on its server thread (not at parity yet)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
|
||||
horizon_core::VANILLA_VERSION
|
||||
);
|
||||
return Ok(None);
|
||||
@@ -1022,9 +1025,11 @@ pub struct UiResources {
|
||||
pub panorama: Arc<horizon_client::gfx::panorama::Faces>,
|
||||
}
|
||||
impl UiResources {
|
||||
pub fn load(root: &std::path::Path) -> Result<Self> {
|
||||
/// From a resource root layering packs over `defaults`, the game's own
|
||||
/// resources (`root` itself when no pack is on).
|
||||
pub fn load(root: &std::path::Path, defaults: &std::path::Path) -> Result<Self> {
|
||||
Ok(Self {
|
||||
atlas: HudAtlas::build(root)?,
|
||||
atlas: HudAtlas::build_over(root, defaults)?,
|
||||
panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)),
|
||||
})
|
||||
}
|
||||
@@ -2576,6 +2581,17 @@ impl Game<'_> {
|
||||
LevelEvent::LevelEvent { id: 2004, pos, .. } => {
|
||||
self.spawner_burst([pos.x, pos.y, pos.z])
|
||||
}
|
||||
// LevelEventHandler 1505: the growth particles, then the sound.
|
||||
LevelEvent::LevelEvent {
|
||||
id: 1505,
|
||||
pos,
|
||||
data,
|
||||
} => {
|
||||
self.growth_particles(pos, data);
|
||||
let at = [pos.x, pos.y, pos.z].map(|v| f64::from(v) + 0.5);
|
||||
self.audio
|
||||
.play("minecraft:item.bone_meal.use", Some(at), 1.0, 1.0);
|
||||
}
|
||||
LevelEvent::LevelEvent {
|
||||
id: 2015,
|
||||
pos,
|
||||
@@ -2619,7 +2635,6 @@ impl Game<'_> {
|
||||
1030 => Some(("minecraft:block.anvil.use", 1.0)),
|
||||
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
|
||||
1031 => Some(("minecraft:block.anvil.land", 0.3)),
|
||||
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
|
||||
1042 => Some(("minecraft:block.grindstone.use", 1.0)),
|
||||
1044 => Some(("minecraft:block.smithing_table.use", 1.0)),
|
||||
// LevelEvent.SOUND_PAGE_TURN (a lectern's page).
|
||||
@@ -4320,7 +4335,7 @@ impl Game<'_> {
|
||||
/// world's entities and blocks, and the network hub.
|
||||
fn tick_world(&mut self, running: bool) -> Result<()> {
|
||||
self.update_chunk_tickets();
|
||||
horizon_client::spans::time("tick_effects", || self.tick_effects());
|
||||
horizon_client::spans::time("tick_effects", || self.tick_effects(running));
|
||||
// Player.tick's ItemCooldowns.tick for the window's player (a
|
||||
// server's players count theirs down in `tick_guests`).
|
||||
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
|
||||
@@ -7051,10 +7066,16 @@ impl Game<'_> {
|
||||
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
|
||||
amount += self.smash_damage_bonus(target_kind);
|
||||
let player = self.player.as_ref();
|
||||
// Player.canCriticalAttack: falling, off the ground, not sprinting.
|
||||
let falling =
|
||||
player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
|
||||
let crit = scale > 0.9 && falling;
|
||||
// Player.canCriticalAttack: falling, off the ground, not in water,
|
||||
// not blind (isMobilityRestricted), not riding, not sprinting.
|
||||
let falling = player.is_some_and(|p| {
|
||||
!p.ground.on_ground
|
||||
&& p.fall_distance > 0.0
|
||||
&& !p.fluids.was_touching_water
|
||||
&& !p.sprinting
|
||||
});
|
||||
let restricted = self.potions.effects.get("blindness").is_some() || self.riding.is_some();
|
||||
let crit = scale > 0.9 && falling && !restricted;
|
||||
if crit {
|
||||
amount *= 1.5;
|
||||
}
|
||||
@@ -7663,6 +7684,8 @@ impl Game<'_> {
|
||||
world.game_time = self.world.game_time;
|
||||
world.day_time = self.world.day_time;
|
||||
world.weather = self.world.weather;
|
||||
// The game rules and the difficulty hold in every dimension.
|
||||
world.health_rules = self.world.health_rules;
|
||||
// An open hub keeps hearing the new level's block changes.
|
||||
world.block_log = self.world.block_log.as_ref().map(|_| Vec::new());
|
||||
world.light_log = self.world.light_log.as_ref().map(|_| Default::default());
|
||||
@@ -8106,13 +8129,15 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
/// `BlockTransformer.transformBlock` for a held axe, hoe or shovel.
|
||||
fn use_block_transformer(
|
||||
&mut self,
|
||||
/// What `BlockTransformer.transformBlock` would do with a held axe, hoe
|
||||
/// or shovel on the block at `pos`, without doing it: the new state, its
|
||||
/// sound, loot table, the durability it costs and its particle.
|
||||
pub(super) fn block_transform(
|
||||
&self,
|
||||
stack: &ItemStack,
|
||||
pos: [i32; 3],
|
||||
face: [i32; 3],
|
||||
) -> Result<bool> {
|
||||
) -> Option<(BlockStateId, String, Option<String>, u32, String)> {
|
||||
use horizon_client::block_transform::Around;
|
||||
struct Column<'w> {
|
||||
world: &'w World,
|
||||
@@ -8132,14 +8157,11 @@ impl Game<'_> {
|
||||
})
|
||||
}
|
||||
}
|
||||
let Some(id) = self
|
||||
let id = self
|
||||
.res
|
||||
.items()
|
||||
.get(&stack.item)
|
||||
.and_then(|i| i.block_transformer.clone())
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
.and_then(|i| i.block_transformer.clone())?;
|
||||
// playerHasBlockingItemUseIntent: a shield in the off hand is raised
|
||||
// instead, unless sneaking.
|
||||
let shield = self
|
||||
@@ -8148,7 +8170,7 @@ impl Game<'_> {
|
||||
.and_then(|s| self.res.items().get(&s.item))
|
||||
.is_some_and(|i| i.blocks_attacks.is_some());
|
||||
if shield && !self.keys.contains(&KeyCode::ShiftLeft) {
|
||||
return Ok(false);
|
||||
return None;
|
||||
}
|
||||
let face_name = match face {
|
||||
[0, -1, 0] => "down",
|
||||
@@ -8159,38 +8181,47 @@ impl Game<'_> {
|
||||
_ => "east",
|
||||
};
|
||||
let registry = self.pack.assets.registry;
|
||||
let (state, sound, loot, damage, particle) = {
|
||||
let around = Column {
|
||||
world: &self.world,
|
||||
registry,
|
||||
pos,
|
||||
};
|
||||
let Some((_, t, state)) =
|
||||
self.res
|
||||
.transformers()
|
||||
.apply(self.res.items(), registry, &id, face_name, &around)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
(
|
||||
state,
|
||||
t.sound.clone(),
|
||||
t.loot.clone(),
|
||||
t.damage,
|
||||
t.particle.clone(),
|
||||
)
|
||||
let around = Column {
|
||||
world: &self.world,
|
||||
registry,
|
||||
pos,
|
||||
};
|
||||
let Ok(new) = registry.resolve(&state) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.level_set(pos, new)?;
|
||||
// BlockTransformer.TransformParticle.send.
|
||||
match particle.as_str() {
|
||||
let (_, t, state) =
|
||||
self.res
|
||||
.transformers()
|
||||
.apply(self.res.items(), registry, &id, face_name, &around)?;
|
||||
let new = registry.resolve(&state).ok()?;
|
||||
Some((
|
||||
new,
|
||||
t.sound.clone(),
|
||||
t.loot.clone(),
|
||||
t.damage,
|
||||
t.particle.clone(),
|
||||
))
|
||||
}
|
||||
/// `BlockTransformer.TransformParticle.send`: its level event.
|
||||
pub(super) fn transform_particle(&mut self, particle: &str, pos: [i32; 3]) {
|
||||
match particle {
|
||||
"scrape" => self.level_event_at(3005, pos, 0),
|
||||
"wax_on" => self.level_event_at(3003, pos, 0),
|
||||
"wax_off" => self.level_event_at(3004, pos, 0),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// `BlockTransformer.transformBlock` for a held axe, hoe or shovel.
|
||||
fn use_block_transformer(
|
||||
&mut self,
|
||||
stack: &ItemStack,
|
||||
pos: [i32; 3],
|
||||
face: [i32; 3],
|
||||
) -> Result<bool> {
|
||||
let Some((new, sound, loot, damage, particle)) = self.block_transform(stack, pos, face)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.level_set(pos, new)?;
|
||||
// BlockTransformer.TransformParticle.send.
|
||||
self.transform_particle(&particle, pos);
|
||||
if loot.as_deref() == Some("minecraft:till/rooted_dirt") {
|
||||
self.pop_resource(
|
||||
[pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]],
|
||||
@@ -9576,6 +9607,7 @@ impl Game<'_> {
|
||||
);
|
||||
map.insert("Air".into(), horizon_world::nbt::Tag::Short(p.air as i16));
|
||||
}
|
||||
level.fall_distance = p.fall_distance;
|
||||
|
||||
level.food = p.health.food.food;
|
||||
level.saturation = p.health.food.saturation;
|
||||
@@ -10743,6 +10775,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
WindowEvent::CloseRequested => {
|
||||
self.pending_save.as_mut().unwrap().quit = true;
|
||||
}
|
||||
WindowEvent::DroppedFile(path) => {
|
||||
self.drop_shader_pack(&path);
|
||||
}
|
||||
WindowEvent::Focused(focused) => {
|
||||
self.focused = focused;
|
||||
if !focused {
|
||||
@@ -12111,7 +12146,20 @@ fn load_resources(
|
||||
// loads; the synchronous launch instead carries it in `Loaded`.
|
||||
let mut loaded_gui = None;
|
||||
let mut ui_ready = false;
|
||||
if let Ok(ui) = UiResources::load(&root) {
|
||||
let mut pack_error = None;
|
||||
let ui = match UiResources::load(&root, vanilla_root) {
|
||||
Ok(ui) => Some(ui),
|
||||
// Minecraft.rollbackResourcePacks: the packs' textures don't fit, start
|
||||
// with the game's own resources.
|
||||
Err(e) if root != vanilla_root => {
|
||||
log::warn!("Horizon: resource packs failed to load ({e}); using the default resources");
|
||||
pack_error = Some(e.to_string());
|
||||
root = vanilla_root.to_path_buf();
|
||||
None
|
||||
}
|
||||
Err(_) => None,
|
||||
};
|
||||
if let Some(ui) = ui {
|
||||
if menu {
|
||||
horizon_client::telemetry::mark_ui_ready();
|
||||
log::info!(
|
||||
@@ -12125,7 +12173,6 @@ fn load_resources(
|
||||
ui_ready = true;
|
||||
}
|
||||
progress.set(0);
|
||||
let mut pack_error = None;
|
||||
let (assets, render) = match Assets::load(&root).and_then(|assets| {
|
||||
let render = assets.reload(&root)?;
|
||||
Ok((assets, render))
|
||||
@@ -12152,7 +12199,7 @@ fn load_resources(
|
||||
let render = Arc::new(render);
|
||||
// The menu bundle must come from the same root as the world bundle.
|
||||
if !ui_ready || root != requested_root {
|
||||
let ui = UiResources::load(&root)?;
|
||||
let ui = UiResources::load(&root, vanilla_root)?;
|
||||
if menu {
|
||||
horizon_client::telemetry::mark_ui_ready();
|
||||
log::info!(
|
||||
@@ -12563,6 +12610,10 @@ fn start_game<'a>(
|
||||
game.rest_loader = rest_loader;
|
||||
game.ui.vanilla_root = vanilla_root;
|
||||
if let Some(error) = pack_error {
|
||||
// Minecraft.clearResourcePacksOnError: the selection is cleared and
|
||||
// saved, so the next launch starts without the packs.
|
||||
game.settings.resource_packs.clear();
|
||||
game.settings.save(&Game::options_path());
|
||||
game.open_options_at(true, horizon_client::options_ui::Page::Packs);
|
||||
game.ui.options.resource_error = Some(error);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use horizon_client::{
|
||||
chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR},
|
||||
command::Registries,
|
||||
gamerules::GameRules,
|
||||
hud::{HudBatch, rgba},
|
||||
hud::HudBatch,
|
||||
screen_draw::Measure,
|
||||
text::{ClickEvent, Style, Text},
|
||||
};
|
||||
@@ -893,10 +893,6 @@ impl Game<'_> {
|
||||
.chat
|
||||
.add(&self.gui.atlas, message, None, self.ticks, focused);
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
fn chat_debug_fill(&self, batch: &mut HudBatch) {
|
||||
batch.fill(&self.gui.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
|
||||
}
|
||||
}
|
||||
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
|
||||
/// approximated as UTC).
|
||||
|
||||
@@ -810,7 +810,10 @@ impl Game<'_> {
|
||||
None => break,
|
||||
},
|
||||
};
|
||||
if self.slot_get(slot) != item && self.slot_set(slot, item) {
|
||||
// ItemStack.isEmpty: air (or a count of 0) is an empty slot.
|
||||
// SlotAccess.set counts every slot it sets, the same item too.
|
||||
let item = item.filter(|s| &*s.item != "minecraft:air" && s.count > 0);
|
||||
if self.slot_set(slot, item) {
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -834,6 +834,12 @@ impl Game<'_> {
|
||||
"velocity": [p.velocity.x, p.velocity.y, p.velocity.z],
|
||||
"on_ground": p.ground.on_ground,
|
||||
"health": p.health.health(),
|
||||
// The maximum the HUD's hearts last read (its cached value).
|
||||
"max_health": p
|
||||
.attributes
|
||||
.lookup(p.attributes.key("minecraft:max_health").as_ref())
|
||||
.and_then(|h| p.attributes.instance(&h).ok())
|
||||
.map(|i| i.cached_value()),
|
||||
"food": p.health.food.food,
|
||||
})
|
||||
});
|
||||
@@ -971,6 +977,10 @@ impl Game<'_> {
|
||||
"flashes": self.lightning_seen[1], "flash": self.flash});
|
||||
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
|
||||
status["projectiles"] = json!(self.projectiles_status());
|
||||
// The particles made so far, by type.
|
||||
status["particles"] = json!(self.particles.made());
|
||||
// The scoreboard sidebar the HUD shows.
|
||||
status["sidebar"] = self.sidebar_status();
|
||||
status
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,8 +343,12 @@ impl Game<'_> {
|
||||
"on_ground": m.on_ground,
|
||||
"variant": m.extra.variant,
|
||||
"color": m.extra.color,
|
||||
"sheared": m.extra.sheared,
|
||||
"burning": m.fire_ticks > 0,
|
||||
"size": m.extra.size,
|
||||
"leash": m.extra.leash.map(|h| format!("{h:?}")),
|
||||
"tame": m.extra.tame,
|
||||
"sitting": m.extra.sitting,
|
||||
"temper": m.extra.variant3,
|
||||
"chested": m.extra.chested,
|
||||
"head": m.extra.head.as_deref(),
|
||||
|
||||
@@ -2697,10 +2697,12 @@ impl Game<'_> {
|
||||
velocity: [d.velocity.x, d.velocity.y, d.velocity.z],
|
||||
data: 0,
|
||||
meta,
|
||||
defaults: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
needs_sync: false,
|
||||
leash: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,15 @@ use super::Game;
|
||||
use horizon_client::{enchant::EffectContext, items::ItemStack};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
|
||||
#[derive(Clone, Copy)]
|
||||
enum MendSlot {
|
||||
Main,
|
||||
Off,
|
||||
/// An `armor` index (head first).
|
||||
Armor(usize),
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Player.getDestroySpeed` after the tool speed: mining efficiency, haste
|
||||
/// and mining fatigue.
|
||||
@@ -314,36 +323,29 @@ impl Game<'_> {
|
||||
pub(super) fn mending(&mut self, amount: u32) -> u32 {
|
||||
let mut amount = amount;
|
||||
loop {
|
||||
// EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged): held and armor.
|
||||
let mut candidates: Vec<(bool, usize)> = Vec::new();
|
||||
if let Some(s) = &self.inventory[self.selected]
|
||||
&& s.damage > 0
|
||||
&& s.enchantment_level("minecraft:mending") > 0
|
||||
{
|
||||
candidates.push((false, self.selected));
|
||||
}
|
||||
for (i, s) in self.armor.iter().enumerate() {
|
||||
if let Some(s) = s
|
||||
&& s.damage > 0
|
||||
&& s.enchantment_level("minecraft:mending") > 0
|
||||
{
|
||||
candidates.push((true, i));
|
||||
}
|
||||
}
|
||||
// EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged), in
|
||||
// EquipmentSlot order: the main hand, the off hand, then feet, legs,
|
||||
// chest and head (`armor` holds head first).
|
||||
let mending = |s: &Option<ItemStack>| {
|
||||
s.as_ref()
|
||||
.is_some_and(|s| s.damage > 0 && s.enchantment_level("minecraft:mending") > 0)
|
||||
};
|
||||
let candidates: Vec<MendSlot> = [MendSlot::Main, MendSlot::Off]
|
||||
.into_iter()
|
||||
.chain((0..self.armor.len()).rev().map(MendSlot::Armor))
|
||||
.filter(|&slot| mending(self.mend_slot(slot)))
|
||||
.collect();
|
||||
if candidates.is_empty() {
|
||||
return amount;
|
||||
}
|
||||
let (armor, i) = candidates[self
|
||||
let slot = candidates[self
|
||||
.world
|
||||
.random
|
||||
.next_int_bound(candidates.len() as i32)
|
||||
.unwrap_or(0) as usize];
|
||||
let stack = if armor {
|
||||
self.armor[i].clone()
|
||||
} else {
|
||||
self.inventory[i].clone()
|
||||
let Some(stack) = self.mend_slot(slot).clone() else {
|
||||
return amount;
|
||||
};
|
||||
let Some(stack) = stack else { return amount };
|
||||
let ctx = EffectContext {
|
||||
items: Some(self.res.items()),
|
||||
..Default::default()
|
||||
@@ -356,12 +358,7 @@ impl Game<'_> {
|
||||
amount as f32,
|
||||
) as u32;
|
||||
let repaired = to_repair_xp.min(stack.damage);
|
||||
let slot = if armor {
|
||||
&mut self.armor[i]
|
||||
} else {
|
||||
&mut self.inventory[i]
|
||||
};
|
||||
if let Some(s) = slot.as_mut() {
|
||||
if let Some(s) = self.mend_slot_mut(slot).as_mut() {
|
||||
s.damage -= repaired;
|
||||
}
|
||||
if repaired == 0 || to_repair_xp == 0 {
|
||||
@@ -374,6 +371,20 @@ impl Game<'_> {
|
||||
amount = remaining;
|
||||
}
|
||||
}
|
||||
fn mend_slot(&self, slot: MendSlot) -> &Option<ItemStack> {
|
||||
match slot {
|
||||
MendSlot::Main => &self.inventory[self.selected],
|
||||
MendSlot::Off => &self.offhand,
|
||||
MendSlot::Armor(i) => &self.armor[i],
|
||||
}
|
||||
}
|
||||
fn mend_slot_mut(&mut self, slot: MendSlot) -> &mut Option<ItemStack> {
|
||||
match slot {
|
||||
MendSlot::Main => &mut self.inventory[self.selected],
|
||||
MendSlot::Off => &mut self.offhand,
|
||||
MendSlot::Armor(i) => &mut self.armor[i],
|
||||
}
|
||||
}
|
||||
/// Bow enchantments at release: (extra base damage, infinity keeps the arrow).
|
||||
pub(super) fn bow_enchantments(&mut self) -> (f64, bool) {
|
||||
let Some(bow) = self.inventory[self.selected].clone() else {
|
||||
|
||||
@@ -97,8 +97,58 @@ impl EndState {
|
||||
}
|
||||
}
|
||||
|
||||
impl EndState {
|
||||
/// The eyes' entity ids, for a server to number them.
|
||||
pub(super) fn eye_ids(&mut self) -> impl Iterator<Item = &mut u32> {
|
||||
self.eyes.iter_mut().map(|e| &mut e.id)
|
||||
}
|
||||
/// The numbered eyes as a server's clients track them: (id, position, motion).
|
||||
pub(super) fn eyes_tracked(&self) -> impl Iterator<Item = (u32, [f64; 3], [f64; 3])> {
|
||||
self.eyes
|
||||
.iter()
|
||||
.filter(|e| e.id != 0)
|
||||
.map(|e| (e.id, e.position.to_array(), e.velocity.to_array()))
|
||||
}
|
||||
/// `handleAddEntity` for an eye of ender on a server's client: it flies
|
||||
/// where the server says.
|
||||
pub(super) fn add_remote_eye(&mut self, id: u32, at: [f64; 3], velocity: [f64; 3]) {
|
||||
self.eyes.retain(|e| e.id != id);
|
||||
let at = glam::DVec3::from_array(at);
|
||||
self.eyes.push(EyeOfEnder {
|
||||
id,
|
||||
position: at,
|
||||
previous: at,
|
||||
velocity: glam::DVec3::from_array(velocity),
|
||||
target: at,
|
||||
life: 0,
|
||||
survive: false,
|
||||
});
|
||||
}
|
||||
/// One tick of a server's client: `step` moves each toward where the
|
||||
/// server put it.
|
||||
pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) {
|
||||
for e in &mut self.eyes {
|
||||
e.previous = e.position;
|
||||
e.life += 1;
|
||||
e.position = glam::DVec3::from_array(step(e.id, e.position.to_array()));
|
||||
}
|
||||
}
|
||||
pub(super) fn remove_remote_eye(&mut self, id: u32) {
|
||||
self.eyes.retain(|e| e.id != id);
|
||||
}
|
||||
pub(super) fn clear_remote_eyes(&mut self) {
|
||||
self.eyes.clear();
|
||||
}
|
||||
/// Where each eye is, for `status`.
|
||||
pub(super) fn eye_positions(&self) -> impl Iterator<Item = (u32, [f64; 3])> {
|
||||
self.eyes.iter().map(|e| (e.id, e.position.to_array()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The EyeOfEnder entity.
|
||||
struct EyeOfEnder {
|
||||
/// Its entity id once a server's clients track it (0 until then).
|
||||
id: u32,
|
||||
position: glam::DVec3,
|
||||
previous: glam::DVec3,
|
||||
velocity: glam::DVec3,
|
||||
@@ -1023,6 +1073,7 @@ impl Game<'_> {
|
||||
};
|
||||
let survive = self.world.random.next_int_bound(5).unwrap_or(0) > 0;
|
||||
self.end.eyes.push(EyeOfEnder {
|
||||
id: 0,
|
||||
position: start,
|
||||
previous: start,
|
||||
velocity: glam::DVec3::ZERO,
|
||||
|
||||
@@ -6,9 +6,12 @@
|
||||
//! the world's options) with [`Integrated::call`], as vanilla's client calls
|
||||
//! into its `IntegratedServer`.
|
||||
//!
|
||||
//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs
|
||||
//! the world in the frame instead (the escape hatch while the network
|
||||
//! player's side catches up with the in-frame one).
|
||||
//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`) until a
|
||||
//! server's players reach parity with the in-frame world: on the server
|
||||
//! thread, signs open no editor, books don't open, a totem doesn't save its
|
||||
//! holder and death keeps the inventory (#1380, #1366, #1292, #1284 and the
|
||||
//! other `[server-thread]` issues). LAN guests and dedicated servers use the
|
||||
//! same code either way.
|
||||
use super::{
|
||||
Game, Options, PackResources, Resources, UiResources,
|
||||
lan::{LanSettings, Owner},
|
||||
|
||||
@@ -14,7 +14,7 @@ use horizon_client::{
|
||||
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
|
||||
playerdata,
|
||||
},
|
||||
mobs::Mob,
|
||||
mobs::{Mob, leash::Holder},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
@@ -91,7 +91,7 @@ pub(super) fn entity_uuid(id: u32) -> u128 {
|
||||
/// The SynchedEntityData index of the baby flag: AgeableMob.DATA_BABY_ID and
|
||||
/// Zombie.DATA_BABY_ID are both the first entry after Mob's (16); Piglin's
|
||||
/// comes after AbstractPiglin's zombification flag (17).
|
||||
fn baby_index(kind: &str) -> Option<u8> {
|
||||
pub(super) fn baby_index(kind: &str) -> Option<u8> {
|
||||
match kind {
|
||||
"minecraft:piglin" => Some(17),
|
||||
"minecraft:cow"
|
||||
@@ -139,7 +139,13 @@ fn baby_index(kind: &str) -> Option<u8> {
|
||||
/// A mob's synched data as ServerEntity sends it (only the values that differ
|
||||
/// from the defaults the client constructs), with vanilla's entry indices:
|
||||
/// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses.
|
||||
fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
|
||||
/// `defaults` gets the defaults of the entries that can go back to theirs.
|
||||
fn mob_meta(
|
||||
m: &Mob,
|
||||
hub: &Hub,
|
||||
meta: &mut Vec<(u8, i32, Value)>,
|
||||
defaults: &mut Vec<(u8, i32, Value)>,
|
||||
) {
|
||||
let kind = m.kind.id.as_str();
|
||||
if m.fire_ticks > 0 {
|
||||
meta.push((0, serializer::BYTE, Value::Byte(1)));
|
||||
@@ -159,15 +165,18 @@ fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
|
||||
if health != 1.0 {
|
||||
meta.push((9, serializer::FLOAT, Value::Float(health)));
|
||||
}
|
||||
defaults.push((9, serializer::FLOAT, Value::Float(1.0)));
|
||||
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2.
|
||||
let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1;
|
||||
if flags != 0 {
|
||||
meta.push((15, serializer::BYTE, Value::Byte(flags)));
|
||||
}
|
||||
if m.is_baby()
|
||||
&& let Some(index) = baby_index(kind)
|
||||
{
|
||||
meta.push((index, serializer::BOOLEAN, Value::Bool(true)));
|
||||
// AgeableMob.DATA_BABY_ID (and Zombie's, Piglin's).
|
||||
if let Some(index) = baby_index(kind) {
|
||||
if m.is_baby() {
|
||||
meta.push((index, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
defaults.push((index, serializer::BOOLEAN, Value::Bool(false)));
|
||||
}
|
||||
let e = &m.extra;
|
||||
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
|
||||
@@ -178,6 +187,7 @@ fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
|
||||
if value != 0 {
|
||||
meta.push((18, serializer::BYTE, Value::Byte(value as i8)));
|
||||
}
|
||||
defaults.push((18, serializer::BYTE, Value::Byte(0)));
|
||||
}
|
||||
"minecraft:cat" | "minecraft:wolf" => {
|
||||
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
|
||||
@@ -200,6 +210,13 @@ fn mob_meta(m: &Mob, hub: &Hub, meta: &mut Vec<(u8, i32, Value)>) {
|
||||
if let Some(v) = id(registry, name) {
|
||||
meta.push((index, serializer, Value::Id(v)));
|
||||
}
|
||||
// Wolf.DATA_COLLAR_COLOR and Cat's, red by default.
|
||||
let collar = if kind == "minecraft:cat" { 23 } else { 21 };
|
||||
let red = i32::from(horizon_client::mobs::tame::RED);
|
||||
if i32::from(e.color & 15) != red {
|
||||
meta.push((collar, serializer::INT, Value::Int(i32::from(e.color & 15))));
|
||||
}
|
||||
defaults.push((collar, serializer::INT, Value::Int(red)));
|
||||
}
|
||||
"minecraft:horse"
|
||||
| "minecraft:donkey"
|
||||
@@ -757,18 +774,37 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
/// The entities guests track: mobs, items and the rest (game/lan_entities.rs).
|
||||
fn lan_entities(&self, host_entity: Option<i32>, hub: &mut Hub, out: &mut States) {
|
||||
/// `mob_players` is the guest each mob sees as its player (game/lan_mobs.rs).
|
||||
fn lan_entities(
|
||||
&self,
|
||||
host_entity: Option<i32>,
|
||||
mob_players: &HashMap<u32, u32>,
|
||||
hub: &mut Hub,
|
||||
out: &mut States,
|
||||
) {
|
||||
out.clear();
|
||||
for m in self.mobs.iter().filter(|m| !m.removed) {
|
||||
// The lead's holder: the player the mob sees (a guest, else the
|
||||
// host) or another mob. A fence knot isn't an entity here.
|
||||
let leash = m.extra.leash.and_then(|h| match h {
|
||||
Holder::Player => mob_players
|
||||
.get(&m.id)
|
||||
.and_then(|conn| hub.guest(*conn))
|
||||
.map(|g| g.entity_id)
|
||||
.or(host_entity),
|
||||
Holder::Mob(id) => Some(id as i32),
|
||||
Holder::Knot(_) => None,
|
||||
});
|
||||
let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str());
|
||||
e.position = [m.position.x, m.position.y, m.position.z];
|
||||
(e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw);
|
||||
e.on_ground = m.on_ground;
|
||||
e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z];
|
||||
e.needs_sync = m.needs_sync;
|
||||
mob_meta(m, hub, &mut e.meta);
|
||||
mob_meta(m, hub, &mut e.meta, &mut e.defaults);
|
||||
mob_equipment(m, hub, &mut e.equipment);
|
||||
self.mob_attributes(m, &mut e.attributes);
|
||||
e.leash = leash;
|
||||
}
|
||||
for d in &self.dropped {
|
||||
let stack = hub.stack(&Some(d.stack.clone()));
|
||||
@@ -830,7 +866,7 @@ impl Game<'_> {
|
||||
.filter_map(|g| Some((g.vehicle?, g.entity_id)))
|
||||
.collect();
|
||||
self.lan_riding(host_entity, &guests, &mut host.hub.riding);
|
||||
self.lan_entities(host_entity, &mut host.hub, &mut states);
|
||||
self.lan_entities(host_entity, &host.mob_players, &mut host.hub, &mut states);
|
||||
} else {
|
||||
states.clear();
|
||||
}
|
||||
@@ -961,6 +997,7 @@ impl Game<'_> {
|
||||
self.lan_update_streaming(&host);
|
||||
self.lan_update_models(&mut host);
|
||||
self.lan_update_waypoints(&mut host, state.as_ref());
|
||||
self.lan_sync_scoreboard(&mut host);
|
||||
drop(holding);
|
||||
lan::flush_all(host.hub.guests.iter().map(|g| &g.sender));
|
||||
self.lan = Some(host);
|
||||
@@ -1018,7 +1055,7 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
// A dedicated server has no host player.
|
||||
self.lan_entities(None, &mut host.hub, &mut theirs);
|
||||
self.lan_entities(None, &host.mob_players, &mut host.hub, &mut theirs);
|
||||
theirs.as_slice()
|
||||
} else {
|
||||
entities
|
||||
@@ -1051,8 +1088,14 @@ impl Game<'_> {
|
||||
}
|
||||
for e in events {
|
||||
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
|
||||
// The acting guest does not predict the egg's teleport particles.
|
||||
let except = if *id == 2015 { None } else { self.lan_acting };
|
||||
// The acting guest does not predict the egg's teleport
|
||||
// particles, nor bone meal's growth (BoneMealItem.useOn's
|
||||
// levelEvent names no player).
|
||||
let except = if matches!(*id, 2015 | 1505) {
|
||||
None
|
||||
} else {
|
||||
self.lan_acting
|
||||
};
|
||||
self.lan_events
|
||||
.push((*id, [pos.x, pos.y, pos.z], *data, except));
|
||||
}
|
||||
|
||||
@@ -220,6 +220,12 @@ impl Game<'_> {
|
||||
host.hub.guests[i].position[2],
|
||||
);
|
||||
host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new);
|
||||
// The first body after joining burns, breathes and falls on as saved.
|
||||
if let Some(saved) = host.hub.guests[i].loaded_body.take()
|
||||
&& let Some(m) = host.hub.guests[i].motion.as_mut()
|
||||
{
|
||||
saved.apply(m);
|
||||
}
|
||||
// The saved golden hearts go on the first body of a player who
|
||||
// has been here before.
|
||||
let saved = host.hub.guests[i].saved_absorption.take();
|
||||
|
||||
@@ -36,10 +36,12 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) ->
|
||||
velocity: [0.0; 3],
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
defaults: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
needs_sync: false,
|
||||
leash: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,6 +277,8 @@ impl Game<'_> {
|
||||
self.rockets.iter_mut().for_each(|r| give(&mut r.id));
|
||||
self.crystals.iter_mut().for_each(|c| give(&mut c.id));
|
||||
self.bolts.iter_mut().for_each(|b| give(&mut b.id));
|
||||
self.potions.thrown_ids().for_each(&mut give);
|
||||
self.end.eye_ids().for_each(&mut give);
|
||||
}
|
||||
|
||||
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
|
||||
@@ -357,6 +361,26 @@ impl Game<'_> {
|
||||
}
|
||||
out.push(e);
|
||||
}
|
||||
// Thrown potions and bottles: ThrowableItemProjectile.DATA_ITEM_STACK
|
||||
// (the potion's colour), which a plain bottle's type already has.
|
||||
for (id, kind, stack, position, velocity) in self.potions.thrown_tracked() {
|
||||
let mut e = state(id, kind, at(position), 0.0, false);
|
||||
e.velocity = at(velocity);
|
||||
if stack.extra.is_some() || stack.count != 1 {
|
||||
e.meta.push((
|
||||
8,
|
||||
serializer::ITEM_STACK,
|
||||
Value::Item(hub.stack(&Some(stack.clone()))),
|
||||
));
|
||||
}
|
||||
out.push(e);
|
||||
}
|
||||
// EyeOfEnder: its item is the plain eye (DATA_ITEM_STACK's default).
|
||||
for (id, position, velocity) in self.end.eyes_tracked() {
|
||||
let mut e = state(id, "minecraft:eye_of_ender", position, 0.0, false);
|
||||
e.velocity = velocity;
|
||||
out.push(e);
|
||||
}
|
||||
for t in self.tridents.iter().filter(|t| t.id != 0) {
|
||||
let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false);
|
||||
e.pitch = t.pitch;
|
||||
|
||||
@@ -129,23 +129,6 @@ impl Game<'_> {
|
||||
}
|
||||
/// The screen title: the custom name, else the profession (the client
|
||||
/// adds the level itself).
|
||||
#[allow(dead_code)]
|
||||
fn merchant_title(&self, state: &MerchantState) -> String {
|
||||
if let Some(name) = &state.name {
|
||||
return name.clone();
|
||||
}
|
||||
let e = &self.res.stations().enchantments;
|
||||
let profession = state.session.profession.trim_start_matches("minecraft:");
|
||||
if state.session.villager {
|
||||
e.translate(&format!("entity.minecraft.villager.{profession}"))
|
||||
.unwrap_or(profession)
|
||||
.to_owned()
|
||||
} else {
|
||||
e.translate("entity.minecraft.wandering_trader")
|
||||
.unwrap_or("Wandering Trader")
|
||||
.to_owned()
|
||||
}
|
||||
}
|
||||
/// `ServerPlayer.sendMerchantOffers`, when the offers changed.
|
||||
fn lan_send_offers(
|
||||
&mut self,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Level events whose client handler (`LevelEventHandler`) spawns particles
|
||||
//! on a block: dragon egg teleportation (2015), a consumable's teleport
|
||||
//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and
|
||||
//! scraping (3005).
|
||||
//! on a block: bone meal's growth (1505), dragon egg teleportation (2015), a
|
||||
//! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax
|
||||
//! off (3004) and scraping (3005).
|
||||
use super::Game;
|
||||
use horizon_client::particles::{self, ParticleOptions, ParticleType};
|
||||
use horizon_core::position::BlockPos;
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
use horizon_world::level::LevelEvent;
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -42,6 +42,65 @@ impl Game<'_> {
|
||||
self.particles.add(&options, p, v);
|
||||
}
|
||||
}
|
||||
/// `BoneMealItem.addGrowthParticles` (event 1505, `count` the data):
|
||||
/// happy villager sparks over a spreading block's neighbourhood (grass,
|
||||
/// nylium, netherrack, moss) or water, or inside a growing block.
|
||||
pub(super) fn growth_particles(&mut self, pos: BlockPos, count: i32) {
|
||||
let p = [pos.x, pos.y, pos.z];
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
let facts = self.res.facts();
|
||||
// ParticleUtils.spawnParticles(level, pos, count, xzSpread, ySpread,
|
||||
// allowFloatingParticles, particle).
|
||||
let (at, count, xz, height, floating) = match self.res.behaviours().bone_meal_spreads(state)
|
||||
{
|
||||
Some(spreads) => {
|
||||
// BonemealableBlock.getParticlePos: below for rooted dirt
|
||||
// (its hanging roots) and mangrove leaves (their propagule).
|
||||
let at = match &*facts.get(state).name {
|
||||
"minecraft:rooted_dirt" | "minecraft:mangrove_leaves" => [p[0], p[1] - 1, p[2]],
|
||||
_ => p,
|
||||
};
|
||||
if spreads {
|
||||
(at, count * 3, 3.0, 1.0, false)
|
||||
} else {
|
||||
// ParticleUtils.spawnParticleInBlock: up to the
|
||||
// block's shape (a full block when air).
|
||||
let inside = self.world.block(at[0], at[1], at[2]);
|
||||
let height = if facts.is_air(inside) {
|
||||
1.0
|
||||
} else {
|
||||
facts
|
||||
.get(inside)
|
||||
.outline
|
||||
.iter()
|
||||
.map(|b| b[4])
|
||||
.fold(0.0, f64::max)
|
||||
};
|
||||
(at, count, 0.5, height, true)
|
||||
}
|
||||
}
|
||||
None if &*facts.get(state).name == "minecraft:water" => (p, count * 3, 3.0, 1.0, false),
|
||||
None => return,
|
||||
};
|
||||
let options = ParticleOptions::simple(ParticleType::HappyVillager);
|
||||
for _ in 0..count.max(0) {
|
||||
let r = self.particles.level_random();
|
||||
let v = [0.0; 3].map(|_: f64| r.next_gaussian() * 0.02);
|
||||
let start = 0.5 - xz;
|
||||
let x = f64::from(at[0]) + start + r.next_double() * xz * 2.0;
|
||||
let y = f64::from(at[1]) + r.next_double() * height;
|
||||
let z = f64::from(at[2]) + start + r.next_double() * xz * 2.0;
|
||||
let below = [x.floor() as i32, y.floor() as i32 - 1, z.floor() as i32];
|
||||
if floating
|
||||
|| !self
|
||||
.res
|
||||
.facts()
|
||||
.is_air(self.world.block(below[0], below[1], below[2]))
|
||||
{
|
||||
self.particles.add(&options, [x, y, z], v);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Queue and play level event `id` at `pos` (`Level.levelEvent`).
|
||||
pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) {
|
||||
self.level_events.push(LevelEvent::LevelEvent {
|
||||
|
||||
@@ -232,6 +232,9 @@ impl Game<'_> {
|
||||
p.world.game_time = self.world.game_time;
|
||||
p.world.day_time = self.world.day_time;
|
||||
p.world.weather = self.world.weather;
|
||||
// The game rules and the difficulty are the server's, not a
|
||||
// level's: natural regeneration holds in every dimension.
|
||||
p.world.health_rules = self.world.health_rules;
|
||||
// The sculk tables' watched blocks are built once per game.
|
||||
p.world.watched = std::mem::take(&mut self.world.watched);
|
||||
self.swap_level(&mut p);
|
||||
|
||||
@@ -243,6 +243,9 @@ impl Game<'_> {
|
||||
super::packs::open_folder(&dir);
|
||||
}
|
||||
Event::Credits => self.open_win_screen(false, super::win::Finish::Options),
|
||||
Event::ReloadShaderPack => {
|
||||
self.load_shader_pack();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -133,7 +133,7 @@ impl Game<'_> {
|
||||
}
|
||||
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
|
||||
let render = std::sync::Arc::new(self.pack.assets.reload(root)?);
|
||||
let mut atlas = HudAtlas::build(root)?;
|
||||
let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?;
|
||||
atlas.font.uniform = self.settings.force_unicode;
|
||||
atlas.font.japanese = self.settings.japanese_glyphs;
|
||||
let gui = super::UiResources {
|
||||
|
||||
@@ -18,6 +18,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
/// A thrown splash or lingering potion in flight.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct ThrownPotion {
|
||||
/// Its entity id once a server's clients track it (0 until then).
|
||||
id: u32,
|
||||
stack: ItemStack,
|
||||
/// The position before the last tick, for drawing between ticks.
|
||||
previous: Vec3,
|
||||
@@ -47,6 +49,7 @@ impl Game<'_> {
|
||||
/// player's throws and dispensers both end up here).
|
||||
pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) {
|
||||
self.potions.thrown.push(ThrownPotion {
|
||||
id: 0,
|
||||
stack,
|
||||
previous: position,
|
||||
position,
|
||||
@@ -90,19 +93,78 @@ impl PotionState {
|
||||
pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> {
|
||||
self.thrown
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let kind = match &*t.stack.item {
|
||||
"minecraft:lingering_potion" => "minecraft:lingering_potion",
|
||||
"minecraft:experience_bottle" => "minecraft:experience_bottle",
|
||||
_ => "minecraft:splash_potion",
|
||||
};
|
||||
(kind, t.position, t.velocity)
|
||||
})
|
||||
.map(|t| (thrown_kind(&t.stack), t.position, t.velocity))
|
||||
.collect()
|
||||
}
|
||||
pub(super) fn clear_thrown(&mut self) {
|
||||
self.thrown.clear();
|
||||
}
|
||||
/// Their entity ids, for a server to number them.
|
||||
pub(super) fn thrown_ids(&mut self) -> impl Iterator<Item = &mut u32> {
|
||||
self.thrown.iter_mut().map(|t| &mut t.id)
|
||||
}
|
||||
/// The numbered ones as a server's clients track them: (id, entity
|
||||
/// type, item, position, motion).
|
||||
pub(super) fn thrown_tracked(
|
||||
&self,
|
||||
) -> impl Iterator<Item = (u32, &'static str, &ItemStack, Vec3, Vec3)> {
|
||||
self.thrown.iter().filter(|t| t.id != 0).map(|t| {
|
||||
(
|
||||
t.id,
|
||||
thrown_kind(&t.stack),
|
||||
&t.stack,
|
||||
t.position,
|
||||
t.velocity,
|
||||
)
|
||||
})
|
||||
}
|
||||
/// `handleAddEntity` for a thrown potion or bottle on a server's client:
|
||||
/// drawn where the server says (its item comes in its entity data).
|
||||
pub(super) fn add_remote_thrown(&mut self, id: u32, kind: &str, at: Vec3, velocity: Vec3) {
|
||||
self.thrown.retain(|t| t.id != id);
|
||||
let item = match kind {
|
||||
"minecraft:lingering_potion" | "minecraft:experience_bottle" => kind,
|
||||
_ => "minecraft:splash_potion",
|
||||
};
|
||||
self.thrown.push(ThrownPotion {
|
||||
id,
|
||||
stack: ItemStack::new(item, 1),
|
||||
previous: at,
|
||||
position: at,
|
||||
velocity,
|
||||
age: 0,
|
||||
});
|
||||
}
|
||||
/// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows.
|
||||
pub(super) fn remote_thrown_item(&mut self, id: u32, stack: ItemStack) {
|
||||
if let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) {
|
||||
t.stack = stack;
|
||||
}
|
||||
}
|
||||
/// One tick of a server's client: `step` moves each toward where the
|
||||
/// server put it.
|
||||
pub(super) fn step_remote_thrown(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
|
||||
for t in &mut self.thrown {
|
||||
t.previous = t.position;
|
||||
t.age += 1;
|
||||
t.position = step(t.id, t.position);
|
||||
}
|
||||
}
|
||||
pub(super) fn remove_remote_thrown(&mut self, id: u32) {
|
||||
self.thrown.retain(|t| t.id != id);
|
||||
}
|
||||
pub(super) fn has_thrown(&self, id: u32) -> bool {
|
||||
self.thrown.iter().any(|t| t.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entity type of a thrown potion or bottle.
|
||||
fn thrown_kind(stack: &ItemStack) -> &'static str {
|
||||
match &*stack.item {
|
||||
"minecraft:lingering_potion" => "minecraft:lingering_potion",
|
||||
"minecraft:experience_bottle" => "minecraft:experience_bottle",
|
||||
_ => "minecraft:splash_potion",
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -297,10 +359,14 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// The local player's effects (`tick_mob_effects`), then the potions
|
||||
/// in flight, which a server without a local player still has.
|
||||
pub(super) fn tick_effects(&mut self) {
|
||||
/// in flight, which a server without a local player still has. A frozen
|
||||
/// tick (`/tick freeze`) leaves the potions where they are
|
||||
/// (`TickRateManager.isEntityFrozen`); players' effects still run.
|
||||
pub(super) fn tick_effects(&mut self, running: bool) {
|
||||
self.tick_mob_effects();
|
||||
self.tick_thrown_potions();
|
||||
if running {
|
||||
self.tick_thrown_potions();
|
||||
}
|
||||
}
|
||||
/// `LivingEntity.tickEffects` (server side) for `self.player`, the local
|
||||
/// player or a guest acting (`as_guest`), then its attribute modifiers
|
||||
|
||||
@@ -164,6 +164,8 @@ pub(super) struct Remote {
|
||||
level_players: HashMap<i32, u128>,
|
||||
/// The local player's profile UUID (always in the level).
|
||||
profile: u128,
|
||||
/// The local player's profile name: its score holder and team member.
|
||||
pub(super) profile_name: String,
|
||||
destroying: Option<([i32; 3], u8, f32)>,
|
||||
destroy_delay: u32,
|
||||
input: horizon_client::interaction_input::InteractionInput,
|
||||
@@ -411,6 +413,7 @@ impl Game<'_> {
|
||||
online_mode: false,
|
||||
level_players: HashMap::new(),
|
||||
profile: 0,
|
||||
profile_name: String::new(),
|
||||
destroying: None,
|
||||
destroy_delay: 0,
|
||||
input: Default::default(),
|
||||
@@ -798,6 +801,7 @@ impl Game<'_> {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.joined = true;
|
||||
r.profile = uuid;
|
||||
r.profile_name = name.clone();
|
||||
r.status = format!("Joined as {name}; loading terrain...");
|
||||
}
|
||||
}
|
||||
@@ -1337,6 +1341,7 @@ impl Game<'_> {
|
||||
}
|
||||
if let Some(t) = mob_type {
|
||||
let mut mob = Mob::new(id as u32, t, at, head);
|
||||
super::remote_mob_data::client_defaults(&mut mob);
|
||||
(mob.yaw, mob.previous_yaw) = (yaw, yaw);
|
||||
(mob.head_pitch, mob.previous_head_pitch) = (pitch, pitch);
|
||||
mob.persistent = true;
|
||||
@@ -1727,29 +1732,10 @@ impl Game<'_> {
|
||||
self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1));
|
||||
}
|
||||
}
|
||||
C::LevelEvent(p) if p.kind == 2015 => {
|
||||
self.dragon_egg_particles(p.pos, p.data);
|
||||
}
|
||||
C::LevelEvent(p) if p.kind == 2017 => {
|
||||
self.consume_teleport_particles(p.pos, p.data);
|
||||
}
|
||||
C::LevelEvent(p) if p.kind == 2001 => {
|
||||
// LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block.
|
||||
let state = BlockStateId(p.data.max(0) as u32);
|
||||
let s = self.res.facts().get(state).sounds.clone();
|
||||
let at = [
|
||||
f64::from(p.pos[0]) + 0.5,
|
||||
f64::from(p.pos[1]) + 0.5,
|
||||
f64::from(p.pos[2]) + 0.5,
|
||||
];
|
||||
self.audio.play(
|
||||
&s.break_sound,
|
||||
Some(at),
|
||||
(s.volume + 1.0) / 2.0,
|
||||
s.pitch * 0.8,
|
||||
);
|
||||
self.destroy_particles(p.pos, state);
|
||||
}
|
||||
// ClientLevel.levelEvent: LevelEventHandler, as this client's own
|
||||
// level plays them (particles and sounds: a spawner's burst, bone
|
||||
// meal, waxing, a block broken by someone else).
|
||||
C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data),
|
||||
C::Sound(p) => {
|
||||
let name = match &p.sound.1 {
|
||||
Some((location, _)) => Some(location.clone()),
|
||||
@@ -1876,6 +1862,19 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers),
|
||||
// ClientPacketListener.handleEntityLinkPacket: who holds a mob's
|
||||
// lead (this player, another player or a mob), for the rope.
|
||||
C::SetEntityLink(p) => {
|
||||
let me = self.remote.as_ref().map(|r| r.entity_id);
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.source as u32) {
|
||||
use horizon_client::mobs::leash::Holder;
|
||||
m.extra.leash = match p.dest {
|
||||
0 => None,
|
||||
d if Some(d) == me => Some(Holder::Player),
|
||||
d => Some(Holder::Mob(d as u32)),
|
||||
};
|
||||
}
|
||||
}
|
||||
C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw),
|
||||
// ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3).
|
||||
C::RotateHead(p) => {
|
||||
@@ -1912,13 +1911,12 @@ impl Game<'_> {
|
||||
&& m.species() == horizon_client::mobs::Species::Rabbit
|
||||
{
|
||||
for (index, _, value) in &p.values {
|
||||
match (index, value) {
|
||||
(15, Value::Byte(flags)) => m.no_ai = flags & 1 != 0,
|
||||
(16, Value::Bool(baby)) => m.extra.age = if *baby { -1 } else { 0 },
|
||||
_ => {}
|
||||
if let (15, Value::Byte(flags)) = (index, value) {
|
||||
m.no_ai = flags & 1 != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.remote_mob_data(p.id, &p.values);
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
|
||||
&& m.species() == horizon_client::mobs::Species::Creeper
|
||||
{
|
||||
@@ -2137,6 +2135,15 @@ impl Game<'_> {
|
||||
m.swing();
|
||||
}
|
||||
}
|
||||
// The player's own instances: its maximum health (the hearts the
|
||||
// HUD draws and the health it may hold), reach, speed and so on.
|
||||
// Then the received health again, which the old maximum clamped.
|
||||
C::UpdateAttributes(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => {
|
||||
if let Some(pl) = self.player.as_mut() {
|
||||
horizon_client::lan::attributes::apply(&mut pl.attributes, &p.values);
|
||||
}
|
||||
self.apply_remote_health();
|
||||
}
|
||||
C::UpdateMobEffect(p) => self.remote_effect(&p),
|
||||
C::RemoveMobEffect(p) => {
|
||||
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
|
||||
@@ -3810,6 +3817,8 @@ impl Game<'_> {
|
||||
}
|
||||
if reacts {
|
||||
self.predict_use(&changes, seq);
|
||||
} else if let Some(stack) = held.as_ref() {
|
||||
self.predict_item_on_block(stack, &hit);
|
||||
}
|
||||
if held_block {
|
||||
if reacts
|
||||
@@ -3828,6 +3837,38 @@ impl Game<'_> {
|
||||
false
|
||||
}
|
||||
|
||||
/// `Item.useOn` on this client's level for the items whose effects are
|
||||
/// the clicker's own (`Level.levelEvent(player, ...)` and
|
||||
/// `playSound(player, ...)`: the server sends them to the others only):
|
||||
/// honeycomb waxing copper, and an axe, hoe or shovel transforming a
|
||||
/// block (stripping, scraping, removing wax, tilling, making a path).
|
||||
fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) {
|
||||
let at = [
|
||||
f64::from(hit.pos[0]) + 0.5,
|
||||
f64::from(hit.pos[1]) + 0.5,
|
||||
f64::from(hit.pos[2]) + 0.5,
|
||||
];
|
||||
if &*stack.item == "minecraft:honeycomb" {
|
||||
// HoneycombItem.useOn.
|
||||
let registry = self.pack.assets.registry;
|
||||
let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let waxes = registry
|
||||
.state(clicked)
|
||||
.and_then(|old| self.res.transformers().waxed(registry, old))
|
||||
.is_some();
|
||||
if waxes {
|
||||
self.level_event_at(3003, hit.pos, 0);
|
||||
self.audio
|
||||
.play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0);
|
||||
}
|
||||
} else if let Some((_, sound, _, _, particle)) =
|
||||
self.block_transform(stack, hit.pos, hit.face)
|
||||
{
|
||||
self.transform_particle(&particle, hit.pos);
|
||||
self.audio.play(&sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the
|
||||
/// use changed on this client's level at once, each kept as predicted
|
||||
/// under the use's sequence until the server acknowledges it (a use the
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! A server's mobs as their synched data has them
|
||||
//! (ClientPacketListener.handleSetEntityData, then each entity's
|
||||
//! `onSyncedDataUpdated`): what a client draws from it rather than from its
|
||||
//! own simulation, which a client of a server doesn't run.
|
||||
use super::Game;
|
||||
use horizon_client::mobs::{Mob, Species, tame};
|
||||
use horizon_protocol::entity_data::Value;
|
||||
|
||||
/// The values `apply` takes from one SetEntityData packet, by vanilla's entry
|
||||
/// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses).
|
||||
fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) {
|
||||
let species = m.species();
|
||||
let baby = super::lan::baby_index(&m.kind.id);
|
||||
for (index, _, value) in values {
|
||||
match (*index, value) {
|
||||
// Entity.DATA_SHARED_FLAGS_ID's FLAG_ONFIRE: Entity.isOnFire on a
|
||||
// client, which draws the flames. A client doesn't count the
|
||||
// fire down: the flag goes off when the server's fire is out.
|
||||
(0, Value::Byte(flags)) => m.fire_ticks = i32::from(flags & 1),
|
||||
// LivingEntity.DATA_HEALTH_ID: the boss bars and the death
|
||||
// animation follow it.
|
||||
(9, Value::Float(health)) => m.health = *health,
|
||||
(i, Value::Bool(b)) if Some(i) == baby => m.extra.age = if *b { -1 } else { 0 },
|
||||
_ => {}
|
||||
}
|
||||
match (species, *index, value) {
|
||||
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared.
|
||||
(Species::Sheep, 18, Value::Byte(wool)) => {
|
||||
m.extra.color = (*wool & 15) as u8;
|
||||
m.extra.sheared = wool & 16 != 0;
|
||||
}
|
||||
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
|
||||
(Species::Wolf | Species::Cat | Species::Parrot, 18, Value::Byte(flags)) => {
|
||||
m.extra.sitting = flags & 1 != 0;
|
||||
m.extra.tame = flags & 4 != 0;
|
||||
}
|
||||
// Wolf.DATA_COLLAR_COLOR and Cat's.
|
||||
(Species::Wolf, 21, Value::Int(c)) | (Species::Cat, 23, Value::Int(c)) => {
|
||||
m.extra.color = (*c & 15) as u8;
|
||||
}
|
||||
// AbstractCubeMob.ID_SIZE: its size and box (refreshDimensions).
|
||||
(Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => {
|
||||
m.extra.size = (*size).clamp(1, 127);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// SetEntityData for a mob of the server's.
|
||||
pub(super) fn remote_mob_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
|
||||
apply(m, values);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mob as a client constructs it before its data arrives: the synched
|
||||
/// defaults the server leaves out (`getNonDefaultValues`) that differ from
|
||||
/// what `Mob::new` gives, such as a wolf's and a cat's red collar.
|
||||
pub(super) fn client_defaults(m: &mut Mob) {
|
||||
if matches!(m.species(), Species::Wolf | Species::Cat) {
|
||||
m.extra.color = tame::RED;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_protocol::entity_data::serializer as s;
|
||||
|
||||
/// A mob of the prepared resources' type `kind`, as a client spawns it
|
||||
/// (None without the resources).
|
||||
fn mob(kind: &str) -> Option<Mob> {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
let types = horizon_client::mobs::MobTypes::load(&root).ok()?;
|
||||
let t = std::sync::Arc::new(types.types.get(kind)?.clone());
|
||||
let mut m = Mob::new(1, t, horizon_core::geometry::Vec3::ZERO, 0.0);
|
||||
client_defaults(&mut m);
|
||||
Some(m)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheep_takes_its_wool_and_a_calf_its_size() {
|
||||
let Some(mut m) = mob("minecraft:sheep") else {
|
||||
return;
|
||||
};
|
||||
apply(&mut m, &[(18, s::BYTE, Value::Byte(14 | 16))]);
|
||||
assert_eq!((m.extra.color, m.extra.sheared), (14, true));
|
||||
apply(&mut m, &[(18, s::BYTE, Value::Byte(0))]);
|
||||
assert_eq!((m.extra.color, m.extra.sheared), (0, false));
|
||||
let mut calf = mob("minecraft:cow").unwrap();
|
||||
apply(&mut calf, &[(16, s::BOOLEAN, Value::Bool(true))]);
|
||||
assert!(calf.is_baby());
|
||||
apply(&mut calf, &[(16, s::BOOLEAN, Value::Bool(false))]);
|
||||
assert!(!calf.is_baby());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wolf_takes_its_owner_flags_and_collar() {
|
||||
let Some(mut m) = mob("minecraft:wolf") else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(m.extra.color, tame::RED);
|
||||
apply(
|
||||
&mut m,
|
||||
&[
|
||||
(18, s::BYTE, Value::Byte(4 | 1)),
|
||||
(21, s::INT, Value::Int(11)),
|
||||
],
|
||||
);
|
||||
assert!(m.extra.tame && m.extra.sitting);
|
||||
assert_eq!(m.extra.color, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fire_health_and_size_follow_the_server() {
|
||||
let Some(mut m) = mob("minecraft:slime") else {
|
||||
return;
|
||||
};
|
||||
apply(
|
||||
&mut m,
|
||||
&[
|
||||
(0, s::BYTE, Value::Byte(1)),
|
||||
(9, s::FLOAT, Value::Float(12.5)),
|
||||
(18, s::INT, Value::Int(4)),
|
||||
],
|
||||
);
|
||||
assert_eq!((m.fire_ticks, m.health, m.extra.size), (1, 12.5, 4));
|
||||
apply(&mut m, &[(0, s::BYTE, Value::Byte(0))]);
|
||||
assert_eq!(m.fire_ticks, 0);
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,15 @@ impl Game<'_> {
|
||||
self.rockets
|
||||
.push(super::fireworks::Rocket::remote(id, at, velocity));
|
||||
}
|
||||
"minecraft:splash_potion"
|
||||
| "minecraft:lingering_potion"
|
||||
| "minecraft:experience_bottle" => {
|
||||
self.potions.add_remote_thrown(id, kind, at, velocity);
|
||||
}
|
||||
"minecraft:eye_of_ender" => {
|
||||
self.end
|
||||
.add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z])
|
||||
}
|
||||
"minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal {
|
||||
id,
|
||||
position: at,
|
||||
@@ -105,6 +114,17 @@ impl Game<'_> {
|
||||
/// `handleSetEntityData` for these types: what changes how they look.
|
||||
pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
|
||||
let id = id as u32;
|
||||
if self.potions.has_thrown(id) {
|
||||
// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is.
|
||||
for (index, _, value) in values {
|
||||
if let (8, Value::Item(stack)) = (index, value)
|
||||
&& let Some(stack) = self.to_stack(stack)
|
||||
{
|
||||
self.potions.remote_thrown_item(id, stack);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (index, _, value) in values {
|
||||
if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) {
|
||||
// PrimedTnt.DATA_FUSE_ID.
|
||||
@@ -184,6 +204,11 @@ impl Game<'_> {
|
||||
c.time += 1;
|
||||
c.position = step(c.id, c.position);
|
||||
}
|
||||
self.potions.step_remote_thrown(&mut step);
|
||||
self.end.step_remote_eyes(|id, at| {
|
||||
let at = step(id, Vec3::new(at[0], at[1], at[2]));
|
||||
[at.x, at.y, at.z]
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn remove_remote_projectile(&mut self, id: u32) {
|
||||
@@ -193,6 +218,8 @@ impl Game<'_> {
|
||||
self.tridents.retain(|t| t.id != id);
|
||||
self.rockets.retain(|r| r.id != id);
|
||||
self.crystals.retain(|c| c.id != id);
|
||||
self.potions.remove_remote_thrown(id);
|
||||
self.end.remove_remote_eye(id);
|
||||
}
|
||||
|
||||
/// Every one a server sent (a new connection, level or dimension).
|
||||
@@ -203,6 +230,8 @@ impl Game<'_> {
|
||||
self.tridents.clear();
|
||||
self.rockets.clear();
|
||||
self.crystals.clear();
|
||||
self.potions.clear_thrown();
|
||||
self.end.clear_remote_eyes();
|
||||
}
|
||||
|
||||
/// Their kind and place, for `status`.
|
||||
@@ -225,6 +254,12 @@ impl Game<'_> {
|
||||
for p in &self.creatures.projectiles {
|
||||
out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)}));
|
||||
}
|
||||
for (kind, p, _) in self.potions.thrown_entities() {
|
||||
out.push(json!({"kind": kind, "position": at(p)}));
|
||||
}
|
||||
for (id, p) in self.end.eye_positions() {
|
||||
out.push(json!({"id": id, "kind": "minecraft:eye_of_ender", "position": p}));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,6 +324,22 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ServerScoreboard`'s packets: each placed player's client is sent
|
||||
/// what changed on the board since it was last sent it (all of it on
|
||||
/// joining), lan/scoreboard.rs.
|
||||
pub(super) fn lan_sync_scoreboard(&mut self, host: &mut super::lan::LanHost) {
|
||||
if host.hub.guests.iter().all(|g| !g.placed) {
|
||||
return;
|
||||
}
|
||||
self.load_scoreboard();
|
||||
let view = horizon_client::lan::scoreboard::View::of(&self.score.board);
|
||||
for g in host.hub.guests.iter_mut().filter(|g| g.placed) {
|
||||
if g.scoreboard != view {
|
||||
g.send_all(&g.scoreboard.changes(&view));
|
||||
g.scoreboard = view.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ServerPlayer.doTick` score updates and the statistic criteria.
|
||||
pub(super) fn tick_scoreboard(&mut self) {
|
||||
self.load_scoreboard();
|
||||
@@ -563,19 +579,42 @@ impl Game<'_> {
|
||||
|
||||
// ---- the sidebar -----------------------------------------------------------
|
||||
|
||||
/// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`.
|
||||
pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) {
|
||||
/// The objective in the player's team's sidebar slot, else the sidebar's.
|
||||
fn sidebar_objective(&self) -> Option<&sb::Objective> {
|
||||
let board = &self.score.board;
|
||||
if board.display.is_empty() {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
// A server's client is in its team by its profile name.
|
||||
let name = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map_or(PLAYER_NAME, |r| r.profile_name.as_str());
|
||||
let team_slot = board
|
||||
.players_team(PLAYER_NAME)
|
||||
.players_team(name)
|
||||
.and_then(|t| t.color.as_ref())
|
||||
.map(|c| format!("sidebar.team.{c}"))
|
||||
.and_then(|slot| board.display_objective(&slot));
|
||||
let Some(objective) = team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR))
|
||||
else {
|
||||
team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR))
|
||||
}
|
||||
/// The sidebar the HUD shows: its objective and its lines, for `status`.
|
||||
pub(super) fn sidebar_status(&self) -> serde_json::Value {
|
||||
let board = &self.score.board;
|
||||
let Some(objective) = self.sidebar_objective() else {
|
||||
return serde_json::Value::Null;
|
||||
};
|
||||
let scores: serde_json::Map<String, serde_json::Value> = board
|
||||
.scores
|
||||
.iter()
|
||||
.filter_map(|(holder, s)| Some((holder.clone(), s.get(&objective.name)?.value.into())))
|
||||
.collect();
|
||||
serde_json::json!({ "objective": objective.name, "title": objective.display_text().plain(), "scores": scores })
|
||||
}
|
||||
|
||||
/// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`.
|
||||
pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) {
|
||||
let board = &self.score.board;
|
||||
let Some(objective) = self.sidebar_objective() else {
|
||||
return;
|
||||
};
|
||||
let draws = hud_overlays::sidebar(
|
||||
|
||||
@@ -101,6 +101,21 @@ impl Game<'_> {
|
||||
self.load_shader_pack();
|
||||
}
|
||||
}
|
||||
/// A file dropped on the window: a shader pack while the Shader Packs
|
||||
/// page shows (`OptionsUi::drop_shader_pack`).
|
||||
pub(super) fn drop_shader_pack(&mut self, path: &std::path::Path) {
|
||||
match self.ui.options.drop_shader_pack(&mut self.settings, path) {
|
||||
Some(Ok(())) => {
|
||||
self.settings.save(&Self::options_path());
|
||||
self.load_shader_pack();
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
log::warn!("Horizon: shader pack {}: {e}", path.display());
|
||||
self.system_message(Text::literal(format!("Shader pack: {e}")));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
fn shader_pack_error(&mut self, id: &str, error: &str) {
|
||||
log::warn!("Horizon: shader pack {id}: {error}");
|
||||
// The Shader Packs page says why on the pack's row: the first line,
|
||||
|
||||
@@ -387,6 +387,9 @@ impl Loading {
|
||||
self.menu.win = Some((screen, Instant::now()));
|
||||
}
|
||||
}
|
||||
Event::ReloadShaderPack => {
|
||||
self.save_menu_settings();
|
||||
}
|
||||
// The startup menu runs before the game opens a control socket.
|
||||
Event::ButtonClick | Event::CopyAgentDetails => {}
|
||||
}
|
||||
@@ -452,6 +455,17 @@ impl Loading {
|
||||
}
|
||||
self.apply_menu_settings();
|
||||
}
|
||||
WindowEvent::DroppedFile(path) => {
|
||||
match self
|
||||
.menu
|
||||
.options
|
||||
.drop_shader_pack(&mut self.settings, &path)
|
||||
{
|
||||
Some(Ok(())) => self.save_menu_settings(),
|
||||
Some(Err(e)) => log::warn!("Horizon: shader pack {}: {e}", path.display()),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => self.draw(),
|
||||
WindowEvent::ModifiersChanged(modifiers) => self.menu.modifiers = modifiers.state(),
|
||||
WindowEvent::Focused(false) => {
|
||||
|
||||
@@ -306,9 +306,18 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `PhantomSpawner.tick`: tired players under an open night sky draw
|
||||
/// phantoms.
|
||||
/// phantoms. A custom spawner ticks only while `spawn_mobs` is on
|
||||
/// (`ServerChunkCache.tickChunks`), and this one only spawns enemies
|
||||
/// (`ServerLevel.isSpawningMonsters`: `spawn_monsters` too). Every
|
||||
/// player of the level counts: the game's own and the hosted ones (a
|
||||
/// server thread's players are all hosted).
|
||||
pub(super) fn spawn_phantoms(&mut self) {
|
||||
if !self.ui.rules.bool("spawn_phantoms") || self.dim != Dim::Overworld {
|
||||
let rules = &self.ui.rules;
|
||||
if !rules.bool("spawn_mobs")
|
||||
|| !rules.bool("spawn_monsters")
|
||||
|| !rules.bool("spawn_phantoms")
|
||||
|| self.dim != Dim::Overworld
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.stats.phantom_tick -= 1;
|
||||
@@ -317,16 +326,42 @@ impl Game<'_> {
|
||||
}
|
||||
let r = &mut self.world.random;
|
||||
self.stats.phantom_tick += (60 + r.next_int_bound(60).unwrap_or(0)) * 20;
|
||||
if self.sky_darken() < 5 || self.spectator() {
|
||||
if self.sky_darken() < 5 {
|
||||
return;
|
||||
}
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let rest = |s: &Stats| s.get("custom", "minecraft:time_since_rest");
|
||||
// `level.players()`: (block position, time since rest) of each player
|
||||
// who isn't a spectator.
|
||||
let mut players = Vec::new();
|
||||
if let Some(p) = self.player.as_ref()
|
||||
&& !self.spectator()
|
||||
{
|
||||
players.push((p.position, rest(&self.stats)));
|
||||
}
|
||||
if let Some(host) = self.lan.as_ref() {
|
||||
let level = self.dim.id();
|
||||
for g in host.hub.guests.iter().filter(|g| {
|
||||
g.placed
|
||||
&& g.dimension == level
|
||||
&& g.game_mode != horizon_client::lan::guest::SPECTATOR
|
||||
}) {
|
||||
let since = host.play.get(&g.conn).map_or(0, |p| rest(&p.stats));
|
||||
players.push((
|
||||
Vec3::new(g.position[0], g.position[1], g.position[2]),
|
||||
since,
|
||||
));
|
||||
}
|
||||
}
|
||||
for (position, since) in players {
|
||||
self.spawn_phantoms_near(position, since);
|
||||
}
|
||||
}
|
||||
/// One player's turn of `PhantomSpawner.tick`.
|
||||
fn spawn_phantoms_near(&mut self, position: Vec3, since_rest: i32) {
|
||||
let pos = [
|
||||
p.position.x.floor() as i32,
|
||||
p.position.y.floor() as i32,
|
||||
p.position.z.floor() as i32,
|
||||
position.x.floor() as i32,
|
||||
position.y.floor() as i32,
|
||||
position.z.floor() as i32,
|
||||
];
|
||||
if pos[1] < 63 || !self.can_see_sky(pos) {
|
||||
return;
|
||||
@@ -336,15 +371,15 @@ impl Game<'_> {
|
||||
if r.next_float() * 3.0 >= 2.0 {
|
||||
return;
|
||||
}
|
||||
let rest = self.stats.get("custom", "minecraft:time_since_rest").max(1);
|
||||
if r.next_int_bound(rest).unwrap_or(0) < 72000 {
|
||||
if r.next_int_bound(since_rest.max(1)).unwrap_or(0) < 72000 {
|
||||
return;
|
||||
}
|
||||
let at = [
|
||||
pos[0] - 10 + r.next_int_bound(21).unwrap_or(10),
|
||||
pos[1] + 20 + r.next_int_bound(15).unwrap_or(0),
|
||||
pos[2] - 10 + r.next_int_bound(21).unwrap_or(10),
|
||||
];
|
||||
// `playerPos.above(20 + nextInt(15)).east(-10 + nextInt(21)).south(...)`:
|
||||
// the height is drawn first.
|
||||
let up = 20 + r.next_int_bound(15).unwrap_or(0);
|
||||
let east = -10 + r.next_int_bound(21).unwrap_or(10);
|
||||
let south = -10 + r.next_int_bound(21).unwrap_or(10);
|
||||
let at = [pos[0] + east, pos[1] + up, pos[2] + south];
|
||||
if !self
|
||||
.res
|
||||
.facts()
|
||||
|
||||
@@ -83,6 +83,40 @@ mod world_post;
|
||||
const COMPLETE_COLUMN: u32 = (1 << (crate::chunk::HEIGHT / 16)) - 1;
|
||||
/// A section's instance: its camera-relative origin and, in `w`, the step of
|
||||
/// its fixed-point UVs (`terrain.wgsl`'s `terrain_uv`).
|
||||
/// The world pass again after occlusion culling's test: it loads both
|
||||
/// targets (phase 2 draws over phase 1, reading the test's results).
|
||||
fn world_pass_after_culling<'e>(
|
||||
encoder: &'e mut wgpu::CommandEncoder,
|
||||
view: &wgpu::TextureView,
|
||||
depth: &wgpu::TextureView,
|
||||
pack: bool,
|
||||
) -> wgpu::RenderPass<'e> {
|
||||
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon world, after culling"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: if pack {
|
||||
wgpu::StoreOp::Store
|
||||
} else {
|
||||
wgpu::StoreOp::Discard
|
||||
},
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
fn section_instance(origin: [f32; 3]) -> [f32; 4] {
|
||||
[
|
||||
origin[0],
|
||||
@@ -316,7 +350,8 @@ pub struct Renderer {
|
||||
flat: Option<flat::Flat>,
|
||||
/// `flat` draws this frame's sections (off: the per-section draws).
|
||||
flat_on: bool,
|
||||
/// Occlusion culling of solid section draws, where multi-draw is native.
|
||||
/// Occlusion culling of solid section draws, where the GPU's instance
|
||||
/// counts reach a multi-draw's entries (Vulkan, Metal).
|
||||
cull: Option<cull::Cull>,
|
||||
cull_on: bool,
|
||||
sky: wgpu::RenderPipeline,
|
||||
@@ -332,6 +367,11 @@ pub struct Renderer {
|
||||
/// (`crosshair_globals`).
|
||||
crosshair_group: wgpu::BindGroup,
|
||||
crosshair_globals: wgpu::Buffer,
|
||||
shadow_pipeline: wgpu::RenderPipeline,
|
||||
shadow_entity_pipeline: wgpu::RenderPipeline,
|
||||
shadow_globals: wgpu::Buffer,
|
||||
shadow_group: wgpu::BindGroup,
|
||||
shadow_entity_group: wgpu::BindGroup,
|
||||
entity_pipeline: wgpu::RenderPipeline,
|
||||
weather: weather::Weather,
|
||||
crumbling_pipeline: wgpu::RenderPipeline,
|
||||
@@ -1272,6 +1312,38 @@ impl Renderer {
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let shadow_globals = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack shadow globals"),
|
||||
size: std::mem::size_of::<Globals>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Terrain shadow"),
|
||||
layout: Some(&layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_terrain"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &terrain_buffers,
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: tri,
|
||||
cull_mode: Some(wgpu::Face::Back),
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: None,
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let prepared = prepared.unwrap_or_else(|| {
|
||||
PreparedTextures::new(sprite_pixels, sprite_size, layers, sprite_mips, forcefield)
|
||||
});
|
||||
@@ -1385,6 +1457,16 @@ impl Renderer {
|
||||
&lightmap_view,
|
||||
&lightmap_sampler,
|
||||
);
|
||||
let shadow_group = terrain_group(
|
||||
&device,
|
||||
"Shader pack shadow terrain resources",
|
||||
&bindings,
|
||||
&shadow_globals,
|
||||
&sprite_views,
|
||||
&sprite_sampler,
|
||||
&lightmap_view,
|
||||
&lightmap_sampler,
|
||||
);
|
||||
let index_quads = 1 << 16;
|
||||
let indices = Self::quad_indices(&device, index_quads);
|
||||
let instance_capacity = 4096;
|
||||
@@ -1408,8 +1490,14 @@ impl Renderer {
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let depth = Self::depth(&device, &config);
|
||||
let (atlas_pixels, atlas_width, atlas_height) = hud_atlas;
|
||||
let limit = device.limits().max_texture_dimension_2d;
|
||||
if atlas_width.max(atlas_height) > limit {
|
||||
return Err(format!(
|
||||
"the shared atlas is {atlas_width}x{atlas_height}; this GPU allows {limit}x{limit}"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let atlas = device.create_texture_with_data(
|
||||
&queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
@@ -1540,6 +1628,32 @@ impl Renderer {
|
||||
},
|
||||
],
|
||||
});
|
||||
let shadow_entity_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Shader pack shadow entity resources"),
|
||||
layout: &entity_bindings,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: shadow_globals.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&atlas_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Sampler(&atlas_sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::TextureView(&lightmap_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: wgpu::BindingResource::Sampler(&lightmap_sampler),
|
||||
},
|
||||
],
|
||||
});
|
||||
let entity_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Entity layout"),
|
||||
bind_group_layouts: &[Some(&entity_bindings)],
|
||||
@@ -1650,6 +1764,32 @@ impl Renderer {
|
||||
wgpu::ColorWrites::ALL,
|
||||
)
|
||||
};
|
||||
let shadow_entity_pipeline =
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Entity shadow"),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &entity_shader,
|
||||
entry_point: Some("vs_entity"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &entity_vertex,
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: None,
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
// RenderPipelines.WATER_MASK: the boat's water patch writes depth only.
|
||||
let water_mask_pipeline = entity_pipeline_with(
|
||||
"Water mask",
|
||||
@@ -2112,14 +2252,25 @@ impl Renderer {
|
||||
.features()
|
||||
.contains(wgpu::Features::INDIRECT_FIRST_INSTANCE);
|
||||
// HORIZON_GPU_CULL=0 turns occlusion culling off, `all` culls every
|
||||
// frame however little it hides (A/B checks).
|
||||
// frame however few its draws and little it hides, `shader` tests in
|
||||
// the shader as on Metal (A/B checks).
|
||||
let cull_env = std::env::var("HORIZON_GPU_CULL");
|
||||
let cull = (cull_env.as_deref() != Ok("0") && cull::Cull::supported(&adapter, &device))
|
||||
.then(|| {
|
||||
let mut cull = cull::Cull::new(&device, config.format.remove_srgb_suffix());
|
||||
let cull = cull::Cull::supported(&adapter, &device)
|
||||
.filter(|_| cull_env.as_deref() != Ok("0"))
|
||||
.map(|depth_test| match cull_env.as_deref() {
|
||||
Ok("shader") => cull::DepthTest::InShader,
|
||||
_ => depth_test,
|
||||
})
|
||||
.map(|depth_test| {
|
||||
let mut cull =
|
||||
cull::Cull::new(&device, config.format.remove_srgb_suffix(), depth_test);
|
||||
cull.always = cull_env.as_deref() == Ok("all");
|
||||
if !cull.always && adapter.get_info().backend == wgpu::Backend::Metal {
|
||||
cull.min_draws = cull::TILED_MIN_DRAWS;
|
||||
}
|
||||
cull
|
||||
});
|
||||
let depth = Self::depth(&device, &config, cull.as_ref());
|
||||
let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix());
|
||||
let uploads = upload::Uploads::new(&device);
|
||||
let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK);
|
||||
@@ -2173,6 +2324,11 @@ impl Renderer {
|
||||
debug_line_capacity: 4096,
|
||||
crosshair_group,
|
||||
crosshair_globals,
|
||||
shadow_pipeline,
|
||||
shadow_entity_pipeline,
|
||||
shadow_globals,
|
||||
shadow_group,
|
||||
shadow_entity_group,
|
||||
entity_pipeline,
|
||||
weather,
|
||||
crumbling_pipeline,
|
||||
@@ -2307,10 +2463,6 @@ impl Renderer {
|
||||
view_formats: &config.view_formats,
|
||||
})
|
||||
}
|
||||
/// Rendering to a texture instead of the window (`--offscreen`).
|
||||
pub fn is_offscreen(&self) -> bool {
|
||||
self.surface.is_none()
|
||||
}
|
||||
/// Release the window surface before another renderer uses the same window.
|
||||
pub fn release_surface(&mut self) {
|
||||
self.surface = None;
|
||||
@@ -2327,7 +2479,13 @@ impl Renderer {
|
||||
self.surface = Some(surface);
|
||||
Ok(())
|
||||
}
|
||||
fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView {
|
||||
/// The world's depth, which occlusion culling's test may read.
|
||||
fn depth(
|
||||
device: &wgpu::Device,
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
cull: Option<&cull::Cull>,
|
||||
) -> wgpu::TextureView {
|
||||
let read = cull.is_some_and(|c| c.depth_test() == cull::DepthTest::InShader);
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Horizon depth"),
|
||||
@@ -2340,7 +2498,11 @@ impl Renderer {
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
usage: if read {
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING
|
||||
} else {
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
},
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
@@ -2391,7 +2553,7 @@ impl Renderer {
|
||||
} else {
|
||||
self.offscreen = Some(Self::offscreen_target(&self.device, &self.config));
|
||||
}
|
||||
self.depth = Self::depth(&self.device, &self.config);
|
||||
self.depth = Self::depth(&self.device, &self.config, self.cull.as_ref());
|
||||
}
|
||||
/// Whether sections are drawn as one index list per frame (`flat`).
|
||||
pub fn flat_draws(&self) -> bool {
|
||||
@@ -2677,7 +2839,12 @@ impl Renderer {
|
||||
&pack.id,
|
||||
java,
|
||||
)?),
|
||||
None => Pack::Horizon(pack_stages::PackStages::new(&self.device, format, pack)?),
|
||||
None => Pack::Horizon(pack_stages::PackStages::new(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
format,
|
||||
pack,
|
||||
)?),
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
@@ -2719,6 +2886,16 @@ impl Renderer {
|
||||
&self.lightmap_view,
|
||||
&self.lightmap_sampler,
|
||||
);
|
||||
self.shadow_group = terrain_group(
|
||||
&self.device,
|
||||
"Shader pack shadow terrain resources",
|
||||
&self.terrain_layout,
|
||||
&self.shadow_globals,
|
||||
&views,
|
||||
&self.sprite_sampler,
|
||||
&self.lightmap_view,
|
||||
&self.lightmap_sampler,
|
||||
);
|
||||
}
|
||||
pub fn view_projection(&self, frame: &Frame) -> Mat4 {
|
||||
self.projection(
|
||||
@@ -3096,15 +3273,13 @@ impl Renderer {
|
||||
.inverse()
|
||||
.transform_point3(Vec3::ZERO);
|
||||
// Occlusion culling leaves the sections its last result did not see
|
||||
// to phase 2, after the others, with instance counts of 0.
|
||||
// to phase 2, after the others, with instance counts of 0. Whether
|
||||
// the frame has draws enough goes by the last one's.
|
||||
let mut cull = self
|
||||
.cull
|
||||
.as_mut()
|
||||
.filter(|_| {
|
||||
self.cull_on
|
||||
&& !frame.title
|
||||
&& self.multi_draw
|
||||
&& !(self.flat_on && self.flat.is_some())
|
||||
.filter(|c| {
|
||||
self.cull_on && !frame.title && self.multi_draw && self.section_draws >= c.min_draws
|
||||
})
|
||||
.and_then(|cull| cull.begin(&self.device).then_some(cull));
|
||||
self.phase2_draws.clear();
|
||||
@@ -3491,6 +3666,16 @@ impl Renderer {
|
||||
frame.hud,
|
||||
[self.config.width, self.config.height],
|
||||
);
|
||||
if culling && let Some(cull) = &mut self.cull {
|
||||
cull.upload(
|
||||
&self.device,
|
||||
&mut self.uploads,
|
||||
&mut encoder,
|
||||
&self.draws[phase1_draws as usize..solid_draws as usize],
|
||||
&self.instances,
|
||||
&self.globals,
|
||||
);
|
||||
}
|
||||
let flat_frame = match &mut self.flat {
|
||||
Some(flat)
|
||||
if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws =>
|
||||
@@ -3498,6 +3683,7 @@ impl Renderer {
|
||||
let sections = &self.sections;
|
||||
let lods = &self.lods;
|
||||
let sorted = &self.sorted_indices;
|
||||
let phase2 = self.cull.as_ref().filter(|_| culling).map(|c| &c.phase2);
|
||||
crate::spans::time("flatten", || {
|
||||
flat.prepare(
|
||||
&self.device,
|
||||
@@ -3505,7 +3691,9 @@ impl Renderer {
|
||||
&mut self.uploads,
|
||||
&self.draws,
|
||||
&self.draw_pages,
|
||||
phase1_draws as usize,
|
||||
solid_draws as usize,
|
||||
phase2,
|
||||
visible
|
||||
.iter()
|
||||
.filter_map(|v| {
|
||||
@@ -3540,16 +3728,6 @@ impl Renderer {
|
||||
0,
|
||||
bytemuck::cast_slice(&self.draws),
|
||||
);
|
||||
if culling && let Some(cull) = &mut self.cull {
|
||||
cull.upload(
|
||||
&self.device,
|
||||
&mut self.uploads,
|
||||
&mut encoder,
|
||||
&self.draws[phase1_draws as usize..solid_draws as usize],
|
||||
&self.instances,
|
||||
&self.globals,
|
||||
);
|
||||
}
|
||||
}
|
||||
let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
format: Some(self.config.format.remove_srgb_suffix()),
|
||||
@@ -3560,14 +3738,81 @@ impl Renderer {
|
||||
}
|
||||
// The world's targets: the screen, or the scaled target of `post`.
|
||||
let pack = self.pack.is_some() && !frame.title;
|
||||
let scaled =
|
||||
// What the pack reads beyond the world's colour and depth: each costs
|
||||
// a pass (the shadow map, the G-buffer) or a copy (the opaque depth).
|
||||
let (shadow_cfg, gbuffer, opaque_depth) = match self.pack.as_ref().filter(|_| pack) {
|
||||
Some(Pack::Horizon(s)) => (
|
||||
s.needs_shadow.then_some((s.shadow_res, s.shadow_dist)),
|
||||
s.needs_gbuffer,
|
||||
s.needs_opaque_depth,
|
||||
),
|
||||
Some(Pack::Java(s)) => (None, false, s.reads_opaque_depth),
|
||||
None => (None, false, false),
|
||||
};
|
||||
if let Some((shadow_res, shadow_dist)) = shadow_cfg {
|
||||
self.world_post
|
||||
.prepare(&self.device, [self.config.width, self.config.height], pack);
|
||||
.prepare_shadow(&self.device, shadow_res, shadow_dist, sun, -sun);
|
||||
let shadow_globals = Globals {
|
||||
view_proj: (self.world_post.shadow_proj * self.world_post.shadow_view)
|
||||
.to_cols_array_2d(),
|
||||
..globals
|
||||
};
|
||||
self.uploads.buffer(
|
||||
&mut encoder,
|
||||
&self.shadow_globals,
|
||||
0,
|
||||
bytemuck::bytes_of(&shadow_globals),
|
||||
);
|
||||
} else {
|
||||
self.world_post.shadow_active = false;
|
||||
}
|
||||
let scaled = self.world_post.prepare(
|
||||
&self.device,
|
||||
[self.config.width, self.config.height],
|
||||
pack,
|
||||
world_post::Extras {
|
||||
opaque_depth,
|
||||
gbuffer,
|
||||
},
|
||||
);
|
||||
let (world_view, world_depth) = match &scaled {
|
||||
Some((color, depth)) => (color, depth),
|
||||
None => (&view_target, &self.depth),
|
||||
};
|
||||
if culling && let Some(cull) = &mut self.cull {
|
||||
cull.bind_depth(&self.device, world_depth);
|
||||
}
|
||||
let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0);
|
||||
if shadow_cfg.is_some() {
|
||||
let shadow_view = self.world_post.shadow_depth().clone();
|
||||
let mut shadow_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon shadow"),
|
||||
color_attachments: &[],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &shadow_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
store: wgpu::StoreOp::Store,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
if solid_draws > 0 && !flat_frame {
|
||||
shadow_pass.set_bind_group(0, &self.shadow_group, &[]);
|
||||
shadow_pass.set_pipeline(&self.shadow_pipeline);
|
||||
shadow_pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
shadow_pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut shadow_pass, &self.indirect, 0, 0, solid_draws);
|
||||
}
|
||||
if entity_quads > 0 {
|
||||
shadow_pass.set_pipeline(&self.shadow_entity_pipeline);
|
||||
shadow_pass.set_bind_group(0, &self.shadow_entity_group, &[]);
|
||||
shadow_pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
shadow_pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
shadow_pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
|
||||
}
|
||||
}
|
||||
{
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
@@ -3647,9 +3892,28 @@ impl Renderer {
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.solid);
|
||||
flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
let vertices = |p| self.arena.buffer(p);
|
||||
match cull {
|
||||
// As below: phase 1, the test, then phase 2's draws
|
||||
// that the test saw, copied after it.
|
||||
Some(cull) => {
|
||||
flat.draw(&mut pass, &flat.calls[..flat.phase1_calls], vertices);
|
||||
cull.test(&mut pass);
|
||||
drop(pass);
|
||||
cull.test_pass(&mut encoder);
|
||||
flat.flatten_phase2(&mut encoder);
|
||||
pass = world_pass_after_culling(
|
||||
&mut encoder,
|
||||
world_view,
|
||||
world_depth,
|
||||
pack,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_pipeline(&flat.solid);
|
||||
flat.draw_phase2(&mut pass, vertices);
|
||||
}
|
||||
None => flat.draw(&mut pass, &flat.calls[..flat.solid_calls], vertices),
|
||||
}
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
@@ -3659,40 +3923,20 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
match cull {
|
||||
Some(cull) => {
|
||||
// Phase 1 and the boxes against its depth, then
|
||||
// Phase 1 and the boxes against its depth (in
|
||||
// its pass, or one of their own on Metal), then
|
||||
// what they found in sight, in a pass that loads
|
||||
// both targets (it reads the test's results).
|
||||
self.draw_sections(&mut pass, &self.indirect, 0, 0, phase1_draws);
|
||||
cull.test(&mut pass);
|
||||
drop(pass);
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon world, after culling"),
|
||||
color_attachments: &attachments,
|
||||
depth_stencil_attachment: Some(
|
||||
wgpu::RenderPassDepthStencilAttachment {
|
||||
view: world_depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: if pack {
|
||||
wgpu::StoreOp::Store
|
||||
} else {
|
||||
wgpu::StoreOp::Discard
|
||||
},
|
||||
}),
|
||||
stencil_ops: None,
|
||||
},
|
||||
),
|
||||
..Default::default()
|
||||
});
|
||||
cull.test_pass(&mut encoder);
|
||||
pass = world_pass_after_culling(
|
||||
&mut encoder,
|
||||
world_view,
|
||||
world_depth,
|
||||
pack,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_pipeline(&self.solid);
|
||||
pass.set_index_buffer(
|
||||
@@ -3769,6 +4013,33 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
|
||||
pass.draw(0..4, debug_depth..debug_depth + debug_top);
|
||||
}
|
||||
if opaque_depth {
|
||||
drop(pass);
|
||||
self.world_post.capture_opaque_depth(&mut encoder);
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon world, translucent"),
|
||||
color_attachments: &attachments,
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: world_depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.translucent);
|
||||
@@ -3840,6 +4111,15 @@ impl Renderer {
|
||||
);
|
||||
}
|
||||
}
|
||||
if gbuffer && scaled.is_some() {
|
||||
self.world_post.build_gbuffer(
|
||||
&self.queue,
|
||||
&mut encoder,
|
||||
&pack_uniform,
|
||||
frame.shader.eye_light,
|
||||
frame.shader.rain,
|
||||
);
|
||||
}
|
||||
if let (true, Some((color, depth)), Some(size), Some(stages)) =
|
||||
(pack, &scaled, self.world_post.size(), self.pack.as_mut())
|
||||
{
|
||||
@@ -3853,6 +4133,7 @@ impl Renderer {
|
||||
size,
|
||||
&self.world_post,
|
||||
pack_uniform,
|
||||
frame.shader.eye_light,
|
||||
),
|
||||
Pack::Java(stages) => stages.run(
|
||||
&self.device,
|
||||
@@ -4005,7 +4286,11 @@ impl Renderer {
|
||||
cull.end(&self.device, &mut encoder);
|
||||
}
|
||||
if let Some(timer) = &mut self.gpu_timer {
|
||||
timer.end(&mut encoder);
|
||||
timer.end(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
(&view_target, self.config.format.remove_srgb_suffix()),
|
||||
);
|
||||
}
|
||||
let readback = self.screenshot.take().and_then(|path| {
|
||||
// The copy and PNG writer both assume 8-bit pixels; a float surface would make
|
||||
@@ -4036,7 +4321,7 @@ impl Renderer {
|
||||
cull.submitted();
|
||||
}
|
||||
if let Some(timer) = &mut self.gpu_timer {
|
||||
timer.submitted();
|
||||
timer.submitted(&self.queue);
|
||||
timer.collect(&self.device, &mut self.gpu_times);
|
||||
}
|
||||
if let Some((path, buffer)) = readback {
|
||||
@@ -4401,7 +4686,11 @@ mod tests {
|
||||
);
|
||||
assert!(files.len() >= 10, "{files:?}");
|
||||
for path in files {
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let mut text = std::fs::read_to_string(&path).unwrap();
|
||||
// Api 2's prelude follows api 1's (`shader_pack::ShaderPack::load`).
|
||||
if path.ends_with("shader_pack_prelude_api2.wgsl") {
|
||||
text = format!("{}\n{text}", crate::shader_pack::PRELUDE);
|
||||
}
|
||||
// entity.wgsl comes after the overlay's constants (entity_shader).
|
||||
let module = naga::front::wgsl::parse_str(&text)
|
||||
.or_else(|_| {
|
||||
|
||||
@@ -22,8 +22,16 @@
|
||||
//! Every solid draw is an entry of one of the two lists, so the CPU records
|
||||
//! as many draws as without culling: drivers that unroll an indirect
|
||||
//! multi-draw on the CPU (Mesa's on Intel Gen9) pay per entry. Phase 2's
|
||||
//! counts come from the GPU, which needs a native multi-draw and forced
|
||||
//! early depth tests: Vulkan. Translucent draws are not culled.
|
||||
//! counts come from the GPU, which reads them from the draws themselves:
|
||||
//! Vulkan's native multi-draw, and Metal's, which wgpu replays as one
|
||||
//! indirect draw per entry. Translucent draws are not culled.
|
||||
//!
|
||||
//! Metal cannot force the depth test before a fragment shader that writes
|
||||
//! storage (naga writes no `[[early_fragment_tests]]`), so there the boxes
|
||||
//! are drawn in a pass of their own between the phases, which reads phase
|
||||
//! 1's depth as a texture and makes the same comparison in the shader: the
|
||||
//! fragment's depth against the stored one, greater or equal passing. The
|
||||
//! same fragments pass, so the same sections are seen.
|
||||
use std::num::NonZeroU64;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
@@ -38,6 +46,13 @@ const RETEST: u32 = 8;
|
||||
/// more than they save. Else one frame in `PROBE` tests every section.
|
||||
const MIN_SHARE: f32 = 0.1;
|
||||
const PROBE: u32 = 64;
|
||||
/// On Metal, section draws from which a frame culls. Apple's GPUs store and
|
||||
/// reload the whole frame at each of the passes the test adds, a fixed cost
|
||||
/// that the sections it hides repay only at high render distances: on an M4
|
||||
/// Pro at 1080p and render distance 12 (1,000–1,600 draws) culling added
|
||||
/// about 0.05 ms of GPU time while hiding 15–30% of the solid indices; at
|
||||
/// 32 (drawn flat, over this many draws) it saved 0.25–1.6 ms.
|
||||
pub const TILED_MIN_DRAWS: usize = 4096;
|
||||
/// Boxes over more than this share of the screen count as seen untested.
|
||||
const BIG: f32 = 0.25;
|
||||
/// Results read back at once, some frames late so the CPU never waits.
|
||||
@@ -74,10 +89,40 @@ struct Group {
|
||||
group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
/// Where the boxes' depth test runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DepthTest {
|
||||
/// Forced before the fragment shader, in phase 1's pass (Vulkan).
|
||||
Early,
|
||||
/// In the fragment shader, against phase 1's depth read as a texture,
|
||||
/// in a pass of its own (Metal).
|
||||
InShader,
|
||||
}
|
||||
|
||||
/// The Vulkan entry point: the depth test forced early, which naga cannot
|
||||
/// write for Metal (so it is not in `cull.wgsl`, which every backend takes).
|
||||
const EARLY_TEST: &str = "
|
||||
@fragment
|
||||
@early_depth_test(force)
|
||||
fn fs_box_early(in: Box) -> @location(0) vec4<f32> {
|
||||
see(in.test);
|
||||
return vec4(0.0);
|
||||
}
|
||||
";
|
||||
|
||||
/// The test's depth texture binding (`InShader`), for the view it was made with.
|
||||
struct DepthGroup {
|
||||
view: wgpu::TextureView,
|
||||
group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
pub struct Cull {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
layout: wgpu::BindGroupLayout,
|
||||
group: Option<Group>,
|
||||
depth_test: DepthTest,
|
||||
depth_layout: Option<wgpu::BindGroupLayout>,
|
||||
depth_group: Option<DepthGroup>,
|
||||
params: wgpu::Buffer,
|
||||
/// Phase 2's draws: the solid draws after phase 1's in the frame's list.
|
||||
pub phase2: wgpu::Buffer,
|
||||
@@ -103,6 +148,8 @@ pub struct Cull {
|
||||
pub hidden: ([usize; 2], f32),
|
||||
/// Cull every frame, whatever the hidden share (A/B checks).
|
||||
pub always: bool,
|
||||
/// Frames with fewer section draws than this do not cull.
|
||||
pub min_draws: usize,
|
||||
}
|
||||
|
||||
fn buffer(
|
||||
@@ -134,20 +181,33 @@ impl Cull {
|
||||
pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features {
|
||||
adapter.features() & wgpu::Features::SHADER_EARLY_DEPTH_TEST
|
||||
}
|
||||
/// Whether the device draws an indirect multi-draw natively and runs
|
||||
/// fragment shaders that write storage only past an early depth test.
|
||||
pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool {
|
||||
adapter.get_info().backend == wgpu::Backend::Vulkan
|
||||
&& device.features().contains(
|
||||
wgpu::Features::SHADER_EARLY_DEPTH_TEST | wgpu::Features::INDIRECT_FIRST_INSTANCE,
|
||||
)
|
||||
/// Where the device can run the test, if it can: Vulkan with early
|
||||
/// depth tests, or Metal, both drawing an indirect multi-draw's entries
|
||||
/// with the instance counts the GPU wrote, with fragment shaders that
|
||||
/// write storage.
|
||||
pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Option<DepthTest> {
|
||||
let depth_test = match adapter.get_info().backend {
|
||||
wgpu::Backend::Vulkan
|
||||
if device
|
||||
.features()
|
||||
.contains(wgpu::Features::SHADER_EARLY_DEPTH_TEST) =>
|
||||
{
|
||||
DepthTest::Early
|
||||
}
|
||||
wgpu::Backend::Metal => DepthTest::InShader,
|
||||
_ => return None,
|
||||
};
|
||||
(device
|
||||
.features()
|
||||
.contains(wgpu::Features::INDIRECT_FIRST_INSTANCE)
|
||||
&& adapter.get_downlevel_capabilities().flags.contains(
|
||||
wgpu::DownlevelFlags::VERTEX_STORAGE
|
||||
| wgpu::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE,
|
||||
)
|
||||
))
|
||||
.then_some(depth_test)
|
||||
}
|
||||
/// `color` is the world pass's colour format.
|
||||
pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat) -> Self {
|
||||
pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat, depth_test: DepthTest) -> Self {
|
||||
let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility,
|
||||
@@ -180,13 +240,41 @@ impl Cull {
|
||||
});
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Section culling"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("cull.wgsl").into()),
|
||||
source: wgpu::ShaderSource::Wgsl(source(depth_test).into()),
|
||||
});
|
||||
let depth_layout = (depth_test == DepthTest::InShader).then(|| {
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Section culling depth"),
|
||||
entries: &[entry(
|
||||
0,
|
||||
fragment,
|
||||
wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Depth,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
)],
|
||||
})
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Section culling"),
|
||||
bind_group_layouts: &[Some(&layout)],
|
||||
bind_group_layouts: &[Some(&layout), depth_layout.as_ref()],
|
||||
..Default::default()
|
||||
});
|
||||
// In the shader: no colour target, and phase 1's depth attached read
|
||||
// only (a pass needs an attachment), its test left to the shader.
|
||||
let (fragment_entry, targets, depth_compare) = match depth_test {
|
||||
DepthTest::Early => (
|
||||
"fs_box_early",
|
||||
&[Some(wgpu::ColorTargetState {
|
||||
format: color,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::empty(),
|
||||
})][..],
|
||||
wgpu::CompareFunction::GreaterEqual,
|
||||
),
|
||||
DepthTest::InShader => ("fs_box", &[][..], wgpu::CompareFunction::Always),
|
||||
};
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Section culling"),
|
||||
layout: Some(&pipeline_layout),
|
||||
@@ -204,20 +292,16 @@ impl Cull {
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
|
||||
depth_compare: Some(depth_compare),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some("fs_box"),
|
||||
entry_point: Some(fragment_entry),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: color,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::empty(),
|
||||
})],
|
||||
targets,
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
@@ -226,6 +310,9 @@ impl Cull {
|
||||
pipeline,
|
||||
layout,
|
||||
group: None,
|
||||
depth_test,
|
||||
depth_layout,
|
||||
depth_group: None,
|
||||
params: buffer(
|
||||
device,
|
||||
"Section culling parameters",
|
||||
@@ -259,6 +346,7 @@ impl Cull {
|
||||
stamp: 0,
|
||||
hidden: ([0; 2], 1.0),
|
||||
always: false,
|
||||
min_draws: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -399,17 +487,69 @@ impl Cull {
|
||||
}
|
||||
}
|
||||
|
||||
/// In the world pass after phase 1: draw the tested boxes against its
|
||||
/// depth. Leaves the pass's pipeline and group 0 changed.
|
||||
pub fn depth_test(&self) -> DepthTest {
|
||||
self.depth_test
|
||||
}
|
||||
|
||||
/// In the world pass after phase 1 (`Early`): draw the tested boxes
|
||||
/// against its depth. Leaves the pass's pipeline and group 0 changed.
|
||||
pub fn test(&self, pass: &mut wgpu::RenderPass<'_>) {
|
||||
let Some(Group { group, .. }) = &self.group else {
|
||||
return;
|
||||
};
|
||||
if self.depth_test != DepthTest::Early || self.test_data.is_empty() {
|
||||
return;
|
||||
}
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, group, &[]);
|
||||
pass.draw(0..36, 0..self.test_data.len() as u32);
|
||||
}
|
||||
|
||||
/// Before the world pass (`InShader`): the binding of the depth the
|
||||
/// world is drawn with this frame.
|
||||
pub fn bind_depth(&mut self, device: &wgpu::Device, depth: &wgpu::TextureView) {
|
||||
let Some(layout) = &self.depth_layout else {
|
||||
return;
|
||||
};
|
||||
if self.depth_group.as_ref().is_none_or(|g| g.view != *depth) {
|
||||
self.depth_group = Some(DepthGroup {
|
||||
view: depth.clone(),
|
||||
group: device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Section culling depth"),
|
||||
layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(depth),
|
||||
}],
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Between the phases (`InShader`): draw the tested boxes in a pass of
|
||||
/// their own that reads phase 1's depth, bound by `bind_depth`.
|
||||
pub fn test_pass(&self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let (Some(Group { group, .. }), Some(DepthGroup { view, group: depth })) =
|
||||
(&self.group, &self.depth_group)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.test_data.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Section culling"),
|
||||
color_attachments: &[],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view,
|
||||
depth_ops: None,
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, group, &[]);
|
||||
pass.set_bind_group(1, depth, &[]);
|
||||
pass.draw(0..36, 0..self.test_data.len() as u32);
|
||||
}
|
||||
|
||||
@@ -498,16 +638,33 @@ impl Cull {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn shader_validates() {
|
||||
let module = naga::front::wgsl::parse_str(include_str!("cull.wgsl")).unwrap();
|
||||
naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::all(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
/// The test's shader for `depth_test`.
|
||||
fn source(depth_test: DepthTest) -> String {
|
||||
let common = include_str!("cull.wgsl");
|
||||
match depth_test {
|
||||
DepthTest::Early => format!("{common}{EARLY_TEST}"),
|
||||
DepthTest::InShader => common.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shaders_validate() {
|
||||
for (depth_test, capabilities) in [
|
||||
(DepthTest::Early, naga::valid::Capabilities::all()),
|
||||
// What wgpu's Metal backend allows: no early depth test.
|
||||
(
|
||||
DepthTest::InShader,
|
||||
naga::valid::Capabilities::all() - naga::valid::Capabilities::EARLY_DEPTH_TEST,
|
||||
),
|
||||
] {
|
||||
let module = naga::front::wgsl::parse_str(&source(depth_test)).unwrap();
|
||||
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities)
|
||||
.validate(&module)
|
||||
.unwrap_or_else(|e| panic!("{depth_test:?}: {e:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,16 +86,28 @@ fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box
|
||||
return out;
|
||||
}
|
||||
|
||||
// Runs only for fragments that pass the depth test (forced early).
|
||||
@fragment
|
||||
@early_depth_test(force)
|
||||
fn fs_box(in: Box) -> @location(0) vec4<f32> {
|
||||
if results[in.test] != params.stamp {
|
||||
results[in.test] = params.stamp;
|
||||
let test = tests[in.test];
|
||||
// The box is seen at this fragment: store the stamp, and give its phase 2
|
||||
// draws their instance.
|
||||
fn see(t: u32) {
|
||||
if results[t] != params.stamp {
|
||||
results[t] = params.stamp;
|
||||
let test = tests[t];
|
||||
for (var k = 0u; k < test.z; k++) {
|
||||
phase2[(test.y + k) * 5u + 1u] = 1u;
|
||||
}
|
||||
}
|
||||
return vec4(0.0);
|
||||
}
|
||||
|
||||
// Phase 1's depth, where the test runs in the shader (gfx/cull.rs).
|
||||
@group(1) @binding(0) var depth: texture_depth_2d;
|
||||
|
||||
// The world pass's reversed depth test, greater or equal passing, made here:
|
||||
// where it cannot be forced before a shader that writes storage, a fragment
|
||||
// that fails it would still write. Where it can, `fs_box_early` (cull.rs)
|
||||
// runs only for the fragments that pass it.
|
||||
@fragment
|
||||
fn fs_box(in: Box) {
|
||||
if in.position.z >= textureLoad(depth, vec2<u32>(in.position.xy), 0) {
|
||||
see(in.test);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,37 @@
|
||||
//! so each block names one section: its id here, which indexes the frame's
|
||||
//! camera-relative origins (computed on the CPU exactly as for the instance
|
||||
//! attribute).
|
||||
//!
|
||||
//! With occlusion culling (`cull`), phase 1's draws and the translucent ones
|
||||
//! are copied before the world pass, as without it. Phase 2's draws are
|
||||
//! copied after the test, which tells which ones it saw: each run of a page
|
||||
//! reserves room for all of its draws, the copy packs the seen ones at its
|
||||
//! start, and the run is drawn indirectly with the count the copy reached.
|
||||
use super::arena::GRAIN;
|
||||
|
||||
/// One section draw for `flatten.wgsl`: index count, first sorted index (or
|
||||
/// `QUADS` for a solid draw), base vertex, first index in the list.
|
||||
/// `QUADS` for a solid draw; phase 2: its entry in phase 2's draws), base
|
||||
/// vertex, first index in the list (phase 2: its draw call in phase 2).
|
||||
type Range = [u32; 4];
|
||||
|
||||
/// Where a group of ranges takes its indices.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Source {
|
||||
/// Solid draws: quads.
|
||||
Quads,
|
||||
/// Occlusion culling's phase 2: quads, of the sections its test saw.
|
||||
Seen,
|
||||
/// Translucent draws: this sorted index page.
|
||||
Sorted(u32),
|
||||
}
|
||||
|
||||
/// The frame's draw calls, as `plan` lays them out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Plan {
|
||||
phase1_calls: usize,
|
||||
solid_calls: usize,
|
||||
total: u64,
|
||||
}
|
||||
const QUADS: u32 = u32::MAX;
|
||||
const GROUP_LIMIT: u32 = 65535;
|
||||
|
||||
@@ -38,6 +64,15 @@ pub struct Flat {
|
||||
pub translucent: wgpu::RenderPipeline,
|
||||
flatten: wgpu::ComputePipeline,
|
||||
compute_layout: wgpu::BindGroupLayout,
|
||||
flatten_seen: wgpu::ComputePipeline,
|
||||
seen_layout: wgpu::BindGroupLayout,
|
||||
/// Phase 2's draw calls (`DrawIndexedIndirectArgs`), whose index counts
|
||||
/// `flatten_seen` makes.
|
||||
phase2_calls: wgpu::Buffer,
|
||||
phase2_call_capacity: u64,
|
||||
phase2_call_data: Vec<[u32; 5]>,
|
||||
/// The copy of phase 2's draws, and its ranges.
|
||||
phase2_group: Option<(wgpu::BindGroup, u32)>,
|
||||
draw_layout: wgpu::BindGroupLayout,
|
||||
blocks_per_page: u64,
|
||||
pages: Vec<Option<PageTable>>,
|
||||
@@ -52,12 +87,14 @@ pub struct Flat {
|
||||
ranges: wgpu::Buffer,
|
||||
range_capacity: u64,
|
||||
range_data: Vec<Range>,
|
||||
/// Segments of `range_data` by index source: (sorted index page or
|
||||
/// `None` for solid draws, first range, ranges).
|
||||
segments: Vec<(Option<u32>, u64, u64)>,
|
||||
/// Segments of `range_data` by index source: (source, first range,
|
||||
/// ranges).
|
||||
segments: Vec<(Source, u64, u64)>,
|
||||
empty: wgpu::Buffer,
|
||||
/// This frame's draw calls: solid ones, then translucent ones.
|
||||
/// This frame's draw calls: solid ones (phase 1's, then phase 2's when
|
||||
/// culling), then translucent ones.
|
||||
pub calls: Vec<Call>,
|
||||
pub phase1_calls: usize,
|
||||
pub solid_calls: usize,
|
||||
/// Frames with fewer section draws keep the per-section draws.
|
||||
pub min_draws: usize,
|
||||
@@ -121,42 +158,60 @@ fn buffer(
|
||||
/// Lays out the frame's index list: each draw's range (destinations in draw
|
||||
/// order) grouped by index source into `ranges`, every group padded to
|
||||
/// `align` entries for binding, with `segments` naming each group; and the
|
||||
/// draw calls, one per run of draws in the same vertex page, solid and
|
||||
/// translucent apart. Returns the first translucent call and the list's
|
||||
/// length.
|
||||
/// draw calls, one per run of draws in the same vertex page, phase 1's solid
|
||||
/// ones, phase 2's (draws `phase1_draws..solid_draws`) and translucent ones
|
||||
/// apart. A phase 2 range names its draw in phase 2 and its call in phase 2
|
||||
/// instead of a destination: the call's room holds all of its draws.
|
||||
fn plan(
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
phase1_draws: usize,
|
||||
solid_draws: usize,
|
||||
align: u64,
|
||||
calls: &mut Vec<Call>,
|
||||
ranges: &mut Vec<Range>,
|
||||
segments: &mut Vec<(Option<u32>, u64, u64)>,
|
||||
) -> (usize, u64) {
|
||||
segments: &mut Vec<(Source, u64, u64)>,
|
||||
) -> Plan {
|
||||
calls.clear();
|
||||
ranges.clear();
|
||||
segments.clear();
|
||||
let mut solid_calls = None;
|
||||
let (mut phase1_calls, mut solid_calls) = (None, None);
|
||||
let mut total = 0u64;
|
||||
let mut by_source: Vec<(Option<u32>, Vec<Range>)> = Vec::new();
|
||||
let mut by_source: Vec<(Source, Vec<Range>)> = Vec::new();
|
||||
for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() {
|
||||
let first = if sorted.is_some() { d[2] } else { QUADS };
|
||||
let range = [d[0], first, d[3], total as u32];
|
||||
match by_source.iter_mut().find(|(s, _)| *s == sorted) {
|
||||
Some((_, list)) => list.push(range),
|
||||
None => by_source.push((sorted, vec![range])),
|
||||
if i == phase1_draws {
|
||||
phase1_calls.get_or_insert(calls.len());
|
||||
}
|
||||
if i == solid_draws {
|
||||
solid_calls = Some(calls.len());
|
||||
}
|
||||
match calls.last_mut() {
|
||||
Some(last) if last.page == page && i != solid_draws => last.count += d[0],
|
||||
Some(last) if last.page == page && i != phase1_draws && i != solid_draws => {
|
||||
last.count += d[0]
|
||||
}
|
||||
_ => calls.push(Call {
|
||||
page,
|
||||
first: total as u32,
|
||||
count: d[0],
|
||||
}),
|
||||
}
|
||||
let (source, range) = match sorted {
|
||||
Some(p) => (Source::Sorted(p), [d[0], d[2], d[3], total as u32]),
|
||||
None if (phase1_draws..solid_draws).contains(&i) => (
|
||||
Source::Seen,
|
||||
[
|
||||
d[0],
|
||||
(i - phase1_draws) as u32,
|
||||
d[3],
|
||||
(calls.len() - 1 - phase1_calls.unwrap_or(0)) as u32,
|
||||
],
|
||||
),
|
||||
None => (Source::Quads, [d[0], QUADS, d[3], total as u32]),
|
||||
};
|
||||
match by_source.iter_mut().find(|(s, _)| *s == source) {
|
||||
Some((_, list)) => list.push(range),
|
||||
None => by_source.push((source, vec![range])),
|
||||
}
|
||||
total += u64::from(d[0]);
|
||||
}
|
||||
for (source, list) in by_source {
|
||||
@@ -165,7 +220,12 @@ fn plan(
|
||||
let padded = (ranges.len() as u64).next_multiple_of(align);
|
||||
ranges.resize(padded as usize, [0; 4]);
|
||||
}
|
||||
(solid_calls.unwrap_or(calls.len()), total)
|
||||
let solid_calls = solid_calls.unwrap_or(calls.len());
|
||||
Plan {
|
||||
phase1_calls: phase1_calls.unwrap_or(calls.len()).min(solid_calls),
|
||||
solid_calls,
|
||||
total,
|
||||
}
|
||||
}
|
||||
|
||||
impl Flat {
|
||||
@@ -201,24 +261,37 @@ impl Flat {
|
||||
storage(2, compute, false),
|
||||
],
|
||||
});
|
||||
let seen_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Flatten phase 2 section draws"),
|
||||
entries: &[
|
||||
storage(0, compute, true),
|
||||
storage(2, compute, false),
|
||||
storage(3, compute, true),
|
||||
storage(4, compute, false),
|
||||
],
|
||||
});
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
|
||||
});
|
||||
let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
layout: Some(
|
||||
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
bind_group_layouts: &[Some(&compute_layout)],
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
module: &module,
|
||||
entry_point: Some("flatten"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let compute_pipeline = |layout: &wgpu::BindGroupLayout, entry| {
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
layout: Some(
|
||||
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
bind_group_layouts: &[Some(layout)],
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
module: &module,
|
||||
entry_point: Some(entry),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let flatten = compute_pipeline(&compute_layout, "flatten");
|
||||
let flatten_seen = compute_pipeline(&seen_layout, "flatten_seen");
|
||||
let storage_usage = wgpu::BufferUsages::STORAGE;
|
||||
Self {
|
||||
solid: pipeline(&layout, "Terrain solid (flat)", "fs_solid", None),
|
||||
@@ -230,6 +303,17 @@ impl Flat {
|
||||
),
|
||||
flatten,
|
||||
compute_layout,
|
||||
flatten_seen,
|
||||
seen_layout,
|
||||
phase2_calls: buffer(
|
||||
device,
|
||||
"Flat section draw calls, phase 2",
|
||||
20,
|
||||
wgpu::BufferUsages::INDIRECT | storage_usage,
|
||||
),
|
||||
phase2_call_capacity: 1,
|
||||
phase2_call_data: Vec::new(),
|
||||
phase2_group: None,
|
||||
draw_layout,
|
||||
blocks_per_page: page_vertices.div_ceil(GRAIN),
|
||||
pages: Vec::new(),
|
||||
@@ -251,6 +335,7 @@ impl Flat {
|
||||
segments: Vec::new(),
|
||||
empty: buffer(device, "No sorted indices", 16, storage_usage),
|
||||
calls: Vec::new(),
|
||||
phase1_calls: 0,
|
||||
solid_calls: 0,
|
||||
min_draws: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") {
|
||||
0
|
||||
@@ -321,6 +406,9 @@ impl Flat {
|
||||
/// the origins of the sections they draw by id. Records the copy into
|
||||
/// `encoder`; `calls` then lists the frame's draw calls. False when the
|
||||
/// frame cannot be drawn flat (the per-section draws then apply).
|
||||
///
|
||||
/// When culling, the solid draws from `phase1_draws` are phase 2's, which
|
||||
/// `phase2` holds as the test leaves them: `flatten_phase2` copies them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
@@ -329,10 +417,18 @@ impl Flat {
|
||||
uploads: &mut super::upload::Uploads,
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
phase1_draws: usize,
|
||||
solid_draws: usize,
|
||||
phase2: Option<&wgpu::Buffer>,
|
||||
origins: impl Iterator<Item = (u32, [f32; 4])>,
|
||||
sorted_page: impl Fn(u32) -> wgpu::Buffer,
|
||||
) -> bool {
|
||||
self.phase2_group = None;
|
||||
let phase1_draws = if phase2.is_some() {
|
||||
phase1_draws
|
||||
} else {
|
||||
solid_draws
|
||||
};
|
||||
// Origins by section id.
|
||||
self.origin_data.clear();
|
||||
for (id, o) in origins {
|
||||
@@ -362,18 +458,25 @@ impl Flat {
|
||||
bytemuck::cast_slice(&self.origin_data),
|
||||
);
|
||||
}
|
||||
let (solid_calls, total) = plan(
|
||||
let Plan {
|
||||
phase1_calls,
|
||||
solid_calls,
|
||||
total,
|
||||
} = plan(
|
||||
draws,
|
||||
pages,
|
||||
phase1_draws,
|
||||
solid_draws,
|
||||
self.range_align,
|
||||
&mut self.calls,
|
||||
&mut self.range_data,
|
||||
&mut self.segments,
|
||||
);
|
||||
self.phase1_calls = phase1_calls;
|
||||
self.solid_calls = solid_calls;
|
||||
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
|
||||
self.calls.clear();
|
||||
self.phase1_calls = 0;
|
||||
self.solid_calls = 0;
|
||||
return false;
|
||||
}
|
||||
@@ -401,22 +504,82 @@ impl Flat {
|
||||
0,
|
||||
bytemuck::cast_slice(&self.range_data),
|
||||
);
|
||||
// Phase 2's calls start empty, each at the start of its room.
|
||||
self.phase2_call_data.clear();
|
||||
self.phase2_call_data.extend(
|
||||
self.calls[phase1_calls..solid_calls]
|
||||
.iter()
|
||||
.map(|c| [0, 1, c.first, 0, 0]),
|
||||
);
|
||||
let phase2_calls = self.phase2_call_data.len() as u64;
|
||||
if phase2_calls > self.phase2_call_capacity {
|
||||
self.phase2_call_capacity = phase2_calls.next_power_of_two();
|
||||
self.phase2_calls = buffer(
|
||||
device,
|
||||
"Flat section draw calls, phase 2",
|
||||
self.phase2_call_capacity * 20,
|
||||
wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::STORAGE,
|
||||
);
|
||||
}
|
||||
if phase2_calls > 0 {
|
||||
uploads.buffer(
|
||||
encoder,
|
||||
&self.phase2_calls,
|
||||
0,
|
||||
bytemuck::cast_slice(&self.phase2_call_data),
|
||||
);
|
||||
}
|
||||
let ranges_at = |first: u64, count: u64| {
|
||||
wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &self.ranges,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
})
|
||||
};
|
||||
if let (Some(phase2), Some(&(_, first, count))) = (
|
||||
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),
|
||||
},
|
||||
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));
|
||||
}
|
||||
let groups: Vec<(wgpu::BindGroup, u32)> = self
|
||||
.segments
|
||||
.iter()
|
||||
.map(|&(source, first, count)| {
|
||||
let sorted = source.map(&sorted_page);
|
||||
.filter_map(|&(source, first, count)| {
|
||||
let sorted = match source {
|
||||
Source::Quads => None,
|
||||
Source::Seen => return None,
|
||||
Source::Sorted(page) => Some(sorted_page(page)),
|
||||
};
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
layout: &self.compute_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &self.ranges,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
}),
|
||||
resource: ranges_at(first, count),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
@@ -428,7 +591,7 @@ impl Flat {
|
||||
},
|
||||
],
|
||||
});
|
||||
(group, count as u32)
|
||||
Some((group, count as u32))
|
||||
})
|
||||
.collect();
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
@@ -464,6 +627,19 @@ impl Flat {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// After occlusion culling's test: copies the phase 2 draws it saw.
|
||||
pub fn flatten_phase2(&self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let Some((group, count)) = &self.phase2_group else {
|
||||
return;
|
||||
};
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("Flatten phase 2 section draws"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
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);
|
||||
}
|
||||
/// Draws `calls` with a flat pipeline set and `vertices` giving each
|
||||
/// page's vertex buffer.
|
||||
pub fn draw<'a>(
|
||||
@@ -474,15 +650,38 @@ impl Flat {
|
||||
) {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for call in calls {
|
||||
let table = self.pages[call.page as usize]
|
||||
.as_ref()
|
||||
.and_then(|t| t.group.as_ref())
|
||||
.expect("prepared page");
|
||||
pass.set_vertex_buffer(0, vertices(call.page).slice(..));
|
||||
pass.set_bind_group(1, table, &[]);
|
||||
self.bind_page(pass, call.page, &vertices);
|
||||
pass.draw_indexed(call.first..call.first + call.count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
/// Draws phase 2's calls, as `flatten_phase2` left them.
|
||||
pub fn draw_phase2<'a>(
|
||||
&self,
|
||||
pass: &mut wgpu::RenderPass<'_>,
|
||||
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
|
||||
) {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (k, call) in self.calls[self.phase1_calls..self.solid_calls]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
self.bind_page(pass, call.page, &vertices);
|
||||
pass.draw_indexed_indirect(&self.phase2_calls, k as u64 * 20);
|
||||
}
|
||||
}
|
||||
fn bind_page<'a>(
|
||||
&self,
|
||||
pass: &mut wgpu::RenderPass<'_>,
|
||||
page: u32,
|
||||
vertices: &impl Fn(u32) -> &'a wgpu::Buffer,
|
||||
) {
|
||||
let table = self.pages[page as usize]
|
||||
.as_ref()
|
||||
.and_then(|t| t.group.as_ref())
|
||||
.expect("prepared page");
|
||||
pass.set_vertex_buffer(0, vertices(page).slice(..));
|
||||
pass.set_bind_group(1, table, &[]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -516,16 +715,22 @@ mod tests {
|
||||
fn plan_draws_runs_of_a_page_in_order() {
|
||||
let (draws, pages, solid) = sample();
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (solid_calls, total) = plan(
|
||||
let Plan {
|
||||
phase1_calls,
|
||||
solid_calls,
|
||||
total,
|
||||
} = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
solid,
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
assert_eq!(total, 6 * 13);
|
||||
assert_eq!(phase1_calls, solid_calls);
|
||||
let call = |page, first, count| Call { page, first, count };
|
||||
// Pages 0, 0 | 1 | 0, then translucent 0, 0 (never merged with solid).
|
||||
assert_eq!(
|
||||
@@ -539,16 +744,65 @@ mod tests {
|
||||
);
|
||||
assert_eq!(solid_calls, 3);
|
||||
// Solid ranges, then each sorted page's, every group padded to 4.
|
||||
assert_eq!(segments, [(None, 0, 4), (Some(0), 4, 1), (Some(1), 8, 1)]);
|
||||
assert_eq!(
|
||||
segments,
|
||||
[
|
||||
(Source::Quads, 0, 4),
|
||||
(Source::Sorted(0), 4, 1),
|
||||
(Source::Sorted(1), 8, 1)
|
||||
]
|
||||
);
|
||||
assert_eq!(ranges[3], [24, QUADS, 1024, 36]);
|
||||
assert_eq!(ranges[4], [12, 6, 768, 60]);
|
||||
assert_eq!(ranges[8], [6, 0, 40, 72]);
|
||||
assert_eq!(ranges.len(), 12);
|
||||
}
|
||||
|
||||
/// Phase 2's draws (here the third and fourth) get calls of their own,
|
||||
/// each with room for all of its draws, and ranges naming their draw
|
||||
/// and call in phase 2.
|
||||
#[test]
|
||||
fn plan_gives_phase_2_calls_of_its_own() {
|
||||
let (draws, pages, solid) = sample();
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let plan = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
2,
|
||||
solid,
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
assert_eq!(
|
||||
plan,
|
||||
Plan {
|
||||
phase1_calls: 1,
|
||||
solid_calls: 3,
|
||||
total: 6 * 13
|
||||
}
|
||||
);
|
||||
let call = |page, first, count| Call { page, first, count };
|
||||
// Phase 1: page 0 | phase 2: page 1, page 0 | translucent: page 0.
|
||||
assert_eq!(
|
||||
calls,
|
||||
[
|
||||
call(0, 0, 30),
|
||||
call(1, 30, 6),
|
||||
call(0, 36, 24),
|
||||
call(0, 60, 18)
|
||||
]
|
||||
);
|
||||
assert_eq!(segments[1], (Source::Seen, 4, 2));
|
||||
assert_eq!(ranges[4], [6, 0, 256, 0]);
|
||||
assert_eq!(ranges[5], [24, 1, 1024, 1]);
|
||||
}
|
||||
|
||||
/// The compute pass writes exactly the indices the per-section draws
|
||||
/// read: quads 0 1 2 0 2 3 for solid draws, sorted indices otherwise,
|
||||
/// plus the base vertex.
|
||||
/// plus the base vertex. With culling, phase 2's runs hold the indices
|
||||
/// of the draws the test saw, in order, and their calls count them.
|
||||
#[test]
|
||||
fn flatten_writes_the_indices_of_the_per_section_draws() {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
@@ -564,101 +818,170 @@ mod tests {
|
||||
use wgpu::util::DeviceExt;
|
||||
let (draws, pages, solid) = sample();
|
||||
let align = (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16).max(1);
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (_, total) = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
align,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
let sorted: [Vec<u32>; 2] = [
|
||||
(0..32).map(|i| (i * 7) % 32).collect(),
|
||||
(0..8).rev().collect(),
|
||||
];
|
||||
let mut expected = Vec::new();
|
||||
for (d, (_, page)) in draws.iter().zip(&pages) {
|
||||
for k in 0..d[0] {
|
||||
let i = match page {
|
||||
None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize],
|
||||
Some(p) => sorted[*p as usize][(d[2] + k) as usize],
|
||||
};
|
||||
expected.push(d[3] + i);
|
||||
}
|
||||
}
|
||||
let storage = |entries: &[u32]| {
|
||||
let indices = |d: &[u32; 5], sorted_page: Option<u32>| -> Vec<u32> {
|
||||
(0..d[0])
|
||||
.map(|k| {
|
||||
d[3] + match sorted_page {
|
||||
None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize],
|
||||
Some(p) => sorted[p as usize][(d[2] + k) as usize],
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let storage = |entries: &[u32], usage| {
|
||||
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: None,
|
||||
contents: bytemuck::cast_slice(entries),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
usage: wgpu::BufferUsages::STORAGE | usage,
|
||||
})
|
||||
};
|
||||
let range_buffer = storage(bytemuck::cast_slice(&ranges));
|
||||
let sorted_buffers = [storage(&sorted[0]), storage(&sorted[1]), storage(&[0; 4])];
|
||||
let out = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: total * 4,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let read = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: total * 4,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let none = wgpu::BufferUsages::empty();
|
||||
let sorted_buffers = [
|
||||
storage(&sorted[0], none),
|
||||
storage(&sorted[1], none),
|
||||
storage(&[0; 4], none),
|
||||
];
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: None,
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some("flatten"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&Default::default());
|
||||
pass.set_pipeline(&pipeline);
|
||||
for &(source, first, count) in &segments {
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &range_buffer,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
}),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sorted_buffers[source.map_or(2, |p| p as usize)]
|
||||
.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: out.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.dispatch_workgroups(count as u32, 1, 1);
|
||||
let pipeline = |entry| {
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: None,
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some(entry),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let (flatten, flatten_seen) = (pipeline("flatten"), pipeline("flatten_seen"));
|
||||
let read_back = |buffer: &wgpu::Buffer, words: u64| -> Vec<u32> {
|
||||
let read = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: words * 4,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
encoder.copy_buffer_to_buffer(buffer, 0, &read, 0, words * 4);
|
||||
queue.submit([encoder.finish()]);
|
||||
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec()
|
||||
};
|
||||
// Without culling, then with the third and fourth draws in phase 2,
|
||||
// of which the test saw only the fourth.
|
||||
for phase1 in [solid, 2] {
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let plan = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
phase1,
|
||||
solid,
|
||||
align,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
// Phase 2's draws as the test leaves them: instance counts of 0,
|
||||
// 1 where it saw the section.
|
||||
let mut phase2: Vec<[u32; 5]> = draws[phase1..solid]
|
||||
.iter()
|
||||
.map(|&[count, _, first, base, instance]| [count, 0, first, base, instance])
|
||||
.collect();
|
||||
if let Some(last) = phase2.last_mut() {
|
||||
last[1] = 1;
|
||||
}
|
||||
let phase2_calls: Vec<[u32; 5]> = calls[plan.phase1_calls..plan.solid_calls]
|
||||
.iter()
|
||||
.map(|c| [0, 1, c.first, 0, 0])
|
||||
.collect();
|
||||
let range_buffer = storage(bytemuck::cast_slice(&ranges), none);
|
||||
let phase2_buffer = storage(
|
||||
bytemuck::cast_slice(&[phase2.as_slice(), &[[0; 5]]].concat()),
|
||||
none,
|
||||
);
|
||||
let calls_buffer = storage(
|
||||
bytemuck::cast_slice(&[phase2_calls.as_slice(), &[[0; 5]]].concat()),
|
||||
wgpu::BufferUsages::COPY_SRC,
|
||||
);
|
||||
let out = storage(&vec![0; plan.total as usize], wgpu::BufferUsages::COPY_SRC);
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&Default::default());
|
||||
for &(source, first, count) in &segments {
|
||||
let ranges = wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &range_buffer,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
});
|
||||
let entry = |binding, resource| wgpu::BindGroupEntry { binding, resource };
|
||||
let (pipeline, entries) = match source {
|
||||
Source::Seen => (
|
||||
&flatten_seen,
|
||||
vec![
|
||||
entry(0, ranges),
|
||||
entry(2, out.as_entire_binding()),
|
||||
entry(3, phase2_buffer.as_entire_binding()),
|
||||
entry(4, calls_buffer.as_entire_binding()),
|
||||
],
|
||||
),
|
||||
Source::Quads | Source::Sorted(_) => {
|
||||
let page = match source {
|
||||
Source::Sorted(p) => p as usize,
|
||||
_ => 2,
|
||||
};
|
||||
(
|
||||
&flatten,
|
||||
vec![
|
||||
entry(0, ranges),
|
||||
entry(1, sorted_buffers[page].as_entire_binding()),
|
||||
entry(2, out.as_entire_binding()),
|
||||
],
|
||||
)
|
||||
}
|
||||
};
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &entries,
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.dispatch_workgroups(count as u32, 1, 1);
|
||||
}
|
||||
}
|
||||
queue.submit([encoder.finish()]);
|
||||
let got = read_back(&out, plan.total);
|
||||
// Phase 1's and the translucent calls: each of their draws, in order.
|
||||
let expected: Vec<u32> = (0..draws.len())
|
||||
.filter(|i| !(phase1..solid).contains(i))
|
||||
.flat_map(|i| indices(&draws[i], pages[i].1))
|
||||
.collect();
|
||||
let drawn: Vec<u32> = calls
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(c, _)| !(plan.phase1_calls..plan.solid_calls).contains(c))
|
||||
.flat_map(|(_, c)| got[c.first as usize..(c.first + c.count) as usize].to_vec())
|
||||
.collect();
|
||||
assert_eq!(drawn, expected);
|
||||
// Phase 2: page 1's run drew nothing; page 0's holds the fourth
|
||||
// draw's indices.
|
||||
if phase1 < solid {
|
||||
let counts = read_back(&calls_buffer, phase2_calls.len() as u64 * 5);
|
||||
assert_eq!(counts[0], 0);
|
||||
assert_eq!(counts[5], draws[3][0]);
|
||||
let run = &calls[plan.phase1_calls + 1];
|
||||
assert_eq!(
|
||||
got[run.first as usize..(run.first + draws[3][0]) as usize],
|
||||
indices(&draws[3], None)
|
||||
);
|
||||
}
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(&out, 0, &read, 0, total * 4);
|
||||
queue.submit([encoder.finish()]);
|
||||
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let got: Vec<u32> =
|
||||
bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec();
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
// translucent ones read their sorted indices.
|
||||
struct Range {
|
||||
count: u32,
|
||||
// First sorted index, or QUADS for a solid draw.
|
||||
// First sorted index, or QUADS for a solid draw (`flatten_seen`: its
|
||||
// entry in occlusion culling's phase 2 draws).
|
||||
first: u32,
|
||||
base: u32,
|
||||
// First index in the list (`flatten_seen`: its draw call).
|
||||
dst: u32,
|
||||
}
|
||||
const QUADS: u32 = 0xffffffffu;
|
||||
@@ -14,6 +16,13 @@ const GROUP: u32 = 64u;
|
||||
@group(0) @binding(0) var<storage, read> ranges: array<Range>;
|
||||
@group(0) @binding(1) var<storage, read> sorted: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> out: array<u32>;
|
||||
|
||||
// Index `k` of a solid draw: quad k / 6's vertices 0 1 2 0 2 3.
|
||||
fn quad(k: u32) -> u32 {
|
||||
let c = k % 6u;
|
||||
return (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u);
|
||||
}
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn flatten(@builtin(workgroup_id) group: vec3<u32>,
|
||||
@builtin(local_invocation_index) lane: u32) {
|
||||
@@ -25,11 +34,43 @@ fn flatten(@builtin(workgroup_id) group: vec3<u32>,
|
||||
for (var k = lane; k < d.count; k += GROUP) {
|
||||
var i: u32;
|
||||
if d.first == QUADS {
|
||||
let c = k % 6u;
|
||||
i = (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u);
|
||||
i = quad(k);
|
||||
} else {
|
||||
i = sorted[d.first + k];
|
||||
}
|
||||
out[d.dst + k] = d.base + i;
|
||||
}
|
||||
}
|
||||
|
||||
// Occlusion culling's phase 2 (gfx/cull.rs), after its test: the draws as
|
||||
// the test left them (`DrawIndexedIndirectArgs`, the instance count 1 where
|
||||
// it saw the section), and phase 2's draw calls, whose index counts start
|
||||
// at 0. A draw the test saw takes the next indices of its call's run.
|
||||
@group(0) @binding(3) var<storage, read> draws: array<u32>;
|
||||
@group(0) @binding(4) var<storage, read_write> calls: array<atomic<u32>>;
|
||||
const UNSEEN: u32 = 0xffffffffu;
|
||||
var<workgroup> start: u32;
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn flatten_seen(@builtin(workgroup_id) group: vec3<u32>,
|
||||
@builtin(local_invocation_index) lane: u32) {
|
||||
let r = group.y * 65535u + group.x;
|
||||
if r >= arrayLength(&ranges) {
|
||||
return;
|
||||
}
|
||||
let d = ranges[r];
|
||||
if lane == 0u {
|
||||
var s = UNSEEN;
|
||||
if draws[d.first * 5u + 1u] != 0u {
|
||||
s = atomicLoad(&calls[d.dst * 5u + 2u]) + atomicAdd(&calls[d.dst * 5u], d.count);
|
||||
}
|
||||
start = s;
|
||||
}
|
||||
let s = workgroupUniformLoad(&start);
|
||||
if s == UNSEEN {
|
||||
return;
|
||||
}
|
||||
for (var k = lane; k < d.count; k += GROUP) {
|
||||
out[s + k] = d.base + quad(k);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,21 @@
|
||||
//! Iris's colour targets (`colortex0..`, each with a main and an alternate
|
||||
//! side) and the pack's `begin`, `prepare`, `deferred`, `composite` and
|
||||
//! `final` programs as full-screen passes over them, as Iris's
|
||||
//! `CompositeRenderer` runs them. Horizon's world enters `colortex0` and
|
||||
//! `depthtex0..2` after `prepare`, where Iris's gbuffers programs would have
|
||||
//! drawn, and the last picture goes to `world_post`. The targets keep GL's
|
||||
//! layout (row 0 at the bottom, which the translated vertex programs
|
||||
//! produce), so the world is flipped going in and the picture coming out.
|
||||
use super::pack_stages::FrameUniform;
|
||||
use crate::java_pack::{JavaFolder, JavaPasses};
|
||||
//! `CompositeRenderer` runs them. Horizon's world enters the target the
|
||||
//! pack's terrain program draws to (`colortex0` for most packs) and
|
||||
//! `depthtex0` after `prepare`, where Iris's gbuffers programs would have
|
||||
//! drawn (`depthtex1`/`depthtex2`: its depth before translucent geometry),
|
||||
//! and the last picture goes to `world_post`. The
|
||||
//! targets keep GL's layout (row 0 at the bottom, which the translated vertex
|
||||
//! programs produce), so the world is flipped going in and the picture coming
|
||||
//! out.
|
||||
use super::pack_stages::{FrameUniform, noise, rgba_view};
|
||||
use crate::java_pack::{JavaFolder, JavaPasses, NOISE_KEY, texture_key};
|
||||
use crate::shader_pack::Rgba;
|
||||
use glam::{Mat3, Mat4, Vec3, Vec4};
|
||||
use horizon_shaderpack::pipeline::TargetSettings;
|
||||
use horizon_shaderpack::pipeline::{Directives, Program, target_index};
|
||||
use horizon_shaderpack::properties::Blend;
|
||||
use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
|
||||
@@ -27,14 +32,13 @@ pub struct JavaFrame {
|
||||
pub moon_angle: f32,
|
||||
}
|
||||
|
||||
/// Iris's `noisetex` size (`noiseTextureResolution`'s default).
|
||||
const NOISE_SIZE: u32 = 256;
|
||||
/// The vertex buffers a pass may read (wgpu's default limit).
|
||||
const MAX_ATTRIBUTES: usize = 8;
|
||||
|
||||
const BLIT: &str = r#"
|
||||
@group(0) @binding(0) var color: texture_2d<f32>;
|
||||
@group(0) @binding(1) var depth: texture_depth_2d;
|
||||
@group(0) @binding(2) var opaque_depth: texture_depth_2d;
|
||||
|
||||
@vertex
|
||||
fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
|
||||
@@ -45,15 +49,20 @@ fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
|
||||
struct World {
|
||||
@location(0) color: vec4f,
|
||||
@location(1) depth: vec4f,
|
||||
@location(2) opaque_depth: vec4f,
|
||||
}
|
||||
|
||||
// The world's colour and depth, upside down into GL's layout; Horizon's
|
||||
// reversed depth (near 1) as GL's (near 0).
|
||||
// The world's colour, depth and pre-translucent depth, upside down into GL's
|
||||
// layout; Horizon's reversed depth (near 1) as GL's (near 0).
|
||||
@fragment
|
||||
fn world_in(@builtin(position) p: vec4f) -> World {
|
||||
let size = textureDimensions(depth);
|
||||
let xy = vec2u(u32(p.x), size.y - 1u - u32(p.y));
|
||||
return World(textureLoad(color, xy, 0), vec4f(1.0 - textureLoad(depth, xy, 0)));
|
||||
return World(
|
||||
textureLoad(color, xy, 0),
|
||||
vec4f(1.0 - textureLoad(depth, xy, 0)),
|
||||
vec4f(1.0 - textureLoad(opaque_depth, xy, 0)),
|
||||
);
|
||||
}
|
||||
|
||||
// A target, upside down back into wgpu's layout.
|
||||
@@ -64,6 +73,42 @@ fn present(@builtin(position) p: vec4f) -> @location(0) vec4f {
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Convert a GL `Blend` override from `shaders.properties` into a wgpu `BlendState`.
|
||||
fn blend_state(blend: &Blend) -> Option<wgpu::BlendState> {
|
||||
let Blend::Factors(factors) = blend else {
|
||||
return None;
|
||||
};
|
||||
let map_factor = |name: &str| -> wgpu::BlendFactor {
|
||||
use wgpu::BlendFactor as B;
|
||||
match name {
|
||||
"ZERO" => B::Zero,
|
||||
"ONE" => B::One,
|
||||
"SRC_COLOR" => B::Src,
|
||||
"ONE_MINUS_SRC_COLOR" => B::OneMinusSrc,
|
||||
"DST_COLOR" => B::Dst,
|
||||
"ONE_MINUS_DST_COLOR" => B::OneMinusDst,
|
||||
"SRC_ALPHA" => B::SrcAlpha,
|
||||
"ONE_MINUS_SRC_ALPHA" => B::OneMinusSrcAlpha,
|
||||
"DST_ALPHA" => B::DstAlpha,
|
||||
"ONE_MINUS_DST_ALPHA" => B::OneMinusDstAlpha,
|
||||
"SRC_ALPHA_SATURATE" => B::SrcAlphaSaturated,
|
||||
_ => B::One,
|
||||
}
|
||||
};
|
||||
Some(wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: map_factor(&factors[0]),
|
||||
dst_factor: map_factor(&factors[1]),
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: map_factor(&factors[2]),
|
||||
dst_factor: map_factor(&factors[3]),
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// A wgpu format for each of Iris's (`InternalTextureFormat`), renderable
|
||||
/// everywhere: 8-bit unsigned normalized formats stay, signed normalized,
|
||||
/// 16-bit and packed float ones become half floats, integer ones 32-bit.
|
||||
@@ -123,8 +168,10 @@ struct Target {
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Source {
|
||||
Target(u32),
|
||||
/// `depthtex0..2`: the world's depth.
|
||||
/// `depthtex0` / `gdepthtex`: the world's depth (including translucent water).
|
||||
Depth,
|
||||
/// `depthtex1` / `depthtex2`: the opaque world's depth (before translucent water).
|
||||
OpaqueDepth,
|
||||
Noise,
|
||||
/// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow);
|
||||
/// also Distant Horizons' and Voxy's depth, as without those mods.
|
||||
@@ -135,7 +182,8 @@ enum Source {
|
||||
|
||||
fn source(name: &str) -> Source {
|
||||
match name {
|
||||
"depthtex0" | "depthtex1" | "depthtex2" | "gdepthtex" => Source::Depth,
|
||||
"depthtex0" | "gdepthtex" => Source::Depth,
|
||||
"depthtex1" | "depthtex2" => Source::OpaqueDepth,
|
||||
"noisetex" => Source::Noise,
|
||||
"shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow,
|
||||
n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow,
|
||||
@@ -146,6 +194,7 @@ fn source(name: &str) -> Source {
|
||||
|
||||
/// A sampler of a pass: its texture and sampler bindings.
|
||||
struct SamplerBinding {
|
||||
name: String,
|
||||
source: Source,
|
||||
dimension: wgpu::TextureViewDimension,
|
||||
/// `isampler` (true) or `usampler` (false).
|
||||
@@ -183,6 +232,7 @@ struct Common {
|
||||
repeat: wgpu::Sampler,
|
||||
compare: wgpu::Sampler,
|
||||
noise: wgpu::TextureView,
|
||||
custom_textures: BTreeMap<String, wgpu::TextureView>,
|
||||
/// Full-screen triangle data per attribute kind (see `PassGpu::attributes`).
|
||||
vertices: [wgpu::Buffer; 4],
|
||||
world_layout: wgpu::BindGroupLayout,
|
||||
@@ -194,12 +244,16 @@ struct Common {
|
||||
struct Bound {
|
||||
folder: usize,
|
||||
size: [u32; 2],
|
||||
/// `world_post`'s targets it binds (`Post::generation`).
|
||||
post_generation: u64,
|
||||
targets: BTreeMap<u32, Target>,
|
||||
depth: wgpu::TextureView,
|
||||
opaque_depth: wgpu::TextureView,
|
||||
/// Per pass, then `final`.
|
||||
groups: Vec<wgpu::BindGroup>,
|
||||
world_in: (wgpu::RenderPipeline, wgpu::BindGroup),
|
||||
/// The world goes to colortex0's alternate side.
|
||||
/// The world's target, and whether the world goes to its alternate side.
|
||||
world_target: u32,
|
||||
world_alt: bool,
|
||||
final_target: Option<wgpu::TextureView>,
|
||||
present: (wgpu::RenderPipeline, wgpu::BindGroup),
|
||||
@@ -212,6 +266,7 @@ struct Bound {
|
||||
struct Folder {
|
||||
targets: Vec<TargetSettings>,
|
||||
world_at: usize,
|
||||
world_target: u32,
|
||||
flipped_after_prepare: BTreeSet<u32>,
|
||||
flipped_at_end: BTreeSet<u32>,
|
||||
passes: Vec<PassGpu>,
|
||||
@@ -221,6 +276,9 @@ struct Folder {
|
||||
|
||||
pub struct JavaStages {
|
||||
pub id: String,
|
||||
/// A pass samples `depthtex1`/`depthtex2`: the world's depth is kept
|
||||
/// before translucent geometry draws.
|
||||
pub reads_opaque_depth: bool,
|
||||
format: wgpu::TextureFormat,
|
||||
common: Common,
|
||||
folders: Vec<Folder>,
|
||||
@@ -234,6 +292,9 @@ pub struct JavaStages {
|
||||
uniform_state: UniformState,
|
||||
/// `eyeBrightnessSmooth`, block then sky.
|
||||
eye_smooth: [SmoothFloat; 2],
|
||||
/// `wetness`: `rainStrength` smoothed with `wetnessHalflife` going up
|
||||
/// and `drynessHalflife` going down.
|
||||
wetness_smooth: SmoothFloat,
|
||||
}
|
||||
|
||||
impl JavaStages {
|
||||
@@ -245,7 +306,7 @@ impl JavaStages {
|
||||
id: &str,
|
||||
pack: &JavaPasses,
|
||||
) -> Result<Self, String> {
|
||||
let common = Common::new(device, queue);
|
||||
let common = Common::new(device, queue, &pack.custom_textures);
|
||||
let folder_for = [-1, 0, 1].map(|d| pack.folder_for(d));
|
||||
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let folders = pack
|
||||
@@ -270,6 +331,7 @@ impl JavaStages {
|
||||
Ok::<_, String>(Folder {
|
||||
targets: plan.targets.clone(),
|
||||
world_at: plan.world_at,
|
||||
world_target: plan.world_target,
|
||||
flipped_after_prepare: plan.flipped_after_prepare.clone(),
|
||||
flipped_at_end: plan.flipped_at_end.clone(),
|
||||
passes,
|
||||
@@ -281,8 +343,14 @@ impl JavaStages {
|
||||
if let Some(error) = pollster::block_on(scope.pop()) {
|
||||
return Err(error.to_string());
|
||||
}
|
||||
let reads_opaque_depth = folders
|
||||
.iter()
|
||||
.flat_map(|f| f.passes.iter().chain(&f.final_pass))
|
||||
.flat_map(|p| &p.samplers)
|
||||
.any(|s| s.source == Source::OpaqueDepth);
|
||||
Ok(Self {
|
||||
id: id.to_owned(),
|
||||
reads_opaque_depth,
|
||||
format,
|
||||
common,
|
||||
folders,
|
||||
@@ -295,6 +363,7 @@ impl JavaStages {
|
||||
uniforms: pack.uniforms.clone(),
|
||||
uniform_state: UniformState::default(),
|
||||
eye_smooth: [SmoothFloat::default(); 2],
|
||||
wetness_smooth: SmoothFloat::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -315,11 +384,9 @@ impl JavaStages {
|
||||
) -> &wgpu::BindGroup {
|
||||
let dimension = (frame.dimension[0] as i32).clamp(-1, 1);
|
||||
let folder = self.folder_for[(dimension + 1) as usize].unwrap_or(0);
|
||||
if self
|
||||
.bound
|
||||
.as_ref()
|
||||
.is_none_or(|b| b.folder != folder || b.size != size)
|
||||
{
|
||||
if self.bound.as_ref().is_none_or(|b| {
|
||||
b.folder != folder || b.size != size || b.post_generation != post.generation()
|
||||
}) {
|
||||
self.bound = Some(self.bind(device, queue, folder, color, depth, size, post));
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
@@ -339,6 +406,12 @@ impl JavaStages {
|
||||
for (i, smooth) in self.eye_smooth.iter_mut().enumerate() {
|
||||
inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time);
|
||||
}
|
||||
inputs.wetness = self.wetness_smooth.update(
|
||||
frame.weather[0],
|
||||
directives.wetness_half_life,
|
||||
directives.dryness_half_life,
|
||||
frame_time,
|
||||
);
|
||||
self.uniforms
|
||||
.update(&mut self.uniform_state, frame_time, &|name| {
|
||||
inputs.builtin(name)
|
||||
@@ -417,8 +490,9 @@ impl JavaStages {
|
||||
let folder = &self.folders[folder_index];
|
||||
let plan = folder;
|
||||
let all = folder.passes.iter().chain(&folder.final_pass);
|
||||
// Every target a pass reads or writes, and colortex0 (the world).
|
||||
let mut used: BTreeSet<u32> = [0].into();
|
||||
// Every target a pass reads or writes, colortex0 (shown without
|
||||
// `final`) and the world's.
|
||||
let mut used: BTreeSet<u32> = [0, folder.world_target].into();
|
||||
for pass in all.clone() {
|
||||
used.extend(pass.draw_buffers.iter().copied());
|
||||
used.extend(pass.samplers.iter().filter_map(|s| match s.source {
|
||||
@@ -496,20 +570,41 @@ impl JavaStages {
|
||||
size,
|
||||
)
|
||||
.create_view(&Default::default());
|
||||
let opaque_depth = texture(
|
||||
"Java shader pack opaque depth",
|
||||
wgpu::TextureFormat::R32Float,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
size,
|
||||
)
|
||||
.create_view(&Default::default());
|
||||
let mut blank = Vec::new();
|
||||
let groups = all
|
||||
.clone()
|
||||
.map(|pass| pass.bind(device, queue, &targets, &depth, &self.common, &mut blank))
|
||||
.map(|pass| {
|
||||
pass.bind(
|
||||
device,
|
||||
queue,
|
||||
&targets,
|
||||
&depth,
|
||||
&opaque_depth,
|
||||
&self.common,
|
||||
&mut blank,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// The world goes into colortex0's side the gbuffers would write.
|
||||
let colortex0 = &targets[&0];
|
||||
// The world goes into its target's side the gbuffers would write.
|
||||
let world_target = &targets[&folder.world_target];
|
||||
let world_pipeline = blit_pipeline(
|
||||
device,
|
||||
&self.common,
|
||||
&self.common.world_layout,
|
||||
"world_in",
|
||||
&[colortex0.format, wgpu::TextureFormat::R32Float],
|
||||
&[
|
||||
world_target.format,
|
||||
wgpu::TextureFormat::R32Float,
|
||||
wgpu::TextureFormat::R32Float,
|
||||
],
|
||||
);
|
||||
let world_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Java shader pack world"),
|
||||
@@ -523,6 +618,10 @@ impl JavaStages {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(world_depth),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::TextureView(post.opaque_depth()),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -536,6 +635,7 @@ impl JavaStages {
|
||||
.create_view(&Default::default())
|
||||
});
|
||||
// Without `final`, Iris shows colortex0 as the last pass left it.
|
||||
let colortex0 = &targets[&0];
|
||||
let shown = final_target.clone().unwrap_or_else(|| {
|
||||
if plan.flipped_at_end.contains(&0) {
|
||||
colortex0.alt_view.clone()
|
||||
@@ -569,11 +669,14 @@ impl JavaStages {
|
||||
Bound {
|
||||
folder: folder_index,
|
||||
size,
|
||||
post_generation: post.generation(),
|
||||
targets,
|
||||
depth,
|
||||
opaque_depth,
|
||||
groups,
|
||||
world_in: (world_pipeline, world_group),
|
||||
world_alt: plan.flipped_after_prepare.contains(&0),
|
||||
world_target: folder.world_target,
|
||||
world_alt: plan.flipped_after_prepare.contains(&folder.world_target),
|
||||
final_target,
|
||||
present: (present_pipeline, present_group),
|
||||
output_view,
|
||||
@@ -584,15 +687,16 @@ impl JavaStages {
|
||||
}
|
||||
|
||||
fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) {
|
||||
let colortex0 = &bound.targets[&0];
|
||||
let target = &bound.targets[&bound.world_target];
|
||||
let side = if bound.world_alt {
|
||||
&colortex0.alt_view
|
||||
&target.alt_view
|
||||
} else {
|
||||
&colortex0.main_view
|
||||
&target.main_view
|
||||
};
|
||||
let attachments = [
|
||||
Some(color_attachment(side, None)),
|
||||
Some(color_attachment(&bound.depth, None)),
|
||||
Some(color_attachment(&bound.opaque_depth, None)),
|
||||
];
|
||||
let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Java shader pack world"),
|
||||
@@ -666,7 +770,8 @@ fn blit_pipeline(
|
||||
}
|
||||
|
||||
impl Common {
|
||||
fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
|
||||
/// `custom` holds the pack's `texture.*` images (`JavaPasses::custom_textures`).
|
||||
fn new(device: &wgpu::Device, queue: &wgpu::Queue, custom: &BTreeMap<String, Rgba>) -> Self {
|
||||
let sampler = |filter, address, compare| {
|
||||
device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Java shader pack"),
|
||||
@@ -680,40 +785,15 @@ impl Common {
|
||||
})
|
||||
};
|
||||
use wgpu::{AddressMode::*, FilterMode::*};
|
||||
// Iris's noise: random RGB, opaque.
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let noise_bytes: Vec<u8> = (0..NOISE_SIZE * NOISE_SIZE * 4)
|
||||
.map(|i| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
if i % 4 == 3 { 255 } else { (seed >> 24) as u8 }
|
||||
})
|
||||
let noise = match custom.get(NOISE_KEY) {
|
||||
Some(image) => rgba_view(device, queue, "noisetex", image),
|
||||
None => rgba_view(device, queue, "noisetex", &noise()),
|
||||
};
|
||||
let custom_textures = custom
|
||||
.iter()
|
||||
.filter(|(key, _)| *key != NOISE_KEY)
|
||||
.map(|(key, image)| (key.clone(), rgba_view(device, queue, key, image)))
|
||||
.collect();
|
||||
let noise = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("noisetex"),
|
||||
size: wgpu::Extent3d {
|
||||
width: NOISE_SIZE,
|
||||
height: NOISE_SIZE,
|
||||
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_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
queue.write_texture(
|
||||
noise.as_image_copy(),
|
||||
&noise_bytes,
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(NOISE_SIZE * 4),
|
||||
rows_per_image: None,
|
||||
},
|
||||
noise.size(),
|
||||
);
|
||||
// The full-screen triangle (0, 0), (2, 0), (0, 2): the pack's
|
||||
// projection maps 0..1 to the screen. Texture coordinates are the
|
||||
// position; colours white; normals up.
|
||||
@@ -753,13 +833,15 @@ impl Common {
|
||||
nearest: sampler(Nearest, ClampToEdge, None),
|
||||
repeat: sampler(Linear, Repeat, None),
|
||||
compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)),
|
||||
noise: noise.create_view(&Default::default()),
|
||||
noise,
|
||||
custom_textures,
|
||||
vertices,
|
||||
world_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Java shader pack world"),
|
||||
entries: &[
|
||||
texture_entry(0, unfilterable),
|
||||
texture_entry(1, wgpu::TextureSampleType::Depth),
|
||||
texture_entry(2, wgpu::TextureSampleType::Depth),
|
||||
],
|
||||
}),
|
||||
present_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
@@ -841,6 +923,7 @@ impl PassGpu {
|
||||
.cloned()
|
||||
.unwrap_or_else(|| format!("{sampler}_s"));
|
||||
samplers.push(SamplerBinding {
|
||||
name: sampler.clone(),
|
||||
source: source(sampler),
|
||||
dimension,
|
||||
signed,
|
||||
@@ -885,7 +968,7 @@ impl PassGpu {
|
||||
)),
|
||||
)
|
||||
}
|
||||
(false, Source::Depth | Source::Shadow) => (
|
||||
(false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => (
|
||||
wgpu::TextureSampleType::Float { filterable: false },
|
||||
Some(false),
|
||||
),
|
||||
@@ -979,10 +1062,11 @@ impl PassGpu {
|
||||
|
||||
// Output location `l` writes target `draw_buffers[l]` (or the screen).
|
||||
let outputs = &program.fragment.interface.outputs;
|
||||
let pass_blend = program.pass.blend.as_ref().and_then(blend_state);
|
||||
let target_states: Vec<Option<wgpu::ColorTargetState>> = match screen {
|
||||
Some(format) => vec![Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
blend: pass_blend,
|
||||
write_mask: if outputs.contains_key(&0) {
|
||||
wgpu::ColorWrites::ALL
|
||||
} else {
|
||||
@@ -994,12 +1078,25 @@ impl PassGpu {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(l, &i)| {
|
||||
let format = formats
|
||||
.get(i as usize)
|
||||
.copied()
|
||||
.unwrap_or(wgpu::TextureFormat::Rgba8Unorm);
|
||||
// Only filterable float/unorm formats support blending.
|
||||
let can_blend = matches!(
|
||||
sample_type(format),
|
||||
wgpu::TextureSampleType::Float { filterable: true }
|
||||
);
|
||||
let buf_blend = program
|
||||
.pass
|
||||
.buffer_blends
|
||||
.iter()
|
||||
.find(|(idx, _)| *idx == i)
|
||||
.map(|(_, b)| blend_state(b))
|
||||
.unwrap_or(pass_blend);
|
||||
Some(wgpu::ColorTargetState {
|
||||
format: formats
|
||||
.get(i as usize)
|
||||
.copied()
|
||||
.unwrap_or(wgpu::TextureFormat::Rgba8Unorm),
|
||||
blend: None,
|
||||
format,
|
||||
blend: if can_blend { buf_blend } else { None },
|
||||
write_mask: if outputs.contains_key(&(l as u32)) {
|
||||
wgpu::ColorWrites::ALL
|
||||
} else {
|
||||
@@ -1068,37 +1165,55 @@ impl PassGpu {
|
||||
}
|
||||
|
||||
/// The pass's bind group over `targets`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn bind(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
targets: &BTreeMap<u32, Target>,
|
||||
depth: &wgpu::TextureView,
|
||||
opaque_depth: &wgpu::TextureView,
|
||||
common: &Common,
|
||||
blank: &mut Vec<wgpu::Texture>,
|
||||
) -> wgpu::BindGroup {
|
||||
let mut views = Vec::new();
|
||||
for s in &self.samplers {
|
||||
let view = match (s.compare, s.source) {
|
||||
(true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth),
|
||||
(false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => {
|
||||
match targets.get(&i) {
|
||||
Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(),
|
||||
Some(t) => t.main_view.clone(),
|
||||
None => blank_view(device, queue, blank, s, BlankKind::Color(false)),
|
||||
let custom = (!s.compare && s.dimension == wgpu::TextureViewDimension::D2)
|
||||
.then(|| {
|
||||
common
|
||||
.custom_textures
|
||||
.get(&texture_key(&self.program, &s.name))
|
||||
})
|
||||
.flatten();
|
||||
let view = if let Some(custom) = custom {
|
||||
custom.clone()
|
||||
} else {
|
||||
match (s.compare, s.source) {
|
||||
(true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth),
|
||||
(false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => {
|
||||
match targets.get(&i) {
|
||||
Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(),
|
||||
Some(t) => t.main_view.clone(),
|
||||
None => blank_view(device, queue, blank, s, BlankKind::Color(false)),
|
||||
}
|
||||
}
|
||||
(false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => {
|
||||
depth.clone()
|
||||
}
|
||||
(false, Source::OpaqueDepth)
|
||||
if s.dimension == wgpu::TextureViewDimension::D2 =>
|
||||
{
|
||||
opaque_depth.clone()
|
||||
}
|
||||
(false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far),
|
||||
(false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => {
|
||||
common.noise.clone()
|
||||
}
|
||||
(false, Source::Blank(white)) => {
|
||||
blank_view(device, queue, blank, s, BlankKind::Color(white))
|
||||
}
|
||||
_ => blank_view(device, queue, blank, s, BlankKind::Color(false)),
|
||||
}
|
||||
(false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => {
|
||||
depth.clone()
|
||||
}
|
||||
(false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far),
|
||||
(false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => {
|
||||
common.noise.clone()
|
||||
}
|
||||
(false, Source::Blank(white)) => {
|
||||
blank_view(device, queue, blank, s, BlankKind::Color(white))
|
||||
}
|
||||
_ => blank_view(device, queue, blank, s, BlankKind::Color(false)),
|
||||
};
|
||||
let sampler = match (s.compare, s.source) {
|
||||
_ if s.shared.is_some() => match s.shared.as_deref() {
|
||||
@@ -1110,7 +1225,7 @@ impl PassGpu {
|
||||
(true, _) => &common.compare,
|
||||
_ if s.signed.is_some() => &common.nearest,
|
||||
(false, Source::Noise) => &common.repeat,
|
||||
(false, Source::Depth | Source::Shadow) => &common.nearest,
|
||||
(false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => &common.nearest,
|
||||
(false, Source::Target(i)) => {
|
||||
match targets.get(&i).map(|t| sample_type(t.format)) {
|
||||
Some(wgpu::TextureSampleType::Float { filterable: true }) | None => {
|
||||
@@ -1442,6 +1557,8 @@ struct Inputs {
|
||||
/// `eyeBrightness` and `eyeBrightnessSmooth`: block, sky light × 16.
|
||||
eye: [f32; 2],
|
||||
eye_smooth: [f32; 2],
|
||||
/// `wetness` (`JavaStages::wetness_smooth`).
|
||||
wetness: f32,
|
||||
/// `CelestialUniforms`, in view space.
|
||||
sun_position: Vec3,
|
||||
moon_position: Vec3,
|
||||
@@ -1499,6 +1616,7 @@ impl Inputs {
|
||||
frame: *frame,
|
||||
eye: [0.0; 2],
|
||||
eye_smooth: [0.0; 2],
|
||||
wetness: frame.weather[0],
|
||||
sun_position: Vec3::ZERO,
|
||||
moon_position: Vec3::ZERO,
|
||||
up_position: Vec3::ZERO,
|
||||
@@ -1591,7 +1709,8 @@ impl Inputs {
|
||||
}),
|
||||
"upPosition" => vec3(self.up_position),
|
||||
"moonPhase" => vec![f.moon[3]],
|
||||
"rainStrength" | "wetness" => vec![f.weather[0]],
|
||||
"rainStrength" => vec![f.weather[0]],
|
||||
"wetness" => vec![self.wetness],
|
||||
"thunderStrength" => vec![f.weather[1]],
|
||||
"fogColor" => f.fog_color[..3].to_vec(),
|
||||
"skyColor" => f.sky_color[..3].to_vec(),
|
||||
@@ -1651,6 +1770,7 @@ mod tests {
|
||||
assert_eq!(source("colortex4"), Source::Target(4));
|
||||
assert_eq!(source("gaux1"), Source::Target(4));
|
||||
assert_eq!(source("gdepthtex"), Source::Depth);
|
||||
assert_eq!(source("depthtex1"), Source::OpaqueDepth);
|
||||
assert_eq!(source("shadowtex1"), Source::Shadow);
|
||||
assert_eq!(source("dhDepthTex0"), Source::Shadow);
|
||||
assert_eq!(source("shadowcolor0"), Source::Blank(true));
|
||||
|
||||
@@ -119,10 +119,6 @@ impl Tile {
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
pub fn resident_lods(&self) -> usize {
|
||||
self.lods.len()
|
||||
}
|
||||
|
||||
pub fn upload_lod(&mut self, key: TileKey, mesh: &SectionMesh) {
|
||||
self.remove_lod(key);
|
||||
if let Some(bounds) = Bounds::mesh(mesh)
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
//! A Horizon shader pack on the GPU (docs/shader-packs.md): each `composite`
|
||||
//! stage is one full-screen pass that reads the world's colour and depth and
|
||||
//! the previous stage's output and writes its own target; the last target
|
||||
//! goes to the screen through `world_post` (copy or FXAA) under the hand and
|
||||
//! HUD. Only exists while a pack is selected.
|
||||
use crate::shader_pack::{ShaderPack, VERTEX_ENTRY};
|
||||
//! A Horizon shader pack on the GPU (docs/shader-packs.md): each stage
|
||||
//! (`shadow`, `gbuffer`, `deferred`, `composite`, `final`) is a full-screen
|
||||
//! pass that reads the world's colour, depth, opaque depth, G-buffer normals
|
||||
//! and materials, shadow map, noise texture and the previous stage's output,
|
||||
//! and writes its own target; the last target goes to the screen through
|
||||
//! `world_post` (copy or FXAA) under the hand and HUD. Only exists while a
|
||||
//! pack is selected.
|
||||
use crate::shader_pack::{Rgba, ShaderPack, VERTEX_ENTRY};
|
||||
use horizon_shaderpack::uniforms::SmoothFloat;
|
||||
|
||||
/// The `Frame` uniform of the prelude (`shader_pack_prelude.wgsl`).
|
||||
#[repr(C)]
|
||||
@@ -27,10 +30,81 @@ pub struct FrameUniform {
|
||||
pub dimension: [f32; 4],
|
||||
}
|
||||
|
||||
/// The API 2 `FrameExt` uniform of the prelude (`shader_pack_prelude.wgsl`).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct FrameExtUniform {
|
||||
pub previous_view: [[f32; 4]; 4],
|
||||
pub previous_projection: [[f32; 4]; 4],
|
||||
pub shadow_view: [[f32; 4]; 4],
|
||||
pub shadow_projection: [[f32; 4]; 4],
|
||||
pub shadow_inverse_view: [[f32; 4]; 4],
|
||||
pub shadow_inverse_projection: [[f32; 4]; 4],
|
||||
pub previous_camera: [f32; 4],
|
||||
pub shadow_params: [f32; 4],
|
||||
pub environment: [f32; 4],
|
||||
}
|
||||
|
||||
/// Iris's `noisetex` without a `texture.noise`: 256² random RGB, opaque.
|
||||
/// Horizon packs get the same one unless `[textures] noise` replaces it.
|
||||
pub(super) fn noise() -> Rgba {
|
||||
const SIZE: u32 = 256;
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let pixels = (0..SIZE * SIZE * 4)
|
||||
.map(|i| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
if i % 4 == 3 { 255 } else { (seed >> 24) as u8 }
|
||||
})
|
||||
.collect();
|
||||
Rgba {
|
||||
width: SIZE,
|
||||
height: SIZE,
|
||||
pixels,
|
||||
}
|
||||
}
|
||||
|
||||
/// `image` as a sampled RGBA8 texture.
|
||||
pub(super) fn rgba_view(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
label: &str,
|
||||
image: &Rgba,
|
||||
) -> wgpu::TextureView {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
queue.write_texture(
|
||||
texture.as_image_copy(),
|
||||
&image.pixels,
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(image.width * 4),
|
||||
rows_per_image: None,
|
||||
},
|
||||
texture.size(),
|
||||
);
|
||||
texture.create_view(&Default::default())
|
||||
}
|
||||
|
||||
struct Pass {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
scale: f32,
|
||||
target_format: wgpu::TextureFormat,
|
||||
uniform: wgpu::Buffer,
|
||||
uniform_ext: wgpu::Buffer,
|
||||
}
|
||||
/// A stage's output and the bindings that read the world into it.
|
||||
struct Target {
|
||||
@@ -41,24 +115,47 @@ struct Target {
|
||||
|
||||
pub struct PackStages {
|
||||
pub id: String,
|
||||
pub needs_shadow: bool,
|
||||
/// The stages read the G-buffer (`build_gbuffer`) or the depth before
|
||||
/// translucent geometry (`capture_opaque_depth`).
|
||||
pub needs_gbuffer: bool,
|
||||
pub needs_opaque_depth: bool,
|
||||
pub shadow_res: u32,
|
||||
pub shadow_dist: f32,
|
||||
layout: wgpu::BindGroupLayout,
|
||||
linear: wgpu::Sampler,
|
||||
nearest: wgpu::Sampler,
|
||||
repeat: wgpu::Sampler,
|
||||
shadow_sampler: wgpu::Sampler,
|
||||
noise_view: wgpu::TextureView,
|
||||
passes: Vec<Pass>,
|
||||
format: wgpu::TextureFormat,
|
||||
/// Built for this world target size.
|
||||
/// Built for this world target size and `world_post` generation.
|
||||
targets: Vec<Target>,
|
||||
/// `world_post`'s bindings of the last stage's output.
|
||||
output: Option<wgpu::BindGroup>,
|
||||
world_size: [u32; 2],
|
||||
post_generation: u64,
|
||||
started: std::time::Instant,
|
||||
last: Option<std::time::Instant>,
|
||||
frames: u32,
|
||||
previous: Option<([[f32; 4]; 4], [[f32; 4]; 4], [f32; 3])>,
|
||||
wetness: SmoothFloat,
|
||||
}
|
||||
|
||||
fn stage_format(name: Option<&str>, default: wgpu::TextureFormat) -> wgpu::TextureFormat {
|
||||
match name.map(str::to_lowercase).as_deref() {
|
||||
Some("rgba16float" | "rgba16f") => wgpu::TextureFormat::Rgba16Float,
|
||||
Some("rgba8unorm" | "rgba8" | "rgba") => wgpu::TextureFormat::Rgba8Unorm,
|
||||
Some("rgb10a2unorm" | "rgb10_a2") => wgpu::TextureFormat::Rgb10a2Unorm,
|
||||
_ => default,
|
||||
}
|
||||
}
|
||||
|
||||
impl PackStages {
|
||||
/// The pipelines of a loaded (already validated) pack, or wgpu's error.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
format: wgpu::TextureFormat,
|
||||
pack: &ShaderPack,
|
||||
) -> Result<Self, String> {
|
||||
@@ -79,6 +176,16 @@ impl PackStages {
|
||||
ty: wgpu::BindingType::Sampler(ty),
|
||||
count: None,
|
||||
};
|
||||
let uniform_entry = |binding| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Shader pack stage"),
|
||||
entries: &[
|
||||
@@ -87,16 +194,15 @@ impl PackStages {
|
||||
texture(2, float),
|
||||
sampler(3, wgpu::SamplerBindingType::Filtering),
|
||||
sampler(4, wgpu::SamplerBindingType::NonFiltering),
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 5,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
uniform_entry(5),
|
||||
uniform_entry(6),
|
||||
texture(7, float),
|
||||
texture(8, float),
|
||||
texture(9, wgpu::TextureSampleType::Depth),
|
||||
texture(10, wgpu::TextureSampleType::Depth),
|
||||
sampler(11, wgpu::SamplerBindingType::Comparison),
|
||||
texture(12, float),
|
||||
sampler(13, wgpu::SamplerBindingType::Filtering),
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
@@ -106,10 +212,18 @@ impl PackStages {
|
||||
});
|
||||
let constants = pack.constants();
|
||||
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let stage_count = pack.stages.len();
|
||||
let passes = pack
|
||||
.stages
|
||||
.iter()
|
||||
.map(|stage| {
|
||||
.enumerate()
|
||||
.map(|(idx, stage)| {
|
||||
let is_last = idx + 1 == stage_count;
|
||||
let target_format = if is_last {
|
||||
format
|
||||
} else {
|
||||
stage_format(stage.format.as_deref(), format)
|
||||
};
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some(&stage.file),
|
||||
source: wgpu::ShaderSource::Wgsl(stage.source.as_str().into()),
|
||||
@@ -140,7 +254,7 @@ impl PackStages {
|
||||
..Default::default()
|
||||
},
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
format: target_format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
@@ -151,38 +265,77 @@ impl PackStages {
|
||||
Pass {
|
||||
pipeline,
|
||||
scale: stage.scale,
|
||||
target_format,
|
||||
uniform: device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack frame"),
|
||||
size: std::mem::size_of::<FrameUniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
}),
|
||||
uniform_ext: device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Shader pack frame ext"),
|
||||
size: std::mem::size_of::<FrameExtUniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
}),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if let Some(error) = pollster::block_on(scope.pop()) {
|
||||
return Err(error.to_string());
|
||||
}
|
||||
let sampler = |filter| {
|
||||
let make_sampler = |filter, address, compare| {
|
||||
device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Shader pack"),
|
||||
address_mode_u: address,
|
||||
address_mode_v: address,
|
||||
address_mode_w: address,
|
||||
mag_filter: filter,
|
||||
min_filter: filter,
|
||||
compare,
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
let noise_view = match &pack.custom_noise {
|
||||
Some(image) => rgba_view(device, queue, "Shader pack noise", image),
|
||||
None => rgba_view(device, queue, "Shader pack noise", &noise()),
|
||||
};
|
||||
let (shadow_res, shadow_dist) = pack.shadow_config();
|
||||
Ok(Self {
|
||||
id: pack.id.clone(),
|
||||
needs_shadow: pack.needs_shadow(),
|
||||
needs_gbuffer: pack.needs_gbuffer(),
|
||||
needs_opaque_depth: pack.needs_opaque_depth(),
|
||||
shadow_res,
|
||||
shadow_dist,
|
||||
layout,
|
||||
linear: sampler(wgpu::FilterMode::Linear),
|
||||
nearest: sampler(wgpu::FilterMode::Nearest),
|
||||
linear: make_sampler(
|
||||
wgpu::FilterMode::Linear,
|
||||
wgpu::AddressMode::ClampToEdge,
|
||||
None,
|
||||
),
|
||||
nearest: make_sampler(
|
||||
wgpu::FilterMode::Nearest,
|
||||
wgpu::AddressMode::ClampToEdge,
|
||||
None,
|
||||
),
|
||||
repeat: make_sampler(wgpu::FilterMode::Linear, wgpu::AddressMode::Repeat, None),
|
||||
shadow_sampler: make_sampler(
|
||||
wgpu::FilterMode::Linear,
|
||||
wgpu::AddressMode::ClampToEdge,
|
||||
Some(wgpu::CompareFunction::GreaterEqual),
|
||||
),
|
||||
noise_view,
|
||||
passes,
|
||||
format,
|
||||
targets: Vec::new(),
|
||||
output: None,
|
||||
world_size: [0, 0],
|
||||
post_generation: u64::MAX,
|
||||
started: std::time::Instant::now(),
|
||||
last: None,
|
||||
frames: 0,
|
||||
previous: None,
|
||||
wetness: SmoothFloat::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -199,9 +352,14 @@ impl PackStages {
|
||||
size: [u32; 2],
|
||||
post: &super::world_post::Post,
|
||||
mut uniform: FrameUniform,
|
||||
eye_light: [u8; 2],
|
||||
) -> &wgpu::BindGroup {
|
||||
if self.world_size != size || self.targets.len() != self.passes.len() {
|
||||
if self.world_size != size
|
||||
|| self.post_generation != post.generation()
|
||||
|| self.targets.len() != self.passes.len()
|
||||
{
|
||||
self.world_size = size;
|
||||
self.post_generation = post.generation();
|
||||
self.targets.clear();
|
||||
for pass in &self.passes {
|
||||
let target_size = size.map(|v| ((v as f32 * pass.scale).round() as u32).max(1));
|
||||
@@ -216,7 +374,7 @@ impl PackStages {
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: self.format,
|
||||
format: pass.target_format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
@@ -251,6 +409,38 @@ impl PackStages {
|
||||
binding: 5,
|
||||
resource: pass.uniform.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 6,
|
||||
resource: pass.uniform_ext.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 7,
|
||||
resource: wgpu::BindingResource::TextureView(post.normal()),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 8,
|
||||
resource: wgpu::BindingResource::TextureView(post.material()),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 9,
|
||||
resource: wgpu::BindingResource::TextureView(post.opaque_depth()),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 10,
|
||||
resource: wgpu::BindingResource::TextureView(post.shadow_depth()),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 11,
|
||||
resource: wgpu::BindingResource::Sampler(&self.shadow_sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 12,
|
||||
resource: wgpu::BindingResource::TextureView(&self.noise_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 13,
|
||||
resource: wgpu::BindingResource::Sampler(&self.repeat),
|
||||
},
|
||||
],
|
||||
});
|
||||
self.targets.push(Target {
|
||||
@@ -262,6 +452,42 @@ impl PackStages {
|
||||
let last = &self.targets.last().expect("a pack has a stage").view;
|
||||
self.output = Some(post.bind(device, last));
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
let dt = self.last.map_or(0.0, |t| (now - t).as_secs_f32());
|
||||
self.last = Some(now);
|
||||
let wet = self.wetness.update(uniform.weather[0], 60.0, 120.0, dt);
|
||||
let cam = [
|
||||
uniform.camera_position[0],
|
||||
uniform.camera_position[1],
|
||||
uniform.camera_position[2],
|
||||
];
|
||||
let (prev_view, prev_proj, prev_cam) =
|
||||
self.previous
|
||||
.unwrap_or((uniform.view, uniform.projection, cam));
|
||||
self.previous = Some((uniform.view, uniform.projection, cam));
|
||||
let shadow_view = post.shadow_view;
|
||||
let shadow_proj = post.shadow_proj;
|
||||
let ext = FrameExtUniform {
|
||||
previous_view: prev_view,
|
||||
previous_projection: prev_proj,
|
||||
shadow_view: shadow_view.to_cols_array_2d(),
|
||||
shadow_projection: shadow_proj.to_cols_array_2d(),
|
||||
shadow_inverse_view: shadow_view.inverse().to_cols_array_2d(),
|
||||
shadow_inverse_projection: shadow_proj.inverse().to_cols_array_2d(),
|
||||
previous_camera: [prev_cam[0], prev_cam[1], prev_cam[2], dt],
|
||||
shadow_params: [
|
||||
post.shadow_resolution as f32,
|
||||
post.shadow_distance,
|
||||
0.0,
|
||||
if post.shadow_active { 1.0 } else { 0.0 },
|
||||
],
|
||||
environment: [
|
||||
f32::from(eye_light[0]) * 16.0,
|
||||
f32::from(eye_light[1]) * 16.0,
|
||||
wet,
|
||||
0.0,
|
||||
],
|
||||
};
|
||||
uniform.time[0] = self.started.elapsed().as_secs_f32();
|
||||
uniform.time[1] = self.frames as f32;
|
||||
self.frames = self.frames.wrapping_add(1);
|
||||
@@ -269,6 +495,7 @@ impl PackStages {
|
||||
let [w, h] = target.size.map(|v| v as f32);
|
||||
uniform.resolution = [w, h, 1.0 / w, 1.0 / h];
|
||||
queue.write_buffer(&pass.uniform, 0, bytemuck::bytes_of(&uniform));
|
||||
queue.write_buffer(&pass.uniform_ext, 0, bytemuck::bytes_of(&ext));
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: &target.view,
|
||||
resolve_target: None,
|
||||
|
||||
@@ -1,18 +1,35 @@
|
||||
//! GPU frame time from timestamp queries, read back a few frames late so the
|
||||
//! CPU never waits for it. Frames whose readback slot is still busy go untimed.
|
||||
//!
|
||||
//! Where the GPU can only time pass boundaries (Apple GPUs on Metal), the
|
||||
//! frame is bracketed by two one-thread compute passes that write the
|
||||
//! timestamps (Metal leaves an empty pass's timestamps at zero).
|
||||
//! Where the GPU can only time pass boundaries (Apple GPUs on Metal), a
|
||||
//! one-thread compute pass stamps the frame's start, and a render pass over
|
||||
//! the frame's target that shades one pixel with every write masked stamps
|
||||
//! its end (Metal leaves the timestamps of a pass that does nothing at zero).
|
||||
//! A pass that loads the target runs after every pass that draws into it; a
|
||||
//! compute pass, which depends on nothing, ran alongside them. Metal also
|
||||
//! resolves timestamps without waiting for the passes that write them, so
|
||||
//! they are resolved in a later frame, once the GPU has finished this one.
|
||||
//! Resolved in the frame itself, the end was mostly the one an earlier frame
|
||||
//! left in the query, and frames read about 0.01 ms.
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU8, Ordering},
|
||||
};
|
||||
|
||||
const SLOTS: usize = 4;
|
||||
/// Frames in flight at once; on Metal a slot is busy for about five frames.
|
||||
const SLOTS: usize = 8;
|
||||
/// Each slot's timestamps have their own queries and resolve range.
|
||||
const RESOLVE_STRIDE: u64 = wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
|
||||
/// The frame's target and its format.
|
||||
pub type Target<'a> = (&'a wgpu::TextureView, wgpu::TextureFormat);
|
||||
const FREE: u8 = 0;
|
||||
const PENDING: u8 = 1;
|
||||
const MAPPED: u8 = 2;
|
||||
/// Its frame is submitted; with markers, until the GPU has finished it.
|
||||
const RUNNING: u8 = 1;
|
||||
/// Its frame is finished: its timestamps can be resolved.
|
||||
const DONE: u8 = 2;
|
||||
/// Resolved and on its way back.
|
||||
const PENDING: u8 = 3;
|
||||
const MAPPED: u8 = 4;
|
||||
|
||||
struct Slot {
|
||||
buffer: wgpu::Buffer,
|
||||
@@ -27,10 +44,29 @@ pub struct GpuTimer {
|
||||
current: Option<usize>,
|
||||
next: usize,
|
||||
period_ns: f32,
|
||||
/// Timestamps between commands, or else this pass's boundaries.
|
||||
marker: Option<wgpu::ComputePipeline>,
|
||||
/// Timestamps between commands, or else these passes' boundaries.
|
||||
markers: Option<Markers>,
|
||||
/// Slots resolved in this frame's commands, read back once it is submitted.
|
||||
resolved: Vec<usize>,
|
||||
}
|
||||
|
||||
/// The marker passes: the start's compute pipeline, and the end's shader and
|
||||
/// pipeline, for the target format it was made for.
|
||||
struct Markers {
|
||||
module: wgpu::ShaderModule,
|
||||
start: wgpu::ComputePipeline,
|
||||
end: Option<(wgpu::TextureFormat, wgpu::RenderPipeline)>,
|
||||
}
|
||||
|
||||
/// The start's one thread; the end's triangle over the whole target (the
|
||||
/// pass's scissor keeps one pixel), shading nothing it writes.
|
||||
const MARKER: &str =
|
||||
"@vertex fn cover(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
||||
return vec4<f32>(f32(i & 1u) * 4.0 - 1.0, f32(i >> 1u) * 4.0 - 1.0, 0.0, 1.0);
|
||||
}
|
||||
@fragment fn nothing() -> @location(0) vec4<f32> { return vec4<f32>(0.0); }
|
||||
@compute @workgroup_size(1) fn mark() {}";
|
||||
|
||||
impl GpuTimer {
|
||||
/// The features timing uses that the adapter has (none: no timing).
|
||||
pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features {
|
||||
@@ -44,11 +80,11 @@ impl GpuTimer {
|
||||
let queries = device.create_query_set(&wgpu::QuerySetDescriptor {
|
||||
label: Some("Frame timestamps"),
|
||||
ty: wgpu::QueryType::Timestamp,
|
||||
count: 2,
|
||||
count: 2 * SLOTS as u32,
|
||||
});
|
||||
let resolve = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Frame timestamp resolve"),
|
||||
size: 16,
|
||||
size: RESOLVE_STRIDE * SLOTS as u64,
|
||||
usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
@@ -70,42 +106,43 @@ impl GpuTimer {
|
||||
current: None,
|
||||
next: 0,
|
||||
period_ns: queue.get_timestamp_period(),
|
||||
marker: (!device
|
||||
markers: (!device
|
||||
.features()
|
||||
.contains(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS))
|
||||
.then(|| {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
"@compute @workgroup_size(1) fn mark() {}".into(),
|
||||
),
|
||||
source: wgpu::ShaderSource::Wgsl(MARKER.into()),
|
||||
});
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some("mark"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
})
|
||||
Markers {
|
||||
start: device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some("mark"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
}),
|
||||
module,
|
||||
end: None,
|
||||
}
|
||||
}),
|
||||
resolved: Vec::new(),
|
||||
})
|
||||
}
|
||||
pub fn begin(&mut self, encoder: &mut wgpu::CommandEncoder) {
|
||||
if self.markers.is_some() {
|
||||
for slot in 0..SLOTS {
|
||||
if self.slots[slot].state.load(Ordering::Acquire) == DONE {
|
||||
self.resolve(encoder, slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
let slot = self.next;
|
||||
self.current = (self.slots[slot].state.load(Ordering::Acquire) == FREE).then_some(slot);
|
||||
if self.current.is_some() {
|
||||
self.stamp(encoder, 0);
|
||||
}
|
||||
}
|
||||
pub fn end(&mut self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let Some(slot) = self.current else { return };
|
||||
self.stamp(encoder, 1);
|
||||
encoder.resolve_query_set(&self.queries, 0..2, &self.resolve, 0);
|
||||
encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.slots[slot].buffer, 0, 16);
|
||||
}
|
||||
fn stamp(&self, encoder: &mut wgpu::CommandEncoder, index: u32) {
|
||||
let Some(marker) = &self.marker else {
|
||||
let index = 2 * slot as u32;
|
||||
let Some(markers) = &self.markers else {
|
||||
encoder.write_timestamp(&self.queries, index);
|
||||
return;
|
||||
};
|
||||
@@ -113,29 +150,85 @@ impl GpuTimer {
|
||||
label: Some("Frame timestamp"),
|
||||
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
|
||||
query_set: &self.queries,
|
||||
beginning_of_pass_write_index: (index == 0).then_some(0),
|
||||
end_of_pass_write_index: (index == 1).then_some(1),
|
||||
beginning_of_pass_write_index: Some(index),
|
||||
end_of_pass_write_index: None,
|
||||
}),
|
||||
});
|
||||
pass.set_pipeline(marker);
|
||||
pass.set_pipeline(&markers.start);
|
||||
pass.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
/// After the frame's submission: start reading its timestamps back.
|
||||
pub fn submitted(&mut self) {
|
||||
/// After the frame's last pass into `target` (the frame's own, of `format`).
|
||||
pub fn end(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
(target, format): Target,
|
||||
) {
|
||||
let Some(slot) = self.current else { return };
|
||||
let index = 2 * slot as u32 + 1;
|
||||
let Some(markers) = &mut self.markers else {
|
||||
encoder.write_timestamp(&self.queries, index);
|
||||
self.resolve(encoder, slot);
|
||||
return;
|
||||
};
|
||||
if markers.end.as_ref().is_none_or(|(f, _)| *f != format) {
|
||||
markers.end = Some((format, end_pipeline(device, &markers.module, format)));
|
||||
}
|
||||
let (_, pipeline) = markers.end.as_ref().expect("made above");
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: target,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Load,
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
timestamp_writes: Some(wgpu::RenderPassTimestampWrites {
|
||||
query_set: &self.queries,
|
||||
beginning_of_pass_write_index: None,
|
||||
end_of_pass_write_index: Some(index),
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_scissor_rect(0, 0, 1, 1);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
/// Copy `slot`'s timestamps to its readback buffer.
|
||||
fn resolve(&mut self, encoder: &mut wgpu::CommandEncoder, slot: usize) {
|
||||
let (first, at) = (2 * slot as u32, RESOLVE_STRIDE * slot as u64);
|
||||
encoder.resolve_query_set(&self.queries, first..first + 2, &self.resolve, at);
|
||||
encoder.copy_buffer_to_buffer(&self.resolve, at, &self.slots[slot].buffer, 0, 16);
|
||||
self.slots[slot].state.store(RUNNING, Ordering::Release);
|
||||
self.resolved.push(slot);
|
||||
}
|
||||
/// After the frame's submission: start reading back what it resolved,
|
||||
/// and with markers, wait for the GPU to finish the frame it timed.
|
||||
pub fn submitted(&mut self, queue: &wgpu::Queue) {
|
||||
for slot in self.resolved.drain(..) {
|
||||
let state = self.slots[slot].state.clone();
|
||||
state.store(PENDING, Ordering::Release);
|
||||
self.slots[slot]
|
||||
.buffer
|
||||
.slice(..)
|
||||
.map_async(wgpu::MapMode::Read, move |result| {
|
||||
state.store(
|
||||
if result.is_ok() { MAPPED } else { FREE },
|
||||
Ordering::Release,
|
||||
);
|
||||
});
|
||||
}
|
||||
let Some(slot) = self.current.take() else {
|
||||
return;
|
||||
};
|
||||
let state = self.slots[slot].state.clone();
|
||||
state.store(PENDING, Ordering::Release);
|
||||
self.slots[slot]
|
||||
.buffer
|
||||
.slice(..)
|
||||
.map_async(wgpu::MapMode::Read, move |result| {
|
||||
state.store(
|
||||
if result.is_ok() { MAPPED } else { FREE },
|
||||
Ordering::Release,
|
||||
);
|
||||
});
|
||||
if self.markers.is_some() {
|
||||
let state = self.slots[slot].state.clone();
|
||||
state.store(RUNNING, Ordering::Release);
|
||||
queue.on_submitted_work_done(move || state.store(DONE, Ordering::Release));
|
||||
}
|
||||
self.next = (slot + 1) % SLOTS;
|
||||
}
|
||||
/// GPU milliseconds of frames whose timestamps have arrived, oldest first.
|
||||
@@ -149,11 +242,46 @@ impl GpuTimer {
|
||||
if let Ok(data) = slot.buffer.slice(..).get_mapped_range() {
|
||||
// Read unaligned: the mapping isn't guaranteed to be 8-byte aligned.
|
||||
let stamps: [u64; 2] = bytemuck::pod_read_unaligned(&data[..16]);
|
||||
let ticks = stamps[1].saturating_sub(stamps[0]);
|
||||
out.push((ticks as f64 * f64::from(self.period_ns) / 1e6) as f32);
|
||||
// A start marker that ran late (rare on Metal) leaves the frame untimed.
|
||||
if let Some(ticks) = stamps[1].checked_sub(stamps[0]) {
|
||||
out.push((ticks as f64 * f64::from(self.period_ns) / 1e6) as f32);
|
||||
}
|
||||
}
|
||||
slot.buffer.unmap();
|
||||
slot.state.store(FREE, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The end marker's pipeline for a `format` target, every write masked.
|
||||
fn end_pipeline(
|
||||
device: &wgpu::Device,
|
||||
module: &wgpu::ShaderModule,
|
||||
format: wgpu::TextureFormat,
|
||||
) -> wgpu::RenderPipeline {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
layout: None,
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some("cover"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some("nothing"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::empty(),
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,26 +1,163 @@
|
||||
//! Resolution scale and FXAA (Horizon settings): the world renders into its
|
||||
//! own target at the scaled size, then one full-screen pass copies or
|
||||
//! anti-aliases it onto the screen, under the hand and HUD. A shader pack
|
||||
//! also needs the target (its stages read the world's colour and depth).
|
||||
//! Resolution scale, FXAA, and shader-pack G-buffer/shadow targets (Horizon
|
||||
//! settings): the world renders into its own target at the scaled size, then
|
||||
//! one full-screen pass copies or anti-aliases it onto the screen, under the
|
||||
//! hand and HUD. For a shader pack that reads them, `Post` also keeps:
|
||||
//! - `opaque_depth`: the depth before translucent terrain (water, stained
|
||||
//! glass, ice) draws, a Java pack's `depthtex1`/`depthtex2`;
|
||||
//! - `normal` and `material`, an api 2 pack's `scene_normal` and
|
||||
//! `scene_material`: surface normals and material properties
|
||||
//! reconstructed from depth and scene colour;
|
||||
//! - `shadow_depth`, an api 2 pack's: the sun/moon shadow map and its
|
||||
//! light-space `shadow_view` and `shadow_proj` matrices.
|
||||
//!
|
||||
//! With none of them on, the world renders straight to the screen as before.
|
||||
|
||||
use super::pack_stages::FrameUniform;
|
||||
use glam::{Mat4, Vec3};
|
||||
|
||||
const GBUFFER_WGSL: &str = r#"
|
||||
struct GbufferParams {
|
||||
inverse_view: mat4x4<f32>,
|
||||
inverse_projection: mat4x4<f32>,
|
||||
resolution: vec4<f32>,
|
||||
// x: eye block light (0..1), y: eye sky light (0..1), z: wetness (0..1), w: sun elevation
|
||||
env: vec4<f32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var world_color: texture_2d<f32>;
|
||||
@group(0) @binding(1) var world_depth: texture_depth_2d;
|
||||
@group(0) @binding(2) var opaque_depth: texture_depth_2d;
|
||||
@group(0) @binding(3) var nearest_sampler: sampler;
|
||||
@group(0) @binding(4) var<uniform> params: GbufferParams;
|
||||
|
||||
struct VsOut {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_gbuffer(@builtin(vertex_index) i: u32) -> VsOut {
|
||||
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
|
||||
var out: VsOut;
|
||||
out.clip = vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);
|
||||
out.uv = vec2<f32>(p.x, 1.0 - p.y);
|
||||
return out;
|
||||
}
|
||||
|
||||
struct GbufferOut {
|
||||
@location(0) normal: vec4<f32>,
|
||||
@location(1) material: vec4<f32>,
|
||||
}
|
||||
|
||||
fn world_pos(uv: vec2<f32>, d: f32) -> vec3<f32> {
|
||||
let v = params.inverse_projection * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0);
|
||||
let view = v.xyz / max(v.w, 1e-6);
|
||||
return (params.inverse_view * vec4<f32>(view, 1.0)).xyz;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_gbuffer(in: VsOut) -> GbufferOut {
|
||||
let d_all = textureSampleLevel(world_depth, nearest_sampler, in.uv, 0);
|
||||
let d_opq = textureSampleLevel(opaque_depth, nearest_sampler, in.uv, 0);
|
||||
let color = textureSampleLevel(world_color, nearest_sampler, in.uv, 0.0);
|
||||
var out: GbufferOut;
|
||||
if d_all <= 0.0 && d_opq <= 0.0 {
|
||||
out.normal = vec4<f32>(0.5, 1.0, 0.5, 0.0);
|
||||
out.material = vec4<f32>(0.0, params.env.y, 0.0, 1.0);
|
||||
return out;
|
||||
}
|
||||
let d = select(d_all, d_opq, d_opq > 0.0);
|
||||
let step_uv = params.resolution.zw;
|
||||
let p0 = world_pos(in.uv, d);
|
||||
let uv_r = clamp(in.uv + vec2<f32>(step_uv.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0));
|
||||
let uv_l = clamp(in.uv - vec2<f32>(step_uv.x, 0.0), vec2<f32>(0.0), vec2<f32>(1.0));
|
||||
let uv_d = clamp(in.uv + vec2<f32>(0.0, step_uv.y), vec2<f32>(0.0), vec2<f32>(1.0));
|
||||
let uv_u = clamp(in.uv - vec2<f32>(0.0, step_uv.y), vec2<f32>(0.0), vec2<f32>(1.0));
|
||||
let dr = textureSampleLevel(opaque_depth, nearest_sampler, uv_r, 0);
|
||||
let dl = textureSampleLevel(opaque_depth, nearest_sampler, uv_l, 0);
|
||||
let dd = textureSampleLevel(opaque_depth, nearest_sampler, uv_d, 0);
|
||||
let du = textureSampleLevel(opaque_depth, nearest_sampler, uv_u, 0);
|
||||
let dx = select(world_pos(uv_r, dr) - p0, p0 - world_pos(uv_l, dl), abs(dl - d) < abs(dr - d));
|
||||
let dy = select(world_pos(uv_d, dd) - p0, p0 - world_pos(uv_u, du), abs(du - d) < abs(dd - d));
|
||||
let raw_n = cross(dy, dx);
|
||||
let n_len = length(raw_n);
|
||||
let n = select(vec3<f32>(0.0, 1.0, 0.0), raw_n / max(n_len, 1e-6), n_len > 1e-6);
|
||||
// Reversed depth: closer translucent geometry has larger depth than opaque geometry.
|
||||
let is_translucent = select(0.0, 1.0, d_all > d_opq + 1e-5);
|
||||
let luma = dot(color.rgb, vec3<f32>(0.2126, 0.7152, 0.0722));
|
||||
let block_light = clamp(max(params.env.x, smoothstep(0.65, 0.98, luma)), 0.0, 1.0);
|
||||
let roughness = select(clamp(0.85 - params.env.z * 0.45, 0.1, 1.0), 0.05, is_translucent > 0.5);
|
||||
out.normal = vec4<f32>(n * 0.5 + 0.5, 1.0);
|
||||
out.material = vec4<f32>(block_light, params.env.y, is_translucent, roughness);
|
||||
return out;
|
||||
}
|
||||
"#;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct GbufferUniform {
|
||||
inverse_view: [[f32; 4]; 4],
|
||||
inverse_projection: [[f32; 4]; 4],
|
||||
resolution: [f32; 4],
|
||||
env: [f32; 4],
|
||||
}
|
||||
|
||||
/// What the frame's shader pack reads beyond the world's colour and depth:
|
||||
/// `Post` keeps these targets only while one does.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Extras {
|
||||
pub opaque_depth: bool,
|
||||
pub gbuffer: bool,
|
||||
}
|
||||
|
||||
struct WorldTarget {
|
||||
size: [u32; 2],
|
||||
extras: Extras,
|
||||
color: wgpu::TextureView,
|
||||
depth_tex: wgpu::Texture,
|
||||
depth: wgpu::TextureView,
|
||||
/// With `extras.opaque_depth` or `extras.gbuffer` (which reads it).
|
||||
opaque_depth: Option<(wgpu::Texture, wgpu::TextureView)>,
|
||||
gbuffer: Option<Gbuffer>,
|
||||
group: wgpu::BindGroup,
|
||||
opaque_captured: bool,
|
||||
}
|
||||
|
||||
struct Gbuffer {
|
||||
normal: wgpu::TextureView,
|
||||
material: wgpu::TextureView,
|
||||
group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
struct ShadowTarget {
|
||||
resolution: u32,
|
||||
depth: wgpu::TextureView,
|
||||
}
|
||||
|
||||
pub struct Post {
|
||||
layout: wgpu::BindGroupLayout,
|
||||
sampler: wgpu::Sampler,
|
||||
nearest: wgpu::Sampler,
|
||||
copy: wgpu::RenderPipeline,
|
||||
fxaa: wgpu::RenderPipeline,
|
||||
gbuffer_layout: wgpu::BindGroupLayout,
|
||||
gbuffer_pipeline: wgpu::RenderPipeline,
|
||||
gbuffer_uniform: wgpu::Buffer,
|
||||
format: wgpu::TextureFormat,
|
||||
/// World resolution relative to the window (0.5..=2.0).
|
||||
pub scale: f32,
|
||||
pub antialias: bool,
|
||||
target: Option<WorldTarget>,
|
||||
shadow: Option<ShadowTarget>,
|
||||
/// Bumped whenever a target is made: bindings of the old ones are stale.
|
||||
generation: u64,
|
||||
fallback_shadow: wgpu::TextureView,
|
||||
fallback_color: wgpu::TextureView,
|
||||
pub shadow_view: Mat4,
|
||||
pub shadow_proj: Mat4,
|
||||
pub shadow_distance: f32,
|
||||
pub shadow_resolution: u32,
|
||||
pub shadow_active: bool,
|
||||
}
|
||||
|
||||
impl Post {
|
||||
@@ -88,76 +225,482 @@ impl Post {
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
let nearest = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Horizon post nearest"),
|
||||
mag_filter: wgpu::FilterMode::Nearest,
|
||||
min_filter: wgpu::FilterMode::Nearest,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let gbuffer_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon gbuffer"),
|
||||
source: wgpu::ShaderSource::Wgsl(GBUFFER_WGSL.into()),
|
||||
});
|
||||
let gbuffer_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Horizon gbuffer layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Depth,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Depth,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let gbuffer_pipe_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Horizon gbuffer"),
|
||||
bind_group_layouts: &[Some(&gbuffer_layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let gbuffer_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Horizon gbuffer"),
|
||||
layout: Some(&gbuffer_pipe_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &gbuffer_shader,
|
||||
entry_point: Some("vs_gbuffer"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &gbuffer_shader,
|
||||
entry_point: Some("fs_gbuffer"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[
|
||||
Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
}),
|
||||
Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
}),
|
||||
],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let gbuffer_uniform = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Horizon gbuffer uniform"),
|
||||
size: std::mem::size_of::<GbufferUniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let fallback_shadow = device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Horizon fallback shadow"),
|
||||
size: wgpu::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default());
|
||||
let fallback_color = device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Horizon fallback gbuffer"),
|
||||
size: wgpu::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default());
|
||||
Self {
|
||||
copy: pipeline("fs_copy"),
|
||||
fxaa: pipeline("fs_fxaa"),
|
||||
layout,
|
||||
sampler,
|
||||
nearest,
|
||||
gbuffer_layout,
|
||||
gbuffer_pipeline,
|
||||
gbuffer_uniform,
|
||||
format,
|
||||
scale: 1.0,
|
||||
antialias: false,
|
||||
target: None,
|
||||
shadow: None,
|
||||
generation: 0,
|
||||
fallback_shadow,
|
||||
fallback_color,
|
||||
shadow_view: Mat4::IDENTITY,
|
||||
shadow_proj: Mat4::IDENTITY,
|
||||
shadow_distance: 128.0,
|
||||
shadow_resolution: 2048,
|
||||
shadow_active: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The world's colour and depth targets this frame, or `None` to draw
|
||||
/// it straight to the screen. `pack`: a shader pack runs this frame.
|
||||
/// it straight to the screen. `pack`: a shader pack runs this frame,
|
||||
/// reading `extras`.
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
window: [u32; 2],
|
||||
pack: bool,
|
||||
extras: Extras,
|
||||
) -> Option<(wgpu::TextureView, wgpu::TextureView)> {
|
||||
if self.scale == 1.0 && !self.antialias && !pack {
|
||||
self.target = None;
|
||||
self.shadow_active = false;
|
||||
return None;
|
||||
}
|
||||
let size = window.map(|v| ((v as f32 * self.scale).round() as u32).clamp(1, 8192));
|
||||
if self.target.as_ref().is_none_or(|t| t.size != size) {
|
||||
if self
|
||||
.target
|
||||
.as_ref()
|
||||
.is_none_or(|t| t.size != size || t.extras != extras)
|
||||
{
|
||||
self.generation += 1;
|
||||
let extent = wgpu::Extent3d {
|
||||
width: size[0],
|
||||
height: size[1],
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = |label, format, usage| {
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: extent,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
let make_tex = |label, format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: extent,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let color = texture(
|
||||
let color = make_tex(
|
||||
"Scaled world",
|
||||
self.format,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
);
|
||||
let depth = texture(
|
||||
)
|
||||
.create_view(&Default::default());
|
||||
let depth_tex = make_tex(
|
||||
"Scaled world depth",
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
let depth = depth_tex.create_view(&Default::default());
|
||||
let opaque_depth = (extras.opaque_depth || extras.gbuffer).then(|| {
|
||||
let tex = make_tex(
|
||||
"Opaque world depth",
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
);
|
||||
let view = tex.create_view(&Default::default());
|
||||
(tex, view)
|
||||
});
|
||||
let gbuffer = opaque_depth
|
||||
.as_ref()
|
||||
.filter(|_| extras.gbuffer)
|
||||
.map(|(_, opaque)| {
|
||||
let color_target = |label| {
|
||||
make_tex(
|
||||
label,
|
||||
wgpu::TextureFormat::Rgba8Unorm,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
)
|
||||
.create_view(&Default::default())
|
||||
};
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Horizon gbuffer"),
|
||||
layout: &self.gbuffer_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&color),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&depth),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::TextureView(opaque),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::Sampler(&self.nearest),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: self.gbuffer_uniform.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
Gbuffer {
|
||||
normal: color_target("World G-buffer normal"),
|
||||
material: color_target("World G-buffer material"),
|
||||
group,
|
||||
}
|
||||
});
|
||||
let group = self.bind(device, &color);
|
||||
self.target = Some(WorldTarget {
|
||||
size,
|
||||
extras,
|
||||
color,
|
||||
depth_tex,
|
||||
depth,
|
||||
opaque_depth,
|
||||
gbuffer,
|
||||
group,
|
||||
opaque_captured: false,
|
||||
});
|
||||
}
|
||||
if let Some(t) = &mut self.target {
|
||||
t.opaque_captured = false;
|
||||
}
|
||||
self.target
|
||||
.as_ref()
|
||||
.map(|t| (t.color.clone(), t.depth.clone()))
|
||||
}
|
||||
|
||||
/// Prepare the directional sun/moon shadow map target and compute its
|
||||
/// camera-relative orthographic `shadow_view` and `shadow_proj` matrices.
|
||||
pub fn prepare_shadow(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
resolution: u32,
|
||||
distance: f32,
|
||||
sun_dir: Vec3,
|
||||
moon_dir: Vec3,
|
||||
) -> &wgpu::TextureView {
|
||||
let resolution = resolution.clamp(256, 4096);
|
||||
let distance = distance.clamp(16.0, 512.0);
|
||||
if self
|
||||
.shadow
|
||||
.as_ref()
|
||||
.is_none_or(|s| s.resolution != resolution)
|
||||
{
|
||||
let depth = device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Horizon shadow map"),
|
||||
size: wgpu::Extent3d {
|
||||
width: resolution,
|
||||
height: resolution,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default());
|
||||
self.shadow = Some(ShadowTarget { resolution, depth });
|
||||
self.generation += 1;
|
||||
}
|
||||
let light_dir = if sun_dir.y >= -0.05 {
|
||||
sun_dir.normalize_or_zero()
|
||||
} else {
|
||||
moon_dir.normalize_or_zero()
|
||||
};
|
||||
let dir = if light_dir.length_squared() > 1e-4 {
|
||||
light_dir
|
||||
} else {
|
||||
Vec3::Y
|
||||
};
|
||||
let up = if dir.y.abs() > 0.99 { Vec3::Z } else { Vec3::Y };
|
||||
self.shadow_view = Mat4::look_at_rh(dir * distance, Vec3::ZERO, up);
|
||||
// Reversed-depth orthographic projection for the world's GreaterEqual
|
||||
// pipelines (near maps to 1.0, far maps to 0.0), and standard 0..1
|
||||
// projection for shader sampling.
|
||||
self.shadow_proj = Mat4::orthographic_rh(
|
||||
-distance,
|
||||
distance,
|
||||
-distance,
|
||||
distance,
|
||||
distance * 2.5,
|
||||
0.05,
|
||||
);
|
||||
self.shadow_distance = distance;
|
||||
self.shadow_resolution = resolution;
|
||||
self.shadow_active = true;
|
||||
&self.shadow.as_ref().expect("created above").depth
|
||||
}
|
||||
|
||||
/// Snapshot `world_depth` into `opaque_depth` (`depthtex1`/`depthtex2`)
|
||||
/// right before translucent water and weather draw.
|
||||
pub fn capture_opaque_depth(&mut self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let Some(t) = &mut self.target else { return };
|
||||
let Some((opaque, _)) = &t.opaque_depth else {
|
||||
return;
|
||||
};
|
||||
encoder.copy_texture_to_texture(
|
||||
t.depth_tex.as_image_copy(),
|
||||
opaque.as_image_copy(),
|
||||
t.depth_tex.size(),
|
||||
);
|
||||
t.opaque_captured = true;
|
||||
}
|
||||
|
||||
/// Reconstruct the G-buffer `normal` and `material` textures after the
|
||||
/// world pass finishes (with `Extras::gbuffer`).
|
||||
pub fn build_gbuffer(
|
||||
&mut self,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
frame: &FrameUniform,
|
||||
eye_light: [u8; 2],
|
||||
wetness: f32,
|
||||
) {
|
||||
if !self.target.as_ref().is_some_and(|t| t.opaque_captured) {
|
||||
self.capture_opaque_depth(encoder);
|
||||
}
|
||||
let Some(t) = &self.target else { return };
|
||||
let Some(gbuffer) = &t.gbuffer else { return };
|
||||
let [w, h] = t.size.map(|v| v.max(1) as f32);
|
||||
let uniform = GbufferUniform {
|
||||
inverse_view: frame.inverse_view,
|
||||
inverse_projection: frame.inverse_projection,
|
||||
resolution: [w, h, 1.0 / w, 1.0 / h],
|
||||
env: [
|
||||
f32::from(eye_light[0]) / 15.0,
|
||||
f32::from(eye_light[1]) / 15.0,
|
||||
wetness,
|
||||
frame.sun[1],
|
||||
],
|
||||
};
|
||||
queue.write_buffer(&self.gbuffer_uniform, 0, bytemuck::bytes_of(&uniform));
|
||||
let attachments = [
|
||||
Some(wgpu::RenderPassColorAttachment {
|
||||
view: &gbuffer.normal,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
}),
|
||||
Some(wgpu::RenderPassColorAttachment {
|
||||
view: &gbuffer.material,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
}),
|
||||
];
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon gbuffer"),
|
||||
color_attachments: &attachments,
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(&self.gbuffer_pipeline);
|
||||
pass.set_bind_group(0, &gbuffer.group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
/// The world target's size, once `prepare` made one.
|
||||
pub fn size(&self) -> Option<[u32; 2]> {
|
||||
self.target.as_ref().map(|t| t.size)
|
||||
}
|
||||
|
||||
/// Changes whenever `prepare` or `prepare_shadow` makes new targets:
|
||||
/// bindings made from the views below must be made again.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
|
||||
/// The depth before translucent geometry (`capture_opaque_depth`), or
|
||||
/// the world's depth when nothing reads it.
|
||||
pub fn opaque_depth(&self) -> &wgpu::TextureView {
|
||||
match &self.target {
|
||||
Some(WorldTarget {
|
||||
opaque_depth: Some((_, view)),
|
||||
..
|
||||
}) => view,
|
||||
Some(t) => &t.depth,
|
||||
None => &self.fallback_shadow,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconstructed world-space normals (`scene_normal`).
|
||||
pub fn normal(&self) -> &wgpu::TextureView {
|
||||
self.gbuffer().map_or(&self.fallback_color, |g| &g.normal)
|
||||
}
|
||||
|
||||
/// Reconstructed material and light (`scene_material`).
|
||||
pub fn material(&self) -> &wgpu::TextureView {
|
||||
self.gbuffer().map_or(&self.fallback_color, |g| &g.material)
|
||||
}
|
||||
|
||||
fn gbuffer(&self) -> Option<&Gbuffer> {
|
||||
self.target.as_ref()?.gbuffer.as_ref()
|
||||
}
|
||||
|
||||
/// The sun/moon shadow map (`shadow_depth` of api 2 packs).
|
||||
pub fn shadow_depth(&self) -> &wgpu::TextureView {
|
||||
self.shadow
|
||||
.as_ref()
|
||||
.map_or(&self.fallback_shadow, |s| &s.depth)
|
||||
}
|
||||
|
||||
/// Bindings that copy (or anti-alias) `view` onto the screen in `finish_with`.
|
||||
pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> wgpu::BindGroup {
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
@@ -175,11 +718,13 @@ impl Post {
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
/// Draw the scaled world onto `screen`.
|
||||
pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) {
|
||||
let Some(target) = &self.target else { return };
|
||||
self.finish_with(encoder, screen, &target.group);
|
||||
}
|
||||
|
||||
/// Draw what `group` binds (`bind`) onto `screen`.
|
||||
pub fn finish_with(
|
||||
&self,
|
||||
|
||||
@@ -7,7 +7,6 @@ use std::collections::BTreeMap;
|
||||
|
||||
/// `ReputationEventType` amounts.
|
||||
pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25;
|
||||
pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20;
|
||||
pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2;
|
||||
/// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten.
|
||||
const DISCARD_THRESHOLD: i32 = 2;
|
||||
|
||||
@@ -112,13 +112,18 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
"Waits for the display's refresh: no tearing, a little latency.",
|
||||
);
|
||||
let gui = v(Opt::GuiScale, None, "Size of menus and the HUD.");
|
||||
let shader_pack = h(
|
||||
H::ShaderPack,
|
||||
High,
|
||||
"Redraws the world with a pack from the shaderpacks folder. Off is vanilla.",
|
||||
);
|
||||
let preset = h(
|
||||
H::Preset,
|
||||
None,
|
||||
"Sets the options below together. Changing one makes it Custom.",
|
||||
);
|
||||
let mut rows = match level {
|
||||
Level::Simple => vec![preset, render, lod, far, fov, fps, vsync, gui],
|
||||
Level::Simple => vec![preset, render, lod, far, fov, fps, vsync, gui, shader_pack],
|
||||
Level::Advanced => vec![
|
||||
Row::Header("Rendering"),
|
||||
render,
|
||||
@@ -246,11 +251,7 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
None,
|
||||
"Lowers the frame rate when minimised, or idle too.",
|
||||
),
|
||||
h(
|
||||
H::ShaderPack,
|
||||
High,
|
||||
"Redraws the world with a pack from the shaderpacks folder. Off is vanilla.",
|
||||
),
|
||||
shader_pack,
|
||||
Row::Header("Preferences"),
|
||||
v(Opt::ViewBobbing, None, "Sways the view while walking."),
|
||||
v(Opt::ChunkFade, None, "Fades newly loaded chunks in."),
|
||||
@@ -485,14 +486,6 @@ impl Item {
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// Caption and value text, split from the label ("Caption: Value").
|
||||
pub fn caption_value(self, s: &Settings) -> (String, String) {
|
||||
let label = self.label(s).plain();
|
||||
match label.split_once(": ") {
|
||||
Some((c, v)) => (c.to_owned(), v.to_owned()),
|
||||
None => (label, String::new()),
|
||||
}
|
||||
}
|
||||
pub fn slider(self, s: &Settings) -> Option<f32> {
|
||||
match self {
|
||||
Item::Vanilla(o) => o.slider_position(s),
|
||||
|
||||
@@ -9,6 +9,11 @@ use std::{
|
||||
};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// A sprite's atlas region, and its size in GUI pixels: the size of the
|
||||
/// default resources' texture of that name, whatever the resolution of the
|
||||
/// pack that replaced it (vanilla's GUI code draws in those units: `blit`
|
||||
/// divides by the texture size it is given, sprites by their `gui.scaling`
|
||||
/// size). Textures the default resources lack keep their own size.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Rect {
|
||||
pub u0: f32,
|
||||
@@ -18,6 +23,15 @@ pub struct Rect {
|
||||
pub w: u32,
|
||||
pub h: u32,
|
||||
}
|
||||
impl Rect {
|
||||
/// The region's size in texels of an atlas this large.
|
||||
pub fn texels(&self, (width, height): (u32, u32)) -> (u32, u32) {
|
||||
(
|
||||
((self.u1 - self.u0) * width as f32).round() as u32,
|
||||
((self.v1 - self.v0) * height as f32).round() as u32,
|
||||
)
|
||||
}
|
||||
}
|
||||
/// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a
|
||||
/// standalone texture (`ReloadableTexture.setSampler`: linear rather than
|
||||
/// nearest filtering, clamp-to-edge rather than repeat addressing).
|
||||
@@ -54,6 +68,9 @@ pub struct HudAtlas {
|
||||
}
|
||||
/// Atlas rows reserved for glyphs rasterized at run time.
|
||||
pub const GLYPH_ROWS: u32 = 512;
|
||||
/// The largest atlas side: the 2D texture limit of the GPUs Horizon runs on
|
||||
/// (Apple silicon, RADV and Intel allow 16384; NVIDIA 32768).
|
||||
pub const MAX_ATLAS_SIZE: u32 = 16384;
|
||||
/// 128x128 atlas slots for map textures. A lobby paints its signs as walls of
|
||||
/// framed maps, so the pool holds a wall; too few slots re-upload every map
|
||||
/// every frame. 26.3's `MapTextureManager` keeps a texture per map instead.
|
||||
@@ -89,6 +106,15 @@ pub fn decode_bytes(data: &[u8]) -> Result<(u32, u32, Vec<u8>)> {
|
||||
}
|
||||
Ok((info.width, info.height, rgba))
|
||||
}
|
||||
/// A PNG's width and height, from its header alone.
|
||||
fn png_size(path: &Path) -> Option<(u32, u32)> {
|
||||
use std::io::Read;
|
||||
let mut header = [0u8; 24];
|
||||
fs::File::open(path).ok()?.read_exact(&mut header).ok()?;
|
||||
let field = |at: usize| u32::from_be_bytes(header[at..at + 4].try_into().unwrap_or_default());
|
||||
(header[..8] == *b"\x89PNG\r\n\x1a\n" && header[12..16] == *b"IHDR")
|
||||
.then(|| (field(16), field(20)))
|
||||
}
|
||||
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return;
|
||||
@@ -201,8 +227,14 @@ impl HudAtlas {
|
||||
(g.rect, g.advance)
|
||||
}
|
||||
pub fn build(root: &Path) -> Result<Self> {
|
||||
Self::build_over(root, root)
|
||||
}
|
||||
/// The atlas of a resource root that layers packs over `defaults` (the
|
||||
/// game's own resources), whose textures give the sprites' GUI sizes.
|
||||
pub fn build_over(root: &Path, defaults: &Path) -> Result<Self> {
|
||||
Self::pack(
|
||||
root,
|
||||
defaults,
|
||||
&[
|
||||
"gui",
|
||||
"item",
|
||||
@@ -265,14 +297,53 @@ impl HudAtlas {
|
||||
/// holding its textures. The pixels are dropped once the glyph widths are
|
||||
/// read, since nothing uploads them.
|
||||
pub fn fonts(root: &Path) -> Result<Self> {
|
||||
let mut atlas = Self::pack(root, &["font"], false)?;
|
||||
let mut atlas = Self::pack(root, root, &["font"], false)?;
|
||||
atlas.pixels = Vec::new();
|
||||
Ok(atlas)
|
||||
}
|
||||
/// Shelf placements of `images` (tallest first) in the narrowest atlas
|
||||
/// width from 4096 up that keeps the atlas, glyph rows included, within
|
||||
/// `max` texels a side; and the first row free for glyphs. High-resolution
|
||||
/// packs fill a 4096-wide atlas past what GPUs allow (Faithful 64x needs
|
||||
/// 32768 rows); vanilla's stitcher fails the reload when its atlases don't
|
||||
/// fit, and the packs are then turned off (`Minecraft.clearResourcePacksOnError`).
|
||||
fn layout(images: &[PackedImage], max: u32) -> Result<(u32, Vec<(u32, u32)>, u32)> {
|
||||
let mut width = 4096.min(max);
|
||||
loop {
|
||||
let mut placements = Vec::with_capacity(images.len());
|
||||
let (mut x, mut y, mut row) = (0u32, 0u32, 0u32);
|
||||
for (_, w, h, _) in images {
|
||||
if x + w + 1 > width {
|
||||
x = 0;
|
||||
y += row + 1;
|
||||
row = 0;
|
||||
}
|
||||
placements.push((x, y));
|
||||
x += w + 1;
|
||||
row = row.max(*h);
|
||||
}
|
||||
let glyph_region = y + row + 1;
|
||||
let wide_enough = images.iter().all(|i| i.1 < width);
|
||||
if wide_enough && glyph_region + GLYPH_ROWS <= max {
|
||||
return Ok((width, placements, glyph_region));
|
||||
}
|
||||
if width >= max {
|
||||
let texels: u64 = images.iter().map(|i| u64::from(i.1) * u64::from(i.2)).sum();
|
||||
return Err(format!(
|
||||
"the textures ({} images, {texels} texels) do not fit a {max}x{max} atlas",
|
||||
images.len()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
width = (width * 2).min(max);
|
||||
}
|
||||
}
|
||||
/// Pack the textures under these folders of `textures/`, and for the
|
||||
/// `full` atlas the generated sprites and the run-time slots too.
|
||||
fn pack(root: &Path, folders: &[&str], full: bool) -> Result<Self> {
|
||||
fn pack(root: &Path, defaults: &Path, folders: &[&str], full: bool) -> Result<Self> {
|
||||
let textures = root.join("assets/minecraft/textures");
|
||||
let default_textures =
|
||||
(defaults != root).then(|| defaults.join("assets/minecraft/textures"));
|
||||
let mut files = Vec::new();
|
||||
for folder in folders {
|
||||
walk(&textures.join(folder), &mut files);
|
||||
@@ -281,7 +352,8 @@ impl HudAtlas {
|
||||
let s = p.to_string_lossy();
|
||||
!s.contains("title/background") && !s.contains("realms") && !s.contains("presets")
|
||||
});
|
||||
let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option<TextureFlags>)> {
|
||||
type Decoded = (PackedImage, Option<TextureFlags>, Option<(u32, u32)>);
|
||||
let decode_one = |path: &PathBuf| -> Option<Decoded> {
|
||||
let name = path
|
||||
.strip_prefix(&textures)
|
||||
.ok()?
|
||||
@@ -289,18 +361,29 @@ impl HudAtlas {
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
let (w, mut h, pixels) = decode(path).ok()?;
|
||||
let is_frame_strip = (name.starts_with("block/") || name.starts_with("item/")) && h > w;
|
||||
let pixels = if is_frame_strip {
|
||||
// Animated strips keep their first frame.
|
||||
let frames = name.starts_with("block/") || name.starts_with("item/");
|
||||
let pixels = if frames && h > w {
|
||||
h = w;
|
||||
pixels[..(w * w * 4) as usize].to_vec()
|
||||
} else {
|
||||
pixels
|
||||
};
|
||||
// The default texture's size, when a pack's differs from it.
|
||||
let gui_size = default_textures
|
||||
.as_ref()
|
||||
.and_then(|d| png_size(&d.join(format!("{name}.png"))))
|
||||
.map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh }))
|
||||
.filter(|&size| size != (w, h));
|
||||
let flags = fs::read_to_string(path.with_extension("png.mcmeta"))
|
||||
.ok()
|
||||
.and_then(|json| TextureFlags::from_mcmeta(&json));
|
||||
(w <= 1024 && (h <= 512 || name.starts_with("font/")))
|
||||
.then_some(((name, w, h, pixels), flags))
|
||||
let (gw, gh) = gui_size.unwrap_or((w, h));
|
||||
(gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some((
|
||||
(name, w, h, pixels),
|
||||
flags,
|
||||
gui_size,
|
||||
))
|
||||
};
|
||||
let threads = std::thread::available_parallelism().map_or(2, |n| n.get());
|
||||
let chunk = files.len().div_ceil(threads).max(1);
|
||||
@@ -317,11 +400,15 @@ impl HudAtlas {
|
||||
.collect()
|
||||
});
|
||||
let mut flags = HashMap::new();
|
||||
let mut gui_sizes = HashMap::new();
|
||||
let mut images: Vec<PackedImage> = Vec::with_capacity(decoded.len());
|
||||
for (image, image_flags) in decoded {
|
||||
for (image, image_flags, gui_size) in decoded {
|
||||
if let Some(f) = image_flags {
|
||||
flags.insert(image.0.clone(), f);
|
||||
}
|
||||
if let Some(size) = gui_size {
|
||||
gui_sizes.insert(image.0.clone(), size);
|
||||
}
|
||||
images.push(image);
|
||||
}
|
||||
if full {
|
||||
@@ -351,21 +438,10 @@ impl HudAtlas {
|
||||
}
|
||||
}
|
||||
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
|
||||
let width = 4096u32;
|
||||
let mut placements = Vec::with_capacity(images.len());
|
||||
let (mut x, mut y, mut row) = (0u32, 0u32, 0u32);
|
||||
for (_, w, h, _) in &images {
|
||||
if x + w + 1 > width {
|
||||
x = 0;
|
||||
y += row + 1;
|
||||
row = 0;
|
||||
}
|
||||
placements.push((x, y));
|
||||
x += w + 1;
|
||||
row = row.max(*h);
|
||||
}
|
||||
let glyph_region = y + row + 1;
|
||||
let height = (glyph_region + GLYPH_ROWS).next_power_of_two();
|
||||
let (width, placements, glyph_region) = Self::layout(&images, MAX_ATLAS_SIZE)?;
|
||||
// A multiple of 1024 rather than a power of two: the default resources
|
||||
// need 4096x5120 (8192 rows before), Faithful 32x 4096x12288 (16384).
|
||||
let height = (glyph_region + GLYPH_ROWS).next_multiple_of(1024);
|
||||
let mut pixels = vec![0u8; (width * height * 4) as usize];
|
||||
let mut sprites = HashMap::new();
|
||||
for ((name, w, h, data), (px, py)) in images.iter().zip(placements) {
|
||||
@@ -376,6 +452,7 @@ impl HudAtlas {
|
||||
}
|
||||
let b = u32::from(bordered.contains(name));
|
||||
let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b);
|
||||
let (gw, gh) = gui_sizes.get(name).copied().unwrap_or((w, h));
|
||||
sprites.insert(
|
||||
name.clone(),
|
||||
Rect {
|
||||
@@ -383,8 +460,8 @@ impl HudAtlas {
|
||||
v0: py as f32 / height as f32,
|
||||
u1: (px + w) as f32 / width as f32,
|
||||
v1: (py + h) as f32 / height as f32,
|
||||
w,
|
||||
h,
|
||||
w: gw,
|
||||
h: gh,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -404,14 +481,15 @@ impl HudAtlas {
|
||||
.find(|a| a.layer == layer)
|
||||
.cloned()
|
||||
{
|
||||
let image = animation.resized_pixels(animation.frame(0), rect.w, rect.h);
|
||||
let (tw, th) = rect.texels((width, height));
|
||||
let image = animation.resized_pixels(animation.frame(0), tw, th);
|
||||
let x = (rect.u0 * width as f32).round() as usize;
|
||||
let y = (rect.v0 * height as f32).round() as usize;
|
||||
for row in 0..rect.h as usize {
|
||||
let row_bytes = tw as usize * 4;
|
||||
for row in 0..th as usize {
|
||||
let dst = ((y + row) * width as usize + x) * 4;
|
||||
let src = row * rect.w as usize * 4;
|
||||
pixels[dst..dst + rect.w as usize * 4]
|
||||
.copy_from_slice(&image[src..src + rect.w as usize * 4]);
|
||||
let src = row * row_bytes;
|
||||
pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]);
|
||||
}
|
||||
fire_animations.push((rect, animation));
|
||||
}
|
||||
@@ -783,24 +861,6 @@ impl HudBatch {
|
||||
};
|
||||
self.text_styled(atlas, &t, x, y, color, shadow)
|
||||
}
|
||||
/// `text_styled` under a pose: GUI positions scaled by `scale`, then
|
||||
/// moved to `origin` (Matrix3x2fStack translate + scale).
|
||||
pub fn text_posed(
|
||||
&mut self,
|
||||
atlas: &HudAtlas,
|
||||
text: &crate::text::Text,
|
||||
at: [f32; 2],
|
||||
color: u32,
|
||||
scale: f32,
|
||||
origin: [f32; 2],
|
||||
) -> f32 {
|
||||
let start = self.vertices.len();
|
||||
let advance = self.text_styled(atlas, text, at[0], at[1], color, true);
|
||||
for v in &mut self.vertices[start..] {
|
||||
v.pos = [origin[0] + v.pos[0] * scale, origin[1] + v.pos[1] * scale];
|
||||
}
|
||||
advance
|
||||
}
|
||||
/// Font.drawInternal: styled glyphs, shadows first, with bold, italic,
|
||||
/// underline and strikethrough. `color` is the default colour and alpha.
|
||||
pub fn text_styled(
|
||||
@@ -1162,7 +1222,8 @@ impl HudRenderer {
|
||||
if frame == *previous {
|
||||
continue;
|
||||
}
|
||||
let pixels = animation.resized_pixels(frame, rect.w, rect.h);
|
||||
let (w, h) = rect.texels((texture.width(), texture.height()));
|
||||
let pixels = animation.resized_pixels(frame, w, h);
|
||||
uploads.texture(
|
||||
encoder,
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
@@ -1175,8 +1236,8 @@ impl HudRenderer {
|
||||
},
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
rect.w,
|
||||
rect.h,
|
||||
w,
|
||||
h,
|
||||
&pixels,
|
||||
);
|
||||
*previous = frame;
|
||||
@@ -1340,6 +1401,87 @@ impl HudRenderer {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `count` images of `w x h`; layout reads only their sizes.
|
||||
fn sized(count: usize, w: u32, h: u32) -> Vec<PackedImage> {
|
||||
(0..count)
|
||||
.map(|i| (format!("i{i}"), w, h, Vec::new()))
|
||||
.collect()
|
||||
}
|
||||
fn assert_inside(images: &[PackedImage], width: u32, placements: &[(u32, u32)], free: u32) {
|
||||
for ((_, w, h, _), (x, y)) in images.iter().zip(placements) {
|
||||
assert!(
|
||||
x + w <= width && y + h < free,
|
||||
"{x},{y} {w}x{h} outside {width}x{free}"
|
||||
);
|
||||
}
|
||||
}
|
||||
fn write_png(root: &Path, name: &str, w: u32, h: u32) {
|
||||
let path = root.join(format!("assets/minecraft/textures/{name}.png"));
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let mut encoder = png::Encoder::new(fs::File::create(path).unwrap(), w, h);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let pixels = vec![255; (w * h * 4) as usize];
|
||||
encoder
|
||||
.write_header()
|
||||
.unwrap()
|
||||
.write_image_data(&pixels)
|
||||
.unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn a_pack_texture_keeps_the_default_textures_gui_size() {
|
||||
let temp = std::env::temp_dir().join(format!("horizon-gui-size-{}", std::process::id()));
|
||||
let (defaults, pack) = (temp.join("defaults"), temp.join("pack"));
|
||||
write_png(&defaults, "gui/container/inventory", 256, 256);
|
||||
write_png(&defaults, "gui/sprites/widget/button", 200, 20);
|
||||
write_png(&defaults, "block/stone", 16, 16);
|
||||
write_png(&defaults, "item/compass", 16, 512);
|
||||
// Faithful 64x's inventory (past the 512 rows a texture may have),
|
||||
// 32x's button and stone, an animated strip, and a texture of its own.
|
||||
write_png(&pack, "gui/container/inventory", 1024, 1024);
|
||||
write_png(&pack, "gui/sprites/widget/button", 400, 40);
|
||||
write_png(&pack, "block/stone", 32, 32);
|
||||
write_png(&pack, "item/compass", 32, 1024);
|
||||
write_png(&pack, "gui/sprites/pack_only", 30, 10);
|
||||
let atlas = HudAtlas::build_over(&pack, &defaults).unwrap();
|
||||
let _ = fs::remove_dir_all(&temp);
|
||||
let size = (atlas.width, atlas.height);
|
||||
for (name, gui, texels) in [
|
||||
("gui/container/inventory", (256, 256), (1024, 1024)),
|
||||
("gui/sprites/widget/button", (200, 20), (400, 40)),
|
||||
("block/stone", (16, 16), (32, 32)),
|
||||
("item/compass", (16, 16), (32, 32)),
|
||||
("gui/sprites/pack_only", (30, 10), (30, 10)),
|
||||
] {
|
||||
let r = atlas.sprites[name];
|
||||
assert_eq!(((r.w, r.h), r.texels(size)), (gui, texels), "{name}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn the_default_textures_keep_a_4096_wide_atlas() {
|
||||
let images = sized(400, 64, 64);
|
||||
let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap();
|
||||
assert_eq!(width, 4096);
|
||||
assert_inside(&images, width, &placements, free);
|
||||
}
|
||||
#[test]
|
||||
fn a_high_resolution_pack_widens_the_atlas_to_fit_the_gpu() {
|
||||
// 34 rows of three 1024x512 GUI textures: 17442 rows at 4096 wide,
|
||||
// past the 16384 GPUs allow (Faithful 64x needed 32768).
|
||||
let images = sized(100, 1024, 512);
|
||||
let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap();
|
||||
assert_eq!(width, 8192);
|
||||
assert!(free + GLYPH_ROWS <= MAX_ATLAS_SIZE);
|
||||
assert_inside(&images, width, &placements, free);
|
||||
}
|
||||
#[test]
|
||||
fn textures_that_cannot_fit_are_an_error_not_a_gpu_panic() {
|
||||
let error = HudAtlas::layout(&sized(300, 1024, 1024), MAX_ATLAS_SIZE).unwrap_err();
|
||||
assert!(error.to_string().contains("do not fit a 16384x16384 atlas"));
|
||||
// One image wider than the largest atlas.
|
||||
assert!(HudAtlas::layout(&sized(1, 2048, 16), 2048).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_border_repeats_the_opposite_edges() {
|
||||
// 2x2 texels a b / c d, one byte each in red.
|
||||
|
||||
@@ -124,17 +124,6 @@ impl ItemRenderState {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.layers.is_empty()
|
||||
}
|
||||
/// `pickParticleMaterial`: a random layer's particle sprite.
|
||||
pub fn pick_particle(
|
||||
&self,
|
||||
random: &mut impl horizon_core::random::RandomSource,
|
||||
) -> Option<String> {
|
||||
if self.layers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize;
|
||||
self.layers.get(i).map(|l| l.particle.clone())
|
||||
}
|
||||
/// `usesBlockLight` of the first layer (GUI lighting choice).
|
||||
pub fn uses_block_light(&self) -> bool {
|
||||
self.layers.first().is_some_and(|l| l.uses_block_light)
|
||||
|
||||
@@ -23,17 +23,36 @@ pub struct JavaFolder {
|
||||
/// `begin*`, `prepare*`, `deferred*`, `composite*`, in order.
|
||||
pub passes: Vec<Program>,
|
||||
/// How many of `passes` run before the world (`begin*`, `prepare*`): the
|
||||
/// world's colour and depth enter `colortex0` and `depthtex*` after them.
|
||||
/// world's colour and depth enter `world_target` and `depthtex*` after them.
|
||||
pub world_at: usize,
|
||||
/// The colour target the world goes into, where the pack's terrain
|
||||
/// program draws (MakeUp: colortex1).
|
||||
pub world_target: u32,
|
||||
/// The targets whose alternate side the world is written to.
|
||||
pub flipped_after_prepare: BTreeSet<u32>,
|
||||
pub final_pass: Option<Program>,
|
||||
/// The targets whose alternate side holds the frame's last write.
|
||||
pub flipped_at_end: BTreeSet<u32>,
|
||||
/// `sunPathRotation` and `eyeBrightnessHalflife`.
|
||||
/// `sunPathRotation`, `eyeBrightnessHalflife`, `wetnessHalflife` and
|
||||
/// `drynessHalflife`.
|
||||
pub directives: Directives,
|
||||
}
|
||||
|
||||
/// The key of `texture.noise` (`noisetex`) in [`JavaPasses::custom_textures`].
|
||||
pub const NOISE_KEY: &str = "noise";
|
||||
|
||||
/// The key of `texture.<stage>.<sampler>` in [`JavaPasses::custom_textures`]
|
||||
/// for a pass of `program` (`world0/composite2`): Iris's texture stages, where
|
||||
/// `final` reads the `composite` ones.
|
||||
pub fn texture_key(program: &str, sampler: &str) -> String {
|
||||
let name = program.rsplit('/').next().unwrap_or(program);
|
||||
let stage = match name.trim_end_matches(|c: char| c.is_ascii_digit()) {
|
||||
"final" => "composite",
|
||||
stage => stage,
|
||||
};
|
||||
format!("{stage}.{sampler}")
|
||||
}
|
||||
|
||||
/// A loaded Java pack.
|
||||
pub struct JavaPasses {
|
||||
pub folders: Vec<JavaFolder>,
|
||||
@@ -41,6 +60,9 @@ pub struct JavaPasses {
|
||||
pub uniforms: CustomUniforms,
|
||||
/// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`).
|
||||
pub sky: SkyDirectives,
|
||||
/// `texture.<stage>.<sampler>` and `texture.noise` images, by
|
||||
/// `"<stage>.<sampler>"` and [`NOISE_KEY`].
|
||||
pub custom_textures: BTreeMap<String, crate::shader_pack::Rgba>,
|
||||
}
|
||||
|
||||
impl JavaPasses {
|
||||
@@ -126,6 +148,7 @@ pub fn load(
|
||||
folder: name.to_owned(),
|
||||
targets: plan.targets,
|
||||
world_at: early.count(),
|
||||
world_target: plan.world_target,
|
||||
passes,
|
||||
flipped_after_prepare: plan.flipped_after_prepare,
|
||||
final_pass,
|
||||
@@ -136,6 +159,27 @@ pub fn load(
|
||||
if folders.is_empty() {
|
||||
return Err("no deferred, composite or final programs".into());
|
||||
}
|
||||
let mut custom_textures = BTreeMap::new();
|
||||
for tex in properties.custom_textures() {
|
||||
let key = match tex.stage {
|
||||
Some(stage) => format!("{stage}.{}", tex.sampler),
|
||||
None if tex.sampler == NOISE_KEY => NOISE_KEY.to_owned(),
|
||||
None => continue,
|
||||
};
|
||||
// Only PNGs for now: resource locations and raw `.dat` textures are
|
||||
// skipped and the sampler reads what it would without them.
|
||||
let image = pack
|
||||
.files
|
||||
.read_bytes(&tex.path)
|
||||
.ok_or_else(|| "not in the pack".to_owned())
|
||||
.and_then(|bytes| crate::shader_pack::decode_png(&bytes));
|
||||
match image {
|
||||
Ok(image) => {
|
||||
custom_textures.insert(key, image);
|
||||
}
|
||||
Err(e) => log::warn!("Horizon: shader pack texture {}: {e}", tex.path),
|
||||
}
|
||||
}
|
||||
let uniforms = properties.custom_uniforms();
|
||||
for problem in &uniforms.problems {
|
||||
log::warn!("Horizon: shader pack custom uniform {problem}");
|
||||
@@ -144,6 +188,7 @@ pub fn load(
|
||||
folders,
|
||||
uniforms,
|
||||
sky: properties.sky(),
|
||||
custom_textures,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -151,6 +196,17 @@ pub fn load(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn custom_textures_belong_to_iris_s_stages() {
|
||||
assert_eq!(texture_key("world0/composite2", "gaux1"), "composite.gaux1");
|
||||
assert_eq!(texture_key("final", "colortex4"), "composite.colortex4");
|
||||
assert_eq!(
|
||||
texture_key("world-1/deferred10", "noisetex"),
|
||||
"deferred.noisetex"
|
||||
);
|
||||
assert_eq!(texture_key("prepare", "depthtex2"), "prepare.depthtex2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_the_full_screen_passes_of_a_java_pack() {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
|
||||
@@ -295,15 +295,6 @@ impl KeyBinds {
|
||||
self.keys.insert(n, key.to_owned());
|
||||
}
|
||||
}
|
||||
/// Load `key_<name>` from options.txt; false for unknown mappings.
|
||||
pub fn set_saved(&mut self, name: &str, key: &str) -> bool {
|
||||
if MAPPINGS.iter().any(|m| m.0 == name) {
|
||||
self.set(name, key);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
pub fn saved(&self) -> Vec<(&'static str, String)> {
|
||||
MAPPINGS
|
||||
.iter()
|
||||
|
||||
@@ -104,8 +104,6 @@ pub const SNEAK: usize = 0;
|
||||
pub const SPRINT: usize = 1;
|
||||
/// Attack (mouse).
|
||||
pub const ATTACK: usize = 2;
|
||||
/// Use (mouse).
|
||||
pub const USE: usize = 3;
|
||||
|
||||
/// The `ToggleKeyMapping`s `Options` builds: sneak and sprint (keyboard,
|
||||
/// restored after a screen), attack (mouse, restored) and use (mouse, not
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! changed since (`getAttributesToSync`), to the trackers and the player itself.
|
||||
use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot};
|
||||
use horizon_world::attributes::{
|
||||
Instance, Operation,
|
||||
Instance, Modifier, Operation,
|
||||
entity::{AttributeId, EntityAttributes},
|
||||
live::LiveAttributes,
|
||||
};
|
||||
@@ -70,6 +70,48 @@ pub fn take_dirty<G: FnMut() -> i32>(map: &mut LiveAttributes<G>) -> Vec<Attribu
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `ClientPacketListener.handleUpdateAttributes`: each instance the server
|
||||
/// synced takes its base and exactly its modifiers (`removeModifiers`, then
|
||||
/// `addTransientModifier` for each). An attribute the map doesn't know is
|
||||
/// skipped, as vanilla warns and skips it.
|
||||
pub fn apply<G: FnMut() -> i32>(map: &mut LiveAttributes<G>, values: &[AttributeSnapshot]) {
|
||||
for s in values {
|
||||
let Some(key) = map
|
||||
.keys()
|
||||
.iter()
|
||||
.find(|k| k.attribute().registry_id() == s.attribute)
|
||||
.cloned()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(Some(handle)) = map.get_instance(Some(key)) else {
|
||||
continue;
|
||||
};
|
||||
let modifiers: Vec<_> = s
|
||||
.modifiers
|
||||
.iter()
|
||||
.filter_map(|m| Modifier::new(&m.id, m.amount, operation(m.operation)).ok())
|
||||
.collect();
|
||||
let _ = map.edit(&handle, |instance, observer| {
|
||||
instance.set_base_value(s.base, observer)?;
|
||||
instance.remove_all(observer)?;
|
||||
for m in modifiers {
|
||||
instance.add_transient(m, observer)?;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `AttributeModifier.Operation.BY_ID`.
|
||||
fn operation(id: i32) -> Operation {
|
||||
match id {
|
||||
1 => Operation::AddMultipliedBase,
|
||||
2 => Operation::AddMultipliedTotal,
|
||||
_ => Operation::AddValue,
|
||||
}
|
||||
}
|
||||
|
||||
/// The client-syncable instances of a generic attribute map.
|
||||
pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator<Item = AttributeSnapshot> + '_ {
|
||||
let catalog = map.catalog();
|
||||
|
||||
@@ -12,8 +12,8 @@ use horizon_protocol::{
|
||||
item::Stack,
|
||||
packets::play::{
|
||||
self, AddEntity, AttributeSnapshot, EntityPositionSync, MoveEntity, MoveEntityPos,
|
||||
MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion,
|
||||
SetEquipment, SetPassengers, UpdateAttributes, VecDelta,
|
||||
MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityLink,
|
||||
SetEntityMotion, SetEquipment, SetPassengers, UpdateAttributes, VecDelta,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -50,6 +50,10 @@ pub struct EntityState {
|
||||
pub data: i32,
|
||||
/// SynchedEntityData entries that differ from the defaults.
|
||||
pub meta: Vec<(u8, i32, Value)>,
|
||||
/// The defaults of entries `meta` leaves out while they are at them,
|
||||
/// sent when one goes back to its default (a calf grown up, a mob healed
|
||||
/// back to 1, wool grown back white) beyond Entity's own below.
|
||||
pub defaults: Vec<(u8, i32, Value)>,
|
||||
/// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs,
|
||||
/// 4 chest, 5 head, 6 body, 7 saddle) and their stacks.
|
||||
pub equipment: Vec<(u8, Option<Stack>)>,
|
||||
@@ -61,6 +65,8 @@ pub struct EntityState {
|
||||
pub precise: bool,
|
||||
/// `Entity.needsSync`: send its changes this tick, due or not.
|
||||
pub needs_sync: bool,
|
||||
/// `Leashable.getLeashHolder`: the entity holding its lead.
|
||||
pub leash: Option<i32>,
|
||||
}
|
||||
|
||||
impl EntityState {
|
||||
@@ -78,10 +84,12 @@ impl EntityState {
|
||||
self.velocity = [0.0; 3];
|
||||
self.data = 0;
|
||||
self.meta.clear();
|
||||
self.defaults.clear();
|
||||
self.equipment.clear();
|
||||
self.attributes.clear();
|
||||
self.precise = false;
|
||||
self.needs_sync = false;
|
||||
self.leash = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +222,8 @@ struct ServerEntity {
|
||||
/// and the first update after it dismounts is a full position sync.
|
||||
passengers: Vec<i32>,
|
||||
was_riding: bool,
|
||||
/// The lead's holder the clients were told of.
|
||||
leash: Option<i32>,
|
||||
/// The level tick it was last seen in, its place in that tick's list, and
|
||||
/// whether it was added in it (its first update is the next tick's).
|
||||
seen: u32,
|
||||
@@ -257,6 +267,7 @@ impl ServerEntity {
|
||||
teleport_delay: 0,
|
||||
passengers: riding.passengers(e.id).to_vec(),
|
||||
was_riding: false,
|
||||
leash: e.leash,
|
||||
seen: 0,
|
||||
index: 0,
|
||||
added: true,
|
||||
@@ -309,6 +320,13 @@ impl ServerEntity {
|
||||
if let Some(&vehicle) = riding.vehicle.get(&e.id) {
|
||||
out.push(riding.set_passengers(vehicle));
|
||||
}
|
||||
// A leashed entity: who holds its lead.
|
||||
if let Some(dest) = e.leash {
|
||||
out.push(play::Clientbound::SetEntityLink(SetEntityLink {
|
||||
source: e.id,
|
||||
dest,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes since the last update (ServerEntity.sendChanges): movement and
|
||||
@@ -322,6 +340,14 @@ impl ServerEntity {
|
||||
self.passengers.clear();
|
||||
self.passengers.extend_from_slice(passengers);
|
||||
}
|
||||
// Leashable.setLeashedTo / dropLeash: sendToTrackingPlayers at once.
|
||||
if e.leash != self.leash {
|
||||
out.push(play::Clientbound::SetEntityLink(SetEntityLink {
|
||||
source: e.id,
|
||||
dest: e.leash.unwrap_or(0),
|
||||
}));
|
||||
self.leash = e.leash;
|
||||
}
|
||||
// SynchedEntityData.isDirty: once for every client.
|
||||
let dirty = e.meta != self.meta;
|
||||
let due = self.interval != 0 && self.tick.is_multiple_of(self.interval);
|
||||
@@ -473,7 +499,10 @@ impl ServerEntity {
|
||||
(14, serializer::OPTIONAL_BLOCK_POS) => Value::OptPos(None),
|
||||
(9, serializer::ITEM_STACK) if frame => Value::Item(None),
|
||||
(10, serializer::INT) if frame => Value::Int(0),
|
||||
_ => continue,
|
||||
_ => match e.defaults.iter().find(|d| (d.0, d.1) == (*index, *kind)) {
|
||||
Some(d) => d.2.clone(),
|
||||
None => continue,
|
||||
},
|
||||
};
|
||||
if !e.meta.iter().any(|m| m.0 == *index) {
|
||||
changed.push((*index, *kind, default));
|
||||
@@ -859,10 +888,12 @@ mod tests {
|
||||
velocity: [0.0; 3],
|
||||
data: 0,
|
||||
meta: Vec::new(),
|
||||
defaults: Vec::new(),
|
||||
equipment: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
precise: false,
|
||||
needs_sync: false,
|
||||
leash: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1112,6 +1143,29 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_back_at_a_listed_default_is_sent() {
|
||||
let mut e = state(0.0);
|
||||
e.defaults = vec![(16, serializer::BOOLEAN, Value::Bool(false))];
|
||||
// A calf: paired with its baby flag, then grown up.
|
||||
e.meta = vec![(16, serializer::BOOLEAN, Value::Bool(true))];
|
||||
let mut s = added(&e);
|
||||
changes(&mut s, &e);
|
||||
e.meta.clear();
|
||||
let data = changes(&mut s, &e)
|
||||
.into_iter()
|
||||
.find_map(|p| match p {
|
||||
play::Clientbound::SetEntityData(d) => Some(d),
|
||||
_ => None,
|
||||
})
|
||||
.expect("growing up is sent");
|
||||
assert_eq!(
|
||||
data.values,
|
||||
vec![(16, serializer::BOOLEAN, Value::Bool(false))]
|
||||
);
|
||||
assert!(changes(&mut s, &e).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_and_equipment_send_only_the_changes() {
|
||||
let mut e = state(0.0);
|
||||
@@ -1137,6 +1191,24 @@ mod tests {
|
||||
assert_eq!(eq.slots, vec![(0, None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lead_tied_and_untied_reaches_the_clients() {
|
||||
let link = |out: &[play::Clientbound]| {
|
||||
out.iter().find_map(|p| match p {
|
||||
play::Clientbound::SetEntityLink(l) => Some((l.source, l.dest)),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let mut e = state(0.0);
|
||||
let mut s = added(&e);
|
||||
changes(&mut s, &e);
|
||||
e.leash = Some(7);
|
||||
assert_eq!(link(&changes(&mut s, &e)), Some((e.id, 7)));
|
||||
assert_eq!(link(&changes(&mut s, &e)), None);
|
||||
e.leash = None;
|
||||
assert_eq!(link(&changes(&mut s, &e)), Some((e.id, 0)));
|
||||
}
|
||||
|
||||
/// Two clients at the origin; the chunks they hold.
|
||||
struct Clients {
|
||||
chunks: crate::fast_hash::FxHashSet<(i32, i32)>,
|
||||
|
||||
@@ -15,9 +15,33 @@ use std::{
|
||||
/// GameType ids.
|
||||
pub const SURVIVAL: i32 = 0;
|
||||
pub const CREATIVE: i32 = 1;
|
||||
pub const ADVENTURE: i32 = 2;
|
||||
pub const SPECTATOR: i32 = 3;
|
||||
|
||||
/// The body state a player's file keeps that lives on `PlayerMotion`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SavedBody {
|
||||
pub fire_ticks: i32,
|
||||
pub air: i32,
|
||||
pub fall_distance: f64,
|
||||
}
|
||||
|
||||
impl SavedBody {
|
||||
/// The body state of `motion`, to save.
|
||||
pub fn of(motion: &PlayerMotion) -> Self {
|
||||
Self {
|
||||
fire_ticks: motion.fire_ticks,
|
||||
air: motion.air,
|
||||
fall_distance: motion.fall_distance,
|
||||
}
|
||||
}
|
||||
/// Put it on a new body.
|
||||
pub fn apply(self, motion: &mut PlayerMotion) {
|
||||
motion.fire_ticks = self.fire_ticks;
|
||||
motion.air = self.air;
|
||||
motion.fall_distance = self.fall_distance;
|
||||
}
|
||||
}
|
||||
|
||||
/// An effect as last sent in ClientboundUpdateMobEffectPacket.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SentEffect {
|
||||
@@ -133,6 +157,9 @@ pub struct Guest {
|
||||
pub tracker: Tracker,
|
||||
// Player state the gameplay code reads and writes.
|
||||
pub motion: Option<Box<PlayerMotion>>,
|
||||
/// What the player's file says of the body (`Entity.load`: the fire
|
||||
/// and air ticks and the fall distance), for the first body it gets.
|
||||
pub loaded_body: Option<SavedBody>,
|
||||
/// The hurt and attack logs of the body it had before it respawned,
|
||||
/// until the new body takes them over (the control socket's `hurtlog`
|
||||
/// reads across a death).
|
||||
@@ -215,6 +242,8 @@ pub struct Guest {
|
||||
pub advancements_loaded: bool,
|
||||
pub advancements_visible: Vec<bool>,
|
||||
pub advancements_changed: std::collections::BTreeSet<usize>,
|
||||
/// The server's scoreboard as this player's client has it (lan/scoreboard.rs).
|
||||
pub scoreboard: super::scoreboard::View,
|
||||
/// Recipes unlocked since the client was last told
|
||||
/// (`ServerRecipeBook.addRecipes` sends them).
|
||||
pub recipes_unlocked: Vec<String>,
|
||||
@@ -282,6 +311,7 @@ impl Guest {
|
||||
batch_quota: 0.0,
|
||||
tracker: Tracker::default(),
|
||||
motion: None,
|
||||
loaded_body: None,
|
||||
logs_kept: None,
|
||||
inventory: vec![None; 36],
|
||||
armor: [None, None, None, None],
|
||||
@@ -326,6 +356,7 @@ impl Guest {
|
||||
advancements_loaded: false,
|
||||
advancements_visible: Vec::new(),
|
||||
advancements_changed: Default::default(),
|
||||
scoreboard: Default::default(),
|
||||
recipes_unlocked: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,13 +172,6 @@ pub struct Hub {
|
||||
fn string(s: &str) -> Tag {
|
||||
Tag::String(JavaString::from(s))
|
||||
}
|
||||
pub fn yellow_translation(key: &str, args: &[&str]) -> Tag {
|
||||
let mut t = translatable(key, args);
|
||||
if let Tag::Compound(map) = &mut t {
|
||||
map.insert(JavaString::from("color"), string("yellow"));
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Player.getDisplayName for a player in no team: the name, suggesting
|
||||
/// `/tell NAME `, showing the player on hover and inserting the name.
|
||||
@@ -1360,21 +1353,6 @@ impl Hub {
|
||||
(!batch.is_empty()).then_some(batch)
|
||||
}
|
||||
|
||||
/// Resend a chunk to everyone who has it (a block entity changed, relight).
|
||||
pub fn resend_chunk(&mut self, world: &World, x: i32, z: i32) {
|
||||
let Some(chunk) = world.chunks.get(&(x, z)) else {
|
||||
return;
|
||||
};
|
||||
let body = self.encoder.body_in(chunk, world);
|
||||
for g in self
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| g.sent_chunks.contains(&(x, z)))
|
||||
{
|
||||
g.sender.send(body.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChunkHolder.broadcastChanges`' light part: the light sections that
|
||||
/// changed in a column go to the players for whom it is on the border of
|
||||
/// what they track (`ChunkMap.isChunkOnTrackedBorder`); the others light
|
||||
@@ -1559,10 +1537,12 @@ impl Hub {
|
||||
velocity: [0.0; 3],
|
||||
data: 0,
|
||||
meta,
|
||||
defaults: Vec::new(),
|
||||
equipment,
|
||||
attributes,
|
||||
precise: false,
|
||||
needs_sync: false,
|
||||
leash: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ pub mod hub;
|
||||
pub mod menu;
|
||||
pub mod playerdata;
|
||||
mod recipes;
|
||||
pub mod scoreboard;
|
||||
pub mod tracking;
|
||||
pub mod waypoints;
|
||||
|
||||
@@ -272,9 +273,6 @@ impl Shared {
|
||||
pub fn max_players(&self) -> usize {
|
||||
self.max_players.load(Ordering::Relaxed)
|
||||
}
|
||||
pub fn set_max_players(&self, n: usize) {
|
||||
self.max_players.store(n, Ordering::Relaxed);
|
||||
}
|
||||
pub fn release(&self, uuid: u128) {
|
||||
self.online.lock().unwrap().retain(|(u, _)| *u != uuid);
|
||||
}
|
||||
@@ -513,9 +511,6 @@ impl Lan {
|
||||
pub fn reserve(&self, uuid: u128) {
|
||||
self.shared.reserved.lock().unwrap().insert(uuid);
|
||||
}
|
||||
pub fn set_motd(&self, motd: &str) {
|
||||
*self.shared.motd.lock().unwrap() = motd.to_owned();
|
||||
}
|
||||
pub fn stop(&mut self) {
|
||||
self.shared.stop.store(true, Ordering::Relaxed);
|
||||
self.stop_listening();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Guests' saved state: `players/data/<uuid>.dat` in the vanilla player
|
||||
//! compound, through the same code that saves the host.
|
||||
use super::guest::Guest;
|
||||
use super::guest::{Guest, SavedBody};
|
||||
use crate::{
|
||||
items::ItemStack,
|
||||
save::{Level, read_dat, write_dat},
|
||||
@@ -80,6 +80,17 @@ pub fn apply(guest: &mut Guest, level: &Level) {
|
||||
.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]);
|
||||
guest.respawn_elsewhere = level.respawn_elsewhere.clone();
|
||||
guest.saved = level.player_extra.clone();
|
||||
let extra = level.player_extra.as_ref();
|
||||
let short = |key: &str, default: i64| {
|
||||
extra
|
||||
.and_then(|t| crate::save::number(t.get(key)))
|
||||
.unwrap_or(default) as i32
|
||||
};
|
||||
guest.loaded_body = Some(SavedBody {
|
||||
fire_ticks: short("Fire", -20),
|
||||
air: short("Air", 300),
|
||||
fall_distance: level.fall_distance,
|
||||
});
|
||||
guest.recipe_book = level.recipe_book.clone();
|
||||
guest.dimension = match level.dimension.as_str() {
|
||||
d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(),
|
||||
@@ -151,6 +162,24 @@ pub fn store(guest: &Guest, level: &mut Level) {
|
||||
level.respawn_elsewhere = guest.respawn_elsewhere.clone();
|
||||
level.on_ground = guest.on_ground;
|
||||
level.player_extra = guest.saved.clone();
|
||||
// The live body's fire, air and fall distance (Entity.saveWithoutId),
|
||||
// or what the file had while the player has no body yet.
|
||||
let body = guest
|
||||
.motion
|
||||
.as_deref()
|
||||
.map(SavedBody::of)
|
||||
.or(guest.loaded_body);
|
||||
if let Some(body) = body {
|
||||
level.fall_distance = body.fall_distance;
|
||||
let extra = level
|
||||
.player_extra
|
||||
.get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default()));
|
||||
if let horizon_world::nbt::Tag::Compound(map) = extra {
|
||||
let short = |v: i32| horizon_world::nbt::Tag::Short(v.clamp(-32768, 32767) as i16);
|
||||
map.insert("Fire".into(), short(body.fire_ticks));
|
||||
map.insert("Air".into(), short(body.air));
|
||||
}
|
||||
}
|
||||
level.recipe_book = guest.recipe_book.clone();
|
||||
level.ender_items = guest.ender_items.clone();
|
||||
level.inventory.clear();
|
||||
@@ -174,3 +203,52 @@ pub fn store(guest: &Guest, level: &mut Level) {
|
||||
put(100, &guest.armor[3]);
|
||||
put(150, &guest.offhand);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::lan::{Joined, PlayerSender};
|
||||
use horizon_protocol::packets::configuration::ClientInformation;
|
||||
use std::sync::{Arc, atomic::AtomicI32, mpsc};
|
||||
|
||||
fn guest() -> Guest {
|
||||
let (tx, _rx) = mpsc::channel();
|
||||
Guest::new(
|
||||
Joined {
|
||||
conn: 2,
|
||||
uuid: 2,
|
||||
name: "Alex".into(),
|
||||
properties: Vec::new(),
|
||||
info: ClientInformation::new(8),
|
||||
brand: "test".into(),
|
||||
sender: PlayerSender::new(tx, Arc::default()),
|
||||
latency: Arc::new(AtomicI32::new(0)),
|
||||
address: "127.0.0.1:25565".parse().unwrap(),
|
||||
},
|
||||
2,
|
||||
[0.0, 64.0, 0.0],
|
||||
8,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_burn_and_fall_come_back() {
|
||||
// A player saved burning in mid-fall (#1323, #1327): Entity.saveWithoutId's
|
||||
// Fire, Air and fall_distance, read back for the next body.
|
||||
let mut g = guest();
|
||||
g.loaded_body = Some(SavedBody {
|
||||
fire_ticks: 96,
|
||||
air: 250,
|
||||
fall_distance: 9.5,
|
||||
});
|
||||
let mut level = Level::default();
|
||||
store(&g, &mut level);
|
||||
let tag = level.player_tag();
|
||||
let mut read = Level::default();
|
||||
read.read_player(&tag);
|
||||
read.player_extra = Some(tag);
|
||||
let mut back = guest();
|
||||
apply(&mut back, &read);
|
||||
assert_eq!(back.loaded_body, g.loaded_body);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
//! `ServerScoreboard`: what a player's client knows of the server's
|
||||
//! scoreboard. Every team goes to every player; an objective goes once it
|
||||
//! sits in a display slot (`startTrackingObjective`: its objective, its
|
||||
//! slots, then its scores) and leaves when it sits in none
|
||||
//! (`stopTrackingObjective`). A joining player gets it all
|
||||
//! (`PlayerList.updateEntireScoreboard`).
|
||||
//!
|
||||
//! A server's commands change the board in place; each tick a player is
|
||||
//! sent the packets that turn what it was last sent into what it should
|
||||
//! have now, which are the ones `ServerScoreboard`'s callbacks send.
|
||||
use crate::scoreboard::{NumberFormat, RenderType, Scoreboard, component_tag, display_slots};
|
||||
use crate::text::COLORS;
|
||||
use horizon_protocol::packets::play::{
|
||||
self, Clientbound as C, ResetScore, SetDisplayObjective, SetObjective, SetPlayerTeam, SetScore,
|
||||
TeamParameters,
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
type Format = Option<play::NumberFormat>;
|
||||
|
||||
/// The scoreboard as one player's client has it.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct View {
|
||||
/// The tracked objectives: display name, render type (1 hearts), format.
|
||||
objectives: BTreeMap<String, (Tag, i32, Format)>,
|
||||
/// `DisplaySlot` id to objective.
|
||||
display: BTreeMap<i32, String>,
|
||||
/// The tracked objectives' scores, by holder and objective.
|
||||
scores: BTreeMap<(String, String), (i32, Option<Tag>, Format)>,
|
||||
/// Every team: its parameters and players, in the team's order.
|
||||
teams: BTreeMap<String, (TeamParameters, Vec<String>)>,
|
||||
}
|
||||
|
||||
fn format(f: Option<&NumberFormat>) -> Format {
|
||||
f.map(|f| match f {
|
||||
NumberFormat::Blank => play::NumberFormat::Blank,
|
||||
NumberFormat::Styled(s) => play::NumberFormat::Styled(crate::scoreboard::json_to_tag(s)),
|
||||
NumberFormat::Fixed(c) => play::NumberFormat::Fixed(component_tag(c)),
|
||||
})
|
||||
}
|
||||
|
||||
impl View {
|
||||
/// What the board's state gives a client.
|
||||
pub fn of(board: &Scoreboard) -> Self {
|
||||
let slots = display_slots();
|
||||
let display: BTreeMap<i32, String> = board
|
||||
.display
|
||||
.iter()
|
||||
.filter_map(|(slot, o)| Some((slots.iter().position(|s| s == slot)? as i32, o.clone())))
|
||||
.collect();
|
||||
let tracked: BTreeSet<&String> = display.values().collect();
|
||||
let objectives = board
|
||||
.objectives
|
||||
.iter()
|
||||
.filter(|o| tracked.contains(&o.name))
|
||||
.map(|o| {
|
||||
let render = i32::from(o.render_type == RenderType::Hearts);
|
||||
(
|
||||
o.name.clone(),
|
||||
(
|
||||
component_tag(&o.display_name),
|
||||
render,
|
||||
format(o.number_format.as_ref()),
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let scores = board
|
||||
.scores
|
||||
.iter()
|
||||
.flat_map(|(holder, scores)| {
|
||||
scores
|
||||
.iter()
|
||||
.filter(|(o, _)| tracked.contains(o))
|
||||
.map(move |(o, s)| {
|
||||
(
|
||||
(holder.clone(), o.clone()),
|
||||
(
|
||||
s.value,
|
||||
s.display.as_ref().map(component_tag),
|
||||
format(s.number_format.as_ref()),
|
||||
),
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let teams = board
|
||||
.teams
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let params = TeamParameters {
|
||||
display_name: component_tag(&t.display_name),
|
||||
prefix: component_tag(&t.prefix),
|
||||
suffix: component_tag(&t.suffix),
|
||||
name_tag_visibility: t.nametag_visibility as i32,
|
||||
collision_rule: t.collision_rule as i32,
|
||||
color: t
|
||||
.color
|
||||
.as_deref()
|
||||
.and_then(|c| COLORS.iter().position(|(_, n, _)| *n == c))
|
||||
.map(|i| i as i32),
|
||||
options: i8::from(t.allow_friendly_fire)
|
||||
| (i8::from(t.see_friendly_invisibles) << 1),
|
||||
};
|
||||
(
|
||||
t.name.clone(),
|
||||
(params, t.players.iter().cloned().collect()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
objectives,
|
||||
display,
|
||||
scores,
|
||||
teams,
|
||||
}
|
||||
}
|
||||
|
||||
/// The packets that take a client from `self` to `next`.
|
||||
pub fn changes(&self, next: &View) -> Vec<C> {
|
||||
let mut out = Vec::new();
|
||||
let team = |name: &str, method, parameters, players| {
|
||||
C::SetPlayerTeam(SetPlayerTeam {
|
||||
name: name.to_owned(),
|
||||
method,
|
||||
parameters,
|
||||
players,
|
||||
})
|
||||
};
|
||||
for name in self.teams.keys().filter(|n| !next.teams.contains_key(*n)) {
|
||||
out.push(team(name, 1, None, Vec::new()));
|
||||
}
|
||||
for (name, (params, players)) in &next.teams {
|
||||
let Some((was, had)) = self.teams.get(name) else {
|
||||
out.push(team(name, 0, Some(params.clone()), players.clone()));
|
||||
continue;
|
||||
};
|
||||
if was != params {
|
||||
out.push(team(name, 2, Some(params.clone()), Vec::new()));
|
||||
}
|
||||
let joined: Vec<_> = players
|
||||
.iter()
|
||||
.filter(|p| !had.contains(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !joined.is_empty() {
|
||||
out.push(team(name, 3, None, joined));
|
||||
}
|
||||
let left: Vec<_> = had
|
||||
.iter()
|
||||
.filter(|p| !players.contains(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
if !left.is_empty() {
|
||||
out.push(team(name, 4, None, left));
|
||||
}
|
||||
}
|
||||
for (name, display) in &next.objectives {
|
||||
let method = match self.objectives.get(name) {
|
||||
None => 0,
|
||||
Some(was) if was != display => 2,
|
||||
Some(_) => continue,
|
||||
};
|
||||
out.push(C::SetObjective(SetObjective {
|
||||
name: name.clone(),
|
||||
method,
|
||||
display: Some(display.clone()),
|
||||
}));
|
||||
}
|
||||
let slots: BTreeSet<i32> = self
|
||||
.display
|
||||
.keys()
|
||||
.chain(next.display.keys())
|
||||
.copied()
|
||||
.collect();
|
||||
for slot in slots {
|
||||
let objective = next.display.get(&slot);
|
||||
if self.display.get(&slot) != objective {
|
||||
out.push(C::SetDisplayObjective(SetDisplayObjective {
|
||||
slot,
|
||||
objective: objective.cloned().unwrap_or_default(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
for ((holder, objective), (value, display, number_format)) in &next.scores {
|
||||
let key = (holder.clone(), objective.clone());
|
||||
if self.scores.get(&key) != Some(&(*value, display.clone(), number_format.clone())) {
|
||||
out.push(C::SetScore(SetScore {
|
||||
owner: holder.clone(),
|
||||
objective: objective.clone(),
|
||||
score: *value,
|
||||
display: display.clone(),
|
||||
number_format: number_format.clone(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
for (holder, objective) in self.scores.keys() {
|
||||
let key = (holder.clone(), objective.clone());
|
||||
if !next.scores.contains_key(&key) && next.objectives.contains_key(objective) {
|
||||
out.push(C::ResetScore(ResetScore {
|
||||
owner: holder.clone(),
|
||||
objective: Some(objective.clone()),
|
||||
}));
|
||||
}
|
||||
}
|
||||
for name in self
|
||||
.objectives
|
||||
.keys()
|
||||
.filter(|n| !next.objectives.contains_key(*n))
|
||||
{
|
||||
out.push(C::SetObjective(SetObjective {
|
||||
name: name.clone(),
|
||||
method: 1,
|
||||
display: None,
|
||||
}));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn methods(packets: &[C]) -> Vec<String> {
|
||||
packets
|
||||
.iter()
|
||||
.map(|p| match p {
|
||||
C::SetObjective(o) => format!("objective {} {}", o.name, o.method),
|
||||
C::SetDisplayObjective(d) => format!("display {} {}", d.slot, d.objective),
|
||||
C::SetScore(s) => format!("score {} {} {}", s.owner, s.objective, s.score),
|
||||
C::ResetScore(r) => format!("reset {} {:?}", r.owner, r.objective),
|
||||
C::SetPlayerTeam(t) => format!("team {} {} {:?}", t.name, t.method, t.players),
|
||||
_ => "other".into(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shown_objective_goes_with_its_scores_and_leaves_when_hidden() {
|
||||
let mut board = Scoreboard::default();
|
||||
board.add_objective(
|
||||
"audit",
|
||||
"dummy",
|
||||
json!("Audit"),
|
||||
RenderType::Integer,
|
||||
false,
|
||||
None,
|
||||
);
|
||||
board.score_mut("Alpha", "audit").value = 7;
|
||||
let empty = View::default();
|
||||
// Not displayed: not tracked, nothing sent.
|
||||
let hidden = View::of(&board);
|
||||
assert!(empty.changes(&hidden).is_empty());
|
||||
board.set_display_objective("sidebar", Some("audit"));
|
||||
let shown = View::of(&board);
|
||||
assert_eq!(
|
||||
methods(&hidden.changes(&shown)),
|
||||
[
|
||||
"objective audit 0",
|
||||
"display 1 audit",
|
||||
"score Alpha audit 7"
|
||||
]
|
||||
);
|
||||
board.score_mut("Alpha", "audit").value = 12;
|
||||
board.score_mut("Beta", "audit").value = 3;
|
||||
board.reset_one("Beta", "audit");
|
||||
let changed = View::of(&board);
|
||||
assert_eq!(methods(&shown.changes(&changed)), ["score Alpha audit 12"]);
|
||||
board.reset_one("Alpha", "audit");
|
||||
let reset = View::of(&board);
|
||||
assert_eq!(
|
||||
methods(&changed.changes(&reset)),
|
||||
["reset Alpha Some(\"audit\")"]
|
||||
);
|
||||
board.set_display_objective("sidebar", None);
|
||||
assert_eq!(
|
||||
methods(&reset.changes(&View::of(&board))),
|
||||
["display 1 ", "objective audit 1"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teams_go_to_everyone_with_their_players() {
|
||||
let mut board = Scoreboard::default();
|
||||
board.add_team("red");
|
||||
board.add_to_team("Alpha", "red");
|
||||
let first = View::of(&board);
|
||||
assert_eq!(
|
||||
methods(&View::default().changes(&first)),
|
||||
["team red 0 [\"Alpha\"]"]
|
||||
);
|
||||
board.add_to_team("Beta", "red");
|
||||
board.remove_from_team("Alpha");
|
||||
let second = View::of(&board);
|
||||
assert_eq!(
|
||||
methods(&first.changes(&second)),
|
||||
["team red 3 [\"Beta\"]", "team red 4 [\"Alpha\"]"]
|
||||
);
|
||||
board.remove_team("red");
|
||||
assert_eq!(
|
||||
methods(&second.changes(&View::of(&board))),
|
||||
["team red 1 []"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -77,12 +77,6 @@ pub fn apply_deprecated(map: &mut HashMap<String, String>, json: &[u8]) {
|
||||
}
|
||||
|
||||
impl Language {
|
||||
pub fn from_map(code: &str, map: HashMap<String, String>) -> Self {
|
||||
Self {
|
||||
code: code.to_owned(),
|
||||
map,
|
||||
}
|
||||
}
|
||||
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
|
||||
/// from every namespace and every source in priority order (later sources
|
||||
/// override).
|
||||
|
||||
@@ -203,7 +203,7 @@ impl LightTables {
|
||||
Ok(tables)
|
||||
}
|
||||
/// Assembled tables (tests and benchmarks): derives the packed light cache.
|
||||
#[allow(dead_code)]
|
||||
#[cfg(test)]
|
||||
fn from_parts(cells: Vec<Cell>, occludes: Vec<bool>, faces: usize) -> Self {
|
||||
let mut tables = Self {
|
||||
cells,
|
||||
|
||||
@@ -239,10 +239,6 @@ pub enum ArmPose {
|
||||
/// Raising a trident to throw it (or to launch with Riptide).
|
||||
ThrowTrident,
|
||||
}
|
||||
/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself.
|
||||
pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) {
|
||||
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
|
||||
}
|
||||
/// HumanoidModel.setupAnim with empty hands (endermen).
|
||||
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
|
||||
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
|
||||
|
||||
@@ -152,10 +152,6 @@ pub fn protector(heart: &mut CreakingHeart, host: &impl HeartHost) -> Option<u32
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `isProtector`.
|
||||
pub fn is_protector(heart: &mut CreakingHeart, host: &impl HeartHost, id: u32) -> bool {
|
||||
protector(heart, host) == Some(id)
|
||||
}
|
||||
fn distance_to_creaking(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> f64 {
|
||||
protector(heart, host)
|
||||
.and_then(|id| host.mob(id))
|
||||
|
||||
@@ -76,9 +76,6 @@ pub struct GoalSelector {
|
||||
locked: [Option<usize>; 4],
|
||||
pub disabled: u8,
|
||||
}
|
||||
fn flag_index(f: u8) -> usize {
|
||||
f.trailing_zeros() as usize
|
||||
}
|
||||
impl GoalSelector {
|
||||
pub fn add(&mut self, priority: i32, goal: impl Goal + 'static) {
|
||||
self.goals.push(Wrapped {
|
||||
@@ -174,10 +171,6 @@ impl GoalSelector {
|
||||
}
|
||||
self.locked = [None; 4];
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
fn locked_by(&self, flag: u8) -> Option<usize> {
|
||||
self.locked[flag_index(flag)]
|
||||
}
|
||||
}
|
||||
|
||||
// --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) -------
|
||||
@@ -565,36 +558,6 @@ impl Mob {
|
||||
m.land_up_out_of_solid(w, p)
|
||||
})
|
||||
}
|
||||
/// LandRandomPos.getPosTowards
|
||||
pub fn land_random_pos_towards(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
h: i32,
|
||||
v: i32,
|
||||
to: [f64; 3],
|
||||
) -> Option<[f64; 3]> {
|
||||
let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z);
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction_within(
|
||||
0.0,
|
||||
f64::from(h),
|
||||
v,
|
||||
0,
|
||||
xd,
|
||||
zd,
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y
|
||||
|| p[1] >= 320
|
||||
|| m.restricted(f64::from(h), p)
|
||||
|| !m.stable_destination(w, p)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
m.land_up_out_of_solid(w, p)
|
||||
})
|
||||
}
|
||||
pub fn target_info(&self, w: &MobWorld) -> Option<TargetInfo> {
|
||||
self.ai.target.and_then(|t| w.target_info(t))
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ use horizon_core::{
|
||||
// Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a
|
||||
// baby and 2 as an adult, `ai.home` the restriction, `counter`
|
||||
// the end tick of the follow-an-adult range pick.
|
||||
pub const BABY_SCALE: f64 = 0.2375;
|
||||
/// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`).
|
||||
pub const FLYING_SPEED: f64 = 0.05;
|
||||
pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0;
|
||||
|
||||
@@ -250,10 +250,6 @@ pub fn nearest_players(m: &Mob) -> Vec<Who> {
|
||||
.and_then(|b| b.mem.nearest_players.value())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
/// The damage the brain remembers (`HURT_BY`).
|
||||
pub fn hurt_by_present(m: &Mob) -> bool {
|
||||
brain(m).is_some_and(|b| b.mem.hurt_by.present())
|
||||
}
|
||||
/// `HURT_BY`'s damage source entity, if a living one.
|
||||
fn hurt_by_entity(m: &Mob, w: &MobWorld) -> Option<Who> {
|
||||
let t = brain(m)?.mem.hurt_by.value()?;
|
||||
|
||||
@@ -76,14 +76,6 @@ pub fn finalize(m: &mut Mob, warm_ocean: bool) {
|
||||
m.extra.variant = u8::from(warm_ocean);
|
||||
}
|
||||
}
|
||||
/// `checkNautilusSpawnRules`: 5 to 25 blocks below sea level, water below
|
||||
/// and above.
|
||||
pub fn spawn_rules_ok(w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
|
||||
let sea = 63;
|
||||
(sea - 25..=sea - 5).contains(&y)
|
||||
&& w.fluid(x, y - 1, z) == Fluid::Water
|
||||
&& w.block_name(x, y + 1, z) == "minecraft:water"
|
||||
}
|
||||
/// `getControllingPassenger`: a player on a saddled nautilus.
|
||||
pub fn controlled(m: &Mob) -> bool {
|
||||
m.rider.is_some() && m.extra.saddled
|
||||
|
||||
@@ -582,26 +582,4 @@ impl Mob {
|
||||
NavKind::Amphibious => !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])),
|
||||
}
|
||||
}
|
||||
pub fn should_recompute_path(&self, p: [i32; 3]) -> bool {
|
||||
if self.ai.nav.delayed_recompute {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = &self.ai.nav.path else {
|
||||
return false;
|
||||
};
|
||||
if path.is_done() || path.nodes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(end) = path.end() else { return false };
|
||||
let mid = [
|
||||
(f64::from(end.x) + self.position.x) / 2.0,
|
||||
(f64::from(end.y) + self.position.y) / 2.0,
|
||||
(f64::from(end.z) + self.position.z) / 2.0,
|
||||
];
|
||||
let d = (f64::from(p[0]) + 0.5 - mid[0]).powi(2)
|
||||
+ (f64::from(p[1]) + 0.5 - mid[1]).powi(2)
|
||||
+ (f64::from(p[2]) + 0.5 - mid[2]).powi(2);
|
||||
let r = (path.nodes.len() - path.next) as f64;
|
||||
d < r * r
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +310,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn love_ticks_survive_a_save() {
|
||||
// Animal.addAdditionalSaveData / readAdditionalSaveData: "InLove" (#1396).
|
||||
let mut m = rabbit();
|
||||
m.extra.in_love = 570;
|
||||
let tag = crate::entity_nbt::mob_to_nbt(&m, [0, 0, 0, 1], None);
|
||||
assert_eq!(tag.get("InLove"), Some(&horizon_world::nbt::Tag::Int(570)));
|
||||
let types = HashMap::from([(m.kind.id.clone(), m.kind.clone())]);
|
||||
let back = crate::entity_nbt::mob_from_nbt(&tag, &types, 2).unwrap();
|
||||
assert_eq!(back.extra.in_love, 570);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn landing_waits_then_real_hop_clock_moves_the_model() {
|
||||
let mut m = rabbit();
|
||||
|
||||
@@ -769,19 +769,6 @@ pub fn weighted_pick(list: &[SpawnEntry], random: &mut impl RandomSource) -> Opt
|
||||
None
|
||||
}
|
||||
|
||||
/// `NaturalSpawner.getRandomSpawnMobAt`.
|
||||
pub fn random_spawn_mob_at(
|
||||
list: &[SpawnEntry],
|
||||
category: &str,
|
||||
reduced_water_ambient: bool,
|
||||
random: &mut impl RandomSource,
|
||||
) -> Option<SpawnEntry> {
|
||||
if category == "water_ambient" && reduced_water_ambient && random.next_float() < 0.98 {
|
||||
return None;
|
||||
}
|
||||
weighted_pick(list, random)
|
||||
}
|
||||
|
||||
/// `SpawnerData.count().sample(random)`: a constant draws nothing.
|
||||
pub fn sample_count(entry: &SpawnEntry, random: &mut impl RandomSource) -> u32 {
|
||||
if entry.constant {
|
||||
|
||||
@@ -30,25 +30,6 @@ pub struct BiomeFacts {
|
||||
pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
|
||||
super::spawn_rules::is_spawn_position_ok(species, w, x, y, z)
|
||||
}
|
||||
/// `SpawnPlacements.checkSpawnRules` for a natural spawn.
|
||||
pub fn spawn_rules_ok(
|
||||
species: Species,
|
||||
w: &MobWorld,
|
||||
random: &mut impl RandomSource,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> bool {
|
||||
super::spawn_rules::check_spawn_rules(
|
||||
species,
|
||||
w,
|
||||
super::spawn_rules::Reason::Natural,
|
||||
random,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
)
|
||||
}
|
||||
/// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs.
|
||||
/// `DifficultyInstance`: the local difficulty at a position.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! other `GateBehavior`s shuffle with a random of their own, seeded with
|
||||
//! `Brain::shuffle_seed` when the brain is built.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Seen, Species, Who,
|
||||
Mob, MobEvent, MobWorld, Species, Who,
|
||||
path::{Path, PathNode},
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -4156,10 +4156,6 @@ pub fn woken(m: &mut Mob, now: i64) {
|
||||
pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> {
|
||||
mem_ref(m).and_then(|mm| mm.potential_job_site.value())
|
||||
}
|
||||
/// Whether a seen mob is a villager wanting to breed (`AgeableMob::canBreed`).
|
||||
pub fn seen_can_breed(s: &Seen) -> bool {
|
||||
s.species == Species::Villager && s.in_love
|
||||
}
|
||||
/// The memories other villagers read: the interaction target, the path's
|
||||
/// nodes (while it is not done), whether a golem was seen lately and the
|
||||
/// last sleep.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! What mobs read from the level: block solidity, ray clipping for line of
|
||||
//! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent
|
||||
//! values and the positions of other entities.
|
||||
use super::{MobWorld, Seen, Species, Who, data};
|
||||
use super::{MobWorld, Seen, Who, data};
|
||||
use crate::{
|
||||
blocks::{BlockFacts, Fluid},
|
||||
collisions::SceneCollisions,
|
||||
@@ -269,12 +269,6 @@ impl MobWorld<'_> {
|
||||
});
|
||||
v.into_iter()
|
||||
}
|
||||
pub fn count_species(&self, species: Species) -> usize {
|
||||
self.others
|
||||
.iter()
|
||||
.filter(|s| s.species == species && s.alive)
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Level.clip with VISUAL shapes and no fluids: the block the segment first
|
||||
|
||||
@@ -337,6 +337,7 @@ impl PlayerMotion {
|
||||
self.air = extra
|
||||
.and_then(|t| crate::save::number(t.get("Air")))
|
||||
.unwrap_or(300) as i32;
|
||||
self.fall_distance = level.fall_distance;
|
||||
self.set_health(level.health, false)?;
|
||||
// LivingEntity.readAdditionalSaveData: internalSetAbsorptionAmount.
|
||||
self.internal_set_absorption(level.absorption)?;
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::{
|
||||
keybinds::{self, CATEGORIES, KeyBinds, MAPPINGS},
|
||||
lang::{self, LanguageInfo},
|
||||
settings::{SOUND_SOURCES, Settings},
|
||||
shader_pack::PackConfig,
|
||||
text::{self, Style, Text},
|
||||
ui,
|
||||
};
|
||||
@@ -864,6 +865,8 @@ pub enum Page {
|
||||
Mods,
|
||||
/// The shader packs in `shaderpacks/`: pick one, open the folder.
|
||||
ShaderPacks,
|
||||
/// Interactive options and profiles for the active shader pack.
|
||||
ShaderPackOptions,
|
||||
/// Horizon's graphics settings (`graphics_ui`).
|
||||
Graphics,
|
||||
GraphicsAdvanced,
|
||||
@@ -901,6 +904,11 @@ enum Act {
|
||||
/// Credits & Attribution's Credits button (WinScreen without the poem).
|
||||
Credits,
|
||||
CopyAgentDetails,
|
||||
ShaderPackProfile,
|
||||
ShaderPackSubscreen(String),
|
||||
ShaderPackBackScreen,
|
||||
ShaderPackOption(usize),
|
||||
ResetShaderPackOptions,
|
||||
}
|
||||
enum WKind {
|
||||
Button {
|
||||
@@ -913,6 +921,11 @@ enum WKind {
|
||||
value: f32,
|
||||
opt: Opt,
|
||||
},
|
||||
ShaderOptionSlider {
|
||||
label: Text,
|
||||
value: f32,
|
||||
index: usize,
|
||||
},
|
||||
Text {
|
||||
text: Text,
|
||||
color: u32,
|
||||
@@ -954,6 +967,9 @@ pub enum Event {
|
||||
Credits,
|
||||
/// Copy how an agent connects (the AI Agent page).
|
||||
CopyAgentDetails,
|
||||
/// The shader pack settings page closed with changes: they are saved,
|
||||
/// the pack is built again with them.
|
||||
ReloadShaderPack,
|
||||
}
|
||||
/// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after
|
||||
/// the last change (`OptionInstanceSliderButton.delayedApplyAt`).
|
||||
@@ -1011,6 +1027,13 @@ pub struct OptionsUi {
|
||||
pub shader_pack_error: Option<(String, String)>,
|
||||
/// The AI Agent page's status lines (set by the game while it shows).
|
||||
pub agent_status: Vec<String>,
|
||||
/// Loaded interactive configuration for the currently selected shader pack.
|
||||
pub shader_pack_config: Option<PackConfig>,
|
||||
/// The shader pack option slider being dragged.
|
||||
pub(crate) dragging_shader_option: Option<usize>,
|
||||
/// `shader_pack_config` changed since the settings page opened: leaving
|
||||
/// it saves the values and reloads the pack.
|
||||
shader_pack_edited: bool,
|
||||
}
|
||||
impl Default for OptionsUi {
|
||||
fn default() -> Self {
|
||||
@@ -1042,6 +1065,9 @@ impl Default for OptionsUi {
|
||||
shader_packs: Default::default(),
|
||||
shader_pack_error: None,
|
||||
agent_status: Vec::new(),
|
||||
shader_pack_config: None,
|
||||
dragging_shader_option: None,
|
||||
shader_pack_edited: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1172,7 +1198,7 @@ impl OptionsUi {
|
||||
}
|
||||
/// Pick shader pack `i` of the folder, or turn it off when it is the
|
||||
/// one running.
|
||||
pub(crate) fn toggle_shader_pack(&self, s: &mut Settings, i: usize) {
|
||||
pub(crate) fn toggle_shader_pack(&mut self, s: &mut Settings, i: usize) {
|
||||
let Some((id, Ok(_))) = self.shader_packs.packs.get(i) else {
|
||||
return;
|
||||
};
|
||||
@@ -1182,6 +1208,83 @@ impl OptionsUi {
|
||||
} else {
|
||||
id.clone()
|
||||
};
|
||||
self.sync_shader_pack_config(s);
|
||||
}
|
||||
/// Ensure `shader_pack_config` matches `s.horizon.shader_pack`.
|
||||
pub fn sync_shader_pack_config(&mut self, s: &Settings) {
|
||||
let id = s.horizon.shader_pack.as_str();
|
||||
if id.is_empty() {
|
||||
self.shader_pack_config = None;
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.shader_pack_config
|
||||
.as_ref()
|
||||
.is_some_and(|cfg| cfg.id == id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// A pack whose options can't be read has none, rather than being
|
||||
// read again every frame.
|
||||
let config = PackConfig::load(&self.shader_pack_dir(), id).unwrap_or_else(|e| {
|
||||
log::warn!("Horizon: shader pack {id} options: {e}");
|
||||
PackConfig {
|
||||
id: id.to_owned(),
|
||||
..Default::default()
|
||||
}
|
||||
});
|
||||
self.shader_pack_config = Some(config);
|
||||
self.shader_pack_edited = false;
|
||||
}
|
||||
/// The picked pack has options or profiles to show.
|
||||
fn shader_pack_has_settings(&self, s: &Settings) -> bool {
|
||||
self.shader_pack_config.as_ref().is_some_and(|c| {
|
||||
!s.horizon.shader_pack.is_empty()
|
||||
&& c.id == s.horizon.shader_pack
|
||||
&& (!c.options.is_empty() || !c.profiles.is_empty())
|
||||
})
|
||||
}
|
||||
fn shader_pack_dir(&self) -> std::path::PathBuf {
|
||||
if self.shader_packs.dir.as_os_str().is_empty() {
|
||||
crate::shader_pack::folder()
|
||||
} else {
|
||||
self.shader_packs.dir.clone()
|
||||
}
|
||||
}
|
||||
/// A file or folder dropped on the window: on the Shader Packs page (as
|
||||
/// Iris's `ShaderPackScreen.onFilesDrop`), a pack copied into
|
||||
/// `shaderpacks/` and picked. `None` elsewhere; the caller saves the
|
||||
/// settings and loads the pack on `Some(Ok)`.
|
||||
pub fn drop_shader_pack(
|
||||
&mut self,
|
||||
s: &mut Settings,
|
||||
path: &std::path::Path,
|
||||
) -> Option<Result<(), String>> {
|
||||
if self.page() != Page::ShaderPacks {
|
||||
return None;
|
||||
}
|
||||
let dir = self.shader_pack_dir();
|
||||
Some(crate::shader_pack::import_pack(path, &dir).map(|id| {
|
||||
self.shader_packs = Default::default();
|
||||
self.shader_packs.poll(dir);
|
||||
s.horizon.shader_pack = id;
|
||||
self.sync_shader_pack_config(s);
|
||||
}))
|
||||
}
|
||||
/// Change the shader pack's options, applied when its page closes.
|
||||
fn edit_shader_pack(&mut self, edit: impl FnOnce(&mut PackConfig)) {
|
||||
if let Some(cfg) = &mut self.shader_pack_config {
|
||||
edit(cfg);
|
||||
self.shader_pack_edited = true;
|
||||
}
|
||||
}
|
||||
/// Save the active shader pack options to `shaderpacks/<id>.txt`.
|
||||
fn save_shader_pack_config(&self) {
|
||||
if let Some(cfg) = &self.shader_pack_config
|
||||
&& let Err(e) = cfg.save(&self.shader_pack_dir())
|
||||
{
|
||||
log::warn!("Horizon: shader pack {} options: {e}", cfg.id);
|
||||
}
|
||||
}
|
||||
pub(crate) fn shader_pack_failed(&self, id: &str) -> bool {
|
||||
self.shader_pack_error
|
||||
@@ -1215,6 +1318,7 @@ impl OptionsUi {
|
||||
Page::Packs => "resourcePack.title",
|
||||
Page::Mods => "Mods",
|
||||
Page::ShaderPacks => "Shader Packs",
|
||||
Page::ShaderPackOptions => "Shader Pack Settings",
|
||||
Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle",
|
||||
Page::Controller => "Controller Settings",
|
||||
Page::PadBinds => "Controller Binds",
|
||||
@@ -1589,6 +1693,87 @@ impl OptionsUi {
|
||||
}
|
||||
rows
|
||||
}
|
||||
Page::ShaderPackOptions => {
|
||||
let Some(cfg) = &self.shader_pack_config else {
|
||||
return vec![Row::Header("No configurable options for this shader pack")];
|
||||
};
|
||||
let screen = cfg.current_screen();
|
||||
let mut rows = vec![Row::Note(format!("{} — {}", cfg.id, screen.label))];
|
||||
if cfg.active_screen.is_some() {
|
||||
rows.push(Row::Buttons(
|
||||
button(
|
||||
0.0,
|
||||
0.0,
|
||||
310.0,
|
||||
Text::literal("Back to Main Screen"),
|
||||
Act::ShaderPackBackScreen,
|
||||
),
|
||||
None,
|
||||
));
|
||||
}
|
||||
let mut widgets = Vec::new();
|
||||
for item in &screen.items {
|
||||
match item {
|
||||
crate::shader_pack::ScreenItem::Empty => {}
|
||||
crate::shader_pack::ScreenItem::Profile => {
|
||||
let label =
|
||||
Text::literal(format!("Profile: {}", cfg.active_profile_label()));
|
||||
widgets.push(button(0.0, 0.0, 150.0, label, Act::ShaderPackProfile));
|
||||
}
|
||||
crate::shader_pack::ScreenItem::Subscreen(sub, title) => {
|
||||
let label = Text::literal(format!("{title}..."));
|
||||
widgets.push(button(
|
||||
0.0,
|
||||
0.0,
|
||||
150.0,
|
||||
label,
|
||||
Act::ShaderPackSubscreen(sub.clone()),
|
||||
));
|
||||
}
|
||||
crate::shader_pack::ScreenItem::Option(idx) => {
|
||||
if let Some(opt) = cfg.options.get(*idx) {
|
||||
let label = Text::literal(format!(
|
||||
"{}: {}",
|
||||
opt.label,
|
||||
opt.display_value()
|
||||
));
|
||||
if let Some(value) = opt.slider_pos() {
|
||||
widgets.push(Widget {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
w: 150.0,
|
||||
h: 20.0,
|
||||
kind: WKind::ShaderOptionSlider {
|
||||
label,
|
||||
value,
|
||||
index: *idx,
|
||||
},
|
||||
list: false,
|
||||
});
|
||||
} else {
|
||||
widgets.push(button(
|
||||
0.0,
|
||||
0.0,
|
||||
150.0,
|
||||
label,
|
||||
Act::ShaderPackOption(*idx),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut iter = widgets.into_iter();
|
||||
while let Some(mut first) = iter.next() {
|
||||
if let Some(second) = iter.next() {
|
||||
rows.push(Row::Buttons(first, Some(second)));
|
||||
} else {
|
||||
first.w = 310.0;
|
||||
rows.push(Row::Buttons(first, None));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
_ => {
|
||||
let _ = s;
|
||||
Vec::new()
|
||||
@@ -1599,6 +1784,9 @@ impl OptionsUi {
|
||||
fn layout(&mut self, s: &Settings, w: f32, h: f32) -> (Vec<Widget>, f32, f32, f32) {
|
||||
let mut out = Vec::new();
|
||||
let page = self.page();
|
||||
if matches!(page, Page::ShaderPacks | Page::ShaderPackOptions) {
|
||||
self.sync_shader_pack_config(s);
|
||||
}
|
||||
let cx = (w / 2.0).floor();
|
||||
if matches!(page, Page::Video | Page::Controls | Page::KeyBinds) {
|
||||
self.settings_search.x = cx - 100.0;
|
||||
@@ -1988,6 +2176,10 @@ impl OptionsUi {
|
||||
if matches!(page, Page::Video | Page::Controls) {
|
||||
top = 38.0;
|
||||
}
|
||||
if page == Page::ShaderPacks {
|
||||
// Two footer rows, as Iris's ShaderPackScreen.
|
||||
bottom = h - 57.0;
|
||||
}
|
||||
out.push(Widget {
|
||||
x: 0.0,
|
||||
y: if matches!(page, Page::Video | Page::Controls) {
|
||||
@@ -2076,12 +2268,34 @@ impl OptionsUi {
|
||||
out[list_start..].iter_mut().for_each(|w| w.list = true);
|
||||
let folder = match page {
|
||||
Page::Mods => Some(("Open Mod Folder", Act::OpenModFolder)),
|
||||
Page::ShaderPacks => {
|
||||
Some(("Open Shader Pack Folder", Act::OpenShaderPackFolder))
|
||||
Page::ShaderPackOptions => {
|
||||
Some(("Reset to Defaults", Act::ResetShaderPackOptions))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some((label, act)) = folder {
|
||||
if page == Page::ShaderPacks {
|
||||
// Iris: the folder and the pack's settings above Done.
|
||||
out.push(button(
|
||||
cx - 154.0,
|
||||
h - 51.0,
|
||||
150.0,
|
||||
Text::literal("Open Shader Pack Folder"),
|
||||
Act::OpenShaderPackFolder,
|
||||
));
|
||||
let settings = button(
|
||||
cx + 4.0,
|
||||
h - 51.0,
|
||||
150.0,
|
||||
Text::literal("Shader Pack Settings..."),
|
||||
Act::Push(Page::ShaderPackOptions),
|
||||
);
|
||||
out.push(if self.shader_pack_has_settings(s) {
|
||||
settings
|
||||
} else {
|
||||
inactive(settings)
|
||||
});
|
||||
out.push(done(h - 27.0));
|
||||
} else if let Some((label, act)) = folder {
|
||||
out.push(button(
|
||||
cx - 154.0,
|
||||
h - 27.0,
|
||||
@@ -2248,6 +2462,16 @@ impl OptionsUi {
|
||||
170.0,
|
||||
));
|
||||
}
|
||||
if let WKind::Button {
|
||||
act: Act::ShaderPackOption(i),
|
||||
..
|
||||
} = &wd.kind
|
||||
&& let Some(cfg) = &self.shader_pack_config
|
||||
&& let Some(opt) = cfg.options.get(*i)
|
||||
&& !opt.description.is_empty()
|
||||
{
|
||||
tooltip = Some(atlas.font.split(&Text::literal(&opt.description), 170.0));
|
||||
}
|
||||
}
|
||||
match &wd.kind {
|
||||
WKind::Button { label, active, act } => {
|
||||
@@ -2288,6 +2512,31 @@ impl OptionsUi {
|
||||
true,
|
||||
);
|
||||
}
|
||||
WKind::ShaderOptionSlider {
|
||||
label,
|
||||
value,
|
||||
index,
|
||||
} => {
|
||||
let dragging = self.dragging_shader_option == Some(*index);
|
||||
if hover
|
||||
&& let Some(cfg) = &self.shader_pack_config
|
||||
&& let Some(opt) = cfg.options.get(*index)
|
||||
&& !opt.description.is_empty()
|
||||
{
|
||||
tooltip = Some(atlas.font.split(&Text::literal(&opt.description), 170.0));
|
||||
}
|
||||
ui::slider(
|
||||
batch,
|
||||
atlas,
|
||||
wd.x,
|
||||
wd.y,
|
||||
wd.w,
|
||||
label,
|
||||
*value,
|
||||
hover || dragging,
|
||||
true,
|
||||
);
|
||||
}
|
||||
WKind::Text {
|
||||
text,
|
||||
color,
|
||||
@@ -2502,6 +2751,19 @@ impl OptionsUi {
|
||||
set_slider(opt, s, v);
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
if let Some(idx) = self.dragging_shader_option
|
||||
&& let Some(wd) = widgets.iter().find(|wd| {
|
||||
matches!(&wd.kind, WKind::ShaderOptionSlider { index, .. } if *index == idx)
|
||||
})
|
||||
{
|
||||
let v = ui::slider_value(wd.x, wd.w, x);
|
||||
self.edit_shader_pack(|cfg| {
|
||||
if let Some(opt) = cfg.options.get_mut(idx) {
|
||||
opt.set_slider_pos(v);
|
||||
}
|
||||
});
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
// Controller Binds: a click cancels the wait.
|
||||
@@ -2589,6 +2851,34 @@ impl OptionsUi {
|
||||
Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder),
|
||||
Act::Credits => events.push(Event::Credits),
|
||||
Act::CopyAgentDetails => events.push(Event::CopyAgentDetails),
|
||||
Act::ShaderPackProfile => {
|
||||
self.edit_shader_pack(|cfg| cfg.cycle_profile(false));
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Act::ShaderPackSubscreen(sub) => {
|
||||
if let Some(cfg) = &mut self.shader_pack_config {
|
||||
cfg.active_screen = Some(sub);
|
||||
}
|
||||
self.scroll = 0.0;
|
||||
}
|
||||
Act::ShaderPackBackScreen => {
|
||||
if let Some(cfg) = &mut self.shader_pack_config {
|
||||
cfg.active_screen = None;
|
||||
}
|
||||
self.scroll = 0.0;
|
||||
}
|
||||
Act::ShaderPackOption(i) => {
|
||||
self.edit_shader_pack(|cfg| {
|
||||
if let Some(opt) = cfg.options.get_mut(i) {
|
||||
opt.cycle(false);
|
||||
}
|
||||
});
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Act::ResetShaderPackOptions => {
|
||||
self.edit_shader_pack(PackConfig::reset_all);
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Act::None => {}
|
||||
}
|
||||
}
|
||||
@@ -2599,6 +2889,16 @@ impl OptionsUi {
|
||||
set_slider(opt, s, v);
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
WKind::ShaderOptionSlider { index, .. } => {
|
||||
self.dragging_shader_option = Some(index);
|
||||
let v = ui::slider_value(wd.x, wd.w, x);
|
||||
self.edit_shader_pack(|cfg| {
|
||||
if let Some(opt) = cfg.options.get_mut(index) {
|
||||
opt.set_slider_pos(v);
|
||||
}
|
||||
});
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
WKind::LanguageRow { code, .. } => {
|
||||
if self.language_choice.as_deref() == Some(code.as_str()) {
|
||||
events.extend(self.back(s));
|
||||
@@ -2627,7 +2927,7 @@ impl OptionsUi {
|
||||
}
|
||||
// AbstractSliderButton suppresses the press sound and plays once on
|
||||
// release, even if the pointer has left the widget or its value stayed.
|
||||
let slider = self.dragging.take().is_some();
|
||||
let slider = self.dragging.take().is_some() || self.dragging_shader_option.take().is_some();
|
||||
let graphics_slider = self.graphics.release();
|
||||
if slider || graphics_slider {
|
||||
vec![Event::ButtonClick]
|
||||
@@ -2683,6 +2983,14 @@ impl OptionsUi {
|
||||
/// Escape or Done: leave the current page, applying page results.
|
||||
pub fn back(&mut self, s: &mut Settings) -> Vec<Event> {
|
||||
let mut events = Vec::new();
|
||||
if self.page() == Page::ShaderPackOptions
|
||||
&& let Some(cfg) = &mut self.shader_pack_config
|
||||
&& cfg.active_screen.is_some()
|
||||
{
|
||||
cfg.active_screen = None;
|
||||
self.scroll = 0.0;
|
||||
return events;
|
||||
}
|
||||
let page = self.stack.pop().unwrap_or(Page::Main);
|
||||
self.scroll = 0.0;
|
||||
self.scrollbar_drag_y = None;
|
||||
@@ -2699,6 +3007,12 @@ impl OptionsUi {
|
||||
events.push(Event::Language(code));
|
||||
}
|
||||
}
|
||||
// Iris's ShaderPackScreen applies its edits on Done, so the
|
||||
// pack is rebuilt once, not on every click or slider step.
|
||||
Page::ShaderPackOptions if std::mem::take(&mut self.shader_pack_edited) => {
|
||||
self.save_shader_pack_config();
|
||||
events.push(Event::ReloadShaderPack);
|
||||
}
|
||||
Page::Packs => {
|
||||
// PackSelectionScreen.onClose: PackSelectionModel.commit.
|
||||
if let Some(p) = self.pack_screen.take()
|
||||
@@ -3126,6 +3440,74 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_pack_is_picked_and_its_settings_apply_on_done() {
|
||||
let atlas = atlas();
|
||||
let mut s = Settings::default();
|
||||
let mut ui = OptionsUi::default();
|
||||
let size = (480.0, 240.0);
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("horizon-shaderpack-drop-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
ui.shader_packs.poll(dir.clone());
|
||||
let sample = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../examples/shaderpacks/horizon-sample");
|
||||
assert_eq!(
|
||||
ui.drop_shader_pack(&mut s, &sample),
|
||||
None,
|
||||
"only on its page"
|
||||
);
|
||||
ui.show(Page::ShaderPacks);
|
||||
assert_eq!(ui.drop_shader_pack(&mut s, &sample), Some(Ok(())));
|
||||
assert_eq!(s.horizon.shader_pack, "horizon-sample");
|
||||
assert!(dir.join("horizon-sample/pack.toml").is_file());
|
||||
let again = ui.drop_shader_pack(&mut s, &sample).unwrap().unwrap_err();
|
||||
assert!(again.contains("already"), "{again}");
|
||||
|
||||
let click = |ui: &mut OptionsUi, s: &mut Settings, act: &dyn Fn(&Act) -> bool| {
|
||||
let w = ui
|
||||
.layout(s, size.0, size.1)
|
||||
.0
|
||||
.into_iter()
|
||||
.find(|w| matches!(&w.kind, WKind::Button { act: a, active: true, .. } if act(a)))
|
||||
.unwrap();
|
||||
ui.click(
|
||||
s,
|
||||
&atlas,
|
||||
w.x + 1.0,
|
||||
w.y + 1.0,
|
||||
size,
|
||||
[480, 240],
|
||||
false,
|
||||
false,
|
||||
)
|
||||
};
|
||||
click(&mut ui, &mut s, &|a| {
|
||||
*a == Act::Push(Page::ShaderPackOptions)
|
||||
});
|
||||
assert_eq!(ui.page(), Page::ShaderPackOptions);
|
||||
for _ in 0..3 {
|
||||
let events = click(&mut ui, &mut s, &|a| matches!(a, Act::ShaderPackOption(_)));
|
||||
assert!(!events.contains(&Event::ReloadShaderPack), "{events:?}");
|
||||
}
|
||||
let txt = dir.join("horizon-sample.txt");
|
||||
assert!(!txt.exists(), "nothing is saved before Done");
|
||||
let events = click(&mut ui, &mut s, &|a| *a == Act::Done);
|
||||
assert!(events.contains(&Event::ReloadShaderPack), "{events:?}");
|
||||
assert_eq!(ui.page(), Page::ShaderPacks);
|
||||
assert!(txt.is_file(), "Done saves the values");
|
||||
click(&mut ui, &mut s, &|a| {
|
||||
*a == Act::Push(Page::ShaderPackOptions)
|
||||
});
|
||||
let events = click(&mut ui, &mut s, &|a| *a == Act::Done);
|
||||
assert!(
|
||||
!events.contains(&Event::ReloadShaderPack),
|
||||
"no change: no reload"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_mods_page_toggles_mods_and_keeps_dev_and_invalid_entries_inactive() {
|
||||
let atlas = atlas();
|
||||
|
||||
@@ -804,11 +804,6 @@ impl SelectionModel {
|
||||
false
|
||||
}
|
||||
}
|
||||
/// Whether activating the entry asks first (`handlePackSelection`'s
|
||||
/// ConfirmScreen for an incompatible pack).
|
||||
pub fn needs_confirmation(&self, selected: bool, i: usize) -> bool {
|
||||
self.can_select(selected, i) && !self.unselected[i].compatible
|
||||
}
|
||||
/// `moveUp` / `moveDown` when allowed.
|
||||
pub fn move_by(&mut self, selected: bool, i: usize, up: bool) -> bool {
|
||||
let ok = if up {
|
||||
|
||||
@@ -1158,6 +1158,8 @@ pub struct ParticleEngine {
|
||||
starters: Vec<Starter>,
|
||||
/// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch).
|
||||
pub sounds: Vec<(&'static str, [f64; 3], f32, f32)>,
|
||||
/// How many of each type were made, for `horizon-ctl status`.
|
||||
made: std::collections::BTreeMap<&'static str, u64>,
|
||||
/// The item particles' sprites (`BreakingItemParticle`'s slime ball, snowball
|
||||
/// and cobweb models, resolved for the ground), one per model layer.
|
||||
pub item_sprites: HashMap<ParticleType, Vec<String>>,
|
||||
@@ -1183,6 +1185,7 @@ impl ParticleEngine {
|
||||
starters: Vec::new(),
|
||||
camera: [0.0; 3],
|
||||
sounds: Vec::new(),
|
||||
made: Default::default(),
|
||||
item_sprites: HashMap::new(),
|
||||
};
|
||||
let dir = root.join("assets/minecraft/particles");
|
||||
@@ -1449,9 +1452,14 @@ impl ParticleEngine {
|
||||
pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) {
|
||||
let seed = self.seeds.next_long();
|
||||
if let Some(particle) = self.make(options, p, v, seed) {
|
||||
*self.made.entry(options.ty.name()).or_default() += 1;
|
||||
self.pending.push(particle);
|
||||
}
|
||||
}
|
||||
/// How many particles of each type were made so far.
|
||||
pub fn made(&self) -> &std::collections::BTreeMap<&'static str, u64> {
|
||||
&self.made
|
||||
}
|
||||
/// Parity probes: seed the provider (`ParticleEngine.random`), level and
|
||||
/// `SpellParticle.RANDOM` generators.
|
||||
pub fn seed_randoms(&mut self, provider: i64, level: i64, spell: i64) {
|
||||
|
||||
@@ -384,21 +384,6 @@ impl Book {
|
||||
order,
|
||||
}
|
||||
}
|
||||
/// Which book a recipe id belongs to.
|
||||
pub fn book_of(&self, id: &str) -> Option<BookType> {
|
||||
let e = self.entries.iter().find(|e| e.id == id)?;
|
||||
Some(match e.category {
|
||||
Category::CraftingBuilding
|
||||
| Category::CraftingRedstone
|
||||
| Category::CraftingEquipment
|
||||
| Category::CraftingMisc => BookType::Crafting,
|
||||
Category::FurnaceFood | Category::FurnaceBlocks | Category::FurnaceMisc => {
|
||||
BookType::Furnace
|
||||
}
|
||||
Category::BlastBlocks | Category::BlastMisc => BookType::BlastFurnace,
|
||||
Category::SmokerFood => BookType::Smoker,
|
||||
})
|
||||
}
|
||||
/// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients
|
||||
/// (`craftingRequirements`) can all be found in `stock`.
|
||||
pub fn can_craft(&self, entry: &Entry, stock: &crate::menu::place::Stacked) -> bool {
|
||||
|
||||
@@ -750,12 +750,6 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag {
|
||||
)
|
||||
}))
|
||||
}
|
||||
/// The heightmaps a ClientboundLevelChunkPacketData carries (the types with
|
||||
/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES),
|
||||
/// as (network id, packed longs) in Heightmap.Types order.
|
||||
pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec<i64>)> {
|
||||
client_heightmaps_in(&chunk.sections, tables, MIN_Y, SECTIONS as i32 * 16)
|
||||
}
|
||||
/// The client heightmaps of a column's sections, in a level from `min_y`,
|
||||
/// `height` blocks high.
|
||||
pub fn client_heightmaps_in(
|
||||
|
||||
@@ -78,7 +78,6 @@ pub const RESONANCE: [&str; 15] = [
|
||||
];
|
||||
pub const SHRIEK: &str = "minecraft:shriek";
|
||||
pub const TENDRILS_CLICKING: &str = "minecraft:sculk_sensor_tendrils_clicking";
|
||||
pub const NO_VIBRATION_FREQUENCY: i32 = 0;
|
||||
|
||||
/// `VibrationSystem.getGameEventFrequency`.
|
||||
pub fn frequency(event: &str) -> i32 {
|
||||
@@ -567,10 +566,6 @@ pub struct WardenSpawnTracker {
|
||||
}
|
||||
impl WardenSpawnTracker {
|
||||
pub const MAX_WARNING_LEVEL: i32 = 4;
|
||||
/// Blocks around a shrieker within which players are warned.
|
||||
pub const PLAYER_SEARCH_RADIUS: f64 = 16.0;
|
||||
/// `AABB.ofSize(centre, 48, 48, 48)` for an existing warden.
|
||||
pub const WARNING_CHECK_DIAMETER: f64 = 48.0;
|
||||
const DECREASE_EVERY: i32 = 12000;
|
||||
const INCREASE_COOLDOWN: i32 = 200;
|
||||
pub fn tick(&mut self) {
|
||||
|
||||
@@ -81,10 +81,6 @@ pub fn sound_source(event: &str) -> usize {
|
||||
index("master")
|
||||
}
|
||||
}
|
||||
/// Volume multiplier of an event's source (master applied separately).
|
||||
pub fn event_volume(event: &str) -> f32 {
|
||||
source_volume(sound_source(event))
|
||||
}
|
||||
/// Volume multiplier of a sound source by index.
|
||||
pub fn source_volume(i: usize) -> f32 {
|
||||
if i == 0 {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,108 @@
|
||||
// Horizon shader pack prelude, api 2 additions (docs/shader-packs.md): placed
|
||||
// after the api 1 prelude before the stages of an `api = 2` pack, so api 1
|
||||
// packs keep every name they may have declared themselves.
|
||||
struct FrameExt {
|
||||
previous_view: mat4x4<f32>,
|
||||
previous_projection: mat4x4<f32>,
|
||||
shadow_view: mat4x4<f32>,
|
||||
shadow_projection: mat4x4<f32>,
|
||||
shadow_inverse_view: mat4x4<f32>,
|
||||
shadow_inverse_projection: mat4x4<f32>,
|
||||
// xyz: previous camera world position, w: frame delta time (seconds)
|
||||
previous_camera: vec4<f32>,
|
||||
// x: shadow map resolution, y: shadow distance (blocks), z: 0,
|
||||
// w: 1 while the shadow map is drawn this frame, else 0
|
||||
shadow_params: vec4<f32>,
|
||||
// x: eye block light (0..240), y: eye sky light (0..240), z: smoothed
|
||||
// rain (0..1), w: 0
|
||||
environment: vec4<f32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(6) var<uniform> frame_ext: FrameExt;
|
||||
@group(0) @binding(7) var scene_normal: texture_2d<f32>;
|
||||
@group(0) @binding(8) var scene_material: texture_2d<f32>;
|
||||
@group(0) @binding(9) var opaque_depth: texture_depth_2d;
|
||||
@group(0) @binding(10) var shadow_depth: texture_depth_2d;
|
||||
@group(0) @binding(11) var shadow_sampler: sampler_comparison;
|
||||
@group(0) @binding(12) var noise_texture: texture_2d<f32>;
|
||||
@group(0) @binding(13) var repeat_sampler: sampler;
|
||||
|
||||
// The opaque world's depth at `uv` (before translucent water and stained glass).
|
||||
fn opaque_depth_at(uv: vec2<f32>) -> f32 {
|
||||
return textureSampleLevel(opaque_depth, nearest_sampler, uv, 0);
|
||||
}
|
||||
|
||||
// World-space surface normal at `uv` from the G-buffer (or reconstructed from depth).
|
||||
fn world_normal_at(uv: vec2<f32>) -> vec3<f32> {
|
||||
let encoded = textureSampleLevel(scene_normal, nearest_sampler, uv, 0.0);
|
||||
if encoded.w > 0.001 {
|
||||
return normalize(encoded.xyz * 2.0 - 1.0);
|
||||
}
|
||||
let step_uv = frame.resolution.zw;
|
||||
let d0 = depth_at(uv);
|
||||
let p0 = world_offset(uv, d0);
|
||||
let px = world_offset(uv + vec2(step_uv.x, 0.0), depth_at(uv + vec2(step_uv.x, 0.0))) - p0;
|
||||
let py = world_offset(uv + vec2(0.0, step_uv.y), depth_at(uv + vec2(0.0, step_uv.y))) - p0;
|
||||
let n = cross(py, px);
|
||||
let len = length(n);
|
||||
if len > 1e-6 {
|
||||
return n / len;
|
||||
}
|
||||
return vec3(0.0, 1.0, 0.0);
|
||||
}
|
||||
// G-buffer material data at `uv`: r = block light (0..1), g = sky light (0..1),
|
||||
// b = water/translucent mask (0..1), a = roughness (0..1).
|
||||
fn material_at(uv: vec2<f32>) -> vec4<f32> {
|
||||
return textureSampleLevel(scene_material, nearest_sampler, uv, 0.0);
|
||||
}
|
||||
// Reproject a camera-relative world position into previous-frame UV and clip depth.
|
||||
fn reproject_uv(world_rel: vec3<f32>) -> vec3<f32> {
|
||||
let camera_delta = frame.camera_position.xyz - frame_ext.previous_camera.xyz;
|
||||
let prev_rel = world_rel + camera_delta;
|
||||
let clip = frame_ext.previous_projection * (frame_ext.previous_view * vec4(prev_rel, 1.0));
|
||||
if clip.w <= 1e-5 {
|
||||
return vec3(-1.0);
|
||||
}
|
||||
let ndc = clip.xyz / clip.w;
|
||||
return vec3(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5, ndc.z);
|
||||
}
|
||||
// Sample the directional sun/moon shadow map with 5-tap PCF and normal offset bias.
|
||||
// Returns 1.0 in full light and 0.0 in full shadow.
|
||||
fn sample_shadow(world_rel: vec3<f32>, world_normal: vec3<f32>) -> f32 {
|
||||
if frame_ext.shadow_params.w <= 0.001 {
|
||||
return 1.0;
|
||||
}
|
||||
let dist = length(world_rel);
|
||||
let max_dist = max(frame_ext.shadow_params.y, 16.0);
|
||||
if dist >= max_dist {
|
||||
return 1.0;
|
||||
}
|
||||
let light_dir = normalize(select(frame.moon.xyz, frame.sun.xyz, frame.sun.y >= -0.05));
|
||||
let ndotl = max(dot(world_normal, light_dir), 0.0);
|
||||
let bias_pos = world_rel + world_normal * (0.06 + 0.12 * (1.0 - ndotl));
|
||||
let light_clip = frame_ext.shadow_projection * (frame_ext.shadow_view * vec4(bias_pos, 1.0));
|
||||
let ndc = light_clip.xyz / max(light_clip.w, 1e-5);
|
||||
let shadow_uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
|
||||
if any(shadow_uv < vec2(0.002)) || any(shadow_uv > vec2(0.998)) || ndc.z <= 0.0 || ndc.z >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let texel = 1.0 / max(frame_ext.shadow_params.x, 512.0);
|
||||
let ref_z = clamp(ndc.z + 0.0008, 0.0, 1.0);
|
||||
var sum = textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv, ref_z);
|
||||
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(texel, 0.0), ref_z);
|
||||
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(texel, 0.0), ref_z);
|
||||
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(0.0, texel), ref_z);
|
||||
sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(0.0, texel), ref_z);
|
||||
let fade = smoothstep(max_dist, max_dist * 0.82, dist);
|
||||
return mix(1.0, sum * 0.2, fade * frame_ext.shadow_params.w);
|
||||
}
|
||||
|
||||
// ACES fitted filmic tonemapping curve (linear HDR -> linear 0..1).
|
||||
fn aces_tonemap(x: vec3<f32>) -> vec3<f32> {
|
||||
let a = 2.51;
|
||||
let b = 0.03;
|
||||
let c = 2.43;
|
||||
let d = 0.59;
|
||||
let e = 0.14;
|
||||
return clamp((x * (a * x + b)) / (x * (c * x + d) + e), vec3(0.0), vec3(1.0));
|
||||
}
|
||||
@@ -317,9 +317,6 @@ impl TabList {
|
||||
self.visible = visible;
|
||||
}
|
||||
}
|
||||
pub fn is_visible(&self) -> bool {
|
||||
self.visible
|
||||
}
|
||||
/// `reset`.
|
||||
pub fn reset(&mut self) {
|
||||
self.header = None;
|
||||
|
||||
@@ -483,9 +483,6 @@ impl Text {
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn char_count(&self) -> usize {
|
||||
self.spans.iter().map(|s| s.text.chars().count()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// The style fields of a component's JSON.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user