diff --git a/.github/workflows/parity-main.yml b/.github/workflows/parity-main.yml
index c47005ab0..70fb33796 100644
--- a/.github/workflows/parity-main.yml
+++ b/.github/workflows/parity-main.yml
@@ -48,6 +48,9 @@ jobs:
GH_TOKEN: ${{ github.token }}
run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT"
- name: The harnesses the merges since then can affect
+ id: harnesses
+ # A failure here is judged by the next step: the run passes when every failed harness passes again at HEAD.
+ continue-on-error: true
env:
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.base.outputs.sha }}
@@ -55,8 +58,8 @@ jobs:
echo "Merges since ${BASE_SHA}:"
git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD"
python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400
- - name: The merge that broke them
- if: failure()
+ - name: A flake, or the merge that broke them
+ if: steps.harnesses.outcome == 'failure'
env:
GH_TOKEN: ${{ github.token }}
PARITY_HOSTS: ''
@@ -65,7 +68,7 @@ jobs:
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
python3 tools/parity_main.py bisect "$BASE_SHA" --comment
- name: Logs of the failed harnesses
- if: failure()
+ if: steps.harnesses.outcome == 'failure'
uses: actions/upload-artifact@v4
with:
name: parity-main-logs
diff --git a/Cargo.lock b/Cargo.lock
index 0e93bba0e..809df3a5a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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"
diff --git a/Cargo.toml b/Cargo.toml
index e4628f962..59bfe5e33 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -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]
diff --git a/ROADMAP.md b/ROADMAP.md
index a04eca2ce..4a2b90643 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -160,6 +160,66 @@ Translatable components resolved through the selected language for items, contai
+#### Cooldowns drawn on items
+
+After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.
+
+Technical
+
+Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763).
+
+More: [#1933](https://github.com/ludovic111/horizon/issues/1933)
+
+
+
+#### Chat settings and team prefixes
+
+The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.
+
+Technical
+
+Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce.
+
+More: [#1932](https://github.com/ludovic111/horizon/issues/1932) · [#1841](https://github.com/ludovic111/horizon/issues/1841)
+
+
+
+#### A pointing hand over buttons
+
+The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.
+
+Technical
+
+26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347).
+
+More: [#1897](https://github.com/ludovic111/horizon/issues/1897)
+
+
+
+#### Ctrl+Backspace and scroll bars in menus
+
+Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.
+
+Technical
+
+`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)).
+
+More: [#1884](https://github.com/ludovic111/horizon/issues/1884) · [#1931](https://github.com/ludovic111/horizon/issues/1931)
+
+
+
+#### Chickens flap while they fall
+
+Chickens should flap their wings while they fall, not stand still in the air.
+
+Technical
+
+Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706).
+
+More: [#1892](https://github.com/ludovic111/horizon/issues/1892)
+
+
+
### Rendering
#### Shader packs, written again from scratch
@@ -902,56 +962,6 @@ Armour and tools in End city chests should come enchanted, as in vanilla.
-#### Cooldowns drawn on items
-
-After you throw an ender pearl, its slot should show the cooldown sweeping away, as in vanilla.
-
-Technical
-
-Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763).
-
-
-
-#### Chat settings and team prefixes
-
-The Hidden and Commands Only chat settings should hide chat, and team prefixes should appear before names in chat.
-
-Technical
-
-Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce.
-
-
-
-#### A pointing hand over buttons
-
-The mouse pointer should turn into a pointing hand over menu buttons, as in vanilla 26.3.
-
-Technical
-
-26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347).
-
-
-
-#### Ctrl+Backspace and scroll bars in menus
-
-Ctrl+Backspace should delete a whole word in the creative search, and every list's scroll bar should be draggable.
-
-Technical
-
-`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)).
-
-
-
-#### Chickens flap while they fall
-
-Chickens should flap their wings while they fall, not stand still in the air.
-
-Technical
-
-Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706).
-
-
-
## Recently shipped
- **OpenGL for old computers** (v0.2.63): Horizon now starts on old PCs whose graphics card has no Vulkan or DirectX 12 driver: it switches to OpenGL by itself, and Options > Graphics can pick OpenGL by hand. [#1917](https://github.com/ludovic111/horizon/issues/1917) · [#1920](https://github.com/ludovic111/horizon/issues/1920) · [#1936](https://github.com/ludovic111/horizon/issues/1936)
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 63a1f7da3..e83ccd840 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -17,4 +17,5 @@ by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1
`crates/horizon-theme/icons/pixel/*.svg` are icons from
[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT
-license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`).
+license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). `star.svg` is Horizon's own, drawn on
+the same grid.
diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml
index d7c6d812b..f1011c534 100644
--- a/crates/horizon-client/Cargo.toml
+++ b/crates/horizon-client/Cargo.toml
@@ -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.
diff --git a/crates/horizon-client/examples/probe/cushion_placement_probe.rs b/crates/horizon-client/examples/probe/cushion_placement_probe.rs
new file mode 100644
index 000000000..45fbdbd72
--- /dev/null
+++ b/crates/horizon-client/examples/probe/cushion_placement_probe.rs
@@ -0,0 +1,89 @@
+use horizon_client::{
+ Result,
+ cushion::{self, World},
+};
+use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
+use serde_json::Value;
+use std::{
+ collections::HashMap,
+ fs::File,
+ io::{BufRead, BufReader, BufWriter, Write},
+};
+
+struct Cell {
+ outline: VoxelShape,
+ collision: VoxelShape,
+ suffocating: bool,
+}
+struct Fixture(HashMap<[i32; 3], Cell>);
+impl World for Fixture {
+ fn outline_bounds(&self, p: [i32; 3]) -> Option {
+ self.0
+ .get(&p)?
+ .outline
+ .bounds()
+ .map(|b| b.move_by(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64)))
+ }
+ fn collision_shapes(&self, _: Aabb) -> Vec {
+ self.0
+ .iter()
+ .map(|(p, c)| {
+ c.collision
+ .moved(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64))
+ })
+ .collect()
+ }
+ fn suffocating(&self, p: [i32; 3]) -> bool {
+ self.0.get(&p).is_some_and(|c| c.suffocating)
+ }
+}
+fn shape(value: &Value) -> Result {
+ let mut shape = VoxelShape::empty();
+ for b in value.as_array().unwrap() {
+ let f = |i: usize| b[i].as_f64().unwrap();
+ shape = shape.join(
+ &VoxelShape::from_box(Aabb::new(
+ Vec3::new(f(0), f(1), f(2)),
+ Vec3::new(f(3), f(4), f(5)),
+ ))?,
+ ShapeOp::OR,
+ )?;
+ }
+ Ok(shape)
+}
+pub fn main() -> Result<()> {
+ let args: Vec<_> = crate::args().collect();
+ 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 world = Fixture(HashMap::new());
+ for c in row["cells"].as_array().unwrap() {
+ let p = std::array::from_fn(|i| c[i].as_i64().unwrap() as i32);
+ world.0.insert(
+ p,
+ Cell {
+ outline: shape(&c[3])?,
+ collision: shape(&c[4])?,
+ suffocating: c[5].as_bool().unwrap(),
+ },
+ );
+ }
+ let p = &row["pos"];
+ let (x, y, z) = (
+ p[0].as_f64().unwrap(),
+ p[1].as_f64().unwrap(),
+ p[2].as_f64().unwrap(),
+ );
+ let bounds = Aabb::new(
+ Vec3::new(x - 0.5, y, z - 0.5),
+ Vec3::new(x + 0.5, y + 0.25, z + 0.5),
+ );
+ writeln!(
+ out,
+ "{} {}",
+ cushion::can_place(&world, bounds),
+ cushion::survives(&world, bounds)
+ )?;
+ }
+ Ok(())
+}
diff --git a/crates/horizon-client/examples/probe/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs
index 0a2e2951f..4aceb9f6f 100644
--- a/crates/horizon-client/examples/probe/entity_anim_fixture.rs
+++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs
@@ -9,7 +9,7 @@ use horizon_client::mesher::Vertex;
use horizon_client::mobs::{
Mob, MobData, MobTypes, Part, Species, allay,
anim::{self, Poses, State},
- aquatic, body_anim as b_anim, equine, guardian,
+ aquatic, bat, body_anim as b_anim, equine, guardian,
keyframes::AnimationState,
render, shulker, sniffer, species, tame,
};
@@ -108,6 +108,22 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
match species {
+ Species::Bat => {
+ mob.extra.flag = flag("isResting");
+ mob.anim.states[0].started = case["flyAnimationState"].as_f64().map(|v| v as f32);
+ mob.anim.states[1].started = case["restAnimationState"].as_f64().map(|v| v as f32);
+ if let Some(ticks) = case["@batTicks"].as_array() {
+ for (i, flags) in ticks.iter().enumerate() {
+ mob.age = i as u32 + 1;
+ bat::set_resting(mob, flags.as_i64().unwrap_or(0) & 1 != 0);
+ if flag("@batInFrame") {
+ bat::tick(mob);
+ } else {
+ bat::setup_animation_states(mob);
+ }
+ }
+ }
+ }
Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32,
Species::Guardian | Species::ElderGuardian => {
mob.anim.v[guardian::TAIL] = num("tailAnimation");
@@ -377,7 +393,7 @@ pub fn main() -> horizon_client::Result<()> {
mob.extra.age = -24000;
}
mob.age = f("ageInTicks") as u32;
- let state = State {
+ let mut state = State {
pos: f("walkAnimationPos"),
speed: f("walkAnimationSpeed"),
age: f("ageInTicks"),
@@ -389,6 +405,20 @@ pub fn main() -> horizon_client::Result<()> {
};
let mut poses = Poses::new(&model);
entity_state(&mut mob, def.species, case);
+ if let Some(ticks) = case["@walkTicks"].as_array() {
+ for speed in ticks {
+ mob.previous_limb_speed = mob.limb_speed;
+ mob.limb_speed += (speed.as_f64().unwrap() as f32 - mob.limb_speed) * 0.4;
+ mob.limb_position += mob.limb_speed;
+ }
+ if !case["@alive"].as_bool().unwrap() {
+ mob.health = 0.0;
+ }
+ let extracted = anim::state(&mob, f("@partial"));
+ state.pos = extracted.pos;
+ state.speed = extracted.speed;
+ }
+
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
let started = |k: &str| AnimationState {
@@ -456,14 +486,6 @@ pub fn main() -> horizon_client::Result<()> {
roll_amount: num("rollAmount"),
},
),
- Species::Bat => b_anim::bat(
- p,
- s,
- flag("isResting"),
- &started("flyAnimationState"),
- &started("restAnimationState"),
- &animations,
- ),
Species::Armadillo => b_anim::armadillo(
p,
s,
@@ -590,7 +612,11 @@ pub fn main() -> horizon_client::Result<()> {
}
_ => anim::setup(&mob, s, p, &animations),
}
- out.push_str(&format!("{}\n", emit(&model, &mut poses, case, layer)));
+ let mut result = emit(&model, &mut poses, case, layer);
+ if case["@walkTicks"].is_array() {
+ result["walk"] = json!([state.pos, state.speed]);
+ }
+ out.push_str(&format!("{result}\n"));
}
fs::write(&args[2], out)?;
Ok(())
diff --git a/crates/horizon-client/examples/probe/main.rs b/crates/horizon-client/examples/probe/main.rs
index e80088fd0..1e1bc04d9 100644
--- a/crates/horizon-client/examples/probe/main.rs
+++ b/crates/horizon-client/examples/probe/main.rs
@@ -28,6 +28,7 @@ mod cloud_fixture;
mod command_parse_fixture;
mod container_screen_probe;
mod creative_search_fixture;
+mod cushion_placement_probe;
mod emitter_particles_probe;
mod enchanting_fixture;
mod entity_anim_fixture;
@@ -107,6 +108,7 @@ probes! {
block_transform_fixture,
breaking_fixture,
camera_probe,
+ cushion_placement_probe,
cauldron_fixture,
chat_screen_fixture,
cloud_fixture,
diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs
index 49f56c250..ecdf02901 100644
--- a/crates/horizon-client/examples/probe/mob_ai_probe.rs
+++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs
@@ -49,6 +49,7 @@ struct Scenario {
name: String,
ticks: i32,
time: i64,
+ difficulty: u8,
rain: bool,
thunder: bool,
origin: [i32; 2],
@@ -85,11 +86,13 @@ fn parse(text: &str) -> Vec {
"scenario" => {
s.name = f[1].to_owned();
s.time = 6000;
+ s.difficulty = 2;
for kv in &f[2..] {
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
match k {
"ticks" => s.ticks = v.parse().unwrap(),
"time" => s.time = v.parse().unwrap(),
+ "difficulty" => s.difficulty = v.parse().unwrap(),
"rain" => s.rain = true,
"thunder" => s.thunder = true,
"levelseed" => {}
@@ -954,6 +957,10 @@ pub fn main() -> horizon_client::Result<()> {
for flag in &spec.flags {
match flag.as_str() {
"persistent" => m.persistent = true,
+ "named" => {
+ m.custom_name = Some("Peaceful regression".into());
+ m.persistent = true;
+ }
"ridden" => {
m.extra.head = Some("minecraft:red_harness".into());
m.rider = Some(horizon_client::mobs::equine::Rider::default());
@@ -1090,7 +1097,7 @@ pub fn main() -> horizon_client::Result<()> {
block_tags: &items.block_tags,
biomes: &biomes,
mob_griefing: true,
- difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
+ difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0),
end: false,
world_seed: 0,
// FlatLevelSource.getSeaLevel.
diff --git a/crates/horizon-client/examples/probe/section_mesh_fixture.rs b/crates/horizon-client/examples/probe/section_mesh_fixture.rs
index e212a5268..89624b78c 100644
--- a/crates/horizon-client/examples/probe/section_mesh_fixture.rs
+++ b/crates/horizon-client/examples/probe/section_mesh_fixture.rs
@@ -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}));
diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs
index bcb94589c..12e38e78a 100644
--- a/crates/horizon-client/src/benchmark.rs
+++ b/crates/horizon-client/src/benchmark.rs
@@ -323,10 +323,15 @@ const QUIET_MESHES_PER_S: f64 = 100.0;
/// happened (`tools/perf_bench.py`'s `wait_loaded`). With `status.streaming`, the sections are
/// drawn once no stage has held work for half a second: blocks changing after the load (fluids
/// settling, random ticks) only remesh in bursts. Without it, meshing has to go quiet.
+///
+/// Right after a teleport (and at spawn) the game reports nothing queued and steady counts for over
+/// a second before it starts loading: the counts must change once, or stay full for 5 s, and the
+/// resident chunks reach [`view_chunks`], before "steady" means loaded.
fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result {
let deadline = Instant::now() + LOAD_LIMIT;
let (mut last, mut changed, mut meshing) = (None, Instant::now(), Instant::now());
let mut previous: Option<(Instant, f64)> = None;
+ let (mut first, mut moved, began) = (None, false, Instant::now());
while Instant::now() < deadline {
let s = control.status();
let now = Instant::now();
@@ -339,6 +344,19 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result 0
+ && resident >= min_chunks
+ && now - began > Duration::from_secs(5));
+ if min_chunks > 0 && (!moved || resident < min_chunks) {
+ (last, changed, previous, meshing) = (None, now, None, now);
+ thread::sleep(Duration::from_millis(50));
+ continue;
+ }
if last != Some(counts) {
(last, changed) = (Some(counts), now);
}
@@ -370,6 +388,12 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result u64 {
+ (0.8 * std::f64::consts::PI * (distance * distance) as f64) as u64
+}
+
/// Vanilla's yaw facing from `start` to `end`.
fn yaw(start: [f64; 3], end: [f64; 3]) -> f64 {
(-(end[0] - start[0])).atan2(end[2] - start[2]).to_degrees()
@@ -420,6 +444,13 @@ mod tests {
assert!(scenes("nether").is_none());
}
+ #[test]
+ fn view_chunks_matches_perf_bench() {
+ assert_eq!(view_chunks(12), 361);
+ assert_eq!(view_chunks(32), 2573);
+ assert_eq!(view_chunks(0), 0);
+ }
+
#[test]
fn yaw_matches_vanilla() {
// South (+Z) is 0, west (-X) 90, east (+X) -90.
diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs
index 10c5e2509..28a876d80 100644
--- a/crates/horizon-client/src/block_entity_render.rs
+++ b/crates/horizon-client/src/block_entity_render.rs
@@ -558,12 +558,11 @@ fn frac(x: f32) -> f32 {
/// `StringSplitter.splitLines(...).get(0)` for plain text: the first line,
/// wrapped at the last space that fits or mid-word when none does.
fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> String {
- let chars: Vec = line.chars().collect();
let mut width = 0.0;
let mut last_space = None;
- for (i, &c) in chars.iter().enumerate() {
+ for (i, c) in line.char_indices() {
if c == '\n' {
- return chars[..i].iter().collect();
+ return line[..i].to_owned();
}
if c == ' ' {
last_space = Some(i);
@@ -572,9 +571,11 @@ fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> Stri
if width > max_width {
let end = match last_space {
Some(s) if s > 0 => s,
- _ => i.max(1),
+ _ if i > 0 => i,
+ // The first char alone is too wide: take that one char.
+ _ => c.len_utf8(),
};
- return chars[..end].iter().collect();
+ return line[..end].to_owned();
}
}
line.to_owned()
@@ -2098,4 +2099,13 @@ mod tests {
assert_eq!(out[1].pos, [2.0, 0.0, 0.0]);
assert_eq!(out[2].uv, [0.5, 0.5]);
}
+
+ #[test]
+ fn first_line_wraps_on_bytes_without_splitting_a_char() {
+ let advance = |c: char| if c == ' ' { 4.0 } else { 6.0 };
+ assert_eq!(first_line("ab cd ef", 13.0, &advance), "ab");
+ assert_eq!(first_line("abcdef", 13.0, &advance), "ab");
+ assert_eq!(first_line("\u{6771}", 3.0, &advance), "\u{6771}");
+ assert_eq!(first_line("ab\ncd", 100.0, &advance), "ab");
+ }
}
diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs
index 8658b5815..42473729f 100644
--- a/crates/horizon-client/src/bundle.rs
+++ b/crates/horizon-client/src/bundle.rs
@@ -166,6 +166,38 @@ impl Contents {
Some(stack)
}
+ /// The stacks inside, in display order (the first is the next out).
+ pub fn items(&self) -> &[ItemStack] {
+ &self.items
+ }
+
+ /// `getNumberOfItemsToShow`: a full grid shows 11 and a `+N`, so the last
+ /// row keeps its fourth cell for the count.
+ pub fn shown_count(&self) -> usize {
+ let count = self.items.len();
+ let available: usize = if count > 12 { 11 } else { 12 };
+ let on_last_row = count % 4;
+ let empty = if on_last_row == 0 { 0 } else { 4 - on_last_row };
+ count.min(available.saturating_sub(empty))
+ }
+
+ /// The items the tooltip shows, and how many sit beyond them.
+ pub fn shown(&self) -> (&[ItemStack], u32) {
+ let n = self.shown_count();
+ let hidden = self.items[n..].iter().map(|s| s.count).sum();
+ (&self.items[..n], hidden)
+ }
+
+ /// The `Fraction` weight as the float the progress bar reads.
+ pub fn weight_fraction(&self) -> f32 {
+ self.weight.n as f32 / self.weight.d as f32
+ }
+
+ /// `Fraction.ONE`: a full bundle draws the full bar and says so.
+ pub fn is_full(&self) -> bool {
+ self.weight.n >= self.weight.d
+ }
+
/// `toImmutable`, written back into the bundle's component.
pub fn store(self, bundle: &mut ItemStack) {
bundle.data_mut().bundle_contents = self.items;
@@ -190,3 +222,174 @@ mod tests {
assert_eq!(over.how_many(Weight::new(1, 64)), 0);
}
}
+
+// ------------------------------------------------------------- the tooltip
+
+/// `ClientBundleTooltip`'s geometry, relative to the tooltip box's top-left:
+/// the 96 pixel column of a 4 wide slot grid and the progress bar under it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TooltipLayout {
+ /// The component's own width (96) and height, the text's excluded.
+ pub width: f32,
+ pub height: f32,
+ /// Each slot's top-left and the stack in it, in reading order.
+ pub slots: Vec<([f32; 2], ItemStack)>,
+ /// The `+N` of the items past the grid: its top-left and the count.
+ pub overflow: Option<([f32; 2], u32)>,
+ /// The progress bar's top-left, its fill's width out of 94, and whether
+ /// the weight fills it (the full sprite).
+ pub bar: [f32; 2],
+ pub fill: f32,
+ pub full: bool,
+ /// `item.minecraft.bundle.empty` / `.full`, centred over the bar.
+ pub label: Option<&'static str>,
+ /// An empty bundle's description, wrapped at `width` from here.
+ pub empty_description: Option<[f32; 2]>,
+}
+
+/// The tooltip of a bundle's contents (`ClientBundleTooltip`), or None when
+/// the stack is not a bundle. `x`/`y` are the box's top-left, `box_width` the
+/// tooltip's width, which the component is centred in.
+pub fn tooltip_layout(
+ items: &Items,
+ stack: &ItemStack,
+ x: f32,
+ y: f32,
+ box_width: f32,
+) -> Option {
+ let contents = Contents::of(items, stack)?;
+ let offset = ((box_width - 96.0) / 2.0).floor();
+ if contents.items().is_empty() {
+ // The description takes the top; the bar follows it.
+ let description_height = 9.0 * 2.0;
+ return Some(TooltipLayout {
+ width: 96.0,
+ height: description_height + 13.0 + 8.0,
+ slots: Vec::new(),
+ overflow: None,
+ bar: [x + offset, y + description_height + 4.0],
+ fill: 0.0,
+ full: false,
+ label: Some("item.minecraft.bundle.empty"),
+ empty_description: Some([x + offset, y]),
+ });
+ }
+ let (shown, hidden) = contents.shown();
+ // `gridSizeY` counts `slotCount()` (at most twelve), not the slots the
+ // overflow count leaves room for.
+ let rows = contents.items().len().min(12).div_ceil(4).max(1);
+ let grid_height = rows as f32 * 24.0;
+ let x_start = x + offset + 96.0;
+ let y_start = y + grid_height;
+ let mut slots = Vec::with_capacity(shown.len());
+ let mut overflow = None;
+ // Rows fill bottom-up and columns right-to-left, as vanilla draws them.
+ let mut slot = 0;
+ for row in 1..=rows {
+ for column in 1..=4 {
+ let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
+ if hidden > 0 && row == 1 && column == 1 {
+ overflow = Some((at, hidden));
+ } else if let Some(stack) = shown.get(slot) {
+ slots.push((at, stack.clone()));
+ slot += 1;
+ }
+ }
+ }
+ let weight = contents.weight_fraction();
+ Some(TooltipLayout {
+ width: 96.0,
+ height: grid_height + 13.0 + 8.0,
+ slots,
+ overflow,
+ bar: [x + offset, y + grid_height + 4.0],
+ // `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
+ fill: (weight * 94.0).trunc().clamp(0.0, 94.0),
+ full: contents.is_full(),
+ label: if contents.is_full() {
+ Some("item.minecraft.bundle.full")
+ } else {
+ None
+ },
+ empty_description: None,
+ })
+}
+
+#[cfg(test)]
+mod tooltip_tests {
+ use super::*;
+
+ /// The prepared resources, when they are on this machine: the tooltip
+ /// asks the item registry whether a stack is a bundle.
+ fn items() -> Option {
+ let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../.local/horizon-client/26.3");
+ if !root.join("items.json").exists() {
+ return None;
+ }
+ let assets = crate::assets::Assets::load(&root).ok()?;
+ let facts = crate::blocks::BlockFacts::load(&root, assets.registry).ok()?;
+ Items::load(&root, assets.registry, &facts).ok()
+ }
+
+ fn bundle_with(counts: &[(&str, u32)]) -> ItemStack {
+ let mut bundle = ItemStack::new("minecraft:bundle", 1);
+ bundle.data_mut().bundle_contents = counts
+ .iter()
+ .map(|(item, n)| ItemStack::new(item, *n))
+ .collect();
+ bundle
+ }
+
+ #[test]
+ fn a_grid_shows_twelve_stacks_and_counts_the_rest() {
+ let Some(items) = items() else { return };
+ let twelve: Vec<(&str, u32)> = (0..12).map(|_| ("minecraft:stone", 1)).collect();
+ let layout = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 96.0).unwrap();
+ assert_eq!(layout.slots.len(), 12);
+ assert_eq!(layout.overflow, None);
+ assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
+ // Rows fill bottom-up and columns right-to-left: the first item is in
+ // the bottom-right cell, the twelfth in the top-left.
+ assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
+ assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
+ assert_eq!(layout.slots[11].0, [0.0, 0.0]);
+ // A wider tooltip centres the 96 pixel column in it.
+ let centred = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 120.0).unwrap();
+ assert_eq!(centred.slots[0].0[0], 12.0 + 96.0 - 24.0);
+ // Thirteen stacks: `getNumberOfItemsToShow` leaves the last row room
+ // for the count, so 8 slots show and `+6` (four stones and two dirt)
+ // takes the first cell.
+ let mut counts = twelve;
+ counts.push(("minecraft:dirt", 2));
+ let layout = tooltip_layout(&items, &bundle_with(&counts), 0.0, 0.0, 96.0).unwrap();
+ assert_eq!(layout.slots.len(), 8);
+ assert_eq!(layout.overflow, Some(([96.0 - 24.0, 48.0], 6)));
+ }
+
+ #[test]
+ fn the_bar_fills_with_the_weight_and_an_empty_bundle_explains_itself() {
+ let Some(items) = items() else { return };
+ let layout = tooltip_layout(&items, &bundle_with(&[]), 4.0, 8.0, 96.0).unwrap();
+ assert!(layout.slots.is_empty());
+ assert_eq!(layout.fill, 0.0);
+ assert_eq!(layout.label, Some("item.minecraft.bundle.empty"));
+ assert_eq!(layout.empty_description, Some([4.0, 8.0]));
+ assert_eq!(layout.bar, [4.0, 8.0 + 18.0 + 4.0]);
+ // A bundle holding one 64 stack is full: the whole bar, the full label.
+ let layout = tooltip_layout(
+ &items,
+ &bundle_with(&[("minecraft:stone", 64)]),
+ 0.0,
+ 0.0,
+ 96.0,
+ )
+ .unwrap();
+ assert!(layout.full);
+ assert_eq!(layout.fill, 94.0);
+ assert_eq!(layout.label, Some("item.minecraft.bundle.full"));
+ // Something that is not a bundle has no component.
+ let dirt = ItemStack::new("minecraft:dirt", 1);
+ assert!(tooltip_layout(&items, &dirt, 0.0, 0.0, 96.0).is_none());
+ }
+}
diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs
index 6b058c0fb..beec6cd81 100644
--- a/crates/horizon-client/src/chat_tests.rs
+++ b/crates/horizon-client/src/chat_tests.rs
@@ -436,3 +436,34 @@ fn the_chat_option_filters_the_lines_both_ways() {
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full));
assert_eq!(shown(&chat), ["client", "server", "player"]);
}
+
+/// The in-frame LAN host's chat: a guest's line is a player message, so the
+/// Chat option's player-message permission hides it at Commands Only and
+/// Hidden; command feedback (`/list`, `/tp`) is a system message and stays
+/// at Commands Only.
+#[test]
+fn a_guests_line_follows_the_player_message_permission() {
+ let font = font();
+ let shown = |visibility, source| {
+ let mut chat = Chat::default();
+ chat.set_abilities(&font, ChatAbilities::new(visibility));
+ chat.add_message(&font, Text::literal("line"), None, source, 0, false);
+ chat.messages.len()
+ };
+ for (visibility, player, system) in [
+ (ChatVisibility::Full, 1, 1),
+ (ChatVisibility::System, 0, 1),
+ (ChatVisibility::Hidden, 0, 0),
+ ] {
+ assert_eq!(
+ shown(visibility, ChatSource::Player),
+ player,
+ "{visibility:?}"
+ );
+ assert_eq!(
+ shown(visibility, ChatSource::Server),
+ system,
+ "{visibility:?}"
+ );
+ }
+}
diff --git a/crates/horizon-client/src/clipboard.rs b/crates/horizon-client/src/clipboard.rs
index c21460cdb..76872091c 100644
--- a/crates/horizon-client/src/clipboard.rs
+++ b/crates/horizon-client/src/clipboard.rs
@@ -346,6 +346,11 @@ mod tests {
assert_eq!(filter_text(s, true), "abc\nde\u{80}");
assert_eq!(strip_formatting("§aRed§r §zx§"), "Red §zx§");
assert_eq!(helper_clipboard_contents("§lone\r\ntwo"), "one\ntwo");
+ // TextFieldHelper.getClipboardContents runs before insertText's filter.
+ assert_eq!(
+ filter_text(&helper_clipboard_contents("§aHello"), false),
+ "Hello"
+ );
}
struct Field {
diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs
index 2c490861a..77c7ad8aa 100644
--- a/crates/horizon-client/src/container_screen.rs
+++ b/crates/horizon-client/src/container_screen.rs
@@ -275,4 +275,30 @@ mod tests {
Release::Click(Input::QuickMove)
);
}
+
+ /// A press whose release never arrives (the pointer left the window, or
+ /// the screen closed first) leaves `isQuickCrafting` set; the next screen
+ /// starts with its own state, as `AbstractContainerScreen` does, so the
+ /// reset the game runs on open/close makes clicks work again.
+ #[test]
+ fn a_lost_release_does_not_wedge_the_next_screen() {
+ let mut clicks = Clicks::default();
+ let slot = Target::::Slot(3);
+ // Pressed with a stack carried: a quick craft drag starts, and its
+ // release is lost.
+ assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None);
+ assert!(clicks.quick_crafting().is_some());
+ assert_eq!(
+ clicks.press(&slot, Button::Left, true, false, false),
+ None,
+ "the stuck drag swallows the next press"
+ );
+ // A new screen: fresh state, so the press is a normal click again.
+ clicks = Clicks::default();
+ assert!(clicks.quick_crafting().is_none());
+ assert_eq!(
+ clicks.press(&slot, Button::Left, true, false, false),
+ Some(Input::Pickup)
+ );
+ }
}
diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs
index 895ea5769..8ca9af0ad 100644
--- a/crates/horizon-client/src/containers.rs
+++ b/crates/horizon-client/src/containers.rs
@@ -49,6 +49,17 @@ pub struct Furnace {
/// rather than per item, and a save keeps it as the `RecipesUsed` compound.
pub recipes_used: HashMap,
}
+/// The key `recipes_used` keeps a recipe under: its full id, as vanilla's `ResourceKey`
+/// writes it in `RecipesUsed`. Horizon's own recipe ids are file names without the namespace, so
+/// keeping both forms would write a key twice, and vanilla refuses such a furnace
+/// ("Duplicate entry for key").
+pub fn recipe_used_key(id: &str) -> String {
+ if id.contains(':') {
+ id.to_owned()
+ } else {
+ format!("minecraft:{id}")
+ }
+}
/// A hopper's slots: the only plain container with five.
pub const HOPPER_SLOTS: usize = 5;
@@ -83,12 +94,69 @@ pub enum BlockEntity {
Beehive(Box),
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
CommandBlock(Box),
+ /// `CampfireBlockEntity` of campfires and soul campfires.
+ Campfire(Box),
/// `SkullBlockEntity` of every skull and head block.
Skull(Skull),
/// `DaylightDetectorBlockEntity`: no data, only the ticker
/// (`DaylightDetectorBlock.tickEntity`).
DaylightDetector,
}
+/// `CampfireBlockEntity`: four cooking slots, each with its
+/// `cookingProgress` and `cookingTime` (the recipe's).
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Campfire {
+ pub items: [Option; 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`.
@@ -310,6 +378,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,
@@ -348,6 +419,7 @@ impl BlockEntity {
Self::CommandBlock(_) => "minecraft:command_block",
Self::Skull(_) => "minecraft:skull",
Self::DaylightDetector => "minecraft:daylight_detector",
+ Self::Campfire(_) => "minecraft:campfire",
}
}
pub fn contents(&self) -> Vec {
@@ -370,6 +442,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] {
@@ -391,7 +464,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] {
@@ -413,7 +488,8 @@ impl BlockEntity {
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
- | Self::CommandBlock(_) => &mut [],
+ | Self::CommandBlock(_)
+ | Self::Campfire(_) => &mut [],
}
}
}
@@ -648,7 +724,10 @@ impl Furnace {
Some(out) => out.count += recipe.result.count,
None => self.items[2] = Some(recipe.result.clone()),
}
- *self.recipes_used.entry(recipe.id.clone()).or_insert(0) += 1;
+ *self
+ .recipes_used
+ .entry(recipe_used_key(&recipe.id))
+ .or_insert(0) += 1;
if let Some(i) = self.items[0].as_mut() {
i.count -= 1;
if i.count == 0 {
@@ -702,6 +781,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() {
diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs
index 690383963..899ce90d9 100644
--- a/crates/horizon-client/src/crafting.rs
+++ b/crates/horizon-client/src/crafting.rs
@@ -1612,7 +1612,9 @@ impl Recipes {
}
/// The `experience` of the cooking recipe with this file name, and 0 for one this data
/// pack does not have (a save from another pack can name it).
+ /// `id` with or without the `minecraft:` namespace (a furnace keeps the full id).
pub fn cooking_experience(&self, id: &str) -> f32 {
+ let id = id.strip_prefix("minecraft:").unwrap_or(id);
self.cooking
.iter()
.find(|c| c.id == id)
diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs
index 249e40b11..033b4daec 100644
--- a/crates/horizon-client/src/creative.rs
+++ b/crates/horizon-client/src/creative.rs
@@ -1,7 +1,7 @@
//! Creative inventory (CreativeModeInventoryScreen): vanilla's tabs and their
//! contents as built by the game's own display generators
//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab.
-use crate::{Result, items::ItemStack};
+use crate::{Result, items::ItemStack, ui::EditBox};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
@@ -35,10 +35,8 @@ pub struct Creative {
pub scroll: f32,
/// The scrollbar is held (scrolling): dragging moves it.
pub scrolling: bool,
- pub search: String,
- /// When the search box took the focus (`EditBox.setFocused`): its
- /// cursor blinks from then.
- pub search_focused: std::time::Instant,
+ /// CreativeModeInventoryScreen's search box: an unbordered `EditBox` of 50.
+ pub search: EditBox,
/// The search tab's stacks, in its display order.
search_items: Vec,
search_index: Vec,
@@ -284,8 +282,13 @@ impl Creative {
selected: 0,
scroll: 0.0,
scrolling: false,
- search: String::new(),
- search_focused: std::time::Instant::now(),
+ search: {
+ let mut search = EditBox::new(0.0, 0.0, 80.0, 9.0);
+ search.bordered = false;
+ search.max_length = 50;
+ search.text_color = u32::MAX;
+ search
+ },
search_items,
search_index,
}
@@ -306,12 +309,13 @@ impl Creative {
/// selectTab: a different tab empties the search box; the scrollbar goes to the top.
pub fn select(&mut self, tab: usize) {
if tab != self.selected {
- self.search.clear();
+ self.search.set_value("");
}
self.selected = tab;
self.scroll = 0.0;
if self.tab().search {
- self.search_focused = std::time::Instant::now();
+ self.search.focused = true;
+ self.search.reset_blink();
}
}
/// The search tab's stacks.
@@ -385,7 +389,7 @@ impl Creative {
let tab = self.tab();
if tab.search {
return self
- .search_results(&self.search, names)
+ .search_results(&self.search.value, names)
.into_iter()
.map(|i| self.search_items[i].clone())
.collect();
@@ -754,13 +758,13 @@ mod tests {
(1, false, true),
(2, true, false),
] {
- c.search = "anvil".into();
+ c.search.set_value("anvil");
c.scroll = 0.5;
c.select(selected);
assert_eq!(c.selected, selected);
assert_eq!(c.tab().inventory, inventory);
assert_eq!(c.tab().search, search);
- assert!(c.search.is_empty());
+ assert!(c.search.value.is_empty());
assert_eq!(c.scroll, 0.0);
}
}
@@ -780,12 +784,12 @@ mod tests {
assert_eq!(c.tabs[0].items[0].item.as_ref(), "minecraft:anvil");
let mut c = c;
c.select(1);
- c.search = "anvil".into();
+ c.search.set_value("anvil");
c.scroll = 0.5;
c.select(1);
- assert_eq!((c.search.as_str(), c.scroll), ("anvil", 0.0));
+ assert_eq!((c.search.value.as_str(), c.scroll), ("anvil", 0.0));
c.select(0);
- assert_eq!(c.search, "");
+ assert_eq!(c.search.value, "");
}
#[test]
@@ -899,4 +903,25 @@ mod tests {
c.scroll = 1.0;
assert_eq!(c.scroller_offset(), 95.0);
}
+
+ #[test]
+ fn search_edits_at_its_cursor() {
+ use winit::keyboard::KeyCode;
+ let mut c = creative(0);
+ c.select(1);
+ c.search.insert_text("hello world");
+ for _ in 0..5 {
+ assert!(c.search.key(KeyCode::ArrowLeft, false, false));
+ }
+ c.search.insert_text("X");
+ assert_eq!(c.search.value, "hello Xworld");
+ c.search.key(KeyCode::Home, false, true);
+ c.search.insert_text("Y");
+ assert_eq!(c.search.value, "Yworld");
+ // Ctrl+Left jumps a word; one step right and Backspace deletes before the cursor.
+ c.search.key(KeyCode::ArrowLeft, true, false);
+ c.search.key(KeyCode::ArrowRight, false, false);
+ c.search.key(KeyCode::Backspace, false, false);
+ assert_eq!(c.search.value, "world");
+ }
}
diff --git a/crates/horizon-client/src/cushion.rs b/crates/horizon-client/src/cushion.rs
new file mode 100644
index 000000000..7610a4aab
--- /dev/null
+++ b/crates/horizon-client/src/cushion.rs
@@ -0,0 +1,59 @@
+//! Cushion placement and support checks (`Cushion.canBePlacedAt`/`wouldSurviveAt`).
+use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
+
+pub trait World {
+ fn outline_bounds(&self, pos: [i32; 3]) -> Option;
+ fn collision_shapes(&self, bounds: Aabb) -> Vec;
+ fn suffocating(&self, pos: [i32; 3]) -> bool;
+}
+
+pub fn blocks_in(a: Aabb) -> impl Iterator- {
+ let (lo, hi) = (a.min_position(), a.max_position());
+ let (x0, y0, z0) = (
+ lo.x.floor() as i32,
+ lo.y.floor() as i32,
+ lo.z.floor() as i32,
+ );
+ let (x1, y1, z1) = (
+ hi.x.floor() as i32,
+ hi.y.floor() as i32,
+ hi.z.floor() as i32,
+ );
+ (y0..=y1).flat_map(move |y| (z0..=z1).flat_map(move |z| (x0..=x1).map(move |x| [x, y, z])))
+}
+
+pub fn survives(world: &impl World, bounds: Aabb) -> bool {
+ let (lo, hi) = (bounds.min_position(), bounds.max_position());
+ let anchor = Aabb::new(
+ Vec3::new(lo.x, lo.y - 0.015625, lo.z),
+ Vec3::new(hi.x.next_down(), lo.y, hi.z.next_down()),
+ );
+ // The extra eighth block expands the scan, not the intersection test.
+ let supported = blocks_in(anchor.expand_towards(Vec3::new(0.0, -0.125, 0.0))).any(|p| {
+ world
+ .outline_bounds(p)
+ .is_some_and(|shape| shape.intersects(anchor))
+ });
+ supported && !blocks_in(bounds.next_deflated()).all(|p| world.suffocating(p))
+}
+
+pub fn can_place(world: &impl World, bounds: Aabb) -> bool {
+ if !survives(world, bounds) {
+ return false;
+ }
+ let (lo, hi) = (bounds.min_position(), bounds.max_position());
+ let slab = Aabb::new(lo, Vec3::new(hi.x, lo.y + 0.015625, hi.z)).next_deflated();
+ let Ok(mut remaining) = VoxelShape::from_box(slab) else {
+ return false;
+ };
+ for shape in world.collision_shapes(slab) {
+ let Ok(next) = remaining.join(&shape, ShapeOp::ONLY_FIRST) else {
+ return false;
+ };
+ remaining = next;
+ if remaining.is_empty() {
+ return false;
+ }
+ }
+ true
+}
diff --git a/crates/horizon-client/src/debug_overlay.rs b/crates/horizon-client/src/debug_overlay.rs
index 7140905a8..f55d4ee6e 100644
--- a/crates/horizon-client/src/debug_overlay.rs
+++ b/crates/horizon-client/src/debug_overlay.rs
@@ -221,18 +221,17 @@ pub fn scale(
pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec {
let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])];
for (lines, align_left) in [(columns[0], true), (columns[1], false)] {
- let placed: Vec<(&String, i32, i32)> = lines
+ let placed: Vec<(&String, i32, i32, i32)> = lines
.iter()
.enumerate()
.filter(|(_, l)| !l.is_empty())
.map(|(i, l)| {
let w = font.width(l) as i32;
let left = if align_left { 2 } else { width - 2 - w };
- (l, left, 2 + LINE_HEIGHT * i as i32)
+ (l, left, 2 + LINE_HEIGHT * i as i32, w)
})
.collect();
- for (line, left, top) in &placed {
- let w = font.width(line) as i32;
+ for (_, left, top, w) in &placed {
out.push(fill(
left - 1,
top - 1,
@@ -241,7 +240,7 @@ pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec
BACKGROUND,
));
}
- for (line, left, top) in placed {
+ for (line, left, top, _) in placed {
out.push(GuiDraw::Text {
text: Text::literal(line.clone()),
x: left,
diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs
index 6e8089e9d..69e053411 100644
--- a/crates/horizon-client/src/entities.rs
+++ b/crates/horizon-client/src/entities.rs
@@ -591,6 +591,57 @@ impl Painting {
)
}
}
+/// The `DyeColor` ordinal of a colour name (`DyeColor.byName`), white when
+/// the name is unknown.
+pub fn dye_index(name: &str) -> u8 {
+ crate::mobs::render::DYE_NAMES
+ .iter()
+ .position(|n| *n == name)
+ .unwrap_or(0) as u8
+}
+/// A cushion (`Cushion`, a `BlockAttachedEntity`): a 1 x 0.25 block pillow
+/// that seats a player. It sits on the top face of a block, at the clicked
+/// height, and is coloured by its `DyeColor`.
+#[derive(Clone, Debug)]
+pub struct Cushion {
+ pub id: u32,
+ /// `Entity.position`: the bottom centre of the cushion.
+ pub position: Vec3,
+ /// `BlockAttachedEntity.pos` (the saved `block_pos`).
+ pub pos: [i32; 3],
+ pub yaw: f32,
+ /// `DyeColor` ordinal: white 0, orange 1, ..., black 15.
+ pub color: u8,
+ /// BlockAttachedEntity.ticksSinceLastCheck.
+ pub check_interval: u32,
+}
+impl Cushion {
+ /// `Entity.makeBoundingBox`: x and z half a block out, y to y + 0.25.
+ pub fn bounds(&self) -> ([f64; 3], [f64; 3]) {
+ let p = self.position;
+ (
+ [p.x - 0.5, p.y, p.z - 0.5],
+ [p.x + 0.5, p.y + 0.25, p.z + 0.5],
+ )
+ }
+ /// The `DyeColor` name of the cushion.
+ pub fn color_name(&self) -> &'static str {
+ crate::mobs::render::DYE_NAMES[usize::from(self.color.min(15))]
+ }
+ /// `Cushion.getCushionItemStackWithData`: the matching coloured item.
+ pub fn item(&self) -> String {
+ format!("minecraft:{}_cushion", self.color_name())
+ }
+ /// `Cushion.interact`'s seat: the vehicle's PASSENGER attachment
+ /// `(0, 0.25, 0)` less the player's `(0, 0.6, 0)`.
+ pub fn seat(&self) -> Vec3 {
+ Vec3::new(self.position.x, self.position.y - 0.35, self.position.z)
+ }
+ /// `Entity.getDismountLocationForPassenger`: on top of the cushion.
+ pub fn dismount(&self) -> Vec3 {
+ Vec3::new(self.position.x, self.position.y + 0.25, self.position.z)
+ }
+}
/// An item frame or glow item frame (`ItemFrame`).
#[derive(Clone, Debug)]
pub struct ItemFrame {
diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs
index 00576ea02..7f3565067 100644
--- a/crates/horizon-client/src/entity_nbt.rs
+++ b/crates/horizon-client/src/entity_nbt.rs
@@ -6,7 +6,7 @@
//! survive a Horizon save.
use crate::{
arrows::Pickup,
- entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting},
+ entities::{ArmorStand, Cushion, ExperienceOrb, ItemEntity, ItemFrame, Painting},
mobs::{Mob, MobType, Who},
projectiles::{Projectile, ProjectileKind},
save::{
@@ -1313,6 +1313,79 @@ pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, String)> {
let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8;
Some((pos, facing, text(tag.get("variant"))?))
}
+/// Cushion.addAdditionalSaveData: the block it sits on and its colour.
+pub fn cushion_to_nbt(c: &Cushion, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
+ let base = Base {
+ id: "minecraft:cushion",
+ uuid,
+ position: c.position,
+ motion: Vec3::ZERO,
+ rotation: [c.yaw, 0.0],
+ on_ground: false,
+ fall_distance: 0.0,
+ };
+ let mut tag = base.tag(raw);
+ put(&mut tag, "block_pos", Tag::IntArray(c.pos.to_vec()));
+ put(&mut tag, "color", string(c.color_name()));
+ tag
+}
+/// The position, block position, yaw and colour of a saved cushion.
+pub fn cushion_from_nbt(tag: &Tag, id: u32) -> Option {
+ let position = position(tag)?;
+ let pos = match tag.get("block_pos") {
+ Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]],
+ _ => [
+ position.x.floor() as i32,
+ position.y.floor() as i32,
+ position.z.floor() as i32,
+ ],
+ };
+ let yaw = match tag.get("Rotation") {
+ Some(Tag::List(l)) => l
+ .first()
+ .and_then(|v| crate::save::float(Some(v)))
+ .unwrap_or(0.0) as f32,
+ _ => 0.0,
+ };
+ let color =
+ crate::entities::dye_index(&text(tag.get("color")).unwrap_or_else(|| "white".into()));
+ Some(Cushion {
+ id,
+ position,
+ pos,
+ yaw,
+ color,
+ check_interval: 0,
+ })
+}
+
+#[cfg(test)]
+mod cushion_tests {
+ use super::*;
+
+ #[test]
+ fn cushion_save_preserves_color_anchor_rotation_and_unknown_data() {
+ let cushion = Cushion {
+ id: 7,
+ position: Vec3::new(-1.5, 64.5, 3.5),
+ pos: [-2, 64, 3],
+ yaw: 270.0,
+ color: 14,
+ check_interval: 55,
+ };
+ let raw = Tag::compound([("CustomName", string("Seat"))]);
+ let tag = cushion_to_nbt(&cushion, [1, 2, 3, 4], Some(&raw));
+ assert_eq!(text(tag.get("CustomName")).as_deref(), Some("Seat"));
+ let loaded = cushion_from_nbt(&tag, 8).unwrap();
+ assert_eq!(loaded.id, 8);
+ assert_eq!(loaded.position, cushion.position);
+ assert_eq!(loaded.pos, cushion.pos);
+ assert_eq!(loaded.yaw, cushion.yaw);
+ assert_eq!(loaded.color_name(), "red");
+ assert_eq!(loaded.check_interval, 0);
+ assert_eq!(loaded.bounds(), cushion.bounds());
+ }
+}
/// ItemFrame.addAdditionalSaveData.
pub fn item_frame_to_nbt(f: &ItemFrame, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
let (lo, hi) = f.bounds();
diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs
index 1903cab7e..d0e8c8499 100644
--- a/crates/horizon-client/src/font.rs
+++ b/crates/horizon-client/src/font.rs
@@ -1201,6 +1201,31 @@ mod tests {
assert!(!font.take_patches().is_empty());
}
+ /// A renderer rebuilt over the same font (the loading screen's handoff)
+ /// makes its atlas texture from the textures alone, so the glyphs it had
+ /// rasterized into the previous texture must be placed into the new one.
+ #[test]
+ fn a_rebuilt_atlas_gets_its_glyphs_again() {
+ let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x));
+ let default = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#;
+ let root = root(
+ "rebuild",
+ &[
+ ("assets/minecraft/font/default.json", default),
+ ("assets/minecraft/textures/font/a.png", &sheet),
+ ],
+ );
+ let font = load(&root);
+ let _ = std::fs::remove_dir_all(&root);
+ let first = font.glyph('a');
+ assert_eq!(font.take_patches().len(), 1);
+ font.reset_cache();
+ // Nothing is left over: drawing the character again places its pixels.
+ assert!(font.take_patches().is_empty());
+ assert_eq!(font.glyph('a').advance, first.advance);
+ assert_eq!(font.take_patches().len(), 1);
+ }
+
#[test]
fn provider_filters_follow_the_font_options() {
let sheet = png(8, 8, |x, _| x < 4);
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 4c866a203..d29c8e095 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -18,6 +18,7 @@ mod boats;
mod books;
mod bossbars;
mod breezes;
+mod campfire;
mod cartography;
mod chat;
mod client_ambient;
@@ -33,6 +34,7 @@ mod copper_golems;
mod creaking;
mod creatures;
mod crossbow;
+pub(crate) mod cushions;
mod debug_keys;
mod decorated_pot;
mod dedicated;
@@ -80,6 +82,7 @@ mod lan_mobs;
mod lan_mount_menu;
mod lan_particles;
mod lan_pvp;
+mod lan_quiet;
mod lan_screen;
mod lan_stations;
mod lan_trading;
@@ -147,6 +150,7 @@ mod scoreboard;
mod screens;
mod sculk;
mod sculk_fixture;
+mod server_mods;
mod server_packs;
mod server_travel;
mod shader_packs;
@@ -1436,6 +1440,8 @@ struct Game<'a> {
map_frame_model: frames::FrameModel,
glow_map_frame_model: frames::FrameModel,
armor_stands: Vec,
+ /// `Cushion` decoration entities (game/cushions.rs).
+ cushions: Vec,
/// Entities of types Horizon does not simulate.
others: Vec,
armor_stand_assets: armor_stands::ArmorStandAssets,
@@ -1451,6 +1457,8 @@ struct Game<'a> {
boat_models: boats::BoatModels,
/// EndCrystalModel's baked layer.
crystal_model: Option,
+ /// CushionModel's baked layer.
+ cushion_model: Option,
carts: Vec,
/// Songs playing from jukeboxes (tracked sound handles).
jukebox_sounds: HashMap<(i32, i32, i32), u64>,
@@ -1587,6 +1595,8 @@ struct Game<'a> {
/// position) for the guests.
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
+ /// Successful crits (attacking guest, hit entity), queued while the hub is taken.
+ lan_critical_hits: Vec<(Option, i32)>,
/// Global level events for every guest (`ServerLevel.globalLevelEvent`).
lan_global_events: Vec<(i32, [i32; 3], i32)>,
/// `ContainerOpenersCounter`: how many players (the host and the guests)
@@ -2797,6 +2807,9 @@ impl Game<'_> {
pos,
data,
} => self.consume_teleport_particles([pos.x, pos.y, pos.z], data),
+ LevelEvent::LevelEvent { id: 2003, pos, .. } => {
+ self.eye_break_particles([pos.x, pos.y, pos.z]);
+ }
LevelEvent::LevelEvent {
id: 2013,
pos,
@@ -3348,6 +3361,7 @@ impl Game<'_> {
self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken);
// ServerPlayerGameMode.destroyBlock.
let state = self.world.block(pos[0], pos[1], pos[2]);
+ let broken = state;
let facts = self.res.facts().get(state).clone();
let state = self.crack_mined_pot(pos, state);
// Block.playerWillDestroy: mining their gold angers all nearby piglins.
@@ -3379,6 +3393,9 @@ impl Game<'_> {
creative,
)
});
+ if removed {
+ self.mod_block_event(pos, broken, false);
+ }
if removed && !creative {
let held = self.held().cloned();
self.mine_block_with_held(&facts.name, facts.hardness);
@@ -3487,6 +3504,7 @@ impl Game<'_> {
fn interact_entity(&mut self) -> Result {
Ok(self.interact_frame()
|| self.interact_armor_stand()
+ || self.interact_cushion()
|| self.interact_boat()
|| self.interact_cart()
|| self.interact_mob()?
@@ -3673,6 +3691,7 @@ impl Game<'_> {
|| self.place_painting(hit, &stack)
|| self.place_item_frame(hit, &stack)
|| self.place_armor_stand(hit, &stack)
+ || self.place_cushion(hit, &stack)
|| self.place_end_crystal(hit, &stack))
{
return Ok(true);
@@ -3721,6 +3740,7 @@ impl Game<'_> {
return Ok(true);
};
let target = [pos.x, pos.y, pos.z];
+ self.mod_block_event(target, state, true);
if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) {
let key = (target[0], target[1], target[2]);
self.world.block_entities.insert(key, entity);
@@ -4254,6 +4274,7 @@ impl Game<'_> {
self.update_totem_ready();
self.tick_command_extras();
self.tick_mods();
+ self.tick_server_mods();
let camera_eye = self.camera_eye_height();
let stick = self.pad_move();
if self.riding.is_some() && self.player.is_some() {
@@ -4556,6 +4577,7 @@ impl Game<'_> {
horizon_client::spans::time("tick_paintings", || self.tick_paintings());
horizon_client::spans::time("tick_item_frames", || self.tick_item_frames());
horizon_client::spans::time("tick_armor_stands", || self.tick_armor_stands());
+ horizon_client::spans::time("tick_cushions", || self.tick_cushions());
horizon_client::spans::time("tick_boats", || self.tick_boats());
horizon_client::spans::time("tick_carts", || self.tick_carts());
horizon_client::spans::time("tick_thunder", || self.tick_thunder());
@@ -4764,7 +4786,10 @@ impl Game<'_> {
if capture && !self.focused {
return;
}
- if !capture {
+ if capture {
+ // The inventory's screens are behind us: no drag survives them.
+ self.reset_inventory_clicks();
+ } else {
self.stop_mining();
}
// The real pointer takes over from an agent's.
@@ -5291,7 +5316,8 @@ impl Game<'_> {
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_)
- | BlockEntity::DaylightDetector,
+ | BlockEntity::DaylightDetector
+ | BlockEntity::Campfire(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -5562,7 +5588,8 @@ impl Game<'_> {
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_)
- | BlockEntity::DaylightDetector,
+ | BlockEntity::DaylightDetector
+ | BlockEntity::Campfire(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -5605,7 +5632,18 @@ impl Game<'_> {
self.draw_inventory_effects(batch, (ox, oy), 176);
}
}
+ /// `AbstractContainerScreen` keeps `isQuickCrafting` and the drag it
+ /// belongs to on the screen; Horizon keeps them on the game, so they are
+ /// dropped when a screen closes. A press whose release never reaches the
+ /// screen (the pointer left the window, or the screen closed first) would
+ /// otherwise leave every later press on every later screen swallowed.
+ pub(super) fn reset_inventory_clicks(&mut self) {
+ self.inv_clicks = Default::default();
+ self.inv_drag = None;
+ self.last_inv_click = None;
+ }
pub(super) fn close_container(&mut self) {
+ self.reset_inventory_clicks();
self.close_station();
self.mount_closed();
self.recipe_ui.reset_screen();
@@ -5701,8 +5739,9 @@ impl Game<'_> {
if self.creative_screen.tab().search {
// CreativeModeInventoryScreen.slotClicked: moveCursorToEnd, then
// setHighlightPos(0), so typing replaces the whole query.
- let search = &self.creative_screen.search;
- self.text_selection.select(("creative.search", 0), search);
+ let search = &mut self.creative_screen.search;
+ search.move_cursor_to_end(false);
+ search.highlight = 0;
}
let items = self.creative_screen.items(&self.pack.names);
let first = self.creative_screen.first_row(&self.pack.names);
@@ -6344,6 +6383,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 {
@@ -6909,6 +6955,9 @@ impl Game<'_> {
self.prepare_entity_culling(camera);
self.prepare_trims();
self.mark_entity(out.len(), "minecraft:entity_flame");
+ // One scan for both passes that draw them (block entities below and the
+ // overlay near the end of this function).
+ let cracks = self.cracks(camera);
let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront {
self.yaw + 180.0
} else {
@@ -7005,6 +7054,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).
@@ -7134,7 +7186,7 @@ impl Game<'_> {
.render(&scene, visible, &mut out);
}
self.mark_stage(out.len(), "DESTROY");
- for (pos, stage) in self.cracks(camera) {
+ for &(pos, stage) in &cracks {
let state = self.world.block(pos[0], pos[1], pos[2]);
self.res
.block_entity_render()
@@ -7247,6 +7299,7 @@ impl Game<'_> {
self.frame_geometry(camera, &mut out);
self.mark_entity(out.len(), "minecraft:armor_stand");
self.armor_stand_geometry(camera, alpha, &mut out);
+ self.cushion_geometry(camera, &mut out);
self.mark_entity(out.len(), "minecraft:oak_boat");
self.boat_geometry(camera, alpha, &mut out);
self.mark_entity(out.len(), "minecraft:minecart");
@@ -7277,7 +7330,7 @@ impl Game<'_> {
);
// Breaking progress overlays (destroy_stage_0..9): ours and the other players'.
self.mark_stage(out.len(), "DESTROY");
- for (pos, stage) in self.cracks(camera) {
+ for &(pos, stage) in &cracks {
let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
- camera)
.as_vec3();
@@ -7325,6 +7378,20 @@ impl Game<'_> {
/// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the
/// furthest progress on each block).
fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> {
+ // `destroy_stage_0` .. `destroy_stage_9`: the sprite name by stage, so the
+ // lookup does not format a string per crack.
+ const DESTROY_STAGES: [&str; 10] = [
+ "block/destroy_stage_0",
+ "block/destroy_stage_1",
+ "block/destroy_stage_2",
+ "block/destroy_stage_3",
+ "block/destroy_stage_4",
+ "block/destroy_stage_5",
+ "block/destroy_stage_6",
+ "block/destroy_stage_7",
+ "block/destroy_stage_8",
+ "block/destroy_stage_9",
+ ];
let mut stages: Vec<([i32; 3], u32)> = Vec::new();
let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) {
Some(c) => c.1 = c.1.max(stage),
@@ -7350,11 +7417,8 @@ impl Game<'_> {
d.length_squared() <= 1024.0
})
.filter_map(|(pos, stage)| {
- let r = self
- .gui
- .atlas
- .sprites
- .get(&format!("block/destroy_stage_{stage}"))?;
+ let name = DESTROY_STAGES.get(stage as usize)?;
+ let r = self.gui.atlas.sprites.get(*name)?;
Some((pos, [r.u0, r.v0]))
})
.collect()
@@ -7532,6 +7596,7 @@ impl Game<'_> {
.map_or(0.0, |i| i.attack_damage);
if self.attack_frame()
|| self.attack_armor_stand()
+ || self.attack_cushion()
|| self.attack_boat(hand_damage)
|| self.attack_cart(hand_damage)
|| self.attack_dragon()
@@ -7619,10 +7684,9 @@ impl Game<'_> {
self.stats
.custom("damage_dealt", (actual * 10.0).round() as i32);
if crit {
- self.particles.tracking_emitter(
- horizon_client::particles::ParticleOptions::simple(
- horizon_client::particles::ParticleType::Crit,
- ),
+ self.critical_hit(
+ self.lan_acting,
+ self.mobs[index].id as i32,
feet,
width,
height,
@@ -8277,6 +8341,7 @@ impl Game<'_> {
self.boats.clear();
self.carts.clear();
self.armor_stands.clear();
+ self.cushions.clear();
self.item_frames.clear();
self.paintings.clear();
self.others.clear();
@@ -8695,6 +8760,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(_)))
@@ -9812,20 +9884,16 @@ impl Game<'_> {
);
}
if tab.search {
- // The search box: an unbordered EditBox of 80 at (82, 6), white.
- let search = &self.creative_screen.search;
- horizon_client::ui::append_field(
- batch,
- atlas,
- search,
- (ox + 82.0, oy + 6.0, 80.0),
- (u32::MAX, true),
- clipboard::CREATIVE_SEARCH_CHARS,
- self.text_selection
- .covers(clipboard::CREATIVE_SEARCH, search),
- true,
- self.creative_screen.search_focused.elapsed().as_millis(),
- );
+ // CreativeModeInventoryScreen: an unbordered EditBox of 50 at (82, 6).
+ let search = &mut self.creative_screen.search;
+ search.x = ox + 82.0;
+ search.y = oy + 6.0;
+ search.width = 80.0;
+ search.bordered = false;
+ search.focused = true;
+ search.text_color = u32::MAX;
+ search.max_length = clipboard::CREATIVE_SEARCH_CHARS;
+ search.draw(batch, atlas, None);
}
let mut hovered: Option = None;
if tab.inventory {
@@ -9933,8 +10001,7 @@ impl Game<'_> {
} else if self.carried.is_none()
&& let Some(item) = hovered
{
- let lines = self.stack_tooltip(&item);
- self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
+ self.draw_stack_tooltip(batch, &item, self.cursor.0, self.cursor.1);
}
self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32);
}
@@ -9987,6 +10054,9 @@ impl Game<'_> {
}
return;
}
+ if !right && self.creative_search_click(ox, oy) {
+ return;
+ }
// Holding the scrollbar scrolls as the mouse moves (mouseDragged).
if !right
&& self
@@ -9999,6 +10069,24 @@ impl Game<'_> {
self.inventory_press(right);
}
}
+ /// A click on the search tab's box (`EditBox.onClick`).
+ fn creative_search_click(&mut self, ox: f32, oy: f32) -> bool {
+ if !self.creative_screen.tab().search {
+ return false;
+ }
+ let (x, y, w, h) = (ox + 82.0, oy + 6.0, 80.0, 9.0);
+ let (mx, my) = self.cursor;
+ if mx < x || my < y || mx >= x + w || my >= y + h {
+ return false;
+ }
+ let shift = self.has_shift_down();
+ let search = &mut self.creative_screen.search;
+ search.x = x;
+ search.y = y;
+ search.width = w;
+ search.click(&self.gui.atlas, mx, shift, false);
+ true
+ }
/// Copy the live player and world state into the `Level` that gets saved.
pub(super) fn sync_level(&mut self) {
// Level.write saves the game rules (game_rules.dat) with the rest.
@@ -10317,8 +10405,6 @@ impl Game<'_> {
Vec::new()
};
let mut hud = horizon_client::spans::time("hud", || self.hud(size));
- // Map textures changed since the last drawn frame (game/maps.rs).
- hud.patches.append(&mut self.map_patches);
// LevelLoadingScreen (Reason.OTHER) draws the title's panorama.
let title = self.title.is_some()
|| self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
@@ -10420,6 +10506,10 @@ impl Game<'_> {
} else {
self.shader_pack_inputs(camera, alpha as f32)
};
+ // Map textures and font glyphs changed while building this frame's
+ // geometry (game/maps.rs, world text) upload with this batch; draining
+ // map_patches any earlier leaves them a frame behind.
+ hud.patches.append(&mut self.map_patches);
let entity_spans = std::mem::take(self.entity_spans.get_mut());
let frame = Frame {
weather: &weather,
@@ -11642,8 +11732,17 @@ impl ApplicationHandler for Game<'_> {
// The hovered slot took the key (`ignoreTextInput`).
} else if let Some(shortcut) = self.edit_shortcut(&event) {
self.creative_search_shortcut(shortcut);
- } else if event.physical_key == PhysicalKey::Code(KeyCode::Backspace) {
- self.creative_search_backspace(self.has_control_down());
+ } else if let PhysicalKey::Code(key) = event.physical_key {
+ // EditBox.keyPressed: arrows, Home, End, Delete and Backspace.
+ let before = self.creative_screen.search.value.clone();
+ let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
+ if self.creative_screen.search.key(key, ctrl, shift) {
+ if self.creative_screen.search.value != before {
+ self.creative_screen.scroll = 0.0;
+ }
+ } else {
+ self.creative_search_edit(event.text.as_deref());
+ }
} else {
self.creative_search_edit(event.text.as_deref());
}
@@ -11664,6 +11763,9 @@ impl ApplicationHandler for Game<'_> {
// The anvil rename box takes every key but Escape (AnvilScreen.keyPressed).
if let Some(shortcut) = self.edit_shortcut(&event) {
self.station_shortcut(shortcut);
+ } else if let PhysicalKey::Code(key) = event.physical_key
+ && self.station_key(key)
+ {
} else {
let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace);
self.station_text(event.text.as_deref(), backspace);
@@ -12280,6 +12382,7 @@ impl<'a> Game<'a> {
map_frame_model: prepared.map_frame_model,
glow_map_frame_model: prepared.glow_map_frame_model,
armor_stands: Vec::new(),
+ cushions: Vec::new(),
others: Vec::new(),
armor_stand_assets: prepared.armor_stand_assets,
waypoint_styles: prepared.waypoint_styles,
@@ -12289,6 +12392,7 @@ impl<'a> Game<'a> {
boats: Vec::new(),
boat_models: prepared.boat_models,
crystal_model: prepared.crystal_model,
+ cushion_model: prepared.cushion_model,
carts: Vec::new(),
jukebox_sounds: HashMap::new(),
bolts: Vec::new(),
@@ -12375,6 +12479,7 @@ impl<'a> Game<'a> {
lan_events: Vec::new(),
lan_block_events: Vec::new(),
lan_entity_events: Vec::new(),
+ lan_critical_hits: Vec::new(),
lan_global_events: Vec::new(),
lid_openers: HashMap::new(),
lan_acting: None,
@@ -12426,6 +12531,7 @@ struct GameCpuResources {
boat_models: boats::BoatModels,
cart_models: minecarts::CartModels,
crystal_model: Option,
+ cushion_model: Option,
dragon_model: Option,
arrow_model: Option,
trident_model: Option,
@@ -12446,6 +12552,7 @@ impl GameCpuResources {
boat_models: boats::BoatModels::load(document.as_ref()),
cart_models: minecarts::CartModels::load(document.as_ref()),
crystal_model: model("minecraft:end_crystal#main"),
+ cushion_model: model("minecraft:cushion#main"),
dragon_model: model("minecraft:ender_dragon#main"),
arrow_model: model("minecraft:arrow#main"),
trident_model: model("minecraft:trident#main"),
@@ -13005,6 +13112,14 @@ fn build_renderer(
) -> Result {
let assets = &pack.render;
let atlas = &gui.atlas;
+ // The new renderer's atlas texture starts from `HudAtlas.pixels`, which
+ // holds the textures but never a glyph rasterized at run time. The font's
+ // cache still answers with the rects it drew into the previous renderer's
+ // texture, so forget them: the glyphs that are drawn again are placed into
+ // this texture (as `ui_theme` does when its atlas changes). Without this,
+ // Chinese and Japanese menu labels go blank when the loading screen hands
+ // over to the game.
+ atlas.font.reset_cache();
let mut renderer = pollster::block_on(Renderer::new(
window,
offscreen,
@@ -13051,6 +13166,12 @@ fn loading_renderer(
Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height),
None => (EMPTY_HUD.as_slice(), 1, 1),
};
+ // A glyph rasterized into an earlier texture is not in these pixels; the
+ // new texture gets it again when the character is drawn (see
+ // `build_renderer`).
+ if let Some(atlas) = atlas {
+ atlas.font.reset_cache();
+ }
let mut renderer = pollster::block_on(Renderer::new(
window,
offscreen,
@@ -13787,7 +13908,7 @@ mod startup_cpu_tests {
r#"{
"minecraft:end_crystal#main": {}, "minecraft:ender_dragon#main": {},
"minecraft:arrow#main": {}, "minecraft:trident#main": {},
- "minecraft:armor_stand#main": {}
+ "minecraft:armor_stand#main": {}, "minecraft:cushion#main": {}
}"#,
)
.unwrap();
@@ -13807,6 +13928,7 @@ mod startup_cpu_tests {
.unwrap();
std::fs::remove_dir_all(&root).unwrap();
assert!(prepared.crystal_model.is_some());
+ assert!(prepared.cushion_model.is_some());
assert!(prepared.dragon_model.is_some());
assert!(prepared.arrow_model.is_some());
assert!(prepared.trident_model.is_some());
diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs
index 24ead3a3d..97177f2b9 100644
--- a/crates/horizon-client/src/game/beacon.rs
+++ b/crates/horizon-client/src/game/beacon.rs
@@ -515,8 +515,7 @@ impl Game<'_> {
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = stack_tip {
- let lines = self.stack_tooltip(&stack);
- self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
+ self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
} else if let Some(key) = tooltip {
let text = self.translate(&key, &key);
self.draw_tooltip_lines(
diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs
index 3ddf58281..2778bb531 100644
--- a/crates/horizon-client/src/game/block_entity_ticks.rs
+++ b/crates/horizon-client/src/game/block_entity_ticks.rs
@@ -58,6 +58,7 @@ impl Game<'_> {
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
Some(BlockEntity::DaylightDetector) => self.tick_daylight_detector(pos),
+ Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
_ => {}
}
}
@@ -95,7 +96,10 @@ impl Game<'_> {
| "minecraft:beehive"
| "minecraft:bee_nest"
| "minecraft:brewing_stand"
- | "minecraft:daylight_detector" => Ticking::Yes,
+ | "minecraft:daylight_detector"
+ // Lit, cookTick; unlit, cooldownTick.
+ | "minecraft:campfire"
+ | "minecraft:soul_campfire" => Ticking::Yes,
"minecraft:jukebox" => {
let record = registry
.state(state)
diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs
index df7158d9a..40dd1b7eb 100644
--- a/crates/horizon-client/src/game/boats.rs
+++ b/crates/horizon-client/src/game/boats.rs
@@ -587,6 +587,9 @@ impl Game<'_> {
}
/// The player's tick while riding: steer, tick the boat, sit in it.
pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> {
+ if self.tick_cushion_riding(keys) {
+ return Ok(());
+ }
let Some(i) = self.boats.iter().position(|b| Some(b.id) == self.riding) else {
if self.tick_cart_riding(keys) || self.tick_mount_riding(keys) {
return Ok(());
diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs
index 9af1da70c..2f38dffd9 100644
--- a/crates/horizon-client/src/game/books.rs
+++ b/crates/horizon-client/src/game/books.rs
@@ -17,7 +17,6 @@ use horizon_client::{
use horizon_core::position::BlockPos;
use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S};
use horizon_world::level::flags as level_flags;
-use std::time::Instant;
use winit::{
event::{ElementState, KeyEvent},
keyboard::{KeyCode, PhysicalKey},
@@ -27,8 +26,24 @@ const BLACK: u32 = 0xFF00_0000;
const PAGE_CHARS: usize = 1024;
const MAX_PAGES: usize = 100;
const LINES: usize = 14;
-/// `BookSignScreen`'s title box.
-const BOOK_TITLE: horizon_client::clipboard::FieldId = ("book.title", 0);
+
+fn book_title_box() -> ui::EditBox {
+ let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
+ edit.bordered = false;
+ edit.max_length = 15;
+ edit.text_color = BLACK;
+ edit.focused = true;
+ edit
+}
+fn book_page_box() -> ui::EditBox {
+ let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
+ edit.bordered = false;
+ edit.multiline = true;
+ edit.max_length = PAGE_CHARS;
+ edit.text_color = BLACK;
+ edit.focused = true;
+ edit
+}
pub(super) enum BookScreen {
Edit {
@@ -38,7 +53,10 @@ pub(super) enum BookScreen {
page: usize,
signing: bool,
title: String,
- opened: Instant,
+ /// BookSignScreen's title box (`EditBox` of 15).
+ title_edit: ui::EditBox,
+ /// BookEditScreen's page (`MultiLineEditBox`).
+ page_edit: ui::EditBox,
},
View {
pages: Vec,
@@ -84,13 +102,16 @@ impl Game<'_> {
if pages.is_empty() {
pages.push(String::new());
}
+ let mut page_edit = book_page_box();
+ page_edit.set_value(&pages[0]);
BookScreen::Edit {
slot: self.held_slot(),
pages,
page: 0,
signing: false,
title: String::new(),
- opened: Instant::now(),
+ title_edit: book_title_box(),
+ page_edit,
}
}
"minecraft:written_book" => BookScreen::View {
@@ -239,34 +260,24 @@ impl Game<'_> {
Some(KeyCode::PageDown) => self.turn_page(true),
_ => {}
},
- Some(BookScreen::Edit {
- signing: true,
- title,
- ..
- }) => match key {
+ Some(BookScreen::Edit { signing: true, .. }) => match key {
Some(KeyCode::Escape) => {
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
*signing = false;
}
}
- Some(KeyCode::Backspace) => {
- if !self.text_selection.take(BOOK_TITLE, title) {
- title.pop();
- }
- }
Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
- if !title.trim().is_empty() {
+ let blank = self.book.as_ref().is_some_and(
+ |b| matches!(b, BookScreen::Edit { title, .. } if title.trim().is_empty()),
+ );
+ if !blank {
self.save_book(true);
}
}
+ Some(key) if self.book_title_key(key) => {}
_ => {
if let Some(typed) = text {
- self.text_selection.take(BOOK_TITLE, title);
- for c in typed.chars().filter(|c| !c.is_control()) {
- if title.chars().count() < 15 {
- title.push(c);
- }
- }
+ self.book_title_insert(typed);
}
}
},
@@ -274,24 +285,13 @@ impl Game<'_> {
Some(KeyCode::Escape) => self.save_book(false),
Some(KeyCode::PageUp) => self.turn_page(false),
Some(KeyCode::PageDown) => self.turn_page(true),
- Some(KeyCode::Backspace) => {
- if !self.take_page_selection() {
- self.edit_page(|p| {
- p.pop();
- })
- }
- }
- Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
- self.take_page_selection();
- self.type_into_page("\n")
- }
+ Some(KeyCode::ArrowUp) => self.book_move_line(-1),
+ Some(KeyCode::ArrowDown) => self.book_move_line(1),
+ Some(KeyCode::Enter | KeyCode::NumpadEnter) => self.page_insert("\n"),
+ Some(key) if self.book_page_key(key) => {}
_ => {
if let Some(typed) = text {
- let typed: String = typed.chars().filter(|c| !c.is_control()).collect();
- if !typed.is_empty() {
- self.take_page_selection();
- }
- self.type_into_page(&typed);
+ self.page_insert(typed);
}
}
},
@@ -302,99 +302,258 @@ impl Game<'_> {
pub(super) fn book_type(&mut self, text: &str) {
let text = text.replace("\\n", "\n");
match self.book.as_mut() {
- Some(BookScreen::Edit {
- signing: true,
- title,
- ..
- }) => {
- for c in text.chars().filter(|c| !c.is_control()) {
- if title.chars().count() < 15 {
- title.push(c);
- }
- }
- }
- Some(BookScreen::Edit { .. }) => self.type_into_page(&text),
+ Some(BookScreen::Edit { signing: true, .. }) => self.book_title_insert(&text),
+ Some(BookScreen::Edit { .. }) => self.page_insert(&text),
_ => {}
}
}
- /// Before typing on a page: Select All's selection is cleared (true).
- fn take_page_selection(&mut self) -> bool {
- match self.book.as_mut() {
- Some(BookScreen::Edit { pages, page, .. }) => self
- .text_selection
- .take(("book.page", *page), &mut pages[*page]),
- _ => false,
+ /// `BookSignScreen.keyPressed` on the title box.
+ fn book_title_key(&mut self, key: KeyCode) -> bool {
+ let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
+ let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ else {
+ return false;
+ };
+ if !title_edit.key(key, ctrl, shift) {
+ return false;
}
+ title.clone_from(&title_edit.value);
+ true
}
- /// Ctrl+A/C/V/X: the title box (an `EditBox` of 15) while signing, else
- /// the page (`MultilineTextField.insertText`: line breaks kept, cut to
- /// the 1024 characters left, rejected when it overflows the 14 lines).
- pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
- let font = &self.gui.atlas.font;
- match self.book.as_mut() {
- Some(BookScreen::Edit {
- signing: true,
- title,
- ..
- }) => {
- Self::append_shortcut(
- &mut self.text_selection,
- &mut self.clipboard,
- BOOK_TITLE,
- title,
- shortcut,
- 15,
- );
- }
- Some(BookScreen::Edit { pages, page, .. }) => {
- // truncateInsertionText counts the whole value, selection included.
- let room = PAGE_CHARS.saturating_sub(pages[*page].chars().count());
- self.text_selection.apply(
- ("book.page", *page),
- &mut pages[*page],
- shortcut,
- &mut self.clipboard,
- |value, pasted| {
- let text: String = horizon_client::clipboard::filter_text(pasted, true)
- .chars()
- .take(room)
- .collect();
- let next = format!("{value}{text}");
- font.split(&Text::literal(&next), 114.0).len() <= LINES && {
- *value = next;
- true
- }
- },
- );
- }
- _ => {}
- }
- }
- fn edit_page(&mut self, f: impl FnOnce(&mut String)) {
- if let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_mut() {
- f(&mut pages[*page]);
- }
- }
- /// MultiLineEditBox: characters that keep the page within 14 lines and 1024 characters.
- fn type_into_page(&mut self, typed: &str) {
- let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_ref() else {
+ fn book_title_insert(&mut self, text: &str) {
+ let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ else {
return;
};
- let mut text = pages[*page].clone();
- for c in typed.chars() {
- let mut next = text.clone();
- next.push(c);
- if next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES {
- text = next;
+ title_edit.insert_text(text);
+ title.clone_from(&title_edit.value);
+ }
+ /// `BookEditScreen.keyPressed` on the page, apart from the line moves.
+ fn book_page_key(&mut self, key: KeyCode) -> bool {
+ let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
+ let before = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => Some((
+ page_edit.value.clone(),
+ page_edit.cursor,
+ page_edit.highlight,
+ )),
+ _ => return false,
+ };
+ let handled = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.key(key, ctrl, shift)
+ } else {
+ false
+ };
+ if handled {
+ self.page_keep(before);
+ }
+ handled
+ }
+ /// One character at a time, so a page stops at the last character that fits.
+ fn page_insert(&mut self, text: &str) {
+ for c in text.chars() {
+ self.page_change(|edit| edit.insert_text(&c.to_string()));
+ }
+ }
+ /// Ctrl+A/C/V/X: the title box while signing, else the page.
+ pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
+ let signing = matches!(self.book, Some(BookScreen::Edit { signing: true, .. }));
+ if signing {
+ if let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ {
+ title_edit.shortcut(shortcut, &mut self.clipboard);
+ title.clone_from(&title_edit.value);
+ }
+ return;
+ }
+ let before = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => Some((
+ page_edit.value.clone(),
+ page_edit.cursor,
+ page_edit.highlight,
+ )),
+ _ => None,
+ };
+ if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.shortcut(shortcut, &mut self.clipboard);
+ }
+ self.page_keep(before);
+ }
+ /// Edit the page box, then keep it only within 14 lines and 1024 characters.
+ fn page_change(&mut self, f: impl FnOnce(&mut ui::EditBox)) -> bool {
+ let before = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => Some((
+ page_edit.value.clone(),
+ page_edit.cursor,
+ page_edit.highlight,
+ )),
+ _ => return false,
+ };
+ let ran = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ f(page_edit);
+ true
+ } else {
+ false
+ };
+ ran && self.page_keep(before)
+ }
+ /// Write the page, or put the previous text back when it no longer fits.
+ fn page_keep(&mut self, before: Option<(String, usize, usize)>) -> bool {
+ let next = match self.book.as_ref() {
+ Some(BookScreen::Edit { page_edit, .. }) => page_edit.value.clone(),
+ _ => return false,
+ };
+ let ok = next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES;
+ let Some(BookScreen::Edit {
+ pages,
+ page,
+ page_edit,
+ ..
+ }) = self.book.as_mut()
+ else {
+ return false;
+ };
+ if ok {
+ pages[*page].clone_from(&page_edit.value);
+ } else if let Some((value, cursor, highlight)) = before {
+ page_edit.value = value;
+ page_edit.cursor = cursor;
+ page_edit.highlight = highlight;
+ }
+ ok
+ }
+ /// ArrowUp and ArrowDown move a visual line, keeping the column.
+ fn book_move_line(&mut self, dir: isize) {
+ let shift = self.has_shift_down();
+ let (text, cursor) = match self.book.as_ref() {
+ Some(BookScreen::Edit {
+ pages,
+ page,
+ page_edit,
+ ..
+ }) => (pages[*page].clone(), page_edit.cursor),
+ _ => return,
+ };
+ let rows = self.page_rows(&text);
+ let (x, line) = self.caret_on(&text, &rows, cursor);
+ let next = (line as isize + dir).clamp(0, rows.len() as isize - 1) as usize;
+ let (start, end) = rows[next];
+ let chars: Vec = text.chars().collect();
+ let slice: String = chars[start..end].iter().collect();
+ let pos = start + self.gui.atlas.font.fit(&slice, x);
+ if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.set_cursor(pos, shift);
+ }
+ }
+ /// Wrapped rows of a page as character ranges, the same breaks as `font.split`.
+ fn page_rows(&self, page: &str) -> Vec<(usize, usize)> {
+ let font = &self.gui.atlas.font;
+ let chars: Vec = page.chars().collect();
+ let mut rows = Vec::new();
+ let mut start = 0;
+ while start < chars.len() {
+ let mut end = chars.len();
+ let mut next = chars.len();
+ let mut last_space = None;
+ for i in start..chars.len() {
+ if chars[i] == '\n' {
+ end = i;
+ next = i + 1;
+ break;
+ }
+ if chars[i] == ' ' {
+ last_space = Some(i);
+ }
+ let slice: String = chars[start..=i].iter().collect();
+ if font.width(&slice) > 114.0 {
+ match last_space {
+ Some(s) if s > start => {
+ end = s;
+ next = s + 1;
+ }
+ _ => {
+ end = i.max(start + 1);
+ next = end;
+ }
+ }
+ break;
+ }
+ }
+ rows.push((start, end));
+ start = next;
+ if start == chars.len() && chars.last() == Some(&'\n') {
+ rows.push((chars.len(), chars.len()));
}
}
- self.edit_page(|p| *p = text);
+ if rows.is_empty() {
+ rows.push((0, 0));
+ }
+ rows
+ }
+ /// GUI x of the caret and the row it sits on.
+ fn caret_on(&self, page: &str, rows: &[(usize, usize)], cursor: usize) -> (f32, usize) {
+ let chars: Vec = page.chars().collect();
+ for (i, &(start, end)) in rows.iter().enumerate() {
+ if cursor <= end || i + 1 == rows.len() {
+ let take = cursor.saturating_sub(start).min(end.saturating_sub(start));
+ let prefix: String = chars.iter().skip(start).take(take).collect();
+ return (self.gui.atlas.font.width(&prefix), i);
+ }
+ }
+ (0.0, 0)
+ }
+ fn page_index_at(&self, page: &str, local_x: f32, local_y: f32) -> usize {
+ let rows = self.page_rows(page);
+ let line = (local_y / 9.0).floor().max(0.0) as usize;
+ let line = line.min(rows.len().saturating_sub(1));
+ let (start, end) = rows[line];
+ let chars: Vec = page.chars().collect();
+ let slice: String = chars[start..end].iter().collect();
+ start + self.gui.atlas.font.fit(&slice, local_x.max(0.0))
+ }
+ /// A click on the centred title (`EditBox.onClick`).
+ fn book_title_click(&mut self, field_x: f32, mx: f32) {
+ let shift = self.has_shift_down();
+ let Some(BookScreen::Edit {
+ title, title_edit, ..
+ }) = self.book.as_mut()
+ else {
+ return;
+ };
+ let tx = field_x + ((114.0 - self.gui.atlas.font.width(title)) / 2.0).floor();
+ let rel = (mx - tx).max(0.0);
+ let pos = self.gui.atlas.font.fit(title, rel);
+ title_edit.set_cursor(pos, shift);
+ }
+ /// A click on the open page.
+ fn book_page_click(&mut self, origin_x: f32, origin_y: f32, mx: f32, my: f32) {
+ let shift = self.has_shift_down();
+ let text = match self.book.as_ref() {
+ Some(BookScreen::Edit { pages, page, .. }) => pages[*page].clone(),
+ _ => return,
+ };
+ let pos = self.page_index_at(&text, mx - origin_x, my - origin_y);
+ if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
+ page_edit.set_cursor(pos, shift);
+ }
}
/// The page buttons (`pageForward` adds a page while editing).
fn turn_page(&mut self, forward: bool) {
let mut lectern_page = None;
match self.book.as_mut() {
- Some(BookScreen::Edit { pages, page, .. }) => {
+ Some(BookScreen::Edit {
+ pages,
+ page,
+ page_edit,
+ ..
+ }) => {
+ let before = *page;
if forward {
if *page + 1 >= pages.len() && pages.len() < MAX_PAGES {
pages.push(String::new());
@@ -405,6 +564,10 @@ impl Game<'_> {
} else if *page > 0 {
*page -= 1;
}
+ if *page != before {
+ let text = pages[*page].clone();
+ page_edit.set_value(&text);
+ }
}
Some(BookScreen::View {
lectern: Some(key), ..
@@ -764,6 +927,8 @@ impl Game<'_> {
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
*signing = false;
}
+ } else if inside(left + 36.0, 50.0, 114.0, 9.0) {
+ self.book_title_click(left + 36.0, mx);
}
}
Some(BookScreen::Edit { page, .. }) => {
@@ -780,6 +945,8 @@ impl Game<'_> {
} else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) {
click(self);
self.save_book(false);
+ } else if inside(left + 36.0, 32.0, 114.0, 14.0 * 9.0) {
+ self.book_page_click(left + 36.0, 32.0, mx, my);
}
}
Some(BookScreen::View {
@@ -865,7 +1032,7 @@ impl Game<'_> {
BookScreen::Edit {
signing: true,
title,
- opened,
+ title_edit,
..
} => {
let edit = tr("book.editTitle", "Enter Book Title:");
@@ -881,19 +1048,35 @@ impl Game<'_> {
// The title box: an unbordered, centred EditBox of 114 with
// black text and no shadow; the value alone is centred, the
// cursor follows it.
+ let value = &title_edit.value;
let x = left + 36.0;
- let tx = x + ((114.0 - HudBatch::text_width(atlas, title)) / 2.0).floor();
- horizon_client::ui::append_field(
- batch,
- atlas,
- title,
- (tx, 50.0, x + 114.0 - tx),
- (BLACK, false),
- 15,
- self.text_selection.covers(BOOK_TITLE, title),
- true,
- opened.elapsed().as_millis(),
- );
+ let tx = x + ((114.0 - HudBatch::text_width(atlas, value)) / 2.0).floor();
+ batch.text(atlas, value, tx, 50.0, BLACK, false);
+ if title_edit.cursor != title_edit.highlight {
+ let (a, b) = (
+ title_edit.cursor.min(title_edit.highlight),
+ title_edit.cursor.max(title_edit.highlight),
+ );
+ let pre: String = value.chars().take(a).collect();
+ let sel: String = value.chars().skip(a).take(b - a).collect();
+ let sx = tx + HudBatch::text_width(atlas, &pre);
+ batch.text_highlight(
+ atlas,
+ (sx, 49.0, HudBatch::text_width(atlas, &sel), 11.0),
+ true,
+ );
+ }
+ if title_edit.cursor_visible() {
+ let pre: String = value.chars().take(title_edit.cursor).collect();
+ batch.fill(
+ atlas,
+ tx + HudBatch::text_width(atlas, &pre),
+ 49.0,
+ 1.0,
+ 9.0,
+ BLACK,
+ );
+ }
let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME);
let tw = HudBatch::text_width(atlas, &by);
batch.text(
@@ -941,12 +1124,12 @@ impl Game<'_> {
BookScreen::Edit {
pages,
page,
- opened,
+ page_edit,
..
} => {
indicator(batch, *page, pages.len());
- let blink = (opened.elapsed().as_millis() / 300) % 2 == 0;
- let lines = self.book_lines(&pages[*page]);
+ let text = &pages[*page];
+ let lines = self.book_lines(text);
for (i, line) in lines.iter().take(LINES).enumerate() {
batch.text_styled(
atlas,
@@ -957,27 +1140,39 @@ impl Game<'_> {
false,
);
}
- if blink {
- // The cursor after the last character.
- let last = lines
- .last()
- .map(|l| atlas.font.width_text(l))
- .unwrap_or(0.0);
- let row = lines.len().saturating_sub(1) as f32
- + if pages[*page].ends_with('\n') {
- 1.0
- } else {
- 0.0
- };
- let x = if pages[*page].ends_with('\n') {
- 0.0
- } else {
- last
- };
+ let rows = self.page_rows(text);
+ let (sel_a, sel_b) = (
+ page_edit.cursor.min(page_edit.highlight),
+ page_edit.cursor.max(page_edit.highlight),
+ );
+ if sel_a != sel_b {
+ let chars: Vec = text.chars().collect();
+ for (i, &(start, end)) in rows.iter().enumerate().take(LINES) {
+ let from = sel_a.max(start);
+ let to = sel_b.min(end);
+ if from >= to {
+ continue;
+ }
+ let pre: String = chars[start..from].iter().collect();
+ let sel: String = chars[from..to].iter().collect();
+ batch.text_highlight(
+ atlas,
+ (
+ left + 36.0 + atlas.font.width(&pre),
+ top + 29.0 + i as f32 * 9.0,
+ atlas.font.width(&sel),
+ 9.0,
+ ),
+ true,
+ );
+ }
+ }
+ if page_edit.cursor_visible() {
+ let (x, row) = self.caret_on(text, &rows, page_edit.cursor);
batch.fill(
atlas,
left + 36.0 + x,
- top + 29.0 + row * 9.0,
+ top + 29.0 + row as f32 * 9.0,
1.0,
9.0,
BLACK,
diff --git a/crates/horizon-client/src/game/campfire.rs b/crates/horizon-client/src/game/campfire.rs
new file mode 100644
index 000000000..c388b7561
--- /dev/null
+++ b/crates/horizon-client/src/game/campfire.rs
@@ -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