Merge main into fix/container-mouse-hotkeys

game.rs: keep this branch's container hotbar-mouse check, then #637's
mouse-bound sort key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 04:50:43 +02:00
58 changed files with 2319 additions and 436 deletions
+1 -1
View File
@@ -83,7 +83,7 @@ jobs:
- name: The harnesses this change can affect
env:
PARITY_HOSTS: ''
run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 1500
run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 2400 # world_spawn takes ~1480 s on a busy runner
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v4
@@ -88,6 +88,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
seed: 0,
max_players: 8,
dedicated: false,
integrated: false,
},
);
let mut next_entity = 100u32;
+26
View File
@@ -199,6 +199,14 @@ pub fn dye_rgb(name: &str) -> u32 {
pub fn layers(stack: &ItemStack) -> &[BannerLayer] {
stack.data().map_or(&[], |d| &d.banner_patterns)
}
/// The ominous banner's component patch hides its pattern tooltip.
pub fn tooltip_layers(stack: &ItemStack) -> &[BannerLayer] {
if stack.data().is_some_and(|d| d.ominous_banner) {
&[]
} else {
layers(stack)
}
}
/// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour.
pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack {
let mut result = ItemStack {
@@ -302,6 +310,24 @@ mod tests {
}
assert!(has_max_layers(&banner));
}
#[test]
fn ominous_banner_hides_tooltip_layers_but_keeps_its_patterns() {
let mut banner = crate::mobs::raider::ominous_banner();
(banner.damage, banner.extra) = crate::item_data::decode_components(
crate::item_data::encode_components(&banner).as_ref(),
);
assert_eq!(
layers(&banner).len(),
crate::item_data::OMINOUS_LAYERS.len()
);
assert!(tooltip_layers(&banner).is_empty());
banner.data_mut().custom_name = Some("Captain's Standard".into());
assert!(tooltip_layers(&banner).is_empty());
banner.data_mut().ominous_banner = false;
assert_eq!(tooltip_layers(&banner), layers(&banner));
assert!(!tooltip_layers(&banner).is_empty());
}
#[test]
fn layers_round_trip_through_nbt() {
let l = vec![
@@ -876,7 +876,7 @@ impl BlockEntityRenderer {
.as_vec3();
let base = Mat4::from_translation(origin);
let packed = scene.world.light(pos[0], pos[1], pos[2]);
self.render_one(scene, *pos, kind, base, packed, lights, out);
self.render_one(scene, *pos, kind, base, packed, lights, false, out);
}
}
/// One block entity at `pos` drawn under `base` with the given packed light
@@ -892,12 +892,39 @@ impl BlockEntityRenderer {
) {
let kind = self.kind(state);
let lights = diffuse_lights(scene.nether);
self.render_one(scene, pos, kind, base, packed, lights, out);
self.render_one(scene, pos, kind, base, packed, lights, false, out);
}
/// Whether this block state has a block-entity renderer here.
pub fn renders(&self, state: u32) -> bool {
!matches!(self.kind(state), Kind::None)
}
/// BannerRenderer submits the support and animated flag once for crumbling.
pub fn render_banner_breaking(
&self,
scene: &Scene,
pos: [i32; 3],
state: u32,
out: &mut Vec<Vertex>,
) {
if !matches!(self.kind(state), Kind::Banner { .. }) {
return;
}
let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
- scene.camera)
.as_vec3();
let start = out.len();
self.render_one(
scene,
pos,
self.kind(state),
Mat4::from_translation(origin),
0xff,
diffuse_lights(scene.nether),
true,
out,
);
crate::breaking::entity_geometry(&mut out[start..], origin);
}
/// `ChestRenderer.extractRenderState`'s openness for the chest of `state`
/// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`)
/// pairs a double half with its neighbour only when that is the same
@@ -970,7 +997,7 @@ impl BlockEntityRenderer {
let kind = self.kind(state);
if !matches!(kind, Kind::None) {
let lights = diffuse_lights(scene.nether);
self.render_one(scene, [i32::MAX; 3], kind, base, packed, lights, out);
self.render_one(scene, [i32::MAX; 3], kind, base, packed, lights, false, out);
}
}
#[allow(clippy::too_many_arguments)]
@@ -982,11 +1009,24 @@ impl BlockEntityRenderer {
base: Mat4,
packed: u8,
lights: (Vec3, Vec3),
crumbling: bool,
out: &mut Vec<Vertex>,
) {
let sprite = |name: &str| scene.sprites.get(name).copied();
let paint = |name: &str, tint: u32, packed: u8| {
sprite(name).map(|s| Paint {
let rect = if crumbling {
Some(Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 16,
h: 16,
})
} else {
sprite(name)
};
rect.map(|s| Paint {
sprite: s,
tint,
light: vertex_light(packed),
@@ -1145,6 +1185,10 @@ impl BlockEntityRenderer {
draw_part(main, "root", m, &none, paint, out);
draw_part(flag, "root", m, &wave, paint, out);
}
// Pattern passes must not multiply the crumbling decal.
if crumbling {
return;
}
// BannerRenderer.submitPatterns: the base pattern layer in the dye colour,
// then up to 16 pattern layers in order.
if let Some(paint) = paint("entity/banner/base", *color, packed) {
@@ -1673,6 +1717,109 @@ fn portal_cube(m: Mat4, faces: &[Direction], layer: u32, out: &mut Vec<Vertex>)
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore = "requires prepared models/textures in HORIZON_TEST_RESOURCES"]
fn banner_particle_and_breaking_use_exported_models() -> crate::Result<()> {
use crate::{models::catalog::StateModels, sprites::Sprites};
use horizon_world::{DATA_VERSION, chunk::BlockState, nbt::Tag};
let root = std::path::PathBuf::from(
std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"),
);
let names = ["white_banner", "white_wall_banner"];
let mut facts: std::collections::BTreeMap<String, Value> =
serde_json::from_slice(&std::fs::read(root.join("model-states.json"))?)?;
let states = names.map(|name| {
let name = format!("minecraft:{name}");
let first = facts[&name]["states"][0].clone();
facts.get_mut(&name).unwrap()["states"] = serde_json::json!([first.clone()]);
BlockState {
name,
properties: serde_json::from_value(first).unwrap(),
}
.to_nbt()
});
let registry = BlockRegistry::from_nbt(&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
("states", Tag::List(states.into())),
(
"defaults",
Tag::compound([
("minecraft:white_banner", Tag::Int(0)),
("minecraft:white_wall_banner", Tag::Int(1)),
]),
),
]))?;
let mut sprites = Sprites::default();
let catalog = StateModels::from_facts(&root, &registry, &names, &mut sprites, &facts)?;
for id in 0..2 {
let models = catalog.collect(
BlockStateId(id),
horizon_core::position::BlockPos::default(),
)?;
assert!(models.iter().all(|(_, model)| model.faces.is_empty()));
assert_eq!(
models[0].1.particle,
Some(sprites.layers["minecraft:block/oak_planks"])
);
}
let all: Value = serde_json::from_slice(&std::fs::read(root.join("entity-models.json"))?)?;
let renderer = BlockEntityRenderer::new(
MODELS
.iter()
.filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v))))
.collect(),
&registry,
);
let world = World::new(BlockStateId(0), 1);
let base_sprites = HashMap::from([(
"entity/banner/banner_base".to_owned(),
Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 16,
h: 16,
},
)]);
let mut scene = Scene {
camera: DVec3::ZERO,
orientation: Quat::IDENTITY,
anim: &|_| BlockAnim::default(),
texts: None,
partial: 0.5,
game_time: 0,
max_y: 320,
world: &world,
sprites: &base_sprites,
nether: false,
lid: &|_| 0.0,
sign: &|_| None,
banner: &|_| Vec::new(),
glyph: &|_| (None, 0.0),
};
for state in 0..2 {
let mut base = Vec::new();
renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base);
let mut cracks = Vec::new();
renderer.render_banner_breaking(&scene, [0; 3], state, &mut cracks);
assert!(!cracks.is_empty());
assert_eq!(
base.iter().map(|v| v.pos).collect::<Vec<_>>(),
cracks.iter().map(|v| v.pos).collect::<Vec<_>>()
);
assert!(cracks.iter().all(|v| v.layer == 11
&& v.color == u32::MAX
&& v.uv.iter().all(|u| u.is_finite())));
scene.game_time = 20;
let mut animated = Vec::new();
renderer.render_banner_breaking(&scene, [0; 3], state, &mut animated);
assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos));
scene.game_time = 0;
}
Ok(())
}
#[test]
fn classifies_vanilla_block_names() {
let props = |pairs: &'static [(&'static str, &'static str)]| {
+48
View File
@@ -41,6 +41,35 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out:
}
}
/// Project a block entity's transformed quads onto the same destroy-stage pass.
pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) {
for quad in vertices.as_chunks_mut::<4>().0 {
let positions = [0, 1, 2].map(|i| glam::Vec3::from(quad[i].pos));
let normal = (positions[1] - positions[0]).cross(positions[2] - positions[0]);
let mut facing = Direction::North;
let mut best = f32::from_bits(1);
for (direction, dot) in [
(Direction::Down, -normal.y),
(Direction::Up, normal.y),
(Direction::North, -normal.z),
(Direction::South, normal.z),
(Direction::West, -normal.x),
(Direction::East, normal.x),
] {
if dot > best {
facing = direction;
best = dot;
}
}
for vertex in quad {
vertex.uv = decal_uv((glam::Vec3::from(vertex.pos) - origin).to_array(), facing);
vertex.layer = 11;
vertex.color = 0xffff_ffff;
vertex.light = 240 | (240 << 8);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -49,6 +78,7 @@ mod tests {
fn slab_top() -> BakedModel {
BakedModel {
ambient_occlusion: true,
particle: None,
cube: None,
faces: vec![BakedFace {
layer: 0,
@@ -86,6 +116,24 @@ mod tests {
assert_eq!(v.color, 0xffff_ffff);
}
}
#[test]
fn entity_overlay_uses_block_local_projected_uvs() {
let origin = glam::Vec3::new(12.0, -3.0, 8.0);
let mut expected = Vec::new();
geometry(&slab_top(), origin, false, &mut expected);
let mut actual = expected.clone();
for vertex in &mut actual {
vertex.uv = [0.0; 2];
vertex.layer = 0;
vertex.color = 0;
}
entity_geometry(&mut actual, origin);
assert_eq!(
bytemuck::cast_slice::<_, u8>(&actual),
bytemuck::cast_slice::<_, u8>(&expected)
);
}
#[test]
fn small_faces_use_projected_not_stretched_uvs() {
let a = decal_uv([0.0, 0.0, 0.0], Direction::North);
+2
View File
@@ -132,6 +132,8 @@ impl Crafter {
pub struct Banner {
pub layers: Vec<crate::banner::BannerLayer>,
pub name: Option<String>,
/// Components not consumed by BannerBlockEntity's implicit fields.
pub components: horizon_world::nbt::Compound,
}
/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`).
#[derive(Clone, Debug, Default)]
+41
View File
@@ -68,6 +68,14 @@ impl EffectInstance {
}
changed
}
/// `MobEffectInstance.tickClient`: a client counts its effects down
/// (the server removes them).
pub fn tick_client(&mut self) {
if self.infinite() || self.duration > 0 {
self.tick_down();
self.downgrade();
}
}
fn tick_down(&mut self) {
if let Some(h) = self.hidden.as_mut() {
h.tick_down();
@@ -170,6 +178,39 @@ impl PlayerEffects {
pub fn clear(&mut self) {
self.list.clear();
}
/// The effects of a saved player (`Player.active_effects`: id,
/// duration, amplifier, ambient, visible).
pub fn from_saved(saved: &[(String, i32, i32, bool, bool)]) -> Self {
let mut effects = Self::default();
for (id, duration, amplifier, ambient, _) in saved {
if let Some(def) = brewing::effect(id) {
let mut e = EffectInstance::new(def.id, *duration, *amplifier);
e.ambient = *ambient;
effects.add(e);
}
}
effects
}
/// `Player.active_effects` for the save.
pub fn saved(&self) -> Vec<(String, i32, i32, bool, bool)> {
self.list
.iter()
.map(|e| {
(
format!("minecraft:{}", e.id),
e.duration,
e.amplifier,
e.ambient,
e.visible,
)
})
.collect()
}
/// ClientboundUpdateMobEffectPacket's flags without blending: ambient,
/// particles visible and the icon shown (always, for these effects).
pub fn flags(e: &EffectInstance) -> i8 {
i8::from(e.ambient) | i8::from(e.visible) << 1 | 4
}
/// `LivingEntity.tickEffects` (server part) with the omens' effect ticks:
/// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect`
/// (on its last tick). Returns the actions to apply, in order, and
+16 -2
View File
@@ -68,6 +68,7 @@ impl Corner {
#[derive(Clone, Debug, PartialEq)]
pub struct Extras {
pub fullbright: bool,
pub zoom: bool,
/// A vanilla key name (`key.keyboard.z`).
pub zoom_key: String,
@@ -108,6 +109,7 @@ pub struct Extras {
impl Default for Extras {
fn default() -> Self {
Self {
fullbright: false,
zoom: false,
zoom_key: "key.keyboard.z".into(),
zoom_level: 4,
@@ -155,6 +157,7 @@ impl Extras {
_ => d,
};
match key.trim() {
"fullbright" => e.fullbright = flag(e.fullbright),
"zoom" => e.zoom = flag(e.zoom),
"zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(),
"zoomLevel" => {
@@ -198,7 +201,8 @@ impl Extras {
}
pub fn serialize(&self) -> String {
format!(
"zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
"fullbright:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
bool_text(self.fullbright),
bool_text(self.zoom),
self.zoom_key,
self.zoom_level,
@@ -418,6 +422,7 @@ impl Cps {
/// The settings the Extras page shows, one per row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Item {
Fullbright,
Zoom,
ZoomKey,
ZoomLevel,
@@ -445,6 +450,8 @@ pub enum Item {
pub fn rows() -> Vec<Result<Item, &'static str>> {
use Item::*;
vec![
Err("Lighting"),
Ok(Fullbright),
Err("Zoom"),
Ok(Zoom),
Ok(ZoomKey),
@@ -493,6 +500,7 @@ fn next<T: Copy + PartialEq>(all: &[T], current: T, back: bool) -> T {
impl Item {
pub fn caption(self) -> &'static str {
match self {
Item::Fullbright => "Fullbright",
Item::Zoom => "Zoom",
Item::ZoomKey => "Zoom key",
Item::ZoomLevel => "Starting zoom",
@@ -518,6 +526,7 @@ impl Item {
/// What the row says under its caption.
pub fn description(self) -> &'static str {
match self {
Item::Fullbright => "Show blocks and entities at full light, even in dark areas.",
Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.",
Item::ZoomKey => "Click, then press a key. Escape unbinds it.",
Item::ZoomLevel => "The zoom the key starts at.",
@@ -556,7 +565,7 @@ impl Item {
pub fn cost(self) -> Option<crate::graphics_style::Cost> {
use crate::graphics_style::Cost;
match self {
Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
Item::Minimap => Some(Cost::Low),
Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None),
_ => None,
@@ -565,6 +574,7 @@ impl Item {
/// On/off items and their value.
pub fn switch(self, e: &Extras) -> Option<bool> {
Some(match self {
Item::Fullbright => e.fullbright,
Item::Zoom => e.zoom,
Item::ZoomSmooth => e.zoom_smooth,
Item::ZoomSensitivity => e.zoom_sensitivity,
@@ -606,6 +616,7 @@ impl Item {
/// A click (`back` for the right button). The zoom key binds instead.
pub fn cycle(self, e: &mut Extras, back: bool) {
match self {
Item::Fullbright => e.fullbright = !e.fullbright,
Item::Zoom => e.zoom = !e.zoom,
Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth,
Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity,
@@ -651,11 +662,14 @@ mod tests {
#[test]
fn everything_is_off_by_default_and_round_trips() {
let d = Extras::default();
assert!(!d.fullbright);
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
assert!(!d.mouse_tweaks && !d.sort);
assert_eq!(Extras::parse(""), d);
assert_eq!(Extras::parse(&d.serialize()), d);
let mut e = d.clone();
Item::Fullbright.cycle(&mut e, false);
assert_eq!(Item::Fullbright.switch(&e), Some(true));
e.zoom = true;
e.zoom_key = "key.keyboard.c".into();
e.zoom_level = 6;
+43 -33
View File
@@ -1087,6 +1087,8 @@ struct Game<'a> {
lan: Option<lan::LanHost>,
/// Single player's server thread, which `remote` is connected to.
integrated: Option<integrated::Integrated>,
/// This game is that server thread's (game/integrated.rs).
serving: Option<integrated::Serving>,
/// The open world is shared behind an invite code (game/friends.rs).
friends: Option<friends::Sharing>,
world_options: Option<lan_screen::WorldOptions>,
@@ -1447,9 +1449,13 @@ impl Game<'_> {
.iter()
.flat_map(|(_, m)| m.faces.iter())
.find(|f| f.quad.facing == horizon_assets::model::Direction::Up)
.or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next())?;
let name = self.pack.layer_names.get(&face.layer)?.clone();
let tint = if face.quad.tint_index >= 0 {
.or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next());
// Entity-rendered blocks may have a particle texture without any faces.
let layer = face
.map(|face| face.layer)
.or_else(|| models.iter().find_map(|(_, model)| model.particle))?;
let name = self.pack.layer_names.get(&layer)?.clone();
let tint = if face.is_some_and(|face| face.quad.tint_index >= 0) {
let n = &self.res.facts.get(state).name;
if n.contains("leaves") || n.contains("vine") {
0x48B518
@@ -1777,6 +1783,12 @@ impl Game<'_> {
});
self.process_level_events()
}
fn attack_block(&mut self, pos: [i32; 3]) -> Result<()> {
self.with_level(|b, level, ticks| {
b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2]));
});
self.process_level_events()
}
/// Track which chunks are ticking (Ticks needs chunk load/unload).
fn sync_tick_chunks(&mut self) {
if !self.tick_chunks.synchronize(&self.world.chunks) {
@@ -2885,6 +2897,7 @@ impl Game<'_> {
return Ok(());
}
if self.mining.as_ref().is_none_or(|m| m.pos != hit.pos) {
self.attack_block(hit.pos)?;
self.mining = Some(Mining {
pos: hit.pos,
progress: 0.0,
@@ -3634,8 +3647,8 @@ impl Game<'_> {
}
/// `Minecraft.pause`: a single-player game with a pausing screen open.
fn pauses_game(&self) -> bool {
(self.remote.is_none() || self.integrated.is_some())
&& self.lan.is_none()
self.has_singleplayer_server()
&& !self.is_published()
&& self.title.is_none()
&& (matches!(
self.screen,
@@ -4336,14 +4349,7 @@ impl Game<'_> {
} else {
("Crafting", 97.0)
};
batch.text(
atlas,
title,
ox + tx,
oy + if self.craft_size == 3 { 6.0 } else { 8.0 },
grey,
false,
);
batch.text(atlas, title, ox + tx, oy + 6.0, grey, false);
if self.craft_size == 3 {
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
}
@@ -5579,6 +5585,20 @@ impl Game<'_> {
.block_entity_render
.render(&scene, visible, &mut out);
}
if let Some(mining) = &self.mining
&& mining.progress > 0.0
&& self.atlas.sprites.contains_key(&format!(
"block/destroy_stage_{}",
((mining.progress * 10.0) as u32).min(9)
))
{
let state = self
.world
.block(mining.pos[0], mining.pos[1], mining.pos[2]);
self.res
.block_entity_render
.render_banner_breaking(&scene, mining.pos, state.0, &mut out);
}
}
// Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.
if let Some(r) = self
@@ -8064,7 +8084,7 @@ impl Game<'_> {
self.creative_screen.search_focused.elapsed().as_millis(),
);
}
let mut hovered: Option<String> = None;
let mut hovered: Option<ItemStack> = None;
if tab.inventory {
self.draw_player_preview(
batch,
@@ -8114,7 +8134,7 @@ impl Game<'_> {
&& self.cursor.1 < y + 16.0
{
batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128));
hovered = Some(stack.item.to_string());
hovered = Some(stack.clone());
}
}
}
@@ -8129,7 +8149,7 @@ impl Game<'_> {
&& self.cursor.1 >= y
&& self.cursor.1 < y + 16.0
{
hovered = Some(stack.item.to_string());
hovered = Some(stack);
}
}
let scrollable = self.creative_screen.rows(&self.pack.names) > 5;
@@ -8165,8 +8185,8 @@ impl Game<'_> {
} else if self.carried.is_none()
&& let Some(item) = hovered
{
let name = self.pack.names.item(&item);
self.tooltip(batch, &name, self.cursor.0, self.cursor.1);
let lines = self.stack_tooltip(&item);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
}
self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32);
}
@@ -8310,21 +8330,7 @@ impl Game<'_> {
self.ender_items = items.clone();
}
level.ender_items = self.ender_items.clone();
level.active_effects = self
.potions
.effects
.list
.iter()
.map(|e| {
(
format!("minecraft:{}", e.id),
e.duration,
e.amplifier,
e.ambient,
e.visible,
)
})
.collect();
level.active_effects = self.potions.effects.saved();
}
fn save_game(&mut self) -> Result<()> {
self.save_game_with(true)
@@ -9375,6 +9381,9 @@ impl ApplicationHandler for Game<'_> {
// Neither edge of a bound button is an ordinary slot click.
return Ok(());
}
if pressed && self.sort_mouse_press(button) {
return Ok(());
}
match self.screen {
Screen::Playing => {
if pressed && !self.captured {
@@ -10098,6 +10107,7 @@ impl<'a> Game<'a> {
remote: None,
lan: None,
integrated: None,
serving: None,
world_options: None,
options_to_world_options: false,
command_block_screen: None,
+4 -1
View File
@@ -460,7 +460,10 @@ impl Game<'_> {
json!({
"screen": self.screen_label(),
"menu": self.title.as_ref().map(|_| self.title_value()),
"world": (self.title.is_none()).then(|| self.level.name.clone()),
"world": (self.title.is_none()).then(|| match &self.integrated {
Some(server) => server.world_name.clone(),
None => self.level.name.clone(),
}),
"dimension": self.dim.id(),
"gamemode": format!("{:?}", self.mode).to_lowercase(),
"time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) },
+6
View File
@@ -425,6 +425,12 @@ impl Game<'_> {
capture.push(text);
return;
}
// Connected to a server (single player's own included), the chat on
// screen is the connection's: the game's own messages join it.
if self.remote.is_some() {
self.chat_line(text.plain());
return;
}
let focused = self.screen == Screen::Chat;
let heard = self.mods.mods.is_running().then(|| text.plain());
self.ui.chat.add(
@@ -758,18 +758,25 @@ impl Game<'_> {
.and_then(|l| l.local_addr())
.map_or(25564, |a| i32::from(a.port())),
};
if let Some(lan) = &self.lan {
return Err(err(
"commands.publish.alreadyPublished.lan",
&[&lan.settings.port],
));
let published = if self.serving() {
self.published_port()
} else {
self.lan.as_ref().map(|l| l.settings.port)
};
if let Some(port) = published {
return Err(err("commands.publish.alreadyPublished.lan", &[&port]));
}
let settings = super::super::lan::LanSettings {
port: port as u16,
guest_commands: allow,
force_game_mode: false,
};
if self.lan_start(settings).is_err() {
let started = if self.serving() {
self.publish(settings).is_ok()
} else {
self.lan_start(settings).is_ok()
};
if !started {
return Err(err("commands.publish.failed", &[]));
}
let port_text = port.to_string();
@@ -785,6 +792,13 @@ impl Game<'_> {
Ok(port)
}
pub(super) fn cmd_unpublish(&mut self) -> R<i32> {
if self.serving() {
if !self.unpublish() {
return Err(err("commands.unpublish.notPublished", &[]));
}
self.feedback(Text::translate("commands.unpublish.success", &[]));
return Ok(1);
}
if self.lan.is_none() {
return Err(err("commands.unpublish.notPublished", &[]));
}
+28 -13
View File
@@ -29,7 +29,7 @@ const HELP: &[&str] = &[
"chat TEXT send a chat line or /command as if typed",
"type TEXT type into the open chat box (key enter tap sends)",
"chat-log [N] the newest N chat messages (default 10)",
"options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs graphics graphics-advanced)",
"options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs mods graphics graphics-advanced)",
"stats [reset] frame-time summary since the last reset",
"bench SECONDS reset stats, wait, then reply with the summary",
"fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]] fly the camera along a line at constant speed, then reply with the frame summary (raw: every frame time too)",
@@ -462,6 +462,7 @@ impl Game<'_> {
"language" => Page::Language,
"font" => Page::Font,
"packs" => Page::Packs,
"mods" => Page::Mods,
"graphics" => Page::Graphics,
"graphics-advanced" => Page::GraphicsAdvanced,
other => return Err(format!("unknown options page {other}").into()),
@@ -475,7 +476,10 @@ impl Game<'_> {
}
"chat-log" => {
let n = words.get(1).map_or(Ok(10), |n| n.parse())?;
Ok(Some(json!({ "chat": self.ui.chat.recent_lines(n) })))
let lines = self
.remote_chat(n)
.unwrap_or_else(|| self.ui.chat.recent_lines(n));
Ok(Some(json!({ "chat": lines })))
}
"stats" => {
let summary = self.frame_stats.summary();
@@ -549,18 +553,20 @@ impl Game<'_> {
self.leave_server(None)?;
ok()
}
"save" => {
"save" | "save-all" => {
self.require_world()?;
self.save_game()?;
ok()
}
"save-all" => {
// Like `save-all flush`: also rewrite chunks that were not modified
// (the save round-trip harness compares them with vanilla's files).
self.require_world()?;
let keys: Vec<_> = self.world.chunks.keys().copied().collect();
self.world.modified.extend(keys);
self.save_game()?;
// `save-all` is like `save-all flush`: it also rewrites chunks
// that were not modified (the save round-trip harness compares
// them with vanilla's files).
let all = words[0] == "save-all";
// Single player's world is its server thread's.
if let Some(server) = &self.integrated {
server
.call(move |g| g.control_save(all).map_err(|e| e.to_string()))
.ok_or("the integrated server stopped")??;
} else {
self.control_save(all)?;
}
ok()
}
"dragon-hurt" => {
@@ -581,6 +587,15 @@ impl Game<'_> {
}
}
/// `horizon-ctl save` and `save-all`.
fn control_save(&mut self, all: bool) -> Result<()> {
if all {
let keys: Vec<_> = self.world.chunks.keys().copied().collect();
self.world.modified.extend(keys);
}
self.save_game()
}
fn require_world(&self) -> Result<()> {
if self.title.is_some() {
return Err("no world open; use: open WORLD [SEED] [creative]".into());
+1 -1
View File
@@ -38,7 +38,7 @@ impl DebugHost for Host<'_, '_> {
// the menu as it always has (key_pressed).
let g = &mut *self.game;
if without_menu && g.screen == Screen::Playing {
g.pause_menu = !(g.remote.is_none() && g.lan.is_none());
g.pause_menu = !(g.has_singleplayer_server() && !g.is_published());
g.screen = Screen::Paused;
g.capture(false);
g.mining = None;
@@ -463,6 +463,7 @@ impl Game<'_> {
seed: self.level.seed,
max_players: props.max_players.max(0) as usize,
dedicated: true,
integrated: false,
};
let settings = LanSettings {
port,
+5 -1
View File
@@ -58,8 +58,12 @@ impl Game<'_> {
pub(super) fn extras_scroll(&mut self, steps: f32) -> bool {
self.settings.extras.zoom && self.extras.zoom.scroll(steps)
}
/// Mouse buttons while playing, for the keystroke overlay.
/// Mouse buttons while playing, for zoom and the keystroke overlay.
pub(super) fn extras_mouse(&mut self, button: MouseButton, pressed: bool) {
let e = &self.settings.extras;
if e.zoom && e.zoom_key == keybinds::mouse_name(button) {
self.extras.zoom.key(pressed, false, true, e.zoom_level);
}
let i = match button {
MouseButton::Left => 0,
MouseButton::Right => 1,
+4 -1
View File
@@ -409,7 +409,10 @@ impl HandWorld for GameHands<'_, '_> {
fn within_border(&mut self, _: [i32; 3]) -> bool {
true
}
fn attack_block(&mut self, _: [i32; 3]) {}
fn attack_block(&mut self, pos: [i32; 3]) {
let result = self.game.attack_block(pos);
self.keep(result);
}
fn destroy_progress(&mut self, pos: [i32; 3]) -> f32 {
self.game.destroy_progress(pos)
}
+290 -23
View File
@@ -2,6 +2,10 @@
//! its own "Server thread", as vanilla's does, and the window joins it as a
//! player through memory, so a world tick never holds up a frame.
//!
//! The window asks its server for what only the server knows (Open to LAN,
//! the world's options) with [`Integrated::call`], as vanilla's client calls
//! into its `IntegratedServer`.
//!
//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the
//! player joins as a network player, and the server side of a network player
//! does not do everything single player does yet. Worlds whose player is
@@ -15,7 +19,7 @@ use horizon_client::{
Result,
audio::Audio,
hud::HudAtlas,
lan::{MAX_PLAYERS, NetConfig, hub::HubConfig},
lan::{Lan, MAX_PLAYERS, NetConfig, hub::HubConfig},
save::Level,
settings::Settings,
title::WorldOptions,
@@ -23,11 +27,12 @@ use horizon_client::{
use horizon_protocol::connection::Pipe;
use horizon_protocol::{crypto::offline_uuid, text::translatable};
use std::{
net::TcpListener,
path::Path,
sync::{
Arc,
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::{Sender, channel},
atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering},
mpsc::{Receiver, Sender, channel, sync_channel},
},
thread::JoinHandle,
time::{Duration, Instant},
@@ -39,13 +44,22 @@ struct Flags {
/// `Minecraft.pause`: a single-player pause screen is open.
paused: AtomicBool,
stop: AtomicBool,
/// `IntegratedServer.getPort`: the port it is open to the LAN on, 0
/// while it is not.
published: AtomicU16,
smoothed_tick_ms: AtomicU32,
}
/// Work the window hands its server thread (`MinecraftServer.execute`).
type Task = Box<dyn FnOnce(&mut Game<'_>) + Send>;
/// The window's handle on its server thread.
pub(super) struct Integrated {
flags: Arc<Flags>,
thread: Option<JoinHandle<()>>,
tasks: Sender<Task>,
/// The world's name (`level.dat`'s `LevelName`), for the pause menu.
pub world_name: String,
}
impl Integrated {
pub fn smoothed_tick_ms(&self) -> f32 {
@@ -55,6 +69,24 @@ impl Integrated {
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
}
/// `IntegratedServer.getPort` while `isPublished`.
pub fn published(&self) -> Option<u16> {
Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0)
}
/// `executeBlocking`: run `f` on the server thread between two ticks and
/// wait for its answer; `None` once the server has stopped.
pub fn call<T: Send + 'static>(
&self,
f: impl FnOnce(&mut Game<'_>) -> T + Send + 'static,
) -> Option<T> {
let (tx, rx) = sync_channel(1);
self.tasks
.send(Box::new(move |g| {
let _ = tx.send(f(g));
}))
.ok()?;
rx.recv_timeout(Duration::from_secs(10)).ok()
}
/// `IntegratedServer.halt(true)`: returns once the world is saved and let go.
pub fn stop(mut self) {
self.halt();
@@ -72,6 +104,25 @@ impl Drop for Integrated {
}
}
/// The server thread's side of the window's handle (`Game::serving`).
pub(super) struct Serving {
flags: Arc<Flags>,
tasks: Receiver<Task>,
/// The window's profile.
owner: u128,
/// Open to LAN or closed from inside a player's command, while the hub
/// is out of its place: applied after the tick.
pending: Option<Publish>,
}
enum Publish {
Open(TcpListener, LanSettings),
Close,
}
/// What the server thread hands the window once the world is open: its end
/// of the connection and the world's name, or why it failed.
type Ready = std::result::Result<(Pipe, String), String>;
/// The world to open and the player who owns it.
struct Launch {
folder: String,
@@ -79,8 +130,11 @@ struct Launch {
seed: Option<i64>,
creative: bool,
create: Option<WorldOptions>,
/// The window's profile: the only one let in, and the world's player.
/// The window's profile: the only one let in until the world is open to
/// the LAN, and the world's player.
owner: u128,
/// Its name, for the LAN's MOTD.
player: String,
}
/// Whether this world opens on a server thread: asked for, and its player
@@ -92,6 +146,19 @@ pub(super) fn wanted(options: &Options, world: &Path) -> bool {
}
impl Game<'_> {
/// `Minecraft.hasSingleplayerServer`: a world of this window's own, run
/// in the frame or on its server thread.
pub(super) fn has_singleplayer_server(&self) -> bool {
self.remote.is_none() || self.integrated.is_some()
}
/// `IntegratedServer.isPublished`: the world is open to the network.
pub(super) fn is_published(&self) -> bool {
self.lan.is_some()
|| self
.integrated
.as_ref()
.is_some_and(|s| s.published().is_some())
}
/// `Minecraft.doWorldLoad`: start the server thread on the world, wait
/// until it can be joined, then join it through memory.
pub(super) fn open_integrated(
@@ -114,6 +181,7 @@ impl Game<'_> {
create: create.cloned(),
// An offline-mode server names its players by their offline profile.
owner: offline_uuid(&player),
player: player.clone(),
};
let mut options = self.options.clone();
// A server without a console: no local player, no window, no control socket.
@@ -131,6 +199,7 @@ impl Game<'_> {
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
let (ready_tx, ready) = channel();
let (tasks, server_tasks) = channel();
let server_flags = flags.clone();
let thread = std::thread::Builder::new()
.name("Server thread".into())
@@ -141,7 +210,8 @@ impl Game<'_> {
options,
settings,
launch,
&server_flags,
server_flags,
server_tasks,
&ready_tx,
);
if let Err(e) = result {
@@ -149,12 +219,17 @@ impl Game<'_> {
let _ = ready_tx.send(Err(e.to_string()));
}
})?;
let handle = Integrated {
let mut handle = Integrated {
flags,
thread: Some(thread),
tasks,
world_name: String::new(),
};
let pipe = match ready.recv() {
Ok(Ok(pipe)) => pipe,
Ok(Ok((pipe, world_name))) => {
handle.world_name = world_name;
pipe
}
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err("the integrated server stopped".into()),
};
@@ -168,8 +243,9 @@ impl Game<'_> {
fn run_integrated(
&mut self,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<Pipe, String>>,
flags: Arc<Flags>,
tasks: Receiver<Task>,
ready: &Sender<Ready>,
) -> Result<()> {
self.open_world(
&launch.folder,
@@ -182,7 +258,8 @@ impl Game<'_> {
let view_distance = self.settings.render_distance.clamp(2, 32);
let config = HubConfig {
default_game_mode: self.level.mode(),
guest_commands: true,
// Only the owner until it is opened to the LAN.
guest_commands: false,
force_game_mode: false,
hardcore: self.level.hardcore,
view_distance,
@@ -192,23 +269,28 @@ impl Game<'_> {
max_players: MAX_PLAYERS,
// No player of its own: the hub runs without a host.
dedicated: true,
integrated: true,
};
let owner = launch.owner;
let published = flags.clone();
let net = NetConfig {
// No network until it is opened to the LAN.
// No network until it is opened to the LAN; the memory connection
// is not compressed (`Connection.isMemoryConnection`).
listen: false,
// A memory connection is not compressed (`Connection.isMemoryConnection`).
compression_threshold: -1,
enable_status: false,
announce: false,
gate: Some(Arc::new(move |_, uuid, _| {
(uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[]))
(uuid != owner && published.published.load(Ordering::Relaxed) == 0)
.then(|| translatable("multiplayer.disconnect.not_whitelisted", &[]))
})),
..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS)
// IntegratedServer.initServer: the MOTD names the owner and the world.
..NetConfig::lan(
0,
format!("{} - {}", launch.player, self.level.name),
MAX_PLAYERS,
)
};
let settings = LanSettings {
port: 0,
guest_commands: true,
guest_commands: false,
force_game_mode: false,
};
self.lan_host(settings, net, config, None)?;
@@ -227,10 +309,17 @@ impl Game<'_> {
});
host.hub.lan.connect_local()?
};
let _ = ready.send(Ok(pipe));
self.serving = Some(Serving {
flags: flags.clone(),
tasks,
owner,
pending: None,
});
let _ = ready.send(Ok((pipe, self.level.name.clone())));
self.settle_spawn()?;
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.run_tasks();
self.update_dedicated_streaming();
self.update_world();
if flags.paused.load(Ordering::Relaxed) {
@@ -245,6 +334,7 @@ impl Game<'_> {
Ordering::Relaxed,
);
}
self.apply_publish();
let rate = self.clock.rate().max(1.0);
next += Duration::from_secs_f64(1.0 / f64::from(rate));
let now = Instant::now();
@@ -260,6 +350,10 @@ impl Game<'_> {
/// `MinecraftServer.stopServer`: the players are saved and sent away,
/// then the world is saved.
fn stop_integrated(&mut self) -> Result<()> {
// IntegratedServer.stopServer: teardownPublishedState.
if let Some(s) = self.serving.take() {
s.flags.published.store(0, Ordering::Relaxed);
}
if let Some(mut host) = self.lan.take() {
for g in &host.hub.guests {
self.save_guest(&host, g);
@@ -282,18 +376,191 @@ impl Game<'_> {
}
}
/// What the world options screen shows of an integrated server.
#[derive(Clone, Copy, Debug)]
pub(super) struct ServerOptions {
pub default_mode: i32,
/// The owner's own game mode.
pub personal_mode: i32,
pub cheats: bool,
pub difficulty: u8,
pub hardcore: bool,
pub difficulty_locked: bool,
pub port: Option<u16>,
pub guest_commands: bool,
pub force: bool,
}
/// The server thread's side.
impl Game<'_> {
/// Whether this game is an integrated server's.
pub(super) fn serving(&self) -> bool {
self.serving.is_some()
}
/// The window's requests, between two ticks.
fn run_tasks(&mut self) {
let tasks: Vec<Task> = match &self.serving {
Some(s) => s.tasks.try_iter().collect(),
None => return,
};
for task in tasks {
task(self);
self.apply_publish();
}
}
/// `IntegratedServer.getPort` while published.
pub(super) fn published_port(&self) -> Option<u16> {
let s = self.serving.as_ref()?;
Some(s.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0)
}
/// `IntegratedServer.publishServer`: listen on `settings.port` (0 picks
/// one) and announce the world. The socket is bound at once so a busy
/// port fails here; the hub starts listening once it is at hand.
pub(super) fn publish(&mut self, settings: LanSettings) -> std::result::Result<u16, String> {
let Some(s) = self.serving.as_mut() else {
return Err("not an integrated server".into());
};
if s.flags.published.load(Ordering::Relaxed) != 0 {
return Err("already published".into());
}
let listener = Lan::bind(None, settings.port).map_err(|e| e.to_string())?;
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
log::info!("Published LAN server on port {port}");
s.flags.published.store(port, Ordering::Relaxed);
s.pending = Some(Publish::Open(listener, LanSettings { port, ..settings }));
self.apply_publish();
Ok(port)
}
/// `IntegratedServer.unpublishServer`: stop listening and send every
/// player but the owner away. False when it was not published.
pub(super) fn unpublish(&mut self) -> bool {
let Some(s) = self.serving.as_mut() else {
return false;
};
if s.flags.published.swap(0, Ordering::Relaxed) == 0 {
return false;
}
s.pending = Some(Publish::Close);
self.apply_publish();
true
}
/// Publish or unpublish for real, once the hub is in its place (a
/// player's `/publish` runs while it is out).
fn apply_publish(&mut self) {
if self.lan.is_none() {
return;
}
let Some(s) = self.serving.as_mut() else {
return;
};
let (Some(pending), owner) = (s.pending.take(), s.owner) else {
return;
};
let allow_commands = self.allow_commands();
let Some(host) = self.lan.as_mut() else {
return;
};
match pending {
Publish::Open(listener, settings) => {
if let Err(e) = host.hub.lan.listen_on(listener, true) {
log::error!("Horizon: Open to LAN: {e}");
}
host.settings = settings;
host.hub.config.force_game_mode = settings.force_game_mode;
// IntegratedServer.setGuestCommandAccess, then updatePermissions.
host.hub.config.guest_commands = settings.guest_commands && allow_commands;
host.hub.resend_commands();
}
Publish::Close => {
host.hub.lan.stop_listening();
log::info!(
"Unpublishing integrated server (was on port {})",
host.settings.port
);
let others: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| g.uuid != owner)
.map(|g| g.conn)
.collect();
for conn in others {
host.hub.kick(
conn,
translatable("multiplayer.disconnect.server_shutdown", &[]),
);
}
}
}
}
/// The world options screen's state, read on the server.
pub(super) fn server_options(&self) -> ServerOptions {
let owner = self.serving.as_ref().map(|s| s.owner);
let host = self.lan.as_ref();
let personal_mode = host
.and_then(|h| h.hub.guests.iter().find(|g| Some(g.uuid) == owner))
.map_or(self.level.mode(), |g| g.game_mode);
let published = self.published_port();
ServerOptions {
default_mode: self.level.mode(),
personal_mode,
cheats: self.allow_commands(),
difficulty: self.ui.difficulty,
hardcore: self.level.hardcore,
difficulty_locked: self.level.difficulty_locked,
port: published,
guest_commands: published.is_some() && host.is_some_and(|h| h.settings.guest_commands),
force: published.is_none() || host.is_some_and(|h| h.settings.force_game_mode),
}
}
/// `IntegratedServer.setPersonalGameType`: the owner's game mode.
pub(super) fn set_owner_mode(&mut self, mode: i32) {
let Some(owner) = self.serving.as_ref().map(|s| s.owner) else {
return;
};
if let Some(host) = self.lan.as_mut()
&& let Some(conn) = host
.hub
.guests
.iter()
.find(|g| g.uuid == owner)
.map(|g| g.conn)
{
host.hub.set_game_mode(conn, mode);
}
}
/// `IntegratedServer.setWorldAllowCommands`: the owner is an operator
/// while the world allows commands; everyone's level is sent again.
pub(super) fn owner_allow_commands(&mut self, allow: bool) {
let Some(owner) = self.serving.as_ref().map(|s| s.owner) else {
return;
};
let published = self.published_port().is_some();
if let Some(host) = self.lan.as_mut() {
host.hub.ops.insert(owner, if allow { 4 } else { 0 });
if published {
host.hub.config.guest_commands = allow && host.settings.guest_commands;
}
host.hub.resend_commands();
}
}
}
/// The server thread: a game of its own over the shared resources.
#[allow(clippy::too_many_arguments)]
fn serve(
res: &Arc<Resources>,
pack: PackResources,
options: Options,
settings: Settings,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<Pipe, String>>,
flags: Arc<Flags>,
tasks: Receiver<Task>,
ready: &Sender<Ready>,
) -> Result<()> {
let atlas = HudAtlas::build(&options.resources)?;
// It draws nothing: only the font, which books and chat measure with.
let atlas = HudAtlas::fonts(&options.resources)?;
let audio = Audio::silent(&options.resources);
let mut server = Game::new(res, pack, atlas, options, settings, audio)?;
server.run_integrated(launch, flags, ready)
server.run_integrated(launch, flags, tasks, ready)
}
+88 -34
View File
@@ -31,7 +31,7 @@ use std::{
static SYNC: OnceLock<std::result::Result<Arc<SyncData>, String>> = OnceLock::new();
/// The settings of the open world (WorldOptionsScreen's multiplayer section).
#[derive(Clone, Debug)]
#[derive(Clone, Copy, Debug)]
pub struct LanSettings {
pub port: u16,
pub guest_commands: bool,
@@ -316,6 +316,15 @@ impl Game<'_> {
if words[0] != "lan" {
return Ok(None);
}
if let Some(server) = &self.integrated
&& words.get(1) == Some(&"status")
{
// The hub is the server thread's.
let status = server
.call(|g| g.lan_status())
.ok_or("the integrated server stopped")?;
return Ok(Some(status));
}
match words.get(1).copied() {
Some("open") => {
if self.title.is_some() {
@@ -337,43 +346,58 @@ impl Game<'_> {
self.lan_close(true);
Ok(Some(json!({ "ok": true })))
}
Some("status") => Ok(Some(match &self.lan {
Some(h) => json!({
"open": true,
"host": h.host_name,
"port": h.settings.port,
"guests": h.hub.guests.iter().map(|g| json!({
"name": g.name,
"position": g.position,
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
f64::from(g.food),
f64::from(g.saturation),
g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)),
],
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// The armour the host draws on this guest, head to feet.
"model_armor": h.models.get(&g.conn).map(|m| {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
.map(|s| s.as_deref())
}),
})).collect::<Vec<_>>(),
}),
None => json!({ "open": false }),
})),
Some("status") => Ok(Some(self.lan_status())),
_ => Err("lan open|close|status".into()),
}
}
/// `horizon-ctl lan status`.
fn lan_status(&self) -> serde_json::Value {
use serde_json::json;
match &self.lan {
Some(h) if !self.serving() || self.published_port().is_some() => json!({
"open": true,
"host": h.host_name,
"port": h.settings.port,
"guests": h.hub.guests.iter().map(|g| json!({
"name": g.name,
"position": g.position,
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
f64::from(g.food),
f64::from(g.saturation),
g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)),
],
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// The armour the host draws on this guest, head to feet.
"model_armor": h.models.get(&g.conn).map(|m| {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
.map(|s| s.as_deref())
}),
})).collect::<Vec<_>>(),
}),
_ => json!({ "open": false }),
}
}
pub(super) fn lan_open(&mut self, settings: LanSettings) -> Result<()> {
self.lan_start(settings)?;
let port = self.lan.as_ref().map_or(0, |l| l.settings.port);
let port = if let Some(server) = &self.integrated {
// ShareToLanScreen: IntegratedServer.publishServer.
server
.call(move |g| g.publish(settings))
.ok_or("the integrated server stopped")??
} else if self.serving() {
return self.publish(settings).map(drop).map_err(Into::into);
} else {
self.lan_start(settings)?;
self.lan.as_ref().map_or(0, |l| l.settings.port)
};
self.system_message(Text::translate(
"menu.multiplayerOptions.publish.started.lan",
&[Text::literal(port.to_string())],
@@ -408,6 +432,7 @@ impl Game<'_> {
seed: self.level.seed,
max_players: MAX_PLAYERS,
dedicated: false,
integrated: false,
};
let net = NetConfig::lan(settings.port, motd, MAX_PLAYERS);
self.lan_host(settings, net, config, Some(host_uuid))
@@ -484,6 +509,22 @@ impl Game<'_> {
/// IntegratedServer.unpublishServer: the guests are sent away.
pub(super) fn lan_close(&mut self, announce: bool) {
if self.integrated.is_some() || self.serving() {
let closed = match &self.integrated {
Some(server) => server.call(|g| g.unpublish()).unwrap_or(false),
None => self.unpublish(),
};
if closed {
self.friends_lan_closed();
}
if closed && announce && self.integrated.is_some() {
self.system_message(Text::translate(
"menu.multiplayerOptions.publish.stopped",
&[],
));
}
return;
}
self.friends_lan_closed();
let Some(mut host) = self.lan.take() else {
return;
@@ -541,16 +582,29 @@ impl Game<'_> {
/// New command access and game mode forcing settings of the open world.
pub(super) fn lan_apply_settings(&mut self, guest_commands: bool, force: bool) {
if let Some(server) = &self.integrated {
server.call(move |g| g.lan_apply_settings(guest_commands, force));
return;
}
// An integrated server gives guests commands only where the world
// allows them (IntegratedServer.getCustomPermissionLevel).
let effective = guest_commands && (!self.serving() || self.allow_commands());
if let Some(host) = self.lan.as_mut() {
host.settings.guest_commands = guest_commands;
host.settings.force_game_mode = force;
host.hub.config.guest_commands = guest_commands;
host.hub.config.guest_commands = effective;
host.hub.config.force_game_mode = force;
host.hub.resend_commands();
}
}
pub(super) fn lan_port(&self) -> Option<u16> {
if let Some(server) = &self.integrated {
return server.published();
}
if self.serving() {
return self.published_port();
}
self.lan.as_ref().map(|h| h.settings.port)
}
+53 -5
View File
@@ -43,6 +43,8 @@ pub(super) struct GuestPlay {
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
/// The inventory menu and the crafting table the guest crafts in.
pub(super) crafting: super::lan_crafting::GuestCrafting,
/// What the guest's body was given for its effects and enchantments.
potions: super::potions::BodyPotions,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -92,7 +94,11 @@ impl Game<'_> {
let mut play = host.play.remove(&conn).unwrap_or_default();
let g = &mut host.hub.guests[i];
// The guest's body.
let mut motion = g.motion.take()?;
let Some(mut motion) = g.motion.take() else {
host.play.insert(conn, play);
return None;
};
self.potions.swap_player(&mut g.effects, &mut play.potions);
motion.position = Vec3::new(g.position[0], g.position[1], g.position[2]);
motion.ground.on_ground = g.on_ground;
motion.yaw = g.yaw;
@@ -188,6 +194,7 @@ impl Game<'_> {
}
let g = &mut host.hub.guests[i];
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
self.potions.swap_player(&mut g.effects, &mut play.potions);
if let Some(key) = host_ender {
self.world
.block_entities
@@ -669,6 +676,31 @@ impl Game<'_> {
);
return;
}
// An integrated server runs every player's commands at their own
// permission level (`CommandSourceStack.permissions`).
if host.hub.config.integrated {
let Some(level) = host.hub.guest(conn).map(|g| g.permission) else {
return;
};
let command = command.trim_start_matches('/').to_owned();
let lines = self.as_guest(host, conn, |g| {
let console = std::mem::replace(&mut g.ui.registries.permission, level);
g.chat_capture = Some(Vec::new());
g.run_command(&command);
g.ui.registries.permission = console;
g.chat_capture.take().unwrap_or_default()
});
for line in lines.unwrap_or_default() {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
return;
}
// A LAN world follows its Allow Commands; a dedicated server leaves
// it to the ops list (the guest's permission level).
let allowed = self.options.dedicated.is_some() || self.allow_commands();
@@ -759,6 +791,10 @@ impl Game<'_> {
g.saturation = 5.0;
g.sent_health = None;
g.motion = None;
// A new body: nothing given to the old one carries over.
if let Some(play) = host.play.get_mut(&conn) {
play.potions = Default::default();
}
host.hub.respawn(i, spawn);
}
@@ -846,12 +882,17 @@ impl Game<'_> {
g.moves_from_ground
};
if g.spectator() {
// Spectators' effects still run (LivingEntity.baseTick).
if !g.effects.list.is_empty() {
self.as_guest(host, conn, |game| game.tick_mob_effects());
}
return;
}
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position;
let sounds = self.as_guest(host, conn, |game| {
let (rules, health) = (game.world.health_rules, &game.motion.health);
let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health;
let Some(player) = game.player.as_mut() else {
return Vec::new();
};
@@ -889,9 +930,16 @@ impl Game<'_> {
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
let _ = w.player.peaceful_regeneration(rules);
let _ = w.player.food_tick(health, rules);
std::mem::take(&mut w.player.events)
let mut events = std::mem::take(&mut w.player.events);
// LivingEntity.baseTick ends with tickEffects.
game.tick_mob_effects();
let Some(player) = game.player.as_mut() else {
return Vec::new();
};
let _ = player.peaceful_regeneration(rules);
let _ = player.food_tick(health, rules);
events.append(&mut player.events);
events
.into_iter()
.filter_map(|e| match e {
MotionEvent::HurtSound(sound) => Some(sound),
+68 -18
View File
@@ -7,6 +7,7 @@
use super::{
Game, Screen,
game_rules_screen::{Exit, RulesScreen},
integrated::ServerOptions,
lan::LanSettings,
};
use horizon_client::{
@@ -50,7 +51,7 @@ enum View {
Restrictions,
GameRules,
}
#[derive(Clone, PartialEq)]
#[derive(Clone, Copy, PartialEq)]
struct Snapshot {
default_mode: i32,
personal_mode: i32,
@@ -406,28 +407,32 @@ impl Restrictions {
impl Game<'_> {
pub(super) fn open_world_options(&mut self) {
let hint = horizon_client::lan::available_port();
let lan = self.lan.is_some();
let mut port = EditBox::new(0.0, 0.0, 150.0, 20.0);
port.max_length = 5;
let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| {
(h.settings.guest_commands, h.settings.force_game_mode)
});
if let Some(p) = self.lan_port() {
// The world is the server thread's when there is one.
let state = match &self.integrated {
Some(server) => match server.call(|g| g.server_options()) {
Some(state) => state,
None => return,
},
None => self.local_server_options(),
};
if let Some(p) = state.port {
port.set_value(&p.to_string());
}
let mut options = WorldOptions {
default_mode: self.level.mode(),
personal_mode: self.mode_id(),
cheats: self.allow_commands(),
difficulty: self.ui.difficulty,
lan,
default_mode: state.default_mode,
personal_mode: state.personal_mode,
cheats: state.cheats,
difficulty: state.difficulty,
lan: state.port.is_some(),
port,
hint,
guest_commands,
force,
hardcore: self.level.hardcore,
difficulty_locked: self.level.difficulty_locked,
locked: self.level.difficulty_locked || self.level.hardcore,
guest_commands: state.guest_commands,
force: state.force,
hardcore: state.hardcore,
difficulty_locked: state.difficulty_locked,
locked: state.difficulty_locked || state.hardcore,
scroll: 0.0,
view: View::Options,
rules: None,
@@ -808,7 +813,7 @@ impl Game<'_> {
fn apply_and_close_world_options(&mut self, o: WorldOptions) {
let wanted = o.snapshot();
let before = o.initial.clone();
let before = o.initial;
self.world_options = Some(o);
self.apply_world_options(&before, &wanted);
self.close_world_options();
@@ -891,7 +896,47 @@ impl Game<'_> {
}
}
/// The world options of a world run in the frame.
fn local_server_options(&self) -> ServerOptions {
let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| {
(h.settings.guest_commands, h.settings.force_game_mode)
});
ServerOptions {
default_mode: self.level.mode(),
personal_mode: self.mode_id(),
cheats: self.allow_commands(),
difficulty: self.ui.difficulty,
hardcore: self.level.hardcore,
difficulty_locked: self.level.difficulty_locked,
port: self.lan_port(),
guest_commands,
force,
}
}
fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) {
if let Some(server) = &self.integrated {
// The server applies them; the window tells what came of
// Open to LAN (ShareToLanScreen's messages).
let (b, w) = (*before, *wanted);
server.call(move |g| g.apply_world_options(&b, &w));
if w.lan != b.lan || (w.lan && w.port != b.port) {
match (w.lan, self.lan_port()) {
(true, Some(port)) => self.system_message(Text::translate(
"menu.multiplayerOptions.publish.started.lan",
&[Text::literal(port.to_string())],
)),
(true, None) => {
self.system_message(Text::translate("commands.publish.failed", &[]));
}
(false, _) => self.system_message(Text::translate(
"menu.multiplayerOptions.publish.stopped",
&[],
)),
}
}
return;
}
if wanted.difficulty != before.difficulty {
let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3];
self.as_console(|g| g.run_command(&format!("difficulty {name}")));
@@ -904,10 +949,15 @@ impl Game<'_> {
self.set_default_game_mode(wanted.default_mode);
}
if wanted.personal_mode != before.personal_mode {
self.set_mode_id(wanted.personal_mode);
if self.serving() {
self.set_owner_mode(wanted.personal_mode);
} else {
self.set_mode_id(wanted.personal_mode);
}
}
if wanted.cheats != before.cheats {
self.set_allow_commands(wanted.cheats);
self.owner_allow_commands(wanted.cheats);
}
let settings_changed =
wanted.guest_commands != before.guest_commands || wanted.force != before.force;
+4 -8
View File
@@ -186,16 +186,11 @@ impl Game<'_> {
}
/// Mouse buttons pressed while a key is being bound.
pub(super) fn options_waiting_for_key(&self) -> bool {
self.ui.options.selected_key.is_some() && self.ui.options.page() == Page::KeyBinds
self.ui.options.selected_key.is_some()
}
pub(super) fn options_bind_mouse(&mut self, button: MouseButton) -> Result<()> {
if let Some(name) = self.ui.options.selected_key.take() {
self.settings
.keys
.set(name, &horizon_client::keybinds::mouse_name(button));
self.handle_option_events(vec![Event::Changed])?;
}
Ok(())
let events = self.ui.options.bind_mouse(&mut self.settings, button);
self.handle_option_events(events)
}
pub(super) fn handle_option_events(&mut self, events: Vec<Event>) -> Result<()> {
for e in events {
@@ -244,6 +239,7 @@ impl Game<'_> {
let s = &self.settings;
if let Some(r) = self.renderer.as_mut() {
r.gamma = s.gamma;
r.fullbright = s.extras.fullbright;
r.set_present_mode(s.vsync, s.horizon.present_mode);
r.animated_textures = s.horizon.animated_textures;
r.set_mipmap_levels(s.mipmap_levels.max(0) as u32);
+61 -7
View File
@@ -427,7 +427,7 @@ impl Game<'_> {
}
/// `extractEntityInInventoryFollowsMouse`: the player in the box
/// `[x0, x1) x [y0, y1)`, `size` pixels per block, turned toward the
/// cursor; drawn as depth-sorted, back-face-culled quads.
/// cursor; drawn with a depth buffer and back-face culling.
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_player_preview(
&self,
@@ -495,9 +495,9 @@ impl Game<'_> {
let quads = player_preview_quads(verts, gui, fire, &atlas.sprites);
let start = batch.vertices.len();
for (_, p, uv, color) in quads {
batch.quad(p, uv, color);
batch.quad_3d(p, uv, color);
}
batch.clip_since(start, x0, y0, x1, y1);
batch.depth_since(start, [x0, y0, x1, y1]);
}
/// The survival inventory's player box (`InventoryScreen`).
pub(super) fn draw_inventory_player(&self, batch: &mut HudBatch, ox: f32, oy: f32) {
@@ -570,7 +570,7 @@ fn player_preview_quads(
gui: glam::Mat4,
fire: Option<(f32, f32)>,
sprites: &std::collections::HashMap<String, horizon_client::hud::Rect>,
) -> Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> {
) -> Vec<(f32, [[f32; 3]; 4], [[f32; 2]; 4], u32)> {
let flame_start = verts.len();
if let Some((width, height)) = fire {
horizon_client::fire_render::flames(
@@ -584,7 +584,7 @@ fn player_preview_quads(
&mut verts,
);
}
let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
let mut quads: Vec<(f32, [[f32; 3]; 4], [[f32; 2]; 4], u32)> = Vec::new();
for (index, q) in verts.as_chunks::<4>().0.iter().enumerate() {
let p: [glam::Vec3; 4] =
std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos)));
@@ -606,12 +606,12 @@ fn player_preview_quads(
let depth = p.iter().map(|v| v.z).sum::<f32>() / 4.0;
quads.push((
depth,
p.map(|v| [v.x, v.y]),
p.map(|v| v.to_array()),
std::array::from_fn(|i| q[i].uv),
color,
));
}
// Far (low z) first: the viewer is on the +z side.
// Keep far-to-near order for translucent faces; opaque overlap uses depth.
quads.sort_by(|a, b| a.0.total_cmp(&b.0));
quads
}
@@ -619,6 +619,60 @@ fn player_preview_quads(
#[cfg(test)]
mod preview_tests {
use super::*;
#[test]
fn preview_keeps_crossing_faces_depth_and_clips_without_dropping_faces() {
use horizon_client::{
hud::{Blend, HudBatch},
mesher::Vertex,
};
let face = |z: [f32; 4]| {
[[-2.0, -1.0], [-2.0, 1.0], [2.0, 1.0], [2.0, -1.0]]
.into_iter()
.zip(z)
.map(|([x, y], z)| Vertex {
pos: [x, y, z],
uv: [0.0; 2],
layer: 0,
color: u32::MAX,
light: 0,
normal: [0; 4],
})
};
// A shield and arm can intersect: neither average depth orders both ends.
let verts = face([1.0, 1.0, -1.0, -1.0]).chain(face([0.0; 4])).collect();
let quads = player_preview_quads(verts, glam::Mat4::IDENTITY, None, &Default::default());
assert_eq!(quads.len(), 2);
let mut batch = HudBatch::new([320, 240]);
for (_, p, uv, color) in quads {
batch.quad_3d(p, uv, color);
}
// Its centre is outside this scissor; the visible part must still be drawn.
batch.depth_since(0, [1.0, 0.0, 2.0, 1.0]);
assert_eq!(batch.vertices.len(), 12);
let shield = &batch.vertices[..6];
let arm = &batch.vertices[6..];
assert!(shield[0].depth < arm[0].depth);
assert!(shield[2].depth > arm[2].depth);
assert_eq!(batch.runs(), vec![(0..12, Blend::Depth([1, 0, 1, 1]))]);
}
#[test]
#[ignore = "requires prepared model data in HORIZON_TEST_RESOURCES"]
fn player_render_transform_uses_vanilla_avatar_scale() {
let root = std::path::PathBuf::from(
std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"),
);
let mut m = Mob::new(1, player_type(&root).unwrap(), Vec3::ZERO, 0.0);
for (id, expected) in [("minecraft:player", 0.9375), ("minecraft:zombie", 1.0)] {
Arc::make_mut(&mut m.kind).id = id.into();
let transform =
horizon_client::mobs::render::base_transform_at(&m, 1.0, glam::Mat4::IDENTITY);
for axis in [glam::Vec3::X, glam::Vec3::Y, glam::Vec3::Z] {
assert!((transform.transform_vector3(axis).length() - expected).abs() < 1e-6);
}
}
}
#[test]
fn burning_inventory_preview_keeps_visible_fullbright_flames() {
let rect = |u0| horizon_client::hud::Rect {
+40 -9
View File
@@ -49,6 +49,14 @@ impl Game<'_> {
});
}
}
/// What a player's body was last given for its effects and enchantments:
/// a guest keeps their own while the host's are in `PotionState`.
#[derive(Default)]
pub(super) struct BodyPotions {
applied: Vec<(&'static str, &'static str, f64, &'static str)>,
protection_for: Option<Vec<Option<ItemStack>>>,
enchant_modifiers: Vec<(String, String, f64, String)>,
}
/// Effects, thrown potions and the attribute modifiers last applied.
#[derive(Default)]
pub(super) struct PotionState {
@@ -63,6 +71,14 @@ pub(super) struct PotionState {
}
impl PotionState {
/// Trade the player's own state (effects and what their body was given)
/// with a guest's, around `as_guest`. Potions in flight stay.
pub(super) fn swap_player(&mut self, effects: &mut PlayerEffects, body: &mut BodyPotions) {
std::mem::swap(&mut self.effects, effects);
std::mem::swap(&mut self.applied, &mut body.applied);
std::mem::swap(&mut self.protection_for, &mut body.protection_for);
std::mem::swap(&mut self.enchant_modifiers, &mut body.enchant_modifiers);
}
/// Thrown potions in flight as (entity type, position, motion), for the
/// dispenser parity fixture.
pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> {
@@ -274,8 +290,16 @@ impl Game<'_> {
}
}
}
/// `LivingEntity.tickEffects`, attribute modifiers and the status flags.
/// The local player's effects (`tick_mob_effects`), then the potions
/// in flight, which a server without a local player still has.
pub(super) fn tick_effects(&mut self) {
self.tick_mob_effects();
self.tick_thrown_potions();
}
/// `LivingEntity.tickEffects` (server side) for `self.player`, the local
/// player or a guest acting (`as_guest`), then its attribute modifiers
/// and status flags.
pub(super) fn tick_mob_effects(&mut self) {
let Some(player) = self.player.as_ref() else {
return;
};
@@ -294,6 +318,20 @@ impl Game<'_> {
for action in actions {
self.apply_effect_action(action);
}
self.apply_effect_status();
}
/// A client's own effects (`LivingEntity.tickEffects` on the client,
/// `MobEffectInstance.tickClient`): they count down, and the server
/// removes them. Their modifiers and flags move the predicted player.
pub(super) fn tick_client_effects(&mut self) {
for e in &mut self.potions.effects.list {
e.tick_client();
}
self.apply_effect_status();
}
/// The effects' attribute modifiers, armor protection and status flags
/// on `self.player`.
fn apply_effect_status(&mut self) {
let modifiers = self.potions.effects.modifiers();
if modifiers != self.potions.applied
&& let Some(p) = self.player.as_mut()
@@ -346,7 +384,6 @@ impl Game<'_> {
status.protection = std::mem::take(&mut p.status.protection);
p.status = status;
}
self.tick_thrown_potions();
}
fn tick_thrown_potions(&mut self) {
let mut thrown = std::mem::take(&mut self.potions.thrown);
@@ -606,13 +643,7 @@ impl Game<'_> {
/// Effects saved in level.dat (`Player.active_effects`).
pub(super) fn restore_effects(&mut self) {
self.potions = PotionState::default();
for (id, duration, amplifier, ambient, _) in self.level.active_effects.clone() {
if let Some(def) = brewing::effect(&id) {
let mut e = EffectInstance::new(def.id, duration, amplifier);
e.ambient = ambient;
self.potions.effects.add(e);
}
}
self.potions.effects = PlayerEffects::from_saved(&self.level.active_effects);
}
pub(super) fn effects_json(&self) -> serde_json::Value {
serde_json::json!({
+45 -1
View File
@@ -382,6 +382,31 @@ impl Game<'_> {
.unwrap_or("minecraft:air"),
)
}
/// A mob effect's network id as the effect (`brewing::EFFECTS` id).
fn remote_effect_id(&self, effect: i32) -> Option<&'static str> {
let r = self.remote.as_ref()?;
let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?;
horizon_client::brewing::effect(name).map(|d| d.id)
}
/// ClientPacketListener.handleUpdateMobEffect for the player itself
/// (`LivingEntity.forceAddEffect`): the effect replaces any of its kind.
/// Other entities' effects are not shown.
fn remote_effect(&mut self, p: &play::UpdateMobEffect) {
if !self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) {
return;
}
let Some(id) = self.remote_effect_id(p.effect) else {
return;
};
let mut e = horizon_client::effects::EffectInstance::new(id, p.duration, p.amplifier);
e.ambient = p.flags & 1 != 0;
e.visible = p.flags & 2 != 0;
let list = &mut self.potions.effects.list;
match list.iter_mut().find(|x| x.id == id) {
Some(existing) => *existing = e,
None => list.push(e),
}
}
fn item_id(&self, name: &str) -> i32 {
let r = self.remote.as_ref().expect("remote");
r.builtin
@@ -417,7 +442,7 @@ impl Game<'_> {
}
Some(stack)
}
fn chat_line(&mut self, text: String) {
pub(super) fn chat_line(&mut self, text: String) {
log::info!("[chat] {text}");
if let Some(r) = self.remote.as_mut() {
r.chat.push((text, Instant::now()));
@@ -827,6 +852,8 @@ impl Game<'_> {
));
}
C::Respawn(p) => {
// A new player, without effects: the server sends them again.
self.potions.effects.clear();
self.enter_remote_dimension(&p.spawn, true);
self.screen = Screen::Playing;
if let Some(r) = self.remote.as_mut() {
@@ -1127,6 +1154,14 @@ impl Game<'_> {
}
}
C::EntityEvent(p) => {
// EntityEvent.PERMISSION_LEVEL_ALL..OWNERS (24..=28) for this
// player: LocalPlayer.setPermissionLevel, which the commands
// the chat offers and checks follow.
if (24..=28).contains(&p.event)
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
{
self.ui.registries.permission = (p.event - 24) as u8;
}
if p.event == 1
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Rabbit
@@ -1141,6 +1176,14 @@ impl Game<'_> {
}
}
C::Animate(p) if p.action == 0 => {}
C::UpdateMobEffect(p) => self.remote_effect(&p),
C::RemoveMobEffect(p) => {
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
&& let Some(id) = self.remote_effect_id(p.effect)
{
self.potions.effects.list.retain(|e| e.id != id);
}
}
C::SetHealth(p) => {
if let Some(r) = self.remote.as_mut() {
r.health = (p.health, p.food, p.saturation);
@@ -1810,6 +1853,7 @@ impl Game<'_> {
self.tick_block_entity_anims();
self.tick_hand();
self.tick_particles();
self.tick_client_effects();
let ghast_collisions = self.happy_ghast_player_collisions();
let Some(player) = self.player.as_mut() else {
return Ok(());
+7 -10
View File
@@ -60,17 +60,14 @@ impl Game<'_> {
&& horizon_client::ui_theme::horizon()
}
fn pause_labels(&self) -> (String, &'static str) {
let world = if self.remote.is_some() {
"Multiplayer".to_owned()
if let Some(server) = &self.integrated {
return (server.world_name.clone(), "Save and quit");
}
if self.remote.is_some() {
("Multiplayer".to_owned(), "Disconnect")
} else {
self.level.name.clone()
};
let quit = if self.remote.is_some() {
"Disconnect"
} else {
"Save and quit"
};
(world, quit)
(self.level.name.clone(), "Save and quit")
}
}
pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) {
if horizon_client::ui_theme::horizon() {
+77 -6
View File
@@ -6,6 +6,7 @@
use super::{Game, GameLevel, Screen, dispenser::new_item_motion, storage::is_shulker_box};
use horizon_client::{
containers::{Banner, BlockEntity},
item_data,
items::ItemStack,
};
use horizon_core::position::BlockPos;
@@ -15,6 +16,7 @@ use horizon_world::{
LevelEvent,
removal::{self, PreRemove},
},
nbt::{JavaString, Tag},
registry::BlockStateId,
};
use std::collections::HashMap;
@@ -80,14 +82,37 @@ impl Pending {
stack.data_mut().pot_decorations = Some(Box::new(sides));
}
if stack.item.ends_with("_banner")
&& let Some(Banner { layers, name }) = self.banner.remove(&pos)
&& let Some(Banner {
layers,
name,
components,
}) = self.banner.remove(&pos)
{
let data = stack.data_mut();
data.banner_patterns = layers;
if name.is_some() {
data.custom_name = name;
let mut patch = match item_data::encode_components(stack) {
Some(Tag::Compound(c)) => c,
_ => Default::default(),
};
// The remaining components in the banner loot table's copy_components.
for key in [
"minecraft:item_name",
"minecraft:rarity",
"minecraft:tooltip_display",
] {
if let Some(value) = components.get(&JavaString::from(key)) {
patch.insert(key.into(), value.clone());
}
}
stack.tidy();
patch.insert(
"minecraft:banner_patterns".into(),
horizon_client::banner::layers_to_nbt(&layers),
);
if let Some(name) = name {
patch.insert(
"minecraft:custom_name".into(),
Tag::String(name.as_str().into()),
);
}
(stack.damage, stack.extra) = item_data::decode_components(Some(&Tag::Compound(patch)));
}
}
/// Remember a decorated pot's sherds from its saved block entity.
@@ -553,3 +578,49 @@ impl Game<'_> {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_client::{block_entity_item, item_data, mobs::raider, save};
use horizon_world::nbt::Tag;
#[test]
fn ominous_banner_survives_placement_save_and_drop() {
let original = raider::ominous_banner();
let Tag::Compound(components) = item_data::encode_components(&original).unwrap() else {
panic!("banner components");
};
for block in ["minecraft:white_banner", "minecraft:white_wall_banner"] {
let pos = (1, 64, 2);
let fresh = BlockEntity::for_block(block).unwrap();
let fresh = save::encode_block_entity(pos, &fresh, block);
let placed = block_entity_item::place(&fresh, &components, false);
let (_, placed) = save::decode_block_entity(&placed).unwrap();
let saved = save::encode_block_entity(pos, &placed, block);
let (_, loaded) = save::decode_block_entity(&saved).unwrap();
let BlockEntity::Banner(banner) = &loaded else {
panic!("placed banner");
};
assert_eq!(banner.layers.len(), item_data::OMINOUS_LAYERS.len());
let mut pending = Pending::default();
pending.record([pos.0, pos.1, pos.2], &loaded, block, None);
let mut dropped = ItemStack::new("minecraft:white_banner", 1);
pending.attach([pos.0, pos.1, pos.2], &mut dropped);
assert!(dropped.data().unwrap().ominous_banner);
assert!(horizon_client::banner::tooltip_layers(&dropped).is_empty());
assert_eq!(
horizon_client::item_tooltip::name_line(&dropped, &|_| None),
"Ominous Banner"
);
assert_eq!(
horizon_client::item_tooltip::rarity(&dropped, "common"),
"uncommon"
);
assert_eq!(
item_data::encode_components(&dropped),
Some(Tag::Compound(components.clone()))
);
}
}
}
+5 -13
View File
@@ -1860,18 +1860,10 @@ impl Game<'_> {
pub(super) fn stack_tooltip(&self, stack: &ItemStack) -> Vec<(String, u32)> {
let e: &Enchantments = &self.res.stations.enchantments;
let props = e.props(&stack.item);
let mut rarity = props.map_or("common", |p| p.rarity.as_str());
// The ominous banner's rarity component.
if stack.data().is_some_and(|d| d.ominous_banner) {
rarity = "uncommon";
}
if !stack.enchantments().is_empty() {
rarity = match rarity {
"common" | "uncommon" => "rare",
"rare" => "epic",
r => r,
};
}
let rarity = horizon_client::item_tooltip::rarity(
stack,
props.map_or("common", |p| p.rarity.as_str()),
);
let color = match rarity {
"uncommon" => rgba(255, 255, 85, 255),
"rare" => rgba(85, 255, 255, 255),
@@ -1952,7 +1944,7 @@ impl Game<'_> {
));
}
// BannerPatternLayers.addToTooltip: up to six layer names.
for layer in horizon_client::banner::layers(stack).iter().take(6) {
for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) {
let key = self.res.stations.banners.layer_key(layer);
lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255)));
}
+7 -14
View File
@@ -6,6 +6,7 @@ use horizon_client::{
hud::HudBatch,
hud_layout,
hud_overlays::HeldName,
item_tooltip,
text::{self, Text},
};
@@ -24,22 +25,14 @@ impl Game<'_> {
fn held_name(&self) -> Option<HeldName> {
let stack = self.inventory.get(self.selected)?.as_ref()?;
let custom = stack.custom_name();
// ItemStack.getRarity: enchanting raises common and uncommon to rare
// and rare to epic.
let mut rarity = self.item_rarity(&stack.item);
if !stack.enchantments().is_empty() {
rarity = match rarity.as_str() {
"common" | "uncommon" => "rare".into(),
"rare" => "epic".into(),
_ => rarity,
};
}
let default_rarity = self.item_rarity(&stack.item);
let rarity = item_tooltip::rarity(stack, &default_rarity);
Some(HeldName {
item: stack.item.to_string(),
hover_name: Text::literal(
custom.map_or_else(|| self.pack.names.item(&stack.item), str::to_owned),
),
rarity_color: match rarity.as_str() {
hover_name: Text::literal(item_tooltip::name_line(stack, &|key| {
self.pack.names.get(key).map(str::to_owned)
})),
rarity_color: match rarity {
"uncommon" => text::YELLOW,
"rare" => text::AQUA,
"epic" => text::LIGHT_PURPLE,
+8 -2
View File
@@ -28,7 +28,7 @@ use horizon_client::{
menu::Input,
stations::hover_name,
};
use winit::keyboard::KeyCode;
use winit::{event::MouseButton, keyboard::KeyCode};
/// A sort button's side in GUI pixels.
const SORT_BUTTON: f32 = 9.0;
@@ -377,8 +377,14 @@ impl Game<'_> {
/// The sort key: sorts the part under the cursor (the container when
/// the cursor is over no slot).
pub(super) fn sort_key_press(&mut self, key: KeyCode) -> bool {
keybinds::key_name(key).is_some_and(|name| self.sort_input(name))
}
pub(super) fn sort_mouse_press(&mut self, button: MouseButton) -> bool {
self.sort_input(&keybinds::mouse_name(button))
}
fn sort_input(&mut self, name: &str) -> bool {
let e = &self.settings.extras;
if !e.sort || keybinds::key_code(&e.sort_key) != Some(key) || self.recipe_search_focused() {
if !e.sort || e.sort_key != name || self.recipe_search_focused() {
return false;
}
let buttons = self.sort_buttons();
+8 -1
View File
@@ -348,6 +348,8 @@ pub struct Renderer {
pub screenshot_result: Option<std::result::Result<[u32; 2], String>>,
/// Brightness option (lightmap gamma), 0..1.
pub gamma: f32,
/// Optional full-light lightmap (Horizon Extras).
pub fullbright: bool,
/// Advance animated block textures (Horizon setting; vanilla always does).
pub animated_textures: bool,
present_modes: Vec<wgpu::PresentMode>,
@@ -1616,6 +1618,7 @@ impl Renderer {
screenshot: None,
screenshot_result: None,
gamma: 0.5,
fullbright: false,
animated_textures: true,
present_modes,
})
@@ -1972,6 +1975,9 @@ impl Renderer {
pixels[i + 3] = 255;
}
}
if self.fullbright {
pixels.fill(255);
}
// The lightmap changes with the time of day, flicker and effects,
// not every frame: upload only what differs from the texture.
if pixels == self.lightmap_pixels && self.lightmap_uploaded {
@@ -2217,7 +2223,7 @@ impl Renderer {
visible.clear();
self.sections.visible(
camera,
frame.distance,
(frame.distance / 16.0) as i32,
&view,
|k| !culling || reachable.contains(k),
&mut visible,
@@ -2776,6 +2782,7 @@ impl Renderer {
&mut self.uploads,
&mut encoder,
&view_target,
&self.depth,
frame.hud,
[self.config.width, self.config.height],
);
+30 -28
View File
@@ -3,7 +3,7 @@
//! the render distance rejects all of its sections with one test, and the
//! sections that remain are reached by index rather than by hashing keys.
use super::{Frustum, SectionKey};
use crate::fast_hash::FxHashMap;
use crate::{fast_hash::FxHashMap, streaming::in_view_distance};
use glam::{DVec3, Vec3};
/// One chunk column's resident sections.
@@ -149,26 +149,28 @@ fn origin(key: SectionKey, camera: DVec3) -> DVec3 {
) - camera
}
/// Whether the section at `key` is drawn: within `distance` blocks of the
/// camera horizontally (plus a section and a half), and partly inside the
/// frustum. `None` when it is not, else its squared centre distance and origin.
fn in_view(
key: SectionKey,
camera: DVec3,
distance: f32,
frustum: &Frustum,
) -> Option<(f64, Vec3)> {
let origin = origin(key, camera);
let center = origin + DVec3::splat(8.0);
let horizontal = (center.x * center.x + center.z * center.z).sqrt();
if horizontal > f64::from(distance) + 24.0 {
/// The camera's chunk column.
fn camera_column(camera: DVec3) -> (i32, i32) {
(
(camera.x.floor() as i32) >> 4,
(camera.z.floor() as i32) >> 4,
)
}
/// Whether the section at `key` is drawn: its column within the render
/// distance of the camera's (`SectionOcclusionGraph.isInViewDistance`), and
/// partly inside the frustum. `None` when it is not, else its squared centre
/// distance and origin.
fn in_view(key: SectionKey, camera: DVec3, radius: i32, frustum: &Frustum) -> Option<(f64, Vec3)> {
if !in_view_distance(camera_column(camera), radius, key.0, key.2) {
return None;
}
let origin = origin(key, camera);
let min = origin.as_vec3();
if !frustum.intersects(min, min + Vec3::splat(16.0)) {
return None;
}
Some((center.length_squared(), min))
Some(((origin + DVec3::splat(8.0)).length_squared(), min))
}
impl<T> Resident<T> {
@@ -178,22 +180,22 @@ impl<T> Resident<T> {
/// Columns are tested first, with the same distance test (it depends
/// only on x and z) and a box spanning their sections: every section box
/// lies inside it and the frustum test rounds monotonically, so a column
/// the frustum rejects holds no section it would accept.
/// the frustum rejects holds no section it would accept. `radius` is the
/// render distance in chunks.
pub fn visible(
&self,
camera: DVec3,
distance: f32,
radius: i32,
frustum: &Frustum,
reachable: impl Fn(SectionKey) -> bool,
out: &mut Vec<Visible>,
) {
let from = camera_column(camera);
for column in &self.columns {
let low = origin((column.x, column.low, column.z), camera);
let center = low + DVec3::splat(8.0);
if (center.x * center.x + center.z * center.z).sqrt() > f64::from(distance) + 24.0 {
if !in_view_distance(from, radius, column.x, column.z) {
continue;
}
let min = low.as_vec3();
let min = origin((column.x, column.low, column.z), camera).as_vec3();
let top = origin((column.x, column.high, column.z), camera).as_vec3();
if !frustum.intersects(min, top + Vec3::splat(16.0)) {
continue;
@@ -203,7 +205,7 @@ impl<T> Resident<T> {
if !reachable(key) {
continue;
}
if let Some((d, o)) = in_view(key, camera, distance, frustum) {
if let Some((d, o)) = in_view(key, camera, radius, frustum) {
out.push(Visible {
distance: d.to_bits(),
key,
@@ -243,20 +245,20 @@ mod tests {
(DVec3::new(8.0, 64.0, 8.0), 45.0, 89.0),
];
for (camera, yaw, pitch) in cameras {
for distance in [32.0, 96.0, 160.0] {
for radius in [2, 6, 10] {
let projection = super::super::world_projection(70.0, 16.0 / 9.0, 512.0);
let view = crate::camera::view_matrix(yaw, pitch);
let frustum = Frustum {
planes: super::super::frustum(projection * view),
};
let mut fast = Vec::new();
r.visible(camera, distance, &frustum, reachable, &mut fast);
r.visible(camera, radius, &frustum, reachable, &mut fast);
let mut slow: Vec<(SectionKey, f64, [f32; 3])> = r
.items
.iter()
.filter(|(k, _)| reachable(*k))
.filter_map(|(k, _)| {
in_view(*k, camera, distance, &frustum).map(|(d, o)| (*k, d, o.to_array()))
in_view(*k, camera, radius, &frustum).map(|(d, o)| (*k, d, o.to_array()))
})
.collect();
slow.sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
@@ -268,7 +270,7 @@ mod tests {
})
.collect();
assert!(!slow.is_empty());
assert_eq!(fast, slow, "{camera} {yaw} {pitch} {distance}");
assert_eq!(fast, slow, "{camera} {yaw} {pitch} {radius}");
}
}
}
@@ -356,7 +358,7 @@ mod tests {
let t = Instant::now();
keys.clear();
keys.extend(map.keys().filter_map(|&k| {
in_view(k, camera, 512.0, &frustum).map(|(d, o)| (k, d, o.to_array()))
in_view(k, camera, 32, &frustum).map(|(d, o)| (k, d, o.to_array()))
}));
keys.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
for (k, _, _) in &keys {
@@ -365,7 +367,7 @@ mod tests {
old = old.min(t.elapsed());
let t = Instant::now();
list.clear();
r.visible(camera, 512.0, &frustum, |_| true, &mut list);
r.visible(camera, 32, &frustum, |_| true, &mut list);
for v in &list {
sum += i64::from(r.get(v.slot)[1] + r.get(v.slot)[0]);
}
+254 -61
View File
@@ -139,19 +139,74 @@ impl HudAtlas {
(g.rect, g.advance)
}
pub fn build(root: &Path) -> Result<Self> {
Self::pack(
root,
&[
"gui",
"item",
"block",
"font",
"environment",
"misc",
"painting",
"entity",
"particle",
"mob_effect",
"map",
],
true,
)
}
/// Empty slots written at run time: map textures (game/maps.rs), the
/// minimap, downloaded skins, world icons and the Horizon menu text.
fn slots(images: &mut Vec<PackedImage>) {
for i in 0..MAP_SLOTS {
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
}
// The minimap extra's image (game/extras.rs).
images.push((
MINIMAP_SPRITE.into(),
crate::minimap::SIZE as u32,
crate::minimap::SIZE as u32,
vec![0; crate::minimap::SIZE * crate::minimap::SIZE * 4],
));
// Downloaded skins (game/scoreboard.rs).
for i in 0..SKIN_SLOTS {
images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4]));
}
for i in 0..WORLD_ICON_SLOTS {
images.push((
format!("horizon/world-icon{i}"),
64,
64,
vec![0; 64 * 64 * 4],
));
}
// Horizon-style menu text and corner masks (ui_theme), rasterized at run time.
images.push((
"horizon/ui-text".into(),
2048,
1024,
vec![0; 2048 * 1024 * 4],
));
}
/// Only the font's metrics, for a game that draws nothing (the
/// integrated server): text measures as with the full atlas, without
/// holding its textures. The pixels are dropped once the glyph widths are
/// read, since nothing uploads them.
pub fn fonts(root: &Path) -> Result<Self> {
let mut atlas = Self::pack(root, &["font"], false)?;
atlas.pixels = Vec::new();
Ok(atlas)
}
/// Pack the textures under these folders of `textures/`, and for the
/// `full` atlas the generated sprites and the run-time slots too.
fn pack(root: &Path, folders: &[&str], full: bool) -> Result<Self> {
let textures = root.join("assets/minecraft/textures");
let mut files = Vec::new();
walk(&textures.join("gui"), &mut files);
walk(&textures.join("item"), &mut files);
walk(&textures.join("block"), &mut files);
walk(&textures.join("font"), &mut files);
walk(&textures.join("environment"), &mut files);
walk(&textures.join("misc"), &mut files);
walk(&textures.join("painting"), &mut files);
walk(&textures.join("entity"), &mut files);
walk(&textures.join("particle"), &mut files);
walk(&textures.join("mob_effect"), &mut files);
walk(&textures.join("map"), &mut files);
for folder in folders {
walk(&textures.join(folder), &mut files);
}
files.retain(|p| {
let s = p.to_string_lossy();
!s.contains("title/background") && !s.contains("realms") && !s.contains("presets")
@@ -187,7 +242,9 @@ impl HudAtlas {
.flat_map(|h| h.join().unwrap_or_default())
.collect()
});
images.extend(atlas_sprites(root, &images));
if full {
images.extend(atlas_sprites(root, &images));
}
// The title screen's "JAVA EDITION" banner reads "RUST EDITION".
if let Some(edition) = images
.iter_mut()
@@ -198,36 +255,9 @@ impl HudAtlas {
edition.3 = pixels;
}
images.push(("horizon/white".into(), 4, 4, vec![255; 64]));
// Map textures (game/maps.rs) are written into these slots at run time.
for i in 0..MAP_SLOTS {
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
if full {
Self::slots(&mut images);
}
// The minimap extra's image (game/extras.rs).
images.push((
MINIMAP_SPRITE.into(),
crate::minimap::SIZE as u32,
crate::minimap::SIZE as u32,
vec![0; crate::minimap::SIZE * crate::minimap::SIZE * 4],
));
// Downloaded skins (game/scoreboard.rs) likewise.
for i in 0..SKIN_SLOTS {
images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4]));
}
for i in 0..WORLD_ICON_SLOTS {
images.push((
format!("horizon/world-icon{i}"),
64,
64,
vec![0; 64 * 64 * 4],
));
}
// Horizon-style menu text and corner masks (ui_theme), rasterized at run time.
images.push((
"horizon/ui-text".into(),
2048,
1024,
vec![0; 2048 * 1024 * 4],
));
images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1)));
let width = 4096u32;
let mut placements = Vec::with_capacity(images.len());
@@ -319,6 +349,7 @@ pub struct HudVertex {
pub pos: [f32; 2],
pub uv: [f32; 2],
pub color: u32,
pub depth: f32,
}
/// The GUI Scale option (0 = auto).
pub static GUI_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
@@ -330,10 +361,10 @@ pub struct HudBatch {
pub height: f32,
/// Glyph pixels to upload into the atlas before drawing.
pub patches: Vec<crate::font::Patch>,
/// Vertex ranges drawn with another blend than alpha blending, in order.
/// Vertex ranges with another blend or depth/scissor state, in order.
pub blends: Vec<(std::ops::Range<u32>, Blend)>,
}
/// How a run of HUD vertices blends with what is under it.
/// How a run of HUD vertices blends and tests depth.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Blend {
/// `BlendFunction.TRANSLUCENT`.
@@ -342,6 +373,8 @@ pub enum Blend {
Invert,
/// `BlendFunction.ADDITIVE` (`RenderPipelines.GUI_TEXT_HIGHLIGHT`).
Additive,
/// Alpha blending with an isolated depth buffer and a pixel scissor.
Depth([u32; 4]),
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
@@ -430,9 +463,44 @@ impl HudBatch {
pos: p[i],
uv: uv[i],
color,
depth: 0.0,
});
}
}
pub fn quad_3d(&mut self, p: [[f32; 3]; 4], uv: [[f32; 2]; 4], color: u32) {
for i in [0, 1, 2, 0, 2, 3] {
self.vertices.push(HudVertex {
pos: [p[i][0], p[i][1]],
uv: uv[i],
color,
depth: p[i][2],
});
}
}
/// Keep per-vertex depth for an orthographic GUI model, with +z toward the viewer.
pub fn depth_since(&mut self, start: usize, clip: [f32; 4]) {
let vertices = &mut self.vertices[start..];
if vertices.is_empty() {
return;
}
let min = vertices
.iter()
.map(|v| v.depth)
.fold(f32::INFINITY, f32::min);
let max = vertices
.iter()
.map(|v| v.depth)
.fold(f32::NEG_INFINITY, f32::max);
for v in vertices {
v.depth = (max - v.depth) / (max - min).max(f32::EPSILON);
}
let [x0, y0, x1, y1] = clip.map(|v| (v * self.scale).max(0.0) as u32);
// Separate previews clear depth independently, even if their scissors match.
self.blends.push((
start as u32..self.vertices.len() as u32,
Blend::Depth([x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0)]),
));
}
pub fn rect_uv(&mut self, x: f32, y: f32, w: f32, h: f32, r: Rect, color: u32) {
self.quad(
[[x, y], [x + w, y], [x + w, y + h], [x, y + h]],
@@ -569,6 +637,7 @@ impl HudBatch {
pos: p[i],
uv,
color: c[i],
depth: 0.0,
});
}
}
@@ -729,6 +798,7 @@ pub struct HudRenderer {
/// `RenderPipelines.CROSSHAIR`.
invert_pipeline: wgpu::RenderPipeline,
additive_pipeline: wgpu::RenderPipeline,
depth_pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
buffer: wgpu::Buffer,
@@ -808,8 +878,8 @@ impl HudRenderer {
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4];
let create = |label, blend, fragment_entry| {
let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4,3=>Float32];
let create = |label, blend, fragment_entry, depth: bool| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
@@ -824,7 +894,13 @@ impl HudRenderer {
})],
},
primitive: Default::default(),
depth_stencil: None,
depth_stencil: depth.then_some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
@@ -840,7 +916,13 @@ impl HudRenderer {
cache: None,
})
};
let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main");
let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main", false);
let depth_pipeline = create(
"HUD model",
wgpu::BlendState::ALPHA_BLENDING,
"fs_main",
true,
);
// BlendFunction.INVERT: ONE_MINUS_DST_COLOR, ONE_MINUS_SRC_COLOR,
// ONE, ZERO.
let invert_pipeline = create(
@@ -858,6 +940,7 @@ impl HudRenderer {
},
},
"fs_crosshair",
false,
);
// BlendFunction.ADDITIVE: ONE, ONE.
let add = wgpu::BlendComponent {
@@ -872,6 +955,7 @@ impl HudRenderer {
alpha: add,
},
"fs_main",
false,
);
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
@@ -886,6 +970,7 @@ impl HudRenderer {
pipeline,
invert_pipeline,
additive_pipeline,
depth_pipeline,
group,
uniform,
buffer,
@@ -935,6 +1020,7 @@ impl HudRenderer {
uploads: &mut crate::gfx::upload::Uploads,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
depth: &wgpu::TextureView,
batch: &HudBatch,
size: [u32; 2],
) {
@@ -965,7 +1051,7 @@ impl HudRenderer {
);
}
}
if batch.vertices.is_empty() {
if batch.vertices.is_empty() || size.contains(&0) {
return;
}
let count = batch.vertices.len() as u64;
@@ -1001,20 +1087,55 @@ impl HudRenderer {
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HUD"),
color_attachments: &attachments,
..Default::default()
});
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.buffer.slice(..));
for (range, blend) in batch.runs() {
pass.set_pipeline(match blend {
Blend::Alpha => &self.pipeline,
Blend::Invert => &self.invert_pipeline,
Blend::Additive => &self.additive_pipeline,
let runs = batch.runs();
let mut at = 0;
while at < runs.len() {
let clip = match runs[at].1 {
Blend::Depth(clip) => Some(clip),
_ => None,
};
let end = if clip.is_some() {
at + 1
} else {
runs[at..]
.iter()
.position(|(_, b)| matches!(b, Blend::Depth(_)))
.map_or(runs.len(), |n| at + n)
};
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HUD"),
color_attachments: &attachments,
depth_stencil_attachment: clip.map(|_| wgpu::RenderPassDepthStencilAttachment {
view: depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Discard,
}),
stencil_ops: None,
}),
..Default::default()
});
pass.draw(range, 0..1);
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.buffer.slice(..));
if let Some([x, y, w, h]) = clip {
let (x, y) = (x.min(size[0]), y.min(size[1]));
let (w, h) = (w.min(size[0] - x), h.min(size[1] - y));
if w == 0 || h == 0 {
at = end;
continue;
}
pass.set_scissor_rect(x, y, w, h);
}
for (range, blend) in &runs[at..end] {
pass.set_pipeline(match blend {
Blend::Alpha => &self.pipeline,
Blend::Invert => &self.invert_pipeline,
Blend::Additive => &self.additive_pipeline,
Blend::Depth(_) => &self.depth_pipeline,
});
pass.draw(range.clone(), 0..1);
}
at = end;
}
}
}
@@ -1023,6 +1144,43 @@ impl HudRenderer {
mod tests {
use super::*;
#[test]
fn the_fonts_only_atlas_measures_text_like_the_full_one() {
// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide.
let root = std::env::temp_dir().join(format!("horizon-fonts-atlas-{}", std::process::id()));
let font = root.join("assets/minecraft/font");
let textures = root.join("assets/minecraft/textures/font");
fs::create_dir_all(&font).unwrap();
fs::create_dir_all(&textures).unwrap();
fs::write(
font.join("default.json"),
r#"{"providers":[{"type":"bitmap","file":"minecraft:font/test.png","ascent":7,"chars":["ab"]}]}"#,
)
.unwrap();
let mut pixels = vec![0u8; 16 * 8 * 4];
for y in 0..8 {
for x in (0..3).chain(8..13) {
pixels[(y * 16 + x) * 4 + 3] = 255;
}
}
let mut encoder =
png::Encoder::new(fs::File::create(textures.join("test.png")).unwrap(), 16, 8);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(&pixels)
.unwrap();
let full = HudAtlas::build(&root).unwrap();
let fonts = HudAtlas::fonts(&root).unwrap();
let _ = fs::remove_dir_all(&root);
assert!(fonts.pixels.is_empty());
let width = full.font.width("abba");
assert!(width > 0.0);
assert_eq!(fonts.font.width("abba"), width);
}
#[test]
fn effect_icons_are_painted_from_the_mob_effect_directory() {
use crate::{effects::EffectInstance, hud_layout, hud_overlays, inventory_effects};
@@ -1092,6 +1250,41 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn gui_models_keep_separate_depth_runs_between_overlay_draws() {
let mut batch = HudBatch::new([640, 480]);
batch.scale = 2.0;
let p = [
[0.0, 0.0, 2.0],
[0.0, 1.0, 2.0],
[1.0, 1.0, 2.0],
[1.0, 0.0, 2.0],
];
let uv = [[0.0; 2]; 4];
batch.quad([[0.0; 2]; 4], uv, u32::MAX);
for _ in 0..2 {
let start = batch.vertices.len();
batch.quad_3d(p, uv, u32::MAX);
batch.depth_since(start, [1.0, 2.0, 4.0, 6.0]);
}
batch.quad([[0.0; 2]; 4], uv, u32::MAX);
assert_eq!(
batch.runs(),
vec![
(0..6, Blend::Alpha),
(6..12, Blend::Depth([2, 4, 6, 8])),
(12..18, Blend::Depth([2, 4, 6, 8])),
(18..24, Blend::Alpha),
]
);
assert!(
batch
.vertices
.iter()
.all(|v| v.depth.is_finite() && (0.0..=1.0).contains(&v.depth))
);
}
#[test]
fn hud_shader_validates_both_fragment_entries() {
let module = naga::front::wgsl::parse_str(include_str!("hud.wgsl")).unwrap();
+2 -2
View File
@@ -7,10 +7,10 @@ struct Out {
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
}
@vertex fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>) -> Out {
@vertex fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>, @location(3) depth: f32) -> Out {
let pixels = pos * hud.size.z;
var out: Out;
out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, 0.0, 1.0);
out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, depth, 1.0);
out.uv = uv;
out.color = color;
return out;
+42
View File
@@ -102,6 +102,10 @@ pub fn name_line(stack: &ItemStack, translate: &dyn Fn(&str) -> Option<String>)
if let Some(name) = stack.custom_name() {
return name.to_owned();
}
if stack.data().is_some_and(|d| d.ominous_banner) {
return translate("block.minecraft.ominous_banner")
.unwrap_or_else(|| "Ominous Banner".to_owned());
}
let key = if is_potion_item(&stack.item) {
Some(crate::brewing::potion_name_key(&stack.item, stack.potion()))
} else if let Some(pattern) = path.strip_suffix("_armor_trim_smithing_template") {
@@ -120,6 +124,24 @@ pub fn name_line(stack: &ItemStack, translate: &dyn Fn(&str) -> Option<String>)
.unwrap_or_else(|| path.replace('_', " "))
}
/// ItemStack.getRarity: the ominous banner override, then the enchantment upgrade.
pub fn rarity<'a>(stack: &ItemStack, default: &'a str) -> &'a str {
let rarity = if stack.data().is_some_and(|d| d.ominous_banner) {
"uncommon"
} else {
default
};
if stack.enchantments().is_empty() {
rarity
} else {
match rarity {
"common" | "uncommon" => "rare",
"rare" => "epic",
r => r,
}
}
}
/// The lines of `stack` below its name that its components give, in
/// `ItemStack.addDetailsToTooltip` order.
pub fn detail_lines(
@@ -292,6 +314,26 @@ pub fn lines(
mod tests {
use super::*;
#[test]
fn ominous_banner_name_and_rarity_use_the_stack() {
let translate = |key: &str| match key {
"block.minecraft.ominous_banner" => Some("Ominous Banner".to_owned()),
"block.minecraft.white_banner" => Some("White Banner".to_owned()),
_ => None,
};
let mut banner = crate::mobs::raider::ominous_banner();
assert_eq!(name_line(&banner, &translate), "Ominous Banner");
assert_eq!(name_line(&banner, &|_| None), "Ominous Banner");
assert_eq!(rarity(&banner, "common"), "uncommon");
banner.data_mut().custom_name = Some("Captain's Standard".into());
assert_eq!(name_line(&banner, &translate), "Captain's Standard");
banner.enchant("minecraft:unbreaking", 1);
assert_eq!(rarity(&banner, "common"), "rare");
let plain = ItemStack::new("minecraft:white_banner", 1);
assert_eq!(name_line(&plain, &translate), "White Banner");
assert_eq!(rarity(&plain, "common"), "common");
}
#[test]
fn container_lines_list_five_stacks_then_how_many_more() {
let mut chest = ItemStack::new("minecraft:chest", 1);
+2 -1
View File
@@ -361,8 +361,9 @@ fn login_and_configure(
name: &str,
) -> Result<Option<Parts>, String> {
let e = |e: horizon_protocol::Error| e.to_string();
// ServerLoginPacketListenerImpl: memory connections are not compressed.
let threshold = shared.config.compression_threshold;
if threshold >= 0 {
if threshold >= 0 && !c.is_memory() {
c.send(&login::Clientbound::Compression(login::Compression { threshold }).encode())
.map_err(e)?;
c.set_compression(threshold);
+18
View File
@@ -18,6 +18,16 @@ pub const CREATIVE: i32 = 1;
pub const ADVENTURE: i32 = 2;
pub const SPECTATOR: i32 = 3;
/// An effect as last sent in ClientboundUpdateMobEffectPacket.
#[derive(Clone, Debug, PartialEq)]
pub struct SentEffect {
pub id: &'static str,
pub amplifier: i32,
pub flags: i8,
pub duration: i32,
pub tick_count: i32,
}
pub struct Guest {
pub conn: u32,
/// The client's address (IP bans, `list`).
@@ -92,6 +102,12 @@ pub struct Guest {
pub xp_level: i32,
pub xp_progress: f32,
pub xp_total: i32,
/// Active status effects (`LivingEntity.activeEffects`).
pub effects: crate::effects::PlayerEffects,
/// What the client was told of each effect: id, amplifier, flags, and
/// the duration and `effects.tick_count` at the time, so a duration that
/// only counted down is not sent again (`ServerPlayer.onEffectUpdated`).
pub sent_effects: Vec<SentEffect>,
/// What the client believes the inventory menu holds (for change detection).
pub menu_sent: Vec<Option<ItemStack>>,
pub menu_state: i32,
@@ -174,6 +190,8 @@ impl Guest {
xp_level: 0,
xp_progress: 0.0,
xp_total: 0,
effects: Default::default(),
sent_effects: Vec::new(),
menu_sent: vec![None; 46],
menu_state: 0,
sent_health: None,
+119 -4
View File
@@ -9,9 +9,13 @@ use super::{
chunks::ChunkEncoder,
data::SyncData,
entity::EntityState,
guest::{Guest, stack_to_network},
guest::{Guest, SentEffect, stack_to_network},
};
use crate::{
effects::{EffectInstance, PlayerEffects},
items::ItemStack,
world::World,
};
use crate::{items::ItemStack, world::World};
use horizon_protocol::ids::play::clientbound as ids;
use horizon_protocol::{
entity_data::{Value, serializer},
@@ -44,6 +48,10 @@ pub struct HubConfig {
pub max_players: usize,
/// A dedicated server: operators from `ops`, the dedicated-only commands.
pub dedicated: bool,
/// An integrated server (`dedicated` too, since it has no host player):
/// the owner's level from `ops`, the others' from Allow Commands and
/// the guests' command access, and the integrated-only commands.
pub integrated: bool,
}
/// The host player as the other players see them.
@@ -441,7 +449,11 @@ impl Hub {
/// (IntegratedServer.setGuestCommandAccess); a dedicated server its
/// operators' level (`ops`).
fn default_permission(&self, uuid: u128) -> u8 {
if self.config.dedicated {
if self.config.integrated {
// IntegratedServer.getProfilePermissions / getCustomPermissionLevel.
let guests = if self.config.guest_commands { 2 } else { 0 };
self.ops.get(&uuid).copied().unwrap_or(guests)
} else if self.config.dedicated {
self.ops.get(&uuid).copied().unwrap_or(0)
} else if self.config.guest_commands {
2
@@ -553,11 +565,106 @@ impl Hub {
}));
g.center_sent = Some((cx, cz));
g.placed_at = self.ticks;
self.send_active_effects(i);
// ServerPlayer.sendPostEffects and initInventoryMenu.
self.guests[i].send(&raw(ids::POST_EFFECTS, vec![0]));
self.send_inventory(i);
}
/// ClientboundUpdateMobEffectPacket for one of the guest's effects.
fn send_effect(&mut self, i: usize, e: &EffectInstance, blend: bool) -> Option<SentEffect> {
let effect = self
.sync
.id("minecraft:mob_effect", &format!("minecraft:{}", e.id))?;
let flags = PlayerEffects::flags(e);
let g = &self.guests[i];
g.send(&C::UpdateMobEffect(play::UpdateMobEffect {
id: g.entity_id,
effect,
amplifier: e.amplifier,
duration: e.duration,
flags: flags | if blend { 8 } else { 0 },
}));
Some(SentEffect {
id: e.id,
amplifier: e.amplifier,
flags,
duration: e.duration,
tick_count: g.effects.tick_count,
})
}
/// PlayerList.sendActivePlayerEffects: every effect, unblended, when the
/// player is placed (or respawns).
pub fn send_active_effects(&mut self, i: usize) {
let effects = self.guests[i].effects.list.clone();
let sent = effects
.iter()
.filter_map(|e| self.send_effect(i, e, false))
.collect();
self.guests[i].sent_effects = sent;
}
/// ServerPlayer.onEffectAdded (blended), onEffectUpdated and
/// onEffectsRemoved, from what changed since the client was told: an
/// effect that only counted down is not sent again, except at every
/// 600 ticks left (`LivingEntity.tickEffects`).
fn sync_effects(&mut self, i: usize) {
let g = &self.guests[i];
if g.effects.list.is_empty() && g.sent_effects.is_empty() {
return;
}
let now = g.effects.tick_count;
let mut sent = Vec::with_capacity(g.effects.list.len());
let mut changes = Vec::new();
for e in &g.effects.list {
match g.sent_effects.iter().find(|s| s.id == e.id) {
None => changes.push((e.clone(), true)),
Some(s) => {
let ticked = now.wrapping_sub(s.tick_count);
let expected = if s.duration == -1 {
-1
} else {
s.duration - ticked
};
let refresh = ticked > 0 && e.duration > 0 && e.duration % 600 == 0;
if s.amplifier != e.amplifier
|| s.flags != PlayerEffects::flags(e)
|| e.duration != expected
|| refresh
{
changes.push((e.clone(), false));
} else {
sent.push(s.clone());
}
}
}
}
let removed: Vec<&'static str> = g
.sent_effects
.iter()
.filter(|s| g.effects.get(s.id).is_none())
.map(|s| s.id)
.collect();
for id in removed {
let Some(effect) = self
.sync
.id("minecraft:mob_effect", &format!("minecraft:{id}"))
else {
continue;
};
let g = &self.guests[i];
g.send(&C::RemoveMobEffect(play::RemoveMobEffect {
id: g.entity_id,
effect,
}));
}
for (e, added) in changes {
sent.extend(self.send_effect(i, &e, added));
}
self.guests[i].sent_effects = sent;
}
/// PlayerList.sendPlayerPermissionLevel: the op level as an entity event
/// (24 + level), then the commands that level may use.
fn send_permission_level(&self, i: usize) {
@@ -583,7 +690,10 @@ impl Hub {
fn send_commands(&self, i: usize) {
let g = &self.guests[i];
let packet = match &self.sync.commands {
Some(tree) => tree.packet(g.permission, self.config.dedicated, &self.sync.builtin),
Some(tree) => {
let dedicated = self.config.dedicated && !self.config.integrated;
tree.packet(g.permission, dedicated, &self.sync.builtin)
}
None => play::Commands {
nodes: vec![play::CommandNode {
kind: 0,
@@ -789,6 +899,7 @@ impl Hub {
for i in 0..self.guests.len() {
if self.guests[i].placed {
self.sync_player_state(i);
self.sync_effects(i);
}
}
let latencies: Vec<_> = self
@@ -1559,6 +1670,10 @@ impl Hub {
spawn: info,
keep: 0,
}));
// The respawned player is a new one, without effects; so is the
// client's (ClientPacketListener.handleRespawn).
g.effects = Default::default();
g.sent_effects.clear();
g.center = None;
g.sent_chunks.clear();
g.chunk_queue.clear();
+75 -38
View File
@@ -310,6 +310,8 @@ pub struct Lan {
events: Receiver<NetEvent>,
pub port: u16,
listener: Option<JoinHandle<()>>,
/// Stops the accept loop alone: local connections stay.
listener_stop: Arc<AtomicBool>,
/// The multicast announcement (LanServerPinger); absent when the socket failed.
_pinger: Option<discovery::Pinger>,
}
@@ -325,26 +327,8 @@ impl Lan {
}
/// ServerConnectionListener.startTcpServerListener with a configuration.
pub fn start_with(sync: Arc<data::SyncData>, config: NetConfig) -> io::Result<Self> {
let listener = if config.listen {
let bind = config
.bind
.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
let listener = TcpListener::bind((bind, config.port))?;
listener.set_nonblocking(true)?;
Some(listener)
} else {
None
};
let port = match &listener {
Some(l) => l.local_addr()?.port(),
None => 0,
};
let _pinger = if config.announce && listener.is_some() {
discovery::Pinger::start(config.motd.clone(), port).ok()
} else {
None
};
let (tx, events) = channel();
let (listen, port, announce) = (config.listen, config.port, config.announce);
let shared = Arc::new(Shared {
sync,
events: tx,
@@ -357,21 +341,77 @@ impl Lan {
random: Mutex::new(crate::server::java_properties::now_millis() as u64 | 1),
config,
});
let accept_shared = shared.clone();
let listener = listener
.map(|listener| {
std::thread::Builder::new()
.name("horizon-lan-accept".into())
.spawn(move || accept_loop(listener, accept_shared))
})
.transpose()?;
Ok(Self {
let mut lan = Self {
shared,
events,
port,
listener,
_pinger,
})
port: 0,
listener: None,
listener_stop: Arc::new(AtomicBool::new(false)),
_pinger: None,
};
if listen {
lan.listen(port, announce)?;
}
Ok(lan)
}
/// Start accepting connections on `port` (0 picks a free one), and
/// announce the world on the local network when `announce`
/// (`IntegratedServer.publishServer`'s LanServerPinger). Returns the port.
pub fn listen(&mut self, port: u16, announce: bool) -> io::Result<u16> {
if self.listener.is_some() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"already listening",
));
}
let listener = Self::bind(self.shared.config.bind, port)?;
self.listen_on(listener, announce)
}
/// The socket [`Lan::listen`] accepts on, bound ahead so that a failure
/// can be reported before the hub is at hand.
pub fn bind(address: Option<std::net::IpAddr>, port: u16) -> io::Result<TcpListener> {
let bind = address.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
let listener = TcpListener::bind((bind, port))?;
listener.set_nonblocking(true)?;
Ok(listener)
}
/// [`Lan::listen`] on a socket already bound.
pub fn listen_on(&mut self, listener: TcpListener, announce: bool) -> io::Result<u16> {
if self.listener.is_some() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"already listening",
));
}
let port = listener.local_addr()?.port();
let stop = Arc::new(AtomicBool::new(false));
let (accept_shared, accept_stop) = (self.shared.clone(), stop.clone());
let thread = std::thread::Builder::new()
.name("horizon-lan-accept".into())
.spawn(move || accept_loop(listener, accept_shared, &accept_stop))?;
self._pinger = if announce {
discovery::Pinger::start(self.shared.motd(), port).ok()
} else {
None
};
self.listener = Some(thread);
self.listener_stop = stop;
self.port = port;
Ok(port)
}
/// Stop accepting connections and announcing; connections already in
/// (the local one included) stay.
pub fn stop_listening(&mut self) {
self.listener_stop.store(true, Ordering::Relaxed);
if let Some(t) = self.listener.take() {
let _ = t.join();
}
self._pinger = None;
self.port = 0;
}
/// Whether connections from the network are accepted.
pub fn listening(&self) -> bool {
self.listener.is_some()
}
/// `Connection.connectToLocalServer`: a connection through memory, its
/// server end served on its own thread like an accepted socket.
@@ -402,10 +442,7 @@ impl Lan {
}
pub fn stop(&mut self) {
self.shared.stop.store(true, Ordering::Relaxed);
if let Some(t) = self.listener.take() {
let _ = t.join();
}
self._pinger = None;
self.stop_listening();
}
}
impl Drop for Lan {
@@ -414,8 +451,8 @@ impl Drop for Lan {
}
}
fn accept_loop(listener: TcpListener, shared: Arc<Shared>) {
while !shared.stop.load(Ordering::Relaxed) {
fn accept_loop(listener: TcpListener, shared: Arc<Shared>, stop: &AtomicBool) {
while !shared.stop.load(Ordering::Relaxed) && !stop.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, addr)) => {
let shared = shared.clone();
@@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
guest.xp_level = level.xp_level;
guest.xp_progress = level.xp_progress;
guest.xp_total = level.xp_total;
guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects);
guest.game_mode = level.mode();
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = level.player_extra.clone();
@@ -119,6 +120,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
level.xp_level = guest.xp_level;
level.xp_progress = guest.xp_progress;
level.xp_total = guest.xp_total;
level.active_effects = guest.effects.saved();
level.game_mode = guest.game_mode;
level.creative = guest.game_mode == 1;
level.selected_slot = guest.selected as i32;
+1
View File
@@ -132,6 +132,7 @@ pub mod particles;
pub mod patrol;
pub mod perf_overlay;
pub mod pick_item;
pub mod poi_sections;
pub mod pose;
pub mod post;
pub mod projectiles;
+4
View File
@@ -847,6 +847,10 @@ fn red_overlay(m: &Mob) -> bool {
m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))
}
fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 {
if m.kind.id == "minecraft:player" {
// AvatarRenderer.scale, shared by the inventory and world renderer.
return glam::Mat4::from_scale(glam::Vec3::splat(0.9375));
}
match m.species() {
Species::Wither => {
glam::Mat4::from_scale(glam::Vec3::splat(super::wither::scale(m, alpha)))
@@ -924,8 +924,35 @@ fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize {
}
n
}
/// The POIs of chunk `(qx, qz)` from `y0` to `y1` (within the world), in
/// scan order: y, then z, then x. Only the indexed POI blocks of the sections
/// are visited (`PoiManager.getInChunk`).
fn chunk_pois(
w: &MobWorld,
(qx, qz): (i32, i32),
y0: i32,
y1: i32,
mut visit: impl FnMut(Poi, [i32; 3]),
) {
let Some(chunk) = w.world.chunks.get(&(qx, qz)) else {
return;
};
let kind = |state: u32| poi_of_state(w, horizon_world::registry::BlockStateId(state));
let min = crate::chunk::MIN_Y;
for s in (y0 - min) >> 4..=(y1 - min) >> 4 {
let section = &chunk.sections[s as usize];
for &(i, poi) in w.world.pois.get((qx, s, qz), section, kind).iter() {
let i = i32::from(i);
let y = min + s * 16 + (i >> 8);
if (y0..=y1).contains(&y) {
visit(poi, [qx * 16 + (i & 15), y, qz * 16 + (i >> 4 & 15)]);
}
}
}
}
/// `PoiManager.getInRange` with `HAS_SPACE`, nearest first (`distSqr` to the
/// block, ties in scan order), filtered by `accept`.
/// block, ties in scan order: chunk by chunk, z then x, and y, z, x within),
/// filtered by `accept`.
fn pois_in_range(
m: &Mob,
w: &MobWorld,
@@ -940,62 +967,24 @@ fn pois_in_range(
let chunks = radius.div_euclid(16) + 1;
let y0 = (c[1] - radius).max(crate::chunk::MIN_Y);
let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1);
// Sections whose palette holds no POI state are skipped whole, as
// PoiManager only visits sections with records: the same positions in
// the same order, without reading and naming every block of the sphere.
let kind = |state: u32| poi_of_state(w, horizon_world::registry::BlockStateId(state));
for qz in cz - chunks..=cz + chunks {
for qx in cx - chunks..=cx + chunks {
let Some(chunk) = w.world.chunks.get(&(qx, qz)) else {
continue;
};
let holds: Vec<bool> = chunk
.sections
.iter()
.map(|s| s.blocks.maybe_has(|v| kind(v).is_some()))
.collect();
for y in y0..=y1 {
if !holds[((y - crate::chunk::MIN_Y) >> 4) as usize] {
continue;
chunk_pois(w, (qx, qz), y0, y1, |poi, p| {
if (p[0] - c[0]).abs() > radius
|| (p[2] - c[2]).abs() > radius
|| dist_sqr(p, c) > r2
|| !poi_matches(m, f, poi)
|| tickets(m, w, p) >= poi.max_tickets()
{
return;
}
for z in qz * 16..qz * 16 + 16 {
for x in qx * 16..qx * 16 + 16 {
if (x - c[0]).abs() > radius || (z - c[2]).abs() > radius {
continue;
}
let d = i64::from(x - c[0]).pow(2)
+ i64::from(y - c[1]).pow(2)
+ i64::from(z - c[2]).pow(2);
if d > r2 {
continue;
}
let state = chunk.block(x & 15, y, z & 15);
if w.facts.is_air(state) {
continue;
}
let Some(poi) = kind(state.0) else {
continue;
};
if !poi_matches(m, f, poi) {
continue;
}
let p = [x, y, z];
if tickets(m, w, p) >= poi.max_tickets() {
continue;
}
if accept(p) {
found.push((poi, p));
}
}
if accept(p) {
found.push((poi, p));
}
}
});
}
}
found.sort_by_key(|(_, p)| {
i64::from(p[0] - c[0]).pow(2)
+ i64::from(p[1] - c[1]).pow(2)
+ i64::from(p[2] - c[2]).pow(2)
});
found.sort_by_key(|&(_, p)| dist_sqr(p, c));
found
}
/// `PoiManager.exists(pos, predicate)`.
@@ -3389,26 +3378,23 @@ fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 {
manhattan_sq(a, b)
}
/// Every bed head within `radius` (`PoiManager.getInRange(HOME, ..., ANY)`),
/// in scan order.
/// in the order of a scan of the cube: y, then z, then x.
fn homes_in_range(m: &Mob, w: &MobWorld, radius: i32) -> Vec<[i32; 3]> {
let c = block_of(m.position);
let r2 = i64::from(radius) * i64::from(radius);
let mut out = Vec::new();
let y0 = (c[1] - radius).max(crate::chunk::MIN_Y);
let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1);
for y in y0..=y1 {
for z in c[2] - radius..=c[2] + radius {
for x in c[0] - radius..=c[0] + radius {
let p = [x, y, z];
if dist_sqr(p, c) <= r2
&& w.world.loaded(x, z)
&& poi_at(w, x, y, z) == Some(Poi::Home)
{
for qz in (c[2] - radius) >> 4..=(c[2] + radius) >> 4 {
for qx in (c[0] - radius) >> 4..=(c[0] + radius) >> 4 {
chunk_pois(w, (qx, qz), y0, y1, |poi, p| {
if poi == Poi::Home && dist_sqr(p, c) <= r2 {
out.push(p);
}
}
});
}
}
out.sort_unstable_by_key(|p| (p[1], p[2], p[0]));
out
}
/// `MoveToSkySeeingSpot.hasNoBlocksAbove`.
@@ -34,6 +34,8 @@ pub struct BakedFace {
}
pub struct BakedModel {
pub ambient_occlusion: bool,
/// The model's particle slot also exists for models without block faces.
pub particle: Option<u32>,
pub faces: Vec<BakedFace>,
pub cube: Option<[super::cube::CubeStyle; 6]>,
}
@@ -190,6 +192,10 @@ impl StateModels {
let mut baked = BTreeMap::new();
for (name, turns, lock) in variants {
let model = library.resolve(&name)?;
let particle = model
.material("particle")?
.map(|material| sprites.insert(root, &material.sprite))
.transpose()?;
let faces: Vec<BakedFace> =
bake_block_model(&model, BlockModelTransform::new(turns, lock))?
.into_iter()
@@ -209,6 +215,7 @@ impl StateModels {
(name, turns, lock),
BakedModel {
ambient_occlusion: model.ambient_occlusion,
particle,
faces,
cube,
},
+9 -2
View File
@@ -587,9 +587,16 @@ impl OptionsUi {
}
return events;
}
// A click anywhere stops waiting for an extra's key.
// Rebinding consumes the click before sidebar or widget actions.
if matches!(self.selected_key, Some(extras::ZOOM_KEY | extras::SORT_KEY)) {
self.selected_key = None;
return self.bind_mouse(
s,
if right {
winit::event::MouseButton::Right
} else {
winit::event::MouseButton::Left
},
);
}
match self.horizon_target(s, atlas, x, y) {
Some(Target::Nav(i)) => {
+207 -12
View File
@@ -708,6 +708,7 @@ pub enum Page {
Language,
Font,
Packs,
Mods,
/// Horizon's graphics settings (`graphics_ui`).
Graphics,
GraphicsAdvanced,
@@ -730,6 +731,7 @@ enum Act {
ResetPadKeys,
/// Back to Horizon's own menus (Horizon only, see `list_rows`).
HorizonMenus,
ToggleMod(usize),
}
enum WKind {
Button {
@@ -971,6 +973,7 @@ impl OptionsUi {
Page::Language => "options.language.title",
Page::Font => "options.font.title",
Page::Packs => "resourcePack.title",
Page::Mods => "Mods",
Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle",
Page::Controller => "Controller Settings",
Page::PadBinds => "Controller Binds",
@@ -1161,6 +1164,36 @@ impl OptionsUi {
Opt::AutoJump,
]),
Page::Font => pairs(&[Opt::ForceUnicode, Opt::JapaneseGlyphs]),
Page::Mods => {
if s.mods.installed.is_empty() {
return vec![Row::Header(
"No mods: put .hmod files in the horizon-mods folder",
)];
}
s.mods
.installed
.iter()
.enumerate()
.map(|(i, installed)| {
let mut label = Text::literal(format!("{}: ", installed.title))
.append(on_off(s.mods.is_on(i)));
if installed.problem.is_some() {
label = label.append(" (Stopped)");
} else if installed.dev {
label = label.append(" (Dev)");
}
let widget = button(0.0, 0.0, 310.0, label, Act::ToggleMod(i));
Row::Buttons(
if installed.dev || installed.id.is_empty() {
inactive(widget)
} else {
widget
},
None,
)
})
.collect()
}
_ => {
let _ = s;
Vec::new()
@@ -1206,7 +1239,7 @@ impl OptionsUi {
("options.chat", Some(Page::Chat)),
("options.resourcepack", Some(Page::Packs)),
("options.accessibility", Some(Page::Accessibility)),
("options.telemetry", None),
("Mods...", Some(Page::Mods)),
("options.credits_and_attribution", None),
];
let gy = (61.0 + 30.0f32).min(h - 33.0 - 120.0);
@@ -1650,6 +1683,21 @@ impl OptionsUi {
if let Some(key) = key.filter(|key| lang::has(key)) {
tooltip = Some(atlas.font.split(&tr(&key), 170.0));
}
if let WKind::Button {
act: Act::ToggleMod(i),
..
} = &wd.kind
&& let Some(installed) = s.mods.installed.get(*i)
{
let description = installed
.problem
.as_deref()
.unwrap_or(&installed.description);
tooltip = Some(atlas.font.split(
&Text::literal(format!("{}\n{description}", installed.title)),
170.0,
));
}
}
match &wd.kind {
WKind::Button { label, active, act } => {
@@ -1876,15 +1924,13 @@ impl OptionsUi {
return events;
}
// Key Binds: a mouse button pressed while waiting binds it.
if let Some(name) = self.selected_key.take() {
if self.selected_key.is_some() {
let button = if right {
"key.mouse.right"
winit::event::MouseButton::Right
} else {
"key.mouse.left"
winit::event::MouseButton::Left
};
s.keys.set(name, button);
events.push(Event::Changed);
return events;
return self.bind_mouse(s, button);
}
// AbstractWidget accepts only the primary button. Rebinding above
// accepts other mouse buttons, but is not a widget activation.
@@ -1944,6 +1990,10 @@ impl OptionsUi {
crate::ui_theme::save_preferences(&dir);
}
}
Act::ToggleMod(i) => {
s.mods.toggle(i);
events.push(Event::Changed);
}
Act::None => {}
}
}
@@ -2126,6 +2176,23 @@ impl OptionsUi {
}
false
}
fn bind_key(&mut self, s: &mut Settings, value: String) -> Vec<Event> {
let Some(name) = self.selected_key.take() else {
return Vec::new();
};
if !s.extras.set_key(name, value.clone()) {
s.keys.set(name, &value);
}
vec![Event::Changed]
}
/// Mouse bindings use the same settings and persistence as keyboard bindings.
pub fn bind_mouse(
&mut self,
s: &mut Settings,
button: winit::event::MouseButton,
) -> Vec<Event> {
self.bind_key(s, keybinds::mouse_name(button))
}
/// Keys while the options are open. Returns events; `handled` false lets
/// Escape fall through.
pub fn key(
@@ -2160,7 +2227,7 @@ impl OptionsUi {
}
return vec![Event::Changed];
}
if let Some(name) = self.selected_key.take() {
if self.selected_key.is_some() {
// KeyBindsScreen.keyPressed: Escape unbinds.
let value = if key == K::Escape {
"key.keyboard.unknown".to_owned()
@@ -2169,10 +2236,7 @@ impl OptionsUi {
.unwrap_or("key.keyboard.unknown")
.to_owned()
};
if !s.extras.set_key(name, value.clone()) {
s.keys.set(name, &value);
}
return vec![Event::Changed];
return self.bind_key(s, value);
}
if key == K::Escape {
return self.back(s);
@@ -2201,6 +2265,88 @@ mod tests {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
#[test]
fn classic_mods_page_toggles_mods_and_keeps_dev_and_invalid_entries_inactive() {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
let size = (480.0, 240.0);
assert!(ui.layout(&s, size.0, size.1).0.iter().any(|w| {
matches!(
w.kind,
WKind::Button {
active: true,
act: Act::Push(Page::Mods),
..
}
)
}));
ui.show(Page::Mods);
let empty = ui.layout(&s, size.0, size.1).0;
assert!(empty.iter().any(|w| {
matches!(&w.kind, WKind::Text { text, .. } if text.plain().contains(".hmod"))
}));
for (id, dev) in [("normal", false), ("dev", true), ("", false)] {
s.mods.installed.push(crate::mod_list::Installed {
id: id.into(),
title: id.into(),
description: "May show HUD panels.".into(),
problem: id.is_empty().then(|| "Invalid package".into()),
dev,
});
}
let (widgets, ..) = ui.layout(&s, size.0, size.1);
let rows: Vec<_> = widgets
.iter()
.filter(|w| {
matches!(
w.kind,
WKind::Button {
act: Act::ToggleMod(_),
..
}
)
})
.collect();
assert_eq!(rows.len(), 3);
for (i, row) in rows.iter().enumerate() {
let events = ui.click(
&mut s,
&atlas,
row.x + 1.0,
row.y + 1.0,
size,
[480, 240],
false,
false,
);
if i == 0 {
assert!(events.contains(&Event::Changed));
assert!(events.contains(&Event::ButtonClick));
} else {
assert!(events.is_empty());
}
}
assert!(s.mods.is_on(0));
assert!(s.mods.is_on(1));
assert!(!s.mods.is_on(2));
assert_eq!(s.mods.serialize(), "mod.normal:true\n");
let row = rows[0];
ui.click(
&mut s,
&atlas,
row.x + 1.0,
row.y + 1.0,
size,
[480, 240],
false,
false,
);
assert!(!s.mods.is_on(0));
assert!(!ui.back(&mut s).contains(&Event::Close));
assert_eq!(ui.page(), Page::Main);
}
#[test]
fn option_tooltip_keys_follow_value_dependent_descriptions() {
let mut s = Settings::default();
@@ -2831,6 +2977,55 @@ mod tests {
}
}
#[test]
fn extras_and_vanilla_bindings_accept_mouse_buttons() {
use crate::extras::{Extras, SORT_KEY, ZOOM_KEY};
use winit::event::MouseButton;
for button in [
MouseButton::Left,
MouseButton::Right,
MouseButton::Middle,
MouseButton::Back,
MouseButton::Forward,
] {
for name in [SORT_KEY, ZOOM_KEY, "key.jump"] {
let mut ui = OptionsUi::default();
let mut s = Settings::default();
ui.selected_key = Some(name);
assert_eq!(ui.bind_mouse(&mut s, button), vec![Event::Changed]);
assert_eq!(ui.selected_key, None);
let value = keybinds::mouse_name(button);
match name {
SORT_KEY => assert_eq!(s.extras.sort_key, value),
ZOOM_KEY => assert_eq!(s.extras.zoom_key, value),
_ => assert_eq!(s.keys.get(name), value),
}
assert_eq!(Extras::parse(&s.extras.serialize()), s.extras);
if name != "key.jump" {
assert_eq!(s.keys, Settings::default().keys);
}
assert!(ui.bind_mouse(&mut s, button).is_empty());
}
}
}
#[test]
fn horizon_extra_mouse_binding_consumes_the_click() {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
for (right, expected) in [(false, "key.mouse.left"), (true, "key.mouse.right")] {
ui.selected_key = Some(crate::extras::SORT_KEY);
assert_eq!(
ui.click_horizon(&mut s, &atlas, 2.0, 2.0, [960, 480], false, right),
vec![Event::Changed]
);
assert_eq!(s.extras.sort_key, expected);
assert_eq!(ui.selected_key, None);
assert_eq!(ui.section, 0);
}
}
#[test]
fn key_rebinding_takes_precedence_over_scrollbar_dragging() {
let atlas = atlas();
+134
View File
@@ -0,0 +1,134 @@
//! The points of interest of each resident section (`PoiSection`), so a
//! search visits the few POI blocks of the sections in range instead of
//! reading every block of them.
//!
//! Vanilla keeps its records up to date from `onBlockStateChange`; here a
//! section's list is rebuilt from its blocks after any edit. Resident
//! sections are immutable behind `Arc` and edited through `Arc::make_mut`, so
//! a weak reference tells an edited or replaced section from the one the list
//! was built from (see `random_tick_sections`), without keeping its blocks.
use crate::{chunk::Section, fast_hash::FxHashMap};
use std::sync::{Arc, Mutex, Weak};
/// A section's POIs: the block index in the section (`y << 8 | z << 4 | x`)
/// and its kind, in ascending index order.
pub type SectionPois<T> = Arc<[(u16, T)]>;
struct Cached<T> {
section: Weak<Section>,
pois: SectionPois<T>,
}
/// Cached POI lists by section, `(chunk x, section index, chunk z)`.
pub struct PoiSections<T> {
sections: Mutex<Lists<T>>,
}
struct Lists<T> {
by_section: FxHashMap<(i32, i32, i32), Cached<T>>,
/// Size above which lists of sections no longer resident are dropped.
prune_at: usize,
}
const MIN_PRUNE: usize = 4096;
impl<T> Default for PoiSections<T> {
fn default() -> Self {
Self {
sections: Mutex::new(Lists {
by_section: FxHashMap::default(),
prune_at: MIN_PRUNE,
}),
}
}
}
impl<T: Copy> PoiSections<T> {
/// The POIs of `section`, whose block states `kind` classifies. `kind`
/// must give the same answer for a state on every call.
pub fn get(
&self,
key: (i32, i32, i32),
section: &Arc<Section>,
mut kind: impl FnMut(u32) -> Option<T>,
) -> SectionPois<T> {
let mut lists = self.sections.lock().unwrap_or_else(|e| e.into_inner());
if let Some(cached) = lists.by_section.get(&key)
&& cached.section.as_ptr() == Arc::as_ptr(section)
{
return cached.pois.clone();
}
let pois: SectionPois<T> = if section.blocks.maybe_has(|v| kind(v).is_some()) {
let mut states = [0u16; 4096];
section.unpack(&mut states);
states
.iter()
.enumerate()
.filter_map(|(i, &state)| kind(u32::from(state)).map(|poi| (i as u16, poi)))
.collect()
} else {
Arc::from([])
};
if lists.by_section.len() >= lists.prune_at {
lists.by_section.retain(|_, c| c.section.strong_count() > 0);
lists.prune_at = (lists.by_section.len() * 2).max(MIN_PRUNE);
}
lists.by_section.insert(
key,
Cached {
section: Arc::downgrade(section),
pois: pois.clone(),
},
);
pois
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chunk::{Chunk, MIN_Y};
#[test]
fn lists_follow_edits_and_replacement() {
let index = PoiSections::<u8>::default();
let kind = |v: u32| (v == 5 || v == 6).then_some(v as u8);
let mut chunk = Arc::new(Chunk::empty(0, 0));
assert!(index.get((0, 0, 0), &chunk.sections[0], kind).is_empty());
Arc::make_mut(&mut chunk).set(3, MIN_Y + 2, 1, 6);
Arc::make_mut(&mut chunk).set(0, MIN_Y, 0, 5);
let found = index.get((0, 0, 0), &chunk.sections[0], kind);
assert_eq!(&*found, &[(0, 5), (2 << 8 | 1 << 4 | 3, 6)]);
// Unchanged: the cached list, not a rescan.
let again = index.get((0, 0, 0), &chunk.sections[0], |_| panic!("rescanned"));
assert!(Arc::ptr_eq(&found, &again));
// An edit in place (no other owner) still invalidates the list.
Arc::make_mut(&mut chunk).set(0, MIN_Y, 0, 1);
assert_eq!(
&*index.get((0, 0, 0), &chunk.sections[0], kind),
&[(2 << 8 | 1 << 4 | 3, 6)]
);
// So does replacing the section, or the chunk.
Arc::make_mut(&mut chunk).sections[0] = Arc::new(Section::default());
assert!(index.get((0, 0, 0), &chunk.sections[0], kind).is_empty());
let mut other = Chunk::empty(0, 0);
other.set(1, MIN_Y, 1, 5);
chunk = Arc::new(other);
assert_eq!(
&*index.get((0, 0, 0), &chunk.sections[0], kind),
&[(1 << 4 | 1, 5)]
);
// An unused palette entry alone yields no POI.
Arc::make_mut(&mut chunk).set(1, MIN_Y, 1, 2);
assert!(index.get((0, 0, 0), &chunk.sections[0], kind).is_empty());
}
#[test]
fn unloaded_sections_are_dropped() {
let index = PoiSections::<u8>::default();
let kind = |v: u32| (v == 5).then_some(5);
let kept = Arc::new(Section::default());
index.get((0, 0, 0), &kept, kind);
for i in 0..MIN_PRUNE as i32 {
index.get((1, i, 0), &Arc::new(Section::default()), kind);
}
let lists = index.sections.lock().unwrap();
assert!(lists.by_section.len() <= 2);
assert!(lists.by_section.contains_key(&(0, 0, 0)));
}
}
+27 -1
View File
@@ -449,13 +449,17 @@ pub fn encode_block_entity(
block: &str,
) -> Tag {
use crate::containers::BlockEntity;
let components = match e {
BlockEntity::Banner(b) => b.components.clone(),
_ => Compound::new(),
};
let mut entries = vec![
("id", string(&block_entity_id(e, block))),
("x", Tag::Int(p.0)),
("y", Tag::Int(p.1)),
("z", Tag::Int(p.2)),
("keepPacked", Tag::Byte(0)),
("components", Tag::Compound(Compound::new())),
("components", Tag::Compound(components)),
];
match e {
BlockEntity::Chest(items) => entries.push(("Items", encode_items(items))),
@@ -583,6 +587,10 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
BlockEntity::Banner(crate::containers::Banner {
layers: crate::banner::layers_from_nbt(tag.get("patterns")),
name: text(tag.get("CustomName")),
components: match tag.get("components") {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
},
}),
));
}
@@ -2361,6 +2369,7 @@ impl Level {
"Inventory",
"EnderItems",
"equipment",
"active_effects",
"Pos",
"respawn",
"recipeBook",
@@ -2984,6 +2993,7 @@ mod tests {
let banner = crate::containers::Banner {
layers: vec![crate::banner::BannerLayer::new("minecraft:creeper", "lime")],
name: Some("Flag".into()),
components: [("minecraft:rarity".into(), string("uncommon"))].into(),
};
let tag = encode_block_entity(
(1, 2, 3),
@@ -2997,6 +3007,7 @@ mod tests {
};
assert_eq!(back.layers, banner.layers);
assert_eq!(back.name, banner.name);
assert_eq!(back.components, banner.components);
}
use super::*;
@@ -3191,4 +3202,19 @@ mod tests {
assert!(dir.join("data/minecraft/world_gen_settings.dat").exists());
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn effects_that_ended_are_not_saved_again() {
// A player loaded with an effect that has since run out: the loaded
// compound still holds it, but the save writes only what is active.
let mut level = Level {
active_effects: vec![("minecraft:speed".into(), 200, 1, false, true)],
..Level::default()
};
let loaded = level.player_tag();
assert!(loaded.get("active_effects").is_some());
level.player_extra = Some(loaded);
level.active_effects.clear();
assert!(level.player_tag().get("active_effects").is_none());
}
}
+43 -6
View File
@@ -968,7 +968,8 @@ impl Streaming {
return (uploads, removed);
}
// Meshing once the column and its neighbours are lit, and the column
// is within the render distance. Sections set aside past it come back
// is within the render distance (`in_view_distance`, the columns
// vanilla draws). Sections set aside past it come back
// when the player moves: a column that loads with its light gets no
// other request (#228).
let area = (self.center, self.radius, self.forced.len());
@@ -981,7 +982,7 @@ impl Streaming {
forced: &self.forced,
};
self.waiting.retain(|&(x, sy, z)| {
let back = ranges.in_main_range(x, z, 0);
let back = ranges.in_view(x, z);
if back {
world.dirty_sections.insert((x, sy, z));
}
@@ -996,7 +997,7 @@ impl Streaming {
world.dirty_sections.remove(&(x, sy, z));
continue;
}
if !self.in_main_range(x, z, 0) {
if !self.ranges().in_view(x, z) {
world.dirty_sections.remove(&(x, sy, z));
self.waiting.insert((x, sy, z));
continue;
@@ -1204,9 +1205,15 @@ impl Streaming {
fn in_range(&self, x: i32, z: i32, margin: i32) -> bool {
self.ranges().in_range(x, z, margin)
}
fn in_main_range(&self, x: i32, z: i32, margin: i32) -> bool {
self.ranges().in_main_range(x, z, margin)
}
}
/// `ChunkTrackingView.isInViewDistance`: whether the column (x, z) is drawn
/// at this render distance around `center`, the camera's column
/// (`SectionOcclusionGraph.isInViewDistance`). Each axis gets a column of
/// slack, so this reaches past the circle of `radius` columns.
pub fn in_view_distance(center: (i32, i32), radius: i32, x: i32, z: i32) -> bool {
let gap = |d: i32| i64::from((d.abs() - 1).max(0));
let (dx, dz) = (gap(x - center.0), gap(z - center.1));
dx * dx + dz * dz < i64::from(radius) * i64::from(radius)
}
/// The areas kept loaded: circles around the player and `extra`, and forced chunks.
struct Ranges<'a> {
@@ -1271,6 +1278,11 @@ impl Ranges<'_> {
dx * dx + dz * dz <= r * r
})
}
/// The columns meshed for drawing: those vanilla draws around the
/// player (`in_view_distance`), and forced ones.
fn in_view(&self, x: i32, z: i32) -> bool {
in_view_distance(self.center, self.radius, x, z) || self.forced.contains(&(x, z))
}
fn in_main_range(&self, x: i32, z: i32, margin: i32) -> bool {
let r = i64::from(self.radius + margin);
let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1));
@@ -1306,6 +1318,31 @@ impl Drop for Streaming {
mod tests {
use super::*;
#[test]
fn view_distance_is_vanillas_shape() {
// ChunkTrackingView.isInViewDistance at render distance 12: a column
// of slack on each axis, so 533 columns rather than the 441 of a
// circle of radius 12.
let count = |r: i32| {
(-40..=40)
.flat_map(|x| (-40..=40).map(move |z| (x, z)))
.filter(|&(x, z)| in_view_distance((5, -7), r, x + 5, z - 7))
.count()
};
assert_eq!(count(12), 533);
assert_eq!(count(2), 25);
for (x, z, inside) in [(12, 0, true), (13, 0, false), (9, 9, true), (10, 9, false)] {
assert_eq!(in_view_distance((0, 0), 12, x, z), inside, "({x}, {z})");
assert_eq!(
in_view_distance((0, 0), 12, -z, -x),
inside,
"({}, {})",
-z,
-x
);
}
}
struct GenerationFixture {
world: World,
center: (i32, i32),
+1
View File
@@ -690,6 +690,7 @@ impl<'a> Ui<'a> {
pos: p[i],
uv: [cu, cv],
color: c[i],
depth: 0.0,
});
}
}
+3
View File
@@ -46,6 +46,8 @@ pub struct World {
/// Every block position written since the log was last drained, kept
/// only while the world is open to the network (see `lan`).
pub block_log: Option<Vec<(i32, i32, i32)>>,
/// The villager POIs of each section (`PoiManager`'s sections).
pub pois: crate::poi_sections::PoiSections<crate::mobs::villager_brain::Poi>,
}
/// ServerLevel weather state (advanceWeatherCycle).
#[derive(Clone, Copy, Debug, Default)]
@@ -130,6 +132,7 @@ impl World {
day_time: 1000,
weather: Weather::default(),
block_log: None,
pois: Default::default(),
}
}
/// A controlled blockstate scene for the native scene probes: material
+1
View File
@@ -241,6 +241,7 @@ fn server(resources: &Path) -> Server {
view_distance: 3,
simulation_distance: 3,
dedicated: false,
integrated: false,
dimension: "minecraft:overworld".into(),
seed: 1234,
max_players: 8,
@@ -227,6 +227,10 @@ impl Connection {
},
})
}
/// `Connection.isMemoryConnection`: through a [`Pipe`] rather than a socket.
pub fn is_memory(&self) -> bool {
matches!(self.reader.stream, Stream::Memory(_))
}
/// ClientboundLoginCompressionPacket: negative thresholds disable compression.
pub fn set_compression(&mut self, threshold: i32) {
let t = usize::try_from(threshold).ok();
@@ -513,6 +513,22 @@ impl Behaviours {
sim.game_event_state(pos, "minecraft:block_change", next);
}
/// The state change of `RedStoneOreBlock.attack` when mining begins.
pub fn attack_block<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
if self.data(state).chain.contains(&Class::RedStoneOre)
&& !self.table.bool(state, self.props.lit)
{
sim.set_block_and_update(pos, self.table.set_bool(state, self.props.lit, true));
}
}
/// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and
/// absolute hit location as in `BlockHitResult`).
pub fn use_without_item<L: LevelAccess + ?Sized>(
+21
View File
@@ -634,6 +634,27 @@ impl World<'_> {
}
}
#[test]
fn mining_lights_redstone_ore_until_its_random_tick() {
let mut w = world!();
let pos = BlockPos::new(0, 1, 0);
for ore in ["redstone_ore", "deepslate_redstone_ore"] {
let unlit = w.id(ore, &[("lit", "false")]);
let lit = w.id(ore, &[("lit", "true")]);
w.put(pos, unlit);
w.b().attack_block(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.get(pos), lit);
w.b().attack_block(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.get(pos), lit);
w.b().random_tick(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.get(pos), unlit);
}
let stone = w.id("stone", &[]);
w.put(pos, stone);
w.b().attack_block(&mut w.level, &mut w.ticks, pos);
assert_eq!(w.get(pos), stone);
}
#[test]
fn placement_orients_blocks() {
let mut w = world!();
+80 -2
View File
@@ -51,7 +51,7 @@ use std::{
collections::{BTreeMap, BTreeSet, HashMap},
fs, io,
path::Path,
sync::{Arc, Mutex},
sync::{Arc, Mutex, OnceLock},
};
#[derive(Debug)]
@@ -184,7 +184,13 @@ pub struct GeneratorData {
/// Block shape-update behaviour (`block-behaviours.json` next to the
/// worldgen directory) for template placement's neighbor updates.
pub(super) behaviours: Option<Arc<crate::level::Behaviours>>,
/// Concentric ring positions by seed and dimension generator (see
/// `rings_for`), most recent last.
ring_cache: Mutex<Vec<RingCacheEntry>>,
}
type RingCacheEntry = ((i64, String), Arc<OnceLock<super::structure::start::Rings>>);
/// Generators whose ring positions are kept: the dimensions of a few worlds.
const RING_CACHE_LIMIT: usize = 8;
type Bundle = BTreeMap<String, String>;
fn read_bundle(dir: &Path, name: &str) -> Result<Bundle, GeneratorError> {
let path = dir.join(format!("{name}.json"));
@@ -458,8 +464,30 @@ impl GeneratorData {
block_tags,
biome_tags,
feature_resources,
ring_cache: Mutex::new(Vec::new()),
}))
}
/// The concentric ring positions (strongholds) of the generator for
/// `seed` and the dimension `generator` definition, shared by every
/// generator built for them. They depend on nothing else, so returning
/// to a dimension, which builds its generator again, finds them done.
pub(super) fn rings_for(
&self,
seed: i64,
generator: &Value,
) -> Arc<OnceLock<super::structure::start::Rings>> {
let key = (seed, generator.to_string());
let mut cache = self.ring_cache.lock().unwrap_or_else(|e| e.into_inner());
let rings = match cache.iter().position(|(k, _)| *k == key) {
Some(i) => cache.remove(i).1,
None => Arc::new(OnceLock::new()),
};
if cache.len() >= RING_CACHE_LIMIT {
cache.remove(0);
}
cache.push((key, rings.clone()));
rings
}
pub fn registry(&self) -> &'static BlockRegistry {
self.registry
}
@@ -821,8 +849,9 @@ where
.into_iter()
.filter_map(|name| pipeline.data.biome_id(name))
.collect();
let rings = pipeline.data.rings_for(seed, generator);
pipeline.structures =
super::generator_structures::StructureState::new(&pipeline.data, &possible)?;
super::generator_structures::StructureState::new(&pipeline.data, &possible, rings)?;
}
Ok(pipeline)
}
@@ -1906,6 +1935,55 @@ impl GeneratorWorker {
mod tests {
use super::*;
/// Generators of one seed and dimension share their ring positions;
/// another seed or generator gets its own, and old entries go.
#[test]
fn ring_positions_are_shared_by_seed_and_dimension() {
let root = std::env::var_os("HORIZON_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
});
if !root.join("worldgen/world_presets.json").exists() {
eprintln!("skipping: no worldgen bundle at {}", root.display());
return;
}
let registry: &'static BlockRegistry = Box::leak(Box::new(
crate::level::data::load_registry(&root).expect("registry"),
));
let data = GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data");
let first = OverworldGenerator::new(data.clone(), 1234).expect("generator");
let again = OverworldGenerator::new(data.clone(), 1234).expect("generator");
{
let cache = data.ring_cache.lock().unwrap();
assert_eq!(cache.len(), 1);
// The cache's handle and the two generators'.
assert_eq!(Arc::strong_count(&cache[0].1), 3);
}
drop((first, again));
let a = data.rings_for(1, &serde_json::json!({ "settings": "a" }));
assert!(Arc::ptr_eq(
&a,
&data.rings_for(1, &serde_json::json!({ "settings": "a" }))
));
assert!(!Arc::ptr_eq(
&a,
&data.rings_for(2, &serde_json::json!({ "settings": "a" }))
));
assert!(!Arc::ptr_eq(
&a,
&data.rings_for(1, &serde_json::json!({ "settings": "b" }))
));
for seed in 10..10 + RING_CACHE_LIMIT as i64 {
data.rings_for(seed, &serde_json::json!({ "settings": "a" }));
}
assert_eq!(data.ring_cache.lock().unwrap().len(), RING_CACHE_LIMIT);
assert!(!Arc::ptr_eq(
&a,
&data.rings_for(1, &serde_json::json!({ "settings": "a" }))
));
}
#[test]
fn parameter_reports_quantize_like_vanilla() {
let report = r#"{"biomes":[{"biome":"minecraft:plains","parameters":{
@@ -31,8 +31,9 @@ pub(super) struct StructureState {
/// Structure indices of each decoration step, in registry order.
pub(super) by_step: Vec<Vec<usize>>,
starts: Mutex<HashMap<(i32, i32), Starts>>,
/// Concentric ring positions, computed on first use.
rings: OnceLock<Rings>,
/// Concentric ring positions, computed on first use and shared with
/// later generators of the same seed and dimension.
rings: Arc<OnceLock<Rings>>,
/// Their biome searches while they are computed.
ring_work: OnceLock<RingWork>,
}
@@ -131,6 +132,7 @@ impl StructureState {
pub(super) fn new(
data: &Arc<GeneratorData>,
possible_biomes: &BTreeSet<BiomeId>,
rings: Arc<OnceLock<Rings>>,
) -> Result<Option<Self>, GeneratorError> {
let (Some(resources), Some(raw)) = (&data.structures, &data.structure_resources) else {
return Ok(None);
@@ -166,7 +168,7 @@ impl StructureState {
possible_sets,
by_step,
starts: Mutex::new(HashMap::new()),
rings: OnceLock::new(),
rings,
ring_work: OnceLock::new(),
}))
}
+6 -1
View File
@@ -1,6 +1,6 @@
# Horizon extras
Optional conveniences built into the client: zoom, a minimap, an FPS counter, a
Optional conveniences built into the client: fullbright, zoom, a minimap, an FPS counter, a
keystroke overlay, auto-reconnect, Mouse Tweaks-style inventory controls and
inventory sorting. **Every one is off by default**: a fresh
install looks and behaves exactly like vanilla 26.3, and turning an extra off
@@ -36,6 +36,11 @@ Horizon category in Controls, and adding one would put a non-vanilla mapping int
## The extras
### Fullbright (`fullbright`, default off)
- Displays blocks and entities with a fully bright lightmap, including in dark caves.
- Turning it off restores the normal lightmap using the current brightness,
time of day and effects. The brightness slider keeps its normal range.
### Zoom (`zoom`, default off)
- Hold the zoom key (default **Z**, unused by every vanilla 26.3 key mapping; C
is `key.saveToolbarActivator`) to zoom. The key does nothing while zoom is off.