Merge remote-tracking branch 'origin/main' into feat/terrain-lod
# Conflicts: # crates/horizon-client/src/gfx.rs # crates/horizon-client/src/graphics.rs
This commit is contained in:
@@ -737,6 +737,8 @@ pub struct Scene<'a> {
|
||||
pub struct BlockEntityRenderer {
|
||||
models: HashMap<&'static str, ModelPart>,
|
||||
kinds: Vec<Kind>,
|
||||
// Closed chest geometry: dimension lighting, chest part, horizontal facing.
|
||||
closed_chests: [[[Vec<Vertex>; 4]; 3]; 2],
|
||||
/// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`).
|
||||
pot_patterns: HashMap<String, String>,
|
||||
/// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock).
|
||||
@@ -817,6 +819,43 @@ impl BlockEntityRenderer {
|
||||
Ok(renderer)
|
||||
}
|
||||
fn new(models: HashMap<&'static str, ModelPart>, registry: &BlockRegistry) -> Self {
|
||||
let closed_chests = [false, true].map(|nether| {
|
||||
["chest", "double_chest_left", "double_chest_right"].map(|name| {
|
||||
[0.0f32, 90.0, 180.0, 270.0].map(|y_rot| {
|
||||
let mut vertices = Vec::new();
|
||||
if let Some(model) = models.get(name) {
|
||||
draw_part(
|
||||
model,
|
||||
"root",
|
||||
around(
|
||||
Mat4::from_rotation_y((-y_rot).to_radians()),
|
||||
Vec3::new(0.5, 0.0, 0.5),
|
||||
),
|
||||
&|name, p| {
|
||||
if name == "lid" || name == "lock" {
|
||||
p[3] = crate::block_entity_anim::chest_lid_x_rot(0.0);
|
||||
}
|
||||
},
|
||||
Paint {
|
||||
sprite: Rect {
|
||||
u0: 0.0,
|
||||
v0: 0.0,
|
||||
u1: 1.0,
|
||||
v1: 1.0,
|
||||
w: 16,
|
||||
h: 16,
|
||||
},
|
||||
tint: 0xFFFFFF,
|
||||
light: 0,
|
||||
lights: diffuse_lights(nether),
|
||||
},
|
||||
&mut vertices,
|
||||
);
|
||||
}
|
||||
vertices
|
||||
})
|
||||
})
|
||||
});
|
||||
let kinds = (0..registry.len() as u32)
|
||||
.map(|id| {
|
||||
registry.state(BlockStateId(id)).map_or(Kind::None, |s| {
|
||||
@@ -831,6 +870,7 @@ impl BlockEntityRenderer {
|
||||
Self {
|
||||
models,
|
||||
kinds,
|
||||
closed_chests,
|
||||
pot_patterns: HashMap::new(),
|
||||
visibility: None,
|
||||
}
|
||||
@@ -876,7 +916,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, false, out);
|
||||
self.render_one(scene, *pos, kind, base, packed, lights, false, true, out);
|
||||
}
|
||||
}
|
||||
/// One block entity at `pos` drawn under `base` with the given packed light
|
||||
@@ -892,7 +932,7 @@ impl BlockEntityRenderer {
|
||||
) {
|
||||
let kind = self.kind(state);
|
||||
let lights = diffuse_lights(scene.nether);
|
||||
self.render_one(scene, pos, kind, base, packed, lights, false, out);
|
||||
self.render_one(scene, pos, kind, base, packed, lights, false, false, out);
|
||||
}
|
||||
/// Whether this block state has a block-entity renderer here.
|
||||
pub fn renders(&self, state: u32) -> bool {
|
||||
@@ -915,6 +955,7 @@ impl BlockEntityRenderer {
|
||||
0xff,
|
||||
diffuse_lights(scene.nether),
|
||||
true,
|
||||
false,
|
||||
out,
|
||||
);
|
||||
crate::breaking::entity_geometry(&mut out[start..], origin);
|
||||
@@ -991,7 +1032,17 @@ 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, false, out);
|
||||
self.render_one(
|
||||
scene,
|
||||
[i32::MAX; 3],
|
||||
kind,
|
||||
base,
|
||||
packed,
|
||||
lights,
|
||||
false,
|
||||
false,
|
||||
out,
|
||||
);
|
||||
}
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -1004,6 +1055,7 @@ impl BlockEntityRenderer {
|
||||
packed: u8,
|
||||
lights: (Vec3, Vec3),
|
||||
crumbling: bool,
|
||||
world_chests: bool,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let sprite = |name: &str| scene.sprites.get(name).copied();
|
||||
@@ -1107,6 +1159,23 @@ impl BlockEntityRenderer {
|
||||
let l = scene.world.light(other[0], other[1], other[2]);
|
||||
packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15);
|
||||
}
|
||||
if world_chests && open == 0.0 {
|
||||
if let Some(paint) = paint(texture, 0xFFFFFF, packed) {
|
||||
let vertices = &self.closed_chests[usize::from(scene.nether)]
|
||||
[*part as usize][*y_rot as usize / 90];
|
||||
let origin = base.w_axis.truncate();
|
||||
out.extend(vertices.iter().map(|v| Vertex {
|
||||
pos: (Vec3::from_array(v.pos) + origin).to_array(),
|
||||
uv: [
|
||||
paint.sprite.u0 + (paint.sprite.u1 - paint.sprite.u0) * v.uv[0],
|
||||
paint.sprite.v0 + (paint.sprite.v1 - paint.sprite.v0) * v.uv[1],
|
||||
],
|
||||
light: paint.light,
|
||||
..*v
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let m = base
|
||||
* around(
|
||||
Mat4::from_rotation_y((-y_rot).to_radians()),
|
||||
@@ -1791,16 +1860,18 @@ mod tests {
|
||||
(
|
||||
name.to_owned(),
|
||||
Rect {
|
||||
u0: 0.0,
|
||||
v0: 0.0,
|
||||
u1: 1.0,
|
||||
v1: 1.0,
|
||||
u0: 0.25,
|
||||
v0: 0.125,
|
||||
u1: 0.375,
|
||||
v1: 0.25,
|
||||
w: 16,
|
||||
h: 16,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let cache_open = std::cell::Cell::new(0.0);
|
||||
let cache_lid = |_| cache_open.get();
|
||||
let mut scene = Scene {
|
||||
camera: DVec3::ZERO,
|
||||
orientation: Quat::IDENTITY,
|
||||
@@ -1817,6 +1888,56 @@ mod tests {
|
||||
banner: &|_| Vec::new(),
|
||||
glyph: &|_| (None, 0.0),
|
||||
};
|
||||
// Compare the cached world path with the original model renderer,
|
||||
// including atlas replacement, current light and animated fallback.
|
||||
scene.lid = &cache_lid;
|
||||
for nether in [false, true] {
|
||||
scene.nether = nether;
|
||||
for part in [ChestPart::Single, ChestPart::Left, ChestPart::Right] {
|
||||
for y_rot in [0.0, 90.0, 180.0, 270.0] {
|
||||
let kind = Kind::Chest {
|
||||
block: "chest".into(),
|
||||
texture: "entity/chest/normal",
|
||||
part,
|
||||
y_rot,
|
||||
double_with: None,
|
||||
};
|
||||
for (open, packed) in [(0.0, 0xF0), (0.0, 0x7F), (0.5, 0x7F)] {
|
||||
cache_open.set(open);
|
||||
let base = Mat4::from_translation(Vec3::new(3.25, -8.5, 12.75));
|
||||
let mut cached = Vec::new();
|
||||
let mut original = Vec::new();
|
||||
for (use_cache, out) in [(true, &mut cached), (false, &mut original)] {
|
||||
renderer.render_one(
|
||||
&scene,
|
||||
[0; 3],
|
||||
&kind,
|
||||
base,
|
||||
packed,
|
||||
diffuse_lights(nether),
|
||||
false,
|
||||
use_cache,
|
||||
out,
|
||||
);
|
||||
}
|
||||
assert!(!cached.is_empty());
|
||||
assert_eq!(cached.len(), original.len());
|
||||
for (a, b) in cached.iter().zip(&original) {
|
||||
assert!(
|
||||
(Vec3::from_array(a.pos) - Vec3::from_array(b.pos)).length() < 3e-6
|
||||
);
|
||||
assert_eq!(a.uv, b.uv);
|
||||
assert_eq!(a.color, b.color);
|
||||
assert_eq!(a.light, b.light);
|
||||
assert_eq!(a.normal, b.normal);
|
||||
assert_eq!(a.layer, b.layer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
scene.nether = false;
|
||||
scene.lid = &|_| 0.0;
|
||||
for state in 0..names.len() as u32 {
|
||||
let mut base = Vec::new();
|
||||
renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base);
|
||||
|
||||
@@ -8,6 +8,7 @@ pub mod block;
|
||||
pub mod codec;
|
||||
pub mod component;
|
||||
pub mod item;
|
||||
pub mod network;
|
||||
pub mod packrat;
|
||||
pub mod selector;
|
||||
pub mod snbt;
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! The command tree a server sends (ClientboundCommandsPacket) as a
|
||||
//! dispatcher the chat parses, colours and completes with
|
||||
//! (ClientPacketListener.handleCommands).
|
||||
//!
|
||||
//! The packet holds each argument's parser and its network properties. A
|
||||
//! node the client's own vanilla tree has at the same path takes that node's
|
||||
//! argument type and suggestion provider (the parsers' suggestion lists and
|
||||
//! the custom providers are the same code on both sides); any other node
|
||||
//! (another server's or a mod's) gets the type its parser and properties
|
||||
//! describe.
|
||||
use super::{ArgType, Dispatcher, Node, NodeKind, Suggests};
|
||||
use horizon_protocol::packets::play::{ARGUMENT_TYPES, ArgumentProperties, Commands};
|
||||
use std::{
|
||||
collections::{HashSet, VecDeque},
|
||||
sync::{Mutex, OnceLock},
|
||||
};
|
||||
|
||||
/// The command id of every executable node of a server's tree: the chat
|
||||
/// sends the command, the server runs it.
|
||||
pub const SERVER_COMMAND: &str = "server";
|
||||
|
||||
/// The dispatcher for a server's tree. `local` is the client's own tree
|
||||
/// (vanilla's), whose matching nodes lend their types and providers.
|
||||
pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher {
|
||||
let count = packet.nodes.len();
|
||||
let root = usize::try_from(packet.root)
|
||||
.ok()
|
||||
.filter(|&r| r < count)
|
||||
.unwrap_or(0);
|
||||
// The packet's root becomes node 0, the others follow in packet order.
|
||||
let index = |i: usize| -> usize {
|
||||
if i == root {
|
||||
0
|
||||
} else if i < root {
|
||||
i + 1
|
||||
} else {
|
||||
i
|
||||
}
|
||||
};
|
||||
let valid = |c: &i32| usize::try_from(*c).ok().filter(|&c| c < count);
|
||||
// The local node at the same path, found breadth first from the roots
|
||||
// along children (redirects are not paths of their own).
|
||||
let mut matched: Vec<Option<usize>> = vec![None; count];
|
||||
matched[root] = Some(0);
|
||||
let mut queue = VecDeque::from([root]);
|
||||
let mut seen = HashSet::from([root]);
|
||||
while let Some(n) = queue.pop_front() {
|
||||
for c in packet.nodes[n].children.iter().filter_map(valid) {
|
||||
if !seen.insert(c) {
|
||||
continue;
|
||||
}
|
||||
let node = &packet.nodes[c];
|
||||
matched[c] = matched[n].and_then(|l| {
|
||||
local.nodes[l].children.iter().copied().find(|&lc| {
|
||||
let ln = &local.nodes[lc];
|
||||
ln.name() == node.name
|
||||
&& matches!(
|
||||
(&ln.kind, node.kind),
|
||||
(NodeKind::Literal(_), 1) | (NodeKind::Argument { .. }, 2)
|
||||
)
|
||||
})
|
||||
});
|
||||
queue.push_back(c);
|
||||
}
|
||||
}
|
||||
let mut nodes = vec![None; count];
|
||||
for (i, node) in packet.nodes.iter().enumerate() {
|
||||
let local_node = matched[i].map(|l| &local.nodes[l]);
|
||||
let kind = match node.kind {
|
||||
1 => NodeKind::Literal(node.name.clone()),
|
||||
2 => {
|
||||
let ty = match local_node.map(|l| &l.kind) {
|
||||
Some(NodeKind::Argument { ty, .. }) => ty.clone(),
|
||||
_ => node
|
||||
.parser
|
||||
.as_ref()
|
||||
.map_or(ArgType::Word, |(id, props)| argument_type(*id, props)),
|
||||
};
|
||||
NodeKind::Argument {
|
||||
name: node.name.clone(),
|
||||
ty,
|
||||
}
|
||||
}
|
||||
_ => NodeKind::Root,
|
||||
};
|
||||
let suggests = match local_node {
|
||||
Some(l) => l.suggests.clone(),
|
||||
None => node.suggestions.as_deref().and_then(provider),
|
||||
};
|
||||
nodes[index(i)] = Some(Node {
|
||||
kind: if i == root { NodeKind::Root } else { kind },
|
||||
children: node.children.iter().filter_map(valid).map(index).collect(),
|
||||
command: node.executable.then_some(SERVER_COMMAND),
|
||||
redirect: node.redirect.as_ref().and_then(valid).map(index),
|
||||
// The server sent only what the player may use.
|
||||
permission: 0,
|
||||
suggests,
|
||||
});
|
||||
}
|
||||
let mut d = Dispatcher::new();
|
||||
if count > 0 {
|
||||
d.nodes = nodes.into_iter().flatten().collect();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// SuggestionProviders by id (`ask_server` asks the server; the client's
|
||||
/// own argument suggestions stand in for it).
|
||||
fn provider(id: &str) -> Option<Suggests> {
|
||||
match id {
|
||||
"minecraft:summonable_entities" => Some(Suggests::SummonableEntities),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A registry name kept for the life of the game (argument types hold
|
||||
/// `&'static str`): each distinct name is stored once.
|
||||
fn intern(name: &str) -> &'static str {
|
||||
static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
|
||||
let mut names = NAMES
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(&n) = names.get(name) {
|
||||
return n;
|
||||
}
|
||||
let n: &'static str = Box::leak(name.to_owned().into_boxed_str());
|
||||
names.insert(n);
|
||||
n
|
||||
}
|
||||
|
||||
/// The argument type a parser and its properties describe
|
||||
/// (ArgumentTypeInfo.Template.instantiate).
|
||||
pub fn argument_type(id: i32, props: &[u8]) -> ArgType {
|
||||
let Some(name) = usize::try_from(id).ok().and_then(|i| ARGUMENT_TYPES.get(i)) else {
|
||||
return ArgType::Word;
|
||||
};
|
||||
let p = ArgumentProperties::decode(id, props).unwrap_or(ArgumentProperties::None);
|
||||
let registry = || match &p {
|
||||
ArgumentProperties::Registry(r) => intern(r),
|
||||
_ => "",
|
||||
};
|
||||
match *name {
|
||||
"brigadier:bool" => ArgType::Bool,
|
||||
"brigadier:integer" => match p {
|
||||
ArgumentProperties::Integer { min, max } => ArgType::Integer {
|
||||
min: min.unwrap_or(i32::MIN),
|
||||
max: max.unwrap_or(i32::MAX),
|
||||
},
|
||||
_ => ArgType::Integer {
|
||||
min: i32::MIN,
|
||||
max: i32::MAX,
|
||||
},
|
||||
},
|
||||
// No long type of its own: a double over the same bounds reads
|
||||
// the same digits.
|
||||
"brigadier:long" => match p {
|
||||
ArgumentProperties::Long { min, max } => ArgType::Double {
|
||||
min: min.map_or(f64::MIN, |v| v as f64),
|
||||
max: max.map_or(f64::MAX, |v| v as f64),
|
||||
},
|
||||
_ => ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
},
|
||||
"brigadier:float" => match p {
|
||||
ArgumentProperties::Float { min, max } => ArgType::Float {
|
||||
min: min.unwrap_or(f32::MIN),
|
||||
max: max.unwrap_or(f32::MAX),
|
||||
},
|
||||
_ => ArgType::Float {
|
||||
min: f32::MIN,
|
||||
max: f32::MAX,
|
||||
},
|
||||
},
|
||||
"brigadier:double" => match p {
|
||||
ArgumentProperties::Double { min, max } => ArgType::Double {
|
||||
min: min.unwrap_or(f64::MIN),
|
||||
max: max.unwrap_or(f64::MAX),
|
||||
},
|
||||
_ => ArgType::Double {
|
||||
min: f64::MIN,
|
||||
max: f64::MAX,
|
||||
},
|
||||
},
|
||||
"brigadier:string" => match p {
|
||||
ArgumentProperties::String(1) => ArgType::Str,
|
||||
ArgumentProperties::String(2) => ArgType::Greedy,
|
||||
_ => ArgType::Word,
|
||||
},
|
||||
"minecraft:entity" => match p {
|
||||
ArgumentProperties::Entity {
|
||||
single,
|
||||
players_only,
|
||||
} => ArgType::Entity {
|
||||
single,
|
||||
players: players_only,
|
||||
},
|
||||
_ => ArgType::Entity {
|
||||
single: false,
|
||||
players: false,
|
||||
},
|
||||
},
|
||||
"minecraft:game_profile" => ArgType::GameProfile,
|
||||
"minecraft:block_pos" => ArgType::BlockPos,
|
||||
"minecraft:column_pos" => ArgType::ColumnPos,
|
||||
"minecraft:vec3" => ArgType::Vec3 { center: true },
|
||||
"minecraft:vec2" => ArgType::Vec2,
|
||||
"minecraft:block_state" => ArgType::BlockState,
|
||||
"minecraft:block_predicate" => ArgType::BlockPredicate,
|
||||
"minecraft:item_stack" => ArgType::Item,
|
||||
"minecraft:item_predicate" => ArgType::ItemPredicate,
|
||||
"minecraft:team_color" => ArgType::TeamColor,
|
||||
"minecraft:hex_color" => ArgType::HexColor,
|
||||
"minecraft:component" => ArgType::Component,
|
||||
"minecraft:style" => ArgType::Style,
|
||||
"minecraft:message" => ArgType::Message,
|
||||
"minecraft:nbt_compound_tag" => ArgType::Nbt,
|
||||
"minecraft:nbt_tag" => ArgType::NbtTag,
|
||||
"minecraft:nbt_path" => ArgType::NbtPath,
|
||||
"minecraft:objective" => ArgType::Objective,
|
||||
"minecraft:objective_criteria" => ArgType::Criteria,
|
||||
"minecraft:operation" => ArgType::Operation,
|
||||
"minecraft:particle" => ArgType::Particle,
|
||||
"minecraft:angle" => ArgType::Angle,
|
||||
"minecraft:rotation" => ArgType::Rotation,
|
||||
"minecraft:scoreboard_slot" => ArgType::ScoreboardSlot,
|
||||
"minecraft:score_holder" => ArgType::ScoreHolder {
|
||||
multiple: matches!(p, ArgumentProperties::ScoreHolder { multiple: true }),
|
||||
},
|
||||
"minecraft:swizzle" => ArgType::Swizzle,
|
||||
"minecraft:team" => ArgType::Team,
|
||||
"minecraft:item_slot" => ArgType::Slot,
|
||||
"minecraft:item_slots" => ArgType::Slots,
|
||||
"minecraft:resource_location" => ArgType::Id("none"),
|
||||
"minecraft:function" => ArgType::Function,
|
||||
"minecraft:entity_anchor" => ArgType::Anchor,
|
||||
"minecraft:int_range" => ArgType::IntRange,
|
||||
"minecraft:float_range" => ArgType::FloatRange,
|
||||
"minecraft:dimension" => ArgType::Dimension,
|
||||
"minecraft:gamemode" => ArgType::GameMode,
|
||||
"minecraft:time" => ArgType::Time {
|
||||
min: match p {
|
||||
ArgumentProperties::Time { min } => min,
|
||||
_ => 0,
|
||||
},
|
||||
},
|
||||
"minecraft:resource_or_tag" => ArgType::ResOrTag(registry()),
|
||||
"minecraft:resource_or_tag_key" => ArgType::ResOrTagKey(registry()),
|
||||
"minecraft:resource" => ArgType::Res(registry()),
|
||||
"minecraft:resource_key" => ArgType::ResKey(registry()),
|
||||
"minecraft:resource_selector" => ArgType::ResourceSelector(registry()),
|
||||
"minecraft:template_mirror" => ArgType::Enum(&["none", "front_back", "left_right"]),
|
||||
"minecraft:template_rotation" => {
|
||||
ArgType::Enum(&["none", "clockwise_90", "180", "counterclockwise_90"])
|
||||
}
|
||||
"minecraft:heightmap" => ArgType::Enum(&[
|
||||
"world_surface",
|
||||
"motion_blocking",
|
||||
"motion_blocking_no_leaves",
|
||||
"ocean_floor",
|
||||
]),
|
||||
"minecraft:swing_animation" => ArgType::Enum(&["none", "whack", "stab"]),
|
||||
"minecraft:loot_table" => ArgType::ResourceOrId("minecraft:loot_table"),
|
||||
"minecraft:loot_predicate" => ArgType::ResourceOrId("minecraft:predicate"),
|
||||
"minecraft:loot_modifier" => ArgType::ResourceOrId("minecraft:item_modifier"),
|
||||
"minecraft:context_float_provider" => {
|
||||
ArgType::ResourceOrId("minecraft:context_float_provider")
|
||||
}
|
||||
"minecraft:context_int_provider" => ArgType::ResourceOrId("minecraft:context_int_provider"),
|
||||
"minecraft:slot_source" => ArgType::SlotSource,
|
||||
"minecraft:dialog" => ArgType::ResourceOrId("minecraft:dialog"),
|
||||
"minecraft:feature" => ArgType::ResourceOrId("minecraft:worldgen/feature"),
|
||||
"minecraft:uuid" => ArgType::Uuid,
|
||||
_ => ArgType::Word,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_protocol::{
|
||||
buf::{Codec, Reader, Writer},
|
||||
packets::play::CommandNode,
|
||||
};
|
||||
|
||||
fn literal(name: &str, children: Vec<i32>, executable: bool) -> CommandNode {
|
||||
CommandNode {
|
||||
kind: 1,
|
||||
executable,
|
||||
restricted: false,
|
||||
children,
|
||||
redirect: None,
|
||||
name: name.into(),
|
||||
parser: None,
|
||||
suggestions: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn argument(name: &str, parser: &str, props: Vec<u8>, executable: bool) -> CommandNode {
|
||||
let id = ARGUMENT_TYPES.iter().position(|p| *p == parser).unwrap() as i32;
|
||||
CommandNode {
|
||||
kind: 2,
|
||||
executable,
|
||||
restricted: false,
|
||||
children: Vec::new(),
|
||||
redirect: None,
|
||||
name: name.into(),
|
||||
parser: Some((id, props)),
|
||||
suggestions: Some("minecraft:ask_server".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A tree with the root last (as vanilla's numbering need not put it
|
||||
/// first), a vanilla command and one the client does not know.
|
||||
fn packet() -> Commands {
|
||||
let mut range = Writer::new();
|
||||
range.u8(3);
|
||||
range.i32(1);
|
||||
range.i32(64);
|
||||
Commands {
|
||||
nodes: vec![
|
||||
literal("give", vec![2], false),
|
||||
literal("warp", vec![3], false),
|
||||
argument("targets", "minecraft:entity", vec![2], false),
|
||||
argument("count", "brigadier:integer", range.data, true),
|
||||
CommandNode {
|
||||
kind: 0,
|
||||
executable: false,
|
||||
restricted: false,
|
||||
children: vec![0, 1],
|
||||
redirect: None,
|
||||
name: String::new(),
|
||||
parser: None,
|
||||
suggestions: None,
|
||||
},
|
||||
],
|
||||
root: 4,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn argument_nodes_round_trip() {
|
||||
let p = packet();
|
||||
let mut w = Writer::new();
|
||||
Commands::write(&p, &mut w);
|
||||
let back = Commands::read(&mut Reader::new(&w.data)).unwrap();
|
||||
assert_eq!(back, p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_tree_becomes_a_dispatcher() {
|
||||
let local = super::super::vanilla::dispatcher();
|
||||
let d = from_packet(&packet(), local);
|
||||
assert!(matches!(d.nodes[0].kind, NodeKind::Root));
|
||||
let warp = d.find("warp").expect("warp");
|
||||
let count = d.nodes[warp].children[0];
|
||||
match &d.nodes[count].kind {
|
||||
NodeKind::Argument {
|
||||
ty: ArgType::Integer { min, max },
|
||||
..
|
||||
} => assert_eq!((*min, *max), (1, 64)),
|
||||
other => panic!("count is {other:?}"),
|
||||
}
|
||||
assert_eq!(d.nodes[count].command, Some(SERVER_COMMAND));
|
||||
// `give <targets>` is vanilla's: it keeps the client's type.
|
||||
let give = d.find("give").expect("give");
|
||||
let targets = d.nodes[give].children[0];
|
||||
assert!(matches!(
|
||||
d.nodes[targets].kind,
|
||||
NodeKind::Argument {
|
||||
ty: ArgType::Entity {
|
||||
single: false,
|
||||
players: true
|
||||
},
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_argument_type_decodes() {
|
||||
for (id, name) in ARGUMENT_TYPES.iter().enumerate() {
|
||||
let mut w = Writer::new();
|
||||
match *name {
|
||||
"brigadier:integer" | "brigadier:long" | "brigadier:float" | "brigadier:double" => {
|
||||
w.u8(0)
|
||||
}
|
||||
"brigadier:string" => w.varint(2),
|
||||
"minecraft:entity" | "minecraft:score_holder" => w.u8(1),
|
||||
"minecraft:time" => w.i32(0),
|
||||
n if n.starts_with("minecraft:resource") && n != "minecraft:resource_location" => {
|
||||
w.string("minecraft:item")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let mut r = Reader::new(&w.data);
|
||||
ArgumentProperties::read(&mut r, id as i32).unwrap();
|
||||
assert_eq!(r.remaining(), 0, "{name}");
|
||||
let _ = argument_type(id as i32, &w.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@ pub struct Furnace {
|
||||
pub cooking_total: i32,
|
||||
pub speed: f32,
|
||||
}
|
||||
/// A hopper's slots: the only plain container with five.
|
||||
pub const HOPPER_SLOTS: usize = 5;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum BlockEntity {
|
||||
Chest(Vec<Option<ItemStack>>),
|
||||
@@ -242,7 +245,7 @@ impl BlockEntity {
|
||||
let size = match name {
|
||||
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
|
||||
n if n.ends_with("copper_chest") => 27,
|
||||
"minecraft:hopper" => 5,
|
||||
"minecraft:hopper" => HOPPER_SLOTS,
|
||||
"minecraft:dispenser" | "minecraft:dropper" => 9,
|
||||
n if n.ends_with("shulker_box") => 27,
|
||||
_ => return None,
|
||||
@@ -270,7 +273,7 @@ impl BlockEntity {
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Chest(items) => match items.len() {
|
||||
5 => "minecraft:hopper",
|
||||
HOPPER_SLOTS => "minecraft:hopper",
|
||||
9 => "minecraft:dispenser",
|
||||
_ => "minecraft:chest",
|
||||
},
|
||||
|
||||
@@ -71,6 +71,7 @@ mod lan_trading;
|
||||
mod lan_waypoints;
|
||||
mod leads;
|
||||
mod level_particles;
|
||||
mod levels;
|
||||
mod lightning;
|
||||
mod llamas;
|
||||
mod loom;
|
||||
@@ -196,7 +197,12 @@ use horizon_world::{
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU32, Ordering},
|
||||
mpsc::{Receiver, TryRecvError},
|
||||
},
|
||||
thread::JoinHandle,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use winit::{
|
||||
@@ -978,8 +984,14 @@ struct Game<'a> {
|
||||
world_root: PathBuf,
|
||||
/// A player carried through a portal, re-placed once the destination loads.
|
||||
travelling: Option<(PlayerMotion, Vec3)>,
|
||||
/// A server's lone player on its way to another level.
|
||||
server_trip: Option<server_travel::Trip>,
|
||||
/// A server's players on their way to another level, each waiting for
|
||||
/// the destination to load around them.
|
||||
server_trips: Vec<server_travel::Trip>,
|
||||
/// A server's levels other than the one in place (game/levels.rs).
|
||||
levels: levels::Levels,
|
||||
/// Which pass of a server tick runs (`tick_server`): the first one reads
|
||||
/// the network, the last one ends the players' tick.
|
||||
level_pass: levels::Pass,
|
||||
/// Nether portals: the player's, items' and mobs' (game/nether_portal.rs).
|
||||
portals: nether_portal::Portals,
|
||||
/// The pending travel goes through an End portal (EndPortalBlock destinations).
|
||||
@@ -1165,7 +1177,7 @@ struct Game<'a> {
|
||||
tab_list: horizon_client::tab_list::TabList,
|
||||
subtitles: subtitle_hud::SubtitleState,
|
||||
adv: advancements::AdvState,
|
||||
restore_player_environment: bool,
|
||||
restore_player_state: bool,
|
||||
stats_ui: stats_screen::StatsUi,
|
||||
adv_ui: advancements_screen::AdvUi,
|
||||
camera_type: perspective::CameraType,
|
||||
@@ -1173,7 +1185,7 @@ struct Game<'a> {
|
||||
/// The local player as a model (third person, the inventory).
|
||||
player_model: Option<Mob>,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
enum Dim {
|
||||
Overworld,
|
||||
Nether,
|
||||
@@ -3089,10 +3101,7 @@ impl Game<'_> {
|
||||
};
|
||||
let mut player = PlayerMotion::new(self.motion, feet)?;
|
||||
player.yaw = self.yaw;
|
||||
player.load_environment_once(
|
||||
&mut self.restore_player_environment,
|
||||
self.level.player_extra.as_ref(),
|
||||
);
|
||||
player.load_saved_state_once(&mut self.restore_player_state, &self.level)?;
|
||||
let spectator = self.mode == horizon_client::command::args::GameMode::Spectator;
|
||||
player.may_fly = self.creative || spectator;
|
||||
player.invulnerable = self.creative || spectator;
|
||||
@@ -3108,10 +3117,12 @@ impl Game<'_> {
|
||||
.get(&s.item)
|
||||
.is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage))
|
||||
});
|
||||
if self.level.health > 0.0 && self.ticks < 2 {
|
||||
player.set_health(self.level.health, false)?;
|
||||
player.health.food.food = self.level.food;
|
||||
player.health.food.saturation = self.level.saturation;
|
||||
// A saved death already dropped inventory/XP and counted the death.
|
||||
if player.health.dead_or_dying() {
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.died_at = Some(Instant::now());
|
||||
self.ui.death_text = None;
|
||||
self.capture(false);
|
||||
}
|
||||
self.previous_position = feet;
|
||||
self.player = Some(player);
|
||||
@@ -3689,6 +3700,11 @@ impl Game<'_> {
|
||||
) || self.book.is_some())
|
||||
}
|
||||
fn capture(&mut self, capture: bool) {
|
||||
// A guest's action (`as_guest`) opens and closes screens on the
|
||||
// guest's own client: the window's pointer stays the host's (#687).
|
||||
if self.lan_acting.is_some() {
|
||||
return;
|
||||
}
|
||||
// MouseHandler.grabMouse never captures an inactive window.
|
||||
if capture && !self.focused {
|
||||
return;
|
||||
@@ -3714,10 +3730,7 @@ impl Game<'_> {
|
||||
/// LevelLoadingScreen.onClose -> Gui.setScreen(null) -> grabMouse.
|
||||
fn capture_loaded_world(&mut self) {
|
||||
// Loading may finish after focus was lost or another screen opened.
|
||||
if self.title.is_none()
|
||||
&& self.screen == Screen::Playing
|
||||
&& !self.remote.as_ref().is_some_and(|r| r.chat_input.is_some())
|
||||
{
|
||||
if self.title.is_none() && self.screen == Screen::Playing {
|
||||
self.capture(true);
|
||||
}
|
||||
}
|
||||
@@ -5607,6 +5620,9 @@ impl Game<'_> {
|
||||
)
|
||||
};
|
||||
let visible = r.block_entities().filter(|(p, state)| {
|
||||
if !self.res.block_entity_render.renders(*state) {
|
||||
return false;
|
||||
}
|
||||
off_screen(*state)
|
||||
|| view.is_none_or(|v| {
|
||||
let o =
|
||||
@@ -6256,7 +6272,7 @@ impl Game<'_> {
|
||||
self.bosses = Default::default();
|
||||
reset_world_progress(&mut self.adv, &mut self.stats);
|
||||
self.prefetch_advancement_tree();
|
||||
self.restore_player_environment = true;
|
||||
self.restore_player_state = true;
|
||||
// RandomSequences: the world's data/minecraft/random_sequences.dat.
|
||||
self.rand_sequences =
|
||||
horizon_client::save::read_dat(&save_root.join("data/minecraft/random_sequences.dat"))
|
||||
@@ -7783,27 +7799,13 @@ impl Game<'_> {
|
||||
pack: &PackResources,
|
||||
atlas: &HudAtlas,
|
||||
) -> Result<Renderer> {
|
||||
let assets = &pack.assets;
|
||||
let mut renderer = pollster::block_on(Renderer::new(
|
||||
build_renderer(
|
||||
window,
|
||||
self.options.offscreen,
|
||||
&assets.pixels,
|
||||
assets.sprite_size,
|
||||
assets.sprite_minimum_size,
|
||||
assets.texture_layers,
|
||||
&assets.sprite_mips,
|
||||
&assets.animations,
|
||||
(&atlas.pixels, atlas.width, atlas.height),
|
||||
(&pack.forcefield.2, pack.forcefield.0),
|
||||
&pack.panorama,
|
||||
pack,
|
||||
atlas,
|
||||
self.renderer.as_ref(),
|
||||
))?;
|
||||
renderer.hud.fire_animations = atlas
|
||||
.fire_animations
|
||||
.iter()
|
||||
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
|
||||
.collect();
|
||||
Ok(renderer)
|
||||
)
|
||||
}
|
||||
fn apply_settings(&mut self) {
|
||||
if let Some(r) = &self.renderer {
|
||||
@@ -8464,18 +8466,10 @@ impl Game<'_> {
|
||||
if self.remote.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
self.streaming.save(&mut self.world, wait);
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
|
||||
self.save
|
||||
.save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?;
|
||||
if wait {
|
||||
self.save.flush();
|
||||
}
|
||||
self.save_entities(wait)?;
|
||||
self.save_level(wait)?;
|
||||
self.save_parked_levels(wait)?;
|
||||
self.save_maps();
|
||||
self.save_random_sequences();
|
||||
self.save_raids();
|
||||
self.save_fight();
|
||||
self.save_wandering_trader();
|
||||
self.save_portal_arrivals();
|
||||
@@ -8492,6 +8486,20 @@ impl Game<'_> {
|
||||
self.message = Some(("Saved the game".into(), Instant::now()));
|
||||
Ok(())
|
||||
}
|
||||
/// Save the level in place: its changed chunks, its entities and its raids.
|
||||
fn save_level(&mut self, wait: bool) -> Result<()> {
|
||||
self.streaming.save(&mut self.world, wait);
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
|
||||
self.save
|
||||
.save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?;
|
||||
if wait {
|
||||
self.save.flush();
|
||||
}
|
||||
self.save_entities(wait)?;
|
||||
self.save_raids();
|
||||
Ok(())
|
||||
}
|
||||
fn render(&mut self) -> Result<bool> {
|
||||
self.poll_shader_pack();
|
||||
let Some(size) = self
|
||||
@@ -9756,9 +9764,6 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.station_text(event.text.as_deref(), backspace);
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => {
|
||||
self.remote_chat_key(&event)
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.screen == Screen::WorldOptions
|
||||
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
|
||||
@@ -9865,7 +9870,6 @@ impl ApplicationHandler for Game<'_> {
|
||||
&& self.title.is_none()
|
||||
&& self.sign_edit.is_none()
|
||||
&& self.book.is_none()
|
||||
&& !self.remote_chat_open()
|
||||
{
|
||||
let turn = |k| f32::from(u8::from(self.keys.contains(&k)));
|
||||
let secs = elapsed.as_secs_f32().min(0.1);
|
||||
@@ -10281,7 +10285,9 @@ impl<'a> Game<'a> {
|
||||
dim: Dim::Overworld,
|
||||
world_root: PathBuf::new(),
|
||||
travelling: None,
|
||||
server_trip: None,
|
||||
server_trips: Vec::new(),
|
||||
levels: Default::default(),
|
||||
level_pass: Default::default(),
|
||||
portals: Default::default(),
|
||||
end_travel: false,
|
||||
respawn_config: None,
|
||||
@@ -10404,7 +10410,7 @@ impl<'a> Game<'a> {
|
||||
tab_list: Default::default(),
|
||||
subtitles: Default::default(),
|
||||
adv: Default::default(),
|
||||
restore_player_environment: true,
|
||||
restore_player_state: true,
|
||||
stats_ui: Default::default(),
|
||||
adv_ui: Default::default(),
|
||||
camera_type: Default::default(),
|
||||
@@ -10414,41 +10420,83 @@ impl<'a> Game<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run() -> Result<()> {
|
||||
let Some(mut options) = Options::read()? else {
|
||||
return Ok(());
|
||||
};
|
||||
if options.dedicated.is_some() && !dedicated::preflight(&mut options)? {
|
||||
return Ok(());
|
||||
/// The data the background loader produces for `Game::new`.
|
||||
struct Loaded {
|
||||
root: PathBuf,
|
||||
pack_error: Option<String>,
|
||||
resources: Resources,
|
||||
pack: PackResources,
|
||||
atlas: HudAtlas,
|
||||
}
|
||||
|
||||
/// The loader's checkpoints, in order; the loading screen reports them.
|
||||
const STAGES: u32 = 9;
|
||||
const STAGE_LINES: [&str; 9] = [
|
||||
"Loading assets",
|
||||
"Loading block facts",
|
||||
"Loading items",
|
||||
"Loading biomes",
|
||||
"Loading pack tables",
|
||||
"Loading atlas",
|
||||
"Loading collision",
|
||||
"Loading resources",
|
||||
"Starting audio",
|
||||
];
|
||||
|
||||
/// The background loader's checkpoint, read by the loading screen each frame.
|
||||
#[derive(Clone)]
|
||||
struct Progress(Arc<AtomicU32>);
|
||||
impl Progress {
|
||||
fn new() -> Self {
|
||||
Self(Arc::new(AtomicU32::new(0)))
|
||||
}
|
||||
let started = Instant::now();
|
||||
horizon_client::spans::enable(options.spikes.is_some());
|
||||
let vanilla_root = options.resources.clone();
|
||||
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
|
||||
// Snapshots of derived tables live in the game folder, never beside the
|
||||
// shared resources.
|
||||
Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache"));
|
||||
fn set(&self, stage: u32) {
|
||||
self.0.store(stage, Ordering::Relaxed);
|
||||
}
|
||||
fn fraction(&self) -> f32 {
|
||||
self.0.load(Ordering::Relaxed) as f32 / (STAGES - 1) as f32
|
||||
}
|
||||
fn line(&self) -> &'static str {
|
||||
STAGE_LINES[(self.0.load(Ordering::Relaxed) as usize).min(STAGE_LINES.len() - 1)]
|
||||
}
|
||||
}
|
||||
|
||||
/// Harness and dedicated runs keep the fully-synchronous startup so their
|
||||
/// output stays byte-identical; only an ordinary launch shows the window first.
|
||||
fn synchronous_startup(options: &Options) -> bool {
|
||||
let classic = std::env::var("HORIZON_MENU_STYLE").ok().as_deref() == Some("classic");
|
||||
options.frames.is_some()
|
||||
|| options.world_frames.is_some()
|
||||
|| options.benchmark.is_some()
|
||||
|| options.control.is_some()
|
||||
|| options.dedicated.is_some()
|
||||
|| classic
|
||||
|| std::env::var_os("HORIZON_DISPENSE_FIXTURE").is_some()
|
||||
|| std::env::var_os("HORIZON_SCULK_FIXTURE").is_some()
|
||||
|| std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some()
|
||||
|| std::env::var_os("HORIZON_NET_REPORT").is_some()
|
||||
}
|
||||
|
||||
/// The current loading sequence, unchanged, as a function so the synchronous
|
||||
/// launch can run it on the main thread and an ordinary launch on a worker.
|
||||
/// `on_stage` reports [`STAGES`] checkpoints to the loading screen.
|
||||
fn load_resources(
|
||||
mut root: PathBuf,
|
||||
vanilla_root: &std::path::Path,
|
||||
settings: &Settings,
|
||||
started: Instant,
|
||||
on_stage: &(dyn Fn(u32) + Sync),
|
||||
) -> Result<Loaded> {
|
||||
let mut pack_error = None;
|
||||
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs)
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!("Horizon: resource packs not applied: {e}");
|
||||
pack_error = Some(e.to_string());
|
||||
vanilla_root.clone()
|
||||
});
|
||||
options.resources = mods::content_root(
|
||||
&options.resources,
|
||||
&early_settings.mods.enabled,
|
||||
&options.dev_mods,
|
||||
);
|
||||
let assets = match Assets::load(&options.resources) {
|
||||
let assets = match Assets::load(&root) {
|
||||
Ok(assets) => assets,
|
||||
// Minecraft.rollbackResourcePacks: the packs break loading, start
|
||||
// with the game's own resources.
|
||||
Err(e) if options.resources != vanilla_root => {
|
||||
Err(e) if root != vanilla_root => {
|
||||
log::warn!("Horizon: resource packs failed to load ({e}); using the default resources");
|
||||
pack_error = Some(e.to_string());
|
||||
options.resources = vanilla_root.clone();
|
||||
Assets::load(&vanilla_root)?
|
||||
root = vanilla_root.to_path_buf();
|
||||
Assets::load(vanilla_root)?
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(format!(
|
||||
@@ -10457,9 +10505,9 @@ pub fn run() -> Result<()> {
|
||||
.into());
|
||||
}
|
||||
};
|
||||
let root = options.resources.clone();
|
||||
let assets = Arc::new(assets);
|
||||
log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32());
|
||||
on_stage(0);
|
||||
let behaviour_json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new(
|
||||
std::fs::File::open(root.join("block-behaviours.json"))?,
|
||||
))?;
|
||||
@@ -10468,23 +10516,28 @@ pub fn run() -> Result<()> {
|
||||
let mob_data = horizon_client::mobs::MobData::load(&root, &facts);
|
||||
horizon_client::mobs::trial_spawner::load_registry(&root);
|
||||
log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32());
|
||||
on_stage(1);
|
||||
let items = Items::load(&root, assets.registry, &facts)?;
|
||||
log::info!("load items: {:.2}s", started.elapsed().as_secs_f32());
|
||||
on_stage(2);
|
||||
let recipes = Recipes::load(&root, &items)?;
|
||||
let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?;
|
||||
let biomes = Arc::new(Biomes::load(&root)?);
|
||||
let environment = Environment::load(&root)?;
|
||||
log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32());
|
||||
on_stage(3);
|
||||
let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?);
|
||||
let pack = PackResources::load(&root, assets.clone(), &facts, biomes.clone(), light)?;
|
||||
log::info!("load pack tables: {:.2}s", started.elapsed().as_secs_f32());
|
||||
on_stage(4);
|
||||
let atlas = HudAtlas::build(&root)?;
|
||||
horizon_client::ui::load_metadata(&root);
|
||||
horizon_client::lang::set(horizon_client::lang::Language::load(
|
||||
&[&root],
|
||||
&early_settings.language,
|
||||
&settings.language,
|
||||
));
|
||||
log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32());
|
||||
on_stage(5);
|
||||
let registry_owner = assets.clone();
|
||||
let collision = collisions::load(&root, registry_owner.registry)?;
|
||||
let motion = MotionResources::load(&root, ®istry_owner)?;
|
||||
@@ -10492,7 +10545,8 @@ pub fn run() -> Result<()> {
|
||||
"load collision+motion: {:.2}s",
|
||||
started.elapsed().as_secs_f32()
|
||||
);
|
||||
let threads = early_settings.horizon.worker_threads();
|
||||
on_stage(6);
|
||||
let threads = settings.horizon.worker_threads();
|
||||
log::info!(
|
||||
"Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads",
|
||||
started.elapsed().as_secs_f32(),
|
||||
@@ -10501,16 +10555,11 @@ pub fn run() -> Result<()> {
|
||||
biomes.list.len(),
|
||||
threads
|
||||
);
|
||||
let audio = if options.dedicated.is_some() {
|
||||
Audio::silent(&root)
|
||||
} else {
|
||||
Audio::new(&root)
|
||||
};
|
||||
let stations = horizon_client::stations::StationData::load(&root, &items);
|
||||
let animate =
|
||||
horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?;
|
||||
let fog = horizon_client::fog::FogTables::load(&root, &biomes);
|
||||
let resources = Arc::new(Resources {
|
||||
let resources = Resources {
|
||||
stations,
|
||||
facts,
|
||||
items,
|
||||
@@ -10547,11 +10596,159 @@ pub fn run() -> Result<()> {
|
||||
player_type: perspective::player_type(&root),
|
||||
player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main")
|
||||
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
|
||||
});
|
||||
};
|
||||
// Both inputs are needed only while constructing the behaviour tables.
|
||||
// Release their owned JSON/Arc buffers before entering the long-lived game loop.
|
||||
drop(gameplay_projection);
|
||||
drop(behaviour_json);
|
||||
on_stage(7);
|
||||
Ok(Loaded {
|
||||
root,
|
||||
pack_error,
|
||||
resources,
|
||||
pack,
|
||||
atlas,
|
||||
})
|
||||
}
|
||||
|
||||
/// The renderer from a pack's block sprites, its shared atlas and its border
|
||||
/// texture; `previous` shares the device and window surface with an old one.
|
||||
fn build_renderer(
|
||||
window: Arc<Window>,
|
||||
offscreen: bool,
|
||||
pack: &PackResources,
|
||||
atlas: &HudAtlas,
|
||||
previous: Option<&Renderer>,
|
||||
) -> Result<Renderer> {
|
||||
let assets = &pack.assets;
|
||||
let mut renderer = pollster::block_on(Renderer::new(
|
||||
window,
|
||||
offscreen,
|
||||
&assets.pixels,
|
||||
assets.sprite_size,
|
||||
assets.sprite_minimum_size,
|
||||
assets.texture_layers,
|
||||
&assets.sprite_mips,
|
||||
&assets.animations,
|
||||
(&atlas.pixels, atlas.width, atlas.height),
|
||||
(&pack.forcefield.2, pack.forcefield.0),
|
||||
&pack.panorama,
|
||||
previous,
|
||||
))?;
|
||||
renderer.hud.fire_animations = atlas
|
||||
.fire_animations
|
||||
.iter()
|
||||
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
|
||||
.collect();
|
||||
Ok(renderer)
|
||||
}
|
||||
|
||||
/// The loading screen's renderer: the real HUD atlas and font over one opaque
|
||||
/// white block-sprite layer, an empty border texture and an empty panorama.
|
||||
fn loading_renderer(
|
||||
window: Arc<Window>,
|
||||
offscreen: bool,
|
||||
atlas: Option<&HudAtlas>,
|
||||
) -> Result<Renderer> {
|
||||
static FORCEFIELD: [u8; 4] = [0; 4];
|
||||
static EMPTY_HUD: [u8; 4] = [0, 0, 0, 255];
|
||||
let panorama = horizon_client::gfx::panorama::Faces {
|
||||
size: 1,
|
||||
pixels: [0u8; 4].repeat(6),
|
||||
};
|
||||
let (pixels, width, height) = match atlas {
|
||||
Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height),
|
||||
None => (EMPTY_HUD.as_slice(), 1, 1),
|
||||
};
|
||||
let mut renderer = pollster::block_on(Renderer::new(
|
||||
window,
|
||||
offscreen,
|
||||
&[255, 255, 255, 255],
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
&[],
|
||||
&[],
|
||||
(pixels, width, height),
|
||||
(&FORCEFIELD[..], 1),
|
||||
&panorama,
|
||||
None,
|
||||
))?;
|
||||
if let Some(atlas) = atlas {
|
||||
renderer.hud.fire_animations = atlas
|
||||
.fire_animations
|
||||
.iter()
|
||||
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
|
||||
.collect();
|
||||
}
|
||||
Ok(renderer)
|
||||
}
|
||||
|
||||
/// A title-shaped frame: black clear and panorama, only the HUD is drawn.
|
||||
fn loading_frame(hud: &HudBatch) -> Frame<'_> {
|
||||
Frame {
|
||||
camera: glam::DVec3::new(0.5, 100.0, 0.5),
|
||||
yaw: 0.0,
|
||||
pitch: 10.0,
|
||||
fov_degrees: 85.0,
|
||||
bob: glam::Mat4::IDENTITY,
|
||||
sky: horizon_client::environment::Sky::default(),
|
||||
distance: 12.0,
|
||||
depth_far: 1000.0,
|
||||
underwater: false,
|
||||
cave_culling: false,
|
||||
title: true,
|
||||
skybox: false,
|
||||
end_sky: false,
|
||||
environment_fog: None,
|
||||
water_fog: [0.0; 3],
|
||||
fog: None,
|
||||
dark_disc: false,
|
||||
outline: Vec::new(),
|
||||
outline_after_terrain: false,
|
||||
debug_lines: &[],
|
||||
debug_lines_on_top: &[],
|
||||
debug_crosshair: &[],
|
||||
hud,
|
||||
nether_lighting: false,
|
||||
entities: &[],
|
||||
clouds: None,
|
||||
additive: &[],
|
||||
see_through: &[],
|
||||
celestial: &[],
|
||||
hand: &[],
|
||||
hand_fov_degrees: 70.0,
|
||||
screen: &[],
|
||||
border: None,
|
||||
game_time: 0.0,
|
||||
shader_game_time: 0.0,
|
||||
end_portal_sprites: [[0.0; 4]; 2],
|
||||
crumbling_sprite: [0.0; 4],
|
||||
ticks: 0,
|
||||
darkness: (0.0, 0.0),
|
||||
night_vision: 0.0,
|
||||
block_flicker: 0.0,
|
||||
post: None,
|
||||
menu_blur: None,
|
||||
shader: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The post-load setup once the resources are ready: `Game::new` and the
|
||||
/// options, packs, mods, control socket, benchmark and world selection the
|
||||
/// old `run` did after loading. `None` means a harness or dedicated run
|
||||
/// finished here instead.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn start_game<'a>(
|
||||
res: &'a Arc<Resources>,
|
||||
pack: PackResources,
|
||||
atlas: HudAtlas,
|
||||
options: Options,
|
||||
pack_error: Option<String>,
|
||||
audio: Audio,
|
||||
vanilla_root: PathBuf,
|
||||
started: Instant,
|
||||
) -> Result<Option<Game<'a>>> {
|
||||
let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
|
||||
horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
|
||||
// Scripted and frame-limited runs (the parity harnesses) see vanilla's
|
||||
@@ -10564,7 +10761,7 @@ pub fn run() -> Result<()> {
|
||||
if let Some(d) = options.distance_override {
|
||||
settings.render_distance = d;
|
||||
}
|
||||
let mut game = Game::new(&resources, pack, atlas, options, settings, audio)?;
|
||||
let mut game = Game::new(res, pack, atlas, options, settings, audio)?;
|
||||
game.ui.vanilla_root = vanilla_root;
|
||||
if let Some(error) = pack_error {
|
||||
game.open_options_at(true, horizon_client::options_ui::Page::Packs);
|
||||
@@ -10614,13 +10811,16 @@ pub fn run() -> Result<()> {
|
||||
);
|
||||
}
|
||||
if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") {
|
||||
return game.dispense_fixture(&spec);
|
||||
game.dispense_fixture(&spec)?;
|
||||
return Ok(None);
|
||||
}
|
||||
if let Ok(spec) = std::env::var("HORIZON_SCULK_FIXTURE") {
|
||||
return game.sculk_fixture(&spec);
|
||||
game.sculk_fixture(&spec)?;
|
||||
return Ok(None);
|
||||
}
|
||||
if game.options.dedicated.is_some() {
|
||||
return game.run_dedicated();
|
||||
game.run_dedicated()?;
|
||||
return Ok(None);
|
||||
}
|
||||
match game.options.world.clone() {
|
||||
_ if game.options.server.is_some() => {
|
||||
@@ -10630,7 +10830,8 @@ pub fn run() -> Result<()> {
|
||||
);
|
||||
game.connect_server(&address, &name)?;
|
||||
if let Some(report) = std::env::var_os("HORIZON_NET_REPORT") {
|
||||
return game.run_net_harness(report.as_ref());
|
||||
game.run_net_harness(report.as_ref())?;
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Some(folder) => {
|
||||
@@ -10656,9 +10857,13 @@ pub fn run() -> Result<()> {
|
||||
std::env::var_os("HORIZON_COMMAND_SCRIPT"),
|
||||
std::env::var_os("HORIZON_COMMAND_OUTPUT"),
|
||||
) {
|
||||
return game.run_command_harness(script.as_ref(), output.as_ref());
|
||||
game.run_command_harness(script.as_ref(), output.as_ref())?;
|
||||
return Ok(None);
|
||||
}
|
||||
EventLoop::new()?.run_app(&mut game)?;
|
||||
Ok(Some(game))
|
||||
}
|
||||
|
||||
fn write_report(game: &Game<'_>) -> Result<()> {
|
||||
if let Some(path) = &game.options.report {
|
||||
let report = serde_json::json!({
|
||||
"frames": game.frames,
|
||||
@@ -10671,12 +10876,388 @@ pub fn run() -> Result<()> {
|
||||
});
|
||||
std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
|
||||
}
|
||||
if let Some(e) = game.error {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_event_loop(mut game: Game<'_>) -> Result<()> {
|
||||
EventLoop::new()?.run_app(&mut game)?;
|
||||
write_report(&game)?;
|
||||
if let Some(e) = game.error.take() {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The loading screen's state while the worker loads the resources.
|
||||
struct Loading {
|
||||
window: Option<Arc<Window>>,
|
||||
renderer: Option<Renderer>,
|
||||
atlas: Option<HudAtlas>,
|
||||
settings: Settings,
|
||||
fullscreen: horizon_client::window::FullscreenState,
|
||||
options: Option<Options>,
|
||||
vanilla_root: PathBuf,
|
||||
pack_error: Option<String>,
|
||||
started: Instant,
|
||||
progress: Progress,
|
||||
receiver: Receiver<std::result::Result<Loaded, String>>,
|
||||
loaded: Option<std::result::Result<Loaded, String>>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
shown: bool,
|
||||
error: Option<Box<dyn std::error::Error>>,
|
||||
}
|
||||
impl Loading {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
}
|
||||
// The Window constructor: created fullscreen when options.txt says so.
|
||||
let fullscreen = self.settings.fullscreen;
|
||||
self.fullscreen = horizon_client::window::FullscreenState::new(fullscreen);
|
||||
let attributes = Window::default_attributes()
|
||||
.with_title("Horizon")
|
||||
.with_window_icon(horizon_client::window::icon());
|
||||
// Wayland names the window by its app id, which the horizon.desktop entry matches.
|
||||
#[cfg(target_os = "linux")]
|
||||
let attributes = winit::platform::wayland::WindowAttributesExtWayland::with_name(
|
||||
attributes, "horizon", "horizon",
|
||||
);
|
||||
let window = match event_loop.create_window(
|
||||
attributes
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0))
|
||||
.with_fullscreen(fullscreen.then_some(winit::window::Fullscreen::Borderless(None))),
|
||||
) {
|
||||
Ok(w) => Arc::new(w),
|
||||
Err(e) => {
|
||||
self.error = Some(e.into());
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen);
|
||||
match loading_renderer(window.clone(), offscreen, self.atlas.as_ref()) {
|
||||
Ok(r) => self.renderer = Some(r),
|
||||
Err(e) => {
|
||||
self.error = Some(e);
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(r) = &self.renderer {
|
||||
self.settings
|
||||
.clamp_gui_scale([r.config.width as i32, r.config.height as i32]);
|
||||
}
|
||||
horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed);
|
||||
self.window = Some(window);
|
||||
}
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
if self.window.as_ref().is_none_or(|w| w.id() != id) {
|
||||
return;
|
||||
}
|
||||
match event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::Resized(size) => {
|
||||
if let Some(r) = &mut self.renderer {
|
||||
r.resize(size.width, size.height);
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => self.draw(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.loaded.is_none() {
|
||||
match self.receiver.try_recv() {
|
||||
Ok(result) => self.loaded = Some(result),
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
self.error = Some("resource loader stopped before finishing".into());
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
Err(TryRecvError::Empty) => {}
|
||||
}
|
||||
}
|
||||
if let Some(w) = &self.window {
|
||||
if self.options.as_ref().is_some_and(|o| o.offscreen) {
|
||||
self.draw();
|
||||
} else {
|
||||
w.request_redraw();
|
||||
}
|
||||
}
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
}
|
||||
fn draw(&mut self) {
|
||||
let Some(renderer) = self.renderer.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let size = [renderer.config.width, renderer.config.height];
|
||||
let mut batch = HudBatch::new(size);
|
||||
if let Some(atlas) = &self.atlas {
|
||||
horizon_client::level_loading::draw_progress(
|
||||
&mut batch,
|
||||
atlas,
|
||||
self.progress.line(),
|
||||
self.progress.fraction(),
|
||||
);
|
||||
}
|
||||
let frame = loading_frame(&batch);
|
||||
if let Err(e) = renderer.render(&frame) {
|
||||
log::warn!("Horizon: loading screen frame failed: {e}");
|
||||
}
|
||||
if !self.shown {
|
||||
self.shown = true;
|
||||
log::info!(
|
||||
"Horizon: loading screen shown after {} ms",
|
||||
self.started.elapsed().as_millis()
|
||||
);
|
||||
}
|
||||
}
|
||||
fn finish(&mut self, loaded: Loaded) -> Result<Option<Game<'static>>> {
|
||||
let mut options = self.options.take().ok_or("loading already finished")?;
|
||||
options.resources = loaded.root.clone();
|
||||
self.progress.set(STAGES - 1);
|
||||
// Audio is created on the main thread, after the join.
|
||||
let audio = if options.dedicated.is_some() {
|
||||
Audio::silent(&options.resources)
|
||||
} else {
|
||||
Audio::new(&options.resources)
|
||||
};
|
||||
let window = self.window.clone().ok_or("window closed")?;
|
||||
// Keep the loader's device and swap in the real textures in one step.
|
||||
if let Some(renderer) = &mut self.renderer {
|
||||
renderer.release_surface();
|
||||
}
|
||||
let renderer = build_renderer(
|
||||
window.clone(),
|
||||
options.offscreen,
|
||||
&loaded.pack,
|
||||
&loaded.atlas,
|
||||
self.renderer.as_ref(),
|
||||
)?;
|
||||
let pack_error = loaded.pack_error.or_else(|| self.pack_error.take());
|
||||
// The game borrows its shared resources for the process's lifetime,
|
||||
// like the single copy an integrated server would share.
|
||||
let res: &'static Arc<Resources> = Box::leak(Box::new(Arc::new(loaded.resources)));
|
||||
let Some(mut game) = start_game(
|
||||
res,
|
||||
loaded.pack,
|
||||
loaded.atlas,
|
||||
options,
|
||||
pack_error,
|
||||
audio,
|
||||
self.vanilla_root.clone(),
|
||||
self.started,
|
||||
)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
game.window = Some(window);
|
||||
game.renderer = Some(renderer);
|
||||
game.fullscreen = self.fullscreen;
|
||||
game.apply_settings();
|
||||
game.previous = Instant::now();
|
||||
Ok(Some(game))
|
||||
}
|
||||
}
|
||||
|
||||
/// The application: the loading screen until the resources are ready, then
|
||||
/// the game itself, on the same event loop and window.
|
||||
enum App {
|
||||
Loading(Box<Loading>),
|
||||
Ready(Box<Game<'static>>),
|
||||
}
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
match self {
|
||||
App::Loading(loading) => loading.resumed(event_loop),
|
||||
App::Ready(game) => game.resumed(event_loop),
|
||||
}
|
||||
}
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
match self {
|
||||
App::Loading(loading) => loading.window_event(event_loop, id, event),
|
||||
App::Ready(game) => game.window_event(event_loop, id, event),
|
||||
}
|
||||
}
|
||||
fn device_event(&mut self, event_loop: &ActiveEventLoop, id: DeviceId, event: DeviceEvent) {
|
||||
if let App::Ready(game) = self {
|
||||
game.device_event(event_loop, id, event);
|
||||
}
|
||||
}
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
enum Step {
|
||||
Waiting,
|
||||
Ready(Box<Game<'static>>),
|
||||
Done,
|
||||
Failed(Box<dyn std::error::Error>),
|
||||
}
|
||||
let step = match self {
|
||||
App::Ready(game) => {
|
||||
game.about_to_wait(event_loop);
|
||||
return;
|
||||
}
|
||||
App::Loading(loading) => {
|
||||
loading.about_to_wait(event_loop);
|
||||
if loading.error.is_some() {
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
match loading.loaded.take() {
|
||||
None => Step::Waiting,
|
||||
Some(Err(e)) => Step::Failed(e.into()),
|
||||
Some(Ok(loaded)) => match loading.finish(loaded) {
|
||||
Ok(Some(game)) => Step::Ready(Box::new(game)),
|
||||
Ok(None) => Step::Done,
|
||||
Err(e) => Step::Failed(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
match step {
|
||||
Step::Waiting => {}
|
||||
Step::Ready(game) => *self = App::Ready(game),
|
||||
Step::Done => event_loop.exit(),
|
||||
Step::Failed(e) => {
|
||||
if let App::Loading(loading) = self {
|
||||
loading.error = Some(e);
|
||||
}
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn exiting(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if let App::Ready(game) = self {
|
||||
game.exiting(event_loop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ordinary launch: load the resources on a worker while the window shows
|
||||
/// the loading screen, then swap in the game on the main thread.
|
||||
fn run_loading(
|
||||
options: Options,
|
||||
settings: Settings,
|
||||
vanilla_root: PathBuf,
|
||||
pack_error: Option<String>,
|
||||
started: Instant,
|
||||
) -> Result<()> {
|
||||
let progress = Progress::new();
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let loader = {
|
||||
let progress = progress.clone();
|
||||
let settings = settings.clone();
|
||||
let vanilla_root = vanilla_root.clone();
|
||||
let root = options.resources.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("resource-loader".into())
|
||||
.spawn(move || {
|
||||
let result = load_resources(root, &vanilla_root, &settings, started, &|stage| {
|
||||
progress.set(stage)
|
||||
})
|
||||
.map_err(|e| e.to_string());
|
||||
let _ = sender.send(result);
|
||||
})?
|
||||
};
|
||||
let atlas = HudAtlas::build(&options.resources).ok();
|
||||
let loading = Loading {
|
||||
window: None,
|
||||
renderer: None,
|
||||
atlas,
|
||||
settings,
|
||||
fullscreen: horizon_client::window::FullscreenState::new(false),
|
||||
options: Some(options),
|
||||
vanilla_root,
|
||||
pack_error,
|
||||
started,
|
||||
progress,
|
||||
receiver,
|
||||
loaded: None,
|
||||
handle: Some(loader),
|
||||
shown: false,
|
||||
error: None,
|
||||
};
|
||||
let mut app = App::Loading(Box::new(loading));
|
||||
EventLoop::new()?.run_app(&mut app)?;
|
||||
match app {
|
||||
App::Ready(mut game) => {
|
||||
write_report(&game)?;
|
||||
if let Some(e) = game.error.take() {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
App::Loading(loading) => {
|
||||
if let Some(e) = loading.error {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run() -> Result<()> {
|
||||
let Some(mut options) = Options::read()? else {
|
||||
return Ok(());
|
||||
};
|
||||
if options.dedicated.is_some() && !dedicated::preflight(&mut options)? {
|
||||
return Ok(());
|
||||
}
|
||||
let started = Instant::now();
|
||||
horizon_client::spans::enable(options.spikes.is_some());
|
||||
let vanilla_root = options.resources.clone();
|
||||
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
|
||||
// Snapshots of derived tables live in the game folder, never beside the
|
||||
// shared resources.
|
||||
Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache"));
|
||||
let mut pack_error = None;
|
||||
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs)
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!("Horizon: resource packs not applied: {e}");
|
||||
pack_error = Some(e.to_string());
|
||||
vanilla_root.clone()
|
||||
});
|
||||
options.resources = mods::content_root(
|
||||
&options.resources,
|
||||
&early_settings.mods.enabled,
|
||||
&options.dev_mods,
|
||||
);
|
||||
// Harnesses and dedicated runs stay synchronous; a normal launch enters
|
||||
// the event loop at once and loads the resources on a worker.
|
||||
if !synchronous_startup(&options) {
|
||||
return run_loading(options, early_settings, vanilla_root, pack_error, started);
|
||||
}
|
||||
let loaded = load_resources(
|
||||
options.resources.clone(),
|
||||
&vanilla_root,
|
||||
&early_settings,
|
||||
started,
|
||||
&|_| {},
|
||||
)?;
|
||||
options.resources = loaded.root.clone();
|
||||
let audio = if options.dedicated.is_some() {
|
||||
Audio::silent(&options.resources)
|
||||
} else {
|
||||
Audio::new(&options.resources)
|
||||
};
|
||||
let resources = Arc::new(loaded.resources);
|
||||
let game = start_game(
|
||||
&resources,
|
||||
loaded.pack,
|
||||
loaded.atlas,
|
||||
options,
|
||||
loaded.pack_error.or(pack_error),
|
||||
audio,
|
||||
vanilla_root,
|
||||
started,
|
||||
)?;
|
||||
if let Some(game) = game {
|
||||
run_event_loop(game)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Player.tick: cap the sleeping fade at 100, then fade out over 10 waking ticks.
|
||||
fn tick_sleep_timer(timer: u32, sleeping: bool) -> u32 {
|
||||
if sleeping {
|
||||
|
||||
@@ -469,6 +469,9 @@ impl Game<'_> {
|
||||
"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) },
|
||||
"weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering },
|
||||
"paused": self.pause,
|
||||
// Mouse movement turns the camera (`apply_mouse_look`): the real
|
||||
// pointer is grabbed, or an agent's `mouse-move` stands in for it.
|
||||
"pointer_grabbed": self.captured || self.agent_pointer,
|
||||
"player": player,
|
||||
"selected": self.selected + 1,
|
||||
"held": self.held().map(|s| self.stack_value(s)),
|
||||
@@ -613,6 +616,9 @@ impl Game<'_> {
|
||||
"screen": self.screen_label(),
|
||||
"buttons": buttons,
|
||||
});
|
||||
if let Some(chat) = &self.ui.chat_screen {
|
||||
v["chat_input"] = json!(chat.input.value);
|
||||
}
|
||||
if self.title.is_some() {
|
||||
v["menu"] = self.title_value();
|
||||
}
|
||||
@@ -631,6 +637,15 @@ impl Game<'_> {
|
||||
v["craft_size"] = json!(self.craft_size);
|
||||
v["station"] = json!(self.station.as_ref().map(|s| format!("{:?}", s.kind)));
|
||||
v["container"] = json!(self.container);
|
||||
// The recipe book's buttons (GUI pixels): the book button, then
|
||||
// the recipe buttons of the page, page arrows, filter and tabs.
|
||||
let book = self.recipe_book_targets();
|
||||
if !book.is_empty() {
|
||||
v["recipe_book"] = json!({
|
||||
"targets": book.iter().map(|t| t.rect).collect::<Vec<_>>(),
|
||||
"known": self.recipe_book_known(),
|
||||
});
|
||||
}
|
||||
v["slot_ids"] = json!(
|
||||
"0-8 hotbar, 9-35 inventory, 100+ crafting grid (row-major), 200 crafting result, 300+ container, 500-503 armor, 504 offhand, 600+ station"
|
||||
);
|
||||
|
||||
@@ -220,7 +220,11 @@ impl Game<'_> {
|
||||
levels
|
||||
}
|
||||
/// `applyEffects`: the powers for players within `levels * 10 + 10` (any height above).
|
||||
/// `BeaconBlockEntity.applyEffects`: every player in range.
|
||||
fn beacon_effects(&mut self, p: [i32; 3], b: &Beacon) {
|
||||
self.for_each_player(|g| g.beacon_effects_on_player(p, b));
|
||||
}
|
||||
fn beacon_effects_on_player(&mut self, p: [i32; 3], b: &Beacon) {
|
||||
let Some(primary) = b.primary.as_deref().and_then(effect_id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -10,6 +10,18 @@ use horizon_client::{
|
||||
text::{ClickEvent, Style, Text},
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The tree the chat parses and completes with: a server's, once it has
|
||||
/// sent one (ClientPacketListener.commands), else the game's own.
|
||||
fn chat_tree<'a>(
|
||||
remote: &'a Option<super::remote::Remote>,
|
||||
mods: &'a super::mods::ModsState,
|
||||
) -> &'a horizon_client::command::Dispatcher {
|
||||
match remote.as_ref().and_then(|r| r.commands.as_ref()) {
|
||||
Some(tree) => tree,
|
||||
None => mods.dispatcher(),
|
||||
}
|
||||
}
|
||||
use winit::{
|
||||
event::KeyEvent,
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
@@ -378,6 +390,10 @@ impl Game<'_> {
|
||||
/// The block the player is looking at, for coordinate suggestions.
|
||||
fn refresh_dynamic_registries(&mut self) {
|
||||
self.ui.registries.target_block = self.pick().map(|h| h.pos);
|
||||
// ClientPacketListener.getOnlinePlayerNames on a server.
|
||||
if let Some(names) = self.remote_online_names() {
|
||||
self.ui.registries.players = names;
|
||||
}
|
||||
}
|
||||
pub(super) fn open_chat(&mut self, initial: &str) {
|
||||
if self.player.is_none() {
|
||||
@@ -391,7 +407,7 @@ impl Game<'_> {
|
||||
let b = HudBatch::new(size);
|
||||
let m = Measure(&self.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: self.mods.dispatcher(),
|
||||
dispatcher: chat_tree(&self.remote, &self.mods),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
let mut screen = ChatScreen::new(
|
||||
@@ -449,7 +465,7 @@ impl Game<'_> {
|
||||
if let Some(shortcut) = self.edit_shortcut(event) {
|
||||
let m = Measure(&self.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: self.mods.dispatcher(),
|
||||
dispatcher: chat_tree(&self.remote, &self.mods),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
@@ -495,7 +511,7 @@ impl Game<'_> {
|
||||
};
|
||||
let m = Measure(&self.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: self.mods.dispatcher(),
|
||||
dispatcher: chat_tree(&self.remote, &self.mods),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) {
|
||||
@@ -521,7 +537,7 @@ impl Game<'_> {
|
||||
pub(super) fn chat_type(&mut self, text: &str) {
|
||||
let m = Measure(&self.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: self.mods.dispatcher(),
|
||||
dispatcher: chat_tree(&self.remote, &self.mods),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
@@ -531,6 +547,11 @@ impl Game<'_> {
|
||||
/// ChatScreen.handleChatInput: history, then a command or a chat line.
|
||||
pub(super) fn handle_chat_input(&mut self, message: &str) {
|
||||
self.ui.chat.add_recent(message);
|
||||
// On a server (single player's own included) the server runs it.
|
||||
if self.remote.is_some() {
|
||||
self.send_chat(message);
|
||||
return;
|
||||
}
|
||||
if let Some(command) = message.strip_prefix('/') {
|
||||
self.run_command(command);
|
||||
} else {
|
||||
@@ -572,7 +593,7 @@ impl Game<'_> {
|
||||
});
|
||||
let m = Measure(&self.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: self.mods.dispatcher(),
|
||||
dispatcher: chat_tree(&self.remote, &self.mods),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
if let Some(screen) = self.ui.chat_screen.as_mut() {
|
||||
@@ -617,7 +638,7 @@ impl Game<'_> {
|
||||
};
|
||||
let m = Measure(&self.atlas.font);
|
||||
let c = Commands {
|
||||
dispatcher: self.mods.dispatcher(),
|
||||
dispatcher: chat_tree(&self.remote, &self.mods),
|
||||
registries: &self.ui.registries,
|
||||
};
|
||||
screen.resize(&m, &c, batch.width as i32, batch.height as i32);
|
||||
|
||||
@@ -174,6 +174,16 @@ impl Game<'_> {
|
||||
.chain(super::pad::HELP)
|
||||
.collect::<Vec<_>>() }))),
|
||||
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
|
||||
"section-draws" => {
|
||||
let r = self.renderer.as_mut().ok_or("no renderer")?;
|
||||
match words.get(1).copied() {
|
||||
None => {}
|
||||
Some("flat") => r.set_flat_draws(true)?,
|
||||
Some("indirect") => r.set_flat_draws(false)?,
|
||||
Some(other) => return Err(format!("unknown section draw mode {other}").into()),
|
||||
}
|
||||
Ok(Some(json!({ "ok": true, "flat": r.flat_draws() })))
|
||||
}
|
||||
"sculk" => Ok(Some(self.sculk_command(&words)?)),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"pad" => Ok(Some(self.pad_command(&words)?)),
|
||||
@@ -616,18 +626,6 @@ impl Game<'_> {
|
||||
|
||||
fn control_key_down(&mut self, key: KeyCode) -> Result<()> {
|
||||
self.physical_keys.insert(key);
|
||||
// A server's chat input takes the keys first, as remote_chat_key does.
|
||||
if self.remote_chat_open() {
|
||||
use winit::keyboard::NamedKey;
|
||||
let named = match key {
|
||||
KeyCode::Escape => Some(NamedKey::Escape),
|
||||
KeyCode::Enter | KeyCode::NumpadEnter => Some(NamedKey::Enter),
|
||||
KeyCode::Backspace => Some(NamedKey::Backspace),
|
||||
_ => None,
|
||||
};
|
||||
self.remote_chat_input(named, None);
|
||||
return Ok(());
|
||||
}
|
||||
if self.screen == Screen::Chat {
|
||||
self.chat_key_code(key, None);
|
||||
return Ok(());
|
||||
@@ -694,6 +692,8 @@ impl Game<'_> {
|
||||
"size": [r.config.width, r.config.height],
|
||||
"present_mode": format!("{:?}", r.config.present_mode),
|
||||
"drawn_sections": r.drawn_sections,
|
||||
"section_draws": r.section_draws,
|
||||
"section_draw_calls": r.section_draw_calls,
|
||||
"uploaded_bytes": r.uploaded_bytes,
|
||||
"resident_sections": r.resident_sections(),
|
||||
"arena_bytes": arena_bytes,
|
||||
|
||||
@@ -362,3 +362,11 @@ pub(super) struct CreakingState {
|
||||
/// Which block states are creaking hearts, by state id.
|
||||
hearts: Vec<bool>,
|
||||
}
|
||||
|
||||
impl CreakingState {
|
||||
/// Exchange the chunks scanned for creaking hearts with another level's
|
||||
/// (game/levels.rs).
|
||||
pub(super) fn swap_level(&mut self, other: &mut Self) {
|
||||
std::mem::swap(&mut self.scanned, &mut other.scanned);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1358,25 +1358,52 @@ impl Game<'_> {
|
||||
/// mining fatigue III for five minutes unless a stronger or longer one
|
||||
/// is on, with the curse sound and the elder's apparition.
|
||||
fn elder_curse(&mut self, at: [f64; 3]) {
|
||||
let mut cursed = Vec::new();
|
||||
self.for_each_player(|g| {
|
||||
if g.elder_curse_player(at) {
|
||||
cursed.push(g.lan_acting);
|
||||
}
|
||||
});
|
||||
// A guest's client shows the apparition and plays the curse itself
|
||||
// (ClientboundGameEventPacket.GUARDIAN_ELDER_EFFECT).
|
||||
if let Some(host) = self.lan.as_ref() {
|
||||
for conn in cursed.into_iter().flatten() {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&horizon_protocol::packets::play::Clientbound::GameEvent(
|
||||
horizon_protocol::packets::play::GameEvent {
|
||||
event: horizon_client::lan::hub::game_event::GUARDIAN_ELDER_EFFECT,
|
||||
param: 1.0,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The curse on the player in place; whether it took.
|
||||
fn elder_curse_player(&mut self, at: [f64; 3]) -> bool {
|
||||
if self.creative || self.spectator() {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
let d = p.position.subtract(Vec3::new(at[0], at[1], at[2]));
|
||||
if d.x * d.x + d.y * d.y + d.z * d.z >= 2500.0 || p.health.dead_or_dying() {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let active = self.potions.effects.get("minecraft:mining_fatigue");
|
||||
if active.is_some_and(|e| e.amplifier >= 2 && e.duration >= 1200) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
self.give_player_effect("minecraft:mining_fatigue", 6000, 2);
|
||||
self.audio
|
||||
.play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0);
|
||||
self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS;
|
||||
if self.lan_acting.is_none() {
|
||||
self.audio
|
||||
.play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0);
|
||||
self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS;
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Damage of a given type to the player from a point.
|
||||
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
|
||||
|
||||
@@ -88,8 +88,7 @@ impl Game<'_> {
|
||||
|| self.book.is_some()
|
||||
|| (self.screen == Screen::Creative && self.creative_screen.tab().search)
|
||||
|| self.recipe_search_focused()
|
||||
|| self.station_typing()
|
||||
|| self.remote_chat_open();
|
||||
|| self.station_typing();
|
||||
// Container screens use Escape, the inventory key and the hotbar and
|
||||
// drop keys first; any other screen closes on Escape.
|
||||
let screen_key = match self.screen {
|
||||
|
||||
@@ -642,18 +642,12 @@ impl Game<'_> {
|
||||
);
|
||||
self.save_game()?;
|
||||
}
|
||||
self.update_dedicated_streaming();
|
||||
self.update_world();
|
||||
if paused {
|
||||
// MinecraftServer.tickServer: only the connections run.
|
||||
self.tick_lan();
|
||||
} else {
|
||||
if !state.autosave {
|
||||
// `save-off`: the periodic save inside the tick is skipped.
|
||||
self.ticks = self.ticks.max(1);
|
||||
}
|
||||
self.tick()?;
|
||||
if !paused && !state.autosave {
|
||||
// `save-off`: the periodic save inside the tick is skipped.
|
||||
self.ticks = self.ticks.max(1);
|
||||
}
|
||||
// MinecraftServer.tickServer: while paused only the connections run.
|
||||
self.tick_server(paused)?;
|
||||
if idle_timeout > 0 {
|
||||
self.kick_idle(idle_timeout);
|
||||
}
|
||||
@@ -694,7 +688,13 @@ impl Game<'_> {
|
||||
let center = self
|
||||
.lan
|
||||
.as_ref()
|
||||
.and_then(|h| h.hub.guests.iter().find(|g| g.placed).map(|g| g.chunk()))
|
||||
.and_then(|h| {
|
||||
h.hub
|
||||
.guests
|
||||
.iter()
|
||||
.find(|g| h.hub.here(g))
|
||||
.map(|g| g.chunk())
|
||||
})
|
||||
.or_else(|| {
|
||||
self.spawn
|
||||
.map(|s| ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4))
|
||||
|
||||
@@ -23,7 +23,7 @@ impl Game<'_> {
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| {
|
||||
g.placed
|
||||
host.hub.here(g)
|
||||
&& g.loaded
|
||||
&& !g.dead
|
||||
&& !g.creative()
|
||||
|
||||
@@ -112,7 +112,7 @@ impl Game<'_> {
|
||||
let hurt = &p.health.hurt;
|
||||
let state = BobState {
|
||||
living: Some(HurtBob {
|
||||
hurt_time: hurt.hurt_time as f32 - partial,
|
||||
hurt_time: p.health.hurt_animation_time as f32 - partial,
|
||||
hurt_duration: hurt.hurt_duration,
|
||||
hurt_dir: 0.0,
|
||||
death_time: self.death_time().map(|t| t as f32 + partial),
|
||||
|
||||
@@ -314,14 +314,12 @@ impl Game<'_> {
|
||||
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) {
|
||||
// Only the connections run.
|
||||
self.tick_lan();
|
||||
self.tick_server(true)?;
|
||||
} else {
|
||||
let started = Instant::now();
|
||||
self.tick()?;
|
||||
self.tick_server(false)?;
|
||||
self.debug_charts.log_tick(started, started.elapsed());
|
||||
flags.smoothed_tick_ms.store(
|
||||
self.debug_charts.smoothed_tick_ms.to_bits(),
|
||||
|
||||
@@ -213,7 +213,7 @@ impl Game<'_> {
|
||||
owner.is_local_player = true;
|
||||
owner.is_view_entity = true;
|
||||
if let (Some((slot, ticks)), Some(stack)) = (self.using, stack)
|
||||
&& self.inventory.get(slot).and_then(Option::as_ref) == Some(stack)
|
||||
&& self.stack_in(slot) == Some(stack)
|
||||
{
|
||||
let view = item_render::stack_view(stack);
|
||||
let duration = use_duration(&self.pack.item_renderer.models.components(&view));
|
||||
|
||||
@@ -52,7 +52,7 @@ pub(super) struct LanHost {
|
||||
/// Blocks broken this tick (their sound is a level event for the guests).
|
||||
pub broken: Vec<[f64; 3]>,
|
||||
/// Hurt and death state of the mobs guests see.
|
||||
mob_state: HashMap<u32, (i32, bool)>,
|
||||
mob_state: HashMap<super::Dim, HashMap<u32, (i32, bool)>>,
|
||||
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
|
||||
pub mob_players: HashMap<u32, u32>,
|
||||
/// An integrated server's owner (game/integrated.rs).
|
||||
@@ -794,7 +794,19 @@ impl Game<'_> {
|
||||
self.ui.rules.bool("player_movement_check"),
|
||||
self.ui.rules.bool("elytra_movement_check"),
|
||||
);
|
||||
host.hub.tick(&mut ctx)
|
||||
// A server with several levels runs a pass for each
|
||||
// (`tick_server`): the network is read once, before the first.
|
||||
let pass = self.level_pass;
|
||||
let mut events = if pass.first {
|
||||
host.hub.poll(&mut ctx)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
events.extend(host.hub.tick_level(&mut ctx));
|
||||
if pass.last {
|
||||
host.hub.end_tick();
|
||||
}
|
||||
events
|
||||
};
|
||||
if let Some(state) = &state
|
||||
&& host.host_mode != state.game_mode
|
||||
@@ -835,7 +847,15 @@ impl Game<'_> {
|
||||
if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos)
|
||||
&& !guest.spectator()
|
||||
{
|
||||
self.container_openers_changed(pos, false);
|
||||
// In the level they were in.
|
||||
let back = self.dim;
|
||||
let theirs = super::Dim::from_id(&guest.dimension);
|
||||
if self.enter_level(Some(&mut host), theirs).is_ok() {
|
||||
self.container_openers_changed(pos, false);
|
||||
}
|
||||
if let Err(e) = self.enter_level(Some(&mut host), back) {
|
||||
log::error!("could not reopen {}: {e}", back.id());
|
||||
}
|
||||
}
|
||||
self.lan_crafting_left(&mut host, &mut guest);
|
||||
self.save_guest(&host, &guest);
|
||||
@@ -875,9 +895,7 @@ impl Game<'_> {
|
||||
self.lan_update_models(&mut host);
|
||||
self.lan_update_waypoints(&mut host, state.as_ref());
|
||||
drop(holding);
|
||||
for g in &host.hub.guests {
|
||||
g.sender.flush();
|
||||
}
|
||||
lan::flush_all(host.hub.guests.iter().map(|g| &g.sender));
|
||||
self.lan = Some(host);
|
||||
}
|
||||
|
||||
@@ -892,6 +910,7 @@ impl Game<'_> {
|
||||
let default_mode = host.hub.config.default_game_mode;
|
||||
let force = host.hub.config.force_game_mode;
|
||||
let root = self.world_root.clone();
|
||||
let in_place = host.hub.config.dimension.clone();
|
||||
let owner = host.owner.as_mut();
|
||||
let Some(g) = host.hub.guest_mut(conn) else {
|
||||
return;
|
||||
@@ -914,8 +933,28 @@ impl Game<'_> {
|
||||
g.previous_position = spawn;
|
||||
g.health = 20.0;
|
||||
g.food = 20;
|
||||
g.dimension = super::Dim::Overworld.id().to_owned();
|
||||
}
|
||||
// A server places each player in their own level
|
||||
// (`PlayerList.placeNewPlayer`); the in-frame game has one.
|
||||
let back = self.dim;
|
||||
let level = super::Dim::from_id(&g.dimension);
|
||||
let elsewhere = self.options.dedicated.is_some() && level != back;
|
||||
if !elsewhere {
|
||||
g.dimension = in_place;
|
||||
}
|
||||
self.load_guest_records(host, conn);
|
||||
let theirs;
|
||||
let entities = if elsewhere {
|
||||
if let Err(e) = self.enter_level(Some(host), level) {
|
||||
log::error!("could not open {}: {e}", level.id());
|
||||
return;
|
||||
}
|
||||
theirs = self.lan_entities(&mut host.hub);
|
||||
&theirs[..]
|
||||
} else {
|
||||
entities
|
||||
};
|
||||
let mut ctx = TickCtx {
|
||||
world: &mut self.world,
|
||||
host: state,
|
||||
@@ -930,6 +969,9 @@ impl Game<'_> {
|
||||
collision: Some(self.collision),
|
||||
};
|
||||
host.hub.place_new_player(conn, &mut ctx);
|
||||
if elsewhere && let Err(e) = self.enter_level(Some(host), back) {
|
||||
log::error!("could not reopen {}: {e}", back.id());
|
||||
}
|
||||
}
|
||||
|
||||
/// Level events the game queued, for the guests (`process_level_events`).
|
||||
@@ -984,7 +1026,11 @@ impl Game<'_> {
|
||||
let mut seen = HashMap::new();
|
||||
for m in &self.mobs {
|
||||
let dead = !m.alive();
|
||||
let old = host.mob_state.get(&m.id).copied();
|
||||
let old = host
|
||||
.mob_state
|
||||
.get(&self.dim)
|
||||
.and_then(|s| s.get(&m.id))
|
||||
.copied();
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
if m.hurt_time > old.map_or(0, |o| o.0) && !dead {
|
||||
host.hub.entity_event(m.id as i32, 2, at);
|
||||
@@ -994,7 +1040,7 @@ impl Game<'_> {
|
||||
}
|
||||
seen.insert(m.id, (m.hurt_time, dead));
|
||||
}
|
||||
host.mob_state = seen;
|
||||
host.mob_state.insert(self.dim, seen);
|
||||
}
|
||||
|
||||
/// Keep the chunks around every guest loaded.
|
||||
@@ -1003,7 +1049,7 @@ impl Game<'_> {
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| g.placed)
|
||||
.filter(|g| host.hub.here(g))
|
||||
// The tracked square's corners and their lit neighbours lie
|
||||
// within (view distance + 2) * √2 of the player's chunk.
|
||||
.map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1))
|
||||
|
||||
@@ -54,6 +54,8 @@ pub(super) struct GuestPlay {
|
||||
/// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw.
|
||||
pub(super) stats: super::stats::Stats,
|
||||
last_inventory: u64,
|
||||
/// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs).
|
||||
pub(super) portal: horizon_client::nether_portal::PortalState,
|
||||
}
|
||||
|
||||
struct ItemRules<'a>(&'a horizon_client::items::Items);
|
||||
@@ -140,13 +142,20 @@ impl Game<'_> {
|
||||
total: g.xp_total,
|
||||
},
|
||||
);
|
||||
let sneak = self.keys.contains(&KeyCode::ShiftLeft);
|
||||
// The host's held keys stay theirs: the guest holds only sneak, and a
|
||||
// screen the guest opens (`keys.clear()`) leaves the host walking.
|
||||
let host_keys = std::mem::take(&mut self.keys);
|
||||
if g.sneaking {
|
||||
self.keys.insert(KeyCode::ShiftLeft);
|
||||
} else {
|
||||
self.keys.remove(&KeyCode::ShiftLeft);
|
||||
}
|
||||
// The window's screens are the host's: a sign, book, command block or
|
||||
// mount menu the guest's action opens is not drawn over the host's
|
||||
// world (#687). The guest's client opens its own.
|
||||
let screen = std::mem::replace(&mut self.screen, Screen::Playing);
|
||||
let host_sign = self.sign_edit.take();
|
||||
let host_book = self.book.take();
|
||||
let host_command_block = self.command_block_screen.take();
|
||||
let host_mount_menu = std::mem::take(&mut self.mount_menu);
|
||||
// The host's crafting grid stays theirs; a crafting table the guest
|
||||
// opens shows as the 3x3 size.
|
||||
let craft_size = std::mem::replace(&mut self.craft_size, 2);
|
||||
@@ -205,11 +214,11 @@ impl Game<'_> {
|
||||
play.swing = std::mem::replace(&mut self.swing, swing);
|
||||
self.container = container;
|
||||
self.screen = screen;
|
||||
if sneak {
|
||||
self.keys.insert(KeyCode::ShiftLeft);
|
||||
} else {
|
||||
self.keys.remove(&KeyCode::ShiftLeft);
|
||||
}
|
||||
self.sign_edit = host_sign;
|
||||
self.book = host_book;
|
||||
self.command_block_screen = host_command_block;
|
||||
self.mount_menu = host_mount_menu;
|
||||
self.keys = host_keys;
|
||||
let g = &mut host.hub.guests[i];
|
||||
std::mem::swap(&mut self.ender_items, &mut g.ender_items);
|
||||
std::mem::swap(&mut self.adv.progress, &mut g.advancements);
|
||||
@@ -282,6 +291,32 @@ impl Game<'_> {
|
||||
Some(result)
|
||||
}
|
||||
|
||||
/// `ServerLevel.players()` in turn: the host's own player, then each
|
||||
/// guest in the level in place with their state swapped in (`as_guest`).
|
||||
/// What reaches the players around a point (a beacon's powers, a splash
|
||||
/// potion, a warden's darkness, an elder guardian's curse) lands on each
|
||||
/// of them, not only on the host. A server has no player of its own.
|
||||
/// Inside a guest's action (the hub taken) only that player is in place.
|
||||
pub(super) fn for_each_player(&mut self, mut f: impl FnMut(&mut Self)) {
|
||||
if self.player.is_some() {
|
||||
f(self);
|
||||
}
|
||||
let Some(mut host) = self.lan.take() else {
|
||||
return;
|
||||
};
|
||||
let conns: Vec<u32> = host
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
|
||||
.map(|g| g.conn)
|
||||
.collect();
|
||||
for conn in conns {
|
||||
self.as_guest(&mut host, conn, &mut f);
|
||||
}
|
||||
self.lan = Some(host);
|
||||
}
|
||||
|
||||
/// The game mode fields without `set_mode`'s side effects on the host.
|
||||
fn set_mode_raw(&mut self, id: i32) {
|
||||
use horizon_client::command::args::GameMode;
|
||||
@@ -664,6 +699,7 @@ impl Game<'_> {
|
||||
{
|
||||
self.guest_suggestions(host, conn, &payload);
|
||||
}
|
||||
S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p),
|
||||
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
|
||||
// ServerStatsCounter.sendStats.
|
||||
S::ClientCommand(c) if c.action == 1 => {
|
||||
@@ -937,7 +973,18 @@ impl Game<'_> {
|
||||
if !host.hub.guests[i].dead {
|
||||
return;
|
||||
}
|
||||
self.respawn_level(host);
|
||||
// PlayerList.respawn: a server's player comes back in the Overworld,
|
||||
// where the world spawn is (respawn anchors and beds aside).
|
||||
let back = self.dim;
|
||||
let away = self.options.dedicated.is_some()
|
||||
&& host.hub.guests[i].dimension != super::Dim::Overworld.id();
|
||||
if away {
|
||||
self.server_trips.retain(|t| !t.is(conn));
|
||||
if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) {
|
||||
log::error!("could not open the Overworld: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
let g = &mut host.hub.guests[i];
|
||||
g.dead = false;
|
||||
g.health = 20.0;
|
||||
@@ -974,6 +1021,9 @@ impl Game<'_> {
|
||||
collision: Some(self.collision),
|
||||
};
|
||||
host.hub.respawn(i, spawn, &ctx);
|
||||
if away && let Err(e) = self.enter_level(Some(host), back) {
|
||||
log::error!("could not reopen {}: {e}", back.id());
|
||||
}
|
||||
}
|
||||
|
||||
/// Per tick, for every guest: dig, use items, pick up drops, die.
|
||||
@@ -984,7 +1034,7 @@ impl Game<'_> {
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| g.placed && g.loaded)
|
||||
.filter(|g| host.hub.here(g) && g.loaded)
|
||||
.map(|g| g.conn)
|
||||
.collect();
|
||||
for conn in conns {
|
||||
@@ -1376,6 +1426,9 @@ impl Game<'_> {
|
||||
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
|
||||
continue;
|
||||
};
|
||||
if !host.hub.here(g) {
|
||||
continue;
|
||||
}
|
||||
let (id, at) = (g.entity_id, g.position);
|
||||
let play = host.play.get_mut(&conn).expect("play");
|
||||
let swinging = play.swing.swinging() && play.swing.ticks == 0;
|
||||
|
||||
@@ -225,6 +225,86 @@ impl Game<'_> {
|
||||
true
|
||||
}
|
||||
|
||||
/// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe
|
||||
/// book places a known recipe in their inventory grid or crafting table
|
||||
/// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items
|
||||
/// are missing.
|
||||
pub(super) fn lan_place_recipe(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
p: &horizon_protocol::packets::recipes::PlaceRecipe,
|
||||
) {
|
||||
use horizon_client::menu::place::PostPlace;
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return;
|
||||
};
|
||||
let g = &host.hub.guests[gi];
|
||||
if g.spectator() {
|
||||
return;
|
||||
}
|
||||
let Some(id) = self
|
||||
.res
|
||||
.stations
|
||||
.recipe_index
|
||||
.recipe_of_display(p.recipe)
|
||||
.map(str::to_owned)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
// An unknown or impossible recipe is refused outright.
|
||||
if !g.recipe_book.knows(&id)
|
||||
|| self
|
||||
.res
|
||||
.recipes
|
||||
.placement(&id)
|
||||
.is_none_or(|placement| placement.impossible())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let creative = g.creative();
|
||||
let placed = if p.container == 0 {
|
||||
let crafting = host.play.entry(conn).or_default();
|
||||
let mut menu = crafting
|
||||
.crafting
|
||||
.inventory
|
||||
.take()
|
||||
.unwrap_or_else(|| Box::new(Menu::new(Kind::Inventory)));
|
||||
let grid = host.hub.guests[gi].craft_grid.clone();
|
||||
let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
|
||||
for (k, s) in grid.into_iter().enumerate() {
|
||||
menu.set_slot(env, 1 + k, s);
|
||||
}
|
||||
menu.place_recipe(env, &id, p.use_max, creative, None)
|
||||
});
|
||||
let g = &mut host.hub.guests[gi];
|
||||
for k in 0..4 {
|
||||
g.craft_grid[k] = menu.slot(1 + k).cloned();
|
||||
}
|
||||
g.craft_result = menu.slot(0).cloned();
|
||||
host.play.entry(conn).or_default().crafting.inventory = Some(menu);
|
||||
host.hub.send_inventory(gi);
|
||||
placed
|
||||
} else {
|
||||
let Some((window, state, mut menu)) = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|play| play.crafting.table.take_if(|(w, _, _)| *w == p.container))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
|
||||
menu.place_recipe(env, &id, p.use_max, creative, None)
|
||||
});
|
||||
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu));
|
||||
self.lan_send_table_content(host, conn);
|
||||
placed
|
||||
};
|
||||
if placed == PostPlace::Ghost {
|
||||
host.hub.send_ghost_recipe(conn, p.container, &id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
|
||||
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
|
||||
self.lan_crafting_closed(host, conn, None);
|
||||
|
||||
@@ -92,7 +92,7 @@ impl Game<'_> {
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| g.placed && g.loaded && !g.dead)
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
|
||||
.map(|g| {
|
||||
let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]);
|
||||
(g.conn, g.uuid, moved)
|
||||
@@ -138,7 +138,7 @@ impl Game<'_> {
|
||||
host.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
|
||||
.map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g)))
|
||||
.collect()
|
||||
}
|
||||
@@ -209,9 +209,12 @@ pub(super) struct Present {
|
||||
impl Game<'_> {
|
||||
/// Every guest in the world (`ServerLevel.getPlayers` past the host).
|
||||
pub(super) fn lan_present(&self) -> Vec<Present> {
|
||||
let guests = self.lan.iter().flat_map(|h| &h.hub.guests);
|
||||
let guests = self
|
||||
.lan
|
||||
.iter()
|
||||
.flat_map(|h| h.hub.guests.iter().filter(|g| h.hub.here(g)));
|
||||
guests
|
||||
.filter(|g| g.placed && g.loaded)
|
||||
.filter(|g| g.loaded)
|
||||
.map(|g| {
|
||||
let [x, y, z] = g.position;
|
||||
Present {
|
||||
|
||||
@@ -32,7 +32,7 @@ impl Game<'_> {
|
||||
host.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
|
||||
.filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?)))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
}
|
||||
@@ -64,7 +64,7 @@ impl Game<'_> {
|
||||
host.hub
|
||||
.guests
|
||||
.iter()
|
||||
.find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead)
|
||||
.find(|g| g.entity_id == id && g.conn != conn && host.hub.here(g) && !g.dead)
|
||||
.map(|g| Victim::Guest(g.conn))
|
||||
}
|
||||
|
||||
|
||||
@@ -372,7 +372,7 @@ impl Game<'_> {
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.find(|g| g.conn == conn)
|
||||
.find(|g| g.conn == conn && host.hub.here(g))
|
||||
.map(|g| uuid_words(g.uuid))
|
||||
else {
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
//! A server's levels, one per dimension (`MinecraftServer.levels`).
|
||||
//!
|
||||
//! The game's tick code reads one level: the one in place, held in `Game`'s
|
||||
//! own fields (the world, its streaming and save, block ticks, entities).
|
||||
//! A server (the dedicated server and single player's server thread) keeps
|
||||
//! the other dimensions' levels here and ticks each one that has players by
|
||||
//! swapping it into place (`enter_level`), the way `as_guest` swaps a player
|
||||
//! in, so the tick code runs unchanged, one level at a time. The in-frame
|
||||
//! game holds one level, which follows its player (`enter_dimension`).
|
||||
//!
|
||||
//! Shared by every level, as vanilla's derived levels share the
|
||||
//! Overworld's level data: the game time, the day time and the weather, the
|
||||
//! game rules, the scoreboard, the maps and the entities waiting to arrive
|
||||
//! through a portal.
|
||||
|
||||
use super::{
|
||||
Dim, ExperienceOrb, FallingBlock, Game, ItemEntity, Mob, boats, commands,
|
||||
creaking::CreakingState, dragon, fireworks, lan::LanHost, lightning, machines, minecarts,
|
||||
ominous_item_spawner, persist, raids::Raiding, sculk::SculkState, tnt, trident,
|
||||
};
|
||||
use horizon_client::{
|
||||
Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections,
|
||||
save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World,
|
||||
};
|
||||
use horizon_world::level::{LevelEvent, Ticks};
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
/// Server ticks a level other than the Overworld stays loaded with no player
|
||||
/// in it, before it is saved and closed (vanilla unloads a level's chunks
|
||||
/// once no ticket holds them; the Overworld stays loaded).
|
||||
const IDLE_TICKS: u32 = 300;
|
||||
|
||||
/// A level that is not in place: every per-level field of `Game`.
|
||||
pub(super) struct Parked {
|
||||
world: World,
|
||||
streaming: Streaming,
|
||||
save: Arc<SaveDir>,
|
||||
block_ticks: Ticks,
|
||||
tick_chunks: TickChunkMembership,
|
||||
random_tick_sections: RandomTickSections,
|
||||
level_events: Vec<LevelEvent>,
|
||||
falling: Vec<FallingBlock>,
|
||||
paintings: Vec<horizon_client::entities::Painting>,
|
||||
item_frames: Vec<horizon_client::entities::ItemFrame>,
|
||||
armor_stands: Vec<horizon_client::entities::ArmorStand>,
|
||||
others: Vec<commands::OtherEntity>,
|
||||
boats: Vec<boats::Boat>,
|
||||
carts: Vec<minecarts::Minecart>,
|
||||
jukebox_sounds: HashMap<(i32, i32, i32), u64>,
|
||||
bolts: Vec<lightning::Bolt>,
|
||||
crystals: Vec<dragon::Crystal>,
|
||||
dragon: Option<dragon::Dragon>,
|
||||
dragon_fireballs: Vec<dragon::DragonFireball>,
|
||||
breath_clouds: Vec<dragon::Breath>,
|
||||
tridents: Vec<trident::ThrownTrident>,
|
||||
rockets: Vec<fireworks::Rocket>,
|
||||
ominous_spawners: Vec<ominous_item_spawner::OminousItemSpawner>,
|
||||
tnts: Vec<tnt::PrimedTnt>,
|
||||
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
|
||||
mobs: Vec<Mob>,
|
||||
projectiles: Vec<horizon_client::projectiles::Projectile>,
|
||||
dropped: Vec<ItemEntity>,
|
||||
orbs: Vec<ExperienceOrb>,
|
||||
persist: persist::EntityMemory,
|
||||
lectern_pulses: Vec<((i32, i32, i32), i32)>,
|
||||
lid_openers: HashMap<(i32, i32, i32), i32>,
|
||||
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
|
||||
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
|
||||
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
|
||||
/// Only the per-level parts of these are used (`swap_level`).
|
||||
anims: BlockEntityAnims,
|
||||
raiding: Raiding,
|
||||
sculk: SculkState,
|
||||
creaking: CreakingState,
|
||||
/// Server ticks since a player was last in the level.
|
||||
idle: u32,
|
||||
}
|
||||
|
||||
/// Which passes of the server tick the level in place runs: the first
|
||||
/// reads the network (`Hub::poll`), the last ends the tick for every player
|
||||
/// (`Hub::end_tick`). A tick with one level is both.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Pass {
|
||||
pub first: bool,
|
||||
pub last: bool,
|
||||
}
|
||||
|
||||
impl Default for Pass {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
first: true,
|
||||
last: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The levels not in place, by dimension.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Levels {
|
||||
parked: HashMap<Dim, Parked>,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
|
||||
fn open_level(&self, dim: Dim) -> Result<Parked> {
|
||||
let (streaming, save) =
|
||||
self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?;
|
||||
let mut world = World::new(self.res.facts.air, self.level.seed);
|
||||
world.fast_lava = dim == Dim::Nether;
|
||||
Ok(Parked {
|
||||
world,
|
||||
streaming,
|
||||
save,
|
||||
block_ticks: Ticks::new(self.level.seed as i32),
|
||||
tick_chunks: Default::default(),
|
||||
random_tick_sections: Default::default(),
|
||||
level_events: Vec::new(),
|
||||
falling: Vec::new(),
|
||||
paintings: Vec::new(),
|
||||
item_frames: Vec::new(),
|
||||
armor_stands: Vec::new(),
|
||||
others: Vec::new(),
|
||||
boats: Vec::new(),
|
||||
carts: Vec::new(),
|
||||
jukebox_sounds: HashMap::new(),
|
||||
bolts: Vec::new(),
|
||||
crystals: Vec::new(),
|
||||
dragon: None,
|
||||
dragon_fireballs: Vec::new(),
|
||||
breath_clouds: Vec::new(),
|
||||
tridents: Vec::new(),
|
||||
rockets: Vec::new(),
|
||||
ominous_spawners: Vec::new(),
|
||||
tnts: Vec::new(),
|
||||
hoppers: HashMap::new(),
|
||||
mobs: Vec::new(),
|
||||
projectiles: Vec::new(),
|
||||
dropped: Vec::new(),
|
||||
orbs: Vec::new(),
|
||||
persist: Default::default(),
|
||||
lectern_pulses: Vec::new(),
|
||||
lid_openers: HashMap::new(),
|
||||
lan_events: Vec::new(),
|
||||
lan_block_events: Vec::new(),
|
||||
lan_entity_events: Vec::new(),
|
||||
anims: Default::default(),
|
||||
raiding: Default::default(),
|
||||
sculk: Default::default(),
|
||||
creaking: Default::default(),
|
||||
idle: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Exchange the level in place with `p`.
|
||||
fn swap_level(&mut self, p: &mut Parked) {
|
||||
use std::mem::swap;
|
||||
swap(&mut self.world, &mut p.world);
|
||||
swap(&mut self.streaming, &mut p.streaming);
|
||||
swap(&mut self.save, &mut p.save);
|
||||
swap(&mut self.block_ticks, &mut p.block_ticks);
|
||||
swap(&mut self.tick_chunks, &mut p.tick_chunks);
|
||||
swap(&mut self.random_tick_sections, &mut p.random_tick_sections);
|
||||
swap(&mut self.level_events, &mut p.level_events);
|
||||
swap(&mut self.falling, &mut p.falling);
|
||||
swap(&mut self.paintings, &mut p.paintings);
|
||||
swap(&mut self.item_frames, &mut p.item_frames);
|
||||
swap(&mut self.armor_stands, &mut p.armor_stands);
|
||||
swap(&mut self.others, &mut p.others);
|
||||
swap(&mut self.boats, &mut p.boats);
|
||||
swap(&mut self.carts, &mut p.carts);
|
||||
swap(&mut self.jukebox_sounds, &mut p.jukebox_sounds);
|
||||
swap(&mut self.bolts, &mut p.bolts);
|
||||
swap(&mut self.crystals, &mut p.crystals);
|
||||
swap(&mut self.dragon, &mut p.dragon);
|
||||
swap(&mut self.dragon_fireballs, &mut p.dragon_fireballs);
|
||||
swap(&mut self.breath_clouds, &mut p.breath_clouds);
|
||||
swap(&mut self.tridents, &mut p.tridents);
|
||||
swap(&mut self.rockets, &mut p.rockets);
|
||||
swap(&mut self.ominous_spawners, &mut p.ominous_spawners);
|
||||
swap(&mut self.tnts, &mut p.tnts);
|
||||
swap(&mut self.hoppers, &mut p.hoppers);
|
||||
swap(&mut self.mobs, &mut p.mobs);
|
||||
swap(&mut self.creatures.projectiles, &mut p.projectiles);
|
||||
swap(&mut self.dropped, &mut p.dropped);
|
||||
swap(&mut self.orbs, &mut p.orbs);
|
||||
swap(&mut self.persist, &mut p.persist);
|
||||
swap(&mut self.lectern_pulses, &mut p.lectern_pulses);
|
||||
swap(&mut self.lid_openers, &mut p.lid_openers);
|
||||
swap(&mut self.lan_events, &mut p.lan_events);
|
||||
swap(&mut self.lan_block_events, &mut p.lan_block_events);
|
||||
swap(&mut self.lan_entity_events, &mut p.lan_entity_events);
|
||||
let (a, b) = (&mut self.be_anims, &mut p.anims);
|
||||
swap(&mut a.chests, &mut b.chests);
|
||||
swap(&mut a.books, &mut b.books);
|
||||
swap(&mut a.shulkers, &mut b.shulkers);
|
||||
swap(&mut a.bells, &mut b.bells);
|
||||
swap(&mut a.conduits, &mut b.conduits);
|
||||
swap(&mut a.skulls, &mut b.skulls);
|
||||
swap(&mut a.pots, &mut b.pots);
|
||||
swap(&mut a.gateways, &mut b.gateways);
|
||||
swap(&mut a.gateway_servers, &mut b.gateway_servers);
|
||||
self.raiding.swap_level(&mut p.raiding);
|
||||
self.sculk.swap_level(&mut p.sculk);
|
||||
self.creaking.swap_level(&mut p.creaking);
|
||||
// What only the client draws starts over.
|
||||
self.particles.clear();
|
||||
self.pickups.clear();
|
||||
}
|
||||
|
||||
/// Put `target`'s level in place, opening it first if it is not loaded.
|
||||
/// The level that was in place is kept with the others; the shared
|
||||
/// clock and weather go with the swap. `host` is the hub when the caller
|
||||
/// holds it (`self.lan` is taken during the network tick).
|
||||
pub(super) fn enter_level(&mut self, host: Option<&mut LanHost>, target: Dim) -> Result<()> {
|
||||
// The in-frame game keeps its one level (`enter_dimension`).
|
||||
if self.options.dedicated.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if target != self.dim {
|
||||
let (mut p, opened) = match self.levels.parked.remove(&target) {
|
||||
Some(p) => (p, false),
|
||||
None => (self.open_level(target)?, true),
|
||||
};
|
||||
p.world.game_time = self.world.game_time;
|
||||
p.world.day_time = self.world.day_time;
|
||||
p.world.weather = self.world.weather;
|
||||
// The sculk tables' watched blocks are built once per game.
|
||||
p.world.watched = std::mem::take(&mut self.world.watched);
|
||||
self.swap_level(&mut p);
|
||||
p.idle = 0;
|
||||
let left = std::mem::replace(&mut self.dim, target);
|
||||
self.levels.parked.insert(left, p);
|
||||
if opened {
|
||||
// The new streaming's radius and meshing options.
|
||||
self.apply_settings();
|
||||
}
|
||||
}
|
||||
let host = match host {
|
||||
Some(h) => Some(h),
|
||||
None => self.lan.as_mut(),
|
||||
};
|
||||
if let Some(h) = host {
|
||||
h.hub.set_dimension(target.id());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One server tick (`MinecraftServer.tickServer`): each level with
|
||||
/// players in turn (`tickChildren`), its chunks streamed and loaded and
|
||||
/// its world ticked. The first pass reads the network and runs the
|
||||
/// tick's shared parts (the clock, the weather, functions, the autosave);
|
||||
/// the next ones only their level. While `paused`, only the connections
|
||||
/// run.
|
||||
pub(super) fn tick_server(&mut self, paused: bool) -> Result<()> {
|
||||
let dims = self.levels_to_tick();
|
||||
let n = dims.len();
|
||||
let mut result = Ok(());
|
||||
for (k, dim) in dims.into_iter().enumerate() {
|
||||
if let Err(e) = self.enter_level(None, dim) {
|
||||
result = Err(e);
|
||||
break;
|
||||
}
|
||||
self.level_pass = Pass {
|
||||
first: k == 0,
|
||||
last: k + 1 == n,
|
||||
};
|
||||
self.update_dedicated_streaming();
|
||||
self.update_world();
|
||||
result = if paused {
|
||||
self.tick_lan();
|
||||
Ok(())
|
||||
} else if k == 0 {
|
||||
self.tick()
|
||||
} else {
|
||||
let running = self.clock.world_runs();
|
||||
if running {
|
||||
self.tick_weather_effects();
|
||||
}
|
||||
self.tick_world(running)
|
||||
};
|
||||
if result.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.level_pass = Pass::default();
|
||||
result?;
|
||||
self.close_idle_levels()
|
||||
}
|
||||
|
||||
/// The levels this server tick runs, in `MinecraftServer.levels` order
|
||||
/// (the Overworld, the Nether, the End): every level with a player in
|
||||
/// it, or the Overworld while nobody is online.
|
||||
pub(super) fn levels_to_tick(&self) -> Vec<Dim> {
|
||||
let guests = self
|
||||
.lan
|
||||
.as_ref()
|
||||
.map_or(&[][..], |h| h.hub.guests.as_slice());
|
||||
let mut dims: Vec<Dim> = [Dim::Overworld, Dim::Nether, Dim::End]
|
||||
.into_iter()
|
||||
.filter(|d| guests.iter().any(|g| g.dimension == d.id()))
|
||||
.collect();
|
||||
if dims.is_empty() {
|
||||
dims.push(Dim::Overworld);
|
||||
}
|
||||
dims
|
||||
}
|
||||
|
||||
/// Count the parked levels' empty ticks, and save and close the ones
|
||||
/// (other than the Overworld) nobody has been in for a while.
|
||||
pub(super) fn close_idle_levels(&mut self) -> Result<()> {
|
||||
let occupied = self.levels_to_tick();
|
||||
let mut closing = Vec::new();
|
||||
for (dim, p) in &mut self.levels.parked {
|
||||
if occupied.contains(dim) {
|
||||
p.idle = 0;
|
||||
continue;
|
||||
}
|
||||
p.idle += 1;
|
||||
if *dim != Dim::Overworld && p.idle >= IDLE_TICKS {
|
||||
closing.push(*dim);
|
||||
}
|
||||
}
|
||||
if closing.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let back = self.dim;
|
||||
for dim in closing {
|
||||
self.enter_level(None, dim)?;
|
||||
self.save_level(true)?;
|
||||
self.enter_level(None, back)?;
|
||||
self.levels.parked.remove(&dim);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Save every parked level (`MinecraftServer.saveAllChunks`); the level
|
||||
/// in place is the caller's to save.
|
||||
pub(super) fn save_parked_levels(&mut self, wait: bool) -> Result<()> {
|
||||
if self.levels.parked.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let back = self.dim;
|
||||
let dims: Vec<Dim> = self.levels.parked.keys().copied().collect();
|
||||
for dim in dims {
|
||||
self.enter_level(None, dim)?;
|
||||
self.save_level(wait)?;
|
||||
}
|
||||
self.enter_level(None, back)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use super::Game;
|
||||
mod crafter;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
containers::BlockEntity,
|
||||
containers::{BlockEntity, HOPPER_SLOTS},
|
||||
items::{ItemStack, Items},
|
||||
world::World,
|
||||
};
|
||||
@@ -506,14 +506,16 @@ impl Game<'_> {
|
||||
.default_state("minecraft:hopper")
|
||||
.map(|s| self.res.facts.get(s).name.clone());
|
||||
let Some(hopper) = hopper else { return Ok(()) };
|
||||
// A hopper's block entity is a plain container (`Chest`): only those
|
||||
// need their block looked up (the ticker runs for a HopperBlockEntity
|
||||
// whose block is still a hopper, `BlockEntityType.isValid`).
|
||||
// A hopper's block entity is the plain container with five slots
|
||||
// (`BlockEntity::for_block`; `BlockEntity::id` names it the hopper):
|
||||
// only those need their block looked up (the ticker runs for a
|
||||
// HopperBlockEntity whose block is still a hopper,
|
||||
// `BlockEntityType.isValid`).
|
||||
let mut positions: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Chest(_)))
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Chest(items) if items.len() == HOPPER_SLOTS))
|
||||
.map(|(p, _)| *p)
|
||||
.filter(|p| self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == hopper)
|
||||
.collect();
|
||||
|
||||
@@ -90,6 +90,10 @@ pub(super) struct Minecart {
|
||||
}
|
||||
const WIDTH: f64 = 0.98;
|
||||
const HEIGHT: f64 = 0.7;
|
||||
/// AbstractMinecart.getDefaultDisplayOffset, in sixteenths of a block.
|
||||
fn display_offset(kind: CartKind) -> f64 {
|
||||
if kind == CartKind::Hopper { 1.0 } else { 6.0 }
|
||||
}
|
||||
/// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT.
|
||||
const SEAT: f64 = 0.1875 - 0.6;
|
||||
/// The placeholder container key under which an open cart's items live.
|
||||
@@ -1230,24 +1234,52 @@ impl Game<'_> {
|
||||
/// front and back points, pitched on slopes, with the display block.
|
||||
pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
let a = alpha as f32;
|
||||
let Some(uv) = self
|
||||
.atlas
|
||||
.sprites
|
||||
.get("entity/minecart/minecart")
|
||||
.map(|r| [r.u0, r.v0, r.u1, r.v1])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
// Entity.shouldRenderAtSqrDistance: 64 times the bounding box's mean
|
||||
// edge, scaled by the entity distance option.
|
||||
let range =
|
||||
(WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * f64::from(self.settings.entity_distance);
|
||||
for c in &self.carts {
|
||||
let entity_start = out.len();
|
||||
let Some(model) = self.cart_models.models.get(&c.kind) else {
|
||||
continue;
|
||||
};
|
||||
let Some(uv) = self
|
||||
.atlas
|
||||
.sprites
|
||||
.get("entity/minecart/minecart")
|
||||
.map(|r| [r.u0, r.v0, r.u1, r.v1])
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let (x, y, z) = (
|
||||
c.previous.x + (c.position.x - c.previous.x) * alpha,
|
||||
c.previous.y + (c.position.y - c.previous.y) * alpha,
|
||||
c.previous.z + (c.position.z - c.previous.z) * alpha,
|
||||
);
|
||||
// LevelExtractor.isEntityVisible: the cart the player rides always draws.
|
||||
if self.riding != Some(c.id) {
|
||||
let d = glam::DVec3::new(c.position.x, c.position.y, c.position.z) - camera;
|
||||
if d.length_squared() >= range * range {
|
||||
continue;
|
||||
}
|
||||
// EntityRenderer.shouldRender: the interpolated box grown by 0.5;
|
||||
// AbstractMinecartRenderer.getBoundingBoxForCulling stretches it
|
||||
// up by the display block's offset.
|
||||
if let Some(view) = &self.view_frustum {
|
||||
let top = HEIGHT
|
||||
+ if c.kind == CartKind::Rideable {
|
||||
0.0
|
||||
} else {
|
||||
display_offset(c.kind) * 0.75 / 16.0
|
||||
};
|
||||
let p = glam::DVec3::new(x, y, z) - camera;
|
||||
let lo = p - glam::DVec3::new(WIDTH / 2.0 + 0.5, 0.5, WIDTH / 2.0 + 0.5);
|
||||
let hi = p + glam::DVec3::new(WIDTH / 2.0 + 0.5, top + 0.5, WIDTH / 2.0 + 0.5);
|
||||
if !view.intersects(lo.as_vec3(), hi.as_vec3()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut yaw =
|
||||
c.previous_yaw + ((c.yaw - c.previous_yaw + 180.0).rem_euclid(360.0) - 180.0) * a;
|
||||
let mut pitch = 0.0f32;
|
||||
|
||||
@@ -257,20 +257,36 @@ impl Game<'_> {
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
// ItemInHandLayer submits with OverlayTexture.NO_OVERLAY: no hurt tint.
|
||||
for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
|
||||
for (item, off_hand) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
|
||||
let Some(item) = item else { continue };
|
||||
let left = off_hand != mob.extra.main_hand_left;
|
||||
let Some(t) =
|
||||
render::held_item_transform(mob, alpha as f32, camera, &self.res.mob_data, left)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let slot = if left {
|
||||
let slot = if off_hand {
|
||||
horizon_client::mobs::gear::OFF
|
||||
} else {
|
||||
horizon_client::mobs::gear::MAIN
|
||||
};
|
||||
let mut stack = ItemStack::new(item, 1);
|
||||
if horizon_client::mobs::gear::enchanted(mob, slot) {
|
||||
let local_player = self
|
||||
.player_model
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.id == mob.id && p.kind.id == mob.kind.id);
|
||||
let mut stack = if local_player {
|
||||
let Some(stack) = self.stack_in(if off_hand {
|
||||
super::shield::OFFHAND_SLOT
|
||||
} else {
|
||||
self.selected
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
stack.clone()
|
||||
} else {
|
||||
ItemStack::new(item, 1)
|
||||
};
|
||||
if !local_player && horizon_client::mobs::gear::enchanted(mob, slot) {
|
||||
// The gear's enchantments are not tracked, only that it has some.
|
||||
stack.enchant("minecraft:unbreaking", 1);
|
||||
}
|
||||
@@ -284,12 +300,13 @@ impl Game<'_> {
|
||||
);
|
||||
// The local player's rod while its hook is out.
|
||||
owner.fishing_cast_with_this_item = self.cast_rod().is_some()
|
||||
&& self.main_hand_rod() != left
|
||||
&& self.main_hand_rod() != off_hand
|
||||
&& self
|
||||
.player_model
|
||||
.as_ref()
|
||||
.is_some_and(|p| std::ptr::eq(p, mob));
|
||||
if !left && mob.extra.using_item > 0 {
|
||||
owner.main_arm_left = mob.extra.main_hand_left;
|
||||
if off_hand == mob.extra.using_off_hand && mob.extra.using_item > 0 {
|
||||
owner.using_this_item = true;
|
||||
owner.use_duration = 72_000;
|
||||
owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item;
|
||||
|
||||
@@ -365,13 +365,6 @@ impl Game<'_> {
|
||||
self.close_book();
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(remote) = self.remote.as_mut()
|
||||
&& remote.chat_input.is_some()
|
||||
{
|
||||
remote.chat_input = None;
|
||||
self.capture(true);
|
||||
return Ok(());
|
||||
}
|
||||
self.key_pressed(KeyCode::Escape)
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ use winit::{
|
||||
dpi::PhysicalPosition,
|
||||
event::{DeviceId, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent},
|
||||
event_loop::ActiveEventLoop,
|
||||
keyboard::{KeyCode, NamedKey},
|
||||
keyboard::KeyCode,
|
||||
};
|
||||
|
||||
/// D-pad auto-repeat: the first step at once, the next after a pause.
|
||||
@@ -859,7 +859,6 @@ impl Game<'_> {
|
||||
|| (self.screen == Screen::Creative && self.creative_screen.tab().search)
|
||||
|| self.recipe_search_focused()
|
||||
|| self.station_typing()
|
||||
|| self.remote_chat_open()
|
||||
}
|
||||
|
||||
/// Open the on-screen keyboard over the focused field: Horizon's, or
|
||||
@@ -890,7 +889,7 @@ impl Game<'_> {
|
||||
&& self.pad.in_use
|
||||
&& menu.open_polls >= 3
|
||||
&& self.pad_focus_mode()
|
||||
&& (self.screen == Screen::Chat || self.sign_edit.is_some() || self.remote_chat_open())
|
||||
&& (self.screen == Screen::Chat || self.sign_edit.is_some())
|
||||
{
|
||||
self.pad.menu.osk_dismissed = true;
|
||||
self.pad_open_keyboard();
|
||||
@@ -901,10 +900,10 @@ impl Game<'_> {
|
||||
/// the field that has focus.
|
||||
fn pad_osk_output(&mut self, out: osk::Output) {
|
||||
use osk::Output;
|
||||
let (key, named, text) = match &out {
|
||||
Output::Text(t) => (None, None, Some(t.as_str())),
|
||||
Output::Backspace => (Some(KeyCode::Backspace), Some(NamedKey::Backspace), None),
|
||||
Output::Enter => (Some(KeyCode::Enter), Some(NamedKey::Enter), None),
|
||||
let (key, text) = match &out {
|
||||
Output::Text(t) => (None, Some(t.as_str())),
|
||||
Output::Backspace => (Some(KeyCode::Backspace), None),
|
||||
Output::Enter => (Some(KeyCode::Enter), None),
|
||||
Output::Close => {
|
||||
self.pad.menu.osk = None;
|
||||
self.pad.menu.osk_dismissed = true;
|
||||
@@ -933,8 +932,6 @@ impl Game<'_> {
|
||||
if key != Some(KeyCode::Enter) {
|
||||
self.station_text(text, backspace);
|
||||
}
|
||||
} else if self.remote_chat_open() {
|
||||
self.remote_chat_input(named, text);
|
||||
} else if self.screen == Screen::WorldOptions {
|
||||
if key != Some(KeyCode::Enter) {
|
||||
self.world_options_text(text);
|
||||
@@ -985,8 +982,7 @@ impl Game<'_> {
|
||||
.menu
|
||||
.focus
|
||||
.is_some_and(|f| f.center().1 > batch.height / 2.0)
|
||||
|| self.screen == Screen::Chat
|
||||
|| self.remote_chat_open();
|
||||
|| self.screen == Screen::Chat;
|
||||
let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor);
|
||||
keyboard.draw(&mut ui, at_top, self.ui.options.pad_style);
|
||||
ui.finish();
|
||||
|
||||
@@ -305,6 +305,13 @@ impl Game<'_> {
|
||||
let (position, flying) = (p.position, p.flying || p.fall_flying);
|
||||
let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity);
|
||||
let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0);
|
||||
let using_off_hand = self
|
||||
.using
|
||||
.is_some_and(|(slot, _)| slot == super::shield::OFFHAND_SLOT);
|
||||
let blocking = self
|
||||
.using
|
||||
.and_then(|(slot, _)| self.stack_in(slot))
|
||||
.is_some_and(|stack| self.blocks_attacks(stack).is_some());
|
||||
let charged = self.inventory[self.selected]
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty()));
|
||||
@@ -328,7 +335,7 @@ impl Game<'_> {
|
||||
.map(|s| s.item.clone());
|
||||
let off = self.offhand.as_ref().map(|s| s.item.clone());
|
||||
let riding = self.riding.is_some();
|
||||
let hurt = p.health.hurt.hurt_time;
|
||||
let hurt = p.health.hurt_animation_time;
|
||||
let Some(m) = self.player_model.as_mut() else {
|
||||
return;
|
||||
};
|
||||
@@ -384,6 +391,8 @@ impl Game<'_> {
|
||||
m.extra.fall_fly_ticks = fly_ticks;
|
||||
m.extra.main_hand_left = self.settings.main_hand_left;
|
||||
m.extra.using_item = using;
|
||||
m.extra.using_off_hand = using_off_hand;
|
||||
m.extra.blocking = blocking;
|
||||
m.extra.charged = charged;
|
||||
m.extra.ints[5] = charge_duration;
|
||||
m.extra.elytra.tick(fall_flying, crouching, velocity);
|
||||
|
||||
@@ -467,6 +467,41 @@ impl Game<'_> {
|
||||
self.splash(&stack, at);
|
||||
}
|
||||
}
|
||||
/// A splash potion's effects on the player in place, by their distance.
|
||||
fn splash_on_player(
|
||||
&mut self,
|
||||
effects: &'static [(&'static str, i32, i32)],
|
||||
at: Vec3,
|
||||
scale: f64,
|
||||
) {
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
let center = Vec3::new(
|
||||
p.position.x,
|
||||
p.position.y + f64::from(p.dimensions.height) / 2.0,
|
||||
p.position.z,
|
||||
);
|
||||
let d2 =
|
||||
(center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2);
|
||||
if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) {
|
||||
let intensity = 1.0 - d2.sqrt() / 4.0;
|
||||
for (id, duration, amp) in effects {
|
||||
let instant = brewing::effect(id).is_some_and(|e| e.instant);
|
||||
if instant {
|
||||
if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) {
|
||||
self.apply_effect_action(a);
|
||||
}
|
||||
} else {
|
||||
let d = (intensity * f64::from(*duration) * scale + 0.5) as i32;
|
||||
if d > 20
|
||||
&& let Some(e) = brewing::effect(id)
|
||||
{
|
||||
self.potions.effects.add(EffectInstance::new(e.id, d, *amp));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash).
|
||||
fn splash(&mut self, stack: &ItemStack, at: Vec3) {
|
||||
if &*stack.item == "minecraft:experience_bottle" {
|
||||
@@ -527,34 +562,9 @@ impl Game<'_> {
|
||||
let Some(def) = stack.potion().and_then(brewing::potion) else {
|
||||
return;
|
||||
};
|
||||
// The player.
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
let center = Vec3::new(
|
||||
p.position.x,
|
||||
p.position.y + f64::from(p.dimensions.height) / 2.0,
|
||||
p.position.z,
|
||||
);
|
||||
let d2 =
|
||||
(center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2);
|
||||
if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) {
|
||||
let intensity = 1.0 - d2.sqrt() / 4.0;
|
||||
for (id, duration, amp) in def.effects {
|
||||
let instant = brewing::effect(id).is_some_and(|e| e.instant);
|
||||
if instant {
|
||||
if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) {
|
||||
self.apply_effect_action(a);
|
||||
}
|
||||
} else {
|
||||
let d = (intensity * f64::from(*duration) * scale + 0.5) as i32;
|
||||
if d > 20
|
||||
&& let Some(e) = brewing::effect(id)
|
||||
{
|
||||
self.potions.effects.add(EffectInstance::new(e.id, d, *amp));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every player in range (`ThrownSplashPotion.applySplash` over
|
||||
// `LivingEntity`s, the players among them).
|
||||
self.for_each_player(|g| g.splash_on_player(def.effects, at, scale));
|
||||
// Mobs take the instant effects (undead invert healing and harming).
|
||||
let undead = &self.res.stations.enchantments.entity_tags;
|
||||
let mut hits = Vec::new();
|
||||
|
||||
@@ -39,6 +39,17 @@ pub(super) struct Raiding {
|
||||
homes: HashMap<i32, (i64, std::sync::Arc<Vec<[i32; 3]>>)>,
|
||||
}
|
||||
|
||||
impl Raiding {
|
||||
/// Exchange the level-held parts (`ServerLevel.getRaids`) with another
|
||||
/// level's (game/levels.rs).
|
||||
pub(super) fn swap_level(&mut self, other: &mut Self) {
|
||||
std::mem::swap(&mut self.raids, &mut other.raids);
|
||||
std::mem::swap(&mut self.loaded, &mut other.loaded);
|
||||
std::mem::swap(&mut self.bar_hurts, &mut other.bar_hurts);
|
||||
std::mem::swap(&mut self.homes, &mut other.homes);
|
||||
}
|
||||
}
|
||||
|
||||
/// `SectionPos` of a block position.
|
||||
pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) {
|
||||
(p[0] >> 4, p[1] >> 4, p[2] >> 4)
|
||||
@@ -613,17 +624,17 @@ impl Game<'_> {
|
||||
raider::state_mut(m).ticks_outside_raid = ticks;
|
||||
}
|
||||
}
|
||||
Action::Victory { heroes, amplifier } => {
|
||||
let me = self.level.player_uuid;
|
||||
if me.is_some_and(|u| heroes.contains(&u)) && !self.spectator() {
|
||||
// Raid.tick on a victory: each hero who is still alive.
|
||||
Action::Victory { heroes, amplifier } => self.for_each_player(|g| {
|
||||
if heroes.contains(&g.acting_uuid()) && !g.spectator() {
|
||||
let mut effect =
|
||||
EffectInstance::new("hero_of_the_village", raid::HERO_DURATION, amplifier);
|
||||
effect.visible = false;
|
||||
self.potions.effects.add(effect);
|
||||
self.stats.custom("raid_win", 1);
|
||||
self.trigger_player("minecraft:hero_of_the_village");
|
||||
g.potions.effects.add(effect);
|
||||
g.stats.custom("raid_win", 1);
|
||||
g.trigger_player("minecraft:hero_of_the_village");
|
||||
}
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
/// `Raid.playSound`: the horn, 13 blocks away from the player toward the
|
||||
|
||||
@@ -110,7 +110,7 @@ fn sprite(name: &str) -> String {
|
||||
impl Game<'_> {
|
||||
/// The book the open screen has, if any.
|
||||
fn active_book(&self) -> Option<BookType> {
|
||||
if self.screen != Screen::Inventory || self.remote.is_some() || self.station.is_some() {
|
||||
if self.screen != Screen::Inventory || self.station.is_some() {
|
||||
return None;
|
||||
}
|
||||
if self.mount_active() {
|
||||
@@ -262,6 +262,33 @@ impl Game<'_> {
|
||||
/// The items the book counts (`RecipeBookComponent.updateStackedContents`):
|
||||
/// the inventory and the menu's crafting slots, as the menu engine counts them.
|
||||
fn book_available(&mut self, _book: BookType) -> Stacked {
|
||||
if self.remote.is_some() {
|
||||
// A server's menu: the slots it last sent, counted the same way.
|
||||
use horizon_client::menu::{Env, Kind, Menu};
|
||||
let table = self.craft_size == 3;
|
||||
let grid: Vec<_> = (0..self.craft_size * self.craft_size)
|
||||
.map(|k| self.slot_mut(100 + k).clone())
|
||||
.collect();
|
||||
let mut menu = Menu::new(if table {
|
||||
Kind::Crafting
|
||||
} else {
|
||||
Kind::Inventory
|
||||
});
|
||||
let env = Env {
|
||||
items: &self.res.items,
|
||||
recipes: &self.res.recipes,
|
||||
brewing: &self.res.stations.brewing,
|
||||
banners: &self.res.stations.banners,
|
||||
trade: None,
|
||||
};
|
||||
for i in 0..36 {
|
||||
menu.set_player_item(i, self.inventory[i].clone());
|
||||
}
|
||||
for (k, stack) in grid.into_iter().enumerate() {
|
||||
menu.set_slot(&env, 1 + k, stack);
|
||||
}
|
||||
return menu.stacked_contents(&env);
|
||||
}
|
||||
let mut out = Stacked::default();
|
||||
let stock = &mut out;
|
||||
self.menu_session(|menu, env, _| {
|
||||
@@ -274,6 +301,10 @@ impl Game<'_> {
|
||||
/// replacing batch (vanilla's server iterates an identity hash set; this
|
||||
/// one goes in id order), then each unlock and removal.
|
||||
fn sync_client_book(&mut self) {
|
||||
// On a server the book is the server's packets' (remote_recipe_book_*).
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let known = &self.level.recipe_book.recipes;
|
||||
let index = &self.res.stations.recipe_index;
|
||||
let ui = &mut self.recipe_ui;
|
||||
@@ -660,6 +691,10 @@ impl Game<'_> {
|
||||
}
|
||||
false
|
||||
}
|
||||
/// How many displays the client's book holds.
|
||||
pub(super) fn recipe_book_known(&self) -> usize {
|
||||
self.recipe_ui.client.displays().len()
|
||||
}
|
||||
/// The recipe book's buttons a controller can focus: the book button,
|
||||
/// recipes, page arrows, the craftable filter and the tabs (GUI pixels;
|
||||
/// the search box registers itself as a field).
|
||||
@@ -800,6 +835,18 @@ impl Game<'_> {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.remote.is_some() {
|
||||
// The server places it and answers with the slots, or a ghost.
|
||||
let container = self.remote_menu_id();
|
||||
self.send(horizon_protocol::packets::play::Serverbound::PlaceRecipe(
|
||||
horizon_protocol::packets::recipes::PlaceRecipe {
|
||||
container,
|
||||
recipe: entry.display_id,
|
||||
use_max,
|
||||
},
|
||||
));
|
||||
return;
|
||||
}
|
||||
let creative = self.creative;
|
||||
let mut post = None;
|
||||
let answer = &mut post;
|
||||
@@ -828,6 +875,80 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- a server's recipe book ----
|
||||
|
||||
/// ClientboundRecipeBookAddPacket (`ClientRecipeBook.add`): the
|
||||
/// displays join the book, highlighted when new, and the recipes whose
|
||||
/// entries ask for it show the toast.
|
||||
pub(super) fn remote_recipe_book_add(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::RecipeBookAdd,
|
||||
) {
|
||||
let ui = &mut self.recipe_ui;
|
||||
if p.replace {
|
||||
ui.client.clear();
|
||||
}
|
||||
let mut toast = Vec::new();
|
||||
for e in &p.entries {
|
||||
ui.client.add(e.id);
|
||||
if e.flags & 2 != 0 {
|
||||
ui.client.highlight.insert(e.id);
|
||||
}
|
||||
if e.flags & 1 != 0
|
||||
&& let Some(id) = self.res.stations.recipe_index.recipe_of_display(e.id)
|
||||
&& !toast.iter().any(|t| t == id)
|
||||
{
|
||||
toast.push(id.to_owned());
|
||||
}
|
||||
}
|
||||
// A local world opened later syncs its book from scratch.
|
||||
ui.client_known = None;
|
||||
ui.client_version += 1;
|
||||
self.recipe_toast(&toast);
|
||||
}
|
||||
/// ClientboundRecipeBookRemovePacket.
|
||||
pub(super) fn remote_recipe_book_remove(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::RecipeBookRemove,
|
||||
) {
|
||||
for id in p.ids {
|
||||
self.recipe_ui.client.remove(id);
|
||||
}
|
||||
self.recipe_ui.client_version += 1;
|
||||
}
|
||||
/// ClientboundRecipeBookSettingsPacket: each book's open and filter flags.
|
||||
pub(super) fn remote_recipe_book_settings(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::RecipeBookSettings,
|
||||
) {
|
||||
for (i, (open, filtering)) in p.books.into_iter().enumerate() {
|
||||
self.level.recipe_book.open[i] = open;
|
||||
self.level.recipe_book.filtering[i] = filtering;
|
||||
}
|
||||
}
|
||||
/// ClientboundPlaceGhostRecipePacket: the recipe last placed, faded into
|
||||
/// the open menu's grid.
|
||||
pub(super) fn remote_ghost_recipe(
|
||||
&mut self,
|
||||
p: horizon_protocol::packets::recipes::PlaceGhostRecipe,
|
||||
) {
|
||||
let open = self.remote_menu_id();
|
||||
let Some(book_type) = self.active_book() else {
|
||||
return;
|
||||
};
|
||||
if p.container != open {
|
||||
return;
|
||||
}
|
||||
let entry = self.recipe_ui.last_placed.as_ref().and_then(|id| {
|
||||
let book = self.recipe_ui.book.as_ref()?;
|
||||
book.entry(id).cloned()
|
||||
});
|
||||
if let Some(entry) = entry {
|
||||
self.recipe_ui.ghost.clear();
|
||||
self.fill_ghost(book_type, &entry);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ghost recipe ----
|
||||
|
||||
/// `fillGhostRecipe`: the recipe's ingredients faded into the slots.
|
||||
|
||||
@@ -111,7 +111,8 @@ pub(super) struct Remote {
|
||||
health: (f32, i32, f32),
|
||||
game_mode: i32,
|
||||
pub chat: Vec<(String, Instant)>,
|
||||
pub chat_input: Option<String>,
|
||||
/// The server's command tree (ClientboundCommandsPacket).
|
||||
pub commands: Option<horizon_client::command::Dispatcher>,
|
||||
action_bar: Option<(String, Instant)>,
|
||||
players: HashMap<u128, String>,
|
||||
/// `ClientPacketListener.playerInfoMap` as player-list entries, and
|
||||
@@ -297,7 +298,7 @@ impl Game<'_> {
|
||||
health: (20.0, 20, 5.0),
|
||||
game_mode: 0,
|
||||
chat: Vec::new(),
|
||||
chat_input: None,
|
||||
commands: None,
|
||||
action_bar: None,
|
||||
players: HashMap::new(),
|
||||
tab_players: HashMap::new(),
|
||||
@@ -476,6 +477,20 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names in the server's player list, sorted.
|
||||
pub(super) fn remote_online_names(&self) -> Option<Vec<String>> {
|
||||
let r = self.remote.as_ref()?;
|
||||
let mut names: Vec<String> = r.players.values().cloned().collect();
|
||||
names.sort();
|
||||
Some(names)
|
||||
}
|
||||
/// The open menu's window id (0: the inventory).
|
||||
pub(super) fn remote_menu_id(&self) -> i32 {
|
||||
self.remote
|
||||
.as_ref()
|
||||
.and_then(|r| r.menu.as_ref())
|
||||
.map_or(0, |m| m.0)
|
||||
}
|
||||
/// The server's last `n` chat lines, newest first.
|
||||
pub(super) fn remote_chat(&self, n: usize) -> Option<Vec<String>> {
|
||||
let r = self.remote.as_ref()?;
|
||||
@@ -1466,6 +1481,21 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
C::GameEvent(p) => match p.event {
|
||||
// GUARDIAN_ELDER_EFFECT: the apparition, and the curse sound
|
||||
// unless the elder guardian is silent.
|
||||
10 => {
|
||||
self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS;
|
||||
if p.param == 1.0
|
||||
&& let Some(at) = self.player.as_ref().map(|m| m.position)
|
||||
{
|
||||
self.audio.play(
|
||||
"minecraft:entity.elder_guardian.curse",
|
||||
Some([at.x, at.y, at.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
self.world.weather.raining = true;
|
||||
self.world.weather.rain_level = (0.0, 0.0);
|
||||
@@ -1544,6 +1574,10 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
C::OpenScreen(p) => self.remote_open_screen(p),
|
||||
C::RecipeBookAdd(p) => self.remote_recipe_book_add(p),
|
||||
C::RecipeBookRemove(p) => self.remote_recipe_book_remove(p),
|
||||
C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p),
|
||||
C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p),
|
||||
C::MerchantOffers(p) => self.remote_merchant_offers(p),
|
||||
C::ContainerClose(_) => {
|
||||
if self.screen == Screen::Inventory {
|
||||
@@ -1552,6 +1586,15 @@ impl Game<'_> {
|
||||
self.capture(true);
|
||||
}
|
||||
}
|
||||
C::Commands(p) => {
|
||||
let tree = horizon_client::command::network::from_packet(
|
||||
&p,
|
||||
horizon_client::command::vanilla::dispatcher(),
|
||||
);
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.commands = Some(tree);
|
||||
}
|
||||
}
|
||||
C::SystemChat(p) => {
|
||||
let text = plain(
|
||||
&p.content,
|
||||
@@ -2175,8 +2218,7 @@ impl Game<'_> {
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
let chatting = self.remote.as_ref().is_some_and(|r| r.chat_input.is_some());
|
||||
let playing = self.screen == Screen::Playing && !chatting;
|
||||
let playing = self.screen == Screen::Playing;
|
||||
let held = |k| playing && self.keys.contains(&k);
|
||||
let keys = Keys {
|
||||
forward: held(KeyCode::KeyW),
|
||||
@@ -2446,8 +2488,7 @@ impl Game<'_> {
|
||||
if r.destroy_delay > 0 {
|
||||
r.destroy_delay -= 1;
|
||||
}
|
||||
let chatting = r.chat_input.is_some();
|
||||
if !self.left || self.screen != Screen::Playing || chatting {
|
||||
if !self.left || self.screen != Screen::Playing {
|
||||
self.stop_remote_mining();
|
||||
self.mining = None;
|
||||
return;
|
||||
@@ -2676,7 +2717,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// Left click: attack the targeted entity (MultiPlayerGameMode.attack).
|
||||
pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> {
|
||||
if self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) {
|
||||
if self.screen == Screen::Chat {
|
||||
return Ok(());
|
||||
}
|
||||
match button {
|
||||
@@ -2735,14 +2776,8 @@ impl Game<'_> {
|
||||
}
|
||||
match key {
|
||||
KeyCode::KeyT | KeyCode::Slash | KeyCode::Enter => {
|
||||
let text = if key == KeyCode::Slash { "/" } else { "" };
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.chat_input = Some(text.to_owned());
|
||||
}
|
||||
self.keys.clear();
|
||||
self.left = false;
|
||||
self.right = false;
|
||||
self.capture(false);
|
||||
// ChatScreen, over the server's command tree.
|
||||
self.open_chat(if key == KeyCode::Slash { "/" } else { "" });
|
||||
Ok(true)
|
||||
}
|
||||
KeyCode::KeyQ => {
|
||||
@@ -2779,84 +2814,6 @@ impl Game<'_> {
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
pub(super) fn remote_chat_open(&self) -> bool {
|
||||
self.remote.as_ref().is_some_and(|r| r.chat_input.is_some())
|
||||
}
|
||||
/// ChatScreen: typing, Enter to send, Escape to cancel.
|
||||
pub(super) fn remote_chat_key(&mut self, event: &winit::event::KeyEvent) {
|
||||
use winit::keyboard::Key;
|
||||
if event.state != winit::event::ElementState::Pressed {
|
||||
return;
|
||||
}
|
||||
let shortcut = self.edit_shortcut(event);
|
||||
let Some(r) = self.remote.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(input) = r.chat_input.as_mut() else {
|
||||
return;
|
||||
};
|
||||
// ChatScreen's input: an EditBox of 256.
|
||||
const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0);
|
||||
if let Some(shortcut) = shortcut {
|
||||
Self::append_shortcut(
|
||||
&mut self.text_selection,
|
||||
&mut self.clipboard,
|
||||
INPUT,
|
||||
input,
|
||||
shortcut,
|
||||
256,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Logical keys: the text, not the scancode, decides (layouts, virtual keyboards).
|
||||
let named = match &event.logical_key {
|
||||
Key::Named(n) => Some(*n),
|
||||
_ => None,
|
||||
};
|
||||
self.remote_chat_input(named, event.text.as_deref());
|
||||
}
|
||||
/// A named key or typed text in the chat input (the keyboard, or a
|
||||
/// controller's on-screen keyboard).
|
||||
pub(super) fn remote_chat_input(
|
||||
&mut self,
|
||||
named: Option<winit::keyboard::NamedKey>,
|
||||
text: Option<&str>,
|
||||
) {
|
||||
use winit::keyboard::NamedKey;
|
||||
const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0);
|
||||
let Some(r) = self.remote.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(input) = r.chat_input.as_mut() else {
|
||||
return;
|
||||
};
|
||||
match named {
|
||||
Some(NamedKey::Escape) => {
|
||||
r.chat_input = None;
|
||||
self.capture(true);
|
||||
}
|
||||
Some(NamedKey::Backspace) => {
|
||||
if !self.text_selection.take(INPUT, input) {
|
||||
input.pop();
|
||||
}
|
||||
}
|
||||
Some(NamedKey::Enter) => {
|
||||
let message = r.chat_input.take().unwrap_or_default();
|
||||
self.send_chat(&message);
|
||||
self.capture(true);
|
||||
}
|
||||
_ => {
|
||||
if let Some(text) = text {
|
||||
self.text_selection.take(INPUT, input);
|
||||
for c in text.chars().filter(|c| !c.is_control()) {
|
||||
if input.chars().count() < 256 {
|
||||
input.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// ClientPacketListener.sendChat / sendCommand (unsigned).
|
||||
pub(super) fn send_chat(&mut self, message: &str) {
|
||||
let message = message.trim();
|
||||
@@ -3199,11 +3156,11 @@ impl Game<'_> {
|
||||
let Some(r) = &self.remote else { return };
|
||||
let atlas = &self.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let open = r.chat_input.is_some();
|
||||
let open = self.screen == Screen::Chat;
|
||||
let now = Instant::now();
|
||||
let mut y = h - 48.0;
|
||||
// Container screens cover the chat (vanilla draws them over the HUD).
|
||||
let shown = if matches!(self.screen, Screen::Playing | Screen::Dead) {
|
||||
let shown = if matches!(self.screen, Screen::Playing | Screen::Dead | Screen::Chat) {
|
||||
if open { 20 } else { 10 }
|
||||
} else {
|
||||
0
|
||||
@@ -3231,16 +3188,6 @@ impl Game<'_> {
|
||||
batch.text(atlas, text, 4.0, y, rgba(255, 255, 255, a), true);
|
||||
y -= 9.0;
|
||||
}
|
||||
if let Some(input) = &r.chat_input {
|
||||
batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, 128));
|
||||
let blink = (self.started.elapsed().as_millis() / 300).is_multiple_of(2);
|
||||
let shown = if blink {
|
||||
format!("{input}_")
|
||||
} else {
|
||||
input.clone()
|
||||
};
|
||||
batch.text(atlas, &shown, 4.0, h - 12.0, rgba(224, 224, 224, 255), true);
|
||||
}
|
||||
if let Some((text, at)) = &r.action_bar
|
||||
&& now.duration_since(*at) < Duration::from_secs(3)
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@ pub const HELP: &[&str] = &[
|
||||
"fill X1 Y1 Z1 X2 Y2 Z2 STATE fill a box with a block state without updates",
|
||||
"particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)",
|
||||
"signedit X Y Z [front|back] open the sign editor for the sign at X Y Z",
|
||||
"section-draws [flat|indirect] how terrain sections are drawn (A/B checks); replies the mode",
|
||||
];
|
||||
|
||||
impl Game<'_> {
|
||||
|
||||
@@ -598,9 +598,7 @@ impl Game<'_> {
|
||||
/// objective.
|
||||
pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) {
|
||||
use horizon_client::tab_list::{self, TabInputs};
|
||||
let chatting = self.remote.is_some() && self.remote_chat_open();
|
||||
let key = self.screen == super::Screen::Playing
|
||||
&& !chatting
|
||||
&& self.keys.contains(&winit::keyboard::KeyCode::Tab);
|
||||
let (players, online_mode, upside_down) = match self.remote_tab_players() {
|
||||
Some(remote) => remote,
|
||||
|
||||
@@ -80,6 +80,15 @@ pub(super) struct SculkState {
|
||||
ticks: u32,
|
||||
pub tracker_loaded: bool,
|
||||
}
|
||||
|
||||
impl SculkState {
|
||||
/// Exchange the level-held parts (its sculk block entities and the
|
||||
/// chunks scanned for them) with another level's (game/levels.rs).
|
||||
pub(super) fn swap_level(&mut self, other: &mut Self) {
|
||||
std::mem::swap(&mut self.index, &mut other.index);
|
||||
std::mem::swap(&mut self.known, &mut other.known);
|
||||
}
|
||||
}
|
||||
/// An insertion-ordered set of block positions (`Level.blockEntityTickers`
|
||||
/// keeps the order block entities were added in).
|
||||
#[derive(Default)]
|
||||
@@ -1168,6 +1177,9 @@ impl Game<'_> {
|
||||
|
||||
/// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`.
|
||||
pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) {
|
||||
self.for_each_player(|g| g.darkness_on_player(at, radius));
|
||||
}
|
||||
fn darkness_on_player(&mut self, at: [f64; 3], radius: f64) {
|
||||
if self.creative || self.spectator() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,59 +1,81 @@
|
||||
//! A server's player between dimensions.
|
||||
//! A server's players between dimensions.
|
||||
//!
|
||||
//! The server holds one level at a time, as the in-frame game does. While a
|
||||
//! single player is online (single player on the server thread, or a world
|
||||
//! with one player in it) that level follows the player through Nether and
|
||||
//! End portals, and back to the Overworld when the player respawns. The swap
|
||||
//! is the in-frame path's (`switch_level`, the portal plans, the arrival
|
||||
//! search); the player hears it as `ServerPlayer.teleport` into another
|
||||
//! level: a Respawn packet keeping all data, then a teleport to the exit once
|
||||
//! the destination has loaded. With several players online the portals do
|
||||
//! not take anyone yet: that needs the server to hold every level.
|
||||
//! A server holds a level per dimension (game/levels.rs). A player who steps
|
||||
//! into a Nether or End portal moves to the destination's level, which opens
|
||||
//! if nobody was there: the swap is the in-frame path's portal plans and
|
||||
//! arrival search, and the player hears it as `ServerPlayer.teleport` into
|
||||
//! another level: a Respawn packet keeping all data, then a teleport to the
|
||||
//! exit once the destination has loaded around them.
|
||||
|
||||
use super::nether_portal::PLAYER_DELAY;
|
||||
use super::nether_portal::{PLAYER_DELAY, Plan};
|
||||
use super::{Dim, Game, lan::LanHost};
|
||||
use horizon_client::lan::hub::TickCtx;
|
||||
use horizon_core::{geometry::Vec3, position::BlockPos};
|
||||
|
||||
/// A trip under way: the level has changed and its chunks are loading
|
||||
/// around `target`.
|
||||
/// A trip under way: the player is in the destination's level, whose
|
||||
/// chunks are loading around `target`.
|
||||
pub(super) struct Trip {
|
||||
conn: u32,
|
||||
dim: Dim,
|
||||
target: Vec3,
|
||||
/// Through an End portal (or out of the End by respawning).
|
||||
/// Through an End portal.
|
||||
end: bool,
|
||||
/// The Nether portal plan, whose exit is found or built on arrival.
|
||||
plan: Option<Plan>,
|
||||
}
|
||||
|
||||
/// The lone player's box: Player's standing dimensions.
|
||||
/// A player's box: Player's standing dimensions.
|
||||
const WIDTH: f64 = 0.6;
|
||||
const HEIGHT: f64 = 1.8;
|
||||
|
||||
impl Trip {
|
||||
pub(super) fn is(&self, conn: u32) -> bool {
|
||||
self.conn == conn
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Whether `conn` is between two levels: the server leaves its body
|
||||
/// alone until it arrives.
|
||||
pub(super) fn on_server_trip(&self, conn: u32) -> bool {
|
||||
self.server_trip.as_ref().is_some_and(|t| t.conn == conn)
|
||||
self.server_trips.iter().any(|t| t.conn == conn)
|
||||
}
|
||||
|
||||
/// Per server tick, after the guests' own: `Entity.handlePortal` for the
|
||||
/// lone player (Nether portals count up their transition time, End
|
||||
/// portals take it at once), or the arrival of the trip under way.
|
||||
/// Per server tick in each level, after the guests' own: the arrivals of
|
||||
/// the trips into this level, then `Entity.handlePortal` for each player
|
||||
/// in it (Nether portals count up their transition time, End portals
|
||||
/// take them at once).
|
||||
pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) {
|
||||
if self.options.dedicated.is_none() {
|
||||
return;
|
||||
}
|
||||
if self.server_trip.is_some() {
|
||||
self.arrive_server_trip(host);
|
||||
return;
|
||||
self.arrive_server_trips(host);
|
||||
let conns: Vec<u32> = host
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
|
||||
.map(|g| g.conn)
|
||||
.collect();
|
||||
for conn in conns {
|
||||
if self.on_server_trip(conn) {
|
||||
continue;
|
||||
}
|
||||
// `Entity.portalProcess` and `portalCooldown` are the player's own.
|
||||
let mut portal = host.play.entry(conn).or_default().portal;
|
||||
std::mem::swap(&mut self.portals.player, &mut portal);
|
||||
self.handle_server_portal(host, conn);
|
||||
std::mem::swap(&mut self.portals.player, &mut portal);
|
||||
host.play.entry(conn).or_default().portal = portal;
|
||||
}
|
||||
let [g] = host.hub.guests.as_slice() else {
|
||||
}
|
||||
|
||||
/// `Entity.handlePortal` for one player, whose portal state is in place.
|
||||
fn handle_server_portal(&mut self, host: &mut LanHost, conn: u32) {
|
||||
let Some(g) = host.hub.guest(conn) else {
|
||||
return;
|
||||
};
|
||||
if !g.placed || !g.loaded || g.dead || g.spectator() {
|
||||
return;
|
||||
}
|
||||
let (conn, at, invulnerable, sleeping) = (
|
||||
g.conn,
|
||||
let (at, invulnerable, sleeping) = (
|
||||
Vec3::new(g.position[0], g.position[1], g.position[2]),
|
||||
g.creative(),
|
||||
g.sleeping,
|
||||
@@ -70,7 +92,7 @@ impl Game<'_> {
|
||||
} else {
|
||||
Dim::End
|
||||
};
|
||||
self.start_server_trip(host, conn, target, true);
|
||||
self.start_server_trip(host, conn, target, None);
|
||||
}
|
||||
// Entity.setAsInsidePortal while cooling down restarts the cooldown.
|
||||
self.portals.player.cooldown = 10;
|
||||
@@ -93,11 +115,10 @@ impl Game<'_> {
|
||||
if !self.may_enter(plan.dim) {
|
||||
return;
|
||||
}
|
||||
self.portals.travel = Some(plan);
|
||||
self.start_server_trip(host, conn, plan.dim, false);
|
||||
self.start_server_trip(host, conn, plan.dim, Some(plan));
|
||||
}
|
||||
|
||||
/// A Nether portal block the lone player's box is in.
|
||||
/// A Nether portal block a player's box is in.
|
||||
fn nether_portal_inside(&self, at: Vec3) -> Option<BlockPos> {
|
||||
let w = WIDTH / 2.0 - 1.0e-5;
|
||||
let lo = [at.x - w, at.y + 1.0e-5, at.z - w];
|
||||
@@ -114,9 +135,16 @@ impl Game<'_> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The level swap, and the player told it is in the new level at the
|
||||
/// approximate exit while it loads.
|
||||
fn start_server_trip(&mut self, host: &mut LanHost, conn: u32, target: Dim, end: bool) {
|
||||
/// The player moves to `target`'s level (opened if nobody was there)
|
||||
/// and is told it is there, at the approximate exit, while it loads. The
|
||||
/// level whose tick is running is put back in place afterwards.
|
||||
fn start_server_trip(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
target: Dim,
|
||||
plan: Option<Plan>,
|
||||
) {
|
||||
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return;
|
||||
};
|
||||
@@ -124,105 +152,100 @@ impl Game<'_> {
|
||||
let from = Vec3::new(g.position[0], g.position[1], g.position[2]);
|
||||
let yaw = g.yaw;
|
||||
let source = self.dim;
|
||||
let end = plan.is_none();
|
||||
// Coordinates scale by 8 between the Overworld and the Nether; an
|
||||
// End portal has fixed destinations.
|
||||
let scale = match (source, target) {
|
||||
(Dim::Overworld, Dim::Nether) | (Dim::End, Dim::Nether) => 1.0 / 8.0,
|
||||
(Dim::Nether, Dim::Overworld) => 8.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
self.end_portal_travel = end;
|
||||
let switched = self.switch_level(target, from);
|
||||
let scaled = self.end_destination(target).unwrap_or(Vec3::new(
|
||||
from.x * scale,
|
||||
from.y,
|
||||
from.z * scale,
|
||||
));
|
||||
self.end_portal_travel = false;
|
||||
let destination = match switched {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
log::error!("could not open {}: {e}", target.id());
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self.enter_level(Some(host), target) {
|
||||
log::error!("could not open {}: {e}", target.id());
|
||||
return;
|
||||
}
|
||||
let destination = match plan {
|
||||
Some(plan) => self.arrival_centre(&plan),
|
||||
None => scaled,
|
||||
};
|
||||
let destination = match self.portals.travel {
|
||||
Some(plan) if !end => self.arrival_centre(&plan),
|
||||
_ => destination,
|
||||
};
|
||||
host.hub.set_dimension(target.id());
|
||||
let at = [destination.x, destination.y, destination.z];
|
||||
let ctx = self.server_ctx();
|
||||
host.hub.change_level(i, at, yaw, &ctx);
|
||||
self.as_guest(host, conn, |g| g.trigger_dimension(source, target));
|
||||
self.server_trip = Some(Trip {
|
||||
self.server_trips.push(Trip {
|
||||
conn,
|
||||
dim: target,
|
||||
target: destination,
|
||||
end,
|
||||
plan,
|
||||
});
|
||||
if let Err(e) = self.enter_level(Some(host), source) {
|
||||
log::error!("could not reopen {}: {e}", source.id());
|
||||
}
|
||||
}
|
||||
|
||||
/// Once the destination has loaded around the trip's target: the exit
|
||||
/// (the Nether portal found or built, the End platform, the Overworld's
|
||||
/// spawn column) and the teleport there.
|
||||
fn arrive_server_trip(&mut self, host: &mut LanHost) {
|
||||
let Some(trip) = self.server_trip.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else {
|
||||
// They left on the way.
|
||||
self.server_trip = None;
|
||||
self.portals.travel = None;
|
||||
return;
|
||||
};
|
||||
let (cx, cz) = (
|
||||
(trip.target.x.floor() as i32) >> 4,
|
||||
(trip.target.z.floor() as i32) >> 4,
|
||||
);
|
||||
if !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
|
||||
return;
|
||||
}
|
||||
let Some(trip) = self.server_trip.take() else {
|
||||
return;
|
||||
};
|
||||
self.resolve_arrivals();
|
||||
let (position, yaw) = if trip.end {
|
||||
match self.end_arrival(trip.target) {
|
||||
Ok((at, yaw)) => (at, yaw.unwrap_or(host.hub.guests[i].yaw)),
|
||||
Err(e) => {
|
||||
log::error!("End arrival: {e}");
|
||||
(trip.target, host.hub.guests[i].yaw)
|
||||
}
|
||||
/// The trips into the level in place whose destination has loaded
|
||||
/// around their target: the exit (the Nether portal found or built, the
|
||||
/// End platform, the Overworld's spawn column) and the teleport there.
|
||||
fn arrive_server_trips(&mut self, host: &mut LanHost) {
|
||||
let mut k = 0;
|
||||
while k < self.server_trips.len() {
|
||||
let trip = &self.server_trips[k];
|
||||
let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else {
|
||||
// They left on the way.
|
||||
self.server_trips.remove(k);
|
||||
continue;
|
||||
};
|
||||
let (cx, cz) = (
|
||||
(trip.target.x.floor() as i32) >> 4,
|
||||
(trip.target.z.floor() as i32) >> 4,
|
||||
);
|
||||
if trip.dim != self.dim
|
||||
|| !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz)))
|
||||
{
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
let plan = self.portals.travel.take();
|
||||
let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan));
|
||||
match (plan, exit) {
|
||||
(Some(plan), Some(exit)) => {
|
||||
let (at, rotation) = self.arrival(&plan, exit);
|
||||
(at, host.hub.guests[i].yaw + rotation)
|
||||
let trip = self.server_trips.remove(k);
|
||||
self.resolve_arrivals();
|
||||
let yaw = host.hub.guests[i].yaw;
|
||||
let (position, yaw) = if trip.end {
|
||||
match self.end_arrival(trip.target) {
|
||||
Ok((at, turned)) => (at, turned.unwrap_or(yaw)),
|
||||
Err(e) => {
|
||||
log::error!("End arrival: {e}");
|
||||
(trip.target, yaw)
|
||||
}
|
||||
}
|
||||
_ => (trip.target, host.hub.guests[i].yaw),
|
||||
}
|
||||
};
|
||||
// Player.getDimensionChangingDelay.
|
||||
self.portals.player.cooldown = 10;
|
||||
let g = &mut host.hub.guests[i];
|
||||
g.yaw = yaw;
|
||||
// A new body at the exit: no fall distance or motion carried over.
|
||||
g.motion = None;
|
||||
host.hub
|
||||
.teleport(i, Some([position.x, position.y, position.z]));
|
||||
}
|
||||
|
||||
/// `PlayerList.respawn` away from the Overworld: the lone player's level
|
||||
/// goes back to the Overworld first, where the world spawn is.
|
||||
pub(super) fn respawn_level(&mut self, host: &mut LanHost) {
|
||||
if self.options.dedicated.is_none() || self.dim == Dim::Overworld {
|
||||
return;
|
||||
} else {
|
||||
let exit = trip
|
||||
.plan
|
||||
.as_ref()
|
||||
.and_then(|plan| self.nether_exit_portal(plan));
|
||||
match (trip.plan, exit) {
|
||||
(Some(plan), Some(exit)) => {
|
||||
let (at, rotation) = self.arrival(&plan, exit);
|
||||
(at, yaw + rotation)
|
||||
}
|
||||
_ => (trip.target, yaw),
|
||||
}
|
||||
};
|
||||
// Player.getDimensionChangingDelay.
|
||||
host.play.entry(trip.conn).or_default().portal.cooldown = 10;
|
||||
let g = &mut host.hub.guests[i];
|
||||
g.yaw = yaw;
|
||||
// A new body at the exit: no fall distance or motion carried over.
|
||||
g.motion = None;
|
||||
host.hub
|
||||
.teleport(i, Some([position.x, position.y, position.z]));
|
||||
}
|
||||
if host.hub.guests.len() != 1 {
|
||||
return;
|
||||
}
|
||||
self.server_trip = None;
|
||||
self.portals.travel = None;
|
||||
self.end_portal_travel = true;
|
||||
let from = self.spawn.unwrap_or(Vec3::ZERO);
|
||||
let switched = self.switch_level(Dim::Overworld, from);
|
||||
self.end_portal_travel = false;
|
||||
if let Err(e) = switched {
|
||||
log::error!("could not open the Overworld: {e}");
|
||||
return;
|
||||
}
|
||||
host.hub.set_dimension(Dim::Overworld.id());
|
||||
}
|
||||
|
||||
/// The hub's view of the server for packets sent outside its own tick.
|
||||
|
||||
@@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]
|
||||
}
|
||||
|
||||
mod arena;
|
||||
mod flat;
|
||||
mod java_stages;
|
||||
mod lod;
|
||||
mod occlusion;
|
||||
@@ -102,6 +103,8 @@ struct SectionGpu {
|
||||
faces: crate::mesher::FaceGroups,
|
||||
sort: translucency::SortState,
|
||||
sorted_indices: Option<(u32, u64)>,
|
||||
/// Its id for flat draws (`flat::Flat::add`), when they are on.
|
||||
flat_id: Option<u32>,
|
||||
}
|
||||
/// Line segments the hit outline can hold.
|
||||
const MAX_OUTLINE_EDGES: u64 = 256;
|
||||
@@ -254,6 +257,10 @@ pub struct Renderer {
|
||||
pub config: wgpu::SurfaceConfiguration,
|
||||
solid: wgpu::RenderPipeline,
|
||||
translucent: wgpu::RenderPipeline,
|
||||
/// Flat section draws (`flat`), where multi-draw is emulated.
|
||||
flat: Option<flat::Flat>,
|
||||
/// `flat` draws this frame's sections (off: the per-section draws).
|
||||
flat_on: bool,
|
||||
sky: wgpu::RenderPipeline,
|
||||
dark_disc: wgpu::RenderPipeline,
|
||||
lines: wgpu::RenderPipeline,
|
||||
@@ -362,6 +369,10 @@ pub struct Renderer {
|
||||
pub info: wgpu::AdapterInfo,
|
||||
pub suspended: bool,
|
||||
pub drawn_sections: usize,
|
||||
/// Last frame's section draws (face ranges and translucent sections),
|
||||
/// and the draw calls the backend issued for them.
|
||||
pub section_draws: usize,
|
||||
pub section_draw_calls: usize,
|
||||
pub uploaded_bytes: u64,
|
||||
started: Instant,
|
||||
/// Write the next presented frame to this PNG path (control socket).
|
||||
@@ -793,18 +804,19 @@ impl Renderer {
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &debug_line_attributes,
|
||||
})];
|
||||
let pipeline = |label: &str,
|
||||
vertex: &str,
|
||||
fragment: &str,
|
||||
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
cull: Option<wgpu::Face>,
|
||||
depth_write: bool,
|
||||
depth_test: bool,
|
||||
blend: Option<wgpu::BlendState>| {
|
||||
let pipeline_in = |layout: &wgpu::PipelineLayout,
|
||||
label: &str,
|
||||
vertex: &str,
|
||||
fragment: &str,
|
||||
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
cull: Option<wgpu::Face>,
|
||||
depth_write: bool,
|
||||
depth_test: bool,
|
||||
blend: Option<wgpu::BlendState>| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(&layout),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some(vertex),
|
||||
@@ -845,6 +857,28 @@ impl Renderer {
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let pipeline = |label: &str,
|
||||
vertex: &str,
|
||||
fragment: &str,
|
||||
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
cull: Option<wgpu::Face>,
|
||||
depth_write: bool,
|
||||
depth_test: bool,
|
||||
blend: Option<wgpu::BlendState>| {
|
||||
pipeline_in(
|
||||
&layout,
|
||||
label,
|
||||
vertex,
|
||||
fragment,
|
||||
buffers,
|
||||
topology,
|
||||
cull,
|
||||
depth_write,
|
||||
depth_test,
|
||||
blend,
|
||||
)
|
||||
};
|
||||
let tri = wgpu::PrimitiveTopology::TriangleList;
|
||||
let solid = pipeline(
|
||||
"Terrain solid",
|
||||
@@ -1661,7 +1695,34 @@ impl Renderer {
|
||||
std::mem::size_of::<TerrainVertex>() as u64,
|
||||
1 << 20,
|
||||
);
|
||||
let sorted_indices = arena::Arena::indices(&device, 1 << 16);
|
||||
// Sections as one index list per frame where multi-draw is emulated.
|
||||
let flat = flat::wanted(&adapter, &device).then(|| {
|
||||
let buffers = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<TerrainVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &TERRAIN_ATTRIBUTES,
|
||||
})];
|
||||
flat::Flat::new(
|
||||
&device,
|
||||
&bindings,
|
||||
arena.page_vertices(),
|
||||
|layout, label, fragment, blend| {
|
||||
pipeline_in(
|
||||
layout,
|
||||
label,
|
||||
"vs_terrain_flat",
|
||||
fragment,
|
||||
&buffers,
|
||||
tri,
|
||||
Some(wgpu::Face::Back),
|
||||
true,
|
||||
true,
|
||||
blend,
|
||||
)
|
||||
},
|
||||
)
|
||||
});
|
||||
let sorted_indices = arena::Arena::indices(&device, 1 << 16, flat.is_some());
|
||||
let indirect = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Section draws"),
|
||||
size: 1024 * 20,
|
||||
@@ -1696,6 +1757,8 @@ impl Renderer {
|
||||
config,
|
||||
solid,
|
||||
translucent,
|
||||
flat_on: flat.is_some(),
|
||||
flat,
|
||||
sky,
|
||||
dark_disc,
|
||||
lines,
|
||||
@@ -1779,6 +1842,8 @@ impl Renderer {
|
||||
info,
|
||||
suspended: size.width == 0 || size.height == 0,
|
||||
drawn_sections: 0,
|
||||
section_draws: 0,
|
||||
section_draw_calls: 0,
|
||||
uploaded_bytes: 0,
|
||||
started: Instant::now(),
|
||||
screenshot: None,
|
||||
@@ -1859,30 +1924,12 @@ impl Renderer {
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
}
|
||||
/// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available.
|
||||
/// VSync, unless Horizon's present-mode setting names a supported mode.
|
||||
/// VSync on presents with Fifo, capped to the display's refresh rate in a
|
||||
/// window and in fullscreen alike; Horizon's present-mode setting applies
|
||||
/// only with VSync off (`window::chosen_present_mode`).
|
||||
pub fn set_present_mode(&mut self, vsync: bool, mode: crate::graphics::PresentMode) {
|
||||
use crate::graphics::PresentMode as P;
|
||||
let wanted = match mode {
|
||||
P::Auto => None,
|
||||
P::Fifo => Some(wgpu::PresentMode::Fifo),
|
||||
P::Mailbox => Some(wgpu::PresentMode::Mailbox),
|
||||
P::Immediate => Some(wgpu::PresentMode::Immediate),
|
||||
};
|
||||
match wanted.filter(|m| self.present_modes.contains(m)) {
|
||||
Some(m) => {
|
||||
if self.config.present_mode != m
|
||||
&& let Some(surface) = &self.surface
|
||||
{
|
||||
self.config.present_mode = m;
|
||||
surface.configure(&self.device, &self.config);
|
||||
}
|
||||
}
|
||||
None => self.set_vsync(vsync),
|
||||
}
|
||||
}
|
||||
pub fn set_vsync(&mut self, vsync: bool) {
|
||||
use crate::window::{PresentMode, vsync_present_mode};
|
||||
use crate::window::{PresentMode, chosen_present_mode};
|
||||
let supported: Vec<PresentMode> = self
|
||||
.present_modes
|
||||
.iter()
|
||||
@@ -1893,8 +1940,13 @@ impl Renderer {
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
// GpuSurface.PresentMode.getSupportedVsyncMode.
|
||||
let mode = match vsync_present_mode(&supported, vsync) {
|
||||
let setting = match mode {
|
||||
P::Auto => None,
|
||||
P::Fifo => Some(PresentMode::Fifo),
|
||||
P::Mailbox => Some(PresentMode::Mailbox),
|
||||
P::Immediate => Some(PresentMode::Immediate),
|
||||
};
|
||||
let mode = match chosen_present_mode(&supported, vsync, setting) {
|
||||
Some(PresentMode::Mailbox) => wgpu::PresentMode::Mailbox,
|
||||
Some(PresentMode::Immediate) => wgpu::PresentMode::Immediate,
|
||||
_ => wgpu::PresentMode::Fifo,
|
||||
@@ -1920,6 +1972,18 @@ impl Renderer {
|
||||
}
|
||||
self.depth = Self::depth(&self.device, &self.config);
|
||||
}
|
||||
/// Whether sections are drawn as one index list per frame (`flat`).
|
||||
pub fn flat_draws(&self) -> bool {
|
||||
self.flat_on
|
||||
}
|
||||
/// Switches between flat and per-section draws, for A/B checks.
|
||||
pub fn set_flat_draws(&mut self, on: bool) -> Result<()> {
|
||||
if on && self.flat.is_none() {
|
||||
return Err("flat section draws are off on this device".into());
|
||||
}
|
||||
self.flat_on = on;
|
||||
Ok(())
|
||||
}
|
||||
pub fn section_count(&self) -> usize {
|
||||
self.sections.len()
|
||||
}
|
||||
@@ -1970,6 +2034,10 @@ impl Renderer {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let flat_id = self
|
||||
.flat
|
||||
.as_mut()
|
||||
.map(|f| f.add(&self.device, &self.queue, page, start, vertices));
|
||||
let stride = std::mem::size_of::<TerrainVertex>() as u64;
|
||||
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
|
||||
if !part.is_empty() {
|
||||
@@ -1997,6 +2065,7 @@ impl Renderer {
|
||||
.collect(),
|
||||
),
|
||||
sorted_indices,
|
||||
flat_id,
|
||||
})
|
||||
}
|
||||
/// Draws `count` section draws from `first` with the arena and section
|
||||
@@ -2030,6 +2099,9 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
fn release_mesh(&mut self, s: SectionGpu) {
|
||||
if let (Some(flat), Some(id)) = (&mut self.flat, s.flat_id) {
|
||||
flat.remove(id);
|
||||
}
|
||||
if let Some((page, start)) = s.sorted_indices {
|
||||
self.sorted_indices
|
||||
.release(page, start, u64::from(s.translucent) * 6);
|
||||
@@ -2047,6 +2119,9 @@ impl Renderer {
|
||||
self.lods.clear();
|
||||
self.detail_columns.clear();
|
||||
self.arena.clear();
|
||||
if let Some(flat) = &mut self.flat {
|
||||
flat.clear();
|
||||
}
|
||||
self.sorted_indices.clear();
|
||||
self.translucency_cursor = 0;
|
||||
self.occlusion.clear();
|
||||
@@ -2241,6 +2316,9 @@ impl Renderer {
|
||||
pub fn render(&mut self, frame: &Frame) -> Result<bool> {
|
||||
self.arena.trim();
|
||||
self.sorted_indices.trim();
|
||||
if let Some(flat) = &mut self.flat {
|
||||
flat.trim(|page| self.arena.has_page(page));
|
||||
}
|
||||
if self.suspended {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -2431,18 +2509,22 @@ impl Renderer {
|
||||
let culling = !frame.title && frame.cave_culling;
|
||||
if culling {
|
||||
let radius = (frame.detail_distance / 16.0) as i32 + 2;
|
||||
self.occlusion.update(camera_section, radius);
|
||||
crate::spans::time("occlusion", || {
|
||||
self.occlusion.update(camera_section, radius)
|
||||
});
|
||||
}
|
||||
let reachable = &self.occlusion;
|
||||
let mut visible = std::mem::take(&mut self.visible);
|
||||
visible.clear();
|
||||
self.sections.visible(
|
||||
camera,
|
||||
(frame.detail_distance / 16.0) as i32,
|
||||
&view,
|
||||
|k| !culling || reachable.contains(k),
|
||||
&mut visible,
|
||||
);
|
||||
crate::spans::time("visibility", || {
|
||||
self.sections.visible(
|
||||
camera,
|
||||
(frame.detail_distance / 16.0) as i32,
|
||||
&view,
|
||||
|k| !culling || reachable.contains(k),
|
||||
&mut visible,
|
||||
)
|
||||
});
|
||||
let mut visible_lods = std::mem::take(&mut self.visible_lods);
|
||||
visible_lods.clear();
|
||||
if frame.title {
|
||||
@@ -2600,7 +2682,49 @@ impl Renderer {
|
||||
}
|
||||
self.translucency_cursor += budget;
|
||||
let translucent_draws = self.draws.len() as u32 - solid_draws;
|
||||
if self.multi_draw && !self.draws.is_empty() {
|
||||
self.section_draws = self.draws.len();
|
||||
// Metal replays a multi-draw as one draw call per entry.
|
||||
self.section_draw_calls = if self.multi_draw && self.info.backend != wgpu::Backend::Metal {
|
||||
(0..self.draws.len())
|
||||
.filter(|&i| {
|
||||
i == 0
|
||||
|| i == solid_draws as usize
|
||||
|| self.draw_pages[i] != self.draw_pages[i - 1]
|
||||
})
|
||||
.count()
|
||||
} else {
|
||||
self.draws.len()
|
||||
};
|
||||
let flat_frame = match &mut self.flat {
|
||||
Some(flat)
|
||||
if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws =>
|
||||
{
|
||||
let sections = &self.sections;
|
||||
let lods = &self.lods;
|
||||
let sorted = &self.sorted_indices;
|
||||
crate::spans::time("flatten", || {
|
||||
flat.prepare(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
&mut self.uploads,
|
||||
&self.draws,
|
||||
&self.draw_pages,
|
||||
solid_draws as usize,
|
||||
visible
|
||||
.iter()
|
||||
.filter_map(|v| sections.get(v.slot).flat_id.map(|id| (id, v.origin)))
|
||||
.chain(visible_lods.iter().filter_map(|v| {
|
||||
lods[&v.key].mesh.flat_id.map(|id| (id, v.origin))
|
||||
})),
|
||||
|page| sorted.buffer(page).clone(),
|
||||
)
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if flat_frame {
|
||||
self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.calls.len());
|
||||
} else if self.multi_draw && !self.draws.is_empty() {
|
||||
if self.draws.len() as u64 > self.indirect_capacity {
|
||||
self.indirect_capacity = (self.draws.len() as u64).next_power_of_two();
|
||||
self.indirect = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
@@ -2835,10 +2959,22 @@ impl Renderer {
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
pass.set_pipeline(&self.solid);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, 0, solid_draws);
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.solid);
|
||||
flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
None => {
|
||||
pass.set_pipeline(&self.solid);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, 0, solid_draws);
|
||||
}
|
||||
}
|
||||
if entity_quads > 0 {
|
||||
pass.set_pipeline(&self.entity_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
@@ -2875,10 +3011,22 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..));
|
||||
pass.draw(0..4, debug_depth..debug_depth + debug_top);
|
||||
}
|
||||
pass.set_pipeline(&self.translucent);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, solid_draws, translucent_draws);
|
||||
match self.flat.as_ref().filter(|_| flat_frame) {
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.translucent);
|
||||
flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
None => {
|
||||
pass.set_pipeline(&self.translucent);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(&mut pass, solid_draws, translucent_draws);
|
||||
}
|
||||
}
|
||||
// LevelRenderer.executeClassicTransparency: translucent targets'
|
||||
// outlines follow terrain, so its blending cannot wash them out.
|
||||
if outline_edges > 0 && frame.outline_after_terrain {
|
||||
@@ -3119,7 +3267,8 @@ impl Renderer {
|
||||
.take()
|
||||
.map(|path| (path, self.copy_frame(&mut encoder, &target_texture)));
|
||||
self.uploads.finish(&encoder);
|
||||
let submission = self.queue.submit([encoder.finish()]);
|
||||
let commands = crate::spans::time("encode", || encoder.finish());
|
||||
let submission = crate::spans::time("submit", || self.queue.submit([commands]));
|
||||
if let Some(timer) = &mut self.gpu_timer {
|
||||
timer.submitted();
|
||||
timer.collect(&self.device, &mut self.gpu_times);
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
//! a frame binds it once and draws every section with indirect multi-draw.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Ranges are rounded up to this many vertices to limit fragmentation.
|
||||
const GRAIN: u64 = 256;
|
||||
/// Ranges are rounded up to this many vertices to limit fragmentation, and
|
||||
/// start at multiples of it (`flat` names sections by these blocks).
|
||||
pub const GRAIN: u64 = 256;
|
||||
/// The largest page, in bytes.
|
||||
pub const PAGE_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// Free vertex ranges: start -> length, never adjacent.
|
||||
#[derive(Debug, PartialEq)]
|
||||
@@ -65,8 +68,14 @@ impl Arena {
|
||||
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
|
||||
Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX)
|
||||
}
|
||||
pub fn indices(device: &wgpu::Device, capacity: u64) -> Self {
|
||||
Self::with_usage(device, 4, capacity, wgpu::BufferUsages::INDEX)
|
||||
/// Sorted translucent indices; `storage` when compute passes read them.
|
||||
pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self {
|
||||
let usage = if storage {
|
||||
wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE
|
||||
} else {
|
||||
wgpu::BufferUsages::INDEX
|
||||
};
|
||||
Self::with_usage(device, 4, capacity, usage)
|
||||
}
|
||||
fn with_usage(
|
||||
device: &wgpu::Device,
|
||||
@@ -75,7 +84,7 @@ impl Arena {
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> Self {
|
||||
// 256 MiB pages, or less where the device's buffers are smaller.
|
||||
let bytes = device.limits().max_buffer_size.min(256 << 20);
|
||||
let bytes = device.limits().max_buffer_size.min(PAGE_BYTES);
|
||||
let page_limit = (bytes / stride) / GRAIN * GRAIN;
|
||||
let capacity = capacity.next_multiple_of(GRAIN).min(page_limit);
|
||||
Self {
|
||||
@@ -132,6 +141,13 @@ impl Arena {
|
||||
pub fn bytes(&self) -> u64 {
|
||||
self.pages.iter().flatten().map(|p| p.capacity).sum::<u64>() * self.stride
|
||||
}
|
||||
/// The most vertices a page holds.
|
||||
pub fn page_vertices(&self) -> u64 {
|
||||
self.page_limit
|
||||
}
|
||||
pub fn has_page(&self, page: u32) -> bool {
|
||||
self.pages.get(page as usize).is_some_and(Option::is_some)
|
||||
}
|
||||
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
|
||||
&self.pages[page as usize]
|
||||
.as_ref()
|
||||
@@ -338,7 +354,7 @@ mod tests {
|
||||
};
|
||||
for mut arena in [
|
||||
Arena::new(&device, 28, GRAIN),
|
||||
Arena::indices(&device, GRAIN),
|
||||
Arena::indices(&device, GRAIN, false),
|
||||
] {
|
||||
arena.alloc(&device, &queue, GRAIN).unwrap();
|
||||
assert_eq!(arena.bytes(), arena.stride * GRAIN);
|
||||
@@ -397,7 +413,7 @@ mod tests {
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut arena = Arena::indices(&device, GRAIN);
|
||||
let mut arena = Arena::indices(&device, GRAIN, false);
|
||||
let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap();
|
||||
queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes());
|
||||
arena.video_memory_full = true;
|
||||
@@ -422,7 +438,7 @@ mod tests {
|
||||
let Some((device, queue)) = device() else {
|
||||
return;
|
||||
};
|
||||
let mut arena = Arena::indices(&device, GRAIN);
|
||||
let mut arena = Arena::indices(&device, GRAIN, false);
|
||||
arena.alloc(&device, &queue, GRAIN).unwrap();
|
||||
arena.video_memory_full = true;
|
||||
// Without mappable primary buffers nothing can spill: the request
|
||||
|
||||
@@ -0,0 +1,658 @@
|
||||
//! Flat section draws: where indirect multi-draw is emulated, as on Metal
|
||||
//! (wgpu replays it as one draw call per indirect entry), the frame's section
|
||||
//! draws are copied by a compute pass into one index list, in draw order, and
|
||||
//! drawn with one draw call per run of sections in the same arena page.
|
||||
//!
|
||||
//! The picture is the one the per-section draws give: the same triangles
|
||||
//! from the same vertices in the same order, through the same vertex and
|
||||
//! fragment code. Only where a vertex finds its section's origin changes:
|
||||
//! from the instance attribute to a table. A section's vertices fill whole
|
||||
//! blocks of `GRAIN` vertices of its page (the arena rounds every range up),
|
||||
//! so each block names one section: its id here, which indexes the frame's
|
||||
//! camera-relative origins (computed on the CPU exactly as for the instance
|
||||
//! attribute).
|
||||
use super::arena::GRAIN;
|
||||
|
||||
/// One section draw for `flatten.wgsl`: index count, first sorted index (or
|
||||
/// `QUADS` for a solid draw), base vertex, first index in the list.
|
||||
type Range = [u32; 4];
|
||||
const QUADS: u32 = u32::MAX;
|
||||
const GROUP_LIMIT: u32 = 65535;
|
||||
|
||||
struct PageTable {
|
||||
/// Section id of every block of the page.
|
||||
blocks: wgpu::Buffer,
|
||||
group: Option<wgpu::BindGroup>,
|
||||
}
|
||||
|
||||
/// A run of the frame's index list drawn from one arena page.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Call {
|
||||
pub page: u32,
|
||||
pub first: u32,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
pub struct Flat {
|
||||
pub solid: wgpu::RenderPipeline,
|
||||
pub translucent: wgpu::RenderPipeline,
|
||||
flatten: wgpu::ComputePipeline,
|
||||
compute_layout: wgpu::BindGroupLayout,
|
||||
draw_layout: wgpu::BindGroupLayout,
|
||||
blocks_per_page: u64,
|
||||
pages: Vec<Option<PageTable>>,
|
||||
free_ids: Vec<u32>,
|
||||
next_id: u32,
|
||||
origins: wgpu::Buffer,
|
||||
origin_capacity: u64,
|
||||
origin_data: Vec<[f32; 4]>,
|
||||
/// The frame's index list.
|
||||
pub indices: wgpu::Buffer,
|
||||
index_capacity: u64,
|
||||
ranges: wgpu::Buffer,
|
||||
range_capacity: u64,
|
||||
range_data: Vec<Range>,
|
||||
/// Segments of `range_data` by index source: (sorted index page or
|
||||
/// `None` for solid draws, first range, ranges).
|
||||
segments: Vec<(Option<u32>, u64, u64)>,
|
||||
empty: wgpu::Buffer,
|
||||
/// This frame's draw calls: solid ones, then translucent ones.
|
||||
pub calls: Vec<Call>,
|
||||
pub solid_calls: usize,
|
||||
/// Frames with fewer section draws keep the per-section draws.
|
||||
pub min_draws: usize,
|
||||
range_align: u64,
|
||||
}
|
||||
|
||||
/// Section draws from which a frame is drawn flat. Below it the index list
|
||||
/// costs the GPU more than the draw calls cost the CPU: on an M4 Pro at
|
||||
/// render distance 16 (2,900 draws) the copy and the list add about 0.4 ms
|
||||
/// of GPU time for 0.5–0.8 ms less CPU time; at 32 (9,300 draws) the CPU
|
||||
/// saves 1.3 ms.
|
||||
const MIN_DRAWS: usize = 4096;
|
||||
|
||||
/// Whether flat draws apply: the backend emulates multi-draw, and vertex
|
||||
/// shaders can read storage buffers large enough for an index page.
|
||||
/// `HORIZON_FLAT_DRAWS=1` draws every frame flat, `0` none.
|
||||
pub fn wanted(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool {
|
||||
match std::env::var("HORIZON_FLAT_DRAWS").as_deref() {
|
||||
Ok("0") => return false,
|
||||
Ok("1") => return supported(adapter, device),
|
||||
_ => {}
|
||||
}
|
||||
adapter.get_info().backend == wgpu::Backend::Metal && supported(adapter, device)
|
||||
}
|
||||
|
||||
fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool {
|
||||
let flags = adapter.get_downlevel_capabilities().flags;
|
||||
let limits = device.limits();
|
||||
flags.contains(wgpu::DownlevelFlags::VERTEX_STORAGE | wgpu::DownlevelFlags::COMPUTE_SHADERS)
|
||||
&& limits.max_storage_buffers_per_shader_stage >= 3
|
||||
&& limits.max_storage_buffer_binding_size >= super::arena::PAGE_BYTES
|
||||
}
|
||||
|
||||
fn storage(binding: u32, stage: wgpu::ShaderStages, read_only: bool) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: stage,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn buffer(
|
||||
device: &wgpu::Device,
|
||||
label: &str,
|
||||
size: u64,
|
||||
usage: wgpu::BufferUsages,
|
||||
) -> wgpu::Buffer {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(label),
|
||||
size: size.max(16),
|
||||
usage: usage | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Lays out the frame's index list: each draw's range (destinations in draw
|
||||
/// order) grouped by index source into `ranges`, every group padded to
|
||||
/// `align` entries for binding, with `segments` naming each group; and the
|
||||
/// draw calls, one per run of draws in the same vertex page, solid and
|
||||
/// translucent apart. Returns the first translucent call and the list's
|
||||
/// length.
|
||||
fn plan(
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
solid_draws: usize,
|
||||
align: u64,
|
||||
calls: &mut Vec<Call>,
|
||||
ranges: &mut Vec<Range>,
|
||||
segments: &mut Vec<(Option<u32>, u64, u64)>,
|
||||
) -> (usize, u64) {
|
||||
calls.clear();
|
||||
ranges.clear();
|
||||
segments.clear();
|
||||
let mut solid_calls = None;
|
||||
let mut total = 0u64;
|
||||
let mut by_source: Vec<(Option<u32>, Vec<Range>)> = Vec::new();
|
||||
for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() {
|
||||
let first = if sorted.is_some() { d[2] } else { QUADS };
|
||||
let range = [d[0], first, d[3], total as u32];
|
||||
match by_source.iter_mut().find(|(s, _)| *s == sorted) {
|
||||
Some((_, list)) => list.push(range),
|
||||
None => by_source.push((sorted, vec![range])),
|
||||
}
|
||||
if i == solid_draws {
|
||||
solid_calls = Some(calls.len());
|
||||
}
|
||||
match calls.last_mut() {
|
||||
Some(last) if last.page == page && i != solid_draws => last.count += d[0],
|
||||
_ => calls.push(Call {
|
||||
page,
|
||||
first: total as u32,
|
||||
count: d[0],
|
||||
}),
|
||||
}
|
||||
total += u64::from(d[0]);
|
||||
}
|
||||
for (source, list) in by_source {
|
||||
segments.push((source, ranges.len() as u64, list.len() as u64));
|
||||
ranges.extend(list);
|
||||
let padded = (ranges.len() as u64).next_multiple_of(align);
|
||||
ranges.resize(padded as usize, [0; 4]);
|
||||
}
|
||||
(solid_calls.unwrap_or(calls.len()), total)
|
||||
}
|
||||
|
||||
impl Flat {
|
||||
/// `pipeline(layout, label, vertex entry, fragment entry, blend)` builds a
|
||||
/// terrain pipeline as the per-section ones, without the origin buffer.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
terrain_layout: &wgpu::BindGroupLayout,
|
||||
page_vertices: u64,
|
||||
pipeline: impl Fn(
|
||||
&wgpu::PipelineLayout,
|
||||
&str,
|
||||
&str,
|
||||
Option<wgpu::BlendState>,
|
||||
) -> wgpu::RenderPipeline,
|
||||
) -> Self {
|
||||
let vertex = wgpu::ShaderStages::VERTEX;
|
||||
let compute = wgpu::ShaderStages::COMPUTE;
|
||||
let draw_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Flat section draws"),
|
||||
entries: &[storage(0, vertex, true), storage(1, vertex, true)],
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Flat terrain layout"),
|
||||
bind_group_layouts: &[Some(terrain_layout), Some(&draw_layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let compute_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
entries: &[
|
||||
storage(0, compute, true),
|
||||
storage(1, compute, true),
|
||||
storage(2, compute, false),
|
||||
],
|
||||
});
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
|
||||
});
|
||||
let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
layout: Some(
|
||||
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
bind_group_layouts: &[Some(&compute_layout)],
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
module: &module,
|
||||
entry_point: Some("flatten"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let storage_usage = wgpu::BufferUsages::STORAGE;
|
||||
Self {
|
||||
solid: pipeline(&layout, "Terrain solid (flat)", "fs_solid", None),
|
||||
translucent: pipeline(
|
||||
&layout,
|
||||
"Terrain translucent (flat)",
|
||||
"fs_translucent",
|
||||
Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
),
|
||||
flatten,
|
||||
compute_layout,
|
||||
draw_layout,
|
||||
blocks_per_page: page_vertices.div_ceil(GRAIN),
|
||||
pages: Vec::new(),
|
||||
free_ids: Vec::new(),
|
||||
next_id: 0,
|
||||
origins: buffer(device, "Section origins by id", 16, storage_usage),
|
||||
origin_capacity: 1,
|
||||
origin_data: Vec::new(),
|
||||
indices: buffer(
|
||||
device,
|
||||
"Flat section indices",
|
||||
16,
|
||||
wgpu::BufferUsages::INDEX | storage_usage,
|
||||
),
|
||||
index_capacity: 4,
|
||||
ranges: buffer(device, "Flat section ranges", 16, storage_usage),
|
||||
range_capacity: 1,
|
||||
range_data: Vec::new(),
|
||||
segments: Vec::new(),
|
||||
empty: buffer(device, "No sorted indices", 16, storage_usage),
|
||||
calls: Vec::new(),
|
||||
solid_calls: 0,
|
||||
min_draws: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") {
|
||||
0
|
||||
} else {
|
||||
MIN_DRAWS
|
||||
},
|
||||
range_align: (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16)
|
||||
.max(1),
|
||||
}
|
||||
}
|
||||
/// A section uploaded to `vertices` vertices from `start` of `page`: its
|
||||
/// id, which its blocks now name.
|
||||
pub fn add(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
page: u32,
|
||||
start: u64,
|
||||
vertices: u64,
|
||||
) -> u32 {
|
||||
let id = self.free_ids.pop().unwrap_or_else(|| {
|
||||
self.next_id += 1;
|
||||
self.next_id - 1
|
||||
});
|
||||
let page = page as usize;
|
||||
if self.pages.len() <= page {
|
||||
self.pages.resize_with(page + 1, || None);
|
||||
}
|
||||
let table = self.pages[page].get_or_insert_with(|| PageTable {
|
||||
blocks: buffer(
|
||||
device,
|
||||
"Section ids by block",
|
||||
self.blocks_per_page * 4,
|
||||
wgpu::BufferUsages::STORAGE,
|
||||
),
|
||||
group: None,
|
||||
});
|
||||
let first = start / GRAIN;
|
||||
let ids = vec![id; vertices.div_ceil(GRAIN) as usize];
|
||||
queue.write_buffer(&table.blocks, first * 4, bytemuck::cast_slice(&ids));
|
||||
id
|
||||
}
|
||||
pub fn remove(&mut self, id: u32) {
|
||||
self.free_ids.push(id);
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.pages.clear();
|
||||
self.free_ids.clear();
|
||||
self.next_id = 0;
|
||||
}
|
||||
/// Forgets the tables of pages the arena released.
|
||||
pub fn trim(&mut self, live: impl Fn(u32) -> bool) {
|
||||
for (i, page) in self.pages.iter_mut().enumerate() {
|
||||
if page.is_some() && !live(i as u32) {
|
||||
*page = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Builds the frame's index list from `draws` (`DrawIndexedIndirectArgs`:
|
||||
/// index count, instances, first index, base vertex, first instance),
|
||||
/// solid ones first, with their (vertex page, sorted index page) and
|
||||
/// the origins of the sections they draw by id. Records the copy into
|
||||
/// `encoder`; `calls` then lists the frame's draw calls. False when the
|
||||
/// frame cannot be drawn flat (the per-section draws then apply).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
uploads: &mut super::upload::Uploads,
|
||||
draws: &[[u32; 5]],
|
||||
pages: &[(u32, Option<u32>)],
|
||||
solid_draws: usize,
|
||||
origins: impl Iterator<Item = (u32, [f32; 3])>,
|
||||
sorted_page: impl Fn(u32) -> wgpu::Buffer,
|
||||
) -> bool {
|
||||
// Origins by section id.
|
||||
self.origin_data.clear();
|
||||
for (id, o) in origins {
|
||||
let id = id as usize;
|
||||
if self.origin_data.len() <= id {
|
||||
self.origin_data.resize(id + 1, [0.0; 4]);
|
||||
}
|
||||
self.origin_data[id] = [o[0], o[1], o[2], 0.0];
|
||||
}
|
||||
if self.origin_data.len() as u64 > self.origin_capacity {
|
||||
self.origin_capacity = (self.origin_data.len() as u64).next_power_of_two();
|
||||
self.origins = buffer(
|
||||
device,
|
||||
"Section origins by id",
|
||||
self.origin_capacity * 16,
|
||||
wgpu::BufferUsages::STORAGE,
|
||||
);
|
||||
for page in self.pages.iter_mut().flatten() {
|
||||
page.group = None;
|
||||
}
|
||||
}
|
||||
if !self.origin_data.is_empty() {
|
||||
uploads.buffer(
|
||||
encoder,
|
||||
&self.origins,
|
||||
0,
|
||||
bytemuck::cast_slice(&self.origin_data),
|
||||
);
|
||||
}
|
||||
let (solid_calls, total) = plan(
|
||||
draws,
|
||||
pages,
|
||||
solid_draws,
|
||||
self.range_align,
|
||||
&mut self.calls,
|
||||
&mut self.range_data,
|
||||
&mut self.segments,
|
||||
);
|
||||
self.solid_calls = solid_calls;
|
||||
if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size {
|
||||
self.calls.clear();
|
||||
self.solid_calls = 0;
|
||||
return false;
|
||||
}
|
||||
if self.range_data.len() as u64 > self.range_capacity {
|
||||
self.range_capacity = (self.range_data.len() as u64).next_power_of_two();
|
||||
self.ranges = buffer(
|
||||
device,
|
||||
"Flat section ranges",
|
||||
self.range_capacity * 16,
|
||||
wgpu::BufferUsages::STORAGE,
|
||||
);
|
||||
}
|
||||
if total > self.index_capacity {
|
||||
self.index_capacity = total.next_power_of_two();
|
||||
self.indices = buffer(
|
||||
device,
|
||||
"Flat section indices",
|
||||
self.index_capacity * 4,
|
||||
wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE,
|
||||
);
|
||||
}
|
||||
uploads.buffer(
|
||||
encoder,
|
||||
&self.ranges,
|
||||
0,
|
||||
bytemuck::cast_slice(&self.range_data),
|
||||
);
|
||||
let groups: Vec<(wgpu::BindGroup, u32)> = self
|
||||
.segments
|
||||
.iter()
|
||||
.map(|&(source, first, count)| {
|
||||
let sorted = source.map(&sorted_page);
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
layout: &self.compute_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &self.ranges,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
}),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sorted.as_ref().unwrap_or(&self.empty).as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.indices.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
(group, count as u32)
|
||||
})
|
||||
.collect();
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("Flatten section draws"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
pass.set_pipeline(&self.flatten);
|
||||
for (group, count) in &groups {
|
||||
pass.set_bind_group(0, group, &[]);
|
||||
pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1);
|
||||
}
|
||||
drop(pass);
|
||||
for page in self.calls.iter().map(|c| c.page) {
|
||||
let table = self.pages[page as usize]
|
||||
.as_mut()
|
||||
.expect("a drawn page has its block table");
|
||||
if table.group.is_none() {
|
||||
table.group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Flat section draws"),
|
||||
layout: &self.draw_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: table.blocks.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.origins.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
}));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Draws `calls` with a flat pipeline set and `vertices` giving each
|
||||
/// page's vertex buffer.
|
||||
pub fn draw<'a>(
|
||||
&self,
|
||||
pass: &mut wgpu::RenderPass<'_>,
|
||||
calls: &[Call],
|
||||
vertices: impl Fn(u32) -> &'a wgpu::Buffer,
|
||||
) {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for call in calls {
|
||||
let table = self.pages[call.page as usize]
|
||||
.as_ref()
|
||||
.and_then(|t| t.group.as_ref())
|
||||
.expect("prepared page");
|
||||
pass.set_vertex_buffer(0, vertices(call.page).slice(..));
|
||||
pass.set_bind_group(1, table, &[]);
|
||||
pass.draw_indexed(call.first..call.first + call.count, 0, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Draws as `render` writes them: solid (page, quads at a base vertex)
|
||||
/// first, then translucent (page, sorted page, count, first sorted index,
|
||||
/// base vertex).
|
||||
fn sample() -> (Vec<[u32; 5]>, Vec<(u32, Option<u32>)>, usize) {
|
||||
let draws = vec![
|
||||
[6 * 3, 1, 0, 0, 0],
|
||||
[6 * 2, 1, 0, 512, 1],
|
||||
[6, 1, 0, 256, 2],
|
||||
[6 * 4, 1, 0, 1024, 3],
|
||||
[6 * 2, 1, 6, 768, 1],
|
||||
[6, 1, 0, 40, 0],
|
||||
];
|
||||
let pages = vec![
|
||||
(0, None),
|
||||
(0, None),
|
||||
(1, None),
|
||||
(0, None),
|
||||
(0, Some(0)),
|
||||
(0, Some(1)),
|
||||
];
|
||||
(draws, pages, 4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_draws_runs_of_a_page_in_order() {
|
||||
let (draws, pages, solid) = sample();
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (solid_calls, total) = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
4,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
assert_eq!(total, 6 * 13);
|
||||
let call = |page, first, count| Call { page, first, count };
|
||||
// Pages 0, 0 | 1 | 0, then translucent 0, 0 (never merged with solid).
|
||||
assert_eq!(
|
||||
calls,
|
||||
[
|
||||
call(0, 0, 30),
|
||||
call(1, 30, 6),
|
||||
call(0, 36, 24),
|
||||
call(0, 60, 18)
|
||||
]
|
||||
);
|
||||
assert_eq!(solid_calls, 3);
|
||||
// Solid ranges, then each sorted page's, every group padded to 4.
|
||||
assert_eq!(segments, [(None, 0, 4), (Some(0), 4, 1), (Some(1), 8, 1)]);
|
||||
assert_eq!(ranges[3], [24, QUADS, 1024, 36]);
|
||||
assert_eq!(ranges[4], [12, 6, 768, 60]);
|
||||
assert_eq!(ranges[8], [6, 0, 40, 72]);
|
||||
assert_eq!(ranges.len(), 12);
|
||||
}
|
||||
|
||||
/// The compute pass writes exactly the indices the per-section draws
|
||||
/// read: quads 0 1 2 0 2 3 for solid draws, sorted indices otherwise,
|
||||
/// plus the base vertex.
|
||||
#[test]
|
||||
fn flatten_writes_the_indices_of_the_per_section_draws() {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
|
||||
eprintln!("no GPU adapter: skipped");
|
||||
return;
|
||||
};
|
||||
let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default()))
|
||||
else {
|
||||
eprintln!("no GPU device: skipped");
|
||||
return;
|
||||
};
|
||||
use wgpu::util::DeviceExt;
|
||||
let (draws, pages, solid) = sample();
|
||||
let align = (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16).max(1);
|
||||
let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let (_, total) = plan(
|
||||
&draws,
|
||||
&pages,
|
||||
solid,
|
||||
align,
|
||||
&mut calls,
|
||||
&mut ranges,
|
||||
&mut segments,
|
||||
);
|
||||
let sorted: [Vec<u32>; 2] = [
|
||||
(0..32).map(|i| (i * 7) % 32).collect(),
|
||||
(0..8).rev().collect(),
|
||||
];
|
||||
let mut expected = Vec::new();
|
||||
for (d, (_, page)) in draws.iter().zip(&pages) {
|
||||
for k in 0..d[0] {
|
||||
let i = match page {
|
||||
None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize],
|
||||
Some(p) => sorted[*p as usize][(d[2] + k) as usize],
|
||||
};
|
||||
expected.push(d[3] + i);
|
||||
}
|
||||
}
|
||||
let storage = |entries: &[u32]| {
|
||||
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: None,
|
||||
contents: bytemuck::cast_slice(entries),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
})
|
||||
};
|
||||
let range_buffer = storage(bytemuck::cast_slice(&ranges));
|
||||
let sorted_buffers = [storage(&sorted[0]), storage(&sorted[1]), storage(&[0; 4])];
|
||||
let out = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: total * 4,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let read = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: total * 4,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()),
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: None,
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some("flatten"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&Default::default());
|
||||
pass.set_pipeline(&pipeline);
|
||||
for &(source, first, count) in &segments {
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &range_buffer,
|
||||
offset: first * 16,
|
||||
size: wgpu::BufferSize::new(count * 16),
|
||||
}),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: sorted_buffers[source.map_or(2, |p| p as usize)]
|
||||
.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: out.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.dispatch_workgroups(count as u32, 1, 1);
|
||||
}
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(&out, 0, &read, 0, total * 4);
|
||||
queue.submit([encoder.finish()]);
|
||||
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
let got: Vec<u32> =
|
||||
bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec();
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Flat section draws (gfx/flat.rs): copies each section draw's indices into
|
||||
// one index list, in draw order, offset by the draw's base vertex. Solid
|
||||
// draws index quads (0 1 2 0 2 3 per quad, as Renderer::quad_indices);
|
||||
// translucent ones read their sorted indices.
|
||||
struct Range {
|
||||
count: u32,
|
||||
// First sorted index, or QUADS for a solid draw.
|
||||
first: u32,
|
||||
base: u32,
|
||||
dst: u32,
|
||||
}
|
||||
const QUADS: u32 = 0xffffffffu;
|
||||
const GROUP: u32 = 64u;
|
||||
@group(0) @binding(0) var<storage, read> ranges: array<Range>;
|
||||
@group(0) @binding(1) var<storage, read> sorted: array<u32>;
|
||||
@group(0) @binding(2) var<storage, read_write> out: array<u32>;
|
||||
@compute @workgroup_size(64)
|
||||
fn flatten(@builtin(workgroup_id) group: vec3<u32>,
|
||||
@builtin(local_invocation_index) lane: u32) {
|
||||
let r = group.y * 65535u + group.x;
|
||||
if r >= arrayLength(&ranges) {
|
||||
return;
|
||||
}
|
||||
let d = ranges[r];
|
||||
for (var k = lane; k < d.count; k += GROUP) {
|
||||
var i: u32;
|
||||
if d.first == QUADS {
|
||||
let c = k % 6u;
|
||||
i = (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u);
|
||||
} else {
|
||||
i = sorted[d.first + k];
|
||||
}
|
||||
out[d.dst + k] = d.base + i;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
//! GPU frame time from timestamp queries, read back a few frames late so the
|
||||
//! CPU never waits for it. Frames whose readback slot is still busy go untimed.
|
||||
//!
|
||||
//! Where the GPU can only time pass boundaries (Apple GPUs on Metal), the
|
||||
//! frame is bracketed by two one-thread compute passes that write the
|
||||
//! timestamps (Metal leaves an empty pass's timestamps at zero).
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU8, Ordering},
|
||||
@@ -23,24 +27,18 @@ pub struct GpuTimer {
|
||||
current: Option<usize>,
|
||||
next: usize,
|
||||
period_ns: f32,
|
||||
/// Timestamps between commands, or else this pass's boundaries.
|
||||
marker: Option<wgpu::ComputePipeline>,
|
||||
}
|
||||
|
||||
impl GpuTimer {
|
||||
/// The features timing needs; `None` when the adapter lacks them.
|
||||
/// The features timing uses that the adapter has (none: no timing).
|
||||
pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features {
|
||||
let wanted =
|
||||
wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS;
|
||||
if adapter.features().contains(wanted) {
|
||||
wanted
|
||||
} else {
|
||||
wgpu::Features::empty()
|
||||
}
|
||||
adapter.features()
|
||||
& (wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS)
|
||||
}
|
||||
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Self> {
|
||||
if !device
|
||||
.features()
|
||||
.contains(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS)
|
||||
{
|
||||
if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
|
||||
return None;
|
||||
}
|
||||
let queries = device.create_query_set(&wgpu::QuerySetDescriptor {
|
||||
@@ -72,21 +70,56 @@ impl GpuTimer {
|
||||
current: None,
|
||||
next: 0,
|
||||
period_ns: queue.get_timestamp_period(),
|
||||
marker: (!device
|
||||
.features()
|
||||
.contains(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS))
|
||||
.then(|| {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
"@compute @workgroup_size(1) fn mark() {}".into(),
|
||||
),
|
||||
});
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
layout: None,
|
||||
module: &module,
|
||||
entry_point: Some("mark"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
})
|
||||
}),
|
||||
})
|
||||
}
|
||||
pub fn begin(&mut self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let slot = self.next;
|
||||
self.current = (self.slots[slot].state.load(Ordering::Acquire) == FREE).then_some(slot);
|
||||
if self.current.is_some() {
|
||||
encoder.write_timestamp(&self.queries, 0);
|
||||
self.stamp(encoder, 0);
|
||||
}
|
||||
}
|
||||
pub fn end(&mut self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let Some(slot) = self.current else { return };
|
||||
encoder.write_timestamp(&self.queries, 1);
|
||||
self.stamp(encoder, 1);
|
||||
encoder.resolve_query_set(&self.queries, 0..2, &self.resolve, 0);
|
||||
encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.slots[slot].buffer, 0, 16);
|
||||
}
|
||||
fn stamp(&self, encoder: &mut wgpu::CommandEncoder, index: u32) {
|
||||
let Some(marker) = &self.marker else {
|
||||
encoder.write_timestamp(&self.queries, index);
|
||||
return;
|
||||
};
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("Frame timestamp"),
|
||||
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
|
||||
query_set: &self.queries,
|
||||
beginning_of_pass_write_index: (index == 0).then_some(0),
|
||||
end_of_pass_write_index: (index == 1).then_some(1),
|
||||
}),
|
||||
});
|
||||
pass.set_pipeline(marker);
|
||||
pass.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
/// After the frame's submission: start reading its timestamps back.
|
||||
pub fn submitted(&mut self) {
|
||||
let Some(slot) = self.current.take() else {
|
||||
|
||||
@@ -53,7 +53,9 @@ impl Preset {
|
||||
/// How the swapchain presents frames.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum PresentMode {
|
||||
/// Follow vanilla's VSync option (Mailbox or Fifo on, Immediate off).
|
||||
/// Vanilla's choice: Fifo with VSync on, else the first of Immediate,
|
||||
/// Mailbox and Fifo the surface supports. The other modes apply only
|
||||
/// with VSync off: VSync on always presents with Fifo.
|
||||
#[default]
|
||||
Auto,
|
||||
Fifo,
|
||||
@@ -276,9 +278,14 @@ impl Graphics {
|
||||
if self.workers > 0 {
|
||||
return self.workers as usize;
|
||||
}
|
||||
// The pool never takes every core. The render thread and the
|
||||
// integrated server thread (single player runs on its own server
|
||||
// thread by default) each need one, and a pool that fills every core
|
||||
// starves them: the frame rate collapses to single digits while the
|
||||
// workers saturate the CPU and its memory bandwidth.
|
||||
let auto = std::thread::available_parallelism()
|
||||
.map_or(2, |n| n.get())
|
||||
.saturating_sub(1)
|
||||
.saturating_sub(2)
|
||||
.max(1);
|
||||
if self.battery { auto.div_ceil(2) } else { auto }
|
||||
}
|
||||
@@ -376,6 +383,17 @@ mod tests {
|
||||
assert_eq!(Graphics::parse("lodDistance:invalid\n").lod_distance, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_workers_leave_cores_for_the_render_and_server_threads() {
|
||||
let g = Graphics::default();
|
||||
assert_eq!(g.workers, 0);
|
||||
let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
|
||||
assert_eq!(g.worker_threads(), cores.saturating_sub(2).max(1));
|
||||
// A manual count is the player's own choice, kept as asked.
|
||||
let manual = Graphics { workers: 3, ..g };
|
||||
assert_eq!(manual.worker_threads(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn battery_mode_only_lowers_the_frame_cap() {
|
||||
let mut g = Graphics::default();
|
||||
|
||||
@@ -218,7 +218,7 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
h(
|
||||
H::PresentMode,
|
||||
None,
|
||||
"How frames reach the screen. Auto follows VSync.",
|
||||
"How frames reach the screen while VSync is off.",
|
||||
),
|
||||
h(
|
||||
H::Pacing,
|
||||
|
||||
@@ -161,6 +161,8 @@ pub struct PlayerHealth {
|
||||
pub ids: PlayerFloatIds,
|
||||
pub food: FoodData,
|
||||
pub hurt: State,
|
||||
/// Client hurt animation; fully blocked hits only refresh the server's hurt state.
|
||||
pub hurt_animation_time: i32,
|
||||
pub dead: bool,
|
||||
pub sync_velocity: bool,
|
||||
pub game_time: i64,
|
||||
@@ -210,6 +212,7 @@ impl PlayerHealth {
|
||||
last_source: None,
|
||||
last_stamp: 0,
|
||||
},
|
||||
hurt_animation_time: 0,
|
||||
dead: false,
|
||||
sync_velocity: false,
|
||||
game_time: 0,
|
||||
@@ -242,6 +245,9 @@ impl PlayerHealth {
|
||||
if self.hurt.hurt_time > 0 {
|
||||
self.hurt.hurt_time -= 1;
|
||||
}
|
||||
if self.hurt_animation_time > 0 {
|
||||
self.hurt_animation_time -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
impl PlayerMotion {
|
||||
@@ -300,8 +306,11 @@ impl PlayerMotion {
|
||||
sound: environment.block_sound,
|
||||
};
|
||||
if environment.totem_fired {
|
||||
self.health.totem_used = true;
|
||||
self.health.totem_ready = false;
|
||||
h.totem_used = true;
|
||||
h.totem_ready = false;
|
||||
}
|
||||
if outcome.hurt {
|
||||
h.hurt_animation_time = h.hurt.hurt_time;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ impl PlayerMotion {
|
||||
data: &mut h.data,
|
||||
ids: h.ids,
|
||||
hurt: &mut h.hurt,
|
||||
hurt_animation_time: &mut h.hurt_animation_time,
|
||||
dead: &mut h.dead,
|
||||
sync_velocity: &mut h.sync_velocity,
|
||||
game_time: h.game_time,
|
||||
@@ -70,6 +71,7 @@ struct TickWorld<'a> {
|
||||
data: &'a mut SyncedFloats,
|
||||
ids: PlayerFloatIds,
|
||||
hurt: &'a mut State,
|
||||
hurt_animation_time: &'a mut i32,
|
||||
dead: &'a mut bool,
|
||||
sync_velocity: &'a mut bool,
|
||||
game_time: i64,
|
||||
@@ -142,8 +144,11 @@ impl FoodWorld for TickWorld<'_> {
|
||||
totem: false,
|
||||
totem_fired: false,
|
||||
};
|
||||
ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)?
|
||||
.hurt(self.hurt, amount)?;
|
||||
if ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)?
|
||||
.hurt(self.hurt, amount)?
|
||||
{
|
||||
*self.hurt_animation_time = self.hurt.hurt_time;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,6 +289,20 @@ impl ServerAdvancements {
|
||||
book_add(entries, true)
|
||||
}
|
||||
|
||||
/// The recipe's display for ClientboundPlaceGhostRecipePacket (the
|
||||
/// recipes the book lists).
|
||||
pub fn ghost_display(
|
||||
&self,
|
||||
id: &str,
|
||||
sync: &SyncData,
|
||||
) -> Option<horizon_protocol::packets::recipes::RecipeDisplay> {
|
||||
let bytes = self.book_entries(id, sync, 0).into_iter().next()?;
|
||||
let mut r = horizon_protocol::buf::Reader::new(&bytes);
|
||||
horizon_protocol::packets::recipes::RecipeBookEntry::read(&mut r)
|
||||
.ok()
|
||||
.map(|e| e.display)
|
||||
}
|
||||
|
||||
/// ClientboundRecipeBookAddPacket.Entry for each display of a recipe:
|
||||
/// highlighted, and with a notification unless the recipe turns it off.
|
||||
fn book_entries(&self, id: &str, sync: &SyncData, flags: i8) -> Vec<Vec<u8>> {
|
||||
|
||||
@@ -7,8 +7,10 @@ use crate::{
|
||||
fast_hash::FxHashMap,
|
||||
};
|
||||
use horizon_protocol::{
|
||||
buf::set_bit,
|
||||
chunk::{BIOMES, BLOCKS, BlockEntityInfo, ChunkData, LightData, Paletted, Strategy},
|
||||
buf::{BitSet, Codec, List, Writer, set_bit},
|
||||
chunk::{
|
||||
BIOMES, BLOCKS, BlockEntityInfo, ChunkData, Heightmaps, LightData, Paletted, Strategy,
|
||||
},
|
||||
packets::play::LevelChunkWithLight,
|
||||
registry::{Builtin, ceil_log2},
|
||||
};
|
||||
@@ -105,9 +107,12 @@ pub struct ChunkEncoder {
|
||||
/// A column's client heightmaps, valid while it holds the same sections.
|
||||
struct Heights {
|
||||
sections: Vec<std::sync::Weak<Section>>,
|
||||
maps: Vec<(i32, Vec<i64>)>,
|
||||
maps: ColumnHeightmaps,
|
||||
}
|
||||
|
||||
/// Heightmap type ids with their packed long arrays.
|
||||
type ColumnHeightmaps = Arc<Vec<(i32, Vec<i64>)>>;
|
||||
|
||||
/// What a resident section gives the wire, kept while the section is
|
||||
/// unchanged. Resident sections are immutable behind `Arc` (edits go through
|
||||
/// `Arc::make_mut`, which moves an edited section to a new address while a
|
||||
@@ -228,7 +233,7 @@ impl ChunkEncoder {
|
||||
|
||||
/// The client heightmaps (Heightmap.prime over the column), from the
|
||||
/// cache while the column's sections are unchanged.
|
||||
fn heightmaps(&self, chunk: &Chunk, tables: &crate::save::SaveTables) -> Vec<(i32, Vec<i64>)> {
|
||||
fn heightmaps(&self, chunk: &Chunk, tables: &crate::save::SaveTables) -> ColumnHeightmaps {
|
||||
let same = |h: &Heights| {
|
||||
h.sections.len() == chunk.sections.len()
|
||||
&& h.sections
|
||||
@@ -250,7 +255,9 @@ impl ChunkEncoder {
|
||||
}
|
||||
let min_y = MIN_Y + 16 * self.sections.start as i32;
|
||||
let height = 16 * self.sections.len() as i32;
|
||||
let maps = crate::save::client_heightmaps_in(chunk, tables, min_y, height);
|
||||
let maps = Arc::new(crate::save::client_heightmaps_in(
|
||||
chunk, tables, min_y, height,
|
||||
));
|
||||
heights.insert(
|
||||
(chunk.x, chunk.z),
|
||||
Heights {
|
||||
@@ -402,7 +409,7 @@ impl ChunkEncoder {
|
||||
/// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir).
|
||||
fn occupied(&self, chunk: &Chunk) -> u64 {
|
||||
let mut bits = 0u64;
|
||||
// One lock for the column: encode_in asks for nine columns' sections.
|
||||
// One lock for the column: body_in asks for nine columns' sections.
|
||||
let mut cache = self.cache.lock().unwrap();
|
||||
for (i, s) in chunk.sections[self.sections.clone()].iter().enumerate() {
|
||||
if self.entry(&mut cache, s).non_air {
|
||||
@@ -412,9 +419,8 @@ impl ChunkEncoder {
|
||||
bits
|
||||
}
|
||||
|
||||
/// The chunk column with its light and block entities. `world` gives the
|
||||
/// neighbouring columns, whose sections decide which light layers exist.
|
||||
pub fn encode_in(&self, chunk: &Chunk, world: &crate::world::World) -> LevelChunkWithLight {
|
||||
/// The non-air sections of the column and its neighbours, as bits.
|
||||
fn around(&self, chunk: &Chunk, world: &crate::world::World) -> u64 {
|
||||
let mut around = 0u64;
|
||||
for dz in -1..=1 {
|
||||
for dx in -1..=1 {
|
||||
@@ -423,9 +429,55 @@ impl ChunkEncoder {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut packet = self.encode_blocks(chunk, &world.block_entities);
|
||||
packet.light = self.light_data(chunk, around);
|
||||
packet
|
||||
around
|
||||
}
|
||||
|
||||
/// The chunk column with its light and block entities, as the body
|
||||
/// `Clientbound::encode` gives for its LevelChunkWithLight. `world` gives
|
||||
/// the neighbouring columns, whose sections decide which light layers
|
||||
/// exist. It is written once into a buffer of its final size: the cached
|
||||
/// sections and light layers go straight to it, with no packet built and
|
||||
/// copied again first.
|
||||
pub fn body_in(&self, chunk: &Chunk, world: &crate::world::World) -> Vec<u8> {
|
||||
self.body(chunk, &world.block_entities, self.around(chunk, world))
|
||||
}
|
||||
|
||||
fn body(
|
||||
&self,
|
||||
chunk: &Chunk,
|
||||
block_entities: &HashMap<(i32, i32, i32), BlockEntity>,
|
||||
around: u64,
|
||||
) -> Vec<u8> {
|
||||
let (wires, entities) = self.blocks(chunk, block_entities);
|
||||
let heightmaps = self.heightmaps_of(chunk);
|
||||
let lights = self.light_sections(chunk, around);
|
||||
let buffer: usize = wires.iter().map(|w| w.len()).sum();
|
||||
// Before the light: their tags' size is only known once written.
|
||||
let mut tags = Writer::new();
|
||||
List::<BlockEntityInfo>::write(&entities, &mut tags);
|
||||
// The masks, counts and lengths fit the 64 bytes.
|
||||
let size = 64
|
||||
+ heightmaps
|
||||
.iter()
|
||||
.map(|(_, h)| 10 + 8 * h.len())
|
||||
.sum::<usize>()
|
||||
+ buffer
|
||||
+ tags.data.len()
|
||||
+ lights.len() * 2 * (2048 + 3);
|
||||
let mut w = Writer {
|
||||
data: Vec::with_capacity(size),
|
||||
};
|
||||
w.varint(horizon_protocol::ids::play::clientbound::LEVEL_CHUNK_WITH_LIGHT);
|
||||
w.i32(chunk.x);
|
||||
w.i32(chunk.z);
|
||||
Heightmaps::write(&*heightmaps, &mut w);
|
||||
w.varint(buffer as i32);
|
||||
for wire in &wires {
|
||||
w.bytes(wire);
|
||||
}
|
||||
w.bytes(&tags.data);
|
||||
write_light(&lights, self.sky, &mut w);
|
||||
w.data
|
||||
}
|
||||
|
||||
pub fn encode(
|
||||
@@ -444,7 +496,41 @@ impl ChunkEncoder {
|
||||
chunk: &Chunk,
|
||||
block_entities: &HashMap<(i32, i32, i32), BlockEntity>,
|
||||
) -> LevelChunkWithLight {
|
||||
let mut buffer = Vec::new();
|
||||
let (wires, block_entities) = self.blocks(chunk, block_entities);
|
||||
LevelChunkWithLight {
|
||||
x: chunk.x,
|
||||
z: chunk.z,
|
||||
chunk: ChunkData {
|
||||
heightmaps: self.heightmaps_of(chunk).to_vec(),
|
||||
buffer: wires.concat(),
|
||||
block_entities,
|
||||
},
|
||||
light: LightData {
|
||||
sky_mask: Vec::new(),
|
||||
block_mask: Vec::new(),
|
||||
empty_sky_mask: Vec::new(),
|
||||
empty_block_mask: Vec::new(),
|
||||
sky: Vec::new(),
|
||||
block: Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn heightmaps_of(&self, chunk: &Chunk) -> ColumnHeightmaps {
|
||||
self.tables
|
||||
.as_ref()
|
||||
.map(|t| self.heightmaps(chunk, t))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The level's sections on the wire, and the column's block entities in
|
||||
/// the packet's order.
|
||||
fn blocks(
|
||||
&self,
|
||||
chunk: &Chunk,
|
||||
block_entities: &HashMap<(i32, i32, i32), BlockEntity>,
|
||||
) -> (Vec<Arc<[u8]>>, Vec<BlockEntityInfo>) {
|
||||
let mut wires = Vec::with_capacity(self.sections.len());
|
||||
let mut entity_infos = Vec::new();
|
||||
for (i, s) in chunk
|
||||
.sections
|
||||
@@ -478,7 +564,7 @@ impl ChunkEncoder {
|
||||
.unwrap_or(Tag::End),
|
||||
});
|
||||
}
|
||||
buffer.extend_from_slice(&encoded);
|
||||
wires.push(encoded);
|
||||
}
|
||||
// A loaded chunk's block entities enter its maps in the save's order
|
||||
// (ChunkAccess.pendingBlockEntities, then LevelChunk.blockEntities):
|
||||
@@ -503,27 +589,7 @@ impl ChunkEncoder {
|
||||
chunk.z * 16 + i32::from(e.packed_xz as u8 & 15),
|
||||
)
|
||||
});
|
||||
LevelChunkWithLight {
|
||||
x: chunk.x,
|
||||
z: chunk.z,
|
||||
chunk: ChunkData {
|
||||
heightmaps: self
|
||||
.tables
|
||||
.as_ref()
|
||||
.map(|t| self.heightmaps(chunk, t))
|
||||
.unwrap_or_default(),
|
||||
buffer,
|
||||
block_entities: entity_infos,
|
||||
},
|
||||
light: LightData {
|
||||
sky_mask: Vec::new(),
|
||||
block_mask: Vec::new(),
|
||||
empty_sky_mask: Vec::new(),
|
||||
empty_block_mask: Vec::new(),
|
||||
sky: Vec::new(),
|
||||
block: Vec::new(),
|
||||
},
|
||||
}
|
||||
(wires, entity_infos)
|
||||
}
|
||||
|
||||
/// ClientboundLightUpdatePacketData: the light layers of the sections
|
||||
@@ -532,23 +598,20 @@ impl ChunkEncoder {
|
||||
/// the cache while it is unchanged (uniform light is quicker to fill than
|
||||
/// to keep).
|
||||
fn light_data(&self, chunk: &Chunk, around: u64) -> LightData {
|
||||
let mut data = light_data_with(&chunk.sections[self.sections.clone()], around, |s| {
|
||||
if matches!(s.light, Light::Uniform(_)) {
|
||||
return Arc::new(Layers::of(&s.light));
|
||||
light_data_of(&self.light_sections(chunk, around), self.sky)
|
||||
}
|
||||
|
||||
fn light_sections(&self, chunk: &Chunk, around: u64) -> Vec<(usize, SectionLight)> {
|
||||
light_sections(&chunk.sections[self.sections.clone()], around, |s| {
|
||||
if let Light::Uniform(v) = s.light {
|
||||
return SectionLight::Uniform(v);
|
||||
}
|
||||
self.cached(s, |e| e.light.clone()).unwrap_or_else(|| {
|
||||
SectionLight::Layers(self.cached(s, |e| e.light.clone()).unwrap_or_else(|| {
|
||||
let layers = Arc::new(Layers::of(&s.light));
|
||||
self.cached(s, |e| e.light = Some(layers.clone()));
|
||||
layers
|
||||
})
|
||||
});
|
||||
if !self.sky {
|
||||
// No sky light storage at all.
|
||||
data.sky_mask.clear();
|
||||
data.empty_sky_mask.clear();
|
||||
data.sky.clear();
|
||||
}
|
||||
data
|
||||
}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -624,51 +687,123 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
|
||||
/// layer is sent, or marked empty when all dark; the others are left out.
|
||||
#[cfg(test)]
|
||||
fn light_data(sections: &[Arc<Section>], around: u64) -> LightData {
|
||||
light_data_with(sections, around, |s| Arc::new(Layers::of(&s.light)))
|
||||
let lights = light_sections(sections, around, |s| {
|
||||
SectionLight::Layers(Arc::new(Layers::of(&s.light)))
|
||||
});
|
||||
light_data_of(&lights, true)
|
||||
}
|
||||
|
||||
/// The light layers, `section` giving a resident section's.
|
||||
fn light_data_with(
|
||||
/// A light section's two DataLayers: a resident section's from the cache,
|
||||
/// or one value everywhere, which is quicker to write than to keep.
|
||||
enum SectionLight {
|
||||
Layers(Arc<Layers>),
|
||||
/// Sky light in the high nibble, block light in the low one.
|
||||
Uniform(u8),
|
||||
}
|
||||
impl SectionLight {
|
||||
/// Whether the sky and the block layer hold any light.
|
||||
fn any(&self) -> (bool, bool) {
|
||||
match self {
|
||||
Self::Layers(l) => (l.sky_any, l.block_any),
|
||||
Self::Uniform(v) => (v >> 4 != 0, v & 15 != 0),
|
||||
}
|
||||
}
|
||||
/// Append the sky or the block layer's 2048 bytes.
|
||||
fn put(&self, sky: bool, out: &mut Vec<u8>) {
|
||||
match self {
|
||||
Self::Layers(l) => out.extend_from_slice(if sky { &l.sky } else { &l.block }),
|
||||
Self::Uniform(v) => {
|
||||
let n = if sky { v >> 4 } else { v & 15 };
|
||||
out.resize(out.len() + 2048, n | n << 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The existing light sections, by index from below the world, with their
|
||||
/// layers (`section` giving a section of the world's).
|
||||
fn light_sections(
|
||||
sections: &[Arc<Section>],
|
||||
around: u64,
|
||||
section: impl Fn(&Arc<Section>) -> Arc<Layers>,
|
||||
) -> LightData {
|
||||
section: impl Fn(&Arc<Section>) -> SectionLight,
|
||||
) -> Vec<(usize, SectionLight)> {
|
||||
let n = sections.len();
|
||||
let mut data = LightData {
|
||||
sky_mask: Vec::new(),
|
||||
block_mask: Vec::new(),
|
||||
empty_sky_mask: Vec::new(),
|
||||
empty_block_mask: Vec::new(),
|
||||
sky: Vec::new(),
|
||||
block: Vec::new(),
|
||||
};
|
||||
// Light section b holds chunk section b - 1.
|
||||
let exists =
|
||||
|b: usize| (b.saturating_sub(2)..=b.min(n - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0);
|
||||
for b in 0..n + 2 {
|
||||
if !exists(b) {
|
||||
continue;
|
||||
(0..n + 2)
|
||||
.filter(|&b| exists(b))
|
||||
.map(|b| {
|
||||
let light = match b {
|
||||
// Below the world nothing is lit; above it the sky is full.
|
||||
0 => SectionLight::Uniform(0),
|
||||
_ if b == n + 1 => SectionLight::Uniform(0xF0),
|
||||
_ => section(§ions[b - 1]),
|
||||
};
|
||||
(b, light)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The four masks of ClientboundLightUpdatePacketData (sky, block, empty
|
||||
/// sky, empty block); a level without sky light has no sky storage at all.
|
||||
fn light_masks(lights: &[(usize, SectionLight)], sky: bool) -> [Vec<u8>; 4] {
|
||||
let mut masks: [Vec<u8>; 4] = Default::default();
|
||||
for (b, light) in lights {
|
||||
let (sky_any, block_any) = light.any();
|
||||
if sky {
|
||||
set_bit(&mut masks[if sky_any { 0 } else { 2 }], *b);
|
||||
}
|
||||
let layers = match b {
|
||||
// Below the world nothing is lit; above it the sky is full.
|
||||
0 => Arc::new(Layers::of(&Light::Uniform(0))),
|
||||
_ if b == n + 1 => Arc::new(Layers::of(&Light::Uniform(0xF0))),
|
||||
_ => section(§ions[b - 1]),
|
||||
};
|
||||
if layers.sky_any {
|
||||
set_bit(&mut data.sky_mask, b);
|
||||
data.sky.push(layers.sky.clone());
|
||||
} else {
|
||||
set_bit(&mut data.empty_sky_mask, b);
|
||||
}
|
||||
if layers.block_any {
|
||||
set_bit(&mut data.block_mask, b);
|
||||
data.block.push(layers.block.clone());
|
||||
} else {
|
||||
set_bit(&mut data.empty_block_mask, b);
|
||||
set_bit(&mut masks[if block_any { 1 } else { 3 }], *b);
|
||||
}
|
||||
masks
|
||||
}
|
||||
|
||||
/// The layers sent of one kind: those with any light.
|
||||
fn sent_layers(
|
||||
lights: &[(usize, SectionLight)],
|
||||
sky: bool,
|
||||
) -> impl Iterator<Item = &SectionLight> + Clone {
|
||||
lights.iter().map(|(_, l)| l).filter(move |l| {
|
||||
let (sky_any, block_any) = l.any();
|
||||
if sky { sky_any } else { block_any }
|
||||
})
|
||||
}
|
||||
|
||||
fn light_data_of(lights: &[(usize, SectionLight)], sky: bool) -> LightData {
|
||||
let [sky_mask, block_mask, empty_sky_mask, empty_block_mask] = light_masks(lights, sky);
|
||||
let layers = |kind: bool| -> Vec<Vec<u8>> {
|
||||
sent_layers(lights, kind)
|
||||
.map(|l| {
|
||||
let mut layer = Vec::with_capacity(2048);
|
||||
l.put(kind, &mut layer);
|
||||
layer
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
LightData {
|
||||
sky_mask,
|
||||
block_mask,
|
||||
empty_sky_mask,
|
||||
empty_block_mask,
|
||||
sky: if sky { layers(true) } else { Vec::new() },
|
||||
block: layers(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// LightData.write, from the layers themselves.
|
||||
fn write_light(lights: &[(usize, SectionLight)], sky: bool, w: &mut Writer) {
|
||||
for mask in light_masks(lights, sky) {
|
||||
BitSet::write(&mask, w);
|
||||
}
|
||||
for kind in [true, false] {
|
||||
let layers = sent_layers(lights, kind).filter(|_| sky || !kind);
|
||||
w.varint(layers.clone().count() as i32);
|
||||
for l in layers {
|
||||
w.varint(2048);
|
||||
l.put(kind, &mut w.data);
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -848,6 +983,73 @@ mod tests {
|
||||
assert!(horizon_protocol::buf::bit(&data.empty_block_mask, 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_body_is_the_packet_encoded() {
|
||||
let builtin = Builtin::parse(
|
||||
r#"{"minecraft:block_entity_type": {"entries": {
|
||||
"minecraft:chest": {"protocol_id": 1},
|
||||
"minecraft:sign": {"protocol_id": 7}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let states = [
|
||||
"minecraft:air",
|
||||
"minecraft:stone",
|
||||
"minecraft:chest",
|
||||
"minecraft:oak_sign",
|
||||
]
|
||||
.map(|n| (Arc::<str>::from(n), false));
|
||||
let mut encoder = ChunkEncoder::new(states, &builtin, &[], &[]);
|
||||
let mut chunk = Chunk::empty(-7, 12);
|
||||
// Every kind of light section: uniform dark, uniform lit, sky and
|
||||
// block light varying, none at all.
|
||||
let mut light = Box::new([0u8; 4096]);
|
||||
for (i, v) in light.iter_mut().enumerate() {
|
||||
*v = (i * 53 % 256) as u8;
|
||||
}
|
||||
Arc::make_mut(&mut chunk.sections[4]).light = Light::Full(light);
|
||||
Arc::make_mut(&mut chunk.sections[5]).light = Light::Uniform(0x07);
|
||||
Arc::make_mut(&mut chunk.sections[6]).light = Light::Uniform(0);
|
||||
Arc::make_mut(&mut chunk.sections[7]).light = Light::Full(Box::new([0x30; 4096]));
|
||||
for (x, y, z, state) in [
|
||||
(3, 70, 9, 1),
|
||||
(5, 70, 5, 2),
|
||||
(0, -60, 15, 2),
|
||||
(15, 300, 0, 1),
|
||||
(8, 64, 1, 3),
|
||||
] {
|
||||
chunk.set(x, y, z, state);
|
||||
}
|
||||
// A sign's update tag goes with the column.
|
||||
let mut entities = HashMap::new();
|
||||
entities.insert(
|
||||
(-7 * 16 + 8, 64, 12 * 16 + 1),
|
||||
BlockEntity::Sign(crate::signs::SignData::default()),
|
||||
);
|
||||
let packet = |encoder: &ChunkEncoder, around: u64| {
|
||||
let mut packet = encoder.encode_blocks(&chunk, &entities);
|
||||
packet.light = encoder.light_data(&chunk, around);
|
||||
horizon_protocol::packets::play::Clientbound::LevelChunkWithLight(packet).encode()
|
||||
};
|
||||
let sent = encoder
|
||||
.encode_blocks(&chunk, &entities)
|
||||
.chunk
|
||||
.block_entities;
|
||||
assert_eq!(sent.len(), 3);
|
||||
assert!(sent.iter().any(|e| e.tag != Tag::End));
|
||||
for around in [0, 1, 0b1010_0000, 1 << 23, u64::MAX] {
|
||||
assert_eq!(
|
||||
encoder.body(&chunk, &entities, around),
|
||||
packet(&encoder, around),
|
||||
"around {around:#b}"
|
||||
);
|
||||
}
|
||||
encoder.set_dimension(0, 256, false);
|
||||
assert_eq!(
|
||||
encoder.body(&chunk, &entities, u64::MAX),
|
||||
packet(&encoder, u64::MAX)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nether_column_sends_its_sixteen_sections_without_sky_light() {
|
||||
let chunk = Chunk::empty(0, 0);
|
||||
|
||||
@@ -150,6 +150,8 @@ pub struct PlayerSender {
|
||||
pub tx: Sender<Out>,
|
||||
pub pending: Arc<AtomicUsize>,
|
||||
held: Arc<Mutex<Vec<Vec<u8>>>>,
|
||||
/// What [`flush_all`] gave the post thread and it hasn't passed on yet.
|
||||
posted: Arc<AtomicUsize>,
|
||||
}
|
||||
impl PlayerSender {
|
||||
pub fn new(tx: Sender<Out>, pending: Arc<AtomicUsize>) -> Self {
|
||||
@@ -157,6 +159,7 @@ impl PlayerSender {
|
||||
tx,
|
||||
pending,
|
||||
held: Arc::default(),
|
||||
posted: Arc::default(),
|
||||
}
|
||||
}
|
||||
fn held(&self) -> std::sync::MutexGuard<'_, Vec<Vec<u8>>> {
|
||||
@@ -168,21 +171,91 @@ impl PlayerSender {
|
||||
self.held().push(body);
|
||||
} else {
|
||||
self.flush();
|
||||
let _ = self.tx.send(Out::Packet(body));
|
||||
self.deliver(Out::Packet(body));
|
||||
}
|
||||
}
|
||||
/// Hand the held packets to the writer thread.
|
||||
pub fn flush(&self) {
|
||||
let held = std::mem::take(&mut *self.held());
|
||||
if !held.is_empty() {
|
||||
let _ = self.tx.send(Out::Packets(held));
|
||||
self.deliver(Out::Packets(held));
|
||||
}
|
||||
}
|
||||
/// Send a play disconnect with this reason after what was sent before.
|
||||
pub fn disconnect(&self, reason: horizon_world::nbt::Tag) {
|
||||
self.flush();
|
||||
let _ = self.tx.send(Out::Disconnect(reason));
|
||||
self.deliver(Out::Disconnect(reason));
|
||||
}
|
||||
/// To the writer thread, after anything still with the post thread.
|
||||
fn deliver(&self, out: Out) {
|
||||
if self.posted.load(Ordering::Acquire) == 0 {
|
||||
let _ = self.tx.send(out);
|
||||
} else {
|
||||
post(vec![self.posting(out)]);
|
||||
}
|
||||
}
|
||||
fn posting(&self, out: Out) -> Posted {
|
||||
self.posted.fetch_add(1, Ordering::AcqRel);
|
||||
Posted {
|
||||
tx: self.tx.clone(),
|
||||
out,
|
||||
posted: self.posted.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand every player's held packets to their writer threads. Waking a writer
|
||||
/// costs a system call, and on a busy machine often the rest of the core's
|
||||
/// time slice; one thread of its own wakes them, so the game thread wakes one
|
||||
/// thread per tick, not one per player. Each player's packets keep their
|
||||
/// order, also with what is sent to it next.
|
||||
pub fn flush_all<'a>(senders: impl IntoIterator<Item = &'a PlayerSender>) {
|
||||
let batch: Vec<Posted> = senders
|
||||
.into_iter()
|
||||
.filter_map(|s| {
|
||||
let held = std::mem::take(&mut *s.held());
|
||||
(!held.is_empty()).then(|| s.posting(Out::Packets(held)))
|
||||
})
|
||||
.collect();
|
||||
if !batch.is_empty() {
|
||||
post(batch);
|
||||
}
|
||||
}
|
||||
|
||||
/// Packets on their way through the post thread.
|
||||
struct Posted {
|
||||
tx: Sender<Out>,
|
||||
out: Out,
|
||||
posted: Arc<AtomicUsize>,
|
||||
}
|
||||
impl Posted {
|
||||
fn hand_over(self) {
|
||||
let _ = self.tx.send(self.out);
|
||||
self.posted.fetch_sub(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a batch to the post thread, started the first time; without one
|
||||
/// (the thread could not start) the batch is handed over here.
|
||||
fn post(batch: Vec<Posted>) {
|
||||
static POST: std::sync::OnceLock<Option<Sender<Vec<Posted>>>> = std::sync::OnceLock::new();
|
||||
let post = POST.get_or_init(|| {
|
||||
let (tx, rx) = channel::<Vec<Posted>>();
|
||||
std::thread::Builder::new()
|
||||
.name("horizon-lan-post".to_owned())
|
||||
.spawn(move || {
|
||||
for batch in rx {
|
||||
batch.into_iter().for_each(Posted::hand_over);
|
||||
}
|
||||
})
|
||||
.ok()
|
||||
.map(|_| tx)
|
||||
});
|
||||
let unsent = match post {
|
||||
Some(tx) => tx.send(batch).err().map(|e| e.0),
|
||||
None => Some(batch),
|
||||
};
|
||||
unsent.into_iter().flatten().for_each(Posted::hand_over);
|
||||
}
|
||||
|
||||
/// LegacyQueryHandler: the pre-1.7 server list ping. What the first read
|
||||
@@ -748,6 +821,82 @@ fn read_loop(
|
||||
}
|
||||
}
|
||||
|
||||
/// Packet bodies at least this large are compressed once for every
|
||||
/// connection: chunk columns, mostly, which every player near them receives.
|
||||
const SHARED_FRAME_MIN: usize = 8 << 10;
|
||||
/// The compressed frames kept, in bytes; the oldest go first.
|
||||
const SHARED_FRAME_BYTES: usize = 32 << 20;
|
||||
|
||||
/// Compressed frame contents by the body they were made from: its length,
|
||||
/// two independently keyed 64-bit hashes of it, and the threshold.
|
||||
struct SharedFrames {
|
||||
hashers: (std::hash::RandomState, std::hash::RandomState),
|
||||
frames: Mutex<FrameCache>,
|
||||
/// [`SHARED_FRAME_BYTES`].
|
||||
limit: usize,
|
||||
}
|
||||
type FrameKey = (usize, u64, u64, usize);
|
||||
#[derive(Default)]
|
||||
struct FrameCache {
|
||||
frames: crate::fast_hash::FxHashMap<FrameKey, Arc<[u8]>>,
|
||||
order: std::collections::VecDeque<FrameKey>,
|
||||
bytes: usize,
|
||||
}
|
||||
impl SharedFrames {
|
||||
fn get() -> &'static Self {
|
||||
static FRAMES: std::sync::OnceLock<SharedFrames> = std::sync::OnceLock::new();
|
||||
FRAMES.get_or_init(|| Self::new(SHARED_FRAME_BYTES))
|
||||
}
|
||||
fn new(limit: usize) -> Self {
|
||||
Self {
|
||||
hashers: Default::default(),
|
||||
frames: Mutex::default(),
|
||||
limit,
|
||||
}
|
||||
}
|
||||
/// `frame::contents(body, Some(threshold))`, compressed only when no
|
||||
/// connection has sent the same body lately.
|
||||
fn contents(&self, body: &[u8], threshold: usize) -> horizon_protocol::Result<Arc<[u8]>> {
|
||||
use std::hash::BuildHasher;
|
||||
let key = (
|
||||
body.len(),
|
||||
self.hashers.0.hash_one(body),
|
||||
self.hashers.1.hash_one(body),
|
||||
threshold,
|
||||
);
|
||||
let cache = || self.frames.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(contents) = cache().frames.get(&key) {
|
||||
return Ok(contents.clone());
|
||||
}
|
||||
let contents: Arc<[u8]> = horizon_protocol::frame::contents(body, Some(threshold))?.into();
|
||||
let mut cache = cache();
|
||||
if cache.frames.insert(key, contents.clone()).is_none() {
|
||||
cache.order.push_back(key);
|
||||
cache.bytes += contents.len();
|
||||
while cache.bytes > self.limit
|
||||
&& let Some(old) = cache.order.pop_front()
|
||||
{
|
||||
if let Some(c) = cache.frames.remove(&old) {
|
||||
cache.bytes -= c.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(contents)
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one packet body: a large one compressed through [`SharedFrames`],
|
||||
/// so a chunk column sent to fifty players is compressed once, not fifty
|
||||
/// times. The bytes on the wire are the same.
|
||||
fn send_body(writer: &mut ConnWriter, body: &[u8]) -> horizon_protocol::Result<()> {
|
||||
match writer.threshold {
|
||||
Some(t) if body.len() >= t.max(SHARED_FRAME_MIN) => {
|
||||
writer.send_contents(&SharedFrames::get().contents(body, t)?)
|
||||
}
|
||||
_ => writer.send(body),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_loop(
|
||||
mut writer: ConnWriter,
|
||||
rx: Receiver<Out>,
|
||||
@@ -761,7 +910,7 @@ fn write_loop(
|
||||
loop {
|
||||
let mut write = |body: Vec<u8>| {
|
||||
pending.fetch_sub(body.len(), Ordering::Relaxed);
|
||||
writer.send(&body).is_ok() && pending.load(Ordering::Relaxed) <= MAX_PENDING
|
||||
send_body(&mut writer, &body).is_ok() && pending.load(Ordering::Relaxed) <= MAX_PENDING
|
||||
};
|
||||
match rx.recv_timeout(Duration::from_millis(200)) {
|
||||
Ok(Out::Packet(body)) => {
|
||||
@@ -819,15 +968,90 @@ fn write_loop(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unpack(out: Out) -> Vec<Vec<u8>> {
|
||||
match out {
|
||||
Out::Packet(body) => vec![body],
|
||||
Out::Packets(bodies) => bodies,
|
||||
Out::Disconnect(_) => vec![b"disconnect".to_vec()],
|
||||
Out::Close => vec![b"close".to_vec()],
|
||||
}
|
||||
}
|
||||
|
||||
fn bodies(rx: &Receiver<Out>) -> Vec<Vec<Vec<u8>>> {
|
||||
rx.try_iter()
|
||||
.map(|out| match out {
|
||||
Out::Packet(body) => vec![body],
|
||||
Out::Packets(bodies) => bodies,
|
||||
Out::Disconnect(_) => vec![b"disconnect".to_vec()],
|
||||
Out::Close => vec![b"close".to_vec()],
|
||||
})
|
||||
.collect()
|
||||
rx.try_iter().map(unpack).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_sent_after_a_posted_tick_follow_it() {
|
||||
let (tx, rx) = channel();
|
||||
let (tx2, rx2) = channel();
|
||||
let sender = PlayerSender::new(tx, Arc::default());
|
||||
let other = PlayerSender::new(tx2, Arc::default());
|
||||
for round in 0..50u8 {
|
||||
let holding = Holding::start();
|
||||
sender.send(vec![round, 1]);
|
||||
sender.send(vec![round, 2]);
|
||||
other.send(vec![round]);
|
||||
drop(holding);
|
||||
flush_all([&sender, &other]);
|
||||
// Straight after the tick, while the post thread may still hold it.
|
||||
sender.send(vec![round, 3]);
|
||||
let next = || unpack(rx.recv_timeout(Duration::from_secs(10)).unwrap());
|
||||
assert_eq!(next(), [vec![round, 1], vec![round, 2]]);
|
||||
assert_eq!(next(), [vec![round, 3]]);
|
||||
let got = unpack(rx2.recv_timeout(Duration::from_secs(10)).unwrap());
|
||||
assert_eq!(got, [vec![round]]);
|
||||
}
|
||||
let holding = Holding::start();
|
||||
sender.send(vec![9]);
|
||||
drop(holding);
|
||||
flush_all([&sender]);
|
||||
sender.disconnect(horizon_world::nbt::Tag::Byte(0));
|
||||
let next = || unpack(rx.recv_timeout(Duration::from_secs(10)).unwrap());
|
||||
assert_eq!(next(), [vec![9]]);
|
||||
assert_eq!(next(), [b"disconnect".to_vec()]);
|
||||
// Nothing sent twice, nothing left with the post thread.
|
||||
assert!(rx.try_recv().is_err());
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while sender.posted.load(Ordering::Acquire) != 0 {
|
||||
assert!(Instant::now() < deadline);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_frames_are_the_frames_compressed_here() {
|
||||
use horizon_protocol::frame;
|
||||
let frames = SharedFrames::new(usize::MAX);
|
||||
let a: Vec<u8> = (0..40_000u32).map(|i| (i * 7 % 13) as u8).collect();
|
||||
let mut b = a.clone();
|
||||
b[20_000] ^= 1;
|
||||
for (body, threshold) in [(&a, 256), (&b, 256), (&a, 256), (&a, 64), (&b, 256)] {
|
||||
let shared = frames.contents(body, threshold).unwrap();
|
||||
assert_eq!(*shared, *frame::contents(body, Some(threshold)).unwrap());
|
||||
}
|
||||
// One frame per body and threshold.
|
||||
assert_eq!(frames.frames.lock().unwrap().frames.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_frames_keep_the_newest_within_their_limit() {
|
||||
let first = SharedFrames::new(0)
|
||||
.contents(&[1; 9000], 256)
|
||||
.unwrap()
|
||||
.len();
|
||||
let frames = SharedFrames::new(first * 2);
|
||||
for n in 0..5u8 {
|
||||
frames.contents(&[n; 9000], 256).unwrap();
|
||||
}
|
||||
let cache = frames.frames.lock().unwrap();
|
||||
assert!((1..=2).contains(&cache.frames.len()));
|
||||
assert_eq!(cache.order.len(), cache.frames.len());
|
||||
assert_eq!(
|
||||
cache.bytes,
|
||||
cache.frames.values().map(|c| c.len()).sum::<usize>()
|
||||
);
|
||||
assert!(cache.bytes <= first * 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -25,7 +25,7 @@ impl Hub {
|
||||
for g in self
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| g.placed && Some(g.conn) != except)
|
||||
.filter(|g| self.here(g) && Some(g.conn) != except)
|
||||
{
|
||||
let d: f64 = (0..3).map(|k| (g.position[k] - at[k]).powi(2)).sum();
|
||||
if d <= range * range {
|
||||
@@ -464,7 +464,7 @@ impl Hub {
|
||||
let Some(menu) = self.guests[i]
|
||||
.menu
|
||||
.as_ref()
|
||||
.filter(|_| self.guests[i].placed)
|
||||
.filter(|_| self.here(&self.guests[i]))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -147,6 +147,9 @@ pub struct Guest {
|
||||
pub dead: bool,
|
||||
/// The join packets were sent (PlayerList.placeNewPlayer ran).
|
||||
pub placed: bool,
|
||||
/// The level the player is in (`ServerPlayer.level().dimension()`): the
|
||||
/// hub's level passes only reach the players in theirs.
|
||||
pub dimension: String,
|
||||
/// The open block container, if any.
|
||||
pub menu: Option<super::menu::Menu>,
|
||||
pub next_window: i32,
|
||||
@@ -248,6 +251,7 @@ impl Guest {
|
||||
moves_from_ground: false,
|
||||
dead: false,
|
||||
placed: false,
|
||||
dimension: "minecraft:overworld".into(),
|
||||
menu: None,
|
||||
next_window: 0,
|
||||
drag: None,
|
||||
|
||||
@@ -39,6 +39,7 @@ pub mod game_event {
|
||||
pub const CHANGE_GAME_MODE: u8 = 3;
|
||||
pub const RAIN_LEVEL: u8 = 7;
|
||||
pub const THUNDER_LEVEL: u8 = 8;
|
||||
pub const GUARDIAN_ELDER_EFFECT: u8 = 10;
|
||||
pub const LEVEL_CHUNKS_LOAD_START: u8 = 13;
|
||||
}
|
||||
|
||||
@@ -127,6 +128,9 @@ pub struct Hub {
|
||||
last_rate: f32,
|
||||
ticking: (f32, bool),
|
||||
weather: (bool, f32, f32),
|
||||
/// The clock and weather last sent in the levels not in place, by
|
||||
/// dimension (`set_dimension` swaps them with the fields above).
|
||||
level_sync: std::collections::HashMap<String, LevelSync>,
|
||||
/// Operators and their permission levels (dedicated servers).
|
||||
pub ops: std::collections::HashMap<u128, u8>,
|
||||
chat_type: i32,
|
||||
@@ -195,6 +199,24 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
|
||||
dx * dx + dz * dz < i64::from(r) * i64::from(r)
|
||||
}
|
||||
|
||||
/// What a level's players were last told of its clock and weather.
|
||||
#[derive(Clone, Copy)]
|
||||
struct LevelSync {
|
||||
last_clock: i64,
|
||||
last_rate: f32,
|
||||
weather: (bool, f32, f32),
|
||||
}
|
||||
|
||||
impl Default for LevelSync {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
last_clock: i64::MIN,
|
||||
last_rate: 0.0,
|
||||
weather: (false, 0.0, 0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
pub fn new(lan: Lan, sync: Arc<SyncData>, encoder: ChunkEncoder, config: HubConfig) -> Self {
|
||||
let chat_type = sync
|
||||
@@ -220,6 +242,7 @@ impl Hub {
|
||||
ticking: (20.0, false),
|
||||
ops: Default::default(),
|
||||
weather: (false, 0.0, 0.0),
|
||||
level_sync: Default::default(),
|
||||
chat_type,
|
||||
dimension_type,
|
||||
clock_ids,
|
||||
@@ -273,6 +296,18 @@ impl Hub {
|
||||
g.sender.send(body.clone());
|
||||
}
|
||||
}
|
||||
/// Whether a guest is placed in the level in place (`config.dimension`).
|
||||
pub fn here(&self, g: &Guest) -> bool {
|
||||
g.placed && g.dimension == self.config.dimension
|
||||
}
|
||||
/// `PlayerList.broadcastAll(packet, dimension)`: the players in the
|
||||
/// level in place.
|
||||
pub fn broadcast_level(&self, packet: &C) {
|
||||
let body = packet.encode();
|
||||
for g in self.guests.iter().filter(|g| self.here(g)) {
|
||||
g.sender.send(body.clone());
|
||||
}
|
||||
}
|
||||
pub fn broadcast_except(&self, conn: u32, packet: &C) {
|
||||
let body = packet.encode();
|
||||
for g in self.guests.iter().filter(|g| g.placed && g.conn != conn) {
|
||||
@@ -464,6 +499,7 @@ impl Hub {
|
||||
guest.joined_tick = self.ticks;
|
||||
guest.position = ctx.spawn;
|
||||
guest.previous_position = ctx.spawn;
|
||||
guest.dimension = self.config.dimension.clone();
|
||||
self.guests.push(guest);
|
||||
conn
|
||||
}
|
||||
@@ -856,6 +892,20 @@ impl Hub {
|
||||
}
|
||||
|
||||
/// ServerPlayer.initInventoryMenu / sendAllDataToRemote for the inventory menu.
|
||||
/// ClientboundPlaceGhostRecipePacket: the recipe `id` faded into the
|
||||
/// guest's menu `container`, whose items were missing.
|
||||
pub fn send_ghost_recipe(&mut self, conn: u32, container: i32, id: &str) {
|
||||
let Some(display) = self.sync.advancements.ghost_display(id, &self.sync) else {
|
||||
return;
|
||||
};
|
||||
self.send_to(
|
||||
conn,
|
||||
&C::PlaceGhostRecipe(horizon_protocol::packets::recipes::PlaceGhostRecipe {
|
||||
container,
|
||||
display,
|
||||
}),
|
||||
);
|
||||
}
|
||||
pub fn send_inventory(&mut self, i: usize) {
|
||||
let items: Vec<Option<ItemStack>> = (0..46).map(|s| self.guests[i].menu_slot(s)).collect();
|
||||
let net: Vec<_> = items.iter().map(|s| self.stack(s)).collect();
|
||||
@@ -875,7 +925,19 @@ impl Hub {
|
||||
|
||||
// ---- per tick ------------------------------------------------------
|
||||
|
||||
/// A whole tick with one level: the network, the level, then the
|
||||
/// players' latencies.
|
||||
pub fn tick(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
|
||||
let mut events = self.poll(ctx);
|
||||
events.extend(self.tick_level(ctx));
|
||||
self.end_tick();
|
||||
events
|
||||
}
|
||||
|
||||
/// The network since the last tick, once per server tick before any
|
||||
/// level ticks: joins (into the level in place), leaves, and each guest's
|
||||
/// packets queued for its own level's pass.
|
||||
pub fn poll(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
|
||||
self.ticks += 1;
|
||||
let mut events = Vec::new();
|
||||
for event in self.lan.poll() {
|
||||
@@ -911,13 +973,25 @@ impl Hub {
|
||||
}
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
/// The level in place's part of the tick (`ServerLevel.tick`'s chunk
|
||||
/// map and the connections of the players in it): their packets, then
|
||||
/// the chunks, block changes, containers and entities they see.
|
||||
pub fn tick_level(&mut self, ctx: &mut TickCtx) -> Vec<HostEvent> {
|
||||
let mut events = Vec::new();
|
||||
for i in 0..self.guests.len() {
|
||||
if self.guests[i].placed {
|
||||
if self.here(&self.guests[i]) {
|
||||
self.process_inbox(i, ctx, &mut events);
|
||||
}
|
||||
}
|
||||
if !self.guests.iter().any(|g| g.placed) {
|
||||
if self.guests.is_empty() {
|
||||
if !self.guests.iter().any(|g| self.here(g)) {
|
||||
if !self
|
||||
.guests
|
||||
.iter()
|
||||
.any(|g| g.dimension == self.config.dimension)
|
||||
{
|
||||
let _ = ctx.world.block_log.take();
|
||||
}
|
||||
return events;
|
||||
@@ -927,7 +1001,7 @@ impl Hub {
|
||||
}
|
||||
self.sync_world(ctx);
|
||||
for i in 0..self.guests.len() {
|
||||
if self.guests[i].placed {
|
||||
if self.here(&self.guests[i]) {
|
||||
self.update_chunks(i, ctx);
|
||||
}
|
||||
}
|
||||
@@ -935,7 +1009,7 @@ impl Hub {
|
||||
// ServerGamePacketListenerImpl.tick: the actions handled since the last tick are
|
||||
// acknowledged after the block changes they made were sent, so a client's predicted
|
||||
// blocks settle on the server's states.
|
||||
for g in &self.guests {
|
||||
for g in self.guests.iter().filter(|g| self.here(g)) {
|
||||
let sequence = g.ack_up_to.replace(-1);
|
||||
if sequence >= 0 {
|
||||
g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence }));
|
||||
@@ -944,11 +1018,16 @@ impl Hub {
|
||||
self.sync_containers(ctx.world);
|
||||
self.track_entities(ctx);
|
||||
for i in 0..self.guests.len() {
|
||||
if self.guests[i].placed {
|
||||
if self.here(&self.guests[i]) {
|
||||
self.sync_player_state(i);
|
||||
self.sync_effects(i);
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
/// After every level: `PlayerList.tick`.
|
||||
pub fn end_tick(&mut self) {
|
||||
let latencies: Vec<_> = self
|
||||
.guests
|
||||
.iter()
|
||||
@@ -970,7 +1049,6 @@ impl Hub {
|
||||
entries,
|
||||
}));
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn remove_guest(&mut self, i: usize, reason: &str) -> Guest {
|
||||
@@ -1001,7 +1079,7 @@ impl Hub {
|
||||
// MinecraftServer.tickServer: the game time every 20 ticks
|
||||
// (forceGameTimeSynchronization, no clocks).
|
||||
if self.ticks.is_multiple_of(20) {
|
||||
self.broadcast(&C::SetTime(play::SetTime {
|
||||
self.broadcast_level(&C::SetTime(play::SetTime {
|
||||
game_time: world.game_time,
|
||||
clocks: Vec::new(),
|
||||
}));
|
||||
@@ -1017,7 +1095,7 @@ impl Hub {
|
||||
.sync
|
||||
.id("minecraft:world_clock", "minecraft:overworld")
|
||||
.unwrap_or(0);
|
||||
self.broadcast(&C::SetTime(play::SetTime {
|
||||
self.broadcast_level(&C::SetTime(play::SetTime {
|
||||
game_time: world.game_time,
|
||||
clocks: vec![play::ClockState {
|
||||
clock: overworld,
|
||||
@@ -1036,7 +1114,7 @@ impl Hub {
|
||||
let w = &world.weather;
|
||||
let (raining, rain, thunder) = self.weather;
|
||||
if w.raining != raining {
|
||||
self.broadcast(&C::GameEvent(play::GameEvent {
|
||||
self.broadcast_level(&C::GameEvent(play::GameEvent {
|
||||
event: if w.raining {
|
||||
game_event::START_RAINING
|
||||
} else {
|
||||
@@ -1046,13 +1124,13 @@ impl Hub {
|
||||
}));
|
||||
}
|
||||
if (w.rain_level.1 - rain).abs() > f32::EPSILON {
|
||||
self.broadcast(&C::GameEvent(play::GameEvent {
|
||||
self.broadcast_level(&C::GameEvent(play::GameEvent {
|
||||
event: game_event::RAIN_LEVEL,
|
||||
param: w.rain_level.1,
|
||||
}));
|
||||
}
|
||||
if (w.thunder_level.1 - thunder).abs() > f32::EPSILON {
|
||||
self.broadcast(&C::GameEvent(play::GameEvent {
|
||||
self.broadcast_level(&C::GameEvent(play::GameEvent {
|
||||
event: game_event::THUNDER_LEVEL,
|
||||
param: w.thunder_level.1,
|
||||
}));
|
||||
@@ -1122,21 +1200,20 @@ impl Hub {
|
||||
if !chunk.lit {
|
||||
continue;
|
||||
}
|
||||
packets.push(C::LevelChunkWithLight(
|
||||
self.encoder.encode_in(chunk, ctx.world),
|
||||
));
|
||||
packets.push(self.encoder.body_in(chunk, ctx.world));
|
||||
taken.push(idx);
|
||||
}
|
||||
if packets.is_empty() {
|
||||
return;
|
||||
}
|
||||
g.batch_quota -= packets.len() as f32;
|
||||
let size = packets.len();
|
||||
g.batch_quota -= size as f32;
|
||||
g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty));
|
||||
for p in &packets {
|
||||
g.send(p);
|
||||
for body in packets {
|
||||
g.sender.send(body);
|
||||
}
|
||||
g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished {
|
||||
size: packets.len() as i32,
|
||||
size: size as i32,
|
||||
}));
|
||||
g.unacknowledged += 1;
|
||||
for idx in taken.into_iter().rev() {
|
||||
@@ -1150,8 +1227,7 @@ impl Hub {
|
||||
let Some(chunk) = world.chunks.get(&(x, z)) else {
|
||||
return;
|
||||
};
|
||||
let packet = C::LevelChunkWithLight(self.encoder.encode_in(chunk, world));
|
||||
let body = packet.encode();
|
||||
let body = self.encoder.body_in(chunk, world);
|
||||
for g in self
|
||||
.guests
|
||||
.iter()
|
||||
@@ -1183,7 +1259,7 @@ impl Hub {
|
||||
for ((sx, sy, sz), positions) in sections {
|
||||
let viewers: Vec<usize> = (0..self.guests.len())
|
||||
.filter(|&i| {
|
||||
self.guests[i].placed && self.guests[i].sent_chunks.contains(&(sx, sz))
|
||||
self.here(&self.guests[i]) && self.guests[i].sent_chunks.contains(&(sx, sz))
|
||||
})
|
||||
.collect();
|
||||
if viewers.is_empty() {
|
||||
@@ -1348,7 +1424,7 @@ impl Hub {
|
||||
));
|
||||
}
|
||||
let placed: Vec<usize> = (0..self.guests.len())
|
||||
.filter(|&i| self.guests[i].placed)
|
||||
.filter(|&i| self.here(&self.guests[i]))
|
||||
.collect();
|
||||
let guest_states: Vec<_> = placed
|
||||
.into_iter()
|
||||
@@ -1388,7 +1464,7 @@ impl Hub {
|
||||
.map(|e| super::entity::tracking_chunks(&e.kind))
|
||||
.collect();
|
||||
for gi in 0..self.guests.len() {
|
||||
if !self.guests[gi].placed {
|
||||
if !self.here(&self.guests[gi]) {
|
||||
continue;
|
||||
}
|
||||
let view = self.guests[gi].view_distance;
|
||||
@@ -1983,12 +2059,15 @@ impl Hub {
|
||||
let mode = self.guests[i].game_mode;
|
||||
let mut info = self.spawn_info(mode);
|
||||
// Player.getLastDeathLocation, set where the player died.
|
||||
// The level they died in: theirs until now.
|
||||
info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos {
|
||||
dimension: self.config.dimension.clone(),
|
||||
dimension: self.guests[i].dimension.clone(),
|
||||
pos,
|
||||
});
|
||||
self.close_container_for(i);
|
||||
let g = &mut self.guests[i];
|
||||
// PlayerList.respawn: into the level in place (the respawn level).
|
||||
g.dimension = self.config.dimension.clone();
|
||||
// ServerLevel.removePlayerImmediately: every entity paired with the dead player is
|
||||
// removed (ServerEntity.removePairing, one packet each). Its chunks are dropped
|
||||
// without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the
|
||||
@@ -2057,6 +2136,20 @@ impl Hub {
|
||||
/// The level the players are in: the server holds one at a time, and the
|
||||
/// hub's packets name it.
|
||||
pub fn set_dimension(&mut self, dimension: &str) {
|
||||
if self.config.dimension == dimension {
|
||||
return;
|
||||
}
|
||||
// What this level's players were told stays with it.
|
||||
let leaving = LevelSync {
|
||||
last_clock: self.last_clock,
|
||||
last_rate: self.last_rate,
|
||||
weather: self.weather,
|
||||
};
|
||||
let entering = self.level_sync.remove(dimension).unwrap_or_default();
|
||||
self.level_sync
|
||||
.insert(std::mem::take(&mut self.config.dimension), leaving);
|
||||
(self.last_clock, self.last_rate, self.weather) =
|
||||
(entering.last_clock, entering.last_rate, entering.weather);
|
||||
self.config.dimension = dimension.to_owned();
|
||||
self.dimension_type = self
|
||||
.sync
|
||||
@@ -2076,6 +2169,7 @@ impl Hub {
|
||||
let info = self.spawn_info(mode);
|
||||
self.close_container_for(i);
|
||||
let g = &mut self.guests[i];
|
||||
g.dimension = self.config.dimension.clone();
|
||||
g.tracker.clear();
|
||||
g.sent_chunks.clear();
|
||||
g.chunk_queue.clear();
|
||||
|
||||
@@ -22,7 +22,7 @@ mod recipes;
|
||||
pub mod tracking;
|
||||
pub mod waypoints;
|
||||
|
||||
pub use conn::{Holding, PlayerSender};
|
||||
pub use conn::{Holding, PlayerSender, flush_all};
|
||||
use horizon_protocol::packets::play;
|
||||
use horizon_protocol::{
|
||||
GAME_VERSION, PROTOCOL_VERSION, crypto::uuid_string, packets::configuration::ClientInformation,
|
||||
|
||||
@@ -71,6 +71,10 @@ pub fn apply(guest: &mut Guest, level: &Level) {
|
||||
guest.selected = (level.selected_slot.max(0) as usize).min(8);
|
||||
guest.saved = level.player_extra.clone();
|
||||
guest.recipe_book = level.recipe_book.clone();
|
||||
guest.dimension = match level.dimension.as_str() {
|
||||
d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(),
|
||||
_ => "minecraft:overworld".to_owned(),
|
||||
};
|
||||
if level.ender_items.len() == 27 {
|
||||
guest.ender_items = level.ender_items.clone();
|
||||
}
|
||||
@@ -100,7 +104,6 @@ pub fn apply(guest: &mut Guest, level: &Level) {
|
||||
pub fn save(guest: &Guest, world: &Path) {
|
||||
let mut level = Level {
|
||||
player_uuid: Some(uuid_ints(guest.uuid)),
|
||||
dimension: "minecraft:overworld".into(),
|
||||
..Level::default()
|
||||
};
|
||||
store(guest, &mut level);
|
||||
@@ -114,6 +117,7 @@ pub fn save(guest: &Guest, world: &Path) {
|
||||
/// Put a guest's state in `level`'s player fields.
|
||||
pub fn store(guest: &Guest, level: &mut Level) {
|
||||
level.position = Some(guest.position);
|
||||
level.dimension = guest.dimension.clone();
|
||||
level.rotation = [guest.yaw, guest.pitch];
|
||||
level.health = guest.health;
|
||||
level.food = guest.food;
|
||||
|
||||
@@ -115,6 +115,27 @@ pub fn draw(
|
||||
}
|
||||
}
|
||||
|
||||
/// The startup loading screen: the stage's line and a progress bar, centred
|
||||
/// like `LevelLoadingScreen`'s text and bar.
|
||||
pub fn draw_progress(batch: &mut HudBatch, atlas: &HudAtlas, line: &str, progress: f32) {
|
||||
let (x_center, y_center) = ((batch.width as i32) / 2, (batch.height as i32) / 2);
|
||||
let text_top = y_center - 50;
|
||||
let text = Text::literal(line);
|
||||
let tw = atlas.font.width_text(&text) as i32;
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&text,
|
||||
(x_center - tw / 2) as f32,
|
||||
text_top as f32,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
let (left, top) = ((x_center - 100) as f32, (text_top + 9 + 3) as f32);
|
||||
batch.fill(atlas, left, top, 200.0, 2.0, opaque(0));
|
||||
let done = (progress.clamp(0.0, 1.0) * 200.0).round();
|
||||
batch.fill(atlas, left, top, done, 2.0, opaque(0x00FF00));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -686,6 +686,8 @@ pub struct Extra {
|
||||
pub legs: Option<Arc<str>>,
|
||||
pub feet: Option<Arc<str>>,
|
||||
pub using_item: i32,
|
||||
pub using_off_hand: bool,
|
||||
pub blocking: bool,
|
||||
pub fall_flying: bool,
|
||||
pub fall_fly_ticks: i32,
|
||||
pub main_hand_left: bool,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::{Mob, Part, keyframes::AnimationState, living::wrap};
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
use std::collections::HashMap;
|
||||
use std::f32::consts::PI;
|
||||
use std::f32::consts::{FRAC_PI_6, PI};
|
||||
|
||||
/// The setupAnim implementation a model uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -232,6 +232,7 @@ fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) {
|
||||
pub enum ArmPose {
|
||||
Empty,
|
||||
Item,
|
||||
Block,
|
||||
Bow,
|
||||
CrossbowHold,
|
||||
CrossbowCharge,
|
||||
@@ -355,6 +356,14 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
|
||||
p.xrot(arm, x * 0.5 - PI / 10.0);
|
||||
p.yrot(arm, 0.0);
|
||||
}
|
||||
ArmPose::Block => {
|
||||
let x = p.get(arm)[3] * 0.5 - 0.942_477_9 + hx.clamp(-1.396_263_4, 0.436_332_32);
|
||||
p.xrot(arm, x);
|
||||
p.yrot(
|
||||
arm,
|
||||
if right { -FRAC_PI_6 } else { FRAC_PI_6 } + hy.clamp(-FRAC_PI_6, FRAC_PI_6),
|
||||
);
|
||||
}
|
||||
ArmPose::Bow => {
|
||||
p.yrot("right_arm", -0.1 + hy - if right { 0.0 } else { 0.4 });
|
||||
p.yrot("left_arm", 0.1 + hy + if right { 0.4 } else { 0.0 });
|
||||
@@ -661,11 +670,13 @@ pub fn setup(
|
||||
} else {
|
||||
ArmPose::Empty
|
||||
};
|
||||
let using_main = m.extra.using_item > 0 && !m.extra.using_off_hand;
|
||||
let pose = if player {
|
||||
match m.extra.main_hand.as_deref() {
|
||||
Some("minecraft:bow") if m.extra.using_item > 0 => ArmPose::Bow,
|
||||
Some("minecraft:trident") if m.extra.using_item > 0 => ArmPose::ThrowTrident,
|
||||
Some("minecraft:crossbow") if m.extra.using_item > 0 && !m.extra.charged => {
|
||||
Some(_) if using_main && m.extra.blocking => ArmPose::Block,
|
||||
Some("minecraft:bow") if using_main => ArmPose::Bow,
|
||||
Some("minecraft:trident") if using_main => ArmPose::ThrowTrident,
|
||||
Some("minecraft:crossbow") if using_main && !m.extra.charged => {
|
||||
ArmPose::CrossbowCharge
|
||||
}
|
||||
Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => {
|
||||
@@ -678,7 +689,11 @@ pub fn setup(
|
||||
right
|
||||
};
|
||||
let off = if player && m.extra.off_hand.is_some() && !pose.affects_offhand() {
|
||||
ArmPose::Item
|
||||
if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking {
|
||||
ArmPose::Block
|
||||
} else {
|
||||
ArmPose::Item
|
||||
}
|
||||
} else {
|
||||
ArmPose::Empty
|
||||
};
|
||||
@@ -791,6 +806,42 @@ pub fn setup(
|
||||
#[cfg(test)]
|
||||
mod flight_pose_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blocking_arm_follows_the_head_with_limits_in_both_hands() {
|
||||
for right in [false, true] {
|
||||
for (pitch, yaw, expected_pitch, expected_yaw) in [
|
||||
(0.0, 0.0, -0.742_477_9, 0.0),
|
||||
(2.0, 2.0, -0.306_145_58, FRAC_PI_6),
|
||||
(-2.0, -2.0, -2.138_741_3, -FRAC_PI_6),
|
||||
] {
|
||||
let mut p = Poses {
|
||||
map: ["head", "right_arm", "left_arm"]
|
||||
.into_iter()
|
||||
.map(|n| (n.to_string(), [0.0; 9]))
|
||||
.collect(),
|
||||
dummy: [0.0; 9],
|
||||
skipped: Default::default(),
|
||||
hidden: Default::default(),
|
||||
};
|
||||
let arm = if right { "right_arm" } else { "left_arm" };
|
||||
p.xrot("head", pitch);
|
||||
p.yrot("head", yaw);
|
||||
p.xrot(arm, 0.4);
|
||||
pose_arm(
|
||||
&mut p,
|
||||
ArmPose::Block,
|
||||
right,
|
||||
&Hum::new(ArmPose::Empty, ArmPose::Empty),
|
||||
);
|
||||
let pose = *p.get(arm);
|
||||
assert!((pose[3] - expected_pitch).abs() < 1e-6);
|
||||
let side = if right { -FRAC_PI_6 } else { FRAC_PI_6 };
|
||||
assert!((pose[4] - (side + expected_yaw)).abs() < 1e-6);
|
||||
assert_eq!(p.get(if right { "left_arm" } else { "right_arm" })[3], 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn flight_slows_limbs_and_sets_the_head_pose() {
|
||||
let state = State {
|
||||
|
||||
@@ -292,19 +292,25 @@ impl PlayerMotion {
|
||||
&& movement.x * movement.x + movement.z * movement.z < limit * limit
|
||||
&& sword
|
||||
}
|
||||
pub fn load_environment_once(
|
||||
/// Restore login state once; a later respawn starts with fresh health and food.
|
||||
pub fn load_saved_state_once(
|
||||
&mut self,
|
||||
pending: &mut bool,
|
||||
extra: Option<&horizon_world::nbt::Tag>,
|
||||
) {
|
||||
level: &crate::save::Level,
|
||||
) -> Result<()> {
|
||||
if std::mem::take(pending) {
|
||||
let extra = level.player_extra.as_ref();
|
||||
self.fire_ticks = extra
|
||||
.and_then(|t| crate::save::number(t.get("Fire")))
|
||||
.unwrap_or(-20) as i32;
|
||||
self.air = extra
|
||||
.and_then(|t| crate::save::number(t.get("Air")))
|
||||
.unwrap_or(300) as i32;
|
||||
self.set_health(level.health, false)?;
|
||||
self.health.food.food = level.food;
|
||||
self.health.food.saturation = level.saturation;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_remaining_fire_ticks(&mut self, ticks: i32) {
|
||||
self.fire_ticks = if self.invulnerable {
|
||||
@@ -2166,8 +2172,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn player_fire_damage_queues_hurt_sound_only_for_fresh_hits() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
|
||||
let root = std::env::var_os("HORIZON_TEST_RESOURCES")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
|
||||
});
|
||||
if !root.join("movement-properties.nbt").exists() {
|
||||
eprintln!("skipped damage regression: prepared resources unavailable");
|
||||
return;
|
||||
}
|
||||
let assets = Assets::load(&root).unwrap();
|
||||
@@ -2195,6 +2206,8 @@ mod tests {
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(player.health.hurt_animation_time, 10);
|
||||
player.health.advance_clock();
|
||||
player.events.clear();
|
||||
assert!(
|
||||
!player
|
||||
@@ -2207,9 +2220,14 @@ mod tests {
|
||||
.iter()
|
||||
.any(|e| matches!(e, MotionEvent::HurtSound(_)))
|
||||
);
|
||||
assert_eq!(
|
||||
player.health.hurt_animation_time, 9,
|
||||
"cooldown hit must not restart animation"
|
||||
);
|
||||
for _ in 0..20 {
|
||||
player.health.advance_clock();
|
||||
}
|
||||
assert_eq!(player.health.hurt_animation_time, 0);
|
||||
player.invulnerable = true;
|
||||
player.events.clear();
|
||||
assert!(
|
||||
@@ -2271,16 +2289,62 @@ mod tests {
|
||||
Default::default(),
|
||||
source,
|
||||
4.0,
|
||||
Some(shield),
|
||||
Some(shield.clone()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!outcome.hurt && outcome.sound && outcome.blocked == 4.0);
|
||||
assert_eq!(
|
||||
player.health.hurt.hurt_time, 10,
|
||||
"preserve server damage bookkeeping"
|
||||
);
|
||||
assert_eq!(
|
||||
player.health.hurt_animation_time, 0,
|
||||
"a fully blocked arrow must not animate hurt"
|
||||
);
|
||||
assert!(
|
||||
!player
|
||||
.events
|
||||
.iter()
|
||||
.any(|e| matches!(e, MotionEvent::HurtSound(_)))
|
||||
);
|
||||
// An unblocked hit after the shield block must still animate normally.
|
||||
for _ in 0..20 {
|
||||
player.health.advance_clock();
|
||||
}
|
||||
assert!(
|
||||
player
|
||||
.hurt(&resources.health, Default::default(), source, 4.0)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(player.health.hurt_animation_time, 10);
|
||||
player.health.advance_clock();
|
||||
assert!(
|
||||
!player
|
||||
.hurt_blocking(
|
||||
&resources.health,
|
||||
Default::default(),
|
||||
source,
|
||||
4.0,
|
||||
Some(shield)
|
||||
)
|
||||
.unwrap()
|
||||
.hurt
|
||||
);
|
||||
assert_eq!(
|
||||
player.health.hurt_animation_time, 9,
|
||||
"blocking must not erase or restart an existing animation"
|
||||
);
|
||||
let mut starving = PlayerMotion::new(&resources, Vec3::ZERO).unwrap();
|
||||
starving.health.food.food = 0;
|
||||
starving.health.food.timer = 79;
|
||||
starving
|
||||
.food_tick(&resources.health, Default::default())
|
||||
.unwrap();
|
||||
assert_eq!(starving.health.health(), 19.0);
|
||||
assert_eq!(
|
||||
starving.health.hurt_animation_time, 10,
|
||||
"starvation must still animate hurt"
|
||||
);
|
||||
}
|
||||
|
||||
/// Footsteps on the prepared vanilla resources, when they are present:
|
||||
@@ -2329,8 +2393,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn resident_water_and_lava_are_not_treated_as_air() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
|
||||
let root = std::env::var_os("HORIZON_TEST_RESOURCES")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
|
||||
});
|
||||
if !root.join("movement-properties.nbt").exists() {
|
||||
eprintln!("skipping resident water/lava test: prepared resources unavailable");
|
||||
return;
|
||||
}
|
||||
let assets = Assets::load(&root).unwrap();
|
||||
@@ -2536,12 +2605,41 @@ mod tests {
|
||||
("Fire", horizon_world::nbt::Tag::Short(160)),
|
||||
("Air", horizon_world::nbt::Tag::Short(8)),
|
||||
]);
|
||||
let mut level = crate::save::Level {
|
||||
health: 13.0,
|
||||
food: 11,
|
||||
saturation: 2.25,
|
||||
player_extra: Some(extra),
|
||||
..Default::default()
|
||||
};
|
||||
let mut pending = true;
|
||||
w.player.load_environment_once(&mut pending, Some(&extra));
|
||||
w.player
|
||||
.load_saved_state_once(&mut pending, &level)
|
||||
.unwrap();
|
||||
assert_eq!((w.player.fire_ticks, w.player.air), (160, 8));
|
||||
assert_eq!(
|
||||
(
|
||||
w.player.health.health(),
|
||||
w.player.health.food.food,
|
||||
w.player.health.food.saturation
|
||||
),
|
||||
(13.0, 11, 2.25)
|
||||
);
|
||||
let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
|
||||
respawn.load_environment_once(&mut pending, Some(&extra));
|
||||
respawn.load_saved_state_once(&mut pending, &level).unwrap();
|
||||
assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300));
|
||||
assert_eq!(
|
||||
(respawn.health.health(), respawn.health.food.food),
|
||||
(20.0, 20)
|
||||
);
|
||||
// Reopening another world restores its state, including a saved death.
|
||||
pending = true;
|
||||
level.health = 0.0;
|
||||
w.player
|
||||
.load_saved_state_once(&mut pending, &level)
|
||||
.unwrap();
|
||||
assert!(w.player.health.dead_or_dying());
|
||||
assert!(!pending);
|
||||
w.player.fluids.was_touching_water = false;
|
||||
assert!(
|
||||
w.player.moving_slowly(),
|
||||
|
||||
@@ -756,6 +756,15 @@ impl RecipeIndex {
|
||||
r.first_display..r.first_display + r.displays as i32
|
||||
})
|
||||
}
|
||||
/// The recipe a display id belongs to (`RecipeManager.getRecipeFromDisplay`).
|
||||
pub fn recipe_of_display(&self, display: i32) -> Option<&str> {
|
||||
self.recipes
|
||||
.iter()
|
||||
.find(|(_, r)| {
|
||||
(r.first_display..r.first_display + r.displays as i32).contains(&display)
|
||||
})
|
||||
.map(|(id, _)| id.as_str())
|
||||
}
|
||||
pub fn first_display(&self, id: &str) -> Option<i32> {
|
||||
self.recipes
|
||||
.get(id)
|
||||
|
||||
@@ -3444,6 +3444,17 @@ mod tests {
|
||||
third.ender_items[3].as_ref().map(|s| (&*s.item, s.count)),
|
||||
Some(("minecraft:diamond", 2))
|
||||
);
|
||||
// A dead player's empty inventory replaces the previously loaded items.
|
||||
let mut dead = third;
|
||||
dead.health = 0.0;
|
||||
dead.inventory.clear();
|
||||
dead.inventory_components.clear();
|
||||
dead.write(&dir).unwrap();
|
||||
let dead = Level::read(&dir).unwrap();
|
||||
assert_eq!(dead.health, 0.0);
|
||||
assert!(dead.inventory.is_empty());
|
||||
assert!(dead.inventory_components.is_empty());
|
||||
assert!(dead.player_extra.unwrap().get("equipment").is_none());
|
||||
assert!(dir.join("data/minecraft/world_gen_settings.dat").exists());
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -76,7 +76,24 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> {
|
||||
@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>,
|
||||
@location(5) origin: vec4<f32>) -> TerrainOut {
|
||||
let pos = position + origin.xyz;
|
||||
return terrain_vertex(position, uv, layer, color, light, origin.xyz);
|
||||
}
|
||||
// Flat section draws (gfx/flat.rs): one draw per arena page over the frame's
|
||||
// index list. A section's vertices fill whole 256-vertex blocks of its page:
|
||||
// the block gives its resident slot, the slot its camera-relative origin.
|
||||
@group(1) @binding(0) var<storage, read> block_slots: array<u32>;
|
||||
@group(1) @binding(1) var<storage, read> slot_origins: array<vec4<f32>>;
|
||||
@vertex fn vs_terrain_flat(
|
||||
@builtin(vertex_index) vertex: u32,
|
||||
@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>
|
||||
) -> TerrainOut {
|
||||
let origin = slot_origins[block_slots[vertex >> 8u]];
|
||||
return terrain_vertex(position, uv, layer, color, light, origin.xyz);
|
||||
}
|
||||
fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f32>,
|
||||
light: vec2<u32>, origin: vec3<f32>) -> TerrainOut {
|
||||
let pos = position + origin;
|
||||
var out: TerrainOut;
|
||||
out.clip = globals.view_proj * vec4(pos, 1.0);
|
||||
out.uv = uv;
|
||||
|
||||
@@ -128,6 +128,20 @@ pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option<Pres
|
||||
preferred.iter().copied().find(|m| supported.contains(m))
|
||||
}
|
||||
|
||||
/// The present mode for the VSync option and Horizon's present-mode setting
|
||||
/// (`None` for Auto). VSync on always means Fifo, in a window and in
|
||||
/// fullscreen alike, as in vanilla; the setting chooses only while VSync is
|
||||
/// off, when the surface supports it, and otherwise vanilla's choice applies.
|
||||
pub fn chosen_present_mode(
|
||||
supported: &[PresentMode],
|
||||
vsync: bool,
|
||||
setting: Option<PresentMode>,
|
||||
) -> Option<PresentMode> {
|
||||
setting
|
||||
.filter(|m| !vsync && supported.contains(m))
|
||||
.or_else(|| vsync_present_mode(supported, vsync))
|
||||
}
|
||||
|
||||
/// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep
|
||||
/// and spin decisions are testable.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -415,4 +429,23 @@ mod tests {
|
||||
Some(PresentMode::Fifo)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn vsync_on_waits_for_the_display_whatever_the_present_mode() {
|
||||
use PresentMode::*;
|
||||
let all = [Mailbox, Fifo, Immediate];
|
||||
for setting in [None, Some(Fifo), Some(Mailbox), Some(Immediate)] {
|
||||
assert_eq!(chosen_present_mode(&all, true, setting), Some(Fifo));
|
||||
}
|
||||
assert_eq!(chosen_present_mode(&all, false, None), Some(Immediate));
|
||||
assert_eq!(
|
||||
chosen_present_mode(&all, false, Some(Mailbox)),
|
||||
Some(Mailbox)
|
||||
);
|
||||
assert_eq!(chosen_present_mode(&all, false, Some(Fifo)), Some(Fifo));
|
||||
// Metal has no Mailbox: vanilla's choice instead.
|
||||
assert_eq!(
|
||||
chosen_present_mode(&[Fifo, Immediate], false, Some(Mailbox)),
|
||||
Some(Immediate)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,9 +342,7 @@ fn status_and_join() {
|
||||
C::PlayerInfoUpdate(u) => {
|
||||
info |= u.entries.iter().any(|e| e.name.as_deref() == Some("Host"));
|
||||
}
|
||||
C::Unknown(id, _) if id == horizon_protocol::ids::play::clientbound::COMMANDS => {
|
||||
commands = true
|
||||
}
|
||||
C::Commands(_) => commands = true,
|
||||
C::LevelChunkWithLight(l) => {
|
||||
chunks += 1;
|
||||
let sections = l.chunk.sections(24, 16, 7).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -23,6 +23,10 @@ impl<'a> Reader<'a> {
|
||||
pub fn position(&self) -> usize {
|
||||
self.pos
|
||||
}
|
||||
/// The bytes read since `start` (a `position()`).
|
||||
pub fn since(&self, start: usize) -> &'a [u8] {
|
||||
&self.data[start.min(self.pos)..self.pos]
|
||||
}
|
||||
pub fn rest(&mut self) -> &'a [u8] {
|
||||
let rest = &self.data[self.pos..];
|
||||
self.pos = self.data.len();
|
||||
|
||||
@@ -289,7 +289,12 @@ impl ConnReader {
|
||||
impl ConnWriter {
|
||||
/// Send one packet body (VarInt id + payload).
|
||||
pub fn send(&mut self, body: &[u8]) -> Result<()> {
|
||||
let mut framed = frame::encode(body, self.threshold)?;
|
||||
self.send_contents(&frame::contents(body, self.threshold)?)
|
||||
}
|
||||
/// Send a frame whose contents [`frame::contents`] made with this
|
||||
/// writer's threshold.
|
||||
pub fn send_contents(&mut self, contents: &[u8]) -> Result<()> {
|
||||
let mut framed = frame::prefixed(contents);
|
||||
if let Some(c) = &mut self.encrypt {
|
||||
c.encrypt(&mut framed);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ pub const MAX_UNCOMPRESSED: usize = 8_388_608;
|
||||
/// length prefix, and with compression enabled the uncompressed-length
|
||||
/// field (0 when below the threshold).
|
||||
pub fn encode(body: &[u8], threshold: Option<usize>) -> Result<Vec<u8>> {
|
||||
Ok(prefixed(&contents(body, threshold)?))
|
||||
}
|
||||
|
||||
/// What [`encode`] puts after the length prefix: the same for every
|
||||
/// connection with the same threshold.
|
||||
pub fn contents(body: &[u8], threshold: Option<usize>) -> Result<Vec<u8>> {
|
||||
let inner = match threshold {
|
||||
None => body.to_vec(),
|
||||
Some(t) if body.len() < t => {
|
||||
@@ -38,10 +44,15 @@ pub fn encode(body: &[u8], threshold: Option<usize>) -> Result<Vec<u8>> {
|
||||
inner.len()
|
||||
)));
|
||||
}
|
||||
let mut out = Vec::with_capacity(inner.len() + 3);
|
||||
write_varint(&mut out, inner.len() as i32);
|
||||
out.extend_from_slice(&inner);
|
||||
Ok(out)
|
||||
Ok(inner)
|
||||
}
|
||||
|
||||
/// A frame: the length prefix, then the [`contents`].
|
||||
pub fn prefixed(contents: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(contents.len() + 3);
|
||||
write_varint(&mut out, contents.len() as i32);
|
||||
out.extend_from_slice(contents);
|
||||
out
|
||||
}
|
||||
|
||||
/// Split one complete frame off the front of `buffer`, if available.
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod configuration;
|
||||
pub mod handshake;
|
||||
pub mod login;
|
||||
pub mod play;
|
||||
pub mod recipes;
|
||||
pub mod status;
|
||||
|
||||
use crate::buf::{Codec, Reader, Writer};
|
||||
|
||||
@@ -901,6 +901,177 @@ pub struct CommandNode {
|
||||
/// Custom suggestion provider (`minecraft:ask_server`).
|
||||
pub suggestions: Option<String>,
|
||||
}
|
||||
/// The `minecraft:command_argument_type` registry of 26.3 in id order
|
||||
/// (ArgumentTypeInfos.bootstrap).
|
||||
pub const ARGUMENT_TYPES: &[&str] = &[
|
||||
"brigadier:bool",
|
||||
"brigadier:float",
|
||||
"brigadier:double",
|
||||
"brigadier:integer",
|
||||
"brigadier:long",
|
||||
"brigadier:string",
|
||||
"minecraft:entity",
|
||||
"minecraft:game_profile",
|
||||
"minecraft:block_pos",
|
||||
"minecraft:column_pos",
|
||||
"minecraft:vec3",
|
||||
"minecraft:vec2",
|
||||
"minecraft:block_state",
|
||||
"minecraft:block_predicate",
|
||||
"minecraft:item_stack",
|
||||
"minecraft:item_predicate",
|
||||
"minecraft:team_color",
|
||||
"minecraft:hex_color",
|
||||
"minecraft:component",
|
||||
"minecraft:style",
|
||||
"minecraft:message",
|
||||
"minecraft:nbt_compound_tag",
|
||||
"minecraft:nbt_tag",
|
||||
"minecraft:nbt_path",
|
||||
"minecraft:objective",
|
||||
"minecraft:objective_criteria",
|
||||
"minecraft:operation",
|
||||
"minecraft:particle",
|
||||
"minecraft:angle",
|
||||
"minecraft:rotation",
|
||||
"minecraft:scoreboard_slot",
|
||||
"minecraft:score_holder",
|
||||
"minecraft:swizzle",
|
||||
"minecraft:team",
|
||||
"minecraft:item_slot",
|
||||
"minecraft:item_slots",
|
||||
"minecraft:resource_location",
|
||||
"minecraft:function",
|
||||
"minecraft:entity_anchor",
|
||||
"minecraft:int_range",
|
||||
"minecraft:float_range",
|
||||
"minecraft:dimension",
|
||||
"minecraft:gamemode",
|
||||
"minecraft:time",
|
||||
"minecraft:resource_or_tag",
|
||||
"minecraft:resource_or_tag_key",
|
||||
"minecraft:resource",
|
||||
"minecraft:resource_key",
|
||||
"minecraft:resource_selector",
|
||||
"minecraft:template_mirror",
|
||||
"minecraft:template_rotation",
|
||||
"minecraft:heightmap",
|
||||
"minecraft:loot_table",
|
||||
"minecraft:loot_predicate",
|
||||
"minecraft:loot_modifier",
|
||||
"minecraft:context_float_provider",
|
||||
"minecraft:context_int_provider",
|
||||
"minecraft:slot_source",
|
||||
"minecraft:dialog",
|
||||
"minecraft:feature",
|
||||
"minecraft:swing_animation",
|
||||
"minecraft:uuid",
|
||||
];
|
||||
|
||||
/// The properties of an argument parser (`ArgumentTypeInfo.Template`) as
|
||||
/// one of the 26.3 parsers decoded from the network.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ArgumentProperties {
|
||||
None,
|
||||
Integer {
|
||||
min: Option<i32>,
|
||||
max: Option<i32>,
|
||||
},
|
||||
Long {
|
||||
min: Option<i64>,
|
||||
max: Option<i64>,
|
||||
},
|
||||
Float {
|
||||
min: Option<f32>,
|
||||
max: Option<f32>,
|
||||
},
|
||||
Double {
|
||||
min: Option<f64>,
|
||||
max: Option<f64>,
|
||||
},
|
||||
/// StringArgumentType.StringType: 0 word, 1 phrase, 2 greedy.
|
||||
String(i32),
|
||||
Entity {
|
||||
single: bool,
|
||||
players_only: bool,
|
||||
},
|
||||
ScoreHolder {
|
||||
multiple: bool,
|
||||
},
|
||||
Time {
|
||||
min: i32,
|
||||
},
|
||||
/// The resource arguments' registry.
|
||||
Registry(String),
|
||||
}
|
||||
|
||||
impl ArgumentProperties {
|
||||
/// ArgumentTypeInfo.deserializeFromNetwork for parser `id`.
|
||||
pub fn read(r: &mut Reader, id: i32) -> Result<Self> {
|
||||
let name = usize::try_from(id)
|
||||
.ok()
|
||||
.and_then(|i| ARGUMENT_TYPES.get(i))
|
||||
.ok_or_else(|| crate::Error::new(format!("unknown argument type {id}")))?;
|
||||
let flagged = |r: &mut Reader| -> Result<(bool, bool)> {
|
||||
let f = r.u8()?;
|
||||
Ok((f & 1 != 0, f & 2 != 0))
|
||||
};
|
||||
Ok(match *name {
|
||||
"brigadier:integer" => {
|
||||
let (min, max) = flagged(r)?;
|
||||
let min = if min { Some(r.i32()?) } else { None };
|
||||
let max = if max { Some(r.i32()?) } else { None };
|
||||
Self::Integer { min, max }
|
||||
}
|
||||
"brigadier:long" => {
|
||||
let (min, max) = flagged(r)?;
|
||||
let min = if min { Some(r.i64()?) } else { None };
|
||||
let max = if max { Some(r.i64()?) } else { None };
|
||||
Self::Long { min, max }
|
||||
}
|
||||
"brigadier:float" => {
|
||||
let (min, max) = flagged(r)?;
|
||||
let min = if min { Some(r.f32()?) } else { None };
|
||||
let max = if max { Some(r.f32()?) } else { None };
|
||||
Self::Float { min, max }
|
||||
}
|
||||
"brigadier:double" => {
|
||||
let (min, max) = flagged(r)?;
|
||||
let min = if min { Some(r.f64()?) } else { None };
|
||||
let max = if max { Some(r.f64()?) } else { None };
|
||||
Self::Double { min, max }
|
||||
}
|
||||
"brigadier:string" => Self::String(r.varint()?),
|
||||
"minecraft:entity" => {
|
||||
let f = r.u8()?;
|
||||
Self::Entity {
|
||||
single: f & 1 != 0,
|
||||
players_only: f & 2 != 0,
|
||||
}
|
||||
}
|
||||
"minecraft:score_holder" => Self::ScoreHolder {
|
||||
multiple: r.u8()? & 1 != 0,
|
||||
},
|
||||
"minecraft:time" => Self::Time { min: r.i32()? },
|
||||
"minecraft:resource"
|
||||
| "minecraft:resource_key"
|
||||
| "minecraft:resource_or_tag"
|
||||
| "minecraft:resource_or_tag_key"
|
||||
| "minecraft:resource_selector" => Self::Registry(r.string(32767)?),
|
||||
_ => Self::None,
|
||||
})
|
||||
}
|
||||
/// Decodes a node's raw `parser` bytes.
|
||||
pub fn decode(id: i32, bytes: &[u8]) -> Result<Self> {
|
||||
Self::read(&mut Reader::new(bytes), id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads past an argument node's parser properties.
|
||||
fn read_argument_properties(r: &mut Reader, id: i32) -> Result<()> {
|
||||
ArgumentProperties::read(r, id).map(|_| ())
|
||||
}
|
||||
|
||||
/// The command tree: nodes and the index of the root.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Commands {
|
||||
@@ -926,11 +1097,14 @@ impl Codec<Commands> for Commands {
|
||||
name = r.string(32767)?;
|
||||
}
|
||||
if kind == 2 {
|
||||
// Properties are parser specific; only the property-less parsers
|
||||
// can be skipped without a table, so keep the rest of the packet.
|
||||
return Err(crate::Error::new("argument nodes are not decoded"));
|
||||
let id = r.varint()?;
|
||||
let start = r.position();
|
||||
read_argument_properties(r, id)?;
|
||||
parser = Some((id, r.since(start).to_vec()));
|
||||
if flags & 16 != 0 {
|
||||
suggestions = Some(r.string(32767)?);
|
||||
}
|
||||
}
|
||||
let _ = (&mut parser, &mut suggestions);
|
||||
nodes.push(CommandNode {
|
||||
kind,
|
||||
executable: flags & 4 != 0,
|
||||
@@ -1189,6 +1363,10 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
||||
ChunkBatchStart(Empty) = CHUNK_BATCH_START,
|
||||
ClearTitles(Bool1) = CLEAR_TITLES,
|
||||
Commands(Commands) = COMMANDS,
|
||||
RecipeBookAdd(super::recipes::RecipeBookAdd) = RECIPE_BOOK_ADD,
|
||||
RecipeBookRemove(super::recipes::RecipeBookRemove) = RECIPE_BOOK_REMOVE,
|
||||
RecipeBookSettings(super::recipes::RecipeBookSettings) = RECIPE_BOOK_SETTINGS,
|
||||
PlaceGhostRecipe(super::recipes::PlaceGhostRecipe) = PLACE_GHOST_RECIPE,
|
||||
ContainerClose(ContainerClose) = CONTAINER_CLOSE,
|
||||
ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT,
|
||||
ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA,
|
||||
@@ -1510,6 +1688,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
ChangeGameMode(ChangeGameMode) = CHANGE_GAME_MODE,
|
||||
Chat(Chat) = CHAT,
|
||||
ChatCommand(ChatCommand) = CHAT_COMMAND,
|
||||
PlaceRecipe(super::recipes::PlaceRecipe) = PLACE_RECIPE,
|
||||
ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED,
|
||||
ClientCommand(ClientCommand) = CLIENT_COMMAND,
|
||||
ClientInformation(ClientInformation) = CLIENT_INFORMATION,
|
||||
|
||||
@@ -0,0 +1,607 @@
|
||||
//! The recipe book's packets and the recipe displays they carry
|
||||
//! (`RecipeDisplay`, `SlotDisplay`, `RecipeDisplayEntry`): the 26.3
|
||||
//! `minecraft:recipe_display` and `minecraft:slot_display` types in id order.
|
||||
use crate::{
|
||||
Result,
|
||||
buf::{Codec, Reader, Writer},
|
||||
item::{Stack, Template},
|
||||
};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// `HolderSet<Item>` on the network: a tag by name, or item ids.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum HolderSet {
|
||||
Tag(String),
|
||||
Items(Vec<i32>),
|
||||
}
|
||||
impl HolderSet {
|
||||
pub fn read(r: &mut Reader) -> Result<Self> {
|
||||
let n = r.varint()? - 1;
|
||||
if n == -1 {
|
||||
return Ok(Self::Tag(r.string(32767)?));
|
||||
}
|
||||
let n = usize::try_from(n).map_err(|_| crate::Error::new("negative holder set size"))?;
|
||||
if n > r.remaining() {
|
||||
return Err(crate::Error::new("holder set larger than the packet"));
|
||||
}
|
||||
Ok(Self::Items(
|
||||
(0..n).map(|_| r.varint()).collect::<Result<_>>()?,
|
||||
))
|
||||
}
|
||||
pub fn write(&self, w: &mut Writer) {
|
||||
match self {
|
||||
Self::Tag(name) => {
|
||||
w.varint(0);
|
||||
w.string(name);
|
||||
}
|
||||
Self::Items(ids) => {
|
||||
w.varint(ids.len() as i32 + 1);
|
||||
ids.iter().for_each(|id| w.varint(*id));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trim pattern as `ByteBufCodecs.holder` sends it: a registry id, or
|
||||
/// the pattern itself.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TrimPattern {
|
||||
Id(i32),
|
||||
Direct {
|
||||
asset: String,
|
||||
description: Tag,
|
||||
decal: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// `SlotDisplay`: what a recipe book slot shows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SlotDisplay {
|
||||
Empty,
|
||||
AnyFuel,
|
||||
WithAnyPotion(Box<SlotDisplay>),
|
||||
/// The source, kept to the stacks with this data component type.
|
||||
OnlyWithComponent(Box<SlotDisplay>, i32),
|
||||
Item(i32),
|
||||
ItemStack(Stack),
|
||||
Tag(HolderSet),
|
||||
Dyed {
|
||||
dye: Box<SlotDisplay>,
|
||||
target: Box<SlotDisplay>,
|
||||
},
|
||||
SmithingTrim {
|
||||
base: Box<SlotDisplay>,
|
||||
material: Box<SlotDisplay>,
|
||||
pattern: TrimPattern,
|
||||
},
|
||||
WithRemainder {
|
||||
input: Box<SlotDisplay>,
|
||||
remainder: Box<SlotDisplay>,
|
||||
},
|
||||
Composite(Vec<SlotDisplay>),
|
||||
}
|
||||
|
||||
/// How deep slot displays may nest (composites of composites…).
|
||||
const MAX_DEPTH: u32 = 32;
|
||||
|
||||
impl SlotDisplay {
|
||||
pub fn read(r: &mut Reader) -> Result<Self> {
|
||||
Self::read_at(r, 0)
|
||||
}
|
||||
fn read_at(r: &mut Reader, depth: u32) -> Result<Self> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(crate::Error::new("slot displays nest too deep"));
|
||||
}
|
||||
let inner = |r: &mut Reader| Self::read_at(r, depth + 1).map(Box::new);
|
||||
Ok(match r.varint()? {
|
||||
0 => Self::Empty,
|
||||
1 => Self::AnyFuel,
|
||||
2 => Self::WithAnyPotion(inner(r)?),
|
||||
3 => {
|
||||
let source = inner(r)?;
|
||||
Self::OnlyWithComponent(source, r.varint()?)
|
||||
}
|
||||
4 => Self::Item(r.varint()?),
|
||||
5 => Self::ItemStack(Template::read(r)?),
|
||||
6 => Self::Tag(HolderSet::read(r)?),
|
||||
7 => Self::Dyed {
|
||||
dye: inner(r)?,
|
||||
target: inner(r)?,
|
||||
},
|
||||
8 => {
|
||||
let base = inner(r)?;
|
||||
let material = inner(r)?;
|
||||
let pattern = match r.varint()? {
|
||||
0 => TrimPattern::Direct {
|
||||
asset: r.string(32767)?,
|
||||
description: r.nbt()?,
|
||||
decal: r.bool()?,
|
||||
},
|
||||
id => TrimPattern::Id(id - 1),
|
||||
};
|
||||
Self::SmithingTrim {
|
||||
base,
|
||||
material,
|
||||
pattern,
|
||||
}
|
||||
}
|
||||
9 => Self::WithRemainder {
|
||||
input: inner(r)?,
|
||||
remainder: inner(r)?,
|
||||
},
|
||||
10 => {
|
||||
let n = r.count(r.remaining())?;
|
||||
let mut out = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
out.push(Self::read_at(r, depth + 1)?);
|
||||
}
|
||||
Self::Composite(out)
|
||||
}
|
||||
id => return Err(crate::Error::new(format!("unknown slot display {id}"))),
|
||||
})
|
||||
}
|
||||
pub fn write(&self, w: &mut Writer) {
|
||||
match self {
|
||||
Self::Empty => w.varint(0),
|
||||
Self::AnyFuel => w.varint(1),
|
||||
Self::WithAnyPotion(d) => {
|
||||
w.varint(2);
|
||||
d.write(w);
|
||||
}
|
||||
Self::OnlyWithComponent(d, component) => {
|
||||
w.varint(3);
|
||||
d.write(w);
|
||||
w.varint(*component);
|
||||
}
|
||||
Self::Item(id) => {
|
||||
w.varint(4);
|
||||
w.varint(*id);
|
||||
}
|
||||
Self::ItemStack(stack) => {
|
||||
w.varint(5);
|
||||
Template::write(stack, w);
|
||||
}
|
||||
Self::Tag(set) => {
|
||||
w.varint(6);
|
||||
set.write(w);
|
||||
}
|
||||
Self::Dyed { dye, target } => {
|
||||
w.varint(7);
|
||||
dye.write(w);
|
||||
target.write(w);
|
||||
}
|
||||
Self::SmithingTrim {
|
||||
base,
|
||||
material,
|
||||
pattern,
|
||||
} => {
|
||||
w.varint(8);
|
||||
base.write(w);
|
||||
material.write(w);
|
||||
match pattern {
|
||||
TrimPattern::Id(id) => w.varint(id + 1),
|
||||
TrimPattern::Direct {
|
||||
asset,
|
||||
description,
|
||||
decal,
|
||||
} => {
|
||||
w.varint(0);
|
||||
w.string(asset);
|
||||
w.nbt(description);
|
||||
w.bool(*decal);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::WithRemainder { input, remainder } => {
|
||||
w.varint(9);
|
||||
input.write(w);
|
||||
remainder.write(w);
|
||||
}
|
||||
Self::Composite(list) => {
|
||||
w.varint(10);
|
||||
w.varint(list.len() as i32);
|
||||
list.iter().for_each(|d| d.write(w));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_list(r: &mut Reader) -> Result<Vec<SlotDisplay>> {
|
||||
let n = r.count(r.remaining())?;
|
||||
let mut out = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
out.push(SlotDisplay::read(r)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn write_list(list: &[SlotDisplay], w: &mut Writer) {
|
||||
w.varint(list.len() as i32);
|
||||
list.iter().for_each(|d| d.write(w));
|
||||
}
|
||||
|
||||
/// `RecipeDisplay`: a recipe as the recipe book draws it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum RecipeDisplay {
|
||||
Shapeless {
|
||||
ingredients: Vec<SlotDisplay>,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
Shaped {
|
||||
width: i32,
|
||||
height: i32,
|
||||
ingredients: Vec<SlotDisplay>,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
Furnace {
|
||||
ingredient: SlotDisplay,
|
||||
fuel: SlotDisplay,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
duration: i32,
|
||||
experience: f32,
|
||||
},
|
||||
Stonecutter {
|
||||
input: SlotDisplay,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
Smithing {
|
||||
template: SlotDisplay,
|
||||
base: SlotDisplay,
|
||||
addition: SlotDisplay,
|
||||
result: SlotDisplay,
|
||||
station: SlotDisplay,
|
||||
},
|
||||
}
|
||||
impl RecipeDisplay {
|
||||
pub fn result(&self) -> &SlotDisplay {
|
||||
match self {
|
||||
Self::Shapeless { result, .. }
|
||||
| Self::Shaped { result, .. }
|
||||
| Self::Furnace { result, .. }
|
||||
| Self::Stonecutter { result, .. }
|
||||
| Self::Smithing { result, .. } => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Codec<RecipeDisplay> for RecipeDisplay {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let slot = SlotDisplay::read;
|
||||
Ok(match r.varint()? {
|
||||
0 => Self::Shapeless {
|
||||
ingredients: read_list(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
},
|
||||
1 => {
|
||||
let (width, height) = (r.varint()?, r.varint()?);
|
||||
let ingredients = read_list(r)?;
|
||||
if i64::from(width) * i64::from(height) != ingredients.len() as i64 {
|
||||
return Err(crate::Error::new("shaped display size mismatch"));
|
||||
}
|
||||
Self::Shaped {
|
||||
width,
|
||||
height,
|
||||
ingredients,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
}
|
||||
}
|
||||
2 => Self::Furnace {
|
||||
ingredient: slot(r)?,
|
||||
fuel: slot(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
duration: r.varint()?,
|
||||
experience: r.f32()?,
|
||||
},
|
||||
3 => Self::Stonecutter {
|
||||
input: slot(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
},
|
||||
4 => Self::Smithing {
|
||||
template: slot(r)?,
|
||||
base: slot(r)?,
|
||||
addition: slot(r)?,
|
||||
result: slot(r)?,
|
||||
station: slot(r)?,
|
||||
},
|
||||
id => return Err(crate::Error::new(format!("unknown recipe display {id}"))),
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
match v {
|
||||
Self::Shapeless {
|
||||
ingredients,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(0);
|
||||
write_list(ingredients, w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
Self::Shaped {
|
||||
width,
|
||||
height,
|
||||
ingredients,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(1);
|
||||
w.varint(*width);
|
||||
w.varint(*height);
|
||||
write_list(ingredients, w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
Self::Furnace {
|
||||
ingredient,
|
||||
fuel,
|
||||
result,
|
||||
station,
|
||||
duration,
|
||||
experience,
|
||||
} => {
|
||||
w.varint(2);
|
||||
ingredient.write(w);
|
||||
fuel.write(w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
w.varint(*duration);
|
||||
w.f32(*experience);
|
||||
}
|
||||
Self::Stonecutter {
|
||||
input,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(3);
|
||||
input.write(w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
Self::Smithing {
|
||||
template,
|
||||
base,
|
||||
addition,
|
||||
result,
|
||||
station,
|
||||
} => {
|
||||
w.varint(4);
|
||||
template.write(w);
|
||||
base.write(w);
|
||||
addition.write(w);
|
||||
result.write(w);
|
||||
station.write(w);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `RecipeDisplayEntry` with `ClientboundRecipeBookAddPacket.Entry`'s flags
|
||||
/// (1 show a notification, 2 highlight as new).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RecipeBookEntry {
|
||||
pub id: i32,
|
||||
pub display: RecipeDisplay,
|
||||
/// The recipe group (0 none, else the group's index + 1).
|
||||
pub group: i32,
|
||||
/// `minecraft:recipe_book_category` id.
|
||||
pub category: i32,
|
||||
/// The ingredients the "craftable" filter checks, if the recipe has any.
|
||||
pub requirements: Option<Vec<HolderSet>>,
|
||||
pub flags: i8,
|
||||
}
|
||||
|
||||
/// ClientboundRecipeBookAddPacket: the entries, and whether they replace the
|
||||
/// client's book.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RecipeBookAdd {
|
||||
pub entries: Vec<RecipeBookEntry>,
|
||||
pub replace: bool,
|
||||
}
|
||||
impl RecipeBookEntry {
|
||||
pub fn read(r: &mut Reader) -> Result<Self> {
|
||||
let id = r.varint()?;
|
||||
let display = RecipeDisplay::read(r)?;
|
||||
let group = r.varint()?;
|
||||
let category = r.varint()?;
|
||||
let requirements = if r.bool()? {
|
||||
let k = r.count(r.remaining())?;
|
||||
let mut list = Vec::with_capacity(k.min(64));
|
||||
for _ in 0..k {
|
||||
list.push(HolderSet::read(r)?);
|
||||
}
|
||||
Some(list)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Self {
|
||||
id,
|
||||
display,
|
||||
group,
|
||||
category,
|
||||
requirements,
|
||||
flags: r.i8()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Codec<RecipeBookAdd> for RecipeBookAdd {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let n = r.count(r.remaining())?;
|
||||
let mut entries = Vec::with_capacity(n.min(4096));
|
||||
for _ in 0..n {
|
||||
entries.push(RecipeBookEntry::read(r)?);
|
||||
}
|
||||
Ok(Self {
|
||||
entries,
|
||||
replace: r.bool()?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.entries.len() as i32);
|
||||
for e in &v.entries {
|
||||
w.varint(e.id);
|
||||
RecipeDisplay::write(&e.display, w);
|
||||
w.varint(e.group);
|
||||
w.varint(e.category);
|
||||
w.bool(e.requirements.is_some());
|
||||
if let Some(list) = &e.requirements {
|
||||
w.varint(list.len() as i32);
|
||||
list.iter().for_each(|s| s.write(w));
|
||||
}
|
||||
w.i8(e.flags);
|
||||
}
|
||||
w.bool(v.replace);
|
||||
}
|
||||
}
|
||||
|
||||
/// ClientboundRecipeBookRemovePacket: the display ids.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RecipeBookRemove {
|
||||
pub ids: Vec<i32>,
|
||||
}
|
||||
impl Codec<RecipeBookRemove> for RecipeBookRemove {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let n = r.count(r.remaining())?;
|
||||
Ok(Self {
|
||||
ids: (0..n).map(|_| r.varint()).collect::<Result<_>>()?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.ids.len() as i32);
|
||||
v.ids.iter().for_each(|id| w.varint(*id));
|
||||
}
|
||||
}
|
||||
|
||||
/// RecipeBookSettings: each book's (open, filtering), in `RecipeBookType`
|
||||
/// order (crafting, furnace, blast furnace, smoker).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RecipeBookSettings {
|
||||
pub books: [(bool, bool); 4],
|
||||
}
|
||||
impl Codec<RecipeBookSettings> for RecipeBookSettings {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
let mut books = [(false, false); 4];
|
||||
for b in &mut books {
|
||||
*b = (r.bool()?, r.bool()?);
|
||||
}
|
||||
Ok(Self { books })
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
for (open, filtering) in v.books {
|
||||
w.bool(open);
|
||||
w.bool(filtering);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ClientboundPlaceGhostRecipePacket: the recipe to show faded in a menu
|
||||
/// whose items were missing.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PlaceGhostRecipe {
|
||||
pub container: i32,
|
||||
pub display: RecipeDisplay,
|
||||
}
|
||||
impl Codec<PlaceGhostRecipe> for PlaceGhostRecipe {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
Ok(Self {
|
||||
container: r.varint()?,
|
||||
display: RecipeDisplay::read(r)?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.container);
|
||||
RecipeDisplay::write(&v.display, w);
|
||||
}
|
||||
}
|
||||
|
||||
/// ServerboundPlaceRecipePacket: place the recipe with this display id in
|
||||
/// the open menu, as many times as possible when `use_max` (shift).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PlaceRecipe {
|
||||
pub container: i32,
|
||||
pub recipe: i32,
|
||||
pub use_max: bool,
|
||||
}
|
||||
impl Codec<PlaceRecipe> for PlaceRecipe {
|
||||
fn read(r: &mut Reader) -> Result<Self> {
|
||||
Ok(Self {
|
||||
container: r.varint()?,
|
||||
recipe: r.varint()?,
|
||||
use_max: r.bool()?,
|
||||
})
|
||||
}
|
||||
fn write(v: &Self, w: &mut Writer) {
|
||||
w.varint(v.container);
|
||||
w.varint(v.recipe);
|
||||
w.bool(v.use_max);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn book_entries_round_trip() {
|
||||
let add = RecipeBookAdd {
|
||||
entries: vec![
|
||||
RecipeBookEntry {
|
||||
id: 7,
|
||||
display: RecipeDisplay::Shaped {
|
||||
width: 2,
|
||||
height: 1,
|
||||
ingredients: vec![
|
||||
SlotDisplay::Tag(HolderSet::Tag("minecraft:planks".into())),
|
||||
SlotDisplay::Empty,
|
||||
],
|
||||
result: SlotDisplay::ItemStack(Stack::new(12, 4)),
|
||||
station: SlotDisplay::Item(300),
|
||||
},
|
||||
group: 3,
|
||||
category: 3,
|
||||
requirements: Some(vec![HolderSet::Items(vec![1, 2])]),
|
||||
flags: 3,
|
||||
},
|
||||
RecipeBookEntry {
|
||||
id: 8,
|
||||
display: RecipeDisplay::Smithing {
|
||||
template: SlotDisplay::Composite(vec![SlotDisplay::Item(1)]),
|
||||
base: SlotDisplay::WithRemainder {
|
||||
input: Box::new(SlotDisplay::AnyFuel),
|
||||
remainder: Box::new(SlotDisplay::Item(2)),
|
||||
},
|
||||
addition: SlotDisplay::OnlyWithComponent(
|
||||
Box::new(SlotDisplay::WithAnyPotion(Box::new(SlotDisplay::Item(3)))),
|
||||
9,
|
||||
),
|
||||
result: SlotDisplay::SmithingTrim {
|
||||
base: Box::new(SlotDisplay::Item(4)),
|
||||
material: Box::new(SlotDisplay::Dyed {
|
||||
dye: Box::new(SlotDisplay::Item(5)),
|
||||
target: Box::new(SlotDisplay::Item(6)),
|
||||
}),
|
||||
pattern: TrimPattern::Id(2),
|
||||
},
|
||||
station: SlotDisplay::Item(7),
|
||||
},
|
||||
group: 0,
|
||||
category: 11,
|
||||
requirements: None,
|
||||
flags: 0,
|
||||
},
|
||||
],
|
||||
replace: true,
|
||||
};
|
||||
let mut w = Writer::new();
|
||||
RecipeBookAdd::write(&add, &mut w);
|
||||
let mut r = Reader::new(&w.data);
|
||||
assert_eq!(RecipeBookAdd::read(&mut r).unwrap(), add);
|
||||
assert_eq!(r.remaining(), 0);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -25,7 +25,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi
|
||||
| Performance | battery mode, worker threads, upload budget per frame | `horizon-graphics.txt` |
|
||||
| Overlay | performance overlay: FPS, frame/CPU/GPU times, frame-time graph | `horizon-graphics.txt` |
|
||||
|
||||
`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels.
|
||||
`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. VSync on always waits for the display (Fifo), in a window and in fullscreen, as in vanilla; the present mode setting chooses how frames are shown only while VSync is off. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels.
|
||||
|
||||
**Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are.
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ class WorldInputCaptureTests(unittest.TestCase):
|
||||
fixture = r'''
|
||||
use std::cell::Cell;
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Screen { Playing, Paused, Inventory }
|
||||
enum Screen { Playing, Paused, Inventory, Chat }
|
||||
enum CursorGrabMode { Locked, Confined, None }
|
||||
#[derive(Default)]
|
||||
struct Window { grabs: Cell<u32>, visible: Cell<bool>, fail: bool }
|
||||
@@ -63,17 +63,17 @@ impl Window {
|
||||
#[derive(Default)]
|
||||
struct Mouse { ignore_first: bool }
|
||||
impl Mouse { fn set_ignore_first_move(&mut self) { self.ignore_first = true; } }
|
||||
struct Remote { chat_input: Option<()> }
|
||||
struct Remote;
|
||||
struct Game {
|
||||
focused: bool, agent_pointer: bool, window: Option<Window>, mouse: Mouse,
|
||||
captured: bool, title: Option<()>, screen: Screen, remote: Option<Remote>,
|
||||
mining: bool,
|
||||
mining: bool, lan_acting: Option<u32>,
|
||||
}
|
||||
impl Default for Game {
|
||||
fn default() -> Self {
|
||||
Self { focused: true, agent_pointer: false, window: Some(Window::default()),
|
||||
mouse: Mouse::default(), captured: false, title: None,
|
||||
screen: Screen::Playing, remote: None, mining: false }
|
||||
screen: Screen::Playing, remote: None, mining: false, lan_acting: None }
|
||||
}
|
||||
}
|
||||
impl Game {
|
||||
@@ -84,7 +84,7 @@ fn main() {
|
||||
// New and existing worlds, returning to title, and reopening a world.
|
||||
for remote in [false, true] {
|
||||
let mut game = Game::default();
|
||||
if remote { game.remote = Some(Remote { chat_input: None }); }
|
||||
if remote { game.remote = Some(Remote); }
|
||||
for _ in 0..3 {
|
||||
game.title = Some(());
|
||||
game.capture(false);
|
||||
@@ -128,11 +128,14 @@ fn main() {
|
||||
assert!(game.captured);
|
||||
}
|
||||
let mut game = Game::default();
|
||||
game.remote = Some(Remote { chat_input: Some(()) });
|
||||
// On a server the chat is ChatScreen (#708): loading never grabs over it.
|
||||
game.remote = Some(Remote);
|
||||
game.screen = Screen::Chat;
|
||||
game.capture_loaded_world();
|
||||
assert!(!game.captured);
|
||||
assert_eq!(game.window.as_ref().unwrap().grabs.get(), 0);
|
||||
game.remote = None;
|
||||
game.screen = Screen::Playing;
|
||||
game.window.as_mut().unwrap().fail = true;
|
||||
game.capture_loaded_world();
|
||||
assert!(!game.captured);
|
||||
|
||||
+216
-7
@@ -10,8 +10,10 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- armour: each side draws the other player in that player's own armour;
|
||||
- nametags: each side draws the other player's name above them;
|
||||
- chest: a chest the guest opens opens on the guest's screen, its lid opens on both sides and
|
||||
closes on both when the guest closes it;
|
||||
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table;
|
||||
closes on both when the guest closes it; the host keeps playing with its mouse look (#687);
|
||||
- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table, which
|
||||
leaves the host's screen and mouse look alone;
|
||||
- sign: a sign the guest places doesn't open a sign editor on the host;
|
||||
- damage: a guest in survival takes fall damage;
|
||||
- mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them;
|
||||
- hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes,
|
||||
@@ -19,7 +21,15 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing;
|
||||
- containers: the guest's ender chest holds the guest's items, not the host's, and a double chest
|
||||
opens as 9x6 with the right half first;
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers.
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers;
|
||||
- effects: a beacon's power reaches every player in range, the host and the guest;
|
||||
- portals: (--server-thread) the server holds a level per dimension: the guest goes to the Nether
|
||||
through a portal while the host stays, then the host goes to the End while the guest is in
|
||||
the Nether, and both come back.
|
||||
- commands: the guest's chat completes commands and their arguments over the server's command
|
||||
tree (Tab), and runs what it completed;
|
||||
- recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it
|
||||
places a log in the inventory's crafting grid (the server places it).
|
||||
|
||||
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
|
||||
both sides go to --out (host-*.png, guest-*.png).
|
||||
@@ -27,6 +37,7 @@ both sides go to --out (host-*.png, guest-*.png).
|
||||
python3 tools/lan_e2e.py # build with the fast profile, run every check
|
||||
python3 tools/lan_e2e.py --bin-dir target/fast # prebuilt binaries
|
||||
python3 tools/lan_e2e.py --check chest --check tab
|
||||
python3 tools/lan_e2e.py --server-thread --check portals # the host's world on its server thread
|
||||
|
||||
Needs the prepared resources in .local/horizon-client and, on Linux, vscreen (the desktop); on
|
||||
macOS both games render offscreen. Games started here have no audio (HORIZON_NO_AUDIO=1).
|
||||
@@ -48,7 +59,9 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials']
|
||||
# The host plays single player on its server thread (--server-thread).
|
||||
SERVER_THREAD = False
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'effects', 'portals']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -180,6 +193,19 @@ def check_nametags(host, guest, out):
|
||||
return {'host': h, 'guest': g}
|
||||
|
||||
|
||||
def grab(game):
|
||||
"""Mouse look on, as a player's grabbed pointer: an agent's mouse-move stands in for it."""
|
||||
game.raw('mouse-move', 1, 0)
|
||||
game.raw('mouse-move', -1, 0)
|
||||
|
||||
|
||||
def host_unaffected(host, what):
|
||||
"""What a guest opens is the guest's: the host keeps its world on screen and its mouse look (#687)."""
|
||||
state = host('state')
|
||||
assert state.get('screen') == 'playing', f'{what} opened the {state.get("screen")} screen on the host'
|
||||
assert state.get('pointer_grabbed'), f"{what} released the host's pointer"
|
||||
|
||||
|
||||
def lid(game, pos):
|
||||
return game.raw('block', *pos).get('lid', 0.0)
|
||||
|
||||
@@ -189,9 +215,11 @@ def check_chest(host, guest, out):
|
||||
chest = (x, y, z + 2)
|
||||
guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest')
|
||||
guest.wait(10)
|
||||
grab(host)
|
||||
guest.raw('interact', *chest)
|
||||
screen = guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
guest.wait(20)
|
||||
host_unaffected(host, "the guest's chest")
|
||||
opened = {'guest': lid(guest, chest), 'host': lid(host, chest)}
|
||||
host.raw('look-at', chest[0] + 0.5, chest[1] + 0.5, chest[2] + 0.5)
|
||||
host.wait(2)
|
||||
@@ -231,8 +259,10 @@ def check_crafting(host, guest, out):
|
||||
table = (x, y, z - 2)
|
||||
guest('command', command=f'setblock {table[0]} {table[1]} {table[2]} minecraft:crafting_table')
|
||||
guest.wait(10)
|
||||
grab(host)
|
||||
guest.raw('interact', *table)
|
||||
guest.raw('wait-for', 'screen', 'inventory', '--timeout', 10)
|
||||
host_unaffected(host, "the guest's crafting table")
|
||||
size = guest('screen').get('craft_size')
|
||||
assert size == 3, f'the crafting table opened a {size}x{size} grid'
|
||||
# Two planks one above the other in the 3x3 grid: four sticks.
|
||||
@@ -252,6 +282,104 @@ def check_crafting(host, guest, out):
|
||||
return {'planks': planks, 'table': counts}
|
||||
|
||||
|
||||
def check_sign(host, guest, out):
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
spot = (x + 2, y, z)
|
||||
guest('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone')
|
||||
guest('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air')
|
||||
guest('command', command='give @s minecraft:oak_sign 1')
|
||||
guest.wait(10)
|
||||
grab(host)
|
||||
guest.raw('place', *spot, '--item', 'minecraft:oak_sign')
|
||||
guest.wait(20)
|
||||
placed = host.raw('block', *spot).get('block')
|
||||
host.shot(out, 'sign')
|
||||
assert placed and 'sign' in placed, f'the guest placed {placed}'
|
||||
host_unaffected(host, "the guest's sign")
|
||||
return placed
|
||||
|
||||
|
||||
def effect_ids(game):
|
||||
return [e.get('id', '').removeprefix('minecraft:') for e in game('state')['player'].get('effects', [])]
|
||||
|
||||
|
||||
def check_effects(host, guest, out):
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
bx, by, bz = x - 3, y, z - 3
|
||||
host('command', command=f'fill {bx - 1} {by - 1} {bz - 1} {bx + 1} {by - 1} {bz + 1} minecraft:iron_block')
|
||||
host('command', command=f'setblock {bx} {by} {bz} minecraft:beacon{{primary_effect:"minecraft:speed"}}')
|
||||
# BeaconBlockEntity.tick applies its powers every 80 ticks, once the beam has reached the sky.
|
||||
seen = {}
|
||||
for _ in range(15):
|
||||
host.wait(20)
|
||||
seen = {'host': effect_ids(host), 'guest': effect_ids(guest)}
|
||||
if all('speed' in v for v in seen.values()):
|
||||
break
|
||||
host.shot(out, 'effects')
|
||||
guest.shot(out, 'effects')
|
||||
assert 'speed' in seen['host'] and 'speed' in seen['guest'], f'beacon effects: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def wait_dimension(game, dimension, ticks):
|
||||
"""Wait up to `ticks` for the game to be in `dimension` with its world loaded around it."""
|
||||
for _ in range(ticks // 20):
|
||||
state = game('state')
|
||||
if state.get('dimension') == dimension and state.get('player'):
|
||||
return state
|
||||
game.wait(20)
|
||||
return game('state')
|
||||
|
||||
|
||||
def nether_portal(game, x, y, z):
|
||||
"""A lit portal along x, two blocks wide and three tall, its inside starting at x y z."""
|
||||
game('command', command=f'fill {x - 1} {y - 1} {z} {x + 2} {y + 3} {z} minecraft:obsidian')
|
||||
game('command', command=f'fill {x} {y} {z} {x + 1} {y + 2} {z} minecraft:nether_portal[axis=x]')
|
||||
|
||||
|
||||
def check_portals(host, guest, out):
|
||||
if not SERVER_THREAD:
|
||||
return 'skipped (needs --server-thread)'
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
nether_portal(guest, x, y, z + 3)
|
||||
guest.wait(5)
|
||||
guest('command', command=f'tp @s {x + 0.5} {y} {z + 3.5}')
|
||||
# players_nether_portal_default_delay: 80 ticks in survival.
|
||||
there = wait_dimension(guest, 'minecraft:the_nether', 600)
|
||||
guest.wait(40)
|
||||
guest.shot(out, 'portals-nether')
|
||||
host_dim = host('state').get('dimension')
|
||||
assert there.get('dimension') == 'minecraft:the_nether', f'the guest is in {there.get("dimension")}'
|
||||
assert host_dim == 'minecraft:overworld', f'the host went to {host_dim} with the guest'
|
||||
arrived = [int(v // 1) for v in pos_of(guest)]
|
||||
below = guest.raw('block', arrived[0], arrived[1] - 1, arrived[2])
|
||||
assert below.get('loaded') and below.get('block') != 'minecraft:air', f'under the guest in the Nether: {below}'
|
||||
# The host takes an End portal while the guest is in the Nether: three levels at once.
|
||||
hx, hy, hz = (int(v // 1) for v in pos_of(host))
|
||||
host('command', command=f'setblock {hx} {hy} {hz} minecraft:end_portal')
|
||||
end = wait_dimension(host, 'minecraft:the_end', 600)
|
||||
host.wait(40)
|
||||
host.shot(out, 'portals-end')
|
||||
guest_dim = guest('state').get('dimension')
|
||||
assert end.get('dimension') == 'minecraft:the_end', f'the host is in {end.get("dimension")}'
|
||||
assert guest_dim == 'minecraft:the_nether', f'the guest left the Nether for {guest_dim}'
|
||||
# Both come back: the host through an exit portal, the guest out of its portal and in again.
|
||||
ex, ey, ez = (int(v // 1) for v in pos_of(host))
|
||||
host('command', command=f'setblock {ex + 2} {ey} {ez} minecraft:end_portal')
|
||||
host('command', command=f'tp @s {ex + 2.5} {ey} {ez + 0.5}')
|
||||
guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] - 2.5}')
|
||||
guest.wait(30)
|
||||
guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] + 0.5}')
|
||||
home = wait_dimension(host, 'minecraft:overworld', 600)
|
||||
back = wait_dimension(guest, 'minecraft:overworld', 600)
|
||||
guest.wait(40)
|
||||
host.shot(out, 'portals-back')
|
||||
guest.shot(out, 'portals-back')
|
||||
assert home.get('dimension') == 'minecraft:overworld', f'the host stayed in {home.get("dimension")}'
|
||||
assert back.get('dimension') == 'minecraft:overworld', f'the guest stayed in {back.get("dimension")}'
|
||||
return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'back': pos_of(guest)}
|
||||
|
||||
|
||||
def check_damage(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest.wait(10)
|
||||
@@ -475,6 +603,80 @@ def check_feedback(host, guest, out):
|
||||
return chat
|
||||
|
||||
|
||||
def chat_input(game):
|
||||
return game('screen').get('chat_input')
|
||||
|
||||
|
||||
def complete(guest, text):
|
||||
"""Opens the chat on `/`, types `text` and presses Tab: the input after it."""
|
||||
guest.raw('key', 'slash', 'tap')
|
||||
guest.wait(3)
|
||||
guest.raw('type', text)
|
||||
guest.wait(2)
|
||||
guest.raw('key', 'tab', 'tap')
|
||||
guest.wait(2)
|
||||
return chat_input(guest)
|
||||
|
||||
|
||||
def check_commands(host, guest, out):
|
||||
literal = complete(guest, 'gamem')
|
||||
# The first Escape hides the suggestions, the next closes the chat.
|
||||
for _ in range(3):
|
||||
if guest('screen').get('screen') != 'chat':
|
||||
break
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(3)
|
||||
argument = complete(guest, 'gamemode cr')
|
||||
guest.shot(out, 'commands')
|
||||
guest.raw('key', 'enter', 'tap')
|
||||
guest.wait(20)
|
||||
mode = guest('state').get('gamemode')
|
||||
screen = guest('state').get('screen')
|
||||
guest('command', command='gamemode survival')
|
||||
guest.wait(10)
|
||||
assert literal == '/gamemode', f'Tab after /gamem: {literal!r}'
|
||||
assert argument == '/gamemode creative', f'Tab after /gamemode cr: {argument!r}'
|
||||
assert mode == 'creative', f'the completed command did not run: {mode}'
|
||||
assert screen in (None, 'playing'), f'the chat did not close: {screen}'
|
||||
return {'literal': literal, 'argument': argument, 'mode': mode}
|
||||
|
||||
|
||||
def centre(rect):
|
||||
x, y, w, h = rect
|
||||
return x + w / 2, y + h / 2
|
||||
|
||||
|
||||
def grid_items(game):
|
||||
slots = game('screen').get('slots') or []
|
||||
return {s['slot']: s.get('item') for s in slots if 100 <= s['slot'] < 109 and s.get('item')}
|
||||
|
||||
|
||||
def check_recipes(host, guest, out):
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='give @s minecraft:oak_log 4')
|
||||
guest.wait(40)
|
||||
guest.raw('key', 'e', 'tap')
|
||||
guest.wait(5)
|
||||
try:
|
||||
book = guest('screen').get('recipe_book')
|
||||
assert book, 'the guest\'s inventory has no recipe book'
|
||||
if len(book['targets']) == 1:
|
||||
guest.raw('click-at', *centre(book['targets'][0]))
|
||||
guest.wait(5)
|
||||
book = guest('screen').get('recipe_book')
|
||||
known = book['known']
|
||||
assert known > 0, f'the guest\'s book is empty: {book}'
|
||||
guest.raw('click-at', *centre(book['targets'][1]))
|
||||
guest.wait(10)
|
||||
grid = grid_items(guest)
|
||||
guest.shot(out, 'recipes')
|
||||
finally:
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(5)
|
||||
assert any('oak_log' in str(item) for item in grid.values()), f'nothing placed in the grid: {grid}'
|
||||
return {'known': known, 'grid': grid}
|
||||
|
||||
|
||||
def png_rows(path):
|
||||
"""The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel."""
|
||||
data = Path(path).read_bytes()
|
||||
@@ -623,14 +825,18 @@ def check_trials(host, guest, out):
|
||||
|
||||
|
||||
CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags,
|
||||
'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage,
|
||||
'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage,
|
||||
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp,
|
||||
'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials,
|
||||
'walls': check_walls}
|
||||
'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands,
|
||||
'recipes': check_recipes,
|
||||
'trials': check_trials,
|
||||
'walls': check_walls, 'effects': check_effects, 'portals': check_portals}
|
||||
|
||||
|
||||
def run(ctl, out, resources, checks):
|
||||
host, guest = Game('host', ctl, resources), Game('guest', ctl, resources)
|
||||
if SERVER_THREAD:
|
||||
host.d.env['HORIZON_SERVER_THREAD'] = '1'
|
||||
results = {}
|
||||
try:
|
||||
host('launch', wait=False, offscreen=sys.platform == 'darwin')
|
||||
@@ -676,7 +882,10 @@ def main():
|
||||
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
|
||||
parser.add_argument('--check', action='append', choices=CHECKS, help='run only these checks (repeatable)')
|
||||
parser.add_argument('--out', default=str(ROOT / '.local/lan-e2e'), help='screenshots and game logs go here')
|
||||
parser.add_argument('--server-thread', action='store_true', help="the host's world runs on its server thread")
|
||||
args = parser.parse_args()
|
||||
global SERVER_THREAD
|
||||
SERVER_THREAD = args.server_thread
|
||||
if args.bin_dir:
|
||||
bins = Path(args.bin_dir).resolve()
|
||||
else:
|
||||
|
||||
Reference in New Issue
Block a user