Merge main (lan_e2e.py and the probe list keep both checks and probes)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+9
@@ -1368,6 +1368,7 @@ dependencies = [
|
||||
"horizon-core",
|
||||
"horizon-dualsense",
|
||||
"horizon-friends",
|
||||
"horizon-hdr",
|
||||
"horizon-mods",
|
||||
"horizon-protocol",
|
||||
"horizon-server-files",
|
||||
@@ -1426,6 +1427,14 @@ dependencies = [
|
||||
"spake2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-hdr"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-mod-sdk"
|
||||
version = "0.1.0"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -12,6 +12,7 @@ horizon-assets = { path = "../horizon-assets" }
|
||||
horizon-core = { path = "../horizon-core" }
|
||||
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
|
||||
horizon-threads = { path = "../horizon-threads" }
|
||||
horizon-hdr = { path = "../horizon-hdr" }
|
||||
horizon-world = { path = "../horizon-world" }
|
||||
horizon-protocol = { path = "../horizon-protocol" }
|
||||
# server.properties, eula.txt and the user lists, shared with horizon-server.
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
use horizon_client::{
|
||||
Result,
|
||||
cushion::{self, World},
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, BufWriter, Write},
|
||||
};
|
||||
|
||||
struct Cell {
|
||||
outline: VoxelShape,
|
||||
collision: VoxelShape,
|
||||
suffocating: bool,
|
||||
}
|
||||
struct Fixture(HashMap<[i32; 3], Cell>);
|
||||
impl World for Fixture {
|
||||
fn outline_bounds(&self, p: [i32; 3]) -> Option<Aabb> {
|
||||
self.0
|
||||
.get(&p)?
|
||||
.outline
|
||||
.bounds()
|
||||
.map(|b| b.move_by(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64)))
|
||||
}
|
||||
fn collision_shapes(&self, _: Aabb) -> Vec<VoxelShape> {
|
||||
self.0
|
||||
.iter()
|
||||
.map(|(p, c)| {
|
||||
c.collision
|
||||
.moved(Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn suffocating(&self, p: [i32; 3]) -> bool {
|
||||
self.0.get(&p).is_some_and(|c| c.suffocating)
|
||||
}
|
||||
}
|
||||
fn shape(value: &Value) -> Result<VoxelShape> {
|
||||
let mut shape = VoxelShape::empty();
|
||||
for b in value.as_array().unwrap() {
|
||||
let f = |i: usize| b[i].as_f64().unwrap();
|
||||
shape = shape.join(
|
||||
&VoxelShape::from_box(Aabb::new(
|
||||
Vec3::new(f(0), f(1), f(2)),
|
||||
Vec3::new(f(3), f(4), f(5)),
|
||||
))?,
|
||||
ShapeOp::OR,
|
||||
)?;
|
||||
}
|
||||
Ok(shape)
|
||||
}
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<_> = crate::args().collect();
|
||||
let mut out = BufWriter::new(File::create(&args[2])?);
|
||||
for line in BufReader::new(File::open(&args[1])?).lines() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
let mut world = Fixture(HashMap::new());
|
||||
for c in row["cells"].as_array().unwrap() {
|
||||
let p = std::array::from_fn(|i| c[i].as_i64().unwrap() as i32);
|
||||
world.0.insert(
|
||||
p,
|
||||
Cell {
|
||||
outline: shape(&c[3])?,
|
||||
collision: shape(&c[4])?,
|
||||
suffocating: c[5].as_bool().unwrap(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let p = &row["pos"];
|
||||
let (x, y, z) = (
|
||||
p[0].as_f64().unwrap(),
|
||||
p[1].as_f64().unwrap(),
|
||||
p[2].as_f64().unwrap(),
|
||||
);
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(x - 0.5, y, z - 0.5),
|
||||
Vec3::new(x + 0.5, y + 0.25, z + 0.5),
|
||||
);
|
||||
writeln!(
|
||||
out,
|
||||
"{} {}",
|
||||
cushion::can_place(&world, bounds),
|
||||
cushion::survives(&world, bounds)
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -29,6 +29,7 @@ mod command_parse_fixture;
|
||||
mod container_screen_probe;
|
||||
mod creative_mining_probe;
|
||||
mod creative_search_fixture;
|
||||
mod cushion_placement_probe;
|
||||
mod emitter_particles_probe;
|
||||
mod enchanting_fixture;
|
||||
mod entity_anim_fixture;
|
||||
@@ -109,6 +110,7 @@ probes! {
|
||||
breaking_fixture,
|
||||
camera_probe,
|
||||
creative_mining_probe,
|
||||
cushion_placement_probe,
|
||||
cauldron_fixture,
|
||||
chat_screen_fixture,
|
||||
cloud_fixture,
|
||||
|
||||
@@ -7,7 +7,7 @@ use horizon_client::{
|
||||
biome::{BiomeInfo, Biomes, GrassModifier},
|
||||
blocks::BlockFacts,
|
||||
chunk::{Chunk, Light, MIN_Y, index},
|
||||
mesher::{MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
|
||||
mesher::{EMISSION_BITS, MeshTables, Mesher, OPAQUE_LAYER, TerrainVertex},
|
||||
models,
|
||||
};
|
||||
use horizon_core::biome::BiomeZoom;
|
||||
@@ -161,7 +161,15 @@ fn scene(
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let ([x, y, z], [u, w]) = (v.pos, v.uv());
|
||||
json!([x, y, z, u, w, argb(v.color), light_coords(v.light)])
|
||||
json!([
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
u,
|
||||
w,
|
||||
argb(v.color | EMISSION_BITS),
|
||||
light_coords(v.light)
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices}));
|
||||
|
||||
@@ -664,7 +664,9 @@ pub fn canonical(tag: &Tag) -> Option<Tag> {
|
||||
}
|
||||
"minecraft:trial_spawner" => {
|
||||
// `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional
|
||||
// and defaulted by vanilla; they are kept as loaded.
|
||||
// and defaulted by vanilla; they are kept as loaded. No `spawn_data` is
|
||||
// added: an absent one loads as Optional.empty and is not stored, and
|
||||
// an empty entity would keep the spawner from ever picking a mob.
|
||||
if let Tag::Compound(c) = tag {
|
||||
for (k, v) in c {
|
||||
let key = k.to_string_lossy();
|
||||
@@ -676,12 +678,6 @@ pub fn canonical(tag: &Tag) -> Option<Tag> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !f.out.contains_key(&"spawn_data".into()) {
|
||||
f.put(
|
||||
"spawn_data",
|
||||
Tag::compound([("entity", Tag::Compound(Compound::new()))]),
|
||||
);
|
||||
}
|
||||
}
|
||||
"minecraft:vault" => {
|
||||
// `VaultConfig.DEFAULT` (when the config is absent): the trial key and the
|
||||
@@ -827,6 +823,21 @@ mod tests {
|
||||
canonical(&snbt(s)).expect("known type")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trial_spawner_without_spawn_data_saves_none() {
|
||||
let fresh = canon(
|
||||
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#,
|
||||
);
|
||||
assert_eq!(fresh.get("spawn_data"), None);
|
||||
let picked = canon(
|
||||
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#,
|
||||
);
|
||||
assert_eq!(
|
||||
picked.get("spawn_data"),
|
||||
Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_type_has_defaults() {
|
||||
for id in TYPES.iter().chain(NEWEST.iter()) {
|
||||
|
||||
@@ -346,6 +346,11 @@ mod tests {
|
||||
assert_eq!(filter_text(s, true), "abc\nde\u{80}");
|
||||
assert_eq!(strip_formatting("§aRed§r §zx§"), "Red §zx§");
|
||||
assert_eq!(helper_clipboard_contents("§lone\r\ntwo"), "one\ntwo");
|
||||
// TextFieldHelper.getClipboardContents runs before insertText's filter.
|
||||
assert_eq!(
|
||||
filter_text(&helper_clipboard_contents("§aHello"), false),
|
||||
"Hello"
|
||||
);
|
||||
}
|
||||
|
||||
struct Field {
|
||||
|
||||
@@ -94,9 +94,66 @@ pub enum BlockEntity {
|
||||
Beehive(Box<crate::beehive::Beehive>),
|
||||
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
|
||||
CommandBlock(Box<crate::command_block::CommandBlock>),
|
||||
/// `CampfireBlockEntity` of campfires and soul campfires.
|
||||
Campfire(Box<Campfire>),
|
||||
/// `SkullBlockEntity` of every skull and head block.
|
||||
Skull(Skull),
|
||||
}
|
||||
/// `CampfireBlockEntity`: four cooking slots, each with its
|
||||
/// `cookingProgress` and `cookingTime` (the recipe's).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Campfire {
|
||||
pub items: [Option<ItemStack>; 4],
|
||||
pub progress: [i32; 4],
|
||||
pub total: [i32; 4],
|
||||
}
|
||||
impl Campfire {
|
||||
/// `placeFood`'s slot: the first empty one, given the item's
|
||||
/// `campfire_cooking` time; it takes one item of `held`.
|
||||
pub fn place_food(&mut self, held: &mut ItemStack, cooking_time: i32) -> bool {
|
||||
let Some(slot) = self.items.iter().position(Option::is_none) else {
|
||||
return false;
|
||||
};
|
||||
self.total[slot] = cooking_time;
|
||||
self.progress[slot] = 0;
|
||||
self.items[slot] = Some(ItemStack {
|
||||
count: 1,
|
||||
..held.clone()
|
||||
});
|
||||
held.count = held.count.saturating_sub(1);
|
||||
true
|
||||
}
|
||||
/// `cookTick` (lit): each item's progress rises by one; the slots whose
|
||||
/// progress reached their cooking time give up their item (the caller
|
||||
/// drops its result).
|
||||
pub fn cook_tick(&mut self) -> Vec<(usize, ItemStack)> {
|
||||
let mut done = Vec::new();
|
||||
for i in 0..4 {
|
||||
if self.items[i].is_none() {
|
||||
continue;
|
||||
}
|
||||
self.progress[i] += 1;
|
||||
if self.progress[i] >= self.total[i]
|
||||
&& let Some(item) = self.items[i].take()
|
||||
{
|
||||
done.push((i, item));
|
||||
}
|
||||
}
|
||||
done
|
||||
}
|
||||
/// `cooldownTick` (unlit): the progress falls by two, no lower than 0.
|
||||
/// Whether anything changed (`setChanged`).
|
||||
pub fn cooldown_tick(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
for i in 0..4 {
|
||||
if self.progress[i] > 0 {
|
||||
changed = true;
|
||||
self.progress[i] = (self.progress[i] - 2).clamp(0, self.total[i]);
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
/// `SkullBlockEntity`: the player profile the head shows (kept as loaded:
|
||||
/// a compound, or a string when it names a player only), the note block
|
||||
/// sound and `custom_name`.
|
||||
@@ -315,6 +372,9 @@ impl BlockEntity {
|
||||
if name == "minecraft:brewing_stand" {
|
||||
return Some(Self::Brewing(Box::new(crate::brewing::BrewingStand::new())));
|
||||
}
|
||||
if name == "minecraft:campfire" || name == "minecraft:soul_campfire" {
|
||||
return Some(Self::Campfire(Box::default()));
|
||||
}
|
||||
let size = match name {
|
||||
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
|
||||
n if n.ends_with("copper_chest") => 27,
|
||||
@@ -352,6 +412,7 @@ impl BlockEntity {
|
||||
Self::Beehive(_) => "minecraft:beehive",
|
||||
Self::CommandBlock(_) => "minecraft:command_block",
|
||||
Self::Skull(_) => "minecraft:skull",
|
||||
Self::Campfire(_) => "minecraft:campfire",
|
||||
}
|
||||
}
|
||||
pub fn contents(&self) -> Vec<ItemStack> {
|
||||
@@ -373,6 +434,7 @@ impl BlockEntity {
|
||||
Self::Sculk(_) => Vec::new(),
|
||||
Self::Banner(_) => Vec::new(),
|
||||
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
|
||||
Self::Campfire(c) => c.items.iter().flatten().cloned().collect(),
|
||||
}
|
||||
}
|
||||
pub fn slots(&self) -> &[Option<ItemStack>] {
|
||||
@@ -393,7 +455,9 @@ impl BlockEntity {
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_) => &[],
|
||||
| Self::CommandBlock(_)
|
||||
// Not a Container (only Clearable): hoppers don't reach in.
|
||||
| Self::Campfire(_) => &[],
|
||||
}
|
||||
}
|
||||
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
|
||||
@@ -414,7 +478,8 @@ impl BlockEntity {
|
||||
| Self::TrialSpawner(_)
|
||||
| Self::Vault(_)
|
||||
| Self::Beehive(_)
|
||||
| Self::CommandBlock(_) => &mut [],
|
||||
| Self::CommandBlock(_)
|
||||
| Self::Campfire(_) => &mut [],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -706,6 +771,41 @@ mod tests {
|
||||
use super::*;
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
|
||||
#[test]
|
||||
fn campfire_slots_take_food_cook_it_and_cool_down() {
|
||||
let mut c = Campfire::default();
|
||||
let mut beef = ItemStack::new("minecraft:beef", 2);
|
||||
// placeFood: the first free slot, one item, its recipe's time.
|
||||
assert!(c.place_food(&mut beef, 600));
|
||||
assert_eq!(beef.count, 1);
|
||||
assert_eq!(c.items[0].as_ref().map(|s| s.count), Some(1));
|
||||
assert_eq!((c.progress[0], c.total[0]), (0, 600));
|
||||
let mut fish = ItemStack::new("minecraft:cod", 1);
|
||||
assert!(c.place_food(&mut fish, 3));
|
||||
assert_eq!(c.items[1].as_ref().map(|s| &*s.item), Some("minecraft:cod"));
|
||||
// cookTick: the cod is done on its third tick, the beef keeps cooking.
|
||||
assert!(c.cook_tick().is_empty());
|
||||
assert!(c.cook_tick().is_empty());
|
||||
let done = c.cook_tick();
|
||||
assert_eq!(done.len(), 1);
|
||||
assert_eq!((done[0].0, &*done[0].1.item), (1, "minecraft:cod"));
|
||||
assert!(c.items[1].is_none());
|
||||
assert_eq!(c.progress[0], 3);
|
||||
// cooldownTick: two a tick, never below zero.
|
||||
assert!(c.cooldown_tick());
|
||||
assert_eq!(c.progress[0], 1);
|
||||
assert!(c.cooldown_tick());
|
||||
assert_eq!(c.progress[0], 0);
|
||||
// Full: four slots, no fifth.
|
||||
for _ in 0..3 {
|
||||
let mut more = ItemStack::new("minecraft:potato", 1);
|
||||
assert!(c.place_food(&mut more, 600));
|
||||
}
|
||||
let mut fifth = ItemStack::new("minecraft:potato", 1);
|
||||
assert!(!c.place_food(&mut fifth, 600));
|
||||
assert_eq!(fifth.count, 1);
|
||||
}
|
||||
|
||||
/// A whole amount pays itself without a draw; a fraction is a chance of one more.
|
||||
#[test]
|
||||
fn create_experience_rounds_the_fraction_by_chance() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Creative inventory (CreativeModeInventoryScreen): vanilla's tabs and their
|
||||
//! contents as built by the game's own display generators
|
||||
//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab.
|
||||
use crate::{Result, items::ItemStack};
|
||||
use crate::{Result, items::ItemStack, ui::EditBox};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, fs, path::Path};
|
||||
|
||||
@@ -35,10 +35,8 @@ pub struct Creative {
|
||||
pub scroll: f32,
|
||||
/// The scrollbar is held (scrolling): dragging moves it.
|
||||
pub scrolling: bool,
|
||||
pub search: String,
|
||||
/// When the search box took the focus (`EditBox.setFocused`): its
|
||||
/// cursor blinks from then.
|
||||
pub search_focused: std::time::Instant,
|
||||
/// CreativeModeInventoryScreen's search box: an unbordered `EditBox` of 50.
|
||||
pub search: EditBox,
|
||||
/// The search tab's stacks, in its display order.
|
||||
search_items: Vec<ItemStack>,
|
||||
search_index: Vec<SearchEntry>,
|
||||
@@ -284,8 +282,13 @@ impl Creative {
|
||||
selected: 0,
|
||||
scroll: 0.0,
|
||||
scrolling: false,
|
||||
search: String::new(),
|
||||
search_focused: std::time::Instant::now(),
|
||||
search: {
|
||||
let mut search = EditBox::new(0.0, 0.0, 80.0, 9.0);
|
||||
search.bordered = false;
|
||||
search.max_length = 50;
|
||||
search.text_color = u32::MAX;
|
||||
search
|
||||
},
|
||||
search_items,
|
||||
search_index,
|
||||
}
|
||||
@@ -306,12 +309,13 @@ impl Creative {
|
||||
/// selectTab: a different tab empties the search box; the scrollbar goes to the top.
|
||||
pub fn select(&mut self, tab: usize) {
|
||||
if tab != self.selected {
|
||||
self.search.clear();
|
||||
self.search.set_value("");
|
||||
}
|
||||
self.selected = tab;
|
||||
self.scroll = 0.0;
|
||||
if self.tab().search {
|
||||
self.search_focused = std::time::Instant::now();
|
||||
self.search.focused = true;
|
||||
self.search.reset_blink();
|
||||
}
|
||||
}
|
||||
/// The search tab's stacks.
|
||||
@@ -385,7 +389,7 @@ impl Creative {
|
||||
let tab = self.tab();
|
||||
if tab.search {
|
||||
return self
|
||||
.search_results(&self.search, names)
|
||||
.search_results(&self.search.value, names)
|
||||
.into_iter()
|
||||
.map(|i| self.search_items[i].clone())
|
||||
.collect();
|
||||
@@ -754,13 +758,13 @@ mod tests {
|
||||
(1, false, true),
|
||||
(2, true, false),
|
||||
] {
|
||||
c.search = "anvil".into();
|
||||
c.search.set_value("anvil");
|
||||
c.scroll = 0.5;
|
||||
c.select(selected);
|
||||
assert_eq!(c.selected, selected);
|
||||
assert_eq!(c.tab().inventory, inventory);
|
||||
assert_eq!(c.tab().search, search);
|
||||
assert!(c.search.is_empty());
|
||||
assert!(c.search.value.is_empty());
|
||||
assert_eq!(c.scroll, 0.0);
|
||||
}
|
||||
}
|
||||
@@ -780,12 +784,12 @@ mod tests {
|
||||
assert_eq!(c.tabs[0].items[0].item.as_ref(), "minecraft:anvil");
|
||||
let mut c = c;
|
||||
c.select(1);
|
||||
c.search = "anvil".into();
|
||||
c.search.set_value("anvil");
|
||||
c.scroll = 0.5;
|
||||
c.select(1);
|
||||
assert_eq!((c.search.as_str(), c.scroll), ("anvil", 0.0));
|
||||
assert_eq!((c.search.value.as_str(), c.scroll), ("anvil", 0.0));
|
||||
c.select(0);
|
||||
assert_eq!(c.search, "");
|
||||
assert_eq!(c.search.value, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -899,4 +903,25 @@ mod tests {
|
||||
c.scroll = 1.0;
|
||||
assert_eq!(c.scroller_offset(), 95.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_edits_at_its_cursor() {
|
||||
use winit::keyboard::KeyCode;
|
||||
let mut c = creative(0);
|
||||
c.select(1);
|
||||
c.search.insert_text("hello world");
|
||||
for _ in 0..5 {
|
||||
assert!(c.search.key(KeyCode::ArrowLeft, false, false));
|
||||
}
|
||||
c.search.insert_text("X");
|
||||
assert_eq!(c.search.value, "hello Xworld");
|
||||
c.search.key(KeyCode::Home, false, true);
|
||||
c.search.insert_text("Y");
|
||||
assert_eq!(c.search.value, "Yworld");
|
||||
// Ctrl+Left jumps a word; one step right and Backspace deletes before the cursor.
|
||||
c.search.key(KeyCode::ArrowLeft, true, false);
|
||||
c.search.key(KeyCode::ArrowRight, false, false);
|
||||
c.search.key(KeyCode::Backspace, false, false);
|
||||
assert_eq!(c.search.value, "world");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Cushion placement and support checks (`Cushion.canBePlacedAt`/`wouldSurviveAt`).
|
||||
use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape};
|
||||
|
||||
pub trait World {
|
||||
fn outline_bounds(&self, pos: [i32; 3]) -> Option<Aabb>;
|
||||
fn collision_shapes(&self, bounds: Aabb) -> Vec<VoxelShape>;
|
||||
fn suffocating(&self, pos: [i32; 3]) -> bool;
|
||||
}
|
||||
|
||||
pub fn blocks_in(a: Aabb) -> impl Iterator<Item = [i32; 3]> {
|
||||
let (lo, hi) = (a.min_position(), a.max_position());
|
||||
let (x0, y0, z0) = (
|
||||
lo.x.floor() as i32,
|
||||
lo.y.floor() as i32,
|
||||
lo.z.floor() as i32,
|
||||
);
|
||||
let (x1, y1, z1) = (
|
||||
hi.x.floor() as i32,
|
||||
hi.y.floor() as i32,
|
||||
hi.z.floor() as i32,
|
||||
);
|
||||
(y0..=y1).flat_map(move |y| (z0..=z1).flat_map(move |z| (x0..=x1).map(move |x| [x, y, z])))
|
||||
}
|
||||
|
||||
pub fn survives(world: &impl World, bounds: Aabb) -> bool {
|
||||
let (lo, hi) = (bounds.min_position(), bounds.max_position());
|
||||
let anchor = Aabb::new(
|
||||
Vec3::new(lo.x, lo.y - 0.015625, lo.z),
|
||||
Vec3::new(hi.x.next_down(), lo.y, hi.z.next_down()),
|
||||
);
|
||||
// The extra eighth block expands the scan, not the intersection test.
|
||||
let supported = blocks_in(anchor.expand_towards(Vec3::new(0.0, -0.125, 0.0))).any(|p| {
|
||||
world
|
||||
.outline_bounds(p)
|
||||
.is_some_and(|shape| shape.intersects(anchor))
|
||||
});
|
||||
supported && !blocks_in(bounds.next_deflated()).all(|p| world.suffocating(p))
|
||||
}
|
||||
|
||||
pub fn can_place(world: &impl World, bounds: Aabb) -> bool {
|
||||
if !survives(world, bounds) {
|
||||
return false;
|
||||
}
|
||||
let (lo, hi) = (bounds.min_position(), bounds.max_position());
|
||||
let slab = Aabb::new(lo, Vec3::new(hi.x, lo.y + 0.015625, hi.z)).next_deflated();
|
||||
let Ok(mut remaining) = VoxelShape::from_box(slab) else {
|
||||
return false;
|
||||
};
|
||||
for shape in world.collision_shapes(slab) {
|
||||
let Ok(next) = remaining.join(&shape, ShapeOp::ONLY_FIRST) else {
|
||||
return false;
|
||||
};
|
||||
remaining = next;
|
||||
if remaining.is_empty() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -591,6 +591,57 @@ impl Painting {
|
||||
)
|
||||
}
|
||||
}
|
||||
/// The `DyeColor` ordinal of a colour name (`DyeColor.byName`), white when
|
||||
/// the name is unknown.
|
||||
pub fn dye_index(name: &str) -> u8 {
|
||||
crate::mobs::render::DYE_NAMES
|
||||
.iter()
|
||||
.position(|n| *n == name)
|
||||
.unwrap_or(0) as u8
|
||||
}
|
||||
/// A cushion (`Cushion`, a `BlockAttachedEntity`): a 1 x 0.25 block pillow
|
||||
/// that seats a player. It sits on the top face of a block, at the clicked
|
||||
/// height, and is coloured by its `DyeColor`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Cushion {
|
||||
pub id: u32,
|
||||
/// `Entity.position`: the bottom centre of the cushion.
|
||||
pub position: Vec3,
|
||||
/// `BlockAttachedEntity.pos` (the saved `block_pos`).
|
||||
pub pos: [i32; 3],
|
||||
pub yaw: f32,
|
||||
/// `DyeColor` ordinal: white 0, orange 1, ..., black 15.
|
||||
pub color: u8,
|
||||
/// BlockAttachedEntity.ticksSinceLastCheck.
|
||||
pub check_interval: u32,
|
||||
}
|
||||
impl Cushion {
|
||||
/// `Entity.makeBoundingBox`: x and z half a block out, y to y + 0.25.
|
||||
pub fn bounds(&self) -> ([f64; 3], [f64; 3]) {
|
||||
let p = self.position;
|
||||
(
|
||||
[p.x - 0.5, p.y, p.z - 0.5],
|
||||
[p.x + 0.5, p.y + 0.25, p.z + 0.5],
|
||||
)
|
||||
}
|
||||
/// The `DyeColor` name of the cushion.
|
||||
pub fn color_name(&self) -> &'static str {
|
||||
crate::mobs::render::DYE_NAMES[usize::from(self.color.min(15))]
|
||||
}
|
||||
/// `Cushion.getCushionItemStackWithData`: the matching coloured item.
|
||||
pub fn item(&self) -> String {
|
||||
format!("minecraft:{}_cushion", self.color_name())
|
||||
}
|
||||
/// `Cushion.interact`'s seat: the vehicle's PASSENGER attachment
|
||||
/// `(0, 0.25, 0)` less the player's `(0, 0.6, 0)`.
|
||||
pub fn seat(&self) -> Vec3 {
|
||||
Vec3::new(self.position.x, self.position.y - 0.35, self.position.z)
|
||||
}
|
||||
/// `Entity.getDismountLocationForPassenger`: on top of the cushion.
|
||||
pub fn dismount(&self) -> Vec3 {
|
||||
Vec3::new(self.position.x, self.position.y + 0.25, self.position.z)
|
||||
}
|
||||
}
|
||||
/// An item frame or glow item frame (`ItemFrame`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ItemFrame {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! survive a Horizon save.
|
||||
use crate::{
|
||||
arrows::Pickup,
|
||||
entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting},
|
||||
entities::{ArmorStand, Cushion, ExperienceOrb, ItemEntity, ItemFrame, Painting},
|
||||
mobs::{Mob, MobType, Who},
|
||||
projectiles::{Projectile, ProjectileKind},
|
||||
save::{
|
||||
@@ -1313,6 +1313,79 @@ pub fn painting_from_nbt(tag: &Tag) -> Option<([i32; 3], u8, String)> {
|
||||
let facing = (number(tag.get("facing")).unwrap_or(0) & 3) as u8;
|
||||
Some((pos, facing, text(tag.get("variant"))?))
|
||||
}
|
||||
/// Cushion.addAdditionalSaveData: the block it sits on and its colour.
|
||||
pub fn cushion_to_nbt(c: &Cushion, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
let base = Base {
|
||||
id: "minecraft:cushion",
|
||||
uuid,
|
||||
position: c.position,
|
||||
motion: Vec3::ZERO,
|
||||
rotation: [c.yaw, 0.0],
|
||||
on_ground: false,
|
||||
fall_distance: 0.0,
|
||||
};
|
||||
let mut tag = base.tag(raw);
|
||||
put(&mut tag, "block_pos", Tag::IntArray(c.pos.to_vec()));
|
||||
put(&mut tag, "color", string(c.color_name()));
|
||||
tag
|
||||
}
|
||||
/// The position, block position, yaw and colour of a saved cushion.
|
||||
pub fn cushion_from_nbt(tag: &Tag, id: u32) -> Option<Cushion> {
|
||||
let position = position(tag)?;
|
||||
let pos = match tag.get("block_pos") {
|
||||
Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]],
|
||||
_ => [
|
||||
position.x.floor() as i32,
|
||||
position.y.floor() as i32,
|
||||
position.z.floor() as i32,
|
||||
],
|
||||
};
|
||||
let yaw = match tag.get("Rotation") {
|
||||
Some(Tag::List(l)) => l
|
||||
.first()
|
||||
.and_then(|v| crate::save::float(Some(v)))
|
||||
.unwrap_or(0.0) as f32,
|
||||
_ => 0.0,
|
||||
};
|
||||
let color =
|
||||
crate::entities::dye_index(&text(tag.get("color")).unwrap_or_else(|| "white".into()));
|
||||
Some(Cushion {
|
||||
id,
|
||||
position,
|
||||
pos,
|
||||
yaw,
|
||||
color,
|
||||
check_interval: 0,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cushion_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cushion_save_preserves_color_anchor_rotation_and_unknown_data() {
|
||||
let cushion = Cushion {
|
||||
id: 7,
|
||||
position: Vec3::new(-1.5, 64.5, 3.5),
|
||||
pos: [-2, 64, 3],
|
||||
yaw: 270.0,
|
||||
color: 14,
|
||||
check_interval: 55,
|
||||
};
|
||||
let raw = Tag::compound([("CustomName", string("Seat"))]);
|
||||
let tag = cushion_to_nbt(&cushion, [1, 2, 3, 4], Some(&raw));
|
||||
assert_eq!(text(tag.get("CustomName")).as_deref(), Some("Seat"));
|
||||
let loaded = cushion_from_nbt(&tag, 8).unwrap();
|
||||
assert_eq!(loaded.id, 8);
|
||||
assert_eq!(loaded.position, cushion.position);
|
||||
assert_eq!(loaded.pos, cushion.pos);
|
||||
assert_eq!(loaded.yaw, cushion.yaw);
|
||||
assert_eq!(loaded.color_name(), "red");
|
||||
assert_eq!(loaded.check_interval, 0);
|
||||
assert_eq!(loaded.bounds(), cushion.bounds());
|
||||
}
|
||||
}
|
||||
/// ItemFrame.addAdditionalSaveData.
|
||||
pub fn item_frame_to_nbt(f: &ItemFrame, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
|
||||
let (lo, hi) = f.bounds();
|
||||
|
||||
@@ -18,6 +18,7 @@ mod boats;
|
||||
mod books;
|
||||
mod bossbars;
|
||||
mod breezes;
|
||||
mod campfire;
|
||||
mod cartography;
|
||||
mod chat;
|
||||
mod client_ambient;
|
||||
@@ -33,6 +34,7 @@ mod copper_golems;
|
||||
mod creaking;
|
||||
mod creatures;
|
||||
mod crossbow;
|
||||
pub(crate) mod cushions;
|
||||
mod debug_keys;
|
||||
mod decorated_pot;
|
||||
mod dedicated;
|
||||
@@ -1431,6 +1433,8 @@ struct Game<'a> {
|
||||
map_frame_model: frames::FrameModel,
|
||||
glow_map_frame_model: frames::FrameModel,
|
||||
armor_stands: Vec<horizon_client::entities::ArmorStand>,
|
||||
/// `Cushion` decoration entities (game/cushions.rs).
|
||||
cushions: Vec<horizon_client::entities::Cushion>,
|
||||
/// Entities of types Horizon does not simulate.
|
||||
others: Vec<commands::OtherEntity>,
|
||||
armor_stand_assets: armor_stands::ArmorStandAssets,
|
||||
@@ -1446,6 +1450,8 @@ struct Game<'a> {
|
||||
boat_models: boats::BoatModels,
|
||||
/// EndCrystalModel's baked layer.
|
||||
crystal_model: Option<horizon_client::mobs::Part>,
|
||||
/// CushionModel's baked layer.
|
||||
cushion_model: Option<horizon_client::mobs::Part>,
|
||||
carts: Vec<minecarts::Minecart>,
|
||||
/// Songs playing from jukeboxes (tracked sound handles).
|
||||
jukebox_sounds: HashMap<(i32, i32, i32), u64>,
|
||||
@@ -2789,6 +2795,9 @@ impl Game<'_> {
|
||||
pos,
|
||||
data,
|
||||
} => self.consume_teleport_particles([pos.x, pos.y, pos.z], data),
|
||||
LevelEvent::LevelEvent { id: 2003, pos, .. } => {
|
||||
self.eye_break_particles([pos.x, pos.y, pos.z]);
|
||||
}
|
||||
LevelEvent::LevelEvent {
|
||||
id: 2013,
|
||||
pos,
|
||||
@@ -3490,6 +3499,7 @@ impl Game<'_> {
|
||||
fn interact_entity(&mut self) -> Result<bool> {
|
||||
Ok(self.interact_frame()
|
||||
|| self.interact_armor_stand()
|
||||
|| self.interact_cushion()
|
||||
|| self.interact_boat()
|
||||
|| self.interact_cart()
|
||||
|| self.interact_mob()?
|
||||
@@ -3676,6 +3686,7 @@ impl Game<'_> {
|
||||
|| self.place_painting(hit, &stack)
|
||||
|| self.place_item_frame(hit, &stack)
|
||||
|| self.place_armor_stand(hit, &stack)
|
||||
|| self.place_cushion(hit, &stack)
|
||||
|| self.place_end_crystal(hit, &stack))
|
||||
{
|
||||
return Ok(true);
|
||||
@@ -4566,6 +4577,7 @@ impl Game<'_> {
|
||||
horizon_client::spans::time("tick_paintings", || self.tick_paintings());
|
||||
horizon_client::spans::time("tick_item_frames", || self.tick_item_frames());
|
||||
horizon_client::spans::time("tick_armor_stands", || self.tick_armor_stands());
|
||||
horizon_client::spans::time("tick_cushions", || self.tick_cushions());
|
||||
horizon_client::spans::time("tick_boats", || self.tick_boats());
|
||||
horizon_client::spans::time("tick_carts", || self.tick_carts());
|
||||
horizon_client::spans::time("tick_thunder", || self.tick_thunder());
|
||||
@@ -5303,7 +5315,8 @@ impl Game<'_> {
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_)
|
||||
| BlockEntity::Skull(_),
|
||||
| BlockEntity::Skull(_)
|
||||
| BlockEntity::Campfire(_),
|
||||
) => {}
|
||||
None => {
|
||||
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
|
||||
@@ -5573,7 +5586,8 @@ impl Game<'_> {
|
||||
| BlockEntity::Vault(_)
|
||||
| BlockEntity::Beehive(_)
|
||||
| BlockEntity::CommandBlock(_)
|
||||
| BlockEntity::Skull(_),
|
||||
| BlockEntity::Skull(_)
|
||||
| BlockEntity::Campfire(_),
|
||||
) => {}
|
||||
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
|
||||
None => {
|
||||
@@ -5723,8 +5737,9 @@ impl Game<'_> {
|
||||
if self.creative_screen.tab().search {
|
||||
// CreativeModeInventoryScreen.slotClicked: moveCursorToEnd, then
|
||||
// setHighlightPos(0), so typing replaces the whole query.
|
||||
let search = &self.creative_screen.search;
|
||||
self.text_selection.select(("creative.search", 0), search);
|
||||
let search = &mut self.creative_screen.search;
|
||||
search.move_cursor_to_end(false);
|
||||
search.highlight = 0;
|
||||
}
|
||||
let items = self.creative_screen.items(&self.pack.names);
|
||||
let first = self.creative_screen.first_row(&self.pack.names);
|
||||
@@ -6366,6 +6381,13 @@ impl Game<'_> {
|
||||
false,
|
||||
);
|
||||
if outside {
|
||||
// AbstractRecipeBookScreen.mouseClicked: the book takes the click
|
||||
// before the outside test, and its tabs sit left of the strip
|
||||
// hasClickedOutside counts as the book.
|
||||
if self.recipe_book_click(right) {
|
||||
self.inv_clicks.skip_release();
|
||||
return;
|
||||
}
|
||||
// slotId -999: an empty hand throws nothing; a carried stack
|
||||
// starts a drag whose release drops it.
|
||||
match input {
|
||||
@@ -7030,6 +7052,9 @@ impl Game<'_> {
|
||||
// `VaultRenderer`.
|
||||
self.mark_entity(out.len(), "");
|
||||
self.vault_geometry(camera, alpha, &mut out);
|
||||
// `CampfireRenderer`.
|
||||
self.mark_entity(out.len(), "");
|
||||
self.campfire_geometry(camera, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:ominous_item_spawner");
|
||||
self.ominous_item_spawner_geometry(camera, alpha, &mut out);
|
||||
// Mobs and their projectiles (a span each).
|
||||
@@ -7272,6 +7297,7 @@ impl Game<'_> {
|
||||
self.frame_geometry(camera, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:armor_stand");
|
||||
self.armor_stand_geometry(camera, alpha, &mut out);
|
||||
self.cushion_geometry(camera, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:oak_boat");
|
||||
self.boat_geometry(camera, alpha, &mut out);
|
||||
self.mark_entity(out.len(), "minecraft:minecart");
|
||||
@@ -7568,6 +7594,7 @@ impl Game<'_> {
|
||||
.map_or(0.0, |i| i.attack_damage);
|
||||
if self.attack_frame()
|
||||
|| self.attack_armor_stand()
|
||||
|| self.attack_cushion()
|
||||
|| self.attack_boat(hand_damage)
|
||||
|| self.attack_cart(hand_damage)
|
||||
|| self.attack_dragon()
|
||||
@@ -8312,6 +8339,7 @@ impl Game<'_> {
|
||||
self.boats.clear();
|
||||
self.carts.clear();
|
||||
self.armor_stands.clear();
|
||||
self.cushions.clear();
|
||||
self.item_frames.clear();
|
||||
self.paintings.clear();
|
||||
self.others.clear();
|
||||
@@ -8730,6 +8758,13 @@ impl Game<'_> {
|
||||
{
|
||||
return Ok(UseResult::Success { swing: true });
|
||||
}
|
||||
if allow_block_actions
|
||||
&& let Some(hit) = self.pick()
|
||||
&& let Some(placed) = self.use_on_campfire(hit.pos)?
|
||||
{
|
||||
// SUCCESS_SERVER swings; a full campfire's CONSUME does not.
|
||||
return Ok(UseResult::Success { swing: placed });
|
||||
}
|
||||
// BucketItem has no useOn: a guest's UseItemOn leaves it to UseItem.
|
||||
let bucket = horizon_client::items::bucket_contents(&stack.item);
|
||||
if matches!(self.guest_use, Some(GuestUse::OnBlock(_)))
|
||||
@@ -9847,20 +9882,16 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
if tab.search {
|
||||
// The search box: an unbordered EditBox of 80 at (82, 6), white.
|
||||
let search = &self.creative_screen.search;
|
||||
horizon_client::ui::append_field(
|
||||
batch,
|
||||
atlas,
|
||||
search,
|
||||
(ox + 82.0, oy + 6.0, 80.0),
|
||||
(u32::MAX, true),
|
||||
clipboard::CREATIVE_SEARCH_CHARS,
|
||||
self.text_selection
|
||||
.covers(clipboard::CREATIVE_SEARCH, search),
|
||||
true,
|
||||
self.creative_screen.search_focused.elapsed().as_millis(),
|
||||
);
|
||||
// CreativeModeInventoryScreen: an unbordered EditBox of 50 at (82, 6).
|
||||
let search = &mut self.creative_screen.search;
|
||||
search.x = ox + 82.0;
|
||||
search.y = oy + 6.0;
|
||||
search.width = 80.0;
|
||||
search.bordered = false;
|
||||
search.focused = true;
|
||||
search.text_color = u32::MAX;
|
||||
search.max_length = clipboard::CREATIVE_SEARCH_CHARS;
|
||||
search.draw(batch, atlas, None);
|
||||
}
|
||||
let mut hovered: Option<ItemStack> = None;
|
||||
if tab.inventory {
|
||||
@@ -10021,6 +10052,9 @@ impl Game<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !right && self.creative_search_click(ox, oy) {
|
||||
return;
|
||||
}
|
||||
// Holding the scrollbar scrolls as the mouse moves (mouseDragged).
|
||||
if !right
|
||||
&& self
|
||||
@@ -10033,6 +10067,24 @@ impl Game<'_> {
|
||||
self.inventory_press(right);
|
||||
}
|
||||
}
|
||||
/// A click on the search tab's box (`EditBox.onClick`).
|
||||
fn creative_search_click(&mut self, ox: f32, oy: f32) -> bool {
|
||||
if !self.creative_screen.tab().search {
|
||||
return false;
|
||||
}
|
||||
let (x, y, w, h) = (ox + 82.0, oy + 6.0, 80.0, 9.0);
|
||||
let (mx, my) = self.cursor;
|
||||
if mx < x || my < y || mx >= x + w || my >= y + h {
|
||||
return false;
|
||||
}
|
||||
let shift = self.has_shift_down();
|
||||
let search = &mut self.creative_screen.search;
|
||||
search.x = x;
|
||||
search.y = y;
|
||||
search.width = w;
|
||||
search.click(&self.gui.atlas, mx, shift, false);
|
||||
true
|
||||
}
|
||||
/// Copy the live player and world state into the `Level` that gets saved.
|
||||
pub(super) fn sync_level(&mut self) {
|
||||
// Level.write saves the game rules (game_rules.dat) with the rest.
|
||||
@@ -11678,8 +11730,17 @@ impl ApplicationHandler for Game<'_> {
|
||||
// The hovered slot took the key (`ignoreTextInput`).
|
||||
} else if let Some(shortcut) = self.edit_shortcut(&event) {
|
||||
self.creative_search_shortcut(shortcut);
|
||||
} else if event.physical_key == PhysicalKey::Code(KeyCode::Backspace) {
|
||||
self.creative_search_backspace(self.has_control_down());
|
||||
} else if let PhysicalKey::Code(key) = event.physical_key {
|
||||
// EditBox.keyPressed: arrows, Home, End, Delete and Backspace.
|
||||
let before = self.creative_screen.search.value.clone();
|
||||
let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
|
||||
if self.creative_screen.search.key(key, ctrl, shift) {
|
||||
if self.creative_screen.search.value != before {
|
||||
self.creative_screen.scroll = 0.0;
|
||||
}
|
||||
} else {
|
||||
self.creative_search_edit(event.text.as_deref());
|
||||
}
|
||||
} else {
|
||||
self.creative_search_edit(event.text.as_deref());
|
||||
}
|
||||
@@ -11700,6 +11761,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
// The anvil rename box takes every key but Escape (AnvilScreen.keyPressed).
|
||||
if let Some(shortcut) = self.edit_shortcut(&event) {
|
||||
self.station_shortcut(shortcut);
|
||||
} else if let PhysicalKey::Code(key) = event.physical_key
|
||||
&& self.station_key(key)
|
||||
{
|
||||
} else {
|
||||
let backspace = event.physical_key == PhysicalKey::Code(KeyCode::Backspace);
|
||||
self.station_text(event.text.as_deref(), backspace);
|
||||
@@ -12316,6 +12380,7 @@ impl<'a> Game<'a> {
|
||||
map_frame_model: prepared.map_frame_model,
|
||||
glow_map_frame_model: prepared.glow_map_frame_model,
|
||||
armor_stands: Vec::new(),
|
||||
cushions: Vec::new(),
|
||||
others: Vec::new(),
|
||||
armor_stand_assets: prepared.armor_stand_assets,
|
||||
waypoint_styles: prepared.waypoint_styles,
|
||||
@@ -12325,6 +12390,7 @@ impl<'a> Game<'a> {
|
||||
boats: Vec::new(),
|
||||
boat_models: prepared.boat_models,
|
||||
crystal_model: prepared.crystal_model,
|
||||
cushion_model: prepared.cushion_model,
|
||||
carts: Vec::new(),
|
||||
jukebox_sounds: HashMap::new(),
|
||||
bolts: Vec::new(),
|
||||
@@ -12463,6 +12529,7 @@ struct GameCpuResources {
|
||||
boat_models: boats::BoatModels,
|
||||
cart_models: minecarts::CartModels,
|
||||
crystal_model: Option<horizon_client::mobs::Part>,
|
||||
cushion_model: Option<horizon_client::mobs::Part>,
|
||||
dragon_model: Option<horizon_client::mobs::Part>,
|
||||
arrow_model: Option<horizon_client::mobs::Part>,
|
||||
trident_model: Option<horizon_client::mobs::Part>,
|
||||
@@ -12483,6 +12550,7 @@ impl GameCpuResources {
|
||||
boat_models: boats::BoatModels::load(document.as_ref()),
|
||||
cart_models: minecarts::CartModels::load(document.as_ref()),
|
||||
crystal_model: model("minecraft:end_crystal#main"),
|
||||
cushion_model: model("minecraft:cushion#main"),
|
||||
dragon_model: model("minecraft:ender_dragon#main"),
|
||||
arrow_model: model("minecraft:arrow#main"),
|
||||
trident_model: model("minecraft:trident#main"),
|
||||
@@ -13838,7 +13906,7 @@ mod startup_cpu_tests {
|
||||
r#"{
|
||||
"minecraft:end_crystal#main": {}, "minecraft:ender_dragon#main": {},
|
||||
"minecraft:arrow#main": {}, "minecraft:trident#main": {},
|
||||
"minecraft:armor_stand#main": {}
|
||||
"minecraft:armor_stand#main": {}, "minecraft:cushion#main": {}
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
@@ -13858,6 +13926,7 @@ mod startup_cpu_tests {
|
||||
.unwrap();
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
assert!(prepared.crystal_model.is_some());
|
||||
assert!(prepared.cushion_model.is_some());
|
||||
assert!(prepared.dragon_model.is_some());
|
||||
assert!(prepared.arrow_model.is_some());
|
||||
assert!(prepared.trident_model.is_some());
|
||||
|
||||
@@ -56,6 +56,7 @@ impl Game<'_> {
|
||||
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
|
||||
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
|
||||
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
|
||||
Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -92,7 +93,10 @@ impl Game<'_> {
|
||||
| "minecraft:vault"
|
||||
| "minecraft:beehive"
|
||||
| "minecraft:bee_nest"
|
||||
| "minecraft:brewing_stand" => Ticking::Yes,
|
||||
| "minecraft:brewing_stand"
|
||||
// Lit, cookTick; unlit, cooldownTick.
|
||||
| "minecraft:campfire"
|
||||
| "minecraft:soul_campfire" => Ticking::Yes,
|
||||
"minecraft:jukebox" => {
|
||||
let record = registry
|
||||
.state(state)
|
||||
|
||||
@@ -587,6 +587,9 @@ impl Game<'_> {
|
||||
}
|
||||
/// The player's tick while riding: steer, tick the boat, sit in it.
|
||||
pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> {
|
||||
if self.tick_cushion_riding(keys) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(i) = self.boats.iter().position(|b| Some(b.id) == self.riding) else {
|
||||
if self.tick_cart_riding(keys) || self.tick_mount_riding(keys) {
|
||||
return Ok(());
|
||||
|
||||
@@ -17,7 +17,6 @@ use horizon_client::{
|
||||
use horizon_core::position::BlockPos;
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S};
|
||||
use horizon_world::level::flags as level_flags;
|
||||
use std::time::Instant;
|
||||
use winit::{
|
||||
event::{ElementState, KeyEvent},
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
@@ -27,8 +26,24 @@ const BLACK: u32 = 0xFF00_0000;
|
||||
const PAGE_CHARS: usize = 1024;
|
||||
const MAX_PAGES: usize = 100;
|
||||
const LINES: usize = 14;
|
||||
/// `BookSignScreen`'s title box.
|
||||
const BOOK_TITLE: horizon_client::clipboard::FieldId = ("book.title", 0);
|
||||
|
||||
fn book_title_box() -> ui::EditBox {
|
||||
let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
|
||||
edit.bordered = false;
|
||||
edit.max_length = 15;
|
||||
edit.text_color = BLACK;
|
||||
edit.focused = true;
|
||||
edit
|
||||
}
|
||||
fn book_page_box() -> ui::EditBox {
|
||||
let mut edit = ui::EditBox::new(0.0, 0.0, 114.0, 9.0);
|
||||
edit.bordered = false;
|
||||
edit.multiline = true;
|
||||
edit.max_length = PAGE_CHARS;
|
||||
edit.text_color = BLACK;
|
||||
edit.focused = true;
|
||||
edit
|
||||
}
|
||||
|
||||
pub(super) enum BookScreen {
|
||||
Edit {
|
||||
@@ -38,7 +53,10 @@ pub(super) enum BookScreen {
|
||||
page: usize,
|
||||
signing: bool,
|
||||
title: String,
|
||||
opened: Instant,
|
||||
/// BookSignScreen's title box (`EditBox` of 15).
|
||||
title_edit: ui::EditBox,
|
||||
/// BookEditScreen's page (`MultiLineEditBox`).
|
||||
page_edit: ui::EditBox,
|
||||
},
|
||||
View {
|
||||
pages: Vec<String>,
|
||||
@@ -84,13 +102,16 @@ impl Game<'_> {
|
||||
if pages.is_empty() {
|
||||
pages.push(String::new());
|
||||
}
|
||||
let mut page_edit = book_page_box();
|
||||
page_edit.set_value(&pages[0]);
|
||||
BookScreen::Edit {
|
||||
slot: self.held_slot(),
|
||||
pages,
|
||||
page: 0,
|
||||
signing: false,
|
||||
title: String::new(),
|
||||
opened: Instant::now(),
|
||||
title_edit: book_title_box(),
|
||||
page_edit,
|
||||
}
|
||||
}
|
||||
"minecraft:written_book" => BookScreen::View {
|
||||
@@ -239,34 +260,24 @@ impl Game<'_> {
|
||||
Some(KeyCode::PageDown) => self.turn_page(true),
|
||||
_ => {}
|
||||
},
|
||||
Some(BookScreen::Edit {
|
||||
signing: true,
|
||||
title,
|
||||
..
|
||||
}) => match key {
|
||||
Some(BookScreen::Edit { signing: true, .. }) => match key {
|
||||
Some(KeyCode::Escape) => {
|
||||
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
|
||||
*signing = false;
|
||||
}
|
||||
}
|
||||
Some(KeyCode::Backspace) => {
|
||||
if !self.text_selection.take(BOOK_TITLE, title) {
|
||||
title.pop();
|
||||
}
|
||||
}
|
||||
Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
|
||||
if !title.trim().is_empty() {
|
||||
let blank = self.book.as_ref().is_some_and(
|
||||
|b| matches!(b, BookScreen::Edit { title, .. } if title.trim().is_empty()),
|
||||
);
|
||||
if !blank {
|
||||
self.save_book(true);
|
||||
}
|
||||
}
|
||||
Some(key) if self.book_title_key(key) => {}
|
||||
_ => {
|
||||
if let Some(typed) = text {
|
||||
self.text_selection.take(BOOK_TITLE, title);
|
||||
for c in typed.chars().filter(|c| !c.is_control()) {
|
||||
if title.chars().count() < 15 {
|
||||
title.push(c);
|
||||
}
|
||||
}
|
||||
self.book_title_insert(typed);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -274,24 +285,13 @@ impl Game<'_> {
|
||||
Some(KeyCode::Escape) => self.save_book(false),
|
||||
Some(KeyCode::PageUp) => self.turn_page(false),
|
||||
Some(KeyCode::PageDown) => self.turn_page(true),
|
||||
Some(KeyCode::Backspace) => {
|
||||
if !self.take_page_selection() {
|
||||
self.edit_page(|p| {
|
||||
p.pop();
|
||||
})
|
||||
}
|
||||
}
|
||||
Some(KeyCode::Enter | KeyCode::NumpadEnter) => {
|
||||
self.take_page_selection();
|
||||
self.type_into_page("\n")
|
||||
}
|
||||
Some(KeyCode::ArrowUp) => self.book_move_line(-1),
|
||||
Some(KeyCode::ArrowDown) => self.book_move_line(1),
|
||||
Some(KeyCode::Enter | KeyCode::NumpadEnter) => self.page_insert("\n"),
|
||||
Some(key) if self.book_page_key(key) => {}
|
||||
_ => {
|
||||
if let Some(typed) = text {
|
||||
let typed: String = typed.chars().filter(|c| !c.is_control()).collect();
|
||||
if !typed.is_empty() {
|
||||
self.take_page_selection();
|
||||
}
|
||||
self.type_into_page(&typed);
|
||||
self.page_insert(typed);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -302,99 +302,258 @@ impl Game<'_> {
|
||||
pub(super) fn book_type(&mut self, text: &str) {
|
||||
let text = text.replace("\\n", "\n");
|
||||
match self.book.as_mut() {
|
||||
Some(BookScreen::Edit {
|
||||
signing: true,
|
||||
title,
|
||||
..
|
||||
}) => {
|
||||
for c in text.chars().filter(|c| !c.is_control()) {
|
||||
if title.chars().count() < 15 {
|
||||
title.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(BookScreen::Edit { .. }) => self.type_into_page(&text),
|
||||
Some(BookScreen::Edit { signing: true, .. }) => self.book_title_insert(&text),
|
||||
Some(BookScreen::Edit { .. }) => self.page_insert(&text),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// Before typing on a page: Select All's selection is cleared (true).
|
||||
fn take_page_selection(&mut self) -> bool {
|
||||
match self.book.as_mut() {
|
||||
Some(BookScreen::Edit { pages, page, .. }) => self
|
||||
.text_selection
|
||||
.take(("book.page", *page), &mut pages[*page]),
|
||||
_ => false,
|
||||
/// `BookSignScreen.keyPressed` on the title box.
|
||||
fn book_title_key(&mut self, key: KeyCode) -> bool {
|
||||
let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
|
||||
let Some(BookScreen::Edit {
|
||||
title, title_edit, ..
|
||||
}) = self.book.as_mut()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if !title_edit.key(key, ctrl, shift) {
|
||||
return false;
|
||||
}
|
||||
title.clone_from(&title_edit.value);
|
||||
true
|
||||
}
|
||||
/// Ctrl+A/C/V/X: the title box (an `EditBox` of 15) while signing, else
|
||||
/// the page (`MultilineTextField.insertText`: line breaks kept, cut to
|
||||
/// the 1024 characters left, rejected when it overflows the 14 lines).
|
||||
pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
|
||||
let font = &self.gui.atlas.font;
|
||||
match self.book.as_mut() {
|
||||
Some(BookScreen::Edit {
|
||||
signing: true,
|
||||
title,
|
||||
..
|
||||
}) => {
|
||||
Self::append_shortcut(
|
||||
&mut self.text_selection,
|
||||
&mut self.clipboard,
|
||||
BOOK_TITLE,
|
||||
title,
|
||||
shortcut,
|
||||
15,
|
||||
);
|
||||
}
|
||||
Some(BookScreen::Edit { pages, page, .. }) => {
|
||||
// truncateInsertionText counts the whole value, selection included.
|
||||
let room = PAGE_CHARS.saturating_sub(pages[*page].chars().count());
|
||||
self.text_selection.apply(
|
||||
("book.page", *page),
|
||||
&mut pages[*page],
|
||||
shortcut,
|
||||
&mut self.clipboard,
|
||||
|value, pasted| {
|
||||
let text: String = horizon_client::clipboard::filter_text(pasted, true)
|
||||
.chars()
|
||||
.take(room)
|
||||
.collect();
|
||||
let next = format!("{value}{text}");
|
||||
font.split(&Text::literal(&next), 114.0).len() <= LINES && {
|
||||
*value = next;
|
||||
true
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn edit_page(&mut self, f: impl FnOnce(&mut String)) {
|
||||
if let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_mut() {
|
||||
f(&mut pages[*page]);
|
||||
}
|
||||
}
|
||||
/// MultiLineEditBox: characters that keep the page within 14 lines and 1024 characters.
|
||||
fn type_into_page(&mut self, typed: &str) {
|
||||
let Some(BookScreen::Edit { pages, page, .. }) = self.book.as_ref() else {
|
||||
fn book_title_insert(&mut self, text: &str) {
|
||||
let Some(BookScreen::Edit {
|
||||
title, title_edit, ..
|
||||
}) = self.book.as_mut()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut text = pages[*page].clone();
|
||||
for c in typed.chars() {
|
||||
let mut next = text.clone();
|
||||
next.push(c);
|
||||
if next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES {
|
||||
text = next;
|
||||
title_edit.insert_text(text);
|
||||
title.clone_from(&title_edit.value);
|
||||
}
|
||||
/// `BookEditScreen.keyPressed` on the page, apart from the line moves.
|
||||
fn book_page_key(&mut self, key: KeyCode) -> bool {
|
||||
let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
|
||||
let before = match self.book.as_ref() {
|
||||
Some(BookScreen::Edit { page_edit, .. }) => Some((
|
||||
page_edit.value.clone(),
|
||||
page_edit.cursor,
|
||||
page_edit.highlight,
|
||||
)),
|
||||
_ => return false,
|
||||
};
|
||||
let handled = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
|
||||
page_edit.key(key, ctrl, shift)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
self.page_keep(before);
|
||||
}
|
||||
handled
|
||||
}
|
||||
/// One character at a time, so a page stops at the last character that fits.
|
||||
fn page_insert(&mut self, text: &str) {
|
||||
for c in text.chars() {
|
||||
self.page_change(|edit| edit.insert_text(&c.to_string()));
|
||||
}
|
||||
}
|
||||
/// Ctrl+A/C/V/X: the title box while signing, else the page.
|
||||
pub(super) fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
|
||||
let signing = matches!(self.book, Some(BookScreen::Edit { signing: true, .. }));
|
||||
if signing {
|
||||
if let Some(BookScreen::Edit {
|
||||
title, title_edit, ..
|
||||
}) = self.book.as_mut()
|
||||
{
|
||||
title_edit.shortcut(shortcut, &mut self.clipboard);
|
||||
title.clone_from(&title_edit.value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let before = match self.book.as_ref() {
|
||||
Some(BookScreen::Edit { page_edit, .. }) => Some((
|
||||
page_edit.value.clone(),
|
||||
page_edit.cursor,
|
||||
page_edit.highlight,
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
|
||||
page_edit.shortcut(shortcut, &mut self.clipboard);
|
||||
}
|
||||
self.page_keep(before);
|
||||
}
|
||||
/// Edit the page box, then keep it only within 14 lines and 1024 characters.
|
||||
fn page_change(&mut self, f: impl FnOnce(&mut ui::EditBox)) -> bool {
|
||||
let before = match self.book.as_ref() {
|
||||
Some(BookScreen::Edit { page_edit, .. }) => Some((
|
||||
page_edit.value.clone(),
|
||||
page_edit.cursor,
|
||||
page_edit.highlight,
|
||||
)),
|
||||
_ => return false,
|
||||
};
|
||||
let ran = if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
|
||||
f(page_edit);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
ran && self.page_keep(before)
|
||||
}
|
||||
/// Write the page, or put the previous text back when it no longer fits.
|
||||
fn page_keep(&mut self, before: Option<(String, usize, usize)>) -> bool {
|
||||
let next = match self.book.as_ref() {
|
||||
Some(BookScreen::Edit { page_edit, .. }) => page_edit.value.clone(),
|
||||
_ => return false,
|
||||
};
|
||||
let ok = next.chars().count() <= PAGE_CHARS && self.book_lines(&next).len() <= LINES;
|
||||
let Some(BookScreen::Edit {
|
||||
pages,
|
||||
page,
|
||||
page_edit,
|
||||
..
|
||||
}) = self.book.as_mut()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if ok {
|
||||
pages[*page].clone_from(&page_edit.value);
|
||||
} else if let Some((value, cursor, highlight)) = before {
|
||||
page_edit.value = value;
|
||||
page_edit.cursor = cursor;
|
||||
page_edit.highlight = highlight;
|
||||
}
|
||||
ok
|
||||
}
|
||||
/// ArrowUp and ArrowDown move a visual line, keeping the column.
|
||||
fn book_move_line(&mut self, dir: isize) {
|
||||
let shift = self.has_shift_down();
|
||||
let (text, cursor) = match self.book.as_ref() {
|
||||
Some(BookScreen::Edit {
|
||||
pages,
|
||||
page,
|
||||
page_edit,
|
||||
..
|
||||
}) => (pages[*page].clone(), page_edit.cursor),
|
||||
_ => return,
|
||||
};
|
||||
let rows = self.page_rows(&text);
|
||||
let (x, line) = self.caret_on(&text, &rows, cursor);
|
||||
let next = (line as isize + dir).clamp(0, rows.len() as isize - 1) as usize;
|
||||
let (start, end) = rows[next];
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let slice: String = chars[start..end].iter().collect();
|
||||
let pos = start + self.gui.atlas.font.fit(&slice, x);
|
||||
if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
|
||||
page_edit.set_cursor(pos, shift);
|
||||
}
|
||||
}
|
||||
/// Wrapped rows of a page as character ranges, the same breaks as `font.split`.
|
||||
fn page_rows(&self, page: &str) -> Vec<(usize, usize)> {
|
||||
let font = &self.gui.atlas.font;
|
||||
let chars: Vec<char> = page.chars().collect();
|
||||
let mut rows = Vec::new();
|
||||
let mut start = 0;
|
||||
while start < chars.len() {
|
||||
let mut end = chars.len();
|
||||
let mut next = chars.len();
|
||||
let mut last_space = None;
|
||||
for i in start..chars.len() {
|
||||
if chars[i] == '\n' {
|
||||
end = i;
|
||||
next = i + 1;
|
||||
break;
|
||||
}
|
||||
if chars[i] == ' ' {
|
||||
last_space = Some(i);
|
||||
}
|
||||
let slice: String = chars[start..=i].iter().collect();
|
||||
if font.width(&slice) > 114.0 {
|
||||
match last_space {
|
||||
Some(s) if s > start => {
|
||||
end = s;
|
||||
next = s + 1;
|
||||
}
|
||||
_ => {
|
||||
end = i.max(start + 1);
|
||||
next = end;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
rows.push((start, end));
|
||||
start = next;
|
||||
if start == chars.len() && chars.last() == Some(&'\n') {
|
||||
rows.push((chars.len(), chars.len()));
|
||||
}
|
||||
}
|
||||
self.edit_page(|p| *p = text);
|
||||
if rows.is_empty() {
|
||||
rows.push((0, 0));
|
||||
}
|
||||
rows
|
||||
}
|
||||
/// GUI x of the caret and the row it sits on.
|
||||
fn caret_on(&self, page: &str, rows: &[(usize, usize)], cursor: usize) -> (f32, usize) {
|
||||
let chars: Vec<char> = page.chars().collect();
|
||||
for (i, &(start, end)) in rows.iter().enumerate() {
|
||||
if cursor <= end || i + 1 == rows.len() {
|
||||
let take = cursor.saturating_sub(start).min(end.saturating_sub(start));
|
||||
let prefix: String = chars.iter().skip(start).take(take).collect();
|
||||
return (self.gui.atlas.font.width(&prefix), i);
|
||||
}
|
||||
}
|
||||
(0.0, 0)
|
||||
}
|
||||
fn page_index_at(&self, page: &str, local_x: f32, local_y: f32) -> usize {
|
||||
let rows = self.page_rows(page);
|
||||
let line = (local_y / 9.0).floor().max(0.0) as usize;
|
||||
let line = line.min(rows.len().saturating_sub(1));
|
||||
let (start, end) = rows[line];
|
||||
let chars: Vec<char> = page.chars().collect();
|
||||
let slice: String = chars[start..end].iter().collect();
|
||||
start + self.gui.atlas.font.fit(&slice, local_x.max(0.0))
|
||||
}
|
||||
/// A click on the centred title (`EditBox.onClick`).
|
||||
fn book_title_click(&mut self, field_x: f32, mx: f32) {
|
||||
let shift = self.has_shift_down();
|
||||
let Some(BookScreen::Edit {
|
||||
title, title_edit, ..
|
||||
}) = self.book.as_mut()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let tx = field_x + ((114.0 - self.gui.atlas.font.width(title)) / 2.0).floor();
|
||||
let rel = (mx - tx).max(0.0);
|
||||
let pos = self.gui.atlas.font.fit(title, rel);
|
||||
title_edit.set_cursor(pos, shift);
|
||||
}
|
||||
/// A click on the open page.
|
||||
fn book_page_click(&mut self, origin_x: f32, origin_y: f32, mx: f32, my: f32) {
|
||||
let shift = self.has_shift_down();
|
||||
let text = match self.book.as_ref() {
|
||||
Some(BookScreen::Edit { pages, page, .. }) => pages[*page].clone(),
|
||||
_ => return,
|
||||
};
|
||||
let pos = self.page_index_at(&text, mx - origin_x, my - origin_y);
|
||||
if let Some(BookScreen::Edit { page_edit, .. }) = self.book.as_mut() {
|
||||
page_edit.set_cursor(pos, shift);
|
||||
}
|
||||
}
|
||||
/// The page buttons (`pageForward` adds a page while editing).
|
||||
fn turn_page(&mut self, forward: bool) {
|
||||
let mut lectern_page = None;
|
||||
match self.book.as_mut() {
|
||||
Some(BookScreen::Edit { pages, page, .. }) => {
|
||||
Some(BookScreen::Edit {
|
||||
pages,
|
||||
page,
|
||||
page_edit,
|
||||
..
|
||||
}) => {
|
||||
let before = *page;
|
||||
if forward {
|
||||
if *page + 1 >= pages.len() && pages.len() < MAX_PAGES {
|
||||
pages.push(String::new());
|
||||
@@ -405,6 +564,10 @@ impl Game<'_> {
|
||||
} else if *page > 0 {
|
||||
*page -= 1;
|
||||
}
|
||||
if *page != before {
|
||||
let text = pages[*page].clone();
|
||||
page_edit.set_value(&text);
|
||||
}
|
||||
}
|
||||
Some(BookScreen::View {
|
||||
lectern: Some(key), ..
|
||||
@@ -764,6 +927,8 @@ impl Game<'_> {
|
||||
if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() {
|
||||
*signing = false;
|
||||
}
|
||||
} else if inside(left + 36.0, 50.0, 114.0, 9.0) {
|
||||
self.book_title_click(left + 36.0, mx);
|
||||
}
|
||||
}
|
||||
Some(BookScreen::Edit { page, .. }) => {
|
||||
@@ -780,6 +945,8 @@ impl Game<'_> {
|
||||
} else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) {
|
||||
click(self);
|
||||
self.save_book(false);
|
||||
} else if inside(left + 36.0, 32.0, 114.0, 14.0 * 9.0) {
|
||||
self.book_page_click(left + 36.0, 32.0, mx, my);
|
||||
}
|
||||
}
|
||||
Some(BookScreen::View {
|
||||
@@ -865,7 +1032,7 @@ impl Game<'_> {
|
||||
BookScreen::Edit {
|
||||
signing: true,
|
||||
title,
|
||||
opened,
|
||||
title_edit,
|
||||
..
|
||||
} => {
|
||||
let edit = tr("book.editTitle", "Enter Book Title:");
|
||||
@@ -881,19 +1048,35 @@ impl Game<'_> {
|
||||
// The title box: an unbordered, centred EditBox of 114 with
|
||||
// black text and no shadow; the value alone is centred, the
|
||||
// cursor follows it.
|
||||
let value = &title_edit.value;
|
||||
let x = left + 36.0;
|
||||
let tx = x + ((114.0 - HudBatch::text_width(atlas, title)) / 2.0).floor();
|
||||
horizon_client::ui::append_field(
|
||||
batch,
|
||||
atlas,
|
||||
title,
|
||||
(tx, 50.0, x + 114.0 - tx),
|
||||
(BLACK, false),
|
||||
15,
|
||||
self.text_selection.covers(BOOK_TITLE, title),
|
||||
true,
|
||||
opened.elapsed().as_millis(),
|
||||
);
|
||||
let tx = x + ((114.0 - HudBatch::text_width(atlas, value)) / 2.0).floor();
|
||||
batch.text(atlas, value, tx, 50.0, BLACK, false);
|
||||
if title_edit.cursor != title_edit.highlight {
|
||||
let (a, b) = (
|
||||
title_edit.cursor.min(title_edit.highlight),
|
||||
title_edit.cursor.max(title_edit.highlight),
|
||||
);
|
||||
let pre: String = value.chars().take(a).collect();
|
||||
let sel: String = value.chars().skip(a).take(b - a).collect();
|
||||
let sx = tx + HudBatch::text_width(atlas, &pre);
|
||||
batch.text_highlight(
|
||||
atlas,
|
||||
(sx, 49.0, HudBatch::text_width(atlas, &sel), 11.0),
|
||||
true,
|
||||
);
|
||||
}
|
||||
if title_edit.cursor_visible() {
|
||||
let pre: String = value.chars().take(title_edit.cursor).collect();
|
||||
batch.fill(
|
||||
atlas,
|
||||
tx + HudBatch::text_width(atlas, &pre),
|
||||
49.0,
|
||||
1.0,
|
||||
9.0,
|
||||
BLACK,
|
||||
);
|
||||
}
|
||||
let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME);
|
||||
let tw = HudBatch::text_width(atlas, &by);
|
||||
batch.text(
|
||||
@@ -941,12 +1124,12 @@ impl Game<'_> {
|
||||
BookScreen::Edit {
|
||||
pages,
|
||||
page,
|
||||
opened,
|
||||
page_edit,
|
||||
..
|
||||
} => {
|
||||
indicator(batch, *page, pages.len());
|
||||
let blink = (opened.elapsed().as_millis() / 300) % 2 == 0;
|
||||
let lines = self.book_lines(&pages[*page]);
|
||||
let text = &pages[*page];
|
||||
let lines = self.book_lines(text);
|
||||
for (i, line) in lines.iter().take(LINES).enumerate() {
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
@@ -957,27 +1140,39 @@ impl Game<'_> {
|
||||
false,
|
||||
);
|
||||
}
|
||||
if blink {
|
||||
// The cursor after the last character.
|
||||
let last = lines
|
||||
.last()
|
||||
.map(|l| atlas.font.width_text(l))
|
||||
.unwrap_or(0.0);
|
||||
let row = lines.len().saturating_sub(1) as f32
|
||||
+ if pages[*page].ends_with('\n') {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let x = if pages[*page].ends_with('\n') {
|
||||
0.0
|
||||
} else {
|
||||
last
|
||||
};
|
||||
let rows = self.page_rows(text);
|
||||
let (sel_a, sel_b) = (
|
||||
page_edit.cursor.min(page_edit.highlight),
|
||||
page_edit.cursor.max(page_edit.highlight),
|
||||
);
|
||||
if sel_a != sel_b {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
for (i, &(start, end)) in rows.iter().enumerate().take(LINES) {
|
||||
let from = sel_a.max(start);
|
||||
let to = sel_b.min(end);
|
||||
if from >= to {
|
||||
continue;
|
||||
}
|
||||
let pre: String = chars[start..from].iter().collect();
|
||||
let sel: String = chars[from..to].iter().collect();
|
||||
batch.text_highlight(
|
||||
atlas,
|
||||
(
|
||||
left + 36.0 + atlas.font.width(&pre),
|
||||
top + 29.0 + i as f32 * 9.0,
|
||||
atlas.font.width(&sel),
|
||||
9.0,
|
||||
),
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
if page_edit.cursor_visible() {
|
||||
let (x, row) = self.caret_on(text, &rows, page_edit.cursor);
|
||||
batch.fill(
|
||||
atlas,
|
||||
left + 36.0 + x,
|
||||
top + 29.0 + row * 9.0,
|
||||
top + 29.0 + row as f32 * 9.0,
|
||||
1.0,
|
||||
9.0,
|
||||
BLACK,
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Campfires' cooking: `CampfireBlock.useItemOn` (`CampfireBlockEntity.placeFood`)
|
||||
//! and the block entity's `cookTick` (lit) and `cooldownTick` (unlit). The
|
||||
//! items drawn on the fire are `campfire_geometry`'s; a server's clients get
|
||||
//! them through the block entity's update tag (`lan::chunks::entity_tag`).
|
||||
use super::Game;
|
||||
use horizon_assets::item_model::DisplayContext;
|
||||
use horizon_client::{
|
||||
Result, block_entities::Pos, block_entity_render::vertex_light, containers::BlockEntity,
|
||||
items::ItemStack, mesher::Vertex, mobs::Who,
|
||||
};
|
||||
use horizon_core::position::BlockPos;
|
||||
|
||||
/// The `campfire_cooking` recipe kind (`RecipeType.CAMPFIRE_COOKING`).
|
||||
const KIND: &str = "minecraft:campfire_cooking";
|
||||
|
||||
fn is_campfire(name: &str) -> bool {
|
||||
name == "minecraft:campfire" || name == "minecraft:soul_campfire"
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `CampfireBlock.useItemOn` with a held item that is a campfire recipe's
|
||||
/// input (`RecipePropertySet.CAMPFIRE_INPUT`): on a server level the food
|
||||
/// goes into the first free slot (`placeFood`), and the use is consumed
|
||||
/// whether or not there was room. A client of a server leaves the placing
|
||||
/// to the server. Whether the food went in; None when this isn't a
|
||||
/// campfire use, so the item's own use runs.
|
||||
pub(super) fn use_on_campfire(&mut self, pos: [i32; 3]) -> Result<Option<bool>> {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
if !is_campfire(&self.res.facts().get(state).name) {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(held) = self.held().cloned() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(time) = self.res.recipes().cook(KIND, &held).map(|r| r.time as i32) else {
|
||||
return Ok(None);
|
||||
};
|
||||
// A client of a server predicts the placing; the server decides.
|
||||
if self.remote.is_some() {
|
||||
return Ok(Some(true));
|
||||
}
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let placed = match self.world.block_entities.get_mut(&key) {
|
||||
Some(BlockEntity::Campfire(c)) => {
|
||||
let mut one = held.clone();
|
||||
c.place_food(&mut one, time)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if placed {
|
||||
// ItemStack.consumeAndReturn: creative keeps the item.
|
||||
self.consume_held();
|
||||
self.stats.custom("interact_with_campfire", 1);
|
||||
self.post_block_game_event(
|
||||
"minecraft:block_change",
|
||||
pos,
|
||||
Some(Who::Player),
|
||||
Some(state),
|
||||
);
|
||||
self.mark_block_entity_updated(key);
|
||||
}
|
||||
Ok(Some(placed))
|
||||
}
|
||||
|
||||
/// `CampfireBlockEntity.cookTick` of a lit campfire, `cooldownTick` of an
|
||||
/// unlit one. A finished item's result (the recipe's, or the item itself
|
||||
/// when no recipe takes it any more) drops at the block's corner
|
||||
/// (`Containers.dropItemStack` at its integer position), then the clients
|
||||
/// see the slot empty and a `block_change` goes out.
|
||||
pub(super) fn tick_campfire(&mut self, pos: Pos) -> Result<()> {
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let lit = self
|
||||
.pack
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("lit"))
|
||||
.is_some_and(|v| v == "true");
|
||||
let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
|
||||
return Ok(());
|
||||
};
|
||||
// BlockEntity.setChanged: a timer that moved is saved with the
|
||||
// chunk (no update to the clients, who don't see the timers).
|
||||
let changed = if lit {
|
||||
c.items.iter().any(Option::is_some)
|
||||
} else {
|
||||
c.cooldown_tick()
|
||||
};
|
||||
if changed {
|
||||
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
|
||||
}
|
||||
if !lit {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(BlockEntity::Campfire(c)) = self.world.block_entities.get_mut(&pos) else {
|
||||
return Ok(());
|
||||
};
|
||||
let done = c.cook_tick();
|
||||
for (_, item) in done {
|
||||
let result = self
|
||||
.res
|
||||
.recipes()
|
||||
.cook(KIND, &item)
|
||||
.map_or_else(|| item.clone(), |r| r.result.clone());
|
||||
self.campfire_drop(pos, result);
|
||||
self.mark_block_entity_updated(pos);
|
||||
self.post_block_game_event(
|
||||
"minecraft:block_change",
|
||||
[pos.0, pos.1, pos.2],
|
||||
None,
|
||||
Some(state),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `CampfireRenderer`: each cooking item lies on the fire, slot `i`
|
||||
/// turned to `Direction.from2DDataValue((i + facing) % 4)`, laid flat
|
||||
/// (90° about X), at a corner and three eighths of its size, drawn as a
|
||||
/// FIXED item seeded by the block's position plus the slot.
|
||||
pub(super) fn campfire_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
|
||||
for (key, entity) in &self.world.block_entities {
|
||||
let BlockEntity::Campfire(c) = entity else {
|
||||
continue;
|
||||
};
|
||||
if c.items.iter().all(Option::is_none) {
|
||||
continue;
|
||||
}
|
||||
let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
|
||||
if at.distance_squared(camera) >= 64.0 * 64.0 {
|
||||
continue;
|
||||
}
|
||||
// Direction.get2DDataValue: south 0, west 1, north 2, east 3.
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
let facing = match self
|
||||
.pack
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("facing"))
|
||||
.map(String::as_str)
|
||||
{
|
||||
Some("west") => 1,
|
||||
Some("north") => 2,
|
||||
Some("east") => 3,
|
||||
_ => 0,
|
||||
};
|
||||
let light = vertex_light(self.world.light(key.0, key.1, key.2));
|
||||
let packed = BlockPos::new(key.0, key.1, key.2).pack();
|
||||
for (i, stack) in c.items.iter().enumerate() {
|
||||
let Some(stack) = stack else {
|
||||
continue;
|
||||
};
|
||||
let seed = (packed as i32).wrapping_add(i as i32);
|
||||
let item = self.resolve_item(stack, DisplayContext::Fixed, None, seed);
|
||||
if item.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Direction.toYRot: 90° per 2D step from south.
|
||||
let yaw = -(((i + facing) % 4) as f32 * 90.0);
|
||||
let pose = glam::Mat4::from_translation(
|
||||
(at - camera).as_vec3() + glam::Vec3::new(0.5, 0.449_218_75, 0.5),
|
||||
) * glam::Mat4::from_rotation_y(yaw.to_radians())
|
||||
* glam::Mat4::from_rotation_x(90f32.to_radians())
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(-0.3125, -0.3125, 0.0))
|
||||
* glam::Mat4::from_scale(glam::Vec3::splat(0.375));
|
||||
self.submit_item_world(&item, pose, light, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Containers.dropItemStack(level, x, y, z, stack)` at the block's
|
||||
/// integer position.
|
||||
fn campfire_drop(&mut self, pos: Pos, stack: ItemStack) {
|
||||
let at = BlockPos::new(pos.0, pos.1, pos.2);
|
||||
for piece in
|
||||
horizon_world::level::removal::drop_item_stack(&mut self.world.random, at, stack.count)
|
||||
{
|
||||
self.spawn_item(
|
||||
ItemStack {
|
||||
count: piece.count,
|
||||
..stack.clone()
|
||||
},
|
||||
piece.pos,
|
||||
piece.motion,
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,8 +63,8 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Typing or a backspace in a field of the title screens: in the server
|
||||
/// screens' append-only fields Select All's selection is replaced first.
|
||||
/// Typing or a backspace in a title-screen field. A field that still only
|
||||
/// appends replaces a Select All selection before the edit.
|
||||
pub(super) fn title_edit(&mut self, typed: Option<&str>, backspace: bool) {
|
||||
let Some(title) = self.title.as_mut() else {
|
||||
return;
|
||||
@@ -86,42 +86,31 @@ impl Game<'_> {
|
||||
}
|
||||
/// Shortcuts in the creative inventory's search box (an `EditBox` of 50).
|
||||
pub(super) fn creative_search_shortcut(&mut self, shortcut: EditShortcut) {
|
||||
if Self::append_shortcut(
|
||||
&mut self.text_selection,
|
||||
&mut self.clipboard,
|
||||
CREATIVE_SEARCH,
|
||||
&mut self.creative_screen.search,
|
||||
shortcut,
|
||||
CREATIVE_SEARCH_CHARS,
|
||||
) {
|
||||
if self
|
||||
.creative_screen
|
||||
.search
|
||||
.shortcut(shortcut, &mut self.clipboard)
|
||||
{
|
||||
self.creative_screen.scroll = 0.0;
|
||||
}
|
||||
}
|
||||
/// A backspace in the creative search box: with Ctrl, the whole word
|
||||
/// before the caret (`EditBox.deleteWords(-1)`), otherwise one character.
|
||||
/// A Select All selection is what it deletes, as in `EditBox.keyPressed`.
|
||||
/// A selection is what it deletes, as in `EditBox.keyPressed`.
|
||||
pub(super) fn creative_search_backspace(&mut self, ctrl: bool) {
|
||||
let search = &mut self.creative_screen.search;
|
||||
if !self.text_selection.take(CREATIVE_SEARCH, search) {
|
||||
if ctrl {
|
||||
horizon_client::ui::delete_words(search, -1);
|
||||
} else {
|
||||
search.pop();
|
||||
}
|
||||
}
|
||||
self.creative_screen
|
||||
.search
|
||||
.key(KeyCode::Backspace, ctrl, false);
|
||||
self.creative_screen.scroll = 0.0;
|
||||
}
|
||||
/// Typing in the creative search box.
|
||||
pub(super) fn creative_search_edit(&mut self, typed: Option<&str>) {
|
||||
let search = &mut self.creative_screen.search;
|
||||
self.text_selection.take(CREATIVE_SEARCH, search);
|
||||
if let Some(text) = typed {
|
||||
clipboard::append_limited(search, text, CREATIVE_SEARCH_CHARS);
|
||||
self.creative_screen.search.insert_text(text);
|
||||
self.creative_screen.scroll = 0.0;
|
||||
}
|
||||
self.creative_screen.scroll = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// `CreativeModeInventoryScreen`'s search box: `setMaxLength(50)`.
|
||||
pub(super) const CREATIVE_SEARCH_CHARS: usize = 50;
|
||||
pub(super) const CREATIVE_SEARCH: horizon_client::clipboard::FieldId = ("creative.search", 0);
|
||||
|
||||
@@ -50,9 +50,9 @@ pub(super) struct Creatures {
|
||||
/// The wandering trader spawner's clock.
|
||||
pub trader: super::wandering_trader::Spawner,
|
||||
}
|
||||
struct ProjWorld<'a, 'w> {
|
||||
w: &'a MobWorld<'w>,
|
||||
targets: Vec<(Who, Aabb)>,
|
||||
pub(super) struct ProjWorld<'a, 'w> {
|
||||
pub w: &'a MobWorld<'w>,
|
||||
pub targets: Vec<(Who, Aabb)>,
|
||||
}
|
||||
impl ProjectileWorld for ProjWorld<'_, '_> {
|
||||
fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> {
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
//! Cushions: `CushionItem.useOn` placement on the top face of a block,
|
||||
//! `Cushion.canBePlacedAt`/`survives`, `Cushion.interact` (sit),
|
||||
//! `BlockAttachedEntity.hurtServer` (break, dropping the matching colour),
|
||||
//! `BlockAttachedEntity.tick` and `CushionRenderer`.
|
||||
//!
|
||||
//! A cushion is a `BlockAttachedEntity`, not a block: it has no block state,
|
||||
//! only an entity whose `Pos` is the click point's height. Placement uses
|
||||
//! outline bounds, collision shapes and suffocation predicates.
|
||||
use super::{Game, Hit, view_vector};
|
||||
use horizon_client::entities::{Cushion, dye_index};
|
||||
use horizon_client::items::ItemStack;
|
||||
use horizon_client::mobs::anim::Poses;
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
/// `Direction.fromYRot(yaw).toYRot()`: the nearest 90 degree step.
|
||||
pub(crate) fn snap_yaw(yaw: f32) -> f32 {
|
||||
(((f64::from(yaw) / 90.0 + 0.5).floor() as i64) & 3) as f32 * 90.0
|
||||
}
|
||||
|
||||
fn aabb(bounds: ([f64; 3], [f64; 3])) -> Aabb {
|
||||
Aabb::new(
|
||||
Vec3::new(bounds.0[0], bounds.0[1], bounds.0[2]),
|
||||
Vec3::new(bounds.1[0], bounds.1[1], bounds.1[2]),
|
||||
)
|
||||
}
|
||||
|
||||
fn overlaps(a: Aabb, b: Aabb) -> bool {
|
||||
a.intersects(b)
|
||||
}
|
||||
use horizon_client::cushion::blocks_in;
|
||||
|
||||
struct PlacementWorld<'a, 'r>(&'a Game<'r>);
|
||||
impl horizon_client::cushion::World for PlacementWorld<'_, '_> {
|
||||
fn outline_bounds(&self, p: [i32; 3]) -> Option<Aabb> {
|
||||
let boxes = self.0.outline_boxes(p);
|
||||
let mut shape = *boxes.first()?;
|
||||
for b in &boxes[1..] {
|
||||
for k in 0..3 {
|
||||
shape[k] = shape[k].min(b[k]);
|
||||
shape[k + 3] = shape[k + 3].max(b[k + 3]);
|
||||
}
|
||||
}
|
||||
Some(Aabb::new(
|
||||
Vec3::new(shape[0], shape[1], shape[2]),
|
||||
Vec3::new(shape[3], shape[4], shape[5]),
|
||||
))
|
||||
}
|
||||
|
||||
fn collision_shapes(&self, bounds: Aabb) -> Vec<horizon_core::geometry::VoxelShape> {
|
||||
let binding = self.0.res.collision();
|
||||
let mut world = horizon_client::collisions::SceneCollisions {
|
||||
world: &self.0.world,
|
||||
binding,
|
||||
subject: None,
|
||||
};
|
||||
// Include neighbour blocks whose collision shape can reach outside their cell.
|
||||
blocks_in(bounds.inflate(Vec3::new(1.0, 1.0, 1.0)))
|
||||
.filter_map(|p| {
|
||||
let state = self.0.world.block(p[0], p[1], p[2]);
|
||||
binding
|
||||
.collision_shape(&mut world, state, p)
|
||||
.ok()
|
||||
.map(|s| s.moved(Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn suffocating(&self, p: [i32; 3]) -> bool {
|
||||
let state = self.0.world.block(p[0], p[1], p[2]);
|
||||
let facts = self.0.res.facts().get(state);
|
||||
let name = facts.name.as_ref();
|
||||
// Blocks' explicit predicates, then the default causes_suffocation/full-shape rule.
|
||||
match name {
|
||||
"minecraft:dirt_path"
|
||||
| "minecraft:farmland"
|
||||
| "minecraft:mud"
|
||||
| "minecraft:soul_sand" => true,
|
||||
"minecraft:piston" | "minecraft:sticky_piston" => self
|
||||
.0
|
||||
.pack
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.is_some_and(|s| s.properties.get("extended").is_some_and(|p| p == "false")),
|
||||
"minecraft:mangrove_roots" | "minecraft:moving_piston" => false,
|
||||
_ if name.ends_with("_leaves")
|
||||
|| name.ends_with("glass")
|
||||
|| name.ends_with("copper_grate") =>
|
||||
{
|
||||
false
|
||||
}
|
||||
// ShulkerBoxBlock: suffocating while closed; a box seen open
|
||||
// here is rare enough to count as closed.
|
||||
_ if name.ends_with("shulker_box") => true,
|
||||
_ => {
|
||||
facts.full_collision
|
||||
&& self
|
||||
.0
|
||||
.res
|
||||
.items()
|
||||
.block_in_tag("minecraft:causes_suffocation", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The cushion under the crosshair, its distance and the hit point.
|
||||
pub(super) fn cushion_hit(&self) -> Option<(usize, f64, [f64; 3])> {
|
||||
let eye = self.eye_position()?;
|
||||
let dir = view_vector(self.yaw, self.pitch);
|
||||
let reach: f64 = if self.creative { 5.0 } else { 3.0 };
|
||||
let mut best: Option<(usize, f64, [f64; 3])> = None;
|
||||
for (i, c) in self.cushions.iter().enumerate() {
|
||||
let Some(d) = super::ray_box(eye, dir, reach, aabb(c.bounds())) else {
|
||||
continue;
|
||||
};
|
||||
if best.is_none_or(|b| d < b.1) {
|
||||
best = Some((i, d, std::array::from_fn(|k| eye[k] + dir[k] * d)));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
pub(super) fn cushion_survives(&self, c: &Cushion) -> bool {
|
||||
horizon_client::cushion::survives(&PlacementWorld(self), aabb(c.bounds()))
|
||||
}
|
||||
|
||||
/// `Cushion.destroyIfInFire`: a fire-tagged block inside the deflated box.
|
||||
fn cushion_in_fire(&self, c: &Cushion) -> bool {
|
||||
let bounds = aabb(c.bounds()).next_deflated();
|
||||
blocks_in(bounds).any(|p| {
|
||||
let facts = self.res.facts().get(self.world.block(p[0], p[1], p[2]));
|
||||
self.res.items().block_in_tag("minecraft:fire", &facts.name)
|
||||
})
|
||||
}
|
||||
|
||||
/// `CushionItem.useOn`: on the top face only, spawning at the click's
|
||||
/// height above the clicked block (or the replaceable block itself).
|
||||
pub(super) fn place_cushion(&mut self, hit: &Hit, stack: &ItemStack) -> bool {
|
||||
let Some(info) = self.res.items().get(&stack.item).cloned() else {
|
||||
return false;
|
||||
};
|
||||
let Some(default_color) = info.cushion_color.as_deref() else {
|
||||
return false;
|
||||
};
|
||||
let color_override = stack
|
||||
.data()
|
||||
.and_then(|d| d.other("minecraft:cushion/color"))
|
||||
.and_then(|tag| match tag {
|
||||
horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
});
|
||||
let color = dye_index(color_override.as_deref().unwrap_or(default_color));
|
||||
// CushionItem.recalculateContextForSpecialCollisionShapes: open containers
|
||||
// (cauldrons, hoppers and composters) use the collision ray's actual height.
|
||||
let mut adjusted = Hit {
|
||||
pos: hit.pos,
|
||||
face: hit.face,
|
||||
point: hit.point,
|
||||
};
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
if self.res.items().block_in_tag(
|
||||
"minecraft:cushion_uses_collision_shape",
|
||||
&self.res.facts().get(state).name,
|
||||
) && let Some(eye) = self.eye_position()
|
||||
{
|
||||
let start = Vec3::new(eye[0], eye[1], eye[2]);
|
||||
let point = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
|
||||
let end = point.add_vector(point.subtract(start).normalize().scale(0.001));
|
||||
let binding = self.res.collision();
|
||||
let mut world = horizon_client::collisions::SceneCollisions {
|
||||
world: &self.world,
|
||||
binding,
|
||||
subject: None,
|
||||
};
|
||||
if let Ok(shape) = binding.collision_shape(&mut world, state, hit.pos)
|
||||
&& let Some(result) = shape.clip(
|
||||
start,
|
||||
end,
|
||||
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
|
||||
)
|
||||
{
|
||||
adjusted.face = result.direction.normal();
|
||||
adjusted.point = [result.location.x, result.location.y, result.location.z];
|
||||
}
|
||||
}
|
||||
let hit = &adjusted;
|
||||
if hit.face != [0, 1, 0] {
|
||||
return false;
|
||||
}
|
||||
// BlockPlaceContext: a replaceable clicked block is replaced.
|
||||
let clicked = self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]));
|
||||
let pos = if clicked.replaceable {
|
||||
hit.pos
|
||||
} else {
|
||||
std::array::from_fn(|i| hit.pos[i] + hit.face[i])
|
||||
};
|
||||
// `Vec3.atCenterOfWithY(clickedPos, clickLocation.y)`.
|
||||
let y = hit.point[1];
|
||||
let position = Vec3::new(f64::from(pos[0]) + 0.5, y, f64::from(pos[2]) + 0.5);
|
||||
let bounds = aabb((
|
||||
[position.x - 0.5, position.y, position.z - 0.5],
|
||||
[position.x + 0.5, position.y + 0.25, position.z + 0.5],
|
||||
));
|
||||
if !horizon_client::cushion::can_place(&PlacementWorld(self), bounds) {
|
||||
return false;
|
||||
}
|
||||
// `getEntitiesOfClass(Cushion.class, spawnAABB).isEmpty()`.
|
||||
if self
|
||||
.cushions
|
||||
.iter()
|
||||
.any(|c| overlaps(aabb(c.bounds()), bounds))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.next_entity += 1;
|
||||
let id = self.next_entity;
|
||||
// `BlockAttachedEntity.setPos`: `BlockPos.containing(position)`.
|
||||
let attached = [
|
||||
position.x.floor() as i32,
|
||||
position.y.floor() as i32,
|
||||
position.z.floor() as i32,
|
||||
];
|
||||
self.cushions.push(Cushion {
|
||||
id,
|
||||
position,
|
||||
pos: attached,
|
||||
yaw: snap_yaw(self.yaw),
|
||||
color,
|
||||
check_interval: 0,
|
||||
});
|
||||
self.world
|
||||
.modified
|
||||
.insert((attached[0] >> 4, attached[2] >> 4));
|
||||
// `destroyIfInFire`: placed into fire, it breaks at once.
|
||||
let placed = self.cushions.len() - 1;
|
||||
if self.cushion_in_fire(&self.cushions[placed]) {
|
||||
self.break_cushion(placed, false);
|
||||
}
|
||||
self.audio.play(
|
||||
"minecraft:entity.cushion.place",
|
||||
Some([position.x, position.y, position.z]),
|
||||
0.75,
|
||||
0.8,
|
||||
);
|
||||
let ctx = self.who_context(Some(horizon_client::mobs::Who::Player), None);
|
||||
self.post_game_event(
|
||||
"minecraft:entity_place",
|
||||
[position.x, position.y, position.z],
|
||||
ctx,
|
||||
);
|
||||
if !self.creative {
|
||||
self.consume_held();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `Cushion.interact`: sit down unless sneaking or already occupied.
|
||||
pub(super) fn interact_cushion(&mut self) -> bool {
|
||||
let Some((i, d, _)) = self.cushion_hit() else {
|
||||
return false;
|
||||
};
|
||||
if !self.before_block(d) {
|
||||
return false;
|
||||
}
|
||||
// isSecondaryUseActive.
|
||||
if self.keys.contains(&KeyCode::ShiftLeft) {
|
||||
return false;
|
||||
}
|
||||
let id = self.cushions[i].id;
|
||||
let occupied = self.riding == Some(id)
|
||||
|| self
|
||||
.lan
|
||||
.as_ref()
|
||||
.is_some_and(|h| h.hub.guests.iter().any(|g| g.vehicle == Some(id)));
|
||||
// `Cushion.interact`: an occupied cushion (`isVehicle`) passes.
|
||||
if occupied {
|
||||
return false;
|
||||
}
|
||||
// `Player.startRiding` gives up the vehicle it already has; the
|
||||
// client never sends that click, so pass instead.
|
||||
if self.riding.is_some() {
|
||||
return false;
|
||||
}
|
||||
self.riding = Some(id);
|
||||
let p = self.cushions[i].position;
|
||||
self.audio.play(
|
||||
"minecraft:entity.cushion.sit",
|
||||
Some([p.x, p.y, p.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
|
||||
/// `Cushion.hurtServer` from a player: killed, then the item dropped.
|
||||
pub(super) fn attack_cushion(&mut self) -> bool {
|
||||
let Some((i, d, _)) = self.cushion_hit() else {
|
||||
return false;
|
||||
};
|
||||
if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) {
|
||||
return false;
|
||||
}
|
||||
// `skipAttackInteraction` when `mayInteract` is false.
|
||||
if !self.may_build() {
|
||||
return true;
|
||||
}
|
||||
self.break_cushion(i, true);
|
||||
true
|
||||
}
|
||||
|
||||
/// `Cushion.dropItem`: the break sound and particles, then the coloured
|
||||
/// item unless drops are off or the breaker has infinite materials.
|
||||
pub(super) fn break_cushion(&mut self, index: usize, by_player: bool) {
|
||||
let c = self.cushions.remove(index);
|
||||
let p = c.position;
|
||||
self.world.modified.insert((c.pos[0] >> 4, c.pos[2] >> 4));
|
||||
if self.riding == Some(c.id) {
|
||||
self.riding = None;
|
||||
}
|
||||
self.audio.play(
|
||||
"minecraft:entity.cushion.break",
|
||||
Some([p.x, p.y, p.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
self.cushion_break_particles(&c);
|
||||
if !self.ui.rules.bool("entity_drops") || (by_player && self.creative) {
|
||||
return;
|
||||
}
|
||||
let stack = ItemStack {
|
||||
item: std::sync::Arc::from(c.item()),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
};
|
||||
self.spawn_item(stack, [p.x, p.y, p.z], [0.0; 3], 10);
|
||||
}
|
||||
|
||||
/// `Cushion.showBreakingParticles`: ten of the matching wool block.
|
||||
fn cushion_break_particles(&mut self, c: &Cushion) {
|
||||
let name = format!("minecraft:{}_wool", c.color_name());
|
||||
let Some(state) = self.pack.assets.registry.default_state(&name) else {
|
||||
return;
|
||||
};
|
||||
let at = [
|
||||
c.position.x.floor() as i32,
|
||||
c.position.y.floor() as i32,
|
||||
c.position.z.floor() as i32,
|
||||
];
|
||||
let Some((sprite, tint)) = self.particle_sprite(state, at) else {
|
||||
return;
|
||||
};
|
||||
let options = horizon_client::particles::ParticleOptions::block(
|
||||
horizon_client::particles::ParticleType::Block,
|
||||
sprite,
|
||||
tint,
|
||||
);
|
||||
let p = c.position;
|
||||
self.particles.send_particles(
|
||||
&options,
|
||||
[p.x, p.y + 0.666_666_7, p.z],
|
||||
[0.25, 0.0625, 0.25],
|
||||
0.05,
|
||||
10,
|
||||
);
|
||||
}
|
||||
|
||||
/// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100.
|
||||
pub(super) fn tick_cushions(&mut self) {
|
||||
let ticking = self.entity_ticking_area();
|
||||
let mut i = 0;
|
||||
while i < self.cushions.len() {
|
||||
let p = self.cushions[i].position;
|
||||
if !ticking(p.x.floor() as i32, p.z.floor() as i32) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let previous = self.cushions[i].check_interval;
|
||||
self.cushions[i].check_interval += 1;
|
||||
if previous < 100 {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
self.cushions[i].check_interval = 0;
|
||||
let c = self.cushions[i].clone();
|
||||
if self.cushion_in_fire(&c) || !self.cushion_survives(&c) {
|
||||
self.break_cushion(i, false);
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// `Player.rideTick` on a cushion: hold the seat, and get up on sneak.
|
||||
pub(super) fn tick_cushion_riding(&mut self, keys: super::Keys) -> bool {
|
||||
let Some(c) = self
|
||||
.cushions
|
||||
.iter()
|
||||
.find(|c| Some(c.id) == self.riding)
|
||||
.cloned()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if keys.shift {
|
||||
let at = c.dismount();
|
||||
self.riding = None;
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
self.previous_position = p.position;
|
||||
p.position = at;
|
||||
p.velocity = Vec3::ZERO;
|
||||
p.fall_distance = 0.0;
|
||||
}
|
||||
// `Cushion.removePassenger`: the get-up sound for a rider that
|
||||
// left rather than one whose cushion was killed.
|
||||
self.audio.play(
|
||||
"minecraft:entity.cushion.get_up",
|
||||
Some([c.position.x, c.position.y, c.position.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
let seat = c.seat();
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
self.previous_position = p.position;
|
||||
p.position = seat;
|
||||
p.velocity = Vec3::ZERO;
|
||||
p.fall_distance = 0.0;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `CushionRenderer`: the coloured model, rotated to the nearest
|
||||
/// direction, with its bottom on the cushion's position.
|
||||
pub(super) fn cushion_geometry(
|
||||
&self,
|
||||
camera: glam::DVec3,
|
||||
out: &mut Vec<horizon_client::mesher::Vertex>,
|
||||
) {
|
||||
let Some(model) = self.cushion_model.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let sprites = &self.gui.atlas.sprites;
|
||||
for c in &self.cushions {
|
||||
let entity_start = out.len();
|
||||
let a = aabb(c.bounds());
|
||||
let (lo, hi) = (a.min_position(), a.max_position());
|
||||
let (lo, hi) = (
|
||||
glam::DVec3::new(lo.x, lo.y, lo.z),
|
||||
glam::DVec3::new(hi.x, hi.y, hi.z),
|
||||
);
|
||||
let range =
|
||||
super::entity_culling::default_range(hi - lo, self.settings.entity_distance);
|
||||
if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) {
|
||||
continue;
|
||||
}
|
||||
let Some(uv) = sprites
|
||||
.get(&format!("entity/cushion/{}_cushion", c.color_name()))
|
||||
.map(|r| [r.u0, r.v0, r.u1, r.v1])
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let p = glam::DVec3::new(c.position.x, c.position.y, c.position.z) - camera;
|
||||
let base = glam::Mat4::from_translation(p.as_vec3())
|
||||
* glam::Mat4::from_rotation_y((180.0 - snap_yaw(c.yaw)).to_radians())
|
||||
* glam::Mat4::from_rotation_x(std::f32::consts::PI)
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0));
|
||||
// `EntityRenderer.getPackedLightCoords` probes at the eye height.
|
||||
let l = self.world.light(
|
||||
c.position.x.floor() as i32,
|
||||
(c.position.y + 0.2125).floor() as i32,
|
||||
c.position.z.floor() as i32,
|
||||
);
|
||||
let packed = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8);
|
||||
horizon_client::mobs::render::draw(
|
||||
model,
|
||||
base,
|
||||
&Poses::new(model),
|
||||
uv,
|
||||
0xFFFF_FFFF,
|
||||
packed,
|
||||
0,
|
||||
out,
|
||||
);
|
||||
self.cull_entity_vertices(out, entity_start);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_protocol::entity_data::Value;
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// Mob ids from here on are dragon parts (`SPECIAL + part`) and crystals
|
||||
@@ -1692,25 +1693,8 @@ impl Game<'_> {
|
||||
}
|
||||
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
let p = d.position;
|
||||
d.nearest_crystal = self
|
||||
.crystals
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| {
|
||||
(c.position.x - p.x).abs() <= 32.0
|
||||
&& (c.position.y - p.y).abs() <= 32.0
|
||||
&& (c.position.z - p.z).abs() <= 32.0
|
||||
})
|
||||
.min_by(|a, b| {
|
||||
let da = (a.1.position.x - p.x).powi(2)
|
||||
+ (a.1.position.y - p.y).powi(2)
|
||||
+ (a.1.position.z - p.z).powi(2);
|
||||
let db = (b.1.position.x - p.x).powi(2)
|
||||
+ (b.1.position.y - p.y).powi(2)
|
||||
+ (b.1.position.z - p.z).powi(2);
|
||||
da.total_cmp(&db)
|
||||
})
|
||||
.map(|(i, _)| i);
|
||||
let nearest = self.nearest_crystal_to(p);
|
||||
self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
|
||||
}
|
||||
let d = self.dragon.as_mut().expect("dragon");
|
||||
d.yaw = wrap(d.yaw);
|
||||
@@ -3143,6 +3127,204 @@ impl Game<'_> {
|
||||
let _ = self.activate_exit_portal();
|
||||
self.fight.dirty = true;
|
||||
}
|
||||
/// `EnderDragon.checkCrystals`' search: the nearest crystal within 32
|
||||
/// blocks on each axis.
|
||||
fn nearest_crystal_to(&self, p: Vec3) -> Option<usize> {
|
||||
self.crystals
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| {
|
||||
(c.position.x - p.x).abs() <= 32.0
|
||||
&& (c.position.y - p.y).abs() <= 32.0
|
||||
&& (c.position.z - p.z).abs() <= 32.0
|
||||
})
|
||||
.min_by(|a, b| {
|
||||
let da = (a.1.position.x - p.x).powi(2)
|
||||
+ (a.1.position.y - p.y).powi(2)
|
||||
+ (a.1.position.z - p.z).powi(2);
|
||||
let db = (b.1.position.x - p.x).powi(2)
|
||||
+ (b.1.position.y - p.y).powi(2)
|
||||
+ (b.1.position.z - p.z).powi(2);
|
||||
da.total_cmp(&db)
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
}
|
||||
|
||||
/// The dragon on a server's client (`ClientPacketListener.handleAddEntity`
|
||||
/// and the client side of `EnderDragon.aiStep`): the server flies it and
|
||||
/// sends its moves, health and phase; the client flaps its wings, keeps
|
||||
/// its flight history and places its parts, so it can be drawn and hit.
|
||||
impl Game<'_> {
|
||||
/// `handleAddEntity` for `minecraft:ender_dragon`. Its constructor
|
||||
/// sets the full health and the hovering phase until the server's
|
||||
/// synched data says otherwise.
|
||||
pub(super) fn spawn_remote_dragon(&mut self, id: i32, position: [f64; 3], yaw: f32) {
|
||||
let at = Vec3::new(position[0], position[1], position[2]);
|
||||
let mut d = Dragon::new(at, yaw, i64::from(id));
|
||||
d.id = id as u32;
|
||||
d.phase = Phase::from_id(10);
|
||||
self.dragon = Some(d);
|
||||
self.place_dragon_parts();
|
||||
if let Some(d) = self.dragon.as_mut() {
|
||||
for part in &mut d.parts {
|
||||
part.1 = part.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The remote dragon, if `id` is it.
|
||||
fn remote_dragon_mut(&mut self, id: i32) -> Option<&mut Dragon> {
|
||||
self.dragon.as_mut().filter(|d| d.id as i32 == id)
|
||||
}
|
||||
/// `handleSetEntityData`: LivingEntity.DATA_HEALTH_ID and
|
||||
/// EnderDragon.DATA_PHASE (`onSyncedDataUpdated` sets the phase).
|
||||
pub(super) fn remote_dragon_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
|
||||
let Some(d) = self.remote_dragon_mut(id) else {
|
||||
return;
|
||||
};
|
||||
for (index, _, value) in values {
|
||||
match (index, value) {
|
||||
(9, Value::Float(health)) => d.health = *health,
|
||||
(16, Value::Int(phase)) => d.set_phase(Phase::from_id(*phase)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `handleSetEntityMotion`: the velocity its wings flap by.
|
||||
pub(super) fn remote_dragon_motion(&mut self, id: i32, velocity: [f64; 3]) {
|
||||
if let Some(d) = self.remote_dragon_mut(id) {
|
||||
d.velocity = Vec3::new(velocity[0], velocity[1], velocity[2]);
|
||||
}
|
||||
}
|
||||
/// `handleHurtAnimation` and `handleDamageEvent`: the red flash.
|
||||
pub(super) fn remote_dragon_hurt(&mut self, id: i32) {
|
||||
if let Some(d) = self.remote_dragon_mut(id) {
|
||||
d.hurt_time = 10;
|
||||
}
|
||||
}
|
||||
/// `handleRemoveEntities`, or a crystal removed: the healing beam
|
||||
/// keeps pointing at the same crystal.
|
||||
pub(super) fn remove_remote_dragon(&mut self, id: i32) {
|
||||
if self.remote_dragon_mut(id).is_some() {
|
||||
self.dragon = None;
|
||||
return;
|
||||
}
|
||||
let Some(index) = self.crystals.iter().position(|c| c.id as i32 == id) else {
|
||||
return;
|
||||
};
|
||||
if let Some(d) = self.dragon.as_mut() {
|
||||
match d.nearest_crystal {
|
||||
Some(n) if n == index => d.nearest_crystal = None,
|
||||
Some(n) if n > index => d.nearest_crystal = Some(n - 1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// One client tick of the dragon. `lerp`: the step toward its last
|
||||
/// sent position and yaw (LivingEntity's interpolation), and the
|
||||
/// steps left including this one.
|
||||
pub(super) fn tick_remote_dragon(&mut self, lerp: Option<([f64; 3], Option<f32>, u32)>) {
|
||||
let Some(d) = self.dragon.as_mut() else {
|
||||
return;
|
||||
};
|
||||
d.previous = d.position;
|
||||
d.previous_yaw = d.yaw;
|
||||
d.old_flap = d.flap;
|
||||
d.ticks += 1;
|
||||
d.hurt_time = (d.hurt_time - 1).max(0);
|
||||
for part in &mut d.parts {
|
||||
part.1 = part.0;
|
||||
}
|
||||
if let Some((target, yaw, steps)) = lerp {
|
||||
let n = f64::from(steps.max(1));
|
||||
d.position = Vec3::new(
|
||||
d.position.x + (target[0] - d.position.x) / n,
|
||||
d.position.y + (target[1] - d.position.y) / n,
|
||||
d.position.z + (target[2] - d.position.z) / n,
|
||||
);
|
||||
if let Some(yaw) = yaw {
|
||||
d.yaw += wrap(yaw - d.yaw) / steps.max(1) as f32;
|
||||
}
|
||||
}
|
||||
if !d.alive() {
|
||||
// EnderDragon.tickDeath on a client: it rises, and bursts
|
||||
// from tick 180 to 200; the server removes it.
|
||||
d.death_time += 1;
|
||||
let (t, p) = (d.death_time, d.position);
|
||||
if (180..=200).contains(&t) {
|
||||
let r = &mut d.random;
|
||||
let o = [
|
||||
f64::from((r.next_float() - 0.5) * 8.0),
|
||||
f64::from((r.next_float() - 0.5) * 4.0),
|
||||
f64::from((r.next_float() - 0.5) * 8.0),
|
||||
];
|
||||
self.particles.add(
|
||||
&ParticleOptions::simple(ParticleType::ExplosionEmitter),
|
||||
[p.x + o[0], p.y + 2.0 + o[1], p.z + o[2]],
|
||||
[0.0; 3],
|
||||
);
|
||||
}
|
||||
if let Some(d) = self.dragon.as_mut() {
|
||||
d.position.y += 0.1;
|
||||
for part in &mut d.parts {
|
||||
part.0.y += 0.1;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// processFlappingMovement and onFlap: its wing beats, and their sound.
|
||||
let flap_was = (d.old_flap * std::f32::consts::TAU).cos();
|
||||
let v = d.velocity;
|
||||
let mut flap_speed = 0.2 / ((v.x.hypot(v.z) as f32) * 10.0 + 1.0);
|
||||
flap_speed *= 2f32.powf(v.y as f32);
|
||||
d.flap += if d.phase.sitting() { 0.1 } else { flap_speed };
|
||||
let flap_now = (d.flap * std::f32::consts::TAU).cos();
|
||||
let at = [d.position.x, d.position.y, d.position.z];
|
||||
if flap_was <= -0.3 && flap_now >= -0.3 {
|
||||
let pitch = 0.8 + self.world.random.next_float() * 0.3;
|
||||
self.audio
|
||||
.play("minecraft:entity.ender_dragon.flap", Some(at), 5.0, pitch);
|
||||
}
|
||||
let d = self.dragon.as_mut().expect("dragon");
|
||||
if !d.phase.sitting() {
|
||||
d.growl -= 1;
|
||||
if d.growl < 0 {
|
||||
d.growl = 200 + d.random.next_int_bound(200).unwrap_or(0);
|
||||
let pitch = 0.8 + self.world.random.next_float() * 0.3;
|
||||
self.audio
|
||||
.play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch);
|
||||
}
|
||||
}
|
||||
// checkCrystals' search runs on a client too (the healing beam).
|
||||
let d = self.dragon.as_mut().expect("dragon");
|
||||
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
let p = d.position;
|
||||
let nearest = self.nearest_crystal_to(p);
|
||||
self.dragon.as_mut().expect("dragon").nearest_crystal = nearest;
|
||||
}
|
||||
let d = self.dragon.as_mut().expect("dragon");
|
||||
d.yaw = wrap(d.yaw);
|
||||
d.record();
|
||||
self.place_dragon_parts();
|
||||
}
|
||||
/// The dragon's parts as a server's client attacks them: the server's
|
||||
/// ids for `EnderDragonPart`s follow the dragon's.
|
||||
pub(super) fn remote_dragon_part_hit(
|
||||
&self,
|
||||
eye: [f64; 3],
|
||||
dir: [f64; 3],
|
||||
reach: f64,
|
||||
) -> Option<(i32, f64, [f64; 3])> {
|
||||
let d = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0)?;
|
||||
(0..8)
|
||||
.filter_map(|i| {
|
||||
let b = d.part_box(i);
|
||||
let p = d.parts[i].0;
|
||||
super::ray_box(eye, dir, reach, b)
|
||||
.map(|t| ((d.id + 1 + i as u32) as i32, t, [p.x, p.y, p.z]))
|
||||
})
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -129,15 +129,32 @@ impl EndState {
|
||||
survive: false,
|
||||
});
|
||||
}
|
||||
/// One tick of a server's client: `step` moves each toward where the
|
||||
/// server put it.
|
||||
pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) {
|
||||
/// `EyeOfEnder.tick` on a server's client: it moves by its last known
|
||||
/// motion; only the server steers it.
|
||||
pub(super) fn step_remote_eyes(&mut self) {
|
||||
for e in &mut self.eyes {
|
||||
e.previous = e.position;
|
||||
e.life += 1;
|
||||
e.position = glam::DVec3::from_array(step(e.id, e.position.to_array()));
|
||||
e.position += e.velocity;
|
||||
}
|
||||
}
|
||||
/// A server's move: an eye has no interpolation handler, so
|
||||
/// `moveOrInterpolateTo` puts it there at once. False when `id` isn't one.
|
||||
pub(super) fn move_remote_eye(&mut self, id: u32, at: [f64; 3]) -> bool {
|
||||
let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else {
|
||||
return false;
|
||||
};
|
||||
e.position = glam::DVec3::from_array(at);
|
||||
true
|
||||
}
|
||||
/// `handleSetEntityMotion` for an eye. False when `id` isn't one.
|
||||
pub(super) fn remote_eye_motion(&mut self, id: u32, velocity: [f64; 3]) -> bool {
|
||||
let Some(e) = self.eyes.iter_mut().find(|e| e.id == id) else {
|
||||
return false;
|
||||
};
|
||||
e.velocity = glam::DVec3::from_array(velocity);
|
||||
true
|
||||
}
|
||||
pub(super) fn remove_remote_eye(&mut self, id: u32) {
|
||||
self.eyes.retain(|e| e.id != id);
|
||||
}
|
||||
@@ -1099,6 +1116,7 @@ impl Game<'_> {
|
||||
/// EyeOfEnder.tick: fly, then drop (4 in 5) or shatter after 80 ticks.
|
||||
fn tick_eyes(&mut self) {
|
||||
let mut eyes = std::mem::take(&mut self.end.eyes);
|
||||
let mut shattered = Vec::new();
|
||||
eyes.retain_mut(|eye| {
|
||||
eye.previous = eye.position;
|
||||
let next = eye.position + eye.velocity;
|
||||
@@ -1122,10 +1140,44 @@ impl Game<'_> {
|
||||
extra: None,
|
||||
};
|
||||
self.spawn_item(stack, at, [vx, 0.2, vz], 0);
|
||||
} else {
|
||||
shattered.push(at.map(|v| v.floor() as i32));
|
||||
}
|
||||
false
|
||||
});
|
||||
self.end.eyes = eyes;
|
||||
for pos in shattered {
|
||||
self.level_event_at(2003, pos, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `LevelEventHandler` 2003: a shattered eye's item crumbs and two rings
|
||||
/// of portal particles drawn in towards it.
|
||||
pub(super) fn eye_break_particles(&mut self, pos: [i32; 3]) {
|
||||
let (x, y, z) = (
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]),
|
||||
f64::from(pos[2]) + 0.5,
|
||||
);
|
||||
let crumbs = self.item_particle(&ItemStack::new("minecraft:ender_eye", 1));
|
||||
for _ in 0..8 {
|
||||
let r = self.particles.random();
|
||||
let v = [
|
||||
r.next_gaussian() * 0.15,
|
||||
r.next_double() * 0.2,
|
||||
r.next_gaussian() * 0.15,
|
||||
];
|
||||
self.particles.add(&crumbs, [x, y, z], v);
|
||||
}
|
||||
let portal = ParticleOptions::simple(ParticleType::Portal);
|
||||
let mut angle = 0.0f64;
|
||||
while angle < std::f64::consts::PI * 2.0 {
|
||||
let (c, s) = (angle.cos(), angle.sin());
|
||||
let at = [x + c * 5.0, y - 0.4, z + s * 5.0];
|
||||
self.particles.add(&portal, at, [c * -5.0, 0.0, s * -5.0]);
|
||||
self.particles.add(&portal, at, [c * -7.0, 0.0, s * -7.0]);
|
||||
angle += std::f64::consts::PI / 20.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// `EyeOfEnder.tick` on a client: behind each eye (a quarter of its last
|
||||
|
||||
@@ -17,6 +17,8 @@ use horizon_core::{
|
||||
random::RandomSource,
|
||||
};
|
||||
|
||||
pub(super) const FIREWORK_EXPLODE_EVENT: i8 = 17;
|
||||
|
||||
pub(super) struct Rocket {
|
||||
/// The entity id a server tracks it by (0 until it is tracked).
|
||||
pub id: u32,
|
||||
@@ -261,6 +263,14 @@ impl Game<'_> {
|
||||
/// `FireworkRocketEntity.explode` and `dealExplosionDamage`.
|
||||
fn explode_rocket(&mut self, r: &Rocket) {
|
||||
let at = [r.position.x, r.position.y, r.position.z];
|
||||
// FireworkRocketEntity.explode broadcasts before discard. Send now:
|
||||
// tick_lan removes missing tracked entities before flushing effects.
|
||||
if r.id != 0
|
||||
&& let Some(host) = &self.lan
|
||||
{
|
||||
host.hub
|
||||
.entity_event(r.id as i32, FIREWORK_EXPLODE_EVENT, at);
|
||||
}
|
||||
if !r.explosions.is_empty() {
|
||||
let damage = 5.0 + r.explosions.len() as f32 * 2.0;
|
||||
let from = r.position;
|
||||
@@ -322,6 +332,16 @@ impl Game<'_> {
|
||||
self.particles
|
||||
.fireworks(at, v, r.explosions.clone(), camera);
|
||||
}
|
||||
/// FireworkRocketEntity.handleEntityEvent: use the synchronized item data.
|
||||
pub(super) fn remote_firework_explosion(&mut self, id: i32) {
|
||||
let camera = self.eye_position();
|
||||
if let Some(r) = self.rockets.iter().find(|r| r.id == id as u32) {
|
||||
let at = [r.position.x, r.position.y, r.position.z];
|
||||
let v = [r.velocity.x, r.velocity.y, r.velocity.z];
|
||||
self.particles
|
||||
.fireworks(at, v, r.explosions.clone(), camera.unwrap_or(at));
|
||||
}
|
||||
}
|
||||
/// `dealExplosionDamage` on a player that is not the rocket's
|
||||
/// `attachedToEntity`: within 5 blocks, when the rocket sees its feet or
|
||||
/// its middle (`ClipContext.Block.COLLIDER`, no fluids).
|
||||
|
||||
@@ -151,6 +151,7 @@ impl Game<'_> {
|
||||
before(self.painting_hit().map(|h| h.1))
|
||||
|| before(self.frame_hit().map(|h| h.1))
|
||||
|| before(self.armor_stand_hit().map(|h| h.1))
|
||||
|| before(self.cushion_hit().map(|h| h.1))
|
||||
|| before(self.boat_hit().map(|h| h.1))
|
||||
|| before(self.cart_hit().map(|h| h.1))
|
||||
|| before(self.dragon_hit().map(|h| h.1))
|
||||
|
||||
@@ -875,7 +875,11 @@ impl Game<'_> {
|
||||
.filter(|g| host.hub.here(g))
|
||||
.filter(|g| {
|
||||
g.menu.as_ref().is_some_and(|m| {
|
||||
m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos)
|
||||
(m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos))
|
||||
|| m.pos.is_some_and(|k| {
|
||||
k.1 == super::minecarts::CART_KEY_Y
|
||||
&& !self.chest_vehicle_still_valid(k.2, g)
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(|g| g.conn)
|
||||
@@ -889,6 +893,35 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ContainerEntity.isChestVehicleStillValid`: the chest minecart or chest
|
||||
/// boat is still there and within the guest's entity interaction range
|
||||
/// plus 4 of its box.
|
||||
fn chest_vehicle_still_valid(&self, id: i32, g: &horizon_client::lan::guest::Guest) -> bool {
|
||||
let bounds = self
|
||||
.carts
|
||||
.iter()
|
||||
.find(|c| c.id as i32 == id)
|
||||
.map(|c| c.bounds())
|
||||
.or_else(|| {
|
||||
self.boats
|
||||
.iter()
|
||||
.find(|b| b.id as i32 == id)
|
||||
.map(|b| b.bounds())
|
||||
});
|
||||
let Some(b) = bounds else {
|
||||
return false;
|
||||
};
|
||||
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let d = [
|
||||
eye[0] - eye[0].clamp(lo.x, hi.x),
|
||||
eye[1] - eye[1].clamp(lo.y, hi.y),
|
||||
eye[2] - eye[2].clamp(lo.z, hi.z),
|
||||
];
|
||||
let range = if g.creative() { 5.0 } else { 3.0 } + 4.0;
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range
|
||||
}
|
||||
|
||||
/// A packet from a guest that the hub does not handle itself.
|
||||
pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) {
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
|
||||
@@ -245,6 +245,16 @@ impl Game<'_> {
|
||||
}
|
||||
out.push(e);
|
||||
}
|
||||
for c in &self.cushions {
|
||||
let p = c.position;
|
||||
let mut e = state(c.id, "minecraft:cushion", [p.x, p.y, p.z], c.yaw, false);
|
||||
// Cushion.DATA_COLOR, set unless it is the default white.
|
||||
if c.color != 0 {
|
||||
e.meta
|
||||
.push((8, serializer::DYE_COLOR, Value::Id(i32::from(c.color))));
|
||||
}
|
||||
out.push(e);
|
||||
}
|
||||
self.lan_projectile_states(host_entity, hub, out);
|
||||
for o in &self.others {
|
||||
let p = o.position;
|
||||
|
||||
@@ -56,6 +56,13 @@ impl Game<'_> {
|
||||
let (lo, hi) = corners(a.bounds());
|
||||
return Some((lo, hi, at(a.position)));
|
||||
}
|
||||
if let Some(c) = self.cushions.iter().find(|c| c.id == id) {
|
||||
let (lo, hi) = corners(Aabb::new(
|
||||
Vec3::new(c.position.x - 0.5, c.position.y, c.position.z - 0.5),
|
||||
Vec3::new(c.position.x + 0.5, c.position.y + 0.25, c.position.z + 0.5),
|
||||
));
|
||||
return Some((lo, hi, at(c.position)));
|
||||
}
|
||||
if let Some(f) = self.item_frames.iter().find(|f| f.id == id) {
|
||||
let (lo, hi) = f.bounds();
|
||||
return Some((lo, hi, centre(f.pos)));
|
||||
@@ -98,9 +105,10 @@ impl Game<'_> {
|
||||
let boat = self.boats.iter().position(|b| b.id == vehicle);
|
||||
let cart = self.carts.iter().any(|c| c.id == vehicle);
|
||||
let mount = self.mobs.iter().any(|m| m.id == vehicle);
|
||||
let cushion = self.cushions.iter().any(|c| c.id == vehicle);
|
||||
// The vehicle is gone (broken, in another level) or the rider died:
|
||||
// its client drops it with the entity or the death screen.
|
||||
if dead || (boat.is_none() && !cart && !mount) {
|
||||
if dead || (boat.is_none() && !cart && !mount && !cushion) {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
(g.vehicle, g.vehicle_good) = (None, None);
|
||||
return;
|
||||
@@ -115,6 +123,17 @@ impl Game<'_> {
|
||||
// Getting out goes through leave_guest, which tells the client and
|
||||
// teleports it (ServerPlayer.dismountTo).
|
||||
let seat = self.as_guest(host, conn, |game| {
|
||||
// A cushion does not move: the rider sits on it until it sneaks
|
||||
// (`Cushion.removePassenger` plays the get-up sound).
|
||||
if game.cushions.iter().any(|c| Some(c.id) == game.riding) {
|
||||
if keys.shift {
|
||||
game.tick_cushion_riding(keys);
|
||||
return None;
|
||||
}
|
||||
let c = game.cushions.iter().find(|c| Some(c.id) == game.riding)?;
|
||||
let p = c.seat();
|
||||
return Some([p.x, p.y, p.z]);
|
||||
}
|
||||
if let Some(i) = game.boats.iter().position(|b| Some(b.id) == game.riding) {
|
||||
if keys.shift {
|
||||
game.dismount(i);
|
||||
@@ -168,6 +187,12 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.find(|c| c.id == vehicle)
|
||||
.map(|c| (c.position, c.position.add_vector(Vec3::new(0.0, SEAT, 0.0))))
|
||||
})
|
||||
.or_else(|| {
|
||||
self.cushions
|
||||
.iter()
|
||||
.find(|c| c.id == vehicle)
|
||||
.map(|c| (c.position, c.seat()))
|
||||
});
|
||||
if let Some((p, seat)) = at {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
|
||||
@@ -50,6 +50,7 @@ pub(super) struct Parked {
|
||||
paintings: Vec<horizon_client::entities::Painting>,
|
||||
item_frames: Vec<horizon_client::entities::ItemFrame>,
|
||||
armor_stands: Vec<horizon_client::entities::ArmorStand>,
|
||||
cushions: Vec<horizon_client::entities::Cushion>,
|
||||
others: Vec<commands::OtherEntity>,
|
||||
boats: Vec<boats::Boat>,
|
||||
carts: Vec<minecarts::Minecart>,
|
||||
@@ -136,6 +137,7 @@ impl Game<'_> {
|
||||
paintings: Vec::new(),
|
||||
item_frames: Vec::new(),
|
||||
armor_stands: Vec::new(),
|
||||
cushions: Vec::new(),
|
||||
others: Vec::new(),
|
||||
boats: Vec::new(),
|
||||
carts: Vec::new(),
|
||||
@@ -187,6 +189,7 @@ impl Game<'_> {
|
||||
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.cushions, &mut p.cushions);
|
||||
swap(&mut self.others, &mut p.others);
|
||||
swap(&mut self.boats, &mut p.boats);
|
||||
swap(&mut self.carts, &mut p.carts);
|
||||
|
||||
@@ -97,7 +97,7 @@ fn display_offset(kind: CartKind) -> f64 {
|
||||
/// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT.
|
||||
pub(super) const SEAT: f64 = 0.1875 - 0.6;
|
||||
/// The placeholder container key under which an open cart's items live.
|
||||
pub(super) const CART_KEY_Y: i32 = -100_000;
|
||||
pub(super) const CART_KEY_Y: i32 = horizon_client::lan::menu::VEHICLE_KEY_Y;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(super) enum Shape {
|
||||
|
||||
@@ -268,6 +268,11 @@ impl Game<'_> {
|
||||
r.animated_textures = s.horizon.animated_textures;
|
||||
r.set_mipmap_levels(s.mipmap_levels.max(0) as u32);
|
||||
r.set_world_post(s.horizon.resolution_scale as f32 / 100.0, s.horizon.fxaa);
|
||||
r.set_hdr(
|
||||
s.horizon.hdr,
|
||||
s.horizon.hdr_paper_white as f32,
|
||||
s.horizon.hdr_peak as f32,
|
||||
);
|
||||
}
|
||||
// Window.updateFullscreenIfChanged: only a changed option asks the
|
||||
// window to change, so applying settings never undoes a fullscreen
|
||||
|
||||
@@ -314,6 +314,13 @@ impl Game<'_> {
|
||||
self.item_frames.push(f);
|
||||
}
|
||||
}
|
||||
"minecraft:cushion" => {
|
||||
self.next_entity += 1;
|
||||
if let Some(c) = entity_nbt::cushion_from_nbt(&tag, self.next_entity) {
|
||||
self.remember(c.id, uuid, tag);
|
||||
self.cushions.push(c);
|
||||
}
|
||||
}
|
||||
"minecraft:painting" => {
|
||||
if let Some((pos, facing, variant)) = entity_nbt::painting_from_nbt(&tag)
|
||||
&& let Some(v) = self.painting_variants.get(&variant).cloned()
|
||||
@@ -776,6 +783,18 @@ impl Game<'_> {
|
||||
out.entry(chunk_of(at)).or_default().push(tag);
|
||||
}
|
||||
}
|
||||
for c in &self.cushions {
|
||||
if keys.contains(&chunk_of(c.position)) {
|
||||
let uuid = self
|
||||
.persist
|
||||
.uuids
|
||||
.get(&c.id)
|
||||
.copied()
|
||||
.unwrap_or_else(random_uuid);
|
||||
let tag = entity_nbt::cushion_to_nbt(c, uuid, self.persist.raw.get(&c.id));
|
||||
out.entry(chunk_of(c.position)).or_default().push(tag);
|
||||
}
|
||||
}
|
||||
for p in &self.paintings {
|
||||
let at = painting_center(p);
|
||||
if keys.contains(&chunk_of(at)) {
|
||||
@@ -868,6 +887,13 @@ impl Game<'_> {
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.cushions.retain(|c| {
|
||||
let keep = !gone(c.position);
|
||||
if !keep {
|
||||
removed.push(c.id);
|
||||
}
|
||||
keep
|
||||
});
|
||||
// Riders leave with their root vehicle, a boat's with the boat.
|
||||
let leaving: HashSet<u32> = (0..self.mobs.len())
|
||||
.filter(|&i| {
|
||||
@@ -934,6 +960,7 @@ impl Game<'_> {
|
||||
.chain(self.boats.iter().map(|e| e.id))
|
||||
.chain(self.carts.iter().map(|e| e.id))
|
||||
.chain(self.armor_stands.iter().map(|e| e.id))
|
||||
.chain(self.cushions.iter().map(|e| e.id))
|
||||
.chain(self.item_frames.iter().map(|e| e.id))
|
||||
.chain(self.paintings.iter().map(|e| e.id))
|
||||
.chain(self.others.iter().map(|e| e.id))
|
||||
|
||||
@@ -141,14 +141,22 @@ impl PotionState {
|
||||
t.stack = stack;
|
||||
}
|
||||
}
|
||||
/// One tick of a server's client: `step` moves each toward where the
|
||||
/// server put it.
|
||||
pub(super) fn step_remote_thrown(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
|
||||
for t in &mut self.thrown {
|
||||
t.previous = t.position;
|
||||
t.age += 1;
|
||||
t.position = step(t.id, t.position);
|
||||
}
|
||||
/// A server's move: thrown potions have no interpolation handler, so
|
||||
/// `moveOrInterpolateTo` puts them there at once. False when `id` isn't one.
|
||||
pub(super) fn move_remote_thrown(&mut self, id: u32, at: Vec3) -> bool {
|
||||
let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) else {
|
||||
return false;
|
||||
};
|
||||
t.position = at;
|
||||
true
|
||||
}
|
||||
/// `handleSetEntityMotion` for a thrown potion. False when `id` isn't one.
|
||||
pub(super) fn remote_thrown_motion(&mut self, id: u32, velocity: Vec3) -> bool {
|
||||
let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) else {
|
||||
return false;
|
||||
};
|
||||
t.velocity = velocity;
|
||||
true
|
||||
}
|
||||
pub(super) fn remove_remote_thrown(&mut self, id: u32) {
|
||||
self.thrown.retain(|t| t.id != id);
|
||||
@@ -484,6 +492,7 @@ impl Game<'_> {
|
||||
thrown.retain_mut(|t| {
|
||||
t.age += 1;
|
||||
t.previous = t.position;
|
||||
self.thrown_potion_motion(t);
|
||||
let next = Vec3::new(
|
||||
t.position.x + t.velocity.x,
|
||||
t.position.y + t.velocity.y,
|
||||
@@ -520,18 +529,6 @@ impl Game<'_> {
|
||||
return false;
|
||||
}
|
||||
t.position = next;
|
||||
// ThrowableItemProjectile: drag 0.99 then gravity 0.05.
|
||||
// ThrownExperienceBottle.getDefaultGravity is 0.07.
|
||||
let gravity = if &*t.stack.item == "minecraft:experience_bottle" {
|
||||
0.07
|
||||
} else {
|
||||
0.05
|
||||
};
|
||||
t.velocity = Vec3::new(
|
||||
t.velocity.x * 0.99,
|
||||
t.velocity.y * 0.99 - gravity,
|
||||
t.velocity.z * 0.99,
|
||||
);
|
||||
t.age < 1200 && t.position.y > -128.0
|
||||
});
|
||||
self.potions.thrown = thrown;
|
||||
@@ -539,6 +536,60 @@ impl Game<'_> {
|
||||
self.splash(&stack, at);
|
||||
}
|
||||
}
|
||||
/// `ThrowableProjectile.tick`'s `applyGravity` and `applyInertia`, which
|
||||
/// come before the move: gravity 0.05 (0.07 for an experience bottle),
|
||||
/// then drag 0.99 (0.8 in water).
|
||||
fn thrown_potion_motion(&self, t: &mut ThrownPotion) {
|
||||
let gravity = if &*t.stack.item == "minecraft:experience_bottle" {
|
||||
0.07
|
||||
} else {
|
||||
0.05
|
||||
};
|
||||
let at = t.position;
|
||||
let water = self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(
|
||||
at.x.floor() as i32,
|
||||
at.y.floor() as i32,
|
||||
at.z.floor() as i32,
|
||||
))
|
||||
.fluid
|
||||
== horizon_client::blocks::Fluid::Water;
|
||||
let inertia = if water { 0.8 } else { 0.99 };
|
||||
t.velocity = Vec3::new(
|
||||
t.velocity.x * inertia,
|
||||
(t.velocity.y - gravity) * inertia,
|
||||
t.velocity.z * inertia,
|
||||
);
|
||||
}
|
||||
/// `ThrowableProjectile.tick` on a server's client: it falls and moves
|
||||
/// by itself between the server's updates and stops at a block; only
|
||||
/// the server breaks it.
|
||||
pub(super) fn step_remote_thrown(&mut self) {
|
||||
let mut thrown = std::mem::take(&mut self.potions.thrown);
|
||||
for t in &mut thrown {
|
||||
t.previous = t.position;
|
||||
t.age += 1;
|
||||
self.thrown_potion_motion(t);
|
||||
let next = Vec3::new(
|
||||
t.position.x + t.velocity.x,
|
||||
t.position.y + t.velocity.y,
|
||||
t.position.z + t.velocity.z,
|
||||
);
|
||||
let state = self.world.block(
|
||||
next.x.floor() as i32,
|
||||
next.y.floor() as i32,
|
||||
next.z.floor() as i32,
|
||||
);
|
||||
if self.res.facts().get(state).full_collision {
|
||||
t.velocity = Vec3::ZERO;
|
||||
} else {
|
||||
t.position = next;
|
||||
}
|
||||
}
|
||||
self.potions.thrown = thrown;
|
||||
}
|
||||
/// `ThrownItemRenderer` for thrown splash and lingering potions and
|
||||
/// experience bottles: the item (GROUND) facing the camera at scale 1,
|
||||
/// lit at the light probe (the eye, 0.85 of the 0.25 height).
|
||||
|
||||
@@ -1261,6 +1261,9 @@ impl Game<'_> {
|
||||
} else {
|
||||
self.res.mob_types().get(kind).cloned()
|
||||
};
|
||||
if kind == "minecraft:ender_dragon" {
|
||||
self.spawn_remote_dragon(id, position, yaw);
|
||||
}
|
||||
if kind == "minecraft:experience_orb" {
|
||||
// Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData.
|
||||
self.orbs.retain(|o| o.id != id as u32);
|
||||
@@ -1367,13 +1370,17 @@ impl Game<'_> {
|
||||
m.on_ground = on_ground;
|
||||
return;
|
||||
}
|
||||
if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| {
|
||||
p.id == id as u32
|
||||
&& matches!(
|
||||
p.kind,
|
||||
horizon_client::projectiles::ProjectileKind::LargeFireball { .. }
|
||||
)
|
||||
}) {
|
||||
// Projectiles keep Entity's NO_OP InterpolationHandler too: the
|
||||
// server's position replaces theirs at once and their own tick
|
||||
// flies them on (`tick_remote_projectiles`). Eased towards it
|
||||
// instead, they only moved when an update came, every 10 to 20
|
||||
// ticks.
|
||||
if let Some(p) = self
|
||||
.creatures
|
||||
.projectiles
|
||||
.iter_mut()
|
||||
.find(|p| p.id == id as u32)
|
||||
{
|
||||
if path.is_some() {
|
||||
p.position = Vec3::new(position[0], position[1], position[2]);
|
||||
}
|
||||
@@ -1383,6 +1390,14 @@ impl Game<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if path.is_some()
|
||||
&& (self.potions.move_remote_thrown(
|
||||
id as u32,
|
||||
Vec3::new(position[0], position[1], position[2]),
|
||||
) || self.end.move_remote_eye(id as u32, position))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(p) = r.pending_items.get_mut(&id) {
|
||||
p.0 = position;
|
||||
}
|
||||
@@ -1429,6 +1444,8 @@ impl Game<'_> {
|
||||
self.mobs.retain(|m| m.id != id as u32);
|
||||
self.orbs.retain(|o| o.id != id as u32);
|
||||
self.dropped.retain(|d| d.id != id as u32);
|
||||
// Before the crystals go: the dragon's beam index follows them.
|
||||
self.remove_remote_dragon(id);
|
||||
self.remove_remote_object(id as u32);
|
||||
self.remove_remote_projectile(id as u32);
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
@@ -1961,6 +1978,7 @@ impl Game<'_> {
|
||||
}
|
||||
self.remote_object_data(p.id, &p.values);
|
||||
self.remote_projectile_data(p.id, &p.values);
|
||||
self.remote_dragon_data(p.id, &p.values);
|
||||
}
|
||||
// ClientPacketListener.handleSetEquipment: what a mob or another
|
||||
// player holds and wears (EquipmentSlot ordinals).
|
||||
@@ -2042,6 +2060,8 @@ impl Game<'_> {
|
||||
} else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
|
||||
m.limb_speed = 1.5;
|
||||
m.hurt_time = 10;
|
||||
} else {
|
||||
self.remote_dragon_hurt(p.id);
|
||||
}
|
||||
}
|
||||
C::HurtAnimation(p) => {
|
||||
@@ -2051,9 +2071,14 @@ impl Game<'_> {
|
||||
}
|
||||
} else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
|
||||
m.hurt_time = 10;
|
||||
} else {
|
||||
self.remote_dragon_hurt(p.id);
|
||||
}
|
||||
}
|
||||
C::EntityEvent(p) => {
|
||||
if p.event == super::fireworks::FIREWORK_EXPLODE_EVENT {
|
||||
self.remote_firework_explosion(p.id);
|
||||
}
|
||||
// LocalPlayer.setPermissions also refreshes an open World Options screen.
|
||||
if (24..=28).contains(&p.event)
|
||||
&& self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
|
||||
@@ -2939,6 +2964,7 @@ impl Game<'_> {
|
||||
/// entities whose own tick moves them on a client: dropped items, falling
|
||||
/// blocks and primed TNT.
|
||||
fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) {
|
||||
self.remote_dragon_motion(id, velocity);
|
||||
let v = Vec3::new(velocity[0], velocity[1], velocity[2]);
|
||||
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
|
||||
d.velocity = v;
|
||||
@@ -2959,6 +2985,8 @@ impl Game<'_> {
|
||||
.and_then(|r| r.pending_items.get_mut(&id))
|
||||
{
|
||||
p.1 = v;
|
||||
} else if !self.potions.remote_thrown_motion(id as u32, v) {
|
||||
self.end.remote_eye_motion(id as u32, velocity);
|
||||
}
|
||||
}
|
||||
fn apply_remote_health(&mut self) {
|
||||
@@ -3532,6 +3560,18 @@ impl Game<'_> {
|
||||
self.remote_player_eating(&item, ticks, at, eye, pitch, yaw);
|
||||
}
|
||||
if running {
|
||||
// The dragon: LivingEntity's interpolation, inside its aiStep.
|
||||
let dragon_lerp = self
|
||||
.dragon
|
||||
.as_ref()
|
||||
.and_then(|d| lerps.get_mut(&(d.id as i32)))
|
||||
.filter(|l| l.steps > 0)
|
||||
.map(|l| {
|
||||
let steps = l.steps;
|
||||
l.steps -= 1;
|
||||
(l.target, l.rotation.map(|r| r.0), steps)
|
||||
});
|
||||
self.tick_remote_dragon(dragon_lerp);
|
||||
// Boats, minecarts, armor stands, projectiles and the rest
|
||||
// interpolate like mobs.
|
||||
let mut step = |id: u32, at: Vec3| match lerps.get_mut(&(id as i32)) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! `handleSetEquipment`): the server simulates them, the client places them
|
||||
//! where it says and interpolates their moves like a mob's.
|
||||
use super::Game;
|
||||
use horizon_client::entities::{ArmorStand, ItemFrame, Painting};
|
||||
use horizon_client::entities::{ArmorStand, Cushion, ItemFrame, Painting};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use horizon_protocol::entity_data::Value;
|
||||
use std::sync::Arc;
|
||||
@@ -57,6 +57,16 @@ impl Game<'_> {
|
||||
invisible: false,
|
||||
check_interval: 0,
|
||||
});
|
||||
} else if kind == "minecraft:cushion" {
|
||||
// BlockAttachedEntity.pos: `BlockPos.containing` of the spawn.
|
||||
self.cushions.push(Cushion {
|
||||
id,
|
||||
position: at,
|
||||
pos: block,
|
||||
yaw: super::cushions::snap_yaw(yaw),
|
||||
color: 0,
|
||||
check_interval: 0,
|
||||
});
|
||||
} else if kind == "minecraft:lightning_bolt" {
|
||||
self.spawn_remote_bolt(id, position);
|
||||
} else if kind == "minecraft:painting" {
|
||||
@@ -152,6 +162,11 @@ impl Game<'_> {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
} else if let Some(c) = self.cushions.iter_mut().find(|c| c.id == id) {
|
||||
// Cushion.DATA_COLOR (DyeColor, a byte-backed id).
|
||||
if let (8, Value::Id(color)) = (index, value) {
|
||||
c.color = (*color).clamp(0, 15) as u8;
|
||||
}
|
||||
} else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
|
||||
// VehicleEntity's hurt, direction and damage; the paddles.
|
||||
match (index, value) {
|
||||
@@ -267,6 +282,12 @@ impl Game<'_> {
|
||||
out.push(json!({"id": a.id, "kind": "minecraft:armor_stand", "position": at(a.position), "yaw": a.yaw,
|
||||
"small": a.small, "arms": a.show_arms, "no_base_plate": a.no_base_plate, "equipment": items}));
|
||||
}
|
||||
for c in &self.cushions {
|
||||
out.push(
|
||||
json!({"id": c.id, "kind": "minecraft:cushion", "position": at(c.position),
|
||||
"yaw": c.yaw, "color": c.color_name()}),
|
||||
);
|
||||
}
|
||||
for f in &self.item_frames {
|
||||
out.push(
|
||||
json!({"id": f.id, "kind": f.kind(), "position": f.pos, "facing": f.facing,
|
||||
@@ -286,6 +307,7 @@ impl Game<'_> {
|
||||
self.carts.clear();
|
||||
self.boats.clear();
|
||||
self.armor_stands.clear();
|
||||
self.cushions.clear();
|
||||
self.item_frames.clear();
|
||||
self.paintings.clear();
|
||||
}
|
||||
@@ -295,6 +317,7 @@ impl Game<'_> {
|
||||
self.carts.retain(|c| c.id != id);
|
||||
self.boats.retain(|b| b.id != id);
|
||||
self.armor_stands.retain(|a| a.id != id);
|
||||
self.cushions.retain(|c| c.id != id);
|
||||
self.item_frames.retain(|f| f.id != id);
|
||||
self.paintings.retain(|p| p.id != id);
|
||||
self.bolts.retain(|b| b.id != id);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! and `handleSetEntityData`): the server simulates them, the client draws
|
||||
//! them where it says and interpolates their moves.
|
||||
use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector};
|
||||
use horizon_client::projectiles::{Projectile, ProjectileKind};
|
||||
use horizon_client::projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld};
|
||||
use horizon_core::{geometry::Vec3, position::BlockPos};
|
||||
use horizon_protocol::entity_data::Value;
|
||||
use horizon_world::registry::BlockStateId;
|
||||
@@ -37,6 +37,32 @@ fn projectile_kind(kind: &str) -> Option<ProjectileKind> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `AbstractArrow.tick` on a client: water drag before the move, air drag
|
||||
/// after it, then gravity; a block it reaches holds it (`inGround`).
|
||||
fn remote_arrow_tick(p: &mut Projectile, w: &impl ProjectileWorld) {
|
||||
p.previous = p.position;
|
||||
p.age += 1;
|
||||
if p.stuck {
|
||||
return;
|
||||
}
|
||||
let water = w.in_water(p.position);
|
||||
if water {
|
||||
p.velocity = p.velocity.scale(0.6);
|
||||
}
|
||||
let to = p.position.add_vector(p.velocity);
|
||||
if let Some((at, _, _)) = w.clip(p.position, to) {
|
||||
p.position = at;
|
||||
p.velocity = Vec3::ZERO;
|
||||
p.stuck = true;
|
||||
return;
|
||||
}
|
||||
p.position = to;
|
||||
if !water {
|
||||
p.velocity = p.velocity.scale(0.99);
|
||||
}
|
||||
p.velocity.y -= 0.05;
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `handleAddEntity` for these types; false when `kind` isn't one.
|
||||
pub(super) fn spawn_remote_projectile(
|
||||
@@ -246,29 +272,34 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
self.falling = falling;
|
||||
for p in &mut self.creatures.projectiles {
|
||||
p.previous = p.position;
|
||||
p.age += 1;
|
||||
if matches!(p.kind, ProjectileKind::LargeFireball { .. }) {
|
||||
// AbstractHurtingProjectile.tick advances on the client between
|
||||
// the tracker updates (ten ticks apart for a ghast's fireball).
|
||||
let at = p.position;
|
||||
let water = self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(
|
||||
at.x.floor() as i32,
|
||||
at.y.floor() as i32,
|
||||
at.z.floor() as i32,
|
||||
))
|
||||
.fluid
|
||||
== horizon_client::blocks::Fluid::Water;
|
||||
p.apply_hurting_inertia(water);
|
||||
p.position = p.position.add_vector(p.velocity);
|
||||
} else {
|
||||
p.position = step(p.id, p.position);
|
||||
// Projectiles tick on the client too and fly on between the tracker's
|
||||
// updates (10 to 20 ticks apart); a block stops them there, and only
|
||||
// the server decides what they hit.
|
||||
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
|
||||
{
|
||||
let w = self.mob_world_base(&[]);
|
||||
let world = super::creatures::ProjWorld {
|
||||
w: &w,
|
||||
targets: Vec::new(),
|
||||
};
|
||||
for p in &mut projectiles {
|
||||
match p.kind {
|
||||
ProjectileKind::Arrow { .. } => remote_arrow_tick(p, &world),
|
||||
// ShulkerBullet.tick: only the server steers it.
|
||||
ProjectileKind::ShulkerBullet { .. } => {
|
||||
p.previous = p.position;
|
||||
p.age += 1;
|
||||
p.position = p.position.add_vector(p.velocity);
|
||||
}
|
||||
_ => {
|
||||
if !matches!(p.tick(&world).1, Hit::None) {
|
||||
p.velocity = Vec3::ZERO;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.creatures.projectiles = projectiles;
|
||||
for t in &mut self.tridents {
|
||||
let id = t.id;
|
||||
t.remote_step(|at| step(id, at));
|
||||
@@ -302,12 +333,9 @@ impl Game<'_> {
|
||||
c.time += 1;
|
||||
c.position = step(c.id, c.position);
|
||||
}
|
||||
self.potions.step_remote_thrown(&mut step);
|
||||
self.step_remote_thrown();
|
||||
self.step_remote_hooks(&mut step);
|
||||
self.end.step_remote_eyes(|id, at| {
|
||||
let at = step(id, Vec3::new(at[0], at[1], at[2]));
|
||||
[at.x, at.y, at.z]
|
||||
});
|
||||
self.end.step_remote_eyes();
|
||||
}
|
||||
|
||||
pub(super) fn remove_remote_projectile(&mut self, id: u32) {
|
||||
@@ -330,6 +358,8 @@ impl Game<'_> {
|
||||
self.tridents.clear();
|
||||
self.rockets.clear();
|
||||
self.crystals.clear();
|
||||
// The dragon a server sent goes with its crystals.
|
||||
self.dragon = None;
|
||||
self.potions.clear_thrown();
|
||||
self.end.clear_remote_eyes();
|
||||
self.clear_remote_hooks();
|
||||
|
||||
@@ -56,6 +56,11 @@ impl Game<'_> {
|
||||
let p = a.position;
|
||||
hits.push((a.id as i32, d, [p.x, p.y, p.z]));
|
||||
}
|
||||
if let Some((i, d, _)) = self.cushion_hit() {
|
||||
let c = &self.cushions[i];
|
||||
let p = c.position;
|
||||
hits.push((c.id as i32, d, [p.x, p.y, p.z]));
|
||||
}
|
||||
if let Some((i, d)) = self.boat_hit() {
|
||||
let p = self.boats[i].position;
|
||||
hits.push((self.boats[i].id as i32, d, [p.x, p.y, p.z]));
|
||||
@@ -79,6 +84,8 @@ impl Game<'_> {
|
||||
hits.push((c.id as i32, d, [p.x, p.y, p.z]));
|
||||
}
|
||||
}
|
||||
// EnderDragonPart.isPickable: the server's dragon hurts by part.
|
||||
hits.extend(self.remote_dragon_part_hit(eye, dir, reach));
|
||||
}
|
||||
let (id, distance, origin) = hits.into_iter().min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
let point = at(distance);
|
||||
@@ -138,7 +145,10 @@ impl Game<'_> {
|
||||
self.position_rider();
|
||||
return true;
|
||||
}
|
||||
let seat = if let Some(i) = self.boats.iter().position(|b| b.id == id) {
|
||||
let seat = if let Some(c) = self.cushions.iter().find(|c| c.id == id) {
|
||||
// The seat does not move; the rider sits on the cushion.
|
||||
Some(c.seat())
|
||||
} else if let Some(i) = self.boats.iter().position(|b| b.id == id) {
|
||||
// AbstractBoat.tick on the controlling client: steer and move.
|
||||
let mut b = self.boats[i].clone();
|
||||
b.input = [keys.left, keys.right, keys.forward, keys.backward];
|
||||
|
||||
@@ -6,9 +6,9 @@ use horizon_client::{
|
||||
containers::BlockEntity,
|
||||
hud::{HudBatch, rgba},
|
||||
signs::wood_type,
|
||||
ui::EditBox,
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S};
|
||||
use std::time::Instant;
|
||||
use winit::{
|
||||
event::{ElementState, KeyEvent},
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
@@ -18,7 +18,16 @@ pub(super) struct SignEditor {
|
||||
pub pos: (i32, i32, i32),
|
||||
pub front: bool,
|
||||
pub line: usize,
|
||||
pub opened: Instant,
|
||||
/// The line being edited (`AbstractSignEditScreen`'s text field).
|
||||
edit: EditBox,
|
||||
}
|
||||
|
||||
fn sign_box() -> EditBox {
|
||||
let mut edit = EditBox::new(0.0, 0.0, 90.0, 9.0);
|
||||
edit.bordered = false;
|
||||
edit.max_length = 384;
|
||||
edit.focused = true;
|
||||
edit
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -28,8 +37,9 @@ impl Game<'_> {
|
||||
pos,
|
||||
front,
|
||||
line: 0,
|
||||
opened: Instant::now(),
|
||||
edit: sign_box(),
|
||||
});
|
||||
self.sign_load();
|
||||
self.keys.clear();
|
||||
self.right = false;
|
||||
self.capture(false);
|
||||
@@ -140,97 +150,154 @@ impl Game<'_> {
|
||||
/// A key and the text it typed on the sign being edited (the keyboard,
|
||||
/// or a controller's on-screen keyboard).
|
||||
pub(super) fn sign_input(&mut self, key: Option<KeyCode>, typed: Option<&str>) {
|
||||
let Some(edit) = self.sign_edit.as_mut() else {
|
||||
if self.sign_edit.is_none() {
|
||||
return;
|
||||
};
|
||||
let front = edit.front;
|
||||
let id = sign_line_id(front, edit.line);
|
||||
}
|
||||
match key {
|
||||
Some(KeyCode::Escape) => self.close_sign_editor(),
|
||||
Some(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3,
|
||||
Some(KeyCode::ArrowUp) => self.sign_move_line(3),
|
||||
Some(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => {
|
||||
edit.line = (edit.line + 1) & 3
|
||||
self.sign_move_line(1)
|
||||
}
|
||||
Some(KeyCode::Backspace) => {
|
||||
let (line, key) = (edit.line, edit.pos);
|
||||
if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) {
|
||||
let text = if front {
|
||||
&mut sign.front
|
||||
} else {
|
||||
&mut sign.back
|
||||
};
|
||||
let value = &mut text.lines[line];
|
||||
if !self.text_selection.take(id, value) {
|
||||
value.pop();
|
||||
}
|
||||
}
|
||||
Some(
|
||||
key @ (KeyCode::ArrowLeft
|
||||
| KeyCode::ArrowRight
|
||||
| KeyCode::Home
|
||||
| KeyCode::End
|
||||
| KeyCode::Backspace
|
||||
| KeyCode::Delete),
|
||||
) => {
|
||||
let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
|
||||
self.sign_change(|edit| {
|
||||
edit.key(key, ctrl, shift);
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
let Some(typed) = typed else {
|
||||
return;
|
||||
};
|
||||
let line = edit.line;
|
||||
let atlas = &self.gui.atlas;
|
||||
let width = |s: &str| HudBatch::text_width(atlas, s);
|
||||
let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else {
|
||||
return;
|
||||
};
|
||||
if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) {
|
||||
let max = sign.max_line_width();
|
||||
let text = if front {
|
||||
&mut sign.front
|
||||
} else {
|
||||
&mut sign.back
|
||||
};
|
||||
self.text_selection.take(id, &mut text.lines[line]);
|
||||
for ch in typed.chars().filter(|c| !c.is_control()) {
|
||||
let mut next = text.lines[line].clone();
|
||||
next.push(ch);
|
||||
// TextFieldHelper filter: font.width(s) <= maxTextLineWidth.
|
||||
if width(&next) <= max {
|
||||
text.lines[line] = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.sign_change(|edit| edit.insert_text(typed));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `TextFieldHelper.keyPressed`'s shortcuts on the edited line: a paste
|
||||
/// (formatting and carriage returns removed) is taken whole or not at
|
||||
/// all, as the line must stay within the sign's width.
|
||||
fn sign_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
|
||||
/// Up or down a line: the box writes the line it leaves and loads the next.
|
||||
fn sign_move_line(&mut self, by: usize) {
|
||||
self.sign_write();
|
||||
if let Some(edit) = self.sign_edit.as_mut() {
|
||||
edit.line = (edit.line + by) & 3;
|
||||
}
|
||||
self.sign_load();
|
||||
}
|
||||
/// The edited line's text.
|
||||
fn sign_current(&self) -> Option<String> {
|
||||
let edit = self.sign_edit.as_ref()?;
|
||||
let BlockEntity::Sign(sign) = self.world.block_entities.get(&edit.pos)? else {
|
||||
return None;
|
||||
};
|
||||
let side = if edit.front { &sign.front } else { &sign.back };
|
||||
Some(side.lines[edit.line].clone())
|
||||
}
|
||||
/// `EditBox.setValue` from the line now being edited.
|
||||
fn sign_load(&mut self) {
|
||||
let Some(text) = self.sign_current() else {
|
||||
return;
|
||||
};
|
||||
if let Some(edit) = self.sign_edit.as_mut() {
|
||||
edit.edit.set_value(&text);
|
||||
}
|
||||
}
|
||||
/// The box's text onto the sign, when it still fits the line.
|
||||
fn sign_write(&mut self) {
|
||||
let Some(edit) = self.sign_edit.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let (key, front, line) = (edit.pos, edit.front, edit.line);
|
||||
let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else {
|
||||
let (pos, front, line, value) = (edit.pos, edit.front, edit.line, edit.edit.value.clone());
|
||||
if !self.sign_fits(&value) {
|
||||
return;
|
||||
}
|
||||
let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&pos) else {
|
||||
return;
|
||||
};
|
||||
let max = sign.max_line_width();
|
||||
let text = if front {
|
||||
let side = if front {
|
||||
&mut sign.front
|
||||
} else {
|
||||
&mut sign.back
|
||||
};
|
||||
let atlas = &self.gui.atlas;
|
||||
self.text_selection.apply(
|
||||
sign_line_id(front, line),
|
||||
&mut text.lines[line],
|
||||
shortcut,
|
||||
&mut self.clipboard,
|
||||
|value, pasted| {
|
||||
let next = format!(
|
||||
"{value}{}",
|
||||
horizon_client::clipboard::helper_clipboard_contents(pasted)
|
||||
);
|
||||
HudBatch::text_width(atlas, &next) <= max && {
|
||||
*value = next;
|
||||
true
|
||||
}
|
||||
},
|
||||
);
|
||||
side.lines[line] = value;
|
||||
}
|
||||
/// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20).
|
||||
/// TextFieldHelper: `font.width(s) <= maxTextLineWidth`.
|
||||
fn sign_fits(&self, value: &str) -> bool {
|
||||
let Some(edit) = self.sign_edit.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else {
|
||||
return false;
|
||||
};
|
||||
HudBatch::text_width(&self.gui.atlas, value) <= sign.max_line_width()
|
||||
}
|
||||
/// Edit the line, then keep the result only when it still fits.
|
||||
fn sign_change(&mut self, f: impl FnOnce(&mut EditBox)) {
|
||||
let before = self
|
||||
.sign_edit
|
||||
.as_ref()
|
||||
.map(|e| (e.edit.value.clone(), e.edit.cursor, e.edit.highlight));
|
||||
if let Some(edit) = self.sign_edit.as_mut() {
|
||||
f(&mut edit.edit);
|
||||
let clean = horizon_client::clipboard::strip_formatting(&edit.edit.value);
|
||||
if clean != edit.edit.value {
|
||||
let n = horizon_client::ui::char_len(&clean);
|
||||
edit.edit.value = clean;
|
||||
edit.edit.cursor = edit.edit.cursor.min(n);
|
||||
edit.edit.highlight = edit.edit.highlight.min(n);
|
||||
}
|
||||
}
|
||||
self.sign_keep(before);
|
||||
}
|
||||
/// Write the box when the line still fits; otherwise put the old text back.
|
||||
fn sign_keep(&mut self, before: Option<(String, usize, usize)>) {
|
||||
let value = self
|
||||
.sign_edit
|
||||
.as_ref()
|
||||
.map(|e| e.edit.value.clone())
|
||||
.unwrap_or_default();
|
||||
if self.sign_fits(&value) {
|
||||
self.sign_write();
|
||||
} else if let (Some(edit), Some((value, cursor, highlight))) =
|
||||
(self.sign_edit.as_mut(), before)
|
||||
{
|
||||
edit.edit.value = value;
|
||||
edit.edit.cursor = cursor;
|
||||
edit.edit.highlight = highlight;
|
||||
}
|
||||
}
|
||||
/// `TextFieldHelper.keyPressed`'s shortcuts on the edited line. Paste
|
||||
/// reads `getClipboardContents` before `insertText`. A paste that would
|
||||
/// pass the sign's width is refused whole.
|
||||
fn sign_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
|
||||
if shortcut == horizon_client::clipboard::EditShortcut::Paste {
|
||||
let raw = horizon_client::clipboard::Clipboard::get(&mut self.clipboard);
|
||||
let text = horizon_client::clipboard::helper_clipboard_contents(&raw);
|
||||
self.sign_change(|edit| edit.insert_text(&text));
|
||||
return;
|
||||
}
|
||||
let before = self
|
||||
.sign_edit
|
||||
.as_ref()
|
||||
.map(|e| (e.edit.value.clone(), e.edit.cursor, e.edit.highlight));
|
||||
if let Some(edit) = self.sign_edit.as_mut() {
|
||||
edit.edit.shortcut(shortcut, &mut self.clipboard);
|
||||
let clean = horizon_client::clipboard::strip_formatting(&edit.edit.value);
|
||||
if clean != edit.edit.value {
|
||||
let n = horizon_client::ui::char_len(&clean);
|
||||
edit.edit.value = clean;
|
||||
edit.edit.cursor = edit.edit.cursor.min(n);
|
||||
edit.edit.highlight = edit.edit.highlight.min(n);
|
||||
}
|
||||
}
|
||||
self.sign_keep(before);
|
||||
}
|
||||
/// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20),
|
||||
/// or a click on a line (`EditBox.onClick`).
|
||||
pub(super) fn sign_edit_click(&mut self, size: [u32; 2]) {
|
||||
let b = HudBatch::new(size);
|
||||
let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0);
|
||||
@@ -238,7 +305,56 @@ impl Game<'_> {
|
||||
if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 {
|
||||
self.audio.play_button_click();
|
||||
self.close_sign_editor();
|
||||
return;
|
||||
}
|
||||
let Some((cx, top, line_height, max_width, lines)) = self.sign_lines(b.width) else {
|
||||
return;
|
||||
};
|
||||
let shift = self.has_shift_down();
|
||||
for i in 0..lines.len() {
|
||||
let ly = top + i as f32 * line_height;
|
||||
let left = cx - max_width / 2.0;
|
||||
if mx < left || mx >= left + max_width || my < ly || my >= ly + line_height {
|
||||
continue;
|
||||
}
|
||||
let current = self.sign_edit.as_ref().map(|e| e.line);
|
||||
if current != Some(i) {
|
||||
self.sign_move_line((i + 4 - current.unwrap_or(0)) & 3);
|
||||
}
|
||||
let value = self
|
||||
.sign_edit
|
||||
.as_ref()
|
||||
.map(|e| e.edit.value.clone())
|
||||
.unwrap_or_default();
|
||||
let lw = HudBatch::text_width(&self.gui.atlas, &value);
|
||||
let text_x = cx - (lw as i32 / 2) as f32;
|
||||
if let Some(edit) = self.sign_edit.as_mut() {
|
||||
edit.edit.x = text_x;
|
||||
edit.edit.y = ly;
|
||||
edit.edit.width = max_width;
|
||||
edit.edit.click(&self.gui.atlas, mx, shift, false);
|
||||
}
|
||||
self.sign_write();
|
||||
return;
|
||||
}
|
||||
}
|
||||
/// Centre x, the first line's y, the line height, the width limit and the four lines.
|
||||
fn sign_lines(&self, width: f32) -> Option<(f32, f32, f32, f32, Vec<String>)> {
|
||||
let edit = self.sign_edit.as_ref()?;
|
||||
let BlockEntity::Sign(sign) = self.world.block_entities.get(&edit.pos)? else {
|
||||
return None;
|
||||
};
|
||||
let text = if edit.front { &sign.front } else { &sign.back };
|
||||
let line_height = sign.line_height();
|
||||
let y = if sign.hanging { 125.0 } else { 90.0 };
|
||||
let top = y - (4.0 * line_height / 2.0).floor();
|
||||
Some((
|
||||
width / 2.0,
|
||||
top,
|
||||
line_height,
|
||||
sign.max_line_width(),
|
||||
text.lines.to_vec(),
|
||||
))
|
||||
}
|
||||
pub(super) fn draw_sign_editor(&self, batch: &mut HudBatch) {
|
||||
let Some(edit) = &self.sign_edit else { return };
|
||||
@@ -304,23 +420,48 @@ impl Game<'_> {
|
||||
let color = rgba((color >> 16) as u8, (color >> 8) as u8, color as u8, 255);
|
||||
let line_height = sign.line_height();
|
||||
let midpoint = (4.0 * line_height / 2.0).floor();
|
||||
let blink = (edit.opened.elapsed().as_millis() / 300) % 2 == 0;
|
||||
for (i, line) in text.lines.iter().enumerate() {
|
||||
let lw = HudBatch::text_width(atlas, line);
|
||||
let shown = if i == edit.line {
|
||||
edit.edit.value.as_str()
|
||||
} else {
|
||||
line.as_str()
|
||||
};
|
||||
let lw = HudBatch::text_width(atlas, shown);
|
||||
let x = cx - (lw as i32 / 2) as f32;
|
||||
let ly = y + i as f32 * line_height - midpoint;
|
||||
batch.text(atlas, line, x, ly, color, false);
|
||||
if i == edit.line
|
||||
&& self
|
||||
.text_selection
|
||||
.covers(sign_line_id(edit.front, i), line)
|
||||
{
|
||||
// AbstractSignEditScreen: the selection from its start to its end.
|
||||
batch.text_highlight(atlas, (x, ly, lw, line_height), true);
|
||||
batch.text(atlas, shown, x, ly, color, false);
|
||||
if i != edit.line {
|
||||
continue;
|
||||
}
|
||||
if i == edit.line && blink {
|
||||
// TextCursorUtils.extractAppendCursor: an underscore after the text.
|
||||
batch.text(atlas, "_", x + lw, ly, color, false);
|
||||
let value = &edit.edit.value;
|
||||
if edit.edit.cursor != edit.edit.highlight {
|
||||
let (a, b) = (
|
||||
edit.edit.cursor.min(edit.edit.highlight),
|
||||
edit.edit.cursor.max(edit.edit.highlight),
|
||||
);
|
||||
let pre: String = value.chars().take(a).collect();
|
||||
let sel: String = value.chars().skip(a).take(b - a).collect();
|
||||
batch.text_highlight(
|
||||
atlas,
|
||||
(
|
||||
x + HudBatch::text_width(atlas, &pre),
|
||||
ly,
|
||||
HudBatch::text_width(atlas, &sel),
|
||||
line_height,
|
||||
),
|
||||
true,
|
||||
);
|
||||
}
|
||||
if edit.edit.cursor_visible() {
|
||||
let pre: String = value.chars().take(edit.edit.cursor).collect();
|
||||
batch.fill(
|
||||
atlas,
|
||||
x + HudBatch::text_width(atlas, &pre),
|
||||
ly,
|
||||
1.0,
|
||||
line_height,
|
||||
color,
|
||||
);
|
||||
}
|
||||
}
|
||||
let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 144.0);
|
||||
@@ -344,8 +485,3 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sign line being edited, for Select All.
|
||||
fn sign_line_id(front: bool, line: usize) -> horizon_client::clipboard::FieldId {
|
||||
(if front { "sign.front" } else { "sign.back" }, line)
|
||||
}
|
||||
|
||||
@@ -398,8 +398,12 @@ impl GameLevel<'_> {
|
||||
}
|
||||
}
|
||||
PreRemove::Campfire => {
|
||||
for _ in 0..4 {
|
||||
self.drop_item_stack(pos, None);
|
||||
let items = match &entity {
|
||||
Some(BlockEntity::Campfire(c)) => c.items.clone(),
|
||||
_ => Default::default(),
|
||||
};
|
||||
for stack in items {
|
||||
self.drop_item_stack(pos, stack);
|
||||
}
|
||||
}
|
||||
PreRemove::Jukebox => {
|
||||
|
||||
@@ -135,8 +135,10 @@ pub(super) struct Station {
|
||||
pub(super) offers: EnchantOffers,
|
||||
bookcases: i32,
|
||||
pub(super) anvil: AnvilResult,
|
||||
/// Anvil rename box text.
|
||||
/// Anvil rename box text (`AnvilMenu.itemName`).
|
||||
pub(super) name: String,
|
||||
/// The box itself (`AnvilScreen`'s `EditBox` of 50, unbordered).
|
||||
pub(super) rename: horizon_client::ui::EditBox,
|
||||
/// Stonecutter: the menu's recipe list (horizon_client::menu), its
|
||||
/// `selectedRecipeIndex` and the screen's first shown index.
|
||||
pub(super) stone: horizon_client::menu::Stonecutter,
|
||||
@@ -146,8 +148,6 @@ pub(super) struct Station {
|
||||
anvil_last: Option<ItemStack>,
|
||||
/// Anvil on a server: the name last sent (the client menu's `itemName`).
|
||||
pub(super) anvil_sent: Option<String>,
|
||||
/// When the screen opened: the rename box has the focus from then.
|
||||
opened: std::time::Instant,
|
||||
pub(super) last_sound: u64,
|
||||
/// Villager trading state.
|
||||
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
|
||||
@@ -169,12 +169,12 @@ impl Station {
|
||||
bookcases: 0,
|
||||
anvil: AnvilResult::default(),
|
||||
name: String::new(),
|
||||
rename: anvil_box(),
|
||||
stone: Default::default(),
|
||||
selected: None,
|
||||
start: 0,
|
||||
anvil_last: None,
|
||||
anvil_sent: None,
|
||||
opened: std::time::Instant::now(),
|
||||
last_sound: 0,
|
||||
merchant: None,
|
||||
beacon: [None; 2],
|
||||
@@ -868,6 +868,9 @@ impl Game<'_> {
|
||||
if kind == Kind::Stonecutter && self.stonecutter_click(local) {
|
||||
return true;
|
||||
}
|
||||
if kind == Kind::Anvil && !right && self.anvil_name_click(ox, oy) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
|
||||
return true;
|
||||
@@ -894,6 +897,8 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.map(|i| stations::hover_name(&|id| self.pack.names.display_item(id), i))
|
||||
.unwrap_or_default();
|
||||
let name = s.name.clone();
|
||||
s.rename.set_value(&name);
|
||||
}
|
||||
self.station_changed();
|
||||
}
|
||||
@@ -960,21 +965,29 @@ impl Game<'_> {
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let cleared = self.text_selection.take(ANVIL_NAME, &mut s.name);
|
||||
if backspace {
|
||||
if !cleared {
|
||||
s.name.pop();
|
||||
}
|
||||
s.rename.delete_chars(-1);
|
||||
} else if let Some(t) = text {
|
||||
for c in t.chars().filter(|c| !c.is_control()) {
|
||||
if s.name.chars().count() < ANVIL_NAME_CHARS {
|
||||
s.name.push(c);
|
||||
}
|
||||
}
|
||||
s.rename.insert_text(t);
|
||||
}
|
||||
s.name.clone_from(&s.rename.value);
|
||||
self.station_changed();
|
||||
self.remote_anvil_rename();
|
||||
}
|
||||
/// `AnvilScreen.keyPressed`: the rename box handles the key.
|
||||
pub(super) fn station_key(&mut self, key: winit::keyboard::KeyCode) -> bool {
|
||||
let (ctrl, shift) = (self.has_control_down(), self.has_shift_down());
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
if !s.rename.key(key, ctrl, shift) {
|
||||
return false;
|
||||
}
|
||||
s.name.clone_from(&s.rename.value);
|
||||
self.station_changed();
|
||||
self.remote_anvil_rename();
|
||||
true
|
||||
}
|
||||
/// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the
|
||||
/// recipe book's search box.
|
||||
pub(super) fn station_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
|
||||
@@ -985,18 +998,52 @@ impl Game<'_> {
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if Self::append_shortcut(
|
||||
&mut self.text_selection,
|
||||
&mut self.clipboard,
|
||||
ANVIL_NAME,
|
||||
&mut s.name,
|
||||
shortcut,
|
||||
ANVIL_NAME_CHARS,
|
||||
) {
|
||||
if s.rename.shortcut(shortcut, &mut self.clipboard) {
|
||||
s.name.clone_from(&s.rename.value);
|
||||
self.station_changed();
|
||||
self.remote_anvil_rename();
|
||||
}
|
||||
}
|
||||
/// A click in the anvil's name box (`EditBox.onClick`).
|
||||
fn anvil_name_click(&mut self, ox: f32, oy: f32) -> bool {
|
||||
let open = self
|
||||
.station
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.kind == Kind::Anvil && s.inputs[0].is_some());
|
||||
if !open {
|
||||
return false;
|
||||
}
|
||||
let (x, y, w, h) = (ox + 62.0, oy + 24.0, 103.0, 12.0);
|
||||
let (mx, my) = self.cursor;
|
||||
if mx < x || my < y || mx >= x + w || my >= y + h {
|
||||
return false;
|
||||
}
|
||||
let shift = self.has_shift_down();
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
s.rename.x = x;
|
||||
s.rename.y = y;
|
||||
s.rename.width = w;
|
||||
s.rename.click(&self.gui.atlas, mx, shift, false);
|
||||
true
|
||||
}
|
||||
/// AnvilScreen's name box, drawn after the station picture.
|
||||
fn draw_anvil_name(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) {
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let edit = &mut s.rename;
|
||||
edit.x = ox + 62.0;
|
||||
edit.y = oy + 24.0;
|
||||
edit.width = 103.0;
|
||||
edit.height = 12.0;
|
||||
edit.bordered = false;
|
||||
edit.focused = true;
|
||||
edit.text_color = u32::MAX;
|
||||
edit.max_length = ANVIL_NAME_CHARS;
|
||||
edit.draw(batch, &self.gui.atlas, None);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- drawing
|
||||
|
||||
@@ -1094,6 +1141,7 @@ impl Game<'_> {
|
||||
let (ox, oy) = self.inventory_origin(batch);
|
||||
let local = (self.cursor.0 - ox, self.cursor.1 - oy);
|
||||
let mut tooltip: Option<Vec<(horizon_client::text::Text, u32)>> = None;
|
||||
let mut anvil_name = false;
|
||||
// Keep item tooltips as stacks until drawing: text alone loses the
|
||||
// bundle contents component (including in the player's inventory).
|
||||
let mut tooltip_stack: Option<ItemStack> = None;
|
||||
@@ -1431,18 +1479,8 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
if s.inputs[0].is_some() {
|
||||
// AnvilScreen's name box: white, 103 wide, no inverted highlight.
|
||||
horizon_client::ui::append_field(
|
||||
batch,
|
||||
atlas,
|
||||
&s.name,
|
||||
(ox + 62.0, oy + 24.0, 103.0),
|
||||
(u32::MAX, true),
|
||||
ANVIL_NAME_CHARS,
|
||||
self.text_selection.covers(ANVIL_NAME, &s.name),
|
||||
false,
|
||||
s.opened.elapsed().as_millis(),
|
||||
);
|
||||
// Drawn once this borrow of the station ends.
|
||||
anvil_name = true;
|
||||
}
|
||||
let cost = s.anvil.cost;
|
||||
if cost > 0 {
|
||||
@@ -1589,6 +1627,9 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if anvil_name {
|
||||
self.draw_anvil_name(batch, ox, oy);
|
||||
}
|
||||
let drag = self.drag_view();
|
||||
for i in self.station_slots().unwrap_or_default() {
|
||||
let Some((sx, sy)) = self.slot_position_any(i) else {
|
||||
@@ -1662,6 +1703,8 @@ impl Game<'_> {
|
||||
};
|
||||
let name = if let Some(n) = stack.custom_name() {
|
||||
n.to_owned()
|
||||
} else if let Some(n) = stack.item_name() {
|
||||
n
|
||||
} else if stack.data().is_some_and(|d| d.ominous_banner) {
|
||||
self.translate("block.minecraft.ominous_banner", "Ominous Banner")
|
||||
} else if stack.data().and_then(|d| d.potion.as_ref()).is_some()
|
||||
@@ -1688,7 +1731,9 @@ impl Game<'_> {
|
||||
// ItemContainerContents.addToTooltip.
|
||||
let hover_name = |s: &ItemStack| {
|
||||
s.custom_name()
|
||||
.map_or_else(|| self.pack.names.display_item(&s.item), str::to_owned)
|
||||
.map(str::to_owned)
|
||||
.or_else(|| s.item_name())
|
||||
.unwrap_or_else(|| self.pack.names.display_item(&s.item))
|
||||
};
|
||||
if display.shows("minecraft:container") {
|
||||
for text in
|
||||
@@ -2204,5 +2249,13 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
/// The anvil's rename box (`AnvilScreen`: `setMaxLength(50)`).
|
||||
const ANVIL_NAME: horizon_client::clipboard::FieldId = ("anvil.name", 0);
|
||||
const ANVIL_NAME_CHARS: usize = 50;
|
||||
|
||||
fn anvil_box() -> horizon_client::ui::EditBox {
|
||||
let mut edit = horizon_client::ui::EditBox::new(0.0, 0.0, 103.0, 12.0);
|
||||
edit.bordered = false;
|
||||
edit.max_length = ANVIL_NAME_CHARS;
|
||||
edit.text_color = u32::MAX;
|
||||
edit.focused = true;
|
||||
edit
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ mod arena;
|
||||
mod cull;
|
||||
mod end_sky;
|
||||
mod flat;
|
||||
mod hdr;
|
||||
pub mod lightning;
|
||||
mod lod;
|
||||
mod native_material;
|
||||
@@ -504,6 +505,10 @@ pub struct Renderer {
|
||||
occlusion: occlusion::Occlusion,
|
||||
/// Resolution scale and FXAA (Horizon settings).
|
||||
world_post: world_post::Post,
|
||||
/// HDR output (Horizon setting): `Some` while the swapchain is scRGB.
|
||||
hdr: Option<hdr::Hdr>,
|
||||
/// Whether the window's surface can present scRGB.
|
||||
hdr_capable: bool,
|
||||
/// The shader pack's post-processing, and the dimension (legacy id) it was loaded for.
|
||||
pack_post: Option<(i32, Option<pack_post::PackPost>)>,
|
||||
/// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s.
|
||||
@@ -910,15 +915,24 @@ async fn open_device(
|
||||
limits.max_storage_buffer_binding_size,
|
||||
limits.max_texture_array_layers,
|
||||
));
|
||||
match adapter
|
||||
.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("Horizon device"),
|
||||
required_features: features,
|
||||
required_limits: limits,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
{
|
||||
let desc = wgpu::DeviceDescriptor {
|
||||
label: Some("Horizon device"),
|
||||
required_features: features,
|
||||
required_limits: limits,
|
||||
..Default::default()
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let opened = match info.backend {
|
||||
wgpu::Backend::Vulkan => horizon_hdr::open_vulkan_device(&adapter, &desc),
|
||||
_ => None,
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let opened = None;
|
||||
let opened = match opened {
|
||||
Some(opened) => opened,
|
||||
None => adapter.request_device(&desc).await,
|
||||
};
|
||||
match opened {
|
||||
Ok((device, queue)) => {
|
||||
return Ok(Opened {
|
||||
instance,
|
||||
@@ -1043,7 +1057,7 @@ impl Renderer {
|
||||
let info = adapter.get_info();
|
||||
crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info));
|
||||
let size = window.inner_size();
|
||||
let (config, present_modes) = if let Some(surface) = &surface {
|
||||
let (config, present_modes, hdr_capable) = if let Some(surface) = &surface {
|
||||
let mut config = surface
|
||||
.get_default_config(&adapter, size.width.max(1), size.height.max(1))
|
||||
.ok_or("surface has no supported configuration")?;
|
||||
@@ -1071,7 +1085,7 @@ impl Renderer {
|
||||
));
|
||||
}
|
||||
surface.configure(&device, &config);
|
||||
(config, caps.present_modes.clone())
|
||||
(config, caps.present_modes.clone(), hdr::supported(&caps))
|
||||
} else {
|
||||
let format = wgpu::TextureFormat::Bgra8Unorm;
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
@@ -1085,7 +1099,7 @@ impl Renderer {
|
||||
view_formats: vec![format],
|
||||
color_space: wgpu::SurfaceColorSpace::default(),
|
||||
};
|
||||
(config, Vec::new())
|
||||
(config, Vec::new(), false)
|
||||
};
|
||||
let offscreen = surface
|
||||
.is_none()
|
||||
@@ -1929,14 +1943,20 @@ impl Renderer {
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: config.format.remove_srgb_suffix(),
|
||||
// RenderPipelines.CELESTIAL: additive (src alpha, one).
|
||||
// RenderPipelines.CELESTIAL: additive (src alpha, one). The
|
||||
// alpha goes to 0: HDR output (hdr.wgsl) lets the sun and
|
||||
// moon shine; nothing else reads the frame's alpha.
|
||||
blend: Some(wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::SrcAlpha,
|
||||
dst_factor: wgpu::BlendFactor::One,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent::OVER,
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::Zero,
|
||||
dst_factor: wgpu::BlendFactor::Zero,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
}),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
@@ -2420,6 +2440,8 @@ impl Renderer {
|
||||
block_entity_revision: next_block_entity_revision(),
|
||||
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
|
||||
world_post,
|
||||
hdr: None,
|
||||
hdr_capable,
|
||||
pack_post: None,
|
||||
native: None,
|
||||
pass_timing: pack_timing::PassTiming::logging(),
|
||||
@@ -2489,7 +2511,12 @@ impl Renderer {
|
||||
// Wayland allows only one tearing-control object per window surface.
|
||||
self.release_surface();
|
||||
let surface = self.instance.create_surface(self.window.clone())?;
|
||||
surface.configure(&self.device, &self.config);
|
||||
Self::configure(
|
||||
&self.device,
|
||||
&surface,
|
||||
&self.surface_config(),
|
||||
self.hdr.as_ref(),
|
||||
);
|
||||
self.surface = Some(surface);
|
||||
Ok(())
|
||||
}
|
||||
@@ -2552,7 +2579,12 @@ impl Renderer {
|
||||
&& let Some(surface) = &self.surface
|
||||
{
|
||||
self.config.present_mode = mode;
|
||||
surface.configure(&self.device, &self.config);
|
||||
Self::configure(
|
||||
&self.device,
|
||||
surface,
|
||||
&self.surface_config(),
|
||||
self.hdr.as_ref(),
|
||||
);
|
||||
}
|
||||
}
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
@@ -2563,7 +2595,12 @@ impl Renderer {
|
||||
self.config.width = width;
|
||||
self.config.height = height;
|
||||
if let Some(surface) = &self.surface {
|
||||
surface.configure(&self.device, &self.config);
|
||||
Self::configure(
|
||||
&self.device,
|
||||
surface,
|
||||
&self.surface_config(),
|
||||
self.hdr.as_ref(),
|
||||
);
|
||||
} else {
|
||||
self.offscreen = Some(Self::offscreen_target(&self.device, &self.config));
|
||||
}
|
||||
@@ -2895,6 +2932,63 @@ impl Renderer {
|
||||
);
|
||||
}
|
||||
/// Horizon's resolution scale (world pixels per window pixel) and FXAA.
|
||||
/// Configures `surface` and, while HDR output is on, sends its HDR metadata
|
||||
/// again: a new swapchain starts without it.
|
||||
fn configure(
|
||||
device: &wgpu::Device,
|
||||
surface: &wgpu::Surface<'_>,
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
hdr: Option<&hdr::Hdr>,
|
||||
) {
|
||||
surface.configure(device, config);
|
||||
if let Some(hdr) = hdr {
|
||||
horizon_hdr::set_metadata(device, surface, hdr.paper_white, hdr.peak);
|
||||
}
|
||||
}
|
||||
fn configure_surface(&self) {
|
||||
if let Some(surface) = &self.surface {
|
||||
Self::configure(
|
||||
&self.device,
|
||||
surface,
|
||||
&self.surface_config(),
|
||||
self.hdr.as_ref(),
|
||||
);
|
||||
}
|
||||
}
|
||||
fn send_hdr_metadata(&self) {
|
||||
if let (Some(surface), Some(hdr)) = (&self.surface, &self.hdr) {
|
||||
horizon_hdr::set_metadata(&self.device, surface, hdr.paper_white, hdr.peak);
|
||||
}
|
||||
}
|
||||
/// The swapchain's configuration: `config` (what every pipeline draws in), or
|
||||
/// scRGB while HDR output is on.
|
||||
fn surface_config(&self) -> wgpu::SurfaceConfiguration {
|
||||
let mut config = self.config.clone();
|
||||
if self.hdr.is_some() {
|
||||
config.format = hdr::FORMAT;
|
||||
config.view_formats = vec![hdr::FORMAT];
|
||||
config.color_space = hdr::COLOR_SPACE;
|
||||
config.usage = wgpu::TextureUsages::RENDER_ATTACHMENT;
|
||||
}
|
||||
config
|
||||
}
|
||||
/// HDR output (Horizon setting): scRGB at `paper_white` nits, the world's
|
||||
/// highlights expanded up to `peak` nits. Off where the surface can't present it.
|
||||
pub fn set_hdr(&mut self, on: bool, paper_white: f32, peak: f32) {
|
||||
let on = on && self.hdr_capable && self.surface.is_some();
|
||||
if on != self.hdr.is_some() {
|
||||
self.hdr =
|
||||
on.then(|| hdr::Hdr::new(&self.device, self.config.format.remove_srgb_suffix()));
|
||||
self.configure_surface();
|
||||
}
|
||||
if let Some(hdr) = &mut self.hdr
|
||||
&& (hdr.paper_white, hdr.peak) != (paper_white, peak)
|
||||
{
|
||||
hdr.paper_white = paper_white;
|
||||
hdr.peak = peak;
|
||||
self.send_hdr_metadata();
|
||||
}
|
||||
}
|
||||
pub fn set_world_post(&mut self, scale: f32, antialias: bool) {
|
||||
self.world_post.scale = scale.clamp(0.25, 2.0);
|
||||
self.world_post.antialias = antialias;
|
||||
@@ -3230,7 +3324,12 @@ impl Renderer {
|
||||
}
|
||||
Some(wgpu::CurrentSurfaceTexture::Outdated) => {
|
||||
if let Some(surface) = &self.surface {
|
||||
surface.configure(&self.device, &self.config);
|
||||
Self::configure(
|
||||
&self.device,
|
||||
surface,
|
||||
&self.surface_config(),
|
||||
self.hdr.as_ref(),
|
||||
);
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -3242,9 +3341,11 @@ impl Renderer {
|
||||
return Err("surface acquisition failed validation".into());
|
||||
}
|
||||
};
|
||||
let target_texture = match &surface_frame {
|
||||
Some(f) => f.texture.clone(),
|
||||
None => self.offscreen.clone().ok_or("no offscreen target")?,
|
||||
let size = [self.config.width, self.config.height];
|
||||
let target_texture = match (&surface_frame, &mut self.hdr) {
|
||||
(Some(_), Some(hdr)) => hdr.frame(&self.device, size),
|
||||
(Some(f), None) => f.texture.clone(),
|
||||
(None, _) => self.offscreen.clone().ok_or("no offscreen target")?,
|
||||
};
|
||||
// One command buffer for the frame, after the section copies staged
|
||||
// since the last one: Metal commits every command buffer wgpu-core
|
||||
@@ -4642,6 +4743,9 @@ impl Renderer {
|
||||
} else if scaled.is_some() {
|
||||
self.world_post.finish(&mut encoder, &view_target);
|
||||
}
|
||||
if let Some(hdr) = &self.hdr {
|
||||
hdr.keep_world(&mut encoder);
|
||||
}
|
||||
if hand_quads > 0 && !pack_draws_hand {
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view_target,
|
||||
@@ -4796,6 +4900,9 @@ impl Renderer {
|
||||
self.section_copy_bytes = 0;
|
||||
self.section_uploads.finish(&encoder);
|
||||
}
|
||||
if let (Some(hdr), Some(f)) = (&self.hdr, &surface_frame) {
|
||||
hdr.present(&self.queue, &mut encoder, &f.texture, !frame.title);
|
||||
}
|
||||
let commands = crate::spans::time("encode", || encoder.finish());
|
||||
let first_frame = self.first_frame == FirstFrame::Submit;
|
||||
if first_frame {
|
||||
@@ -4832,7 +4939,12 @@ impl Renderer {
|
||||
}
|
||||
self.queue.present(surface_frame);
|
||||
if reconfigure && let Some(surface) = &self.surface {
|
||||
surface.configure(&self.device, &self.config);
|
||||
Self::configure(
|
||||
&self.device,
|
||||
surface,
|
||||
&self.surface_config(),
|
||||
self.hdr.as_ref(),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// No swapchain paces offscreen frames: keep two on the GPU at most.
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//! HDR output (Horizon setting, off by default): the frame renders exactly as
|
||||
//! without it, into an 8-bit target in vanilla's gamma space, and one pass
|
||||
//! (`hdr.wgsl`) writes it to an scRGB swapchain at the player's paper white,
|
||||
//! expanding the world's highlights towards their peak brightness. The world
|
||||
//! is copied aside before the hand and HUD so only it is expanded.
|
||||
|
||||
/// The swapchain format and colour space HDR output presents in.
|
||||
pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
|
||||
pub const COLOR_SPACE: wgpu::SurfaceColorSpace = wgpu::SurfaceColorSpace::ExtendedSrgbLinear;
|
||||
|
||||
/// Whether `caps` can present scRGB.
|
||||
pub fn supported(caps: &wgpu::SurfaceCapabilities) -> bool {
|
||||
caps.color_spaces(FORMAT)
|
||||
.contains(wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR)
|
||||
}
|
||||
|
||||
struct Targets {
|
||||
size: [u32; 2],
|
||||
frame: wgpu::Texture,
|
||||
world: wgpu::Texture,
|
||||
group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
pub struct Hdr {
|
||||
layout: wgpu::BindGroupLayout,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
params: wgpu::Buffer,
|
||||
/// The frame's format: what every other pipeline draws in.
|
||||
format: wgpu::TextureFormat,
|
||||
targets: Option<Targets>,
|
||||
/// `HORIZON_HDR_DEBUG=1`: paint expanded pixels magenta.
|
||||
debug: bool,
|
||||
/// Paper white and peak brightness, in nits.
|
||||
pub paper_white: f32,
|
||||
pub peak: f32,
|
||||
}
|
||||
|
||||
impl Hdr {
|
||||
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon HDR"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("../hdr.wgsl").into()),
|
||||
});
|
||||
let texture = |binding| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Horizon HDR bindings"),
|
||||
entries: &[
|
||||
texture(0),
|
||||
texture(1),
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Horizon HDR"),
|
||||
bind_group_layouts: &[Some(&layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Horizon HDR"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_hdr"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
primitive: Default::default(),
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_hdr"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: FORMAT,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let params = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Horizon HDR parameters"),
|
||||
size: 16,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
Self {
|
||||
layout,
|
||||
pipeline,
|
||||
params,
|
||||
format,
|
||||
targets: None,
|
||||
debug: std::env::var_os("HORIZON_HDR_DEBUG").is_some_and(|v| v == "1"),
|
||||
paper_white: 200.0,
|
||||
peak: 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The 8-bit frame every pass draws into this frame, sized like the window.
|
||||
pub fn frame(&mut self, device: &wgpu::Device, size: [u32; 2]) -> wgpu::Texture {
|
||||
if self.targets.as_ref().is_none_or(|t| t.size != size) {
|
||||
let texture = |label, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: size[0].max(1),
|
||||
height: size[1].max(1),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: self.format,
|
||||
usage: usage | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let frame = texture(
|
||||
"Horizon HDR frame",
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
let world = texture("Horizon HDR world", wgpu::TextureUsages::COPY_DST);
|
||||
let view = |t: &wgpu::Texture| t.create_view(&Default::default());
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Horizon HDR bindings"),
|
||||
layout: &self.layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&view(&frame)),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&view(&world)),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: self.params.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
self.targets = Some(Targets {
|
||||
size,
|
||||
frame,
|
||||
world,
|
||||
group,
|
||||
});
|
||||
}
|
||||
self.targets.as_ref().unwrap().frame.clone()
|
||||
}
|
||||
|
||||
/// Keeps the world as drawn so far, before the hand and HUD cover it.
|
||||
pub fn keep_world(&self, encoder: &mut wgpu::CommandEncoder) {
|
||||
let Some(t) = &self.targets else {
|
||||
return;
|
||||
};
|
||||
encoder.copy_texture_to_texture(
|
||||
t.frame.as_image_copy(),
|
||||
t.world.as_image_copy(),
|
||||
t.frame.size(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Writes the finished frame to the swapchain image `target`.
|
||||
pub fn present(
|
||||
&self,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
target: &wgpu::Texture,
|
||||
world: bool,
|
||||
) {
|
||||
let Some(t) = &self.targets else {
|
||||
return;
|
||||
};
|
||||
let paper = self.paper_white.max(1.0);
|
||||
let params = [
|
||||
paper / 80.0,
|
||||
(self.peak / paper).max(1.0),
|
||||
f32::from(u8::from(world)),
|
||||
f32::from(u8::from(self.debug)),
|
||||
];
|
||||
queue.write_buffer(&self.params, 0, bytemuck::cast_slice(¶ms));
|
||||
let view = target.create_view(&Default::default());
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon HDR"),
|
||||
color_attachments: &attachments,
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, &t.group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ fn horizon_material_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color
|
||||
out.clip = horizon_terrain_globals.view_proj * vec4(pos, 1.0);
|
||||
out.uv = uv;
|
||||
out.layer = layer;
|
||||
out.tint = color;
|
||||
out.tint = vec4(color.rgb, 1.0);
|
||||
let block = max(f32(light.y), horizon_terrain_dynamic_block_light(pos));
|
||||
let sky = f32(light.x);
|
||||
// 16 per level, 15 levels.
|
||||
|
||||
@@ -169,6 +169,7 @@ impl PackAtlas {
|
||||
];
|
||||
let columns = self.columns;
|
||||
// UVs past a sprite (models up to 2, distant tiles) cannot repeat in an atlas: clamped.
|
||||
// The colour's alpha holds HDR's emission level (`mesher::EMISSION_BITS`): packs get 1.
|
||||
let body = format!(
|
||||
" vec4 hz_origin = {origin};\n \
|
||||
uint hz_layer = hz_v_layer & 32767u;\n \
|
||||
@@ -178,7 +179,7 @@ impl PackAtlas {
|
||||
hz_MultiTexCoord0 = vec4((hz_cell + clamp(vec2(hz_v_uv) * hz_origin.w, 0.0, 1.0)) * hz_scale, 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord1 = vec4(float(hz_v_light.y), float(hz_v_light.x), 0.0, 1.0);\n \
|
||||
hz_MultiTexCoord2 = hz_MultiTexCoord1;\n \
|
||||
hz_Color = hz_v_color;\n \
|
||||
hz_Color = vec4(hz_v_color.rgb, 1.0);\n \
|
||||
hz_Normal = vec3(0.0, 1.0, 0.0);\n \
|
||||
hz_tangent = vec4(1.0, 0.0, 0.0, 1.0);\n",
|
||||
scale[0], scale[1],
|
||||
|
||||
@@ -255,6 +255,12 @@ pub struct Graphics {
|
||||
pub resolution_scale: u32,
|
||||
/// FXAA over the world.
|
||||
pub fxaa: bool,
|
||||
/// HDR output (scRGB), where the display path offers it.
|
||||
pub hdr: bool,
|
||||
/// HDR paper white (where SDR white sits), in nits.
|
||||
pub hdr_paper_white: u32,
|
||||
/// HDR peak brightness the world's highlights reach, in nits.
|
||||
pub hdr_peak: u32,
|
||||
/// Battery mode: at most 60 frames per second in a world and 30 in menus
|
||||
/// or behind other windows, and half the worker threads. Off by default;
|
||||
/// it changes when frames are drawn, never what they show or the ticks.
|
||||
@@ -286,6 +292,9 @@ impl Default for Graphics {
|
||||
overlay: Overlay::Off,
|
||||
resolution_scale: 100,
|
||||
fxaa: false,
|
||||
hdr: false,
|
||||
hdr_paper_white: 200,
|
||||
hdr_peak: 1000,
|
||||
battery: false,
|
||||
api: GraphicsApi::Auto,
|
||||
shader_pack: String::new(),
|
||||
@@ -337,6 +346,9 @@ impl Graphics {
|
||||
"workers" => g.workers = number(g.workers).min(64),
|
||||
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
|
||||
"fxaa" => g.fxaa = flag(g.fxaa),
|
||||
"hdr" => g.hdr = flag(g.hdr),
|
||||
"hdrPaperWhite" => g.hdr_paper_white = number(g.hdr_paper_white).clamp(80, 480),
|
||||
"hdrPeak" => g.hdr_peak = number(g.hdr_peak).clamp(200, 2000),
|
||||
"batteryMode" => g.battery = flag(g.battery),
|
||||
"graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(),
|
||||
"pickedShaderPack" => g.shader_pack = value.to_owned(),
|
||||
@@ -354,7 +366,7 @@ impl Graphics {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n",
|
||||
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nhdr:{}\nhdrPaperWhite:{}\nhdrPeak:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n",
|
||||
self.preset.name(),
|
||||
self.lod_distance,
|
||||
self.far_detail.name(),
|
||||
@@ -379,6 +391,9 @@ impl Graphics {
|
||||
},
|
||||
self.resolution_scale,
|
||||
bool_text(self.fxaa),
|
||||
bool_text(self.hdr),
|
||||
self.hdr_paper_white,
|
||||
self.hdr_peak,
|
||||
bool_text(self.battery),
|
||||
self.api.name(),
|
||||
self.shader_pack,
|
||||
@@ -476,6 +491,9 @@ mod tests {
|
||||
overlay: Overlay::Graph,
|
||||
resolution_scale: 75,
|
||||
fxaa: true,
|
||||
hdr: true,
|
||||
hdr_paper_white: 240,
|
||||
hdr_peak: 1400,
|
||||
battery: true,
|
||||
api: GraphicsApi::Dx12,
|
||||
shader_pack: "Golden Hour".into(),
|
||||
|
||||
@@ -37,6 +37,9 @@ pub enum H {
|
||||
Overlay,
|
||||
ResolutionScale,
|
||||
Antialiasing,
|
||||
Hdr,
|
||||
HdrPaperWhite,
|
||||
HdrPeak,
|
||||
BatteryMode,
|
||||
GraphicsApi,
|
||||
}
|
||||
@@ -221,6 +224,21 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
Medium,
|
||||
"FXAA smooths jagged edges of the world; slightly softer image.",
|
||||
),
|
||||
h(
|
||||
H::Hdr,
|
||||
None,
|
||||
"HDR output on an HDR display: lava, fire and sunlight shine brighter.",
|
||||
),
|
||||
h(
|
||||
H::HdrPaperWhite,
|
||||
None,
|
||||
"HDR: how bright white paper and menus look. Match your desktop.",
|
||||
),
|
||||
h(
|
||||
H::HdrPeak,
|
||||
None,
|
||||
"HDR: how bright the brightest highlights get. Your display's peak.",
|
||||
),
|
||||
h(
|
||||
H::PresentMode,
|
||||
None,
|
||||
@@ -324,6 +342,8 @@ impl H {
|
||||
}
|
||||
H::Workers => Some(g.workers as f32 / max_workers() as f32),
|
||||
H::ResolutionScale => Some((g.resolution_scale as f32 - 50.0) / 150.0),
|
||||
H::HdrPaperWhite => Some((g.hdr_paper_white as f32 - 80.0) / 400.0),
|
||||
H::HdrPeak => Some((g.hdr_peak as f32 - 200.0) / 1800.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -365,6 +385,9 @@ impl H {
|
||||
},
|
||||
H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)),
|
||||
H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }),
|
||||
H::Hdr => labelled("HDR", on_off(g.hdr)),
|
||||
H::HdrPaperWhite => labelled("Paper White", format!("{} nits", g.hdr_paper_white)),
|
||||
H::HdrPeak => labelled("Peak Brightness", format!("{} nits", g.hdr_peak)),
|
||||
H::BatteryMode => labelled("Battery Mode", on_off(g.battery)),
|
||||
H::GraphicsApi => labelled("Graphics API", g.api.label()),
|
||||
H::Overlay => labelled(
|
||||
@@ -387,6 +410,8 @@ impl H {
|
||||
}
|
||||
H::Workers => g.workers = (v * max_workers() as f32).round() as u32,
|
||||
H::ResolutionScale => g.resolution_scale = (50.0 + (v * 30.0).round() * 5.0) as u32,
|
||||
H::HdrPaperWhite => g.hdr_paper_white = (80.0 + (v * 40.0).round() * 10.0) as u32,
|
||||
H::HdrPeak => g.hdr_peak = (200.0 + (v * 36.0).round() * 50.0) as u32,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -418,6 +443,7 @@ impl H {
|
||||
H::AnimatedTextures => g.animated_textures = !g.animated_textures,
|
||||
H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back),
|
||||
H::Antialiasing => g.fxaa = !g.fxaa,
|
||||
H::Hdr => g.hdr = !g.hdr,
|
||||
H::BatteryMode => g.battery = !g.battery,
|
||||
H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back),
|
||||
H::Pacing => {
|
||||
@@ -453,6 +479,7 @@ impl Item {
|
||||
Item::Horizon(H::Weather) => g.weather,
|
||||
Item::Horizon(H::AnimatedTextures) => g.animated_textures,
|
||||
Item::Horizon(H::Antialiasing) => g.fxaa,
|
||||
Item::Horizon(H::Hdr) => g.hdr,
|
||||
Item::Horizon(H::BatteryMode) => g.battery,
|
||||
Item::Vanilla(Opt::ViewBobbing) => s.view_bobbing,
|
||||
Item::Vanilla(Opt::Vsync) => s.vsync,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// Horizon's HDR output pass: the frame, drawn as without HDR in vanilla's gamma
|
||||
// space, decoded to linear light at the paper white and written to the scRGB
|
||||
// swapchain (1.0 = 80 nits). Bright pixels of light sources that still show the
|
||||
// world as it was before the hand and HUD are expanded towards the peak.
|
||||
@group(0) @binding(0) var frame: texture_2d<f32>;
|
||||
@group(0) @binding(1) var world: texture_2d<f32>;
|
||||
|
||||
struct Params {
|
||||
// Paper white in scRGB units (nits / 80).
|
||||
paper: f32,
|
||||
// Peak brightness relative to paper white; 1 expands nothing.
|
||||
peak: f32,
|
||||
// 1 when this frame drew a world.
|
||||
world: f32,
|
||||
// 1 paints expanded pixels magenta (HORIZON_HDR_DEBUG=1).
|
||||
debug: f32,
|
||||
};
|
||||
@group(0) @binding(2) var<uniform> params: Params;
|
||||
|
||||
// Light sources are lifted evenly rather than by a highlight curve: vanilla's
|
||||
// textures were drawn for SDR, so a curve on their brightest pixels blows out
|
||||
// near-white spots (glowstone) and leaves the rest (lava, a jack o'lantern's
|
||||
// face) nearly as it was. Pixels brighter than LIFT_FULL get STRENGTH of the
|
||||
// headroom, dimmer ones less down to none at LIFT_START (lava's crust, a
|
||||
// lantern's metal), and no channel goes past the peak. Brightness is the mean
|
||||
// of luminance and the brightest channel, so saturated light counts as bright.
|
||||
const LIFT_START: f32 = 0.18;
|
||||
const LIFT_FULL: f32 = 0.42;
|
||||
const STRENGTH: f32 = 0.7;
|
||||
|
||||
// Whether `c` still shows the world pixel `w`: the same, or darkened evenly
|
||||
// across its channels, as the vignette and other screen-wide tints darken it.
|
||||
// The hand, HUD and text replace pixels instead, so they never pass.
|
||||
fn shows_world(c: vec3<f32>, w: vec3<f32>) -> bool {
|
||||
if all(c == w) {
|
||||
return true;
|
||||
}
|
||||
let k = c / max(w, vec3(1.0 / 255.0));
|
||||
let mean = (k.r + k.g + k.b) / 3.0;
|
||||
return mean <= 1.01 && mean > 0.5 && all(abs(k - vec3(mean)) < vec3(0.03));
|
||||
}
|
||||
|
||||
@vertex fn vs_hdr(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
||||
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
|
||||
return vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
@fragment fn fs_hdr(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let at = vec2<i32>(pos.xy);
|
||||
let c = textureLoad(frame, at, 0).rgb;
|
||||
// Gamma 2.2, as SDR displays and the compositors' SDR paths decode it.
|
||||
var light = pow(max(c, vec3(0.0)), vec3(2.2));
|
||||
let w = textureLoad(world, at, 0);
|
||||
// The world's alpha is 0 on light-emitting blocks, the sun and the moon
|
||||
// (terrain.wgsl, the celestial pipeline): only those shine.
|
||||
if params.world > 0.5 && params.peak > 1.0 && w.a < 0.75 && shows_world(c, w.rgb) {
|
||||
let y = 0.5 * (dot(light, vec3(0.2126, 0.7152, 0.0722)) + max(light.r, max(light.g, light.b)));
|
||||
let lift = smoothstep(LIFT_START, LIFT_FULL, y);
|
||||
if lift > 0.0 {
|
||||
let top = max(light.r, max(light.g, light.b));
|
||||
let gain = min(1.0 + (params.peak - 1.0) * STRENGTH * lift, params.peak / max(top, 1e-4));
|
||||
light *= max(gain, 1.0);
|
||||
if params.debug > 0.5 {
|
||||
light = mix(light, vec3(gain, 0.0, gain), 0.6);
|
||||
}
|
||||
}
|
||||
}
|
||||
return vec4(light * params.paper, 1.0);
|
||||
}
|
||||
@@ -204,6 +204,14 @@ impl ItemStack {
|
||||
pub fn custom_name(&self) -> Option<&str> {
|
||||
self.data().and_then(|d| d.custom_name.as_deref())
|
||||
}
|
||||
/// `minecraft:item_name` in the current language (`getItemName`'s
|
||||
/// component). It stays in the patch as loaded, so a translatable name
|
||||
/// saves and reaches clients unchanged; the ominous banner's is modelled
|
||||
/// by `ominous_banner` instead.
|
||||
pub fn item_name(&self) -> Option<String> {
|
||||
let name = self.data()?.other("minecraft:item_name")?;
|
||||
Some(crate::entity_nbt::name_text(name).plain())
|
||||
}
|
||||
pub fn potion(&self) -> Option<&str> {
|
||||
self.data().and_then(|d| d.potion.as_deref())
|
||||
}
|
||||
|
||||
@@ -286,6 +286,7 @@ mod tests {
|
||||
for (id, name) in [
|
||||
(component::DAMAGE, "minecraft:damage"),
|
||||
(component::CUSTOM_NAME, "minecraft:custom_name"),
|
||||
(component::ITEM_NAME, "minecraft:item_name"),
|
||||
(component::ENCHANTMENTS, "minecraft:enchantments"),
|
||||
(component::POTION_CONTENTS, "minecraft:potion_contents"),
|
||||
(component::REPAIR_COST, "minecraft:repair_cost"),
|
||||
@@ -345,6 +346,10 @@ mod tests {
|
||||
.push((Arc::from("minecraft:sharpness"), 2));
|
||||
d.repair_cost = 9;
|
||||
d.custom_name = Some("Keeper".to_owned());
|
||||
// A translatable item name reaches the client as the same component.
|
||||
let item_name = Tag::compound([("translate", Tag::String("filled_map.monument".into()))]);
|
||||
d.other
|
||||
.push(("minecraft:item_name".into(), item_name.clone()));
|
||||
d.trim = Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry")));
|
||||
let id = |registry: &str, name: &str| {
|
||||
builtin
|
||||
@@ -374,6 +379,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(d.repair_cost, 9);
|
||||
assert_eq!(d.custom_name.as_deref(), Some("Keeper"));
|
||||
assert_eq!(d.other("minecraft:item_name"), Some(&item_name));
|
||||
assert_eq!(
|
||||
d.trim,
|
||||
Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry")))
|
||||
|
||||
@@ -188,6 +188,9 @@ pub fn name_line(stack: &ItemStack, translate: &dyn Fn(&str) -> Option<String>)
|
||||
if let Some(name) = stack.custom_name() {
|
||||
return name.to_owned();
|
||||
}
|
||||
if let Some(name) = stack.item_name() {
|
||||
return name;
|
||||
}
|
||||
if stack.data().is_some_and(|d| d.ominous_banner) {
|
||||
return translate("block.minecraft.ominous_banner")
|
||||
.unwrap_or_else(|| "Ominous Banner".to_owned());
|
||||
@@ -611,6 +614,14 @@ mod tests {
|
||||
assert_eq!(rarity(&banner, "common"), "uncommon");
|
||||
banner.data_mut().custom_name = Some("Captain's Standard".into());
|
||||
assert_eq!(name_line(&banner, &translate), "Captain's Standard");
|
||||
let mut custom_item = ItemStack::new("minecraft:diamond_sword", 1);
|
||||
custom_item.data_mut().other.push((
|
||||
"minecraft:item_name".into(),
|
||||
Tag::String("Excalibur".into()),
|
||||
));
|
||||
assert_eq!(name_line(&custom_item, &translate), "Excalibur");
|
||||
custom_item.data_mut().custom_name = Some("Custom Blade".into());
|
||||
assert_eq!(name_line(&custom_item, &translate), "Custom Blade");
|
||||
banner.enchant("minecraft:unbreaking", 1);
|
||||
assert_eq!(rarity(&banner, "common"), "rare");
|
||||
let plain = ItemStack::new("minecraft:white_banner", 1);
|
||||
|
||||
@@ -122,6 +122,8 @@ pub struct ItemInfo {
|
||||
pub crafting_remainder: Option<String>,
|
||||
/// `dye`: the dye colour name (dyes, and anything else with the component).
|
||||
pub dye: Option<String>,
|
||||
/// `cushion/color`: the DyeColor name of a cushion item.
|
||||
pub cushion_color: Option<String>,
|
||||
/// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks.
|
||||
pub block_transformer: Option<String>,
|
||||
/// Has a default `bundle_contents` (the bundles, `BundleItem`).
|
||||
@@ -609,6 +611,7 @@ impl Items {
|
||||
.map(str::to_owned),
|
||||
jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned),
|
||||
dye: c["minecraft:dye"].as_str().map(str::to_owned),
|
||||
cushion_color: c["minecraft:cushion/color"].as_str().map(str::to_owned),
|
||||
block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned),
|
||||
bundle: c.get("minecraft:bundle_contents").is_some(),
|
||||
crafting_remainder: CRAFT_REMAINDERS
|
||||
|
||||
@@ -952,6 +952,11 @@ pub fn entity_tag(entity: &BlockEntity) -> Option<Tag> {
|
||||
Some(Tag::compound(entries))
|
||||
}
|
||||
BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None,
|
||||
// CampfireBlockEntity.getUpdateTag: the items alone.
|
||||
BlockEntity::Campfire(c) => Some(Tag::compound([(
|
||||
"Items",
|
||||
crate::save::encode_items(&c.items),
|
||||
)])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,6 +645,13 @@ fn network_stack(
|
||||
horizon_protocol::item::Component::Text(horizon_protocol::text::literal(name)),
|
||||
));
|
||||
}
|
||||
// The component as loaded, so a translatable name stays one.
|
||||
if let Some(name) = s.data().and_then(|d| d.other("minecraft:item_name")) {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::ITEM_NAME,
|
||||
horizon_protocol::item::Component::Text(name.clone()),
|
||||
));
|
||||
}
|
||||
Some(stack)
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,10 @@ pub struct Menu {
|
||||
pub sent_data: Vec<i16>,
|
||||
}
|
||||
|
||||
/// The y of the key a chest minecart's or chest boat's items are kept under
|
||||
/// while a menu shows them.
|
||||
pub const VEHICLE_KEY_Y: i32 = -100_000;
|
||||
|
||||
/// Where the slots of a container menu live.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Slots {
|
||||
@@ -72,10 +76,12 @@ impl Slots {
|
||||
Slots::Ender => at.into_iter().collect(),
|
||||
_ => self.halves(),
|
||||
};
|
||||
// A vehicle's container is kept under a key, not a block: the game
|
||||
// checks its reach to the vehicle (`isChestVehicleStillValid`).
|
||||
self.valid(world)
|
||||
&& blocks
|
||||
.iter()
|
||||
.all(|k| guest.within_block_range([k.0, k.1, k.2], 4.0))
|
||||
.all(|k| k.1 == VEHICLE_KEY_Y || guest.within_block_range([k.0, k.1, k.2], 4.0))
|
||||
}
|
||||
/// Container slot `n`.
|
||||
pub fn get(self, world: &World, guest: &Guest, mut n: usize) -> Option<ItemStack> {
|
||||
|
||||
@@ -50,6 +50,7 @@ pub mod cooldowns;
|
||||
pub mod crafting;
|
||||
pub mod crash;
|
||||
pub mod creative;
|
||||
pub mod cushion;
|
||||
pub mod data_cmd;
|
||||
pub mod datapack;
|
||||
pub mod debug_chart;
|
||||
|
||||
@@ -113,6 +113,14 @@ mod vertex_tests {
|
||||
assert!((a - b).abs() <= 0.5 / 32768.0, "{a} {b}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn emission_keeps_the_colour_and_the_free_bits() {
|
||||
let rgb = super::pack_rgb([0x12, 0x34, 0x56]);
|
||||
assert_eq!(super::emitting(rgb, 0), rgb);
|
||||
assert_eq!(super::emitting(rgb, 9), 0xF656_3412);
|
||||
assert_eq!(super::emitting(rgb, 15), 0xF056_3412);
|
||||
assert_eq!(super::emitting(rgb, 15) | super::EMISSION_BITS, rgb);
|
||||
}
|
||||
}
|
||||
pub struct SectionMesh {
|
||||
pub solid: Vec<TerrainVertex>,
|
||||
@@ -566,6 +574,14 @@ impl Padded {
|
||||
}
|
||||
/// Set on a terrain vertex's sprite layer when its texture alpha must be ignored.
|
||||
pub const OPAQUE_LAYER: u16 = 1 << 15;
|
||||
/// The bits of `TerrainVertex::color`'s alpha byte that hold the light its face emits, for
|
||||
/// HDR output's highlights (`gfx/hdr.rs`): 15 minus the level, so the usual 0xFF means none.
|
||||
/// The byte's other four bits stay set.
|
||||
pub const EMISSION_BITS: u32 = 0x0F00_0000;
|
||||
/// `color` marked as emitting light `level` (0 to 15).
|
||||
pub fn emitting(color: u32, level: u8) -> u32 {
|
||||
color & !EMISSION_BITS | u32::from(15 - level.min(15)) << 24
|
||||
}
|
||||
const UNSET: u32 = u32::MAX;
|
||||
const NO_BIOME: u16 = u16::MAX;
|
||||
/// The `ColorResolver`s `ClientLevel` caches block tints for.
|
||||
@@ -880,7 +896,7 @@ impl Mesher<'_> {
|
||||
} else {
|
||||
face.layer as u16
|
||||
},
|
||||
pack_rgb(rgb),
|
||||
emitting(pack_rgb(rgb), state.emission.max(q.light_emission)),
|
||||
pack_coords(lighting::with_emission(coords[i], q.light_emission)),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -227,8 +227,11 @@ pub(super) fn tesselate(
|
||||
} else {
|
||||
0xFF_FFFF
|
||||
};
|
||||
// Lava emits light level 15.
|
||||
let emission = if water { 0 } else { 15 };
|
||||
let color = |by: f32| {
|
||||
pack_rgb([16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32))
|
||||
let rgb = [16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32);
|
||||
crate::mesher::emitting(pack_rgb(rgb), emission)
|
||||
};
|
||||
let height = |p: [i32; 3]| -> f32 {
|
||||
let s = at(p);
|
||||
|
||||
@@ -11,9 +11,15 @@ use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const SERVER_NAME: crate::clipboard::FieldId = ("server.name", 0);
|
||||
const SERVER_ADDRESS: crate::clipboard::FieldId = ("server.address", 0);
|
||||
const SERVER_DIRECT: crate::clipboard::FieldId = ("server.direct", 0);
|
||||
const FRIEND_CODE: crate::clipboard::FieldId = ("friend.code", 0);
|
||||
const FRIEND_RELAY: crate::clipboard::FieldId = ("friend.relay", 0);
|
||||
|
||||
/// The result of pinging one address.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Ping {
|
||||
@@ -587,18 +593,21 @@ impl Screen {
|
||||
}
|
||||
}
|
||||
/// An EditBox and its label: the label at `label_y` (one pixel in, in
|
||||
/// 0xA0A0A0), the 200x20 box at `box_y`.
|
||||
/// 0xA0A0A0), the 200x20 box at `box_y`. The box is the same `EditBox`
|
||||
/// the world screens edit (`Caret`): cursor, selection and scrolling.
|
||||
fn field(
|
||||
atlas: &HudAtlas,
|
||||
batch: &mut HudBatch,
|
||||
caret: &mut crate::ui::Caret,
|
||||
focused_at: Instant,
|
||||
label: &str,
|
||||
value: &str,
|
||||
id: crate::clipboard::FieldId,
|
||||
max: usize,
|
||||
(label_y, box_y): (f32, f32),
|
||||
focused: bool,
|
||||
blink: bool,
|
||||
) {
|
||||
let x = (batch.width.ceil() / 2.0).floor() - 100.0;
|
||||
crate::widgets::target_as([x, box_y, 200.0, 20.0], crate::widgets::Kind::Field);
|
||||
batch.text(
|
||||
atlas,
|
||||
label,
|
||||
@@ -607,35 +616,25 @@ impl Screen {
|
||||
rgba(160, 160, 160, 255),
|
||||
true,
|
||||
);
|
||||
batch.fill(
|
||||
caret.draw(
|
||||
batch,
|
||||
atlas,
|
||||
x,
|
||||
box_y,
|
||||
200.0,
|
||||
20.0,
|
||||
if focused {
|
||||
u32::MAX
|
||||
} else {
|
||||
rgba(160, 160, 160, 255)
|
||||
},
|
||||
);
|
||||
batch.fill(atlas, x + 1.0, box_y + 1.0, 198.0, 18.0, rgba(0, 0, 0, 255));
|
||||
let shown = if focused && blink {
|
||||
format!("{value}_")
|
||||
} else {
|
||||
value.to_owned()
|
||||
};
|
||||
batch.text(
|
||||
atlas,
|
||||
&shown,
|
||||
x + 4.0,
|
||||
box_y + 6.0,
|
||||
rgba(224, 224, 224, 255),
|
||||
true,
|
||||
(id, value, max),
|
||||
[x, box_y, 200.0, 20.0],
|
||||
focused,
|
||||
focused_at,
|
||||
);
|
||||
}
|
||||
pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool, cursor: (f32, f32)) {
|
||||
pub fn draw(
|
||||
&self,
|
||||
atlas: &HudAtlas,
|
||||
batch: &mut HudBatch,
|
||||
caret: &mut crate::ui::Caret,
|
||||
focused_at: Instant,
|
||||
cursor: (f32, f32),
|
||||
) {
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let max = self.max_length();
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| {
|
||||
let tw = HudBatch::text_width(atlas, text);
|
||||
@@ -888,20 +887,26 @@ impl Screen {
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
caret,
|
||||
focused_at,
|
||||
&crate::lang::get_or("manageServer.enterName", "Server Name"),
|
||||
name,
|
||||
SERVER_NAME,
|
||||
max,
|
||||
(53.0, 66.0),
|
||||
*focus == 0,
|
||||
blink,
|
||||
);
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
caret,
|
||||
focused_at,
|
||||
&crate::lang::get_or("manageServer.enterIp", "Server Address"),
|
||||
address,
|
||||
SERVER_ADDRESS,
|
||||
max,
|
||||
(94.0, 106.0),
|
||||
*focus == 1,
|
||||
blink,
|
||||
);
|
||||
}
|
||||
Self::Direct { address } => {
|
||||
@@ -916,11 +921,14 @@ impl Screen {
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
caret,
|
||||
focused_at,
|
||||
&crate::lang::get_or("manageServer.enterIp", "Server Address"),
|
||||
address,
|
||||
SERVER_DIRECT,
|
||||
max,
|
||||
(100.0, 116.0),
|
||||
true,
|
||||
blink,
|
||||
);
|
||||
}
|
||||
Self::ConfirmDelete { name, lines, .. } => {
|
||||
@@ -954,20 +962,26 @@ impl Screen {
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
caret,
|
||||
focused_at,
|
||||
"Invite Code",
|
||||
code,
|
||||
FRIEND_CODE,
|
||||
max,
|
||||
(53.0, 64.0),
|
||||
*focus == 0,
|
||||
blink,
|
||||
);
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
caret,
|
||||
focused_at,
|
||||
"Relay (optional)",
|
||||
relay,
|
||||
FRIEND_RELAY,
|
||||
max,
|
||||
(94.0, 105.0),
|
||||
*focus == 1,
|
||||
blink,
|
||||
);
|
||||
}
|
||||
Self::Disconnected { reason, retry } => {
|
||||
@@ -1261,6 +1275,19 @@ impl Screen {
|
||||
scroll.release();
|
||||
}
|
||||
}
|
||||
/// The focused box, in GUI pixels: name at 66, address at 106
|
||||
/// (`ManageServerScreen`), direct address at 116, friend fields at 64 and 105.
|
||||
pub fn focused_box(&self, (w, _h): (f32, f32)) -> Option<[f32; 4]> {
|
||||
let y = match self {
|
||||
Self::Edit { focus: 0, .. } => 66.0,
|
||||
Self::Edit { .. } => 106.0,
|
||||
Self::Direct { .. } => 116.0,
|
||||
Self::Friend { focus: 0, .. } => 64.0,
|
||||
Self::Friend { .. } => 105.0,
|
||||
_ => return None,
|
||||
};
|
||||
Some([(w / 2.0).floor() - 100.0, y, 200.0, 20.0])
|
||||
}
|
||||
fn focused_field(&mut self) -> Option<&mut String> {
|
||||
match self {
|
||||
Self::Edit {
|
||||
@@ -1297,11 +1324,11 @@ impl Screen {
|
||||
/// The focused text field, its id and maximum length (copy and paste).
|
||||
pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> {
|
||||
let id = match self {
|
||||
Self::Edit { focus: 0, .. } => ("server.name", 0),
|
||||
Self::Edit { .. } => ("server.address", 0),
|
||||
Self::Direct { .. } => ("server.direct", 0),
|
||||
Self::Friend { focus: 0, .. } => ("friend.code", 0),
|
||||
Self::Friend { .. } => ("friend.relay", 0),
|
||||
Self::Edit { focus: 0, .. } => SERVER_NAME,
|
||||
Self::Edit { .. } => SERVER_ADDRESS,
|
||||
Self::Direct { .. } => SERVER_DIRECT,
|
||||
Self::Friend { focus: 0, .. } => FRIEND_CODE,
|
||||
Self::Friend { .. } => FRIEND_RELAY,
|
||||
_ => return None,
|
||||
};
|
||||
let max = self.max_length();
|
||||
@@ -1315,21 +1342,6 @@ impl Screen {
|
||||
128
|
||||
}
|
||||
}
|
||||
pub fn type_text(&mut self, text: &str) {
|
||||
let max = self.max_length();
|
||||
if let Some(field) = self.focused_field() {
|
||||
for c in text.chars().filter(|c| !c.is_control()) {
|
||||
if field.chars().count() < max {
|
||||
field.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn backspace(&mut self) {
|
||||
if let Some(field) = self.focused_field() {
|
||||
field.pop();
|
||||
}
|
||||
}
|
||||
pub fn tab(&mut self) {
|
||||
if let Self::Edit { focus, .. } | Self::Friend { focus, .. } = self {
|
||||
*focus = (*focus + 1) % 2;
|
||||
|
||||
@@ -526,6 +526,12 @@ pub fn encode_block_entity(
|
||||
}
|
||||
}
|
||||
BlockEntity::Sculk(s) => entries.extend(s.to_nbt()),
|
||||
// CampfireBlockEntity.saveAdditional.
|
||||
BlockEntity::Campfire(c) => {
|
||||
entries.push(("Items", encode_items(&c.items)));
|
||||
entries.push(("CookingTimes", Tag::IntArray(c.progress.to_vec())));
|
||||
entries.push(("CookingTotalTimes", Tag::IntArray(c.total.to_vec())));
|
||||
}
|
||||
BlockEntity::Crafter(c) => {
|
||||
entries.push(("Items", encode_items(&c.items)));
|
||||
entries.push((
|
||||
@@ -706,6 +712,18 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
|
||||
}
|
||||
BlockEntity::Sign(sign) => sign.decode(tag),
|
||||
BlockEntity::Sculk(s) => s.load(tag),
|
||||
// CampfireBlockEntity.loadAdditional: missing time arrays stay zeros.
|
||||
BlockEntity::Campfire(c) => {
|
||||
for (slot, item) in decode_items(tag.get("Items"), 4).into_iter().enumerate() {
|
||||
c.items[slot] = item;
|
||||
}
|
||||
let ints = |key: &str| match tag.get(key) {
|
||||
Some(Tag::IntArray(v)) => std::array::from_fn(|i| v.get(i).copied().unwrap_or(0)),
|
||||
_ => [0; 4],
|
||||
};
|
||||
c.progress = ints("CookingTimes");
|
||||
c.total = ints("CookingTotalTimes");
|
||||
}
|
||||
BlockEntity::Crafter(c) => {
|
||||
for (slot, item) in decode_items(tag.get("Items"), 9).into_iter().enumerate() {
|
||||
c.items[slot] = item;
|
||||
@@ -3875,6 +3893,31 @@ mod tests {
|
||||
assert_eq!(back.redstone_signal(), 2);
|
||||
}
|
||||
#[test]
|
||||
fn campfire_block_entity_round_trips() {
|
||||
let mut c = crate::containers::Campfire::default();
|
||||
c.items[1] = Some(crate::items::ItemStack::new("minecraft:beef", 1));
|
||||
c.progress[1] = 120;
|
||||
c.total[1] = 600;
|
||||
let tag = encode_block_entity(
|
||||
(3, 64, -2),
|
||||
&crate::containers::BlockEntity::Campfire(Box::new(c.clone())),
|
||||
"minecraft:soul_campfire",
|
||||
);
|
||||
// One block entity type for both campfires.
|
||||
assert_eq!(text(tag.get("id")).as_deref(), Some("minecraft:campfire"));
|
||||
let (pos, back) = decode_block_entity(&tag).expect("campfire");
|
||||
assert_eq!(pos, (3, 64, -2));
|
||||
let crate::containers::BlockEntity::Campfire(back) = back else {
|
||||
panic!("not a campfire");
|
||||
};
|
||||
assert_eq!(*back, c);
|
||||
// The update tag a server's clients get: the items alone.
|
||||
let update =
|
||||
crate::lan::chunks::entity_tag(&crate::containers::BlockEntity::Campfire(Box::new(c)))
|
||||
.expect("update tag");
|
||||
assert!(update.get("Items").is_some() && update.get("CookingTimes").is_none());
|
||||
}
|
||||
#[test]
|
||||
fn spawner_block_entity_round_trips() {
|
||||
// A dungeon spawner as vanilla saves it (`id` is mob_spawner, not the block).
|
||||
let saved = horizon_world::nbt::parse_snbt(
|
||||
|
||||
@@ -175,7 +175,9 @@ pub fn increased_repair_cost(cost: u32) -> u32 {
|
||||
pub fn hover_name(names: &dyn Fn(&str) -> String, stack: &ItemStack) -> String {
|
||||
stack
|
||||
.custom_name()
|
||||
.map_or_else(|| names(&stack.item), str::to_owned)
|
||||
.map(str::to_owned)
|
||||
.or_else(|| stack.item_name())
|
||||
.unwrap_or_else(|| names(&stack.item))
|
||||
}
|
||||
/// `AnvilMenu.createResult`. `name` is the rename box text (None = untouched).
|
||||
pub fn anvil_result(
|
||||
|
||||
@@ -69,6 +69,8 @@ struct TerrainOut {
|
||||
@location(2) color: vec4<f32>,
|
||||
@location(3) spherical: f32,
|
||||
@location(4) cylindrical: f32,
|
||||
// The light the face emits, 0 to 15 (mesher.rs's `EMISSION_BITS`).
|
||||
@location(5) @interpolate(flat) emission: u32,
|
||||
}
|
||||
// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units
|
||||
// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one
|
||||
@@ -121,7 +123,8 @@ fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f3
|
||||
out.uv = uv;
|
||||
out.layer = layer;
|
||||
let block = max(f32(light.y), dynamic_block_light(pos));
|
||||
out.color = color * sample_lightmap(f32(light.x) / 16.0, block / 16.0);
|
||||
out.color = vec4(color.rgb, 1.0) * sample_lightmap(f32(light.x) / 16.0, block / 16.0);
|
||||
out.emission = 15u - (u32(round(color.a * 255.0)) & 15u);
|
||||
out.spherical = length(pos);
|
||||
out.cylindrical = max(length(pos.xz), abs(pos.y));
|
||||
return out;
|
||||
@@ -140,7 +143,10 @@ fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
|
||||
// Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
|
||||
let color = sprite(in.uv, in.layer & 0x7fffu) * in.color;
|
||||
if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; }
|
||||
return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical);
|
||||
// Alpha 0 tells HDR output (hdr.wgsl) a light-emitting block's bright pixels
|
||||
// may shine. Nothing else reads the frame's alpha.
|
||||
let emissive = select(1.0, 0.0, in.emission > 0u);
|
||||
return apply_fog(vec4(color.rgb, emissive), in.spherical, in.cylindrical);
|
||||
}
|
||||
@fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4<f32> {
|
||||
let color = sprite(in.uv, in.layer & 0x7fffu) * in.color;
|
||||
|
||||
@@ -1119,7 +1119,8 @@ impl Title {
|
||||
Mode::Multiplayer(screen) => screen.draw(
|
||||
atlas,
|
||||
batch,
|
||||
(self.started.elapsed().as_millis() / 300).is_multiple_of(2),
|
||||
&mut self.caret.borrow_mut(),
|
||||
self.started,
|
||||
cursor,
|
||||
),
|
||||
}
|
||||
@@ -1414,8 +1415,7 @@ impl Title {
|
||||
mode => caret_field(mode, self.search_focused, &mut self.search),
|
||||
}
|
||||
}
|
||||
/// Whether the focused field edits at its cursor (every field but the
|
||||
/// server screens', which still append).
|
||||
/// Whether the focused field edits at its cursor.
|
||||
pub fn has_caret_field(&mut self) -> bool {
|
||||
caret_field(&mut self.mode, self.search_focused, &mut self.search).is_some()
|
||||
}
|
||||
@@ -1435,15 +1435,9 @@ impl Title {
|
||||
}
|
||||
/// EditBox.charTyped / insertText at the cursor.
|
||||
pub fn type_text(&mut self, text: &str) {
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode {
|
||||
return screen.type_text(text);
|
||||
}
|
||||
self.edit_field(|edit| edit.insert_text(text));
|
||||
}
|
||||
pub fn backspace(&mut self) {
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode {
|
||||
return screen.backspace();
|
||||
}
|
||||
self.field_key(winit::keyboard::KeyCode::Backspace, false, false);
|
||||
}
|
||||
/// EditBox.keyPressed: moving and deleting in the focused field.
|
||||
@@ -1471,6 +1465,7 @@ impl Title {
|
||||
Mode::Create { focus, options, .. } => create_world::field_rect(w, h, options.tab)
|
||||
.filter(|(id, _)| id == focus)
|
||||
.map(|(_, rect)| rect),
|
||||
Mode::Multiplayer(screen) => screen.focused_box((w, h)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -1623,8 +1618,9 @@ const SEARCH: crate::clipboard::FieldId = ("world.search", 0);
|
||||
const EDIT_NAME: crate::clipboard::FieldId = ("world.edit-name", 0);
|
||||
const WORLD_NAME: crate::clipboard::FieldId = ("world.name", 0);
|
||||
const WORLD_SEED: crate::clipboard::FieldId = ("world.seed", 0);
|
||||
/// The focused field of the world screens: the list's search, the world
|
||||
/// name being edited, or Create New World's name or seed.
|
||||
/// The focused field of the world screens and the server screens: the list's
|
||||
/// search, a world name or seed, or Add Server, Direct Connection and Join a
|
||||
/// Friend.
|
||||
fn caret_field<'a>(
|
||||
mode: &'a mut Mode,
|
||||
search_focused: bool,
|
||||
@@ -1644,6 +1640,7 @@ fn caret_field<'a>(
|
||||
1 => Some((WORLD_SEED, seed, 32)),
|
||||
_ => None,
|
||||
},
|
||||
Mode::Multiplayer(screen) => screen.focused_text(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -824,3 +824,50 @@ fn world_fields_edit_at_their_cursor() {
|
||||
f.title.field_key(KeyCode::Backspace, false, false);
|
||||
assert_eq!(f.title.search, "world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_fields_edit_at_their_cursor() {
|
||||
use winit::keyboard::KeyCode;
|
||||
let mut f = Fixture::new();
|
||||
f.title.mode = Mode::Multiplayer(crate::multiplayer::Screen::Edit {
|
||||
index: None,
|
||||
name: "Minecraft Server".into(),
|
||||
address: String::new(),
|
||||
focus: 1,
|
||||
packs: None,
|
||||
});
|
||||
f.title.type_text("localhost");
|
||||
for _ in 0..4 {
|
||||
assert!(f.title.field_key(KeyCode::ArrowLeft, false, false));
|
||||
}
|
||||
f.title.type_text("X");
|
||||
let Mode::Multiplayer(crate::multiplayer::Screen::Edit { address, .. }) = &f.title.mode else {
|
||||
panic!("add server");
|
||||
};
|
||||
assert_eq!(address, "localXhost");
|
||||
// Shift+Home selects back to the start; typing replaces the selection.
|
||||
f.title.field_key(KeyCode::Home, false, true);
|
||||
f.title.type_text("Y");
|
||||
let Mode::Multiplayer(crate::multiplayer::Screen::Edit { address, .. }) = &f.title.mode else {
|
||||
panic!("add server");
|
||||
};
|
||||
assert_eq!(address, "Yhost");
|
||||
// Tab moves to the name, which edits at its own cursor.
|
||||
f.title.tab();
|
||||
f.title.field_key(KeyCode::ArrowLeft, false, false);
|
||||
f.title.type_text("X");
|
||||
let Mode::Multiplayer(crate::multiplayer::Screen::Edit { name, .. }) = &f.title.mode else {
|
||||
panic!("add server");
|
||||
};
|
||||
assert_eq!(name, "Minecraft ServeXr");
|
||||
f.title.mode = Mode::Multiplayer(crate::multiplayer::Screen::Direct {
|
||||
address: String::new(),
|
||||
});
|
||||
f.title.type_text("one two");
|
||||
// Ctrl+Backspace deletes the word before the caret.
|
||||
f.title.field_key(KeyCode::Backspace, true, false);
|
||||
let Mode::Multiplayer(crate::multiplayer::Screen::Direct { address }) = &f.title.mode else {
|
||||
panic!("direct");
|
||||
};
|
||||
assert_eq!(address, "one ");
|
||||
}
|
||||
|
||||
@@ -658,6 +658,8 @@ pub struct EditBox {
|
||||
display: usize,
|
||||
pub max_length: usize,
|
||||
pub bordered: bool,
|
||||
/// `MultiLineEditBox`: a book page keeps line breaks. A single-line box strips them.
|
||||
pub multiline: bool,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub width: f32,
|
||||
@@ -669,7 +671,7 @@ pub struct EditBox {
|
||||
pub text_color: u32,
|
||||
}
|
||||
/// The focused text field of a screen that keeps its values as `String`s
|
||||
/// (the world list's search, world names, seeds): the `EditBox` state that
|
||||
/// (the world list's search, world names, seeds, and the server screens): the `EditBox` state that
|
||||
/// outlives a frame, its cursor, selection and scroll.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Caret {
|
||||
@@ -853,6 +855,38 @@ pub fn word_position(value: &str, dir: isize, from: usize) -> usize {
|
||||
}
|
||||
pos
|
||||
}
|
||||
/// `MultilineTextField.getPreviousWord` / `getNextWord`'s `beginIndex` (a book page): any
|
||||
/// whitespace, line breaks included, separates words, and the search starts from the cursor
|
||||
/// clamped to the last character, as vanilla's does.
|
||||
pub fn multiline_word_position(value: &str, dir: isize, from: usize) -> usize {
|
||||
let chars: Vec<char> = value.chars().collect();
|
||||
if chars.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let mut pos = from.min(chars.len() - 1);
|
||||
if dir < 0 {
|
||||
while pos > 0 && java_whitespace(chars[pos - 1]) {
|
||||
pos -= 1;
|
||||
}
|
||||
while pos > 0 && !java_whitespace(chars[pos - 1]) {
|
||||
pos -= 1;
|
||||
}
|
||||
} else {
|
||||
while pos < chars.len() && !java_whitespace(chars[pos]) {
|
||||
pos += 1;
|
||||
}
|
||||
while pos < chars.len() && java_whitespace(chars[pos]) {
|
||||
pos += 1;
|
||||
}
|
||||
}
|
||||
pos
|
||||
}
|
||||
/// `Character.isWhitespace`: Unicode spaces and line breaks but not the no-break spaces, plus
|
||||
/// the ASCII separators U+001C to U+001F.
|
||||
fn java_whitespace(c: char) -> bool {
|
||||
(c.is_whitespace() && !matches!(c, '\u{85}' | '\u{a0}' | '\u{2007}' | '\u{202f}'))
|
||||
|| ('\u{1c}'..='\u{1f}').contains(&c)
|
||||
}
|
||||
/// `EditBox.deleteWords(dir)` for an append-only field, whose caret is at the
|
||||
/// end: removes the word in that direction. True when the value changed.
|
||||
pub fn delete_words(value: &mut String, dir: isize) -> bool {
|
||||
@@ -887,6 +921,7 @@ impl EditBox {
|
||||
display: 0,
|
||||
max_length: 32,
|
||||
bordered: true,
|
||||
multiline: false,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
@@ -917,6 +952,10 @@ impl EditBox {
|
||||
pub fn reset_blink(&mut self) {
|
||||
self.focused_at = Instant::now();
|
||||
}
|
||||
/// The caret is showing (`EditBox`'s blink, on for 300 ms of every 600).
|
||||
pub fn cursor_visible(&self) -> bool {
|
||||
self.focused && (self.focused_at.elapsed().as_millis() / 300).is_multiple_of(2)
|
||||
}
|
||||
pub fn set_value(&mut self, value: &str) {
|
||||
self.value = value.chars().take(self.max_length).collect();
|
||||
self.move_cursor_to_end(false);
|
||||
@@ -934,7 +973,7 @@ impl EditBox {
|
||||
/// EditBox.insertText: replace the selection, respecting the maximum length.
|
||||
pub fn insert_text(&mut self, text: &str) {
|
||||
let (a, b) = self.selected();
|
||||
let filtered = crate::clipboard::filter_text(text, false);
|
||||
let filtered = crate::clipboard::filter_text(text, self.multiline);
|
||||
let room = self
|
||||
.max_length
|
||||
.saturating_sub(char_len(&self.value) - (b - a));
|
||||
@@ -960,9 +999,13 @@ impl EditBox {
|
||||
pub fn word_position(&self, dir: isize) -> usize {
|
||||
self.word_position_from(dir, self.cursor)
|
||||
}
|
||||
/// EditBox.getWordPosition(dir, from).
|
||||
/// EditBox.getWordPosition(dir, from), or MultilineTextField's word for a book page.
|
||||
fn word_position_from(&self, dir: isize, from: usize) -> usize {
|
||||
word_position(&self.value, dir, from)
|
||||
if self.multiline {
|
||||
multiline_word_position(&self.value, dir, from)
|
||||
} else {
|
||||
word_position(&self.value, dir, from)
|
||||
}
|
||||
}
|
||||
pub fn set_cursor(&mut self, pos: usize, select: bool) {
|
||||
self.cursor = pos.min(char_len(&self.value));
|
||||
@@ -1492,6 +1535,17 @@ mod tests {
|
||||
assert_eq!(word_position("hi", 1, 99), 2);
|
||||
}
|
||||
#[test]
|
||||
fn multiline_words_split_at_any_whitespace() {
|
||||
// Ctrl+Backspace at the end of `one\ntwo` deletes `two` only.
|
||||
assert_eq!(multiline_word_position("one\ntwo", -1, 7), 4);
|
||||
// From the end the search starts at the last character, as vanilla's does.
|
||||
assert_eq!(multiline_word_position("one\n", -1, 4), 0);
|
||||
assert_eq!(multiline_word_position("a b", -1, 3), 0);
|
||||
assert_eq!(multiline_word_position("one\n\ntwo", 1, 0), 5);
|
||||
assert_eq!(multiline_word_position("one\u{a0}two", 1, 0), 7);
|
||||
assert_eq!(multiline_word_position("", -1, 0), 0);
|
||||
}
|
||||
#[test]
|
||||
fn delete_words_removes_the_word_before_the_end() {
|
||||
let mut v = "stone bricks".to_string();
|
||||
assert!(delete_words(&mut v, -1));
|
||||
|
||||
@@ -18,7 +18,8 @@ struct PostOut {
|
||||
}
|
||||
|
||||
@fragment fn fs_copy(in: PostOut) -> @location(0) vec4<f32> {
|
||||
return vec4(textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb, 1.0);
|
||||
// The alpha carries the emissive mark through to HDR output (hdr.wgsl).
|
||||
return textureSampleLevel(world, world_sampler, in.uv, 0.0);
|
||||
}
|
||||
|
||||
fn luma(c: vec3<f32>) -> f32 {
|
||||
@@ -28,7 +29,8 @@ fn luma(c: vec3<f32>) -> f32 {
|
||||
// FXAA 3.11 (console quality): blend along the local edge direction.
|
||||
@fragment fn fs_fxaa(in: PostOut) -> @location(0) vec4<f32> {
|
||||
let texel = 1.0 / vec2<f32>(textureDimensions(world));
|
||||
let rgb_m = textureSampleLevel(world, world_sampler, in.uv, 0.0).rgb;
|
||||
let centre = textureSampleLevel(world, world_sampler, in.uv, 0.0);
|
||||
let rgb_m = centre.rgb;
|
||||
let nw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, -0.5) * texel, 0.0).rgb);
|
||||
let ne = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(0.5, -0.5) * texel, 0.0).rgb);
|
||||
let sw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, 0.5) * texel, 0.0).rgb);
|
||||
@@ -37,7 +39,7 @@ fn luma(c: vec3<f32>) -> f32 {
|
||||
let lo = min(m, min(min(nw, ne), min(sw, se)));
|
||||
let hi = max(m, max(max(nw, ne), max(sw, se)));
|
||||
if hi - lo < max(0.0312, hi * 0.125) {
|
||||
return vec4(rgb_m, 1.0);
|
||||
return centre;
|
||||
}
|
||||
var dir = vec2(-((nw + ne) - (sw + se)), (nw + sw) - (ne + se));
|
||||
let reduce = max((nw + ne + sw + se) * 0.25 * 0.125, 1.0 / 128.0);
|
||||
@@ -49,7 +51,7 @@ fn luma(c: vec3<f32>) -> f32 {
|
||||
+ textureSampleLevel(world, world_sampler, in.uv + dir * 0.5, 0.0).rgb);
|
||||
let lb = luma(b);
|
||||
if lb < lo || lb > hi {
|
||||
return vec4(a, 1.0);
|
||||
return vec4(a, centre.a);
|
||||
}
|
||||
return vec4(b, 1.0);
|
||||
return vec4(b, centre.a);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "horizon-hdr"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.85"
|
||||
description = "HDR metadata for the swapchain: the Vulkan calls the crates that forbid unsafe code can't make"
|
||||
|
||||
[dependencies]
|
||||
wgpu = { version = "30.0.1", default-features = false, features = ["vulkan"] }
|
||||
|
||||
[target.'cfg(not(target_os = "macos"))'.dependencies]
|
||||
# The version wgpu-hal already uses.
|
||||
ash = { version = "0.38", default-features = false }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,95 @@
|
||||
//! HDR metadata for the swapchain: the Vulkan calls the game crate, which
|
||||
//! forbids unsafe code, can't make itself. wgpu sets no HDR metadata, and
|
||||
//! without it a compositor may clip or tone-map everything above 1.0 (80 nits)
|
||||
//! of an scRGB swapchain.
|
||||
|
||||
/// Opens a Vulkan device with `VK_EXT_hdr_metadata` too, when the GPU offers
|
||||
/// it, so [`set_metadata`] can tell the compositor the real peak brightness.
|
||||
/// `None` leaves opening to wgpu.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn open_vulkan_device(
|
||||
adapter: &wgpu::Adapter,
|
||||
desc: &wgpu::DeviceDescriptor<'_>,
|
||||
) -> Option<Result<(wgpu::Device, wgpu::Queue), wgpu::RequestDeviceError>> {
|
||||
use wgpu::hal::api::Vulkan;
|
||||
let open = {
|
||||
// Safety: only read and opened from here; dropped before wgpu takes it back.
|
||||
let hal = unsafe { adapter.as_hal::<Vulkan>() }?;
|
||||
let instance = hal.shared_instance().raw_instance();
|
||||
// Safety: the adapter's own physical device on its own instance.
|
||||
let offered =
|
||||
unsafe { instance.enumerate_device_extension_properties(hal.raw_physical_device()) }
|
||||
.ok()?
|
||||
.iter()
|
||||
.any(|e| e.extension_name_as_c_str() == Ok(ash::ext::hdr_metadata::NAME));
|
||||
if !offered {
|
||||
return None;
|
||||
}
|
||||
// Safety: what wgpu's own request_device does, with one more extension.
|
||||
unsafe {
|
||||
hal.open_with_callback(
|
||||
desc.required_features,
|
||||
&desc.required_limits,
|
||||
&desc.memory_hints,
|
||||
Some(Box::new(
|
||||
|args: wgpu::hal::vulkan::CreateDeviceCallbackArgs| {
|
||||
args.extensions.push(ash::ext::hdr_metadata::NAME);
|
||||
},
|
||||
)),
|
||||
)
|
||||
}
|
||||
.ok()?
|
||||
};
|
||||
// Safety: opened from this adapter with exactly `desc`'s features.
|
||||
Some(unsafe { adapter.create_device_from_hal(open, desc) })
|
||||
}
|
||||
|
||||
/// Tells the compositor, through `VK_EXT_hdr_metadata`, that the swapchain's
|
||||
/// content is BT.709 and peaks at `peak` nits. Needs a device from
|
||||
/// `open_vulkan_device` and a configured surface; does nothing otherwise.
|
||||
pub fn set_metadata(
|
||||
device: &wgpu::Device,
|
||||
surface: &wgpu::Surface<'_>,
|
||||
paper_white: f32,
|
||||
peak: f32,
|
||||
) {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
use wgpu::hal::api::Vulkan;
|
||||
// Safety: read-only access to handles wgpu keeps alive while these guards live.
|
||||
let (Some(hal_device), Some(hal_surface)) =
|
||||
(unsafe { device.as_hal::<Vulkan>() }, unsafe {
|
||||
surface.as_hal::<Vulkan>()
|
||||
})
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !hal_device
|
||||
.enabled_device_extensions()
|
||||
.contains(&ash::ext::hdr_metadata::NAME)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(swapchain) = hal_surface.raw_native_swapchain() else {
|
||||
return;
|
||||
};
|
||||
let xy = |x, y| ash::vk::XYColorEXT { x, y };
|
||||
let metadata = ash::vk::HdrMetadataEXT::default()
|
||||
.display_primary_red(xy(0.64, 0.33))
|
||||
.display_primary_green(xy(0.30, 0.60))
|
||||
.display_primary_blue(xy(0.15, 0.06))
|
||||
.white_point(xy(0.3127, 0.3290))
|
||||
.max_luminance(peak)
|
||||
.min_luminance(0.0)
|
||||
.max_content_light_level(peak)
|
||||
.max_frame_average_light_level(paper_white.min(peak));
|
||||
let loader = ash::ext::hdr_metadata::Device::new(
|
||||
hal_device.shared_instance().raw_instance(),
|
||||
hal_device.raw_device(),
|
||||
);
|
||||
// Safety: a live swapchain of this device, one metadata entry for it.
|
||||
unsafe { loader.set_hdr_metadata(&[swapchain], &[metadata]) };
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ = (device, surface, paper_white, peak);
|
||||
}
|
||||
@@ -143,7 +143,9 @@ pub fn fetch(
|
||||
if let Some((dest, url)) = crate::worldgen::loader_jar(work, &pack.loader, &pack.loader_version)
|
||||
.filter(|(dest, _)| !dest.exists())
|
||||
{
|
||||
let sha1 = ureq::get(&format!("{url}.sha1"))
|
||||
let checksum = format!("{url}.sha1");
|
||||
let sha1 = crate::net::agent(&checksum)
|
||||
.get(&checksum)
|
||||
.set("User-Agent", modrinth::AGENT)
|
||||
.call()
|
||||
.ok()
|
||||
@@ -201,7 +203,8 @@ pub fn url_of(file: &PackFile, cache: &Cache) -> Option<String> {
|
||||
|
||||
/// Downloads `url` to `dest`, kept only if its SHA-1 is `sha1`.
|
||||
fn download(url: &str, sha1: Option<&str>, dest: &Path) -> Result<(), String> {
|
||||
let response = ureq::get(url)
|
||||
let response = crate::net::agent(url)
|
||||
.get(url)
|
||||
.set("User-Agent", modrinth::AGENT)
|
||||
.call()
|
||||
.map_err(|e| format!("{url}: {e}"))?;
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod jar;
|
||||
pub(crate) mod legacy_structure_mods;
|
||||
mod lithostitched;
|
||||
pub mod modrinth;
|
||||
pub mod net;
|
||||
pub mod oracle;
|
||||
pub mod pipeline;
|
||||
pub mod processors;
|
||||
|
||||
@@ -79,7 +79,8 @@ impl Cache {
|
||||
}
|
||||
|
||||
fn post(url: &str, body: &Value) -> Result<Value, String> {
|
||||
let response = ureq::post(url)
|
||||
let response = crate::net::agent(url)
|
||||
.post(url)
|
||||
.set("User-Agent", AGENT)
|
||||
.set("Content-Type", "application/json")
|
||||
.send_string(&body.to_string())
|
||||
@@ -88,7 +89,8 @@ fn post(url: &str, body: &Value) -> Result<Value, String> {
|
||||
}
|
||||
|
||||
fn get(url: &str) -> Result<Value, String> {
|
||||
let response = ureq::get(url)
|
||||
let response = crate::net::agent(url)
|
||||
.get(url)
|
||||
.set("User-Agent", AGENT)
|
||||
.call()
|
||||
.map_err(|e| format!("{url}: {e}"))?;
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
//! The agents port-pack's downloads go through: the jars of an imported modpack come from the same
|
||||
//! places as everything else, so they take the same proxy — and leave the same hosts alone.
|
||||
//!
|
||||
//! The launcher hands its own setting over (`set_proxy`, from `proxy.rs`); a run of the
|
||||
//! `horizon-port-pack` command reads `HTTPS_PROXY`, `HTTP_PROXY` and `ALL_PROXY` instead (`env_for`),
|
||||
//! taking the one that matches the address's scheme the way the launcher does. Either way a host in
|
||||
//! `NO_PROXY`, or on this computer, is reached directly: a host that only answers without the proxy
|
||||
//! would otherwise fail here while the launcher's own downloads worked.
|
||||
//!
|
||||
//! Which hosts those are is decided here and nowhere else. The launcher asks `direct`, `env_for`,
|
||||
//! `host_of`, `scheme_of`, `socks` and `parse` for its own traffic, and keeps its agents here too
|
||||
//! (`keep`), so the two agree whatever the player set — and there is one copy of the rules to
|
||||
//! change when they need it.
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
/// What the launcher set, when it did.
|
||||
static PROXY: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// Agents kept for reuse, named by the part that asked and the proxy they use: a fresh `Agent`
|
||||
/// starts a new connection pool, so building one per request costs a handshake per file.
|
||||
static KEPT: Mutex<Option<HashMap<String, ureq::Agent>>> = Mutex::new(None);
|
||||
|
||||
/// The proxy to use from now on: the launcher's setting, or None to fall back to the environment.
|
||||
/// The agents built so far are dropped when it changes, since they hold the address it replaces.
|
||||
pub fn set_proxy(spec: Option<String>) {
|
||||
let spec = spec.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty());
|
||||
let mut proxy = lock(&PROXY);
|
||||
if *proxy == spec {
|
||||
return;
|
||||
}
|
||||
*proxy = spec;
|
||||
drop(proxy);
|
||||
*lock(&KEPT) = None;
|
||||
}
|
||||
|
||||
/// The proxy address `url` is fetched through: what the launcher set, else the environment's for
|
||||
/// its scheme, unless `url` is a host that must be reached directly.
|
||||
fn spec_for(url: &str) -> Option<String> {
|
||||
if direct(url) {
|
||||
return None;
|
||||
}
|
||||
lock(&PROXY)
|
||||
.clone()
|
||||
.or_else(|| env_for(scheme_of(url).unwrap_or("https")))
|
||||
}
|
||||
|
||||
/// An agent for downloading `url`: through the proxy when one is set, unless `url` is a host that
|
||||
/// must be reached directly.
|
||||
pub fn agent(url: &str) -> ureq::Agent {
|
||||
keep("port-pack", spec_for(url).as_deref(), |proxy| {
|
||||
let builder = ureq::AgentBuilder::new();
|
||||
match proxy {
|
||||
Some(proxy) => builder.proxy(proxy).build(),
|
||||
None => builder.build(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The agent `url` is fetched with, built by `build` and then kept for the next request that names
|
||||
/// the same `slot` and proxy: a fresh `Agent` starts a new connection pool, so building one per
|
||||
/// request is a handshake per file, and a modpack's jars are fetched one after another.
|
||||
pub fn keep(
|
||||
slot: &str,
|
||||
spec: Option<&str>,
|
||||
build: impl FnOnce(Option<ureq::Proxy>) -> ureq::Agent,
|
||||
) -> ureq::Agent {
|
||||
let proxy = spec.and_then(parse);
|
||||
// An address that isn't a proxy is used as none, and remembered as none.
|
||||
let key = format!(
|
||||
"{slot} {}",
|
||||
if proxy.is_some() {
|
||||
spec.unwrap_or_default()
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
if let Some(agent) = lock(&KEPT).as_ref().and_then(|kept| kept.get(&key)) {
|
||||
return agent.clone();
|
||||
}
|
||||
let agent = build(proxy);
|
||||
lock(&KEPT)
|
||||
.get_or_insert_with(HashMap::new)
|
||||
.insert(key, agent.clone());
|
||||
agent
|
||||
}
|
||||
|
||||
/// `spec` as a proxy, when it is one. An address that can't be used is said once: a download left
|
||||
/// to go direct would otherwise fail with nothing pointing at the proxy.
|
||||
pub fn parse(spec: &str) -> Option<ureq::Proxy> {
|
||||
if socks(spec) {
|
||||
say(&format!(
|
||||
"{} is a SOCKS proxy; downloads go without one. Write the http:// address your \
|
||||
proxy app listens on as well.",
|
||||
redacted(spec)
|
||||
));
|
||||
return None;
|
||||
}
|
||||
match ureq::Proxy::new(spec) {
|
||||
Ok(proxy) => Some(proxy),
|
||||
Err(e) => {
|
||||
say(&format!(
|
||||
"The proxy address {} can't be used ({e}); downloads go without one.",
|
||||
redacted(spec)
|
||||
));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `spec` as it may be shown: a user name and password in it become `***`. An address that can't
|
||||
/// be used is printed to stderr and shown in the launcher, and a proxy's credentials don't belong in
|
||||
/// either. Everything up to the last `@` is the credentials, so a password with an unescaped `/` or
|
||||
/// `@` is hidden too.
|
||||
pub fn redacted(spec: &str) -> String {
|
||||
let (scheme, rest) = match spec.split_once("://") {
|
||||
Some((scheme, rest)) => (format!("{scheme}://"), rest),
|
||||
None => (String::new(), spec),
|
||||
};
|
||||
match rest.rfind('@') {
|
||||
Some(at) => format!("{scheme}***@{}", &rest[at + 1..]),
|
||||
None => spec.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `spec` names a SOCKS proxy, which these downloads don't go through: `ureq` reads a
|
||||
/// SOCKS address happily and only fails when it connects through it.
|
||||
pub fn socks(spec: &str) -> bool {
|
||||
matches!(
|
||||
spec.split_once("://")
|
||||
.map(|(s, _)| s.to_ascii_lowercase())
|
||||
.as_deref(),
|
||||
Some("socks" | "socks4" | "socks4a" | "socks5" | "socks5h")
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether `url` is reached without the proxy: a local address, or a host `NO_PROXY` names. The
|
||||
/// launcher asks this of its own requests, so both reach the same hosts directly.
|
||||
pub fn direct(url: &str) -> bool {
|
||||
host_of(url).is_some_and(|host| local(host) || excluded(host, &no_proxy()))
|
||||
}
|
||||
|
||||
/// `HTTPS_PROXY` (`HTTP_PROXY` for an http address), then `ALL_PROXY`, in the upper-case spelling
|
||||
/// first and the lower-case one after, as the tools that write them do.
|
||||
pub fn env_for(scheme: &str) -> Option<String> {
|
||||
let names: &[&str] = if scheme.eq_ignore_ascii_case("http") {
|
||||
&["HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"]
|
||||
} else {
|
||||
&["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"]
|
||||
};
|
||||
names.iter().find_map(|name| {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.map(|v| v.trim().to_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
/// `NO_PROXY`'s list: the hosts reached directly whatever the proxy is.
|
||||
fn no_proxy() -> String {
|
||||
["NO_PROXY", "no_proxy"]
|
||||
.iter()
|
||||
.find_map(|name| std::env::var(name).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The host part of a URL (`https://user@host:port/path` is `host`).
|
||||
pub fn host_of(url: &str) -> Option<&str> {
|
||||
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
|
||||
let rest = rest.split(['/', '?', '#']).next()?;
|
||||
let rest = rest.rsplit_once('@').map_or(rest, |(_, host)| host);
|
||||
Some(match rest.rfind(':') {
|
||||
// A port follows the last colon; an IPv6 literal keeps the colons inside its brackets.
|
||||
Some(at) if !rest[at..].contains(']') => &rest[..at],
|
||||
_ => rest,
|
||||
})
|
||||
}
|
||||
|
||||
/// `https` in `https://…`, or None for anything that isn't an absolute address.
|
||||
pub fn scheme_of(url: &str) -> Option<&str> {
|
||||
url.split_once("://").map(|(scheme, _)| scheme)
|
||||
}
|
||||
|
||||
/// Whether `host` is this computer: the game's own API and a server on the same machine.
|
||||
fn local(host: &str) -> bool {
|
||||
let host = bare(host);
|
||||
host == "localhost"
|
||||
|| host.ends_with(".localhost")
|
||||
|| host == "::1"
|
||||
|| host == "0.0.0.0"
|
||||
|| host.starts_with("127.")
|
||||
}
|
||||
|
||||
/// Whether `host` is in `NO_PROXY`: `*`, `host`, `.domain`, `*.domain` and `host:port` entries.
|
||||
fn excluded(host: &str, no_proxy: &str) -> bool {
|
||||
let host = bare(host);
|
||||
no_proxy
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|e| !e.is_empty())
|
||||
.any(|entry| {
|
||||
if entry == "*" {
|
||||
return true;
|
||||
}
|
||||
let entry = entry.trim_start_matches('*').trim_start_matches('.');
|
||||
let entry = match entry.rfind(':') {
|
||||
Some(at) if !entry[at..].contains(']') => &entry[..at],
|
||||
_ => entry,
|
||||
};
|
||||
let entry = bare(entry);
|
||||
!entry.is_empty() && (host == entry || host.ends_with(&format!(".{entry}")))
|
||||
})
|
||||
}
|
||||
|
||||
/// A host without the brackets an IPv6 literal wears, lower case.
|
||||
fn bare(host: &str) -> String {
|
||||
host.trim().trim_matches(['[', ']']).to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// Said once, however many downloads follow: a wrong address is one thing to report, not one
|
||||
/// report per file.
|
||||
fn say(what: &str) {
|
||||
static SAID: AtomicBool = AtomicBool::new(false);
|
||||
if !SAID.swap(true, Ordering::Relaxed) {
|
||||
eprintln!("{what}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The lock, even after a thread panicked while holding it: an address lost to a panic is worse
|
||||
/// than an old one kept.
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// What the tests below share, since the address and the agents are one of each for the whole
|
||||
/// process: they take it in turn.
|
||||
fn alone() -> MutexGuard<'static, ()> {
|
||||
static TURN: Mutex<()> = Mutex::new(());
|
||||
lock(&TURN)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credentials_are_not_shown() {
|
||||
assert_eq!(redacted("http://127.0.0.1:7890"), "http://127.0.0.1:7890");
|
||||
assert_eq!(redacted("proxy.local:3128"), "proxy.local:3128");
|
||||
assert_eq!(
|
||||
redacted("http://user:pass@proxy.local:3128"),
|
||||
"http://***@proxy.local:3128"
|
||||
);
|
||||
assert_eq!(
|
||||
redacted("socks5://u:p@10.0.0.1:1080"),
|
||||
"socks5://***@10.0.0.1:1080"
|
||||
);
|
||||
assert_eq!(
|
||||
redacted("user:pass@proxy.local:3128"),
|
||||
"***@proxy.local:3128"
|
||||
);
|
||||
assert_eq!(redacted("http://u:p/a@ss@proxy:1"), "http://***@proxy:1");
|
||||
assert_eq!(redacted("http://user:pass@"), "http://***@");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_the_launcher_sets_is_trimmed_and_kept() {
|
||||
let _turn = alone();
|
||||
set_proxy(Some(" http://127.0.0.1:7890 ".into()));
|
||||
assert_eq!(
|
||||
PROXY.lock().unwrap().as_deref(),
|
||||
Some("http://127.0.0.1:7890")
|
||||
);
|
||||
set_proxy(Some(" ".into()));
|
||||
assert!(PROXY.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
/// An address on this computer is reached directly whatever `NO_PROXY` says: what an import
|
||||
/// needs when the launcher's own requests to it go direct.
|
||||
#[test]
|
||||
fn a_local_address_is_reached_directly() {
|
||||
assert!(direct("http://127.0.0.1:8130/api/v1/status"));
|
||||
assert!(direct("http://localhost/api/v1/status"));
|
||||
assert!(direct("https://[::1]:25565/"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_is_read_out_of_the_address() {
|
||||
assert_eq!(
|
||||
host_of("https://cdn.modrinth.com/v2/x.jar"),
|
||||
Some("cdn.modrinth.com")
|
||||
);
|
||||
assert_eq!(
|
||||
host_of("https://user:pass@piston-meta.mojang.com:8443/a"),
|
||||
Some("piston-meta.mojang.com")
|
||||
);
|
||||
assert_eq!(
|
||||
host_of("http://127.0.0.1:8130/api/v1/status"),
|
||||
Some("127.0.0.1")
|
||||
);
|
||||
assert_eq!(host_of("https://[::1]:25565/"), Some("[::1]"));
|
||||
assert_eq!(host_of("https://example.com?x=1"), Some("example.com"));
|
||||
assert_eq!(host_of("https://example.com#top"), Some("example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_absolute_addresses_have_a_scheme() {
|
||||
assert_eq!(scheme_of("https://a.b"), Some("https"));
|
||||
assert_eq!(scheme_of("http://a.b"), Some("http"));
|
||||
assert_eq!(scheme_of("a.b/c"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_computer_is_never_proxied() {
|
||||
for host in [
|
||||
"localhost",
|
||||
"LOCALHOST",
|
||||
"[::1]",
|
||||
"::1",
|
||||
"127.0.0.1",
|
||||
"127.1.2.3",
|
||||
] {
|
||||
assert!(local(host), "{host}");
|
||||
}
|
||||
for host in ["playhorizon.dev", "api.minecraftservices.com", "10.0.0.1"] {
|
||||
assert!(!local(host), "{host}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What an import with `NO_PROXY=modrinth.com` needs: the launcher's own requests to it go
|
||||
/// direct, so the jars fetched for it must too.
|
||||
#[test]
|
||||
fn no_proxy_lists_hosts_and_their_subdomains() {
|
||||
assert!(excluded("anything.at.all", "*"));
|
||||
assert!(excluded("cdn.modrinth.com", "modrinth.com"));
|
||||
assert!(excluded("api.modrinth.com", "modrinth.com"));
|
||||
assert!(excluded("piston-meta.mojang.com", "mojang.com"));
|
||||
assert!(excluded(
|
||||
"wiki.corp.example",
|
||||
" .corp.example , other.host "
|
||||
));
|
||||
assert!(excluded("github.com", "github.com:443"));
|
||||
assert!(!excluded("notmodrinth.com", "modrinth.com"));
|
||||
assert!(!excluded("modrinth.com", " .corp.example , mojang.com "));
|
||||
assert!(!excluded("edge.forgecdn.net", "modrinth.com"));
|
||||
assert!(!excluded("modrinth.com", ""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_that_cant_be_used_becomes_no_proxy() {
|
||||
assert!(parse("http://127.0.0.1:7890").is_some());
|
||||
assert!(parse("127.0.0.1:7890").is_some());
|
||||
// `ureq` reads a SOCKS address and only fails once it connects through it.
|
||||
assert!(socks("socks5://127.0.0.1:7891"));
|
||||
assert!(parse("socks5://127.0.0.1:7891").is_none());
|
||||
assert!(!socks("http://127.0.0.1:7890"));
|
||||
}
|
||||
|
||||
/// The agent a second request gets is the one the first built: one connection pool, not one
|
||||
/// handshake per jar.
|
||||
#[test]
|
||||
fn an_agent_is_kept_for_the_next_request() {
|
||||
let _turn = alone();
|
||||
set_proxy(None);
|
||||
let mut built = 0;
|
||||
for _ in 0..3 {
|
||||
keep("kept", None, |_| {
|
||||
built += 1;
|
||||
ureq::AgentBuilder::new().build()
|
||||
});
|
||||
}
|
||||
assert_eq!(built, 1, "three requests, one agent");
|
||||
// Another address is another agent, and a new setting drops the ones before it.
|
||||
keep("kept", Some("http://127.0.0.1:7890"), |proxy| {
|
||||
assert!(proxy.is_some());
|
||||
built += 1;
|
||||
ureq::AgentBuilder::new().build()
|
||||
});
|
||||
assert_eq!(built, 2, "a second address needs a second agent");
|
||||
set_proxy(Some("http://127.0.0.1:7891".into()));
|
||||
keep("kept", Some("http://127.0.0.1:7891"), |_| {
|
||||
built += 1;
|
||||
ureq::AgentBuilder::new().build()
|
||||
});
|
||||
assert_eq!(built, 3, "a new setting drops the agents kept before it");
|
||||
set_proxy(None);
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,11 @@ of the main action. The game's menus keep `LIGHT` and `DARK`.
|
||||
ships no third-party pictures. The Horizon instance shows a grass block drawn from the player's
|
||||
own prepared Minecraft textures. Sources are named in text ("from Modrinth"): Modrinth's logo is
|
||||
all rights reserved, so it is not shown.
|
||||
- **Partner banner**: the one exception to shipping no third-party pictures. Sculk, a server host,
|
||||
sponsors Horizon: its banner (`launcher/assets/sculk-banner.webp`, `launcher/src/partner.rs`) sits
|
||||
under a muted mono "Partner" label at the end of the Servers page and of Home, below Play, and opens
|
||||
Sculk's page in the browser. The website shows the same banner the same way on Home and the hosting
|
||||
docs, as a `rel="sponsored"` link.
|
||||
- **Pixel art drawn in code.** The stone behind the pages is close shades of the page colour
|
||||
(`TILE_SHADES`), never Minecraft's stone; the landscape is a banded sky, a sun cut in slices like
|
||||
the mark, hills and square trees (a sunset in dark, a dawn in light). The launcher bakes them in
|
||||
|
||||
+4
-2
@@ -21,14 +21,16 @@ Every row has a one-line description and its cost in frame time (none, low, medi
|
||||
| Quality | smooth lighting, mipmap levels, biome blend, clouds, cloud distance, weather radius, particles, entity shadows, cutout leaves | `options.txt` |
|
||||
| | sky, fog, weather, animated textures | `horizon-graphics.txt` |
|
||||
| Display | FOV, max framerate, VSync, fullscreen, GUI scale | `options.txt` |
|
||||
| | resolution scale, anti-aliasing (FXAA), present mode, frame pacing | `horizon-graphics.txt` |
|
||||
| | resolution scale, anti-aliasing (FXAA), HDR, paper white, peak brightness, present mode, frame pacing | `horizon-graphics.txt` |
|
||||
| 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. 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.
|
||||
`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, HDR off, 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.
|
||||
|
||||
**HDR** (Display, off by default) presents to an scRGB swapchain (`Rgba16Float`, extended linear sRGB) on displays and compositors that offer it. The frame is drawn exactly as in SDR, in vanilla's gamma space, and a last pass (`hdr.wgsl`) decodes it to linear light at the **Paper White** and lifts light sources (blocks that emit light, lava, the sun and the moon) towards the **Peak Brightness**; everything else stays as in SDR. The mesher puts the light a block's face emits in its vertex colour's alpha (`EMISSION_BITS`), the frame's alpha carries the mark, and only pixels that still show the world before the hand and HUD are lifted. On Vulkan, `horizon-hdr` sends HDR metadata (MaxCLL, mastering luminance), which wgpu doesn't: without it a compositor may clip everything above SDR white. KWin maps the content's reference white onto the desktop's SDR brightness, so on Linux the default Paper White matches SDR mode. `HORIZON_HDR_DEBUG=1` paints lifted pixels magenta. Not lifted yet: glowing particles, distant LOD terrain.
|
||||
|
||||
Which settings each screen shows, their descriptions and costs are in `crates/horizon-client/src/graphics_ui.rs` (`rows`); `graphics_style.rs` draws them.
|
||||
|
||||
## Distant terrain
|
||||
|
||||
@@ -132,11 +132,11 @@ MCP: `account_offline`.
|
||||
|
||||
## `horizon-launcher settings`
|
||||
|
||||
Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off.
|
||||
Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off, proxy http://host:port ("default" removes it).
|
||||
|
||||
horizon-launcher settings [KEY] [VALUE]
|
||||
|
||||
- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation)
|
||||
- `KEY` (selected-version, minecraft-dir, server-dir, install-new-versions, opening-animation, proxy)
|
||||
- `VALUE`: The new value (with KEY)
|
||||
|
||||
MCP: `settings`.
|
||||
|
||||
+11
-1
@@ -79,7 +79,8 @@ page `servers.json` (the list), `servers/<name>/` (the servers created there) an
|
||||
|
||||
- **Settings**: install new Horizon versions automatically (on unless you turn it off; the
|
||||
selected version only moves to the new one if you were on the newest), the opening animation,
|
||||
the game's extra command-line arguments, and the launcher's own version and update state.
|
||||
the game's extra command-line arguments, an HTTP proxy for downloads, and the launcher's own
|
||||
version and update state.
|
||||
- **Updates**: there is one channel. Every release is published as the release, GitHub's latest,
|
||||
once its smoke test passed (docs/release-flow.md), and the launcher installs it. The game
|
||||
pre-releases of the old Alpha channel (v0.2.1 on) stay on the Versions page to install
|
||||
@@ -90,6 +91,15 @@ page `servers.json` (the list), `servers/<name>/` (the servers created there) an
|
||||
launcher's own arguments, kept as `game_args` in `settings.json`, and apply the next time the
|
||||
game starts. `horizon-launcher game-args "<line>"` sets them too, and `play --arg <ARG>` passes
|
||||
one for a single run.
|
||||
- **Proxy**: when the internet here needs one (a school's, an office's, a country where a host is
|
||||
unreachable), Settings' Proxy takes the `http://host:port` address your proxy app listens on, and
|
||||
every download goes through it: Horizon's releases and the launcher's own update, Minecraft's
|
||||
files and Java from Mojang, Modrinth, CurseForge, Horizon's mod registry, pictures, Microsoft
|
||||
sign-in, and the jars a modpack import fetches. It is kept as `proxy` in `settings.json`, and
|
||||
`horizon-launcher settings proxy http://127.0.0.1:7890` sets it too ("default" removes it).
|
||||
Without one, `HTTPS_PROXY` and `HTTP_PROXY` are used when the launcher is started with them, and
|
||||
`NO_PROXY` names the hosts to reach directly, a modpack import's jars included. A server on this
|
||||
computer never goes through it.
|
||||
- **Links**: the Discord invite, the Sponsors page and the website come from `launcher/links.json` on main
|
||||
(`{"discord": "...", "sponsor": "...", "website": "..."}`), so they change without a launcher release. Offline,
|
||||
the launcher uses the same values built in; an empty address hides its button.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
+22
-13
@@ -60,11 +60,17 @@ impl Endpoints {
|
||||
}
|
||||
}
|
||||
|
||||
fn agent() -> ureq::Agent {
|
||||
ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.user_agent(&format!("horizon-launcher/{}", crate::backend::VERSION))
|
||||
.build()
|
||||
/// A request to `url`: the launcher's user agent, a 20 s timeout, and the player's proxy when one
|
||||
/// is set (`proxy`), since a sign-in has to get out the way downloads do.
|
||||
fn request_to(method: &str, url: &str) -> ureq::Request {
|
||||
crate::proxy::agent(
|
||||
ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.user_agent(&format!("horizon-launcher/{}", crate::backend::VERSION)),
|
||||
url,
|
||||
)
|
||||
.build()
|
||||
.request(method, url)
|
||||
}
|
||||
|
||||
/// One request's result: the status and the JSON body (empty when there is none). Transport
|
||||
@@ -147,7 +153,7 @@ pub enum Poll {
|
||||
|
||||
pub fn device_code(ep: &Endpoints, client_id: &str) -> Result<DeviceCode, String> {
|
||||
let (status, v) = send(
|
||||
agent().post(&format!("{}/devicecode", ep.microsoft)),
|
||||
request_to("POST", &format!("{}/devicecode", ep.microsoft)),
|
||||
Some(Body::Form(vec![("client_id", client_id), ("scope", SCOPE)])),
|
||||
"Microsoft",
|
||||
)?;
|
||||
@@ -190,7 +196,7 @@ fn oauth_error(v: &Value) -> String {
|
||||
/// One poll of the token endpoint while the player signs in.
|
||||
pub fn poll(ep: &Endpoints, client_id: &str, code: &DeviceCode) -> Result<Poll, String> {
|
||||
let (status, v) = send(
|
||||
agent().post(&format!("{}/token", ep.microsoft)),
|
||||
request_to("POST", &format!("{}/token", ep.microsoft)),
|
||||
Some(Body::Form(vec![
|
||||
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
|
||||
("client_id", client_id),
|
||||
@@ -247,7 +253,7 @@ pub fn wait_for_sign_in(
|
||||
|
||||
fn refresh_ms(ep: &Endpoints, client_id: &str, refresh: &str) -> Result<MsTokens, String> {
|
||||
let (status, v) = send(
|
||||
agent().post(&format!("{}/token", ep.microsoft)),
|
||||
request_to("POST", &format!("{}/token", ep.microsoft)),
|
||||
Some(Body::Form(vec![
|
||||
("grant_type", "refresh_token"),
|
||||
("client_id", client_id),
|
||||
@@ -281,7 +287,7 @@ struct Minecraft {
|
||||
|
||||
fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result<Minecraft, String> {
|
||||
let (status, xbl) = send(
|
||||
agent().post(&ep.xbox_user),
|
||||
request_to("POST", &ep.xbox_user),
|
||||
Some(Body::Json(json!({
|
||||
"Properties": {
|
||||
"AuthMethod": "RPS",
|
||||
@@ -297,7 +303,7 @@ fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result<Minecraft, String>
|
||||
.filter(|_| status == 200)
|
||||
.ok_or("Xbox Live refused the sign-in.")?;
|
||||
let (status, xsts) = send(
|
||||
agent().post(&ep.xsts),
|
||||
request_to("POST", &ep.xsts),
|
||||
Some(Body::Json(json!({
|
||||
"Properties": { "SandboxId": "RETAIL", "UserTokens": [xbl_token] },
|
||||
"RelyingParty": "rp://api.minecraftservices.com/",
|
||||
@@ -317,7 +323,10 @@ fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result<Minecraft, String>
|
||||
};
|
||||
let xuid = claims.and_then(|c| str_field(c, "xid"));
|
||||
let (status, mc) = send(
|
||||
agent().post(&format!("{}/authentication/login_with_xbox", ep.minecraft)),
|
||||
request_to(
|
||||
"POST",
|
||||
&format!("{}/authentication/login_with_xbox", ep.minecraft),
|
||||
),
|
||||
Some(Body::Json(
|
||||
json!({ "identityToken": format!("XBL3.0 x={uhs};{xsts_token}") }),
|
||||
)),
|
||||
@@ -350,7 +359,7 @@ fn bearer(request: ureq::Request, token: &str) -> ureq::Request {
|
||||
fn owns_game(ep: &Endpoints, token: &str) -> Result<bool, String> {
|
||||
let (status, v) = send(
|
||||
bearer(
|
||||
agent().get(&format!("{}/entitlements/mcstore", ep.minecraft)),
|
||||
request_to("GET", &format!("{}/entitlements/mcstore", ep.minecraft)),
|
||||
token,
|
||||
),
|
||||
None,
|
||||
@@ -387,7 +396,7 @@ pub struct Account {
|
||||
fn profile(ep: &Endpoints, token: &str) -> Result<Account, String> {
|
||||
let (status, v) = send(
|
||||
bearer(
|
||||
agent().get(&format!("{}/minecraft/profile", ep.minecraft)),
|
||||
request_to("GET", &format!("{}/minecraft/profile", ep.minecraft)),
|
||||
token,
|
||||
),
|
||||
None,
|
||||
|
||||
+13
-5
@@ -80,14 +80,18 @@ const CLIENT: &str = if cfg!(windows) {
|
||||
"horizon-client"
|
||||
};
|
||||
|
||||
fn agent() -> ureq::Agent {
|
||||
ureq::AgentBuilder::new()
|
||||
.user_agent(&format!("horizon-launcher/{VERSION}"))
|
||||
.build()
|
||||
/// The agent `url` is fetched with: the launcher's own user agent, through the player's proxy when
|
||||
/// one is set (`proxy`).
|
||||
fn agent(url: &str) -> ureq::Agent {
|
||||
crate::proxy::agent(
|
||||
ureq::AgentBuilder::new().user_agent(&format!("horizon-launcher/{VERSION}")),
|
||||
url,
|
||||
)
|
||||
.build()
|
||||
}
|
||||
|
||||
fn get(url: &str) -> Result<ureq::Response, String> {
|
||||
let mut request = agent().get(url);
|
||||
let mut request = agent(url).get(url);
|
||||
// CI runners share addresses and hit GitHub's anonymous rate limit; they pass their own token.
|
||||
if let Some(token) = std::env::var("HORIZON_GITHUB_TOKEN")
|
||||
.ok()
|
||||
@@ -2530,6 +2534,10 @@ pub struct Settings {
|
||||
/// default. Appended after the launcher's own arguments, so they can add to or override them.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub game_args: String,
|
||||
/// The HTTP proxy every download goes through (`proxy`), such as `http://127.0.0.1:7890`.
|
||||
/// Unset means none: the environment's `HTTPS_PROXY` and `HTTP_PROXY` apply instead.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub proxy: Option<String>,
|
||||
/// Dark, Light, or the system's: the launcher's look. Dark by default.
|
||||
#[serde(default)]
|
||||
pub appearance: Appearance,
|
||||
|
||||
@@ -55,7 +55,7 @@ impl CurseForge {
|
||||
}
|
||||
|
||||
fn get(&self, url: &str) -> Result<Value, String> {
|
||||
let response = super::download::agent()
|
||||
let response = super::download::agent(url)
|
||||
.get(url)
|
||||
.set("x-api-key", &self.key)
|
||||
.set("Accept", "application/json")
|
||||
|
||||
@@ -17,16 +17,26 @@ const HOSTS: [&str; 4] = [
|
||||
/// Bigger than any pack these sources serve (Modrinth caps uploads at 500 MiB).
|
||||
const MAX: u64 = 1 << 30;
|
||||
|
||||
/// The HTTP agent the sources share. Modrinth asks for a user agent that names the project.
|
||||
pub(super) fn agent() -> ureq::Agent {
|
||||
ureq::AgentBuilder::new()
|
||||
.user_agent(&format!(
|
||||
"ludovic111/horizon horizon-launcher/{} (github.com/ludovic111/horizon)",
|
||||
crate::backend::VERSION
|
||||
))
|
||||
.timeout_connect(std::time::Duration::from_secs(15))
|
||||
.timeout_read(std::time::Duration::from_secs(60))
|
||||
.build()
|
||||
/// The HTTP agent the sources share, reaching `url` through the player's proxy when one is set
|
||||
/// (`proxy`). Modrinth asks for a user agent that names the project.
|
||||
///
|
||||
/// It is kept between downloads: a fresh agent starts a new connection pool, so one per file would
|
||||
/// be a handshake per file, and a modpack brings hundreds.
|
||||
pub(super) fn agent(url: &str) -> ureq::Agent {
|
||||
let spec = crate::proxy::spec_for(url);
|
||||
horizon_port_pack::net::keep("browser", spec.as_deref(), |proxy| {
|
||||
let builder = ureq::AgentBuilder::new()
|
||||
.user_agent(&format!(
|
||||
"ludovic111/horizon horizon-launcher/{} (github.com/ludovic111/horizon)",
|
||||
crate::backend::VERSION
|
||||
))
|
||||
.timeout_connect(std::time::Duration::from_secs(15))
|
||||
.timeout_read(std::time::Duration::from_secs(60));
|
||||
match proxy {
|
||||
Some(proxy) => builder.proxy(proxy).build(),
|
||||
None => builder.build(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Why a file can't be downloaded at all, before any byte is read.
|
||||
@@ -159,9 +169,12 @@ pub fn fetch(file: &FileRef, folder: &Path, progress: &dyn Fn(f32)) -> Result<Pa
|
||||
if let Some(why) = refuse(file) {
|
||||
return Err(why);
|
||||
}
|
||||
let response = agent().get(&file.url).call().map_err(|e| match e {
|
||||
ureq::Error::Status(code, _) => format!("{} answered {code}.", file.url),
|
||||
ureq::Error::Transport(t) => format!("No connection: {t}"),
|
||||
})?;
|
||||
let response = agent(&file.url)
|
||||
.get(&file.url)
|
||||
.call()
|
||||
.map_err(|e| match e {
|
||||
ureq::Error::Status(code, _) => format!("{} answered {code}.", file.url),
|
||||
ureq::Error::Transport(t) => format!("No connection: {t}"),
|
||||
})?;
|
||||
save(file, response.into_reader(), folder, progress)
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ fn fetch_index() -> Result<(Index, String), String> {
|
||||
use std::io::Read;
|
||||
let at = location();
|
||||
let text = if at.starts_with("https://") {
|
||||
let response = download::agent().get(&at).call().map_err(|e| match e {
|
||||
let response = download::agent(&at).get(&at).call().map_err(|e| match e {
|
||||
ureq::Error::Status(code, _) => format!("The mod registry answered {code}."),
|
||||
ureq::Error::Transport(t) => format!("The mod registry can't be reached: {t}"),
|
||||
})?;
|
||||
@@ -160,7 +160,7 @@ fn refresh_ratings() {
|
||||
}
|
||||
let at = given.unwrap_or_else(|| RATINGS_URL.to_owned());
|
||||
let text = if at.starts_with("https://") {
|
||||
download::agent().get(&at).call().ok().and_then(|r| {
|
||||
download::agent(&at).get(&at).call().ok().and_then(|r| {
|
||||
use std::io::Read;
|
||||
let mut text = String::new();
|
||||
r.into_reader()
|
||||
|
||||
@@ -63,7 +63,7 @@ pub fn fetch(home: &Path, url: &str, size: u32) -> Result<PathBuf, String> {
|
||||
if let Some(why) = refuse(url) {
|
||||
return Err(format!("{url}: {why}"));
|
||||
}
|
||||
let response = super::download::agent()
|
||||
let response = super::download::agent(url)
|
||||
.get(url)
|
||||
.call()
|
||||
.map_err(|e| format!("{url}: {e}"))?;
|
||||
|
||||
@@ -227,7 +227,7 @@ impl Source for Modrinth {
|
||||
}
|
||||
|
||||
fn get(url: &str) -> Result<Value, String> {
|
||||
let response = super::download::agent()
|
||||
let response = super::download::agent(url)
|
||||
.get(url)
|
||||
.call()
|
||||
.map_err(|e| match e {
|
||||
|
||||
+14
-2
@@ -297,7 +297,7 @@ enum Cmd {
|
||||
},
|
||||
/// Show the launcher's settings, or set one (the Settings page): selected-version TAG,
|
||||
/// minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions
|
||||
/// on|off, opening-animation on|off
|
||||
/// on|off, opening-animation on|off, proxy http://host:port ("default" removes it)
|
||||
Settings {
|
||||
#[arg(value_parser = SETTING_KEYS)]
|
||||
key: Option<String>,
|
||||
@@ -399,12 +399,13 @@ pub fn command() -> clap::Command {
|
||||
pub const AI_COMMANDS: [&str; 2] = ["mcp", "agent-config"];
|
||||
|
||||
/// The keys `settings` sets.
|
||||
const SETTING_KEYS: [&str; 5] = [
|
||||
const SETTING_KEYS: [&str; 6] = [
|
||||
"selected-version",
|
||||
"minecraft-dir",
|
||||
"server-dir",
|
||||
"install-new-versions",
|
||||
"opening-animation",
|
||||
"proxy",
|
||||
];
|
||||
|
||||
fn on_off(value: &str) -> Result<bool, String> {
|
||||
@@ -423,6 +424,15 @@ fn set_setting(s: &mut backend::Settings, key: &str, value: &str) -> Result<(),
|
||||
"server-dir" => s.server_dir = folder(value),
|
||||
"install-new-versions" => s.install_new_versions = Some(on_off(value)?),
|
||||
"opening-animation" => s.skip_opening = !on_off(value)?,
|
||||
"proxy" => {
|
||||
if value == "default" || value.is_empty() {
|
||||
s.proxy = None;
|
||||
} else if let Some(why) = horizon_launcher::proxy::refuse(value) {
|
||||
return Err(why);
|
||||
} else {
|
||||
s.proxy = Some(value.trim().to_string());
|
||||
}
|
||||
}
|
||||
_ => return Err(format!("No setting {key}.")),
|
||||
}
|
||||
Ok(())
|
||||
@@ -437,6 +447,7 @@ fn settings_json(s: &backend::Settings) -> serde_json::Value {
|
||||
"install_new_versions": s.install_new_versions.unwrap_or(true),
|
||||
"opening_animation": !s.skip_opening,
|
||||
"game_args": s.game_args,
|
||||
"proxy": s.proxy,
|
||||
"desktop_entry": s.desktop_entry.unwrap_or(true),
|
||||
"no_ai": backend::no_ai(),
|
||||
})
|
||||
@@ -722,6 +733,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
let value = value.ok_or("settings KEY VALUE: the value is missing")?;
|
||||
set_setting(&mut settings, &key, &value)?;
|
||||
settings.save();
|
||||
horizon_launcher::proxy::announce(settings.proxy.clone());
|
||||
}
|
||||
let all = settings_json(&settings);
|
||||
if as_json {
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod heads;
|
||||
pub mod modpacks;
|
||||
pub mod mojang;
|
||||
pub mod process;
|
||||
pub mod proxy;
|
||||
pub mod servers;
|
||||
pub mod signed;
|
||||
pub mod sources;
|
||||
|
||||
+110
-8
@@ -18,6 +18,7 @@ mod mcp;
|
||||
mod modpacks_page;
|
||||
mod mods_page;
|
||||
mod mods_project;
|
||||
mod partner;
|
||||
mod perf;
|
||||
mod scrollbar;
|
||||
mod servers_page;
|
||||
@@ -186,6 +187,10 @@ struct Launcher {
|
||||
args_input: String,
|
||||
args_focused: bool,
|
||||
args_focus: FocusHandle,
|
||||
/// Settings' Proxy field, the same way (`proxy`).
|
||||
proxy_input: String,
|
||||
proxy_focused: bool,
|
||||
proxy_focus: FocusHandle,
|
||||
/// Opt-in data collection: the player's answer and Settings' section (`collection`).
|
||||
collection: collection::Collection,
|
||||
/// Settings' "Connect an AI agent" (`agents_page`).
|
||||
@@ -301,6 +306,9 @@ impl Launcher {
|
||||
args_input: settings.game_args.clone(),
|
||||
args_focused: false,
|
||||
args_focus: cx.focus_handle(),
|
||||
proxy_input: settings.proxy.clone().unwrap_or_default(),
|
||||
proxy_focused: false,
|
||||
proxy_focus: cx.focus_handle(),
|
||||
settings,
|
||||
links: backend::Links::default(),
|
||||
preparing: false,
|
||||
@@ -2123,7 +2131,8 @@ impl Launcher {
|
||||
if let Some(crash) = self.crash.clone() {
|
||||
page = page.child(self.crash_notice(crash, cx));
|
||||
}
|
||||
page
|
||||
// Below everything the player needs to start, so it never moves Play.
|
||||
page.child(partner::banner("partner-home", 560., &t))
|
||||
}
|
||||
|
||||
/// "Horizon crashed": the report and the logs, and where to report it.
|
||||
@@ -2539,28 +2548,30 @@ impl Launcher {
|
||||
Some(opening.into_any_element()),
|
||||
&t,
|
||||
))
|
||||
.child(group("Network", "globe"))
|
||||
.child(self.proxy_row(n + 4, cx))
|
||||
.child(group("Game", "gamepad"))
|
||||
.child(self.game_args_row(n + 4, cx))
|
||||
.child(self.game_args_row(n + 5, cx))
|
||||
.child(group("AI", "terminal"))
|
||||
.child(self.no_ai_row(n + 4, cx))
|
||||
.child(self.no_ai_row(n + 6, cx))
|
||||
.child(group("About", "info-box"))
|
||||
.child(index_row(n + 5, "Horizon", Some(plain(&horizon)), horizon_action, &t))
|
||||
.child(index_row(n + 7, "Horizon", Some(plain(&horizon)), horizon_action, &t))
|
||||
.child(index_row(
|
||||
n + 6,
|
||||
n + 8,
|
||||
"Launcher",
|
||||
Some(plain(&launcher)),
|
||||
launcher_action,
|
||||
&t,
|
||||
))
|
||||
.child(index_row(
|
||||
n + 7,
|
||||
n + 9,
|
||||
"Data folder",
|
||||
Some(mono(short(&backend::data_dir()))),
|
||||
None,
|
||||
&t,
|
||||
))
|
||||
.child(index_row(
|
||||
n + 8,
|
||||
n + 10,
|
||||
"Logs",
|
||||
Some(mono(format!(
|
||||
"{} · crash reports beside it",
|
||||
@@ -2579,7 +2590,7 @@ impl Launcher {
|
||||
))
|
||||
.when(cfg!(target_os = "linux"), |d| {
|
||||
d.child(index_row(
|
||||
n + 9,
|
||||
n + 11,
|
||||
"Applications menu",
|
||||
Some(plain(if self.settings.desktop_entry() {
|
||||
"Horizon and its icon are in your desktop's menu."
|
||||
@@ -2668,6 +2679,93 @@ impl Launcher {
|
||||
)
|
||||
}
|
||||
|
||||
/// Settings' Proxy row: the HTTP proxy every download and sign-in goes through, kept in
|
||||
/// `settings.json` and read back by `proxy.rs` on each request.
|
||||
fn proxy_row(&self, n: usize, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let focused = self.proxy_focused;
|
||||
let field = div()
|
||||
.id("proxy")
|
||||
.track_focus(&self.proxy_focus)
|
||||
.flex()
|
||||
.items_center()
|
||||
.w(px(300.))
|
||||
.h(px(30.))
|
||||
.px(px(12.))
|
||||
.overflow_hidden()
|
||||
.border_2()
|
||||
.border_color(if focused { t.accent } else { t.outline })
|
||||
.bg(t.well)
|
||||
.font_family(theme::MONO)
|
||||
.text_size(px(12.))
|
||||
.cursor_text()
|
||||
.child(if self.proxy_input.is_empty() && !focused {
|
||||
div()
|
||||
.text_color(t.muted)
|
||||
.child("For example http://127.0.0.1:7890")
|
||||
} else {
|
||||
// The end of a long line stays in view while typing.
|
||||
let chars: Vec<char> = self.proxy_input.chars().collect();
|
||||
let shown: String = chars[chars.len().saturating_sub(44)..].iter().collect();
|
||||
div().text_color(t.ink).child(shown)
|
||||
})
|
||||
.when(focused, |d| d.child(div().w(px(1.)).h(px(14.)).bg(t.ink)))
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
|
||||
window.focus(&this.proxy_focus);
|
||||
cx.notify();
|
||||
}))
|
||||
.on_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| {
|
||||
let k = &ev.keystroke;
|
||||
let paste = k.key == "v" && (k.modifiers.control || k.modifiers.platform);
|
||||
match k.key.as_str() {
|
||||
"backspace" => {
|
||||
this.proxy_input.pop();
|
||||
}
|
||||
_ if paste => {
|
||||
if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) {
|
||||
// A copied line, not a copied page: the field takes one address.
|
||||
let line = text.lines().next().unwrap_or(&text);
|
||||
this.proxy_input.push_str(line.trim());
|
||||
}
|
||||
}
|
||||
_ if !k.modifiers.control && !k.modifiers.platform => {
|
||||
if let Some(ch) = &k.key_char {
|
||||
this.proxy_input.push_str(ch);
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
// `truncate` counts bytes, and a cut inside a character panics: count characters.
|
||||
if this.proxy_input.chars().count() > 256 {
|
||||
this.proxy_input = this.proxy_input.chars().take(256).collect();
|
||||
}
|
||||
this.save_proxy();
|
||||
cx.stop_propagation();
|
||||
cx.notify();
|
||||
}));
|
||||
// A half-typed address is no reason to complain; one left behind is.
|
||||
let detail = match (focused, horizon_launcher::proxy::refuse(&self.proxy_input)) {
|
||||
(false, Some(why)) => div().text_color(t.danger).child(why).into_any_element(),
|
||||
_ => div()
|
||||
.child(
|
||||
"Downloads, sign-ins and updates go through this HTTP proxy \
|
||||
(http://host:port). Empty means none: HTTPS_PROXY is used instead when the \
|
||||
launcher was started with one.",
|
||||
)
|
||||
.into_any_element(),
|
||||
};
|
||||
index_row(n, "Proxy", Some(detail), Some(field.into_any_element()), &t)
|
||||
}
|
||||
|
||||
/// Keeps the Proxy field in `settings.json`, and tells the parts that build their own agents
|
||||
/// (`horizon-port-pack`) which proxy to use.
|
||||
fn save_proxy(&mut self) {
|
||||
let value = self.proxy_input.trim().to_owned();
|
||||
self.settings.proxy = (!value.is_empty()).then_some(value);
|
||||
self.settings.save();
|
||||
horizon_launcher::proxy::announce(self.settings.proxy.clone());
|
||||
}
|
||||
|
||||
/// Settings' Microsoft accounts: who is signed in and plays, the sign-in with its code. The
|
||||
/// rows are numbered from 01; returns them and how many there are.
|
||||
fn account_rows(&mut self, cx: &mut Context<Self>) -> (Div, usize) {
|
||||
@@ -3317,6 +3415,7 @@ impl Render for Launcher {
|
||||
self.friend_focused = self.friend_focus.is_focused(window);
|
||||
self.mods.note_focus(window);
|
||||
self.args_focused = self.args_focus.is_focused(window);
|
||||
self.proxy_focused = self.proxy_focus.is_focused(window);
|
||||
let size = window.viewport_size();
|
||||
let banner_width = f32::from(size.width) - theme::SIDEBAR - scrollbar::GUTTER;
|
||||
let content = match self.page {
|
||||
@@ -3578,6 +3677,9 @@ fn main() {
|
||||
}
|
||||
perf::process_started();
|
||||
backend::exe_path();
|
||||
// What the launcher downloads goes through the player's proxy, if they set one: the parts
|
||||
// that build their own agents (`horizon-port-pack`) are told before anything starts.
|
||||
horizon_launcher::proxy::announce(horizon_launcher::backend::Settings::load().proxy);
|
||||
if let Some(code) = cli::run() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Sculk's banner: a server host that sponsors Horizon (Ludovic, 2026-10-26), on the Servers page
|
||||
//! and under Home's rows. The picture is in the binary, never fetched; a click opens Sculk's page in
|
||||
//! the browser. A "Partner" label above it says it is an ad.
|
||||
use crate::theme::Theme;
|
||||
use gpui::{div, img, prelude::*, px, ClickEvent, Div, Image, ImageFormat, Stateful};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
pub const URL: &str = "https://my.sculkhosting.com/ref/horizon";
|
||||
|
||||
/// 1200×441: twice the widest it is shown at, for Retina screens. Its transparent edges let the
|
||||
/// characters stand out of the card.
|
||||
const WIDTH: f32 = 1200.;
|
||||
const HEIGHT: f32 = 441.;
|
||||
static BANNER: LazyLock<Arc<Image>> = LazyLock::new(|| {
|
||||
Arc::new(Image::from_bytes(
|
||||
ImageFormat::Webp,
|
||||
include_bytes!("../assets/sculk-banner.webp").to_vec(),
|
||||
))
|
||||
});
|
||||
|
||||
/// The banner `width` logical pixels wide, under its label. Hovering lifts it a little and turns the
|
||||
/// label to ink. The narrowest window (960) leaves the page 648 pixels, so it always fits.
|
||||
pub fn banner(id: &'static str, width: f32, t: &Theme) -> Stateful<Div> {
|
||||
let t = *t;
|
||||
let el = div()
|
||||
.id(id)
|
||||
.group(id)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(8.))
|
||||
.w(px(width))
|
||||
.cursor_pointer()
|
||||
.child(
|
||||
crate::text(crate::theme::MICRO)
|
||||
.text_color(t.muted)
|
||||
.group_hover(id, move |s| s.text_color(t.ink))
|
||||
.child("PARTNER"),
|
||||
)
|
||||
.child(
|
||||
div().relative().group_hover(id, |s| s.top(px(-2.))).child(
|
||||
img(BANNER.clone())
|
||||
.w(px(width))
|
||||
.h(px(width * HEIGHT / WIDTH)),
|
||||
),
|
||||
)
|
||||
.on_click(|_: &ClickEvent, _, cx| cx.open_url(URL));
|
||||
crate::keyboard(el, &t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{HEIGHT, WIDTH};
|
||||
|
||||
#[test]
|
||||
fn the_bundled_banner_decodes() {
|
||||
let bytes = include_bytes!("../assets/sculk-banner.webp");
|
||||
let banner = image::load_from_memory_with_format(bytes, image::ImageFormat::WebP)
|
||||
.expect("the banner is a WebP");
|
||||
assert_eq!(
|
||||
(banner.width(), banner.height()),
|
||||
(WIDTH as u32, HEIGHT as u32)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! The proxy every download and request goes through, when the player needs one: a school's or an
|
||||
//! office's, or a country where a host is unreachable. The Settings page's Proxy row (kept as
|
||||
//! `proxy` in `settings.json`) wins; without it the usual `HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY`
|
||||
//! and `NO_PROXY` variables apply, so a launcher started from a shell that has them needs nothing.
|
||||
//!
|
||||
//! What goes through it: Horizon's releases and the launcher's own update, Minecraft's files and
|
||||
//! Java from Mojang, Modrinth, CurseForge, Horizon's mod registry, pictures, Microsoft sign-in,
|
||||
//! Tailscale's API, and the jars a modpack import downloads. A local address never does, and the
|
||||
//! Servers page's calls to a game server's API (`servers.rs`) build their agent without it: they
|
||||
//! are on loopback and asked every second.
|
||||
//!
|
||||
//! Which hosts are reached directly, and how an address is read, are `horizon-port-pack`'s rules
|
||||
//! (`crates/horizon-port-pack/src/net.rs`): the jars an import fetches are downloaded there, and
|
||||
//! the same hosts have to be left alone on both sides. This module adds what is the launcher's
|
||||
//! own — the setting in `settings.json`, kept in memory so a request doesn't read the file — and
|
||||
//! hands the address to the parts that build their agents.
|
||||
use crate::backend::Settings;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The launcher's setting, as `announce` last read it, or None before it has: a request shouldn't
|
||||
/// read `settings.json` every time, and an import fetches hundreds of jars.
|
||||
static SET: Mutex<Option<Option<String>>> = Mutex::new(None);
|
||||
|
||||
/// The proxy address to reach `url` through: the launcher's setting, else the environment's, unless
|
||||
/// `url` is a local address or `NO_PROXY` names its host.
|
||||
pub fn spec_for(url: &str) -> Option<String> {
|
||||
let scheme = horizon_port_pack::net::scheme_of(url)?;
|
||||
if horizon_port_pack::net::direct(url) {
|
||||
return None;
|
||||
}
|
||||
setting().or_else(|| horizon_port_pack::net::env_for(scheme))
|
||||
}
|
||||
|
||||
/// The proxy to reach `url` through: `spec_for`'s address, read as one.
|
||||
pub fn for_url(url: &str) -> Option<ureq::Proxy> {
|
||||
spec_for(url).and_then(|spec| horizon_port_pack::net::parse(&spec))
|
||||
}
|
||||
|
||||
/// `builder`, reaching `url` through the proxy when one is set. For the parts that ask for a few
|
||||
/// addresses; the ones that fetch file after file keep their agent instead (`keep`).
|
||||
pub fn agent(builder: ureq::AgentBuilder, url: &str) -> ureq::AgentBuilder {
|
||||
match for_url(url) {
|
||||
Some(proxy) => builder.proxy(proxy),
|
||||
None => builder,
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `spec` can't be used as a proxy, or None when it can (empty means none).
|
||||
pub fn refuse(spec: &str) -> Option<String> {
|
||||
let spec = spec.trim();
|
||||
if spec.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if horizon_port_pack::net::socks(spec) {
|
||||
return Some(format!(
|
||||
"{} is a SOCKS proxy; Horizon downloads through an HTTP proxy, such as the \
|
||||
http:// address your proxy app also listens on.",
|
||||
horizon_port_pack::net::redacted(spec)
|
||||
));
|
||||
}
|
||||
// `ureq` takes `http://` without a host, which would leave a download failing with nothing
|
||||
// said about the proxy.
|
||||
if horizon_port_pack::net::parse(spec).is_none()
|
||||
|| horizon_port_pack::net::host_of(spec).is_none_or(str::is_empty)
|
||||
{
|
||||
return Some(format!(
|
||||
"{} isn't a proxy address. Write it as http://host:port.",
|
||||
horizon_port_pack::net::redacted(spec)
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Tells the parts that build their own agents (`horizon-port-pack`) which proxy to use, and keeps
|
||||
/// the setting for the launcher's own requests. Called with what `settings.json` holds: at start,
|
||||
/// and whenever the player changes the setting.
|
||||
///
|
||||
/// The environment's is left to them: they read it per address (`HTTPS_PROXY` for an https jar,
|
||||
/// `HTTP_PROXY` for an http one), the way the launcher does for its own.
|
||||
pub fn announce(setting: Option<String>) {
|
||||
let spec = setting
|
||||
.map(|p| p.trim().to_owned())
|
||||
.filter(|p| !p.is_empty());
|
||||
*held() = Some(spec.clone());
|
||||
horizon_port_pack::net::set_proxy(spec);
|
||||
}
|
||||
|
||||
/// The launcher's setting: read from `settings.json` the first time it is needed and kept after
|
||||
/// that, so a download doesn't read the file once per file.
|
||||
fn setting() -> Option<String> {
|
||||
let mut set = held();
|
||||
match set.clone() {
|
||||
Some(kept) => kept,
|
||||
None => {
|
||||
let read = written();
|
||||
*set = Some(read.clone());
|
||||
read
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The launcher's setting as it is written down, or None when there is none.
|
||||
fn written() -> Option<String> {
|
||||
Settings::load()
|
||||
.proxy
|
||||
.map(|p| p.trim().to_owned())
|
||||
.filter(|p| !p.is_empty())
|
||||
}
|
||||
|
||||
/// The setting's lock, even after a thread panicked while holding it: an address lost to a panic
|
||||
/// is worse than an old one kept.
|
||||
fn held() -> std::sync::MutexGuard<'static, Option<Option<String>>> {
|
||||
SET.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_local_address_takes_no_proxy() {
|
||||
assert_eq!(spec_for("http://127.0.0.1:8130/api/v1/status"), None);
|
||||
assert_eq!(spec_for("http://localhost/api/v1/status"), None);
|
||||
}
|
||||
|
||||
/// An address the launcher knows nothing about is one nothing is written for either.
|
||||
#[test]
|
||||
fn a_relative_address_has_no_scheme_to_read_a_proxy_for() {
|
||||
assert_eq!(spec_for("data/a.jar"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_proxy_address_is_checked_before_it_is_kept() {
|
||||
assert_eq!(refuse(""), None);
|
||||
assert_eq!(refuse(" "), None);
|
||||
assert_eq!(refuse("http://127.0.0.1:7890"), None);
|
||||
assert_eq!(refuse("127.0.0.1:7890"), None);
|
||||
assert_eq!(refuse("http://user:pass@proxy.local:3128"), None);
|
||||
assert!(refuse("http://").is_some());
|
||||
assert!(refuse("socks5://127.0.0.1:7891").is_some());
|
||||
}
|
||||
|
||||
/// The reason is shown under the field and printed by `horizon-launcher settings set`.
|
||||
#[test]
|
||||
fn a_refused_address_keeps_its_credentials_to_itself() {
|
||||
let why = refuse("socks5://user:secret@127.0.0.1:7891").unwrap();
|
||||
assert!(why.starts_with("socks5://***@127.0.0.1:7891 "), "{why}");
|
||||
let why = refuse("http://user:secret@").unwrap();
|
||||
assert!(!why.contains("secret"), "{why}");
|
||||
}
|
||||
}
|
||||
@@ -813,6 +813,8 @@ impl Api {
|
||||
}
|
||||
|
||||
pub fn call(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value, String> {
|
||||
// No proxy here on purpose: the server is on this computer, and this is asked every
|
||||
// second (`proxy` never sends a loopback address through one either).
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build();
|
||||
|
||||
@@ -1167,12 +1167,15 @@ impl Launcher {
|
||||
{
|
||||
page = page.child(self.problem_notice(p, cx));
|
||||
}
|
||||
let partner = super::partner::banner("partner-servers", 600., &t);
|
||||
if self.servers.list.is_empty() {
|
||||
return page.child(centered(
|
||||
"No server yet. Create one: it takes a few seconds, and with the defaults (tick \
|
||||
the EULA, press Create) you get a friends-only survival world.",
|
||||
&t,
|
||||
));
|
||||
return page
|
||||
.child(centered(
|
||||
"No server yet. Create one: it takes a few seconds, and with the defaults \
|
||||
(tick the EULA, press Create) you get a friends-only survival world.",
|
||||
&t,
|
||||
))
|
||||
.child(partner);
|
||||
}
|
||||
let mut list = div().flex().flex_col().border_t_1().border_color(t.rule);
|
||||
for (i, e) in self.servers.list.clone().into_iter().enumerate() {
|
||||
@@ -1213,7 +1216,7 @@ impl Launcher {
|
||||
&t,
|
||||
));
|
||||
}
|
||||
page.child(list)
|
||||
page.child(list).child(partner)
|
||||
}
|
||||
|
||||
fn add_server_folder(&mut self, cx: &mut Context<Self>) {
|
||||
|
||||
@@ -260,11 +260,14 @@ impl Api {
|
||||
body: Option<&Value>,
|
||||
if_match: Option<&str>,
|
||||
) -> Result<(Value, Option<String>), String> {
|
||||
let agent = ureq::AgentBuilder::new()
|
||||
.timeout(Duration::from_secs(20))
|
||||
.build();
|
||||
let url = format!("{}/api/v2{path}", self.base);
|
||||
let agent = crate::proxy::agent(
|
||||
ureq::AgentBuilder::new().timeout(Duration::from_secs(20)),
|
||||
&url,
|
||||
)
|
||||
.build();
|
||||
let mut request = agent
|
||||
.request(method, &format!("{}/api/v2{path}", self.base))
|
||||
.request(method, &url)
|
||||
.set("Authorization", &format!("Bearer {}", self.token))
|
||||
.set("Accept", "application/json");
|
||||
if let Some(etag) = if_match {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.*;
|
||||
import net.minecraft.util.Continuation;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.decoration.Cushion;
|
||||
import net.minecraft.world.level.BlockGetter;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.*;
|
||||
import net.minecraft.world.level.blockscan.*;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.minecraft.world.phys.shapes.*;
|
||||
|
||||
public final class VanillaCushionPlacementOracle {
|
||||
record Cell(VoxelShape outline, VoxelShape collision, boolean suffocating) {}
|
||||
static final Cell AIR = new Cell(Shapes.empty(), Shapes.empty(), false);
|
||||
static final class FixtureBlock extends Block {
|
||||
FixtureBlock() { super(BlockBehaviour.Properties.of().dynamicShape()
|
||||
.setId(ResourceKey.create(Registries.BLOCK, Identifier.parse("horizon:cushion_fixture")))
|
||||
.isSuffocating((s, w, p) -> ((World)w).cell(p).suffocating())); }
|
||||
@Override protected VoxelShape getShape(BlockState s, BlockGetter w, BlockPos p, CollisionContext c) {
|
||||
return w instanceof World f ? f.cell(p).outline() : Shapes.empty();
|
||||
}
|
||||
}
|
||||
static BlockState state;
|
||||
static final class World extends ClientLevel {
|
||||
Map<BlockPos, Cell> cells;
|
||||
World() { super(null, null, null, null, 0, 0, null, false, 0, 0); }
|
||||
Cell cell(BlockPos p) { return cells.getOrDefault(p, AIR); }
|
||||
@Override public BlockState getBlockState(BlockPos p) { return state; }
|
||||
@Override public Iterable<VoxelShape> getBlockCollisions(Entity e, AABB b) {
|
||||
var result = new ArrayList<VoxelShape>();
|
||||
cells.forEach((p, c) -> result.add(c.collision().move(p)));
|
||||
return result;
|
||||
}
|
||||
@Override public BlockMatcher findBlocksIn(AABB bounds) {
|
||||
return new BlockMatcher(this) {
|
||||
@Override public boolean atLeastMatched(int n) { throw new AssertionError(); }
|
||||
@Override protected boolean anyMatched(Predicate<BlockState> p) { throw new AssertionError(); }
|
||||
@Override public void forEach(BiConsumer<BlockPos, BlockState> c) { throw new AssertionError(); }
|
||||
@Override public boolean forEachUntil(BlockStateConsumer consumer) {
|
||||
for (var p : BlockPos.betweenClosed(bounds)) {
|
||||
if (consumer.apply(p, state) == Continuation.ABORT) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
static VoxelShape shape(JsonElement v) {
|
||||
var result = Shapes.empty();
|
||||
for (var e : v.getAsJsonArray()) {
|
||||
var b = e.getAsJsonArray();
|
||||
result = Shapes.or(result, Shapes.box(b.get(0).getAsDouble(), b.get(1).getAsDouble(), b.get(2).getAsDouble(), b.get(3).getAsDouble(), b.get(4).getAsDouble(), b.get(5).getAsDouble()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion(); net.minecraft.server.Bootstrap.bootStrap();
|
||||
// Supply one unregistered fixture block without changing the checks under test.
|
||||
var registry = net.minecraft.core.registries.BuiltInRegistries.BLOCK;
|
||||
var holders = net.minecraft.core.MappedRegistry.class.getDeclaredField("unregisteredIntrusiveHolders");
|
||||
holders.setAccessible(true); holders.set(registry, new IdentityHashMap<>());
|
||||
var frozen = net.minecraft.core.MappedRegistry.class.getDeclaredField("frozen");
|
||||
frozen.setAccessible(true); frozen.setBoolean(registry, false);
|
||||
state = new FixtureBlock().defaultBlockState();
|
||||
var u = Class.forName("sun.misc.Unsafe"); var f = u.getDeclaredField("theUnsafe"); f.setAccessible(true);
|
||||
var unsafe = f.get(null); var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (var line : (Iterable<String>)lines::iterator) {
|
||||
var row = JsonParser.parseString(line).getAsJsonObject();
|
||||
var world = (World)allocate.invoke(unsafe, World.class); world.cells = new HashMap<>();
|
||||
for (var e : row.getAsJsonArray("cells")) {
|
||||
var c = e.getAsJsonArray();
|
||||
world.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), new Cell(shape(c.get(3)), shape(c.get(4)), c.get(5).getAsBoolean()));
|
||||
}
|
||||
var p = row.getAsJsonArray("pos"); double x=p.get(0).getAsDouble(), y=p.get(1).getAsDouble(), z=p.get(2).getAsDouble();
|
||||
var bounds = new AABB(x-.5, y, z-.5, x+.5, y+.25, z+.5);
|
||||
out.println(Cushion.canBePlacedAt(world, bounds) + " " + Cushion.wouldSurviveAt(world, bounds));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+105
-2
@@ -290,7 +290,15 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
# Match normal single player; --in-frame is the comparison path.
|
||||
SERVER_THREAD = True
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater']
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp',
|
||||
'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles',
|
||||
'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing',
|
||||
'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push',
|
||||
'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles',
|
||||
'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects',
|
||||
'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands',
|
||||
'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption',
|
||||
'breath', 'lava', 'levels', 'drops', 'underwater', 'fireworks']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -2898,6 +2906,55 @@ def sparked(player, other, kinds, act, ticks=20):
|
||||
return seen
|
||||
|
||||
|
||||
def check_fireworks(host, guest, out):
|
||||
"""Event 17 must arrive before removal, with the item's colored, trailing explosion (#1478).
|
||||
|
||||
FireworkRocketEntity.explode / handleEntityEvent; run with and without --server-thread.
|
||||
The flash proves a configured explosion reached both clients; red pixels in later screenshots
|
||||
check that its sparks keep rendering after the tracked rocket disappears.
|
||||
"""
|
||||
x, y, z = (int(v // 1) for v in pos_of(host))
|
||||
at = (x, y - 1, z + 3)
|
||||
host('command', command=f'fill {x - 5} {y - 1} {z - 2} {x + 5} {y - 1} {z + 8} minecraft:stone')
|
||||
host('command', command=f'fill {x - 5} {y} {z - 2} {x + 5} {y + 4} {z + 8} minecraft:air')
|
||||
host('command', command=f'fill {x - 2} {y + 2} {z + 1} {x + 2} {y + 2} {z + 5} minecraft:stone')
|
||||
for game, dx in ((host, -2), (guest, 2)):
|
||||
game('command', command='gamemode creative')
|
||||
game('command', command=f'tp @s {x + dx + 0.5} {y} {z + 0.5}')
|
||||
game.raw('look-at', x + 0.5, y + 1.5, z + 3.5)
|
||||
|
||||
def red(path):
|
||||
rows, bpp = png_rows(path)
|
||||
# Exclude the hotbar and chat at the bottom of the view.
|
||||
return sum(row[i] > 80 and row[i] > 2 * row[i + 1] and row[i] > 2 * row[i + 2]
|
||||
for row in rows[:len(rows) * 3 // 4] for i in range(0, len(row), bpp))
|
||||
|
||||
baseline = {g.name: red(g.shot(out, 'fireworks-before')) for g in (host, guest)}
|
||||
before = {g.name: made(g, 'flash') for g in (host, guest)}
|
||||
host('command', command='item replace entity @s weapon.mainhand with minecraft:firework_rocket'
|
||||
'[fireworks={flight_duration:0,explosions:[{shape:"large_ball",colors:[I;16711680],has_trail:true}]}]')
|
||||
host.raw('interact', *at)
|
||||
# The held item's red texture must not count as a burst or a later spark.
|
||||
host('command', command='item replace entity @s weapon.mainhand with minecraft:air')
|
||||
for _ in range(30):
|
||||
host.wait(2)
|
||||
if all(made(g, 'flash') > before[g.name] for g in (host, guest)):
|
||||
break
|
||||
flashes = {g.name: made(g, 'flash') - before[g.name] for g in (host, guest)}
|
||||
assert all(n == 1 for n in flashes.values()), f'configured burst missing or duplicated: {flashes}'
|
||||
# Capture both views before decoding PNGs: decoding must not consume the sparks' lifetime.
|
||||
burst_shots = {g.name: g.shot(out, 'fireworks-burst') for g in (host, guest)}
|
||||
host.wait(16)
|
||||
trail_shots = {g.name: g.shot(out, 'fireworks-trail-fade') for g in (host, guest)}
|
||||
burst = {name: red(path) - baseline[name] for name, path in burst_shots.items()}
|
||||
trails = {name: red(path) - baseline[name] for name, path in trail_shots.items()}
|
||||
rockets = {g.name: g('status')['rockets'] for g in (host, guest)}
|
||||
assert not any(rockets.values()), f'exploded rocket remains: {rockets}'
|
||||
assert all(n > 20 for n in burst.values()), f'no red burst: {burst}'
|
||||
assert all(n > 20 for n in trails.values()), f'no later red trail/fade: {trails}'
|
||||
return {'flashes': flashes, 'red_burst': burst, 'red_trail_fade': trails, 'rockets': rockets}
|
||||
|
||||
|
||||
def check_sparks(host, guest, out):
|
||||
spots = apart(host, guest)
|
||||
result = {}
|
||||
@@ -4631,7 +4688,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour,
|
||||
'hud': check_hud,
|
||||
'sidebar': check_sidebar,
|
||||
'border': check_border,
|
||||
'particles': check_particles}
|
||||
'particles': check_particles, 'fireworks': check_fireworks}
|
||||
|
||||
|
||||
def run(ctl, out, resources, checks):
|
||||
@@ -6993,5 +7050,51 @@ CHECKS += ['creative_tools']
|
||||
CHECK_FNS['creative_tools'] = check_creative_tools
|
||||
|
||||
|
||||
def check_cushions(host, guest, out):
|
||||
"""#1935: place a colored cushion, consume it, track it, sit, dismount and break it."""
|
||||
seen = {}
|
||||
for label, player, color in (('host', host, 'red'), ('guest', guest, 'blue')):
|
||||
x, y, z = (int(v // 1) for v in pos_of(player))
|
||||
at = (x + 0.5, y, z + 2.5)
|
||||
host('command', command=f'fill {x - 1} {y} {z + 1} {x + 1} {y + 3} {z + 3} minecraft:air')
|
||||
host('command', command=f'setblock {x} {y - 1} {z + 2} minecraft:stone')
|
||||
player('command', command='gamemode survival')
|
||||
player('command', command=f'item replace entity @s weapon.mainhand with minecraft:{color}_cushion')
|
||||
player.wait(10)
|
||||
player.raw('look-at', *at)
|
||||
player.raw('mouse', 'right', 'click')
|
||||
player.wait(15)
|
||||
def cushions(game):
|
||||
return [o for o in game('status')['objects'] if o['kind'] == 'minecraft:cushion'
|
||||
and abs(o['position'][0] - at[0]) < .1 and abs(o['position'][2] - at[2]) < .1]
|
||||
server, client = cushions(host), cushions(player)
|
||||
seen[label] = {'server': server, 'client': client,
|
||||
'remaining': player('inventory')['counts'].get(f'minecraft:{color}_cushion', 0)}
|
||||
assert len(server) == len(client) == 1, seen
|
||||
assert server[0]['color'] == client[0]['color'] == color, seen
|
||||
assert seen[label]['remaining'] == 0, seen
|
||||
player.shot(out, 'cushion-placed')
|
||||
player.raw('look-at', at[0], at[1] + .125, at[2])
|
||||
player.raw('mouse', 'right', 'click')
|
||||
player.wait(10)
|
||||
seen[label]['riding'] = player('status').get('riding')
|
||||
assert seen[label]['riding'] == server[0]['id'], seen
|
||||
player.raw('key', 'shift', 'down')
|
||||
player.wait(5)
|
||||
player.raw('key', 'shift', 'up')
|
||||
player.wait(5)
|
||||
assert player('status').get('riding') is None, seen
|
||||
player('command', command='gamemode creative')
|
||||
player.raw('look-at', at[0], at[1] + .125, at[2])
|
||||
player.raw('mouse', 'left', 'click')
|
||||
player.wait(10)
|
||||
assert not cushions(host) and not cushions(player), seen
|
||||
return seen
|
||||
|
||||
|
||||
CHECKS += ['cushions']
|
||||
CHECK_FNS['cushions'] = check_cushions
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare cushion support, burial and coverage against vanilla's real checks."""
|
||||
import json
|
||||
import random
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def make_input(build):
|
||||
full = [[0, 0, 0, 1, 1, 1]]
|
||||
shapes = [[], full, [[0, 0, 0, 1, .5, 1]], [[0, .5, 0, 1, 1, 1]],
|
||||
[[.375, 0, .375, .625, 1.5, .625]], [[0, 0, 0, .5, 1, 1]],
|
||||
[[0, 0, 0, .5, 1, 1], [.5, 0, 0, 1, 1, 1]]]
|
||||
rows = []
|
||||
for x, z in ((0, 0), (-2, -3), (17, 31)):
|
||||
for y in (0, .125, .5, .875, 1, 1.00000001, 1.015625, 1.125):
|
||||
for outline in shapes:
|
||||
for collision in shapes:
|
||||
for suffocating in (False, True):
|
||||
rows.append(dict(pos=[x + .5, y, z + .5],
|
||||
cells=[[x, 0, z, outline, collision, suffocating]]))
|
||||
rng = random.Random(1935)
|
||||
for _ in range(500):
|
||||
cells = []
|
||||
for y in (-1, 0, 1):
|
||||
for x in (-1, 0, 1):
|
||||
for z in (-1, 0, 1):
|
||||
if rng.random() < .3:
|
||||
cells.append([x, y, z, rng.choice(shapes), rng.choice(shapes), bool(rng.randrange(2))])
|
||||
rows.append(dict(pos=[rng.choice((0, .5, 1)), rng.choice((0, .5, 1, 1.125)), rng.choice((0, .5, 1))], cells=cells))
|
||||
path = build / 'inputs.jsonl'
|
||||
path.write_text(''.join(json.dumps(row) + '\n' for row in rows))
|
||||
return path, len(rows)
|
||||
|
||||
|
||||
def main():
|
||||
harness.differential(
|
||||
'rust-cushion-placement-parity', 'VanillaCushionPlacementOracle',
|
||||
'cushion_placement_probe', make_input,
|
||||
'Actual Cushion.canBePlacedAt and wouldSurviveAt, with controlled outline, collision '
|
||||
'and suffocation queries. Includes partial supports, burial, complete coverage, '
|
||||
'overhanging outlines, negative coordinates and boundary heights. Item use, '
|
||||
'entity tracking, interaction and persistence are checked separately.',
|
||||
sources=[lab.ROOT / 'crates/horizon-client/src/cushion.rs'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -519,7 +519,9 @@ def main():
|
||||
# The oracle's server world: cleared before each run, never left in /tmp.
|
||||
world = build / 'world'
|
||||
shutil.rmtree(world, ignore_errors=True)
|
||||
oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
# Each scenario forces 9x9 chunks 512 blocks past the last one, so a run generates ~80 chunks per scenario;
|
||||
# 3g ran out of heap in PoiManager.tick on a busy runner (#2160's CI, 143 scenarios).
|
||||
oracle_harness.run_logged(['java', '-Xmx4g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt', world],
|
||||
build, 'vanilla', timeout=3600)
|
||||
if not args.java_only:
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""FireworkRocketEntity event 17 renders the configured burst before tracked removal.
|
||||
|
||||
Exercise both hosting paths and subsequent trail/fade frames through real clients.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
import lab
|
||||
import lan_e2e as lan
|
||||
|
||||
|
||||
def main():
|
||||
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client',
|
||||
'--bin', 'horizon-client', '--bin', 'horizon-ctl'], cwd=lab.ROOT, check=True)
|
||||
metadata = json.loads(subprocess.check_output(
|
||||
['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=lab.ROOT, text=True))
|
||||
ctl = lab.ROOT / metadata['target_directory'] / 'fast' / 'horizon-ctl'
|
||||
# CI supplies the display; each game still gets fresh scratch homes.
|
||||
lan.game_env = lambda _screen, home: lab.game_env(
|
||||
HORIZON_HOME=home, HORIZON_TELEMETRY_URL='off')
|
||||
reports = {}
|
||||
for threaded in (True, False):
|
||||
lan.SERVER_THREAD = threaded
|
||||
mode = 'server-thread' if threaded else 'in-frame'
|
||||
out = lab.LOCAL / 'remote-fireworks-parity' / mode
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
reports[mode] = lan.run(ctl, out, lab.RESOURCES.resolve(), ['fireworks'])
|
||||
lab.write_json(lab.LOCAL / 'remote-fireworks-parity' / 'report.json', reports)
|
||||
assert all(r['pass'] for mode in reports.values() for r in mode.values()), reports
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -80,6 +80,8 @@ IGNORED = {
|
||||
# chunk generation first), so counters and positions of live things move on.
|
||||
r'^chunk\.block_entities\.\(2, -60, 5\)\.(cooking_time_spent|lit_time_remaining|Items\[\]\.count)$':
|
||||
'the lit furnace keeps smelting',
|
||||
r'^chunk\.block_entities\.\(14, -60, 5\)\.CookingTimes$':
|
||||
'the lit campfire keeps cooking',
|
||||
r'^chunk\.block_entities\..*\.(ticks_since_song_started|Age|BrewTime|warning_level|ticks_in_hive|last_vibration_frequency|listener\..*|RecipesUsed\..*|'
|
||||
r'server_data\.state_updating_resumes_at)$':
|
||||
'block entity timers advance',
|
||||
|
||||
Reference in New Issue
Block a user