Merge remote-tracking branch 'upstream/main' into fix/leave-game-statistic

# Conflicts:
#	tools/lan_e2e.py
This commit is contained in:
Carlos Nunez
2026-10-26 13:33:28 -04:00
290 changed files with 5647 additions and 17045 deletions
-1
View File
@@ -2,7 +2,6 @@
target/
.local/
**/node_modules/
website/
benchmarks/
packs/
mods/
+1 -1
View File
@@ -2,5 +2,5 @@
# where Git for Windows' core.autocrlf would check them out with CRLF.
docs/launcher-commands.md text eol=lf
docs/horizon-ctl-commands.md text eol=lf
website/src/tokens.css text eol=lf
crates/horizon-theme/tokens.css text eol=lf
docs/api/*-reference.md text eol=lf
+36
View File
@@ -73,6 +73,42 @@ jobs:
run: |
cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack
cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack
# The launcher is its own workspace (launcher/Cargo.toml), so verify's cargo runs never build it. A pull request that
# changes it or a crate it builds is checked here, and so is every push to main: two pull requests can each pass
# alone and break it together (#2059 and the registry ratings did, 2026-10-26).
launcher:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Does this pull request change the launcher or a crate it builds?
if: github.event_name == 'pull_request'
id: launcher
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: python3 tools/ci/rust_changes.py --launcher "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_OUTPUT"
- name: Install Rust and the headers GPUI links against
if: steps.launcher.outputs.required != 'false'
run: |
sudo apt-get update && sudo apt-get install -y --no-install-recommends libxkbcommon-x11-dev libwayland-dev \
libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev libudev-dev
rustup toolchain install stable --profile minimal --component rustfmt --component clippy
- uses: Swatinem/rust-cache@v2
if: steps.launcher.outputs.required != 'false'
with:
workspaces: launcher
shared-key: launcher
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Check the launcher's formatting, lint and tests
if: steps.launcher.outputs.required != 'false'
working-directory: launcher
run: |
cargo +stable fmt --check
cargo +stable clippy --all-targets --locked -- -D warnings
cargo +stable test --locked --lib
# Most pull requests leave the harnesses to parity-main, which runs them on main a batch of merges at a time
# (.github/workflows/parity-main.yml; releases wait for it). A pull request still runs them itself when it changes
# a harness, an oracle, a probe or the runner, or carries the run-parity label (run-parity.yml, when it is added).
+2 -1
View File
@@ -54,7 +54,8 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
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/`.
`docs/`, `.github/workflows/`. The website (playhorizon.dev) is the private ludovic111/horizon-site: its build
reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` and `crates/horizon-theme/tokens.css` from main.
## Build and test fast
+2 -2
View File
@@ -4,8 +4,8 @@ Thanks for helping. Horizon is Minecraft: Java Edition 26.3 rewritten in Rust, a
everything is that **it plays exactly like vanilla**. This page is the short version of how we work; questions are
welcome on [Discord](https://discord.gg/HcTeMZxe5E).
This repository holds the game, the launcher and the website, plus the tools, tests and docs that build, check and
release them. Anything else (videos, Discord and other community material) lives elsewhere.
This repository holds the game and the launcher, plus the tools, tests and docs that build, check and release them.
The website (playhorizon.dev) is built in a separate repository from this one's README, `docs/api/` and roadmap. Anything else (videos, Discord and other community material) lives elsewhere.
**Where to start: [playhorizon.dev/hub](https://playhorizon.dev/hub).** It shows what is being done now and next
([ROADMAP.md](ROADMAP.md) in the repository), the work board, good first tasks, and the forms to report a bug or
Generated
+9
View File
@@ -1368,6 +1368,7 @@ dependencies = [
"horizon-core",
"horizon-dualsense",
"horizon-friends",
"horizon-hdr",
"horizon-mods",
"horizon-protocol",
"horizon-server-files",
@@ -1426,6 +1427,14 @@ dependencies = [
"spake2",
]
[[package]]
name = "horizon-hdr"
version = "0.1.0"
dependencies = [
"ash",
"wgpu",
]
[[package]]
name = "horizon-mod-sdk"
version = "0.1.0"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
resolver = "2"
[workspace.package]
+8 -4
View File
@@ -134,7 +134,7 @@ Better tools for mod makers: a test runner that needs no game window, templates
`cargo horizon-mod test` runs a mod's test scripts against a fake game snapshot ([#1816](https://github.com/ludovic111/horizon/issues/1816)) and, for server mods, scripted server events ([#1837](https://github.com/ludovic111/horizon/issues/1837)); the content template and the guides are merged ([#1859](https://github.com/ludovic111/horizon/issues/1859), [#1810](https://github.com/ludovic111/horizon/issues/1810), [docs/api/stability.md](docs/api/stability.md)). Left: templates for hud, server and machine mods, typed wrappers in the SDK, a frozen 0.1 compatibility mod that every runtime must load, a CI check that fails when a stable reference entry is removed without a new major version, and the SDK on crates.io once the API is stable.
More: [website/docs/test-a-mod.md](website/docs/test-a-mod.md)
More: [https://playhorizon.dev/docs/test-a-mod](https://playhorizon.dev/docs/test-a-mod)
</details>
@@ -310,7 +310,7 @@ Horizon should run well on small machines: integrated graphics, the Steam Deck,
Partly done: an opt-in 60 FPS cap with fewer workers on battery, Far Detail Reduced for integrated GPUs and animated textures on the GPU (both shipped). Left: measured targets and fixes per class of machine (memory use, worker counts, startup) on a Steam Deck, old Intel and Apple Silicon Macs and 8 GB computers, reported on the Benchmarks page.
More: [docs/benchmark.md](docs/benchmark.md) · [website/docs/performance.md](website/docs/performance.md)
More: [docs/benchmark.md](docs/benchmark.md) · [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
</details>
@@ -600,7 +600,9 @@ You can port a mod to Horizon with your own AI agent on your own computer. Horiz
<details><summary>Technical</summary>
A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide ([website/docs/agents.md](website/docs/agents.md), [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off.
A player runs their own agent locally with `horizon-ctl` and the MCP servers ([docs/agent-control.md](docs/agent-control.md)), `cargo horizon-mod`, `horizon-port-pack` and the parity harnesses as the check. Horizon writes the guide (playhorizon.dev/docs/agents, [docs/modpacks.md](docs/modpacks.md)) and runs no agents, accounts or keys for players. The No AI switch turns all of it off.
More: [https://playhorizon.dev/docs/agents](https://playhorizon.dev/docs/agents)
</details>
@@ -936,7 +938,9 @@ Run Horizon's built-in benchmark and share the report: every new computer makes
<details><summary>Technical</summary>
`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark <report>` shows what would be sent and uploads it ([website/docs/performance.md](website/docs/performance.md)). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711).
`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark <report>` shows what would be sent and uploads it (playhorizon.dev/docs/performance). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711).
More: [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance)
</details>
+3
View File
@@ -262,6 +262,9 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
format!("{}: {text}", if error { "error" } else { "feedback" })
}
Output::Command { line } => format!("command: /{line}"),
Output::QuietCommands { lines, .. } => {
format!("{} quiet command(s)", lines.len())
}
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
+10 -7
View File
@@ -1031,19 +1031,22 @@ pub struct ItemModels {
}
impl ItemModels {
pub fn components(&self, stack: &StackView) -> Components {
let mut out = self
.prototypes
.get(&stack.item)
.cloned()
.unwrap_or_default();
/// The stack's components: its item's defaults with the stack's patch on top. A stack
/// with no patch (most stacks a screen draws) borrows the defaults instead of copying them.
pub fn components(&self, stack: &StackView) -> std::borrow::Cow<'_, Components> {
static NONE: Components = BTreeMap::new();
let prototype = self.prototypes.get(&stack.item).unwrap_or(&NONE);
if stack.patch.is_empty() {
return std::borrow::Cow::Borrowed(prototype);
}
let mut out = prototype.clone();
for (key, value) in &stack.patch {
match value {
Some(v) => out.insert(key.clone(), v.clone()),
None => out.remove(key),
};
}
out
std::borrow::Cow::Owned(out)
}
/// `ItemModelResolver.updateForTopItem`.
pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem {
+1
View File
@@ -12,6 +12,7 @@ horizon-assets = { path = "../horizon-assets" }
horizon-core = { path = "../horizon-core" }
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
horizon-threads = { path = "../horizon-threads" }
horizon-hdr = { path = "../horizon-hdr" }
horizon-world = { path = "../horizon-world" }
horizon-protocol = { path = "../horizon-protocol" }
# server.properties, eula.txt and the user lists, shared with horizon-server.
@@ -0,0 +1,48 @@
use horizon_client::{
Result,
item_data::StackData,
items::{ItemStack, Items},
};
use horizon_world::nbt::Tag;
use serde_json::Value;
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
};
pub fn main() -> Result<()> {
let args: Vec<_> = crate::args().collect();
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
let items = Items::catalog(&root)?;
let mut out = BufWriter::new(File::create(&args[2])?);
for line in BufReader::new(File::open(&args[1])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let mut stack = ItemStack::new(
row["item"].as_str().unwrap(),
row["count"].as_u64().unwrap() as u32,
);
match row["tool"].as_str().unwrap() {
"default" => {}
mode => {
let mut data = StackData::default();
let tool = if mode == "implicit" {
Tag::compound([] as [(&str, Tag); 0])
} else {
Tag::compound([(
"can_destroy_blocks_in_creative",
Tag::Byte(i8::from(mode == "allow")),
)])
};
data.set_other("minecraft:tool", Some(tool));
stack.extra = Some(Box::new(data));
}
}
writeln!(
out,
"{}",
items.can_destroy_block(Some(&stack), row["creative"].as_bool().unwrap())
)?;
}
Ok(())
}
@@ -27,6 +27,7 @@ mod chat_screen_fixture;
mod cloud_fixture;
mod command_parse_fixture;
mod container_screen_probe;
mod creative_mining_probe;
mod creative_search_fixture;
mod cushion_placement_probe;
mod emitter_particles_probe;
@@ -84,6 +85,7 @@ mod sound_engine_fixture;
mod sound_event_fixture;
mod spawn_rules_fixture;
mod sprint_probe;
mod squid_client_probe;
mod subtitle_fixture;
mod tab_list_fixture;
mod team_rules_fixture;
@@ -108,6 +110,8 @@ probes! {
block_transform_fixture,
breaking_fixture,
camera_probe,
squid_client_probe,
creative_mining_probe,
cushion_placement_probe,
cauldron_fixture,
chat_screen_fixture,
@@ -7,7 +7,7 @@ use horizon_client::{
biome::{BiomeInfo, Biomes, GrassModifier},
blocks::BlockFacts,
chunk::{Chunk, Light, MIN_Y, index},
mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
mesher::{EMISSION_BITS, MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
models,
};
use horizon_core::biome::BiomeZoom;
@@ -161,7 +161,15 @@ fn scene(
.iter()
.map(|v| {
let ([x, y, z], [u, w]) = (v.pos, v.uv());
json!([x, y, z, u, w, argb(v.color), light_coords(v.light)])
json!([
x,
y,
z,
u,
w,
argb(v.color | EMISSION_BITS),
light_coords(v.light)
])
})
.collect();
quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices}));
@@ -0,0 +1,51 @@
use horizon_client::{
Result,
mobs::{Mob, MobTypes, aquatic},
};
use horizon_core::geometry::Vec3;
use serde_json::Value;
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
sync::Arc,
};
pub fn main() -> Result<()> {
let args: Vec<_> = crate::args().collect();
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
let types = MobTypes::load(&root)?;
let mut out = BufWriter::new(File::create(&args[2])?);
for line in BufReader::new(File::open(&args[1])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let kind = Arc::new(
types.types[&format!("minecraft:{}", row["species"].as_str().unwrap())].clone(),
);
let mut mob = Mob::new(1, kind, Vec3::ZERO, 0.0);
mob.fluids.in_water = row["water"].as_bool().unwrap();
mob.velocity = Vec3::new(
row["x"].as_f64().unwrap(),
row["y"].as_f64().unwrap(),
row["z"].as_f64().unwrap(),
);
mob.body_yaw = row["body"].as_f64().unwrap() as f32;
for (i, value) in row["v"].as_array().unwrap().iter().enumerate() {
mob.anim.v[i] = value.as_f64().unwrap() as f32;
}
if row["reset"].as_bool().unwrap() {
aquatic::squid_cycle_event(&mut mob);
}
let velocity = mob.velocity;
aquatic::squid_client_step(&mut mob);
assert_eq!(
velocity, mob.velocity,
"a remote animation must preserve packet velocity"
);
write!(out, "{:08x}", mob.body_yaw.to_bits())?;
for value in &mob.anim.v[..6] {
write!(out, " {:08x}", value.to_bits())?;
}
writeln!(out)?;
}
Ok(())
}
+74 -3
View File
@@ -58,7 +58,10 @@ enum Animate {
BubbleColumn {
drag: bool,
},
Fire,
/// `BaseFireBlock` (`SoulFireBlock.canBurn` is always true).
Fire {
soul: bool,
},
/// An active sculk sensor.
SculkSensor,
/// Potent sulfur that is not dry.
@@ -140,7 +143,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
"bubble_column" => Animate::BubbleColumn {
drag: prop("drag").as_deref() == Some("true"),
},
"fire" | "soul_fire" => Animate::Fire,
"fire" => Animate::Fire { soul: false },
"soul_fire" => Animate::Fire { soul: true },
"dried_ghast" => Animate::DriedGhast {
waterlogged: prop("waterlogged").as_deref() == Some("true"),
},
@@ -190,6 +194,8 @@ pub struct AnimateTables {
power_transmitter: Vec<bool>,
/// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil).
dried_ghast_sounds: Vec<bool>,
/// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged).
burnable: Vec<bool>,
/// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`).
ambient: Vec<Vec<(T, f32)>>,
}
@@ -220,6 +226,21 @@ impl AnimateTables {
})
.collect()
};
let behaviour: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("block-behaviours.json"))?)?;
let ignite_odds = behaviour["fire"]["igniteOdds"].as_object();
let burnable = (0..registry.len() as u32)
.map(|id| {
// FireBlock.getIgniteOdds: a waterlogged state never burns.
registry.state(BlockStateId(id)).is_some_and(|s| {
s.properties.get("waterlogged").map(String::as_str) != Some("true")
&& ignite_odds
.and_then(|m| m.get(s.name.as_str()))
.and_then(serde_json::Value::as_i64)
.is_some_and(|odds| odds > 0)
})
})
.collect();
let mut ambient = vec![Vec::new(); biomes.list.len()];
for (name, &id) in &biomes.index {
let path = root.join(format!(
@@ -248,6 +269,7 @@ impl AnimateTables {
power_provider: by_state("minecraft:enchantment_power_provider"),
power_transmitter: by_state("minecraft:enchantment_power_transmitter"),
dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"),
burnable,
ambient,
})
}
@@ -1103,7 +1125,7 @@ fn block_animate_tick(
}
}
}
Animate::Fire => {
Animate::Fire { soul } => {
let r = engine.random();
if next_int(r, 24) == 0 {
let (volume, pitch) = (1.0 + r.next_float(), r.next_float() * 0.7 + 0.3);
@@ -1115,6 +1137,55 @@ fn block_animate_tick(
pitch,
);
}
// BaseFireBlock.animateTick: three large smoke above the fire, or
// two at each burnable neighbour's face when nothing burnable or
// sturdy supports it (SoulFireBlock.canBurn is always true).
let can_burn = |p: [i32; 3]| {
soul || tables
.burnable
.get(ctx.state(p).0 as usize)
.copied()
.unwrap_or(false)
};
let below = [pos[0], pos[1] - 1, pos[2]];
let sturdy = ctx.facts.get(ctx.state(below)).sturdy_full & (1 << 1) != 0;
if !can_burn(below) && !sturdy {
// (neighbour, coordinate axis, face at the axis' high end): the
// west, east, north, south and above faces, in vanilla order.
for (at, axis, high) in [
([pos[0] - 1, pos[1], pos[2]], 0usize, false),
([pos[0] + 1, pos[1], pos[2]], 0, true),
([pos[0], pos[1], pos[2] - 1], 2, false),
([pos[0], pos[1], pos[2] + 1], 2, true),
([pos[0], pos[1] + 1, pos[2]], 1, true),
] {
if !can_burn(at) {
continue;
}
for _ in 0..2 {
let r = engine.random();
let d = [r.next_double(), r.next_double(), r.next_double()];
let mut p = [fx + d[0], fy + d[1], fz + d[2]];
// The face coordinate hugs the edge: `* 0.1F` (float).
p[axis] = if high {
f64::from(pos[axis]) + 1.0 - d[axis] * f64::from(0.1f32)
} else {
f64::from(pos[axis]) + d[axis] * f64::from(0.1f32)
};
add(engine, T::LargeSmoke, p, [0.0; 3]);
}
}
} else {
for _ in 0..3 {
let r = engine.random();
let p = [
fx + r.next_double(),
fy + r.next_double() * 0.5 + 0.5,
fz + r.next_double(),
];
add(engine, T::LargeSmoke, p, [0.0; 3]);
}
}
}
}
}
+18 -7
View File
@@ -664,7 +664,9 @@ pub fn canonical(tag: &Tag) -> Option<Tag> {
}
"minecraft:trial_spawner" => {
// `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional
// and defaulted by vanilla; they are kept as loaded.
// and defaulted by vanilla; they are kept as loaded. No `spawn_data` is
// added: an absent one loads as Optional.empty and is not stored, and
// an empty entity would keep the spawner from ever picking a mob.
if let Tag::Compound(c) = tag {
for (k, v) in c {
let key = k.to_string_lossy();
@@ -676,12 +678,6 @@ pub fn canonical(tag: &Tag) -> Option<Tag> {
}
}
}
if !f.out.contains_key(&"spawn_data".into()) {
f.put(
"spawn_data",
Tag::compound([("entity", Tag::Compound(Compound::new()))]),
);
}
}
"minecraft:vault" => {
// `VaultConfig.DEFAULT` (when the config is absent): the trial key and the
@@ -827,6 +823,21 @@ mod tests {
canonical(&snbt(s)).expect("known type")
}
#[test]
fn a_trial_spawner_without_spawn_data_saves_none() {
let fresh = canon(
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#,
);
assert_eq!(fresh.get("spawn_data"), None);
let picked = canon(
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#,
);
assert_eq!(
picked.get("spawn_data"),
Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#))
);
}
#[test]
fn every_type_has_defaults() {
for id in TYPES.iter().chain(NEWEST.iter()) {
+4
View File
@@ -161,6 +161,9 @@ pub struct Chunk {
/// Structure starts reaching into this chunk (`structures.References`):
/// structure id and the start's chunk.
pub structure_refs: Vec<(Arc<str>, (i32, i32))>,
/// The starts generation made in this chunk (`structures.starts`), saved
/// with the state their placement has reached by then.
pub structure_starts: Vec<Arc<horizon_world::worldgen::structure::start::StructureStart>>,
}
impl Chunk {
pub fn empty(x: i32, z: i32) -> Self {
@@ -178,6 +181,7 @@ impl Chunk {
block_entities: Vec::new(),
block_names: Vec::new(),
structure_refs: Vec::new(),
structure_starts: Vec::new(),
postprocess: Vec::new(),
saved: None,
entities: Vec::new(),
+102 -2
View File
@@ -94,9 +94,66 @@ pub enum BlockEntity {
Beehive(Box<crate::beehive::Beehive>),
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
CommandBlock(Box<crate::command_block::CommandBlock>),
/// `CampfireBlockEntity` of campfires and soul campfires.
Campfire(Box<Campfire>),
/// `SkullBlockEntity` of every skull and head block.
Skull(Skull),
}
/// `CampfireBlockEntity`: four cooking slots, each with its
/// `cookingProgress` and `cookingTime` (the recipe's).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Campfire {
pub items: [Option<ItemStack>; 4],
pub progress: [i32; 4],
pub total: [i32; 4],
}
impl Campfire {
/// `placeFood`'s slot: the first empty one, given the item's
/// `campfire_cooking` time; it takes one item of `held`.
pub fn place_food(&mut self, held: &mut ItemStack, cooking_time: i32) -> bool {
let Some(slot) = self.items.iter().position(Option::is_none) else {
return false;
};
self.total[slot] = cooking_time;
self.progress[slot] = 0;
self.items[slot] = Some(ItemStack {
count: 1,
..held.clone()
});
held.count = held.count.saturating_sub(1);
true
}
/// `cookTick` (lit): each item's progress rises by one; the slots whose
/// progress reached their cooking time give up their item (the caller
/// drops its result).
pub fn cook_tick(&mut self) -> Vec<(usize, ItemStack)> {
let mut done = Vec::new();
for i in 0..4 {
if self.items[i].is_none() {
continue;
}
self.progress[i] += 1;
if self.progress[i] >= self.total[i]
&& let Some(item) = self.items[i].take()
{
done.push((i, item));
}
}
done
}
/// `cooldownTick` (unlit): the progress falls by two, no lower than 0.
/// Whether anything changed (`setChanged`).
pub fn cooldown_tick(&mut self) -> bool {
let mut changed = false;
for i in 0..4 {
if self.progress[i] > 0 {
changed = true;
self.progress[i] = (self.progress[i] - 2).clamp(0, self.total[i]);
}
}
changed
}
}
/// `SkullBlockEntity`: the player profile the head shows (kept as loaded:
/// a compound, or a string when it names a player only), the note block
/// sound and `custom_name`.
@@ -315,6 +372,9 @@ impl BlockEntity {
if name == "minecraft:brewing_stand" {
return Some(Self::Brewing(Box::new(crate::brewing::BrewingStand::new())));
}
if name == "minecraft:campfire" || name == "minecraft:soul_campfire" {
return Some(Self::Campfire(Box::default()));
}
let size = match name {
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
n if n.ends_with("copper_chest") => 27,
@@ -352,6 +412,7 @@ impl BlockEntity {
Self::Beehive(_) => "minecraft:beehive",
Self::CommandBlock(_) => "minecraft:command_block",
Self::Skull(_) => "minecraft:skull",
Self::Campfire(_) => "minecraft:campfire",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -373,6 +434,7 @@ impl BlockEntity {
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
Self::Campfire(c) => c.items.iter().flatten().cloned().collect(),
}
}
pub fn slots(&self) -> &[Option<ItemStack>] {
@@ -393,7 +455,9 @@ impl BlockEntity {
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => &[],
| Self::CommandBlock(_)
// Not a Container (only Clearable): hoppers don't reach in.
| Self::Campfire(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -414,7 +478,8 @@ impl BlockEntity {
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => &mut [],
| Self::CommandBlock(_)
| Self::Campfire(_) => &mut [],
}
}
}
@@ -706,6 +771,41 @@ mod tests {
use super::*;
use horizon_core::random::{LegacyRandom, RandomSource};
#[test]
fn campfire_slots_take_food_cook_it_and_cool_down() {
let mut c = Campfire::default();
let mut beef = ItemStack::new("minecraft:beef", 2);
// placeFood: the first free slot, one item, its recipe's time.
assert!(c.place_food(&mut beef, 600));
assert_eq!(beef.count, 1);
assert_eq!(c.items[0].as_ref().map(|s| s.count), Some(1));
assert_eq!((c.progress[0], c.total[0]), (0, 600));
let mut fish = ItemStack::new("minecraft:cod", 1);
assert!(c.place_food(&mut fish, 3));
assert_eq!(c.items[1].as_ref().map(|s| &*s.item), Some("minecraft:cod"));
// cookTick: the cod is done on its third tick, the beef keeps cooking.
assert!(c.cook_tick().is_empty());
assert!(c.cook_tick().is_empty());
let done = c.cook_tick();
assert_eq!(done.len(), 1);
assert_eq!((done[0].0, &*done[0].1.item), (1, "minecraft:cod"));
assert!(c.items[1].is_none());
assert_eq!(c.progress[0], 3);
// cooldownTick: two a tick, never below zero.
assert!(c.cooldown_tick());
assert_eq!(c.progress[0], 1);
assert!(c.cooldown_tick());
assert_eq!(c.progress[0], 0);
// Full: four slots, no fifth.
for _ in 0..3 {
let mut more = ItemStack::new("minecraft:potato", 1);
assert!(c.place_food(&mut more, 600));
}
let mut fifth = ItemStack::new("minecraft:potato", 1);
assert!(!c.place_food(&mut fifth, 600));
assert_eq!(fifth.count, 1);
}
/// A whole amount pays itself without a draw; a fraction is a chance of one more.
#[test]
fn create_experience_rounds_the_fraction_by_chance() {
+70 -10
View File
@@ -3,7 +3,12 @@
//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab.
use crate::{Result, items::ItemStack, ui::EditBox};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
use std::{
collections::HashMap,
fs,
path::Path,
sync::{Arc, Mutex},
};
#[derive(Clone, Debug)]
pub struct Tab {
@@ -40,6 +45,17 @@ pub struct Creative {
/// The search tab's stacks, in its display order.
search_items: Vec<ItemStack>,
search_index: Vec<SearchEntry>,
/// ItemPickerMenu.items: what the grid shows, filled when the tab or the
/// search changes (selectTab, refreshSearchResults), not on every frame.
shown: Mutex<Option<Shown>>,
}
/// The grid's stacks for one tab, search text and language.
struct Shown {
tab: usize,
search: String,
/// A display name, so a language change refills the search results.
language: String,
items: Arc<[ItemStack]>,
}
/// Display names from the pinned en_us language file.
#[derive(Default)]
@@ -291,6 +307,7 @@ impl Creative {
},
search_items,
search_index,
shown: Mutex::new(None),
}
}
/// Where a stack comes in the creative tabs (the search tab lists them
@@ -303,6 +320,22 @@ impl Creative {
.position(|s| s.same_item_same_components(stack))
.or_else(|| items.iter().position(|s| s.item == stack.item))
}
/// The tabs without their stacks: what the screen draws of them each frame.
pub fn tab_headers(&self) -> Vec<Tab> {
self.tabs
.iter()
.map(|t| Tab {
id: t.id.clone(),
title: t.title.clone(),
icon: t.icon.clone(),
items: Vec::new(),
top: t.top,
column: t.column,
search: t.search,
inventory: t.inventory,
})
.collect()
}
pub fn tab(&self) -> &Tab {
&self.tabs[self.selected.min(self.tabs.len() - 1)]
}
@@ -384,17 +417,44 @@ impl Creative {
})
.collect()
}
/// Items shown by the selected tab (the search tab filters by `search`).
pub fn items(&self, names: &Names) -> Vec<ItemStack> {
let tab = self.tab();
if tab.search {
return self
.search_results(&self.search.value, names)
/// Items shown by the selected tab (the search tab filters by `search`),
/// worked out again only when the tab, the search or the language changed.
pub fn items(&self, names: &Names) -> Arc<[ItemStack]> {
let tab = self.selected.min(self.tabs.len() - 1);
let search = if self.tab().search {
self.search.value.as_str()
} else {
""
};
let language = names.display_get("itemGroup.search").unwrap_or_default();
let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner());
if let Some(s) = shown.as_ref()
&& s.tab == tab
&& s.search == search
&& s.language == language
{
return s.items.clone();
}
let items: Arc<[ItemStack]> = if self.tab().search {
self.search_results(search, names)
.into_iter()
.map(|i| self.search_items[i].clone())
.collect();
}
tab.items.clone()
.collect()
} else {
self.tab().items.as_slice().into()
};
*shown = Some(Shown {
tab,
search: search.to_owned(),
language,
items: items.clone(),
});
items
}
/// Drop the shown items, so the next `items` works them out again: a
/// reload can rename items without changing the Search label.
pub fn forget_items(&self) {
*self.shown.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
pub fn rows(&self, names: &Names) -> usize {
self.items(names).len().div_ceil(9)
+48 -5
View File
@@ -18,6 +18,7 @@ mod boats;
mod books;
mod bossbars;
mod breezes;
mod campfire;
mod cartography;
mod chat;
mod client_ambient;
@@ -1269,6 +1270,13 @@ struct Game<'a> {
/// Controllers (Horizon's own).
pad: pad::Pads,
frames: u64,
/// `item_level` for one frame, game time, day time and dimension.
item_level_cache: std::cell::RefCell<
Option<(
(u64, i64, i64, &'static str),
horizon_assets::item_model::LevelState,
)>,
>,
/// Frames drawn with the player in the world, for `--world-frames`.
world_frames: u64,
fps: f32,
@@ -3345,6 +3353,13 @@ impl Game<'_> {
self.with_player_actor(|game| game.break_block_as_player(pos))
}
fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> {
if !self
.res
.items()
.can_destroy_block(self.held(), self.creative)
{
return Ok(());
}
self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken);
// ServerPlayerGameMode.destroyBlock.
let state = self.world.block(pos[0], pos[1], pos[2]);
@@ -3970,7 +3985,12 @@ impl Game<'_> {
return Ok(());
};
// GameType.isBlockPlacingRestricted: adventure and spectator.
if !self.may_build() {
if !self.may_build()
|| !self
.res
.items()
.can_destroy_block(self.held(), self.creative)
{
self.mining = None;
return Ok(());
}
@@ -5302,7 +5322,8 @@ impl Game<'_> {
| BlockEntity::Vault(_)
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_),
| BlockEntity::Skull(_)
| BlockEntity::Campfire(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -5572,7 +5593,8 @@ impl Game<'_> {
| BlockEntity::Vault(_)
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_),
| BlockEntity::Skull(_)
| BlockEntity::Campfire(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -6366,6 +6388,13 @@ impl Game<'_> {
false,
);
if outside {
// AbstractRecipeBookScreen.mouseClicked: the book takes the click
// before the outside test, and its tabs sit left of the strip
// hasClickedOutside counts as the book.
if self.recipe_book_click(right) {
self.inv_clicks.skip_release();
return;
}
// slotId -999: an empty hand throws nothing; a carried stack
// starts a drag whose release drops it.
match input {
@@ -7030,6 +7059,9 @@ impl Game<'_> {
// `VaultRenderer`.
self.mark_entity(out.len(), "");
self.vault_geometry(camera, alpha, &mut out);
// `CampfireRenderer`.
self.mark_entity(out.len(), "");
self.campfire_geometry(camera, &mut out);
self.mark_entity(out.len(), "minecraft:ominous_item_spawner");
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
// Mobs and their projectiles (a span each).
@@ -8041,6 +8073,7 @@ impl Game<'_> {
/// (scaled coordinates, or the End portal's fixed destination).
pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result<Vec3> {
// Save the departing dimension's changed chunks.
self.save.save_forced_chunks(&self.streaming.forced)?;
self.streaming.save(&mut self.world, true);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
@@ -8733,6 +8766,13 @@ impl Game<'_> {
{
return Ok(UseResult::Success { swing: true });
}
if allow_block_actions
&& let Some(hit) = self.pick()
&& let Some(placed) = self.use_on_campfire(hit.pos)?
{
// SUCCESS_SERVER swings; a full campfire's CONSUME does not.
return Ok(UseResult::Success { swing: placed });
}
// BucketItem has no useOn: a guest's UseItemOn leaves it to UseItem.
let bucket = horizon_client::items::bucket_contents(&stack.item);
if matches!(self.guest_use, Some(GuestUse::OnBlock(_)))
@@ -9783,8 +9823,9 @@ impl Game<'_> {
fn draw_creative(&mut self, batch: &mut HudBatch) {
let (ox, oy) = Self::creative_origin(batch);
let selected = self.creative_screen.selected;
let tabs = self.creative_screen.tabs.clone();
let tab = self.creative_screen.tab().clone();
// Only what is drawn of the tabs: their stacks stay where they are.
let tabs = self.creative_screen.tab_headers();
let tab = tabs[selected.min(tabs.len() - 1)].clone();
let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| {
format!(
"gui/sprites/container/creative_inventory/tab_{}_{}_{}",
@@ -10172,6 +10213,7 @@ impl Game<'_> {
}
/// Save the level in place: its changed chunks, its entities and its raids.
fn save_level(&mut self, wait: bool) -> Result<()> {
self.save.save_forced_chunks(&self.streaming.forced)?;
self.streaming.save(&mut self.world, wait);
let keys: Vec<_> = self.world.modified.drain().collect();
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
@@ -12244,6 +12286,7 @@ impl<'a> Game<'a> {
last_input: now,
pad: Default::default(),
frames: 0,
item_level_cache: Default::default(),
world_frames: 0,
fps: 0.0,
fps_frames: 0,
@@ -56,6 +56,7 @@ impl Game<'_> {
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
_ => {}
}
}
@@ -92,7 +93,10 @@ impl Game<'_> {
| "minecraft:vault"
| "minecraft:beehive"
| "minecraft:bee_nest"
| "minecraft:brewing_stand" => Ticking::Yes,
| "minecraft:brewing_stand"
// Lit, cookTick; unlit, cooldownTick.
| "minecraft:campfire"
| "minecraft:soul_campfire" => Ticking::Yes,
"minecraft:jukebox" => {
let record = registry
.state(state)
+1 -1
View File
@@ -55,7 +55,7 @@ pub(super) struct Boat {
/// `ChestBoat.CONTAINER_SIZE`.
pub(super) const CHEST_SLOTS: usize = 27;
pub(super) const WIDTH: f64 = 1.375;
const HEIGHT: f64 = 0.5625;
pub(super) const HEIGHT: f64 = 0.5625;
impl Boat {
pub fn new(id: u32, wood: Arc<str>, position: Vec3, yaw: f32) -> Self {
Self {
+190
View File
@@ -0,0 +1,190 @@
//! Campfires' cooking: `CampfireBlock.useItemOn` (`CampfireBlockEntity.placeFood`)
//! and the block entity's `cookTick` (lit) and `cooldownTick` (unlit). The
//! items drawn on the fire are `campfire_geometry`'s; a server's clients get
//! them through the block entity's update tag (`lan::chunks::entity_tag`).
use super::Game;
use horizon_assets::item_model::DisplayContext;
use horizon_client::{
Result, block_entities::Pos, block_entity_render::vertex_light, containers::BlockEntity,
items::ItemStack, mesher::Vertex, mobs::Who,
};
use horizon_core::position::BlockPos;
/// The `campfire_cooking` recipe kind (`RecipeType.CAMPFIRE_COOKING`).
const KIND: &str = "minecraft:campfire_cooking";
fn is_campfire(name: &str) -> bool {
name == "minecraft:campfire" || name == "minecraft:soul_campfire"
}
impl Game<'_> {
/// `CampfireBlock.useItemOn` with a held item that is a campfire recipe's
/// input (`RecipePropertySet.CAMPFIRE_INPUT`): on a server level the food
/// goes into the first free slot (`placeFood`), and the use is consumed
/// whether or not there was room. A client of a server leaves the placing
/// to the server. Whether the food went in; None when this isn't a
/// campfire use, so the item's own use runs.
pub(super) fn use_on_campfire(&mut self, pos: [i32; 3]) -> Result<Option<bool>> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !is_campfire(&self.res.facts().get(state).name) {
return Ok(None);
}
let Some(held) = self.held().cloned() else {
return Ok(None);
};
let Some(time) = self.res.recipes().cook(KIND, &held).map(|r| r.time as i32) else {
return Ok(None);
};
// A client of a server predicts the placing; the server decides.
if self.remote.is_some() {
return Ok(Some(true));
}
let key = (pos[0], pos[1], pos[2]);
let placed = match self.world.block_entities.get_mut(&key) {
Some(BlockEntity::Campfire(c)) => {
let mut one = held.clone();
c.place_food(&mut one, time)
}
_ => false,
};
if placed {
// ItemStack.consumeAndReturn: creative keeps the item.
self.consume_held();
self.stats.custom("interact_with_campfire", 1);
self.post_block_game_event(
"minecraft:block_change",
pos,
Some(Who::Player),
Some(state),
);
self.mark_block_entity_updated(key);
}
Ok(Some(placed))
}
/// `CampfireBlockEntity.cookTick` of a lit campfire, `cooldownTick` of an
/// unlit one. A finished item's result (the recipe's, or the item itself
/// when no recipe takes it any more) drops at the block's corner
/// (`Containers.dropItemStack` at its integer position), then the clients
/// see the slot empty and a `block_change` goes out.
pub(super) fn tick_campfire(&mut self, pos: Pos) -> Result<()> {
let state = self.world.block(pos.0, pos.1, pos.2);
let lit = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("lit"))
.is_some_and(|v| v == "true");
let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
return Ok(());
};
// BlockEntity.setChanged: a timer that moved is saved with the
// chunk (no update to the clients, who don't see the timers).
let changed = if lit {
c.items.iter().any(Option::is_some)
} else {
c.cooldown_tick()
};
if changed {
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
}
if !lit {
return Ok(());
}
let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
return Ok(());
};
let done = c.cook_tick();
for (_, item) in done {
let result = self
.res
.recipes()
.cook(KIND, &item)
.map_or_else(|| item.clone(), |r| r.result.clone());
self.campfire_drop(pos, result);
self.mark_block_entity_updated(pos);
self.post_block_game_event(
"minecraft:block_change",
[pos.0, pos.1, pos.2],
None,
Some(state),
);
}
Ok(())
}
/// `CampfireRenderer`: each cooking item lies on the fire, slot `i`
/// turned to `Direction.from2DDataValue((i + facing) % 4)`, laid flat
/// (90° about X), at a corner and three eighths of its size, drawn as a
/// FIXED item seeded by the block's position plus the slot.
pub(super) fn campfire_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
for (key, entity) in &self.world.block_entities {
let BlockEntity::Campfire(c) = entity else {
continue;
};
if c.items.iter().all(Option::is_none) {
continue;
}
let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
if at.distance_squared(camera) >= 64.0 * 64.0 {
continue;
}
// Direction.get2DDataValue: south 0, west 1, north 2, east 3.
let state = self.world.block(key.0, key.1, key.2);
let facing = match self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing"))
.map(String::as_str)
{
Some("west") => 1,
Some("north") => 2,
Some("east") => 3,
_ => 0,
};
let light = vertex_light(self.world.light(key.0, key.1, key.2));
let packed = BlockPos::new(key.0, key.1, key.2).pack();
for (i, stack) in c.items.iter().enumerate() {
let Some(stack) = stack else {
continue;
};
let seed = (packed as i32).wrapping_add(i as i32);
let item = self.resolve_item(stack, DisplayContext::Fixed, None, seed);
if item.is_empty() {
continue;
}
// Direction.toYRot: 90° per 2D step from south.
let yaw = -(((i + facing) % 4) as f32 * 90.0);
let pose = glam::Mat4::from_translation(
(at - camera).as_vec3() + glam::Vec3::new(0.5, 0.449_218_75, 0.5),
) * glam::Mat4::from_rotation_y(yaw.to_radians())
* glam::Mat4::from_rotation_x(90f32.to_radians())
* glam::Mat4::from_translation(glam::Vec3::new(-0.3125, -0.3125, 0.0))
* glam::Mat4::from_scale(glam::Vec3::splat(0.375));
self.submit_item_world(&item, pose, light, out);
}
}
}
/// `Containers.dropItemStack(level, x, y, z, stack)` at the block's
/// integer position.
fn campfire_drop(&mut self, pos: Pos, stack: ItemStack) {
let at = BlockPos::new(pos.0, pos.1, pos.2);
for piece in
horizon_world::level::removal::drop_item_stack(&mut self.world.random, at, stack.count)
{
self.spawn_item(
ItemStack {
count: piece.count,
..stack.clone()
},
piece.pos,
piece.motion,
0,
);
}
}
}
+77 -34
View File
@@ -1885,11 +1885,12 @@ impl Game<'_> {
}
}
}
let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else {
let Some((_, mut new)) = horizon_client::save::decode_block_entity(&tag) else {
return false;
};
let rolled = self.take_loot_table(key, &tag, &mut new);
let after = horizon_client::save::encode_block_entity(key, &new, &name);
if after == before {
if after == before && !rolled {
return false;
}
self.world.block_entities.insert(key, new);
@@ -1897,6 +1898,79 @@ impl Game<'_> {
let _ = self.world.set(pos[0], pos[1], pos[2], state);
true
}
/// RandomizableContainer.tryLoadLootTable for a tag a command gives a
/// container (`setblock`, `data`): an empty container with a `LootTable`
/// is rolled now, as a loaded chunk's are (`save::roll_loaded_loot`), and
/// the roll is kept with its chunk, so that the container saves, and
/// `data get` shows, its table and seed until its items change. A tag
/// without one drops what the container had. True when it had a table.
pub(super) fn take_loot_table(
&mut self,
key: (i32, i32, i32),
tag: &horizon_world::nbt::Tag,
entity: &mut horizon_client::containers::BlockEntity,
) -> bool {
use horizon_client::{containers::BlockEntity, save, structure_blocks};
let table = save::text(tag.get("LootTable"));
let rolled = match (table, entity) {
(Some(table), BlockEntity::Chest(slots)) if slots.iter().all(Option::is_none) => {
let loot = structure_blocks::loot_data(&self.options.resources);
let at = Vec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
let biome = self.biome_name_at(at).unwrap_or_default();
Some(structure_blocks::roll_container(
slots,
loot.as_deref(),
table,
structure_blocks::loot_seed(tag),
key,
&biome,
))
}
_ => None,
};
let Some(chunk) = self.world.chunks.get_mut(&(key.0 >> 4, key.2 >> 4)) else {
return false;
};
let held = |c: &horizon_client::chunk::Chunk| {
c.saved
.as_ref()
.is_some_and(|s| s.rolled_loot.iter().any(|r| r.pos == key))
};
if rolled.is_none() && !held(chunk) {
return false;
}
let chunk = std::sync::Arc::make_mut(chunk);
let mut extras = chunk
.saved
.take()
.map(std::sync::Arc::unwrap_or_clone)
.unwrap_or_default();
extras.rolled_loot.retain(|r| r.pos != key);
let taken = rolled.is_some();
extras.rolled_loot.extend(rolled);
chunk.saved = Some(std::sync::Arc::new(extras));
taken
}
/// The loot table and seed a container still holding its roll saves
/// (`RolledLoot::restore`), in place of its items.
pub(super) fn restore_loot_table(
&self,
key: (i32, i32, i32),
tag: &mut horizon_world::nbt::Tag,
) {
let horizon_world::nbt::Tag::Compound(map) = tag else {
return;
};
let rolled = self
.world
.chunks
.get(&(key.0 >> 4, key.2 >> 4))
.and_then(|c| c.saved.as_ref())
.and_then(|s| s.rolled_loot.iter().find(|r| r.pos == key));
if let Some(r) = rolled {
r.restore(map);
}
}
fn cmd_fill(&mut self, ctx: &Context) -> R<i32> {
let a = self.block_pos_arg(ctx, "from")?;
let b = self.block_pos_arg(ctx, "to")?;
@@ -2593,38 +2667,7 @@ impl Game<'_> {
/// `PoiTypes`: the point of interest type of a block state.
fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> {
let s = self.pack.assets.registry.state(state)?;
let name = s.name.strip_prefix("minecraft:")?;
Some(match name {
"blast_furnace" => "minecraft:armorer",
"smoker" => "minecraft:butcher",
"cartography_table" => "minecraft:cartographer",
"brewing_stand" => "minecraft:cleric",
"composter" => "minecraft:farmer",
"barrel" => "minecraft:fisherman",
"fletching_table" => "minecraft:fletcher",
"cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => {
"minecraft:leatherworker"
}
"lectern" => "minecraft:librarian",
"stonecutter" => "minecraft:mason",
"loom" => "minecraft:shepherd",
"smithing_table" => "minecraft:toolsmith",
"grindstone" => "minecraft:weaponsmith",
"bell" => "minecraft:meeting",
"beehive" => "minecraft:beehive",
"bee_nest" => "minecraft:bee_nest",
"nether_portal" => "minecraft:nether_portal",
"lodestone" => "minecraft:lodestone",
"test_instance_block" => "minecraft:test_instance",
n if n.ends_with("_bed") => {
if s.properties.get("part").map(String::as_str) != Some("head") {
return None;
}
"minecraft:home"
}
n if n.ends_with("lightning_rod") => "minecraft:lightning_rod",
_ => return None,
})
horizon_client::save::poi_type(s).map(|(kind, _)| kind)
}
/// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within
/// 256 blocks of the source, over the loaded chunks.
@@ -286,6 +286,7 @@ impl Game<'_> {
if let Tag::Compound(c) = &mut tag {
c.remove(&"keepPacked".into());
}
self.restore_loot_table(key, &mut tag);
Ok(tag)
}
DataRef::Storage(id) => Ok(self.score.storage.get(id)),
@@ -296,7 +297,8 @@ impl Game<'_> {
DataRef::Entity(t) => self.apply_entity_nbt(*t, tag),
DataRef::Block(p) => {
let key = (p[0], p[1], p[2]);
if let Some((_, new)) = save::decode_block_entity(&tag) {
if let Some((_, mut new)) = save::decode_block_entity(&tag) {
self.take_loot_table(key, &tag, &mut new);
self.world.block_entities.insert(key, new);
let state = self.world.block(p[0], p[1], p[2]);
// Redraw what shows the block entity (signs, banners).
@@ -49,26 +49,12 @@ impl Game<'_> {
let mut tracker = Tracker::default();
for &t in &targets {
let h = holder(self.target_name(t));
// ServerRecipeBook.addRecipes/removeRecipes count recipe book
// displays (a transmute recipe has one per material count).
let mut n = 0;
// ServerPlayer.awardRecipes / resetRecipes: the displays changed.
let index = &self.res.stations().recipe_index;
n += if give {
let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes);
self.recipe_unlocked(&unlocked);
count as i32
} else {
let removed = self.level.recipe_book.remove_recipes(index, &recipes);
let count = removed.len() as i32;
// A network player's client drops them from its book.
if self.lan_acting.is_some() && !removed.is_empty() {
self.guest_packets.push(C::RecipeBookRemove(
horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed },
));
}
count
};
// ServerPlayer.awardRecipes / resetRecipes on the target's own
// ServerRecipeBook: a guest's is swapped in for the call, and the
// packets go to its client.
let n = self
.for_player(t, |g| g.change_recipes(give, &recipes))
.unwrap_or(0);
tracker.track(&h, n);
}
let verb = if give { "give" } else { "take" };
@@ -92,6 +78,27 @@ impl Game<'_> {
Ok(total)
}
/// ServerRecipeBook.addRecipes/removeRecipes for the player in place: how
/// many recipe book displays changed (a transmute recipe has one per
/// material count).
fn change_recipes(&mut self, give: bool, recipes: &[String]) -> i32 {
let index = &self.res.stations().recipe_index;
if give {
let (count, unlocked) = self.level.recipe_book.add_recipes(index, recipes);
self.recipe_unlocked(&unlocked);
return count as i32;
}
let removed = self.level.recipe_book.remove_recipes(index, recipes);
let count = removed.len() as i32;
// A network player's client drops them from its book.
if self.lan_acting.is_some() && !removed.is_empty() {
self.guest_packets.push(C::RecipeBookRemove(
horizon_protocol::packets::recipes::RecipeBookRemove { ids: removed },
));
}
count
}
// ---- /damage ----------------------------------------------------------------
fn damage_kind(ty: &str) -> DamageKind {
+6 -1
View File
@@ -373,6 +373,7 @@ impl Game<'_> {
// Drawn seated (Entity.isPassenger); set apart because the
// json! above is at the macro recursion limit.
state["passenger"] = m.extra.passenger.into();
state["guardian_beam"] = serde_json::json!(horizon_client::mobs::guardian::beam(m, 0.0));
state
})
.collect();
@@ -840,6 +841,7 @@ impl Game<'_> {
pub(super) fn handle_mob_events(&mut self, events: Vec<MobEvent>) -> Result<()> {
for e in events {
match e {
MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at),
MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at),
MobEvent::Sound(name, at, volume, pitch)
| MobEvent::LocalSound(name, at, volume, pitch) => {
@@ -1065,7 +1067,10 @@ impl Game<'_> {
}
MobEvent::BreakBlock { pos, drop } => {
let old = self.world.block(pos[0], pos[1], pos[2]);
self.destroy_particles(pos, old);
// Block.spawnDestroyParticles: fire breaks leave nothing.
if !self.res.facts().get(old).has_class("BaseFireBlock") {
self.destroy_particles(pos, old);
}
if drop {
let drops = self.res.items().block_drops_in(
self.pack.assets.registry,
+253 -25
View File
@@ -18,6 +18,7 @@ use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
use horizon_protocol::entity_data::Value;
use horizon_world::nbt::Tag;
/// Mob ids from here on are dragon parts (`SPECIAL + part`) and crystals
@@ -1559,6 +1560,7 @@ impl Game<'_> {
y -= 1.0;
}
self.breath_clouds.push(Breath {
id: 0,
at: [x, y.floor() + 1.0, z],
radius: 5.0,
age: 0,
@@ -1692,25 +1694,8 @@ impl Game<'_> {
}
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
let p = d.position;
d.nearest_crystal = self
.crystals
.iter()
.enumerate()
.filter(|(_, c)| {
(c.position.x - p.x).abs() <= 32.0
&& (c.position.y - p.y).abs() <= 32.0
&& (c.position.z - p.z).abs() <= 32.0
})
.min_by(|a, b| {
let da = (a.1.position.x - p.x).powi(2)
+ (a.1.position.y - p.y).powi(2)
+ (a.1.position.z - p.z).powi(2);
let db = (b.1.position.x - p.x).powi(2)
+ (b.1.position.y - p.y).powi(2)
+ (b.1.position.z - p.z).powi(2);
da.total_cmp(&db)
})
.map(|(i, _)| i);
let nearest = self.nearest_crystal_to(p);
self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
}
let d = self.dragon.as_mut().expect("dragon");
d.yaw = wrap(d.yaw);
@@ -2038,6 +2023,7 @@ impl Game<'_> {
// assignDirectionalMovement: the direction times the acceleration power 0.1.
let velocity = Vec3::new(v.x * 0.1, v.y * 0.1, v.z * 0.1);
self.dragon_fireballs.push(DragonFireball {
id: 0,
position: at,
previous: at,
velocity,
@@ -2084,6 +2070,7 @@ impl Game<'_> {
});
if hit_block || hit_player || b.age > 600 {
self.breath_clouds.push(Breath {
id: 0,
at: [next.x, next.y, next.z],
radius: 3.0,
age: 0,
@@ -2213,15 +2200,58 @@ impl Game<'_> {
}
}
pub(super) struct DragonFireball {
position: Vec3,
previous: Vec3,
velocity: Vec3,
/// Its entity id once a server's players track it (0 until then).
pub(super) id: u32,
pub(super) position: Vec3,
pub(super) previous: Vec3,
pub(super) velocity: Vec3,
age: i32,
}
impl DragonFireball {
/// One a server sent (`handleAddEntity`).
pub(super) fn remote(id: u32, at: Vec3, velocity: Vec3) -> Self {
Self {
id,
position: at,
previous: at,
velocity,
age: 0,
}
}
/// `AbstractHurtingProjectile.tick` on a server's client: `applyInertia`
/// first (power 0.1, inertia 0.95 or 0.8 in water), then the move; only
/// the server decides what it hits.
pub(super) fn remote_step(&mut self, water: bool) {
self.previous = self.position;
self.age += 1;
let v = self.velocity;
// Vec3.normalize: a vector shorter than 1e-5 stays zero.
let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt();
let n = if l < 1.0e-5 {
Vec3::new(0.0, 0.0, 0.0)
} else {
Vec3::new(v.x / l, v.y / l, v.z / l)
};
let inertia = f64::from(if water { 0.8f32 } else { 0.95f32 });
let v = Vec3::new(
(v.x + n.x * 0.1) * inertia,
(v.y + n.y * 0.1) * inertia,
(v.z + n.z * 0.1) * inertia,
);
self.velocity = v;
self.position = Vec3::new(
self.position.x + v.x,
self.position.y + v.y,
self.position.z + v.z,
);
}
}
pub(super) struct Breath {
at: [f64; 3],
radius: f32,
age: i32,
/// Its entity id once a server's players track it (0 until then).
pub(super) id: u32,
pub(super) at: [f64; 3],
pub(super) radius: f32,
pub(super) age: i32,
duration: i32,
from_dragon: bool,
}
@@ -3143,6 +3173,204 @@ impl Game<'_> {
let _ = self.activate_exit_portal();
self.fight.dirty = true;
}
/// `EnderDragon.checkCrystals`' search: the nearest crystal within 32
/// blocks on each axis.
fn nearest_crystal_to(&self, p: Vec3) -> Option<usize> {
self.crystals
.iter()
.enumerate()
.filter(|(_, c)| {
(c.position.x - p.x).abs() <= 32.0
&& (c.position.y - p.y).abs() <= 32.0
&& (c.position.z - p.z).abs() <= 32.0
})
.min_by(|a, b| {
let da = (a.1.position.x - p.x).powi(2)
+ (a.1.position.y - p.y).powi(2)
+ (a.1.position.z - p.z).powi(2);
let db = (b.1.position.x - p.x).powi(2)
+ (b.1.position.y - p.y).powi(2)
+ (b.1.position.z - p.z).powi(2);
da.total_cmp(&db)
})
.map(|(i, _)| i)
}
}
/// The dragon on a server's client (`ClientPacketListener.handleAddEntity`
/// and the client side of `EnderDragon.aiStep`): the server flies it and
/// sends its moves, health and phase; the client flaps its wings, keeps
/// its flight history and places its parts, so it can be drawn and hit.
impl Game<'_> {
/// `handleAddEntity` for `minecraft:ender_dragon`. Its constructor
/// sets the full health and the hovering phase until the server's
/// synched data says otherwise.
pub(super) fn spawn_remote_dragon(&mut self, id: i32, position: [f64; 3], yaw: f32) {
let at = Vec3::new(position[0], position[1], position[2]);
let mut d = Dragon::new(at, yaw, i64::from(id));
d.id = id as u32;
d.phase = Phase::from_id(10);
self.dragon = Some(d);
self.place_dragon_parts();
if let Some(d) = self.dragon.as_mut() {
for part in &mut d.parts {
part.1 = part.0;
}
}
}
/// The remote dragon, if `id` is it.
fn remote_dragon_mut(&mut self, id: i32) -> Option<&mut Dragon> {
self.dragon.as_mut().filter(|d| d.id as i32 == id)
}
/// `handleSetEntityData`: LivingEntity.DATA_HEALTH_ID and
/// EnderDragon.DATA_PHASE (`onSyncedDataUpdated` sets the phase).
pub(super) fn remote_dragon_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
let Some(d) = self.remote_dragon_mut(id) else {
return;
};
for (index, _, value) in values {
match (index, value) {
(9, Value::Float(health)) => d.health = *health,
(16, Value::Int(phase)) => d.set_phase(Phase::from_id(*phase)),
_ => {}
}
}
}
/// `handleSetEntityMotion`: the velocity its wings flap by.
pub(super) fn remote_dragon_motion(&mut self, id: i32, velocity: [f64; 3]) {
if let Some(d) = self.remote_dragon_mut(id) {
d.velocity = Vec3::new(velocity[0], velocity[1], velocity[2]);
}
}
/// `handleHurtAnimation` and `handleDamageEvent`: the red flash.
pub(super) fn remote_dragon_hurt(&mut self, id: i32) {
if let Some(d) = self.remote_dragon_mut(id) {
d.hurt_time = 10;
}
}
/// `handleRemoveEntities`, or a crystal removed: the healing beam
/// keeps pointing at the same crystal.
pub(super) fn remove_remote_dragon(&mut self, id: i32) {
if self.remote_dragon_mut(id).is_some() {
self.dragon = None;
return;
}
let Some(index) = self.crystals.iter().position(|c| c.id as i32 == id) else {
return;
};
if let Some(d) = self.dragon.as_mut() {
match d.nearest_crystal {
Some(n) if n == index => d.nearest_crystal = None,
Some(n) if n > index => d.nearest_crystal = Some(n - 1),
_ => {}
}
}
}
/// One client tick of the dragon. `lerp`: the step toward its last
/// sent position and yaw (LivingEntity's interpolation), and the
/// steps left including this one.
pub(super) fn tick_remote_dragon(&mut self, lerp: Option<([f64; 3], Option<f32>, u32)>) {
let Some(d) = self.dragon.as_mut() else {
return;
};
d.previous = d.position;
d.previous_yaw = d.yaw;
d.old_flap = d.flap;
d.ticks += 1;
d.hurt_time = (d.hurt_time - 1).max(0);
for part in &mut d.parts {
part.1 = part.0;
}
if let Some((target, yaw, steps)) = lerp {
let n = f64::from(steps.max(1));
d.position = Vec3::new(
d.position.x + (target[0] - d.position.x) / n,
d.position.y + (target[1] - d.position.y) / n,
d.position.z + (target[2] - d.position.z) / n,
);
if let Some(yaw) = yaw {
d.yaw += wrap(yaw - d.yaw) / steps.max(1) as f32;
}
}
if !d.alive() {
// EnderDragon.tickDeath on a client: it rises, and bursts
// from tick 180 to 200; the server removes it.
d.death_time += 1;
let (t, p) = (d.death_time, d.position);
if (180..=200).contains(&t) {
let r = &mut d.random;
let o = [
f64::from((r.next_float() - 0.5) * 8.0),
f64::from((r.next_float() - 0.5) * 4.0),
f64::from((r.next_float() - 0.5) * 8.0),
];
self.particles.add(
&ParticleOptions::simple(ParticleType::ExplosionEmitter),
[p.x + o[0], p.y + 2.0 + o[1], p.z + o[2]],
[0.0; 3],
);
}
if let Some(d) = self.dragon.as_mut() {
d.position.y += 0.1;
for part in &mut d.parts {
part.0.y += 0.1;
}
}
return;
}
// processFlappingMovement and onFlap: its wing beats, and their sound.
let flap_was = (d.old_flap * std::f32::consts::TAU).cos();
let v = d.velocity;
let mut flap_speed = 0.2 / ((v.x.hypot(v.z) as f32) * 10.0 + 1.0);
flap_speed *= 2f32.powf(v.y as f32);
d.flap += if d.phase.sitting() { 0.1 } else { flap_speed };
let flap_now = (d.flap * std::f32::consts::TAU).cos();
let at = [d.position.x, d.position.y, d.position.z];
if flap_was <= -0.3 && flap_now >= -0.3 {
let pitch = 0.8 + self.world.random.next_float() * 0.3;
self.audio
.play("minecraft:entity.ender_dragon.flap", Some(at), 5.0, pitch);
}
let d = self.dragon.as_mut().expect("dragon");
if !d.phase.sitting() {
d.growl -= 1;
if d.growl < 0 {
d.growl = 200 + d.random.next_int_bound(200).unwrap_or(0);
let pitch = 0.8 + self.world.random.next_float() * 0.3;
self.audio
.play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch);
}
}
// checkCrystals' search runs on a client too (the healing beam).
let d = self.dragon.as_mut().expect("dragon");
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
let p = d.position;
let nearest = self.nearest_crystal_to(p);
self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
}
let d = self.dragon.as_mut().expect("dragon");
d.yaw = wrap(d.yaw);
d.record();
self.place_dragon_parts();
}
/// The dragon's parts as a server's client attacks them: the server's
/// ids for `EnderDragonPart`s follow the dragon's.
pub(super) fn remote_dragon_part_hit(
&self,
eye: [f64; 3],
dir: [f64; 3],
reach: f64,
) -> Option<(i32, f64, [f64; 3])> {
let d = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0)?;
(0..8)
.filter_map(|i| {
let b = d.part_box(i);
let p = d.parts[i].0;
super::ray_box(eye, dir, reach, b)
.map(|t| ((d.id + 1 + i as u32) as i32, t, [p.x, p.y, p.z]))
})
.min_by(|a, b| a.1.total_cmp(&b.1))
}
}
#[cfg(test)]
@@ -17,6 +17,8 @@ use horizon_core::{
random::RandomSource,
};
pub(super) const FIREWORK_EXPLODE_EVENT: i8 = 17;
pub(super) struct Rocket {
/// The entity id a server tracks it by (0 until it is tracked).
pub id: u32,
@@ -261,6 +263,14 @@ impl Game<'_> {
/// `FireworkRocketEntity.explode` and `dealExplosionDamage`.
fn explode_rocket(&mut self, r: &Rocket) {
let at = [r.position.x, r.position.y, r.position.z];
// FireworkRocketEntity.explode broadcasts before discard. Send now:
// tick_lan removes missing tracked entities before flushing effects.
if r.id != 0
&& let Some(host) = &self.lan
{
host.hub
.entity_event(r.id as i32, FIREWORK_EXPLODE_EVENT, at);
}
if !r.explosions.is_empty() {
let damage = 5.0 + r.explosions.len() as f32 * 2.0;
let from = r.position;
@@ -322,6 +332,16 @@ impl Game<'_> {
self.particles
.fireworks(at, v, r.explosions.clone(), camera);
}
/// FireworkRocketEntity.handleEntityEvent: use the synchronized item data.
pub(super) fn remote_firework_explosion(&mut self, id: i32) {
let camera = self.eye_position();
if let Some(r) = self.rockets.iter().find(|r| r.id == id as u32) {
let at = [r.position.x, r.position.y, r.position.z];
let v = [r.velocity.x, r.velocity.y, r.velocity.z];
self.particles
.fireworks(at, v, r.explosions.clone(), camera.unwrap_or(at));
}
}
/// `dealExplosionDamage` on a player that is not the rocket's
/// `attachedToEntity`: within 5 blocks, when the rocket sees its feet or
/// its middle (`ClipContext.Block.COLLIDER`, no fluids).
+1 -1
View File
@@ -231,7 +231,7 @@ impl Game<'_> {
}
damage
}
fn biome_name_at(&self, p: Vec3) -> Option<String> {
pub(super) fn biome_name_at(&self, p: Vec3) -> Option<String> {
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
let c = self.world.chunks.get(&(x >> 4, z >> 4))?;
Some(
+15 -4
View File
@@ -355,12 +355,23 @@ impl Game<'_> {
* glam::DMat4::from_rotation_y(y_rot.to_radians());
let light = self.world.light(f.pos[0], f.pos[1], f.pos[2]);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
// ItemFrameRenderer.getBlockLightLevel: a glow frame's model is at least 5 bright.
let frame_light = if f.glow {
(light & 0xF0) | (light & 15).max(5)
} else {
light
};
let frame_packed =
(u32::from(frame_light >> 4) * 16) | ((u32::from(frame_light & 15) * 16) << 8);
let mut quad =
|m: &glam::DMat4, corners: [[f64; 3]; 4], uv: [[f32; 2]; 4], light: u32| {
for (c, uv) in corners.iter().zip(uv) {
let p = m.transform_point3(glam::DVec3::from_array(*c));
// The frame model is drawn with the entity shader, lit by its face normal.
let at = corners.map(|c| m.transform_point3(glam::DVec3::from_array(c)));
let n = (at[1] - at[0]).cross(at[2] - at[0]).normalize_or_zero();
let normal = [0, 1, 2].map(|k| (n[k].clamp(-1.0, 1.0) * 127.0) as i8);
for (p, uv) in at.into_iter().zip(uv) {
out.push(Vertex {
normal: [0; 4],
normal: [normal[0], normal[1], normal[2], -127],
pos: p.as_vec3().to_array(),
uv,
layer: 0,
@@ -393,7 +404,7 @@ impl Game<'_> {
]
}),
map_uv(r, *uv),
packed,
frame_packed,
);
}
}
+19 -1
View File
@@ -196,13 +196,31 @@ impl Game<'_> {
skins: &self.skin_downloads,
}
}
/// The client level as item models read it.
/// The client level as item models read it: worked out once a frame (a
/// screen of items read the same level, its sky sampled once).
pub(super) fn item_level(&self) -> LevelState {
let dimension = match self.dim {
Dim::Overworld => "minecraft:overworld",
Dim::Nether => "minecraft:the_nether",
Dim::End => "minecraft:the_end",
};
let key = (
self.frames,
self.world.game_time,
self.world.day_time,
dimension,
);
let mut cached = self.item_level_cache.borrow_mut();
if let Some((at, level)) = cached.as_ref()
&& *at == key
{
return level.clone();
}
let level = self.level_state_now(dimension);
*cached = Some((key, level.clone()));
level
}
fn level_state_now(&self, dimension: &'static str) -> LevelState {
let sky = self
.dim_environment()
.sample(self.world.day_time, None, None);
+28 -7
View File
@@ -14,7 +14,7 @@ use horizon_client::{
hub::{HostEvent, HostState, Hub, HubConfig, TickCtx},
playerdata,
},
mobs::{Mob, leash::Holder},
mobs::{Mob, Who, leash::Holder},
text::Text,
};
use horizon_core::geometry::Vec3;
@@ -174,6 +174,7 @@ pub(super) fn baby_index(kind: &str) -> Option<u8> {
fn mob_meta(
m: &Mob,
hub: &Hub,
player_entity: Option<i32>,
meta: &mut Vec<(u8, i32, Value)>,
defaults: &mut Vec<(u8, i32, Value)>,
) {
@@ -223,6 +224,25 @@ fn mob_meta(
let e = &m.extra;
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
match kind {
"minecraft:guardian" | "minecraft:elder_guardian" => {
// Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET.
if e.flag2 {
meta.push((16, serializer::BOOLEAN, Value::Bool(true)));
}
let target = if e.flag {
m.ai.target.and_then(|who| match who {
Who::Player => player_entity,
Who::Mob(id) => Some(id as i32),
})
} else {
None
};
if let Some(target) = target {
meta.push((17, serializer::INT, Value::Int(target)));
}
defaults.push((16, serializer::BOOLEAN, Value::Bool(false)));
defaults.push((17, serializer::INT, Value::Int(0)));
}
// Bat.DATA_ID_FLAGS: resting in bit 0, flying by default.
"minecraft:bat" => {
if e.flag {
@@ -859,12 +879,13 @@ impl Game<'_> {
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 player_entity = mob_players
.get(&m.id)
.and_then(|conn| hub.guest(*conn))
.map(|g| g.entity_id)
.or(host_entity);
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::Player => player_entity,
Holder::Mob(id) => Some(id as i32),
Holder::Knot(_) => None,
});
@@ -874,7 +895,7 @@ impl Game<'_> {
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, &mut e.defaults);
mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults);
mob_equipment(m, hub, &mut e.equipment);
self.mob_attributes(m, &mut e.attributes);
e.leash = leash;
+45 -1
View File
@@ -80,6 +80,10 @@ pub(super) struct GuestPlay {
last_inventory: u64,
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
pub(super) portal: horizon_client::nether_portal::PortalState,
/// `ServerPlayer.wonGame`: the End poem is showing, the player waits for
/// its client's PERFORM_RESPAWN (`respawn_requested`).
pub(super) won_game: bool,
pub(super) respawn_requested: bool,
/// `Player.takeXpDelay`: ticks until the next orb can be taken.
xp_delay: u32,
/// What last killed the guest outright (`/kill`): the death message's key.
@@ -878,7 +882,11 @@ impl Game<'_> {
.filter(|g| host.hub.here(g))
.filter(|g| {
g.menu.as_ref().is_some_and(|m| {
m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos)
(m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos))
|| m.pos.is_some_and(|k| {
k.1 == super::minecarts::CART_KEY_Y
&& !self.chest_vehicle_still_valid(k.2, g)
})
})
})
.map(|g| g.conn)
@@ -892,6 +900,35 @@ impl Game<'_> {
}
}
/// `ContainerEntity.isChestVehicleStillValid`: the chest minecart or chest
/// boat is still there and within the guest's entity interaction range
/// plus 4 of its box.
fn chest_vehicle_still_valid(&self, id: i32, g: &horizon_client::lan::guest::Guest) -> bool {
let bounds = self
.carts
.iter()
.find(|c| c.id as i32 == id)
.map(|c| c.bounds())
.or_else(|| {
self.boats
.iter()
.find(|b| b.id as i32 == id)
.map(|b| b.bounds())
});
let Some(b) = bounds else {
return false;
};
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
let (lo, hi) = (b.min_position(), b.max_position());
let d = [
eye[0] - eye[0].clamp(lo.x, hi.x),
eye[1] - eye[1].clamp(lo.y, hi.y),
eye[2] - eye[2].clamp(lo.z, hi.z),
];
let range = if g.creative() { 5.0 } else { 3.0 } + 4.0;
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range
}
/// A packet from a guest that the hub does not handle itself.
pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
@@ -1317,6 +1354,13 @@ impl Game<'_> {
self.guest_suggestions(host, conn, &payload);
}
S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p),
// handleClientCommand: PERFORM_RESPAWN after the poem leaves the End
// (the next server tick sends the player on).
S::ClientCommand(c)
if c.action == 0 && host.play.get(&conn).is_some_and(|p| p.won_game) =>
{
host.play.entry(conn).or_default().respawn_requested = true;
}
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
// ServerStatsCounter.sendStats.
S::ClientCommand(c) if c.action == 1 => {
@@ -289,6 +289,10 @@ impl Game<'_> {
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);
self.breath_clouds.iter_mut().for_each(|b| give(&mut b.id));
self.dragon_fireballs
.iter_mut()
.for_each(|b| give(&mut b.id));
}
/// Primed TNT, falling blocks, projectiles, tridents, firework rockets and
@@ -445,6 +449,35 @@ impl Game<'_> {
}
out.push(e);
}
// The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS,
// DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the
// client draws them from these (`tick_remote_clouds`).
let breath = self.network_particle(
&horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::DragonBreath,
),
None,
);
for b in self.dragon_fireballs.iter().filter(|b| b.id != 0) {
let p = b.position;
let mut e = state(b.id, "minecraft:dragon_fireball", at(p), 0.0, false);
e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z];
out.push(e);
}
for b in self.breath_clouds.iter().filter(|b| b.id != 0) {
let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false);
e.meta.push((8, serializer::FLOAT, Value::Float(b.radius)));
if b.age < 20 {
e.meta.push((9, serializer::BOOLEAN, Value::Bool(true)));
}
if let Some(p) = &breath {
e.meta
.push((10, serializer::PARTICLE, Value::Particle(p.clone())));
}
e.defaults
.push((9, serializer::BOOLEAN, Value::Bool(false)));
out.push(e);
}
out.extend(self.lan_dragon_state());
}
}
@@ -95,7 +95,11 @@ impl Game<'_> {
/// The options a server's particle stands for (None for a type or data
/// this client doesn't draw).
fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option<ParticleOptions> {
pub(super) fn received_particle(
&mut self,
p: &Particle,
at: [f64; 3],
) -> Option<ParticleOptions> {
let name = self
.remote
.as_ref()?
@@ -144,15 +144,16 @@ impl Game<'_> {
.offers
.iter()
.filter_map(|o| {
let cost =
|st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| play::NetCost {
item: hub.item_id(&st.item),
count: st.count as i32,
};
let cost = |st: &ItemStack, hub: &mut horizon_client::lan::hub::Hub| {
hub.stack(&Some(st.clone())).map(play::NetCost::from)
};
Some(play::NetOffer {
cost_a: cost(&o.base_cost_a.stack, &mut host.hub),
cost_a: cost(&o.base_cost_a.stack, &mut host.hub)?,
result: host.hub.stack(&Some(o.result.clone()))?,
cost_b: o.cost_b.as_ref().map(|b| cost(&b.stack, &mut host.hub)),
cost_b: match &o.cost_b {
Some(b) => Some(cost(&b.stack, &mut host.hub)?),
None => None,
},
out_of_stock: o.out_of_stock(),
uses: o.uses,
max_uses: o.max_uses,
+13 -3
View File
@@ -87,9 +87,12 @@ pub(super) struct Minecart {
pub fuse: i32,
/// Hopper minecarts: an unpowered activator rail enables them.
pub enabled: bool,
/// Chest minecarts: the loot table rolled into `items` on load, saved
/// again while the items are still that roll.
pub loot: Option<horizon_client::save::RolledLoot>,
}
const WIDTH: f64 = 0.98;
const HEIGHT: f64 = 0.7;
pub(super) const WIDTH: f64 = 0.98;
pub(super) const HEIGHT: f64 = 0.7;
/// AbstractMinecart.getDefaultDisplayOffset, in sixteenths of a block.
fn display_offset(kind: CartKind) -> f64 {
if kind == CartKind::Hopper { 1.0 } else { 6.0 }
@@ -97,7 +100,7 @@ fn display_offset(kind: CartKind) -> f64 {
/// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT.
pub(super) const SEAT: f64 = 0.1875 - 0.6;
/// The placeholder container key under which an open cart's items live.
pub(super) const CART_KEY_Y: i32 = -100_000;
pub(super) const CART_KEY_Y: i32 = horizon_client::lan::menu::VEHICLE_KEY_Y;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Shape {
@@ -182,6 +185,7 @@ impl Minecart {
push: [0.0; 2],
fuse: -1,
enabled: true,
loot: None,
}
}
pub fn bounds(&self) -> Aabb {
@@ -1527,6 +1531,12 @@ impl Minecart {
}
CartKind::Rideable => {}
}
// A loaded loot table goes back while the items are still its roll;
// otherwise the items replace it, as vanilla's unpackLootTable does.
if !self.loot.as_ref().is_some_and(|l| l.restore(map)) {
map.remove(&JavaString::from("LootTable"));
map.remove(&JavaString::from("LootTableSeed"));
}
}
tag
}
+56
View File
@@ -68,6 +68,10 @@ pub(super) struct ModsState {
/// is still being shown, and a mod answering its own lines would recurse.
#[cfg(feature = "mods")]
commands: Vec<String>,
/// `command.run-quiet` batches for this window's own world, by mod id,
/// run on the next tick as `commands` are.
#[cfg(feature = "mods")]
quiet: Vec<(String, Vec<String>)>,
/// The server's command tree with the running mods' commands added.
#[cfg(feature = "mods")]
remote_tree: Option<Dispatcher>,
@@ -505,6 +509,51 @@ impl Game<'_> {
}
None
}
/// A mod's `command.run-quiet` lines (vanilla's commands only, as
/// `command.run`): to a server that runs them quietly as one payload
/// (`horizon_protocol::quiet`), to any other as chat commands, or for this
/// window's own world next tick.
fn mod_quiet_commands(&mut self, mod_id: String, lines: Vec<String>) {
let lines: Vec<String> = lines
.into_iter()
.filter(|l| vanilla_command(l.split(' ').next().unwrap_or_default()))
.collect();
match self.remote.as_ref().map(|r| r.quiet_commands) {
Some(true) => {
for data in horizon_protocol::quiet::encode(&mod_id, &lines) {
self.send(horizon_protocol::packets::play::Serverbound::CustomPayload(
horizon_protocol::packets::configuration::CustomPayload {
channel: horizon_protocol::quiet::CHANNEL.into(),
data,
},
));
}
}
// The server checks the player's permissions; its feedback shows.
Some(false) => {
for line in lines {
self.send_chat(&format!("/{line}"));
}
}
None => self.mods.quiet.push((mod_id, lines)),
}
}
/// A quiet batch in this window's own world, as a server runs one
/// (game/lan_quiet.rs): each line as the player typing it, no chat, a
/// chat message refused; one line in the log.
fn run_quiet_batch(&mut self, mod_id: &str, lines: &[String]) {
let permission = self.ui.registries.permission;
let mut failed = 0;
for line in lines {
let ok = self.signable_arguments(permission, line).is_empty()
&& self.run_command_quietly(line);
failed += usize::from(!ok);
}
log::info!(
"[mod {mod_id}] ran {} quiet command(s): {failed} failed",
lines.len()
);
}
/// A game tick.
pub(super) fn tick_mods(&mut self) {
// Here, at the player's level: shown inside a console call (a control
@@ -512,6 +561,9 @@ impl Game<'_> {
for line in std::mem::take(&mut self.mods.commands) {
self.run_command(&line);
}
for (mod_id, lines) in std::mem::take(&mut self.mods.quiet) {
self.run_quiet_batch(&mod_id, &lines);
}
if !self.mods.mods.is_running() {
return;
}
@@ -606,6 +658,10 @@ impl Game<'_> {
}
continue;
}
Output::QuietCommands { mod_id, lines } => {
self.mod_quiet_commands(mod_id, lines);
continue;
}
Output::Stopped { name, reason } => {
// Its screen goes with it: the entry's run is gone, so
// `mod_ui_view` finds no widgets and the screen closes.
@@ -454,11 +454,24 @@ impl Game<'_> {
for m in &self.mobs {
self.portals.before.insert(m.id, m.position);
}
for b in &self.boats {
self.portals.before.insert(b.id, b.position);
}
for c in &self.carts {
self.portals.before.insert(c.id, c.position);
}
let ids: Vec<(u32, bool)> = self
.dropped
.iter()
.map(|e| (e.id, true))
.chain(self.mobs.iter().map(|m| (m.id, self.mob_can_use_portal(m))))
.chain(
self.boats
.iter()
.map(|b| b.id)
.chain(self.carts.iter().map(|c| c.id))
.map(|id| (id, !self.vehicle_occupied(id))),
)
.collect();
let present: std::collections::HashSet<u32> = ids.iter().map(|(id, _)| *id).collect();
self.portals.entities.retain(|id, _| present.contains(id));
@@ -501,8 +514,15 @@ impl Game<'_> {
&& self.riding != Some(m.id)
&& m.species() != Species::Wither
}
/// `NetherPortalBlock.entityInside` for the items and mobs that moved this
/// tick: the portal blocks their box swept through.
/// Whether the player, a server player or a mob rides vehicle `id`.
fn vehicle_occupied(&self, id: u32) -> bool {
self.riding == Some(id)
|| self.ridden_by_guest(id)
|| self.mobs.iter().any(|m| m.extra.mount == Some(id))
}
/// `NetherPortalBlock.entityInside` for the items, mobs and empty boats
/// and minecarts that moved this tick: the portal blocks their box swept
/// through.
pub(super) fn find_entity_portals(&mut self) {
if self.remote.is_some() {
return;
@@ -519,8 +539,23 @@ impl Game<'_> {
.filter(|m| self.mob_can_use_portal(m))
.map(|m| (m.id, m.position, m.width(), m.height()))
.collect();
let vehicles: Vec<(u32, Vec3, f32, f32)> = self
.boats
.iter()
.map(|b| (b.id, b.position, super::boats::WIDTH, super::boats::HEIGHT))
.chain(self.carts.iter().map(|c| {
(
c.id,
c.position,
super::minecarts::WIDTH,
super::minecarts::HEIGHT,
)
}))
.filter(|(id, ..)| !self.vehicle_occupied(*id))
.map(|(id, at, w, h)| (id, at, w as f32, h as f32))
.collect();
let mut portal_sections = std::mem::take(&mut self.portals.sections);
for (id, to, width, height) in items.into_iter().chain(mobs) {
for (id, to, width, height) in items.into_iter().chain(mobs).chain(vehicles) {
let from = self.portals.before.get(&id).copied().unwrap_or(to);
if let Some(pos) = self.swept_portal(from, to, width, height, &mut portal_sections) {
inside.push((id, pos));
@@ -678,6 +713,44 @@ impl Game<'_> {
}
self.portals.arrivals.push(Arrival { plan, tag });
self.portals.dirty = true;
} else if let Some(i) = self.boats.iter().position(|b| b.id == id) {
let b = &self.boats[i];
let (width, height) = (super::boats::WIDTH as f32, super::boats::HEIGHT as f32);
let plan = self.portal_plan(entry, b.position, width, height, false);
if !self.may_enter(plan.dim) {
return;
}
let uuid = self.uuid_for(id);
let b = &self.boats[i];
let tag = horizon_client::entity_nbt::boat_to_nbt(
&b.entity_type(),
b.position,
b.velocity,
b.yaw,
uuid,
self.persist_raw(id),
b.chest.then_some(&b.items[..]),
);
self.boats.remove(i);
self.forget_entity(id);
self.portals.arrivals.push(Arrival { plan, tag });
self.portals.dirty = true;
} else if let Some(i) = self.carts.iter().position(|c| c.id == id) {
let c = &self.carts[i];
let (width, height) = (
super::minecarts::WIDTH as f32,
super::minecarts::HEIGHT as f32,
);
let plan = self.portal_plan(entry, c.position, width, height, false);
if !self.may_enter(plan.dim) {
return;
}
let uuid = self.uuid_for(id);
let tag = self.carts[i].to_nbt(uuid, self.persist_raw(id));
self.carts.remove(i);
self.forget_entity(id);
self.portals.arrivals.push(Arrival { plan, tag });
self.portals.dirty = true;
}
}
/// Entities waiting for the loaded dimension whose exit area is loaded:
@@ -257,6 +257,7 @@ impl Game<'_> {
lang::set(lang::Language::load(&[&root], code));
self.refresh_remote_language();
self.ui.chat.rescale(&self.gui.atlas);
self.creative_screen.forget_items();
}
/// Settings that Horizon applies beyond render distance, volume and GUI scale.
pub(super) fn apply_ui_settings(&mut self) {
@@ -268,6 +269,11 @@ impl Game<'_> {
r.animated_textures = s.horizon.animated_textures;
r.set_mipmap_levels(s.mipmap_levels.max(0) as u32);
r.set_world_post(s.horizon.resolution_scale as f32 / 100.0, s.horizon.fxaa);
r.set_hdr(
s.horizon.hdr,
s.horizon.hdr_paper_white as f32,
s.horizon.hdr_peak as f32,
);
}
// Window.updateFullscreenIfChanged: only a changed option asks the
// window to change, so applying settings never undoes a fullscreen
+3 -1
View File
@@ -163,7 +163,7 @@ impl Game<'_> {
self.pack.context.biomes.clone(),
self.pack.context.light.clone(),
)?;
// Keep the working GPU resources, but release its exclusive window surface.
// Keep the working GPU resources, and hand its window surface over.
if let Some(renderer) = &mut self.renderer {
renderer.release_surface();
}
@@ -221,6 +221,8 @@ impl Game<'_> {
self.apply_ui_settings();
}
self.ui.chat.rescale(&self.gui.atlas);
// The creative screen survives the reload; item names may not.
self.creative_screen.forget_items();
Ok(())
}
}
+26 -1
View File
@@ -279,7 +279,8 @@ impl Game<'_> {
k if super::minecarts::CartKind::from_id(k).is_some() => {
let kind = super::minecarts::CartKind::from_id(k).unwrap();
let id = self.next_entity + 1;
if let Some(c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) {
if let Some(mut c) = super::minecarts::Minecart::from_nbt(&tag, id, kind) {
self.roll_cart_loot(&mut c, &tag);
self.next_entity = id;
self.remember(id, uuid, tag);
self.carts.push(c);
@@ -534,6 +535,30 @@ impl Game<'_> {
pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> {
self.persist.raw.get(&id)
}
/// A loaded chest minecart with a loot table and no items: the table
/// rolled now, as generated containers are (Horizon does not unpack on
/// first open), and kept to save it again while unchanged.
fn roll_cart_loot(&self, cart: &mut super::minecarts::Minecart, tag: &Tag) {
let Some(table) = horizon_client::save::text(tag.get("LootTable")) else {
return;
};
if cart.items.is_empty() || cart.items.iter().any(Option::is_some) {
return;
}
let loot = horizon_client::structure_blocks::loot_data(&self.options.resources);
let p = cart.position;
let pos = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
let biome = self.biome_name_at(p).unwrap_or_default();
let seed = horizon_client::structure_blocks::loot_seed(tag);
cart.loot = Some(horizon_client::structure_blocks::roll_container(
&mut cart.items,
loot.as_deref(),
table,
seed,
pos,
&biome,
));
}
fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) {
self.restore_portal_cooldown(id, &tag);
if let Some(u) = uuid {
@@ -71,6 +71,8 @@ pub(super) struct BodyPotions {
pub(super) struct PotionState {
pub(super) effects: PlayerEffects,
thrown: Vec<ThrownPotion>,
/// The area effect clouds a server tracks (game/remote_projectiles.rs).
pub(super) clouds: Vec<super::remote_projectiles::RemoteCloud>,
applied: Vec<(&'static str, &'static str, f64, &'static str)>,
/// Armor the protection table was computed for.
protection_for: Option<Vec<Option<ItemStack>>>,
+79 -5
View File
@@ -109,6 +109,8 @@ enum Received {
pub(super) struct Remote {
pub session: Session,
pub brand: String,
/// The server announced it runs mods' quiet commands.
pub quiet_commands: bool,
pub(super) builtin: Arc<Builtin>,
lang: Arc<Language>,
pub(super) registries: Arc<Dynamic>,
@@ -419,6 +421,7 @@ impl Game<'_> {
self.remote = Some(Remote {
session,
brand: "unknown".into(),
quiet_commands: false,
builtin: Arc::new(builtin),
lang,
registries: Arc::new(Dynamic::default()),
@@ -839,6 +842,11 @@ impl Game<'_> {
remote.brand = brand;
}
}
Event::QuietCommands => {
if let Some(remote) = &mut self.remote {
remote.quiet_commands = true;
}
}
Event::Reconfigured(registries) => {
self.boss_overlay.reset();
self.set_registries(registries);
@@ -1261,6 +1269,9 @@ impl Game<'_> {
} else {
self.res.mob_types().get(kind).cloned()
};
if kind == "minecraft:ender_dragon" {
self.spawn_remote_dragon(id, position, yaw);
}
if kind == "minecraft:experience_orb" {
// Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData.
self.orbs.retain(|o| o.id != id as u32);
@@ -1395,6 +1406,14 @@ impl Game<'_> {
{
return;
}
// A dragon fireball keeps Entity's NO_OP InterpolationHandler too:
// the server's position replaces its own at once.
if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) {
if path.is_some() {
b.position = Vec3::new(position[0], position[1], position[2]);
}
return;
}
if let Some(p) = r.pending_items.get_mut(&id) {
p.0 = position;
}
@@ -1441,6 +1460,8 @@ impl Game<'_> {
self.mobs.retain(|m| m.id != id as u32);
self.orbs.retain(|o| o.id != id as u32);
self.dropped.retain(|d| d.id != id as u32);
// Before the crystals go: the dragon's beam index follows them.
self.remove_remote_dragon(id);
self.remove_remote_object(id as u32);
self.remove_remote_projectile(id as u32);
if let Some(r) = self.remote.as_mut() {
@@ -1973,6 +1994,7 @@ impl Game<'_> {
}
self.remote_object_data(p.id, &p.values);
self.remote_projectile_data(p.id, &p.values);
self.remote_dragon_data(p.id, &p.values);
}
// ClientPacketListener.handleSetEquipment: what a mob or another
// player holds and wears (EquipmentSlot ordinals).
@@ -2054,6 +2076,8 @@ impl Game<'_> {
} else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
m.limb_speed = 1.5;
m.hurt_time = 10;
} else {
self.remote_dragon_hurt(p.id);
}
}
C::HurtAnimation(p) => {
@@ -2063,9 +2087,14 @@ impl Game<'_> {
}
} else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
m.hurt_time = 10;
} else {
self.remote_dragon_hurt(p.id);
}
}
C::EntityEvent(p) => {
if p.event == super::fireworks::FIREWORK_EXPLODE_EVENT {
self.remote_firework_explosion(p.id);
}
// LocalPlayer.setPermissions also refreshes an open World Options screen.
if (24..=28).contains(&p.event)
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
@@ -2079,6 +2108,11 @@ impl Game<'_> {
{
horizon_client::mobs::rabbit::hop_event(m);
}
if p.event == 19
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
{
horizon_client::mobs::aquatic::squid_cycle_event(m);
}
// EntityEvent.DEATH: start the death animation.
if p.event == 3
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
@@ -2951,8 +2985,12 @@ impl Game<'_> {
/// entities whose own tick moves them on a client: dropped items, falling
/// blocks and primed TNT.
fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) {
self.remote_dragon_motion(id, velocity);
let v = Vec3::new(velocity[0], velocity[1], velocity[2]);
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
// Squid.aiStep derives its body pitch and roll from network motion.
m.velocity = v;
} else if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
d.velocity = v;
} else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) {
f.velocity = v;
@@ -2965,6 +3003,8 @@ impl Game<'_> {
.find(|p| p.id == id as u32)
{
p.velocity = v;
} else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) {
b.velocity = v;
} else if let Some(p) = self
.remote
.as_mut()
@@ -3448,6 +3488,13 @@ impl Game<'_> {
if m.species() == horizon_client::mobs::Species::Creeper {
horizon_client::mobs::hostile::creeper_client_tick(m);
}
if matches!(
m.species(),
horizon_client::mobs::Species::Guardian
| horizon_client::mobs::Species::ElderGuardian
) {
horizon_client::mobs::guardian::client_tick(m);
}
if m.hurt_time > 0 {
m.hurt_time -= 1;
}
@@ -3507,6 +3554,8 @@ impl Game<'_> {
} else if m.alive() {
m.body_rotation_tick();
}
// Squid.aiStep follows LivingEntity's interpolation and head turn.
horizon_client::mobs::aquatic::squid_client_step(m);
// WalkAnimationState.update from the horizontal distance moved.
let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z);
let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0);
@@ -3546,6 +3595,18 @@ impl Game<'_> {
self.remote_player_eating(&item, ticks, at, eye, pitch, yaw);
}
if running {
// The dragon: LivingEntity's interpolation, inside its aiStep.
let dragon_lerp = self
.dragon
.as_ref()
.and_then(|d| lerps.get_mut(&(d.id as i32)))
.filter(|l| l.steps > 0)
.map(|l| {
let steps = l.steps;
l.steps -= 1;
(l.target, l.rotation.map(|r| r.0), steps)
});
self.tick_remote_dragon(dragon_lerp);
// Boats, minecarts, armor stands, projectiles and the rest
// interpolate like mobs.
let mut step = |id: u32, at: Vec3| match lerps.get_mut(&(id as i32)) {
@@ -3708,6 +3769,15 @@ impl Game<'_> {
/// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock.
fn remote_mining(&mut self, start: bool) {
if !self
.res
.items()
.can_destroy_block(self.held(), self.creative)
{
self.stop_remote_mining();
self.mining = None;
return;
}
let Some(r) = self.remote.as_mut() else {
return;
};
@@ -4842,16 +4912,20 @@ impl Game<'_> {
if self.open_menu_name(p.container) != "minecraft:merchant" {
return;
}
let cost = |g: &Self, c: &play::NetCost| horizon_client::merchant::ItemCost {
stack: ItemStack::new(&g.item_name(c.item), c.count.max(0) as u32),
let cost = |g: &Self, c: &play::NetCost| {
g.to_stack(&Some(c.clone().into()))
.map(|stack| horizon_client::merchant::ItemCost { stack })
};
let offers: Vec<_> = p
.offers
.iter()
.filter_map(|o| {
let mut offer = horizon_client::merchant::MerchantOffer {
base_cost_a: cost(self, &o.cost_a),
cost_b: o.cost_b.as_ref().map(|b| cost(self, b)),
base_cost_a: cost(self, &o.cost_a)?,
cost_b: match &o.cost_b {
Some(b) => Some(cost(self, b)?),
None => None,
},
result: self.to_stack(&Some(o.result.clone()))?,
uses: o.uses,
max_uses: o.max_uses,
@@ -4,14 +4,14 @@
//! own simulation, which a client of a server doesn't run.
use super::Game;
use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
use horizon_client::mobs::{Mob, Species, bat, tame};
use horizon_client::mobs::{Mob, Species, Who, bat, tame};
use horizon_protocol::entity_data::Value;
use horizon_protocol::registry::Builtin;
/// The values `apply` takes from one SetEntityData packet, by vanilla's entry
/// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses).
/// `builtin` names the ids of built-in registries.
fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_entity: i32) {
let species = m.species();
let baby = super::lan::baby_index(&m.kind.id);
for (index, _, value) in values {
@@ -46,6 +46,19 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
_ => {}
}
match (species, *index, value) {
(Species::Guardian | Species::ElderGuardian, 16, Value::Bool(moving)) => {
m.extra.flag2 = *moving;
}
(Species::Guardian | Species::ElderGuardian, 17, Value::Int(target)) => {
// Guardian.onSyncedDataUpdated resets the visual charge clock.
m.extra.counter2 = 0;
m.extra.flag = *target != 0;
m.ai.target = (*target != 0).then_some(if *target == local_entity {
Who::Player
} else {
Who::Mob(*target as u32)
});
}
// Bat.DATA_ID_FLAGS: resting in bit 0.
(Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0),
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared.
@@ -116,7 +129,7 @@ impl Game<'_> {
return;
};
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
apply(m, values, &r.builtin);
apply(m, values, &r.builtin, r.entity_id);
}
}
}
@@ -153,7 +166,7 @@ mod tests {
}
fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) {
super::apply(m, values, &builtin());
super::apply(m, values, &builtin(), 99);
}
fn mob(kind: &str) -> Option<Mob> {
@@ -164,6 +177,49 @@ mod tests {
Some(m)
}
#[test]
fn guardian_charge_follows_target_updates_and_caps_at_its_duration() {
use horizon_client::mobs::guardian::{beam, client_tick};
for (kind, duration) in [("guardian", 80), ("elder_guardian", 60)] {
let Some(mut m) = mob(&format!("minecraft:{kind}")) else {
return;
};
assert!(beam(&m, 0.0).is_none());
apply(
&mut m,
&[
(16, s::BOOLEAN, Value::Bool(true)),
(17, s::INT, Value::Int(99)),
],
);
assert!(m.extra.flag2);
assert_eq!(m.ai.target, Some(Who::Player));
assert_eq!(beam(&m, 0.0), Some((0.0, 0.0)));
for _ in 0..duration + 10 {
client_tick(&mut m);
}
assert_eq!(beam(&m, 0.0), Some((duration as f32, 1.0)));
// Another player or a mob retains its network entity id.
apply(&mut m, &[(17, s::INT, Value::Int(42))]);
assert_eq!(m.ai.target, Some(Who::Mob(42)));
assert_eq!(m.extra.counter2, 0);
client_tick(&mut m);
assert_eq!(m.extra.counter2, 1);
apply(
&mut m,
&[
(16, s::BOOLEAN, Value::Bool(false)),
(17, s::INT, Value::Int(0)),
],
);
client_tick(&mut m);
assert!(!m.extra.flag2);
assert_eq!(m.ai.target, None);
assert_eq!(m.extra.counter2, 0);
assert!(beam(&m, 0.0).is_none());
}
}
#[test]
fn a_sheep_takes_its_wool_and_a_calf_its_size() {
let Some(mut m) = mob("minecraft:sheep") else {
@@ -3,11 +3,26 @@
//! and `handleSetEntityData`): the server simulates them, the client draws
//! them where it says and interpolates their moves.
use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector};
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_client::projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld};
use horizon_core::{geometry::Vec3, position::BlockPos};
use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
use horizon_protocol::entity_data::Value;
use horizon_world::registry::BlockStateId;
/// An `AreaEffectCloud` a server tracks: what its client tick reads.
pub(super) struct RemoteCloud {
id: u32,
at: [f64; 3],
radius: f32,
waiting: bool,
particle: ParticleOptions,
}
/// `AreaEffectCloud.DEFAULT_PARTICLE`: a white entity effect.
fn default_cloud_particle() -> ParticleOptions {
ParticleOptions::colored(ParticleType::EntityEffect, [1.0; 4])
}
/// The projectile a type id names, as Horizon models it.
fn projectile_kind(kind: &str) -> Option<ProjectileKind> {
Some(match kind {
@@ -118,6 +133,16 @@ impl Game<'_> {
| "minecraft:experience_bottle" => {
self.potions.add_remote_thrown(id, kind, at, velocity);
}
"minecraft:dragon_fireball" => self
.dragon_fireballs
.push(super::dragon::DragonFireball::remote(id, at, velocity)),
"minecraft:area_effect_cloud" => self.potions.clouds.push(RemoteCloud {
id,
at: position,
radius: 3.0,
waiting: false,
particle: default_cloud_particle(),
}),
"minecraft:eye_of_ender" => {
self.end
.add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z])
@@ -151,6 +176,31 @@ impl Game<'_> {
pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
let id = id as u32;
self.remote_hook_data(id, values);
if let Some(at) = self
.potions
.clouds
.iter()
.find(|c| c.id == id)
.map(|c| c.at)
{
// AreaEffectCloud.DATA_RADIUS, DATA_WAITING and DATA_PARTICLE.
for (index, _, value) in values {
let particle = match (index, value) {
(10, Value::Particle(p)) => self.received_particle(p, at),
_ => None,
};
let Some(c) = self.potions.clouds.iter_mut().find(|c| c.id == id) else {
return;
};
match (index, value) {
(8, Value::Float(r)) => c.radius = *r,
(9, Value::Bool(w)) => c.waiting = *w,
(10, _) => c.particle = particle.unwrap_or_else(default_cloud_particle),
_ => {}
}
}
return;
}
if self.rockets.iter().any(|r| r.id == id) {
for (index, _, value) in values {
match (index, value) {
@@ -336,6 +386,75 @@ impl Game<'_> {
self.step_remote_thrown();
self.step_remote_hooks(&mut step);
self.end.step_remote_eyes();
self.tick_remote_clouds();
// The dragon's fireballs fly on between the tracker's updates, with
// their dragon_breath trail (`AbstractHurtingProjectile.getTrailParticle`).
let trail = ParticleOptions::simple(ParticleType::DragonBreath);
for b in &mut self.dragon_fireballs {
let at = b.position;
let water = self
.res
.facts()
.get(self.world.block(
at.x.floor() as i32,
at.y.floor() as i32,
at.z.floor() as i32,
))
.fluid
== horizon_client::blocks::Fluid::Water;
b.remote_step(water);
let p = b.position;
self.particles.add(&trail, [p.x, p.y + 0.5, p.z], [0.0; 3]);
}
}
/// `AreaEffectCloud.clientTick`: while waiting, now and then two
/// particles near the middle; then about one per square block of the
/// disc, drifting (an entity effect stays still).
fn tick_remote_clouds(&mut self) {
for c in &self.potions.clouds {
let r = self.particles.random();
if c.waiting && r.next_boolean() {
continue;
}
let (count, spread) = if c.waiting {
(2, 0.2)
} else {
(
(std::f32::consts::PI * c.radius * c.radius).ceil() as i32,
c.radius,
)
};
for _ in 0..count {
let r = self.particles.random();
let angle = r.next_float() * std::f32::consts::TAU;
let distance = r.next_float().sqrt() * spread;
let at = [
c.at[0] + f64::from(angle.cos() * distance),
c.at[1],
c.at[2] + f64::from(angle.sin() * distance),
];
let (options, velocity) = if c.particle.ty == ParticleType::EntityEffect {
let default = c.waiting && r.next_boolean();
let options = if default {
default_cloud_particle()
} else {
c.particle.clone()
};
(options, [0.0; 3])
} else if c.waiting {
(c.particle.clone(), [0.0; 3])
} else {
let v = [
(0.5 - r.next_double()) * 0.15,
f64::from(0.01f32),
(0.5 - r.next_double()) * 0.15,
];
(c.particle.clone(), v)
};
self.particles.add(&options, at, velocity);
}
}
}
pub(super) fn remove_remote_projectile(&mut self, id: u32) {
@@ -346,6 +465,8 @@ impl Game<'_> {
self.rockets.retain(|r| r.id != id);
self.crystals.retain(|c| c.id != id);
self.potions.remove_remote_thrown(id);
self.potions.clouds.retain(|c| c.id != id);
self.dragon_fireballs.retain(|b| b.id != id);
self.end.remove_remote_eye(id);
self.remove_remote_hook(id);
}
@@ -358,7 +479,11 @@ impl Game<'_> {
self.tridents.clear();
self.rockets.clear();
self.crystals.clear();
// The dragon a server sent goes with its crystals.
self.dragon = None;
self.potions.clear_thrown();
self.potions.clouds.clear();
self.dragon_fireballs.clear();
self.end.clear_remote_eyes();
self.clear_remote_hooks();
}
@@ -84,6 +84,8 @@ impl Game<'_> {
hits.push((c.id as i32, d, [p.x, p.y, p.z]));
}
}
// EnderDragonPart.isPickable: the server's dragon hurts by part.
hits.extend(self.remote_dragon_part_hit(eye, dir, reach));
}
let (id, distance, origin) = hits.into_iter().min_by(|a, b| a.1.total_cmp(&b.1))?;
let point = at(distance);
+1
View File
@@ -179,6 +179,7 @@ impl Game<'_> {
if keys.is_empty() {
self.prune_entity_memory();
self.save_raids();
self.save.save_forced_chunks(&self.streaming.forced)?;
self.save_game_metadata()?;
save.stage = Stage::Writes;
}
@@ -13,6 +13,7 @@ use super::respawn_anchor::RespawnConfig;
use super::{Dim, Game, lan::LanHost};
use horizon_client::{lan::hub::TickCtx, text::Text};
use horizon_core::{geometry::Vec3, position::BlockPos};
use horizon_protocol::packets::play::{self, Clientbound as C};
/// A trip under way: the player is in the destination's level, whose
/// chunks are loading around `target`.
@@ -103,8 +104,35 @@ impl Game<'_> {
if let Some(pos) = self.nether_portal_inside(at) {
self.portals.player.set_inside(pos, PLAYER_DELAY);
}
// `ServerPlayer.showEndCredits`: the player stays out of the world while the
// poem rolls, then PERFORM_RESPAWN takes it to its respawn point.
let play = host.play.entry(conn).or_default();
if play.won_game {
if std::mem::take(&mut play.respawn_requested) {
play.won_game = false;
self.start_server_trip(host, conn, Dim::Overworld, None);
self.portals.player.cooldown = 10;
}
return;
}
let (end_portal, gateway) = self.inside_end_portals(at, WIDTH, HEIGHT);
if end_portal {
// EndPortalBlock.entityInside: the first exit from the End shows the credits.
if self.dim == Dim::End && !host.hub.guest(conn).is_some_and(|g| g.seen_credits) {
if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) {
g.seen_credits = true;
}
host.play.entry(conn).or_default().won_game = true;
// ClientboundGameEventPacket.WIN_GAME.
host.hub.send_to(
conn,
&C::GameEvent(play::GameEvent {
event: 4,
param: 0.0,
}),
);
return;
}
if self.portals.player.cooldown == 0 {
let target = if self.dim == Dim::End {
Dim::Overworld
+6 -2
View File
@@ -398,8 +398,12 @@ impl GameLevel<'_> {
}
}
PreRemove::Campfire => {
for _ in 0..4 {
self.drop_item_stack(pos, None);
let items = match &entity {
Some(BlockEntity::Campfire(c)) => c.items.clone(),
_ => Default::default(),
};
for stack in items {
self.drop_item_stack(pos, stack);
}
}
PreRemove::Jukebox => {
+5 -1
View File
@@ -1703,6 +1703,8 @@ impl Game<'_> {
};
let name = if let Some(n) = stack.custom_name() {
n.to_owned()
} else if let Some(n) = stack.item_name() {
n
} else if stack.data().is_some_and(|d| d.ominous_banner) {
self.translate("block.minecraft.ominous_banner", "Ominous Banner")
} else if stack.data().and_then(|d| d.potion.as_ref()).is_some()
@@ -1729,7 +1731,9 @@ impl Game<'_> {
// ItemContainerContents.addToTooltip.
let hover_name = |s: &ItemStack| {
s.custom_name()
.map_or_else(|| self.pack.names.display_item(&s.item), str::to_owned)
.map(str::to_owned)
.or_else(|| s.item_name())
.unwrap_or_else(|| self.pack.names.display_item(&s.item))
};
if display.shows("minecraft:container") {
for text in
@@ -261,6 +261,7 @@ pub(super) fn make_streaming(
res.threads(),
)
};
streaming.forced = save.load_forced_chunks();
streaming.radius = settings.render_distance;
streaming.biome_blend = settings.biome_blend;
streaming.smooth_lighting = settings.smooth_lighting;
+167 -28
View File
@@ -65,6 +65,7 @@ mod arena;
mod cull;
mod end_sky;
mod flat;
mod hdr;
pub mod lightning;
mod lod;
mod native_material;
@@ -333,6 +334,10 @@ pub struct Renderer {
adapter: wgpu::Adapter,
/// The window's swapchain; `None` when rendering offscreen (`--offscreen`).
surface: Option<wgpu::Surface<'static>>,
/// The surface `release_surface` set aside for the renderer that replaces
/// this one on the same device: reused, not created again, as a new
/// surface for the window can come back lost (Wayland on Mesa).
spare_surface: std::sync::Mutex<Option<wgpu::Surface<'static>>>,
/// The offscreen colour target, sized like `config`.
offscreen: Option<wgpu::Texture>,
/// Offscreen submissions still on the GPU: at most two frames run ahead.
@@ -504,6 +509,10 @@ pub struct Renderer {
occlusion: occlusion::Occlusion,
/// Resolution scale and FXAA (Horizon settings).
world_post: world_post::Post,
/// HDR output (Horizon setting): `Some` while the swapchain is scRGB.
hdr: Option<hdr::Hdr>,
/// Whether the window's surface can present scRGB.
hdr_capable: bool,
/// The shader pack's post-processing, and the dimension (legacy id) it was loaded for.
pack_post: Option<(i32, Option<pack_post::PackPost>)>,
/// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s.
@@ -910,15 +919,24 @@ async fn open_device(
limits.max_storage_buffer_binding_size,
limits.max_texture_array_layers,
));
match adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("Horizon device"),
required_features: features,
required_limits: limits,
..Default::default()
})
.await
{
let desc = wgpu::DeviceDescriptor {
label: Some("Horizon device"),
required_features: features,
required_limits: limits,
..Default::default()
};
#[cfg(not(target_os = "macos"))]
let opened = match info.backend {
wgpu::Backend::Vulkan => horizon_hdr::open_vulkan_device(&adapter, &desc),
_ => None,
};
#[cfg(target_os = "macos")]
let opened = None;
let opened = match opened {
Some(opened) => opened,
None => adapter.request_device(&desc).await,
};
match opened {
Ok((device, queue)) => {
return Ok(Opened {
instance,
@@ -1030,7 +1048,15 @@ impl Renderer {
surface: if offscreen {
None
} else {
Some(renderer.instance.create_surface(window.clone())?)
let spare = renderer
.spare_surface
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
Some(match spare {
Some(surface) => surface,
None => renderer.instance.create_surface(window.clone())?,
})
},
instance: renderer.instance.clone(),
adapter: renderer.adapter.clone(),
@@ -1043,7 +1069,7 @@ impl Renderer {
let info = adapter.get_info();
crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info));
let size = window.inner_size();
let (config, present_modes) = if let Some(surface) = &surface {
let (config, present_modes, hdr_capable) = if let Some(surface) = &surface {
let mut config = surface
.get_default_config(&adapter, size.width.max(1), size.height.max(1))
.ok_or("surface has no supported configuration")?;
@@ -1071,7 +1097,7 @@ impl Renderer {
));
}
surface.configure(&device, &config);
(config, caps.present_modes.clone())
(config, caps.present_modes.clone(), hdr::supported(&caps))
} else {
let format = wgpu::TextureFormat::Bgra8Unorm;
let config = wgpu::SurfaceConfiguration {
@@ -1085,7 +1111,7 @@ impl Renderer {
view_formats: vec![format],
color_space: wgpu::SurfaceColorSpace::default(),
};
(config, Vec::new())
(config, Vec::new(), false)
};
let offscreen = surface
.is_none()
@@ -1929,14 +1955,20 @@ impl Renderer {
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
// RenderPipelines.CELESTIAL: additive (src alpha, one).
// RenderPipelines.CELESTIAL: additive (src alpha, one). The
// alpha goes to 0: HDR output (hdr.wgsl) lets the sun and
// moon shine; nothing else reads the frame's alpha.
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::SrcAlpha,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::OVER,
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
}),
write_mask: wgpu::ColorWrites::ALL,
})],
@@ -2300,6 +2332,7 @@ impl Renderer {
instance,
adapter,
surface,
spare_surface: std::sync::Mutex::new(None),
offscreen,
in_flight: std::collections::VecDeque::new(),
first_frame: if previous.is_none() {
@@ -2420,6 +2453,8 @@ impl Renderer {
block_entity_revision: next_block_entity_revision(),
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
world_post,
hdr: None,
hdr_capable,
pack_post: None,
native: None,
pass_timing: pack_timing::PassTiming::logging(),
@@ -2477,19 +2512,38 @@ impl Renderer {
view_formats: &config.view_formats,
})
}
/// Release the window surface before another renderer uses the same window.
/// Hand the window surface over to the renderer that replaces this one on
/// the same device (it takes `spare_surface`).
pub fn release_surface(&mut self) {
self.surface = None;
*self
.spare_surface
.get_mut()
.unwrap_or_else(std::sync::PoisonError::into_inner) = self.surface.take();
}
/// Reattach a window after surface loss or a failed renderer replacement.
pub fn recreate_surface(&mut self) -> Result<()> {
if self.offscreen.is_some() {
return Ok(());
}
// Wayland allows only one tearing-control object per window surface.
self.release_surface();
let surface = self.instance.create_surface(self.window.clone())?;
surface.configure(&self.device, &self.config);
// The surface set aside for a replacement that failed, else a new one
// (Wayland allows only one tearing-control object per window surface,
// so the old one goes first).
let spare = self
.spare_surface
.get_mut()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
self.surface = None;
let surface = match spare {
Some(surface) => surface,
None => self.instance.create_surface(self.window.clone())?,
};
Self::configure(
&self.device,
&surface,
&self.surface_config(),
self.hdr.as_ref(),
);
self.surface = Some(surface);
Ok(())
}
@@ -2552,7 +2606,12 @@ impl Renderer {
&& let Some(surface) = &self.surface
{
self.config.present_mode = mode;
surface.configure(&self.device, &self.config);
Self::configure(
&self.device,
surface,
&self.surface_config(),
self.hdr.as_ref(),
);
}
}
pub fn resize(&mut self, width: u32, height: u32) {
@@ -2563,7 +2622,12 @@ impl Renderer {
self.config.width = width;
self.config.height = height;
if let Some(surface) = &self.surface {
surface.configure(&self.device, &self.config);
Self::configure(
&self.device,
surface,
&self.surface_config(),
self.hdr.as_ref(),
);
} else {
self.offscreen = Some(Self::offscreen_target(&self.device, &self.config));
}
@@ -2895,6 +2959,63 @@ impl Renderer {
);
}
/// Horizon's resolution scale (world pixels per window pixel) and FXAA.
/// Configures `surface` and, while HDR output is on, sends its HDR metadata
/// again: a new swapchain starts without it.
fn configure(
device: &wgpu::Device,
surface: &wgpu::Surface<'_>,
config: &wgpu::SurfaceConfiguration,
hdr: Option<&hdr::Hdr>,
) {
surface.configure(device, config);
if let Some(hdr) = hdr {
horizon_hdr::set_metadata(device, surface, hdr.paper_white, hdr.peak);
}
}
fn configure_surface(&self) {
if let Some(surface) = &self.surface {
Self::configure(
&self.device,
surface,
&self.surface_config(),
self.hdr.as_ref(),
);
}
}
fn send_hdr_metadata(&self) {
if let (Some(surface), Some(hdr)) = (&self.surface, &self.hdr) {
horizon_hdr::set_metadata(&self.device, surface, hdr.paper_white, hdr.peak);
}
}
/// The swapchain's configuration: `config` (what every pipeline draws in), or
/// scRGB while HDR output is on.
fn surface_config(&self) -> wgpu::SurfaceConfiguration {
let mut config = self.config.clone();
if self.hdr.is_some() {
config.format = hdr::FORMAT;
config.view_formats = vec![hdr::FORMAT];
config.color_space = hdr::COLOR_SPACE;
config.usage = wgpu::TextureUsages::RENDER_ATTACHMENT;
}
config
}
/// HDR output (Horizon setting): scRGB at `paper_white` nits, the world's
/// highlights expanded up to `peak` nits. Off where the surface can't present it.
pub fn set_hdr(&mut self, on: bool, paper_white: f32, peak: f32) {
let on = on && self.hdr_capable && self.surface.is_some();
if on != self.hdr.is_some() {
self.hdr =
on.then(|| hdr::Hdr::new(&self.device, self.config.format.remove_srgb_suffix()));
self.configure_surface();
}
if let Some(hdr) = &mut self.hdr
&& (hdr.paper_white, hdr.peak) != (paper_white, peak)
{
hdr.paper_white = paper_white;
hdr.peak = peak;
self.send_hdr_metadata();
}
}
pub fn set_world_post(&mut self, scale: f32, antialias: bool) {
self.world_post.scale = scale.clamp(0.25, 2.0);
self.world_post.antialias = antialias;
@@ -3230,7 +3351,12 @@ impl Renderer {
}
Some(wgpu::CurrentSurfaceTexture::Outdated) => {
if let Some(surface) = &self.surface {
surface.configure(&self.device, &self.config);
Self::configure(
&self.device,
surface,
&self.surface_config(),
self.hdr.as_ref(),
);
}
return Ok(false);
}
@@ -3242,9 +3368,11 @@ impl Renderer {
return Err("surface acquisition failed validation".into());
}
};
let target_texture = match &surface_frame {
Some(f) => f.texture.clone(),
None => self.offscreen.clone().ok_or("no offscreen target")?,
let size = [self.config.width, self.config.height];
let target_texture = match (&surface_frame, &mut self.hdr) {
(Some(_), Some(hdr)) => hdr.frame(&self.device, size),
(Some(f), None) => f.texture.clone(),
(None, _) => self.offscreen.clone().ok_or("no offscreen target")?,
};
// One command buffer for the frame, after the section copies staged
// since the last one: Metal commits every command buffer wgpu-core
@@ -4642,6 +4770,9 @@ impl Renderer {
} else if scaled.is_some() {
self.world_post.finish(&mut encoder, &view_target);
}
if let Some(hdr) = &self.hdr {
hdr.keep_world(&mut encoder);
}
if hand_quads > 0 && !pack_draws_hand {
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view_target,
@@ -4796,6 +4927,9 @@ impl Renderer {
self.section_copy_bytes = 0;
self.section_uploads.finish(&encoder);
}
if let (Some(hdr), Some(f)) = (&self.hdr, &surface_frame) {
hdr.present(&self.queue, &mut encoder, &f.texture, !frame.title);
}
let commands = crate::spans::time("encode", || encoder.finish());
let first_frame = self.first_frame == FirstFrame::Submit;
if first_frame {
@@ -4832,7 +4966,12 @@ impl Renderer {
}
self.queue.present(surface_frame);
if reconfigure && let Some(surface) = &self.surface {
surface.configure(&self.device, &self.config);
Self::configure(
&self.device,
surface,
&self.surface_config(),
self.hdr.as_ref(),
);
}
} else {
// No swapchain paces offscreen frames: keep two on the GPU at most.
+222
View File
@@ -0,0 +1,222 @@
//! HDR output (Horizon setting, off by default): the frame renders exactly as
//! without it, into an 8-bit target in vanilla's gamma space, and one pass
//! (`hdr.wgsl`) writes it to an scRGB swapchain at the player's paper white,
//! expanding the world's highlights towards their peak brightness. The world
//! is copied aside before the hand and HUD so only it is expanded.
/// The swapchain format and colour space HDR output presents in.
pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
pub const COLOR_SPACE: wgpu::SurfaceColorSpace = wgpu::SurfaceColorSpace::ExtendedSrgbLinear;
/// Whether `caps` can present scRGB.
pub fn supported(caps: &wgpu::SurfaceCapabilities) -> bool {
caps.color_spaces(FORMAT)
.contains(wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR)
}
struct Targets {
size: [u32; 2],
frame: wgpu::Texture,
world: wgpu::Texture,
group: wgpu::BindGroup,
}
pub struct Hdr {
layout: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
params: wgpu::Buffer,
/// The frame's format: what every other pipeline draws in.
format: wgpu::TextureFormat,
targets: Option<Targets>,
/// `HORIZON_HDR_DEBUG=1`: paint expanded pixels magenta.
debug: bool,
/// Paper white and peak brightness, in nits.
pub paper_white: f32,
pub peak: f32,
}
impl Hdr {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon HDR"),
source: wgpu::ShaderSource::Wgsl(include_str!("../hdr.wgsl").into()),
});
let texture = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon HDR bindings"),
entries: &[
texture(0),
texture(1),
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Horizon HDR"),
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Horizon HDR"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_hdr"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_hdr"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: FORMAT,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let params = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon HDR parameters"),
size: 16,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
Self {
layout,
pipeline,
params,
format,
targets: None,
debug: std::env::var_os("HORIZON_HDR_DEBUG").is_some_and(|v| v == "1"),
paper_white: 200.0,
peak: 1000.0,
}
}
/// The 8-bit frame every pass draws into this frame, sized like the window.
pub fn frame(&mut self, device: &wgpu::Device, size: [u32; 2]) -> wgpu::Texture {
if self.targets.as_ref().is_none_or(|t| t.size != size) {
let texture = |label, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size[0].max(1),
height: size[1].max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: usage | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
};
let frame = texture(
"Horizon HDR frame",
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
);
let world = texture("Horizon HDR world", wgpu::TextureUsages::COPY_DST);
let view = |t: &wgpu::Texture| t.create_view(&Default::default());
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon HDR bindings"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&view(&frame)),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&view(&world)),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.params.as_entire_binding(),
},
],
});
self.targets = Some(Targets {
size,
frame,
world,
group,
});
}
self.targets.as_ref().unwrap().frame.clone()
}
/// Keeps the world as drawn so far, before the hand and HUD cover it.
pub fn keep_world(&self, encoder: &mut wgpu::CommandEncoder) {
let Some(t) = &self.targets else {
return;
};
encoder.copy_texture_to_texture(
t.frame.as_image_copy(),
t.world.as_image_copy(),
t.frame.size(),
);
}
/// Writes the finished frame to the swapchain image `target`.
pub fn present(
&self,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::Texture,
world: bool,
) {
let Some(t) = &self.targets else {
return;
};
let paper = self.paper_white.max(1.0);
let params = [
paper / 80.0,
(self.peak / paper).max(1.0),
f32::from(u8::from(world)),
f32::from(u8::from(self.debug)),
];
queue.write_buffer(&self.params, 0, bytemuck::cast_slice(&params));
let view = target.create_view(&Default::default());
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view,
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 HDR"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &t.group, &[]);
pass.draw(0..3, 0..1);
}
}
@@ -36,7 +36,7 @@ fn horizon_material_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color
out.clip = horizon_terrain_globals.view_proj * vec4(pos, 1.0);
out.uv = uv;
out.layer = layer;
out.tint = color;
out.tint = vec4(color.rgb, 1.0);
let block = max(f32(light.y), horizon_terrain_dynamic_block_light(pos));
let sky = f32(light.x);
// 16 per level, 15 levels.
+2 -1
View File
@@ -169,6 +169,7 @@ impl PackAtlas {
];
let columns = self.columns;
// UVs past a sprite (models up to 2, distant tiles) cannot repeat in an atlas: clamped.
// The colour's alpha holds HDR's emission level (`mesher::EMISSION_BITS`): packs get 1.
let body = format!(
" vec4 hz_origin = {origin};\n \
uint hz_layer = hz_v_layer & 32767u;\n \
@@ -178,7 +179,7 @@ impl PackAtlas {
hz_MultiTexCoord0 = vec4((hz_cell + clamp(vec2(hz_v_uv) * hz_origin.w, 0.0, 1.0)) * hz_scale, 0.0, 1.0);\n \
hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
hz_Color = hz_v_color;\n \
hz_Color = vec4(hz_v_color.rgb, 1.0);\n \
hz_Normal = vec3(0.0, 1.0, 0.0);\n \
hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\n",
scale[0], scale[1],
+19 -1
View File
@@ -255,6 +255,12 @@ pub struct Graphics {
pub resolution_scale: u32,
/// FXAA over the world.
pub fxaa: bool,
/// HDR output (scRGB), where the display path offers it.
pub hdr: bool,
/// HDR paper white (where SDR white sits), in nits.
pub hdr_paper_white: u32,
/// HDR peak brightness the world's highlights reach, in nits.
pub hdr_peak: u32,
/// Battery mode: at most 60 frames per second in a world and 30 in menus
/// or behind other windows, and half the worker threads. Off by default;
/// it changes when frames are drawn, never what they show or the ticks.
@@ -286,6 +292,9 @@ impl Default for Graphics {
overlay: Overlay::Off,
resolution_scale: 100,
fxaa: false,
hdr: false,
hdr_paper_white: 200,
hdr_peak: 1000,
battery: false,
api: GraphicsApi::Auto,
shader_pack: String::new(),
@@ -337,6 +346,9 @@ impl Graphics {
"workers" => g.workers = number(g.workers).min(64),
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
"fxaa" => g.fxaa = flag(g.fxaa),
"hdr" => g.hdr = flag(g.hdr),
"hdrPaperWhite" => g.hdr_paper_white = number(g.hdr_paper_white).clamp(80, 480),
"hdrPeak" => g.hdr_peak = number(g.hdr_peak).clamp(200, 2000),
"batteryMode" => g.battery = flag(g.battery),
"graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(),
"pickedShaderPack" => g.shader_pack = value.to_owned(),
@@ -354,7 +366,7 @@ impl Graphics {
}
pub fn serialize(&self) -> String {
format!(
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n",
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nhdr:{}\nhdrPaperWhite:{}\nhdrPeak:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n",
self.preset.name(),
self.lod_distance,
self.far_detail.name(),
@@ -379,6 +391,9 @@ impl Graphics {
},
self.resolution_scale,
bool_text(self.fxaa),
bool_text(self.hdr),
self.hdr_paper_white,
self.hdr_peak,
bool_text(self.battery),
self.api.name(),
self.shader_pack,
@@ -476,6 +491,9 @@ mod tests {
overlay: Overlay::Graph,
resolution_scale: 75,
fxaa: true,
hdr: true,
hdr_paper_white: 240,
hdr_peak: 1400,
battery: true,
api: GraphicsApi::Dx12,
shader_pack: "Golden Hour".into(),
+27
View File
@@ -37,6 +37,9 @@ pub enum H {
Overlay,
ResolutionScale,
Antialiasing,
Hdr,
HdrPaperWhite,
HdrPeak,
BatteryMode,
GraphicsApi,
}
@@ -221,6 +224,21 @@ pub fn rows(level: Level) -> Vec<Row> {
Medium,
"FXAA smooths jagged edges of the world; slightly softer image.",
),
h(
H::Hdr,
None,
"HDR output on an HDR display: lava, fire and sunlight shine brighter.",
),
h(
H::HdrPaperWhite,
None,
"HDR: how bright white paper and menus look. Match your desktop.",
),
h(
H::HdrPeak,
None,
"HDR: how bright the brightest highlights get. Your display's peak.",
),
h(
H::PresentMode,
None,
@@ -324,6 +342,8 @@ impl H {
}
H::Workers => Some(g.workers as f32 / max_workers() as f32),
H::ResolutionScale => Some((g.resolution_scale as f32 - 50.0) / 150.0),
H::HdrPaperWhite => Some((g.hdr_paper_white as f32 - 80.0) / 400.0),
H::HdrPeak => Some((g.hdr_peak as f32 - 200.0) / 1800.0),
_ => None,
}
}
@@ -365,6 +385,9 @@ impl H {
},
H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)),
H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }),
H::Hdr => labelled("HDR", on_off(g.hdr)),
H::HdrPaperWhite => labelled("Paper White", format!("{} nits", g.hdr_paper_white)),
H::HdrPeak => labelled("Peak Brightness", format!("{} nits", g.hdr_peak)),
H::BatteryMode => labelled("Battery Mode", on_off(g.battery)),
H::GraphicsApi => labelled("Graphics API", g.api.label()),
H::Overlay => labelled(
@@ -387,6 +410,8 @@ impl H {
}
H::Workers => g.workers = (v * max_workers() as f32).round() as u32,
H::ResolutionScale => g.resolution_scale = (50.0 + (v * 30.0).round() * 5.0) as u32,
H::HdrPaperWhite => g.hdr_paper_white = (80.0 + (v * 40.0).round() * 10.0) as u32,
H::HdrPeak => g.hdr_peak = (200.0 + (v * 36.0).round() * 50.0) as u32,
_ => {}
}
}
@@ -418,6 +443,7 @@ impl H {
H::AnimatedTextures => g.animated_textures = !g.animated_textures,
H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back),
H::Antialiasing => g.fxaa = !g.fxaa,
H::Hdr => g.hdr = !g.hdr,
H::BatteryMode => g.battery = !g.battery,
H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back),
H::Pacing => {
@@ -453,6 +479,7 @@ impl Item {
Item::Horizon(H::Weather) => g.weather,
Item::Horizon(H::AnimatedTextures) => g.animated_textures,
Item::Horizon(H::Antialiasing) => g.fxaa,
Item::Horizon(H::Hdr) => g.hdr,
Item::Horizon(H::BatteryMode) => g.battery,
Item::Vanilla(Opt::ViewBobbing) => s.view_bobbing,
Item::Vanilla(Opt::Vsync) => s.vsync,
+69
View File
@@ -0,0 +1,69 @@
// Horizon's HDR output pass: the frame, drawn as without HDR in vanilla's gamma
// space, decoded to linear light at the paper white and written to the scRGB
// swapchain (1.0 = 80 nits). Bright pixels of light sources that still show the
// world as it was before the hand and HUD are expanded towards the peak.
@group(0) @binding(0) var frame: texture_2d<f32>;
@group(0) @binding(1) var world: texture_2d<f32>;
struct Params {
// Paper white in scRGB units (nits / 80).
paper: f32,
// Peak brightness relative to paper white; 1 expands nothing.
peak: f32,
// 1 when this frame drew a world.
world: f32,
// 1 paints expanded pixels magenta (HORIZON_HDR_DEBUG=1).
debug: f32,
};
@group(0) @binding(2) var<uniform> params: Params;
// Light sources are lifted evenly rather than by a highlight curve: vanilla's
// textures were drawn for SDR, so a curve on their brightest pixels blows out
// near-white spots (glowstone) and leaves the rest (lava, a jack o'lantern's
// face) nearly as it was. Pixels brighter than LIFT_FULL get STRENGTH of the
// headroom, dimmer ones less down to none at LIFT_START (lava's crust, a
// lantern's metal), and no channel goes past the peak. Brightness is the mean
// of luminance and the brightest channel, so saturated light counts as bright.
const LIFT_START: f32 = 0.18;
const LIFT_FULL: f32 = 0.42;
const STRENGTH: f32 = 0.7;
// Whether `c` still shows the world pixel `w`: the same, or darkened evenly
// across its channels, as the vignette and other screen-wide tints darken it.
// The hand, HUD and text replace pixels instead, so they never pass.
fn shows_world(c: vec3<f32>, w: vec3<f32>) -> bool {
if all(c == w) {
return true;
}
let k = c / max(w, vec3(1.0 / 255.0));
let mean = (k.r + k.g + k.b) / 3.0;
return mean <= 1.01 && mean > 0.5 && all(abs(k - vec3(mean)) < vec3(0.03));
}
@vertex fn vs_hdr(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
return vec4(p * 2.0 - 1.0, 0.0, 1.0);
}
@fragment fn fs_hdr(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let at = vec2<i32>(pos.xy);
let c = textureLoad(frame, at, 0).rgb;
// Gamma 2.2, as SDR displays and the compositors' SDR paths decode it.
var light = pow(max(c, vec3(0.0)), vec3(2.2));
let w = textureLoad(world, at, 0);
// The world's alpha is 0 on light-emitting blocks, the sun and the moon
// (terrain.wgsl, the celestial pipeline): only those shine.
if params.world > 0.5 && params.peak > 1.0 && w.a < 0.75 && shows_world(c, w.rgb) {
let y = 0.5 * (dot(light, vec3(0.2126, 0.7152, 0.0722)) + max(light.r, max(light.g, light.b)));
let lift = smoothstep(LIFT_START, LIFT_FULL, y);
if lift > 0.0 {
let top = max(light.r, max(light.g, light.b));
let gain = min(1.0 + (params.peak - 1.0) * STRENGTH * lift, params.peak / max(top, 1e-4));
light *= max(gain, 1.0);
if params.debug > 0.5 {
light = mix(light, vec3(gain, 0.0, gain), 0.6);
}
}
}
return vec4(light * params.paper, 1.0);
}
+8
View File
@@ -204,6 +204,14 @@ impl ItemStack {
pub fn custom_name(&self) -> Option<&str> {
self.data().and_then(|d| d.custom_name.as_deref())
}
/// `minecraft:item_name` in the current language (`getItemName`'s
/// component). It stays in the patch as loaded, so a translatable name
/// saves and reaches clients unchanged; the ominous banner's is modelled
/// by `ominous_banner` instead.
pub fn item_name(&self) -> Option<String> {
let name = self.data()?.other("minecraft:item_name")?;
Some(crate::entity_nbt::name_text(name).plain())
}
pub fn potion(&self) -> Option<&str> {
self.data().and_then(|d| d.potion.as_deref())
}
+4
View File
@@ -363,6 +363,9 @@ pub struct ItemRenderer {
sprites: FileSprites,
baked: Mutex<HashMap<String, Arc<BakedItemModel>>>,
extents: Mutex<HashMap<String, Arc<Vec<Vec3>>>>,
/// GUI items already drawn: the HUD vertices of a static item at a GUI position
/// (`gui::draw`), which are the same every frame it stays there.
pub(crate) gui_drawn: Mutex<HashMap<gui::DrawnKey, Arc<[crate::hud::HudVertex]>>>,
/// Entity model layers of the special renderers.
parts: HashMap<String, ModelPart>,
/// `colormap/grass.png` as ARGB.
@@ -452,6 +455,7 @@ impl ItemRenderer {
},
baked: Mutex::default(),
extents: Mutex::default(),
gui_drawn: Mutex::default(),
parts,
grass,
})
+90 -1
View File
@@ -8,7 +8,7 @@
use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost};
use crate::hud::{HudBatch, Rect};
use glam::{EulerRot, Mat4, Vec2, Vec3};
use std::{collections::HashMap, f32::consts::PI};
use std::{collections::HashMap, f32::consts::PI, sync::Arc};
mod depth;
@@ -148,6 +148,95 @@ pub fn draw(
if state.is_empty() {
return;
}
// A static item drawn where it was drawn before gives the same vertices:
// take them instead of submitting, sorting and clipping its quads again.
let key = DrawnKey::of(state, renderer, sprites, x, y);
if let Some(key) = &key
&& let Some(drawn) = renderer
.gui_drawn
.lock()
.ok()
.and_then(|d| d.get(key).cloned())
{
batch.vertices.extend_from_slice(&drawn);
return;
}
let start = batch.vertices.len();
draw_now(state, renderer, sprites, host, batch, x, y, time);
if let Some(key) = key
&& let Ok(mut drawn) = renderer.gui_drawn.lock()
{
// GUI positions and items are few; a long scroll through every tab stays bounded.
if drawn.len() >= DRAWN_LIMIT {
drawn.clear();
}
drawn.insert(key, batch.vertices[start..].into());
}
}
/// Entries of `ItemRenderer::gui_drawn` before it starts over.
const DRAWN_LIMIT: usize = 8192;
/// What a GUI item's vertices depend on: its layers' baked models (kept for the
/// renderer's life, so their addresses name them), tints and transforms, the
/// atlas, and the exact position. None for items whose drawing changes with time
/// or the host: a glint, or a special model renderer.
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct DrawnKey {
renderer: usize,
sprites: (usize, usize),
at: [u32; 2],
oversized: bool,
layers: Vec<(usize, Vec<i32>, [u32; 16], bool)>,
}
impl DrawnKey {
fn of(
state: &ItemRenderState,
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
x: f32,
y: f32,
) -> Option<Self> {
if state.animated {
return None;
}
let layers = state
.layers
.iter()
.map(|layer| match &layer.geometry {
super::LayerGeometry::Quads(baked) if layer.foil == super::FoilType::None => {
Some((
Arc::as_ptr(baked) as usize,
layer.tints.clone(),
layer.matrix.to_cols_array().map(f32::to_bits),
layer.uses_block_light,
))
}
_ => None,
})
.collect::<Option<Vec<_>>>()?;
Some(Self {
renderer: std::ptr::from_ref(renderer) as usize,
sprites: (std::ptr::from_ref(sprites) as usize, sprites.len()),
at: [x.to_bits(), y.to_bits()],
oversized: state.oversized_in_gui,
layers,
})
}
}
/// [`draw`] without the cache.
#[allow(clippy::too_many_arguments)]
fn draw_now(
state: &ItemRenderState,
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
host: &dyn SpecialHost,
batch: &mut HudBatch,
x: f32,
y: f32,
time: f32,
) {
let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0))
* Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0));
let mut quads: Vec<ItemQuad> = Vec::new();
+85
View File
@@ -238,6 +238,85 @@ mod tests {
use super::*;
use horizon_protocol::registry::Ids;
#[test]
fn merchant_water_cost_survives_the_offer_packet() {
use horizon_protocol::{
buf::{Codec, Reader, Writer},
packets::play::{NetOffer, Offers},
};
let mut components = vec![String::new(); component::POTION_CONTENTS as usize + 1];
components[component::POTION_CONTENTS as usize] = "minecraft:potion_contents".into();
let builtin = Builtin {
registries: [
(
"minecraft:item".into(),
Ids::from_names(vec!["minecraft:potion".into(), "minecraft:emerald".into()]),
),
(
"minecraft:potion".into(),
Ids::from_names(vec!["minecraft:water".into()]),
),
(
"minecraft:data_component_type".into(),
Ids::from_names(components),
),
]
.into(),
};
let dynamic = Dynamic::default();
let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water");
let wire = crate::lan::guest::stack_to_network(
|name| builtin.get("minecraft:item").unwrap().id(name).unwrap(),
|registry, name| builtin.get(registry)?.id(name),
&Some(water.clone()),
)
.unwrap();
let offers = vec![NetOffer {
cost_a: wire.into(),
result: Stack::new(1, 1),
cost_b: Some(Stack::new(1, 2).into()),
out_of_stock: false,
uses: 0,
max_uses: 2,
xp: 0,
special_price: 0,
price_multiplier: 0.05,
demand: 0,
}];
let mut w = Writer::new();
Offers::write(&offers, &mut w);
let mut r = Reader::new(&w.data);
let decoded = Offers::read(&mut r).unwrap();
assert_eq!(r.remaining(), 0);
let cost = crate::merchant::ItemCost {
stack: from_network(&decoded[0].cost_a.clone().into(), &builtin, &dynamic),
};
assert_eq!(cost.stack, water);
assert_eq!(cost.stack.potion(), Some("minecraft:water"));
let authoritative = crate::merchant::ItemCost {
stack: water.clone(),
};
for payment in [
water,
ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness"),
ItemStack::new("minecraft:potion", 1),
] {
assert_eq!(cost.test(&payment), authoritative.test(&payment));
}
assert!(cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water")));
assert!(
!cost.test(&ItemStack::new("minecraft:potion", 1).with_potion("minecraft:swiftness"))
);
let emerald = crate::merchant::ItemCost {
stack: from_network(
&decoded[0].cost_b.clone().unwrap().into(),
&builtin,
&dynamic,
),
};
assert!(emerald.test(&ItemStack::new("minecraft:emerald", 2)));
}
/// A bundle's contents cross the wire, so a server's client can draw
/// its tooltip (BundleContents' stream codec: a list of templates).
#[test]
@@ -286,6 +365,7 @@ mod tests {
for (id, name) in [
(component::DAMAGE, "minecraft:damage"),
(component::CUSTOM_NAME, "minecraft:custom_name"),
(component::ITEM_NAME, "minecraft:item_name"),
(component::ENCHANTMENTS, "minecraft:enchantments"),
(component::POTION_CONTENTS, "minecraft:potion_contents"),
(component::REPAIR_COST, "minecraft:repair_cost"),
@@ -345,6 +425,10 @@ mod tests {
.push((Arc::from("minecraft:sharpness"), 2));
d.repair_cost = 9;
d.custom_name = Some("Keeper".to_owned());
// A translatable item name reaches the client as the same component.
let item_name = Tag::compound([("translate", Tag::String("filled_map.monument".into()))]);
d.other
.push(("minecraft:item_name".into(), item_name.clone()));
d.trim = Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry")));
let id = |registry: &str, name: &str| {
builtin
@@ -374,6 +458,7 @@ mod tests {
);
assert_eq!(d.repair_cost, 9);
assert_eq!(d.custom_name.as_deref(), Some("Keeper"));
assert_eq!(d.other("minecraft:item_name"), Some(&item_name));
assert_eq!(
d.trim,
Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry")))
+11
View File
@@ -188,6 +188,9 @@ pub fn name_line(stack: &ItemStack, translate: &dyn Fn(&str) -> Option<String>)
if let Some(name) = stack.custom_name() {
return name.to_owned();
}
if let Some(name) = stack.item_name() {
return name;
}
if stack.data().is_some_and(|d| d.ominous_banner) {
return translate("block.minecraft.ominous_banner")
.unwrap_or_else(|| "Ominous Banner".to_owned());
@@ -611,6 +614,14 @@ mod tests {
assert_eq!(rarity(&banner, "common"), "uncommon");
banner.data_mut().custom_name = Some("Captain's Standard".into());
assert_eq!(name_line(&banner, &translate), "Captain's Standard");
let mut custom_item = ItemStack::new("minecraft:diamond_sword", 1);
custom_item.data_mut().other.push((
"minecraft:item_name".into(),
Tag::String("Excalibur".into()),
));
assert_eq!(name_line(&custom_item, &translate), "Excalibur");
custom_item.data_mut().custom_name = Some("Custom Blade".into());
assert_eq!(name_line(&custom_item, &translate), "Custom Blade");
banner.enchant("minecraft:unbreaking", 1);
assert_eq!(rarity(&banner, "common"), "rare");
let plain = ItemStack::new("minecraft:white_banner", 1);
+26
View File
@@ -71,6 +71,8 @@ pub struct ItemInfo {
/// The `tool` component's `damage_per_block`, when the item has the
/// component (a mace or trident has one without rules).
pub tool_damage_per_block: Option<u32>,
/// `tool.can_destroy_blocks_in_creative` (defaults to true).
pub can_destroy_blocks_in_creative: bool,
pub food: Option<(u32, f32)>,
pub can_always_eat: bool,
/// `consumable`: its timing, sound, particles and `on_consume_effects`.
@@ -558,6 +560,10 @@ impl Items {
tool_damage_per_block: c
.get("minecraft:tool")
.map(|t| t["damage_per_block"].as_u64().unwrap_or(1) as u32),
can_destroy_blocks_in_creative:
c["minecraft:tool"]["can_destroy_blocks_in_creative"]
.as_bool()
.unwrap_or(true),
food,
can_always_eat,
// Consumable.CODEC's defaults.
@@ -758,6 +764,26 @@ impl Items {
None => spec == block,
}
}
/// `Item.canDestroyBlock`: a tool may forbid block destruction with instabuild.
pub fn can_destroy_block(&self, held: Option<&ItemStack>, creative: bool) -> bool {
if !creative {
return true;
}
let Some(held) = held.filter(|s| s.count > 0 && &*s.item != "minecraft:air") else {
return true;
};
if let Some(tool) = held.data().and_then(|d| d.other("minecraft:tool")) {
return tool
.get("can_destroy_blocks_in_creative")
.and_then(|v| match v {
horizon_world::nbt::Tag::Byte(v) => Some(*v),
_ => None,
})
.is_none_or(|v| v != 0);
}
self.get(&held.item)
.is_none_or(|info| info.can_destroy_blocks_in_creative)
}
/// `Tool.getMiningSpeed` for the held item (1.0 without a tool component).
pub fn mining_speed(&self, held: Option<&ItemStack>, block: &str) -> f32 {
let Some(info) = held.and_then(|s| self.get(&s.item)) else {
+5
View File
@@ -952,6 +952,11 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
Some(Tag::compound(entries))
}
BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None,
// CampfireBlockEntity.getUpdateTag: the items alone.
BlockEntity::Campfire(c) => Some(Tag::compound([(
"Items",
crate::save::encode_items(&c.items),
)])),
_ => None,
}
}
+10
View File
@@ -237,6 +237,8 @@ pub struct Guest {
pub drag: Option<(u8, Vec<usize>)>,
/// The compound this player was loaded from, for fields Horizon does not model.
pub saved: Option<horizon_world::nbt::Tag>,
/// `ServerPlayer.seenCredits`: the end poem has been shown.
pub seen_credits: bool,
/// `ServerPlayer.recipeBook`.
pub recipe_book: crate::recipe_book::Settings,
/// `PlayerAdvancements`: the criteria obtained, whether they came from
@@ -358,6 +360,7 @@ impl Guest {
next_window: 0,
drag: None,
saved: None,
seen_credits: false,
recipe_book: Default::default(),
advancements: Default::default(),
advancements_loaded: false,
@@ -645,6 +648,13 @@ fn network_stack(
horizon_protocol::item::Component::Text(horizon_protocol::text::literal(name)),
));
}
// The component as loaded, so a translatable name stays one.
if let Some(name) = s.data().and_then(|d| d.other("minecraft:item_name")) {
stack.added.push((
horizon_protocol::item::component::ITEM_NAME,
horizon_protocol::item::Component::Text(name.clone()),
));
}
Some(stack)
}
+7 -1
View File
@@ -37,6 +37,10 @@ pub struct Menu {
pub sent_data: Vec<i16>,
}
/// The y of the key a chest minecart's or chest boat's items are kept under
/// while a menu shows them.
pub const VEHICLE_KEY_Y: i32 = -100_000;
/// Where the slots of a container menu live.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Slots {
@@ -72,10 +76,12 @@ impl Slots {
Slots::Ender => at.into_iter().collect(),
_ => self.halves(),
};
// A vehicle's container is kept under a key, not a block: the game
// checks its reach to the vehicle (`isChestVehicleStillValid`).
self.valid(world)
&& blocks
.iter()
.all(|k| guest.within_block_range([k.0, k.1, k.2], 4.0))
.all(|k| k.1 == VEHICLE_KEY_Y || guest.within_block_range([k.0, k.1, k.2], 4.0))
}
/// Container slot `n`.
pub fn get(self, world: &World, guest: &Guest, mut n: usize) -> Option<ItemStack> {
@@ -85,6 +85,7 @@ 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();
guest.seen_credits = level.seen_credits;
let extra = level.player_extra.as_ref();
let short = |key: &str, default: i64| {
extra
@@ -166,6 +167,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]);
level.respawn_elsewhere = guest.respawn_elsewhere.clone();
level.on_ground = guest.on_ground;
level.seen_credits = guest.seen_credits;
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.
+17 -1
View File
@@ -113,6 +113,14 @@ mod vertex_tests {
assert!((a - b).abs() <= 0.5 / 32768.0, "{a} {b}");
}
}
#[test]
fn emission_keeps_the_colour_and_the_free_bits() {
let rgb = super::pack_rgb([0x12, 0x34, 0x56]);
assert_eq!(super::emitting(rgb, 0), rgb);
assert_eq!(super::emitting(rgb, 9), 0xF656_3412);
assert_eq!(super::emitting(rgb, 15), 0xF056_3412);
assert_eq!(super::emitting(rgb, 15) | super::EMISSION_BITS, rgb);
}
}
pub struct SectionMesh {
pub solid: Vec<TerrainVertex>,
@@ -566,6 +574,14 @@ impl Padded {
}
/// Set on a terrain vertex's sprite layer when its texture alpha must be ignored.
pub const OPAQUE_LAYER: u16 = 1 << 15;
/// The bits of `TerrainVertex::color`'s alpha byte that hold the light its face emits, for
/// HDR output's highlights (`gfx/hdr.rs`): 15 minus the level, so the usual 0xFF means none.
/// The byte's other four bits stay set.
pub const EMISSION_BITS: u32 = 0x0F00_0000;
/// `color` marked as emitting light `level` (0 to 15).
pub fn emitting(color: u32, level: u8) -> u32 {
color & !EMISSION_BITS | u32::from(15 - level.min(15)) << 24
}
const UNSET: u32 = u32::MAX;
const NO_BIOME: u16 = u16::MAX;
/// The `ColorResolver`s `ClientLevel` caches block tints for.
@@ -880,7 +896,7 @@ impl Mesher<'_> {
} else {
face.layer as u16
},
pack_rgb(rgb),
emitting(pack_rgb(rgb), state.emission.max(q.light_emission)),
pack_coords(lighting::with_emission(coords[i], q.light_emission)),
));
}
+4 -1
View File
@@ -227,8 +227,11 @@ pub(super) fn tesselate(
} else {
0xFF_FFFF
};
// Lava emits light level 15.
let emission = if water { 0 } else { 15 };
let color = |by: f32| {
pack_rgb([16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32))
let rgb = [16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32);
crate::mesher::emitting(pack_rgb(rgb), emission)
};
let height = |p: [i32; 3]| -> f32 {
let s = at(p);
+5
View File
@@ -868,6 +868,11 @@ pub struct Mob {
/// Events a mob tick asks the game to act on.
#[derive(Clone, Debug)]
pub enum MobEvent {
/// Squid.handleEntityEvent(19), resetting the remote tentacle cycle.
SquidCycle {
mob: u32,
at: [f64; 3],
},
/// Rabbit entity event 1, sent only when a ground jump actually happens.
RabbitHop {
mob: u32,
+50 -11
View File
@@ -234,12 +234,40 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
/// Squid.aiStep: tentacle cycle, propulsion and body rotation.
fn squid_ai_step(m: &mut Mob) {
squid_step(m, false);
}
/// Squid.aiStep also runs on remote entities: animate from packet velocity,
/// without running goals or replacing that velocity with the server's movement vector.
pub fn squid_client_step(m: &mut Mob) {
if matches!(m.species(), Species::Squid | Species::GlowSquid) {
m.anim.vo = m.anim.v;
squid_step(m, true);
}
}
/// Squid.handleEntityEvent(19): begin the next server-synchronised tentacle cycle.
pub fn squid_cycle_event(m: &mut Mob) {
if matches!(m.species(), Species::Squid | Species::GlowSquid) {
m.anim.v[TENTACLE_MOVEMENT] = 0.0;
}
}
fn squid_step(m: &mut Mob, client: bool) {
let v = &mut m.anim.v;
v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED];
if v[TENTACLE_MOVEMENT] > PI * 2.0 {
v[TENTACLE_MOVEMENT] -= PI * 2.0;
if m.random.next_int_bound(10).unwrap_or(1) == 0 {
m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2;
if f64::from(v[TENTACLE_MOVEMENT]) > std::f64::consts::TAU {
if client {
v[TENTACLE_MOVEMENT] = PI * 2.0;
} else {
v[TENTACLE_MOVEMENT] -= PI * 2.0;
if m.random.next_int_bound(10).unwrap_or(1) == 0 {
m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2;
}
m.outbox.push(MobEvent::SquidCycle {
mob: m.id,
at: [m.position.x, m.position.y, m.position.z],
});
}
}
let v = &mut m.anim.v;
@@ -248,28 +276,39 @@ fn squid_ai_step(m: &mut Mob) {
let scale = v[TENTACLE_MOVEMENT] / PI;
v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25;
if scale > 0.75 {
let mv = m.extra.vector;
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
if !client {
let mv = m.extra.vector;
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
}
m.anim.v[ROTATE_SPEED] = 1.0;
} else {
m.anim.v[ROTATE_SPEED] *= 0.8;
}
} else {
v[TENTACLE_ANGLE] = 0.0;
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
if !client {
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
}
m.anim.v[ROTATE_SPEED] *= 0.99;
}
let mv = m.velocity;
let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt();
m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1;
m.body_yaw += (-(horizon_core::geometry::trig::atan2(mv.x, mv.z) as f32) * 57.295776
- m.body_yaw)
* 0.1;
m.yaw = m.body_yaw;
let v = &mut m.anim.v;
v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5;
v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1;
v[X_BODY_ROT] += (-(horizon_core::geometry::trig::atan2(horizontal, mv.y) as f32)
* 57.295776
- v[X_BODY_ROT])
* 0.1;
} else {
v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25;
let yd = m.velocity.y - m.kind.gravity;
m.velocity = Vec3::new(0.0, yd * 0.98, 0.0);
if !client {
let yd = m.velocity.y - m.kind.gravity;
m.velocity = Vec3::new(0.0, yd * 0.98, 0.0);
}
let v = &mut m.anim.v;
v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02;
}
+8 -3
View File
@@ -241,9 +241,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
} else {
a.v[SPIKES] += (1.0 - a.v[SPIKES]) * 0.06;
}
if m.extra.flag && m.extra.counter2 < attack_duration(m) {
m.extra.counter2 += 1;
}
client_tick(m);
if in_water {
m.air = 300;
} else if m.on_ground {
@@ -332,6 +330,13 @@ pub fn elder_server_ai_step(m: &mut Mob, cx: &mut Cx) {
]);
}
}
/// Guardian.aiStep's visual attack clock, also used by server clients.
/// Does not run attack goals, movement, damage or random draws.
pub fn client_tick(m: &mut Mob) {
if m.extra.flag && m.extra.counter2 < attack_duration(m) {
m.extra.counter2 += 1;
}
}
/// The beam's clock for rendering: (attack time with the partial tick,
/// attack scale), while a target is locked.
pub fn beam(m: &Mob, partial: f32) -> Option<(f32, f32)> {
+4
View File
@@ -40,6 +40,8 @@ pub enum Event {
Status(String),
/// The server's `minecraft:brand` custom payload.
Brand(String),
/// The server runs mods' quiet commands (`horizon_protocol::quiet`).
QuietCommands,
/// Configuration finished: the play state begins with these registries.
Joined {
registries: Arc<Dynamic>,
@@ -668,6 +670,8 @@ fn receive_brand(payload: &cfg::CustomPayload, send: &Sender<Event>) {
&& let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767)
{
let _ = send.send(Event::Brand(brand));
} else if payload.channel == horizon_protocol::quiet::CHANNEL {
let _ = send.send(Event::QuietCommands);
}
}
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -175,7 +175,9 @@ pub fn increased_repair_cost(cost: u32) -> u32 {
pub fn hover_name(names: &dyn Fn(&str) -> String, stack: &ItemStack) -> String {
stack
.custom_name()
.map_or_else(|| names(&stack.item), str::to_owned)
.map(str::to_owned)
.or_else(|| stack.item_name())
.unwrap_or_else(|| names(&stack.item))
}
/// `AnvilMenu.createResult`. `name` is the rename box text (None = untouched).
pub fn anvil_result(
+86 -63
View File
@@ -108,9 +108,10 @@ pub fn has_pending_map(item: &ItemStack) -> bool {
})
}
static LOOT: OnceLock<Option<Arc<LootData>>> = OnceLock::new();
/// Loot data of the resource root, loaded once per process.
pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
static LOOT: OnceLock<Option<Arc<LootData>>> = OnceLock::new();
LOOT.get_or_init(|| match LootData::load(root) {
Ok(data) => Some(Arc::new(data)),
Err(e) => {
@@ -121,6 +122,54 @@ pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
.clone()
}
/// The loot data `loot_data` loaded, if it ran.
pub fn loaded_loot_data() -> Option<Arc<LootData>> {
LOOT.get().cloned().flatten()
}
/// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table`
/// rolled into `slots`. A missing or zero seed is the level's random in
/// vanilla; Horizon derives one from the position. Without loot data the
/// container stays empty and still saves its table.
pub fn roll_container(
slots: &mut [Option<ItemStack>],
loot: Option<&LootData>,
table: String,
saved_seed: Option<i64>,
pos: (i32, i32, i32),
biome: &str,
) -> crate::save::RolledLoot {
let seed = saved_seed.filter(|s| *s != 0).unwrap_or_else(|| {
horizon_core::random::position_seed(horizon_core::position::BlockPos::new(
pos.0, pos.1, pos.2,
))
});
if let Some(loot) = loot {
// LootTable.fill spreads the items over the container's own size.
let rolled = loot.fill(&table, seed, slots.len(), Some(biome));
for (slot, stack) in slots.iter_mut().zip(rolled) {
// With what the rolls put on them: enchantments
// (enchant_with_levels in End city chests), potions and an
// ominous bottle's level.
*slot = stack.map(|s| loot_item_with_components(&s));
}
}
crate::save::RolledLoot {
pos,
table,
seed: saved_seed,
items: crate::save::encode_items(slots),
}
}
/// A saved `LootTableSeed`, if any.
pub fn loot_seed(nbt: &Tag) -> Option<i64> {
match nbt.get("LootTableSeed") {
Some(Tag::Long(seed)) => Some(*seed),
_ => None,
}
}
fn text(nbt: &Compound, key: &str) -> Option<String> {
match nbt.get(&JavaString::from(key)) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
@@ -149,81 +198,37 @@ fn generated_block_entity(block: &str, nbt: &Compound) -> Option<BlockEntity> {
Some(entity)
}
/// Client block entities for the generated block entities of a chunk.
/// Client block entities for the generated block entities of a chunk, and the
/// loot rolled into its containers.
pub fn block_entities(
chunk: &ProtoChunk,
loot: Option<&LootData>,
) -> Vec<((i32, i32, i32), BlockEntity)> {
) -> (
Vec<((i32, i32, i32), BlockEntity)>,
Vec<crate::save::RolledLoot>,
) {
let mut out = Vec::new();
let mut rolled = Vec::new();
for (pos, nbt) in &chunk.block_entities {
let [x, y, z] = *pos;
let block = chunk.block_name(x, y, z);
let Some(mut entity) = generated_block_entity(block, nbt) else {
continue;
};
if let (BlockEntity::Chest(slots), Some(table), Some(loot)) =
(&mut entity, text(nbt, "LootTable"), loot)
{
let seed = match nbt.get(&JavaString::from("LootTableSeed")) {
Some(Tag::Long(seed)) => *seed,
// Seed 0 means "the level's random": derive one from the position.
_ => horizon_core::random::position_seed(horizon_core::position::BlockPos::new(
x, y, z,
)),
};
let biome = chunk.biome_at(x, y, z);
for (slot, stack) in slots
.iter_mut()
.zip(loot.fill(&table, seed, 27, Some(biome)))
{
// With what the rolls put on them: enchantments
// (enchant_with_levels in End city chests), potions and an
// ominous bottle's level.
*slot = stack.map(|s| loot_item_with_components(&s));
}
if let (BlockEntity::Chest(slots), Some(table)) = (&mut entity, text(nbt, "LootTable")) {
let seed = loot_seed(&Tag::Compound(nbt.clone()));
rolled.push(roll_container(
slots,
loot,
table,
seed,
(x, y, z),
chunk.biome_at(x, y, z),
));
}
out.push(((x, y, z), entity));
}
out
}
/// Chest minecarts placed with a loot table (mineshafts): the table rolled
/// into `Items` as `unpackLootTable` would on first open.
pub fn unpack_entity_loot(
chunk: &ProtoChunk,
mut nbt: horizon_world::nbt::Compound,
loot: Option<&LootData>,
) -> horizon_world::nbt::Compound {
let (Some(table), Some(loot)) = (
match nbt.get(&JavaString::from("LootTable")) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
},
loot,
) else {
return nbt;
};
let seed = match nbt.get(&JavaString::from("LootTableSeed")) {
Some(Tag::Long(seed)) => *seed,
_ => 0,
};
let pos = match nbt.get(&JavaString::from("Pos")) {
Some(Tag::List(p)) => std::array::from_fn(|i| match p.get(i) {
Some(Tag::Double(b)) => f64::from_bits(*b).floor() as i32,
_ => 0,
}),
_ => [0; 3],
};
let biome = chunk.biome_at(pos[0], pos[1], pos[2]);
let slots: Vec<Option<ItemStack>> = loot
.fill(&table, seed, 27, Some(biome))
.into_iter()
.map(|s| s.map(|s| loot_item_with_components(&s)))
.collect();
nbt.remove(&JavaString::from("LootTable"));
nbt.remove(&JavaString::from("LootTableSeed"));
nbt.insert("Items".into(), crate::save::encode_items(&slots));
nbt
(out, rolled)
}
#[cfg(test)]
@@ -270,6 +275,24 @@ mod tests {
assert_eq!(arrow.potion(), Some("minecraft:slowness"));
}
#[test]
fn a_container_rolled_without_loot_data_saves_its_table() {
let mut slots = vec![None; 27];
let rolled = roll_container(
&mut slots,
None,
"minecraft:chests/simple_dungeon".into(),
Some(7),
(1, 2, 3),
"minecraft:plains",
);
let mut saved = horizon_world::nbt::Compound::new();
saved.insert("Items".into(), crate::save::encode_items(&slots));
assert!(rolled.restore(&mut saved));
assert!(!saved.contains_key(&"Items".into()));
assert_eq!(saved.get(&"LootTableSeed".into()), Some(&Tag::Long(7)));
}
#[test]
fn exploration_maps_wait_in_custom_data_until_searched() {
let mut stack = LootStack {
+8 -2
View File
@@ -69,6 +69,8 @@ struct TerrainOut {
@location(2) color: vec4<f32>,
@location(3) spherical: f32,
@location(4) cylindrical: f32,
// The light the face emits, 0 to 15 (mesher.rs's `EMISSION_BITS`).
@location(5) @interpolate(flat) emission: u32,
}
// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units
// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one
@@ -121,7 +123,8 @@ fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f3
out.uv = uv;
out.layer = layer;
let block = max(f32(light.y), dynamic_block_light(pos));
out.color = color * sample_lightmap(f32(light.x) / 16.0, block / 16.0);
out.color = vec4(color.rgb, 1.0) * sample_lightmap(f32(light.x) / 16.0, block / 16.0);
out.emission = 15u - (u32(round(color.a * 255.0)) & 15u);
out.spherical = length(pos);
out.cylindrical = max(length(pos.xz), abs(pos.y));
return out;
@@ -140,7 +143,10 @@ fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
// Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
let color = sprite(in.uv, in.layer & 0x7fffu) * in.color;
if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; }
return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical);
// Alpha 0 tells HDR output (hdr.wgsl) a light-emitting block's bright pixels
// may shine. Nothing else reads the frame's alpha.
let emissive = select(1.0, 0.0, in.emission > 0u);
return apply_fog(vec4(color.rgb, emissive), in.spherical, in.cylindrical);
}
@fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4<f32> {
let color = sprite(in.uv, in.layer & 0x7fffu) * in.color;
+20 -10
View File
@@ -158,6 +158,12 @@ impl VanillaTerrain {
chunk.terrain.min_y().max(MIN_Y),
(chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT),
);
out.structure_refs = chunk
.structures()
.into_iter()
.map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z)))
.collect();
out.structure_starts = chunk.own_starts();
let mut values = Box::new([0u32; 4096]);
for si in 0..SECTIONS as i32 {
let base = MIN_Y + si * 16;
@@ -436,6 +442,14 @@ impl ChunkGenerator for VanillaTerrain {
.iter()
.map(|(pos, nbt)| {
let mut nbt = nbt.clone();
// Placed data can lack its type (a brushable block's loot table
// alone); vanilla saves every pending block entity with its id,
// and skips one without when the chunk finishes.
if let Some(id) =
crate::lan::chunks::block_entity_type(chunk.block_name(pos[0], pos[1], pos[2]))
{
nbt.insert("id".into(), Tag::String(id.into()));
}
for (key, v) in ["x", "y", "z"].into_iter().zip(pos) {
nbt.insert(key.into(), Tag::Int(*v));
}
@@ -533,7 +547,9 @@ impl ChunkGenerator for VanillaTerrain {
VanillaProto::Failed(x, z) => return Chunk::empty(x, z),
};
let mut out = self.column(&chunk);
out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref());
let (block_entities, rolled_loot) =
crate::structure_blocks::block_entities(&chunk, self.loot.as_deref());
out.block_entities = block_entities;
// The block entities Horizon does not model (decorated pots with their
// sherds and loot table, brushable blocks) stay as placed, like a
// loaded chunk's.
@@ -557,26 +573,20 @@ impl ChunkGenerator for VanillaTerrain {
Some(Tag::Compound(nbt))
})
.collect();
if !unmodelled.is_empty() {
if !unmodelled.is_empty() || !rolled_loot.is_empty() {
let mut extras = out
.saved
.take()
.map(Arc::unwrap_or_clone)
.unwrap_or_default();
extras.block_entities = unmodelled;
extras.rolled_loot = rolled_loot;
out.saved = Some(Arc::new(extras));
}
out.structure_refs = chunk
.structures()
.into_iter()
.map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z)))
.collect();
let entities = std::mem::take(&mut chunk.entities);
// Chest minecarts keep their loot table; the game rolls it on load.
out.entities = entities
.into_iter()
.map(|nbt| {
crate::structure_blocks::unpack_entity_loot(&chunk, nbt, self.loot.as_deref())
})
.map(horizon_world::nbt::Tag::Compound)
.collect();
for s in &mut out.sections {
+7 -5
View File
@@ -18,7 +18,8 @@ struct PostOut {
}
@fragment fn fs_copy(in: PostOut) -> @location(0) vec4<f32> {
return vec4(textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb, 1.0);
// The alpha carries the emissive mark through to HDR output (hdr.wgsl).
return textureSampleLevel(world, world_sampler, in.uv, 0.0);
}
fn luma(c: vec3<f32>) -> f32 {
@@ -28,7 +29,8 @@ fn luma(c: vec3<f32>) -> f32 {
// FXAA 3.11 (console quality): blend along the local edge direction.
@fragment fn fs_fxaa(in: PostOut) -> @location(0) vec4<f32> {
let texel = 1.0 / vec2<f32>(textureDimensions(world));
let rgb_m = textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb;
let centre = textureSampleLevel(world, world_sampler, in.uv, 0.0);
let rgb_m = centre.rgb;
let nw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, -0.5) * texel, 0.0).rgb);
let ne = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(0.5, -0.5) * texel, 0.0).rgb);
let sw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, 0.5) * texel, 0.0).rgb);
@@ -37,7 +39,7 @@ fn luma(c: vec3<f32>) -> f32 {
let lo = min(m, min(min(nw, ne), min(sw, se)));
let hi = max(m, max(max(nw, ne), max(sw, se)));
if hi - lo < max(0.0312, hi * 0.125) {
return vec4(rgb_m, 1.0);
return centre;
}
var dir = vec2(-((nw + ne) - (sw + se)), (nw + sw) - (ne + se));
let reduce = max((nw + ne + sw + se) * 0.25 * 0.125, 1.0 / 128.0);
@@ -49,7 +51,7 @@ fn luma(c: vec3<f32>) -> f32 {
+ textureSampleLevel(world, world_sampler, in.uv + dir * 0.5, 0.0).rgb);
let lb = luma(b);
if lb < lo || lb > hi {
return vec4(a, 1.0);
return vec4(a, centre.a);
}
return vec4(b, 1.0);
return vec4(b, centre.a);
}
@@ -315,3 +315,70 @@ fn saved_proto_chunks_restore_exactly() {
drop(save);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn saved_proto_block_entities_keep_their_id() {
use horizon_client::{
save::{Persistent, SaveDir},
vanillagen::VanillaTerrain,
};
use horizon_world::{
nbt::{Limits, Tag},
region::RegionFile,
};
let Some(root) = resources() else {
return;
};
let assets = Arc::new(Assets::load(&root).unwrap());
let biomes = Arc::new(Biomes::load(&root).unwrap());
let terrain = VanillaTerrain::for_dimension(
&root.join("worldgen"),
assets.registry,
&biomes,
12345,
"minecraft:overworld",
)
.unwrap();
let dir = std::env::temp_dir().join(format!("horizon-proto-ids-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let save = Arc::new(SaveDir::new(dir.clone()));
let generator = Persistent {
inner: Arc::new(terrain),
save: save.clone(),
registry: assets.clone(),
biomes,
};
let mut worker = generator.worker();
// A cold ocean ruin of seed 12345: its suspicious gravel is placed with a
// loot table and no type.
let keys: Vec<(i32, i32)> = (0..9).map(|i| (43 + i % 3 - 1, 21 + i / 3 - 1)).collect();
let mut region: [Proto; 9] =
std::array::from_fn(|i| generator.proto(&mut worker, keys[i].0, keys[i].1));
generator.decorate(&mut worker, &mut region);
generator.save_protos(&region.iter().collect::<Vec<_>>());
save.flush().unwrap();
let mut file = RegionFile::open(dir.join("region/r.1.0.mca")).unwrap();
let mut suspicious = 0;
for &(x, z) in &keys {
let Some(record) = file
.read(horizon_core::position::ChunkPos::new(x, z))
.unwrap()
else {
continue;
};
let root = record.nbt(Limits::default()).unwrap();
let Some(Tag::List(entities)) = root.tag.get("block_entities") else {
continue;
};
for e in entities {
assert!(e.get("id").is_some(), "chunk {x} {z}: {e:?}");
if let Some(Tag::String(table)) = e.get("LootTable") {
suspicious += usize::from(table.to_string_lossy().contains("archaeology/"));
}
}
}
assert!(suspicious > 0, "the ruin placed no suspicious blocks");
drop(generator);
drop(save);
let _ = std::fs::remove_dir_all(&dir);
}
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "horizon-hdr"
version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.85"
description = "HDR metadata for the swapchain: the Vulkan calls the crates that forbid unsafe code can't make"
[dependencies]
wgpu = { version = "30.0.1", default-features = false, features = ["vulkan"] }
[target.'cfg(not(target_os = "macos"))'.dependencies]
# The version wgpu-hal already uses.
ash = { version = "0.38", default-features = false }
[lints]
workspace = true
+95
View File
@@ -0,0 +1,95 @@
//! HDR metadata for the swapchain: the Vulkan calls the game crate, which
//! forbids unsafe code, can't make itself. wgpu sets no HDR metadata, and
//! without it a compositor may clip or tone-map everything above 1.0 (80 nits)
//! of an scRGB swapchain.
/// Opens a Vulkan device with `VK_EXT_hdr_metadata` too, when the GPU offers
/// it, so [`set_metadata`] can tell the compositor the real peak brightness.
/// `None` leaves opening to wgpu.
#[cfg(not(target_os = "macos"))]
pub fn open_vulkan_device(
adapter: &wgpu::Adapter,
desc: &wgpu::DeviceDescriptor<'_>,
) -> Option<Result<(wgpu::Device, wgpu::Queue), wgpu::RequestDeviceError>> {
use wgpu::hal::api::Vulkan;
let open = {
// Safety: only read and opened from here; dropped before wgpu takes it back.
let hal = unsafe { adapter.as_hal::<Vulkan>() }?;
let instance = hal.shared_instance().raw_instance();
// Safety: the adapter's own physical device on its own instance.
let offered =
unsafe { instance.enumerate_device_extension_properties(hal.raw_physical_device()) }
.ok()?
.iter()
.any(|e| e.extension_name_as_c_str() == Ok(ash::ext::hdr_metadata::NAME));
if !offered {
return None;
}
// Safety: what wgpu's own request_device does, with one more extension.
unsafe {
hal.open_with_callback(
desc.required_features,
&desc.required_limits,
&desc.memory_hints,
Some(Box::new(
|args: wgpu::hal::vulkan::CreateDeviceCallbackArgs| {
args.extensions.push(ash::ext::hdr_metadata::NAME);
},
)),
)
}
.ok()?
};
// Safety: opened from this adapter with exactly `desc`'s features.
Some(unsafe { adapter.create_device_from_hal(open, desc) })
}
/// Tells the compositor, through `VK_EXT_hdr_metadata`, that the swapchain's
/// content is BT.709 and peaks at `peak` nits. Needs a device from
/// `open_vulkan_device` and a configured surface; does nothing otherwise.
pub fn set_metadata(
device: &wgpu::Device,
surface: &wgpu::Surface<'_>,
paper_white: f32,
peak: f32,
) {
#[cfg(not(target_os = "macos"))]
{
use wgpu::hal::api::Vulkan;
// Safety: read-only access to handles wgpu keeps alive while these guards live.
let (Some(hal_device), Some(hal_surface)) =
(unsafe { device.as_hal::<Vulkan>() }, unsafe {
surface.as_hal::<Vulkan>()
})
else {
return;
};
if !hal_device
.enabled_device_extensions()
.contains(&ash::ext::hdr_metadata::NAME)
{
return;
}
let Some(swapchain) = hal_surface.raw_native_swapchain() else {
return;
};
let xy = |x, y| ash::vk::XYColorEXT { x, y };
let metadata = ash::vk::HdrMetadataEXT::default()
.display_primary_red(xy(0.64, 0.33))
.display_primary_green(xy(0.30, 0.60))
.display_primary_blue(xy(0.15, 0.06))
.white_point(xy(0.3127, 0.3290))
.max_luminance(peak)
.min_luminance(0.0)
.max_content_light_level(peak)
.max_frame_average_light_level(paper_white.min(peak));
let loader = ash::ext::hdr_metadata::Device::new(
hal_device.shared_instance().raw_instance(),
hal_device.raw_device(),
);
// Safety: a live swapchain of this device, one metadata entry for it.
unsafe { loader.set_hdr_metadata(&[swapchain], &[metadata]) };
}
#[cfg(target_os = "macos")]
let _ = (device, surface, paper_white, peak);
}
+8
View File
@@ -111,6 +111,14 @@ interface storage {
interface command {
/// `line` without its slash; its feedback goes to the chat as if typed.
run: func(line: string);
/// `lines` (each without its slash, at most 256 a call) as `run` does,
/// but with nothing in the chat: no feedback and no failure. In single
/// player and on Horizon's servers, each runs exactly as the player
/// typing it would (the same rights), in order, 64 a tick, and the
/// server logs one line a batch; one that carries a chat message (`say`,
/// `msg`) is refused. On any other server they go as chat commands, and
/// there their feedback shows: a mod running many should say so.
run-quiet: func(lines: list<string>);
}
/// Capability `ui`: widgets the game draws with its own menus' widgets, for
+3 -2
View File
@@ -7,13 +7,13 @@
//! version's level so the launcher can tell before it installs.
/// The newest level this Horizon serves.
pub const LEVEL: u32 = 2;
pub const LEVEL: u32 = 3;
/// Every function the game offers mods, as `interface.function`, with its
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
/// function takes the next level and raises [`LEVEL`] (the `api_reference`
/// test fails until it is listed here).
pub const FUNCTIONS: [(&str, u32); 33] = [
pub const FUNCTIONS: [(&str, u32); 34] = [
("log.write", 0),
("game.get-player", 0),
("game.get-clock", 0),
@@ -47,6 +47,7 @@ pub const FUNCTIONS: [(&str, u32); 33] = [
("players.tell", 1),
("players.broadcast", 1),
("game.raycast", 2),
("command.run-quiet", 3),
];
/// What the game's program carries so the launcher can read its level
+23
View File
@@ -89,6 +89,9 @@ const FUEL_FRAME: u64 = 10_000_000;
const FUEL_EVENT: u64 = 100_000_000;
/// Chat lines a mod may show per call, HUD lines and their length.
const CHAT_PER_CALL: usize = 8;
/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's
/// cap, `horizon_protocol::quiet::MAX_LINES`).
const QUIET_PER_CALL: usize = 256;
/// How far `game.raycast` sees, in blocks.
pub const RAYCAST_MAX: f32 = 1024.0;
const HUD_LINES: usize = 16;
@@ -160,6 +163,9 @@ pub enum Output {
/// `command.run`: a vanilla command line, without its slash, to run as
/// the player.
Command { line: String },
/// `command.run-quiet`: vanilla command lines to run as the player with
/// nothing in the chat (`horizon_protocol::quiet` on a server).
QuietCommands { mod_id: String, lines: Vec<String> },
/// The mod was turned off: it trapped, overran or failed to start.
Stopped { name: String, reason: String },
/// `players.tell`: a line after the mod's name, to the player with this id.
@@ -1408,6 +1414,23 @@ impl command::Host for State {
self.out.push(Output::Command { line: clip(line) });
}
}
fn run_quiet(&mut self, lines: Vec<String>) {
let queued: usize = self
.out
.iter()
.map(|o| match o {
Output::QuietCommands { lines, .. } => lines.len(),
_ => 0,
})
.sum();
let room = QUIET_PER_CALL.saturating_sub(queued);
if room > 0 && !lines.is_empty() {
self.out.push(Output::QuietCommands {
mod_id: self.id.clone(),
lines: lines.into_iter().take(room).map(clip).collect(),
});
}
}
}
impl hud::Host for State {
fn set_panel(&mut self, corner: Corner, lines: Vec<Line>) {
+27 -1
View File
@@ -26,7 +26,7 @@ id = "test_ui_guest"
name = "Test UI Guest"
version = "0.1.0"
api = "0.1"
capabilities = ["game-read", "chat", "ui", "render", "input"]
capabilities = ["game-read", "chat", "command", "ui", "render", "input"]
experimental = ["ui", "render", "input"]
"#;
@@ -763,6 +763,32 @@ fn game_raycast_sees_the_view_hit_within_its_distance() {
assert_eq!(said(&mut mods, "1e9"), [hit]);
}
#[test]
fn quiet_commands_come_out_as_one_batch_capped() {
let mut mods = load("horizon_mods_test_ui_guest.hmod");
let quiet = |mods: &mut Mods, command: &str| -> Vec<(String, Vec<String>)> {
assert!(mods.command(command));
mods.drain()
.into_iter()
.filter_map(|o| match o {
Output::QuietCommands { mod_id, lines } => Some((mod_id, lines)),
_ => None,
})
.collect()
};
assert_eq!(
quiet(&mut mods, "quiet setblock 0 0 0 stone;say hi"),
[(
"test_ui_guest".to_string(),
vec!["setblock 0 0 0 stone".to_string(), "say hi".to_string()]
)]
);
let batches = quiet(&mut mods, "quiet_many 300");
assert_eq!(batches.len(), 1);
assert_eq!(batches[0].1.len(), 256);
assert_eq!(batches[0].1[255], "setblock 255 300 0 stone");
}
#[test]
fn corner_panels_text_width_and_readings() {
let mut mods = load("horizon_mods_test_ui_guest.hmod");
+14 -2
View File
@@ -5,9 +5,10 @@
//! `/input_claim`, `/input_poll`, `/input_held` and `/input_wheel` test
//! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`;
//! `/corner` and `/readings` the calls the official extras mods use;
//! `/raycast DISTANCE` says what `game.raycast` sees.
//! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs
//! lines with `command.run-quiet` (`/quiet_many N`: N of them).
use horizon_mod_sdk::{
Mod, Registration, chat, game,
Mod, Registration, chat, command, game,
input::{self, Event},
render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape},
ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget},
@@ -99,6 +100,8 @@ impl Mod for Guest {
"zoom",
"minimap",
"raycast",
"quiet",
"quiet_many",
"corner",
"readings",
]
@@ -219,6 +222,15 @@ impl Mod for Guest {
});
render::set_minimap(map);
}
"quiet" => command::run_quiet(&args.split(';').map(str::to_owned).collect::<Vec<_>>()),
"quiet_many" => {
let n: usize = args.parse().unwrap_or(0);
command::run_quiet(
&(0..n)
.map(|i| format!("setblock {i} 300 0 stone"))
.collect::<Vec<_>>(),
);
}
"raycast" => {
let distance = args.parse().unwrap_or(f32::NAN);
chat::show(&match game::raycast(distance) {
+40 -3
View File
@@ -91,8 +91,9 @@ pub fn keep(
pub fn parse(spec: &str) -> Option<ureq::Proxy> {
if socks(spec) {
say(&format!(
"{spec} is a SOCKS proxy; downloads go without one. Write the http:// address your \
proxy app listens on as well."
"{} is a SOCKS proxy; downloads go without one. Write the http:// address your \
proxy app listens on as well.",
redacted(spec)
));
return None;
}
@@ -100,13 +101,29 @@ pub fn parse(spec: &str) -> Option<ureq::Proxy> {
Ok(proxy) => Some(proxy),
Err(e) => {
say(&format!(
"The proxy address {spec} can't be used ({e}); downloads go without one."
"The proxy address {} can't be used ({e}); downloads go without one.",
redacted(spec)
));
None
}
}
}
/// `spec` as it may be shown: a user name and password in it become `***`. An address that can't
/// be used is printed to stderr and shown in the launcher, and a proxy's credentials don't belong in
/// either. Everything up to the last `@` is the credentials, so a password with an unescaped `/` or
/// `@` is hidden too.
pub fn redacted(spec: &str) -> String {
let (scheme, rest) = match spec.split_once("://") {
Some((scheme, rest)) => (format!("{scheme}://"), rest),
None => (String::new(), spec),
};
match rest.rfind('@') {
Some(at) => format!("{scheme}***@{}", &rest[at + 1..]),
None => spec.to_owned(),
}
}
/// Whether `spec` names a SOCKS proxy, which these downloads don't go through: `ureq` reads a
/// SOCKS address happily and only fails when it connects through it.
pub fn socks(spec: &str) -> bool {
@@ -227,6 +244,26 @@ mod tests {
lock(&TURN)
}
#[test]
fn credentials_are_not_shown() {
assert_eq!(redacted("http://127.0.0.1:7890"), "http://127.0.0.1:7890");
assert_eq!(redacted("proxy.local:3128"), "proxy.local:3128");
assert_eq!(
redacted("http://user:pass@proxy.local:3128"),
"http://***@proxy.local:3128"
);
assert_eq!(
redacted("socks5://u:p@10.0.0.1:1080"),
"socks5://***@10.0.0.1:1080"
);
assert_eq!(
redacted("user:pass@proxy.local:3128"),
"***@proxy.local:3128"
);
assert_eq!(redacted("http://u:p/a@ss@proxy:1"), "http://***@proxy:1");
assert_eq!(redacted("http://user:pass@"), "http://***@");
}
#[test]
fn a_proxy_the_launcher_sets_is_trimmed_and_kept() {
let _turn = alone();
+2 -2
View File
@@ -164,7 +164,7 @@ pub struct Profile {
pub properties: Vec<(String, String, Option<String>)>,
}
impl Component {
fn read(kind: i32, r: &mut Reader) -> Result<Self> {
pub(crate) fn read(kind: i32, r: &mut Reader) -> Result<Self> {
use component::*;
Ok(match kind {
MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID
@@ -338,7 +338,7 @@ impl Component {
}
})
}
fn write(&self, kind: i32, w: &mut Writer) {
pub(crate) fn write(&self, kind: i32, w: &mut Writer) {
match self {
Self::Raw(bytes) => w.bytes(bytes),
Self::Trim { material, pattern } => {
+72 -8
View File
@@ -8,7 +8,7 @@ use crate::{
},
chunk::{ChunkData, LightData},
entity_data::{EntityData, Particle, Value},
item::{Hashed, HashedSlot, Slot, Stack},
item::{Component, Hashed, HashedSlot, Slot, Stack},
packet, packet_enum,
packets::{
Empty,
@@ -88,11 +88,31 @@ packet!(ContainerSetContent {
carried: Option<Stack> => Slot,
});
/// ItemCost.STREAM_CODEC: item, count, then the exact component predicate
/// (Horizon sends and reads it as a component patch without removals).
/// (a list of typed component values, with no patch removal count).
#[derive(Clone, Debug, PartialEq)]
pub struct NetCost {
pub item: i32,
pub count: i32,
pub components: Vec<(i32, Component)>,
}
impl From<Stack> for NetCost {
fn from(stack: Stack) -> Self {
Self {
item: stack.item,
count: stack.count,
components: stack.added,
}
}
}
impl From<NetCost> for Stack {
fn from(cost: NetCost) -> Self {
Self {
item: cost.item,
count: cost.count,
added: cost.components,
removed: Vec::new(),
}
}
}
/// MerchantOffer.STREAM_CODEC.
#[derive(Clone, Debug, PartialEq)]
@@ -114,10 +134,17 @@ impl Codec<Vec<NetOffer>> for Offers {
fn cost(r: &mut Reader) -> Result<NetCost> {
let item = r.varint()?;
let count = r.varint()?;
if r.varint()? != 0 {
return Err(Error::new("item cost components are not supported"));
let n = r.count(r.remaining())?;
let mut components = Vec::with_capacity(n.min(64));
for _ in 0..n {
let kind = r.varint()?;
components.push((kind, Component::read(kind, r)?));
}
Ok(NetCost { item, count })
Ok(NetCost {
item,
count,
components,
})
}
let n = r.count(r.remaining())?;
let mut out = Vec::with_capacity(n.min(64));
@@ -144,7 +171,11 @@ impl Codec<Vec<NetOffer>> for Offers {
fn cost(c: &NetCost, w: &mut Writer) {
w.varint(c.item);
w.varint(c.count);
w.varint(0);
w.varint(c.components.len() as i32);
for (kind, value) in &c.components {
w.varint(*kind);
value.write(*kind, w);
}
}
w.varint(v.len() as i32);
for o in v {
@@ -2300,6 +2331,39 @@ mod tests {
use super::*;
use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal};
#[test]
fn merchant_cost_predicate_is_a_typed_list_without_patch_counts() {
// ItemCost.STREAM_CODEC: item=7, count=1, one typed component,
// potion_contents=53, potion present (water=0), no color/effects/name.
// Result: count=1, item=8, empty component patch. Secondary cost:
// item=9, count=2, empty predicate, followed by the offer fields.
let mut bytes = vec![1, 7, 1, 1, 53, 1, 0, 0, 0, 0, 1, 8, 0, 0, 1, 9, 2, 0, 0];
bytes.extend_from_slice(&[0; 4]); // uses
bytes.extend_from_slice(&2i32.to_be_bytes()); // max uses
bytes.extend_from_slice(&[0; 16]); // xp, special price, multiplier, demand
let mut r = Reader::new(&bytes);
let offers = Offers::read(&mut r).unwrap();
assert_eq!(r.remaining(), 0);
assert_eq!(
offers[0].cost_a.components,
vec![(
53,
Component::Potion {
potion: Some(0),
color: None,
rest: Vec::new()
}
)]
);
assert!(offers[0].cost_b.as_ref().unwrap().components.is_empty());
let mut w = Writer::new();
Offers::write(&offers, &mut w);
assert_eq!(w.data, bytes);
for len in 0..bytes.len() {
assert!(Offers::read(&mut Reader::new(&bytes[..len])).is_err());
}
}
#[test]
fn serverbound_abilities_carry_only_flying() {
// ServerboundPlayerAbilitiesPacket.write: one byte, 2 when flying.
@@ -2576,9 +2640,9 @@ mod tests {
Clientbound::MerchantOffers(MerchantOffers {
container: 3,
offers: vec![NetOffer {
cost_a: NetCost { item: 5, count: 24 },
cost_a: Stack::new(5, 24).into(),
result: Stack::new(7, 1),
cost_b: Some(NetCost { item: 9, count: 1 }),
cost_b: Some(Stack::new(9, 1).into()),
out_of_stock: false,
uses: 2,
max_uses: 16,
+1 -1
View File
@@ -1,4 +1,4 @@
/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (website/src/tokens.css). */
/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (crates/horizon-theme/tokens.css). */
:root {
--page: #fafafc;
--plate-soft: #f3f3f8;
+1 -1
View File
@@ -30,7 +30,7 @@ The totals are grouped per version, OS, GPU vendor and render distance. Each gro
## Benchmarks summary
`src/summary.rs` makes it with the same rules as `website/scripts/benchmarks.mjs`, which bakes the page's fallback copy; both are tested against the same fixtures (`website/scripts/fixtures/benchmarks/`).
`src/summary.rs` makes it with the same rules as the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site), which bakes the page's fallback copy; both are tested against the same fixtures (`tests/fixtures/benchmarks/` here, copied in the site's repository).
- Only reports that compare: a version 1 `horizon-benchmark-report` of the standard flight over the four scenes, VSync off, no frame cap, on screen, from Horizon or plain vanilla, naming its GPU and CPU.
- A group (GPU, CPU, render distance, game) is published only with **at least 3 different installs**. Each install counts once: the median of its runs, then the median across installs.
@@ -1,6 +1,6 @@
//! The hardware classes the public output breaks results down by. Coarse on purpose: a class
//! holds many machines, and a published cell still needs `MIN_INSTALLS` different installs.
//! `website/scripts/benchmarks.mjs` has the same functions, tested on the same fixtures.
//! The website's `scripts/benchmarks.mjs` (ludovic111/horizon-site) has the same functions, tested on the same fixtures.
//!
//! The raw values (the exact memory, the driver, the screen) stay in the database for the
//! retention period and are never published.
@@ -1,7 +1,7 @@
//! `GET /v1/benchmarks/summary`: players' benchmark uploads, grouped for the website's Benchmarks page.
//!
//! The same rules as `website/scripts/benchmarks.mjs` (which builds the page's baked copy), checked against the
//! same fixtures (`website/scripts/fixtures/benchmarks/`):
//! The same rules as the website's `scripts/benchmarks.mjs` (ludovic111/horizon-site; it builds the page's baked
//! copy), checked against the same fixtures (`tests/fixtures/benchmarks/`, which the site's test keeps a copy of):
//!
//! - Only reports that compare: `horizon-benchmark-report` version 1, kind `game`, Horizon or plain vanilla, the
//! standard flight over the four scenes, VSync off, no frame cap, drawn on a screen, with a GPU and CPU name.
@@ -198,7 +198,7 @@ struct Group {
versions: BTreeSet<String>,
}
/// Players' groups of at least `min_installs` installs, as `website/scripts/benchmarks.mjs` makes them.
/// Players' groups of at least `min_installs` installs, as the website's `scripts/benchmarks.mjs` makes them.
pub fn groups(uploads: &[Upload], min_installs: usize) -> Vec<Value> {
let mut by: BTreeMap<(String, String, i64, &str), Group> = BTreeMap::new();
for u in uploads {
@@ -1,7 +1,8 @@
# Benchmark summary fixtures
Shared by the website's aggregator test (`website/scripts/benchmarks.test.mjs`) and the telemetry server's
`GET /v1/benchmarks/summary` test: the same `benchmark` items in, the same groups out.
Used by the telemetry server's `GET /v1/benchmarks/summary` test (`tests/summary.rs`) and, as a copy, by the
website's aggregator test (`scripts/benchmarks.test.mjs` in ludovic111/horizon-site, which checks its copy against
this one on main): the same `benchmark` items in, the same groups out. Change both together.
- `items.jsonl`: one stored item per line (`install_id`, `day`, `version`, `data`: a benchmark report). Group
RTX 4080 + i7-13700KF at render distance 12 has three installs (one with two runs); the same install at 32,

Some files were not shown because too many files have changed in this diff Show More