Merge main into agent branch

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 09:57:55 +02:00
98 changed files with 13539 additions and 1293 deletions
@@ -0,0 +1,97 @@
//! Block transformer lookups for tools/test_block_transformer_parity.py: reads
//! "transformer TAB face TAB clicked TAB above" lines (states as
//! "name|prop=value,...") and prints the oracle's result lines.
//!
//! usage: block_transform_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
assets::Assets,
block_transform::{Around, Transformers},
items::Items,
};
use horizon_world::chunk::BlockState;
use std::{fs, path::Path};
fn parse(text: &str) -> BlockState {
let (name, props) = text.split_once('|').unwrap_or((text, ""));
BlockState {
name: name.to_owned(),
properties: props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
}
}
fn describe(state: &BlockState) -> String {
let props: Vec<String> = state
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}|{}", state.name, props.join(","))
}
struct Column {
clicked: BlockState,
above: BlockState,
}
impl Around for Column {
fn state(&self, offset: [i32; 3]) -> BlockState {
match offset {
[0, 0, 0] => self.clicked.clone(),
[0, 1, 0] => self.above.clone(),
_ => BlockState {
name: "minecraft:stone".into(),
properties: Default::default(),
},
}
}
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let assets = Assets::load(root)?;
let transformers = Transformers::load(root, assets.registry)?;
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split('\t').collect();
let around = Column {
clicked: parse(f[2]),
above: parse(f[3]),
};
if f[0] == "honeycomb" {
let waxed = transformers.waxed(assets.registry, &around.clicked);
out += &format!("{}\n", waxed.map_or("none".to_owned(), |s| describe(&s)));
continue;
}
let id = format!("minecraft:{}", f[0]);
match transformers.apply(&items, assets.registry, &id, f[1], &around) {
None => out += "none\n",
Some((index, t, state)) => {
out += &format!(
"{index}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
describe(&state),
t.sound,
t.particle,
t.loot.as_deref().unwrap_or("-"),
t.drop_strategy,
t.update_from_neighbors,
t.transform_type,
t.consume_on_use,
t.damage
);
}
}
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,145 @@
//! Cauldron interactions for tools/test_cauldron_parity.py: reads one JSON
//! case per line and prints "result TAB events TAB inventory".
//!
//! usage: cauldron_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
cauldron::{Outcome, Player, interact, removes_dye},
crafting::Recipes,
item_data::{canon_stack, parse_stack},
items::{ItemStack, Items},
menu::{Env, Kind, Menu},
};
use horizon_world::chunk::BlockState;
use serde_json::Value;
use std::{fs, path::Path};
struct Stand<'a> {
menu: Menu,
env: &'a Env<'a>,
events: Vec<String>,
hand: Option<ItemStack>,
}
impl Player for Stand<'_> {
fn creative(&self) -> bool {
self.menu.creative
}
fn hand(&mut self) -> &mut Option<ItemStack> {
&mut self.hand
}
fn add(&mut self, stack: &mut ItemStack) -> bool {
// The held stack lives in inventory slot 0 for Inventory.add.
self.menu.set_player_item(0, self.hand.take());
let added = self.menu.give(self.env, stack);
self.hand = self.menu.player_item(0).cloned();
self.menu.set_player_item(0, None);
added
}
fn contains(&self, stack: &ItemStack) -> bool {
self.menu.player_contains(stack)
|| self
.hand
.as_ref()
.is_some_and(|h| h.same_item_same_components(stack))
}
fn drop_stack(&mut self, stack: ItemStack) {
self.events
.push(format!("drop {}", canon_stack(Some(&stack))));
}
}
fn parse(text: &str) -> BlockState {
let (name, props) = text.split_once('|').unwrap_or((text, ""));
BlockState {
name: name.to_owned(),
properties: props
.split(',')
.filter(|p| !p.is_empty())
.filter_map(|p| p.split_once('='))
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
}
}
fn describe(state: &BlockState) -> String {
let props: Vec<String> = state
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}|{}", state.name, props.join(","))
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
};
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
let mut menu = Menu::new(Kind::Inventory);
menu.creative = case["creative"].as_bool().unwrap_or(false);
for pair in case["inventory"].as_array().ok_or("inventory")? {
menu.set_player_item(
pair[0].as_u64().unwrap_or(0) as usize,
parse_stack(pair[1].as_str().unwrap_or("-"))?,
);
}
let held = parse_stack(case["held"].as_str().unwrap_or("-"))?;
let mut stand = Stand {
menu,
env: &env,
events: Vec::new(),
hand: held,
};
let cauldron = parse(case["state"].as_str().unwrap_or_default());
let dye = stand
.hand
.as_ref()
.is_some_and(|h| removes_dye(&items, &h.item));
let result = interact(
&cauldron,
case["under_water"].as_bool().unwrap_or(false),
dye,
&mut stand,
);
if let Some(block) = &result.block {
stand.events.push(format!("set {}", describe(block)));
}
if let Some(sound) = result.sound {
stand.events.push(format!("sound {sound}"));
}
let kind = match result.outcome {
Outcome::Success => "success",
Outcome::Consume => "consume",
Outcome::Pass => "pass",
};
stand.menu.set_player_item(0, stand.hand.take());
let inventory: Vec<String> = (0..41)
.filter_map(|i| {
stand
.menu
.player_item(i)
.map(|s| format!("{i}={}", canon_stack(Some(s))))
})
.collect();
out += &format!(
"{kind}\t{}\t{}\n",
stand.events.join(";"),
inventory.join(" ")
);
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,212 @@
//! Resident chunk storage benchmark: generates a block of vanilla terrain, then
//! reports the resident block/biome memory, the cost of lookups, meshing and
//! lighting on it.
//!
//! chunk_bench <client resource dir> [--seed S] [--size N]
#![forbid(unsafe_code)]
use horizon_client::{
assets::Assets,
biome::Biomes,
blocks::BlockFacts,
chunk::{Chunk, MIN_Y, SECTIONS},
light::{LightTables, light_chunk},
mesher::{MeshTables, Mesher},
models,
streaming::{ChunkGenerator, Proto},
vanillagen::VanillaTerrain,
};
use horizon_core::biome::BiomeZoom;
use std::{path::PathBuf, sync::Arc, time::Instant};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let root = PathBuf::from(args.first().ok_or("usage: chunk_bench RESOURCES")?);
let flag = |name: &str, default: i64| -> i64 {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1))
.and_then(|v| v.parse().ok())
.unwrap_or(default)
};
let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32);
let assets = Assets::load(&root)?;
let facts = BlockFacts::load(&root, assets.registry)?;
let biomes = Biomes::load(&root)?;
let tables = MeshTables::new(
&assets,
&facts,
models::load_visibility(&root, assets.registry)?,
)?;
let light = LightTables::load(&root, assets.registry, &facts)?;
let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, seed)?;
let mut worker = terrain.worker();
// Protos for size+4 columns, decorated for the inner size+2, finished as size+2.
let started = Instant::now();
let outer = size + 4;
let mut protos: Vec<Option<Proto>> = (0..outer * outer)
.map(|i| Some(terrain.proto(&mut worker, i % outer, i / outer)))
.collect();
eprintln!("proto: {:.2}s", started.elapsed().as_secs_f64());
let started = Instant::now();
let inner = size + 2;
for z in 1..=inner {
for x in 1..=inner {
let mut region: [Proto; 9] = std::array::from_fn(|k| {
let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1);
protos[((z + dz) * outer + x + dx) as usize]
.take()
.expect("proto")
});
terrain.decorate(&mut worker, &mut region);
for (k, p) in region.into_iter().enumerate() {
let (dx, dz) = (k as i32 % 3 - 1, k as i32 / 3 - 1);
protos[((z + dz) * outer + x + dx) as usize] = Some(p);
}
}
}
eprintln!("decorate: {:.2}s", started.elapsed().as_secs_f64());
let started = Instant::now();
let mut chunks: Vec<Chunk> = Vec::new();
for z in 1..=inner {
for x in 1..=inner {
let proto = protos[(z * outer + x) as usize].take().expect("proto");
let mut chunk = terrain.finish(proto);
chunk.x = x;
chunk.z = z;
chunks.push(chunk);
}
}
let finish = started.elapsed().as_secs_f64();
println!(
"finish (proto -> resident chunk): {:.1} ms per chunk",
finish * 1e3 / chunks.len() as f64
);
let chunks: Vec<Arc<Chunk>> = chunks.into_iter().map(Arc::new).collect();
let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone();
// Light all inner-inner columns.
let started = Instant::now();
let mut lit = Vec::new();
for z in 2..inner {
for x in 2..inner {
let region: [[Option<Arc<Chunk>>; 3]; 3] = std::array::from_fn(|dz| {
std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1)))
});
let borrowed = horizon_client::mesher::borrow(&region);
lit.push(((x, z), light_chunk(&borrowed, &light, true)));
}
}
println!(
"light: {:.2} ms per column",
started.elapsed().as_secs_f64() * 1e3 / lit.len() as f64
);
let mut chunks: Vec<Chunk> = chunks.iter().map(|c| (**c).clone()).collect();
for ((x, z), sections) in lit {
chunks[((z - 1) * inner + x - 1) as usize].sections = sections;
}
let chunks: Vec<Arc<Chunk>> = chunks.into_iter().map(Arc::new).collect();
let at = |x: i32, z: i32| chunks[((z - 1) * inner + x - 1) as usize].clone();
// Memory.
let (mut bytes, mut sections, mut uniform) = (0usize, 0usize, 0usize);
for chunk in &chunks {
bytes += chunk.heap_bytes();
for s in &chunk.sections {
sections += 1;
uniform += usize::from(s.is_uniform(s.get(0)));
}
}
println!(
"resident: {} chunks, {} sections ({} uniform), {:.1} KiB per chunk ({:.2} MiB total)",
chunks.len(),
sections,
uniform,
bytes as f64 / 1024.0 / chunks.len() as f64,
bytes as f64 / 1048576.0
);
// Meshing.
let mut mesher = Mesher {
nether_shading: false,
assets: &assets,
tables: &tables,
biomes: &biomes,
visibility: tables.visibility.clone(),
zoom: BiomeZoom::new(7),
blend_radius: 2,
smooth_lighting: true,
cutout_leaves: true,
};
let mut best = f64::MAX;
let mut quads = 0usize;
for _ in 0..3 {
let started = Instant::now();
let mut jobs = 0;
quads = 0;
for z in 2..inner {
for x in 2..inner {
let region: [[Option<Arc<Chunk>>; 3]; 3] = std::array::from_fn(|dz| {
std::array::from_fn(|dx| Some(at(x + dx as i32 - 1, z + dz as i32 - 1)))
});
let borrowed = horizon_client::mesher::borrow(&region);
for sy in 0..SECTIONS as i32 {
let mesh = mesher.mesh(&borrowed, sy);
quads += (mesh.solid.len() + mesh.translucent.len()) / 4;
jobs += 1;
}
}
}
best = best.min(started.elapsed().as_secs_f64() / f64::from(jobs));
}
println!(
"mesh: {:.1} us per section ({} quads total)",
best * 1e6,
quads
);
// Random lookups, as collision and entity queries do.
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let started = Instant::now();
let mut sum = 0u64;
let lookups = 20_000_000u64;
for _ in 0..lookups {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
let cx = 2 + (state % u64::from((inner - 2) as u32)) as i32;
let cz = 2 + ((state >> 8) % u64::from((inner - 2) as u32)) as i32;
let chunk = &chunks[((cz - 1) * inner + cx - 1) as usize];
let (x, y, z) = (
(state >> 16) as i32 & 15,
MIN_Y + ((state >> 24) % 384) as i32,
(state >> 40) as i32 & 15,
);
sum += u64::from(chunk.get(x, y, z));
}
println!(
"random get: {:.2} ns per lookup (checksum {sum})",
started.elapsed().as_secs_f64() * 1e9 / lookups as f64
);
// Coherent scan, as a column or area query does.
let started = Instant::now();
let mut sum = 0u64;
for _ in 0..4 {
for chunk in &chunks {
for y in MIN_Y..MIN_Y + 384 {
for z in 0..16 {
for x in 0..16 {
sum += u64::from(chunk.get(x, y, z));
}
}
}
}
}
println!(
"scan get: {:.2} ns per lookup (checksum {sum})",
started.elapsed().as_secs_f64() * 1e9 / (4.0 * chunks.len() as f64 * 98304.0)
);
Ok(())
}
@@ -0,0 +1,301 @@
#![forbid(unsafe_code)]
//! Runs the JSON-lines scenarios of tools/test_game_loop_parity.py through the
//! Rust timer, tick-rate manager, window, mouse and key-mapping code.
use horizon_client::{
Result,
clock::{ServerTickRateManager, Timer},
keymapping::KeyState,
mouse::{LookOptions, MouseLook, Rotation},
options_file::{OptionsFile, V},
window::{self, FrameContext, InactivityFpsLimit},
};
use serde_json::Value;
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
};
fn fl(v: &Value) -> f32 {
f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}
fn db(v: &Value) -> f64 {
f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}
fn fb(v: f32) -> String {
format!("{:08x}", if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() })
}
fn dbs(v: f64) -> String {
format!(
"{:016x}",
if v.is_nan() {
0x7ff8_0000_0000_0000
} else {
v.to_bits()
}
)
}
fn b(v: &Value) -> bool {
v.as_bool().unwrap()
}
fn timer(c: &Value, out: &mut impl Write) -> Result<()> {
let mut timer = Timer::new(fl(&c["tps"]), c["start"].as_i64().unwrap());
writeln!(out, "timer")?;
for op in c["ops"].as_array().unwrap() {
let name = op[0].as_str().unwrap();
let mut result = String::new();
match name {
"adv" => {
let mspt = if op[2].is_null() { 0.0 } else { fl(&op[2]) };
let ticks = timer.advance_game_time(op[1].as_i64().unwrap(), |d| {
if mspt == 0.0 { d } else { java_max(d, mspt) }
});
result = format!(" {ticks}");
}
"real" => timer.advance_real_time(op[1].as_i64().unwrap()),
"pause" => timer.update_pause_state(b(&op[1])),
"frozen" => timer.update_frozen_state(b(&op[1])),
_ => panic!("{name}"),
}
writeln!(
out,
"{name}{result} {} {} {} {}",
fb(timer.game_time_delta_ticks()),
fb(timer.game_time_delta_partial_tick(false)),
fb(timer.game_time_delta_partial_tick(true)),
fb(timer.realtime_delta_ticks())
)?;
}
Ok(())
}
/// Math.max(float, float).
fn java_max(a: f32, b: f32) -> f32 {
if a.is_nan() || b.is_nan() {
f32::NAN
} else if a == 0.0 && b == 0.0 {
f32::from_bits(a.to_bits() & b.to_bits())
} else if a >= b {
a
} else {
b
}
}
fn rate(c: &Value, out: &mut impl Write) -> Result<()> {
let mut m = ServerTickRateManager::default();
writeln!(out, "rate")?;
for op in c["ops"].as_array().unwrap() {
let name = op[0].as_str().unwrap();
let mut result = String::new();
let mut report = None;
match name {
"rate" => m.set_tick_rate(fl(&op[1])),
"freeze" => m.base.set_frozen(b(&op[1])),
"step" => {
result = format!(" {}", m.step_game_if_paused(op[1].as_i64().unwrap() as i32))
}
"stopstep" => result = format!(" {}", m.stop_stepping()),
"sprint" => {
result = format!(
" {}",
m.request_game_to_sprint(op[1].as_i64().unwrap() as i32)
)
}
"check" => {
let (run, r) = m.check_should_sprint_this_tick(op[1].as_i64().unwrap());
result = format!(" {run}");
report = r;
}
"end" => m.end_tick_work(op[1].as_i64().unwrap()),
"stopsprint" => {
report = m.stop_sprinting();
result = format!(" {}", report.is_some());
}
"tick" => m.base.tick(),
_ => panic!("{name}"),
}
let tail = report.map_or(String::new(), |r| {
format!(" report {} {}", r.ticks_per_second, r.milliseconds_per_tick)
});
writeln!(
out,
"{name}{result} | {} {} {} {} {} {} {} {}{tail}",
fb(m.base.tickrate()),
m.base.nanoseconds_per_tick(),
fb(m.base.milliseconds_per_tick()),
m.base.runs_normally(),
m.base.is_stepping_forward(),
m.base.frozen_ticks_to_run(),
m.base.is_frozen(),
m.is_sprinting()
)?;
}
Ok(())
}
fn scale(c: &Value, out: &mut impl Write) -> Result<()> {
let i = |k: &str| c[k].as_i64().unwrap() as i32;
let fbsize = [i("w"), i("h")];
let scale = window::calculate_scale(fbsize, i("max"), b(&c["uni"]));
let [gw, gh] = window::gui_scaled_size(fbsize, scale);
writeln!(
out,
"scale {scale} {gw} {gh} {} {}",
dbs(window::scaled_pos(db(&c["x"]), gw, i("sw"))),
dbs(window::scaled_pos(db(&c["y"]), gh, i("sh")))
)?;
Ok(())
}
fn limit(c: &Value, out: &mut impl Write) -> Result<()> {
let ctx = FrameContext {
inactivity: if b(&c["afk"]) {
InactivityFpsLimit::Afk
} else {
InactivityFpsLimit::Minimized
},
iconified: b(&c["iconified"]),
focused: b(&c["focused"]),
exclusive_fullscreen: false,
now_ms: c["ago"].as_i64().unwrap(),
latest_input_ms: 0,
has_level: b(&c["level"]),
has_screen: b(&c["screen"]),
has_overlay: b(&c["overlay"]),
};
let reason = window::throttle_reason(ctx);
let name = match reason {
window::ThrottleReason::None => "NONE",
window::ThrottleReason::WindowIconified => "WINDOW_ICONIFIED",
window::ThrottleReason::LongAfk => "LONG_AFK",
window::ThrottleReason::ShortAfk => "SHORT_AFK",
window::ThrottleReason::OutOfLevelMenu => "OUT_OF_LEVEL_MENU",
};
writeln!(
out,
"limit {name} {} {}",
window::framerate_limit(c["opt"].as_i64().unwrap() as i32, ctx),
window::heavily_throttled(reason)
)?;
Ok(())
}
fn mouse(c: &Value, out: &mut impl Write) -> Result<()> {
let look = LookOptions {
sensitivity: db(&c["sens"]),
smooth_camera: b(&c["smooth"]),
scoping: b(&c["scoping"]),
invert_x: b(&c["ix"]),
invert_y: b(&c["iy"]),
};
let (active, grabbed) = (b(&c["active"]), b(&c["grabbed"]));
let mut handler = MouseLook::default();
let mut rotation = Rotation {
x_rot: 0.0,
y_rot: 0.0,
x_rot_o: 0.0,
y_rot_o: 0.0,
};
writeln!(out, "mouse")?;
for op in c["ops"].as_array().unwrap() {
match op[0].as_str().unwrap() {
"move" => handler.on_move(
db(&op[1]),
db(&op[2]),
db(&op[3]),
db(&op[4]),
active,
grabbed,
),
"ignore" => handler.set_ignore_first_move(),
"frame" => {
if let Some((xo, yo)) =
handler.handle_accumulated_movement(db(&op[1]), active, grabbed, look)
{
rotation.turn(xo, yo);
}
writeln!(
out,
"frame {} {} {} {}",
fb(rotation.x_rot),
fb(rotation.y_rot),
fb(rotation.x_rot_o),
fb(rotation.y_rot_o)
)?;
}
other => panic!("{other}"),
}
}
Ok(())
}
fn scroll(c: &Value, out: &mut impl Write) -> Result<()> {
let mut handler = MouseLook::default();
let mut slot = c["slot"].as_i64().unwrap() as i32;
// OptionInstance.set quantises the wheel sensitivity.
let mut file = OptionsFile::default();
file.set("mouseWheelSensitivity", V::Double(db(&c["sens"])));
let sensitivity = file.double("mouseWheelSensitivity");
writeln!(out, "scroll")?;
for op in c["ops"].as_array().unwrap() {
if let Some((wheel, _)) =
handler.on_scroll(db(&op[0]), db(&op[1]), b(&c["discrete"]), sensitivity)
{
slot = horizon_client::mouse::ScrollWheelHandler::next_selection(
f64::from(wheel),
slot,
9,
);
}
writeln!(out, "{slot}")?;
}
Ok(())
}
fn key(c: &Value, out: &mut impl Write) -> Result<()> {
let mut state = if b(&c["toggle"]) {
KeyState::toggle(b(&c["restore"]), b(&c["keyboard"]))
} else {
KeyState::plain()
};
let mut option = false;
writeln!(out, "key")?;
for op in c["ops"].as_array().unwrap() {
let name = op[0].as_str().unwrap();
let mut result = String::new();
match name {
"option" => option = b(&op[1]),
"down" => state.set_down(b(&op[1]), option),
"release" => state.release(option),
"restore" => {
result = format!(" {}", state.should_restore_state_on_screen_closed(option))
}
"click" => state.click(),
"consume" => result = format!(" {}", state.consume_click()),
"ingame" => result = format!(" {}", state.should_set_on_ingame_focus(option)),
_ => panic!("{name}"),
}
writeln!(out, "{name}{result} {}", state.is_down)?;
}
Ok(())
}
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
let mut out = BufWriter::new(File::create(&args[1])?);
for line in BufReader::new(File::open(&args[0])?).lines() {
let c: Value = serde_json::from_str(&line?)?;
match c["t"].as_str().unwrap() {
"timer" => timer(&c, &mut out)?,
"rate" => rate(&c, &mut out)?,
"scale" => scale(&c, &mut out)?,
"limit" => limit(&c, &mut out)?,
"mouse" => mouse(&c, &mut out)?,
"scroll" => scroll(&c, &mut out)?,
"key" => key(&c, &mut out)?,
other => panic!("{other}"),
}
}
Ok(())
}
@@ -0,0 +1,71 @@
//! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per
//! line (menu, creative, slots, carried, data, ops) and prints the oracle's
//! state lines after every click.
//!
//! usage: menu_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
crafting::Recipes,
item_data::{canon_stack, parse_stack},
items::Items,
menu::{Env, Input, Kind, Menu},
};
use serde_json::Value;
use std::{fs, path::Path};
fn state(menu: &Menu) -> String {
let slots: Vec<String> = (0..menu.slot_count())
.map(|i| canon_stack(menu.slot(i)))
.collect();
let data: String = menu.data.iter().map(|d| format!(" {d}")).collect();
format!(
"{} | {} |{data} | {}",
slots.join(" "),
canon_stack(menu.carried.as_ref()),
menu.drops.join(";")
)
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: menu_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
let env = Env {
items: &items,
recipes: &recipes,
brewing: &brewing,
};
let mut out = String::new();
for line in input.lines() {
let case: Value = serde_json::from_str(line)?;
let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?;
let mut menu = Menu::new(kind);
menu.creative = case["creative"].as_bool().unwrap_or(false);
for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() {
menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?);
}
menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?;
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
}
menu.drops.clear();
out += &format!("init {}\n", state(&menu));
for op in case["ops"].as_array().ok_or("ops")? {
let slot = op[0].as_i64().unwrap_or(0) as i32;
let button = op[1].as_i64().unwrap_or(0) as i32;
let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?;
match menu.click(&env, slot, button, kind) {
Ok(()) => out += &format!("{}\n", state(&menu)),
Err(name) => out += &format!("error {name}\n"),
}
}
out += "end\n";
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -0,0 +1,32 @@
#![forbid(unsafe_code)]
//! Loads and saves option files like `Options.load`/`save`, for the
//! differential harness (tools/test_options_parity.py).
use horizon_client::{Result, keybinds, options_file::OptionsFile};
use std::{fs, io::Write};
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
let mut names: Vec<_> = fs::read_dir(&args[0])?
.map(|e| e.map(|e| e.path()))
.collect::<std::io::Result<_>>()?;
names.sort();
let mut out = fs::File::create(&args[1])?;
let mut first = true;
for path in names {
let name = path.file_name().unwrap().to_string_lossy().into_owned();
let file = if name == "absent.txt" {
OptionsFile::default()
} else {
OptionsFile::parse(&String::from_utf8_lossy(&fs::read(&path)?))
};
write!(out, "== {name}\n{}", file.serialize())?;
if first {
first = false;
writeln!(out, "== keys")?;
for (name, key, category) in keybinds::MAPPINGS {
writeln!(out, "{name} {key} {category} {}", keybinds::is_toggle(name))?;
}
}
}
Ok(())
}
@@ -0,0 +1,91 @@
//! Recipe lookups for tools/test_recipe_parity.py: reads the oracle's
//! tab-separated commands (craft, cook, stonecut, smith) and prints one line
//! per command in the oracle's format.
//!
//! usage: recipe_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
crafting::Recipes,
enchant::Enchantments,
item_data::{canon_stack, parse_stack},
items::Items,
stations::StationRecipes,
};
use std::{fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: recipe_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let stations = StationRecipes::load(root, &items);
let enchantments = Enchantments::load(root);
let mut out = String::new();
for line in input.lines() {
let f: Vec<&str> = line.split('\t').collect();
let stack = |i: usize| parse_stack(f[i]);
let text = match f[0] {
"craft" => {
let n: usize = f[1].parse()?;
let mut grid = Vec::new();
for i in 0..n * n {
grid.push(stack(2 + i)?);
}
match recipes.find(&grid, n) {
None => "none".to_owned(),
Some((id, result)) => {
let rest = recipes.remainders(id, &grid, n);
let rest: Vec<String> = rest
.iter()
.enumerate()
.filter_map(|(i, s)| {
Some(format!("{i}={}", canon_stack(Some(s.as_ref()?))))
})
.collect();
format!("{id}\t{}\t{}", canon_stack(Some(&result)), rest.join(";"))
}
}
}
"cook" => match stack(2)?.and_then(|s| {
recipes
.cook(&format!("minecraft:{}", f[1]), &s)
.map(|c| (c.id.clone(), c.result.clone(), c.experience, c.time))
}) {
None => "none".to_owned(),
Some((id, result, xp, time)) => {
format!("{id}\t{}\t{xp:?}\t{time}", canon_stack(Some(&result)))
}
},
"stonecut" => match stack(1)? {
None => String::new(),
Some(s) => stations
.stonecutter(&s)
.iter()
.map(|r| {
format!(
"{}={}",
r.id.trim_start_matches("minecraft:"),
canon_stack(Some(&r.result))
)
})
.collect::<Vec<_>>()
.join(";"),
},
"smith" => {
let (t, b, a) = (stack(1)?, stack(2)?, stack(3)?);
match stations.smithing_result(&enchantments, t.as_ref(), b.as_ref(), a.as_ref()) {
None => "none".to_owned(),
Some(r) => canon_stack(Some(&r)),
}
}
other => return Err(format!("unknown command {other}").into()),
};
out.push_str(&text);
out.push('\n');
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
@@ -4,12 +4,13 @@
#![forbid(unsafe_code)]
use horizon_client::{
assets::Assets,
biome::{Biomes, GrassModifier},
biome::{BiomeInfo, Biomes, GrassModifier},
blocks::BlockFacts,
chunk::{Chunk, Light, MIN_Y, index},
mesher::{MeshTables, Mesher, Vertex},
mesher::{MeshTables, Mesher, OPAQUE_LAYER, Vertex},
models,
};
use horizon_core::biome::BiomeZoom;
use horizon_world::registry::BlockStateId;
use serde_json::{Value, json};
use std::{
@@ -48,17 +49,23 @@ fn scene(
assets: &Assets,
tables: &MeshTables,
biomes: &mut Biomes,
pristine: &[BiomeInfo],
names: &BTreeMap<u32, &str>,
elapsed: &mut Duration,
) -> Result<Value> {
let colors = &row["colors"];
let color = |k: &str| -> Result<u32> { Ok(int(&colors[k])? as u32 & 0xFF_FFFF) };
for biome in &mut biomes.list {
biome.grass = color("grass")?;
biome.modifier = GrassModifier::None;
biome.foliage = color("foliage")?;
biome.dry_foliage = color("dry_foliage")?;
biome.water = color("water")?;
// Scenes without a biome field give every biome the same constant colours;
// the others use the real biome definitions.
biomes.list = pristine.to_vec();
if row.get("biomes").is_none() {
for biome in &mut biomes.list {
biome.grass = color("grass")?;
biome.modifier = GrassModifier::None;
biome.foliage = color("foliage")?;
biome.dry_foliage = color("dry_foliage")?;
biome.water = color("water")?;
}
}
let default = row["light"].as_array().ok_or("missing default light")?;
let packed = |sky: i32, block: i32| (sky << 4 | block) as u8;
@@ -89,6 +96,31 @@ fn scene(
values[index(x, y, z)] = packed(int(&cell[3])?, int(&cell[4])?);
}
}
let (mut zoom, mut blend_radius) = (BiomeZoom::new(0), 2);
let smooth_lighting = row["smooth"].as_bool().unwrap_or(true);
let cutout_leaves = row["cutout_leaves"].as_bool().unwrap_or(true);
if let Some(field) = row.get("biomes") {
zoom = BiomeZoom::new(field["seed"].as_i64().ok_or("missing biome seed")?);
blend_radius = int(&field["radius"])?;
let default = biomes.id(field["default"].as_str().ok_or("missing default biome")?);
for chunk in &mut chunks {
for qy in 0..96 {
for cell in 0..16 {
chunk.set_biome_cell(cell & 3, qy, cell >> 2, default);
}
}
}
for cell in field["cells"].as_array().ok_or("missing biome cells")? {
let (qx, qy, qz) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?);
let i = chunk_index(qx * 4, qz * 4)?;
chunks[i].set_biome_cell(
qx,
qy - MIN_Y / 4,
qz,
biomes.id(cell[3].as_str().ok_or("biome name")?),
);
}
}
let region: [[Option<&Chunk>; 3]; 3] =
std::array::from_fn(|z| std::array::from_fn(|x| Some(&chunks[z * 3 + x])));
let mut mesher = Mesher {
@@ -97,6 +129,10 @@ fn scene(
tables,
biomes: &*biomes,
visibility: tables.visibility.clone(),
zoom,
blend_radius,
smooth_lighting,
cutout_leaves,
};
let section_y = int(&row["section_y"])?;
let started = Instant::now();
@@ -109,7 +145,9 @@ fn scene(
return Err("partial quad".into());
}
for quad in vertices {
let sprite = names.get(&quad[0].layer).ok_or("unknown sprite layer")?;
let sprite = names
.get(&(quad[0].layer & !OPAQUE_LAYER))
.ok_or("unknown sprite layer")?;
if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) {
return Err("quad mixes sprite layers".into());
}
@@ -150,6 +188,7 @@ fn main() -> Result<()> {
.iter()
.map(|(name, layer)| (*layer, name.as_str()))
.collect();
let pristine = biomes.list.clone();
let mut output = BufWriter::new(fs::File::create(&args[2])?);
if args[1] == "facts" {
// The per-state facts the mesher derives, in the oracle's order and positions.
@@ -175,7 +214,15 @@ fn main() -> Result<()> {
let (mut elapsed, mut sections) = (Duration::ZERO, 0u32);
for line in BufReader::new(fs::File::open(&args[1])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let result = scene(&row, &assets, &tables, &mut biomes, &names, &mut elapsed)?;
let result = scene(
&row,
&assets,
&tables,
&mut biomes,
&pristine,
&names,
&mut elapsed,
)?;
serde_json::to_writer(&mut output, &result)?;
output.write_all(b"\n")?;
sections += 1;
@@ -0,0 +1,269 @@
//! The `minecraft:block_transformer` registry (axe, hoe, shovel) that
//! `BlockTransformer.transformBlock` reads: each transform's rule based state
//! provider is evaluated against the clicked block and the block above.
//! `tools/test_block_transformer_parity.py` compares every block state with
//! vanilla.
use crate::{Result, items::Items};
use horizon_world::{chunk::BlockState, registry::BlockRegistry};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
enum Predicate {
Blocks(Vec<String>),
Tag { tag: String, offset: [i32; 3] },
AllOf(Vec<Predicate>),
AnyOf(Vec<Predicate>),
}
enum Provider {
Rules(Vec<(Predicate, Provider)>),
State(BlockState),
/// `CopyPropertiesProvider`: the source with the clicked block's properties.
Copy(Box<Provider>),
}
/// One `BlockTransformData`.
pub struct Transform {
provider: Provider,
pub disallowed_faces: Vec<String>,
pub sound: String,
pub particle: String,
pub loot: Option<String>,
pub drop_strategy: String,
pub update_from_neighbors: bool,
pub transform_type: String,
pub consume_on_use: bool,
pub damage: u32,
}
pub struct Transformers {
transformers: HashMap<String, Vec<Transform>>,
}
/// What the transformer reads of the world: the block state at an offset from
/// the clicked position.
pub trait Around {
fn state(&self, offset: [i32; 3]) -> BlockState;
}
fn state_of(value: &Value, registry: &BlockRegistry) -> Option<BlockState> {
let name = value["id"].as_str().or_else(|| value["Name"].as_str())?;
let default = registry.default_state(name)?;
let mut state = registry.state(default)?.clone();
for (k, v) in value["properties"].as_object().into_iter().flatten() {
state.properties.insert(k.clone(), v.as_str()?.to_owned());
}
Some(state)
}
fn predicate(value: &Value) -> Option<Predicate> {
Some(match value["type"].as_str()? {
"minecraft:matching_blocks" => Predicate::Blocks(match &value["blocks"] {
Value::String(s) => vec![s.clone()],
Value::Array(a) => a
.iter()
.filter_map(|b| b.as_str().map(str::to_owned))
.collect(),
_ => return None,
}),
"minecraft:matching_block_tag" => {
let o = value["offset"].as_array();
let at = |i: usize| {
o.and_then(|o| o.get(i))
.and_then(Value::as_i64)
.unwrap_or(0) as i32
};
Predicate::Tag {
tag: value["tag"].as_str()?.to_owned(),
offset: [at(0), at(1), at(2)],
}
}
"minecraft:all_of" => Predicate::AllOf(
value["predicates"]
.as_array()?
.iter()
.map(predicate)
.collect::<Option<_>>()?,
),
"minecraft:any_of" => Predicate::AnyOf(
value["predicates"]
.as_array()?
.iter()
.map(predicate)
.collect::<Option<_>>()?,
),
_ => return None,
})
}
fn provider(value: &Value, registry: &BlockRegistry) -> Option<Provider> {
match value["type"].as_str() {
Some("minecraft:rule_based") => {
let mut rules = Vec::new();
for rule in value["rules"].as_array()? {
rules.push((
predicate(&rule["if_true"])?,
provider(&rule["then"], registry)?,
));
}
Some(Provider::Rules(rules))
}
Some("minecraft:copy_properties") => Some(Provider::Copy(Box::new(provider(
&value["source"],
registry,
)?))),
_ => state_of(value, registry).map(Provider::State),
}
}
/// `BlockState.withPropertiesOf`: the properties both blocks have.
fn with_properties_of(
registry: &BlockRegistry,
mut state: BlockState,
old: &BlockState,
) -> Option<BlockState> {
let defaults = registry
.default_state(&state.name)
.and_then(|id| registry.state(id))?;
for (k, v) in &old.properties {
if defaults.properties.contains_key(k) {
let mut candidate = state.clone();
candidate.properties.insert(k.clone(), v.clone());
if registry.resolve(&candidate).is_ok() {
state = candidate;
}
}
}
Some(state)
}
impl Predicate {
fn test(&self, items: &Items, around: &dyn Around) -> bool {
match self {
Self::Blocks(names) => {
let state = around.state([0, 0, 0]);
names.contains(&state.name)
}
Self::Tag { tag, offset } => {
let state = around.state(*offset);
items
.block_tags
.get(tag)
.is_some_and(|members| members.contains(&state.name))
}
Self::AllOf(all) => all.iter().all(|p| p.test(items, around)),
Self::AnyOf(any) => any.iter().any(|p| p.test(items, around)),
}
}
}
impl Provider {
fn state(
&self,
items: &Items,
registry: &BlockRegistry,
around: &dyn Around,
) -> Option<BlockState> {
match self {
Self::Rules(rules) => rules
.iter()
.find(|(p, _)| p.test(items, around))
.and_then(|(_, then)| then.state(items, registry, around)),
Self::State(state) => Some(state.clone()),
Self::Copy(source) => {
let state = source.state(items, registry, around)?;
with_properties_of(registry, state, &around.state([0, 0, 0]))
}
}
}
}
impl Transformers {
/// Reads `data/minecraft/block_transformer/*.json`.
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
let mut transformers = HashMap::new();
let dir = root.join("data/minecraft/block_transformer");
if dir.exists() {
for entry in fs::read_dir(&dir)?.flatten() {
let path = entry.path();
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
let list: Value = serde_json::from_slice(&fs::read(&path)?)?;
let mut transforms = Vec::new();
for t in list.as_array().into_iter().flatten() {
let text = |k: &str, d: &str| t[k].as_str().unwrap_or(d).to_owned();
let Some(provider) = provider(&t["block_state_provider"], registry) else {
continue;
};
transforms.push(Transform {
provider,
disallowed_faces: t["disallowed_faces"]
.as_array()
.into_iter()
.flatten()
.filter_map(|f| f.as_str().map(str::to_owned))
.collect(),
sound: text("sound", "minecraft:empty"),
particle: text("particle", "none"),
loot: t["loot"].as_str().map(str::to_owned),
drop_strategy: text("drop_strategy", "from_middle"),
update_from_neighbors: t["update_from_neighbors"].as_bool().unwrap_or(true),
transform_type: text("transform_type", "single_block"),
consume_on_use: t["consume_on_use"].as_bool().unwrap_or(true),
damage: t["item_damage_per_use"].as_u64().unwrap_or(0) as u32,
});
}
transformers.insert(format!("minecraft:{stem}"), transforms);
}
}
Ok(Self { transformers })
}
/// `BlockTransformer.transformBlock` without the world writes: the first
/// transform that allows the clicked face and provides a state, with its
/// index.
pub fn apply<'a>(
&'a self,
items: &Items,
registry: &BlockRegistry,
id: &str,
face: &str,
around: &dyn Around,
) -> Option<(usize, &'a Transform, BlockState)> {
self.transformers
.get(id)?
.iter()
.enumerate()
.filter(|(_, t)| !t.disallowed_faces.iter().any(|f| f == face))
.find_map(|(i, t)| Some((i, t, t.provider.state(items, registry, around)?)))
}
/// `HoneycombItem.getWaxed`: the waxed twin of a copper block, found from
/// the axe's wax-off transforms (`WAX_OFF_BY_BLOCK` is the inverse of
/// `WAXABLES`).
pub fn waxed(&self, registry: &BlockRegistry, old: &BlockState) -> Option<BlockState> {
for transform in self.transformers.get("minecraft:axe")? {
if transform.particle != "wax_off" {
continue;
}
let Provider::Rules(rules) = &transform.provider else {
continue;
};
for (predicate, then) in rules {
if let (Predicate::Blocks(names), Provider::Copy(source)) = (predicate, then)
&& let Provider::State(unwaxed) = &**source
&& unwaxed.name == old.name
&& let Some(waxed) = names.first()
{
let target = registry
.default_state(waxed)
.and_then(|id| registry.state(id))?
.clone();
return with_properties_of(registry, target, old);
}
}
}
None
}
}
+298
View File
@@ -0,0 +1,298 @@
//! `CauldronInteractions`: what an item does to an empty, water, lava or
//! powder snow cauldron. `tools/test_cauldron_parity.py` compares every item
//! with vanilla's `useItemOn`.
use crate::items::{ItemStack, Items};
/// `ItemTags.CAULDRON_CAN_REMOVE_DYE` membership.
pub fn removes_dye(items: &Items, item: &str) -> bool {
items
.item_tags
.get("minecraft:cauldron_can_remove_dye")
.is_some_and(|members| members.contains(item))
}
use horizon_world::chunk::BlockState;
/// The player side of an interaction.
pub trait Player {
fn creative(&self) -> bool;
/// The stack in the interacting hand.
fn hand(&mut self) -> &mut Option<ItemStack>;
/// `Inventory.add`; the leftover stays in `stack`.
fn add(&mut self, stack: &mut ItemStack) -> bool;
/// `Inventory.contains`.
fn contains(&self, stack: &ItemStack) -> bool;
fn drop_stack(&mut self, stack: ItemStack);
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Outcome {
/// `InteractionResult.SUCCESS`
Success,
/// `InteractionResult.CONSUME`
Consume,
/// `TRY_WITH_EMPTY_HAND`
Pass,
}
#[derive(Debug)]
pub struct Interaction {
pub outcome: Outcome,
/// The cauldron's new state.
pub block: Option<BlockState>,
pub sound: Option<&'static str>,
}
fn state(name: &str, level: Option<u8>) -> BlockState {
BlockState {
name: name.to_owned(),
properties: level
.map(|l| ("level".to_owned(), l.to_string()))
.into_iter()
.collect(),
}
}
fn pass() -> Interaction {
Interaction {
outcome: Outcome::Pass,
block: None,
sound: None,
}
}
/// `ItemUtils.createFilledResult`.
fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) {
let creative = player.creative();
if limit_creative && creative {
if !player.contains(&new) {
let mut new = new;
player.add(&mut new);
}
return;
}
let hand = player.hand();
if !creative && let Some(held) = hand.as_mut() {
held.count -= 1;
if held.count == 0 {
*hand = None;
}
}
if hand.is_none() {
*hand = Some(new);
return;
}
let mut new = new;
if !player.add(&mut new) {
player.drop_stack(new);
}
}
/// `LayeredCauldronBlock.lowerFillLevel`.
fn lowered(cauldron: &BlockState) -> BlockState {
let level: u8 = cauldron
.properties
.get("level")
.and_then(|l| l.parse().ok())
.unwrap_or(1);
if level <= 1 {
state("minecraft:cauldron", None)
} else {
let mut next = cauldron.clone();
next.properties
.insert("level".into(), (level - 1).to_string());
next
}
}
fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction {
Interaction {
outcome: Outcome::Success,
block: Some(block),
sound,
}
}
const COLORS: [&str; 16] = [
"white",
"orange",
"magenta",
"light_blue",
"yellow",
"lime",
"pink",
"gray",
"light_gray",
"cyan",
"purple",
"blue",
"brown",
"green",
"red",
"black",
];
/// The cauldron interaction of the held item (`useItemOn`); the hand stack is
/// changed through `player`. `removes_dye` is whether the held item is in the
/// `cauldron_can_remove_dye` tag.
pub fn interact(
cauldron: &BlockState,
under_water: bool,
removes_dye: bool,
player: &mut dyn Player,
) -> Interaction {
let Some(held) = player.hand().clone() else {
return pass();
};
let kind = match cauldron.name.as_str() {
"minecraft:cauldron" => "empty",
"minecraft:water_cauldron" => "water",
"minecraft:lava_cauldron" => "lava",
"minecraft:powder_snow_cauldron" => "powder_snow",
_ => return pass(),
};
let level: u8 = cauldron
.properties
.get("level")
.and_then(|l| l.parse().ok())
.unwrap_or(0);
let item = &*held.item;
let water_potion = held.data().and_then(|d| d.potion.as_deref()) == Some("minecraft:water");
// Dispatcher.get: tags first, then the item map.
if kind == "water" && removes_dye {
if held.data().and_then(|d| d.dyed_color).is_none() {
return pass();
}
if let Some(stack) = player.hand().as_mut() {
stack.data_mut().dyed_color = None;
stack.tidy();
}
return changed(lowered(cauldron), None);
}
let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| {
if !can_fill {
return pass();
}
filled(player, ItemStack::new(new, 1), true);
changed(state("minecraft:cauldron", None), Some(sound))
};
let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| {
filled(player, ItemStack::new("minecraft:bucket", 1), true);
changed(block, Some(sound))
};
match item {
"minecraft:lava_bucket" => {
return if under_water {
Interaction {
outcome: Outcome::Consume,
block: None,
sound: None,
}
} else {
empty_bucket(
player,
state("minecraft:lava_cauldron", None),
"minecraft:item.bucket.empty_lava",
)
};
}
"minecraft:water_bucket" => {
return empty_bucket(
player,
state("minecraft:water_cauldron", Some(3)),
"minecraft:item.bucket.empty",
);
}
"minecraft:powder_snow_bucket" => {
return if under_water {
Interaction {
outcome: Outcome::Consume,
block: None,
sound: None,
}
} else {
empty_bucket(
player,
state("minecraft:powder_snow_cauldron", Some(3)),
"minecraft:item.bucket.empty_powder_snow",
)
};
}
_ => {}
}
match (kind, item) {
("empty", "minecraft:potion") => {
if !water_potion {
return pass();
}
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
changed(
state("minecraft:water_cauldron", Some(1)),
Some("minecraft:item.bottle.empty"),
)
}
("water", "minecraft:bucket") => fill_bucket(
player,
"minecraft:water_bucket",
level == 3,
"minecraft:item.bucket.fill",
),
("water", "minecraft:glass_bottle") => {
filled(
player,
ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"),
true,
);
changed(lowered(cauldron), Some("minecraft:item.bottle.fill"))
}
("water", "minecraft:potion") => {
if level == 3 || !water_potion {
return pass();
}
filled(player, ItemStack::new("minecraft:glass_bottle", 1), true);
let mut next = cauldron.clone();
// BlockState.cycle on a 1..=3 property
next.properties
.insert("level".into(), (level % 3 + 1).to_string());
changed(next, Some("minecraft:item.bottle.empty"))
}
("water", name)
if name
.strip_prefix("minecraft:")
.and_then(|n| n.strip_suffix("_banner"))
.is_some_and(|c| COLORS.contains(&c)) =>
{
let layers = held.data().map_or(0, |d| d.banner_patterns.len());
if layers == 0 {
return pass();
}
let mut cleaned = held.clone();
cleaned.count = 1;
cleaned.data_mut().banner_patterns.pop();
cleaned.tidy();
filled(player, cleaned, false);
changed(lowered(cauldron), None)
}
("water", name)
if name
.strip_prefix("minecraft:")
.and_then(|n| n.strip_suffix("_shulker_box"))
.is_some_and(|c| COLORS.contains(&c)) =>
{
filled(player, held.transmute("minecraft:shulker_box", 1), false);
changed(lowered(cauldron), None)
}
("lava", "minecraft:bucket") => fill_bucket(
player,
"minecraft:lava_bucket",
true,
"minecraft:item.bucket.fill_lava",
),
("powder_snow", "minecraft:bucket") => fill_bucket(
player,
"minecraft:powder_snow_bucket",
level == 3,
"minecraft:item.bucket.fill_powder_snow",
),
_ => pass(),
}
}
+60 -35
View File
@@ -1,6 +1,7 @@
//! Resident client chunk storage. Sections are reference-counted so worker
//! threads can mesh and light immutable snapshots while the game thread edits
//! (copy-on-write through `Arc::make_mut`).
use horizon_core::paletted::{PalettedContainer, Strategy};
use horizon_world::registry::BlockStateId;
use std::sync::Arc;
@@ -8,11 +9,11 @@ pub const MIN_Y: i32 = -64;
pub const HEIGHT: i32 = 384;
pub const SECTIONS: usize = (HEIGHT / 16) as usize;
#[derive(Clone)]
pub enum Blocks {
Uniform(u16),
Full(Box<[u16; 4096]>),
}
/// Block states are `PalettedContainer`s over the pinned registry (35,723
/// states: a 16-bit global palette); biomes are 4x4x4 containers over the
/// biome table (67 entries: a 7-bit global palette).
pub const BLOCK_STRATEGY: Strategy = Strategy::blocks(16);
pub const BIOME_STRATEGY: Strategy = Strategy::biomes(7);
/// Packed light per block: sky light in the high nibble, block light in the low one.
#[derive(Clone)]
pub enum Light {
@@ -25,13 +26,16 @@ pub fn index(x: i32, y: i32, z: i32) -> usize {
}
#[derive(Clone)]
pub struct Section {
pub blocks: Blocks,
pub blocks: PalettedContainer,
/// Biome table index per 4x4x4 cell, `(y << 2 | z) << 2 | x`.
pub biomes: PalettedContainer,
pub light: Light,
}
impl Default for Section {
fn default() -> Self {
Self {
blocks: Blocks::Uniform(0),
blocks: PalettedContainer::new(BLOCK_STRATEGY, 0),
biomes: PalettedContainer::new(BIOME_STRATEGY, 0),
light: Light::Uniform(0xF0),
}
}
@@ -39,23 +43,19 @@ impl Default for Section {
impl Section {
#[inline]
pub fn get(&self, i: usize) -> u16 {
match &self.blocks {
Blocks::Uniform(v) => *v,
Blocks::Full(a) => a[i],
}
self.blocks.get(i) as u16
}
pub fn set(&mut self, i: usize, v: u16) -> u16 {
match &mut self.blocks {
Blocks::Uniform(u) if *u == v => v,
Blocks::Uniform(u) => {
let old = *u;
let mut a = Box::new([old; 4096]);
a[i] = v;
self.blocks = Blocks::Full(a);
old
}
Blocks::Full(a) => std::mem::replace(&mut a[i], v),
}
self.blocks.set(i, u32::from(v)) as u16
}
/// All 4,096 block states in index order.
pub fn unpack(&self, out: &mut [u16; 4096]) {
self.blocks.unpack_u16(out);
}
/// The block states of a whole section at once.
pub fn from_blocks(values: &[u16; 4096]) -> PalettedContainer {
let wide: Vec<u32> = values.iter().map(|&v| u32::from(v)).collect();
PalettedContainer::from_values(BLOCK_STRATEGY, &wide)
}
#[inline]
pub fn light(&self, i: usize) -> u8 {
@@ -65,17 +65,26 @@ impl Section {
}
}
pub fn is_uniform(&self, v: u16) -> bool {
match &self.blocks {
Blocks::Uniform(u) => *u == v,
Blocks::Full(a) => a.iter().all(|&b| b == v),
}
self.blocks.is_uniform(u32::from(v))
}
/// Collapse storage that became uniform.
/// Heap bytes held by the block, biome and light storage (benchmark accounting).
pub fn heap_bytes(&self) -> usize {
self.blocks.heap_bytes()
+ self.biomes.heap_bytes()
+ match &self.light {
Light::Uniform(_) => 0,
Light::Full(_) => 4096,
}
}
/// Collapse storage that became uniform, and drop palette entries no
/// block uses any more.
pub fn compact(&mut self) {
if let Blocks::Full(a) = &self.blocks
&& a.iter().all(|&b| b == a[0])
{
self.blocks = Blocks::Uniform(a[0]);
for container in [&mut self.blocks, &mut self.biomes] {
if container.bits() != 0
&& let Some(v) = container.uniform()
{
*container = PalettedContainer::new(container.strategy(), v);
}
}
if let Light::Full(a) = &self.light
&& a.iter().all(|&b| b == a[0])
@@ -89,8 +98,6 @@ pub struct Chunk {
pub x: i32,
pub z: i32,
pub sections: Vec<Arc<Section>>,
/// Biome index per 4x4x4 cell (x,z in 0..4, y in 0..96) into `Biomes`.
pub biomes: Arc<Vec<u16>>,
/// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky.
pub heights: Arc<[i16; 256]>,
pub lit: bool,
@@ -100,6 +107,8 @@ pub struct Chunk {
pub fresh: bool,
/// Block entities read from a save, moved into the world on arrival.
pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>,
/// `CustomName` of the container block entities (shown as the screen title).
pub block_names: Vec<((i32, i32, i32), String)>,
/// Generation postprocessing marks (ProtoChunk.postProcessing) as world
/// positions, applied once by LevelChunk.postProcessGeneration.
pub postprocess: Vec<[i32; 3]>,
@@ -119,12 +128,12 @@ impl Chunk {
sections: (0..SECTIONS)
.map(|_| Arc::new(Section::default()))
.collect(),
biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]),
heights: Arc::new([MIN_Y as i16; 256]),
lit: false,
light_loaded: false,
fresh: false,
block_entities: Vec::new(),
block_names: Vec::new(),
structure_refs: Vec::new(),
postprocess: Vec::new(),
saved: None,
@@ -161,9 +170,25 @@ impl Chunk {
}
self.sections[s as usize].light(index(x, y, z))
}
/// Heap bytes held by the sections (benchmark accounting).
pub fn heap_bytes(&self) -> usize {
self.sections.iter().map(|s| s.heap_bytes()).sum::<usize>()
}
/// Biome table index at a block position (`ChunkAccess.getNoiseBiome` with
/// the quart y clamped to the column).
#[inline]
pub fn biome(&self, x: i32, y: i32, z: i32) -> u16 {
let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1);
self.biomes[(qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize]
self.sections[(qy >> 2) as usize]
.biomes
.get(((qy & 3) << 4 | ((z & 15) >> 2) << 2 | (x & 15) >> 2) as usize) as u16
}
/// Sets the biome of one quart cell (`qy` counts from the column's bottom).
pub fn set_biome_cell(&mut self, qx: i32, qy: i32, qz: i32, biome: u16) {
let section = Arc::make_mut(&mut self.sections[(qy >> 2) as usize]);
section.biomes.set(
((qy & 3) << 4 | (qz & 3) << 2 | (qx & 3)) as usize,
u32::from(biome),
);
}
}
+422 -145
View File
@@ -1,134 +1,445 @@
//! Fixed-rate development simulation driver. Rendering consumes elapsed time;
//! a per-frame work cap retains its backlog instead of dropping simulation time.
//! The rate, freezing, stepping and sprinting are what `/tick` controls
//! (`ServerTickRateManager`).
use std::time::Duration;
//! `DeltaTracker.Timer` and the tick-rate managers of 26.3: how real
//! milliseconds turn into game ticks, partial ticks and real-time deltas, and
//! the `/tick` freeze, step and sprint state.
pub const TICK: Duration = Duration::from_millis(50);
/// Ticks one sprint frame may run.
const SPRINT_PER_FRAME: u32 = 40;
/// `DeltaTracker.Timer`: float arithmetic on integer milliseconds, exactly as
/// the client does it.
#[derive(Clone, Debug)]
pub struct Timer {
delta_ticks: f32,
delta_tick_residual: f32,
realtime_delta_ticks: f32,
paused_delta_tick_residual: f32,
last_ms: i64,
last_ui_ms: i64,
ms_per_tick: f32,
paused: bool,
frozen: bool,
}
impl Timer {
pub fn new(ticks_per_second: f32, current_ms: i64) -> Self {
Self {
delta_ticks: 0.0,
delta_tick_residual: 0.0,
realtime_delta_ticks: 0.0,
paused_delta_tick_residual: 0.0,
last_ms: current_ms,
last_ui_ms: current_ms,
ms_per_tick: 1000.0 / ticks_per_second,
paused: false,
frozen: false,
}
}
/// `advanceGameTime`: the whole ticks to run now. `target_mspt` maps the
/// default milliseconds per tick to the target in force (the tick-rate
/// manager's, when the level runs normally). The caller runs at most ten.
pub fn advance_game_time(
&mut self,
current_ms: i64,
target_mspt: impl FnOnce(f32) -> f32,
) -> i32 {
self.delta_ticks = (current_ms - self.last_ms) as f32 / target_mspt(self.ms_per_tick);
self.last_ms = current_ms;
self.delta_tick_residual += self.delta_ticks;
let ticks = self.delta_tick_residual as i32;
self.delta_tick_residual -= ticks as f32;
ticks
}
/// `advanceRealTime`.
pub fn advance_real_time(&mut self, current_ms: i64) {
self.realtime_delta_ticks = (current_ms - self.last_ui_ms) as f32 / self.ms_per_tick;
self.last_ui_ms = current_ms;
}
/// `updatePauseState`.
pub fn update_pause_state(&mut self, pause: bool) {
if pause {
if !self.paused {
self.paused_delta_tick_residual = self.delta_tick_residual;
}
self.paused = true;
} else {
if self.paused {
self.delta_tick_residual = self.paused_delta_tick_residual;
}
self.paused = false;
}
}
/// `updateFrozenState`.
pub fn update_frozen_state(&mut self, frozen: bool) {
self.frozen = frozen;
}
pub fn game_time_delta_ticks(&self) -> f32 {
self.delta_ticks
}
/// `getGameTimeDeltaPartialTick`.
pub fn game_time_delta_partial_tick(&self, ignore_frozen_game: bool) -> f32 {
if !ignore_frozen_game && self.frozen {
1.0
} else if self.paused {
self.paused_delta_tick_residual
} else {
self.delta_tick_residual
}
}
/// `getRealtimeDeltaTicks`.
pub fn realtime_delta_ticks(&self) -> f32 {
if self.realtime_delta_ticks > 7.0 {
0.5
} else {
self.realtime_delta_ticks
}
}
}
const NANOSECONDS_PER_SECOND: i64 = 1_000_000_000;
const NANOSECONDS_PER_MILLISECOND: i64 = 1_000_000;
/// `TickRateManager`.
#[derive(Clone, Debug)]
pub struct TickRateManager {
tickrate: f32,
nanoseconds_per_tick: i64,
frozen_ticks_to_run: i32,
run_game_elements: bool,
is_frozen: bool,
}
impl Default for TickRateManager {
fn default() -> Self {
Self {
tickrate: 20.0,
nanoseconds_per_tick: NANOSECONDS_PER_SECOND / 20,
frozen_ticks_to_run: 0,
run_game_elements: true,
is_frozen: false,
}
}
}
impl TickRateManager {
/// `setTickRate` (`Math.max(rate, 1.0F)`, NaN propagates).
pub fn set_tick_rate(&mut self, rate: f32) {
self.tickrate = if rate.is_nan() || rate > 1.0 {
rate
} else {
1.0
};
self.nanoseconds_per_tick =
(NANOSECONDS_PER_SECOND as f64 / f64::from(self.tickrate)) as i64;
}
pub fn tickrate(&self) -> f32 {
self.tickrate
}
pub fn milliseconds_per_tick(&self) -> f32 {
self.nanoseconds_per_tick as f32 / NANOSECONDS_PER_MILLISECOND as f32
}
pub fn nanoseconds_per_tick(&self) -> i64 {
self.nanoseconds_per_tick
}
pub fn runs_normally(&self) -> bool {
self.run_game_elements
}
pub fn is_stepping_forward(&self) -> bool {
self.frozen_ticks_to_run > 0
}
pub fn set_frozen_ticks_to_run(&mut self, ticks: i32) {
self.frozen_ticks_to_run = ticks;
}
pub fn frozen_ticks_to_run(&self) -> i32 {
self.frozen_ticks_to_run
}
pub fn set_frozen(&mut self, frozen: bool) {
self.is_frozen = frozen;
}
pub fn is_frozen(&self) -> bool {
self.is_frozen
}
/// `tick`: decides whether game elements run this tick.
pub fn tick(&mut self) {
self.run_game_elements = !self.is_frozen || self.frozen_ticks_to_run > 0;
if self.frozen_ticks_to_run > 0 {
self.frozen_ticks_to_run -= 1;
}
}
/// `isEntityFrozen` for an entity that is not (and does not carry) a player.
pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool {
!self.runs_normally() && !is_player_or_carries_player
}
}
/// What `/tick sprint` reports when it ends.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SprintReport {
pub ticks_per_second: i32,
pub milliseconds_per_tick: String,
}
/// `ServerTickRateManager`: the freeze, step and sprint state kept by the
/// server (the broadcasts to clients are the caller's concern).
#[derive(Clone, Debug, Default)]
pub struct ServerTickRateManager {
pub base: TickRateManager,
remaining_sprint_ticks: i64,
sprint_tick_start_time: i64,
sprint_time_spend: i64,
scheduled_current_sprint_ticks: i64,
previous_is_frozen: bool,
}
impl ServerTickRateManager {
pub fn is_sprinting(&self) -> bool {
self.scheduled_current_sprint_ticks > 0
}
pub fn remaining_sprint_ticks(&self) -> i64 {
self.remaining_sprint_ticks
}
/// `stepGameIfPaused`.
pub fn step_game_if_paused(&mut self, ticks: i32) -> bool {
if !self.base.is_frozen() {
return false;
}
self.base.set_frozen_ticks_to_run(ticks);
true
}
/// `stopStepping`.
pub fn stop_stepping(&mut self) -> bool {
if self.base.frozen_ticks_to_run() > 0 {
self.base.set_frozen_ticks_to_run(0);
true
} else {
false
}
}
/// `stopSprinting`.
pub fn stop_sprinting(&mut self) -> Option<SprintReport> {
if self.remaining_sprint_ticks > 0 {
Some(self.finish_tick_sprint())
} else {
None
}
}
/// `requestGameToSprint`: true when an earlier sprint was interrupted.
pub fn request_game_to_sprint(&mut self, time: i32) -> bool {
let interrupted = self.remaining_sprint_ticks > 0;
self.sprint_time_spend = 0;
self.scheduled_current_sprint_ticks = i64::from(time);
self.remaining_sprint_ticks = i64::from(time);
self.previous_is_frozen = self.base.is_frozen();
self.base.set_frozen(false);
interrupted
}
fn finish_tick_sprint(&mut self) -> SprintReport {
let completed_ticks = self.scheduled_current_sprint_ticks - self.remaining_sprint_ticks;
let milliseconds_to_complete =
(self.sprint_time_spend.max(1)) as f64 / NANOSECONDS_PER_MILLISECOND as f64;
let ticks_per_second = (1000.0 * completed_ticks as f64 / milliseconds_to_complete) as i32;
let per_tick = if completed_ticks == 0 {
f64::from(self.base.milliseconds_per_tick())
} else {
milliseconds_to_complete / completed_ticks as f64
};
self.scheduled_current_sprint_ticks = 0;
self.sprint_time_spend = 0;
self.remaining_sprint_ticks = 0;
self.base.set_frozen(self.previous_is_frozen);
SprintReport {
ticks_per_second,
milliseconds_per_tick: crate::java_text::format_fixed2(per_tick),
}
}
/// `checkShouldSprintThisTick`: whether to run this tick without waiting,
/// plus the report when the sprint just finished.
pub fn check_should_sprint_this_tick(&mut self, now_ns: i64) -> (bool, Option<SprintReport>) {
if !self.base.run_game_elements {
(false, None)
} else if self.remaining_sprint_ticks > 0 {
self.sprint_tick_start_time = now_ns;
self.remaining_sprint_ticks -= 1;
(true, None)
} else {
(false, Some(self.finish_tick_sprint()))
}
}
/// `endTickWork`.
pub fn end_tick_work(&mut self, now_ns: i64) {
self.sprint_time_spend += now_ns - self.sprint_tick_start_time;
}
/// `setTickRate`.
pub fn set_tick_rate(&mut self, rate: f32) {
self.base.set_tick_rate(rate);
}
}
/// Ticks one sprint frame may run (rendering carries on between frames).
const SPRINT_PER_FRAME: i64 = 40;
const SAMPLES: usize = 100;
/// The game's clock: `DeltaTracker.Timer` pacing driven by the
/// `ServerTickRateManager` the `/tick` command controls, over a virtual
/// millisecond clock built from the frame times it is fed. The integrated
/// simulation is one loop, so the tick rate paces it directly (the vanilla
/// client timer only ever slows down, because its server ticks separately).
#[derive(Clone, Debug)]
pub struct FixedStep {
pending: Duration,
/// Ticks per second (`tickrate`).
rate: f32,
frozen: bool,
/// Ticks the frozen world still runs (`/tick step`).
step: u32,
/// Ticks left in a sprint.
sprint: u32,
/// How long recent ticks took (nanoseconds), newest last.
samples: Vec<u64>,
timer: Timer,
manager: ServerTickRateManager,
now: std::time::Duration,
pause: bool,
sprint_checked: bool,
sprint_report: Option<SprintReport>,
tick_times: [i64; SAMPLES],
aggregated: i64,
tick_count: i64,
}
impl Default for FixedStep {
fn default() -> Self {
Self {
pending: Duration::ZERO,
rate: 20.0,
frozen: false,
step: 0,
sprint: 0,
samples: Vec::new(),
timer: Timer::new(20.0, 0),
manager: ServerTickRateManager::default(),
now: std::time::Duration::ZERO,
pause: false,
sprint_checked: false,
sprint_report: None,
tick_times: [0; SAMPLES],
aggregated: 0,
tick_count: 0,
}
}
}
impl FixedStep {
fn now_ms(&self) -> i64 {
self.now.as_millis() as i64
}
fn now_ns(&self) -> i64 {
self.now.as_nanos() as i64
}
/// The length of one tick at the current rate.
pub fn tick_duration(&self) -> Duration {
Duration::from_secs_f64(1.0 / f64::from(self.rate.max(0.01)))
pub fn tick_duration(&self) -> std::time::Duration {
std::time::Duration::from_nanos(self.manager.base.nanoseconds_per_tick().max(1) as u64)
}
pub fn advance(&mut self, elapsed: Duration) -> u32 {
if self.sprint > 0 {
let n = self.sprint.min(SPRINT_PER_FRAME);
self.sprint -= n;
self.pending = Duration::ZERO;
return n;
/// Feed one frame's elapsed time; returns the ticks to run (at most ten,
/// or a sprint frame's worth).
pub fn advance(&mut self, elapsed: std::time::Duration) -> u32 {
self.now += elapsed;
let now_ms = self.now_ms();
if self.manager.is_sprinting() {
// Keep the timer current so leaving the sprint does not replay it.
self.timer.advance_game_time(now_ms, |d| d);
let remaining = self.manager.remaining_sprint_ticks();
// One extra pass lets the sprint finish and report.
return (remaining + 1).min(SPRINT_PER_FRAME) as u32;
}
self.pending += elapsed;
let tick = self.tick_duration();
let steps = (self.pending.as_nanos() / tick.as_nanos().max(1)).min(10) as u32;
self.pending -= tick * steps;
steps
let runs = self.manager.base.runs_normally();
let mspt = self.manager.base.milliseconds_per_tick();
let ticks = self
.timer
.advance_game_time(now_ms, |default| if runs { mspt } else { default });
ticks.clamp(0, 10) as u32
}
/// Restart pacing from now (after loading, so no backlog replays).
pub fn reset(&mut self) {
self.pending = Duration::ZERO;
self.timer = Timer::new(20.0, self.now_ms());
self.timer.update_pause_state(self.pause);
}
/// The partial tick for interpolation (`getGameTimeDeltaPartialTick(false)`).
pub fn fraction(&self) -> f64 {
(self.pending.as_secs_f64() / self.tick_duration().as_secs_f64()).min(1.0)
f64::from(self.timer.game_time_delta_partial_tick(false))
}
/// Whether the world ticks this time (`ServerTickRateManager.runsNormally`
/// or a pending step); called once per tick.
/// After a frame: whether the game is paused by a screen (the residual
/// stops accumulating) and whether the level is frozen.
pub fn end_frame(&mut self, pause: bool) {
self.pause = pause;
self.timer.update_pause_state(pause);
self.timer
.update_frozen_state(!self.manager.base.runs_normally());
}
pub fn paused(&self) -> bool {
self.pause
}
/// `TickRateManager.tick` for one tick, then whether the world runs
/// (`runsNormally`). Also the sprint check that opens a sprint tick.
pub fn world_runs(&mut self) -> bool {
if !self.frozen {
return true;
self.manager.base.tick();
self.sprint_checked = false;
if self.manager.is_sprinting() {
let (_, report) = self.manager.check_should_sprint_this_tick(self.now_ns());
self.sprint_checked = report.is_none();
if report.is_some() {
self.sprint_report = report;
}
}
if self.step > 0 {
self.step -= 1;
return true;
}
false
self.manager.base.runs_normally()
}
/// The report of a sprint that just finished, once.
pub fn take_sprint_report(&mut self) -> Option<SprintReport> {
self.sprint_report.take()
}
pub fn rate(&self) -> f32 {
self.rate
self.manager.base.tickrate()
}
pub fn set_rate(&mut self, rate: f32) {
self.rate = rate.clamp(1.0, 10000.0);
self.manager.set_tick_rate(rate);
}
pub fn frozen(&self) -> bool {
self.frozen
self.manager.base.is_frozen()
}
pub fn set_frozen(&mut self, frozen: bool) {
self.frozen = frozen;
if !frozen {
self.step = 0;
}
self.manager.base.set_frozen(frozen);
}
pub fn sprinting(&self) -> bool {
self.sprint > 0
self.manager.is_sprinting()
}
/// `requestGameToSprint`: true when a sprint was already running.
pub fn start_sprint(&mut self, ticks: u32) -> bool {
let was = self.sprint > 0;
self.sprint = ticks;
was
self.manager
.request_game_to_sprint(ticks.min(i32::MAX as u32) as i32)
}
pub fn stop_sprint(&mut self) -> bool {
let was = self.sprint > 0;
self.sprint = 0;
was
/// `stopSprinting`: the report when a sprint was running.
pub fn stop_sprint(&mut self) -> Option<SprintReport> {
self.manager.stop_sprinting()
}
pub fn stepping(&self) -> bool {
self.step > 0
self.manager.base.is_stepping_forward()
}
/// `stepGameIfPaused`: only works while frozen.
pub fn start_step(&mut self, ticks: u32) -> bool {
if !self.frozen {
return false;
}
self.step = ticks;
true
self.manager
.step_game_if_paused(ticks.min(i32::MAX as u32) as i32)
}
pub fn stop_step(&mut self) -> bool {
let was = self.step > 0;
self.step = 0;
was
self.manager.stop_stepping()
}
pub fn record(&mut self, took: Duration) {
if self.samples.len() == SAMPLES {
self.samples.remove(0);
/// Record how long a tick took (`MinecraftServer.tickServer` bookkeeping
/// and `endTickWork`).
pub fn record(&mut self, took: std::time::Duration) {
let took = took.as_nanos() as i64;
let index = (self.tick_count % SAMPLES as i64) as usize;
self.aggregated -= self.tick_times[index];
self.aggregated += took;
self.tick_times[index] = took;
self.tick_count += 1;
if self.sprint_checked {
let end = self.now_ns() + took;
self.manager.end_tick_work(end);
}
self.samples.push(took.as_nanos() as u64);
}
/// `getAverageTickTimeNanos`.
pub fn average_nanos(&self) -> u64 {
if self.samples.is_empty() {
return 0;
}
self.samples.iter().sum::<u64>() / self.samples.len() as u64
(self.aggregated / SAMPLES.min(self.tick_count.max(1) as usize) as i64).max(0) as u64
}
/// The sorted tick times (p50, p95, p99 inputs) and their count.
/// The sorted `getTickTimesNanos` array (always 100 entries).
pub fn sorted_samples(&self) -> Vec<u64> {
let mut v = self.samples.clone();
let mut v: Vec<u64> = self.tick_times.iter().map(|&t| t.max(0) as u64).collect();
v.sort_unstable();
v
}
@@ -137,70 +448,36 @@ impl FixedStep {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_schedules_preserve_ticks_and_stall_backlog() {
for schedule in [&[7, 13, 18, 12][..], &[50][..], &[1, 999, 2700, 300][..]] {
let mut clock = FixedStep::default();
let mut elapsed = Duration::ZERO;
let mut ticks = 0;
for _ in 0..100 {
for &ms in schedule {
let frame = Duration::from_millis(ms);
elapsed += frame;
let count = clock.advance(frame);
assert!(count <= 10);
ticks += count;
}
}
loop {
let count = clock.advance(Duration::ZERO);
ticks += count;
if count == 0 {
break;
}
}
assert_eq!(u128::from(ticks), elapsed.as_nanos() / TICK.as_nanos());
fn timer_carries_fractions_and_caps_nothing_itself() {
let mut t = Timer::new(20.0, 0);
assert_eq!(t.advance_game_time(49, |d| d), 0);
assert_eq!(t.advance_game_time(50, |d| d), 1);
assert_eq!(t.advance_game_time(1050, |d| d), 20);
}
#[test]
fn pause_restores_the_residual() {
let mut t = Timer::new(20.0, 0);
t.advance_game_time(25, |d| d);
t.update_pause_state(true);
t.advance_game_time(1000, |d| d);
assert_eq!(t.game_time_delta_partial_tick(false), 0.5);
t.update_pause_state(false);
assert_eq!(t.game_time_delta_partial_tick(false), 0.5);
}
#[test]
fn frozen_step_runs_exactly_the_requested_ticks() {
let mut m = ServerTickRateManager::default();
m.base.set_frozen(true);
m.base.tick();
assert!(!m.base.runs_normally());
assert!(m.step_game_if_paused(2));
for _ in 0..2 {
m.base.tick();
assert!(m.base.runs_normally());
}
}
#[test]
fn pause_discards_only_explicitly_reset_time() {
let mut clock = FixedStep::default();
assert_eq!(clock.advance(Duration::from_millis(49)), 0);
assert_eq!(clock.advance(Duration::from_millis(1)), 1);
assert_eq!(clock.advance(Duration::from_millis(24)), 0);
clock.reset();
assert_eq!(clock.advance(Duration::from_millis(26)), 0);
assert_eq!(clock.advance(Duration::from_millis(24)), 1);
}
#[test]
fn rate_changes_the_tick_length() {
let mut clock = FixedStep::default();
clock.set_rate(40.0);
assert_eq!(clock.advance(Duration::from_millis(100)), 4);
clock.set_rate(5.0);
assert_eq!(clock.advance(Duration::from_millis(400)), 2);
clock.set_rate(1.0e9);
assert_eq!(clock.rate(), 10000.0);
}
#[test]
fn freeze_step_and_sprint() {
let mut clock = FixedStep::default();
assert!(clock.world_runs());
assert!(!clock.start_step(3), "stepping needs a frozen game");
clock.set_frozen(true);
assert!(!clock.world_runs());
assert!(clock.start_step(2));
assert!(clock.world_runs() && clock.world_runs() && !clock.world_runs());
assert!(clock.start_step(5) && clock.stop_step() && !clock.stop_step());
clock.set_frozen(false);
assert!(!clock.start_sprint(100));
assert!(clock.sprinting());
assert_eq!(clock.advance(Duration::ZERO), SPRINT_PER_FRAME);
assert!(clock.stop_sprint() && !clock.sprinting());
for ns in [3, 1, 2] {
clock.record(Duration::from_nanos(ns));
}
assert_eq!(clock.average_nanos(), 2);
assert_eq!(clock.sorted_samples(), vec![1, 2, 3]);
m.base.tick();
assert!(!m.base.runs_normally());
}
}
File diff suppressed because it is too large Load Diff
+17 -13
View File
@@ -239,11 +239,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&"Items".into());
}
let mut equipment = Vec::new();
if m.extra.saddled {
equipment.push((
"saddle",
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
));
if let Some(saddle) = m.saddle_item() {
equipment.push(("saddle", crate::save::item_to_nbt(&saddle)));
}
if let Some(armor) = &m.extra.head {
equipment.push((
@@ -273,11 +270,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
};
if m.extra.saddled {
equipment.insert(
"saddle".into(),
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
);
if let Some(saddle) = m.saddle_item() {
equipment.insert("saddle".into(), crate::save::item_to_nbt(&saddle));
} else {
equipment.remove(&"saddle".into());
}
@@ -571,8 +565,15 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.species(),
crate::mobs::Species::Pig | crate::mobs::Species::Strider
) {
m.extra.saddled =
tag.get("equipment").and_then(|e| e.get("saddle")).is_some() || flag(tag, "Saddle");
let saddle = tag
.get("equipment")
.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt);
if saddle.is_some() || flag(tag, "Saddle") {
m.set_saddle(Some(saddle.unwrap_or_else(|| {
crate::items::ItemStack::new("minecraft:saddle", 1)
})));
}
}
if crate::mobs::equine::is_equine(m.species()) {
m.extra.tame = flag(tag, "Tame");
@@ -589,7 +590,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.items = crate::save::decode_items(tag.get("Items"), 15);
}
let eq = tag.get("equipment");
m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some();
m.set_saddle(
eq.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt),
);
m.extra.head = eq
.and_then(|e| e.get("body"))
.and_then(|b| text(b.get("id")))
File diff suppressed because it is too large Load Diff
@@ -1,11 +1,15 @@
//! `/random` (RandomCommand) and `/teammsg` (TeamMsgCommand).
use super::{Arg, Context, Game, R, Target, err};
use crate::game::chat::PLAYER_NAME;
use horizon_client::text::{self, Text};
use horizon_client::{
clock::SprintReport,
java_text::format_fixed,
text::{self, Text},
};
use horizon_core::random::RandomSource;
fn millis(nanos: u64) -> String {
format!("{:.1}", nanos as f32 / 1_000_000.0)
format_fixed(f64::from(nanos as f32 / 1_000_000.0), 1)
}
impl Game<'_> {
@@ -79,14 +83,14 @@ impl Game<'_> {
self.clock.set_rate(rate);
self.feedback(t(
"commands.tick.rate.success",
&[lit(format!("{rate:.1}"))],
&[lit(format_fixed(f64::from(rate), 1))],
));
Ok(rate as i32)
}
"tick.query" => {
let rate = self.clock.rate();
let busy = millis(self.clock.average_nanos());
let rate_text = format!("{rate:.1}");
let rate_text = format_fixed(f64::from(rate), 1);
if self.clock.sprinting() {
self.feedback(t("commands.tick.status.sprinting", &[]));
self.feedback(t(
@@ -137,16 +141,19 @@ impl Game<'_> {
Ok(1)
}
"tick.sprint.stop" => {
if !self.clock.stop_sprint() {
let Some(report) = self.clock.stop_sprint() else {
return Err(err("commands.tick.sprint.stop.fail", &[]));
}
};
self.sprint_report(&report);
self.feedback(t("commands.tick.sprint.stop.success", &[]));
Ok(1)
}
"tick.freeze" | "tick.unfreeze" => {
let freeze = id == "tick.freeze";
if freeze {
self.clock.stop_sprint();
if let Some(report) = self.clock.stop_sprint() {
self.sprint_report(&report);
}
self.clock.stop_step();
}
self.clock.set_frozen(freeze);
@@ -176,6 +183,16 @@ impl Game<'_> {
}
}
}
/// The report `/tick sprint` prints when a sprint ends.
pub(in crate::game) fn sprint_report(&mut self, report: &SprintReport) {
self.feedback(Text::translate(
"commands.tick.sprint.report",
&[
Text::literal(report.ticks_per_second.to_string()),
Text::literal(report.milliseconds_per_tick.clone()),
],
));
}
pub(super) fn cmd_random(&mut self, id: &str, ctx: &Context) -> R<i32> {
let seed = self.level.seed;
if id == "random.reset" {
@@ -214,10 +214,9 @@ impl Game<'_> {
continue;
}
let qy = ((y - MIN_Y) >> 2).clamp(0, HEIGHT / 4 - 1);
let index = (qy * 16 + ((z & 15) >> 2) * 4 + ((x & 15) >> 2)) as usize;
if let Some(chunk) = self.world.chunks.get_mut(&key) {
let chunk = std::sync::Arc::make_mut(chunk);
std::sync::Arc::make_mut(&mut chunk.biomes)[index] = target as u16;
chunk.set_biome_cell((x & 15) >> 2, qy, (z & 15) >> 2, target as u16);
}
touched.insert(key);
changed += 1;
+7 -2
View File
@@ -466,6 +466,11 @@ impl Game<'_> {
block_tags: &self.res.items.block_tags,
biomes: &self.res.biomes,
mob_griefing: self.ui.rules.bool("mob_griefing"),
difficulty: self.local_difficulty(
self.player
.as_ref()
.map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]),
),
}
}
/// `ServerLevel.getCurrentDifficultyAt`.
@@ -777,8 +782,8 @@ impl Game<'_> {
}
// Saddles, horse armour and chests always drop.
let mut gear: Vec<&str> = Vec::new();
if m.extra.saddled {
gear.push("minecraft:saddle");
if let Some(saddle) = m.saddle_item() {
self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10);
}
// WitherBoss.dropCustomDeathLoot.
if m.species() == Species::Wither {
+2 -1
View File
@@ -578,7 +578,7 @@ impl Game<'_> {
(_, Some(1)) => m.extra.chest = Some(item.clone()),
(_, Some(2)) => m.extra.legs = Some(item.clone()),
(_, Some(3)) => m.extra.feet = Some(item.clone()),
("saddle", _) => m.extra.saddled = true,
("saddle", _) => m.set_saddle(Some(one.clone())),
_ => m.extra.head = Some(item.clone()),
}
// setGuaranteedDrop / setPersistenceRequired.
@@ -1155,6 +1155,7 @@ impl Game<'_> {
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
self.world.block_entities.insert(target, entity);
self.fill_placed_box([target.0, target.1, target.2], &stack);
self.name_placed_container([target.0, target.1, target.2], &stack);
}
let sounds = self.res.facts.get(state).sounds.clone();
self.audio.play(
+7 -2
View File
@@ -933,9 +933,14 @@ impl Game<'_> {
};
let mut found = Vec::new();
for (s, section) in chunk.sections.iter().enumerate() {
let horizon_client::chunk::Blocks::Full(blocks) = &section.blocks else {
if !section
.blocks
.maybe_has(|v| v == u32::from(portal) || v == u32::from(gateway))
{
continue;
};
}
let mut blocks = Box::new([0u16; 4096]);
section.unpack(&mut blocks);
for (i, &b) in blocks.iter().enumerate() {
if b == portal || b == gateway {
let y = horizon_client::chunk::MIN_Y + s as i32 * 16 + (i >> 8) as i32;
+1
View File
@@ -79,6 +79,7 @@ impl Game<'_> {
let ally = matches!(
m.species(),
Species::Evoker
| Species::Illusioner
| Species::Vex
| Species::Pillager
| Species::Vindicator
@@ -746,6 +746,7 @@ impl Game<'_> {
batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX);
}
let grey = horizon_client::hud::rgba(64, 64, 64, 255);
let title = &self.container_title(title.to_owned());
let title_x = if screen == Screen::Hopper {
8.0
} else {
@@ -125,7 +125,7 @@ impl Game<'_> {
true,
horizon_world::level::flags::UPDATE_CLIENTS,
);
let remainders = self.res.recipes.remainders(&self.res.items, &grid, &result);
let remainders = self.res.recipes.remainders(&recipe, &grid, 3);
self.crafter_eject(key, facing, result, &recipe);
for rest in remainders.into_iter().flatten() {
self.crafter_eject(key, facing, rest, &recipe);
@@ -270,7 +270,7 @@ impl Game<'_> {
256.0,
);
let grey = rgba(64, 64, 64, 255);
let title = self.translate("container.crafter", "Crafter");
let title = self.container_title(self.translate("container.crafter", "Crafter"));
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+4 -7
View File
@@ -67,10 +67,7 @@ impl Game<'_> {
mob: m.id,
species,
columns,
saddle: m
.extra
.saddled
.then(|| ItemStack::new("minecraft:saddle", 1)),
saddle: m.saddle_item(),
armor: m
.extra
.head
@@ -137,18 +134,18 @@ impl Game<'_> {
let Some(index) = self.mount_mob_index(open.mob) else {
return;
};
let (saddle, armor) = (open.saddle.is_some(), open.armor.clone());
let (saddle, armor) = (open.saddle.clone(), open.armor.clone());
let items = open.items.clone();
let m = &mut self.mobs[index];
let at = m.center();
let sound = if saddle && !m.extra.saddled {
let sound = if saddle.is_some() && !m.extra.saddled {
Some("minecraft:entity.horse.saddle")
} else if armor.is_some() && m.extra.head.is_none() {
Some("minecraft:entity.horse.armor")
} else {
None
};
m.extra.saddled = saddle;
m.set_saddle(saddle);
if open.show_armor {
m.extra.head = armor.map(|a| a.item);
}
+4 -2
View File
@@ -45,13 +45,14 @@ impl Game<'_> {
}
/// `Pig` / `Strider.mobInteract`: saddle an adult, or ride a saddled one.
fn interact_steerable(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &mut self.mobs[index];
if m.is_baby() || !m.alive() || Some(m.id) == self.riding {
return false;
}
let at = m.center();
if item == "minecraft:saddle" && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
let sound = if m.species() == Species::Strider {
"minecraft:entity.strider.saddle"
} else {
@@ -98,6 +99,7 @@ impl Game<'_> {
}
/// `AbstractHorse.mobInteract`. Returns whether the click was used.
pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &self.mobs[index];
let species = m.species();
if matches!(species, Species::Pig | Species::Strider) {
@@ -131,7 +133,7 @@ impl Game<'_> {
let at = m.center();
let tamed = m.extra.tame;
let sound = if item == "minecraft:saddle" && tamed && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
Some("minecraft:entity.horse.saddle")
} else if item.ends_with("_horse_armor")
&& species == Species::Horse
+25 -7
View File
@@ -6,6 +6,7 @@ use horizon_client::{
hud::HudBatch,
lang,
options_ui::{Event, Page},
window::{FrameContext, InactivityFpsLimit, framerate_limit},
};
use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen};
@@ -177,16 +178,33 @@ impl Game<'_> {
}
/// Frame limiter for the Max Framerate option: when the next frame is due.
pub(super) fn next_frame_due(&self) -> Option<std::time::Instant> {
let fps = self.settings.max_fps;
if fps >= 260 || self.options.frames.is_some() {
if self.options.frames.is_some() {
return None;
}
// Menus without a world run at 60 fps like vanilla's title screen.
let fps = if self.title.is_some() {
fps.min(60)
} else {
fps
// FramerateLimitTracker.getFramerateLimit: the option, throttled when
// minimised, idle, or in a menu without a world.
let context = FrameContext {
inactivity: if self.settings.inactivity_fps_limit == "minimized" {
InactivityFpsLimit::Minimized
} else {
InactivityFpsLimit::Afk
},
iconified: self
.window
.as_ref()
.is_some_and(|w| w.is_minimized().unwrap_or(false)),
focused: self.focused,
exclusive_fullscreen: false,
now_ms: self.started.elapsed().as_millis() as i64,
latest_input_ms: self.last_input.duration_since(self.started).as_millis() as i64,
has_level: self.title.is_none(),
has_screen: self.title.is_some() || self.screen != super::Screen::Playing,
has_overlay: false,
};
let fps = framerate_limit(self.settings.max_fps as i32, context);
if fps >= 260 {
return None;
}
let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps));
(due > std::time::Instant::now()).then_some(due)
}
+98 -10
View File
@@ -68,6 +68,9 @@ pub(super) struct RecipeUi {
overlay: Option<Overlay>,
view: View,
view_key: u64,
/// Squeeze animations of new recipes: ticks left per button index and tab.
button_anim: Vec<(usize, f32)>,
tab_anim: Vec<(Tab, f32)>,
}
impl RecipeUi {
@@ -179,6 +182,11 @@ impl Game<'_> {
return;
}
self.ensure_book();
for id in recipes {
if !self.level.recipe_book.to_be_displayed.contains(id) {
self.level.recipe_book.to_be_displayed.push(id.clone());
}
}
let icon = self
.recipe_ui
.book
@@ -291,6 +299,71 @@ impl Game<'_> {
if self.recipe_ui.page >= pages.max(1) {
self.recipe_ui.page = 0;
}
self.start_new_recipe_animations(book_type);
}
/// `RecipeBookTabButton.startAnimation` and `RecipeButton.init`: tabs
/// holding a recipe still to be displayed squeeze, and the buttons of the
/// shown page squeeze once and clear their recipes' highlight.
fn start_new_recipe_animations(&mut self, book_type: BookType) {
if self.level.recipe_book.to_be_displayed.is_empty() {
return;
}
let Some(book) = self.recipe_ui.book.take() else {
return;
};
let unlocked = self.unlocked_recipes();
let filtering = self.book_filtering(book_type);
let (gw, gh) = self.book_grid();
let available = self.book_available(book_type);
let shown = |e: &Entry| {
(book_type != BookType::Crafting || e.fits(gw, gh))
&& (!filtering || available.can_craft(&e.requirements()))
};
let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id);
let mut tabs = Vec::new();
for tab in self.recipe_ui.view.tabs.clone() {
if tab == Tab::Search {
continue;
}
let hit = book
.collections(&unlocked, book_type, tab)
.iter()
.flat_map(|c| c.entries.iter())
.any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i]));
if hit {
tabs.push((tab, 15.0));
}
}
self.recipe_ui.tab_anim = tabs;
let first = self.recipe_ui.page * 20;
let mut buttons = Vec::new();
let mut cleared = Vec::new();
for (n, button) in self
.recipe_ui
.view
.buttons
.iter()
.skip(first)
.take(20)
.enumerate()
{
let ids: Vec<&String> = button
.entries
.iter()
.map(|e| &book.entries[e.0].id)
.filter(|id| self.level.recipe_book.to_be_displayed.contains(*id))
.collect();
if !ids.is_empty() {
buttons.push((first + n, 15.0));
cleared.extend(ids.into_iter().cloned());
}
}
self.level
.recipe_book
.to_be_displayed
.retain(|id| !cleared.contains(id));
self.recipe_ui.button_anim = buttons;
self.recipe_ui.book = Some(book);
}
fn build_view(&mut self, ui: &RecipeUi, book_type: BookType) -> View {
let Some(book) = ui.book.as_ref() else {
@@ -329,9 +402,8 @@ impl Game<'_> {
continue;
}
if !query.is_empty()
&& !c.entries.iter().any(|&i| {
let e = &book.entries[i];
book.matches_search(e, &query, &self.res.names.item(&e.result.item))
&& !book.collection_matches(&c.entries, &query, &|stack| {
self.stack_tooltip(stack).into_iter().map(|l| l.0).collect()
})
{
continue;
@@ -972,26 +1044,30 @@ impl Game<'_> {
.tab
.filter(|t| tabs.contains(t))
.unwrap_or(Tab::Search);
let mut tab_icons = Vec::new();
let frame = self.frame_ticks;
for (n, tab) in tabs.iter().enumerate() {
let (x, y) = self.tab_pos(xo, yo, n);
let selected = *tab == current;
let name = if selected { "tab_selected" } else { "tab" };
let sx = if selected { x - 2.0 } else { x };
let start = batch.vertices.len();
batch.sprite(&self.res.atlas, &sprite(name), sx, y);
let (a, b) = tab.icons();
let shift = if selected { -2.0 } else { 0.0 };
match b {
Some(b) => {
tab_icons.push((a, x + 3.0 + shift, y + 5.0));
tab_icons.push((b, x + 14.0 + shift, y + 5.0));
self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0);
self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0);
}
None => tab_icons.push((a, x + 9.0 + shift, y + 5.0)),
None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0),
}
if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) {
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze);
entry.1 -= frame;
}
}
for (item, x, y) in tab_icons {
self.draw_item(batch, &ItemStack::new(item, 1), x, y);
}
self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0);
// Craftable filter.
let filtering = self.book_filtering(book_type);
let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0);
@@ -1019,6 +1095,7 @@ impl Game<'_> {
break;
};
let (x, y) = Self::button_pos(xo, yo, n);
let anim_start = batch.vertices.len();
let many = button.entries.len() > 1;
let name = match (button.craftable(), many) {
(true, true) => "slot_many_craftable",
@@ -1048,6 +1125,16 @@ impl Game<'_> {
offset -= 1.0;
}
self.draw_item_plain(batch, &stack, x + offset, y + offset);
if let Some(entry) = self
.recipe_ui
.button_anim
.iter_mut()
.find(|e| e.0 == first + n)
{
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze);
entry.1 -= self.frame_ticks;
}
if inside(cursor, x, y, 25.0, 25.0) && !overlay_open {
let mut lines = self.stack_tooltip(&stack);
if many {
@@ -1059,6 +1146,7 @@ impl Game<'_> {
tooltip = Some(lines);
}
}
self.recipe_ui.button_anim.retain(|e| e.1 > 0.0);
// Page arrows and number.
if pages > 1 {
let page_text = self
+38 -35
View File
@@ -9,7 +9,7 @@
use super::{Dim, Game, Mining, Screen};
use horizon_client::{
Result,
chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section},
chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section},
containers::{BlockEntity, Furnace, FurnaceKind},
entities::{Experience, ItemEntity},
hud::{HudBatch, rgba},
@@ -22,7 +22,7 @@ use horizon_client::{
streaming::{ChunkGenerator, Proto, Streaming},
world::World,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_core::{geometry::Vec3, paletted::PalettedContainer, random::RandomSource};
use horizon_protocol::{
entity_data::{ITEM_ENTITY_ITEM, Value},
item::{Hashed, Stack},
@@ -420,6 +420,8 @@ impl Game<'_> {
.is_none_or(|r| r.dimension.has_skylight);
self.streaming.sky_light = has_sky;
self.streaming.nether_shading = self.dim == Dim::Nether;
// The seed in SpawnInfo is already the hashed one the client's BiomeManager holds.
self.streaming.biome_zoom = horizon_core::biome::BiomeZoom::new(spawn.seed);
self.player = None;
self.apply_settings();
}
@@ -432,54 +434,55 @@ impl Game<'_> {
.sections(r.dimension.sections(), 16, r.biome_bits)
.map_err(|e| e.to_string())?;
let mut chunk = Chunk::empty(p.x, p.z);
let mut biomes = vec![0u16; chunk.biomes.len()];
let offset = (r.dimension.min_y - MIN_Y).div_euclid(16);
// Biome table index per quart cell of the dimension's own sections.
let mut biome_cells: Vec<[u32; 64]> = Vec::with_capacity(sections.len());
for (i, s) in sections.iter().enumerate() {
let target = offset + i as i32;
let mut cells = [0u32; 64];
for (j, cell) in cells.iter_mut().enumerate() {
*cell = u32::from(
r.biome_map
.get(s.biomes.get(j) as usize)
.copied()
.unwrap_or(0),
);
}
biome_cells.push(cells);
if !(0..SECTIONS as i32).contains(&target) {
continue;
}
let blocks = if s.states.bits == 0 {
Blocks::Uniform(s.states.get(0) as u16)
} else {
let mut a = Box::new([0u16; 4096]);
for (j, v) in a.iter_mut().enumerate() {
*v = s.states.get(j) as u16;
}
Blocks::Full(a)
};
let strategy = BLOCK_STRATEGY;
let palette = s.states.palette.iter().map(|&p| p as u32).collect();
let words = s.states.data.iter().map(|&w| w as u64).collect();
let blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words)
.map_err(|e| e.to_string())?;
let mut section = Section {
blocks,
biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells),
light: Light::Uniform(0xF0),
};
section.compact();
chunk.sections[target as usize] = Arc::new(section);
for j in 0..64 {
let biome = r
.biome_map
.get(s.biomes.get(j) as usize)
.copied()
.unwrap_or(0);
if let Some(cell) = biomes.get_mut(target as usize * 64 + j) {
*cell = biome;
}
// Sections outside the dimension's range take its nearest biomes
// (the column's top or bottom cell layer repeated).
if !biome_cells.is_empty() {
let last = biome_cells.len() - 1;
for si in 0..SECTIONS as i32 {
let i = si - offset;
if (0..sections.len() as i32).contains(&i) {
continue;
}
let (edge, layer) = if i < 0 { (0, 0) } else { (last, 3) };
let mut cells = [0u32; 64];
for (j, cell) in cells.iter_mut().enumerate() {
*cell = biome_cells[edge][layer * 16 + j % 16];
}
Arc::make_mut(&mut chunk.sections[si as usize]).biomes =
PalettedContainer::from_values(BIOME_STRATEGY, &cells);
}
}
// Columns outside the dimension's range take its nearest biome.
let (lo, hi) = (
offset.max(0) as usize * 64,
((offset + sections.len() as i32).min(SECTIONS as i32)) as usize * 64,
);
if lo < hi {
for j in 0..biomes.len() {
if j < lo {
biomes[j] = biomes[lo + j % 16];
} else if j >= hi {
biomes[j] = biomes[hi - 16 + j % 16];
}
}
}
chunk.biomes = Arc::new(biomes);
Ok(chunk)
}
/// Keep the renderable block entities (chests, furnaces) in step with blocks.
+16 -18
View File
@@ -336,30 +336,28 @@ impl Game<'_> {
}
}
fn sculk_scan_chunk(&mut self, key: (i32, i32)) {
use horizon_client::chunk::{Blocks, MIN_Y};
use horizon_client::chunk::MIN_Y;
let Some(chunk) = self.world.chunks.get(&key).cloned() else {
return;
};
let mut found = Vec::new();
for (s, section) in chunk.sections.iter().enumerate() {
let y0 = MIN_Y + s as i32 * 16;
match &section.blocks {
Blocks::Uniform(v) => {
// A uniform section of sculk blocks does not exist.
let _ = v;
}
Blocks::Full(a) => {
for (i, v) in a.iter().enumerate() {
if self.kind_of_state(*v) != 0 {
let (x, z, y) = (i & 15, (i >> 4) & 15, i >> 8);
found.push((
key.0 * 16 + x as i32,
y0 + y as i32,
key.1 * 16 + z as i32,
*v,
));
}
}
if section.blocks.uniform().is_some() {
// A uniform section of sculk blocks does not exist.
continue;
}
let mut a = [0u16; 4096];
section.unpack(&mut a);
for (i, v) in a.iter().enumerate() {
if self.kind_of_state(*v) != 0 {
let (x, z, y) = (i & 15, (i >> 4) & 15, i >> 8);
found.push((
key.0 * 16 + x as i32,
y0 + y as i32,
key.1 * 16 + z as i32,
*v,
));
}
}
}
+7 -1
View File
@@ -1305,7 +1305,13 @@ impl Game<'_> {
);
}
}
let title = self.translate("container.brewing", "Brewing Stand");
let default = self.translate("container.brewing", "Brewing Stand");
let title = self
.station
.as_ref()
.and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2])))
.cloned()
.unwrap_or(default);
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+44 -66
View File
@@ -11,6 +11,14 @@ impl Game<'_> {
/// Block-entity contents on removal: shulker boxes keep theirs for the
/// dropped box (`copy_components`), other containers spill them.
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
if let Some(name) = self
.world
.block_names
.remove(&(pos[0], pos[1], pos[2]))
.filter(|_| !matches!(entity, BlockEntity::Banner(_)))
{
self.pending_names.insert(pos, (block.to_owned(), name));
}
if let BlockEntity::Banner(banner) = entity {
self.pending_banner.insert(pos, banner);
return;
@@ -41,6 +49,38 @@ impl Game<'_> {
stack.data_mut().container = contents;
}
}
/// The custom name a broken container drops with (`copy_components`).
pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
if self
.pending_names
.get(&pos)
.is_some_and(|(item, _)| **item == *stack.item)
&& let Some((_, name)) = self.pending_names.remove(&pos)
{
stack.data_mut().custom_name = Some(name);
}
}
/// A placed container takes the item's custom name.
pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) {
let key = (pos[0], pos[1], pos[2]);
if let Some(name) = stack.custom_name()
&& !matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Banner(_) | BlockEntity::Sign(_))
)
{
self.world.block_names.insert(key, name.to_owned());
}
}
/// The custom name of the open container, or its default title
/// (a double chest is named by whichever half has a name).
pub(super) fn container_title(&self, default: String) -> String {
self.container_parts()
.iter()
.find_map(|(key, _)| self.world.block_names.get(key))
.cloned()
.unwrap_or(default)
}
/// A placed shulker box takes the item's contents.
pub(super) fn fill_placed_box(&mut self, pos: [i32; 3], stack: &ItemStack) {
let Some(data) = stack.data() else { return };
@@ -234,7 +274,7 @@ impl Game<'_> {
_ if rows > 3 => ("container.chestDouble", "Large Chest"),
_ => ("container.chest", "Chest"),
};
self.translate(key, fallback)
self.container_title(self.translate(key, fallback))
}
/// `ContainerScreen` / `ShulkerBoxScreen`: the background with its
/// container rows, the title and the inventory label.
@@ -302,72 +342,10 @@ impl Game<'_> {
impl Game<'_> {
/// `quickMoveStack` of the open chest-like, hopper, dispenser or furnace
/// menu for a shift-click on `slot`; false when the menu has none.
/// menu for a shift-click on `slot`, run by the verified menu engine
/// (`horizon_client::menu`); false when the menu has none.
pub(super) fn container_quick_move(&mut self, slot: usize) -> bool {
let size = self.container_size();
let furnace = match self.container_kind() {
Some(BlockEntity::Chest(_)) => None,
Some(BlockEntity::Furnace(f)) => Some(f.kind),
_ => return false,
};
if slot >= 300 + size.max(3) {
return false;
}
let Some(mut stack) = self.slot_mut(slot).take() else {
return true;
};
let player: Vec<usize> = (9..36).chain(0..9).collect();
let hotbar_or_main = |slot: usize| -> Vec<usize> {
if slot < 9 {
(9..36).collect()
} else {
(0..9).collect()
}
};
match furnace {
None => {
if slot >= 300 {
self.move_to(&mut stack, &player, true);
} else {
let targets: Vec<usize> = (300..300 + size).collect();
self.move_to(&mut stack, &targets, false);
}
}
Some(kind) => {
// AbstractFurnaceMenu.quickMoveStack.
if slot >= 300 {
self.move_to(&mut stack, &player, slot == 302);
} else {
let smeltable = self.res.recipes.cook(kind.recipe_type(), &stack).is_some();
let fuel = self
.res
.items
.get(&stack.item)
.is_some_and(|i| i.fuel.is_some());
let moved = if smeltable {
self.move_to(&mut stack, &[300], false)
} else if fuel {
self.move_to(&mut stack, &[301], false)
} else {
false
};
if !moved && !smeltable && !fuel {
let other = hotbar_or_main(slot);
self.move_to(&mut stack, &other, false);
}
if let Some(BlockEntity::Furnace(f)) = self
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
f.cooking_timer = 0;
}
}
}
}
if stack.count > 0 {
*self.slot_mut(slot) = Some(stack);
}
true
self.menu_click(Some(slot), 0, horizon_client::menu::Input::QuickMove)
}
}
+15 -10
View File
@@ -919,16 +919,21 @@ impl Renderer {
}
/// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available.
pub fn set_vsync(&mut self, vsync: bool) {
let has = |m| self.present_modes.contains(&m);
let mode = match (
vsync,
has(wgpu::PresentMode::Mailbox),
has(wgpu::PresentMode::Immediate),
) {
(true, true, _) => wgpu::PresentMode::Mailbox,
(true, false, _) => wgpu::PresentMode::Fifo,
(false, _, true) => wgpu::PresentMode::Immediate,
(false, true, false) => wgpu::PresentMode::Mailbox,
use crate::window::{PresentMode, vsync_present_mode};
let supported: Vec<PresentMode> = self
.present_modes
.iter()
.filter_map(|m| match m {
wgpu::PresentMode::Fifo => Some(PresentMode::Fifo),
wgpu::PresentMode::Mailbox => Some(PresentMode::Mailbox),
wgpu::PresentMode::Immediate => Some(PresentMode::Immediate),
_ => None,
})
.collect();
// GpuSurface.PresentMode.getSupportedVsyncMode.
let mode = match vsync_present_mode(&supported, vsync) {
Some(PresentMode::Mailbox) => wgpu::PresentMode::Mailbox,
Some(PresentMode::Immediate) => wgpu::PresentMode::Immediate,
_ => wgpu::PresentMode::Fifo,
};
if self.config.present_mode != mode {
+8
View File
@@ -278,6 +278,14 @@ impl HudBatch {
/// Clip the quads drawn since `start` to `[x0, x1) x [y0, y1)` (the
/// GUI scissor): axis-aligned quads are cut with their UVs, others are
/// kept or dropped by their centre.
/// Scale the vertices pushed since `start` about `(cx, cy)` (a GUI pose
/// matrix of translate, scale, translate back).
pub fn scale_since(&mut self, start: usize, cx: f32, cy: f32, sx: f32, sy: f32) {
for v in &mut self.vertices[start..] {
v.pos[0] = cx + (v.pos[0] - cx) * sx;
v.pos[1] = cy + (v.pos[1] - cy) * sy;
}
}
pub fn clip_since(&mut self, start: usize, x0: f32, y0: f32, x1: f32, y1: f32) {
let quads: Vec<[HudVertex; 6]> = self.vertices[start..].as_chunks::<6>().0.to_vec();
self.vertices.truncate(start);
+279 -67
View File
@@ -44,6 +44,18 @@ pub struct StackData {
pub ominous_banner: bool,
/// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0).
pub ominous_amplifier: Option<u8>,
/// `minecraft:dyed_color` (leather armour, wolf armour, ... as RGB).
pub dyed_color: Option<i32>,
/// `minecraft:firework_explosion` (a firework star).
pub firework_explosion: Option<crate::particles::FireworkExplosion>,
/// `minecraft:pot_decorations`: back, left, right, front sherds.
pub pot_decorations: Option<Box<[Option<ItemStack>; 4]>>,
/// `minecraft:bundle_contents`.
pub bundle_contents: Vec<ItemStack>,
/// `minecraft:suspicious_stew_effects`: (effect id, duration).
pub stew_effects: Vec<(Arc<str>, i32)>,
/// `minecraft:map_post_processing`: 0 lock, 1 scale.
pub map_post_processing: Option<u8>,
}
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
@@ -243,6 +255,151 @@ fn read_text(t: &Tag) -> Option<String> {
}
}
/// A `FireworkExplosion` as vanilla's codec writes it (defaults omitted).
fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag {
let colors = |c: &[u32]| Tag::List(c.iter().map(|c| Tag::Int(*c as i32)).collect());
let mut fields = vec![("shape", Tag::String(e.shape.name().into()))];
if !e.colors.is_empty() {
fields.push(("colors", colors(&e.colors)));
}
if !e.fade.is_empty() {
fields.push(("fade_colors", colors(&e.fade)));
}
if e.trail {
fields.push(("has_trail", Tag::Byte(1)));
}
if e.twinkle {
fields.push(("has_twinkle", Tag::Byte(1)));
}
Tag::compound(fields)
}
fn explosion_from(e: &Tag) -> crate::particles::FireworkExplosion {
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
Some(Tag::List(v)) => v.iter().filter_map(int).map(|c| c as u32).collect(),
_ => Vec::new(),
};
crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.map_or("small_ball", |s| s.strip_prefix("minecraft:").unwrap_or(s)),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
}
}
/// An `ItemStackTemplate`: `{id, count?, components?}`.
fn template_tag(stack: &ItemStack) -> Tag {
let mut entries = vec![("id", Tag::String((&*stack.item).into()))];
if stack.count != 1 {
entries.push(("count", Tag::Int(stack.count as i32)));
}
if let Some(components) = encode_components(stack) {
entries.push(("components", components));
}
Tag::compound(entries)
}
/// The pot prototype's decorations: a brick on every side.
pub fn all_bricks(sides: &[Option<ItemStack>; 4]) -> bool {
sides.iter().all(|s| {
s.as_ref()
.is_some_and(|s| &*s.item == "minecraft:brick" && s.count == 1 && s.extra.is_none())
})
}
fn template_from(tag: &Tag) -> Option<ItemStack> {
match tag {
Tag::String(id) => Some(ItemStack::new(&id.to_string_lossy(), 1)),
_ => {
let id = tag.get("id").and_then(string)?;
let (damage, extra) = decode_components(tag.get("components"));
Some(ItemStack {
item: Arc::from(id.as_str()),
count: tag.get("count").and_then(int).unwrap_or(1).max(1) as u32,
damage,
extra,
})
}
}
}
/// Sorted-key, type-annotated text of a tag (the differential harnesses
/// print the same form from the vanilla side).
pub fn canon_tag(tag: &Tag) -> String {
fn list(out: &mut String, prefix: &str, items: impl Iterator<Item = String>) {
out.push_str(prefix);
out.push_str(&items.collect::<Vec<_>>().join(","));
out.push(']');
}
fn go(tag: &Tag, out: &mut String) {
use std::fmt::Write as _;
match tag {
Tag::End => {}
Tag::Byte(v) => write!(out, "{v}b").unwrap(),
Tag::Short(v) => write!(out, "{v}s").unwrap(),
Tag::Int(v) => write!(out, "{v}").unwrap(),
Tag::Long(v) => write!(out, "{v}L").unwrap(),
Tag::Float(v) => write!(out, "{}f", f32::from_bits(*v)).unwrap(),
Tag::Double(v) => write!(out, "{}d", f64::from_bits(*v)).unwrap(),
Tag::String(s) => write!(
out,
"\"{}\"",
s.to_string_lossy()
.replace('\\', "\\\\")
.replace('"', "\\\"")
)
.unwrap(),
Tag::ByteArray(v) => list(out, "[B;", v.iter().map(|b| (*b as i8).to_string())),
Tag::IntArray(v) => list(out, "[I;", v.iter().map(i32::to_string)),
Tag::LongArray(v) => list(out, "[L;", v.iter().map(i64::to_string)),
Tag::List(items) => {
out.push('[');
for (i, t) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
go(t, out);
}
out.push(']');
}
Tag::Compound(map) => {
let mut keys: Vec<(String, &Tag)> =
map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
out.push('{');
for (i, (k, v)) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&k);
out.push(':');
go(v, out);
}
out.push('}');
}
}
}
let mut out = String::new();
go(tag, &mut out);
out
}
/// `canon_tag` of a stack as `ItemStack.CODEC` writes it; "-" for none.
pub fn canon_stack(stack: Option<&ItemStack>) -> String {
stack.map_or_else(
|| "-".to_owned(),
|s| canon_tag(&crate::save::item_to_nbt(s)),
)
}
/// The stack of an SNBT `ItemStack.CODEC` compound; None for "-".
pub fn parse_stack(snbt: &str) -> Result<Option<ItemStack>, String> {
if snbt == "-" {
return Ok(None);
}
let (tag, _) = horizon_world::nbt::parse_snbt(snbt)?;
Ok(crate::save::item_from_nbt(&tag))
}
/// The `components` compound for a stack, or None when every component is default.
pub fn encode_components(stack: &ItemStack) -> Option<Tag> {
components_tag(stack.damage, stack.data())
@@ -317,40 +474,73 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.collect();
entries.push((
"minecraft:written_book_content",
Tag::compound([
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("generation", Tag::Int(i32::from(w.generation))),
("pages", Tag::List(pages)),
("resolved", Tag::Byte(1)),
]),
Tag::compound({
let mut fields = vec![
("title", raw(Tag::String(w.title.as_str().into()))),
("author", Tag::String(w.author.as_str().into())),
("pages", Tag::List(pages)),
];
if w.generation != 0 {
fields.push(("generation", Tag::Int(i32::from(w.generation))));
}
fields
}),
));
}
if let Some((flight, explosions)) = &d.fireworks {
let list = explosions
.iter()
.map(|e| {
Tag::compound([
("shape", Tag::String(e.shape.name().into())),
(
"colors",
Tag::IntArray(e.colors.iter().map(|c| *c as i32).collect()),
),
(
"fade_colors",
Tag::IntArray(e.fade.iter().map(|c| *c as i32).collect()),
),
("has_trail", Tag::Byte(i8::from(e.trail))),
("has_twinkle", Tag::Byte(i8::from(e.twinkle))),
])
})
.collect();
let mut fields = Vec::new();
if *flight != 0 {
fields.push(("flight_duration", Tag::Byte(*flight as i8)));
}
if !explosions.is_empty() {
fields.push((
"explosions",
Tag::List(explosions.iter().map(explosion_tag).collect()),
));
}
entries.push(("minecraft:fireworks", Tag::compound(fields)));
}
if let Some(e) = &d.firework_explosion {
entries.push(("minecraft:firework_explosion", explosion_tag(e)));
}
if let Some(color) = d.dyed_color {
entries.push(("minecraft:dyed_color", Tag::Int(color)));
}
if let Some(sides) = &d.pot_decorations {
let mut sherds = Vec::new();
for (name, side) in ["back", "left", "right", "front"].iter().zip(sides.iter()) {
if let Some(stack) = side {
sherds.push((*name, template_tag(stack)));
}
}
entries.push(("minecraft:pot_decorations", Tag::compound(sherds)));
}
if !d.bundle_contents.is_empty() {
entries.push((
"minecraft:fireworks",
Tag::compound([
("flight_duration", Tag::Byte(*flight as i8)),
("explosions", Tag::List(list)),
]),
"minecraft:bundle_contents",
Tag::List(d.bundle_contents.iter().map(template_tag).collect()),
));
}
if !d.stew_effects.is_empty() {
entries.push((
"minecraft:suspicious_stew_effects",
Tag::List(
d.stew_effects
.iter()
.map(|(id, duration)| {
Tag::compound([
("id", Tag::String((&**id).into())),
("duration", Tag::Int(*duration)),
])
})
.collect(),
),
));
}
if let Some(mode) = d.map_post_processing {
entries.push((
"minecraft:map_post_processing",
Tag::String(if mode == 0 { "lock" } else { "scale" }.into()),
));
}
if !d.charged.is_empty() {
@@ -399,7 +589,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
.map(|(slot, stack)| {
Tag::compound([
("slot", Tag::Int(i32::from(*slot))),
("item", crate::save::item_to_nbt(stack)),
("item", template_tag(stack)),
])
})
.collect();
@@ -456,36 +646,54 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
_ => Vec::new(),
},
}),
fireworks: c.get("minecraft:fireworks").map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let ints = |t: Option<&Tag>| match t {
Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(),
_ => Vec::new(),
};
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list
.iter()
.map(|e| crate::particles::FireworkExplosion {
shape: crate::particles::FireworkShape::from_name(
e.get("shape")
.and_then(string)
.as_deref()
.unwrap_or("small_ball"),
),
colors: ints(e.get("colors")),
fade: ints(e.get("fade_colors")),
trail: e.get("has_trail").and_then(int).unwrap_or(0) != 0,
twinkle: e.get("has_twinkle").and_then(int).unwrap_or(0) != 0,
})
.collect(),
_ => Vec::new(),
};
(flight, explosions)
}),
fireworks: c
.get("minecraft:fireworks")
.map(|f| {
let flight = f
.get("flight_duration")
.and_then(int)
.unwrap_or(0)
.clamp(0, 255) as u8;
let explosions = match f.get("explosions") {
Some(Tag::List(list)) => list.iter().map(explosion_from).collect(),
_ => Vec::new(),
};
(flight, explosions)
})
.filter(|(flight, explosions)| !(*flight == 1 && explosions.is_empty())),
firework_explosion: c.get("minecraft:firework_explosion").map(explosion_from),
dyed_color: c
.get("minecraft:dyed_color")
.and_then(int)
.map(|v| v as i32),
pot_decorations: c
.get("minecraft:pot_decorations")
.map(|p| {
let side = |name: &str| p.get(name).and_then(template_from);
Box::new([side("back"), side("left"), side("right"), side("front")])
})
.filter(|sides| !all_bricks(sides)),
bundle_contents: match c.get("minecraft:bundle_contents") {
Some(Tag::List(list)) => list.iter().filter_map(template_from).collect(),
_ => Vec::new(),
},
stew_effects: match c.get("minecraft:suspicious_stew_effects") {
Some(Tag::List(list)) => list
.iter()
.filter_map(|e| {
Some((
Arc::from(e.get("id").and_then(string)?.as_str()),
e.get("duration").and_then(int).unwrap_or(160) as i32,
))
})
.collect(),
_ => Vec::new(),
},
map_post_processing: match c.get("minecraft:map_post_processing") {
Some(Tag::String(s)) => Some(u8::from(s.to_string_lossy() != "lock")),
Some(t) => int(t).map(|v| v.clamp(0, 1) as u8),
None => None,
},
charged: match c.get("minecraft:charged_projectiles") {
Some(Tag::List(list)) => list.iter().filter_map(crate::save::item_from_nbt).collect(),
_ => Vec::new(),
@@ -496,17 +704,21 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
.filter_map(|e| {
Some((
e.get("slot").and_then(int)?.clamp(0, 255) as u8,
crate::save::item_from_nbt(e.get("item")?)?,
template_from(e.get("item")?)?,
))
})
.collect(),
_ => Vec::new(),
},
ominous_banner: matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.first().is_some_and(|l|
l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus"))
),
ominous_banner: c
.get("minecraft:item_name")
.and_then(|n| n.get("translate"))
.and_then(string)
.as_deref()
== Some("block.minecraft.ominous_banner")
&& matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.len() == OMINOUS_LAYERS.len()),
ominous_amplifier: c
.get("minecraft:ominous_bottle_amplifier")
.and_then(int)
+31 -2
View File
@@ -60,7 +60,22 @@ pub struct ItemInfo {
pub equip_sound: Option<String>,
/// `jukebox_playable`: the jukebox song it plays.
pub jukebox_song: Option<String>,
/// `crafting_remainder`: what stays in the grid when the item is used in a recipe.
pub crafting_remainder: Option<String>,
/// `dye`: the dye colour name (dyes, and anything else with the component).
pub dye: Option<String>,
/// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks.
pub block_transformer: Option<String>,
}
/// `Item.Properties.craftRemainder` (not a data component, so not in the
/// default-component report): what an item leaves in the grid when crafted with.
pub const CRAFT_REMAINDERS: [(&str, &str); 5] = [
("minecraft:water_bucket", "minecraft:bucket"),
("minecraft:lava_bucket", "minecraft:bucket"),
("minecraft:milk_bucket", "minecraft:bucket"),
("minecraft:dragon_breath", "minecraft:glass_bottle"),
("minecraft:honey_bottle", "minecraft:glass_bottle"),
];
/// A reduction of `blocks_attacks.damage_reductions`.
#[derive(Clone, Debug)]
pub struct BlockReduction {
@@ -264,8 +279,6 @@ fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<S
}
impl Items {
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
let default = registry.default_state(&s.name);
@@ -275,6 +288,16 @@ impl Items {
.or_insert(BlockStateId(i as u32));
}
}
Self::load_with(root, &block_for_item)
}
/// Every item's default components and the tags, without the block <->
/// item mapping (for headless tools that never place blocks).
pub fn catalog(root: &Path) -> Result<Self> {
Self::load_with(root, &HashMap::new())
}
fn load_with(root: &Path, block_for_item: &HashMap<&str, BlockStateId>) -> Result<Self> {
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let entity_tags = load_tags(root, "entity_type")?;
let mut items = HashMap::new();
let mut order = Vec::new();
@@ -352,6 +375,12 @@ impl Items {
.as_str()
.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),
block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned),
crafting_remainder: CRAFT_REMAINDERS
.iter()
.find(|(item, _)| *item == name)
.map(|(_, rest)| (*rest).to_owned()),
use_speed: c["minecraft:use_effects"]["speed_multiplier"]
.as_f64()
.unwrap_or(0.2) as f32,
+613
View File
@@ -0,0 +1,613 @@
//! Java text conventions the vanilla option files depend on: shortest-digit
//! `Double.toString`/`Float.toString`, Gson's HTML-safe string escaping and a
//! reader for Gson's lenient JSON (`JsonParser.parseString`).
/// Digits and decimal exponent of the shortest round-trip form.
fn shortest(text: &str) -> (String, i32) {
// `{:e}` yields "d.ddde-5" or "de5".
let (mantissa, exponent) = text.split_once('e').unwrap_or((text, "0"));
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
(digits, exponent.parse().unwrap_or(0))
}
fn render(negative: bool, digits: &str, exponent: i32) -> String {
let mut out = String::new();
if negative {
out.push('-');
}
let digits = if digits.is_empty() { "0" } else { digits };
if (-3..7).contains(&exponent) {
if exponent >= 0 {
let int_len = exponent as usize + 1;
if digits.len() <= int_len {
out.push_str(digits);
out.extend(std::iter::repeat_n('0', int_len - digits.len()));
out.push_str(".0");
} else {
out.push_str(&digits[..int_len]);
out.push('.');
out.push_str(&digits[int_len..]);
}
} else {
out.push_str("0.");
out.extend(std::iter::repeat_n('0', (-exponent - 1) as usize));
out.push_str(digits);
}
} else {
out.push_str(&digits[..1]);
out.push('.');
if digits.len() > 1 {
out.push_str(&digits[1..]);
} else {
out.push('0');
}
out.push('E');
out.push_str(&exponent.to_string());
}
out
}
/// `Double.toString`.
pub fn double_to_string(value: f64) -> String {
if value.is_nan() {
return "NaN".into();
}
if value.is_infinite() {
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
}
if value == 0.0 {
return if value.is_sign_negative() {
"-0.0"
} else {
"0.0"
}
.into();
}
let (digits, exponent) = shortest(&format!("{:e}", value.abs()));
render(value < 0.0, &digits, exponent)
}
/// `Float.toString`.
pub fn float_to_string(value: f32) -> String {
if value.is_nan() {
return "NaN".into();
}
if value.is_infinite() {
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
}
if value == 0.0 {
return if value.is_sign_negative() {
"-0.0"
} else {
"0.0"
}
.into();
}
let (digits, exponent) = shortest(&format!("{:e}", value.abs()));
render(value < 0.0, &digits, exponent)
}
/// Gson's default (HTML-safe) JSON string literal.
pub fn gson_string(value: &str) -> String {
let mut out = String::from("\"");
for c in value.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
'<' | '>' | '&' | '=' | '\'' | '\u{2028}' | '\u{2029}' => {
out.push_str(&format!("\\u{:04x}", c as u32));
}
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// A parsed JSON element as Gson models it.
#[derive(Clone, Debug, PartialEq)]
pub enum Json {
Null,
Bool(bool),
/// The number's source text (`LazilyParsedNumber`).
Number(String),
String(String),
Array(Vec<Json>),
Object,
}
impl Json {
/// `Number.intValue()` of a `LazilyParsedNumber`: `Integer.parseInt`, else
/// `BigDecimal.intValue()` (truncate, keep the low 32 bits).
pub fn int_value(text: &str) -> i32 {
let (negative, body) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text),
};
let (mantissa, exponent) = match body.split_once(['e', 'E']) {
Some((m, e)) => (
m,
e.strip_prefix('+').unwrap_or(e).parse::<i64>().unwrap_or(0),
),
None => (body, 0),
};
let (int_part, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let digits: Vec<u32> = int_part
.chars()
.chain(fraction.chars())
.filter_map(|c| c.to_digit(10))
.collect();
// value = digits * 10^scale; truncating drops digits below the point.
let scale = exponent - fraction.len() as i64;
let keep = if scale >= 0 {
digits.len()
} else {
digits
.len()
.saturating_sub(scale.unsigned_abs().min(usize::MAX as u64) as usize)
};
let mut v: u32 = 0;
for d in &digits[..keep] {
v = v.wrapping_mul(10).wrapping_add(*d);
}
if scale > 0 {
// v * 10^scale modulo 2^32 by repeated squaring.
let (mut base, mut power, mut e) = (10u32, 1u32, scale as u64);
while e > 0 {
if e & 1 == 1 {
power = power.wrapping_mul(base);
}
base = base.wrapping_mul(base);
e >>= 1;
}
v = v.wrapping_mul(power);
}
let v = v as i32;
if negative { v.wrapping_neg() } else { v }
}
/// `Number.doubleValue()`.
pub fn double_value(text: &str) -> f64 {
text.parse::<f64>().unwrap_or(0.0)
}
}
/// A syntax error aborts the whole options load, as in vanilla.
#[derive(Debug)]
pub struct SyntaxError;
struct Reader {
chars: Vec<char>,
pos: usize,
}
fn is_literal(c: char) -> bool {
!matches!(
c,
'/' | '\\'
| ';'
| '#'
| '='
| '{'
| '}'
| '['
| ']'
| ':'
| ','
| ' '
| '\t'
| '\u{c}'
| '\r'
| '\n'
)
}
impl Reader {
fn peek_char(&self) -> Option<char> {
self.chars.get(self.pos).copied()
}
/// `nextNonWhitespace` with lenient comments; `None` at the end.
fn skip(&mut self) -> Result<Option<char>, SyntaxError> {
loop {
match self.peek_char() {
None => return Ok(None),
Some(' ' | '\t' | '\r' | '\n') => self.pos += 1,
Some('#') => self.line_comment(),
Some('/') => match self.chars.get(self.pos + 1) {
Some('/') => self.line_comment(),
Some('*') => {
self.pos += 2;
loop {
match (self.peek_char(), self.chars.get(self.pos + 1)) {
(Some('*'), Some('/')) => {
self.pos += 2;
break;
}
(Some(_), _) => self.pos += 1,
(None, _) => return Err(SyntaxError),
}
}
}
_ => return Ok(Some('/')),
},
Some(c) => return Ok(Some(c)),
}
}
}
fn line_comment(&mut self) {
while let Some(c) = self.peek_char() {
self.pos += 1;
if c == '\n' || c == '\r' {
break;
}
}
}
fn quoted(&mut self, quote: char) -> Result<String, SyntaxError> {
self.pos += 1;
let mut out = String::new();
loop {
let c = self.peek_char().ok_or(SyntaxError)?;
self.pos += 1;
if c == quote {
return Ok(out);
}
if c != '\\' {
out.push(c);
continue;
}
let e = self.peek_char().ok_or(SyntaxError)?;
self.pos += 1;
match e {
'u' => {
let mut v = 0u32;
for _ in 0..4 {
let d = self.peek_char().ok_or(SyntaxError)?;
self.pos += 1;
v = v * 16 + d.to_digit(16).ok_or(SyntaxError)?;
}
// Lone surrogates cannot be represented; keep the replacement.
out.push(char::from_u32(v).unwrap_or('\u{fffd}'));
}
't' => out.push('\t'),
'b' => out.push('\u{8}'),
'n' => out.push('\n'),
'r' => out.push('\r'),
'f' => out.push('\u{c}'),
'\n' | '\'' | '"' | '\\' | '/' => out.push(e),
_ => return Err(SyntaxError),
}
}
}
fn literal(&mut self) -> String {
let start = self.pos;
while self.peek_char().is_some_and(is_literal) {
self.pos += 1;
}
self.chars[start..self.pos].iter().collect()
}
/// JSON number grammar with Gson's leading-zero rule.
fn is_number(text: &str) -> bool {
let b: Vec<char> = text.chars().collect();
let mut i = 0;
if b.first() == Some(&'-') {
i += 1;
}
match b.get(i) {
Some('0') => {
i += 1;
}
Some(c) if c.is_ascii_digit() => {
while b.get(i).is_some_and(char::is_ascii_digit) {
i += 1;
}
}
_ => return false,
}
if b.get(i) == Some(&'.') {
i += 1;
if !b.get(i).is_some_and(char::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(char::is_ascii_digit) {
i += 1;
}
}
if matches!(b.get(i), Some('e' | 'E')) {
i += 1;
if matches!(b.get(i), Some('+' | '-')) {
i += 1;
}
if !b.get(i).is_some_and(char::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(char::is_ascii_digit) {
i += 1;
}
}
i == b.len()
}
fn keyword(text: &str, word: &str) -> bool {
text.len() == word.len() && text.eq_ignore_ascii_case(word)
}
fn value(&mut self) -> Result<Json, SyntaxError> {
let c = self.skip()?.ok_or(SyntaxError)?;
match c {
'"' | '\'' => Ok(Json::String(self.quoted(c)?)),
'[' => {
self.pos += 1;
let mut items = Vec::new();
loop {
match self.skip()?.ok_or(SyntaxError)? {
']' => {
self.pos += 1;
// A trailing separator leaves an implicit null.
return Ok(Json::Array(items));
}
',' | ';' => {
self.pos += 1;
items.push(Json::Null);
continue;
}
_ => {}
}
items.push(self.value()?);
match self.skip()?.ok_or(SyntaxError)? {
']' => {
self.pos += 1;
return Ok(Json::Array(items));
}
',' | ';' => self.pos += 1,
_ => return Err(SyntaxError),
}
}
}
'{' => {
self.pos += 1;
loop {
match self.skip()?.ok_or(SyntaxError)? {
'}' => {
self.pos += 1;
return Ok(Json::Object);
}
'"' | '\'' => {
let q = self.skip()?.ok_or(SyntaxError)?;
self.quoted(q)?;
}
c if is_literal(c) => {
self.literal();
}
_ => return Err(SyntaxError),
}
match self.skip()?.ok_or(SyntaxError)? {
':' => self.pos += 1,
'=' => {
self.pos += 1;
if self.peek_char() == Some('>') {
self.pos += 1;
}
}
_ => return Err(SyntaxError),
}
self.value()?;
match self.skip()?.ok_or(SyntaxError)? {
'}' => {
self.pos += 1;
return Ok(Json::Object);
}
',' | ';' => self.pos += 1,
_ => return Err(SyntaxError),
}
}
}
']' | '}' | ',' | ';' | ':' | '=' | '\\' | '/' => Err(SyntaxError),
_ => {
let text = self.literal();
if text.is_empty() {
return Err(SyntaxError);
}
if Self::keyword(&text, "true") {
Ok(Json::Bool(true))
} else if Self::keyword(&text, "false") {
Ok(Json::Bool(false))
} else if Self::keyword(&text, "null") {
Ok(Json::Null)
} else if Self::is_number(&text) {
Ok(Json::Number(text))
} else {
Ok(Json::String(text))
}
}
}
}
}
/// `JsonParser.parseString`: one lenient value and nothing after it.
pub fn parse_lenient(text: &str) -> Result<Json, SyntaxError> {
let text = text.strip_prefix(")]}'\n").unwrap_or(text);
let mut reader = Reader {
chars: text.chars().collect(),
pos: 0,
};
if reader.skip()?.is_none() {
return Ok(Json::Null);
}
let value = reader.value()?;
// The trailing check runs after Gson restored its legacy-strict mode:
// only whitespace may follow the value.
if value != Json::Null
&& reader.chars[reader.pos..]
.iter()
.any(|c| !matches!(c, ' ' | '\t' | '\r' | '\n'))
{
return Err(SyntaxError);
}
Ok(value)
}
impl Reader {
/// Next non-whitespace char in strict mode (comments are errors).
fn strict_skip(&mut self) -> Option<char> {
while matches!(self.peek_char(), Some(' ' | '\t' | '\r' | '\n')) {
self.pos += 1;
}
self.peek_char()
}
}
/// `Gson.getAdapter(List<String>).read` on a strict `JsonReader`
/// (`GsonHelper.fromNullableJson`): `Ok(None)` for `null`, an error for
/// anything Gson rejects, including an empty document.
pub fn parse_strict_string_list(text: &str) -> Result<Option<Vec<String>>, SyntaxError> {
let mut r = Reader {
chars: text.chars().collect(),
pos: 0,
};
match r.strict_skip().ok_or(SyntaxError)? {
'n' => {
let word = r.literal();
if word == "null" {
Ok(None)
} else {
Err(SyntaxError)
}
}
'[' => {
r.pos += 1;
let mut items = Vec::new();
if r.strict_skip().ok_or(SyntaxError)? == ']' {
return Ok(Some(items));
}
loop {
let c = r.strict_skip().ok_or(SyntaxError)?;
match c {
'"' => items.push(r.quoted('"')?),
'-' | '0'..='9' => {
let word = r.literal();
if !Reader::is_number(&word) {
return Err(SyntaxError);
}
items.push(word);
}
't' | 'f' | 'n' => {
let word = r.literal();
match word.as_str() {
"true" | "false" => items.push(word),
"null" => {}
_ => return Err(SyntaxError),
}
}
_ => return Err(SyntaxError),
}
match r.strict_skip().ok_or(SyntaxError)? {
',' => r.pos += 1,
']' => return Ok(Some(items)),
_ => return Err(SyntaxError),
}
}
}
_ => Err(SyntaxError),
}
}
/// `String.format(Locale.ROOT, "%.<n>f", value)`: Java rounds the shortest
/// round-trip decimal expansion half-up (so 1.005 gives 1.01).
pub fn format_fixed(value: f64, decimals: usize) -> String {
if value.is_nan() {
return "NaN".into();
}
if value.is_infinite() {
return if value < 0.0 { "-Infinity" } else { "Infinity" }.into();
}
let negative = value.is_sign_negative();
let (digits, exponent) = if value == 0.0 {
("0".to_owned(), 0)
} else {
shortest(&format!("{:e}", value.abs()))
};
let mut int_part: Vec<u8> = Vec::new();
let mut frac: Vec<u8> = Vec::new();
let d: Vec<u8> = digits.bytes().map(|b| b - b'0').collect();
let point = exponent + 1; // digits before the decimal point
if point <= 0 {
int_part.push(0);
frac.extend(std::iter::repeat_n(0, (-point) as usize));
frac.extend(&d);
} else {
let point = point as usize;
for i in 0..point {
int_part.push(d.get(i).copied().unwrap_or(0));
}
if d.len() > point {
frac.extend(&d[point..]);
}
}
let round_up = frac.get(decimals).is_some_and(|&x| x >= 5);
frac.truncate(decimals);
frac.resize(decimals, 0);
if round_up {
let mut carry = true;
for x in frac.iter_mut().rev().chain(int_part.iter_mut().rev()) {
if !carry {
break;
}
if *x == 9 {
*x = 0;
} else {
*x += 1;
carry = false;
}
}
if carry {
int_part.insert(0, 1);
}
}
let mut out = String::new();
if negative {
out.push('-');
}
out.extend(int_part.iter().map(|&x| (b'0' + x) as char));
if decimals > 0 {
out.push('.');
out.extend(frac.iter().map(|&x| (b'0' + x) as char));
}
out
}
/// `%.2f`.
pub fn format_fixed2(value: f64) -> String {
format_fixed(value, 2)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn java_number_text() {
assert_eq!(double_to_string(1.0), "1.0");
assert_eq!(double_to_string(0.5), "0.5");
assert_eq!(double_to_string(0.0001), "1.0E-4");
assert_eq!(double_to_string(0.001), "0.001");
assert_eq!(double_to_string(1234567.0), "1234567.0");
assert_eq!(double_to_string(12345678.0), "1.2345678E7");
assert_eq!(double_to_string(100.0), "100.0");
assert_eq!(float_to_string(0.15), "0.15");
assert_eq!(float_to_string(1.0e10), "1.0E10");
assert_eq!(double_to_string(-2.5), "-2.5");
}
#[test]
fn lenient_json() {
assert_eq!(parse_lenient("0.5").unwrap(), Json::Number("0.5".into()));
assert_eq!(parse_lenient("fast").unwrap(), Json::String("fast".into()));
assert_eq!(parse_lenient("TRUE").unwrap(), Json::Bool(true));
assert_eq!(parse_lenient("007").unwrap(), Json::String("007".into()));
assert!(parse_lenient("1 2").is_err());
assert!(parse_lenient("\"abc").is_err());
assert_eq!(parse_lenient(" ").unwrap(), Json::Null);
assert_eq!(gson_string("a=b"), "\"a\\u003db\"");
}
}
+265
View File
@@ -0,0 +1,265 @@
//! InputConstants key tables of 26.3 (SDL scancodes), generated from the
//! pinned client by `VanillaOptionsTableExporter`.
/// Keyboard keys: (SDL scancode, key name).
pub const KEYBOARD: &[(i32, &str)] = &[
(0, "key.keyboard.unknown"),
(4, "key.keyboard.a"),
(5, "key.keyboard.b"),
(6, "key.keyboard.c"),
(7, "key.keyboard.d"),
(8, "key.keyboard.e"),
(9, "key.keyboard.f"),
(10, "key.keyboard.g"),
(11, "key.keyboard.h"),
(12, "key.keyboard.i"),
(13, "key.keyboard.j"),
(14, "key.keyboard.k"),
(15, "key.keyboard.l"),
(16, "key.keyboard.m"),
(17, "key.keyboard.n"),
(18, "key.keyboard.o"),
(19, "key.keyboard.p"),
(20, "key.keyboard.q"),
(21, "key.keyboard.r"),
(22, "key.keyboard.s"),
(23, "key.keyboard.t"),
(24, "key.keyboard.u"),
(25, "key.keyboard.v"),
(26, "key.keyboard.w"),
(27, "key.keyboard.x"),
(28, "key.keyboard.y"),
(29, "key.keyboard.z"),
(30, "key.keyboard.1"),
(31, "key.keyboard.2"),
(32, "key.keyboard.3"),
(33, "key.keyboard.4"),
(34, "key.keyboard.5"),
(35, "key.keyboard.6"),
(36, "key.keyboard.7"),
(37, "key.keyboard.8"),
(38, "key.keyboard.9"),
(39, "key.keyboard.0"),
(40, "key.keyboard.enter"),
(41, "key.keyboard.escape"),
(42, "key.keyboard.backspace"),
(43, "key.keyboard.tab"),
(44, "key.keyboard.space"),
(45, "key.keyboard.minus"),
(46, "key.keyboard.equal"),
(47, "key.keyboard.left.bracket"),
(48, "key.keyboard.right.bracket"),
(49, "key.keyboard.backslash"),
(50, "key.keyboard.world.2"),
(51, "key.keyboard.semicolon"),
(52, "key.keyboard.apostrophe"),
(53, "key.keyboard.grave.accent"),
(54, "key.keyboard.comma"),
(55, "key.keyboard.period"),
(56, "key.keyboard.slash"),
(57, "key.keyboard.caps.lock"),
(58, "key.keyboard.f1"),
(59, "key.keyboard.f2"),
(60, "key.keyboard.f3"),
(61, "key.keyboard.f4"),
(62, "key.keyboard.f5"),
(63, "key.keyboard.f6"),
(64, "key.keyboard.f7"),
(65, "key.keyboard.f8"),
(66, "key.keyboard.f9"),
(67, "key.keyboard.f10"),
(68, "key.keyboard.f11"),
(69, "key.keyboard.f12"),
(70, "key.keyboard.print.screen"),
(71, "key.keyboard.scroll.lock"),
(72, "key.keyboard.pause"),
(73, "key.keyboard.insert"),
(74, "key.keyboard.home"),
(75, "key.keyboard.page.up"),
(76, "key.keyboard.delete"),
(77, "key.keyboard.end"),
(78, "key.keyboard.page.down"),
(79, "key.keyboard.right"),
(80, "key.keyboard.left"),
(81, "key.keyboard.down"),
(82, "key.keyboard.up"),
(83, "key.keyboard.num.lock"),
(84, "key.keyboard.keypad.divide"),
(85, "key.keyboard.keypad.multiply"),
(86, "key.keyboard.keypad.subtract"),
(87, "key.keyboard.keypad.add"),
(88, "key.keyboard.keypad.enter"),
(89, "key.keyboard.keypad.1"),
(90, "key.keyboard.keypad.2"),
(91, "key.keyboard.keypad.3"),
(92, "key.keyboard.keypad.4"),
(93, "key.keyboard.keypad.5"),
(94, "key.keyboard.keypad.6"),
(95, "key.keyboard.keypad.7"),
(96, "key.keyboard.keypad.8"),
(97, "key.keyboard.keypad.9"),
(98, "key.keyboard.keypad.0"),
(99, "key.keyboard.keypad.period"),
(100, "key.keyboard.world.1"),
(101, "key.keyboard.application"),
(102, "key.keyboard.power"),
(103, "key.keyboard.keypad.equal"),
(104, "key.keyboard.f13"),
(105, "key.keyboard.f14"),
(106, "key.keyboard.f15"),
(107, "key.keyboard.f16"),
(108, "key.keyboard.f17"),
(109, "key.keyboard.f18"),
(110, "key.keyboard.f19"),
(111, "key.keyboard.f20"),
(112, "key.keyboard.f21"),
(113, "key.keyboard.f22"),
(114, "key.keyboard.f23"),
(115, "key.keyboard.f24"),
(116, "key.keyboard.execute"),
(117, "key.keyboard.help"),
(118, "key.keyboard.menu"),
(119, "key.keyboard.select"),
(120, "key.keyboard.stop"),
(121, "key.keyboard.again"),
(122, "key.keyboard.undo"),
(123, "key.keyboard.cut"),
(124, "key.keyboard.copy"),
(125, "key.keyboard.paste"),
(126, "key.keyboard.find"),
(127, "key.keyboard.mute"),
(128, "key.keyboard.volume.up"),
(129, "key.keyboard.volume.down"),
(133, "key.keyboard.keypad.comma"),
(134, "key.keyboard.keypad.equals.as400"),
(135, "key.keyboard.international1"),
(136, "key.keyboard.international2"),
(137, "key.keyboard.international3"),
(138, "key.keyboard.international4"),
(139, "key.keyboard.international5"),
(140, "key.keyboard.international6"),
(141, "key.keyboard.international7"),
(142, "key.keyboard.international8"),
(143, "key.keyboard.international9"),
(144, "key.keyboard.lang1"),
(145, "key.keyboard.lang2"),
(146, "key.keyboard.lang3"),
(147, "key.keyboard.lang4"),
(148, "key.keyboard.lang5"),
(149, "key.keyboard.lang6"),
(150, "key.keyboard.lang7"),
(151, "key.keyboard.lang8"),
(152, "key.keyboard.lang9"),
(153, "key.keyboard.alternate.erase"),
(154, "key.keyboard.sys.req"),
(155, "key.keyboard.cancel"),
(156, "key.keyboard.clear"),
(157, "key.keyboard.prior"),
(158, "key.keyboard.enter2"),
(159, "key.keyboard.separator"),
(160, "key.keyboard.out"),
(161, "key.keyboard.oper"),
(162, "key.keyboard.clear.again"),
(163, "key.keyboard.crsel"),
(164, "key.keyboard.exsel"),
(176, "key.keyboard.keypad.00"),
(177, "key.keyboard.keypad.000"),
(178, "key.keyboard.thousands.separator"),
(179, "key.keyboard.decimal.separator"),
(180, "key.keyboard.currency.unit"),
(181, "key.keyboard.currency.subunit"),
(182, "key.keyboard.keypad.left.parenthesis"),
(183, "key.keyboard.keypad.right.parenthesis"),
(184, "key.keyboard.keypad.left.brace"),
(185, "key.keyboard.keypad.right.brace"),
(186, "key.keyboard.keypad.tab"),
(187, "key.keyboard.keypad.backspace"),
(188, "key.keyboard.keypad.a"),
(189, "key.keyboard.keypad.b"),
(190, "key.keyboard.keypad.c"),
(191, "key.keyboard.keypad.d"),
(192, "key.keyboard.keypad.e"),
(193, "key.keyboard.keypad.f"),
(194, "key.keyboard.keypad.xor"),
(195, "key.keyboard.keypad.power"),
(196, "key.keyboard.keypad.percent"),
(197, "key.keyboard.keypad.less"),
(198, "key.keyboard.keypad.greater"),
(199, "key.keyboard.keypad.ampersand"),
(200, "key.keyboard.keypad.double.ampersand"),
(201, "key.keyboard.keypad.vertical.bar"),
(202, "key.keyboard.keypad.double.vertical.bar"),
(203, "key.keyboard.keypad.colon"),
(204, "key.keyboard.keypad.hash"),
(205, "key.keyboard.keypad.space"),
(206, "key.keyboard.keypad.at"),
(207, "key.keyboard.keypad.exclamation"),
(208, "key.keyboard.keypad.memory.store"),
(209, "key.keyboard.keypad.memory.recall"),
(210, "key.keyboard.keypad.memory.clear"),
(211, "key.keyboard.keypad.memory.add"),
(212, "key.keyboard.keypad.memory.subtract"),
(213, "key.keyboard.keypad.memory.multiply"),
(214, "key.keyboard.keypad.memory.divide"),
(215, "key.keyboard.keypad.plus.minus"),
(216, "key.keyboard.keypad.clear"),
(217, "key.keyboard.keypad.clear.entry"),
(218, "key.keyboard.keypad.binary"),
(219, "key.keyboard.keypad.octal"),
(220, "key.keyboard.keypad.decimal"),
(221, "key.keyboard.keypad.hexadecimal"),
(224, "key.keyboard.left.control"),
(225, "key.keyboard.left.shift"),
(226, "key.keyboard.left.alt"),
(227, "key.keyboard.left.win"),
(228, "key.keyboard.right.control"),
(229, "key.keyboard.right.shift"),
(230, "key.keyboard.right.alt"),
(231, "key.keyboard.right.win"),
(257, "key.keyboard.mode"),
(258, "key.keyboard.sleep"),
(259, "key.keyboard.wake"),
(260, "key.keyboard.channel.up"),
(261, "key.keyboard.channel.down"),
(262, "key.keyboard.media.play"),
(263, "key.keyboard.media.pause"),
(264, "key.keyboard.media.record"),
(265, "key.keyboard.media.fast.forward"),
(266, "key.keyboard.media.rewind"),
(267, "key.keyboard.media.next.track"),
(268, "key.keyboard.media.previous.track"),
(269, "key.keyboard.media.stop"),
(270, "key.keyboard.media.eject"),
(271, "key.keyboard.media.play.pause"),
(272, "key.keyboard.media.select"),
(273, "key.keyboard.ac.new"),
(274, "key.keyboard.ac.open"),
(275, "key.keyboard.ac.close"),
(276, "key.keyboard.ac.exit"),
(277, "key.keyboard.ac.save"),
(278, "key.keyboard.ac.print"),
(279, "key.keyboard.ac.properties"),
(280, "key.keyboard.ac.search"),
(281, "key.keyboard.ac.home"),
(282, "key.keyboard.ac.back"),
(283, "key.keyboard.ac.forward"),
(284, "key.keyboard.ac.stop"),
(285, "key.keyboard.ac.refresh"),
(286, "key.keyboard.ac.bookmarks"),
(287, "key.keyboard.soft.left"),
(288, "key.keyboard.soft.right"),
(289, "key.keyboard.call"),
(290, "key.keyboard.end.call"),
];
/// Mouse buttons: (button number, key name).
pub const MOUSE: &[(i32, &str)] = &[
(1, "key.mouse.left"),
(2, "key.mouse.middle"),
(3, "key.mouse.right"),
(4, "key.mouse.4"),
(5, "key.mouse.5"),
(6, "key.mouse.6"),
(7, "key.mouse.7"),
(8, "key.mouse.8"),
];
+26
View File
@@ -43,6 +43,7 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[
("key.advancements", "key.keyboard.l", "misc"),
("key.quickActions", "key.keyboard.g", "misc"),
("key.debug.overlay", "key.keyboard.f3", "debug"),
("key.debug.modifier", "key.keyboard.f3", "debug"),
("key.hotbar.1", "key.keyboard.1", "inventory"),
("key.hotbar.2", "key.keyboard.2", "inventory"),
("key.hotbar.3", "key.keyboard.3", "inventory"),
@@ -52,7 +53,32 @@ pub const MAPPINGS: &[(&str, &str, &str)] = &[
("key.hotbar.7", "key.keyboard.7", "inventory"),
("key.hotbar.8", "key.keyboard.8", "inventory"),
("key.hotbar.9", "key.keyboard.9", "inventory"),
("key.debug.reloadChunk", "key.keyboard.a", "debug"),
("key.debug.showHitboxes", "key.keyboard.b", "debug"),
("key.debug.clearChat", "key.keyboard.d", "debug"),
("key.debug.crash", "key.keyboard.c", "debug"),
("key.debug.showChunkBorders", "key.keyboard.g", "debug"),
("key.debug.showAdvancedTooltips", "key.keyboard.h", "debug"),
("key.debug.copyRecreateCommand", "key.keyboard.i", "debug"),
("key.debug.spectate", "key.keyboard.n", "debug"),
("key.debug.switchGameMode", "key.keyboard.f4", "debug"),
("key.debug.debugOptions", "key.keyboard.f6", "debug"),
("key.debug.focusPause", "key.keyboard.p", "debug"),
("key.debug.dumpDynamicTextures", "key.keyboard.s", "debug"),
("key.debug.reloadResourcePacks", "key.keyboard.t", "debug"),
("key.debug.profiling", "key.keyboard.l", "debug"),
("key.debug.copyLocation", "key.keyboard.c", "debug"),
("key.debug.dumpVersion", "key.keyboard.v", "debug"),
("key.debug.profilingChart", "key.keyboard.1", "debug"),
("key.debug.fpsCharts", "key.keyboard.2", "debug"),
("key.debug.networkCharts", "key.keyboard.3", "debug"),
("key.debug.lightmapTexture", "key.keyboard.4", "debug"),
("key.debug.improvedTransparency", "key.keyboard.x", "debug"),
];
/// Mappings Options builds as `ToggleKeyMapping` (hold or toggle by option).
pub fn is_toggle(name: &str) -> bool {
matches!(name, "key.sneak" | "key.sprint" | "key.use" | "key.attack")
}
/// KeyMapping.Category sort order.
pub const CATEGORIES: [&str; 8] = [
"movement",
+110
View File
@@ -0,0 +1,110 @@
//! The down/click state of `KeyMapping` and `ToggleKeyMapping` (sneak,
//! sprint, attack and use can be toggled instead of held).
/// One mapping's runtime state. `toggle` is `Some(restore)` for a
/// `ToggleKeyMapping` (with its `shouldRestore` flag), `None` for a plain one.
#[derive(Clone, Debug)]
pub struct KeyState {
pub is_down: bool,
click_count: i32,
released_by_screen_when_down: bool,
toggle: Option<bool>,
keyboard: bool,
}
impl KeyState {
pub fn plain() -> Self {
Self {
is_down: false,
click_count: 0,
released_by_screen_when_down: false,
toggle: None,
keyboard: true,
}
}
/// A `ToggleKeyMapping`; `keyboard` is whether the bound key is a keyboard key.
pub fn toggle(should_restore: bool, keyboard: bool) -> Self {
Self {
toggle: Some(should_restore),
keyboard,
..Self::plain()
}
}
/// `KeyMapping.click`: one more pending click.
pub fn click(&mut self) {
self.click_count += 1;
}
/// `consumeClick`.
pub fn consume_click(&mut self) -> bool {
if self.click_count == 0 {
false
} else {
self.click_count -= 1;
true
}
}
/// `setDown`; `needs_toggle` is the mapping's option value.
pub fn set_down(&mut self, down: bool, needs_toggle: bool) {
if self.toggle.is_some() && needs_toggle {
if down {
self.is_down = !self.is_down;
}
} else {
self.is_down = down;
}
}
/// `shouldSetOnIngameFocus` for a keyboard-bound, bound key.
pub fn should_set_on_ingame_focus(&self, needs_toggle: bool) -> bool {
self.keyboard && (self.toggle.is_none() || !needs_toggle)
}
/// `release` (a screen opened): drops pending clicks and the held state.
pub fn release(&mut self, needs_toggle: bool) {
if self.toggle.is_some() {
// ToggleKeyMapping.release does not clear pending clicks.
if needs_toggle && self.is_down || self.released_by_screen_when_down {
self.released_by_screen_when_down = true;
}
self.reset();
} else {
self.click_count = 0;
self.set_down(false, needs_toggle);
}
}
/// `ToggleKeyMapping.reset`.
pub fn reset(&mut self) {
self.is_down = false;
}
/// `shouldRestoreStateOnScreenClosed` (clears the remembered release).
pub fn should_restore_state_on_screen_closed(&mut self, needs_toggle: bool) -> bool {
let Some(restore) = self.toggle else {
return false;
};
let result = restore && needs_toggle && self.keyboard && self.released_by_screen_when_down;
self.released_by_screen_when_down = false;
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggle_flips_on_press_and_ignores_release() {
let mut k = KeyState::toggle(true, true);
k.set_down(true, true);
assert!(k.is_down);
k.set_down(false, true);
assert!(k.is_down);
k.set_down(true, true);
assert!(!k.is_down);
}
#[test]
fn screen_release_restores_toggled_state() {
let mut k = KeyState::toggle(true, true);
k.set_down(true, true);
k.release(true);
assert!(!k.is_down);
assert!(k.should_restore_state_on_screen_closed(true));
assert!(!k.should_restore_state_on_screen_closed(true));
}
}
+9 -20
View File
@@ -2,7 +2,7 @@
//! (sections with their paletted containers, block entities and the sky and
//! block DataLayers) and the section block-change batches.
use crate::{
chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section},
chunk::{Chunk, Light, MIN_Y, SECTIONS, Section},
containers::BlockEntity,
};
use horizon_protocol::{
@@ -154,12 +154,7 @@ impl ChunkEncoder {
.is_none_or(|f| f & NON_AIR == 0)
}
fn section(
&self,
section: &Section,
chunk: &Chunk,
index: usize,
) -> (horizon_protocol::chunk::Section, bool) {
fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, bool) {
let mut values = Vec::with_capacity(BLOCKS);
let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false);
let mut count = |state: u16, n: i16| {
@@ -172,21 +167,15 @@ impl ChunkEncoder {
}
f & ENTITY != 0
};
match &section.blocks {
Blocks::Uniform(v) => {
entities |= count(*v, BLOCKS as i16);
values.resize(BLOCKS, i32::from(*v));
}
Blocks::Full(a) => {
for &v in a.iter() {
entities |= count(v, 1);
values.push(i32::from(v));
}
}
let mut unpacked = [0u16; BLOCKS];
section.unpack(&mut unpacked);
for &v in &unpacked {
entities |= count(v, 1);
values.push(i32::from(v));
}
let biome_values: Vec<i32> = (0..BIOMES)
.map(|j| {
let internal = chunk.biomes.get(index * BIOMES + j).copied().unwrap_or(0);
let internal = section.biomes.get(j) as u16;
self.biome_ids
.get(usize::from(internal))
.copied()
@@ -213,7 +202,7 @@ impl ChunkEncoder {
let mut sections = Vec::with_capacity(SECTIONS);
let mut entity_infos = Vec::new();
for (i, s) in chunk.sections.iter().enumerate() {
let (encoded, has_entities) = self.section(s, chunk, i);
let (encoded, has_entities) = self.section(s);
if has_entities {
for y in 0..16 {
for z in 0..16 {
+169
View File
@@ -0,0 +1,169 @@
//! LAN game discovery: LanServerPinger announces a hosted world on the
//! multicast group 224.0.2.60:4445 every 1.5 seconds as
//! `[MOTD]text[/MOTD][AD]port[/AD]`, and LanServerDetection collects those
//! announcements for the multiplayer screen.
use std::{
io,
net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket},
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
thread::JoinHandle,
time::{Duration, Instant},
};
pub const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 2, 60);
pub const PORT: u16 = 4445;
/// LanServerPinger sleeps 1500 ms between announcements.
const INTERVAL: Duration = Duration::from_millis(1500);
/// LanServerDetection.LanServerList drops entries not refreshed for 5 s.
const EXPIRY: Duration = Duration::from_secs(5);
/// LanServerPinger.createPingString.
pub fn ping_string(motd: &str, port: u16) -> String {
format!("[MOTD]{motd}[/MOTD][AD]{port}[/AD]")
}
fn between<'a>(s: &'a str, open: &str, close: &str) -> Option<&'a str> {
let start = s.find(open)? + open.len();
let end = s[start..].find(close)? + start;
Some(&s[start..end])
}
/// LanServerPinger.parseMotd; vanilla shows "missing no" when absent.
pub fn parse_motd(s: &str) -> String {
between(s, "[MOTD]", "[/MOTD]")
.unwrap_or("missing no")
.to_owned()
}
/// LanServerPinger.parseAddress: the announced port, if present and valid.
pub fn parse_port(s: &str) -> Option<u16> {
between(s, "[AD]", "[/AD]")?.parse().ok().filter(|p| *p > 0)
}
/// Announces one hosted world until dropped.
pub struct Pinger {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl Pinger {
pub fn start(motd: String, port: u16) -> io::Result<Self> {
let socket = UdpSocket::bind(("0.0.0.0", 0))?;
let _ = socket.set_multicast_ttl_v4(4);
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let message = ping_string(&motd, port);
let thread = std::thread::Builder::new()
.name("horizon-lan-ping".into())
.spawn(move || {
let target = SocketAddr::V4(SocketAddrV4::new(GROUP, PORT));
while !flag.load(Ordering::Relaxed) {
let _ = socket.send_to(message.as_bytes(), target);
let mut slept = Duration::ZERO;
while slept < INTERVAL && !flag.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(50));
slept += Duration::from_millis(50);
}
}
})?;
Ok(Self {
stop,
thread: Some(thread),
})
}
}
impl Drop for Pinger {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
/// A world announced on the local network.
#[derive(Clone, Debug, PartialEq)]
pub struct LanGame {
pub motd: String,
pub address: String,
}
type Games = Arc<Mutex<Vec<(LanGame, Instant)>>>;
/// Listens for announcements until the last clone is dropped.
#[derive(Clone, Debug)]
pub struct Scanner {
inner: Arc<ScanInner>,
}
#[derive(Debug)]
struct ScanInner {
games: Games,
stop: Arc<AtomicBool>,
}
impl Drop for ScanInner {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
}
}
impl Scanner {
/// Bind the discovery port; without it the list simply stays empty.
pub fn start() -> Self {
let games: Games = Arc::default();
let stop = Arc::new(AtomicBool::new(false));
if let Ok(socket) = bind_listener() {
let (games, stop) = (games.clone(), stop.clone());
let _ = std::thread::Builder::new()
.name("horizon-lan-scan".into())
.spawn(move || listen(socket, games, stop));
}
Self {
inner: Arc::new(ScanInner { games, stop }),
}
}
/// The live announcements, oldest first.
pub fn games(&self) -> Vec<LanGame> {
let mut games = self.inner.games.lock().unwrap();
games.retain(|(_, seen)| seen.elapsed() < EXPIRY);
games.iter().map(|(g, _)| g.clone()).collect()
}
}
fn bind_listener() -> io::Result<UdpSocket> {
let socket = UdpSocket::bind(("0.0.0.0", PORT))?;
socket.join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)?;
socket.set_read_timeout(Some(Duration::from_millis(250)))?;
Ok(socket)
}
fn listen(socket: UdpSocket, games: Games, stop: Arc<AtomicBool>) {
let mut buf = [0u8; 1024];
while !stop.load(Ordering::Relaxed) {
let Ok((n, from)) = socket.recv_from(&mut buf) else {
continue;
};
let text = String::from_utf8_lossy(&buf[..n]);
let Some(port) = parse_port(&text) else {
continue;
};
let game = LanGame {
motd: parse_motd(&text),
address: format!("{}:{port}", from.ip()),
};
let mut games = games.lock().unwrap();
match games.iter_mut().find(|(g, _)| g.address == game.address) {
Some(entry) => *entry = (game, Instant::now()),
None => games.push((game, Instant::now())),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ping_string_round_trips() {
let s = ping_string("Steve - World", 25565);
assert_eq!(s, "[MOTD]Steve - World[/MOTD][AD]25565[/AD]");
assert_eq!(parse_motd(&s), "Steve - World");
assert_eq!(parse_port(&s), Some(25565));
assert_eq!(parse_port("[AD]0[/AD]"), None);
assert_eq!(parse_motd("junk"), "missing no");
}
}
+6
View File
@@ -8,6 +8,7 @@ pub mod chunks;
pub mod conn;
pub mod containers;
pub mod data;
pub mod discovery;
pub mod entity;
pub mod guest;
pub mod hub;
@@ -111,6 +112,8 @@ pub struct Lan {
events: Receiver<NetEvent>,
pub port: u16,
listener: Option<JoinHandle<()>>,
/// The multicast announcement (LanServerPinger); absent when the socket failed.
_pinger: Option<discovery::Pinger>,
}
impl Lan {
/// Listen on `port` (0 picks a free one).
@@ -123,6 +126,7 @@ impl Lan {
let listener = TcpListener::bind(("0.0.0.0", port))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let _pinger = discovery::Pinger::start(motd.clone(), port).ok();
let (tx, events) = channel();
let shared = Arc::new(Shared {
sync,
@@ -142,6 +146,7 @@ impl Lan {
events,
port,
listener: Some(listener),
_pinger,
})
}
/// Everything the connection threads reported since the last call.
@@ -160,6 +165,7 @@ impl Lan {
if let Some(t) = self.listener.take() {
let _ = t.join();
}
self._pinger = None;
}
}
impl Drop for Lan {
+10
View File
@@ -11,9 +11,11 @@ pub mod banner;
pub mod biome;
pub mod block_entity_nbt;
pub mod block_entity_render;
pub mod block_transform;
pub mod blocks;
pub mod bossbar;
pub mod brewing;
pub mod cauldron;
pub mod chat;
pub mod chunk;
pub mod clock;
@@ -43,20 +45,27 @@ pub mod hunger;
pub mod input;
pub mod item_data;
pub mod items;
pub mod java_text;
pub mod key_names;
pub mod keybinds;
pub mod keymapping;
pub mod lan;
pub mod landing;
pub mod lang;
pub mod light;
pub mod menu;
pub mod merchant;
pub mod mesher;
pub mod mobs;
pub mod models;
pub mod motion;
pub mod mouse;
pub mod multiplayer;
pub mod music;
pub mod nbt_path;
pub mod net;
pub mod options_file;
pub mod options_fixes;
pub mod options_ui;
pub mod packs;
pub mod particles;
@@ -86,6 +95,7 @@ pub mod text;
pub mod title;
pub mod ui;
pub mod vanillagen;
pub mod window;
pub mod world;
pub mod worldborder;
pub mod zip;
+3 -2
View File
@@ -216,6 +216,7 @@ pub fn light_chunk(
let mut block = vec![0u8; W * W * h];
let mut queue = VecDeque::new();
let mut sky_queue = VecDeque::new();
let mut ids = Box::new([0u16; 4096]);
for (dz, row) in region.iter().enumerate() {
for (dx, chunk) in row.iter().enumerate() {
let Some(chunk) = chunk else { continue };
@@ -223,8 +224,8 @@ pub fn light_chunk(
if section.is_uniform(0) {
continue;
}
for i in 0..4096 {
let id = section.get(i);
section.unpack(&mut ids);
for (i, &id) in ids.iter().enumerate() {
let (lx, lz, ly) = (i & 15, (i >> 4) & 15, i >> 8);
let p = at(dx * 16 + lx, si * 16 + ly, dz * 16 + lz);
states[p] = id;
File diff suppressed because it is too large Load Diff
+168 -63
View File
@@ -12,7 +12,9 @@ use crate::{
chunk::{Chunk, MIN_Y},
models::catalog::BakedFace,
};
use horizon_core::{geometry::Direction, position::BlockPos, random::position_seed};
use horizon_core::{
biome::BiomeZoom, geometry::Direction, position::BlockPos, random::position_seed,
};
use horizon_world::{
block_render::FaceVisibility,
fluid::{FluidKind, FluidState},
@@ -161,6 +163,8 @@ struct Info {
legacy_solid: bool,
/// `HalfTransparentBlock`/`LeavesBlock`: water sides show the overlay sprite.
overlay: bool,
/// `LeavesBlock`: with opaque leaves the faces between two leaf blocks are skipped.
leaves: bool,
blocks_flow: bool,
ice: bool,
sturdy: u8,
@@ -313,6 +317,7 @@ impl MeshTables {
offset,
legacy_solid: s.legacy_solid,
overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"),
leaves: s.has_class("LeavesBlock"),
blocks_flow: assets.blocks_fluid_flow.contains(&*s.name),
ice: s.has_class("IceBlock"),
sturdy: s.sturdy_full,
@@ -378,6 +383,13 @@ impl Padded {
let mut blocks = vec![0u16; P * P * P];
let mut light = vec![0u8; P * P * P];
let base_y = MIN_Y + sy * 16;
// The section itself is unpacked in one pass; the border cells of the
// neighbouring sections are read one by one.
let mut own = Box::new([0u16; 4096]);
let center = region[1][1].map(|c| &c.sections[sy as usize]);
if let Some(section) = center {
section.unpack(&mut own);
}
for y in -B..16 + B {
let wy = base_y + y;
for z in -B..16 + B {
@@ -385,7 +397,13 @@ impl Padded {
let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize];
let i = pi(x, y, z);
if let Some(c) = chunk {
blocks[i] = c.get(x & 15, wy, z & 15);
blocks[i] =
if (0..16).contains(&x) && (0..16).contains(&y) && (0..16).contains(&z)
{
own[(y << 8 | z << 4 | x) as usize]
} else {
c.get(x & 15, wy, z & 15)
};
light[i] = c.light(x & 15, wy, z & 15);
} else {
light[i] = 0xF0;
@@ -396,57 +414,113 @@ impl Padded {
Self { blocks, light }
}
}
/// Set on a vertex's sprite layer when its texture alpha must be ignored.
pub const OPAQUE_LAYER: u32 = 1 << 31;
const UNSET: u32 = u32::MAX;
const NO_BIOME: u16 = u16::MAX;
/// The `ColorResolver`s `ClientLevel` caches block tints for.
#[derive(Clone, Copy)]
struct Colors {
grass: [u32; 256],
tall_upper: [u32; 256],
foliage: [u32; 256],
dry: [u32; 256],
water: [u32; 256],
enum Resolver {
Grass,
Foliage,
Dry,
Water,
}
fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y: i32) -> Colors {
// Vanilla blends over a (2r+1)^2 area; r = 2 is the default option.
const R: i32 = 2;
let biome_at = |x: i32, z: i32| -> u16 {
region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize]
.map_or(0, |c| c.biome(x & 15, y, z & 15))
};
let mut colors = Colors {
grass: [0; 256],
tall_upper: [0; 256],
foliage: [0; 256],
dry: [0; 256],
water: [0; 256],
};
let avg = |f: &dyn Fn(u16, i32, i32) -> u32, x: i32, z: i32| -> u32 {
let (mut r, mut g, mut b) = (0, 0, 0);
for dz in -R..=R {
for dx in -R..=R {
let c = f(biome_at(x + dx, z + dz), x + dx, z + dz);
r += c >> 16 & 255;
g += c >> 8 & 255;
b += c & 255;
}
}
let n = ((2 * R + 1) * (2 * R + 1)) as u32;
(r / n) << 16 | (g / n) << 8 | (b / n)
};
for z in 0..16 {
for x in 0..16 {
let i = (z * 16 + x) as usize;
let (wx, wz) = (cx * 16 + x, cz * 16 + z);
colors.grass[i] = avg(
&|b, dx, dz| biomes.grass(b, f64::from(wx + dx - x), f64::from(wz + dz - z)),
x,
z,
);
colors.tall_upper[i] = colors.grass[i];
colors.foliage[i] = avg(&|b, _, _| biomes.get(b).foliage, x, z);
colors.dry[i] = avg(&|b, _, _| biomes.get(b).dry_foliage, x, z);
colors.water[i] = avg(&|b, _, _| biomes.get(b).water, x, z);
/// Biome tints of one block layer: the zoomed biome of every block of the
/// layer plus the blend radius around it, and the blended colours per column.
struct Layer {
zoomed: Vec<u16>,
colors: [[u32; 256]; 4],
}
/// `ClientLevel.calculateBlockTint` behind a per-layer `BlockTintCache`: each
/// block averages the colours of the biomes `BiomeManager.getBiome` picks (the
/// eight-corner zoom) over a `(2r+1)^2` square at the block's own height.
/// Layers and columns are only computed when a tinted block asks for them.
struct Tints<'a> {
region: &'a [[Option<&'a Chunk>; 3]; 3],
biomes: &'a Biomes,
zoom: BiomeZoom,
radius: i32,
plains: u16,
/// Chunk x, chunk z and the section's lowest block y.
origin: [i32; 3],
layers: [Option<Box<Layer>>; 16],
}
impl<'a> Tints<'a> {
fn new(
region: &'a [[Option<&'a Chunk>; 3]; 3],
biomes: &'a Biomes,
zoom: BiomeZoom,
radius: i32,
origin: [i32; 3],
) -> Self {
Self {
region,
biomes,
zoom,
radius: radius.clamp(0, 7),
plains: biomes.id("minecraft:plains"),
origin,
layers: Default::default(),
}
}
colors
/// The blended tint of block `(x, y, z)` (section-local x/z, y in 0..16).
fn get(&mut self, resolver: Resolver, x: i32, y: i32, z: i32) -> u32 {
let r = self.radius;
let dim = (16 + 2 * r) as usize;
let layer = self.layers[y as usize].get_or_insert_with(|| {
Box::new(Layer {
zoomed: vec![NO_BIOME; dim * dim],
colors: [[UNSET; 256]; 4],
})
});
let slot = (z * 16 + x) as usize;
let cached = layer.colors[resolver as usize][slot];
if cached != UNSET {
return cached;
}
let [cx, cz, base_y] = self.origin;
let (bx, by, bz) = (cx * 16, base_y + y, cz * 16);
let (mut red, mut green, mut blue) = (0, 0, 0);
for dz in -r..=r {
for dx in -r..=r {
let cell = ((z + dz + r) as usize) * dim + (x + dx + r) as usize;
let mut biome = layer.zoomed[cell];
if biome == NO_BIOME {
// BiomeManager.getBiome over the loaded chunks (plains
// where there is none).
let q = self
.zoom
.quart_at_block(BlockPos::new(bx + x + dx, by, bz + z + dz));
let (rx, rz) = ((q[0] >> 2) - cx + 1, (q[2] >> 2) - cz + 1);
biome = if (0..3).contains(&rx) && (0..3).contains(&rz) {
self.region[rz as usize][rx as usize].map_or(self.plains, |c| {
c.biome((q[0] & 3) * 4, q[1] * 4, (q[2] & 3) * 4)
})
} else {
self.plains
};
layer.zoomed[cell] = biome;
}
let c = match resolver {
Resolver::Grass => {
self.biomes
.grass(biome, f64::from(bx + x + dx), f64::from(bz + z + dz))
}
Resolver::Foliage => self.biomes.get(biome).foliage,
Resolver::Dry => self.biomes.get(biome).dry_foliage,
Resolver::Water => self.biomes.get(biome).water,
};
red += c >> 16 & 255;
green += c >> 8 & 255;
blue += c & 255;
}
}
let n = ((2 * r + 1) * (2 * r + 1)) as u32;
let color = (red / n) << 16 | (green / n) << 8 | (blue / n);
layer.colors[resolver as usize][slot] = color;
color
}
}
/// Packs 8-bit RGB into the vertex's RGBA8 (red in the low byte), opaque.
fn pack_rgb([r, g, b]: [u32; 3]) -> u32 {
@@ -464,6 +538,14 @@ pub struct Mesher<'a> {
pub tables: &'a MeshTables,
pub biomes: &'a Biomes,
pub visibility: FaceVisibility,
/// The client's biome zoom (the hashed world seed `BiomeManager` holds).
pub zoom: BiomeZoom,
/// The `biomeBlendRadius` option, 0 to 7.
pub blend_radius: i32,
/// The `ao` option: smooth lighting for models that allow it.
pub smooth_lighting: bool,
/// The `cutoutLeaves` option (fancy graphics); off makes leaves opaque.
pub cutout_leaves: bool,
}
impl Mesher<'_> {
/// `region[dz][dx]` are the chunks around the meshed column (centre 1,1).
@@ -477,7 +559,13 @@ impl Mesher<'_> {
let pad = Padded::new(region, sy);
out.visibility = visibility(&pad, &self.tables.info);
let base_y = MIN_Y + sy * 16;
let colors = blend(region, self.biomes, center.x, center.z, base_y + 8);
let mut tints = Tints::new(
region,
self.biomes,
self.zoom,
self.blend_radius,
[center.x, center.z, base_y],
);
let info = &self.tables.info;
for y in 0..16 {
for z in 0..16 {
@@ -502,7 +590,7 @@ impl Mesher<'_> {
continue;
}
if state.fluid.kind() != FluidKind::Empty {
let water = colors.water[(z * 16 + x) as usize];
let water = tints.get(Resolver::Water, x, y, z);
let nether = self.nether_shading;
fluid::tesselate(self.tables, nether, &pad, water, &mut out, [x, y, z]);
}
@@ -522,7 +610,7 @@ impl Mesher<'_> {
let Some((_, first)) = models.first() else {
continue;
};
let ao = state.emission == 0 && first.ambient_occlusion;
let ao = self.smooth_lighting && state.emission == 0 && first.ambient_occlusion;
let origin = match offset(state, world.x, world.z) {
Some(o) => [
x as f32 + o[0] as f32,
@@ -544,13 +632,26 @@ impl Mesher<'_> {
true,
)
.unwrap_or(true);
// LeavesBlock.skipRendering with opaque leaves.
if !self.cutout_leaves && state.leaves && info[neighbor as usize].leaves {
visible[d as usize] = false;
}
}
for (_, model) in &models {
for face in &model.faces {
if face.quad.cull.is_some_and(|d| !visible[d as usize]) {
continue;
}
self.face(&pad, &colors, &mut out, [x, y, z], origin, face, ao, state);
self.face(
&pad,
&mut tints,
&mut out,
[x, y, z],
origin,
face,
ao,
state,
);
}
}
}
@@ -559,18 +660,17 @@ impl Mesher<'_> {
out
}
/// `BlockColors` tint source `index`, or `None` for an untinted (-1) layer.
fn tint(state: &Info, index: i32, colors: &Colors, x: i32, z: i32) -> Option<u32> {
fn tint(state: &Info, index: i32, tints: &mut Tints, [x, y, z]: [i32; 3]) -> Option<u32> {
if index < 0 || index >= i32::from(state.tint_count) {
return None;
}
let column = (z * 16 + x) as usize;
Some(match state.tints[(index as usize).min(1)] {
Tint::None => return None,
Tint::Grass => colors.grass[column],
Tint::TallGrassUpper => colors.tall_upper[column],
Tint::Foliage => colors.foliage[column],
Tint::DryFoliage => colors.dry[column],
Tint::Water => colors.water[column],
Tint::Grass => tints.get(Resolver::Grass, x, y, z),
Tint::TallGrassUpper => tints.get(Resolver::Grass, x, y, z),
Tint::Foliage => tints.get(Resolver::Foliage, x, y, z),
Tint::DryFoliage => tints.get(Resolver::Dry, x, y, z),
Tint::Water => tints.get(Resolver::Water, x, y, z),
Tint::Constant(c) => c,
Tint::Redstone(p) => redstone_color(p),
Tint::Stem(age) => {
@@ -583,7 +683,7 @@ impl Mesher<'_> {
fn face(
&self,
pad: &Padded,
colors: &Colors,
tints: &mut Tints,
out: &mut SectionMesh,
pos: [i32; 3],
origin: [f32; 3],
@@ -608,7 +708,7 @@ impl Mesher<'_> {
};
([lighting::gray(directional); 4], [coords; 4])
};
let tint = Self::tint(state, q.tint_index, colors, pos[0], pos[2]);
let tint = Self::tint(state, q.tint_index, tints, pos);
let target = if face.translucent {
&mut out.translucent
} else {
@@ -624,7 +724,12 @@ impl Mesher<'_> {
target.push(Vertex {
pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]],
uv: q.uv[i],
layer: face.layer,
// Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout.
layer: if !self.cutout_leaves && state.leaves {
face.layer | OPAQUE_LAYER
} else {
face.layer
},
color: pack_rgb(rgb),
light: pack_coords(lighting::with_emission(coords[i], q.light_emission)),
});
+27
View File
@@ -27,6 +27,7 @@ pub mod guardian;
pub mod happy_ghast;
pub mod hostile;
pub mod illager;
pub mod illusioner;
pub mod keyframes;
pub mod leash;
pub mod living;
@@ -452,6 +453,9 @@ pub struct Extra {
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
pub pick_up_loot: bool,
pub saddled: bool,
/// The saddle's components (name, enchantments...) when it is not a bare
/// one; `saddled` stays the gameplay flag.
pub saddle_stack: Option<crate::items::ItemStack>,
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
pub items: Vec<Option<crate::items::ItemStack>>,
@@ -488,6 +492,8 @@ pub struct Extra {
pub vector: [f64; 3],
/// Active status effects: (effect id, ticks left, amplifier).
pub effects: Vec<(&'static str, i32, i32)>,
/// An invisible illusioner's mirror images.
pub illusions: Option<illusioner::Illusions>,
/// A villager's claimed bed head and meeting bell.
pub bed: Option<[i32; 3]>,
pub meeting: Option<[i32; 3]>,
@@ -887,6 +893,8 @@ pub struct MobWorld<'a> {
pub biomes: &'a crate::biome::Biomes,
/// The `mob_griefing` game rule.
pub mob_griefing: bool,
/// `getCurrentDifficultyAt` near the player.
pub difficulty: spawning::LocalDifficulty,
}
impl Mob {
pub fn new(id: u32, kind: Arc<MobType>, position: Vec3, yaw: f32) -> Self {
@@ -1222,3 +1230,22 @@ pub fn render_model(
}
}
}
impl Mob {
/// The saddle worn, with its components.
pub fn saddle_item(&self) -> Option<crate::items::ItemStack> {
self.extra.saddled.then(|| {
self.extra
.saddle_stack
.clone()
.unwrap_or_else(|| crate::items::ItemStack::new("minecraft:saddle", 1))
})
}
/// Wear (or take off) a saddle stack, keeping its components.
pub fn set_saddle(&mut self, saddle: Option<crate::items::ItemStack>) {
self.extra.saddled = saddle.is_some();
self.extra.saddle_stack = saddle
.map(|s| crate::items::ItemStack { count: 1, ..s })
.filter(|s| s.damage != 0 || s.extra.is_some());
}
}
+5 -1
View File
@@ -122,7 +122,7 @@ pub fn family(s: Species) -> Family {
S::Wolf | S::Cat => Family::Tame,
S::Blaze | S::Ghast => Family::Nether,
S::IronGolem | S::SnowGolem => Family::Golem,
S::Pillager | S::Vindicator | S::Evoker => Family::Illager,
S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => Family::Illager,
S::Vex => Family::Vex,
S::Ravager => Family::Ravager,
S::Wither => Family::Wither,
@@ -168,6 +168,7 @@ pub fn register(m: &mut Mob) {
Family::Golem => super::golem::register_snow(m),
Family::Illager if m.species() == Species::Pillager => super::illager::register_pillager(m),
Family::Illager if m.species() == Species::Evoker => super::illager::register_evoker(m),
Family::Illager if m.species() == Species::Illusioner => super::illusioner::register(m),
Family::Illager => super::illager::register_vindicator(m),
Family::Equine => super::equine::register(m),
Family::Phantom => super::phantom::register(m),
@@ -383,6 +384,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
}
tick_effects(m);
if m.species() == Species::Illusioner {
super::illusioner::tick(m, events);
}
if m.hurt_time > 0 {
m.hurt_time -= 1;
}
+23 -2
View File
@@ -20,6 +20,7 @@ fn raider(s: Species) -> bool {
| Species::Vindicator
| Species::Witch
| Species::Evoker
| Species::Illusioner
| Species::Ravager
)
}
@@ -30,6 +31,7 @@ fn targets(m: &mut Mob, villagers_seen: bool) {
Species::Vindicator,
Species::Witch,
Species::Evoker,
Species::Illusioner,
Species::Vex,
Species::Ravager,
];
@@ -95,7 +97,7 @@ enum Spell {
/// `SpellcasterCastingSpellGoal`: stand still facing the target while a
/// spell is cast.
#[derive(Clone, Debug)]
struct CastingSpell;
pub(super) struct CastingSpell;
impl Goal for CastingSpell {
goal_clone!();
fn flags(&self) -> u8 {
@@ -542,6 +544,7 @@ enum ArmPose {
Attacking,
CrossbowHold,
CrossbowCharge,
Bow,
}
/// `Pillager` / `Vindicator.getArmPose`.
fn arm_pose(m: &Mob) -> ArmPose {
@@ -557,6 +560,9 @@ fn arm_pose(m: &Mob) -> ArmPose {
ArmPose::Neutral
}
}
Species::Illusioner if m.extra.variant2 != 0 => ArmPose::Spellcasting,
Species::Illusioner if m.ai.aggressive => ArmPose::Bow,
Species::Illusioner => ArmPose::Crossed,
Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting,
Species::Evoker if celebrating(m) => ArmPose::Celebrating,
Species::Evoker => ArmPose::Crossed,
@@ -576,7 +582,11 @@ fn celebrating(m: &Mob) -> bool {
}
/// Whether the held item shows (vindicators only draw their axe when angry).
pub fn shows_item(m: &Mob) -> bool {
m.species() != Species::Vindicator || m.ai.aggressive
match m.species() {
Species::Vindicator => m.ai.aggressive,
Species::Illusioner => m.extra.variant2 != 0 || m.ai.aggressive,
_ => true,
}
}
fn hide(p: &mut Poses, part: &str) {
if p.has(part) {
@@ -600,6 +610,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.zrot("left_arm", 0.0);
p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp * 0.5);
p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp * 0.5);
// IllagerModel hides the hat; the illusioner's renderer shows it.
if m.species() != Species::Illusioner {
hide(p, "hat");
}
let pose = arm_pose(m);
match pose {
ArmPose::Attacking => {
@@ -638,6 +652,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
bob(p, "right_arm", 1.0);
bob(p, "left_arm", -1.0);
}
ArmPose::Bow => {
p.yrot("right_arm", -0.1 + hy);
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -0.942_477_9 + hx);
p.yrot("left_arm", hy - 0.4);
p.zrot("left_arm", PI / 2.0);
}
ArmPose::CrossbowHold => {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
@@ -0,0 +1,235 @@
//! The illusioner (`Illusioner`): a bow-wielding spellcaster that turns
//! invisible behind four mirror images and blinds its target.
use super::{
Mob, MobEvent, Species, Who,
goals::{
Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Stroll,
goal_clone, reduced,
},
illager::CastingSpell,
undead::BowAttack,
};
use horizon_core::random::RandomSource;
const INVISIBILITY: &str = "minecraft:invisibility";
const BLINDNESS: &str = "minecraft:blindness";
/// `Illusioner.NUM_ILLUSIONS`.
pub const COPIES: usize = 4;
/// `Illusioner.clientSideIllusionTicks` and the two offset sets.
#[derive(Clone, Debug, Default)]
pub struct Illusions {
pub ticks: i32,
pub offsets: [[[f64; 3]; COPIES]; 2],
}
pub const MIRROR: u8 = 5;
pub const BLINDNESS_SPELL: u8 = 4;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, CastingSpell);
g.add(
3,
AvoidEntity::new(Avoid::Species(vec![Species::Creaking]), 8.0, 1.0, 1.2),
);
g.add(4, Spell::new(MIRROR));
g.add(5, Spell::new(BLINDNESS_SPELL));
g.add(6, BowAttack::new(0.5, 20, 15.0));
g.add(8, Stroll::new(0.6));
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
g.add(10, LookAtPlayer::new(8.0));
let mut hurt = HurtByTarget::new().alert();
hurt.ignore = vec![
Species::Pillager,
Species::Vindicator,
Species::Witch,
Species::Evoker,
Species::Illusioner,
Species::Vex,
Species::Ravager,
];
m.ai.targets.add(1, hurt);
m.ai.targets.add(2, NearestTarget::player(true));
m.ai.targets.add(
3,
NearestTarget::species(&[Species::Villager, Species::WanderingTrader], false),
);
m.ai.targets
.add(3, NearestTarget::species(&[Species::IronGolem], false));
}
/// `Illusioner.finalizeSpawn`: a bow in the main hand.
pub fn finalize(m: &mut Mob) {
m.extra.main_hand = Some("minecraft:bow".into());
}
/// `IllusionerMirrorSpellGoal` and `IllusionerBlindnessSpellGoal`.
#[derive(Clone, Debug)]
struct Spell {
spell: u8,
warmup: i32,
next: i64,
last_target: Option<Who>,
}
impl Spell {
fn new(spell: u8) -> Self {
Self {
spell,
warmup: 0,
next: 0,
last_target: None,
}
}
/// (casting time, interval, prepare sound).
fn timing(&self) -> (i32, i64, &'static str) {
if self.spell == MIRROR {
(20, 340, "entity.illusioner.prepare_mirror")
} else {
(20, 180, "entity.illusioner.prepare_blindness")
}
}
}
impl Goal for Spell {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !m.target_info(cx.w).is_some_and(|t| t.alive)
|| m.extra.counter > 0
|| i64::from(m.age) < self.next
{
return false;
}
if self.spell == MIRROR {
!m.has_effect(INVISIBILITY)
} else {
m.ai.target != self.last_target && cx.w.difficulty.effective > 2.0
}
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.target_info(cx.w).is_some_and(|t| t.alive) && self.warmup > 0
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
let (casting, interval, sound) = self.timing();
self.warmup = reduced(20);
m.extra.counter = casting;
self.next = i64::from(m.age) + interval;
cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0));
m.extra.variant2 = self.spell;
if self.spell == BLINDNESS_SPELL {
self.last_target = m.ai.target;
}
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.warmup -= 1;
if self.warmup != 0 {
return;
}
if self.spell == MIRROR {
m.add_effect(INVISIBILITY, 1200, 0);
} else if m.ai.target == Some(Who::Player) {
cx.events.push(MobEvent::EffectPlayer {
effect: BLINDNESS,
ticks: 400,
amplifier: 0,
});
}
cx.events.push(MobEvent::Sound(
"entity.illusioner.cast_spell",
m.center(),
1.0,
1.0,
));
}
}
/// The client-side half of `Illusioner.aiStep`: new image offsets when
/// hurt and once a minute, with a puff of cloud and a sound.
pub fn tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
if !m.has_effect(INVISIBILITY) {
return;
}
let hurt = m.hurt_time;
let age = m.age;
let mut il = m.extra.illusions.take().unwrap_or_default();
il.ticks = (il.ticks - 1).max(0);
if hurt == 1 || age.is_multiple_of(1200) {
il.ticks = 3;
for i in 0..COPIES {
il.offsets[0][i] = il.offsets[1][i];
let r = &mut m.random;
let x = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
let y = (r.next_int_bound(6).unwrap_or(0) - 4).max(0) as f64;
let z = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5;
il.offsets[1][i] = [x, y, z];
}
events.push(MobEvent::Particles {
kind: "minecraft:cloud",
at: [m.position.x, m.position.y + 0.9, m.position.z],
count: 16,
});
events.push(MobEvent::Sound(
"entity.illusioner.mirror_move",
m.center(),
1.0,
1.0,
));
} else if hurt == 9 {
il.ticks = 3;
for i in 0..COPIES {
il.offsets[0][i] = il.offsets[1][i];
il.offsets[1][i] = [0.0; 3];
}
}
m.extra.illusions = Some(il);
}
/// `Illusioner.getIllusionOffsets`.
pub fn offsets(m: &Mob, partial: f32) -> [[f64; 3]; COPIES] {
let Some(il) = &m.extra.illusions else {
return [[0.0; 3]; COPIES];
};
if il.ticks <= 0 {
return il.offsets[1];
}
let scale = (f64::from(il.ticks as f32 - partial) / 3.0).powf(0.25);
let mut out = [[0.0; 3]; COPIES];
for (i, o) in out.iter_mut().enumerate() {
for k in 0..3 {
o[k] = il.offsets[1][i][k] * (1.0 - scale) + il.offsets[0][i][k] * scale;
}
}
out
}
/// The wobble `IllusionerRenderer.submit` adds to each image.
pub fn wobble(i: usize, age: f32) -> [f64; 3] {
let i = i as f32;
[
f64::from((i + age * 0.5).cos()) * 0.025,
f64::from((i + age * 0.75).cos()) * 0.0125,
f64::from((i + age * 0.7).cos()) * 0.025,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn settled_offsets_are_the_new_set() {
let il = Illusions {
ticks: 0,
offsets: [[[1.0; 3]; COPIES], [[2.0; 3]; COPIES]],
};
let mut v = [[0.0; 3]; COPIES];
v.copy_from_slice(&il.offsets[1]);
assert_eq!(v[0], [2.0; 3]);
}
#[test]
fn wobble_is_small() {
assert!(wobble(1, 10.0).iter().all(|c| c.abs() <= 0.025));
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ fn is_zombie(s: &Seen) -> bool {
pub fn is_illager(s: &Seen) -> bool {
matches!(
s.species,
Species::Pillager | Species::Vindicator | Species::Evoker
Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner
)
}
pub fn register(m: &mut Mob) {
+1
View File
@@ -57,6 +57,7 @@ pub fn is_raider(s: Species) -> bool {
Species::Pillager
| Species::Vindicator
| Species::Evoker
| Species::Illusioner
| Species::Witch
| Species::Ravager
)
+2 -1
View File
@@ -25,6 +25,7 @@ pub fn register(m: &mut Mob) {
Species::Pillager,
Species::Vindicator,
Species::Evoker,
Species::Illusioner,
Species::Witch,
Species::Ravager,
];
@@ -180,7 +181,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
let illager = matches!(
s.species,
Species::Pillager | Species::Vindicator | Species::Evoker
Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner
);
if !illager {
events.push(MobEvent::AttackMob {
+24 -1
View File
@@ -822,10 +822,33 @@ pub fn render_with(
extra: &[(&Part, [f32; 4], u32)],
out: &mut Vec<Vertex>,
) {
// The invisibility effect hides the model (a drinking wandering trader).
// The invisibility effect hides the model (a drinking wandering trader);
// an illusioner shows its four mirror images instead.
if super::trader::is_invisible(m) {
if m.species() == Species::Illusioner {
let age = m.age as f32 + alpha;
for (i, off) in super::illusioner::offsets(m, alpha).iter().enumerate() {
let w = super::illusioner::wobble(i, age);
let shifted =
camera - glam::DVec3::new(off[0] + w[0], off[1] + w[1], off[2] + w[2]);
render_visible(m, alpha, shifted, atlas, light, data, extra, out);
}
}
return;
}
render_visible(m, alpha, camera, atlas, light, data, extra, out);
}
#[allow(clippy::too_many_arguments)]
fn render_visible(
m: &Mob,
alpha: f32,
camera: glam::DVec3,
atlas: Atlas,
light: u32,
data: &MobData,
extra: &[(&Part, [f32; 4], u32)],
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
+1 -1
View File
@@ -48,7 +48,7 @@ pub fn vehicle_attachment(r: &Mob) -> f64 {
| S::Bogged
| S::Parched
| S::WitherSkeleton => 0.7,
S::Pillager | S::Vindicator | S::Evoker => 0.6,
S::Pillager | S::Vindicator | S::Evoker | S::Illusioner => 0.6,
_ => 0.0,
}
}
@@ -397,6 +397,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
m.extra.main_hand = Some("minecraft:golden_axe".into());
m.extra.pick_up_loot = true;
}
S::Illusioner => super::illusioner::finalize(m),
S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()),
S::Villager => {
m.extra.variant = villager_type(biome);
+16
View File
@@ -78,6 +78,7 @@ pub enum Species {
ElderGuardian,
Shulker,
Evoker,
Illusioner,
Vex,
Ravager,
Wither,
@@ -905,6 +906,20 @@ pub const ALL: &[Def] = &[
None,
Baby::None
),
def!(
Illusioner,
"illusioner",
"illusioner#main",
"entity/illager/illusioner",
A::Illager,
[
"entity.illusioner.ambient",
"entity.illusioner.hurt",
"entity.illusioner.death"
],
None,
Baby::None
),
def!(
Allay,
"allay",
@@ -1435,6 +1450,7 @@ impl Def {
| S::ElderGuardian
| S::Shulker
| S::Evoker
| S::Illusioner
| S::Vex
| S::Ravager
| S::Wither
+1
View File
@@ -44,6 +44,7 @@ pub fn register(m: &mut Mob) {
for (species, distance) in [
(Species::Zombie, 8.0),
(Species::Evoker, 12.0),
(Species::Illusioner, 12.0),
(Species::Vindicator, 8.0),
(Species::Vex, 8.0),
(Species::Pillager, 15.0),
+1
View File
@@ -32,6 +32,7 @@ pub fn register(m: &mut Mob) {
Species::Pillager,
Species::Vindicator,
Species::Evoker,
Species::Illusioner,
Species::Witch,
Species::Vex,
];
+2 -1
View File
@@ -63,6 +63,7 @@ pub fn register(m: &mut Mob) {
Species::Pillager,
Species::Vindicator,
Species::Evoker,
Species::Illusioner,
Species::Ravager,
Species::Zoglin,
];
@@ -1217,7 +1218,7 @@ fn hostile_range(s: Species) -> f64 {
| Species::Vex
| Species::Zombie
| Species::ZombieVillager => 8.0,
Species::Evoker | Species::Ravager => 12.0,
Species::Evoker | Species::Illusioner | Species::Ravager => 12.0,
Species::Pillager => 15.0,
Species::Vindicator | Species::Zoglin => 10.0,
_ => 0.0,
+314
View File
@@ -0,0 +1,314 @@
//! Mouse look and scrolling of 26.3: `MouseHandler` (accumulated movement,
//! sensitivity curve, cinematic smoothing, inversion), `SmoothDouble`,
//! `ScrollWheelHandler` and `Entity.turn`.
/// `SmoothDouble`.
#[derive(Clone, Debug, Default)]
pub struct SmoothDouble {
target_value: f64,
remaining_value: f64,
last_amount: f64,
}
impl SmoothDouble {
pub fn get_new_delta_value(&mut self, target_delta: f64, time: f64) -> f64 {
self.target_value += target_delta;
let mut delta = self.target_value - self.remaining_value;
let new_last_amount = self.last_amount + 0.5 * (delta - self.last_amount);
let delta_sign = java_signum(delta);
if delta_sign * delta > delta_sign * self.last_amount {
delta = new_last_amount;
}
self.last_amount = new_last_amount;
self.remaining_value += delta * time;
delta * time
}
pub fn reset(&mut self) {
*self = Self::default();
}
}
/// `Math.signum(double)`.
pub fn java_signum(v: f64) -> f64 {
if v == 0.0 || v.is_nan() {
v
} else {
v.signum()
}
}
/// `ScrollWheelHandler`.
#[derive(Clone, Debug, Default)]
pub struct ScrollWheelHandler {
accumulated_x: f64,
accumulated_y: f64,
}
impl ScrollWheelHandler {
/// `onMouseScroll`: whole wheel steps `(x, y)` once enough has accumulated.
pub fn on_mouse_scroll(&mut self, x: f64, y: f64) -> (i32, i32) {
if self.accumulated_x != 0.0 && java_signum(x) != java_signum(self.accumulated_x) {
self.accumulated_x = 0.0;
}
if self.accumulated_y != 0.0 && java_signum(y) != java_signum(self.accumulated_y) {
self.accumulated_y = 0.0;
}
self.accumulated_x += x;
self.accumulated_y += y;
// Java's double-to-int cast saturates and maps NaN to zero, like Rust's.
let wheel_x = self.accumulated_x as i32;
let wheel_y = self.accumulated_y as i32;
if wheel_x == 0 && wheel_y == 0 {
return (0, 0);
}
self.accumulated_x -= f64::from(wheel_x);
self.accumulated_y -= f64::from(wheel_y);
(wheel_x, wheel_y)
}
/// `getNextScrollWheelSelection`.
pub fn next_selection(wheel: f64, current_selected: i32, limit: i32) -> i32 {
let step = java_signum(wheel) as i32;
let mut current = (current_selected - step).max(-1);
while current < 0 {
current += limit;
}
while current >= limit {
current -= limit;
}
current
}
}
/// Entity rotation as `Entity.turn` keeps it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rotation {
pub x_rot: f32,
pub y_rot: f32,
pub x_rot_o: f32,
pub y_rot_o: f32,
}
impl Rotation {
fn set_x_rot(&mut self, x_rot: f32) {
if x_rot.is_finite() {
self.x_rot = (x_rot % 360.0).clamp(-90.0, 90.0);
}
}
fn set_y_rot(&mut self, y_rot: f32) {
if y_rot.is_finite() {
self.y_rot = y_rot;
}
}
/// `Entity.turn(xo, yo)`: mouse deltas in, 0.15 degrees per unit, pitch clamped.
pub fn turn(&mut self, xo: f64, yo: f64) {
let x_delta = (yo as f32) * 0.15;
let y_delta = (xo as f32) * 0.15;
self.set_x_rot(self.x_rot + x_delta);
self.set_y_rot(self.y_rot + y_delta);
self.set_x_rot(mth_clamp(self.x_rot, -90.0, 90.0));
self.x_rot_o += x_delta;
self.y_rot_o += y_delta;
self.x_rot_o = mth_clamp(self.x_rot_o, -90.0, 90.0);
}
}
/// `Mth.clamp(float, float, float)`.
pub fn mth_clamp(value: f32, min: f32, max: f32) -> f32 {
if value < min {
min
} else if value.is_nan() || max.is_nan() {
f32::NAN
} else {
value.min(max)
}
}
/// The options `turnPlayer` reads.
#[derive(Clone, Copy, Debug)]
pub struct LookOptions {
pub sensitivity: f64,
pub smooth_camera: bool,
/// First-person camera and the player is scoping (spyglass).
pub scoping: bool,
pub invert_x: bool,
pub invert_y: bool,
}
/// The input state of `MouseHandler` that drives the camera and the hotbar.
#[derive(Clone, Debug)]
pub struct MouseLook {
xpos: f64,
ypos: f64,
ignore_first_move: bool,
smooth_turn_x: SmoothDouble,
smooth_turn_y: SmoothDouble,
accumulated_dx: f64,
accumulated_dy: f64,
pub scroll: ScrollWheelHandler,
last_handle_movement_time: f64,
}
impl Default for MouseLook {
fn default() -> Self {
Self {
xpos: 0.0,
ypos: 0.0,
ignore_first_move: true,
smooth_turn_x: SmoothDouble::default(),
smooth_turn_y: SmoothDouble::default(),
accumulated_dx: 0.0,
accumulated_dy: 0.0,
scroll: ScrollWheelHandler::default(),
// Double.MIN_VALUE
last_handle_movement_time: 4.9e-324,
}
}
}
impl MouseLook {
/// `setIgnoreFirstMove`.
pub fn set_ignore_first_move(&mut self) {
self.ignore_first_move = true;
}
/// `onMove`: relative motion counts while the pointer is grabbed, absolute
/// motion otherwise.
pub fn on_move(
&mut self,
xpos: f64,
ypos: f64,
xrel: f64,
yrel: f64,
window_active: bool,
grabbed: bool,
) {
if self.ignore_first_move {
self.xpos = xpos;
self.ypos = ypos;
self.ignore_first_move = false;
} else {
if window_active {
if grabbed {
self.accumulated_dx += xrel;
self.accumulated_dy += yrel;
} else {
self.accumulated_dx += xpos - self.xpos;
self.accumulated_dy += ypos - self.ypos;
}
}
self.xpos = xpos;
self.ypos = ypos;
}
}
/// Movement accumulated since the last frame (for screens' mouse-moved events).
pub fn accumulated(&self) -> (f64, f64) {
(self.accumulated_dx, self.accumulated_dy)
}
/// `handleAccumulatedMovement` for a frame at `time` seconds: the
/// `(xo, yo)` passed to `Entity.turn` when the pointer is grabbed and the
/// window is active. The accumulators are cleared either way.
pub fn handle_accumulated_movement(
&mut self,
time: f64,
window_active: bool,
grabbed_with_player: bool,
look: LookOptions,
) -> Option<(f64, f64)> {
let mousea = time - self.last_handle_movement_time;
self.last_handle_movement_time = time;
let turn = (window_active && grabbed_with_player).then(|| self.turn_player(mousea, look));
self.accumulated_dx = 0.0;
self.accumulated_dy = 0.0;
turn
}
fn turn_player(&mut self, mousea: f64, look: LookOptions) -> (f64, f64) {
let ss = look.sensitivity * f64::from(0.6f32) + f64::from(0.2f32);
let sensitivity_mod = ss * ss * ss;
let sens = sensitivity_mod * 8.0;
let (xo, yo) = if look.smooth_camera {
(
self.smooth_turn_x
.get_new_delta_value(self.accumulated_dx * sens, mousea * sens),
self.smooth_turn_y
.get_new_delta_value(self.accumulated_dy * sens, mousea * sens),
)
} else if look.scoping {
self.smooth_turn_x.reset();
self.smooth_turn_y.reset();
(
self.accumulated_dx * sensitivity_mod,
self.accumulated_dy * sensitivity_mod,
)
} else {
self.smooth_turn_x.reset();
self.smooth_turn_y.reset();
(self.accumulated_dx * sens, self.accumulated_dy * sens)
};
(
if look.invert_x { -xo } else { xo },
if look.invert_y { -yo } else { yo },
)
}
/// `onScroll` for the in-game case (no screen, player present): the wheel
/// value `wheel` the hotbar or spectator speed reacts to, and the raw
/// wheel steps. `None` when no whole step has accumulated.
pub fn on_scroll(
&mut self,
xoffset: f64,
yoffset: f64,
discrete: bool,
wheel_sensitivity: f64,
) -> Option<(i32, (i32, i32))> {
let scale = |v: f64| (if discrete { java_signum(v) } else { v }) * wheel_sensitivity;
let (x, y) = self.scroll.on_mouse_scroll(scale(xoffset), scale(yoffset));
if x == 0 && y == 0 {
return None;
}
let wheel = if y == 0 { -x } else { y };
Some((wheel, (x, y)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_sensitivity_turns_point_fifteen_degrees_per_count_at_one() {
let mut look = MouseLook::default();
look.on_move(0.0, 0.0, 0.0, 0.0, true, true);
look.on_move(1.0, 0.0, 1.0, 0.0, true, true);
let (xo, _) = look
.handle_accumulated_movement(
1.0,
true,
true,
LookOptions {
sensitivity: 0.5,
smooth_camera: false,
scoping: false,
invert_x: false,
invert_y: false,
},
)
.unwrap();
let mut rot = Rotation {
x_rot: 0.0,
y_rot: 0.0,
x_rot_o: 0.0,
y_rot_o: 0.0,
};
rot.turn(xo, 0.0);
assert!((rot.y_rot - 0.15 * 1.0).abs() < 1e-6, "{}", rot.y_rot);
}
#[test]
fn scroll_accumulates_fractions() {
let mut look = MouseLook::default();
assert_eq!(look.on_scroll(0.0, 0.4, false, 1.0), None);
assert_eq!(look.on_scroll(0.0, 0.7, false, 1.0), Some((1, (0, 1))));
}
}
+69 -12
View File
@@ -3,6 +3,7 @@
//! Disconnected screen. Entries are pinged in the background like
//! ServerStatusPinger to show the MOTD, player count and latency.
use crate::hud::{HudAtlas, HudBatch, rgba};
use crate::lan::discovery::Scanner;
use horizon_protocol::servers::{self, ServerEntry};
use std::{
collections::HashMap,
@@ -31,6 +32,8 @@ pub enum Screen {
servers: Vec<ServerEntry>,
selected: Option<usize>,
pings: Pings,
/// Worlds announced on the local network, listed after the servers.
lan: Scanner,
},
/// Add (index None) or edit a server entry.
Edit {
@@ -92,6 +95,18 @@ fn ping_all(servers: &[ServerEntry], pings: &Pings) {
}
}
/// The address of list row `index`: the saved servers, then the LAN games.
fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option<String> {
match servers.get(index) {
Some(s) => Some(s.ip.clone()),
None => lan
.games()
.into_iter()
.nth(index - servers.len())
.map(|g| g.address),
}
}
impl Screen {
pub fn list(saves: &Path) -> Self {
let servers = servers::load(&servers_file(saves));
@@ -101,6 +116,7 @@ impl Screen {
servers,
selected: None,
pings,
lan: Scanner::start(),
}
}
pub fn buttons(&self, w: f32, h: f32) -> Vec<ButtonSpec> {
@@ -256,6 +272,7 @@ impl Screen {
servers,
selected,
pings,
lan,
} => {
centered(batch, "Play Multiplayer", 8.0, u32::MAX);
batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100));
@@ -319,6 +336,42 @@ impl Screen {
);
}
}
for (k, game) in lan.games().iter().enumerate() {
let i = servers.len() + k;
let y = 36.0 + i as f32 * 36.0;
if y + 36.0 > h - 64.0 {
break;
}
let x = w / 2.0 - 152.0;
if *selected == Some(i) {
batch.fill(
atlas,
x - 2.0,
y - 2.0,
306.0,
36.0,
rgba(128, 128, 128, 255),
);
batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255));
}
batch.text(atlas, "LAN World", x + 35.0, y + 1.0, u32::MAX, false);
batch.text(
atlas,
&game.motd,
x + 35.0,
y + 12.0,
rgba(128, 128, 128, 255),
false,
);
batch.text(
atlas,
&game.address,
x + 35.0,
y + 22.0,
rgba(96, 96, 96, 255),
false,
);
}
if servers.is_empty() {
centered(
batch,
@@ -392,12 +445,15 @@ impl Screen {
match (&mut *self, id) {
(
Self::List {
servers, selected, ..
servers,
selected,
lan,
..
},
Some(40),
) => {
if let Some(s) = selected.and_then(|i| servers.get(i)) {
return Outcome::Connect(s.ip.clone());
if let Some(address) = selected.and_then(|i| entry_address(servers, lan, i)) {
return Outcome::Connect(address);
}
}
(Self::List { .. }, Some(41)) => {
@@ -446,21 +502,22 @@ impl Screen {
(Self::List { .. }, Some(46)) => return Outcome::Back,
(
Self::List {
servers, selected, ..
servers,
selected,
lan,
..
},
None,
) => {
let index = ((y - 36.0) / 36.0).floor();
if y >= 36.0
&& y < h - 64.0
&& (x - w / 2.0).abs() < 154.0
&& (index as usize) < servers.len()
{
if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 {
let index = index as usize;
if *selected == Some(index) {
return Outcome::Connect(servers[index].ip.clone());
if let Some(address) = entry_address(servers, lan, index) {
if *selected == Some(index) {
return Outcome::Connect(address);
}
*selected = Some(index);
}
*selected = Some(index);
}
}
(
+719
View File
@@ -0,0 +1,719 @@
//! `options.txt` exactly as `Options.load`/`Options.save` handle it in 26.3:
//! the processing order, per-option codecs and validation (`OptionInstance`),
//! plain fields, key mappings, sound volumes and model parts. Typed access for
//! the game lives in `settings`.
use crate::{
java_text::{self, Json},
key_names,
};
use std::sync::LazyLock;
/// A stored option value.
#[derive(Clone, Debug, PartialEq)]
pub enum V {
Bool(bool),
Int(i32),
Double(f64),
Str(String),
List(Vec<String>),
}
/// How an `OptionInstance` decodes, validates and encodes its value.
#[derive(Clone, Copy, Debug)]
pub enum Spec {
/// `Codec.BOOL`.
Bool,
/// `IntRange(min, max)`: codec `intRange(min, max + 1)`, validated to `max`.
Int(i32, i32),
/// `ClampingLazyMaxIntRange(min, ..)` while the game is not running.
LazyInt(i32),
/// `IntRange(imin, imax).xmap(i / k, (int)(v * k))` with `doubleRange(lo, hi)`.
Scaled(i32, i32, f64, f64, f64),
/// The frame rate limit: `IntRange(1, 26).xmap(i * 10, v / 10)`, codec 10..=260.
FrameLimit,
/// Field of view degrees stored as `(fov - 70) / 40`.
Fov,
/// `IntRange(-200, 100).xmap(10^(i/100), floor(log10(v) * 100))`.
WheelSensitivity,
/// `UnitDouble`.
Unit,
/// `UnitDouble.xmap(square, sqrt)` with an explicit `doubleRange(0, 1)` codec.
UnitSquare,
/// `UnitDouble.xmap(square, sqrt)` using the value set's own codec.
UnitSquareImplicit,
/// String-represented enum.
Named(&'static [&'static str]),
/// Enum stored as its id, wrapping out-of-range ids.
Id(i32),
/// `CloudStatus` with the boolean alternative.
Clouds,
/// Any string (`LazyEnum` while the game is not running).
AnyStr,
}
#[derive(Clone, Copy, Debug)]
enum Kind {
Option(Spec),
PlainBool,
PlainInt,
PlainStr,
List,
Tutorial,
Key,
}
struct Def {
key: String,
kind: Kind,
default: V,
}
const TUTORIAL_STEPS: [&str; 6] = [
"movement",
"find_tree",
"punch_tree",
"open_inventory",
"craft_planks",
"none",
];
const MODEL_PARTS: [&str; 7] = [
"cape",
"jacket",
"left_sleeve",
"right_sleeve",
"left_pants_leg",
"right_pants_leg",
"hat",
];
const GRAPHICS_BACKEND: &[&str] = &["default", "opengl", "vulkan"];
const GRAPHICS_PRESET: &[&str] = &["fast", "fancy", "fabulous", "custom"];
const INACTIVITY: &[&str] = &["minimized", "afk"];
const CLOUDS: &[&str] = &["false", "fast", "true"];
const MAIN_HAND: &[&str] = &["left", "right"];
const PRESENCE: &[&str] = &["none", "limited", "all"];
const MUSIC_TOAST: &[&str] = &["never", "pause", "pause_and_toast"];
const MUSIC_FREQUENCY: &[&str] = &["DEFAULT", "FREQUENT", "CONSTANT"];
fn def(key: &str, kind: Kind, default: V) -> Def {
Def {
key: key.to_owned(),
kind,
default,
}
}
/// The processing order of `Options.processOptions`.
static TABLE: LazyLock<Vec<Def>> = LazyLock::new(|| {
use Kind::{List, Option as O, PlainBool as PB, PlainInt as PI, PlainStr as PS, Tutorial};
use Spec::{
AnyStr, Bool, Clouds, Fov, FrameLimit, Id, Int, LazyInt, Named, Scaled, Unit, UnitSquare,
UnitSquareImplicit, WheelSensitivity,
};
let b = |key: &str, d: bool| def(key, O(Bool), V::Bool(d));
let i = |key: &str, lo, hi, d: i32| def(key, O(Int(lo, hi)), V::Int(d));
let u = |key: &str, d: f64| def(key, O(Unit), V::Double(d));
let n =
|key: &str, names: &'static [&'static str], d: i32| def(key, O(Named(names)), V::Int(d));
let id = |key: &str, count: i32, d: i32| def(key, O(Id(count)), V::Int(d));
let pb = |key: &str, d: bool| def(key, PB, V::Bool(d));
let mut t = vec![
b("ao", true),
i("biomeBlendRadius", 0, 7, 2),
def(
"chunkSectionFadeInTime",
O(Scaled(0, 40, 20.0, 0.0, 2.0)),
V::Double(0.75),
),
b("cutoutLeaves", true),
b("enableVsync", true),
def(
"entityDistanceScaling",
O(Scaled(2, 20, 4.0, 0.5, 5.0)),
V::Double(1.0),
),
b("entityShadows", true),
b("forceUnicodeFont", false),
b("japaneseGlyphVariants", false),
def("fov", O(Fov), V::Int(70)),
def("fovEffectScale", O(UnitSquare), V::Double(1.0)),
def("darknessEffectScale", O(UnitSquareImplicit), V::Double(1.0)),
u("glintSpeed", 0.5),
u("glintStrength", 0.75),
n("preferredGraphicsBackend", GRAPHICS_BACKEND, 0),
n("graphicsPreset", GRAPHICS_PRESET, 1),
id("prioritizeChunkUpdates", 3, 0),
b("fullscreen", false),
b("exclusiveFullscreen", false),
b("macFullscreenMenuVisibility", false),
u("gamma", 0.5),
def("guiScale", O(LazyInt(0)), V::Int(0)),
def("debugGuiScale", O(LazyInt(-1)), V::Int(0)),
i("maxAnisotropyBit", 1, 3, 2),
id("textureFiltering", 3, 0),
def("maxFps", O(FrameLimit), V::Int(120)),
b("improvedTransparency", false),
n("inactivityFpsLimit", INACTIVITY, 1),
i("mipmapLevels", 0, 4, 4),
id("narrator", 4, 0),
id("particles", 3, 0),
b("reducedDebugInfo", false),
def("renderClouds", O(Clouds), V::Int(2)),
i("cloudRange", 2, 128, 128),
i("renderDistance", 2, 32, 12),
i("simulationDistance", 5, 32, 12),
u("screenEffectScale", 1.0),
def("soundDevice", O(AnyStr), V::Str(String::new())),
b("vignette", true),
i("weatherRadius", 3, 10, 10),
b("autoJump", false),
b("rotateWithMinecart", false),
b("operatorItemsTab", false),
b("autoSuggestions", true),
b("chatColors", true),
b("chatLinks", true),
b("chatLinksPrompt", true),
b("discrete_mouse_scroll", false),
b("invertXMouse", false),
b("invertYMouse", false),
b("realmsNotifications", true),
b("showSubtitles", false),
b("directionalAudio", false),
b("bobView", true),
b("toggleCrouch", false),
b("toggleSprint", false),
b("toggleAttack", false),
b("toggleUse", false),
i("sprintWindow", 0, 10, 7),
b("darkMojangStudiosBackground", false),
b("hideLightningFlashes", false),
b("hideSplashTexts", false),
u("mouseSensitivity", 0.5),
u("damageTiltStrength", 1.0),
b("highContrast", false),
b("highContrastBlockOutline", false),
b("narratorHotkey", true),
def("resourcePacks", List, V::List(Vec::new())),
def("incompatibleResourcePacks", List, V::List(Vec::new())),
def("lastServer", PS, V::Str(String::new())),
def("lang", PS, V::Str("en_us".into())),
id("chatVisibility", 3, 0),
u("chatOpacity", 1.0),
u("chatLineSpacing", 0.0),
u("textBackgroundOpacity", 0.5),
b("backgroundForChatOnly", true),
pb("hideServerAddress", false),
pb("advancedItemTooltips", false),
pb("pauseOnLostFocus", true),
def("overrideWidth", PI, V::Int(0)),
def("overrideHeight", PI, V::Int(0)),
u("chatHeightFocused", 1.0),
def(
"chatDelay",
O(Scaled(0, 60, 10.0, 0.0, 6.0)),
V::Double(0.0),
),
u("chatHeightUnfocused", 0.4375),
u("chatScale", 1.0),
u("chatWidth", 1.0),
def(
"notificationDisplayTime",
O(Scaled(5, 100, 10.0, 0.5, 10.0)),
V::Double(1.0),
),
pb("useNativeTransport", true),
n("mainHand", MAIN_HAND, 1),
id("attackIndicator", 3, 1),
def("tutorialStep", Tutorial, V::Int(0)),
def("mouseWheelSensitivity", O(WheelSensitivity), V::Double(1.0)),
b("allowCursorChanges", true),
b("quitShortcuts", true),
b("ctrlClickEmulatesRightClick", false),
def("glDebugVerbosity", PI, V::Int(1)),
pb("skipMultiplayerWarning", false),
b("hideMatchedNames", true),
pb("joinedFirstServer", false),
pb("syncChunkWrites", false),
b("showAutosaveIndicator", true),
b("allowServerListing", true),
b("inGameNotification", false),
n("sharePresence", PRESENCE, 2),
b("onlyShowSecureChat", false),
b("saveChatDrafts", false),
u("panoramaScrollSpeed", 1.0),
b("telemetryOptInExtra", false),
pb("onboardAccessibility", true),
i("menuBackgroundBlurriness", 0, 10, 5),
pb("startedCleanly", true),
n("musicToast", MUSIC_TOAST, 0),
n("musicFrequency", MUSIC_FREQUENCY, 0),
];
for (name, key, _) in crate::keybinds::MAPPINGS {
t.push(def(
&format!("key_{name}"),
Kind::Key,
V::Str((*key).to_owned()),
));
}
for source in crate::settings::SOUND_SOURCES {
t.push(u(&format!("soundCategory_{source}"), 1.0));
}
for part in MODEL_PARTS {
t.push(pb(&format!("modelPart_{part}"), true));
}
t
});
/// Mth.floor for doubles.
fn floor_int(v: f64) -> i32 {
let i = v as i32;
if v < f64::from(i) { i - 1 } else { i }
}
fn number(json: &Json) -> Option<&str> {
match json {
Json::Number(n) => Some(n),
_ => None,
}
}
fn codec_int(json: &Json) -> Option<i32> {
number(json).map(Json::int_value)
}
fn codec_double(json: &Json) -> Option<f64> {
number(json).map(Json::double_value)
}
fn codec_bool(json: &Json) -> Option<bool> {
match json {
Json::Bool(b) => Some(*b),
_ => None,
}
}
fn codec_string(json: &Json) -> Option<&str> {
match json {
Json::String(s) => Some(s),
_ => None,
}
}
fn double_range(v: f64, lo: f64, hi: f64) -> Option<f64> {
// Double.compareTo: -0.0 sorts below 0.0 and NaN above everything.
(v.total_cmp(&lo).is_ge() && v.total_cmp(&hi).is_le() && !v.is_nan()).then_some(v)
}
fn log_mouse(value: i32) -> f64 {
10f64.powf(f64::from(value) / 100.0)
}
fn unit_alt(json: &Json) -> Option<f64> {
codec_double(json)
.and_then(|v| double_range(v, 0.0, 1.0))
.or_else(|| codec_bool(json).map(|b| if b { 1.0 } else { 0.0 }))
}
impl Spec {
/// `codec.parse(JsonOps.INSTANCE, element)`.
fn decode(self, json: &Json) -> Option<V> {
match self {
Spec::Bool => codec_bool(json).map(V::Bool),
Spec::Int(lo, hi) => {
let v = codec_int(json)?;
(v >= lo && i64::from(v) <= i64::from(hi) + 1).then_some(V::Int(v))
}
Spec::LazyInt(lo) => {
let v = codec_int(json)?;
(v >= lo).then_some(V::Int(v))
}
Spec::Scaled(.., lo, hi) => double_range(codec_double(json)?, lo, hi).map(V::Double),
Spec::FrameLimit => {
let v = codec_int(json)?;
(10..=260).contains(&v).then_some(V::Int(v))
}
Spec::Fov => Some(V::Int((codec_double(json)? * 40.0 + 70.0) as i32)),
Spec::WheelSensitivity => {
double_range(codec_double(json)?, log_mouse(-200), log_mouse(100)).map(V::Double)
}
Spec::Unit => unit_alt(json).map(V::Double),
Spec::UnitSquare => double_range(codec_double(json)?, 0.0, 1.0).map(V::Double),
Spec::UnitSquareImplicit => unit_alt(json).map(|v| V::Double(v * v)),
Spec::Named(names) => {
let s = codec_string(json)?;
names.iter().position(|n| *n == s).map(|i| V::Int(i as i32))
}
Spec::Id(count) => codec_int(json).map(|v| V::Int(v.rem_euclid(count))),
Spec::Clouds => {
if let Some(s) = codec_string(json) {
return CLOUDS
.iter()
.position(|n| *n == s)
.map(|i| V::Int(i as i32));
}
codec_bool(json).map(|b| V::Int(if b { 2 } else { 0 }))
}
Spec::AnyStr => codec_string(json).map(|s| V::Str(s.to_owned())),
}
}
/// `ValueSet.validateValue`; `None` makes `OptionInstance.set` fall back
/// to the option's initial value.
fn validate(self, v: &V) -> Option<V> {
match (self, v) {
(Spec::Bool, V::Bool(_)) => Some(v.clone()),
(Spec::Int(lo, hi), V::Int(x)) => (*x >= lo && *x <= hi).then(|| v.clone()),
(Spec::LazyInt(lo), V::Int(x)) => Some(V::Int((*x).clamp(lo, 2_147_483_646))),
(Spec::Scaled(imin, imax, k, ..), V::Double(x)) => {
let i = (x * k) as i32;
(i >= imin && i <= imax).then(|| V::Double(f64::from(i) / k))
}
(Spec::FrameLimit, V::Int(x)) => {
let i = x / 10;
(1..=26).contains(&i).then(|| V::Int(i * 10))
}
(Spec::Fov, V::Int(x)) => (30..=110).contains(x).then(|| v.clone()),
(Spec::WheelSensitivity, V::Double(x)) => {
let i = floor_int(x.log10() * 100.0);
(-200..=100).contains(&i).then(|| V::Double(log_mouse(i)))
}
(Spec::Unit, V::Double(x)) => (*x >= 0.0 && *x <= 1.0).then(|| v.clone()),
(Spec::UnitSquare | Spec::UnitSquareImplicit, V::Double(x)) => {
let root = x.sqrt();
(0.0..=1.0)
.contains(&root)
.then_some(V::Double(root * root))
}
(Spec::Named(names), V::Int(x)) => {
(*x >= 0 && (*x as usize) < names.len()).then(|| v.clone())
}
(Spec::Id(count), V::Int(x)) => (*x >= 0 && *x < count).then(|| v.clone()),
(Spec::Clouds, V::Int(x)) => (0..3).contains(x).then(|| v.clone()),
(Spec::AnyStr, V::Str(_)) => Some(v.clone()),
_ => None,
}
}
/// `codec.encodeStart(JsonOps.INSTANCE, value)` rendered by Gson.
fn encode(self, v: &V) -> Option<String> {
let double = |x: f64| java_text::double_to_string(x);
Some(match (self, v) {
(Spec::Bool, V::Bool(b)) => b.to_string(),
(Spec::Int(lo, hi), V::Int(x)) => {
if *x < lo || i64::from(*x) > i64::from(hi) + 1 {
return None;
}
x.to_string()
}
(Spec::LazyInt(lo), V::Int(x)) => {
if *x < lo {
return None;
}
x.to_string()
}
(Spec::Scaled(.., lo, hi), V::Double(x)) => {
double_range(*x, lo, hi)?;
double(*x)
}
(Spec::FrameLimit, V::Int(x)) => {
if !(10..=260).contains(x) {
return None;
}
x.to_string()
}
(Spec::Fov, V::Int(x)) => double((f64::from(*x) - 70.0) / 40.0),
(Spec::WheelSensitivity, V::Double(x)) => {
double_range(*x, log_mouse(-200), log_mouse(100))?;
double(*x)
}
(Spec::Unit, V::Double(x)) => {
double_range(*x, 0.0, 1.0)?;
double(*x)
}
(Spec::UnitSquare, V::Double(x)) => {
double_range(*x, 0.0, 1.0)?;
double(*x)
}
(Spec::UnitSquareImplicit, V::Double(x)) => {
let root = x.sqrt();
double_range(root, 0.0, 1.0)?;
double(root)
}
(Spec::Named(names), V::Int(x)) => {
java_text::gson_string(names.get(usize::try_from(*x).ok()?)?)
}
(Spec::Id(_), V::Int(x)) => x.to_string(),
(Spec::Clouds, V::Int(x)) => {
java_text::gson_string(CLOUDS.get(usize::try_from(*x).ok()?)?)
}
(Spec::AnyStr, V::Str(s)) => java_text::gson_string(s),
_ => return None,
})
}
}
/// `InputConstants.getKey(name)`: the canonical name of a key, or the
/// unbound key when `name` is invalid.
pub fn canonical_key(name: &str) -> Result<String, java_text::SyntaxError> {
for (_, n) in key_names::KEYBOARD.iter().chain(key_names::MOUSE) {
if *n == name {
return Ok(name.to_owned());
}
}
for (prefix, table) in [
("key.keyboard", key_names::KEYBOARD),
("key.mouse", key_names::MOUSE),
] {
if let Some(rest) = name.strip_prefix(prefix) {
// substring(prefix.length() + 1): the separator is skipped blindly.
let mut chars = rest.chars();
if chars.next().is_none() {
// StringIndexOutOfBoundsException is not an IllegalArgumentException.
return Err(java_text::SyntaxError);
}
let Some(value) = crate::options_fixes::java_parse_int(chars.as_str()) else {
return Ok("key.keyboard.unknown".into());
};
return Ok(table
.iter()
.find(|(v, _)| *v == value)
.map_or_else(|| format!("{prefix}.{value}"), |(_, n)| (*n).to_owned()));
}
}
Ok("key.keyboard.unknown".into())
}
fn read_list(text: &str) -> Result<Vec<String>, java_text::SyntaxError> {
// GsonHelper.fromNullableJson with a List<String> type token.
Ok(java_text::parse_strict_string_list(text)?.unwrap_or_default())
}
/// All option values in `processOptions` order.
#[derive(Clone, Debug, PartialEq)]
pub struct OptionsFile {
values: Vec<V>,
/// `fullscreenResolution`, kept verbatim.
pub fullscreen_resolution: Option<String>,
}
impl Default for OptionsFile {
fn default() -> Self {
Self {
values: TABLE.iter().map(|d| d.default.clone()).collect(),
fullscreen_resolution: None,
}
}
}
impl OptionsFile {
fn index(key: &str) -> Option<usize> {
TABLE.iter().position(|d| d.key == key)
}
pub fn get(&self, key: &str) -> Option<&V> {
Self::index(key).map(|i| &self.values[i])
}
pub fn bool(&self, key: &str) -> bool {
matches!(self.get(key), Some(V::Bool(true)))
}
pub fn int(&self, key: &str) -> i32 {
match self.get(key) {
Some(V::Int(i)) => *i,
_ => 0,
}
}
pub fn double(&self, key: &str) -> f64 {
match self.get(key) {
Some(V::Double(d)) => *d,
_ => 0.0,
}
}
pub fn string(&self, key: &str) -> String {
match self.get(key) {
Some(V::Str(s)) => s.clone(),
_ => String::new(),
}
}
pub fn list(&self, key: &str) -> Vec<String> {
match self.get(key) {
Some(V::List(l)) => l.clone(),
_ => Vec::new(),
}
}
/// The serialized name of an enum-valued option.
pub fn name(&self, key: &str) -> String {
let Some(i) = Self::index(key) else {
return String::new();
};
match (TABLE[i].kind, &self.values[i]) {
(Kind::Option(Spec::Named(names)), V::Int(x)) => {
names.get(*x as usize).copied().unwrap_or("").to_owned()
}
(Kind::Option(Spec::Clouds), V::Int(x)) => {
CLOUDS.get(*x as usize).copied().unwrap_or("").to_owned()
}
_ => String::new(),
}
}
/// `OptionInstance.set` with a candidate value (invalid values revert to
/// the initial value).
pub fn set(&mut self, key: &str, value: V) {
let Some(i) = Self::index(key) else { return };
let Kind::Option(spec) = TABLE[i].kind else {
self.values[i] = value;
return;
};
self.values[i] = spec
.validate(&value)
.unwrap_or_else(|| TABLE[i].default.clone());
}
/// Select an enum option by serialized name.
pub fn set_name(&mut self, key: &str, name: &str) {
let Some(i) = Self::index(key) else { return };
let names: &[&str] = match TABLE[i].kind {
Kind::Option(Spec::Named(names)) => names,
Kind::Option(Spec::Clouds) => CLOUDS,
_ => return,
};
if let Some(p) = names.iter().position(|n| *n == name) {
self.values[i] = V::Int(p as i32);
}
}
/// Key mapping value by mapping name.
pub fn key_binding(&self, name: &str) -> String {
self.string(&format!("key_{name}"))
}
/// `Options.load` on the text of an options file.
pub fn parse(text: &str) -> Self {
let mut file = Self::default();
let mut raw: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for line in split_lines(text) {
if let Some((k, v)) = line.split_once(':') {
raw.insert(k.to_owned(), v.to_owned());
}
}
let version = raw
.get("version")
.and_then(|v| crate::options_fixes::java_parse_int(v))
.unwrap_or(0);
// A fixer failure abandons the whole file, leaving the defaults.
if crate::options_fixes::update(&mut raw, version).is_ok() {
file.apply(&raw);
}
file
}
fn apply(&mut self, raw: &std::collections::HashMap<String, String>) {
// A syntax error aborts the rest of the load, fullscreenResolution included.
if self.try_apply(raw).is_ok()
&& let Some(r) = raw.get("fullscreenResolution")
{
self.fullscreen_resolution = Some(r.clone());
}
}
fn try_apply(
&mut self,
raw: &std::collections::HashMap<String, String>,
) -> Result<(), java_text::SyntaxError> {
for (i, d) in TABLE.iter().enumerate() {
let Some(text) = raw.get(&d.key) else {
continue;
};
match d.kind {
Kind::Option(spec) => {
let json =
java_text::parse_lenient(if text.is_empty() { "\"\"" } else { text })?;
if let Some(decoded) = spec.decode(&json) {
self.values[i] =
spec.validate(&decoded).unwrap_or_else(|| d.default.clone());
}
}
Kind::PlainBool => self.values[i] = V::Bool(text == "true"),
Kind::PlainInt => {
if let Some(v) = crate::options_fixes::java_parse_int(text) {
self.values[i] = V::Int(v);
}
}
Kind::PlainStr => self.values[i] = V::Str(text.clone()),
Kind::List => self.values[i] = V::List(read_list(text)?),
Kind::Tutorial => {
let step = TUTORIAL_STEPS.iter().position(|n| n == text).unwrap_or(5);
self.values[i] = V::Int(step as i32);
}
Kind::Key => {
let V::Str(current) = &self.values[i] else {
continue;
};
if current != text {
self.values[i] = V::Str(canonical_key(text)?);
}
}
}
}
Ok(())
}
/// `Options.save`.
pub fn serialize(&self) -> String {
let mut out = format!("version:{}\n", horizon_world::DATA_VERSION);
for (d, v) in TABLE.iter().zip(&self.values) {
let rendered = match (d.kind, v) {
(Kind::Option(spec), v) => match spec.encode(v) {
Some(s) => s,
None => continue,
},
(Kind::PlainBool, V::Bool(b)) => b.to_string(),
(Kind::PlainInt, V::Int(x)) => x.to_string(),
(Kind::PlainStr | Kind::Key, V::Str(s)) => s.clone(),
(Kind::List, V::List(items)) => {
let parts: Vec<String> =
items.iter().map(|s| java_text::gson_string(s)).collect();
format!("[{}]", parts.join(","))
}
(Kind::Tutorial, V::Int(x)) => TUTORIAL_STEPS
.get(*x as usize)
.copied()
.unwrap_or("none")
.to_owned(),
_ => continue,
};
out.push_str(&d.key);
out.push(':');
out.push_str(&rendered);
out.push('\n');
}
if let Some(r) = &self.fullscreen_resolution {
out.push_str("fullscreenResolution:");
out.push_str(r);
out.push('\n');
}
out
}
}
/// `BufferedReader.lines()`: \n, \r\n and \r terminate lines.
fn split_lines(text: &str) -> Vec<&str> {
let mut lines = Vec::new();
let bytes = text.as_bytes();
let mut start = 0;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\n' => {
lines.push(&text[start..i]);
start = i + 1;
}
b'\r' => {
lines.push(&text[start..i]);
if bytes.get(i + 1) == Some(&b'\n') {
i += 1;
}
start = i + 1;
}
_ => {}
}
i += 1;
}
if start < bytes.len() {
lines.push(&text[start..]);
}
lines
}
/// Option names in processing order (for tests and tooling).
pub fn keys() -> Vec<&'static str> {
TABLE.iter().map(|d| d.key.as_str()).collect()
}
+324
View File
@@ -0,0 +1,324 @@
//! The `OPTIONS` data fixers of 26.3 (`DataFixTypes.OPTIONS`), applied to the
//! raw key/value strings of an `options.txt` older than the current version.
use std::collections::HashMap;
/// A fixer threw an exception; vanilla abandons loading the file.
#[derive(Debug)]
pub struct FixFailed;
pub type Raw = HashMap<String, String>;
/// OptionsKeyLwjgl3Fix.MAP: GLFW 2 key codes to key names.
const LWJGL3: &[(i32, &str)] = &[
(0, "key.unknown"),
(11, "key.0"),
(2, "key.1"),
(3, "key.2"),
(4, "key.3"),
(5, "key.4"),
(6, "key.5"),
(7, "key.6"),
(8, "key.7"),
(9, "key.8"),
(10, "key.9"),
(30, "key.a"),
(40, "key.apostrophe"),
(48, "key.b"),
(43, "key.backslash"),
(14, "key.backspace"),
(46, "key.c"),
(58, "key.caps.lock"),
(51, "key.comma"),
(32, "key.d"),
(211, "key.delete"),
(208, "key.down"),
(18, "key.e"),
(207, "key.end"),
(28, "key.enter"),
(13, "key.equal"),
(1, "key.escape"),
(33, "key.f"),
(59, "key.f1"),
(68, "key.f10"),
(87, "key.f11"),
(88, "key.f12"),
(100, "key.f13"),
(101, "key.f14"),
(102, "key.f15"),
(103, "key.f16"),
(104, "key.f17"),
(105, "key.f18"),
(113, "key.f19"),
(60, "key.f2"),
(61, "key.f3"),
(62, "key.f4"),
(63, "key.f5"),
(64, "key.f6"),
(65, "key.f7"),
(66, "key.f8"),
(67, "key.f9"),
(34, "key.g"),
(41, "key.grave.accent"),
(35, "key.h"),
(199, "key.home"),
(23, "key.i"),
(210, "key.insert"),
(36, "key.j"),
(37, "key.k"),
(82, "key.keypad.0"),
(79, "key.keypad.1"),
(80, "key.keypad.2"),
(81, "key.keypad.3"),
(75, "key.keypad.4"),
(76, "key.keypad.5"),
(77, "key.keypad.6"),
(71, "key.keypad.7"),
(72, "key.keypad.8"),
(73, "key.keypad.9"),
(78, "key.keypad.add"),
(83, "key.keypad.decimal"),
(181, "key.keypad.divide"),
(156, "key.keypad.enter"),
(141, "key.keypad.equal"),
(55, "key.keypad.multiply"),
(74, "key.keypad.subtract"),
(38, "key.l"),
(203, "key.left"),
(56, "key.left.alt"),
(26, "key.left.bracket"),
(29, "key.left.control"),
(42, "key.left.shift"),
(219, "key.left.win"),
(50, "key.m"),
(12, "key.minus"),
(49, "key.n"),
(69, "key.num.lock"),
(24, "key.o"),
(25, "key.p"),
(209, "key.page.down"),
(201, "key.page.up"),
(197, "key.pause"),
(52, "key.period"),
(183, "key.print.screen"),
(16, "key.q"),
(19, "key.r"),
(205, "key.right"),
(184, "key.right.alt"),
(27, "key.right.bracket"),
(157, "key.right.control"),
(54, "key.right.shift"),
(220, "key.right.win"),
(31, "key.s"),
(70, "key.scroll.lock"),
(39, "key.semicolon"),
(53, "key.slash"),
(57, "key.space"),
(20, "key.t"),
(15, "key.tab"),
(22, "key.u"),
(200, "key.up"),
(47, "key.v"),
(17, "key.w"),
(45, "key.x"),
(21, "key.y"),
(44, "key.z"),
];
/// `Integer.parseInt(String)`.
pub fn java_parse_int(text: &str) -> Option<i32> {
let digits = text.strip_prefix(['+', '-']).unwrap_or(text);
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
return None;
}
text.parse::<i32>().ok()
}
enum Number<'a> {
Special(f64),
Decimal(bool, &'a str),
}
fn java_number(text: &str) -> Option<Number<'_>> {
let t = text.trim_matches(|c: char| c <= ' ');
let (negative, body) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t.strip_prefix('+').unwrap_or(t)),
};
match body {
"NaN" => return Some(Number::Special(f64::NAN)),
"Infinity" => {
return Some(Number::Special(if negative {
f64::NEG_INFINITY
} else {
f64::INFINITY
}));
}
_ => {}
}
let body = body.strip_suffix(['f', 'F', 'd', 'D']).unwrap_or(body);
if body.is_empty()
|| !body
.chars()
.all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-'))
|| !body.chars().any(|c| c.is_ascii_digit())
{
return None;
}
Some(Number::Decimal(negative, body))
}
/// `Double.parseDouble(String)` for decimal and special forms.
pub fn java_parse_double(text: &str) -> Option<f64> {
match java_number(text)? {
Number::Special(v) => Some(v),
Number::Decimal(negative, body) => body
.parse::<f64>()
.ok()
.map(|v| if negative { -v } else { v }),
}
}
/// `Float.parseFloat(String)`.
pub fn java_parse_float(text: &str) -> Option<f32> {
match java_number(text)? {
Number::Special(v) => Some(v as f32),
Number::Decimal(negative, body) => body
.parse::<f32>()
.ok()
.map(|v| if negative { -v } else { v }),
}
}
fn rename(raw: &mut Raw, from: &str, to: &str, fix: impl FnOnce(&str) -> String) {
if let Some(old) = raw.remove(from) {
let value = fix(&old);
raw.insert(to.to_owned(), value);
}
}
/// `OPTIONS` fixers from `version` up to the current data version.
pub fn update(raw: &mut Raw, version: i32) -> Result<(), FixFailed> {
if version < 816
&& let Some(lang) = raw.get_mut("lang")
{
*lang = lang.to_lowercase();
}
if version < 1344 {
let keys: Vec<String> = raw
.keys()
.filter(|k| k.starts_with("key_"))
.cloned()
.collect();
for key in keys {
let old = java_parse_int(&raw[&key]).ok_or(FixFailed)?;
let name = if old < 0 {
match old + 100 {
0 => "key.mouse.left".to_owned(),
1 => "key.mouse.right".to_owned(),
2 => "key.mouse.middle".to_owned(),
button => format!("key.mouse.{}", button + 1),
}
} else {
LWJGL3
.iter()
.find(|(v, _)| *v == old)
.map_or("key.unknown", |(_, n)| n)
.to_owned()
};
raw.insert(key, name);
}
}
if version < 1446 {
let keys: Vec<String> = raw
.keys()
.filter(|k| k.starts_with("key_"))
.cloned()
.collect();
for key in keys {
let old = raw[&key].clone();
if !old.starts_with("key.mouse") && !old.starts_with("scancode.") {
// substring(4) on a shorter value throws.
let rest: String = old.chars().skip(4).collect();
if old.chars().count() < 4 {
return Err(FixFailed);
}
raw.insert(key, format!("key.keyboard.{rest}"));
}
}
}
if version < 1936
&& let Some(opacity) = raw.get("chatOpacity")
{
let background = java_parse_double(opacity).map_or(0.5, |v| (0.9 * v + 0.1) / 2.0);
raw.insert(
"textBackgroundOpacity".into(),
crate::java_text::double_to_string(background),
);
}
if version < 2556 {
rename(raw, "fancyGraphics", "graphicsMode", |v| {
if v == "true" { "1" } else { "0" }.to_owned()
});
}
if version < 2558
&& let Some(v) = raw.remove("key_key.swapHands")
{
raw.insert("key_key.swapOffhand".into(), v);
}
if version < 3201 {
for key in ["resourcePacks", "incompatibleResourcePacks"] {
if let Some(v) = raw.get_mut(key) {
*v = v.replace("\"programer_art\"", "\"programmer_art\"");
}
}
}
if version < 3214
&& let Some(ao) = raw.get_mut("ao")
{
match ao.as_str() {
"0" => *ao = "false".into(),
"1" | "2" => *ao = "true".into(),
_ => {}
}
}
if version < 3319 {
raw.insert("onboardAccessibility".into(), "false".into());
}
if version < 3943
&& let Some(v) = raw.get_mut("menuBackgroundBlurriness")
{
let value = java_parse_float(v).map_or(5, |d| ((d * 10.0) + 0.5).floor() as i32);
*v = value.to_string();
}
if version < 4651 {
let mode = raw.get("graphicsMode").cloned();
for (name, fast, fancy, fabulous) in [
("cutoutLeaves", "false", "true", "true"),
("weatherRadius", "5", "10", "10"),
("vignette", "false", "true", "true"),
("improvedTransparency", "false", "false", "true"),
] {
let value = match mode.as_deref() {
Some("2") => fabulous,
Some("0") => fast,
_ => fancy,
};
raw.insert(name.into(), value.into());
}
raw.insert("graphicsPreset".into(), "custom".into());
}
if version < 4661 {
rename(raw, "showNowPlayingToast", "musicToast", |v| {
if v == "false" {
"never"
} else {
"pause_and_toast"
}
.to_owned()
});
}
if version < 4892 {
raw.insert("preferredGraphicsBackend".into(), "default".into());
}
Ok(())
}
+71 -25
View File
@@ -280,14 +280,27 @@ impl Book {
ingredients,
result,
} => (Display::Shapeless(ingredients.clone()), result),
Recipe::Special(_) => continue,
// Custom recipes are never learnable; the others show one
// display per material count (TransmuteRecipe.display).
Recipe::Special(special) => {
for (display, result) in special.book_displays() {
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result,
});
}
continue;
}
};
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result: result.clone(),
result: result.create(),
});
}
for c in &recipes.cooking {
@@ -376,24 +389,33 @@ impl Book {
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
items
}
/// `RecipeCollection` search: the result's name or registry path, or
/// `@namespace`.
pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool {
/// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a
/// `FullTextSearchTree`): without a colon the text must occur in a
/// tooltip line of a result item of the collection; `namespace:path`
/// needs the namespace in a result id and the path in an id or a line.
pub fn collection_matches(
&self,
entries: &[usize],
query: &str,
tooltip: &dyn Fn(&ItemStack) -> Vec<String>,
) -> bool {
let query = query.to_lowercase();
if let Some(ns) = query.strip_prefix('@') {
return entry
.result
.item
.split(':')
.next()
.is_some_and(|n| n.starts_with(ns));
}
name.to_lowercase().contains(&query)
|| entry
.result
.item
.trim_start_matches("minecraft:")
.contains(&query)
let results: Vec<&ItemStack> = entries.iter().map(|&i| &self.entries[i].result).collect();
let in_lines = |text: &str| {
results
.iter()
.any(|r| tooltip(r).iter().any(|l| l.to_lowercase().contains(text)))
};
let Some((namespace, path)) = query.split_once(':') else {
return in_lines(&query);
};
let (namespace, path) = (namespace.trim(), path.trim());
let id = |r: &&ItemStack| {
let (ns, p) = r.item.split_once(':').unwrap_or(("minecraft", &r.item));
(ns.to_lowercase(), p.to_lowercase())
};
results.iter().any(|r| id(r).0.contains(namespace))
&& (results.iter().any(|r| id(r).1.contains(path)) || in_lines(path))
}
}
@@ -524,6 +546,8 @@ pub struct Settings {
pub filtering: [bool; 4],
/// Unlocked recipe ids (`recipes`).
pub recipes: Vec<String>,
/// Recipes not yet shown in the book (`toBeDisplayed`): they animate once.
pub to_be_displayed: Vec<String>,
}
impl Settings {
pub fn read(tag: Option<&Tag>) -> Self {
@@ -535,18 +559,21 @@ impl Settings {
s.open[b.index()] = flag(open);
s.filtering[b.index()] = flag(filter);
}
if let Some(Tag::List(list)) = tag.get("recipes") {
s.recipes = list
let ids = |key: &str| match tag.get(key) {
Some(Tag::List(list)) => list
.iter()
.filter_map(|t| match t {
Tag::String(id) => Some(id.to_string_lossy()),
_ => None,
})
.collect();
}
.collect(),
_ => Vec::new(),
};
s.recipes = ids("recipes");
s.to_be_displayed = ids("toBeDisplayed");
s
}
/// The compound written to the player file; `toBeDisplayed` stays empty.
/// The compound written to the player file.
pub fn write(&self) -> Tag {
let mut entries: Vec<(&str, Tag)> = Vec::new();
for b in BookType::ALL {
@@ -558,7 +585,7 @@ impl Settings {
Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect())
};
entries.push(("recipes", list(&self.recipes)));
entries.push(("toBeDisplayed", Tag::List(Vec::new())));
entries.push(("toBeDisplayed", list(&self.to_be_displayed)));
Tag::compound(entries)
}
}
@@ -672,6 +699,25 @@ mod tests {
assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1);
}
#[test]
fn search_reads_tooltip_lines_and_ids() {
let book = Book {
entries: vec![Entry {
id: "minecraft:stick".into(),
category: Category::CraftingMisc,
group: None,
display: Display::Shapeless(Vec::new()),
result: ItemStack::new("minecraft:stick", 4),
}],
order: HashMap::new(),
};
let lines = |s: &ItemStack| vec![format!("Item {}", s.item), "Stick".to_owned()];
assert!(book.collection_matches(&[0], "STI", &lines));
// Plain text searches tooltips only, not the registry path.
assert!(!book.collection_matches(&[0], "stick:", &lines));
assert!(book.collection_matches(&[0], "minecraft:stic", &lines));
assert!(!book.collection_matches(&[0], "other:stick", &lines));
}
#[test]
fn settings_round_trip() {
let mut s = Settings::default();
s.open[BookType::Furnace.index()] = true;
+49 -78
View File
@@ -16,10 +16,11 @@
use crate::{
Result,
biome::Biomes,
chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS},
chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS},
streaming::ChunkGenerator,
};
use horizon_core::{
paletted::PalettedContainer,
position::{BlockPos, ChunkPos},
ticks::{SavedTick, TickPriority, TickTypeId},
};
@@ -42,29 +43,6 @@ use std::{
pub const VERSION_NAME: &str = "26.3";
fn pack(indices: &[u16], bits: u32) -> Vec<i64> {
let per_long = (64 / bits) as usize;
let mut longs = vec![0i64; indices.len().div_ceil(per_long)];
for (i, &v) in indices.iter().enumerate() {
longs[i / per_long] |=
(i64::from(v) & ((1i64 << bits) - 1)) << ((i % per_long) as u32 * bits);
}
longs
}
fn unpack(longs: &[i64], bits: u32, count: usize) -> Vec<u16> {
let per_long = (64 / bits) as usize;
let mask = (1u64 << bits) - 1;
(0..count)
.map(|i| {
longs.get(i / per_long).map_or(0, |&l| {
((l as u64 >> ((i % per_long) as u32 * bits)) & mask) as u16
})
})
.collect()
}
fn bits_for(len: usize, min: u32) -> u32 {
(usize::BITS - (len.max(1) - 1).leading_zeros()).max(min)
}
fn string(s: &str) -> Tag {
Tag::String(s.into())
}
@@ -670,33 +648,22 @@ pub fn encode_with(
});
for (si, section) in chunk.sections.iter().enumerate() {
let y = (MIN_Y >> 4) + si as i32;
let ids: Vec<u16> = match &section.blocks {
Blocks::Uniform(v) => vec![*v],
Blocks::Full(a) => a.to_vec(),
};
let mut palette: Vec<u16> = Vec::new();
let mut lookup: HashMap<u16, u16> = HashMap::new();
let indices: Vec<u16> = ids
.iter()
.map(|id| {
*lookup.entry(*id).or_insert_with(|| {
palette.push(*id);
(palette.len() - 1) as u16
})
})
.collect();
// PalettedContainer.pack: distinct states in index order, indices at
// the saved width.
let packed = section.blocks.pack();
let mut states = vec![(
"palette",
Tag::List(
palette
packed
.palette
.iter()
.map(|id| {
let state = registry.state(BlockStateId(u32::from(*id)));
.map(|&id| {
let state = registry.state(BlockStateId(id));
match state {
// BlockState.CODEC: the block name for default states.
Some(s)
if tables.is_some_and(|t| {
t.default_state.get(*id as usize) == Some(&true)
t.default_state.get(id as usize) == Some(&true)
}) =>
{
string(&s.name)
@@ -708,37 +675,27 @@ pub fn encode_with(
.collect(),
),
)];
if palette.len() > 1 {
if let Some(data) = &packed.data {
states.push((
"data",
Tag::LongArray(pack(&indices, bits_for(palette.len(), 4))),
Tag::LongArray(data.iter().map(|&w| w as i64).collect()),
));
}
let quart: Vec<u16> = (0..64).map(|i| chunk.biomes[si * 64 + i]).collect();
let mut biome_palette: Vec<u16> = Vec::new();
let biome_indices: Vec<u16> = quart
.iter()
.map(|b| match biome_palette.iter().position(|p| p == b) {
Some(i) => i as u16,
None => {
biome_palette.push(*b);
(biome_palette.len() - 1) as u16
}
})
.collect();
let biome_packed = section.biomes.pack();
let mut biome_tag = vec![(
"palette",
Tag::List(
biome_palette
biome_packed
.palette
.iter()
.map(|b| string(&biomes.get(*b).name))
.map(|&b| string(&biomes.get(b as u16).name))
.collect(),
),
)];
if biome_palette.len() > 1 {
if let Some(data) = &biome_packed.data {
biome_tag.push((
"data",
Tag::LongArray(pack(&biome_indices, bits_for(biome_palette.len(), 0))),
Tag::LongArray(data.iter().map(|&w| w as i64).collect()),
));
}
let mut entries = vec![
@@ -772,7 +729,12 @@ pub fn encode_with(
.iter()
.map(|(p, e)| {
let block = block_name(p);
let current = encode_block_entity(*p, e, &block);
let mut current = encode_block_entity(*p, e, &block);
if let Some((_, name)) = chunk.block_names.iter().find(|(q, _)| q == p)
&& let Tag::Compound(map) = &mut current
{
map.insert("CustomName".into(), string(name));
}
let source = extras
.and_then(|x| x.block_entity_sources.iter().find(|(q, _)| q == p))
.map(|(_, tag)| tag)
@@ -918,7 +880,6 @@ pub fn decode_with(
}
let air = registry.default_state("minecraft:air")?.0 as u16;
let mut cache: HashMap<String, u16> = HashMap::new();
let mut biome_data = (*chunk.biomes).clone();
let Some(Tag::List(sections)) = tag.get("sections") else {
return Some(chunk);
};
@@ -961,15 +922,17 @@ pub fn decode_with(
})
.collect();
let target = Arc::make_mut(&mut chunk.sections[si as usize]);
if ids.len() <= 1 {
target.blocks = Blocks::Uniform(ids.first().copied().unwrap_or(air));
} else if let Some(Tag::LongArray(data)) = states.get("data") {
let indices = unpack(data, bits_for(ids.len(), 4), 4096);
let mut full = Box::new([air; 4096]);
for (i, idx) in indices.iter().enumerate() {
full[i] = ids.get(*idx as usize).copied().unwrap_or(air);
let data = match states.get("data") {
Some(Tag::LongArray(data)) => {
Some(data.iter().map(|&w| w as u64).collect::<Vec<_>>())
}
target.blocks = Blocks::Full(full);
_ => None,
};
let palette: Vec<u32> = ids.iter().map(|&id| u32::from(id)).collect();
if let Ok(blocks) =
PalettedContainer::from_packed(BLOCK_STRATEGY, palette, data.as_deref())
{
target.blocks = blocks;
}
}
if let Some(b) = section.get("biomes")
@@ -982,18 +945,23 @@ pub fn decode_with(
_ => 0,
})
.collect();
let indices = match b.get("data") {
Some(Tag::LongArray(data)) if ids.len() > 1 => {
unpack(data, bits_for(ids.len(), 0), 64)
let data = match b.get("data") {
Some(Tag::LongArray(data)) => {
Some(data.iter().map(|&w| w as u64).collect::<Vec<_>>())
}
_ => vec![0; 64],
_ => None,
};
for (i, idx) in indices.iter().enumerate() {
biome_data[si as usize * 64 + i] = ids.get(*idx as usize).copied().unwrap_or(0);
let palette: Vec<u32> = ids.iter().map(|&id| u32::from(id)).collect();
let target = Arc::make_mut(&mut chunk.sections[si as usize]);
if let Ok(container) =
PalettedContainer::from_packed(BIOME_STRATEGY, palette.clone(), data.as_deref())
{
target.biomes = container;
} else if let Some(&first) = palette.first() {
target.biomes = PalettedContainer::new(BIOME_STRATEGY, first);
}
}
}
chunk.biomes = Arc::new(biome_data);
let mut extras = ChunkExtras {
last_update: number(tag.get("LastUpdate")).unwrap_or(0),
..ChunkExtras::default()
@@ -1002,6 +970,9 @@ pub fn decode_with(
for e in entities {
match decode_block_entity(e) {
Some(be) => {
if let Some(name) = text(e.get("CustomName")) {
chunk.block_names.push((be.0, name));
}
extras.block_entity_sources.push((be.0, e.clone()));
chunk.block_entities.push(be);
}
+214 -245
View File
@@ -2,7 +2,8 @@
//! encodings (Options.processOptions); lines Horizon does not know are kept.
//! The option screens live in `options_ui`.
use crate::keybinds::KeyBinds;
use std::{collections::BTreeMap, fs, path::Path};
use crate::options_file::{OptionsFile, V};
use std::{fs, path::Path};
/// SoundSource names in vanilla order.
pub const SOUND_SOURCES: [&str; 11] = [
@@ -20,7 +21,7 @@ pub fn set_source_volumes(volumes: [f32; 11]) {
pub fn sound_source(event: &str) -> usize {
let e = event.trim_start_matches("minecraft:");
let index = |name: &str| SOUND_SOURCES.iter().position(|n| *n == name).unwrap_or(0);
const HOSTILE: [&str; 24] = [
const HOSTILE: [&str; 25] = [
"zombie",
"skeleton",
"creeper",
@@ -39,6 +40,7 @@ pub fn sound_source(event: &str) -> usize {
"pillager",
"vindicator",
"evoker",
"illusioner",
"ravager",
"guardian",
"elder_guardian",
@@ -166,8 +168,13 @@ pub struct Settings {
/// Enabled resource packs, bottom first (resourcePacks).
pub resource_packs: Vec<String>,
pub keys: KeyBinds,
/// Lines Horizon does not interpret, kept verbatim.
pub extra: BTreeMap<String, String>,
/// Every option in its stored form (the typed fields above mirror it).
pub file: OptionsFile,
pub invert_x: bool,
pub toggle_attack: bool,
pub toggle_use: bool,
/// Taps of the sprint key counted as double taps (sprintWindow).
pub sprint_window: i32,
}
impl Default for Settings {
fn default() -> Self {
@@ -229,267 +236,228 @@ impl Default for Settings {
show_subtitles: false,
notification_display_time: 1.0,
main_hand_left: false,
resource_packs: vec!["vanilla".into()],
resource_packs: Vec::new(),
keys: KeyBinds::default(),
extra: BTreeMap::new(),
file: OptionsFile::default(),
invert_x: false,
toggle_attack: false,
toggle_use: false,
sprint_window: 7,
}
}
}
fn unquote(v: &str) -> &str {
v.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.unwrap_or(v)
fn put_f(f: &mut OptionsFile, key: &str, v: f32) {
if v != f.double(key) as f32 {
f.set(key, V::Double(f64::from(v)));
}
}
fn parse_list(v: &str) -> Vec<String> {
serde_json::from_str::<Vec<String>>(v).unwrap_or_default()
fn put_i(f: &mut OptionsFile, key: &str, v: i32) {
if v != f.int(key) {
f.set(key, V::Int(v));
}
}
fn put_b(f: &mut OptionsFile, key: &str, v: bool) {
if v != f.bool(key) {
f.set(key, V::Bool(v));
}
}
fn put_name(f: &mut OptionsFile, key: &str, v: &str) {
if v != f.name(key) {
f.set_name(key, v);
}
}
fn put_s(f: &mut OptionsFile, key: &str, v: &str) {
if v != f.string(key) {
f.set(key, V::Str(v.to_owned()));
}
}
impl Settings {
pub fn load(path: &Path) -> Self {
let Ok(text) = fs::read_to_string(path) else {
let Ok(bytes) = fs::read(path) else {
return Self::default();
};
Self::parse(&text)
Self::parse(&String::from_utf8_lossy(&bytes))
}
pub fn parse(text: &str) -> Self {
let mut s = Self::default();
for line in text.lines() {
let Some((k, v)) = line.split_once(':') else {
continue;
};
let f = |d: f32| v.parse::<f32>().unwrap_or(d);
let b = |d: bool| match v {
"true" => true,
"false" => false,
_ => d,
};
let i = |d: i32| v.parse::<i32>().unwrap_or(d);
match k {
"version" => {}
"fov" => {
s.fov = v
.parse::<f32>()
.map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0))
}
"renderDistance" => s.render_distance = i(12).clamp(2, 32),
"simulationDistance" => s.simulation_distance = i(12).clamp(5, 32),
"mouseSensitivity" => s.sensitivity = f(0.5).clamp(0.0, 1.0),
"guiScale" => s.gui_scale = v.parse().unwrap_or(0),
"bobView" => s.view_bobbing = b(true),
"gamma" => s.gamma = f(0.5).clamp(0.0, 1.0),
"maxFps" => s.max_fps = v.parse::<u32>().unwrap_or(260).clamp(10, 260),
"enableVsync" => s.vsync = b(true),
"fullscreen" => s.fullscreen = b(false),
"ao" => s.smooth_lighting = b(true),
"renderClouds" => s.clouds = unquote(v).to_owned(),
"cloudRange" => s.cloud_range = i(128).clamp(2, 128),
"particles" => s.particles = v.parse::<u8>().unwrap_or(0).min(2),
"entityDistanceScaling" => s.entity_distance = f(1.0).clamp(0.5, 5.0),
"entityShadows" => s.entity_shadows = b(true),
"biomeBlendRadius" => s.biome_blend = i(2).clamp(0, 7),
"graphicsPreset" => s.graphics_preset = unquote(v).to_owned(),
"mipmapLevels" => s.mipmap_levels = i(4).clamp(0, 4),
"weatherRadius" => s.weather_radius = i(10).clamp(3, 10),
"chunkSectionFadeInTime" => s.chunk_fade = f(0.75).clamp(0.0, 2.0),
"vignette" => s.vignette = b(true),
"showAutosaveIndicator" => s.autosave_indicator = b(true),
"cutoutLeaves" => s.cutout_leaves = b(true),
"improvedTransparency" => s.improved_transparency = b(false),
"attackIndicator" => s.attack_indicator = v.parse::<u8>().unwrap_or(1).min(2),
"inactivityFpsLimit" => s.inactivity_fps_limit = unquote(v).to_owned(),
"prioritizeChunkUpdates" => {
s.prioritize_chunk_updates = v.parse::<u8>().unwrap_or(0).min(2)
}
"menuBackgroundBlurriness" => s.menu_blur = i(5).clamp(0, 10),
"invertYMouse" => s.invert_y = b(false),
"mouseWheelSensitivity" => s.mouse_wheel_sensitivity = f(1.0).clamp(0.01, 10.0),
"discrete_mouse_scroll" => s.discrete_scroll = b(false),
"toggleCrouch" => s.toggle_crouch = b(false),
"toggleSprint" => s.toggle_sprint = b(false),
"autoJump" => s.auto_jump = b(false),
"lang" => s.language = v.to_owned(),
"forceUnicodeFont" => s.force_unicode = b(false),
"japaneseGlyphVariants" => s.japanese_glyphs = b(false),
"chatVisibility" => s.chat_visibility = v.parse::<u8>().unwrap_or(0).min(2),
"chatColors" => s.chat_colors = b(true),
"chatLinks" => s.chat_links = b(true),
"chatOpacity" => s.chat_opacity = f(1.0).clamp(0.0, 1.0),
"textBackgroundOpacity" => s.text_background_opacity = f(0.5).clamp(0.0, 1.0),
"chatScale" => s.chat_scale = f(1.0).clamp(0.0, 1.0),
"chatWidth" => s.chat_width = f(1.0).clamp(0.0, 1.0),
"chatHeightFocused" => s.chat_height_focused = f(1.0).clamp(0.0, 1.0),
"chatHeightUnfocused" => s.chat_height_unfocused = f(0.4375).clamp(0.0, 1.0),
"chatLineSpacing" => s.chat_line_spacing = f(0.0).clamp(0.0, 1.0),
"autoSuggestions" => s.auto_suggestions = b(true),
"reducedDebugInfo" => s.reduced_debug_info = b(false),
"highContrast" => s.high_contrast = b(false),
"showSubtitles" => s.show_subtitles = b(false),
"notificationDisplayTime" => {
s.notification_display_time = f(1.0).clamp(0.5, 10.0);
}
"mainHand" => s.main_hand_left = unquote(v) == "left",
"resourcePacks" => s.resource_packs = parse_list(v),
_ if k.starts_with("key_") => {
if !s.keys.set_saved(&k[4..], v) {
s.extra.insert(k.to_owned(), v.to_owned());
}
}
_ if k.starts_with("soundCategory_") => {
let name = &k["soundCategory_".len()..];
match SOUND_SOURCES.iter().position(|n| *n == name) {
Some(0) => s.master_volume = f(1.0).clamp(0.0, 1.0),
Some(i) => s.volumes[i] = f(1.0).clamp(0.0, 1.0),
None => {
s.extra.insert(k.to_owned(), v.to_owned());
}
}
}
_ => {
s.extra.insert(k.to_owned(), v.to_owned());
}
}
}
s
Self::from_file(OptionsFile::parse(text))
}
/// The `options.txt` text (Options.save: `version` first, then key:value).
pub fn serialize(&self) -> String {
let mut lines: Vec<(String, String)> = vec![
("ao".into(), self.smooth_lighting.to_string()),
("biomeBlendRadius".into(), self.biome_blend.to_string()),
("chunkSectionFadeInTime".into(), self.chunk_fade.to_string()),
("cutoutLeaves".into(), self.cutout_leaves.to_string()),
("enableVsync".into(), self.vsync.to_string()),
(
"entityDistanceScaling".into(),
self.entity_distance.to_string(),
),
("entityShadows".into(), self.entity_shadows.to_string()),
("forceUnicodeFont".into(), self.force_unicode.to_string()),
(
"japaneseGlyphVariants".into(),
self.japanese_glyphs.to_string(),
),
("fov".into(), ((self.fov - 70.0) / 40.0).to_string()),
(
"graphicsPreset".into(),
format!("\"{}\"", self.graphics_preset),
),
(
"prioritizeChunkUpdates".into(),
self.prioritize_chunk_updates.to_string(),
),
("fullscreen".into(), self.fullscreen.to_string()),
("gamma".into(), self.gamma.to_string()),
("guiScale".into(), self.gui_scale.to_string()),
("maxFps".into(), self.max_fps.to_string()),
(
"improvedTransparency".into(),
self.improved_transparency.to_string(),
),
(
"inactivityFpsLimit".into(),
format!("\"{}\"", self.inactivity_fps_limit),
),
("mipmapLevels".into(), self.mipmap_levels.to_string()),
("particles".into(), self.particles.to_string()),
(
"reducedDebugInfo".into(),
self.reduced_debug_info.to_string(),
),
("renderClouds".into(), format!("\"{}\"", self.clouds)),
("cloudRange".into(), self.cloud_range.to_string()),
("renderDistance".into(), self.render_distance.to_string()),
(
"simulationDistance".into(),
self.simulation_distance.to_string(),
),
("vignette".into(), self.vignette.to_string()),
("weatherRadius".into(), self.weather_radius.to_string()),
("autoJump".into(), self.auto_jump.to_string()),
("autoSuggestions".into(), self.auto_suggestions.to_string()),
("chatColors".into(), self.chat_colors.to_string()),
("chatLinks".into(), self.chat_links.to_string()),
(
"discrete_mouse_scroll".into(),
self.discrete_scroll.to_string(),
),
("invertYMouse".into(), self.invert_y.to_string()),
("bobView".into(), self.view_bobbing.to_string()),
("toggleCrouch".into(), self.toggle_crouch.to_string()),
("toggleSprint".into(), self.toggle_sprint.to_string()),
("mouseSensitivity".into(), self.sensitivity.to_string()),
("highContrast".into(), self.high_contrast.to_string()),
("showSubtitles".into(), self.show_subtitles.to_string()),
(
"notificationDisplayTime".into(),
self.notification_display_time.to_string(),
),
(
"resourcePacks".into(),
serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into()),
),
("lang".into(), self.language.clone()),
("chatVisibility".into(), self.chat_visibility.to_string()),
("chatOpacity".into(), self.chat_opacity.to_string()),
("chatLineSpacing".into(), self.chat_line_spacing.to_string()),
(
"textBackgroundOpacity".into(),
self.text_background_opacity.to_string(),
),
(
"chatHeightFocused".into(),
self.chat_height_focused.to_string(),
),
(
"chatHeightUnfocused".into(),
self.chat_height_unfocused.to_string(),
),
("chatScale".into(), self.chat_scale.to_string()),
("chatWidth".into(), self.chat_width.to_string()),
(
"mainHand".into(),
if self.main_hand_left {
"\"left\"".into()
} else {
"\"right\"".into()
},
),
("attackIndicator".into(), self.attack_indicator.to_string()),
(
"mouseWheelSensitivity".into(),
self.mouse_wheel_sensitivity.to_string(),
),
(
"showAutosaveIndicator".into(),
self.autosave_indicator.to_string(),
),
(
"menuBackgroundBlurriness".into(),
self.menu_blur.to_string(),
),
];
for (name, key) in self.keys.saved() {
lines.push((format!("key_{name}"), key));
/// Typed view of an options file.
pub fn from_file(f: OptionsFile) -> Self {
let mut keys = KeyBinds::default();
for (name, _, _) in crate::keybinds::MAPPINGS {
keys.set(name, &f.key_binding(name));
}
let mut volumes = [1.0; 11];
for (i, source) in SOUND_SOURCES.iter().enumerate() {
volumes[i] = f.double(&format!("soundCategory_{source}")) as f32;
}
Self {
fov: f.int("fov") as f32,
render_distance: f.int("renderDistance"),
simulation_distance: f.int("simulationDistance"),
sensitivity: f.double("mouseSensitivity") as f32,
master_volume: volumes[0],
volumes,
gui_scale: f.int("guiScale").max(0) as u32,
view_bobbing: f.bool("bobView"),
gamma: f.double("gamma") as f32,
max_fps: f.int("maxFps") as u32,
vsync: f.bool("enableVsync"),
fullscreen: f.bool("fullscreen"),
smooth_lighting: f.bool("ao"),
clouds: f.name("renderClouds"),
cloud_range: f.int("cloudRange"),
particles: f.int("particles") as u8,
entity_distance: f.double("entityDistanceScaling") as f32,
entity_shadows: f.bool("entityShadows"),
biome_blend: f.int("biomeBlendRadius"),
graphics_preset: f.name("graphicsPreset"),
mipmap_levels: f.int("mipmapLevels"),
weather_radius: f.int("weatherRadius"),
chunk_fade: f.double("chunkSectionFadeInTime") as f32,
vignette: f.bool("vignette"),
autosave_indicator: f.bool("showAutosaveIndicator"),
cutout_leaves: f.bool("cutoutLeaves"),
improved_transparency: f.bool("improvedTransparency"),
attack_indicator: f.int("attackIndicator") as u8,
inactivity_fps_limit: f.name("inactivityFpsLimit"),
prioritize_chunk_updates: f.int("prioritizeChunkUpdates") as u8,
menu_blur: f.int("menuBackgroundBlurriness"),
invert_x: f.bool("invertXMouse"),
invert_y: f.bool("invertYMouse"),
mouse_wheel_sensitivity: f.double("mouseWheelSensitivity") as f32,
discrete_scroll: f.bool("discrete_mouse_scroll"),
toggle_crouch: f.bool("toggleCrouch"),
toggle_sprint: f.bool("toggleSprint"),
toggle_attack: f.bool("toggleAttack"),
toggle_use: f.bool("toggleUse"),
sprint_window: f.int("sprintWindow"),
auto_jump: f.bool("autoJump"),
language: f.string("lang"),
force_unicode: f.bool("forceUnicodeFont"),
japanese_glyphs: f.bool("japaneseGlyphVariants"),
chat_visibility: f.int("chatVisibility") as u8,
chat_colors: f.bool("chatColors"),
chat_links: f.bool("chatLinks"),
chat_opacity: f.double("chatOpacity") as f32,
text_background_opacity: f.double("textBackgroundOpacity") as f32,
chat_scale: f.double("chatScale") as f32,
chat_width: f.double("chatWidth") as f32,
chat_height_focused: f.double("chatHeightFocused") as f32,
chat_height_unfocused: f.double("chatHeightUnfocused") as f32,
chat_line_spacing: f.double("chatLineSpacing") as f32,
auto_suggestions: f.bool("autoSuggestions"),
reduced_debug_info: f.bool("reducedDebugInfo"),
high_contrast: f.bool("highContrast"),
show_subtitles: f.bool("showSubtitles"),
notification_display_time: f.double("notificationDisplayTime") as f32,
main_hand_left: f.name("mainHand") == "left",
resource_packs: f.list("resourcePacks"),
keys,
file: f,
}
}
/// The options file reflecting the typed fields; values the game did not
/// change keep their stored form.
pub fn to_file(&self) -> OptionsFile {
let mut f = self.file.clone();
put_i(&mut f, "fov", self.fov as i32);
put_i(&mut f, "renderDistance", self.render_distance);
put_i(&mut f, "simulationDistance", self.simulation_distance);
put_f(&mut f, "mouseSensitivity", self.sensitivity);
for (i, source) in SOUND_SOURCES.iter().enumerate() {
let v = if i == 0 {
self.master_volume
} else {
self.volumes[i]
};
lines.push((format!("soundCategory_{source}"), v.to_string()));
put_f(&mut f, &format!("soundCategory_{source}"), v);
}
let known: std::collections::BTreeSet<String> =
lines.iter().map(|(k, _)| k.clone()).collect();
for (k, v) in &self.extra {
if !known.contains(k) {
lines.push((k.clone(), v.clone()));
}
put_i(&mut f, "guiScale", self.gui_scale as i32);
put_b(&mut f, "bobView", self.view_bobbing);
put_f(&mut f, "gamma", self.gamma);
put_i(&mut f, "maxFps", self.max_fps as i32);
put_b(&mut f, "enableVsync", self.vsync);
put_b(&mut f, "fullscreen", self.fullscreen);
put_b(&mut f, "ao", self.smooth_lighting);
put_name(&mut f, "renderClouds", &self.clouds);
put_i(&mut f, "cloudRange", self.cloud_range);
put_i(&mut f, "particles", i32::from(self.particles));
put_f(&mut f, "entityDistanceScaling", self.entity_distance);
put_b(&mut f, "entityShadows", self.entity_shadows);
put_i(&mut f, "biomeBlendRadius", self.biome_blend);
put_name(&mut f, "graphicsPreset", &self.graphics_preset);
put_i(&mut f, "mipmapLevels", self.mipmap_levels);
put_i(&mut f, "weatherRadius", self.weather_radius);
put_f(&mut f, "chunkSectionFadeInTime", self.chunk_fade);
put_b(&mut f, "vignette", self.vignette);
put_b(&mut f, "showAutosaveIndicator", self.autosave_indicator);
put_b(&mut f, "cutoutLeaves", self.cutout_leaves);
put_b(&mut f, "improvedTransparency", self.improved_transparency);
put_i(&mut f, "attackIndicator", i32::from(self.attack_indicator));
put_name(&mut f, "inactivityFpsLimit", &self.inactivity_fps_limit);
put_i(
&mut f,
"prioritizeChunkUpdates",
i32::from(self.prioritize_chunk_updates),
);
put_i(&mut f, "menuBackgroundBlurriness", self.menu_blur);
put_b(&mut f, "invertXMouse", self.invert_x);
put_b(&mut f, "invertYMouse", self.invert_y);
put_f(
&mut f,
"mouseWheelSensitivity",
self.mouse_wheel_sensitivity,
);
put_b(&mut f, "discrete_mouse_scroll", self.discrete_scroll);
put_b(&mut f, "toggleCrouch", self.toggle_crouch);
put_b(&mut f, "toggleSprint", self.toggle_sprint);
put_b(&mut f, "toggleAttack", self.toggle_attack);
put_b(&mut f, "toggleUse", self.toggle_use);
put_i(&mut f, "sprintWindow", self.sprint_window);
put_b(&mut f, "autoJump", self.auto_jump);
put_s(&mut f, "lang", &self.language);
put_b(&mut f, "forceUnicodeFont", self.force_unicode);
put_b(&mut f, "japaneseGlyphVariants", self.japanese_glyphs);
put_i(&mut f, "chatVisibility", i32::from(self.chat_visibility));
put_b(&mut f, "chatColors", self.chat_colors);
put_b(&mut f, "chatLinks", self.chat_links);
put_f(&mut f, "chatOpacity", self.chat_opacity);
put_f(
&mut f,
"textBackgroundOpacity",
self.text_background_opacity,
);
put_f(&mut f, "chatScale", self.chat_scale);
put_f(&mut f, "chatWidth", self.chat_width);
put_f(&mut f, "chatHeightFocused", self.chat_height_focused);
put_f(&mut f, "chatHeightUnfocused", self.chat_height_unfocused);
put_f(&mut f, "chatLineSpacing", self.chat_line_spacing);
put_b(&mut f, "autoSuggestions", self.auto_suggestions);
put_b(&mut f, "reducedDebugInfo", self.reduced_debug_info);
put_b(&mut f, "highContrast", self.high_contrast);
put_b(&mut f, "showSubtitles", self.show_subtitles);
put_f(
&mut f,
"notificationDisplayTime",
self.notification_display_time,
);
put_name(
&mut f,
"mainHand",
if self.main_hand_left { "left" } else { "right" },
);
if self.resource_packs != f.list("resourcePacks") {
f.set("resourcePacks", V::List(self.resource_packs.clone()));
}
let mut out = format!("version:{}\n", horizon_world::DATA_VERSION);
for (k, v) in lines {
out.push_str(&format!("{k}:{v}\n"));
for (name, key) in self.keys.saved() {
put_s(&mut f, &format!("key_{name}"), &key);
}
out
f
}
/// The `options.txt` text (Options.save).
pub fn serialize(&self) -> String {
self.to_file().serialize()
}
pub fn save(&self, path: &Path) {
let _ = fs::write(path, self.serialize());
@@ -538,7 +506,8 @@ mod tests {
let out = s.serialize();
assert!(out.starts_with("version:"));
assert!(out.contains("\nkey_key.jump:key.keyboard.j\n"));
assert!(out.contains("\nsomeFutureOption:42\n"));
// Options.save writes only the options it knows.
assert!(!out.contains("someFutureOption"));
assert!(out.contains("\nrenderClouds:\"fast\"\n"));
let again = Settings::parse(&out);
assert_eq!(again.fov, 90.0);
@@ -555,10 +524,10 @@ mod tests {
let d = Settings::parse("");
assert!(!d.show_subtitles);
assert_eq!(d.notification_display_time, 1.0);
// The multiplier stays within the slider's range.
// Codec.doubleRange(0.5, 10.0) rejects other values; the default stays.
assert_eq!(
Settings::parse("notificationDisplayTime:50\n").notification_display_time,
10.0
1.0
);
}
}
+48 -4
View File
@@ -8,6 +8,7 @@ use crate::{
mesher::{MeshTables, Mesher, Region, SectionMesh, borrow},
world::World,
};
use horizon_core::biome::BiomeZoom;
use std::{
collections::{BinaryHeap, HashMap, HashSet},
sync::{
@@ -40,12 +41,21 @@ pub trait ChunkGenerator: Send + Sync + 'static {
fn decorate(&self, _worker: &mut Self::Worker, _region: &mut [Proto; 9]) {}
fn finish(&self, proto: Proto) -> Chunk;
}
/// Per-job mesher inputs that change with the dimension or the options.
#[derive(Clone, Copy)]
struct MeshSettings {
nether: bool,
zoom: BiomeZoom,
blend_radius: i32,
smooth_lighting: bool,
cutout_leaves: bool,
}
enum Job {
Generate(i32, i32),
Decorate(i32, i32, Box<[Proto; 9]>),
Finish(Proto),
Light(i32, i32, Box<Region>, u64, bool),
Mesh(i32, i32, i32, Box<Region>, u64, bool),
Mesh(i32, i32, i32, Box<Region>, u64, MeshSettings),
}
pub enum Done {
Generated(Chunk),
@@ -111,6 +121,12 @@ pub struct Streaming {
/// Dimension flags: sky light, Nether face shading.
pub sky_light: bool,
pub nether_shading: bool,
/// `BiomeManager`'s zoom seed (the hashed world seed) and `biomeBlendRadius`.
pub biome_zoom: BiomeZoom,
pub biome_blend: i32,
/// The `ao` and `cutoutLeaves` options.
pub smooth_lighting: bool,
pub cutout_leaves: bool,
/// Incremental relighting of block edits on lit chunks (see `light::relight`).
light_tables: Arc<LightTables>,
/// Applied edits by sequence, replayed onto light jobs snapshotted before them.
@@ -158,6 +174,10 @@ impl Streaming {
let mut worker = generator.worker();
let mut mesher = Mesher {
nether_shading: false,
zoom: BiomeZoom::new(0),
blend_radius: 2,
smooth_lighting: true,
cutout_leaves: true,
assets: &context.assets,
tables: &context.tables,
biomes: &context.biomes,
@@ -192,8 +212,12 @@ impl Streaming {
light_chunk(&borrow(&region), &context.light, sky),
seq,
),
Job::Mesh(x, sy, z, region, seq, nether) => {
mesher.nether_shading = nether;
Job::Mesh(x, sy, z, region, seq, settings) => {
mesher.nether_shading = settings.nether;
mesher.zoom = settings.zoom;
mesher.blend_radius = settings.blend_radius;
mesher.smooth_lighting = settings.smooth_lighting;
mesher.cutout_leaves = settings.cutout_leaves;
Done::Meshed(x, sy, z, mesher.mesh(&borrow(&region), sy), seq)
}
};
@@ -227,6 +251,10 @@ impl Streaming {
paused: false,
sky_light: true,
nether_shading: false,
biome_zoom: BiomeZoom::new(0),
biome_blend: 2,
smooth_lighting: true,
cutout_leaves: true,
light_tables,
light_log: Vec::new(),
light_edit_sequence: 0,
@@ -333,6 +361,9 @@ impl Streaming {
world
.block_entities
.extend(std::mem::take(&mut chunk.block_entities));
world
.block_names
.extend(std::mem::take(&mut chunk.block_names));
let entities = std::mem::take(&mut chunk.entities);
if !entities.is_empty() {
world.loaded_entities.push(((chunk.x, chunk.z), entities));
@@ -599,7 +630,20 @@ impl Streaming {
self.meshing.insert((x, sy, z), self.sequence);
self.submit(
self.distance(x, z) * 4 + if first { 2 } else { 0 },
Job::Mesh(x, sy, z, region, self.sequence, self.nether_shading),
Job::Mesh(
x,
sy,
z,
region,
self.sequence,
MeshSettings {
nether: self.nether_shading,
zoom: self.biome_zoom,
blend_radius: self.biome_blend,
smooth_lighting: self.smooth_lighting,
cutout_leaves: self.cutout_leaves,
},
),
);
}
(uploads, removed)
+4 -3
View File
@@ -59,12 +59,13 @@ fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
}
@fragment fn fs_solid(in: TerrainOut) -> @location(0) vec4<f32> {
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color;
if color.a < 0.5 { discard; }
// Bit 31 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color;
if color.a < 0.5 && (in.layer & 0x80000000u) == 0u { discard; }
return apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical);
}
@fragment fn fs_translucent(in: TerrainOut) -> @location(0) vec4<f32> {
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer)) * in.color;
let color = textureSample(sprites, sprite_sampler, in.uv, i32(in.layer & 0x7fffffffu)) * in.color;
if color.a < 0.01 { discard; }
return apply_fog(color, in.spherical, in.cylindrical);
}
+6 -1
View File
@@ -76,7 +76,12 @@ impl ChunkGenerator for TestTerrain {
impl TestTerrain {
fn generate(&self, _: &mut (), cx: i32, cz: i32) -> Chunk {
let mut chunk = Chunk::empty(cx, cz);
chunk.biomes = std::sync::Arc::new(vec![self.plains; chunk.biomes.len()]);
for s in &mut chunk.sections {
std::sync::Arc::make_mut(s).biomes = horizon_core::paletted::PalettedContainer::new(
crate::chunk::BIOME_STRATEGY,
u32::from(self.plains),
);
}
for z in 0..16 {
for x in 0..16 {
let (wx, wz) = (cx * 16 + x, cz * 16 + z);
+29 -19
View File
@@ -2,10 +2,10 @@
//! aquifers, surface rules, carvers and placed features) to chunk streaming.
use crate::{
biome::Biomes,
chunk::{Chunk, HEIGHT, MIN_Y},
chunk::{BIOME_STRATEGY, Chunk, HEIGHT, MIN_Y, SECTIONS, Section},
streaming::{ChunkGenerator, Proto},
};
use horizon_core::position::ChunkPos;
use horizon_core::{paletted::PalettedContainer, position::ChunkPos};
use horizon_world::{
registry::BlockRegistry,
worldgen::generator::{GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk},
@@ -177,15 +177,27 @@ impl ChunkGenerator for VanillaTerrain {
chunk.terrain.min_y().max(MIN_Y),
(chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT),
);
for y in lo..hi {
for z in 0..16 {
for x in 0..16 {
let id = chunk.block(bx + x, y, bz + z).0 as u16;
if id != 0 {
out.set(x, y, z, id);
let mut values = Box::new([0u16; 4096]);
for si in 0..SECTIONS as i32 {
let base = MIN_Y + si * 16;
if base + 16 <= lo || base >= hi {
continue;
}
values.fill(0);
let mut any = false;
for y in base.max(lo)..(base + 16).min(hi) {
for z in 0..16 {
for x in 0..16 {
let id = chunk.block(bx + x, y, bz + z).0 as u16;
values[((y & 15) << 8 | z << 4 | x) as usize] = id;
any |= id != 0;
}
}
}
if any {
Arc::make_mut(&mut out.sections[si as usize]).blocks =
Section::from_blocks(&values);
}
}
let base_section = chunk.terrain.min_y() >> 4;
for (i, marks) in chunk.terrain.postprocessing().iter().enumerate() {
@@ -199,19 +211,17 @@ impl ChunkGenerator for VanillaTerrain {
}
}
}
let mut biomes = vec![0u16; 16 * (HEIGHT as usize / 4)];
for qy in 0..HEIGHT / 4 {
for qz in 0..4 {
for qx in 0..4 {
let y = (MIN_Y + qy * 4).clamp(lo, hi - 1);
let id = chunk.biome_id_at(bx + qx * 4, y, bz + qz * 4);
let index = id.0 as usize;
biomes[(qy * 16 + qz * 4 + qx) as usize] =
self.biome_map.get(index).copied().unwrap_or(0);
}
for si in 0..SECTIONS as i32 {
let mut cells = [0u32; 64];
for (j, cell) in cells.iter_mut().enumerate() {
let (qx, qz, qy) = (j as i32 & 3, (j as i32 >> 2) & 3, si * 4 + (j as i32 >> 4));
let y = (MIN_Y + qy * 4).clamp(lo, hi - 1);
let id = chunk.biome_id_at(bx + qx * 4, y, bz + qz * 4);
*cell = u32::from(self.biome_map.get(id.0 as usize).copied().unwrap_or(0));
}
Arc::make_mut(&mut out.sections[si as usize]).biomes =
PalettedContainer::from_values(BIOME_STRATEGY, &cells);
}
out.biomes = Arc::new(biomes);
out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref());
out.structure_refs = chunk
.structures()
+246
View File
@@ -0,0 +1,246 @@
//! Window sizing and frame pacing of 26.3: `Window.calculateScale` and
//! `setGuiScale`, `MouseHandler`'s scaled positions, `FramerateLimitTracker`,
//! `FramerateLimiter` and the vsync present-mode choice.
/// `Window.calculateScale`: the largest scale that leaves at least 320x240
/// GUI pixels, capped by `max_scale` (0 = automatic); an odd result is bumped
/// to even when unicode is enforced.
pub fn calculate_scale(framebuffer: [i32; 2], max_scale: i32, enforce_unicode: bool) -> i32 {
let [width, height] = framebuffer;
let mut scale = 1;
while scale != max_scale
&& scale < width
&& scale < height
&& width / (scale + 1) >= 320
&& height / (scale + 1) >= 240
{
scale += 1;
}
if enforce_unicode && scale % 2 != 0 {
scale += 1;
}
scale
}
/// `Window.setGuiScale`: the GUI-scaled size of a framebuffer.
pub fn gui_scaled_size(framebuffer: [i32; 2], gui_scale: i32) -> [i32; 2] {
let scaled = |v: i32| (f64::from(v) / f64::from(gui_scale)).ceil() as i32;
[scaled(framebuffer[0]), scaled(framebuffer[1])]
}
/// `MouseHandler.getScaledXPos`/`getScaledYPos`.
pub fn scaled_pos(pos: f64, gui_scaled: i32, screen: i32) -> f64 {
pos * f64::from(gui_scaled) / f64::from(screen)
}
/// `InactivityFpsLimit`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InactivityFpsLimit {
Minimized,
Afk,
}
/// `FramerateLimitTracker.FramerateThrottleReason`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ThrottleReason {
None,
WindowIconified,
LongAfk,
ShortAfk,
OutOfLevelMenu,
}
/// What `FramerateLimitTracker` looks at.
#[derive(Clone, Copy, Debug)]
pub struct FrameContext {
pub inactivity: InactivityFpsLimit,
pub iconified: bool,
pub focused: bool,
pub exclusive_fullscreen: bool,
pub now_ms: i64,
pub latest_input_ms: i64,
pub has_level: bool,
pub has_screen: bool,
pub has_overlay: bool,
}
/// `getThrottleReason`.
pub fn throttle_reason(c: FrameContext) -> ThrottleReason {
if !c.iconified && (c.focused || !c.exclusive_fullscreen) {
if c.inactivity == InactivityFpsLimit::Afk {
let afk = c.now_ms - c.latest_input_ms;
if afk > 600_000 {
return ThrottleReason::LongAfk;
}
if afk > 60_000 {
return ThrottleReason::ShortAfk;
}
}
if c.has_level || (!c.has_screen && !c.has_overlay) {
ThrottleReason::None
} else {
ThrottleReason::OutOfLevelMenu
}
} else {
ThrottleReason::WindowIconified
}
}
/// `getFramerateLimit`.
pub fn framerate_limit(option_limit: i32, c: FrameContext) -> i32 {
match throttle_reason(c) {
ThrottleReason::None => option_limit,
ThrottleReason::WindowIconified | ThrottleReason::LongAfk => 10,
ThrottleReason::ShortAfk => option_limit.min(30),
ThrottleReason::OutOfLevelMenu => 60,
}
}
/// `isHeavilyThrottled`.
pub fn heavily_throttled(reason: ThrottleReason) -> bool {
matches!(
reason,
ThrottleReason::WindowIconified | ThrottleReason::LongAfk
)
}
/// Present modes the renderer can choose between.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PresentMode {
Fifo,
Mailbox,
Immediate,
}
/// `GpuSurface.PresentMode.getSupportedVsyncMode`: vsync means Fifo only,
/// otherwise the first of Immediate, Mailbox, Fifo that is supported.
pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option<PresentMode> {
let preferred: &[PresentMode] = if vsync {
&[PresentMode::Fifo]
} else {
&[
PresentMode::Immediate,
PresentMode::Mailbox,
PresentMode::Fifo,
]
};
preferred.iter().copied().find(|m| supported.contains(m))
}
/// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep
/// and spin decisions are testable.
#[derive(Clone, Debug)]
pub struct FramerateLimiter {
last_frame_time: i64,
average_overshoot_ns: i64,
last_framerate_limit: i32,
}
/// Time source of the limiter.
pub trait LimiterClock {
fn nanos(&mut self) -> i64;
/// `LockSupport.parkNanos`.
fn park(&mut self, nanos: i64);
/// `Thread.onSpinWait`.
fn spin(&mut self);
}
impl FramerateLimiter {
pub fn new(now_ns: i64) -> Self {
Self {
last_frame_time: now_ns,
average_overshoot_ns: 0,
last_framerate_limit: 0,
}
}
pub fn limit_display_fps(&mut self, framerate_limit: i32, clock: &mut impl LimiterClock) {
let target_time_per_frame = 1_000_000_000 / i64::from(framerate_limit);
let target_time_ns = self.last_frame_time + target_time_per_frame;
if framerate_limit != self.last_framerate_limit {
self.average_overshoot_ns = 0;
self.last_framerate_limit = framerate_limit;
}
loop {
let remaining = target_time_ns - clock.nanos();
if remaining <= 0 {
break;
}
if remaining > self.average_overshoot_ns + 500_000 {
let sleep_start = clock.nanos();
let expected = remaining - self.average_overshoot_ns - 500_000;
clock.park(expected);
let duration = clock.nanos() - sleep_start;
let overshoot = duration - expected;
if overshoot > 0 && overshoot < 25_000_000 {
self.average_overshoot_ns =
(0.1 * overshoot as f64 + 0.9 * self.average_overshoot_ns as f64) as i64;
self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000);
}
} else {
clock.spin();
}
}
self.last_frame_time = clock.nanos();
}
pub fn last_frame_time(&self) -> i64 {
self.last_frame_time
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Virtual {
now: i64,
oversleep: i64,
}
impl LimiterClock for Virtual {
fn nanos(&mut self) -> i64 {
self.now
}
fn park(&mut self, nanos: i64) {
self.now += nanos + self.oversleep;
}
fn spin(&mut self) {
self.now += 1000;
}
}
#[test]
fn scale_matches_the_320_by_240_rule() {
assert_eq!(calculate_scale([854, 480], 0, false), 2);
assert_eq!(calculate_scale([1920, 1080], 0, false), 4);
assert_eq!(calculate_scale([1920, 1080], 3, false), 3);
assert_eq!(calculate_scale([1920, 1080], 3, true), 4);
assert_eq!(gui_scaled_size([1921, 1081], 4), [481, 271]);
}
#[test]
fn limiter_paces_frames_at_the_target() {
let mut limiter = FramerateLimiter::new(0);
let mut clock = Virtual {
now: 1_000_000,
oversleep: 200_000,
};
limiter.limit_display_fps(100, &mut clock);
assert!(clock.now >= 10_000_000);
assert!(clock.now < 10_000_000 + 1_000_000);
}
#[test]
fn vsync_only_uses_fifo() {
let all = [
PresentMode::Mailbox,
PresentMode::Fifo,
PresentMode::Immediate,
];
assert_eq!(vsync_present_mode(&all, true), Some(PresentMode::Fifo));
assert_eq!(
vsync_present_mode(&all, false),
Some(PresentMode::Immediate)
);
assert_eq!(
vsync_present_mode(&[PresentMode::Fifo], false),
Some(PresentMode::Fifo)
);
}
}
+3
View File
@@ -26,6 +26,8 @@ pub struct World {
/// Chunks changed since the last save.
pub modified: HashSet<(i32, i32)>,
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
/// `BaseContainerBlockEntity.name`: custom names of container block entities.
pub block_names: HashMap<(i32, i32, i32), String>,
/// States (by id) whose writes are recorded in `watched_writes` (sculk
/// blocks, which need a block entity).
pub watched: Vec<bool>,
@@ -114,6 +116,7 @@ impl World {
loaded_entities: Vec::new(),
modified: HashSet::new(),
block_entities: HashMap::new(),
block_names: HashMap::new(),
watched: Vec::new(),
watched_writes: Vec::new(),
inhabited: HashMap::new(),
@@ -0,0 +1,136 @@
//! Text transport for the PalettedContainer comparison: replays scripted edits
//! and prints the same hashes as `VanillaPalettedContainerOracle`.
use horizon_core::paletted::{PalettedContainer, Strategy};
use std::{
fs,
io::{self, Write},
};
const BASIS: u64 = 0xcbf2_9ce4_8422_2325;
fn fnv(h: u64, b: u8) -> u64 {
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
}
fn hash_bytes(bytes: &[u8]) -> u64 {
bytes.iter().fold(BASIS, |h, &b| fnv(h, b))
}
fn varint(out: &mut Vec<u8>, mut v: u32) {
while v >= 0x80 {
out.push((v & 0x7F) as u8 | 0x80);
v >>= 7;
}
out.push(v as u8);
}
/// `PalettedContainer.write`.
fn write(c: &PalettedContainer) -> Vec<u8> {
let (bits, palette, words) = c.to_wire();
let mut out = vec![bits];
if bits == 0 {
varint(&mut out, palette[0]);
} else if !palette.is_empty() {
varint(&mut out, palette.len() as u32);
for p in palette {
varint(&mut out, p);
}
}
for w in words {
out.extend(w.to_be_bytes());
}
out
}
/// `PalettedContainer.read` for the leading byte, palette and longs.
fn read(strategy: Strategy, bytes: &[u8]) -> PalettedContainer {
let mut at = 1;
let mut varint = || {
let (mut v, mut shift) = (0u32, 0);
loop {
let b = bytes[at];
at += 1;
v |= u32::from(b & 0x7F) << shift;
if b & 0x80 == 0 {
return v;
}
shift += 7;
}
};
let bits = bytes[0];
let palette = if bits == 0 {
vec![varint()]
} else if strategy.wire_has_palette(bits) {
let n = varint();
(0..n).map(|_| varint()).collect()
} else {
Vec::new()
};
let words = bytes[at..]
.chunks_exact(8)
.map(|c| u64::from_be_bytes(c.try_into().unwrap()))
.collect();
PalettedContainer::from_wire(strategy, bits, palette, words).unwrap()
}
fn wire(c: &PalettedContainer) -> String {
let bytes = write(c);
format!("{}:{}", bytes.len(), hash_bytes(&bytes) as i64)
}
fn values(c: &PalettedContainer) -> i64 {
let mut h = BASIS;
for i in 0..c.strategy().entries() {
for b in c.get(i).to_le_bytes() {
h = fnv(h, b);
}
}
h as i64
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
let mut out = io::BufWriter::new(fs::File::create(&args[2])?);
for line in fs::read_to_string(&args[1])?.lines() {
let t: Vec<&str> = line.split_whitespace().collect();
let strategy = if t[1] == "blocks" {
Strategy::blocks(16)
} else {
Strategy::biomes(7)
};
let mut c = PalettedContainer::new(strategy, t[2].parse()?);
let every: usize = t[3].parse()?;
let (mut olds, mut n) = (BASIS, 0usize);
let mut checkpoints = Vec::new();
for pair in t[4..].chunks(2) {
let old = c.set(pair[0].parse()?, pair[1].parse()?);
for b in old.to_le_bytes() {
olds = fnv(olds, b);
}
n += 1;
if n % every == 0 {
checkpoints.push(wire(&c));
}
}
let reread = read(strategy, &write(&c));
let packed = c.pack();
let storage = packed.data.as_ref().map_or(BASIS, |data| {
data.iter().flat_map(|w| w.to_le_bytes()).fold(BASIS, fnv)
});
let palette: Vec<String> = packed.palette.iter().map(u32::to_string).collect();
let loaded = PalettedContainer::from_packed(
strategy,
packed.palette.clone(),
packed.data.as_deref(),
)?;
writeln!(
out,
"{} {} cp={} bits={} final={} values={} read={}/{} packed={}/{}/{} loaded={}/{}",
t[0],
olds as i64,
checkpoints.join(","),
c.bits(),
wire(&c),
values(&c),
values(&reread),
wire(&reread),
packed.bits,
storage as i64,
palette.join(","),
values(&loaded),
wire(&loaded),
)?;
}
Ok(())
}
+1
View File
@@ -9,6 +9,7 @@ pub mod carving;
pub mod density;
pub mod geometry;
pub mod noise;
pub mod paletted;
pub mod position;
pub mod random;
pub mod storage;
+744
View File
@@ -0,0 +1,744 @@
//! Resident `PalettedContainer` of Java Edition 26.3: single-value, linear and
//! hash-map palettes with vanilla's bit-width thresholds, and the global
//! palette beyond them, over `SimpleBitStorage` words (values never span
//! longs). One container type serves blocks (16^3 entries) and biomes (4^3).
//!
//! Growth follows `PalettedContainer.onResize`: a full palette asks for one
//! more bit, the new configuration is built by re-adding the distinct values
//! in index order, and the value that did not fit is added last. Palettes
//! never shrink while resident; `pack` writes the canonical saved form.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
/// `Strategy.createForBlockStates`: 4096 entries, linear palettes up to 4
/// bits and hash-map palettes from 5 to 8.
Blocks,
/// `Strategy.createForBiomes`: 64 entries, linear palettes up to 3 bits.
Biomes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Strategy {
pub kind: Kind,
/// `ceillog2` of the registry size: the width of the global palette.
pub global_bits: u8,
}
/// `getConfigurationForBitCount`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Config {
Single,
/// Palette of up to `1 << bits` entries, stored in `bits` bits.
List(u8),
Global,
}
impl Strategy {
pub const fn blocks(global_bits: u8) -> Self {
Self {
kind: Kind::Blocks,
global_bits,
}
}
pub const fn biomes(global_bits: u8) -> Self {
Self {
kind: Kind::Biomes,
global_bits,
}
}
pub const fn entries(self) -> usize {
match self.kind {
Kind::Blocks => 4096,
Kind::Biomes => 64,
}
}
fn config(self, bits: u8) -> Config {
match (self.kind, bits) {
(_, 0) => Config::Single,
(Kind::Blocks, 1..=4) => Config::List(4),
(Kind::Blocks, 5..=8) => Config::List(bits),
(Kind::Biomes, 1..=3) => Config::List(bits),
_ => Config::Global,
}
}
/// Whether a container written with leading byte `bits` lists its palette
/// (all but the global one).
pub fn wire_has_palette(self, bits: u8) -> bool {
self.config(bits) != Config::Global
}
/// Bits of the storage a configuration keeps in memory.
fn storage_bits(self, config: Config) -> u8 {
match config {
Config::Single => 0,
Config::List(bits) => bits,
Config::Global => self.global_bits,
}
}
}
/// `Mth.ceillog2`.
pub fn ceil_log2(n: usize) -> u8 {
if n <= 1 {
0
} else {
(usize::BITS - (n - 1).leading_zeros()) as u8
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PaletteError {
/// A palette bigger than its configuration allows, or empty.
BadPalette { len: usize },
/// Storage with the wrong number of longs.
BadStorage { expected: usize, actual: usize },
/// A stored index past the palette.
BadIndex { index: u32, palette: usize },
/// The declared bit count does not match the palette.
BadBits { declared: u8, expected: u8 },
}
impl std::fmt::Display for PaletteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for PaletteError {}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Palette {
Single(u32),
/// Linear and hash-map palettes alike: ids in insertion order.
List(Vec<u32>),
Global,
}
/// `n / per_word` for `n < 4096` by multiplication: `MAGIC[bits] = ceil(2^20 /
/// (64 / bits))` is exact while `n * (64 / bits) < 2^20`.
const MAGIC: [u32; 33] = {
let mut table = [0; 33];
let mut bits = 1;
while bits <= 32 {
let per = 64 / bits as u32;
table[bits] = (1u32 << 20).div_ceil(per);
bits += 1;
}
table
};
/// Words of `bits`-wide values: `entries.div_ceil(64 / bits)`.
pub fn storage_len(bits: u8, entries: usize) -> usize {
if bits == 0 {
0
} else {
entries.div_ceil(64 / usize::from(bits))
}
}
#[inline]
fn locate(bits: u8, i: usize) -> (usize, u32) {
if bits.is_power_of_two() {
// 64 / bits is a power of two: shifts instead of the multiplication.
let log = bits.trailing_zeros();
let word = i >> (6 - log);
(word, ((i & ((64 >> log) - 1)) as u32) << log)
} else {
let per = 64 / u32::from(bits);
let word = (i as u32 * MAGIC[usize::from(bits)]) >> 20;
(word as usize, (i as u32 - word * per) * u32::from(bits))
}
}
#[inline]
fn mask(bits: u8) -> u64 {
(1u64 << bits) - 1
}
fn read(words: &[u64], bits: u8, i: usize) -> u32 {
let (word, shift) = locate(bits, i);
((words[word] >> shift) & mask(bits)) as u32
}
fn write(words: &mut [u64], bits: u8, i: usize, value: u32) {
let (word, shift) = locate(bits, i);
words[word] = (words[word] & !(mask(bits) << shift)) | (u64::from(value) << shift);
}
/// Words holding `ids` in `bits`-wide slots.
fn pack_words(bits: u8, entries: usize, ids: impl Iterator<Item = u32>) -> Vec<u64> {
let mut words = vec![0u64; storage_len(bits, entries)];
for (i, id) in ids.enumerate() {
write(&mut words, bits, i, id);
}
words
}
/// The saved form: distinct values in index order, and the packed indices
/// when there is more than one value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Packed {
pub palette: Vec<u32>,
/// Bits per index in `data` (0 when `data` is absent).
pub bits: u8,
pub data: Option<Vec<u64>>,
}
#[derive(Clone, Debug)]
pub struct PalettedContainer {
strategy: Strategy,
bits: u8,
palette: Palette,
words: Vec<u64>,
}
impl PalettedContainer {
/// `new PalettedContainer(initialValue, strategy)`.
pub fn new(strategy: Strategy, value: u32) -> Self {
Self {
strategy,
bits: 0,
palette: Palette::Single(value),
words: Vec::new(),
}
}
pub fn strategy(&self) -> Strategy {
self.strategy
}
/// Bits per stored index (`BitStorage.getBits`).
pub fn bits(&self) -> u8 {
self.bits
}
/// Entries in the palette (the global palette reports its bit capacity).
pub fn palette_len(&self) -> usize {
match &self.palette {
Palette::Single(_) => 1,
Palette::List(list) => list.len(),
Palette::Global => 1 << self.bits.min(31),
}
}
pub fn is_global(&self) -> bool {
matches!(self.palette, Palette::Global)
}
#[inline]
fn raw(&self, i: usize) -> usize {
let (word, shift) = locate(self.bits, i);
((self.words[word] >> shift) & mask(self.bits)) as usize
}
#[inline]
pub fn get(&self, i: usize) -> u32 {
match &self.palette {
Palette::Single(value) => *value,
Palette::List(list) => list[self.raw(i)],
Palette::Global => self.raw(i) as u32,
}
}
/// The value when every entry is equal, without the palette having to be
/// minimal.
pub fn uniform(&self) -> Option<u32> {
match &self.palette {
Palette::Single(value) => Some(*value),
Palette::List(list) if list.len() == 1 => Some(list[0]),
Palette::Global => self.all_equal(self.get(0)).then(|| self.get(0)),
Palette::List(list) => {
let first = list[self.raw(0)];
self.all_equal(first).then_some(first)
}
}
}
/// Whether all entries equal `value`.
pub fn is_uniform(&self, value: u32) -> bool {
match &self.palette {
Palette::Single(v) => *v == value,
Palette::List(list) => match list.iter().position(|&v| v == value) {
None => false,
Some(_) if list.len() == 1 => true,
Some(_) => self.all_equal(value),
},
Palette::Global => self.all_equal(value),
}
}
fn all_equal(&self, value: u32) -> bool {
let id = match &self.palette {
Palette::Single(v) => return *v == value,
Palette::List(list) => match list.iter().position(|&v| v == value) {
Some(id) => id as u64,
None => return false,
},
Palette::Global => u64::from(value),
};
let bits = usize::from(self.bits);
let per = 64 / bits;
let pattern = (0..per).fold(0u64, |word, slot| word | id << (slot * bits));
let entries = self.strategy.entries();
let full = entries / per;
if self.words[..full].iter().any(|&w| w != pattern) {
return false;
}
let tail = entries - full * per;
tail == 0 || {
let used = (1u64 << (tail * bits)) - 1;
self.words[full] & used == pattern & used
}
}
/// `getAndSet`: stores `value` and returns the previous one.
pub fn set(&mut self, i: usize, value: u32) -> u32 {
let id = self.id_for(value);
match &self.palette {
Palette::Single(old) => *old,
Palette::List(list) => {
let old = read(&self.words, self.bits, i) as usize;
write(&mut self.words, self.bits, i, id as u32);
list[old]
}
Palette::Global => {
let old = read(&self.words, self.bits, i);
write(&mut self.words, self.bits, i, id as u32);
old
}
}
}
/// `Palette.idFor`, growing the container when the palette is full.
fn id_for(&mut self, value: u32) -> usize {
match &mut self.palette {
Palette::Single(v) if *v == value => 0,
Palette::Single(_) => self.resize(1, value),
Palette::List(list) => {
if let Some(id) = list.iter().position(|&v| v == value) {
id
} else if list.len() < 1 << self.bits {
list.push(value);
list.len() - 1
} else {
self.resize(self.bits + 1, value)
}
}
Palette::Global => value as usize,
}
}
/// `PalettedContainer.onResize`: rebuild with the configuration for
/// `bits`, then add `last` and return its id.
fn resize(&mut self, bits: u8, last: u32) -> usize {
let strategy = self.strategy;
let config = strategy.config(bits);
let storage_bits = strategy.storage_bits(config);
let entries = strategy.entries();
let mut palette = match config {
Config::Single => Palette::Single(last),
Config::List(_) => Palette::List(Vec::new()),
Config::Global => Palette::Global,
};
let mut words = vec![0u64; storage_len(storage_bits, entries)];
let id_in = |palette: &mut Palette, value: u32| -> u32 {
match palette {
Palette::Single(_) => 0,
Palette::List(list) => match list.iter().position(|&v| v == value) {
Some(id) => id as u32,
None => {
list.push(value);
list.len() as u32 - 1
}
},
Palette::Global => value,
}
};
if let Palette::Single(only) = self.palette {
let id = id_in(&mut palette, only);
if storage_bits > 0 && id != 0 {
for i in 0..entries {
write(&mut words, storage_bits, i, id);
}
}
} else {
let (mut last_old, mut new_id) = (u32::MAX, 0);
for i in 0..entries {
let old = read(&self.words, self.bits, i);
if old != last_old {
last_old = old;
let value = match &self.palette {
Palette::List(list) => list[old as usize],
_ => old,
};
new_id = id_in(&mut palette, value);
}
if storage_bits > 0 {
write(&mut words, storage_bits, i, new_id);
}
}
}
let id = id_in(&mut palette, last);
self.palette = palette;
self.bits = storage_bits;
self.words = words;
id as usize
}
/// All values in index order.
pub fn unpack(&self, out: &mut [u32]) {
assert_eq!(out.len(), self.strategy.entries());
match &self.palette {
Palette::Single(value) => out.fill(*value),
palette => {
let bits = usize::from(self.bits);
let per = 64 / bits;
let m = mask(self.bits);
for (chunk, &word) in out.chunks_mut(per).zip(&self.words) {
for (slot, cell) in chunk.iter_mut().enumerate() {
let id = ((word >> (slot * bits)) & m) as u32;
*cell = match palette {
Palette::List(list) => list[id as usize],
_ => id,
};
}
}
}
}
}
/// Block ids as 16-bit values (callers whose registry fits in 16 bits).
pub fn unpack_u16(&self, out: &mut [u16; 4096]) {
debug_assert_eq!(self.strategy.entries(), 4096);
match &self.palette {
Palette::Single(value) => out.fill(*value as u16),
palette => {
let bits = usize::from(self.bits);
let per = 64 / bits;
let m = mask(self.bits);
for (chunk, &word) in out.chunks_mut(per).zip(&self.words) {
for (slot, cell) in chunk.iter_mut().enumerate() {
let id = ((word >> (slot * bits)) & m) as usize;
*cell = match palette {
Palette::List(list) => list[id] as u16,
_ => id as u16,
};
}
}
}
}
}
/// A container holding `values` in the smallest configuration for their
/// distinct count, with palette ids in first-occurrence order, like a
/// container unpacked from disk.
pub fn from_values(strategy: Strategy, values: &[u32]) -> Self {
assert_eq!(values.len(), strategy.entries());
let mut palette: Vec<u32> = Vec::new();
let mut small = true;
let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
let mut ids = Vec::with_capacity(values.len());
for &value in values {
let id = if small {
match palette.iter().position(|&v| v == value) {
Some(id) => id as u32,
None => {
palette.push(value);
if palette.len() > 16 {
small = false;
lookup.extend(palette.iter().enumerate().map(|(i, &v)| (v, i as u32)));
}
palette.len() as u32 - 1
}
}
} else {
*lookup.entry(value).or_insert_with(|| {
palette.push(value);
palette.len() as u32 - 1
})
};
ids.push(id);
}
Self::build(strategy, palette, &ids)
}
/// A container over a distinct-value `palette` and an id per entry.
fn build(strategy: Strategy, palette: Vec<u32>, ids: &[u32]) -> Self {
let config = strategy.config(ceil_log2(palette.len()));
match config {
Config::Single => Self::new(strategy, palette[0]),
Config::List(bits) => Self {
strategy,
bits,
words: pack_words(bits, ids.len(), ids.iter().copied()),
palette: Palette::List(palette),
},
Config::Global => {
let bits = strategy.global_bits;
Self {
strategy,
bits,
words: pack_words(bits, ids.len(), ids.iter().map(|&id| palette[id as usize])),
palette: Palette::Global,
}
}
}
}
/// `PalettedContainer.read`: the container as sent on the wire. `bits` is
/// the leading byte, `palette` the VarInt entries (a single one for
/// `bits == 0`, none for the global palette) and `words` the longs.
pub fn from_wire(
strategy: Strategy,
bits: u8,
palette: Vec<u32>,
words: Vec<u64>,
) -> Result<Self, PaletteError> {
let config = strategy.config(bits);
let storage_bits = strategy.storage_bits(config);
let expected = storage_len(storage_bits, strategy.entries());
if words.len() != expected {
return Err(PaletteError::BadStorage {
expected,
actual: words.len(),
});
}
match config {
Config::Single => {
if palette.len() != 1 {
return Err(PaletteError::BadPalette { len: palette.len() });
}
Ok(Self::new(strategy, palette[0]))
}
Config::List(bits) => {
if palette.is_empty() || palette.len() > 1 << bits {
return Err(PaletteError::BadPalette { len: palette.len() });
}
let container = Self {
strategy,
bits,
palette: Palette::List(palette),
words,
};
container.check_indices()?;
Ok(container)
}
Config::Global => Ok(Self {
strategy,
bits: storage_bits,
palette: Palette::Global,
words,
}),
}
}
fn check_indices(&self) -> Result<(), PaletteError> {
let Palette::List(list) = &self.palette else {
return Ok(());
};
if list.len() == 1 << self.bits {
return Ok(());
}
for i in 0..self.strategy.entries() {
let index = read(&self.words, self.bits, i);
if index as usize >= list.len() {
return Err(PaletteError::BadIndex {
index,
palette: list.len(),
});
}
}
Ok(())
}
/// `PalettedContainer.write`: the leading bits byte, the palette entries
/// (none for the global palette) and the raw longs, exactly as resident.
pub fn to_wire(&self) -> (u8, Vec<u32>, &[u64]) {
let palette = match &self.palette {
Palette::Single(value) => vec![*value],
Palette::List(list) => list.clone(),
Palette::Global => Vec::new(),
};
(self.bits, palette, &self.words)
}
/// `PalettedContainer.pack`: distinct values in index order, indices
/// re-encoded for the saved bit width.
pub fn pack(&self) -> Packed {
let entries = self.strategy.entries();
let mut palette: Vec<u32> = Vec::new();
let mut ids = Vec::with_capacity(entries);
let mut values = vec![0u32; entries];
self.unpack(&mut values);
let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new();
for &value in &values {
let id = *lookup.entry(value).or_insert_with(|| {
palette.push(value);
palette.len() as u32 - 1
});
ids.push(id);
}
let bits = match self.strategy.config(ceil_log2(palette.len())) {
Config::Single => 0,
Config::List(bits) => bits,
Config::Global => ceil_log2(palette.len()),
};
let data = (bits != 0).then(|| pack_words(bits, entries, ids.iter().copied()));
Packed {
palette,
bits,
data,
}
}
/// `PalettedContainer.unpack`: a container from the saved form.
pub fn from_packed(
strategy: Strategy,
palette: Vec<u32>,
data: Option<&[u64]>,
) -> Result<Self, PaletteError> {
if palette.is_empty() {
return Err(PaletteError::BadPalette { len: 0 });
}
let config = strategy.config(ceil_log2(palette.len()));
let entries = strategy.entries();
let disc_bits = match config {
Config::Single => return Ok(Self::new(strategy, palette[0])),
Config::List(bits) => bits,
Config::Global => ceil_log2(palette.len()),
};
let data = data.ok_or(PaletteError::BadStorage {
expected: storage_len(disc_bits, entries),
actual: 0,
})?;
let expected = storage_len(disc_bits, entries);
if data.len() != expected {
return Err(PaletteError::BadStorage {
expected,
actual: data.len(),
});
}
let mut ids = Vec::with_capacity(entries);
for i in 0..entries {
let index = read(data, disc_bits, i);
if index as usize >= palette.len() {
return Err(PaletteError::BadIndex {
index,
palette: palette.len(),
});
}
ids.push(index);
}
Ok(match config {
Config::List(bits) => Self {
strategy,
bits,
words: data.to_vec(),
palette: Palette::List(palette),
},
_ => Self::build(strategy, palette, &ids),
})
}
/// Whether any palette entry satisfies `predicate` (`maybeHas`): entries
/// no longer used by any position still count.
pub fn maybe_has(&self, mut predicate: impl FnMut(u32) -> bool) -> bool {
match &self.palette {
Palette::Single(value) => predicate(*value),
Palette::List(list) => list.iter().any(|&v| predicate(v)),
Palette::Global => (0..1u32 << self.bits.min(31)).any(predicate),
}
}
/// Heap bytes held by the palette and the storage.
pub fn heap_bytes(&self) -> usize {
self.words.capacity() * 8
+ match &self.palette {
Palette::List(list) => list.capacity() * 4,
_ => 0,
}
}
}
impl PartialEq for PalettedContainer {
/// Equal when every entry is.
fn eq(&self, other: &Self) -> bool {
let entries = self.strategy.entries();
entries == other.strategy.entries() && (0..entries).all(|i| self.get(i) == other.get(i))
}
}
#[cfg(test)]
mod tests {
use super::*;
const BLOCKS: Strategy = Strategy::blocks(16);
const BIOMES: Strategy = Strategy::biomes(7);
fn rng(state: &mut u64) -> u64 {
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
*state
}
#[test]
fn grows_through_vanilla_widths() {
let mut c = PalettedContainer::new(BLOCKS, 0);
assert_eq!((c.bits(), c.palette_len()), (0, 1));
let mut expected = Vec::new();
for n in 1..=300u32 {
c.set(n as usize, n);
expected.push(match n + 1 {
2..=16 => 4,
17..=32 => 5,
33..=64 => 6,
65..=128 => 7,
129..=256 => 8,
_ => 16,
});
assert_eq!(c.bits(), *expected.last().unwrap(), "after {n} values");
}
assert!(c.is_global());
for n in 1..=300u32 {
assert_eq!(c.get(n as usize), n);
}
let mut b = PalettedContainer::new(BIOMES, 3);
for n in 1..=9u32 {
b.set(n as usize, n + 3);
let want = match n + 1 {
2 => 1,
3..=4 => 2,
5..=8 => 3,
_ => 7,
};
assert_eq!(b.bits(), want, "after {n} biomes");
}
}
#[test]
fn matches_a_plain_array_under_random_edits() {
for (strategy, distinct) in [(BLOCKS, 700u64), (BLOCKS, 12), (BIOMES, 9), (BIOMES, 3)] {
let entries = strategy.entries();
let mut state = 0x1234_5678_9ABC_DEF1u64;
let mut c = PalettedContainer::new(strategy, 5);
let mut plain = vec![5u32; entries];
for _ in 0..20_000 {
let r = rng(&mut state);
let i = (r % entries as u64) as usize;
let v = ((r >> 20) % distinct) as u32 * 7;
assert_eq!(c.set(i, v), plain[i]);
plain[i] = v;
}
let mut out = vec![0; entries];
c.unpack(&mut out);
assert_eq!(out, plain);
for (i, &v) in plain.iter().enumerate() {
assert_eq!(c.get(i), v);
}
let packed = c.pack();
let loaded = PalettedContainer::from_packed(
strategy,
packed.palette.clone(),
packed.data.as_deref(),
)
.unwrap();
assert_eq!(loaded, c);
assert_eq!(loaded.pack(), packed);
let again = PalettedContainer::from_values(strategy, &plain);
assert_eq!(again, c);
assert_eq!(again.pack(), packed);
let (bits, palette, words) = c.to_wire();
let wire =
PalettedContainer::from_wire(strategy, bits, palette, words.to_vec()).unwrap();
assert_eq!(wire, c);
}
}
#[test]
fn uniform_detection_ignores_stale_palette_entries() {
let mut c = PalettedContainer::new(BLOCKS, 0);
c.set(10, 3);
assert!(!c.is_uniform(0));
c.set(10, 0);
assert!(c.palette_len() == 2 && c.is_uniform(0) && c.uniform() == Some(0));
assert!(!c.is_uniform(3));
for i in 0..4096 {
c.set(i, 3);
}
assert_eq!(c.uniform(), Some(3));
}
#[test]
fn rejects_malformed_wire_data() {
assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![1, 2], vec![0; 255]).is_err());
assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![1, 2], vec![0x3333; 256]).is_err());
assert!(PalettedContainer::from_wire(BLOCKS, 4, vec![], vec![0; 256]).is_err());
assert!(PalettedContainer::from_wire(BLOCKS, 0, vec![1, 2], vec![]).is_err());
assert!(PalettedContainer::from_wire(BIOMES, 2, vec![1, 2, 3, 4, 5], vec![0; 4]).is_err());
assert!(PalettedContainer::from_wire(BLOCKS, 0, vec![9], vec![]).is_ok());
}
#[test]
fn division_magic_is_exact() {
for bits in 1..=32u8 {
let per = 64 / usize::from(bits);
for i in 0..4096usize {
assert_eq!(locate(bits, i).0, i / per, "bits {bits} index {i}");
}
}
}
}