Merge current main; restore player hurt sounds and bucket fluid updates

This commit is contained in:
Cosmic
2026-10-14 10:33:06 -04:00
108 changed files with 5857 additions and 501 deletions
@@ -20,10 +20,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
write!(output, " {x},{z},{direction},{}", u8::from(inside)).unwrap();
}
};
let radius = if *kind == 2 {
clouds::radius_cells(*x)
} else {
*x
};
if *kind == 0 {
cell(*x, *z, *neighbors);
} else {
for (x, z) in clouds::cells(*x) {
for (x, z) in clouds::cells(radius) {
cell(x, z, 0);
}
}
@@ -0,0 +1,86 @@
#![forbid(unsafe_code)]
//! Runs tools/test_container_screen_parity.py's screens and mouse events
//! through `horizon_client::container_screen`.
use horizon_client::{
Result,
container_screen::{Book, Button, Clicks, Image, Release, Target, clicked_outside},
menu::Input,
};
use serde_json::Value;
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
};
fn input_name(input: Input) -> &'static str {
match input {
Input::Pickup => "PICKUP",
Input::QuickMove => "QUICK_MOVE",
Input::Swap => "SWAP",
Input::Clone => "CLONE",
Input::Throw => "THROW",
Input::QuickCraft => "QUICK_CRAFT",
Input::PickupAll => "PICKUP_ALL",
}
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
let input = BufReader::new(File::open(&args[1])?);
let mut out = BufWriter::new(File::create(&args[2])?);
for (n, line) in input.lines().enumerate() {
let c: Value = serde_json::from_str(&line?)?;
writeln!(out, "== {n}")?;
let int = |v: &Value| v.as_i64().unwrap() as i32;
let image = Image {
left: int(&c["image"][0]),
top: int(&c["image"][1]),
width: int(&c["image"][2]),
height: int(&c["image"][3]),
};
let book = c.get("book").map(|b| Book {
visible: b[0].as_bool().unwrap(),
selected_tab_hovered: b[1].as_bool().unwrap(),
});
let mut clicks = Clicks::default();
for ev in c["events"].as_array().unwrap() {
let name = ev[0].as_str().unwrap();
let (x, y) = (ev[1].as_f64().unwrap(), ev[2].as_f64().unwrap());
let outside = clicked_outside(x, y, image, book);
let mut line = format!("{name} {outside}");
if name != "point" {
// The case says whether the event is over the menu's slot (7).
let on_slot = ev[6].as_bool().unwrap();
line += &format!(" {on_slot}");
let target = Target::of(on_slot.then_some(7), outside);
let button = match ev[3].as_i64().unwrap() {
1 => Button::Left,
3 => Button::Right,
_ => Button::Middle,
};
let shift = ev[4].as_i64().unwrap() & 3 != 0;
let carried_empty = !ev[5].as_bool().unwrap();
let click = if name == "press" {
clicks.press(&target, button, carried_empty, shift, false)
} else {
match clicks.release(&target, button, carried_empty, false, shift, false) {
Release::Click(input) => Some(input),
Release::QuickCraft => panic!("no drags in these cases"),
Release::Nothing => None,
}
};
if let Some(input) = click {
let id = match target {
Target::Slot(s) => s,
Target::Outside => -999,
Target::Nothing => -1,
};
line += &format!(" click {id} {} {}", button.menu_button(), input_name(input));
}
}
writeln!(out, "{line}")?;
}
}
out.flush()?;
Ok(())
}
@@ -0,0 +1,89 @@
#![forbid(unsafe_code)]
//! Runs tools/test_entity_components_parity.py's entities and advancement
//! entity predicates through `horizon_client::advancements::entity`, with the
//! variant component `mobs::finalize::species_variant_component` reports.
use horizon_client::{
Result,
advancements::{EntityView, World, entity},
mobs::{
Species,
finalize::{species_variant_component, variant_index},
},
};
use serde_json::Value;
use std::{
collections::BTreeMap,
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
};
/// Nothing but the entity: these predicates read only its type and components.
struct Empty;
impl World for Empty {
fn dimension(&self) -> &str {
"minecraft:overworld"
}
fn biome(&self, _: [i32; 3]) -> String {
"minecraft:plains".into()
}
fn structures(&self, _: [i32; 3]) -> Vec<String> {
Vec::new()
}
fn block(&self, _: [i32; 3]) -> (String, BTreeMap<String, String>) {
("minecraft:air".into(), BTreeMap::new())
}
fn fluid(&self, _: [i32; 3]) -> Option<String> {
None
}
fn can_see_sky(&self, _: [i32; 3]) -> bool {
true
}
fn light(&self, _: [i32; 3]) -> i32 {
15
}
fn smokey(&self, _: [i32; 3]) -> bool {
false
}
fn in_tag(&self, _: &str, _: &str, _: &str) -> bool {
false
}
}
fn species(id: &str) -> Species {
match id {
"minecraft:wolf" => Species::Wolf,
"minecraft:cat" => Species::Cat,
"minecraft:frog" => Species::Frog,
"minecraft:pig" => Species::Pig,
"minecraft:cow" => Species::Cow,
"minecraft:chicken" => Species::Chicken,
other => panic!("no species for {other}"),
}
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
let input = BufReader::new(File::open(&args[1])?);
let mut out = BufWriter::new(File::create(&args[2])?);
for (n, line) in input.lines().enumerate() {
let c: Value = serde_json::from_str(&line?)?;
writeln!(out, "== {n}")?;
let kind = c["type"].as_str().unwrap();
let s = species(kind);
let variant = variant_index(s, c["variant"].as_str().unwrap());
let view = EntityView {
kind: kind.to_owned(),
position: [0.5, 64.0, 0.5],
components: species_variant_component(s, variant)
.map(|(id, v)| (id.to_owned(), v))
.into_iter()
.collect(),
..Default::default()
};
for p in c["predicates"].as_array().unwrap() {
writeln!(out, "{}", entity(p, &view, &Empty, [2.5, 64.0, 0.5]))?;
}
}
out.flush()?;
Ok(())
}
@@ -64,6 +64,10 @@ fn main() -> horizon_client::Result<()> {
);
put("visual/fog_start_distance", format!("{:?}", sky.fog_start));
put("visual/fog_end_distance", format!("{:?}", sky.fog_end));
put(
"visual/cloud_fog_end_distance",
format!("{:?}", sky.cloud_fog_end),
);
out.push_str(&row);
out.push_str("}\n");
}
@@ -0,0 +1,32 @@
#![forbid(unsafe_code)]
//! Runs tools/test_fire_starter_sound_parity.py's level random seeds through
//! the fire charge's use sound (`horizon_client::items::fire_starter_pitch`).
use horizon_client::{
Result,
items::{fire_starter_pitch, fire_starter_sound},
};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
};
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
let input = BufReader::new(File::open(&args[1])?);
let mut out = BufWriter::new(File::create(&args[2])?);
for line in input.lines() {
let mut random = LegacyRandom::new(line?.trim().parse()?);
let pitch = fire_starter_pitch(true, &mut random);
writeln!(
out,
"{} {} {} {}",
fire_starter_sound(true),
1.0f32.to_bits() as i32,
pitch.to_bits() as i32,
random.next_long()
)?;
}
out.flush()?;
Ok(())
}
@@ -5,7 +5,7 @@ use horizon_client::{
Result,
attack_strength::{AttackStrength, HeldStack},
first_person::{
Clicks, Hand, HandHeights, HandWorld, Hit, SwingAnimation, SwingState, UseResult,
Clicks, Hand, HandHeights, HandSway, HandWorld, Hit, SwingAnimation, SwingState, UseResult,
swing_duration,
},
};
@@ -308,6 +308,9 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> {
let mut strength = AttackStrength::default();
// FirstPersonHandsAndItems' visible items start as ItemStack.EMPTY.
let mut visible = [0usize, 0usize];
// The player's xRot and yRot, and the hands' lag behind them.
let mut rot = [0.0f32; 2];
let mut sway = HandSway::default();
for (s, step) in case["steps"].as_array().unwrap().iter().enumerate() {
probe.step = step;
probe.events.clear();
@@ -327,6 +330,10 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> {
step["ud"].as_bool().unwrap(),
);
probe.swing.tick();
if let Some(r) = step["rot"].as_array() {
rot = [fl(&r[0]), fl(&r[1])];
}
sway.tick(rot[0], rot[1]);
let main = probe.stack(Hand::Main).clone();
strength.tick(held(&main));
// FirstPersonHandsAndItems.tick: shouldInstantlyReplaceVisibleItem
@@ -363,7 +370,7 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> {
let d = &clicks.destroying;
writeln!(
out,
"tick {s} {current} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}",
"tick {s} {current} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}",
sw.ticks,
fb(sw.animation),
fb(sw.old_animation),
@@ -379,7 +386,11 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> {
clicks.right_click_delay,
d.delay,
d.active,
fb(d.progress)
fb(d.progress),
fb(sway.x_bob),
fb(sway.y_bob),
fb(sway.x_bob_o),
fb(sway.y_bob_o)
)?;
}
Ok(())
+35 -3
View File
@@ -1,9 +1,11 @@
//! 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.
//! state lines after every click. The `*_be` furnace menus run over a furnace
//! block entity: its data slots follow `Furnace::input_clicked`.
//!
//! usage: menu_fixture RESOURCES INPUT OUTPUT
use horizon_client::{
containers::{Furnace, FurnaceKind},
crafting::Recipes,
item_data::{canon_stack, parse_stack},
items::Items,
@@ -46,7 +48,20 @@ fn main() -> horizon_client::Result<()> {
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 name = case["menu"].as_str().unwrap_or_default();
// FurnaceMenu over the server's AbstractFurnaceBlockEntity.
let furnace_kind = match name {
"furnace_be" => Some(FurnaceKind::Furnace),
"blast_furnace_be" => Some(FurnaceKind::BlastFurnace),
"smoker_be" => Some(FurnaceKind::Smoker),
_ => None,
};
let kind = Kind::parse(
name.strip_suffix("_be")
.filter(|_| furnace_kind.is_some())
.unwrap_or(name),
)
.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() {
@@ -57,6 +72,15 @@ fn main() -> horizon_client::Result<()> {
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
}
let mut furnace = furnace_kind.map(|kind| Furnace {
kind,
items: [0, 1, 2].map(|i| menu.slot(i).cloned()),
lit_remaining: menu.data[0],
lit_total: menu.data[1],
cooking_timer: menu.data[2],
cooking_total: menu.data[3],
speed: 1.0,
});
menu.drops.clear();
out += &format!("init {}\n", state(&menu));
for op in case["ops"].as_array().ok_or("ops")? {
@@ -80,7 +104,15 @@ fn main() -> horizon_client::Result<()> {
_ => {}
}
let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?;
match menu.click(&env, slot, button, kind) {
let clicked = menu.click(&env, slot, button, kind);
if let Some(f) = furnace.as_mut() {
let before = f.items[0].clone();
f.items = [0, 1, 2].map(|i| menu.slot(i).cloned());
f.input_clicked(&recipes, before);
menu.data[2] = f.cooking_timer;
menu.data[3] = f.cooking_total;
}
match clicked {
Ok(()) => out += &format!("{}\n", state(&menu)),
Err(name) => out += &format!("error {name}\n"),
}
@@ -56,6 +56,9 @@ struct Scenario {
spawning: bool,
/// The player hits a mob for 1 at the start of a tick: (tick, mob index).
hurts: Vec<(i32, usize)>,
/// The player feeds an animal at the start of a tick (Animal.mobInteract):
/// (tick, mob index); the scenario only feeds each animal its food.
feeds: Vec<(i32, usize)>,
hand: Option<String>,
mobs: Vec<MobSpec>,
}
@@ -92,6 +95,7 @@ fn parse(text: &str) -> Vec<Scenario> {
}
"heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()),
"hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())),
"feed" => s.feeds.push((f[1].parse().unwrap(), f[2].parse().unwrap())),
"player" => {
s.player = Some([
f[1].parse().unwrap(),
@@ -893,6 +897,9 @@ fn main() -> horizon_client::Result<()> {
}
});
let mut scratch = LegacyRandom::new(0);
// The level's random for eating sounds: only goats and sniffers draw
// from it, and the scenarios feed neither.
let mut level_random = LegacyRandom::new(0);
for (i, m) in mobs.iter().enumerate() {
print(&mut out, 0, i, m, s.creative);
}
@@ -996,6 +1003,16 @@ fn main() -> horizon_client::Result<()> {
}
events.append(&mut mobs[i].outbox);
}
for &(tick, i) in &s.feeds {
if tick != t || i >= mobs.len() || mobs[i].removed {
continue;
}
if let Some(Some((name, volume, pitch))) =
horizon_client::mobs::ai::feed_animal(&mut mobs[i], &mut level_random)
{
events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch));
}
}
#[allow(unused_mut)] // filled only with the rng-trace feature
let mut traces: Vec<String> = Vec::new();
let mut pushes = Vec::new();
@@ -0,0 +1,92 @@
//! The resource root Horizon builds for a pack selection (`packs::build_overlay`)
//! and what its loaders read from it, for VanillaPackResourcesOracle.
use horizon_client::{lang::Language, packs, sound_events::SoundRegistry};
use std::{fmt::Write, fs, path::PathBuf};
fn fnv(bytes: &[u8]) -> u64 {
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| {
(h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3)
})
}
/// `namespace:path` to a file under the root's `assets/`.
fn asset(root: &std::path::Path, id: &str, prefix: &str, suffix: &str) -> PathBuf {
let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id));
root.join("assets")
.join(namespace)
.join(format!("{prefix}{path}{suffix}"))
}
fn types(root: &std::path::Path, file: PathBuf, key: &str) -> String {
let _ = root;
let value: serde_json::Value = fs::read(file)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
value[key]
.as_array()
.into_iter()
.flatten()
.map(|v| {
let t = v["type"].as_str().unwrap_or("?");
format!(" {}", t.strip_prefix("minecraft:").unwrap_or(t))
})
.collect()
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let input = fs::read_to_string(&args[1])?;
let mut lines = input.lines();
let root: Vec<&str> = lines.next().ok_or("empty input")?.split(' ').collect();
let vanilla = PathBuf::from(root[1]);
let ids: Vec<String> = root[3..].iter().map(|s| (*s).to_owned()).collect();
let all = packs::discover(&vanilla, &PathBuf::from(root[2]));
let enabled = packs::enabled(&all, &ids);
let overlay = PathBuf::from(&args[2]).with_extension("overlay");
packs::build_overlay(&vanilla, &enabled, &overlay)?;
let language = Language::load(&[&overlay], "en_us");
let sounds = SoundRegistry::load(&overlay);
let mut out = String::new();
for line in lines {
let (kind, arg) = line.split_once(' ').unwrap_or((line, ""));
write!(out, "{line} =>")?;
match kind {
"file" => match fs::read(asset(&overlay, arg, "", "")) {
Ok(bytes) => write!(out, " {:x}", fnv(&bytes))?,
Err(_) => out.push_str(" missing"),
},
"lang" => write!(out, " {}", language.get(arg).unwrap_or(arg))?,
"sound" => {
let event = if arg.contains(':') {
arg.to_owned()
} else {
format!("minecraft:{arg}")
};
match sounds.get(&event) {
None => out.push_str(" missing"),
Some(e) => {
write!(out, " subtitle={}", e.subtitle.as_deref().unwrap_or("none"))?;
for s in &e.sounds {
if s.event {
out.push_str(" event");
} else {
write!(out, " {}*{}", s.location, s.weight)?;
}
}
}
}
}
"font" => out.push_str(&types(
&overlay,
asset(&overlay, arg, "font/", ".json"),
"providers",
)),
"atlas" => out.push_str(&types(
&overlay,
asset(&overlay, arg, "atlases/", ".json"),
"sources",
)),
_ => return Err(format!("unknown query {line}").into()),
}
out.push('\n');
}
fs::write(&args[2], out)?;
Ok(())
}
@@ -0,0 +1,217 @@
#![forbid(unsafe_code)]
//! Runs tools/test_particle_providers_parity.py's particles through
//! `ParticleEngine`: built with the seeds the vanilla oracle recovered, then
//! ticked over air or a stone floor at y 63, printing their state each tick.
use horizon_client::{
Result,
assets::Assets,
blocks::BlockFacts,
chunk::Chunk,
collisions,
particles::{ParticleEngine, ParticleLevel, ParticleOptions, ParticleSnapshot, ParticleType},
world::World,
};
use serde_json::Value;
use std::{
collections::HashMap,
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
sync::Arc,
};
fn d(v: f64) -> String {
format!("{:016x}", v.to_bits())
}
fn f(v: f32) -> String {
format!("{:08x}", v.to_bits())
}
fn color(v: &Value, default: u32) -> u32 {
v.as_u64().map_or(default, |c| c as u32)
}
fn rgb(c: u32) -> [f32; 3] {
[
((c >> 16) & 255) as f32 / 255.0,
((c >> 8) & 255) as f32 / 255.0,
(c & 255) as f32 / 255.0,
]
}
fn options(case: &Value) -> Option<ParticleOptions> {
let ty = ParticleType::from_name(case["type"].as_str()?)?;
let o = &case["options"];
let scale = o["scale"].as_f64().unwrap_or(1.0) as f32;
let c = color(&o["color"], 0xFFFF_FFFF);
let argb = {
let [r, g, b] = rgb(c);
[r, g, b, ((c >> 24) & 255) as f32 / 255.0]
};
Some(match ty {
ParticleType::Block | ParticleType::BlockCrumble | ParticleType::DustPillar => {
ParticleOptions::block(ty, "terrain".into(), 0xFF_FFFF)
}
// Stone's map colour: FallingDustParticle.Provider's tint without a tint source.
ParticleType::FallingDust => ParticleOptions::block(ty, "terrain".into(), 0x70_7070),
ParticleType::Dust => ParticleOptions::dust(rgb(c), scale),
ParticleType::DustColorTransition => {
ParticleOptions::dust_transition(rgb(c), rgb(color(&o["to"], 0)), scale)
}
ParticleType::Effect | ParticleType::InstantEffect => ParticleOptions {
scale,
..ParticleOptions::colored(ty, argb)
},
ParticleType::EntityEffect | ParticleType::TintedLeaves => {
ParticleOptions::colored(ty, argb)
}
ParticleType::DragonBreath => ParticleOptions {
scale,
..ParticleOptions::simple(ty)
},
ParticleType::SculkCharge => ParticleOptions::sculk_charge(scale),
ParticleType::Shriek => ParticleOptions::shriek(scale as i32),
ParticleType::Trail => {
let t = &o["target"];
ParticleOptions::trail(
[t[0].as_f64()?, t[1].as_f64()?, t[2].as_f64()?],
c & 0xFF_FFFF,
o["duration"].as_i64()? as i32,
)
}
_ => ParticleOptions::simple(ty),
})
}
fn state(s: &ParticleSnapshot) -> String {
let mut out = format!(
"{} {} {} {}",
s.age,
s.lifetime,
u8::from(s.removed),
u8::from(s.on_ground)
);
for v in s.position.iter().chain(&s.velocity).chain(&s.previous) {
out += &format!(" {}", d(*v));
}
if let Some(q) = &s.quad {
out += &format!(" | {} {}", f(q.size[0]), f(q.size[1]));
for v in q.rgba.iter().chain(&q.roll) {
out += &format!(" {}", f(*v));
}
out += &format!(" {}", q.sprite);
for v in q.uv {
out += &format!(" {}", f(v));
}
out += &format!(" {:x}", q.light);
}
out
}
fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result<World> {
let mut world = World::new(facts.air, 0);
let stone = assets
.registry
.default_state("minecraft:stone")
.ok_or("missing stone")?;
for cz in -3..=2 {
for cx in -3..=2 {
world
.chunks
.insert((cx, cz), Arc::new(Chunk::empty(cx, cz)));
if floor {
for z in 0..16 {
for x in 0..16 {
world.set(cx * 16 + x, 63, cz * 16 + z, stone)?;
}
}
}
}
}
Ok(world)
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(".local/horizon-client/26.3");
let assets = Assets::load(root)?;
let facts = BlockFacts::load(root, assets.registry)?;
let collision = collisions::load(root, assets.registry)?;
let worlds = [
world(&assets, &facts, false)?,
world(&assets, &facts, true)?,
];
let mut engine = ParticleEngine::new(root, &HashMap::new());
// The oracle's output: the seed line of each case.
let mut seeds = Vec::new();
for line in BufReader::new(File::open(&args[2])?).lines() {
let line = line?;
if line.starts_with("seed ") || line.starts_with("null ") || line == "no provider" {
seeds.push(line);
}
}
let mut out = BufWriter::new(File::create(&args[3])?);
for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() {
let case: Value = serde_json::from_str(&line?)?;
writeln!(out, "== {n}")?;
let Some(options) = options(&case) else {
writeln!(out, "no provider")?;
continue;
};
let seed = case["seed"].as_i64().ok_or("seed")?;
engine.seed_randoms(seed, seed ^ 0x6C_6576_656C, seed ^ 0x73_7065_6C6C);
engine.requested = Some(Vec::new());
engine.sounds.clear();
let level = ParticleLevel {
world: &worlds[usize::from(case["floor"].as_bool() == Some(true))],
facts: &facts,
collision: &collision,
player: None,
};
let v = |key: &str| -> [f64; 3] {
std::array::from_fn(|i| case[key][i].as_f64().unwrap_or(0.0))
};
let seed_line = seeds.get(n).cloned().unwrap_or_default();
let local = seed_line
.split(' ')
.nth(1)
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(0);
let Some(mut particle) = engine.probe_create(&options, v("pos"), v("vel"), local, &level)
else {
writeln!(out, "null {}", engine.next_randoms()[0])?;
continue;
};
writeln!(out, "{seed_line}")?;
let [a, b, c] = engine.next_randoms();
writeln!(out, "next {a} {b} {c}")?;
let events = |engine: &mut ParticleEngine, out: &mut BufWriter<File>| -> Result<()> {
for (o, p, v) in engine.requested.replace(Vec::new()).unwrap_or_default() {
write!(out, "+ {}", o.ty.name())?;
for x in p.iter().chain(&v) {
write!(out, " {}", d(*x))?;
}
writeln!(out)?;
}
for (name, p, volume, pitch) in std::mem::take(&mut engine.sounds) {
writeln!(
out,
"~ {name} {} {} {} {} {}",
d(p[0]),
d(p[1]),
d(p[2]),
f(volume),
f(pitch)
)?;
}
Ok(())
};
writeln!(out, "0 {}", state(&engine.snapshot(&particle)))?;
events(&mut engine, &mut out)?;
let ticks = case["ticks"].as_i64().unwrap_or(0);
let mut t = 1;
while t <= ticks && particle.is_alive() {
engine.probe_tick(&mut particle, &level);
writeln!(out, "{t} {}", state(&engine.snapshot(&particle)))?;
events(&mut engine, &mut out)?;
t += 1;
}
}
out.flush()?;
Ok(())
}
@@ -40,6 +40,7 @@ fn main() -> Result<()> {
let mut scene = collisions::SceneCollisions {
world: &world,
binding: &binding,
subject: None,
};
fs::write(
dir.join("scene.json"),
@@ -165,6 +165,17 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
.filter_map(|e| match e {
MotionEvent::Fall(e) => Some(e.trace()),
MotionEvent::Health(e) => Some(e.trace()),
MotionEvent::Snowflake { position, velocity } => Some(format!(
"snowflake {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}",
position.x.to_bits(),
position.y.to_bits(),
position.z.to_bits(),
velocity.x.to_bits(),
velocity.y.to_bits(),
velocity.z.to_bits()
)),
// The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so.
MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()),
MotionEvent::Waypoint { receiver, enabled } => Some(format!(
"waypoint {} {enabled}",
if *receiver { "receive" } else { "transmit" }
@@ -232,6 +243,8 @@ fn main() -> Result<()> {
instances.next().expect("unexpected instance allocation")
}),
)?;
// The oracle runs block-inside effects only in "snow_tick".
player.block_effects = false;
for op in f["ops"].as_array().unwrap() {
let mut world = MotionWorld {
player: &mut player,
@@ -409,6 +422,26 @@ fn main() -> Result<()> {
op["jumping"].as_bool().unwrap(),
)?;
}
"snow_tick" => {
// The clock, then the player tick: baseTick's powder snow
// flags lead PlayerMotion::player_movement_tick.
world.player.health.advance_clock();
let v = vector(&op["value"]);
world.player.block_effects = true;
let ticked = world.player_movement_tick(
[v.x as f32, v.z as f32],
op["jumping"].as_bool().unwrap(),
);
world.player.block_effects = false;
ticked?;
}
"boots" => {
// Leather boots are also freeze-immune wearables.
let boots = op["value"].as_bool().unwrap();
world.player.leather_boots = boots;
world.player.freeze_immune = boots;
}
"frozen" => world.player.ticks_frozen = op["value"].as_i64().unwrap() as i32,
"trigger" => world.player.jump_trigger_time = op["value"].as_i64().unwrap() as i32,
"delay" => world.player.no_jump_delay = op["value"].as_i64().unwrap() as i32,
"move" => world.move_self(vector(&op["value"]))?,
@@ -478,7 +511,18 @@ fn main() -> Result<()> {
}
let check_block = scene.block(25, 3, 25);
snapshot(&mut out, &player)?;
writeln!(out, "block {}", check_block.0)?;
let stuck = player.stuck_multiplier;
writeln!(
out,
"block {} frozen {} {} {} {:016x},{:016x},{:016x}",
check_block.0,
player.ticks_frozen,
player.in_powder_snow,
player.was_in_powder_snow,
stuck.x.to_bits(),
stuck.y.to_bits(),
stuck.z.to_bits()
)?;
let h = &player.health;
let canonical = |v: f32| {
if v.is_nan() {
@@ -0,0 +1,59 @@
//! WeatherEffectRenderer column instances and quads, without a GPU.
use horizon_client::weather;
use std::{fmt::Write, fs};
fn bits(value: f32) -> String {
if value.is_nan() {
"nan".into()
} else {
format!("{:x}", value.to_bits())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let mut output = String::new();
for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() {
let p: Vec<&str> = line.split_whitespace().collect();
let int = |i: usize| p[i].parse::<i32>().unwrap();
let kind = int(0);
let ticks: i64 = p[1].parse()?;
let (x, bottom, top, z, light) = (int(2), int(3), int(4), int(5), int(6));
let partial: f32 = p[7].parse()?;
let camera = [p[8].parse()?, p[9].parse()?, p[10].parse()?];
let radius = int(11);
let intensity: f32 = p[12].parse()?;
let mut random = weather::column_random(x, z);
let column = if kind == 0 {
weather::rain_column(&mut random, ticks, x, bottom, top, z, light, partial)
} else {
weather::snow_column(&mut random, ticks, x, bottom, top, z, light, partial)
};
write!(
output,
"{case} {} {} {} {} {} {} {}",
column.x,
column.z,
column.bottom_y,
column.top_y,
bits(column.u_offset),
bits(column.v_offset),
column.light_coords
)?;
let max_alpha = if kind == 0 { 1.0 } else { 0.8 };
for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) {
write!(
output,
" |{},{},{},{},{},{:x},{}",
bits(v.pos[0]),
bits(v.pos[1]),
bits(v.pos[2]),
bits(v.uv[0]),
bits(v.uv[1]),
v.color,
v.light_coords
)?;
}
output.push('\n');
}
fs::write(&args[2], output)?;
Ok(())
}
+25 -2
View File
@@ -294,6 +294,8 @@ pub struct EntityView {
pub struck: Vec<EntityView>,
pub fishing_open_water: Option<bool>,
pub variant: Option<String>,
/// The data components the entity reports (`Entity.get`): id and value.
pub components: Vec<(String, String)>,
}
fn range_f(v: &Value, x: f64) -> bool {
match v {
@@ -310,7 +312,7 @@ fn range_i(v: &Value, x: i64) -> bool {
range_f(v, x as f64)
}
/// A registry id, `#tag`, or list matched against one id.
fn id_matches(v: &Value, registry: &str, id: &str, w: &dyn World) -> bool {
pub fn id_matches(v: &Value, registry: &str, id: &str, w: &dyn World) -> bool {
match v {
Value::Null => true,
Value::String(s) => match s.strip_prefix('#') {
@@ -442,6 +444,26 @@ pub fn location(v: &Value, p: [f64; 3], w: &dyn World) -> bool {
}
true
}
/// `DataComponentExactPredicate.test` on an entity: every expected
/// component equals what the entity reports (absent ones never match).
fn components(expected: &Value, have: &[(String, String)]) -> bool {
let full = |id: &str| {
if id.contains(':') {
id.to_owned()
} else {
format!("minecraft:{id}")
}
};
expected.as_object().is_some_and(|o| {
o.iter().all(|(id, want)| {
let id = full(id);
want.as_str().is_some_and(|want| {
have.iter()
.any(|(k, v)| full(k) == id && full(v) == full(want))
})
})
})
}
/// `EntityPredicate` (26.x keyed sub-predicates).
pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> bool {
if v.is_null() {
@@ -521,7 +543,8 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo
"minecraft:type_specific/fishing_hook" => p["in_open_water"]
.as_bool()
.is_none_or(|want| e.fishing_open_water == Some(want)),
"minecraft:components" | "minecraft:predicates" => true,
"minecraft:components" => components(p, &e.components),
"minecraft:predicates" => true,
_ => false,
};
if !ok {
+33 -4
View File
@@ -180,15 +180,43 @@ impl Assets {
.collect::<Result<_>>()?,
));
let mut material_states = [BlockStateId(0); 6];
let mut sprites = crate::sprites::Sprites::default();
for (layer, name) in MATERIALS.iter().enumerate() {
let state = registry
material_states[layer] = registry
.default_state(&format!("minecraft:{name}"))
.ok_or_else(|| invalid("missing test-scene material"))?;
material_states[layer] = state;
sprites.insert(root, &format!("minecraft:block/{name}"))?;
}
let registry: &'static BlockRegistry = Box::leak(Box::new(registry));
Self::with_models(
root,
registry,
properties,
material_states,
blocks_fluid_flow,
)
}
/// The same blocks with the models and sprites of another resource root
/// (resource packs changed): the registry and block facts come from the
/// game data, which resource packs do not touch.
pub fn reload(&self, root: &Path) -> Result<Self> {
Self::with_models(
root,
self.registry,
self.properties.clone(),
self.material_states,
self.blocks_fluid_flow.clone(),
)
}
fn with_models(
root: &Path,
registry: &'static BlockRegistry,
properties: Properties,
material_states: [BlockStateId; 6],
blocks_fluid_flow: BTreeSet<String>,
) -> Result<Self> {
let mut sprites = crate::sprites::Sprites::default();
for name in MATERIALS {
sprites.insert(root, &format!("minecraft:block/{name}"))?;
}
let models = crate::models::prepare(root, registry, &mut sprites)?;
// Fluids are drawn by the fluid renderer, not block models; breaking
// progress uses the destroy-stage overlays.
@@ -204,6 +232,7 @@ impl Assets {
for stage in 0..10 {
sprites.insert(root, &format!("minecraft:block/destroy_stage_{stage}"))?;
}
sprites.finish();
Ok(Self {
registry,
properties,
+10
View File
@@ -600,6 +600,16 @@ impl Audio {
pub fn stop_all(&mut self) {
self.engine.stop_all(&mut self.backend);
}
/// `SoundManager.reload` (resource packs changed): stop every sound, then
/// read sound events and sound files from the new resource root.
pub fn reload(&mut self, root: &Path) {
self.stop_all();
self.engine.registry = SoundRegistry::load(root);
self.backend.root = root.to_owned();
let mut cache = self.backend.cache.lock().unwrap();
cache.entries.clear();
cache.bytes = 0;
}
/// Play a sound event at a world position, as `ClientLevel.playLocalSound`
/// (a `SimpleSoundInstance` seeded from the level random), or relative to
/// the listener without attenuation (`None`).
+13
View File
@@ -590,6 +590,12 @@ impl Camera {
modify_fov_based_on_death_or_fluid(partial, 70.0, effect_scale, dead, fluid)
}
}
/// `Camera.update`: the far plane covers four times the render distance and
/// the whole cloud range (`depthFar`).
pub fn depth_far(render_distance_chunks: i32, cloud_range_chunks: i32) -> f32 {
(render_distance_chunks as f32 * 16.0 * 4.0).max((cloud_range_chunks * 16) as f32)
}
/// `Projection.getMatrix` for a perspective set up by `setupPerspective`:
/// JOML's `Matrix4f.setPerspective(fov * DEG_TO_RAD, width / height, near,
/// far, zZeroToOne)`, column-major. Vanilla passes its planes reversed
@@ -768,6 +774,13 @@ pub fn bob_matrix(state: &BobState, damage_tilt_strength: f64, bob_view_option:
#[cfg(test)]
mod tests {
#[test]
fn depth_far_covers_the_cloud_range() {
// renderDistance 2 with the default Cloud Distance (128 chunks).
assert_eq!(super::depth_far(2, 128), 2048.0);
assert_eq!(super::depth_far(32, 2), 2048.0);
assert_eq!(super::depth_far(12, 12), 768.0);
}
use super::*;
#[test]
fn view_keeps_yaw_at_vertical_pitch_limits() {
+12
View File
@@ -32,6 +32,12 @@ pub fn faces(mask: u16) -> impl Iterator<Item = (u8, bool)> {
)
}
/// `CloudRenderer.prepare`: the cell radius for the Cloud Distance option
/// (in chunks), independent of the render distance.
pub fn radius_cells(cloud_range_chunks: i32) -> i32 {
((cloud_range_chunks * 16) as f32 / 12.0).ceil() as i32
}
/// CloudRenderer builds cells in expanding Manhattan rings, nearest first.
pub fn cells(radius: i32) -> impl Iterator<Item = (i32, i32)> {
(0..=2 * radius).flat_map(move |ring| {
@@ -71,6 +77,12 @@ mod tests {
assert_eq!(face_mask(2, 2, 0.0, [false; 4]), 3);
}
#[test]
fn cloud_distance_sets_the_radius() {
assert_eq!(radius_cells(2), 3);
assert_eq!(radius_cells(12), 16);
assert_eq!(radius_cells(128), 171);
}
#[test]
fn connected_cells_have_no_exterior_walls() {
assert_eq!(face_mask(2, 2, 10.0, [false; 4]), 1);
}
+20 -5
View File
@@ -39,9 +39,24 @@ pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result<BlockCollisi
Ok(BlockCollisionRegistry::new(Arc::new(cached))?)
}
/// What powder snow's contextual collision asks of the colliding entity
/// (`PowderSnowBlock.getCollisionShape`).
#[derive(Clone, Copy, Debug, Default)]
pub struct PowderSnowSubject {
pub fall_distance: f64,
/// `FallingBlockEntity`.
pub falling_block: bool,
/// A living entity with leather boots on its feet.
pub leather_boots: bool,
/// `EntityTypeTags.POWDER_SNOW_WALKABLE_MOBS`.
pub walkable_type: bool,
}
pub struct SceneCollisions<'w, 'r> {
pub world: &'w World,
pub binding: &'w BlockCollisionRegistry<'r>,
/// The entity colliding, for powder snow; None: no fall, no boots.
pub subject: Option<PowderSnowSubject>,
}
impl SceneCollisions<'_, '_> {
/// Position contexts permit geometric movement probes without inventing a
@@ -169,18 +184,18 @@ impl LiquidCollisionWorld for SceneCollisions<'_, '_> {
}
impl PowderSnowWorld for SceneCollisions<'_, '_> {
type Error = io::Error;
// Entities here are never falling blocks and wear no leather boots.
fn powder_snow_entity(&mut self, _: EntityIdentity) -> io::Result<PowderSnowEntity> {
let subject = self.subject.unwrap_or_default();
Ok(PowderSnowEntity {
fall_distance: 0.0,
falling_block: false,
fall_distance: subject.fall_distance,
falling_block: subject.falling_block,
})
}
fn powder_snow_walkable_tag(&mut self, _: EntityIdentity) -> io::Result<bool> {
Ok(false)
Ok(self.subject.is_some_and(|s| s.walkable_type))
}
fn feet_are_leather_boots(&mut self, _: EntityIdentity) -> io::Result<bool> {
Ok(false)
Ok(self.subject.is_some_and(|s| s.leather_boots))
}
}
@@ -0,0 +1,278 @@
//! The mouse handling every survival and container screen shares
//! (`AbstractContainerScreen.mouseClicked` / `mouseReleased`): which slot id
//! a click targets (-999 outside the window, `hasClickedOutside` with the
//! recipe book's own rule) and which `ContainerInput` it sends. Shift is
//! the event's own modifiers (`InputWithModifiers.hasShiftDown`: the
//! physical Shift keys, never the remapped or toggled sneak key).
use crate::menu::Input;
/// The screen's window: `leftPos`, `topPos`, `imageWidth`, `imageHeight`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Image {
pub left: i32,
pub top: i32,
pub width: i32,
pub height: i32,
}
/// The recipe book of an `AbstractRecipeBookScreen`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Book {
/// `RecipeBookComponent.isVisible`.
pub visible: bool,
/// `selectedTab.isHoveredOrFocused()`.
pub selected_tab_hovered: bool,
}
/// `RecipeBookComponent.IMAGE_WIDTH`.
const BOOK_WIDTH: i32 = 147;
fn outside(mx: f64, my: f64, image: Image) -> bool {
mx < f64::from(image.left)
|| my < f64::from(image.top)
|| mx >= f64::from(image.left + image.width)
|| my >= f64::from(image.top + image.height)
}
/// `AbstractContainerScreen.hasClickedOutside`, or
/// `AbstractRecipeBookScreen.hasClickedOutside` when the screen has a book
/// (`RecipeBookComponent.hasClickedOutside`: a click on the book, or with
/// its selected tab hovered, is not outside).
pub fn clicked_outside(mx: f64, my: f64, image: Image, book: Option<Book>) -> bool {
let out = outside(mx, my, image);
let Some(book) = book else {
return out;
};
let book_outside = !book.visible || {
let on_book = f64::from(image.left - BOOK_WIDTH) < mx
&& mx < f64::from(image.left)
&& f64::from(image.top) < my
&& my < f64::from(image.top + image.height);
out && !on_book && !book.selected_tab_hovered
};
book_outside && out
}
/// What a click points at: a slot, outside the window (slot id -999), or
/// neither (slot id -1).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Target<S> {
Slot(S),
Outside,
Nothing,
}
impl<S> Target<S> {
/// Outside wins over a hovered slot, as in `mouseClicked`.
pub fn of(slot: Option<S>, outside: bool) -> Self {
match slot {
_ if outside => Self::Outside,
Some(s) => Self::Slot(s),
None => Self::Nothing,
}
}
}
/// The left, right and middle buttons (SDL's 1, 3 and 2).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Button {
Left,
Right,
Middle,
}
impl Button {
/// `getContainerClickButton`: the button a menu click carries.
pub fn menu_button(self) -> i32 {
match self {
Self::Left => 0,
Self::Right => 1,
Self::Middle => 2,
}
}
}
/// The input state `mouseClicked`/`mouseReleased` keep between events.
#[derive(Clone, Debug, Default)]
pub struct Clicks {
/// `isQuickCrafting` with `quickCraftingButton`.
quick_crafting: Option<Button>,
skip_next_release: bool,
}
/// What a release does.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Release {
/// `slotClicked` with this input on the release's target.
Click(Input),
/// `quickCraftToSlots` over the dragged slots.
QuickCraft,
Nothing,
}
impl Clicks {
/// A quick craft drag in progress, and the button that started it.
pub fn quick_crafting(&self) -> Option<Button> {
self.quick_crafting
}
/// A press Horizon handled itself (a double click's `PICKUP_ALL`): its
/// release clicks nothing more.
pub fn skip_release(&mut self) {
self.quick_crafting = None;
self.skip_next_release = true;
}
/// `mouseClicked` (no double click): the `slotClicked` input it sends on
/// `target`, if any. A press holding a stack starts a quick craft drag
/// instead. `cloning` is `keyPickItem` with infinite materials.
pub fn press<S>(
&mut self,
target: &Target<S>,
button: Button,
carried_empty: bool,
shift: bool,
cloning: bool,
) -> Option<Input> {
self.skip_next_release = false;
if button == Button::Middle && !cloning {
return None;
}
if matches!(target, Target::Nothing) || self.quick_crafting.is_some() {
return None;
}
if !carried_empty {
self.quick_crafting = Some(button);
return None;
}
self.skip_next_release = true;
Some(if cloning {
Input::Clone
} else if shift && !matches!(target, Target::Outside) {
Input::QuickMove
} else if matches!(target, Target::Outside) {
Input::Throw
} else {
Input::Pickup
})
}
/// `mouseReleased` (no double click). `dragged` is whether the quick
/// craft drag collected any slots; `pick_item` is the release of the
/// `keyPickItem` button.
pub fn release<S>(
&mut self,
target: &Target<S>,
button: Button,
carried_empty: bool,
dragged: bool,
shift: bool,
pick_item: bool,
) -> Release {
if self.quick_crafting.is_some_and(|b| b != button) {
self.quick_crafting = None;
self.skip_next_release = true;
return Release::Nothing;
}
if self.skip_next_release {
self.skip_next_release = false;
return Release::Nothing;
}
let quick_crafting = self.quick_crafting.take().is_some();
if quick_crafting && dragged {
Release::QuickCraft
} else if carried_empty {
Release::Nothing
} else if pick_item {
Release::Click(Input::Clone)
} else if shift && !matches!(target, Target::Outside) {
Release::Click(Input::QuickMove)
} else {
Release::Click(Input::Pickup)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const INV: Image = Image {
left: 100,
top: 50,
width: 176,
height: 166,
};
#[test]
fn window_edges() {
assert!(!clicked_outside(100.0, 50.0, INV, None));
assert!(clicked_outside(99.9, 60.0, INV, None));
assert!(clicked_outside(276.0, 60.0, INV, None));
assert!(!clicked_outside(275.9, 215.9, INV, None));
}
#[test]
fn the_open_book_is_not_outside() {
let book = Book {
visible: true,
selected_tab_hovered: false,
};
assert!(!clicked_outside(10.0, 100.0, INV, Some(book)));
assert!(clicked_outside(-60.0, 100.0, INV, Some(book)));
assert!(!clicked_outside(
-60.0,
100.0,
INV,
Some(Book {
selected_tab_hovered: true,
..book
})
));
let closed = Book {
visible: false,
..book
};
assert!(clicked_outside(10.0, 100.0, INV, Some(closed)));
}
#[test]
fn a_carried_stack_thrown_outside() {
let mut clicks = Clicks::default();
let out = Target::<usize>::Outside;
assert_eq!(clicks.press(&out, Button::Left, false, false, false), None);
assert_eq!(
clicks.release(&out, Button::Left, false, false, false, false),
Release::Click(Input::Pickup)
);
// Shift never quick-moves outside, and an empty hand throws nothing.
assert_eq!(
clicks.press(&out, Button::Right, true, true, false),
Some(Input::Throw)
);
assert_eq!(
clicks.release(&out, Button::Right, true, false, true, false),
Release::Nothing
);
}
#[test]
fn another_button_cancels_the_drag() {
let mut clicks = Clicks::default();
let slot = Target::Slot(3);
clicks.press(&slot, Button::Left, false, false, false);
assert_eq!(
clicks.release(&slot, Button::Right, false, true, false, false),
Release::Nothing
);
assert_eq!(
clicks.release(&slot, Button::Left, false, true, false, false),
Release::Nothing
);
assert_eq!(
clicks.release(&slot, Button::Left, false, true, true, false),
Release::Click(Input::QuickMove)
);
}
}
+26
View File
@@ -427,6 +427,32 @@ fn remainder(item: &str) -> Option<&'static str> {
}
}
impl Furnace {
/// `AbstractFurnaceBlockEntity.setItem` on the input slot: anything but
/// the same item with the same components restarts cooking, with the
/// total time of the new input's recipe (200 ticks without one).
pub fn set_input(&mut self, recipes: &Recipes, stack: Option<ItemStack>) {
let same = match (&self.items[0], &stack) {
(Some(old), Some(new)) => old.same_item_same_components(new),
_ => false,
};
self.items[0] = stack;
if !same {
self.cooking_total = self.items[0]
.as_ref()
.and_then(|input| recipes.cook(self.kind.recipe_type(), input))
.map_or(200, |recipe| total_time(recipe.time, self.speed));
self.cooking_timer = 0;
}
}
/// A menu click wrote its slots into `items`, and `before` was the input
/// slot until then: the menu called `setItem` on it only if it changed
/// (`Slot.setByPlayer`; partial takes and merges keep the stack).
pub fn input_clicked(&mut self, recipes: &Recipes, before: Option<ItemStack>) {
if self.items[0] != before {
let after = std::mem::replace(&mut self.items[0], before);
self.set_input(recipes, after);
}
}
/// One server tick. Returns `Some(lit)` when the LIT block state must change.
pub fn tick(
&mut self,
+2
View File
@@ -132,6 +132,7 @@ impl ItemEntity {
let mut scene = SceneCollisions {
world,
binding: collision,
subject: None,
};
let wanted = self.velocity;
let moved = scene
@@ -333,6 +334,7 @@ impl ExperienceOrb {
let mut scene = SceneCollisions {
world,
binding: collision,
subject: None,
};
let wanted = self.velocity;
let moved = scene
+2
View File
@@ -161,6 +161,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
if m.kind.category == "creature" && aged {
map.insert("Age".into(), Tag::Int(m.extra.age));
map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked)));
map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age));
for (key, value) in [
("Age", Tag::Int(0)),
("ForcedAge", Tag::Int(0)),
@@ -595,6 +596,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.custom_name = custom_name(tag);
if m.kind.category == "creature" {
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32;
m.extra.age_locked = flag(tag, "AgeLocked");
}
m.name_visible = flag(tag, "CustomNameVisible");
+6
View File
@@ -139,6 +139,8 @@ pub struct Sky {
/// Environmental fog (`visual/fog_start_distance` / `fog_end_distance`).
pub fog_start: f32,
pub fog_end: f32,
/// `visual/cloud_fog_end_distance`.
pub cloud_fog_end: f32,
}
impl Environment {
pub fn load(root: &Path) -> Result<Self> {
@@ -299,6 +301,10 @@ impl Environment {
.base
.get("minecraft:visual/fog_end_distance")
.map_or(1024.0, |v| v[0]),
cloud_fog_end: self
.base
.get("minecraft:visual/cloud_fog_end_distance")
.map_or(2048.0, |v| v[0]),
}
}
}
+29
View File
@@ -311,6 +311,35 @@ impl HandHeights {
}
}
/// `LocalPlayer.xBob` and `yBob`: the hands lag behind the view when it
/// turns. `LocalPlayer.applyInput` eases them halfway to the rotation every
/// tick; `FirstPersonHandsAndItemsRenderer` turns the hands by a tenth of
/// the gap left.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct HandSway {
pub x_bob: f32,
pub y_bob: f32,
pub x_bob_o: f32,
pub y_bob_o: f32,
}
impl HandSway {
/// `LocalPlayer.applyInput` with the player's `getXRot` and `getYRot`.
pub fn tick(&mut self, x_rot: f32, y_rot: f32) {
self.y_bob_o = self.y_bob;
self.x_bob_o = self.x_bob;
self.x_bob += (x_rot - self.x_bob) * 0.5;
self.y_bob += (y_rot - self.y_bob) * 0.5;
}
/// The degrees the hands turn about X, then Y, before either is drawn:
/// `(viewXRot - xBob) * 0.1` and `(viewYRot - yBob) * 0.1`, the bobs
/// interpolated as `extractRenderState` does.
pub fn rotation(&self, partial: f32, view_x_rot: f32, view_y_rot: f32) -> [f32; 2] {
let x_bob = crate::camera::lerp(partial, self.x_bob_o, self.x_bob);
let y_bob = crate::camera::lerp(partial, self.y_bob_o, self.y_bob);
[(view_x_rot - x_bob) * 0.1, (view_y_rot - y_bob) * 0.1]
}
}
/// `HitResult` at the crosshair (`Minecraft.hitResult`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Hit {
+27 -1
View File
@@ -196,6 +196,8 @@ pub struct FogInputs<'a> {
pub water_fog_color: [f32; 3],
pub biome: u16,
pub render_distance_chunks: i32,
/// The Cloud Distance option, in chunks.
pub cloud_range_chunks: i32,
pub camera_y: f64,
pub min_y: i32,
/// Flat worlds use a 1-block void darkness range.
@@ -335,7 +337,7 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog
let min_end = sky.fog_end.min(96.0);
fog.environmental_end = min_end.max(sky.fog_end + -256.0 * state.rain_fog_multiplier);
fog.sky_end = rd.min(512.0);
fog.cloud_end = 2048.0f32.min(128.0 * 16.0);
fog.cloud_end = ((input.cloud_range_chunks * 16) as f32).min(sky.cloud_fog_end);
}
}
let span = (rd / 10.0).clamp(4.0, 64.0);
@@ -373,6 +375,7 @@ mod tests {
water_fog_color: [0.0, 0.0, 0.2],
biome: 0,
render_distance_chunks: 12,
cloud_range_chunks: 128,
camera_y: 70.0,
min_y: -64,
flat: false,
@@ -402,6 +405,29 @@ mod tests {
assert_eq!(fog.sky_end, 192.0);
}
#[test]
fn cloud_fog_ends_at_the_cloud_distance() {
let sky = Sky {
fog_end: 1024.0,
cloud_fog_end: 2048.0,
..Sky::default()
};
let tables = FogTables {
water_fog_end: vec![1.0],
};
let mut input = inputs(&sky);
input.render_distance_chunks = 2;
input.cloud_range_chunks = 64;
assert_eq!(
setup_fog(&tables, &FogState::default(), &input).cloud_end,
1024.0
);
input.cloud_range_chunks = 128;
assert_eq!(
setup_fog(&tables, &FogState::default(), &input).cloud_end,
2048.0
);
}
#[test]
fn water_vision_ramps() {
let mut s = FogState::default();
for _ in 0..100 {
+451 -168
View File
@@ -19,6 +19,7 @@ mod chat;
mod combat;
mod command_harness;
mod commands;
mod composter;
mod control;
mod copper_golems;
mod creaking;
@@ -73,6 +74,7 @@ mod perspective;
mod piglins;
mod postprocess;
mod potions;
mod powder_snow;
mod raids;
mod recipe_book;
mod remote;
@@ -533,6 +535,8 @@ struct FallingBlock {
no_gravity: bool,
/// `FallingBlockEntity.dropItem`.
drop_item: bool,
/// `Entity.fallDistance` (powder snow holds a block that fell far at 0.9).
fall_distance: f64,
/// The UUID and compound it was loaded with, kept while it moves.
saved: Option<Box<([i32; 4], horizon_world::nbt::Tag)>>,
}
@@ -594,6 +598,8 @@ struct Game<'a> {
craft_size: usize,
/// A quick craft drag over inventory slots: (button, game slots so far).
inv_drag: Option<(i32, Vec<usize>)>,
/// `AbstractContainerScreen`'s quick craft and skip-release state.
inv_clicks: horizon_client::container_screen::Clicks,
/// The last inventory click, for the double click that gathers a stack.
last_inv_click: Option<(std::time::Instant, usize, bool)>,
/// Open container block entity, if any.
@@ -610,6 +616,8 @@ struct Game<'a> {
/// The game mode; `creative` mirrors `mode == Creative`.
mode: horizon_client::command::args::GameMode,
keys: HashSet<KeyCode>,
// Physical input is separate from remapped and toggled movement keys.
physical_keys: HashSet<KeyCode>,
left: bool,
right: bool,
cursor: (f32, f32),
@@ -705,6 +713,9 @@ struct Game<'a> {
/// The first-person equip heights and the items the hands show (with
/// the slot each came from).
heights: horizon_client::first_person::HandHeights,
/// The hands' lag behind the view (`LocalPlayer.xBob`, `yBob`); a new
/// LocalPlayer (joining, respawning, changing dimension) starts at 0.
sway: horizon_client::first_person::HandSway,
visible_hands: [(usize, Option<ItemStack>); 2],
/// `Minecraft`'s attack handling, attack clicks since the last tick and
/// the attack strength tickers the hand reads.
@@ -819,6 +830,8 @@ struct Game<'a> {
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
world_options: Option<lan_screen::WorldOptions>,
/// The world was saved for the application ending (`save_for_exit`).
saved_for_exit: bool,
/// The block a guest is acting on (game/lan_actions.rs).
forced_hit: Option<Hit>,
/// Level events of this tick for the guests, and the guest acting now.
@@ -1571,6 +1584,11 @@ impl Game<'_> {
data,
} => self.sculk_charge_event(pos, data),
LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos),
LevelEvent::LevelEvent {
id: 1500,
pos,
data,
} => self.composter_fill_event(pos, data == 1),
LevelEvent::LevelEvent { id, pos, .. } => {
let c = Some([
f64::from(pos.x) + 0.5,
@@ -1632,6 +1650,7 @@ impl Game<'_> {
age: 0,
no_gravity: false,
drop_item: true,
fall_distance: 0.0,
saved: None,
});
}
@@ -1843,7 +1862,17 @@ impl Game<'_> {
next.y.floor() as i32,
next.z.floor() as i32,
);
let solid = self.res.facts.get(below).full_collision && f.velocity.y < 0.0;
let below_facts = self.res.facts.get(below);
// PowderSnowBlock.getCollisionShape for a FallingBlockEntity: the
// whole block, or 0.9 high after a fall of more than 2.5 blocks,
// where the block it rests in is the snow itself.
let powder_snow = &*below_facts.name == "minecraft:powder_snow";
let sunk = powder_snow
&& f.fall_distance > 2.5
&& next.y - next.y.floor() < f64::from(0.9_f32);
let solid =
(below_facts.full_collision || powder_snow && f.fall_distance <= 2.5 || sunk)
&& f.velocity.y < 0.0;
// FallingBlockEntity.tick: off the ground, it gives up after 600
// ticks (100 outside the world) and drops itself as an item.
let y = next.y.floor() as i32;
@@ -1860,12 +1889,15 @@ impl Game<'_> {
f.state,
[
next.x.floor() as i32,
next.y.floor() as i32 + 1,
next.y.floor() as i32 + i32::from(!sunk),
next.z.floor() as i32,
],
));
return false;
}
if next.y < f.position.y {
f.fall_distance += f.position.y - next.y;
}
f.position = next;
f.velocity = Vec3::new(
f.velocity.x * 0.98,
@@ -2049,6 +2081,10 @@ impl Game<'_> {
self.swing_arm();
return Ok(());
}
if self.use_composter(hit.pos, held.as_ref()) {
self.swing_arm();
return Ok(());
}
let face = match hit.face {
[0, 1, 0] => Direction::Up,
[0, -1, 0] => Direction::Down,
@@ -2215,8 +2251,15 @@ impl Game<'_> {
f64::from(target[1]) + 0.5,
f64::from(target[2]) + 0.5,
];
// SolidBucketItem.getPlaceSound: the bucket's own empty sound.
let solid_bucket = &*stack.item == "minecraft:powder_snow_bucket";
let place_sound = if solid_bucket {
"minecraft:item.bucket.empty_powder_snow"
} else {
&sounds.place
};
self.audio.play(
&sounds.place,
place_sound,
Some(center),
(sounds.volume + 1.0) / 2.0,
sounds.pitch * 0.8,
@@ -2228,6 +2271,10 @@ impl Game<'_> {
self.check_wither_spawn(target)?;
self.check_golem_spawn(target)?;
self.consume_held();
// SolidBucketItem.useOn: BucketItem.getEmptySuccessItem in hand.
if solid_bucket && !self.creative {
self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1));
}
Ok(())
}
fn consume_held(&mut self) {
@@ -2618,6 +2665,7 @@ impl Game<'_> {
}
self.previous_position = feet;
self.player = Some(player);
self.sway = Default::default();
self.apply_equipment();
self.eye = 1.62;
self.previous_eye = 1.62;
@@ -2725,6 +2773,20 @@ impl Game<'_> {
})
.and_then(|s| self.res.items.get(&s.item))
.map(|i| i.use_speed);
// PowderSnowBlock.canEntityWalkOnPowderSnow and LivingEntity.canFreeze.
player.leather_boots = self.armor[3]
.as_ref()
.is_some_and(|s| &*s.item == "minecraft:leather_boots");
let immune = self
.res
.items
.item_tags
.get("minecraft:freeze_immune_wearables");
player.freeze_immune = self
.armor
.iter()
.flatten()
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
let grounded = player.ground.on_ground;
let before = (
grounded,
@@ -2761,6 +2823,12 @@ impl Game<'_> {
self.record_combat(&events);
for event in events {
match event {
MotionEvent::HurtSound(sound) => {
let pitch = (self.world.random.next_float() - self.world.random.next_float())
* 0.2
+ 1.0;
self.audio.play(sound, Some(feet), 1.0, pitch);
}
MotionEvent::Emission {
position, state, ..
} if !crouching => {
@@ -2804,13 +2872,12 @@ impl Game<'_> {
b.notify_written(level, ticks, position, level_flags::UPDATE_ALL)
});
}
MotionEvent::Fall(horizon_client::landing::FallEvent::Damage { .. }) => {
self.audio
.play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0);
}
MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
_ => {}
}
}
self.powder_snow_fire()?;
self.apply_totem();
let Some(player) = self.player.as_mut() else {
return Ok(());
@@ -3169,6 +3236,8 @@ impl Game<'_> {
hud_layout::HeartKind::Poisoned
} else if effects.get("wither").is_some() {
hud_layout::HeartKind::Withered
} else if p.is_fully_frozen() {
hud_layout::HeartKind::Frozen
} else {
hud_layout::HeartKind::Normal
};
@@ -4059,7 +4128,8 @@ impl Game<'_> {
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
f.cooking_timer = 0;
// AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking.
f.input_clicked(&self.res.recipes, before[0].clone());
}
self.apply_equipment();
true
@@ -4109,13 +4179,30 @@ impl Game<'_> {
/// The plain inventory mouse press: starts a quick craft drag when a
/// stack is held, gathers on a double click, else the normal click.
fn inventory_press(&mut self, right: bool) {
use horizon_client::container_screen::Target;
use horizon_client::menu::Input;
let slot = self.renderer.as_ref().and_then(|r| {
let batch = HudBatch::new([r.config.width, r.config.height]);
self.slot_at(&batch, self.cursor.0, self.cursor.1)
});
let shift =
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
let (slot, outside) = self.inventory_target();
let shift = self.has_shift_down();
let target = Target::of(slot, outside);
let input = self.inv_clicks.press(
&target,
Self::screen_button(right),
self.carried.is_none(),
shift,
false,
);
if outside {
// slotId -999: an empty hand throws nothing; a carried stack
// starts a drag whose release drops it.
match input {
Some(input) => self.throw_click(right, input),
None if self.inv_clicks.quick_crafting().is_some() => {
self.inv_drag = Some((i32::from(right), Vec::new()));
}
None => {}
}
return;
}
if let Some(slot) = slot
&& !shift
&& slot != 200
@@ -4129,6 +4216,8 @@ impl Game<'_> {
self.last_inv_click = Some((now, slot, right));
if double && self.menu_click(Some(slot), 0, Input::PickupAll) {
self.last_inv_click = None;
// The double click's own release (`mouseReleased`'s PICKUP_ALL).
self.inv_clicks.skip_release();
return;
}
if self.carried.is_some() {
@@ -4155,6 +4244,125 @@ impl Game<'_> {
slots.push(slot);
}
}
/// The hovered slot and whether the cursor is outside the window.
fn inventory_target(&self) -> (Option<usize>, bool) {
let Some(r) = self.renderer.as_ref() else {
return (None, false);
};
let batch = HudBatch::new([r.config.width, r.config.height]);
(
self.slot_at(&batch, self.cursor.0, self.cursor.1),
self.clicked_outside(&batch),
)
}
fn screen_button(right: bool) -> horizon_client::container_screen::Button {
use horizon_client::container_screen::Button;
if right { Button::Right } else { Button::Left }
}
/// `Screen.hasShiftDown` / `InputWithModifiers.hasShiftDown`: the
/// physical Shift keys, whatever the sneak key is bound or toggled to.
pub(super) fn has_shift_down(&self) -> bool {
self.physical_keys.contains(&KeyCode::ShiftLeft)
|| self.physical_keys.contains(&KeyCode::ShiftRight)
}
/// `hasClickedOutside` of the open screen at the cursor.
fn clicked_outside(&self, batch: &HudBatch) -> bool {
use horizon_client::container_screen::{Book, Image, clicked_outside};
let (ox, oy) = self.inventory_origin(batch);
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
let image = Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height: self.screen_height() as i32,
};
let book = self
.recipe_book_area(batch)
.map(|(visible, tab_hovered)| Book {
visible,
selected_tab_hovered: tab_hovered,
});
clicked_outside(
f64::from(self.cursor.0),
f64::from(self.cursor.1),
image,
book,
)
}
/// A click outside the window (slot id -999): `THROW` does nothing; a
/// `PICKUP` drops the carried stack (left) or one of it (right), thrown
/// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`).
fn throw_click(&mut self, right: bool, input: horizon_client::menu::Input) {
use horizon_client::menu::Input;
let button = i32::from(right);
if self.remote.is_some() {
self.remote_throw(right, input);
return;
}
let before = self.carried.clone();
if !self.menu_click(None, button, input) && input == Input::Pickup {
// A screen the menu engine doesn't model: the same doClick.
if let Some(c) = self.carried.as_mut() {
let thrown = if right {
let one = ItemStack {
count: 1,
..c.clone()
};
c.count -= 1;
if c.count == 0 {
self.carried = None;
}
one
} else {
self.carried.take().expect("some")
};
self.player_drop(thrown);
}
}
if self.carried != before {
self.swing_arm();
}
if let Some(key) = self.container {
self.container_changed(key);
}
}
/// Mouse release over an inventory screen: `mouseReleased` ends or
/// cancels the drag, drops a stack released outside, or clicks.
fn inventory_mouse_release(&mut self, right: bool) {
use horizon_client::container_screen::{Release, Target};
let (slot, outside) = self.inventory_target();
let dragged = self.inv_drag.as_ref().is_some_and(|(_, s)| !s.is_empty());
let release = self.inv_clicks.release(
&Target::of(slot, outside),
Self::screen_button(right),
self.carried.is_none(),
dragged,
self.has_shift_down(),
false,
);
match (release, Target::of(slot, outside)) {
(Release::QuickCraft, _) => self.inventory_release(),
(Release::Click(input), Target::Outside) => {
self.inv_drag = None;
self.throw_click(right, input);
}
(Release::Click(input), Target::Slot(slot)) if self.inv_drag.is_some() => {
// The drag never reached a slot: a plain click where it ends.
self.inv_drag = None;
if !self.menu_click(Some(slot), i32::from(right), input) {
self.click_inventory(right);
}
if let Some(key) = self.container {
self.container_changed(key);
}
}
_ => self.inv_drag = None,
}
}
/// Mouse release: finishes a quick craft drag (one slot is a plain click).
fn inventory_release(&mut self) {
use horizon_client::menu::Input;
@@ -4207,8 +4415,7 @@ impl Game<'_> {
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
return;
};
let held_shift =
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
let held_shift = self.has_shift_down();
if self.crafter_click(slot, held_shift, right) {
return;
}
@@ -4224,8 +4431,7 @@ impl Game<'_> {
return;
}
let max = |items: &Items, s: &ItemStack| items.get(&s.item).map_or(64, |i| i.max_stack);
let shift =
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
let shift = held_shift;
if slot >= 300
&& let Some(key) = self.container
{
@@ -4249,15 +4455,8 @@ impl Game<'_> {
}
return;
}
if is_furnace
&& slot == 300
&& let Some(BlockEntity::Furnace(f)) = self
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
// Changing the input restarts cooking (AbstractFurnaceBlockEntity.setItem).
f.cooking_timer = 0;
}
// Changing the input restarts cooking (AbstractFurnaceBlockEntity.setItem).
let furnace_input = (is_furnace && slot == 300).then(|| self.slot_mut(300).clone());
if slot == 200 {
// ResultSlot: take the crafted stack and consume one of each ingredient.
let mut crafted = 0;
@@ -4368,8 +4567,15 @@ impl Game<'_> {
}
(Some(c), Some(s)) => (Some(c), Some(s)),
};
*self.slot_mut(slot) = new_slot;
self.carried = new_carried;
*self.slot_mut(slot) = new_slot;
if let Some(before) = furnace_input
&& let Some(BlockEntity::Furnace(f)) = self
.container
.and_then(|k| self.world.block_entities.get_mut(&k))
{
f.input_clicked(&self.res.recipes, before);
}
}
/// ItemEntityRenderer: items bob and spin; blocks render as small cubes.
fn entity_geometry(&mut self, camera: glam::DVec3, alpha: f64) -> Vec<Vertex> {
@@ -5222,7 +5428,8 @@ impl Game<'_> {
let z_in = (cloud_z - cell_z as f64 * 12.0) as f32;
let bottom = (cloud_height - camera.y) as f32;
let filled = |cx: i64, cz: i64| cells[(cz.rem_euclid(h) * w + cx.rem_euclid(w)) as usize];
let radius = (self.streaming.radius * 16 + 11) / 12;
// The Cloud Distance option, not the render distance.
let radius = horizon_client::clouds::radius_cells(self.settings.cloud_range);
let c = sky.cloud_color;
let color = |shade: f32| {
let ch = |v: f32| ((v * shade).clamp(0.0, 1.0) * 255.0) as u32;
@@ -5774,6 +5981,7 @@ impl Game<'_> {
player.velocity = Vec3::ZERO;
self.previous_position = player.position;
self.player = Some(player);
self.sway = Default::default();
self.apply_equipment();
let at = [f64::from(spot[0]), f64::from(spot[1]), f64::from(spot[2])];
self.audio
@@ -5838,6 +6046,20 @@ impl Game<'_> {
}
Ok(())
}
/// Leaving the game with a world open (window closed, Quit, `quit`):
/// menu items go back (Player.closeContainer), then the world is saved,
/// once.
pub(super) fn save_for_exit(&mut self) -> Result<()> {
if self.title.is_some() || self.saved_for_exit {
return Ok(());
}
self.saved_for_exit = true;
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.save_game()
}
fn close_world(&mut self) -> Result<()> {
self.ambience.clear(&mut self.audio);
// updateLevelInEngines(null): every sound stops; the music manager
@@ -6282,6 +6504,23 @@ impl Game<'_> {
return Ok(UseResult::Success { swing: true });
}
if item == "bucket" {
// getPlayerPOVHitResult(SOURCE_ONLY): powder snow's outline before
// a fluid source behind it.
if let Some(hit) = self.pick()
&& self.is_powder_snow(hit.pos)
{
let eye = self.eye_position().unwrap_or(hit.point);
let d = |p: [f64; 3]| {
(p[0] - eye[0]).powi(2) + (p[1] - eye[1]).powi(2) + (p[2] - eye[2]).powi(2)
};
if self
.pick_fluid()
.is_none_or(|fluid| d(fluid.point) >= d(hit.point))
{
self.pick_up_powder_snow(hit.pos)?;
return Ok(UseResult::Success { swing: true });
}
}
let Some(hit) = self.pick_fluid() else {
return Ok(UseResult::Pass);
};
@@ -6290,12 +6529,17 @@ impl Game<'_> {
if f.fluid == Fluid::None || f.fluid_level != 8 || f.fluid_falling {
return Ok(UseResult::Pass);
}
let (filled, sound) = match f.fluid {
Fluid::Water => ("minecraft:water_bucket", "minecraft:item.bucket.fill"),
_ => ("minecraft:lava_bucket", "minecraft:item.bucket.fill_lava"),
let sound = match f.fluid {
Fluid::Water => "minecraft:item.bucket.fill",
_ => "minecraft:item.bucket.fill_lava",
};
self.world
.set(hit.pos[0], hit.pos[1], hit.pos[2], self.world.air)?;
let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]);
let Some(filled) =
self.with_level(|b, level, ticks| b.bucket_pickup(level, ticks, pos))
else {
return Ok(UseResult::Pass);
};
self.process_level_events()?;
self.audio.play(sound, Some(at(hit.pos)), 1.0, 1.0);
self.trigger_item("minecraft:filled_bucket", &ItemStack::new(filled, 1));
if !self.creative {
@@ -6403,12 +6647,10 @@ impl Game<'_> {
},
Some(at(hit.pos)),
1.0,
if item == "fire_charge" {
(self.world.random.next_float() - self.world.random.next_float()) * 0.2
+ 1.0
} else {
self.world.random.next_float() * 0.4 + 0.8
},
horizon_client::items::fire_starter_pitch(
item == "fire_charge",
&mut self.world.random,
),
);
if item == "fire_charge" {
self.consume_held();
@@ -6426,17 +6668,12 @@ impl Game<'_> {
if !self.try_light_portal(target)? {
self.place_used_fire(target)?;
}
let sound = if item == "fire_charge" {
"minecraft:item.firecharge.use"
} else {
"minecraft:item.flintandsteel.use"
};
self.audio.play(
sound,
Some(at(target)),
1.0,
self.world.random.next_float() * 0.4 + 0.8,
let sound = horizon_client::items::fire_starter_sound(item == "fire_charge");
let pitch = horizon_client::items::fire_starter_pitch(
item == "fire_charge",
&mut self.world.random,
);
self.audio.play(sound, Some(at(target)), 1.0, pitch);
if item == "fire_charge" {
self.consume_held();
} else {
@@ -6675,7 +6912,11 @@ impl Game<'_> {
};
let inverse_height = 1.0 - self.heights.interpolated(a)[0];
let view = horizon_client::camera::view_matrix(self.yaw, self.pitch);
let to_world = view.inverse();
// The hand sway: both hands turn by a tenth of the bobs' lag.
let [sway_x, sway_y] = self.sway.rotation(a, self.pitch, self.yaw);
let to_world = view.inverse()
* glam::Mat4::from_rotation_x(sway_x.to_radians())
* glam::Mat4::from_rotation_y(sway_y.to_radians());
let eye = self.eye_position().unwrap_or_default();
let light = self.world.light(
eye[0].floor() as i32,
@@ -6808,6 +7049,33 @@ impl Game<'_> {
}
out
}
/// The renderer for the window, with the current block sprites, shared
/// atlas and world border texture.
fn new_renderer(&self, window: Arc<Window>) -> Result<Renderer> {
let assets = &self.res.assets;
let mut renderer = pollster::block_on(Renderer::new(
window,
self.options.offscreen,
&assets.pixels,
assets.sprite_size,
assets.texture_layers,
&assets.animations,
(
&self.res.atlas.pixels,
self.res.atlas.width,
self.res.atlas.height,
),
(&self.res.forcefield.2, self.res.forcefield.0),
))?;
renderer.hud.fire_animations = self
.res
.atlas
.fire_animations
.iter()
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
.collect();
Ok(renderer)
}
fn apply_settings(&mut self) {
self.streaming.radius = self.settings.render_distance;
self.streaming.biome_blend = self.settings.biome_blend;
@@ -6884,10 +7152,11 @@ impl Game<'_> {
}
}
}
/// WeatherEffectRenderer: rain/snow columns within 10 blocks.
/// WeatherEffectRenderer: rain and snow columns within the weather radius.
fn weather_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let (rain, _) = self.world.weather.levels(alpha as f32);
if rain <= 0.0 {
use horizon_client::weather;
let (intensity, _) = self.world.weather.levels(alpha as f32);
if intensity <= 0.0 {
return;
}
let atlas = &self.res.atlas;
@@ -6902,76 +7171,71 @@ impl Game<'_> {
camera.y.floor() as i32,
camera.z.floor() as i32,
);
let radius = 10;
let time = self.ticks as f32 + alpha as f32;
for dz in -radius..=radius {
for dx in -radius..=radius {
let (x, z) = (cx + dx, cz + dz);
let d2 = (dx * dx + dz * dz) as f32;
if d2 > (radius * radius) as f32 {
continue;
}
let radius = self.settings.weather_radius;
let ticks = self.world.game_time;
let partial = alpha as f32;
let eye = [camera.x, camera.y, camera.z];
// Vanilla draws every rain column before the snow ones.
let mut columns = (Vec::new(), Vec::new());
for z in cz - radius..=cz + radius {
for x in cx - radius..=cx + radius {
let top = self.rain_height(x, z, cy + radius + 10);
let y0 = (cy - radius).max(top);
let y1 = (cy + radius).max(top);
if y0 >= y1 {
if y1 == y0 {
continue;
}
let Some(snow) = self.precipitation(x, top, z) else {
let Some(snow) = self.precipitation(x, cy, z) else {
continue;
};
let hash = (x
.wrapping_mul(x)
.wrapping_mul(3121)
.wrapping_add(x.wrapping_mul(45_238_971))
^ z.wrapping_mul(z)
.wrapping_mul(418_711)
.wrapping_add(z.wrapping_mul(13761)))
& 31;
let r = if snow { snow_tex } else { rain_tex };
// Columns face the camera horizontally.
let (fx, fz) = (f64::from(x) + 0.5 - camera.x, f64::from(z) + 0.5 - camera.z);
let len = (fx * fx + fz * fz).sqrt().max(1e-3);
let (sx, sz) = ((-fz / len * 0.5) as f32, (fx / len * 0.5) as f32);
let center = glam::Vec3::new(fx as f32, 0.0, fz as f32);
let scroll = if snow {
(time / 512.0 + hash as f32 / 32.0) % 1.0
} else {
((time + hash as f32) / 32.0 * (3.0 + (hash % 5) as f32 * 0.25)) % 1.0
};
let fade = ((1.0 - d2 / (radius * radius) as f32) * 0.5 + 0.5) * rain;
let a = (fade.clamp(0.0, 1.0) * 255.0) as u32;
let color = a << 24 | 0xFF_FFFF;
let mut random = weather::column_random(x, z);
let light = self.world.light(x, top.max(cy), z);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let (b, t) = (
(f64::from(y0) - camera.y) as f32,
(f64::from(y1) - camera.y) as f32,
);
let vh = r.v1 - r.v0;
let corners = [
center + glam::Vec3::new(-sx, b, -sz),
center + glam::Vec3::new(sx, b, sz),
center + glam::Vec3::new(sx, t, sz),
center + glam::Vec3::new(-sx, t, -sz),
];
// The rain texture is a vertical strip; sample a scrolling window of it.
let s0 = scroll * 0.75;
let uv0 = r.v0 + vh * s0;
let uv1 = r.v0 + vh * (s0 + 0.25);
let uvs = [[r.u0, uv1], [r.u1, uv1], [r.u1, uv0], [r.u0, uv0]];
for (p, uv) in corners.iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 0,
color,
light: packed,
});
let coords = i32::from(light & 15) << 4 | i32::from(light >> 4) << 20;
if snow {
columns.1.push(weather::snow_column(
&mut random,
ticks,
x,
y0,
y1,
z,
coords,
partial,
));
} else {
columns.0.push(weather::rain_column(
&mut random,
ticks,
x,
y0,
y1,
z,
coords,
partial,
));
}
}
}
let rain = columns.0.iter().map(|c| (c, 1.0, rain_tex));
let snow = columns.1.iter().map(|c| (c, 0.8, snow_tex));
for (column, max_alpha, r) in rain.chain(snow) {
let quad = weather::column_quad(column, eye, max_alpha, radius, intensity);
let color = quad[0].color;
let lc = quad[0].light_coords;
let light = ((lc >> 20 & 15) * 16) as u32 | (((lc >> 4 & 15) * 16) as u32) << 8;
weather::tile(&quad, |pos, uvs| {
for (p, [u, v]) in pos.into_iter().zip(uvs) {
out.push(Vertex {
normal: [0; 4],
pos: p,
uv: [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v],
layer: 0,
color,
light,
});
}
});
}
}
/// Player.startSleepInBed: night or thunder, no monsters within 8 blocks;
/// the bed becomes the respawn point either way.
@@ -7296,6 +7560,8 @@ impl Game<'_> {
}
/// Copy the live player and world state into the `Level` that gets saved.
pub(super) fn sync_level(&mut self) {
// Level.write saves the game rules (game_rules.dat) with the rest.
self.level.game_rules = self.ui.rules.by_name();
self.level.selected_slot = self.selected as i32;
let mode = self.mode_id();
let level = &mut self.level;
@@ -7523,10 +7789,12 @@ impl Game<'_> {
self.bob_matrix(alpha as f32)
};
let distance = (self.streaming.radius * 16) as f32;
let depth_far =
horizon_client::camera::depth_far(self.streaming.radius, self.settings.cloud_range);
self.view_frustum = self
.renderer
.as_ref()
.map(|r| r.camera_frustum(fov_degrees, yaw, pitch, bob, distance));
.map(|r| r.camera_frustum(fov_degrees, yaw, pitch, bob, depth_far));
let mut entities = if title {
Vec::new()
} else {
@@ -7598,6 +7866,7 @@ impl Game<'_> {
bob,
sky,
distance,
depth_far,
underwater,
title: title && !live,
skybox: self.dim == Dim::Overworld && self.settings.horizon.sky,
@@ -7684,7 +7953,8 @@ impl Game<'_> {
&mut self.border_state,
);
// Camera.depthFar, as the renderer's far plane.
let depth_far = (distance as f32 * 4.0).max(1024.0);
let depth_far =
horizon_client::camera::depth_far(self.streaming.radius, self.settings.cloud_range);
if !self
.border_renderer
.prepare(&self.border_state, camera, distance, depth_far)
@@ -7966,31 +8236,8 @@ impl ApplicationHandler for Game<'_> {
return;
}
};
let assets = &self.res.assets;
match pollster::block_on(Renderer::new(
window.clone(),
self.options.offscreen,
&assets.pixels,
assets.sprite_size,
assets.texture_layers,
&assets.animations,
(
&self.res.atlas.pixels,
self.res.atlas.width,
self.res.atlas.height,
),
(&self.res.forcefield.2, self.res.forcefield.0),
)) {
Ok(mut r) => {
r.hud.fire_animations = self
.res
.atlas
.fire_animations
.iter()
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
.collect();
self.renderer = Some(r);
}
match self.new_renderer(window.clone()) {
Ok(r) => self.renderer = Some(r),
Err(e) => {
self.error = Some(e.to_string());
event_loop.exit();
@@ -8004,6 +8251,18 @@ impl ApplicationHandler for Game<'_> {
if self.window.as_ref().is_none_or(|w| w.id() != id) {
return;
}
if let WindowEvent::KeyboardInput { event, .. } = &event
&& let PhysicalKey::Code(key) = event.physical_key
{
if event.state == ElementState::Pressed {
self.physical_keys.insert(key);
} else {
self.physical_keys.remove(&key);
}
}
if let WindowEvent::Focused(false) = &event {
self.physical_keys.clear();
}
if matches!(
event,
WindowEvent::KeyboardInput { .. }
@@ -8025,13 +8284,7 @@ impl ApplicationHandler for Game<'_> {
let result: Result<()> = (|| {
match event {
WindowEvent::CloseRequested => {
if self.title.is_none() {
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.save_game()?;
}
self.save_for_exit()?;
event_loop.exit();
}
WindowEvent::Resized(size) => {
@@ -8218,7 +8471,7 @@ impl ApplicationHandler for Game<'_> {
}
}
Screen::Inventory => {
self.inventory_release();
self.inventory_mouse_release(button == MouseButton::Right);
self.loom_release();
}
Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(),
@@ -8546,6 +8799,33 @@ impl ApplicationHandler for Game<'_> {
}
event_loop.set_control_flow(ControlFlow::Poll);
}
/// The application is ending. On macOS, Quit (Cmd+Q) ends it through
/// applicationWillTerminate without a CloseRequested; vanilla's GLFW
/// window turns it into a window close, so Minecraft.stop saves the world.
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
if let Err(e) = self.save_for_exit() {
eprintln!("Horizon: failed to save the world on exit: {e}");
}
}
}
/// clouds.png as filled cells (`CloudRenderer.prepare`: alpha 10 or more).
fn load_clouds(root: &std::path::Path) -> (u32, u32, Vec<bool>) {
horizon_client::hud::decode(&root.join("assets/minecraft/textures/environment/clouds.png"))
.map(|(w, h, px)| {
(
w,
h,
px.as_chunks::<4>().0.iter().map(|p| p[3] >= 10).collect(),
)
})
.unwrap_or((1, 1, vec![false]))
}
/// misc/forcefield.png for the world border wall (square, power of two).
fn load_forcefield(root: &std::path::Path) -> (u32, u32, Vec<u8>) {
horizon_client::hud::decode(&root.join("assets/minecraft/textures/misc/forcefield.png"))
.ok()
.filter(|(w, h, _)| w == h && w.is_power_of_two())
.unwrap_or((1, 1, vec![0; 4]))
}
pub fn run() -> Result<()> {
let Some(mut options) = Options::read()? else {
@@ -8559,10 +8839,24 @@ pub fn run() -> Result<()> {
let vanilla_root = options.resources.clone();
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs);
let assets = match Assets::load(&options.resources) {
Ok(assets) => assets,
// Minecraft.rollbackResourcePacks: the packs break loading, start
// with the game's own resources.
Err(e) if options.resources != vanilla_root => {
eprintln!("Horizon: resource packs failed to load ({e}); using the default resources");
options.resources = vanilla_root.clone();
Assets::load(&vanilla_root)?
}
Err(e) => {
return Err(format!(
"{e}\nPrepare resources with: python3 tools/prepare_native_client.py --prepare"
)
.into());
}
};
let root = options.resources.clone();
let assets = Arc::new(Assets::load(&root).map_err(|e| {
format!("{e}\nPrepare resources with: python3 tools/prepare_native_client.py --prepare")
})?);
let assets = Arc::new(assets);
eprintln!("load assets: {:.2}s", started.elapsed().as_secs_f32());
let facts = BlockFacts::load(&root, assets.registry)?;
let mob_data = horizon_client::mobs::MobData::load(&root, &facts);
@@ -8663,23 +8957,8 @@ pub fn run() -> Result<()> {
end_environment: Environment::load_dimension(&root, "the_end", false)?,
behaviours: Behaviours::load(registry_owner.registry, &root)?,
names: Names::load(&root),
clouds: horizon_client::hud::decode(
&root.join("assets/minecraft/textures/environment/clouds.png"),
)
.map(|(w, h, px)| {
(
w,
h,
px.as_chunks::<4>().0.iter().map(|p| p[3] >= 10).collect(),
)
})
.unwrap_or((1, 1, vec![false])),
forcefield: horizon_client::hud::decode(
&root.join("assets/minecraft/textures/misc/forcefield.png"),
)
.ok()
.filter(|(w, h, _)| w == h && w.is_power_of_two())
.unwrap_or((1, 1, vec![0; 4])),
clouds: load_clouds(&root),
forcefield: load_forcefield(&root),
mob_types: MobTypes::load(&root)?
.types
.into_iter()
@@ -8730,6 +9009,7 @@ pub fn run() -> Result<()> {
craft_grid: vec![None; 9],
craft_size: 2,
inv_drag: None,
inv_clicks: Default::default(),
last_inv_click: None,
container: None,
station: None,
@@ -8745,6 +9025,7 @@ pub fn run() -> Result<()> {
horizon_client::command::args::GameMode::Survival
},
keys: HashSet::new(),
physical_keys: HashSet::new(),
left: false,
right: false,
cursor: (0.0, 0.0),
@@ -8818,6 +9099,7 @@ pub fn run() -> Result<()> {
swing: Default::default(),
swings_started: 0,
heights: Default::default(),
sway: Default::default(),
visible_hands: [(0, None), (0, None)],
clicks: Default::default(),
attack_clicks: 0,
@@ -8902,6 +9184,7 @@ pub fn run() -> Result<()> {
remote: None,
lan: None,
world_options: None,
saved_for_exit: false,
forced_hit: None,
lan_events: Vec::new(),
lan_acting: None,
@@ -338,6 +338,10 @@ impl Game<'_> {
baby: m.is_baby(),
on_ground: m.on_ground,
equipment,
components: horizon_client::mobs::finalize::variant_component(m)
.map(|(id, value)| (id.to_owned(), value))
.into_iter()
.collect(),
..Default::default()
}
}
@@ -577,6 +581,28 @@ impl Game<'_> {
adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w)
});
}
/// `EnterBlockTrigger`: the block, its state properties and the player.
pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) {
let Some(definition) = self.res.assets.registry.state(state).cloned() else {
return;
};
let me = self.player_entity();
self.trigger("minecraft:enter_block", move |c, w| {
let block_ok = adv::id_matches(&c["blocks"], "block", &definition.name, w);
let state_ok = c["state"]
.as_object()
.into_iter()
.flatten()
.all(|(k, v)| definition.properties.get(k).map(String::as_str) == v.as_str());
let pctx = adv::Entities {
this: Some(&me),
origin: me.position,
tool: None,
block_pos: None,
};
block_ok && state_ok && adv::conditions(&c["player"], &pctx, w)
});
}
/// `ItemUsedOnLocationTrigger` (placed_block, item_used_on_block).
pub(super) fn trigger_block(&mut self, name: &str, pos: [i32; 3], stack: &ItemStack) {
let me = self.player_entity();
@@ -162,6 +162,7 @@ impl Game<'_> {
let mut scene = horizon_client::collisions::SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if !scene.unobstructed(bounds).unwrap_or(false)
|| self
@@ -365,6 +366,7 @@ impl Game<'_> {
let mut scene = horizon_client::collisions::SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let mut dead = Vec::new();
for (i, a) in self.armor_stands.iter_mut().enumerate() {
@@ -142,6 +142,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
no_collision_empty(
&mut scene,
+2
View File
@@ -318,6 +318,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if b.old_status == Status::InAir && b.status != Status::InAir && b.status != Status::OnLand
{
@@ -583,6 +584,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if !scene.unobstructed(inner).unwrap_or(false) {
return false;
+3 -4
View File
@@ -642,14 +642,13 @@ impl Game<'_> {
self.build_registries();
self.sync_rules();
}
/// Save game rules, the clock and the difficulty beside level.dat.
/// Save the clock and the difficulty beside level.dat (Level.write saves
/// the game rules: a second writer of game_rules.dat could leave it with
/// the rules loaded when the world opened).
pub(super) fn save_world_state(&mut self) {
if self.world_root.as_os_str().is_empty() {
return;
}
if let Err(e) = self.ui.rules.save(&self.world_root) {
eprintln!("Horizon: failed to save game rules: {e}");
}
use horizon_world::nbt::Tag;
let c = self.ui.clock;
// The other clocks stay as saved; the overworld one keeps the fields Horizon
+1 -1
View File
@@ -1,6 +1,6 @@
//! Command execution (the `execute` side of each vanilla command class):
//! entity selectors resolved against the game, vanilla feedback and errors.
mod compute;
pub(super) mod compute;
mod data;
mod effects;
pub(super) mod execute;
+122
View File
@@ -0,0 +1,122 @@
//! `ComposterBlock`: compostable items go in by hand (`useItemOn`) or
//! through its input container (hoppers, droppers, crafters above), and the
//! fill feedback of level event 1500 (`handleFill`). Emptying a full
//! composter by hand is `useWithoutItem` in horizon-world.
use super::{Game, commands::compute::ComputeContext};
use horizon_client::{
items::ItemStack,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{position::BlockPos, random::RandomSource};
impl Game<'_> {
/// The composter's `level` at `pos`, None when it isn't a composter.
pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option<i32> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let s = self.res.assets.registry.state(state)?;
if &*s.name != "minecraft:composter" {
return None;
}
s.properties.get("level")?.parse().ok()
}
/// The item's `compostable` layers provider.
fn compostable(&self, stack: &ItemStack) -> Option<serde_json::Value> {
self.res.items.get(&stack.item)?.compostable.clone()
}
/// `ComposterBlock.addLayer` and level event 1500: the provider is
/// evaluated in the composter's block-interaction loot context (its
/// state; the level random), then the layer is added. True when it was.
fn composter_add(&mut self, pos: [i32; 3], layers: &serde_json::Value) -> bool {
let context = ComputeContext {
block: Some(pos),
target: None,
};
let layers = self.provider_int(layers, &context, 0).unwrap_or(0);
let before = self.world.block(pos[0], pos[1], pos[2]);
let at = BlockPos::new(pos[0], pos[1], pos[2]);
let after = self.with_level(|b, level, ticks| b.composter_insert(level, ticks, at, layers));
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
// The game event and level event 1500 happen here, before the caller goes on.
let _ = self.process_level_events();
after != before
}
/// `ComposterBlock.useItemOn` with the main-hand stack: true when it
/// consumed the action (SUCCESS; a full composter falls through to
/// `useWithoutItem`, which empties it).
pub(super) fn use_composter(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool {
let Some(level) = self.composter_level(pos) else {
return false;
};
let Some(stack) = held else {
return false;
};
let Some(layers) = self.compostable(stack) else {
return false;
};
if level >= 8 {
return false;
}
if level < 7 {
self.composter_add(pos, &layers);
self.stats.add("used", &stack.item, 1);
self.consume_held();
}
// ServerPlayerGameMode.useItemOn: the action was consumed.
self.trigger_block("minecraft:item_used_on_block", pos, stack);
true
}
/// `HopperBlockEntity.addItem` into the composter's `InputContainer`
/// (levels 0 to 6; one item, compostable, from above): the remainder.
pub(super) fn composter_container_insert(
&mut self,
pos: [i32; 3],
mut stack: ItemStack,
from_above: bool,
) -> Option<ItemStack> {
let level = self.composter_level(pos)?;
if !from_above || level >= 7 {
return Some(stack);
}
let Some(layers) = self.compostable(&stack) else {
return Some(stack);
};
// InputContainer.getMaxStackSize is 1: one item goes in, and its
// setChanged composts it at once.
stack.count -= 1;
self.composter_add(pos, &layers);
(stack.count > 0).then_some(stack)
}
/// `ComposterBlock.handleFill` (level event 1500) on the client: the
/// fill sound and ten composter particles above the compost.
pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) {
let center = [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 0.5,
f64::from(pos.z) + 0.5,
];
let sound = if success {
"minecraft:block.composter.fill_success"
} else {
"minecraft:block.composter.fill"
};
self.audio.play(sound, Some(center), 1.0, 1.0);
// getShape(..).max(Y, 0.5, 0.5): the compost surface (SHAPES[8] = SHAPES[7]).
let level = self.composter_level([pos.x, pos.y, pos.z]).unwrap_or(0);
let height = f64::from((1 + level.min(7) * 2).clamp(2, 16)) / 16.0 + 0.03125;
let options = ParticleOptions::simple(ParticleType::Composter);
for _ in 0..10 {
let r = self.particles.random();
let v = [
r.next_gaussian() * 0.02,
r.next_gaussian() * 0.02,
r.next_gaussian() * 0.02,
];
let p = [
f64::from(pos.x) + 0.1875 + 0.625 * f64::from(r.next_float()),
f64::from(pos.y) + height + f64::from(r.next_float()) * (1.0 - height),
f64::from(pos.z) + 0.1875 + 0.625 * f64::from(r.next_float()),
];
self.particles.add(&options, p, v);
}
}
}
+5 -8
View File
@@ -166,10 +166,12 @@ impl Game<'_> {
"down" => self.control_key_down(key)?,
"up" => {
self.keys.remove(&key);
self.physical_keys.remove(&key);
}
"tap" => {
self.control_key_down(key)?;
self.keys.remove(&key);
self.physical_keys.remove(&key);
}
other => {
return Err(
@@ -181,6 +183,7 @@ impl Game<'_> {
}
"release" => {
self.keys.clear();
self.physical_keys.clear();
self.left = false;
self.right = false;
ok()
@@ -480,14 +483,7 @@ impl Game<'_> {
ok()
}
"quit" => {
if self.title.is_none() {
// Player.closeContainer: menu items go back before saving.
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.save_game()?;
}
self.save_for_exit()?;
event_loop.exit();
ok()
}
@@ -506,6 +502,7 @@ impl Game<'_> {
}
fn control_key_down(&mut self, key: KeyCode) -> Result<()> {
self.physical_keys.insert(key);
if self.screen == Screen::Chat {
self.chat_key_code(key, None);
return Ok(());
+47 -30
View File
@@ -11,6 +11,7 @@ use horizon_client::{
mesher::Vertex,
mobs::{
Damage, DamageKind, Mob, MobEvent, MobWorld, PlayerView, Seen, SpawnSetup, Species, Who,
ai::{eating_sound, feed_animal},
farm::Climate,
spawning::{self, BiomeFacts},
},
@@ -45,6 +46,7 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
let mut scene = SceneCollisions {
world: self.w.world,
binding: self.w.collision,
subject: None,
};
let r = traverse_blocks(from, to, 256, |p: BlockPos| {
let state = self.w.world.block(p.x, p.y, p.z);
@@ -1903,6 +1905,9 @@ impl Game<'_> {
let mut consume = false;
let mut give: Option<&str> = None;
let mut sound: Option<&str> = None;
// Sounds played as vanilla plays them: (event, volume, pitch) at the feet.
let mut eat: Option<(&'static str, f32, f32)> = None;
let feet = [m.position.x, m.position.y, m.position.z];
let mut handled = true;
let mut drops: Vec<(String, u32)> = Vec::new();
let is_food = m.kind.food.contains(&item);
@@ -1978,9 +1983,9 @@ impl Game<'_> {
.get(&item)
.and_then(|i| i.food.as_ref())
.map_or(2.0, |f| f.0 as f32);
// TamableAnimal.feed: playEatingSound, which wolves leave empty.
m.health = (m.health + heal).min(m.attrs.max_health);
consume = true;
sound = Some("entity.wolf.eat");
}
Species::Wolf
if m.extra.tame
@@ -2082,9 +2087,10 @@ impl Game<'_> {
.get(&item)
.and_then(|i| i.food.as_ref())
.map_or(1.0, |f| f.0 as f32);
// TamableAnimal.feed.
m.health = (m.health + heal).min(m.attrs.max_health);
consume = true;
sound = Some("entity.cat.eat");
eat = eating_sound(m, &mut self.world.random);
}
Species::Cat
if m.extra.tame && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) =>
@@ -2097,7 +2103,6 @@ impl Game<'_> {
}
Species::Cat if !m.extra.tame && is_food => {
consume = true;
sound = Some("entity.cat.eat");
m.persistent = true;
let at = [
m.position.x,
@@ -2110,6 +2115,7 @@ impl Game<'_> {
m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1]));
m.extra.sitting = true;
}
eat = eating_sound(m, &mut self.world.random);
let kind = if tamed { "heart" } else { "smoke" };
self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?;
if tamed {
@@ -2135,25 +2141,45 @@ impl Game<'_> {
sound = Some("item.flintandsteel.use");
self.damage_held_tool();
}
// Parrot.mobInteract: parrot food may tame a wild one (one time in
// ten); a parrot never takes it as Animal food (isFood is false).
Species::Parrot if !m.extra.tame && is_food => {
consume = true;
if !m.silent {
let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2;
eat = Some(("entity.parrot.eat", 1.0, pitch));
}
let at = [
m.position.x,
m.position.y + f64::from(m.height()) * 0.5 + 0.5,
m.position.z,
];
let tamed = m.random.next_int_bound(10).unwrap_or(1) == 0;
if tamed {
m.extra.tame = true;
m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1]));
}
let kind = if tamed { "heart" } else { "smoke" };
self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?;
if tamed {
let view = self.mob_entity(&self.mobs[index]);
self.trigger_entity("minecraft:tame_animal", "entity", &view);
}
}
// HappyGhast.canFallInLove: never, so only a ghastling takes food.
_ if is_food
&& m.kind.flags.animal
&& species != Species::Parrot
&& (species != Species::HappyGhast || m.is_baby()) =>
{
// Animal.mobInteract: breed adults, speed up babies.
if m.extra.age == 0 && m.extra.in_love <= 0 {
m.extra.in_love = 600;
m.extra.love_player = true;
consume = true;
sound = Some(eat_sound(species));
} else if m.extra.age < 0 {
// AgeableMob.ageUp(getSpeedUpSecondsWhenFeeding(-age)) = 10%.
let secs = (-m.extra.age / 20) as f32 * 0.1;
m.extra.age = (m.extra.age + (secs as i32) * 20).min(0);
consume = true;
sound = Some(eat_sound(species));
} else {
handled = false;
// Animal.mobInteract: breed adults, speed up babies, then
// playEatingSound (silent unless the species overrides it).
match feed_animal(m, &mut self.world.random) {
Some(sound) => {
consume = true;
eat = sound;
}
None => handled = false,
}
}
_ => handled = false,
@@ -2168,6 +2194,10 @@ impl Game<'_> {
self.audio
.play(&format!("minecraft:{s}"), Some(center), 1.0, pitch);
}
if let Some((s, volume, pitch)) = eat {
self.audio
.play(&format!("minecraft:{s}"), Some(feet), volume, pitch);
}
if consume
&& !creative
&& let Some(stack) = self.inventory[selected].as_mut()
@@ -2516,19 +2546,6 @@ impl Game<'_> {
}
}
}
fn eat_sound(s: Species) -> &'static str {
match s {
Species::Pig => "entity.pig.eat",
Species::Horse | Species::Donkey | Species::Mule => "entity.horse.eat",
Species::Llama | Species::TraderLlama => "entity.llama.eat",
Species::Goat => "entity.goat.eat",
Species::Sniffer => "entity.sniffer.eat",
Species::Fox => "entity.fox.eat",
Species::Cat => "entity.cat.eat",
Species::Panda => "entity.panda.eat",
_ => "entity.generic.eat",
}
}
/// Mob.getBaseExperienceReward
/// The damage type id of a Horizon damage kind.
fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str {
@@ -131,6 +131,8 @@ impl Game<'_> {
self.level_events.clear();
self.orbs.clear();
self.falling.clear();
// Hopper cooldowns of an earlier case.
self.hoppers.clear();
self.ui.rules = Default::default();
// The oracle level plays on normal difficulty.
self.ui.difficulty = 2;
@@ -260,8 +262,15 @@ impl Game<'_> {
pos[2].as_i64().unwrap_or(0) as i32,
);
let state = self.world.block(origin.x, origin.y, origin.z);
let mut used = Vec::new();
if let Some(op) = case.get("remove") {
self.fixture_remove(origin, op)?;
} else if let Some(op) = case.get("use") {
used = self.fixture_use(origin, op)?;
} else if case.get("hopper").is_some() {
// HopperBlockEntity.pushItemsTick, once.
self.hopper_try_move_items((origin.x, origin.y, origin.z));
self.process_level_events()?;
} else {
self.dispense_from(origin, state)?;
// CrafterBlockEntity.serverTick, the crafting animation running down.
@@ -335,10 +344,64 @@ impl Game<'_> {
for (sound, at, _, _) in self.audio.capture.take().unwrap_or_default() {
out.push(format!("S {} {sound}", floor_pos(at)));
}
out.extend(used);
out.push(format!("rng {}", self.world.random.next_long()));
Ok(out)
}
/// A player holding the case's item right-clicks the block at `pos`
/// (`use_item_as_player`'s block steps): the statistics, the result
/// and the held stack, as `VanillaDispenserOracle.use` prints them.
fn fixture_use(&mut self, pos: BlockPos, op: &Value) -> Result<Vec<String>> {
let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
self.creative = op["creative"].as_bool().unwrap_or(false);
self.inventory[self.selected] = stack.clone();
let used_before = stack
.as_ref()
.map_or(0, |s| self.stats.get("used", &s.item));
let at = [pos.x, pos.y, pos.z];
let mut consumed = self.use_composter(at, stack.as_ref());
if !consumed {
let player = horizon_world::level::PlayerContext {
yaw: 0.0,
pitch: 90.0,
may_build: true,
can_eat: self.creative,
game_master: false,
};
let hit = horizon_core::geometry::Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 0.5,
);
let result = self.with_level(|b, level, ticks| {
b.use_without_item(
level,
ticks,
pos,
horizon_core::geometry::Direction::Up,
hit,
player,
)
});
consumed = result.consumes_action();
}
self.process_level_events()?;
let mut out = Vec::new();
if let Some(s) = &stack {
let used = self.stats.get("used", &s.item) - used_before;
if used != 0 {
out.push(format!("stat {} minecraft:used {used}", s.item));
}
}
out.push(format!(
"use {} held {}",
if consumed { "consumed" } else { "pass" },
canon_stack(self.inventory[self.selected].as_ref())
));
Ok(out)
}
/// A stack in a block entity's slot: a container's, a jukebox's record, a
/// lectern's book, or the items of a block entity Horizon keeps as saved.
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
@@ -722,6 +722,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let mut amount = -1.0;
// Level.getCollisions(null, aabb): CollisionContext.empty().
+1
View File
@@ -485,6 +485,7 @@ impl Game<'_> {
player.fall_distance = 0.0;
self.previous_position = player.position;
self.player = Some(player);
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
self.audio
@@ -129,6 +129,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let h = 0.125;
let bounds = Aabb::new(
@@ -444,6 +444,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if let Ok(moved) = scene.resolve(bounds(h.position), h.velocity, 0.0, h.on_ground) {
let horizontal =
+1
View File
@@ -104,6 +104,7 @@ impl Game<'_> {
let mut scene = horizon_client::collisions::SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if !scene.unobstructed(bounds).unwrap_or(false) {
return false;
+4
View File
@@ -170,6 +170,10 @@ impl Game<'_> {
/// strength and item swap tickers (`Player.tick`), then
/// `FirstPersonHandsAndItems.tick`.
pub(super) fn tick_hand(&mut self) {
// LocalPlayer.applyInput (the camera is the player's own).
if self.player.is_some() {
self.sway.tick(self.pitch, self.yaw);
}
self.swing.tick();
let main = self.inventory[self.selected].clone();
self.hand_strength.tick(main.as_ref().map(|s| HeldStack {
+1 -3
View File
@@ -15,7 +15,6 @@ use horizon_client::{
mesher::Vertex,
};
use serde_json::Value;
use winit::keyboard::KeyCode;
/// The game's answers to what the resolver cannot read from the stack.
pub(super) struct Env<'a, 'g> {
@@ -59,8 +58,7 @@ impl ItemEnv for Env<'_, '_> {
total as f32
}
fn has_shift_down(&self) -> bool {
self.game.keys.contains(&KeyCode::ShiftLeft)
|| self.game.keys.contains(&KeyCode::ShiftRight)
self.game.has_shift_down()
}
fn local_time(&self, pattern: &str, _locale: &str, _time_zone: Option<&str>) -> String {
local_time(pattern)
+62 -2
View File
@@ -41,6 +41,9 @@ enum Kind {
Crafter,
/// `BrewingStandBlockEntity` (a `WorldlyContainer`).
Brewing,
/// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder`
/// without a block entity): input below 7, empty at 7, bone meal at 8.
Composter(i32),
}
/// A container: one block entity, or a double chest (`CompoundContainer`).
@@ -71,6 +74,9 @@ impl View {
(Kind::Brewing, Some(Direction::Up)) => vec![3],
(Kind::Brewing, Some(Direction::Down)) => vec![0, 1, 2, 3],
(Kind::Brewing, Some(_)) => vec![0, 1, 2, 4],
(Kind::Composter(8), Some(Direction::Down)) => vec![0],
(Kind::Composter(level), Some(Direction::Up)) if level < 7 => vec![0],
(Kind::Composter(_), _) => vec![],
_ => (0..self.len()).collect(),
}
}
@@ -119,6 +125,8 @@ struct Containers<'a> {
registry: &'static horizon_world::registry::BlockRegistry,
/// Brewing recipes, for what a brewing stand accepts (not needed for signals).
brewing: Option<&'a horizon_client::brewing::Brewing>,
/// The stack of a full composter's `OutputContainer`.
bone_meal: ItemStack,
}
impl Containers<'_> {
fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> {
@@ -141,9 +149,16 @@ impl Containers<'_> {
/// first). `blocked_chests`: `ChestBlock.getContainer(.., false)` returns
/// nothing for a chest under a redstone conductor.
fn view(&self, pos: Pos, blocked_chests: bool) -> Option<View> {
let entity = self.world.block_entities.get(&pos)?;
let state = self.world.block(pos.0, pos.1, pos.2);
let name = self.name(state);
if name == "minecraft:composter" {
let level = self.prop(state, "level").and_then(|l| l.parse().ok())?;
return Some(View {
parts: vec![(pos, usize::from(level != 7))],
kind: Kind::Composter(level),
});
}
let entity = self.world.block_entities.get(&pos)?;
let kind = match (entity, name) {
(BlockEntity::Furnace(_), _) => Kind::Furnace,
(BlockEntity::Crafter(_), _) => Kind::Crafter,
@@ -202,6 +217,10 @@ impl Containers<'_> {
})
}
fn get(&self, view: &View, slot: usize) -> Option<&ItemStack> {
if let Kind::Composter(level) = view.kind {
// OutputContainer holds one bone meal; InputContainer composts at once.
return (level == 8 && slot == 0).then_some(&self.bone_meal);
}
let (pos, i) = view.locate(slot)?;
self.world
.block_entities
@@ -264,6 +283,10 @@ impl Containers<'_> {
}
/// `canTakeItemThroughFace` (furnaces and brewing stands restrict it).
fn can_take(&self, view: &View, slot: usize, stack: &ItemStack, face: Direction) -> bool {
if let Kind::Composter(level) = view.kind {
// OutputContainer.canTakeItemThroughFace.
return level == 8 && face == Direction::Down && &*stack.item == "minecraft:bone_meal";
}
if view.kind == Kind::Brewing {
return slot != 3 || &*stack.item == "minecraft:glass_bottle";
}
@@ -300,6 +323,15 @@ impl Containers<'_> {
}
}
fn bone_meal() -> ItemStack {
ItemStack {
item: "minecraft:bone_meal".into(),
count: 1,
damage: 0,
extra: None,
}
}
/// Comparator input from a container block entity (0 when there is none).
pub(super) fn container_signal(
world: &World,
@@ -314,8 +346,10 @@ pub(super) fn container_signal(
items,
registry,
brewing: None,
bone_meal: bone_meal(),
};
c.view((pos.x, pos.y, pos.z), true)
.filter(|v| !matches!(v.kind, Kind::Composter(_)))
.map_or(0, |v| c.signal(&v))
}
@@ -327,6 +361,7 @@ impl Game<'_> {
items: &self.res.items,
registry: self.res.assets.registry,
brewing: Some(&self.res.stations.brewing),
bone_meal: bone_meal(),
}
}
fn slot_mut_at(&mut self, view: &View, slot: usize) -> Option<&mut Option<ItemStack>> {
@@ -339,6 +374,10 @@ impl Game<'_> {
}
/// `BlockEntity.setChanged` for every block entity of a container.
fn view_changed(&mut self, view: &View) {
// A composter's containers change its block state instead.
if let Kind::Composter(_) = view.kind {
return;
}
for &(pos, _) in &view.parts {
self.container_changed(pos);
}
@@ -415,6 +454,10 @@ impl Game<'_> {
stack: ItemStack,
face: Option<Direction>,
) -> Option<ItemStack> {
if let Kind::Composter(_) = view.kind {
let (x, y, z) = view.parts[0].0;
return self.composter_container_insert([x, y, z], stack, face == Some(Direction::Up));
}
let slots = if matches!(view.kind, Kind::Furnace | Kind::Brewing) && face.is_some() {
view.slots_for_face(face)
} else {
@@ -482,7 +525,7 @@ impl Game<'_> {
Ok(())
}
/// `HopperBlockEntity.tryMoveItems` with `suckInItems`.
fn hopper_try_move_items(&mut self, pos: Pos) {
pub(super) fn hopper_try_move_items(&mut self, pos: Pos) {
let state = self.world.block(pos.0, pos.1, pos.2);
let c = self.containers();
let enabled = c.prop(state, "enabled") != Some("false");
@@ -540,6 +583,23 @@ impl Game<'_> {
let above = (pos.0, pos.1 + 1, pos.2);
let c = self.containers();
if let Some(source) = c.view(above, false) {
if let Kind::Composter(level) = source.kind {
if level != 8 {
return false;
}
// tryTakeInItemFromSlot on the OutputContainer: removeItem calls
// its setChanged, which empties the composter, and so does the
// second setChanged after the move or, when the hopper has no
// room, the setItem putting the bone meal back into the detached
// container (whose bone meal is lost with it).
let bone_meal = c.bone_meal.clone();
let at = BlockPos::new(above.0, above.1, above.2);
self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at));
let moved = self.add_item(None, hopper, bone_meal, None).is_none();
self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at));
self.world.modified.insert((above.0 >> 4, above.2 >> 4));
return moved;
}
let source_hopper = (source.kind == Kind::Hopper).then_some(above);
for slot in source.slots_for_face(Some(Direction::Down)) {
let c = self.containers();
@@ -304,6 +304,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if let Ok(moved) = scene.resolve(c.bounds(), delta, 0.0, c.on_ground) {
c.position = Vec3::new(
@@ -163,6 +163,7 @@ impl NaturalLevel for GameLevel<'_, '_> {
let mut scene = SceneCollisions {
world: &self.game.world,
binding: self.w.collision,
subject: None,
};
no_collision_empty(&mut scene, bounds)
}
+2 -2
View File
@@ -59,8 +59,8 @@ impl Game<'_> {
}
let m = &mut self.mobs[index];
if !m.extra.age_locked {
let secs = (-m.extra.age / 20) as f32 * 0.1;
m.extra.age = (m.extra.age + (secs as i32) * 20).min(0);
let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32;
horizon_client::mobs::ai::age_up(m, secs, true);
}
let sound = nautilus::eat_sound(m);
self.use_nautilus_food(item);
+2 -4
View File
@@ -121,11 +121,9 @@ impl Game<'_> {
self.reload_packs();
}
Event::OpenPackFolder => {
let dir = std::env::current_dir()
.unwrap_or_default()
.join("resourcepacks");
let dir = super::packs::packs_dir();
let _ = std::fs::create_dir_all(&dir);
let _ = std::process::Command::new("xdg-open").arg(&dir).spawn();
super::packs::open_folder(&dir);
}
}
}
+69 -53
View File
@@ -1,6 +1,5 @@
//! Resource pack selection bound to the game: the pack screen lists and
//! reloading after a change (atlas, fonts, GUI metadata, languages and item
//! icons live; block textures and models from the next start).
//! Resource pack selection bound to the game: the pack screen lists, and a
//! full resource reload after a change, while playing.
use super::Game;
use horizon_client::{
hud::HudAtlas,
@@ -22,6 +21,19 @@ pub fn packs_dir() -> PathBuf {
.unwrap_or_default()
.join("resourcepacks")
}
/// `Util.getPlatform().openPath`: the system file manager on the folder.
pub fn open_folder(dir: &Path) {
let program = if cfg!(target_os = "windows") {
"explorer"
} else if cfg!(target_os = "macos") {
"open"
} else {
"xdg-open"
};
if let Err(e) = std::process::Command::new(program).arg(dir).spawn() {
eprintln!("Horizon: could not open {}: {e}", dir.display());
}
}
/// The resource root to load from, given the vanilla root and the selection.
pub fn startup_root(vanilla: &Path, selected: &[String]) -> PathBuf {
let all = packs::discover(vanilla, &packs_dir());
@@ -81,63 +93,67 @@ impl Game<'_> {
o.pack_selection = self.settings.resource_packs.clone();
o.pack_screen = None;
}
/// Rebuild the overlay and reload what can change while running.
/// `Minecraft.reloadResourcePacks`: rebuild the overlay and reload every
/// client resource from it, as vanilla's reload listeners do: block
/// models and sprites (every section is meshed again,
/// `LevelRenderer.allChanged`), the shared atlas (GUI, item, entity,
/// particle and font textures), item models, sounds, languages, GUI
/// metadata and the cloud and world border textures.
pub(super) fn reload_packs(&mut self) {
let vanilla = self.vanilla_root();
if self.ui.vanilla_root.as_os_str().is_empty() {
self.ui.vanilla_root = vanilla.clone();
}
let root = startup_root(&vanilla, &self.settings.resource_packs);
self.options.resources = root.clone();
horizon_client::ui::load_metadata(&root);
match HudAtlas::build(&root) {
Ok(mut atlas) => {
atlas.font.uniform = self.settings.force_unicode;
atlas.font.japanese = self.settings.japanese_glyphs;
let same_size =
atlas.width == self.res.atlas.width && atlas.height == self.res.atlas.height;
if same_size {
if let Some(texture) = self
.renderer
.as_ref()
.and_then(|r| r.hud.atlas_texture.clone())
&& let Some(r) = self.renderer.as_ref()
{
r.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&atlas.pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(atlas.width * 4),
rows_per_image: None,
},
wgpu::Extent3d {
width: atlas.width,
height: atlas.height,
depth_or_array_layers: 1,
},
);
}
self.res.atlas = atlas;
match horizon_client::item_render::ItemRenderer::load(&root) {
Ok(r) => self.res.item_renderer = std::sync::Arc::new(r),
Err(e) => eprintln!("Horizon: item model reload failed: {e}"),
}
} else {
eprintln!(
"Horizon: resource pack atlas size changed; restart to apply GUI textures"
);
}
}
Err(e) => eprintln!("Horizon: resource pack reload failed: {e}"),
if let Err(e) = self.reload_resources(&root) {
eprintln!("Horizon: resource reload failed: {e}");
}
}
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
let assets = std::sync::Arc::new(self.res.assets.reload(root)?);
let mut atlas = HudAtlas::build(root)?;
atlas.font.uniform = self.settings.force_unicode;
atlas.font.japanese = self.settings.japanese_glyphs;
let item_renderer = horizon_client::item_render::ItemRenderer::load(root)?;
let visibility = horizon_client::models::load_visibility(root, assets.registry)?;
let tables = std::sync::Arc::new(horizon_client::mesher::MeshTables::new(
&assets,
&self.res.facts,
visibility,
)?);
// Everything loaded: switch over.
self.options.resources = root.to_path_buf();
let context = std::sync::Arc::new(horizon_client::streaming::WorkerContext {
assets: assets.clone(),
tables,
biomes: self.res.context.biomes.clone(),
light: self.res.context.light.clone(),
});
self.res.layer_names = assets
.sprite_layers
.iter()
.map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned()))
.collect();
self.res.assets = assets;
self.res.context = context.clone();
self.res.atlas = atlas;
self.res.item_renderer = std::sync::Arc::new(item_renderer);
self.res.clouds = super::load_clouds(root);
self.res.forcefield = super::load_forcefield(root);
self.res.names = super::Names::load(root);
horizon_client::ui::load_metadata(root);
lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code()));
self.audio.reload(root);
self.streaming.reload_resources(&mut self.world, context);
self.pending_uploads.clear();
// New GPU textures: a renderer built from the reloaded resources; the
// sections are uploaded again as they are meshed.
if let Some(window) = self.window.clone() {
self.renderer = None;
self.renderer = Some(self.new_renderer(window)?);
self.apply_ui_settings();
}
let code = lang::code();
lang::set(lang::Language::load(&[&root], &code));
self.ui.chat.rescale(&self.res.atlas);
Ok(())
}
}
@@ -80,6 +80,7 @@ impl Game<'_> {
let mut scene = horizon_client::collisions::SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if !scene.unobstructed(bounds).unwrap_or(false) {
return false;
@@ -204,6 +204,7 @@ impl Game<'_> {
age,
no_gravity,
drop_item,
fall_distance: 0.0,
saved: uuid.map(|u| Box::new((u, tag.clone()))),
});
}
@@ -259,6 +259,7 @@ impl Game<'_> {
scene: SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
},
facts: &self.res.facts,
context,
@@ -0,0 +1,135 @@
//! Powder snow around the player: its snowflakes, fire put out by it, and the
//! bucket that picks it up (`BucketItem.use` on a `BucketPickup` block). The
//! sinking, slowing, climbing and freezing are `PlayerMotion`'s
//! (`crate::motion`); placing it is the powder snow bucket's `BlockItem.place`.
use super::Game;
use horizon_client::{
Result,
items::ItemStack,
mobs::Who,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
impl Game<'_> {
/// `ClientPacketListener.handleParticleEvent` for the one ALTERNATIVE
/// snowflake `PowderSnowBlock.entityInside` sends: no spread, its speed.
pub(super) fn snowflake(&mut self, position: Vec3, velocity: Vec3) {
let r = self.particles.random();
// nextDouble() * dist for each axis, the distances being 0.
let offset = [
r.next_double() * 0.0,
r.next_double() * 0.0,
r.next_double() * 0.0,
];
let options = ParticleOptions::simple(ParticleType::Snowflake);
self.particles.add(
&options,
[
position.x + offset[0],
position.y + offset[1],
position.z + offset[2],
],
[velocity.x, velocity.y, velocity.z],
);
}
/// The EXTINGUISH effect of the powder snow the player went into this
/// tick: burning, it destroys those blocks (a player always may), then
/// its fire goes out (`Entity.clearFire`) with the extinguish sound.
pub(super) fn powder_snow_fire(&mut self) -> Result<()> {
let Some(player) = self.player.as_mut() else {
return Ok(());
};
let entered = std::mem::take(&mut player.powder_snow_entered);
let at = [player.position.x, player.position.y, player.position.z];
if entered.is_empty() || player.fire_ticks <= 0 {
return Ok(());
}
for pos in entered {
self.with_level(|b, level, ticks| b.destroy_block(level, ticks, pos, false));
self.world.modified.insert((pos.x >> 4, pos.z >> 4));
}
self.process_level_events()?;
if let Some(player) = self.player.as_mut() {
player.fire_ticks = 0;
}
// Entity.playEntityOnFireExtinguishedSound
let r = self.particles.random();
let pitch = 1.6 + (r.next_float() - r.next_float()) * 0.4;
self.audio.play(
"minecraft:entity.generic.extinguish_fire",
Some(at),
0.7,
pitch,
);
Ok(())
}
/// Whether the block at `pos` is powder snow.
pub(super) fn is_powder_snow(&self, pos: [i32; 3]) -> bool {
&*self
.res
.facts
.get(self.world.block(pos[0], pos[1], pos[2]))
.name
== "minecraft:powder_snow"
}
/// `BucketItem.use` with an empty bucket on powder snow:
/// `PowderSnowBlock.pickupBlock` (air, level event 2001), the used
/// statistic, the fill sound, FLUID_PICKUP, `ItemUtils.createFilledResult`
/// and the filled_bucket trigger.
pub(super) fn pick_up_powder_snow(&mut self, pos: [i32; 3]) -> Result<()> {
let at = BlockPos::new(pos[0], pos[1], pos[2]);
let picked = self.with_level(|b, level, ticks| b.bucket_pickup(level, ticks, at));
self.process_level_events()?;
let Some(filled) = picked else {
return Ok(());
};
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
self.stats.add("used", "minecraft:bucket", 1);
if let Some(eye) = self
.player
.as_ref()
.map(|p| [p.position.x, p.position.y, p.position.z])
{
self.audio.play(
"minecraft:item.bucket.fill_powder_snow",
Some(eye),
1.0,
1.0,
);
}
self.post_block_game_event("minecraft:fluid_pickup", pos, Some(Who::Player), None);
let filled = ItemStack::new(filled, 1);
self.filled_result(filled.clone());
self.trigger_item("minecraft:filled_bucket", &filled);
self.swing_arm();
Ok(())
}
/// `ItemUtils.createFilledResult(held, player, filled)` for the held stack.
fn filled_result(&mut self, filled: ItemStack) {
if self.creative {
// Kept, and the filled one added unless the inventory has it.
let has = self
.inventory
.iter()
.flatten()
.any(|s| s.same_item_same_components(&filled));
if !has {
let _ = self.give(filled);
}
return;
}
let held = &mut self.inventory[self.selected];
let last = held.as_ref().is_none_or(|s| s.count <= 1);
if last {
*held = Some(filled);
return;
}
if let Some(s) = held.as_mut() {
s.count -= 1;
}
if let Some(rest) = self.give(filled) {
self.player_drop(rest);
}
}
}
+18 -3
View File
@@ -169,7 +169,7 @@ impl Game<'_> {
pub(super) fn recipe_key(&mut self, event: &winit::event::KeyEvent) {
use winit::keyboard::{KeyCode, PhysicalKey};
let ctrl = self.keys.contains(&KeyCode::ControlLeft);
let shift = self.keys.contains(&KeyCode::ShiftLeft);
let shift = self.has_shift_down();
let Some(search) = self.recipe_ui.search.as_mut() else {
return;
};
@@ -620,8 +620,23 @@ impl Game<'_> {
false
}
fn shift_down(&self) -> bool {
use winit::keyboard::KeyCode;
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight)
self.has_shift_down()
}
/// The open screen's book for `hasClickedOutside`: (visible, selected tab
/// hovered); None when the screen has no book.
pub(super) fn recipe_book_area(&self, batch: &HudBatch) -> Option<(bool, bool)> {
let book = self.active_book()?;
if !self.book_open(book) {
return Some((false, false));
}
let (xo, yo) = self.book_origin(batch);
let tabs = &self.recipe_ui.view.tabs;
let selected = self.recipe_ui.tab.unwrap_or(Tab::Search);
let hovered = tabs.iter().position(|t| *t == selected).is_some_and(|n| {
let (x, y) = self.tab_pos(xo, yo, n);
inside(self.cursor, x, y, 35.0, 27.0)
});
Some((true, hovered))
}
/// The grid, result and furnace slots clicks on which end a ghost recipe.
fn is_book_slot(&self, book: BookType, slot: usize) -> bool {
+34 -2
View File
@@ -1571,6 +1571,7 @@ impl Game<'_> {
let mut player = PlayerMotion::new(self.motion, position)?;
player.velocity = delta;
self.player = Some(player);
self.sway = Default::default();
self.eye = 1.62;
self.previous_eye = 1.62;
self.clock.reset();
@@ -2284,8 +2285,7 @@ impl Game<'_> {
};
let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal));
let Some(slot) = slot else { return };
let shift =
self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight);
let shift = self.has_shift_down();
let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s));
let state = self.remote.as_ref().map_or(0, |r| r.state_id);
self.send(S::ContainerClick(play::ContainerClick {
@@ -2298,6 +2298,38 @@ impl Game<'_> {
carried,
}));
}
/// A click outside a server's window (slot -999): predicted like
/// `MultiPlayerGameMode.handleContainerInput` (the carried stack after
/// `doClick`; the server drops the stack and swings the hand).
pub(super) fn remote_throw(&mut self, right: bool, input: horizon_client::menu::Input) {
use horizon_client::menu::Input;
let container = self
.remote
.as_ref()
.and_then(|r| r.menu.as_ref())
.map_or(0, |m| m.0);
if input == Input::Pickup
&& let Some(c) = self.carried.as_mut()
{
if right && c.count > 1 {
c.count -= 1;
} else {
self.carried = None;
}
self.swing_arm();
}
let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s));
let state = self.remote.as_ref().map_or(0, |r| r.state_id);
self.send(S::ContainerClick(play::ContainerClick {
container,
state,
slot: -999,
button: i8::from(right),
input: if input == Input::Throw { 4 } else { 0 },
changed: Vec::new(),
carried,
}));
}
pub(super) fn remote_close_container(&mut self) {
let id = self
.remote
@@ -83,6 +83,7 @@ impl Game<'_> {
],
biome,
render_distance_chunks: self.streaming.radius,
cloud_range_chunks: self.settings.cloud_range,
camera_y: camera.y,
min_y: MIN_Y,
flat: false,
@@ -160,8 +161,8 @@ impl Game<'_> {
}
_ => Vec::new(),
},
ticks_frozen: 0,
percent_frozen: 0.0,
ticks_frozen: p.ticks_frozen,
percent_frozen: p.percent_frozen(),
partial,
portal: [fx.o_portal, fx.portal],
nausea: 0.0,
@@ -46,13 +46,13 @@ impl Game<'_> {
use winit::keyboard::KeyCode;
let saved = self.cursor;
self.cursor = (x, y);
let had_shift = self.keys.contains(&KeyCode::ShiftLeft);
let had_shift = self.physical_keys.contains(&KeyCode::ShiftLeft);
if shift {
self.keys.insert(KeyCode::ShiftLeft);
self.physical_keys.insert(KeyCode::ShiftLeft);
}
self.click_inventory(right);
if shift && !had_shift {
self.keys.remove(&KeyCode::ShiftLeft);
self.physical_keys.remove(&KeyCode::ShiftLeft);
}
self.cursor = saved;
}
+1
View File
@@ -88,6 +88,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let wanted = t.velocity;
let moved = scene
@@ -274,6 +274,7 @@ impl Game<'_> {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if let Ok(moved) = scene.resolve(bounds(t.position), t.velocity, 0.0, false) {
let blocked = (moved.x - t.velocity.x).abs() > 1e-7
+37
View File
@@ -164,6 +164,20 @@ impl GameRules {
}
ok
}
/// Every rule's value by name without namespace, as `save::Level` holds
/// them (booleans as 0 or 1).
pub fn by_name(&self) -> BTreeMap<String, i32> {
RULES
.iter()
.map(|r| {
let v = match self.values.get(r.name).copied().unwrap_or(r.default) {
Value::Bool(b) => i32::from(b),
Value::Int(i) => i,
};
(r.name.to_owned(), v)
})
.collect()
}
/// GameRuleMap codec: `{data: {"minecraft:<rule>": value...}, DataVersion}`.
pub fn to_nbt(&self) -> NamedTag {
let data: Vec<(horizon_world::nbt::JavaString, Tag)> = RULES
@@ -253,4 +267,27 @@ mod tests {
assert_eq!(GameRules::load(&dir), rules);
let _ = fs::remove_dir_all(dir);
}
/// The world's save (Level.write) writes the rules as they are now, and a
/// world opened again reads them back (#74).
#[test]
fn level_save_keeps_changed_rules() {
let dir =
std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let mut level = crate::save::Level::default();
level.write(&dir).unwrap();
// Rules changed while playing, then saved and loaded again.
let mut rules = GameRules::load(&dir);
assert_eq!(rules, GameRules::default());
assert!(rules.set("advance_time", Value::Bool(false)));
assert!(rules.set("advance_weather", Value::Bool(false)));
assert!(rules.set("random_tick_speed", Value::Int(0)));
level.game_rules = rules.by_name();
level.write(&dir).unwrap();
assert_eq!(GameRules::load(&dir), rules);
let read = crate::save::Level::read(&dir).unwrap();
assert_eq!(read.game_rules, rules.by_name());
assert_eq!(read.game_rule("advance_time"), 0);
let _ = fs::remove_dir_all(dir);
}
}
+11 -7
View File
@@ -123,6 +123,8 @@ pub struct Frame<'a> {
pub sky: Sky,
/// Render distance in blocks (fog end).
pub distance: f32,
/// `Camera.depthFar`: the far plane (`crate::camera::depth_far`).
pub depth_far: f32,
pub underwater: bool,
/// Skip sections the camera cannot see through open faces (vanilla's
/// occlusion graph; off in spectator-like views inside blocks).
@@ -253,6 +255,8 @@ pub struct Renderer {
lightmap_view: wgpu::TextureView,
lightmap_sampler: wgpu::Sampler,
animations: Vec<(SpriteAnimation, usize)>,
/// Edge length of the block sprite array's layers.
sprite_size: u32,
indices: wgpu::Buffer,
index_quads: u32,
instances: wgpu::Buffer,
@@ -1325,6 +1329,7 @@ impl Renderer {
lightmap_view,
lightmap_sampler,
animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(),
sprite_size,
indices,
index_quads,
instances,
@@ -1614,7 +1619,7 @@ impl Renderer {
frame.yaw,
frame.pitch,
frame.bob,
frame.distance,
frame.depth_far,
)
}
/// The view frustum `render` will cull with, for culling geometry built
@@ -1625,15 +1630,14 @@ impl Renderer {
yaw: f32,
pitch: f32,
bob: Mat4,
distance: f32,
depth_far: f32,
) -> Frustum {
Frustum {
planes: frustum(self.projection(fov_degrees, yaw, pitch, bob, distance)),
planes: frustum(self.projection(fov_degrees, yaw, pitch, bob, depth_far)),
}
}
fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, distance: f32) -> Mat4 {
fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, far: f32) -> Mat4 {
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
let far = (distance * 4.0).max(1024.0);
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, 0.05, far)
* bob
* crate::camera::view_matrix(yaw, pitch)
@@ -1700,7 +1704,7 @@ impl Renderer {
animate_sprites(
&mut self.animations,
tick,
self.sprite_texture.width(),
self.sprite_size,
self.mip_levels,
|layer, level, size, pixels| {
self.queue.write_texture(
@@ -1860,7 +1864,7 @@ impl Renderer {
frame.hand_fov_degrees,
self.config.width as f32,
self.config.height.max(1) as f32,
(frame.distance * 4.0).max(1024.0),
frame.depth_far,
));
let hand_globals = Globals {
view_proj: (hand_projection * frame.bob * view).to_cols_array_2d(),
+13 -1
View File
@@ -79,6 +79,8 @@ impl HealthResources {
#[derive(Clone, Copy, Debug)]
pub enum HealthEvent {
StarvationDamage(f32),
/// `LivingEntity.aiStep` hurting a fully frozen entity.
FreezeDamage(f32),
Updated {
id: u8,
value: f32,
@@ -103,6 +105,7 @@ impl HealthEvent {
pub fn trace(self) -> String {
match self {
Self::StarvationDamage(amount) => format!("damage starve {:08x}", amount.to_bits()),
Self::FreezeDamage(amount) => format!("damage freeze {:08x}", amount.to_bits()),
Self::Updated { id, value, dirty } => {
format!("updated {id} {:08x} {dirty}", value.to_bits())
}
@@ -588,7 +591,16 @@ impl HurtWorld for Environment<'_> {
self.phase("death-request")
}
fn hurt_sound(&mut self, _: &mut State) -> io::Result<()> {
self.phase("hurt-sound")
self.phase("hurt-sound")?;
let sound = match self.source.definition().effects.as_str() {
"burning" => "minecraft:entity.player.hurt_on_fire",
"drowning" => "minecraft:entity.player.hurt_drown",
"freezing" => "minecraft:entity.player.hurt_freeze",
"poking" => "minecraft:entity.player.hurt_sweet_berry_bush",
_ => "minecraft:entity.player.hurt",
};
self.events.push(MotionEvent::HurtSound(sound));
Ok(())
}
fn game_time(&mut self, _: &mut State) -> io::Result<i64> {
Ok(self.game_time)
+24
View File
@@ -12,6 +12,27 @@ use std::{
sync::Arc,
};
/// A fire starter's use sound: `SoundEvents.FIRECHARGE_USE` or
/// `FLINTANDSTEEL_USE`.
pub fn fire_starter_sound(fire_charge: bool) -> &'static str {
if fire_charge {
"minecraft:item.firecharge.use"
} else {
"minecraft:item.flintandsteel.use"
}
}
/// The pitch of a fire starter's use sound, from the level's random:
/// `FlintAndSteelItem.useOn`'s `nextFloat() * 0.4 + 0.8`, or
/// `FireChargeItem.playSound`'s `(nextFloat() - nextFloat()) * 0.2 + 1.0`.
pub fn fire_starter_pitch(fire_charge: bool, random: &mut impl RandomSource) -> f32 {
if fire_charge {
(random.next_float() - random.next_float()) * 0.2 + 1.0
} else {
random.next_float() * 0.4 + 0.8
}
}
#[derive(Clone, Debug)]
pub struct ToolRule {
pub blocks: Vec<String>,
@@ -37,6 +58,8 @@ pub struct ItemInfo {
pub fuel: Option<(Value, Value)>,
/// `brewing_fuel`: uses and speed-multiplier provider references.
pub brewing_fuel: Option<(Value, Value)>,
/// `compostable.layers`: the layers provider (`ComposterBlock.addLayer`).
pub compostable: Option<Value>,
/// Item left behind after crafting/fuel use (e.g. bucket).
pub remainder: Option<String>,
/// `equippable.slot` (head, chest, legs, feet, ...).
@@ -467,6 +490,7 @@ impl Items {
brewing_fuel: c
.get("minecraft:brewing_fuel")
.map(|f| (f["uses"].clone(), f["speed_multiplier"].clone())),
compostable: c.get("minecraft:compostable").map(|f| f["layers"].clone()),
remainder: c["minecraft:use_remainder"]["id"]
.as_str()
.or(c["minecraft:crafting_remainder"]["id"].as_str())
+1
View File
@@ -295,6 +295,7 @@ impl BlockPushWorld for MotionWorld<'_, '_, '_> {
let mut world = SceneCollisions {
world: self.scene,
binding: self.collision_binding,
subject: None,
};
self.collision_binding
.collision_shape(&mut world, state, [p.x, p.y, p.z])
+26 -7
View File
@@ -32,11 +32,24 @@ static CURRENT: RwLock<Option<Arc<Language>>> = RwLock::new(None);
/// A source of resource files: the prepared root plus packs, highest priority last.
pub trait ResourceSource {
fn read(&self, path: &str) -> Option<Vec<u8>>;
/// The namespaces under `assets/` (resource packs may add their own).
fn namespaces(&self) -> Vec<String> {
vec!["minecraft".into()]
}
}
impl ResourceSource for std::path::PathBuf {
fn read(&self, path: &str) -> Option<Vec<u8>> {
std::fs::read(self.join(path)).ok()
}
fn namespaces(&self) -> Vec<String> {
std::fs::read_dir(self.join("assets"))
.into_iter()
.flatten()
.flatten()
.filter(|e| e.path().is_dir())
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
.collect()
}
}
/// DeprecatedTranslationsInfo.applyToMap: drop removed keys, then move each
@@ -71,20 +84,26 @@ impl Language {
}
}
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
/// from every source in priority order (later sources override).
/// from every namespace and every source in priority order (later sources
/// override).
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
let mut map = HashMap::new();
let mut codes = vec![DEFAULT];
if code != DEFAULT {
codes.push(code);
}
let namespaces: std::collections::BTreeSet<String> =
sources.iter().flat_map(|s| s.namespaces()).collect();
for c in codes {
for source in sources {
let Some(bytes) = source.read(&format!("assets/minecraft/lang/{c}.json")) else {
continue;
};
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(&bytes) {
map.extend(entries);
for namespace in &namespaces {
for source in sources {
let Some(bytes) = source.read(&format!("assets/{namespace}/lang/{c}.json"))
else {
continue;
};
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(&bytes) {
map.extend(entries);
}
}
}
}
+2
View File
@@ -31,6 +31,7 @@ pub mod collisions;
pub mod command;
pub mod command_storage;
pub mod component;
pub mod container_screen;
pub mod containers;
pub mod control;
pub mod crafting;
@@ -131,6 +132,7 @@ pub mod title;
pub mod ui;
pub mod ui_theme;
pub mod vanillagen;
pub mod weather;
pub mod widgets;
pub mod window;
pub mod world;
+5
View File
@@ -620,6 +620,11 @@ pub struct Extra {
pub age: i32,
/// `AgeLocked` (tadpoles fed a slime ball... and ageable mobs).
pub age_locked: bool,
/// AgeableMob.forcedAge: the age fed food added, restored as the age
/// when it reaches 0 (`ForcedAge`).
pub forced_age: i32,
/// AgeableMob.forcedAgeTimer: ticks of happy villager particles left.
pub forced_age_timer: i32,
pub in_love: i32,
pub love_player: bool,
/// Texture/model variant index (cat type, horse colour, rabbit type...).
+108 -2
View File
@@ -571,7 +571,7 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry",
Species::Piglin if m.ai.target.is_some() => "entity.piglin.angry",
Species::Hoglin if m.ai.target.is_some() => "entity.hoglin.angry",
_ => m.kind.sounds[0],
_ => voice_sounds(m)[0],
};
let _ = w;
if !sound.is_empty() {
@@ -633,7 +633,23 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
if m.kind.flags.climber {
m.climbing = m.horizontal_collision;
}
// AgeableMob.aiStep
// AgeableMob.aiStep: a forced age-up's particles (positions drawn on the
// server too), then the age.
if m.extra.forced_age_timer > 0 {
if m.extra.forced_age_timer % 4 == 0 {
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
let r = &mut m.random;
let x = m.position.x + w * (2.0 * r.next_double() - 1.0);
let y = m.position.y + h * r.next_double() + 0.5;
let z = m.position.z + w * (2.0 * r.next_double() - 1.0);
events.push(MobEvent::Particles {
kind: "happy_villager",
at: [x, y, z],
count: 1,
});
}
m.extra.forced_age_timer -= 1;
}
if m.alive() {
if m.extra.age < 0 {
let (bw, bh, _) = m.dims();
@@ -996,9 +1012,99 @@ pub fn voice_sounds(m: &Mob) -> [&'static str; 3] {
match m.species() {
Species::Nautilus | Species::ZombieNautilus => super::nautilus::sounds(m),
Species::SulfurCube => super::sulfur_cube::sounds(m),
// The sound variant's baby_sounds (classic sets, like the rest here).
Species::Pig if m.is_baby() => [
"entity.baby_pig.ambient",
"entity.baby_pig.hurt",
"entity.baby_pig.death",
],
Species::Chicken if m.is_baby() => [
"entity.baby_chicken.ambient",
"entity.baby_chicken.hurt",
"entity.baby_chicken.death",
],
_ => m.kind.sounds,
}
}
/// `Animal.mobInteract` with its food in hand: an adult that can fall in
/// love does, a baby grows up by a tenth, and either plays its eating sound
/// (`Strider.mobInteract` plays its own afterwards). `None` when the animal
/// does not take the food; otherwise the sound to play, if any.
pub fn feed_animal(
m: &mut Mob,
level: &mut impl RandomSource,
) -> Option<Option<(&'static str, f32, f32)>> {
if m.extra.age == 0 && m.extra.in_love <= 0 {
m.extra.in_love = 600;
m.extra.love_player = true;
} else if m.extra.age < 0 {
// AgeableMob.ageUp(getSpeedUpSecondsWhenFeeding(-age), true): a tenth.
let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32;
age_up(m, secs, true);
} else {
return None;
}
let mut sound = eating_sound(m, level);
if m.species() == Species::Strider && !m.silent {
let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2;
sound = Some(("entity.strider.eat", 1.0, pitch));
}
Some(sound)
}
/// `AgeableMob.ageUp(seconds, forced)`.
pub fn age_up(m: &mut Mob, seconds: i32, forced: bool) {
let age = m.extra.age;
let grown = (age + seconds * 20).min(0);
m.extra.age = grown;
if forced {
m.extra.forced_age += grown - age;
if m.extra.forced_age_timer == 0 {
m.extra.forced_age_timer = 40;
}
}
if m.extra.age == 0 {
m.extra.age = m.extra.forced_age;
}
}
/// `Animal.playEatingSound` (empty) and its overrides, as (sound, volume,
/// pitch); `level` is the level's random. Pigs and cats use the classic sound
/// set, like their other sounds here.
pub fn eating_sound(
m: &mut Mob,
level: &mut impl RandomSource,
) -> Option<(&'static str, f32, f32)> {
let baby = m.is_baby();
// Mth.randomBetween(level.getRandom(), 0.8, 1.2).
let mut between = || level.next_float() * 0.4 + 0.8;
let (sound, volume, pitch, entity_sound) = match m.species() {
// makeSound: getSoundVolume, getVoicePitch.
Species::Armadillo | Species::Pig | Species::SulfurCube => {
let sound = match m.species() {
Species::Armadillo => "entity.armadillo.eat",
Species::Pig if baby => "entity.baby_pig.eat",
Species::Pig => "entity.pig.eat",
_ => "entity.small_sulfur_cube.eat",
};
let pitch = m.voice_pitch();
(sound, sound_volume(m), pitch, true)
}
// playSound(sound, 1, 1).
Species::Cat if baby => ("entity.baby_cat.eat", 1.0, 1.0, true),
Species::Cat => ("entity.cat.eat", 1.0, 1.0, true),
Species::Fox => ("entity.fox.eat", 1.0, 1.0, true),
// level().playSound(null, this, sound, NEUTRAL, volume, pitch).
Species::Frog => ("entity.frog.eat", 2.0, 1.0, false),
Species::Goat if m.extra.screaming => ("entity.goat.screaming.eat", 1.0, between(), false),
Species::Goat => ("entity.goat.eat", 1.0, between(), false),
Species::Sniffer => ("entity.sniffer.eat", 1.0, between(), false),
_ => return None,
};
// Entity.playSound is skipped for a silent entity.
if entity_sound && m.silent {
return None;
}
Some((sound, volume, pitch))
}
pub fn sound_volume(m: &Mob) -> f32 {
match m.species() {
Species::Ghast => 5.0,
@@ -360,6 +360,7 @@ fn can_spawn_on(b: &Blocks, pos: [i32; 3], state: BlockStateId, above: BlockStat
let mut scene = SceneCollisions {
world: b.w.world,
binding: b.w.collision,
subject: None,
};
let above_pos = [pos[0], pos[1] + 1, pos[2]];
let above_empty =
@@ -422,6 +423,7 @@ fn spawn_protector(
let mut scene = SceneCollisions {
world: w.world,
binding: w.collision,
subject: None,
};
if !scene.unobstructed(bounds).unwrap_or(false) {
continue;
@@ -1988,6 +1988,25 @@ pub fn variant_index(s: Species, name: &str) -> u8 {
};
i.unwrap_or(0) as u8
}
/// The variant data component a mob reports (`Entity.get`, e.g.
/// `Wolf.get(DataComponents.WOLF_VARIANT)`): component id and registry entry.
pub fn variant_component(m: &Mob) -> Option<(&'static str, String)> {
species_variant_component(m.species(), m.extra.variant)
}
/// [`variant_component`] of a species with the game's variant index.
pub fn species_variant_component(s: Species, variant: u8) -> Option<(&'static str, String)> {
let component = match s {
Species::Wolf => "minecraft:wolf/variant",
Species::Cat => "minecraft:cat/variant",
Species::Frog => "minecraft:frog/variant",
Species::Pig => "minecraft:pig/variant",
Species::Cow => "minecraft:cow/variant",
Species::Chicken => "minecraft:chicken/variant",
Species::ZombieNautilus => "minecraft:zombie_nautilus/variant",
_ => return None,
};
Some((component, format!("minecraft:{}", variant_name(s, variant))))
}
/// The registry name of the game's variant index.
pub fn variant_name(s: Species, index: u8) -> &'static str {
let i = index as usize;
+3
View File
@@ -122,6 +122,7 @@ impl MobWorld<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
let state = self.world.block(x, y, z);
let at = horizon_core::position::BlockPos::new(x, y, z);
@@ -168,6 +169,7 @@ impl MobWorld<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
scene.unobstructed(b).unwrap_or(false)
}
@@ -311,6 +313,7 @@ impl Mob {
let mut scene = SceneCollisions {
world: w.world,
binding: w.collision,
subject: None,
};
let moved = scene
.resolve(self.bounds(), wanted, step, self.on_ground)
+5
View File
@@ -63,6 +63,7 @@ impl MobWorld<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
let state = self.world.block(p.x, p.y, p.z);
@@ -87,6 +88,7 @@ impl MobWorld<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
let full = horizon_core::geometry::Aabb::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
@@ -118,6 +120,7 @@ impl MobWorld<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
let state = self.world.block(p.x, p.y, p.z);
@@ -138,6 +141,7 @@ impl MobWorld<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
let result = traverse_blocks(from, to, 512, |p: BlockPos| {
let state = self.world.block(p.x, p.y, p.z);
@@ -157,6 +161,7 @@ impl MobWorld<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
let state = self.world.block(p[0], p[1], p[2]);
self.collision
+429 -8
View File
@@ -1,10 +1,12 @@
//! Stored movement state for the resident scene. This binds the validated air,
//! jump, collision, support, restitution and stored health bindings. Entity lifecycle,
//! jump, collision, support, restitution and stored health bindings, and
//! powder snow's block-inside effects and freezing. Entity lifecycle, other
//! block-inside effects and audiovisual event consumers remain separate work.
use crate::{Result, assets::Assets, collisions::SceneCollisions, world::World};
use horizon_core::{
geometry::{Aabb, Vec3, VoxelShape, traverse_blocks},
geometry::{Aabb, Axis, Direction, Vec3, VoxelShape, traverse_blocks},
position::BlockPos,
random::RandomSource,
};
use horizon_world::{
attribute_map::ValueKind,
@@ -109,6 +111,7 @@ pub enum MotionEvent {
enabled: bool,
},
Health(crate::health::HealthEvent),
HurtSound(&'static str),
Fall(crate::landing::FallEvent),
Recorded {
mover: MoverType,
@@ -130,6 +133,16 @@ pub enum MotionEvent {
state: BlockStateId,
fall_distance: f64,
},
/// `PowderSnowBlock.entityInside`'s server particle: one snowflake at
/// `position` with `velocity` (`RandomizationType.ALTERNATIVE`).
Snowflake {
position: Vec3,
velocity: Vec3,
},
/// `ServerPlayer.onInsideBlock`: the enter_block criterion trigger.
EnterBlock {
state: BlockStateId,
},
}
pub struct PlayerMotion {
pub fluids: horizon_world::entity_fluid::EntityFluidInteraction,
@@ -199,6 +212,23 @@ pub struct PlayerMotion {
pub health: crate::health::PlayerHealth,
/// Status effects and armor protection seen by movement and damage.
pub status: crate::effects::StatusFlags,
/// `Entity.isInPowderSnow` / `wasInPowderSnow`.
pub in_powder_snow: bool,
pub was_in_powder_snow: bool,
/// `Entity.DATA_TICKS_FROZEN`.
pub ticks_frozen: i32,
/// Leather boots on the feet (`PowderSnowBlock.canEntityWalkOnPowderSnow`).
pub leather_boots: bool,
/// An armor piece in `#freeze_immune_wearables` (`LivingEntity.canFreeze`).
pub freeze_immune: bool,
/// `Entity.oldPosition`: where this tick started.
pub old_position: Vec3,
/// `Entity.applyEffectsFromBlocks` runs after travel (always in the game;
/// differential fixtures turn it off where their reference does).
pub block_effects: bool,
/// The powder snow blocks this tick's movement went into: the game
/// destroys them if the player is burning, then puts the fire out.
pub powder_snow_entered: Vec<BlockPos>,
}
fn attribute_error(error: impl std::fmt::Debug) -> io::Error {
io::Error::other(format!("movement attribute: {error:?}"))
@@ -312,8 +342,68 @@ impl PlayerMotion {
sync_position: false,
events: Vec::new(),
attributes,
in_powder_snow: false,
was_in_powder_snow: false,
ticks_frozen: 0,
leather_boots: false,
freeze_immune: false,
old_position: position,
block_effects: true,
powder_snow_entered: Vec::new(),
})
}
/// `Entity.getTicksRequiredToFreeze`.
pub const TICKS_REQUIRED_TO_FREEZE: i32 = 140;
/// `Entity.getPercentFrozen`.
pub fn percent_frozen(&self) -> f32 {
self.ticks_frozen.min(Self::TICKS_REQUIRED_TO_FREEZE) as f32
/ Self::TICKS_REQUIRED_TO_FREEZE as f32
}
/// `Entity.isFullyFrozen`.
pub fn is_fully_frozen(&self) -> bool {
self.ticks_frozen >= Self::TICKS_REQUIRED_TO_FREEZE
}
/// `LivingEntity.canFreeze`: not a spectator, no freeze-immune armor.
pub fn can_freeze(&self) -> bool {
!self.spectator && !self.freeze_immune
}
/// What powder snow's contextual collision asks of the player.
pub fn powder_snow_subject(&self) -> crate::collisions::PowderSnowSubject {
crate::collisions::PowderSnowSubject {
fall_distance: self.fall_distance,
falling_block: false,
leather_boots: self.leather_boots,
walkable_type: false,
}
}
/// `LivingEntity.tryAddFrost`: the frozen slowdown, on anything but air.
fn try_add_frost(&mut self, on_air: bool) -> Result<()> {
if on_air || self.ticks_frozen <= 0 {
return Ok(());
}
let Some(key) = self.attributes.key("minecraft:movement_speed") else {
return Ok(());
};
let Some(handle) = self
.attributes
.get_instance(Some(key))
.map_err(attribute_error)?
else {
return Ok(());
};
let slow = -0.05f32 * self.percent_frozen();
let modifier = Modifier::new(
"minecraft:powder_snow",
f64::from(slow),
Operation::AddValue,
)?;
self.attributes
.edit(&handle, |value, observer| {
value.add_transient(modifier, observer)
})
.map_err(attribute_error)?;
Ok(())
}
pub fn bounds(&self) -> Aabb {
self.dimensions.bounds(self.position)
}
@@ -463,6 +553,7 @@ impl MotionWorld<'_, '_, '_> {
SceneCollisions {
world: self.scene,
binding: self.collision_binding,
subject: Some(self.player.powder_snow_subject()),
}
}
pub(crate) fn no_player_collision(&mut self, bounds: Aabb) -> Result<bool> {
@@ -517,9 +608,10 @@ impl MotionWorld<'_, '_, '_> {
pub fn travel_in_air(&mut self, input: Vec3) -> Result<()> {
living_air::travel_in_air(self, input)
}
/// Dry, standing movement phases of LivingEntity.aiStep, including server
/// frost-modifier cleanup with zero frozen ticks. Equipment, interpolation,
/// effects and world/entity effects remain unbound. Inputs are the native
/// Dry, standing movement phases of LivingEntity.aiStep, including powder
/// snow's block-inside effects and server freezing (thawing, the frost
/// modifier, freeze damage). Equipment, interpolation, effects and other
/// world/entity effects remain unbound. Inputs are the native
/// float xxa/yya/zza fields, before LivingEntity.applyInput damping.
pub fn movement_tick(&mut self, input: [f32; 3]) -> Result<()> {
self.dry_tick(TickInput::Living(input))
@@ -528,6 +620,10 @@ impl MotionWorld<'_, '_, '_> {
/// caller applies LocalPlayer input preparation once. Empty inventory,
/// equipment and nearby-entity sets are the current scene domain.
pub fn player_movement_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> {
// Entity.baseTick
self.player.was_in_powder_snow = self.player.in_powder_snow;
self.player.in_powder_snow = false;
self.player.old_position = self.player.position;
if self.player.jump_trigger_time > 0 {
self.player.jump_trigger_time -= 1;
}
@@ -739,7 +835,269 @@ impl MotionWorld<'_, '_, '_> {
} else {
self.travel_in_air(input)?;
}
self.player.remove_frost()
if self.player.block_effects {
self.apply_effects_from_blocks()?;
}
// LivingEntity.aiStep "freezing" (server).
if !self.player.in_powder_snow || !self.player.can_freeze() {
self.player.ticks_frozen = (self.player.ticks_frozen - 2).max(0);
}
self.player.remove_frost()?;
let on = self.support(movement_support::LEGACY_SUPPORT_OFFSET)?;
let on_air = self.assets.registry.state(self.block(on)).is_none_or(|s| {
matches!(
s.name.as_str(),
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
)
});
self.player.try_add_frost(on_air)?;
if self.player.health.tick_count % 40 == 0
&& self.player.is_fully_frozen()
&& self.player.can_freeze()
{
self.freeze_damage()?;
}
Ok(())
}
/// `hurtServer(damageSources().freeze(), 1)` for a fully frozen player.
fn freeze_damage(&mut self) -> Result<()> {
let id = self
.resources
.health
.damage
.id("minecraft:freeze")
.ok_or("missing freeze damage type")?;
self.player.events.push(MotionEvent::Health(
crate::health::HealthEvent::FreezeDamage(1.0),
));
let rules = self.scene.health_rules;
self.player.hurt(&self.resources.health, rules, id, 1.0)?;
Ok(())
}
/// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts
/// to inside its movement path: powder snow (`PowderSnowBlock.entityInside`
/// and the FREEZE / EXTINGUISH effects). Pressure plates, tripwires and
/// rails are the world tick's scan.
pub fn apply_effects_from_blocks(&mut self) -> Result<()> {
use horizon_world::entity_move::MovementRecord;
let mut movements: Vec<MovementRecord> =
self.player.history.records().iter().copied().collect();
self.player.history.clear();
let position = self.player.position;
match movements.last() {
None => movements.push(MovementRecord {
from: self.player.old_position,
to: position,
original: None,
}),
Some(last) if last.to.distance_squared(position) > f64::from(9.999_999_4e-11_f32) => {
movements.push(MovementRecord {
from: last.to,
to: position,
original: None,
})
}
_ => {}
}
// isAffectedByBlocks: no physics for spectators.
if self.player.spectator {
return Ok(());
}
let mut visited = std::collections::HashSet::new();
let mut entered = Vec::new();
for movement in &movements {
let mut from = movement.from;
let delta = movement.to.subtract(movement.from);
let mut budget = 16;
match movement.original {
Some(original) if delta.length_squared() > 0.0 => {
for axis in Axis::step_order(original) {
let step = delta.component(axis);
if step != 0.0 {
let to = from.relative(
match axis {
Axis::X => Direction::East,
Axis::Y => Direction::Up,
Axis::Z => Direction::South,
},
step,
);
budget -= self.check_inside_blocks(
from,
to,
&mut visited,
&mut entered,
budget,
)?;
from = to;
}
}
}
_ => {
budget -= self.check_inside_blocks(
movement.from,
movement.to,
&mut visited,
&mut entered,
16,
)?;
}
}
if budget <= 0 {
self.check_inside_blocks(movement.to, movement.to, &mut visited, &mut entered, 1)?;
}
}
// InsideBlockEffectApplier.StepBasedCollector: the blocks entered
// at one step (a sweep iteration differing from the last) form a
// group whose EXTINGUISH callbacks (the game destroys those blocks if
// the player burns), FREEZE and EXTINGUISH apply once, in order.
let mut last_step = -1;
let mut groups = 0;
for (index, &(step, p)) in entered.iter().enumerate() {
if index == 0 || step != last_step {
groups += 1;
last_step = step;
}
if groups == 1 {
// A later group finds the fire already out.
self.player.powder_snow_entered.push(p);
}
}
for _ in 0..groups {
if self.player.health.dead_or_dying() {
break;
}
self.player.in_powder_snow = true;
if self.player.can_freeze() {
self.player.ticks_frozen =
(self.player.ticks_frozen + 1).min(PlayerMotion::TICKS_REQUIRED_TO_FREEZE);
}
}
Ok(())
}
/// `Entity.checkInsideBlocks(from, to, ...)`: the blocks the box at `to`
/// sweeps through from `from`; returns the iterations used plus one.
fn check_inside_blocks(
&mut self,
from: Vec3,
to: Vec3,
visited: &mut std::collections::HashSet<i64>,
entered: &mut Vec<(i32, BlockPos)>,
max_iterations: i32,
) -> Result<i32> {
let deflated = self.player.dimensions.bounds(to).deflate(Vec3::new(
f64::from(1.0e-5_f32),
f64::from(1.0e-5_f32),
f64::from(1.0e-5_f32),
));
let mut hits = Vec::new();
let mut iterations = 0;
let alive = !self.player.health.dead_or_dying();
horizon_core::geometry::sweep_intersected_blocks(
from,
to,
deflated,
1_000_000,
|p, iteration| {
if !alive || iteration >= max_iterations {
return false;
}
iterations = iteration;
hits.push((iteration, p));
true
},
)
.map_err(|e| format!("block sweep: {e:?}"))?;
for (step, p) in hits {
let state = self.block(p);
let Some(definition) = self.assets.registry.state(state) else {
continue;
};
let name = definition.name.as_str();
if matches!(
name,
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
) {
continue;
}
let powder_snow = name == "minecraft:powder_snow";
// getEntityInsideCollisionShape is the whole block but for powder
// snow (its collision shape, the whole block when it is empty),
// filled cauldrons, end portals and tripwires; Horizon doesn't
// follow the player into those last three.
if matches!(
name,
"minecraft:water_cauldron"
| "minecraft:lava_cauldron"
| "minecraft:powder_snow_cauldron"
| "minecraft:end_portal"
| "minecraft:tripwire"
) {
continue;
}
let inside = !powder_snow || {
let context = self.context();
let binding = self.collision_binding;
let shape = binding.collision_shape_with_context(
&mut self.collisions(),
state,
p,
&context,
)?;
shape.is_empty() || shape.boxes() == VoxelShape::block().boxes() || {
let boxes: Vec<_> = shape
.moved(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))
.boxes()
.to_vec();
self.player
.dimensions
.bounds(from)
.collided_along_vector(to.subtract(from), &boxes)
}
};
if inside && visited.insert(p.pack()) {
if powder_snow {
self.powder_snow_inside(p)?;
entered.push((step, p));
}
// ServerPlayer.onInsideBlock
self.player.events.push(MotionEvent::EnterBlock { state });
}
}
Ok(iterations + 1)
}
/// `PowderSnowBlock.entityInside` for the player: stuck while the block
/// at its feet is powder snow, with a snowflake now and then (server).
fn powder_snow_inside(&mut self, p: BlockPos) -> Result<()> {
let feet = BlockPos::containing(self.player.position);
let in_block = self
.assets
.registry
.state(self.block(feet))
.is_some_and(|s| s.name == "minecraft:powder_snow");
if !in_block {
return Ok(());
}
// Entity.makeStuckInBlock
EntityMoveWorld::reset_fall_distance(self)?;
self.player.stuck_multiplier = Vec3::new(f64::from(0.9_f32), 1.5, f64::from(0.9_f32));
// ServerPlayer.getKnownMovement: this tick's movement.
let known = self.player.position.subtract(self.player.old_position);
let random = &mut self.scene.random;
if (known.x != 0.0 || known.z != 0.0) && random.next_boolean() {
// Mth.randomBetween(random, -1, 1) * (1 / 12)
let xa = (random.next_float() * 2.0 - 1.0) * 0.083_333_336_f32;
let za = (random.next_float() * 2.0 - 1.0) * 0.083_333_336_f32;
self.player.events.push(MotionEvent::Snowflake {
position: Vec3::new(
self.player.position.x,
f64::from(p.y + 1),
self.player.position.z,
),
velocity: Vec3::new(f64::from(xa), f64::from(0.05_f32), f64::from(za)),
});
}
Ok(())
}
pub fn jump_from_ground(&mut self) -> Result<()> {
living_motion::jump_from_ground(self)?;
@@ -1032,6 +1390,7 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
let mut collisions = SceneCollisions {
world: self.scene,
binding: self.collision_binding,
subject: Some(self.player.powder_snow_subject()),
};
self.player.ground.set_with_movement(
below,
@@ -1364,10 +1723,10 @@ impl LivingAirWorld for MotionWorld<'_, '_, '_> {
self.player.jumping
}
fn was_in_powder_snow(&self) -> bool {
false
self.player.was_in_powder_snow
}
fn can_walk_powder_snow(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.leather_boots)
}
fn levitation_amplifier(&mut self) -> Result<Option<i32>> {
Ok(self.player.status.levitation)
@@ -1464,6 +1823,68 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> {
mod tests {
use super::*;
#[test]
fn player_fire_damage_queues_hurt_sound_only_for_fresh_hits() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
if !root.join("movement-properties.nbt").exists() {
return;
}
let assets = Assets::load(&root).unwrap();
let resources = MotionResources::load(&root, &assets).unwrap();
for name in ["on_fire", "in_fire", "lava"] {
let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap();
let source = resources
.health
.damage
.id(&format!("minecraft:{name}"))
.unwrap();
assert!(
player
.hurt(&resources.health, Default::default(), source, 1.0)
.unwrap()
);
assert_eq!(
player
.events
.iter()
.filter(|e| matches!(
e,
MotionEvent::HurtSound("minecraft:entity.player.hurt_on_fire")
))
.count(),
1
);
player.events.clear();
assert!(
!player
.hurt(&resources.health, Default::default(), source, 1.0)
.unwrap()
);
assert!(
!player
.events
.iter()
.any(|e| matches!(e, MotionEvent::HurtSound(_)))
);
for _ in 0..20 {
player.health.advance_clock();
}
player.invulnerable = true;
player.events.clear();
assert!(
!player
.hurt(&resources.health, Default::default(), source, 1.0)
.unwrap()
);
assert!(
!player
.events
.iter()
.any(|e| matches!(e, MotionEvent::HurtSound(_)))
);
}
}
/// Footsteps on the prepared vanilla resources, when they are present:
/// none while standing (gravity still moves the player every tick), one
/// per `nextStep` metre while walking.
+208 -5
View File
@@ -387,10 +387,19 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
fs::create_dir_all(out)?;
// Final owner of every overridden file.
let mut files: BTreeMap<String, (usize, Provided)> = BTreeMap::new();
// Every pack's copy of the files vanilla reads as a resource stack.
let mut stacks: BTreeMap<String, Vec<(usize, Provided)>> = BTreeMap::new();
for (i, p) in packs.iter().enumerate() {
// A pack's filter hides what the packs below it provide.
files.retain(|name, _| !p.filter.iter().any(|f| f.blocks(name)));
stacks.retain(|name, _| !p.filter.iter().any(|f| f.blocks(name)));
for (name, provided) in pack_files(p)? {
if merge_kind(&name).is_some() {
stacks
.entry(name.clone())
.or_default()
.push((i, provided.clone()));
}
files.insert(name, (i, provided));
}
}
@@ -413,12 +422,39 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
}
})
.collect();
// Stacked files merge every layer, vanilla's first (unless filtered).
let mut merged: BTreeMap<String, Vec<u8>> = BTreeMap::new();
for (name, stack) in &stacks {
let mut layers = Vec::new();
if !filters.iter().any(|f| f.blocks(name))
&& let Ok(bytes) = fs::read(vanilla.join(name))
{
layers.push(bytes);
}
for (owner, (path, inner)) in stack {
let bytes = match path {
Some(p) => fs::read(p).ok(),
None => zips
.get(*owner)
.and_then(Option::as_ref)
.and_then(|z| z.read(inner).ok()),
};
layers.extend(bytes);
}
if let Some(kind) = merge_kind(name)
&& let Some(bytes) = merge(kind, &layers)
{
merged.insert(name.clone(), bytes);
}
}
#[allow(clippy::too_many_arguments)]
fn mirror(
rel: &str,
vanilla: &Path,
out: &Path,
touched: &BTreeSet<String>,
files: &BTreeMap<String, (usize, Provided)>,
merged: &BTreeMap<String, Vec<u8>>,
filters: &[&Filter],
zips: &[Option<Zip>],
) -> io::Result<()> {
@@ -451,7 +487,9 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
}
for name in names {
let child = format!("{prefix}{name}");
if let Some((owner, (path, inner))) = files.get(&child) {
if let Some(bytes) = merged.get(&child) {
fs::write(out.join(&child), bytes)?;
} else if let Some((owner, (path, inner))) = files.get(&child) {
let target = out.join(&child);
match path {
Some(p) => link(p, &target)?,
@@ -464,7 +502,7 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
} else if touched.contains(&child)
|| (vanilla.join(&child).is_dir() && !filters.is_empty())
{
mirror(&child, vanilla, out, touched, files, filters, zips)?;
mirror(&child, vanilla, out, touched, files, merged, filters, zips)?;
} else if filters.iter().any(|f| f.blocks(&child)) {
// Hidden by a pack's filter.
} else {
@@ -473,7 +511,93 @@ pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<(
}
Ok(())
}
mirror("", vanilla, out, &touched_dirs, &files, &filters, &zips)
mirror(
"",
vanilla,
out,
&touched_dirs,
&files,
&merged,
&filters,
&zips,
)
}
/// Files vanilla loads from every pack in turn (`getResourceStack`) rather
/// than from the top pack only.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Merge {
/// `ClientLanguage.appendFrom`: later packs override keys.
Lang,
/// `SoundManager.Preparations.handleRegistration`: sounds add up unless
/// an event says `replace`.
Sounds,
/// `FontManager.loadResourceStack`: the top pack's providers come first.
Font,
/// `SpriteSourceList.load`: sources from the bottom pack up.
Atlas,
}
fn merge_kind(name: &str) -> Option<Merge> {
let (_, rest) = name.strip_prefix("assets/")?.split_once('/')?;
if rest == "sounds.json" {
return Some(Merge::Sounds);
}
let dir = rest.strip_suffix(".json")?.split_once('/')?.0;
match dir {
"lang" => Some(Merge::Lang),
"font" => Some(Merge::Font),
"atlases" => Some(Merge::Atlas),
_ => None,
}
}
/// One file with the effect of loading `layers` (bottom first) as vanilla
/// does. Layers that do not parse are skipped, as vanilla logs and skips them.
fn merge(kind: Merge, layers: &[Vec<u8>]) -> Option<Vec<u8>> {
use serde_json::{Map, Value};
let parsed: Vec<Map<String, Value>> = layers
.iter()
// SoundManager skips a sounds.json Gson rejects, whole.
.filter(|b| kind != Merge::Sounds || crate::sound_events::is_valid_file(b))
.filter_map(|b| match serde_json::from_slice(b) {
Ok(Value::Object(m)) => Some(m),
_ => None,
})
.collect();
let list = |key: &str, layers: &mut dyn Iterator<Item = &Map<String, Value>>| {
let items: Vec<Value> = layers
.filter_map(|l| l.get(key).and_then(Value::as_array))
.flatten()
.cloned()
.collect();
Value::Object(Map::from_iter([(key.to_owned(), Value::Array(items))]))
};
let out = match kind {
Merge::Lang => Value::Object(parsed.into_iter().flatten().collect()),
Merge::Sounds => {
let mut events = Map::new();
for (event, def) in parsed.into_iter().flatten() {
if !events.contains_key(&event)
|| crate::sound_events::json_bool(&def["replace"], false)
{
let mut fresh = Map::new();
if let Some(subtitle) = def.get("subtitle") {
fresh.insert("subtitle".into(), subtitle.clone());
}
fresh.insert("sounds".into(), Value::Array(Vec::new()));
events.insert(event.clone(), Value::Object(fresh));
}
if let (Some(Value::Array(sounds)), Some(Value::Array(more))) = (
events.get_mut(&event).and_then(|e| e.get_mut("sounds")),
def.get("sounds"),
) {
sounds.extend(more.iter().cloned());
}
}
Value::Object(events)
}
Merge::Font => list("providers", &mut parsed.iter().rev()),
Merge::Atlas => list("sources", &mut parsed.iter()),
};
serde_json::to_vec(&out).ok()
}
/// The packs to apply for an options.txt `resourcePacks` list (bottom first).
pub fn enabled(all: &[Pack], ids: &[String]) -> Vec<Pack> {
@@ -709,6 +833,74 @@ mod tests {
);
}
#[test]
fn stacked_resources_merge_like_vanilla() {
let json = |v: &str| v.as_bytes().to_vec();
let parse = |b: Vec<u8>| serde_json::from_slice::<serde_json::Value>(&b).unwrap();
// ClientLanguage: later packs override keys, the rest stays.
let lang = merge(
Merge::Lang,
&[
json(r#"{"a":"vanilla a","b":"vanilla b"}"#),
json(r#"{"b":"pack b"}"#),
],
);
assert_eq!(
parse(lang.unwrap()),
serde_json::json!({"a":"vanilla a","b":"pack b"})
);
// SoundManager: sounds add up; `replace` starts the event over.
let sounds = merge(
Merge::Sounds,
&[
json(r#"{"x":{"subtitle":"s.x","sounds":["v1"]},"y":{"sounds":["v2"]}}"#),
json(
r#"{"x":{"sounds":["p1"]},"y":{"replace":true,"subtitle":"s.y","sounds":["p2"]}}"#,
),
b"not json".to_vec(),
],
);
assert_eq!(
parse(sounds.unwrap()),
serde_json::json!({
"x":{"subtitle":"s.x","sounds":["v1","p1"]},
"y":{"subtitle":"s.y","sounds":["p2"]}
})
);
// FontManager: the top pack's providers come first.
let font = merge(
Merge::Font,
&[json(r#"{"providers":[1,2]}"#), json(r#"{"providers":[3]}"#)],
);
assert_eq!(
parse(font.unwrap()),
serde_json::json!({"providers":[3,1,2]})
);
// SpriteSourceList: sources from the bottom pack up.
let atlas = merge(
Merge::Atlas,
&[json(r#"{"sources":[1]}"#), json(r#"{"sources":[2]}"#)],
);
assert_eq!(parse(atlas.unwrap()), serde_json::json!({"sources":[1,2]}));
assert_eq!(
merge_kind("assets/minecraft/lang/en_us.json"),
Some(Merge::Lang)
);
assert_eq!(
merge_kind("assets/minecraft/sounds.json"),
Some(Merge::Sounds)
);
assert_eq!(
merge_kind("assets/minecraft/font/default.json"),
Some(Merge::Font)
);
assert_eq!(merge_kind("assets/minecraft/font/unifont.zip"), None);
assert_eq!(
merge_kind("assets/minecraft/atlases/blocks.json"),
Some(Merge::Atlas)
);
assert_eq!(merge_kind("assets/minecraft/models/block/stone.json"), None);
}
#[test]
fn overlay_layers_packs_over_vanilla() {
let base = std::env::temp_dir().join(format!("horizon-packs-{}", std::process::id()));
let _ = fs::remove_dir_all(&base);
@@ -725,7 +917,11 @@ mod tests {
b"vanilla dirt",
)
.unwrap();
fs::write(vanilla.join("assets/minecraft/lang/en_us.json"), b"{}").unwrap();
fs::write(
vanilla.join("assets/minecraft/lang/en_us.json"),
br#"{"a":"vanilla","b":"vanilla"}"#,
)
.unwrap();
fs::write(vanilla.join("facts.json"), b"[]").unwrap();
let pack_dir = base.join("packs/Mine");
fs::create_dir_all(pack_dir.join("assets/minecraft/textures/block")).unwrap();
@@ -739,6 +935,12 @@ mod tests {
b"pack",
)
.unwrap();
fs::create_dir_all(pack_dir.join("assets/minecraft/lang")).unwrap();
fs::write(
pack_dir.join("assets/minecraft/lang/en_us.json"),
br#"{"b":"pack"}"#,
)
.unwrap();
let packs = discover(&vanilla, &base.join("packs"));
assert_eq!(packs.len(), 1);
assert_eq!(packs[0].id, "file/Mine");
@@ -752,9 +954,10 @@ mod tests {
fs::read(out.join("assets/minecraft/textures/block/dirt.png")).unwrap(),
b"vanilla dirt"
);
// A pack's language file adds to vanilla's instead of replacing it.
assert_eq!(
fs::read(out.join("assets/minecraft/lang/en_us.json")).unwrap(),
b"{}"
br#"{"a":"vanilla","b":"pack"}"#
);
assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]");
let _ = fs::remove_dir_all(base);
+260 -82
View File
@@ -14,7 +14,7 @@ use crate::{
};
use glam::{DVec3, Quat, Vec3 as FVec3};
use horizon_core::{
geometry::{Aabb, Axis, Vec3},
geometry::{Aabb, Axis, Vec3, trig},
random::{LegacyRandom, RandomSource},
};
use horizon_world::block_collision::BlockCollisionRegistry;
@@ -406,6 +406,8 @@ pub struct Particle {
no_render: bool,
/// Ticked once when created (`CritParticle` constructor).
pre_tick: bool,
/// `Particle.random`: the particle's own generator (`RandomSource.create()`).
random: LegacyRandom,
}
fn aabb_at(p: [f64; 3], w: f32, h: f32) -> Aabb {
let w = f64::from(w) / 2.0;
@@ -475,9 +477,14 @@ pub fn destroy_positions(
impl Particle {
/// `Particle(level, x, y, z)` + `SingleQuadParticle` (no initial velocity).
fn at(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3]) -> Self {
let mut particle = Self::base_at(random, ty, p);
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
/// `Particle(level, x, y, z)` without `SingleQuadParticle` (`NoRenderParticle`).
fn base_at(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3]) -> Self {
let mut particle = Self::blank(ty, p);
particle.lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as i32;
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
fn blank(ty: ParticleType, p: [f64; 3]) -> Self {
@@ -511,10 +518,17 @@ impl Particle {
behaviour: Behaviour::Base,
no_render: false,
pre_tick: false,
random: LegacyRandom::new(0),
}
}
/// `Particle(level, x, y, z, xa, ya, za)`: jittered, normalized initial velocity.
fn moving(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3], v: [f64; 3]) -> Self {
let mut particle = Self::base_moving(random, ty, p, v);
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
/// `Particle(level, x, y, z, xa, ya, za)` without `SingleQuadParticle`.
fn base_moving(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3], v: [f64; 3]) -> Self {
let lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as i32;
let mut d = [
v[0] + f64::from((random.next_float() * 2.0 - 1.0) * 0.4),
@@ -532,7 +546,6 @@ impl Particle {
let mut particle = Self::blank(ty, p);
particle.lifetime = lifetime;
particle.velocity = d;
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
/// `TerrainParticle(level, x, y, z, xa, ya, za, state)`: a crumb from a
@@ -556,6 +569,19 @@ impl Particle {
p.uv = [(uo + 1.0) / 4.0, vo / 4.0, uo / 4.0, (vo + 1.0) / 4.0];
p
}
/// What `CritParticle`'s providers do once its constructor has ticked it.
fn after_constructor_tick(&mut self) {
match self.ty {
// MagicProvider.
ParticleType::EnchantedHit => {
self.rgba[0] *= 0.3;
self.rgba[1] *= 0.8;
}
// DamageIndicatorProvider.
ParticleType::DamageIndicator => self.lifetime = 20,
_ => {}
}
}
/// `Particle.setPower`.
pub fn set_power(&mut self, power: f32) {
let power = f64::from(power);
@@ -653,6 +679,21 @@ impl Particle {
self.velocity[2] *= f64::from(0.7f32);
}
}
/// `getLightCoords(a)` from the world's smooth sky and block light (0..=240).
fn light_coords(&self, partial: f32, sky: u32, block: u32) -> (u32, u32) {
let t = ((self.age as f32 + partial) / self.lifetime as f32).clamp(0.0, 1.0);
match self.light {
Light::World => (sky, block),
Light::FullBright => (240, 240),
Light::Block15 => (sky, 240),
Light::AgeEmission => (sky, (block + (t * 240.0) as u32).min(240)),
Light::AgeEmission4 => {
let b = self.age as f32 / self.lifetime as f32;
let b = (b * b) * (b * b);
(sky, (block + (b.clamp(0.0, 1.0) * 240.0) as u32).min(240))
}
}
}
fn quad_size(&self, a: f32) -> f32 {
let t = (self.age as f32 + a) / self.lifetime as f32;
match self.size_curve {
@@ -672,6 +713,34 @@ impl Particle {
}
}
/// A particle's fields as the parity probe reports them.
#[derive(Clone, Debug)]
pub struct ParticleSnapshot {
pub age: i32,
pub lifetime: i32,
pub removed: bool,
pub on_ground: bool,
pub position: [f64; 3],
pub velocity: [f64; 3],
pub previous: [f64; 3],
/// `SingleQuadParticle` state; `None` for `NoRenderParticle`s.
pub quad: Option<QuadSnapshot>,
}
/// `SingleQuadParticle` state at a render.
#[derive(Clone, Debug)]
pub struct QuadSnapshot {
/// `getQuadSize` at partial ticks 0 and 0.5.
pub size: [f32; 2],
pub rgba: [f32; 4],
/// `roll`, `oRoll`.
pub roll: [f32; 2],
pub sprite: String,
/// `getU0`, `getU1`, `getV0`, `getV1` within the sprite.
pub uv: [f32; 4],
/// `getLightCoords(0.5)` over full sky light and no block light.
pub light: u32,
}
/// World access for particle physics.
pub struct ParticleLevel<'a> {
pub world: &'a World,
@@ -685,6 +754,7 @@ impl ParticleLevel<'_> {
let mut scene = SceneCollisions {
world: self.world,
binding: self.collision,
subject: None,
};
match scene.resolve(bb, Vec3::new(d[0], d[1], d[2]), 0.0, false) {
Ok(v) => [v.x, v.y, v.z],
@@ -733,7 +803,17 @@ impl ParticleLevel<'_> {
pub struct ParticleEngine {
particles: Vec<Particle>,
pending: Vec<Particle>,
/// `ParticleEngine.random`, handed to every `ParticleProvider`.
random: LegacyRandom,
/// `ClientLevel.random` as particle constructors use it (`level.getRandom()`).
level_random: LegacyRandom,
/// `SpellParticle.RANDOM`.
spell_random: LegacyRandom,
/// Seeds for each particle's own random (`RandomSource.create()`).
seeds: LegacyRandom,
/// When set, particles ask the level for other particles here instead
/// (type, position, velocity), as the parity probe's stand-in level does.
pub requested: Option<Vec<(ParticleOptions, [f64; 3], [f64; 3])>>,
names: Vec<String>,
rects: Vec<Option<Rect>>,
atlas: HashMap<String, Rect>,
@@ -756,6 +836,10 @@ impl ParticleEngine {
particles: Vec::new(),
pending: Vec::new(),
random: LegacyRandom::new(0x7061_7274),
level_random: LegacyRandom::new(0x6c65_7665),
spell_random: LegacyRandom::new(0x7370_656c),
seeds: LegacyRandom::new(0x7365_6564),
requested: None,
names: Vec::new(),
rects: Vec::new(),
atlas: atlas.clone(),
@@ -846,6 +930,10 @@ impl ParticleEngine {
pub fn add(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) {
let c = self.camera;
let d2 = (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2);
if let Some(requested) = &mut self.requested {
requested.push((options.clone(), p, v));
return;
}
if !options.ty.override_limiter() && d2 > 1024.0 {
return;
}
@@ -981,10 +1069,76 @@ impl ParticleEngine {
}
/// `ParticleEngine.createParticle`: always spawned.
pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) {
if let Some(particle) = self.make(options, p, v) {
let seed = self.seeds.next_long();
if let Some(particle) = self.make(options, p, v, seed) {
self.pending.push(particle);
}
}
/// Parity probes: seed the provider (`ParticleEngine.random`), level and
/// `SpellParticle.RANDOM` generators.
pub fn seed_randoms(&mut self, provider: i64, level: i64, spell: i64) {
self.random = LegacyRandom::new(provider);
self.level_random = LegacyRandom::new(level);
self.spell_random = LegacyRandom::new(spell);
}
/// Parity probes: the next long of the provider, level and spell generators.
pub fn next_randoms(&mut self) -> [i64; 3] {
[
self.random.next_long(),
self.level_random.next_long(),
self.spell_random.next_long(),
]
}
/// Parity probes: `ParticleProvider.createParticle` with the particle's own
/// random seeded `seed`, ticked in its constructor where vanilla does.
pub fn probe_create(
&mut self,
options: &ParticleOptions,
p: [f64; 3],
v: [f64; 3],
seed: i64,
level: &ParticleLevel,
) -> Option<Particle> {
let mut particle = self.make(options, p, v, seed)?;
if particle.pre_tick {
particle.pre_tick = false;
self.tick_particle(&mut particle, level);
particle.after_constructor_tick();
}
Some(particle)
}
/// Parity probes: `Particle.tick`.
pub fn probe_tick(&mut self, particle: &mut Particle, level: &ParticleLevel) {
self.tick_particle(particle, level);
}
/// Parity probes: the state vanilla's particle fields hold.
pub fn snapshot(&self, p: &Particle) -> ParticleSnapshot {
let sprite = match &p.sprite {
Sprite::Index(i) => self.names.get(*i as usize).map_or_else(
|| "-".to_owned(),
|n| n.strip_prefix("particle/").unwrap_or(n).to_owned(),
),
Sprite::Named(n) => n.clone(),
};
let (sky, block) = p.light_coords(0.5, 240, 0);
ParticleSnapshot {
age: p.age,
lifetime: p.lifetime,
removed: p.removed,
on_ground: p.on_ground,
position: p.position,
velocity: p.velocity,
previous: p.previous,
quad: (!p.no_render).then(|| QuadSnapshot {
size: [p.quad_size(0.0), p.quad_size(0.5)],
rgba: p.rgba,
roll: [p.roll, p.o_roll],
sprite,
uv: [p.uv[0], p.uv[2], p.uv[1], p.uv[3]],
light: block | sky << 16,
}),
}
}
/// `SpriteSet.get(random)`.
fn sprite_from_set(&mut self, ty: ParticleType) -> Sprite {
match self.sets.get(&ty) {
@@ -1022,28 +1176,38 @@ impl ParticleEngine {
}
}
#[allow(clippy::too_many_lines)]
fn make(&mut self, o: &ParticleOptions, p: [f64; 3], v: [f64; 3]) -> Option<Particle> {
/// `ParticleProvider.createParticle`: provider draws use the engine's
/// random, constructor and tick draws the particle's own (seeded `seed`).
fn make(
&mut self,
o: &ParticleOptions,
p: [f64; 3],
v: [f64; 3],
seed: i64,
) -> Option<Particle> {
use ParticleType as T;
let ty = o.ty;
let set = self.set_of(ty);
let r = &mut self.random;
let mut local = LegacyRandom::new(seed);
let r = &mut local;
let mut particle = match ty {
T::Block | T::BlockCrumble | T::DustPillar => {
let (sprite, tint) = o.block.clone()?;
let mut q = Particle::terrain(r, p, v, sprite, tint);
q.ty = ty;
let pr = &mut self.random;
if ty == T::BlockCrumble {
q.velocity = [0.0; 3];
q.lifetime = r.next_int_bound(10).unwrap_or(0) + 1;
q.lifetime = pr.next_int_bound(10).unwrap_or(0) + 1;
} else if ty == T::DustPillar {
q.velocity = [
r.next_gaussian() / 30.0,
v[1] + r.next_gaussian() / 2.0,
r.next_gaussian() / 30.0,
pr.next_gaussian() / 30.0,
v[1] + pr.next_gaussian() / 2.0,
pr.next_gaussian() / 30.0,
];
q.lifetime = r.next_int_bound(20).unwrap_or(0) + 20;
q.lifetime = pr.next_int_bound(20).unwrap_or(0) + 20;
}
return Some(q);
q
}
T::FallingDust => {
let (_, tint) = o.block.clone()?;
@@ -1070,13 +1234,17 @@ impl ParticleEngine {
T::LargeSmoke => ([0.1, 0.1, 0.1], 2.5, 0.3, 8, -0.1, true, v),
T::Ash => ([0.1, -0.1, 0.1], 1.0, 0.5, 20, 0.1, false, [0.0; 3]),
_ => {
let xa = f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1;
let ya = f64::from(r.next_float())
// WhiteAshParticle.Provider draws the motion.
let pr = &mut self.random;
let xa =
f64::from(pr.next_float()) * -1.9 * f64::from(pr.next_float()) * 0.1;
let ya = f64::from(pr.next_float())
* -0.5
* f64::from(r.next_float())
* f64::from(pr.next_float())
* 0.1
* 5.0;
let za = f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1;
let za =
f64::from(pr.next_float()) * -1.9 * f64::from(pr.next_float()) * 0.1;
([0.1, -0.1, 0.1], 1.0, 0.0, 20, 0.0125, false, [xa, ya, za])
}
};
@@ -1169,7 +1337,10 @@ impl ParticleEngine {
| T::FallingDripstoneWater
| T::DrippingDripstoneLava
| T::FallingDripstoneLava => {
// The provider picks the sprite first (`sprite.get(random)`).
let sprite = self.sprite_from_set(ty);
let mut q = Particle::at(r, ty, p);
q.sprite = sprite;
q.set_size(0.01, 0.01);
q.gravity = 0.06;
let water = [0.2, 0.3, 1.0];
@@ -1305,14 +1476,18 @@ impl ParticleEngine {
q.gravity *= 0.01;
q.lifetime = 100;
}
// Lifetimes the providers draw from their own random.
T::LandingHoney => {
q.lifetime = (128.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32
q.lifetime =
(128.0 / (f64::from(self.random.next_float()) * 0.8 + 0.2)) as i32
}
T::LandingObsidianTear => {
q.lifetime = (28.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32
q.lifetime =
(28.0 / (f64::from(self.random.next_float()) * 0.8 + 0.2)) as i32
}
T::FallingNectar => {
q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32;
q.lifetime =
(16.0 / (f64::from(self.random.next_float()) * 0.8 + 0.2)) as i32;
q.gravity = 0.007;
}
T::FallingSporeBlossom => {
@@ -1396,26 +1571,29 @@ impl ParticleEngine {
q
}
T::Underwater | T::CrimsonSpore | T::WarpedSpore | T::SporeBlossomAir => {
// SuspendedParticle; the providers draw motion, then the sprite.
let below = [p[0], p[1] - 0.125, p[2]];
let pr = &mut self.random;
let vel = match ty {
T::CrimsonSpore => [
pr.next_gaussian() * f64::from(1.0e-6f32),
pr.next_gaussian() * f64::from(1.0e-4f32),
pr.next_gaussian() * f64::from(1.0e-6f32),
],
T::WarpedSpore => [
0.0,
f64::from(pr.next_float()) * -1.9 * f64::from(pr.next_float()) * 0.1,
0.0,
],
_ => [0.0, f64::from(-0.8f32), 0.0],
};
let sprite = self.sprite_from_set(ty);
let mut q = if ty == T::Underwater {
let mut q = Particle::at(r, ty, below);
q.set_size(0.01, 0.01);
q.size *= r.next_float() * 0.6 + 0.2;
q
} else {
let vel = match ty {
T::CrimsonSpore => [
r.next_gaussian() * 1.0e-6,
r.next_gaussian() * 1.0e-4,
r.next_gaussian() * 1.0e-6,
],
T::WarpedSpore => [
0.0,
f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1,
0.0,
],
_ => [0.0, f64::from(-0.8f32), 0.0],
};
let mut q = Particle::moving(r, ty, below, vel);
q.set_size(0.01, 0.01);
q.size *= r.next_float() * 0.6 + 0.6;
@@ -1433,11 +1611,12 @@ impl ParticleEngine {
q.set_size(0.001, 0.001);
}
_ => {
q.lifetime = r.next_int_bound(501).unwrap_or(0) + 500;
q.lifetime = self.random.next_int_bound(501).unwrap_or(0) + 500;
q.gravity = 0.01;
q.set_color(0.32, 0.5, 0.22);
}
}
q.sprite = sprite;
q
}
T::Portal | T::ReversePortal => {
@@ -1532,7 +1711,10 @@ impl ParticleEngine {
q
}
T::HappyVillager | T::Composter | T::Mycelium | T::Dolphin | T::EggCrack => {
// SuspendedTownParticle; the provider picks the sprite first.
let sprite = self.sprite_from_set(ty);
let mut q = Particle::moving(r, ty, p, v);
q.sprite = sprite;
let br = r.next_float() * 0.1 + 0.2;
q.set_color(br, br, br);
q.set_size(0.02, 0.02);
@@ -1547,11 +1729,11 @@ impl ParticleEngine {
T::HappyVillager | T::EggCrack => q.set_color(1.0, 1.0, 1.0),
T::Composter => {
q.set_color(1.0, 1.0, 1.0);
q.lifetime = 3 + r.next_int_bound(5).unwrap_or(0);
q.lifetime = 3 + self.level_random.next_int_bound(5).unwrap_or(0);
}
T::Dolphin => {
q.set_color(0.3, 0.5, 1.0);
q.rgba[3] = 1.0 - r.next_float() * 0.7;
q.rgba[3] = 1.0 - self.random.next_float() * 0.7;
q.lifetime /= 2;
}
_ => {}
@@ -1606,7 +1788,7 @@ impl ParticleEngine {
q
}
T::ExplosionEmitter => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
let mut q = Particle::base_moving(r, ty, p, [0.0; 3]);
q.lifetime = 8;
q.no_render = true;
q.behaviour = Behaviour::ExplosionSeed;
@@ -1615,8 +1797,7 @@ impl ParticleEngine {
// GustParticle: a still, bright, opaque quad that animates over
// its 12 to 15 ticks; the small one is scaled to 15%.
T::Gust | T::SmallGust => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
q.velocity = [0.0; 3];
let mut q = Particle::at(r, ty, p);
q.lifetime = 12 + r.next_int_bound(4).unwrap_or(0);
q.size = 1.0;
q.set_size(1.0, 1.0);
@@ -1629,7 +1810,7 @@ impl ParticleEngine {
q
}
T::GustEmitterLarge | T::GustEmitterSmall => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
let mut q = Particle::base_moving(r, ty, p, [0.0; 3]);
let (scale, lifetime, delay) = if ty == T::GustEmitterLarge {
(3.0, 7, 0)
} else {
@@ -1669,13 +1850,13 @@ impl ParticleEngine {
}
q.velocity[1] += 0.2;
let color = v[0] as f32;
// `Mth.sin` (the quantized table) of a float angle.
let channel = |offset: f32| {
((color + offset) * std::f32::consts::TAU)
.sin()
.mul_add(0.65, 0.35)
(trig::sin(f64::from((color + offset) * std::f64::consts::TAU as f32)) * 0.65
+ 0.35)
.max(0.0)
};
q.set_color(channel(0.0), channel(1.0 / 3.0), channel(2.0 / 3.0));
q.set_color(channel(0.0), channel(0.333_333_34), channel(0.666_666_7));
q.size *= 1.5;
q.lifetime = 6;
q.size_curve = Size::GrowIn;
@@ -1721,9 +1902,9 @@ impl ParticleEngine {
if ty == T::SculkCharge {
q.roll = o.scale;
q.o_roll = o.scale;
q.lifetime = r.next_int_bound(12).unwrap_or(0) + 8;
q.lifetime = self.random.next_int_bound(12).unwrap_or(0) + 8;
} else {
q.lifetime = r.next_int_bound(4).unwrap_or(0) + 6;
q.lifetime = self.random.next_int_bound(4).unwrap_or(0) + 6;
}
q
}
@@ -1741,7 +1922,6 @@ impl ParticleEngine {
q.behaviour = Behaviour::Shriek {
delay: o.scale as i32,
};
q.set = set;
q
}
T::Dust => {
@@ -1776,6 +1956,7 @@ impl ParticleEngine {
q.size *= 0.75;
q.lifetime = 48 + r.next_int_bound(12).unwrap_or(0);
q.rgba[3] = 0.99;
q.light = Light::FullBright;
q.behaviour = Behaviour::Spark {
fade: None,
trail: false,
@@ -1861,9 +2042,9 @@ impl ParticleEngine {
q
}
T::Effect | T::InstantEffect | T::EntityEffect | T::Witch | T::Infested => {
// SpellParticle: x/z velocity from a shared random, y from the option.
let xa = 0.5 - r.next_double();
let za = 0.5 - r.next_double();
// SpellParticle: x/z velocity from `SpellParticle.RANDOM`, y from the option.
let xa = 0.5 - self.spell_random.next_double();
let za = 0.5 - self.spell_random.next_double();
let mut q = Particle::moving(r, ty, p, [xa, v[1], za]);
q.friction = 0.96;
q.gravity = -0.1;
@@ -1878,7 +2059,7 @@ impl ParticleEngine {
q.has_physics = false;
match ty {
T::Witch => {
let b = r.next_float() * 0.5 + 0.35;
let b = self.random.next_float() * 0.5 + 0.35;
q.set_color(b, 0.0, b);
}
T::EntityEffect => {
@@ -1938,13 +2119,17 @@ impl ParticleEngine {
}
T::Trail => {
let (target, duration) = o.trail?;
let mut q = Particle::at(r, ty, p);
let mut q = Particle::moving(r, ty, p, v);
let jitter = |r: &mut LegacyRandom| 0.875 + r.next_float() * 0.25;
let (jr, jg, jb) = (jitter(r), jitter(r), jitter(r));
// `ARGB.scaleRGB` on the 8-bit channels.
let scaled = |c: f32, s: f32| {
((((c * 255.0).round() as i32) as f32 * s) as i32).clamp(0, 255) as f32 / 255.0
};
q.set_color(
(o.color[0] * jr).min(1.0),
(o.color[1] * jg).min(1.0),
(o.color[2] * jb).min(1.0),
scaled(o.color[0], jr),
scaled(o.color[1], jg),
scaled(o.color[2], jb),
);
q.size = 0.26;
q.lifetime = duration;
@@ -1961,6 +2146,7 @@ impl ParticleEngine {
} else if matches!(particle.sprite, Sprite::Index(u32::MAX)) {
particle.sprite = self.sprite_from_set(ty);
}
particle.random = local;
Some(particle)
}
@@ -1976,13 +2162,16 @@ impl ParticleEngine {
trail: bool,
twinkle: bool,
) -> Particle {
let mut q = Particle::at(&mut self.random, ParticleType::Firework, at);
let mut local = LegacyRandom::new(self.seeds.next_long());
let mut q = Particle::at(&mut local, ParticleType::Firework, at);
q.velocity = v;
q.gravity = 0.1;
q.friction = 0.91;
q.size *= 0.75;
q.lifetime = 48 + self.random.next_int_bound(12).unwrap_or(0);
q.lifetime = 48 + local.next_int_bound(12).unwrap_or(0);
q.random = local;
q.rgba = [rgba[0], rgba[1], rgba[2], 0.99];
q.light = Light::FullBright;
q.behaviour = Behaviour::Spark {
fade,
trail,
@@ -2180,6 +2369,7 @@ impl ParticleEngine {
if p.pre_tick {
p.pre_tick = false;
self.tick_particle(&mut p, level);
p.after_constructor_tick();
}
// ParticleGroup.add: the last quarter fills with decreasing probability.
let size = self.particles.len();
@@ -2214,7 +2404,7 @@ impl ParticleEngine {
p.base_tick(level);
if !p.removed {
let odds = p.age as f32 / p.lifetime as f32;
if self.random.next_float() > odds {
if p.random.next_float() > odds {
self.add(
&ParticleOptions::simple(ParticleType::Smoke),
p.position,
@@ -2270,7 +2460,7 @@ impl ParticleEngine {
self.add(&ParticleOptions::simple(next), p.position, [0.0; 3]);
}
if let Some(sound) = sound {
let volume = self.random.next_float() * 0.7 + 0.3;
let volume = p.random.next_float() * 0.7 + 0.3;
self.sounds.push((sound, p.position, volume, 1.0));
}
}
@@ -2304,7 +2494,7 @@ impl ParticleEngine {
*c *= f64::from(0.98f32);
}
if p.on_ground {
if self.random.next_float() < 0.5 {
if p.random.next_float() < 0.5 {
p.removed = true;
}
p.velocity[0] *= f64::from(0.7f32);
@@ -2447,7 +2637,6 @@ impl ParticleEngine {
p.behaviour = Behaviour::Shriek { delay: delay - 1 };
} else {
p.base_tick(level);
self.sprite_from_age(p);
}
}
Behaviour::Vibration {
@@ -2489,9 +2678,10 @@ impl ParticleEngine {
p.removed = true;
return;
}
let alpha = 1.0 / f64::from((p.lifetime - p.age).max(1));
// `Mth.lerp(1.0 / ticksRemaining, x, target)`, infinite on the last tick.
let alpha = 1.0 / f64::from(p.lifetime - p.age);
for i in 0..3 {
p.position[i] += (target[i] - p.position[i]) * alpha;
p.position[i] += alpha * (target[i] - p.position[i]);
}
}
Behaviour::HugeExplosion => {
@@ -2507,7 +2697,7 @@ impl ParticleEngine {
Behaviour::GustSeed { scale, delay } => {
if p.age % (delay + 1) == 0 {
for _ in 0..3 {
let r = &mut self.random;
let r = &mut p.random;
let at = [
p.position[0] + (r.next_double() - r.next_double()) * scale,
p.position[1] + (r.next_double() - r.next_double()) * scale,
@@ -2529,7 +2719,7 @@ impl ParticleEngine {
}
Behaviour::ExplosionSeed => {
for _ in 0..6 {
let r = &mut self.random;
let r = &mut p.random;
let at = [
p.position[0] + (r.next_double() - r.next_double()) * 4.0,
p.position[1] + (r.next_double() - r.next_double()) * 4.0,
@@ -2552,7 +2742,7 @@ impl ParticleEngine {
let age = p.age;
p.age += 1;
if age < p.lifetime && p.rgba[3] > 0.0 {
let r = &mut self.random;
let r = &mut p.random;
let dx = r.next_float() / 5000.0 * if r.next_boolean() { 1.0 } else { -1.0 };
p.velocity[0] += f64::from(dx);
let dz = r.next_float() / 5000.0 * if r.next_boolean() { 1.0 } else { -1.0 };
@@ -2828,23 +3018,11 @@ impl ParticleEngine {
}
let block = ParticleLevel::block_at(p.position);
let packed = light_at(block);
let (sky, mut block_light) = (u32::from(packed >> 4) * 16, u32::from(packed & 15) * 16);
let mut sky_light = sky;
let t = ((p.age as f32 + partial) / p.lifetime as f32).clamp(0.0, 1.0);
match p.light {
Light::World => {}
Light::FullBright => {
block_light = 240;
sky_light = 240;
}
Light::Block15 => block_light = 240,
Light::AgeEmission => block_light = (block_light + (t * 240.0) as u32).min(240),
Light::AgeEmission4 => {
let b = p.age as f32 / p.lifetime as f32;
let b = (b * b) * (b * b);
block_light = (block_light + (b.clamp(0.0, 1.0) * 240.0) as u32).min(240);
}
}
let (sky_light, block_light) = p.light_coords(
partial,
u32::from(packed >> 4) * 16,
u32::from(packed & 15) * 16,
);
let light = sky_light | block_light << 8;
let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0) as u32;
let color = c(alpha) << 24 | c(rgb[2]) << 16 | c(rgb[1]) << 8 | c(rgb[0]);
+38 -22
View File
@@ -106,6 +106,42 @@ pub struct WeighedSoundEvents {
/// The subtitle translation key.
pub subtitle: Option<String>,
}
/// A `sounds.json` entry: event, `replace`, subtitle and sounds.
type Registration = (String, bool, Option<String>, Vec<Sound>);
/// Parse a `sounds.json`; `None` when Gson would reject the whole file (a
/// malformed entry anywhere in it).
fn parse_file(namespace: &str, text: &[u8]) -> Option<Vec<Registration>> {
let Ok(Value::Object(map)) = serde_json::from_slice::<Value>(text) else {
return None;
};
let mut parsed = Vec::new();
for (name, def) in &map {
let Value::Object(object) = def else {
return None;
};
let replace = json_bool(object.get("replace").unwrap_or(&Value::Null), false);
let subtitle = match object.get("subtitle") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(s.clone()),
Some(_) => return None,
};
let mut sounds = Vec::new();
if let Some(list) = object.get("sounds") {
let Value::Array(list) = list else {
return None;
};
for s in list {
sounds.push(parse_sound(s)?);
}
}
parsed.push((format!("{namespace}:{name}"), replace, subtitle, sounds));
}
Some(parsed)
}
/// Whether vanilla's `SoundManager` reads this `sounds.json` at all.
pub fn is_valid_file(text: &[u8]) -> bool {
parse_file("minecraft", text).is_some()
}
/// The sound event registry (`SoundManager.registry`).
#[derive(Clone, Debug, Default)]
pub struct SoundRegistry {
@@ -148,7 +184,7 @@ fn json_int(v: &Value, fallback: i32) -> i32 {
_ => fallback,
}
}
fn json_bool(v: &Value, fallback: bool) -> bool {
pub(crate) fn json_bool(v: &Value, fallback: bool) -> bool {
match v {
Value::Bool(b) => *b,
Value::String(s) => s == "true",
@@ -213,29 +249,9 @@ impl SoundRegistry {
/// One `sounds.json` (`Preparations.handleRegistration` for each entry).
/// `exists(namespace, path)` says whether a sound file is present.
pub fn add_file(&mut self, namespace: &str, text: &[u8], exists: &dyn Fn(&str, &str) -> bool) {
let Ok(Value::Object(map)) = serde_json::from_slice::<Value>(text) else {
let Some(parsed) = parse_file(namespace, text) else {
return;
};
// A malformed entry makes Gson reject the whole file.
let mut parsed = Vec::new();
for (name, def) in &map {
let Value::Object(object) = def else { return };
let replace = json_bool(object.get("replace").unwrap_or(&Value::Null), false);
let subtitle = match object.get("subtitle") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(s.clone()),
Some(_) => return,
};
let mut sounds = Vec::new();
if let Some(list) = object.get("sounds") {
let Value::Array(list) = list else { return };
for s in list {
let Some(sound) = parse_sound(s) else { return };
sounds.push(sound);
}
}
parsed.push((format!("{namespace}:{name}"), replace, subtitle, sounds));
}
for (location, replace, subtitle, sounds) in parsed {
let entry = match self.events.get_mut(&location) {
Some(entry) if !replace => entry,
+101 -15
View File
@@ -21,11 +21,11 @@ impl SpriteAnimation {
}
pub fn resized_pixels(&self, frame: usize, width: u32, height: u32) -> Vec<u8> {
let source = self.pixels(frame);
let side = (source.len() / 4).isqrt() as u32;
let mut out = Vec::with_capacity((width * height * 4) as usize);
for y in 0..height {
for x in 0..width {
let offset = ((y * SPRITE_SIZE / height * SPRITE_SIZE + x * SPRITE_SIZE / width)
* 4) as usize;
let offset = ((y * side / height * side + x * side / width) * 4) as usize;
out.extend_from_slice(&source[offset..offset + 4]);
}
}
@@ -38,22 +38,96 @@ impl SpriteAnimation {
#[derive(Default)]
pub struct Sprites {
/// Edge length of every array layer and the layers' current frames, set
/// by [`Sprites::finish`].
pub size: u32,
pub pixels: Vec<u8>,
pub layers: BTreeMap<String, u32>,
pub animations: Vec<SpriteAnimation>,
pub opaque: Vec<bool>,
pub translucent: Vec<bool>,
/// Each layer's frames at the texture's own resolution (square), and the
/// frame shown first.
native: Vec<(u32, Arc<Vec<Vec<u8>>>, usize)>,
}
/// Edge length of vanilla's block textures: the smallest array layer.
pub const SPRITE_SIZE: u32 = 16;
/// Largest sprite array (all layers of the top mip level): resource packs
/// with bigger textures are sampled down to fit.
const MAX_ARRAY_BYTES: u64 = 256 << 20;
/// Nearest-resample a square RGBA frame to another square size.
fn resample(frame: &[u8], from: u32, to: u32) -> Vec<u8> {
if from == to {
return frame.to_vec();
}
let mut out = Vec::with_capacity((to * to * 4) as usize);
for row in 0..to {
let source_row = row * from / to;
for column in 0..to {
let offset = ((source_row * from + column * from / to) * 4) as usize;
out.extend_from_slice(&frame[offset..offset + 4]);
}
}
out
}
/// Edge length of every sprite array layer.
// Flow sprites are 32 square: each fluid face samples a 16-texel subregion.
// shortcut: HD frames above 32 are resampled; use variable-resolution storage for HD-pack parity.
pub const SPRITE_SIZE: u32 = 32;
impl Sprites {
/// Lay every layer out at one size: the largest texture's (resource packs
/// may ship 32x, 64x... textures, like vanilla's stitched atlas), rounded
/// up to a power of two and limited to [`MAX_ARRAY_BYTES`]. Smaller
/// textures are scaled up by whole pixels, so UVs stay per layer.
pub fn finish(&mut self) {
let layers = self.native.len().max(1) as u64;
let largest = self.native.iter().map(|n| n.0).max().unwrap_or(SPRITE_SIZE);
let mut size = largest.max(SPRITE_SIZE).next_power_of_two();
while size > SPRITE_SIZE && layers * u64::from(size * size) * 4 > MAX_ARRAY_BYTES {
size /= 2;
}
let mut resized = Vec::with_capacity(self.native.len());
self.pixels.clear();
for (from, frames, initial) in &self.native {
let frames: Arc<Vec<Vec<u8>>> =
Arc::new(frames.iter().map(|f| resample(f, *from, size)).collect());
self.pixels.extend_from_slice(&frames[*initial]);
resized.push(frames);
}
for animation in &mut self.animations {
animation.frames = resized[animation.layer as usize].clone();
}
self.size = size;
}
/// The layer of a texture, added on first use. A texture that is missing
/// or does not load (a resource pack's filter or a broken file) becomes
/// vanilla's missing texture, as in a stitched atlas.
pub fn insert(&mut self, root: &Path, name: &str) -> Result<u32> {
if let Some(layer) = self.layers.get(name) {
return Ok(*layer);
}
match self.load(root, name) {
Ok(layer) => Ok(layer),
Err(e) => {
eprintln!("Horizon: using the missing texture for {name}: {e}");
// MissingTextureAtlasSprite.generateMissingImage: 16x16,
// magenta and black quarters.
let frame: Vec<u8> = (0..SPRITE_SIZE * SPRITE_SIZE)
.flat_map(|i| {
let (x, y) = (i % SPRITE_SIZE, i / SPRITE_SIZE);
if (y < SPRITE_SIZE / 2) ^ (x < SPRITE_SIZE / 2) {
[248, 0, 248, 255]
} else {
[0, 0, 0, 255]
}
})
.collect();
let layer = u32::try_from(self.layers.len())?;
self.opaque.push(true);
self.translucent.push(false);
self.layers.insert(name.to_owned(), layer);
self.native.push((SPRITE_SIZE, Arc::new(vec![frame]), 0));
Ok(layer)
}
}
}
fn load(&mut self, root: &Path, name: &str) -> Result<u32> {
let (namespace, path) = name.split_once(':').ok_or("invalid sprite identifier")?;
let path = root.join(format!("assets/{namespace}/textures/{path}.png"));
let metadata = match fs::read_to_string(path.with_extension("png.mcmeta")) {
@@ -103,18 +177,19 @@ impl Sprites {
let layer = u32::try_from(self.layers.len())?;
let columns = info.width / width;
let count = columns * (info.height / height);
// Layers are square; a frame of another shape is nearest-resampled to
// its longer side so UVs (normalized per layer) are unchanged.
let side = width.max(height);
let mut frames = Vec::new();
for index in 0..count {
let x = index % columns * width;
let y = index / columns * height;
// Every array layer is SPRITE_SIZE square; other sizes are
// nearest-resampled so UVs (normalized per layer) are unchanged.
let mut frame = Vec::with_capacity((SPRITE_SIZE * SPRITE_SIZE * 4) as usize);
for row in 0..SPRITE_SIZE {
let source_row = y + row * height / SPRITE_SIZE;
for column in 0..SPRITE_SIZE {
let mut frame = Vec::with_capacity((side * side * 4) as usize);
for row in 0..side {
let source_row = y + row * height / side;
for column in 0..side {
let offset =
((source_row * info.width + x + column * width / SPRITE_SIZE) * 4) as usize;
((source_row * info.width + x + column * width / side) * 4) as usize;
frame.extend_from_slice(&pixels[offset..offset + 4]);
}
}
@@ -145,8 +220,7 @@ impl Sprites {
.any(|p| p[3] != 0 && p[3] != 255),
);
self.layers.insert(name.to_owned(), layer);
self.size = SPRITE_SIZE;
self.pixels.extend_from_slice(&frames[initial]);
self.native.push((side, frames, initial));
Ok(layer)
}
}
@@ -169,6 +243,17 @@ pub(crate) fn test_animation(size: u32, layer: u32) -> SpriteAnimation {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hud_animation_resampling_uses_the_actual_frame_size() {
for size in [16, 32, 64] {
let animation = test_animation(size, 0);
let resized = animation.resized_pixels(1, 16, 16);
let last = (15 * size / 16) as u8;
assert_eq!(&resized[15 * 4..16 * 4], &[last, 0, 99, 255]);
assert_eq!(&resized[255 * 4..256 * 4], &[last, last, 99, 255]);
}
}
#[test]
fn native_fire_sprites_register_full_animation_sequences() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
@@ -233,6 +318,7 @@ mod tests {
fs::write(path.with_extension("png.mcmeta"), r#"{"animation":{}}"#).unwrap();
let mut sprites = Sprites::default();
sprites.insert(&root, "test:flow").unwrap();
sprites.finish();
let size = sprites.size;
let initial = sprites.pixels.clone();
let animation = sprites.animations[0].clone();
+35 -24
View File
@@ -14,7 +14,7 @@ use horizon_world::worldgen::decoration_order::DecorationOrder;
use std::{
collections::{BinaryHeap, HashSet},
sync::{
Arc, Condvar, Mutex,
Arc, Condvar, Mutex, RwLock,
atomic::{AtomicBool, Ordering},
mpsc,
},
@@ -94,6 +94,9 @@ struct Shared {
queue: Mutex<BinaryHeap<Queued>>,
ready: Condvar,
stop: AtomicBool,
/// What meshing reads (block models and sprites), swapped when resource
/// packs reload; each mesh job takes the current one.
context: RwLock<Arc<WorkerContext>>,
}
pub struct Streaming {
shared: Arc<Shared>,
@@ -165,6 +168,7 @@ impl Streaming {
queue: Mutex::new(BinaryHeap::new()),
ready: Condvar::new(),
stop: AtomicBool::new(false),
context: RwLock::new(context.clone()),
});
let (send, results) = mpsc::channel();
let light_tables = context.light.clone();
@@ -173,22 +177,11 @@ impl Streaming {
let shared = shared.clone();
let send = send.clone();
let generator = generator.clone();
let context = context.clone();
let light = context.light.clone();
thread::Builder::new()
.name(format!("horizon-worker-{i}"))
.spawn(move || {
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,
visibility: context.tables.visibility.clone(),
};
loop {
let job = {
let mut queue = shared.queue.lock().unwrap();
@@ -212,18 +205,22 @@ impl Streaming {
Done::Decorated(x, z, region)
}
Job::Finish(proto) => Done::Generated(generator.finish(proto)),
Job::Light(x, z, region, seq, sky) => Done::Lit(
x,
z,
light_chunk(&borrow(&region), &context.light, sky),
seq,
),
Job::Light(x, z, region, seq, sky) => {
Done::Lit(x, z, light_chunk(&borrow(&region), &light, sky), seq)
}
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;
let context = shared.context.read().unwrap().clone();
let mut mesher = Mesher {
nether_shading: settings.nether,
zoom: settings.zoom,
blend_radius: settings.blend_radius,
smooth_lighting: settings.smooth_lighting,
cutout_leaves: settings.cutout_leaves,
assets: &context.assets,
tables: &context.tables,
biomes: &context.biomes,
visibility: context.tables.visibility.clone(),
};
Done::Meshed(x, sy, z, mesher.mesh(&borrow(&region), sy), seq)
}
};
@@ -273,6 +270,20 @@ impl Streaming {
extra: Vec::new(),
}
}
/// Resource packs reloaded (`LevelRenderer.allChanged`): mesh with the new
/// models and sprites, and rebuild every loaded section. Meshes in flight
/// were made with the old resources; their results are dropped.
pub fn reload_resources(&mut self, world: &mut World, context: Arc<WorkerContext>) {
*self.shared.context.write().unwrap() = context;
self.meshing.clear();
for &(x, z) in world.chunks.keys() {
if self.lit.contains(&(x, z)) {
for sy in 0..SECTIONS as i32 {
world.dirty_sections.insert((x, sy, z));
}
}
}
}
/// A column received from a server: store it and relight it and its neighbours.
pub fn insert_remote(&mut self, world: &mut World, chunk: Chunk) {
let key = (chunk.x, chunk.z);
+273
View File
@@ -0,0 +1,273 @@
//! Rain and snow columns around the camera (`WeatherEffectRenderer`).
//!
//! Vanilla draws each column as one camera-facing quad whose texture
//! coordinates run past 0..1 (`v` advances a quarter of the texture per block,
//! so `rain.png` repeats every 4 blocks) and relies on a repeating sampler.
//! Horizon samples the sprite from its atlas, so [`tile`] splits a quad at
//! every whole texture repeat into pieces that stay inside the sprite.
use horizon_core::random::{LegacyRandom, RandomSource};
/// `WeatherEffectRenderer.ColumnInstance`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Column {
pub x: i32,
pub z: i32,
pub bottom_y: i32,
pub top_y: i32,
pub u_offset: f32,
pub v_offset: f32,
/// Vanilla packed light (`LightCoordsUtil.pack`: block << 4 | sky << 20).
pub light_coords: i32,
}
/// One vertex of a column quad, in vanilla's emission order.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ColumnVertex {
/// Camera-relative position.
pub pos: [f32; 3],
/// Texture coordinates before wrapping (the sampler repeats).
pub uv: [f32; 2],
/// ARGB (`ARGB.white(alpha)`).
pub color: u32,
pub light_coords: i32,
}
/// The random seed of a column (`extractRenderState`).
pub fn column_seed(x: i32, z: i32) -> i32 {
(x.wrapping_mul(x)
.wrapping_mul(3121)
.wrapping_add(x.wrapping_mul(45_238_971)))
^ (z.wrapping_mul(z)
.wrapping_mul(418_711)
.wrapping_add(z.wrapping_mul(13761)))
}
/// The column's random source, seeded as `random.setSeed(seed)`.
pub fn column_random(x: i32, z: i32) -> LegacyRandom {
LegacyRandom::new(i64::from(column_seed(x, z)))
}
/// `createRainColumnInstance`.
#[allow(clippy::too_many_arguments)]
pub fn rain_column(
random: &mut impl RandomSource,
ticks: i64,
x: i32,
bottom_y: i32,
top_y: i32,
z: i32,
light_coords: i32,
partial: f32,
) -> Column {
let wrapped_ticks = (ticks & 131_071) as i32;
let tick_offset = x
.wrapping_mul(x)
.wrapping_mul(3121)
.wrapping_add(x.wrapping_mul(45_238_971))
.wrapping_add(z.wrapping_mul(z).wrapping_mul(418_711))
.wrapping_add(z.wrapping_mul(13761))
& 0xFF;
let speed = 3.0 + random.next_float();
let offset = -((wrapped_ticks + tick_offset) as f32 + partial) / 32.0 * speed;
Column {
x,
z,
bottom_y,
top_y,
u_offset: 0.0,
v_offset: offset % 32.0,
light_coords,
}
}
/// `createSnowColumnInstance`: snow drifts sideways and is brightened.
#[allow(clippy::too_many_arguments)]
pub fn snow_column(
random: &mut impl RandomSource,
ticks: i64,
x: i32,
bottom_y: i32,
top_y: i32,
z: i32,
light_coords: i32,
partial: f32,
) -> Column {
let wrapped_ticks = (ticks & 131_071) as i32;
let time = wrapped_ticks as f32 + partial;
let u = random.next_double();
let u = (u + f64::from(time * 0.01 * random.next_gaussian() as f32)) as f32;
let v = random.next_double();
let v = (v + f64::from(time * random.next_gaussian() as f32 * 0.001)) as f32;
let v_offset = -((ticks & 511) as f32 + partial) / 512.0;
let (block, sky) = (light_coords >> 4 & 15, light_coords >> 20 & 15);
Column {
x,
z,
bottom_y,
top_y,
u_offset: u,
v_offset: v_offset + v,
light_coords: ((block * 3 + 15) / 4) << 4 | ((sky * 3 + 15) / 4) << 20,
}
}
/// The constructor's 32x32 table of horizontal column half-widths, indexed
/// relative to the camera block. The camera's own column divides 0 by 0.
fn column_size(index: usize) -> (f32, f32) {
let delta_x = (index % 32) as f32 - 16.0;
let delta_z = (index / 32) as f32 - 16.0;
let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32;
(-delta_z / distance, delta_x / distance)
}
/// `prepareInstances` for one column: rain uses `max_alpha` 1, snow 0.8.
pub fn column_quad(
column: &Column,
camera: [f64; 3],
max_alpha: f32,
radius: i32,
intensity: f32,
) -> [ColumnVertex; 4] {
let radius_sq = (radius * radius) as f32;
let relative_x = (f64::from(column.x) + 0.5 - camera[0]) as f32;
let relative_z = (f64::from(column.z) + 0.5 - camera[2]) as f32;
let distance_sq = relative_x * relative_x + relative_z * relative_z;
let t = (distance_sq / radius_sq).min(1.0);
let alpha = (max_alpha + t * (0.5 - max_alpha)) * intensity;
let color = ((alpha * 255.0).floor() as i32 as u32) << 24 | 0xFF_FFFF;
let index =
(column.z - camera[2].floor() as i32 + 16) * 32 + column.x - camera[0].floor() as i32 + 16;
let (size_x, size_z) = column_size(index as usize);
let (half_x, half_z) = (size_x / 2.0, size_z / 2.0);
let (x0, x1) = (relative_x - half_x, relative_x + half_x);
let y1 = (f64::from(column.top_y) - camera[1]) as f32;
let y0 = (f64::from(column.bottom_y) - camera[1]) as f32;
let (z0, z1) = (relative_z - half_z, relative_z + half_z);
let (u0, u1) = (column.u_offset, column.u_offset + 1.0);
let v0 = column.bottom_y as f32 * 0.25 + column.v_offset;
let v1 = column.top_y as f32 * 0.25 + column.v_offset;
let vertex = |pos, uv| ColumnVertex {
pos,
uv,
color,
light_coords: column.light_coords,
};
[
vertex([x0, y1, z0], [u0, v0]),
vertex([x1, y1, z1], [u1, v0]),
vertex([x1, y0, z1], [u1, v1]),
vertex([x0, y0, z0], [u0, v1]),
]
}
/// Split a column quad (vertices as [`column_quad`] emits them: top edge
/// `u0..u1` at `v0`, bottom edge at `v1`) at every whole texture repeat.
/// Each piece gets positions on the quad and texture coordinates in `0..=1`
/// of one repeat, ready to map onto an atlas sprite.
pub fn tile(quad: &[ColumnVertex; 4], mut emit: impl FnMut([[f32; 3]; 4], [[f32; 2]; 4])) {
let [u0, v0] = quad[0].uv;
let [u1, v1] = quad[2].uv;
let (top_left, top_right) = (quad[0].pos, quad[1].pos);
let (bottom_right, bottom_left) = (quad[2].pos, quad[3].pos);
let lerp3 = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] {
std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t)
};
// Position at fraction s across (u) and t down (v) the quad.
let at = |s: f32, t: f32| {
lerp3(
lerp3(top_left, top_right, s),
lerp3(bottom_left, bottom_right, s),
t,
)
};
let cuts = |a: f32, b: f32| {
let mut cuts = vec![a];
let mut k = a.floor() + 1.0;
while k < b {
cuts.push(k);
k += 1.0;
}
cuts.push(b);
cuts
};
if !(u1 > u0 && v1 > v0) {
return;
}
let (us, vs) = (cuts(u0, u1), cuts(v0, v1));
for v in vs.windows(2) {
let repeat_v = v[0].floor();
let (ta, tb) = ((v[0] - v0) / (v1 - v0), (v[1] - v0) / (v1 - v0));
let (la, lb) = (v[0] - repeat_v, v[1] - repeat_v);
for u in us.windows(2) {
let repeat_u = u[0].floor();
let (sa, sb) = ((u[0] - u0) / (u1 - u0), (u[1] - u0) / (u1 - u0));
let (ka, kb) = (u[0] - repeat_u, u[1] - repeat_u);
emit(
[at(sa, ta), at(sb, ta), at(sb, tb), at(sa, tb)],
[[ka, la], [kb, la], [kb, lb], [ka, lb]],
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rain_repeats_every_four_blocks() {
let column = Column {
x: 3,
z: 0,
bottom_y: 60,
top_y: 80,
u_offset: 0.0,
v_offset: 0.0,
light_coords: 15 << 20,
};
let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0);
// 20 blocks of rain: five repeats of the texture, split at each seam.
let mut pieces = Vec::new();
tile(&quad, |pos, uv| pieces.push((pos, uv)));
assert_eq!(pieces.len(), 5);
for (pos, uv) in &pieces {
assert!(((pos[0][1] - pos[3][1]) - 4.0).abs() < 1e-4);
assert_eq!(uv[0], [0.0, 0.0]);
assert_eq!(uv[2], [1.0, 1.0]);
}
}
#[test]
fn snow_drifts_across_one_seam() {
let column = Column {
x: 3,
z: 2,
bottom_y: 64,
top_y: 66,
u_offset: 0.25,
v_offset: 0.0,
light_coords: 0,
};
let quad = column_quad(&column, [0.5, 70.0, 0.5], 0.8, 10, 1.0);
let mut pieces = Vec::new();
tile(&quad, |pos, uv| pieces.push((pos, uv)));
assert_eq!(pieces.len(), 2);
assert_eq!(pieces[0].1[0], [0.25, 0.0]);
assert_eq!(pieces[1].1[2], [0.25, 0.5]);
}
#[test]
fn camera_column_is_degenerate() {
let column = Column {
x: 0,
z: 0,
bottom_y: 60,
top_y: 80,
u_offset: 0.0,
v_offset: 0.0,
light_coords: 0,
};
let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0);
assert!(quad[0].pos[0].is_nan());
}
}
@@ -435,6 +435,25 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
InteractionResult::Success
}
/// `ComposterBlock.addLayer` once its `compostable` provider gave
/// `layers`: the new state (the old one when no layer is added).
fn composter_add_layer(&mut self, pos: BlockPos, layers: i32) -> BlockStateId {
let b = self.b;
let state = self.state(pos);
if layers <= 0 {
return state;
}
let level = b.table.int(state, b.props.level);
let next_level = (level + layers).clamp(0, 7);
let next = b.table.set_int(state, b.props.level, next_level);
self.set_block_and_update(pos, next);
self.game_event_state(pos, "minecraft:block_change", next);
if next_level == 7 {
self.schedule_tick(pos, b.block(state), 20);
}
next
}
/// `DragonEggBlock.teleport`.
fn dragon_egg_teleport(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
@@ -462,6 +481,38 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
impl Behaviours {
/// `ComposterBlock.addLayer` at `pos` with the layers its item's
/// `compostable` provider gave, followed by level event 1500 (fill
/// particles and sound; data 1 when a layer was added) as every caller
/// does: `useItemOn` and the hopper input container. The new state.
pub fn composter_insert<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
layers: i32,
) -> BlockStateId {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
let next = sim.composter_add_layer(pos, layers);
sim.level_event(1500, pos, i32::from(next != state));
next
}
/// `ComposterBlock.empty`: the hopper output container took the bone meal.
pub fn composter_empty<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) {
let mut sim = self.sim(level, ticks);
let state = sim.state(pos);
let next = self.table.set_int(state, self.props.level, 0);
sim.set_block_and_update(pos, next);
sim.game_event_state(pos, "minecraft:block_change", next);
}
/// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and
/// absolute hit location as in `BlockHitResult`).
pub fn use_without_item<L: LevelAccess + ?Sized>(
+34
View File
@@ -367,6 +367,40 @@ fn water_spreads_on_a_floor() {
assert_eq!(w.prop(BlockPos::new(2, 1, 2), "level"), "4");
}
#[test]
fn bucket_source_removal_drains_spread_water() {
let mut w = world!();
w.floor(0, 10, "stone");
let at = BlockPos::new(0, 1, 0);
assert!(w.b().bucket_empty(
&mut w.level,
&mut w.ticks,
at,
BucketContent::Fluid(crate::fluid::FluidKind::Water),
"minecraft:item.bucket.empty"
));
for _ in 0..60 {
w.tick();
}
assert_ne!(w.get(BlockPos::new(1, 1, 0)), w.b().air());
assert_eq!(
w.b().bucket_pickup(&mut w.level, &mut w.ticks, at),
Some("minecraft:water_bucket")
);
for _ in 0..120 {
w.tick();
}
for x in -8..=8 {
for z in -8..=8 {
assert_eq!(
w.get(BlockPos::new(x, 1, z)),
w.b().air(),
"water remains at {x}, {z}"
);
}
}
}
#[test]
fn water_falls_and_makes_sources() {
let mut w = world!();
@@ -432,6 +432,11 @@ public final class VanillaBlockUpdateOracle {
world.emit("D " + id.identifier());
return delegate != null ? delegate.getLootTable(id) : net.minecraft.world.level.storage.loot.LootTable.EMPTY;
}
/** The registries loot contexts resolve providers in (a composter's compostable layers). */
@Override
public net.minecraft.core.HolderLookup.Provider lookup() {
return delegate != null ? delegate.lookup() : ParityData.lookup;
}
}
static final class Server extends net.minecraft.server.MinecraftServer {
@@ -29,13 +29,17 @@ public final class VanillaCloudRenderOracle {
int kind = Integer.parseInt(parts[0]), x = Integer.parseInt(parts[1]), z = Integer.parseInt(parts[2]);
int bottom = Integer.parseInt(parts[3]), neighbors = Integer.parseInt(parts[4]);
Object pos = positions[bottom > 0 ? 2 : bottom + 4 < 0 ? 0 : 1];
ByteBuffer buffer = ByteBuffer.allocate(100000);
ByteBuffer buffer = ByteBuffer.allocate(kind == 2 ? 4_000_000 : 100000);
if (kind == 0) {
long flags = ((neighbors & 1) != 0 ? 8 : 0) | ((neighbors & 2) != 0 ? 2 : 0)
| ((neighbors & 4) != 0 ? 1 : 0) | ((neighbors & 8) != 0 ? 4 : 0);
cell.invoke(renderer, pos, buffer, x, z, 0xfffffff0L | flags);
} else {
} else if (kind == 1) {
mesh.invoke(renderer, pos, buffer, 0, 0, true, x);
} else {
// prepare(..., range, ...): radiusCells from the Cloud Distance option.
int radiusBlocks = x * 16;
mesh.invoke(renderer, pos, buffer, 0, 0, true, net.minecraft.util.Mth.ceil(radiusBlocks / 12.0F));
}
output.append(index++);
buffer.flip();
@@ -0,0 +1,170 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Options;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.*;
import net.minecraft.client.gui.screens.recipebook.*;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.input.MouseButtonInfo;
import net.minecraft.core.NonNullList;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.inventory.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
/**
* Original oracle for the mouse handling of the survival and container
* screens: the real AbstractContainerScreen.mouseClicked/mouseReleased of
* ContainerScreen, HopperScreen, ShulkerBoxScreen and BeaconScreen (one slot
* in the menu, the carried stack and the event's Shift modifiers from the
* case) recording every slotClicked call they make, and the real
* hasClickedOutside of those screens, MerchantScreen and the recipe book
* screens (InventoryScreen, CraftingScreen, FurnaceScreen) with their
* RecipeBookComponent's visibility and selected tab hover from the case.
*/
public final class VanillaContainerScreenOracle {
static Object unsafe;
static Method allocate;
static final StringBuilder clicks = new StringBuilder();
@SuppressWarnings("unchecked")
static <T> T alloc(Class<T> type) throws Exception {
return (T) allocate.invoke(unsafe, type);
}
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
Class<?> t = f.getType();
String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : "putObject";
Class<?> param = t.isPrimitive() ? t : Object.class;
unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value);
}
static void record(int slotId, int button, ContainerInput input) {
clicks.append(" click ").append(slotId).append(' ').append(button).append(' ').append(input.name());
}
// The screens with slotClicked recording what the real mouse handling sends.
public static final class Chest extends ContainerScreen {
Chest() { super(null, null, null); }
@Override protected void slotClicked(Slot slot, int slotId, int button, ContainerInput input) { record(slotId, button, input); }
}
public static final class Hopper extends HopperScreen {
Hopper() { super(null, null, null); }
@Override protected void slotClicked(Slot slot, int slotId, int button, ContainerInput input) { record(slotId, button, input); }
}
public static final class Shulker extends ShulkerBoxScreen {
Shulker() { super(null, null, null); }
@Override protected void slotClicked(Slot slot, int slotId, int button, ContainerInput input) { record(slotId, button, input); }
}
public static final class Beacon extends BeaconScreen {
Beacon() { super(null, null, null); }
@Override protected void slotClicked(Slot slot, int slotId, int button, ContainerInput input) { record(slotId, button, input); }
}
static AbstractContainerScreen<?> screen(String kind) throws Exception {
return switch (kind) {
case "chest" -> alloc(Chest.class);
case "hopper" -> alloc(Hopper.class);
case "shulker" -> alloc(Shulker.class);
case "beacon" -> alloc(Beacon.class);
case "merchant" -> alloc(MerchantScreen.class);
case "inventory" -> alloc(InventoryScreen.class);
case "crafting" -> alloc(CraftingScreen.class);
case "furnace" -> alloc(FurnaceScreen.class);
default -> throw new IllegalArgumentException(kind);
};
}
public static void main(String[] args) throws Exception {
ParityData.init();
var u = Class.forName("sun.misc.Unsafe");
Field theUnsafe = u.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = theUnsafe.get(null);
allocate = u.getMethod("allocateInstance", Class.class);
Minecraft shell = alloc(Minecraft.class);
put(shell, Minecraft.class, "fixerUpper", net.minecraft.util.datafix.DataFixers.getDataFixer());
Field instance = Minecraft.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null, shell);
Options options = new Options(shell, Files.createTempDirectory("opts").toFile());
put(shell, Minecraft.class, "options", options);
Method outside = AbstractContainerScreen.class.getDeclaredMethod("hasClickedOutside", double.class, double.class, int.class, int.class);
outside.setAccessible(true);
Method hovered = AbstractContainerScreen.class.getDeclaredMethod("getHoveredSlot", double.class, double.class);
hovered.setAccessible(true);
Field carried = AbstractContainerMenu.class.getDeclaredField("carried");
carried.setAccessible(true);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
int n = 0;
for (var line : (Iterable<String>) lines::iterator) {
var c = JsonParser.parseString(line).getAsJsonObject();
out.println("== " + n++);
String kind = c.get("kind").getAsString();
var screen = screen(kind);
var image = c.getAsJsonArray("image");
put(screen, AbstractContainerScreen.class, "leftPos", image.get(0).getAsInt());
put(screen, AbstractContainerScreen.class, "topPos", image.get(1).getAsInt());
put(screen, AbstractContainerScreen.class, "imageWidth", image.get(2).getAsInt());
put(screen, AbstractContainerScreen.class, "imageHeight", image.get(3).getAsInt());
put(screen, Screen.class, "minecraft", shell);
put(screen, Screen.class, "children", new ArrayList<>());
put(screen, AbstractContainerScreen.class, "quickCraftSlots", new HashSet<Slot>());
put(screen, AbstractContainerScreen.class, "lastQuickMoved", ItemStack.EMPTY);
if (c.has("book")) {
var book = c.getAsJsonArray("book");
var component = alloc(CraftingRecipeBookComponent.class);
put(component, RecipeBookComponent.class, "visible", book.get(0).getAsBoolean());
var tab = alloc(RecipeBookTabButton.class);
put(tab, net.minecraft.client.gui.components.AbstractWidget.class, "isHovered", book.get(1).getAsBoolean());
put(component, RecipeBookComponent.class, "selectedTab", tab);
put(screen, AbstractRecipeBookScreen.class, "recipeBookComponent", component);
}
var menu = alloc(ChestMenu.class);
NonNullList<Slot> slots = NonNullList.create();
var pos = c.getAsJsonArray("slot");
var slot = new Slot(new SimpleContainer(1), 0, pos.get(0).getAsInt(), pos.get(1).getAsInt());
slot.index = 7;
slots.add(slot);
put(menu, AbstractContainerMenu.class, "slots", slots);
carried.set(menu, ItemStack.EMPTY);
put(screen, AbstractContainerScreen.class, "menu", menu);
int left = image.get(0).getAsInt(), top = image.get(1).getAsInt();
for (var e : c.getAsJsonArray("events")) {
var ev = e.getAsJsonArray();
String name = ev.get(0).getAsString();
double x = ev.get(1).getAsDouble(), y = ev.get(2).getAsDouble();
var sb = new StringBuilder(name);
sb.append(' ').append(outside.invoke(screen, x, y, left, top));
if (!name.equals("point")) {
sb.append(' ').append(hovered.invoke(screen, x, y) != null);
carried.set(menu, ev.get(5).getAsBoolean() ? new ItemStack(Items.STONE, 5) : ItemStack.EMPTY);
var event = new MouseButtonEvent(x, y, new MouseButtonInfo(ev.get(3).getAsInt(), ev.get(4).getAsInt()));
clicks.setLength(0);
if (name.equals("press")) {
screen.mouseClicked(event, false);
} else {
screen.mouseReleased(event);
}
sb.append(clicks);
}
out.println(sb);
}
}
}
System.exit(0);
}
}
@@ -51,6 +51,7 @@ public final class VanillaDispenserOracle {
case 1051 -> "minecraft:entity.wind_charge.throw";
case 1505 -> "minecraft:item.bone_meal.use";
case 1501 -> "minecraft:block.lava.extinguish";
case 1500 -> data == 1 ? "minecraft:block.composter.fill_success" : "minecraft:block.composter.fill";
case 1009 -> data == 0 ? "minecraft:block.fire.extinguish" : data == 1 ? "minecraft:block.generic.extinguish_fire" : null;
case 2001 -> {
BlockState state = Block.stateById(data);
@@ -289,8 +290,15 @@ public final class VanillaDispenserOracle {
List<Entity> targets = List.copyOf(w.entities);
BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos"));
BlockState state = w.getBlockState(origin);
List<String> used = new ArrayList<>();
if (f.has("remove")) {
remove(w, origin, f.getAsJsonObject("remove"));
} else if (f.has("use")) {
used = use(w, origin, f.getAsJsonObject("use"));
} else if (f.has("hopper")) {
// HopperBlockEntity.pushItemsTick, once.
var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin);
net.minecraft.world.level.block.entity.HopperBlockEntity.pushItemsTick(w, origin, state, hopper);
} else if (state.getBlock() instanceof CrafterBlock) {
Method craft = CrafterBlock.class.getDeclaredMethod("dispenseFrom", BlockState.class, ServerLevel.class, BlockPos.class);
craft.setAccessible(true);
@@ -348,9 +356,60 @@ public final class VanillaDispenserOracle {
}
}
result.addAll(w.blockEvents);
result.addAll(used);
result.add("rng " + w.rng.nextLong());
}
/** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */
static final class User extends net.minecraft.server.level.ServerPlayer {
VanillaBlockUpdateOracle.World world;
boolean creative;
ItemStack hand;
List<String> stats;
User() {
super(null, null, null, null);
}
@Override public ServerLevel level() { return world; }
@Override public boolean hasInfiniteMaterials() { return creative; }
@Override public boolean isCreative() { return creative; }
@Override public boolean isSpectator() { return false; }
@Override public EntityType<?> getType() { return EntityTypes.PLAYER; }
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
@Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY;
}
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) {
stats.add("stat " + key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
}
static <T> String key(net.minecraft.stats.Stat<T> stat) {
return String.valueOf(stat.getType().getRegistry().getKey(stat.getValue()));
}
}
/**
* ServerPlayerGameMode.useItemOn by a player holding the case's item on the
* block at `pos` (not sneaking): `useItemOn`, then `useWithoutItem` when the
* block asks to try with an empty hand. The held stack and statistics follow.
*/
static List<String> use(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception {
User player = (User) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, User.class);
player.world = w;
player.creative = use.has("creative") && use.get("creative").getAsBoolean();
player.hand = stack(use.get("item").getAsString());
player.stats = new ArrayList<>();
var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0),
net.minecraft.core.Direction.UP, pos, false);
BlockState state = w.getBlockState(pos);
var hand = net.minecraft.world.InteractionHand.MAIN_HAND;
var result = state.useItemOn(player.getItemInHand(hand), w, player, hand, hit);
if (result instanceof net.minecraft.world.InteractionResult.TryEmptyHandInteraction) {
result = state.useWithoutItem(w, player, hit);
}
List<String> out = new ArrayList<>(player.stats);
out.add("use " + (result.consumesAction() ? "consumed" : "pass") + " held " + ParityData.canon(player.hand));
return out;
}
/** The level's block entity positions by x, y, z. */
static List<BlockPos> sortedEntities(VanillaBlockUpdateOracle.World w) {
List<BlockPos> out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
@@ -0,0 +1,116 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.serialization.JsonOps;
import java.io.PrintWriter;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.function.Predicate;
import net.minecraft.advancements.predicates.entity.EntityPredicate;
import net.minecraft.core.*;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.damagesource.DamageSources;
import net.minecraft.world.entity.*;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.gamerules.GameRules;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
/**
* Original oracle for the entity predicates advancements match tamed, leashed
* or bred animals with: real entities made with EntityType.create(LOAD) on a
* level stand-in, given the case's variant through Entity.setComponent (the
* variant data component, e.g. minecraft:wolf/variant), then tested with the
* real EntityPredicate (decoded from the case with the registries' ops), which
* reads the variant back through Entity.get for its minecraft:components.
*/
public final class VanillaEntityComponentsOracle {
static Object unsafe;
static Method allocate, putObject, objectFieldOffset;
static void put(Object target, Class<?> owner, String field, Object value) throws Exception {
Field f = owner.getDeclaredField(field);
long offset = (long) objectFieldOffset.invoke(unsafe, f);
putObject.invoke(unsafe, target, offset, value);
}
static final class Lvl extends ServerLevel {
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
net.minecraft.server.MinecraftServer fake;
RegistryAccess registries;
GameRules rules;
@Override public net.minecraft.server.MinecraftServer getServer() { return fake; }
int next = 1;
@Override public RegistryAccess registryAccess() { return registries; }
@Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; }
@Override public long getGameTime() { return 0L; }
@Override public int getNextEntityId() { return next++; }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
@Override public GameRules getGameRules() { return rules; }
@Override public boolean addFreshEntity(Entity entity) { return true; }
@Override public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> type, AABB bb, Predicate<? super T> selector) { return new ArrayList<>(); }
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
@Override public int getSeaLevel() { return 63; }
@Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(net.minecraft.world.Difficulty.NORMAL, 0L, 0L, 0.0F); }
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static void main(String[] args) throws Exception {
ParityData.init();
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = unsafeField.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class);
objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class);
RegistryAccess access = ParityData.access;
Lvl level = (Lvl) allocate.invoke(unsafe, Lvl.class);
level.registries = access;
// A server that only answers debug subscribers (PathNavigation asks).
var server = (net.minecraft.server.MinecraftServer) allocate.invoke(unsafe, net.minecraft.server.dedicated.DedicatedServer.class);
put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", allocate.invoke(unsafe, net.minecraft.util.debug.ServerDebugSubscribers.class));
level.fake = server;
put(level, ServerLevel.class, "server", server);
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build();
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
put(level, Level.class, "damageSources", new DamageSources(access));
put(level, Level.class, "random", RandomSource.create(0L));
var ops = RegistryOps.create(JsonOps.INSTANCE, ParityData.lookup);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
int n = 0;
for (var line : (Iterable<String>) lines::iterator) {
var c = JsonParser.parseString(line).getAsJsonObject();
out.println("== " + n++);
String type = c.get("type").getAsString();
Entity entity = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(type)).create(level, EntitySpawnReason.LOAD);
if (c.has("variant")) {
// The species' variant component and registry: minecraft:<species>/variant
// holds an entry of minecraft:<species>_variant.
String species = Identifier.parse(type).getPath();
var component = (DataComponentType) BuiltInRegistries.DATA_COMPONENT_TYPE.getValue(Identifier.parse("minecraft:" + species + "/variant"));
ResourceKey<Registry<Object>> registry = ResourceKey.createRegistryKey(Identifier.parse("minecraft:" + species + "_variant"));
var holder = access.lookupOrThrow(registry).getOrThrow(ResourceKey.create(registry, Identifier.parse(c.get("variant").getAsString())));
entity.setComponent(component, holder);
}
entity.setPos(0.5, 64.0, 0.5);
for (var p : c.getAsJsonArray("predicates")) {
var predicate = EntityPredicate.CODEC.parse(ops, p).getOrThrow();
out.println(predicate.matches(level, new Vec3(2.5, 64.0, 0.5), entity));
}
}
}
System.exit(0);
}
}
@@ -0,0 +1,66 @@
package dev.horizonlab.parity;
import java.io.*;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.FireChargeItem;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
/**
* Original oracle for the fire charge's use sound: the real private
* FireChargeItem.playSound (used for both a lit campfire or candle and a
* placed fire) on a level stand-in whose random is seeded from the case,
* recording the sound, its volume and pitch and the level random's next long
* (which shows how many values the sound drew).
*/
public final class VanillaFireStarterSoundOracle {
static final StringBuilder sounds = new StringBuilder();
static final class World extends ServerLevel {
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z,
net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) {
sounds.append(s.unwrapKey().orElseThrow().identifier()).append(' ')
.append(Float.floatToIntBits(v)).append(' ').append(Float.floatToIntBits(pitch));
}
}
static void put(Object unsafe, Object target, String name, Object value) throws Exception {
Field f = Level.class.getDeclaredField(name);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, target, offset, value);
}
public static void main(String[] args) throws Exception {
ParityData.init();
var u = Class.forName("sun.misc.Unsafe");
Field theUnsafe = u.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Object unsafe = theUnsafe.get(null);
World world = (World) u.getMethod("allocateInstance", Class.class).invoke(unsafe, World.class);
Method play = FireChargeItem.class.getDeclaredMethod("playSound", Level.class, BlockPos.class);
play.setAccessible(true);
var item = (FireChargeItem) Items.FIRE_CHARGE;
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
var lines = Files.lines(Path.of(args[0]))) {
for (var line : (Iterable<String>) lines::iterator) {
long seed = Long.parseLong(line.trim());
RandomSource random = RandomSource.create(seed);
put(unsafe, world, "random", random);
put(unsafe, world, "soundSeedGenerator", RandomSource.create(0));
sounds.setLength(0);
play.invoke(item, world, new BlockPos(3, 64, -7));
out.println(sounds + " " + random.nextLong());
}
}
System.exit(0);
}
}
@@ -50,7 +50,9 @@ import net.minecraft.world.phys.*;
* level, connection and item model resolver are shells answering what these
* read, and the results of using items on blocks, entities and the air are
* scripted. The attack and use part of Minecraft.handleKeybinds and the
* ticker lines of Player.tick are mirrored here in vanilla's order.
* ticker lines of Player.tick are mirrored here in vanilla's order. Steps may
* turn the player; the real LocalPlayer.applyInput moves the hands' xBob and
* yBob after it.
*/
public final class VanillaFirstPersonOracle {
static Object unsafe;
@@ -150,6 +152,8 @@ public final class VanillaFirstPersonOracle {
}
@Override public AttributeMap getAttributes() { return attributes; }
// The shell Minecraft has no game renderer: the player is the camera.
@Override protected boolean isControlledCamera() { return true; }
@Override public boolean isEyeInFluid(TagKey<Fluid> type) { return false; }
@Override public boolean onGround() { return true; }
@Override public boolean isWithinEntityInteractionRange(Entity entity, double buffer) { return inRange; }
@@ -274,6 +278,7 @@ public final class VanillaFirstPersonOracle {
swingState.set(player, new LivingEntity.SwingState());
lastItem.set(player, ItemStack.EMPTY);
hands.set(player, new FirstPersonHandsAndItems());
player.input = new net.minecraft.client.player.ClientInput();
var effects = new HashMap<Holder<MobEffect>, MobEffectInstance>();
if (!c.get("haste").isJsonNull()) {
effects.put(MobEffects.HASTE, new MobEffectInstance(MobEffects.HASTE, 100000, c.get("haste").getAsInt()));
@@ -363,6 +368,13 @@ public final class VanillaFirstPersonOracle {
}
lastItem.set(player, main.copy());
}
// LocalPlayer.aiStep's applyInput, after the step's turn.
if (step.has("rot") && !step.get("rot").isJsonNull()) {
var rot = step.getAsJsonArray("rot");
player.setXRot(Float.intBitsToFloat(Integer.parseUnsignedInt(rot.get(0).getAsString(), 16)));
player.setYRot(Float.intBitsToFloat(Integer.parseUnsignedInt(rot.get(1).getAsString(), 16)));
}
player.applyInput();
var fp = (FirstPersonHandsAndItems) hands.get(player);
fp.tick(player);
for (var ev : events) {
@@ -376,7 +388,8 @@ public final class VanillaFirstPersonOracle {
+ " " + fb(mainHeight.getFloat(fp)) + " " + fb(oMainHeight.getFloat(fp))
+ " " + fb(offHeight.getFloat(fp)) + " " + fb(oOffHeight.getFloat(fp))
+ " " + missTime.getInt(mc) + " " + rightClickDelay.getInt(mc) + " " + destroyDelay.getInt(gameMode)
+ " " + destroying.getBoolean(gameMode) + " " + fb(progress.getFloat(gameMode)));
+ " " + destroying.getBoolean(gameMode) + " " + fb(progress.getFloat(gameMode))
+ " " + fb(player.xBob) + " " + fb(player.yBob) + " " + fb(player.xBobO) + " " + fb(player.yBobO));
}
}
}
@@ -82,6 +82,9 @@ public final class VanillaMenuOracle {
@Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { }
@Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; }
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { }
// BlockEntity.setChanged of the "*_be" furnaces: no chunks here.
@Override public void blockEntityChanged(BlockPos pos) { }
@Override public void updateNeighbourForOutputSignal(BlockPos pos, net.minecraft.world.level.block.Block block) { }
}
static final class FakePlayer extends ServerPlayer {
@@ -145,6 +148,31 @@ public final class VanillaMenuOracle {
throw new AssertionError(e);
}
}
case "furnace_be", "blast_furnace_be", "smoker_be" -> {
// The server's menu: the block entity is the container and its data,
// so AbstractFurnaceBlockEntity.setItem restarts cooking.
net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity be = switch (kind) {
case "furnace_be" -> new net.minecraft.world.level.block.entity.FurnaceBlockEntity(BlockPos.ZERO,
net.minecraft.world.level.block.Blocks.FURNACE.defaultBlockState());
case "blast_furnace_be" -> new net.minecraft.world.level.block.entity.BlastFurnaceBlockEntity(BlockPos.ZERO,
net.minecraft.world.level.block.Blocks.BLAST_FURNACE.defaultBlockState());
default -> new net.minecraft.world.level.block.entity.SmokerBlockEntity(BlockPos.ZERO,
net.minecraft.world.level.block.Blocks.SMOKER.defaultBlockState());
};
be.setLevel(player.world);
try {
Field data = net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity.class.getDeclaredField("dataAccess");
data.setAccessible(true);
ContainerData furnaceData = (ContainerData) data.get(be);
yield switch (kind) {
case "furnace_be" -> new FurnaceMenu(0, inv, be, furnaceData);
case "blast_furnace_be" -> new BlastFurnaceMenu(0, inv, be, furnaceData);
default -> new SmokerMenu(0, inv, be, furnaceData);
};
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
case "loom" -> new LoomMenu(0, inv);
default -> throw new IllegalArgumentException(kind);
};
@@ -184,6 +184,9 @@ public final class VanillaMobAiOracle {
boolean spawning;
/** The player hits a mob for 1 at the start of a tick: {tick, mob index}. */
List<int[]> hurts = new ArrayList<>();
/** The player feeds an animal at the start of a tick (Animal.mobInteract with the item in
* its main hand): {tick, mob index, item id}. */
List<Object[]> feeds = new ArrayList<>();
}
static void parse(Path path) throws Exception {
@@ -220,6 +223,7 @@ public final class VanillaMobAiOracle {
}
case "heart" -> s.hearts.add(f);
case "hurt" -> s.hurts.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2])});
case "feed" -> s.feeds.add(new Object[] {Integer.parseInt(f[1]), Integer.parseInt(f[2]), f[3]});
case "player" -> {
s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])};
for (int i = 4; i < f.length; i++) {
@@ -713,6 +717,17 @@ public final class VanillaMobAiOracle {
if (hurt[0] == t && hurt[1] < ENTS.size() && ENTS.get(hurt[1]) instanceof LivingEntity hurtMob && !hurtMob.isRemoved())
hurtMob.hurtServer(level, level.damageSources().playerAttack(player), 1.0F);
}
for (Object[] feed : s.feeds) {
int index = (Integer) feed[1];
if ((Integer) feed[0] != t || index >= ENTS.size()
|| !(ENTS.get(index) instanceof net.minecraft.world.entity.animal.Animal animal) || animal.isRemoved()) continue;
var hand = net.minecraft.world.InteractionHand.MAIN_HAND;
var held = player.getItemInHand(hand);
player.setItemInHand(hand, new net.minecraft.world.item.ItemStack(
BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse((String) feed[2])), 64));
animal.mobInteract(player, hand);
player.setItemInHand(hand, held);
}
for (Entity e : List.copyOf(ENTS)) {
if (e.isRemoved()) continue;
e.checkDespawn();
@@ -0,0 +1,160 @@
package dev.horizonlab.parity;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.mojang.serialization.JsonOps;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import net.minecraft.client.gui.font.providers.GlyphProviderDefinition;
import net.minecraft.client.renderer.texture.atlas.SpriteSourceList;
import net.minecraft.client.renderer.texture.atlas.SpriteSources;
import net.minecraft.client.resources.language.ClientLanguage;
import net.minecraft.client.resources.sounds.Sound;
import net.minecraft.client.sounds.SoundManager;
import net.minecraft.client.sounds.WeighedSoundEvents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.contents.TranslatableContents;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.PackLocationInfo;
import net.minecraft.server.packs.PackResources;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.PathPackResources;
import net.minecraft.server.packs.repository.FolderRepositorySource;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.PackSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.util.profiling.InactiveProfiler;
import net.minecraft.world.level.validation.DirectoryValidator;
/**
* The client resource manager over vanilla's resources and a selection of
* resource packs from a folder (FolderRepositorySource: folder and zip packs,
* pack.mcmeta overlays and filters), and what the reload listeners read from
* it: which pack provides a file, translations (ClientLanguage), sound events
* (SoundManager.prepare), font providers (FontManager) and atlas sources
* (SpriteSourceList).
*
* Input: a first line "root VANILLA PACKS ID..." (bottom first), then queries:
* "file PATH", "lang KEY", "sound EVENT", "font ID", "atlas ID".
*/
public final class VanillaPackResourcesOracle {
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
net.minecraft.server.Bootstrap.bootStrap();
SpriteSources.bootstrap();
List<String> lines = Files.readAllLines(Path.of(args[0]));
String[] root = lines.get(0).split(" ");
List<PackResources> packs = new ArrayList<>();
packs.add(new PathPackResources(
new PackLocationInfo("vanilla", Component.literal("vanilla"), PackSource.BUILT_IN, Optional.empty()), Path.of(root[1])));
var repository = new PackRepository(new FolderRepositorySource(
Path.of(root[2]), PackType.CLIENT_RESOURCES, PackSource.DEFAULT, new DirectoryValidator(path -> true)));
repository.reload();
for (int i = 3; i < root.length; i++) {
repository.getPack(root[i]).open().forEach(packs::add);
}
var manager = new MultiPackResourceManager(PackType.CLIENT_RESOURCES, packs);
ClientLanguage language = ClientLanguage.loadFrom(manager, List.of("en_us"), false);
Object unsafe = theUnsafe();
SoundManager sounds = (SoundManager) unsafe.getClass().getMethod("allocateInstance", Class.class)
.invoke(unsafe, SoundManager.class);
Method prepare = SoundManager.class.getDeclaredMethod("prepare",
net.minecraft.server.packs.resources.ResourceManager.class, net.minecraft.util.profiling.ProfilerFiller.class);
prepare.setAccessible(true);
Object preparations = prepare.invoke(sounds, manager, InactiveProfiler.INSTANCE);
var registryField = preparations.getClass().getDeclaredField("registry");
registryField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<Identifier, WeighedSoundEvents> registry = (Map<Identifier, WeighedSoundEvents>) registryField.get(preparations);
Method fontStack = net.minecraft.client.gui.font.FontManager.class.getDeclaredMethod("loadResourceStack", List.class, Identifier.class);
fontStack.setAccessible(true);
StringBuilder out = new StringBuilder();
for (String line : lines.subList(1, lines.size())) {
String[] q = line.split(" ", 2);
out.append(line).append(" =>");
switch (q[0]) {
case "file" -> {
Optional<Resource> resource = manager.getResource(Identifier.parse(q[1]));
if (resource.isEmpty()) {
out.append(" missing");
} else {
try (InputStream in = resource.get().open()) {
out.append(' ').append(Long.toHexString(fnv(in.readAllBytes())));
}
}
}
case "lang" -> out.append(' ').append(language.getOrDefault(q[1]));
case "sound" -> {
WeighedSoundEvents event = registry.get(Identifier.parse(q[1]));
if (event == null) {
out.append(" missing");
break;
}
Component subtitle = event.getSubtitle();
out.append(" subtitle=").append(subtitle == null ? "none"
: ((TranslatableContents) subtitle.getContents()).getKey());
var listField = WeighedSoundEvents.class.getDeclaredField("list");
listField.setAccessible(true);
for (Object weighted : (List<?>) listField.get(event)) {
out.append(' ').append(weighted instanceof Sound sound
? sound.getLocation() + "*" + sound.getWeight() : "event");
}
}
case "font" -> {
Identifier id = Identifier.parse(q[1]);
List<Resource> stack = manager.getResourceStack(id.withPath(p -> "font/" + p + ".json"));
List<?> builders = new ArrayList<>((List<?>) fontStack.invoke(null, stack, id));
java.util.Collections.reverse(builders);
for (Object pair : builders) {
var conditional = (GlyphProviderDefinition.Conditional) ((com.mojang.datafixers.util.Pair<?, ?>) pair).getSecond();
JsonElement json = GlyphProviderDefinition.Conditional.CODEC.encodeStart(JsonOps.INSTANCE, conditional).getOrThrow();
out.append(' ').append(strip(json.getAsJsonObject().get("type").getAsString()));
}
}
case "atlas" -> {
SpriteSourceList list = SpriteSourceList.load(manager, Identifier.parse(q[1]));
var sourcesField = SpriteSourceList.class.getDeclaredField("sources");
sourcesField.setAccessible(true);
@SuppressWarnings("unchecked")
var sources = (List<net.minecraft.client.renderer.texture.atlas.SpriteSource>) sourcesField.get(list);
JsonArray json = SpriteSources.FILE_CODEC.encodeStart(JsonOps.INSTANCE, sources).getOrThrow()
.getAsJsonObject().getAsJsonArray("sources");
for (JsonElement source : json) {
out.append(' ').append(strip(source.getAsJsonObject().get("type").getAsString()));
}
}
default -> throw new IllegalArgumentException(line);
}
out.append('\n');
}
Files.writeString(Path.of(args[1]), out);
}
private static String strip(String type) {
return type.startsWith("minecraft:") ? type.substring("minecraft:".length()) : type;
}
/** FNV-1a 64 of a file's bytes. */
private static long fnv(byte[] bytes) {
long hash = 0xcbf29ce484222325L;
for (byte b : bytes) {
hash = (hash ^ (b & 0xff)) * 0x100000001b3L;
}
return hash;
}
private static Object theUnsafe() throws Exception {
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
var field = unsafeClass.getDeclaredField("theUnsafe");
field.setAccessible(true);
return field.get(null);
}
}
@@ -0,0 +1,292 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.platform.NativeImage;
import java.io.InputStreamReader;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.*;
import net.minecraft.client.renderer.block.BlockStateModelSet;
import net.minecraft.client.renderer.item.ItemModelResolver;
import net.minecraft.client.renderer.item.ItemStackRenderState;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.sprite.Material;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.Bootstrap;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.ItemOwner;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemStackTemplate;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.gameevent.BlockPositionSource;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.levelgen.RandomSupport;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.Vec3;
import org.jspecify.annotations.Nullable;
/** Builds each particle through its real registered ParticleProvider (the real
* ParticleResources, sprite sets bound to stand-in sprites named after the
* vanilla particles/*.json textures) in a stand-in ClientLevel (air, an
* optional stone floor at y 63, no fluids), then ticks it and records its
* state, the particles and sounds it asks the level for, tick by tick.
*
* Each vanilla Particle owns a RandomSource.create() random seeded from the
* clock; its seed is recovered after construction (the SEED_UNIQUIFIER value
* and the System.nanoTime window around the call, checked against the
* random's state stepped back over its draws) and printed first so the probe
* can replay the same draws. The provider random, the level random and
* SpellParticle.RANDOM are seeded from the case. */
public final class VanillaParticleProvidersOracle {
private static Object unsafe;
private static Method allocate;
private static final long MULTIPLIER = 0x5DEECE66DL, MASK = (1L << 48) - 1, INVERSE = 0xDFE05BCB1365L;
static Field field(Class<?> type, String name) throws Exception {
var f = type.getDeclaredField(name); f.setAccessible(true); return f;
}
static <T> T make(Class<T> type) throws Exception { return type.cast(allocate.invoke(unsafe, type)); }
static final class Level0 extends ClientLevel {
boolean floor;
List<String> events;
Level0() { super(null, null, null, null, 0, 0, null, false, 0L, 0); }
@Override public BlockState getBlockState(BlockPos p) {
return floor && p.getY() == 63 ? Blocks.STONE.defaultBlockState() : Blocks.AIR.defaultBlockState();
}
@Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); }
@Override public @Nullable BlockGetter getChunkForCollisions(int x, int z) { return this; }
@Override public boolean hasChunkAt(BlockPos p) { return false; }
@Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) {
events.add("+ " + name(o) + " " + d(x) + " " + d(y) + " " + d(z) + " " + d(xd) + " " + d(yd) + " " + d(zd));
}
@Override public void addParticle(ParticleOptions o, boolean override, boolean always, double x, double y, double z, double xd, double yd, double zd) {
addParticle(o, x, y, z, xd, yd, zd);
}
@Override public void addAlwaysVisibleParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) {
addParticle(o, x, y, z, xd, yd, zd);
}
@Override public void addAlwaysVisibleParticle(ParticleOptions o, boolean override, double x, double y, double z, double xd, double yd, double zd) {
addParticle(o, x, y, z, xd, yd, zd);
}
@Override public void playLocalSound(double x, double y, double z, SoundEvent sound, SoundSource source, float volume, float pitch, boolean delay) {
events.add("~ " + sound.location() + " " + d(x) + " " + d(y) + " " + d(z) + " " + f(volume) + " " + f(pitch));
}
@Override public net.minecraft.world.entity.player.@Nullable Player getNearestPlayer(double x, double y, double z, double distance, boolean creative) { return null; }
}
static String name(ParticleOptions o) { return BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType()).getPath(); }
static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); }
static String f(float v) { return String.format("%08x", Float.floatToRawIntBits(v)); }
static final class Sprite extends TextureAtlasSprite {
Sprite(Identifier atlas, Identifier name) { super(atlas, new SpriteContents(name, new FrameSize(16, 16), new NativeImage(16, 16, true)), 16, 16, 0, 0, 0); }
}
static final Map<String, TextureAtlasSprite> SPRITES = new HashMap<>();
static TextureAtlasSprite sprite(Identifier atlas, String name) {
return SPRITES.computeIfAbsent(name, n -> new Sprite(atlas, Identifier.withDefaultNamespace(n)));
}
static final class Models extends BlockStateModelSet {
Models() { super(Map.of(), null); }
@Override public Material.Baked getParticleMaterial(BlockState state) {
return new Material.Baked(sprite(TextureAtlas.LOCATION_BLOCKS, "terrain"), false);
}
}
/** Every item resolves to one layer whose particle sprite is named after the item. */
static final class Items0 extends ItemModelResolver {
Items0() { super(null); }
@Override public void updateForTopItem(ItemStackRenderState out, ItemStack item, ItemDisplayContext context, @Nullable Level level, @Nullable ItemOwner owner, int seed) {
out.clear();
out.newLayer().setParticleMaterial(new Material.Baked(sprite(TextureAtlas.LOCATION_BLOCKS, "item_" + BuiltInRegistries.ITEM.getKey(item.getItem()).getPath()), false));
}
}
static ParticleOptions options(JsonObject c) {
var id = Identifier.withDefaultNamespace(c.get("type").getAsString());
ParticleType<?> type = BuiltInRegistries.PARTICLE_TYPE.getValue(id);
if (type == null) throw new AssertionError("unknown particle " + id);
var o = c.has("options") ? c.getAsJsonObject("options") : new JsonObject();
if (type instanceof SimpleParticleType simple) return simple;
@SuppressWarnings("unchecked") var any = (ParticleType<ParticleOptions>) (ParticleType<?>) type;
int color = o.has("color") ? (int) o.get("color").getAsLong() : 0xFFFFFFFF;
float scale = o.has("scale") ? o.get("scale").getAsFloat() : 1.0F;
if (type == ParticleTypes.DUST) return new DustParticleOptions(color, scale);
if (type == ParticleTypes.DUST_COLOR_TRANSITION) return new DustColorTransitionOptions(color, (int) o.get("to").getAsLong(), scale);
if (type == ParticleTypes.EFFECT || type == ParticleTypes.INSTANT_EFFECT)
return SpellParticleOption.create(castSpell(type), color, scale);
if (type == ParticleTypes.DRAGON_BREATH) return PowerParticleOption.create(ParticleTypes.DRAGON_BREATH, scale);
if (type == ParticleTypes.SCULK_CHARGE) return new SculkChargeParticleOptions(scale);
if (type == ParticleTypes.SHRIEK) return new ShriekParticleOption((int) scale);
if (type == ParticleTypes.ITEM)
return new ItemParticleOption(ParticleTypes.ITEM, new ItemStackTemplate(BuiltInRegistries.ITEM.getValue(Identifier.parse(o.get("item").getAsString()))));
if (type == ParticleTypes.TRAIL) {
var t = o.getAsJsonArray("target");
return new TrailParticleOption(new Vec3(t.get(0).getAsDouble(), t.get(1).getAsDouble(), t.get(2).getAsDouble()), color, o.get("duration").getAsInt());
}
if (type == ParticleTypes.VIBRATION) {
var t = o.getAsJsonArray("target");
return new VibrationParticleOption(new BlockPositionSource(new BlockPos(t.get(0).getAsInt(), t.get(1).getAsInt(), t.get(2).getAsInt())), o.get("duration").getAsInt());
}
if (o.has("state")) return new BlockParticleOption(castBlock(type), Block.stateById(o.get("state").getAsInt()));
if (o.has("color")) return ColorParticleOption.create(castColor(type), color);
throw new AssertionError("no options for " + id);
}
@SuppressWarnings("unchecked") static ParticleType<SpellParticleOption> castSpell(ParticleType<?> t) { return (ParticleType<SpellParticleOption>) t; }
@SuppressWarnings("unchecked") static ParticleType<BlockParticleOption> castBlock(ParticleType<?> t) { return (ParticleType<BlockParticleOption>) t; }
@SuppressWarnings("unchecked") static ParticleType<ColorParticleOption> castColor(ParticleType<?> t) { return (ParticleType<ColorParticleOption>) t; }
static Field X, Y, Z, XO, YO, ZO, XD, YD, ZD, AGE, LIFETIME, REMOVED, ON_GROUND, RANDOM, SEED;
static Field QUAD, R, G, B, A, ROLL, O_ROLL, SPRITE;
static Method U0, U1, V0, V1, LIGHT;
static String state(Particle p) throws Exception {
var s = new StringBuilder();
s.append(AGE.getInt(p)).append(' ').append(LIFETIME.getInt(p)).append(' ').append(REMOVED.getBoolean(p) ? 1 : 0)
.append(' ').append(ON_GROUND.getBoolean(p) ? 1 : 0);
for (var f : new Field[] {X, Y, Z, XD, YD, ZD, XO, YO, ZO}) s.append(' ').append(d(f.getDouble(p)));
if (p instanceof SingleQuadParticle q) {
s.append(" | ").append(f(q.getQuadSize(0.0F))).append(' ').append(f(q.getQuadSize(0.5F)));
for (var f : new Field[] {R, G, B, A, ROLL, O_ROLL}) s.append(' ').append(f(f.getFloat(q)));
var sprite = (TextureAtlasSprite) SPRITE.get(q);
s.append(' ').append(sprite == null ? "-" : sprite.contents().name().getPath());
for (var m : new Method[] {U0, U1, V0, V1}) s.append(' ').append(f((float) m.invoke(q)));
s.append(' ').append(Integer.toHexString((int) LIGHT.invoke(q, 0.5F)));
}
return s.toString();
}
/** Recover the seed of RandomSource.create() that made `random`, which was
* created after `before` was the uniquifier and inside [t0, t1]. */
static long recover(LegacyRandomSource random, long before, long t0, long t1) throws Exception {
long end = ((AtomicLong) SEED.get(random)).get();
var back = new HashMap<Long, Integer>();
long s = end;
for (int k = 0; k <= 4096; k++) { back.putIfAbsent(s, k); s = ((s - 0xBL) * INVERSE) & MASK; }
long u = before;
Long found = null;
for (int j = 0; j < 8 && found == null; j++) {
u *= 1181783497276652981L;
for (long t = t0; t <= t1; t++) {
long seed = u ^ t;
if (back.containsKey((seed ^ MULTIPLIER) & MASK)) {
if (found != null && ((found ^ MULTIPLIER) & MASK) != ((seed ^ MULTIPLIER) & MASK)) throw new AssertionError("ambiguous seed");
found = seed;
}
}
}
if (found == null) throw new AssertionError("particle seed not recovered");
return found;
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion(); Bootstrap.bootStrap();
var u = Class.forName("sun.misc.Unsafe"); unsafe = field(u, "theUnsafe").get(null); allocate = u.getMethod("allocateInstance", Class.class);
var mc = make(Minecraft.class); field(Minecraft.class, "instance").set(null, mc);
var manager = make(ModelManager.class); field(ModelManager.class, "blockStateModelSet").set(manager, new Models());
field(Minecraft.class, "modelManager").set(mc, manager); field(Minecraft.class, "blockColors").set(mc, new BlockColors());
field(Minecraft.class, "itemModelResolver").set(mc, new Items0());
var level = make(Level0.class); level.events = new ArrayList<>(); field(ClientLevel.class, "minecraft").set(level, mc);
field(Minecraft.class, "particleEngine").set(mc, new ParticleEngine(level, null));
X = field(Particle.class, "x"); Y = field(Particle.class, "y"); Z = field(Particle.class, "z");
XO = field(Particle.class, "xo"); YO = field(Particle.class, "yo"); ZO = field(Particle.class, "zo");
XD = field(Particle.class, "xd"); YD = field(Particle.class, "yd"); ZD = field(Particle.class, "zd");
AGE = field(Particle.class, "age"); LIFETIME = field(Particle.class, "lifetime"); REMOVED = field(Particle.class, "removed");
ON_GROUND = field(Particle.class, "onGround"); RANDOM = field(Particle.class, "random"); SEED = field(LegacyRandomSource.class, "seed");
QUAD = field(SingleQuadParticle.class, "quadSize"); R = field(SingleQuadParticle.class, "rCol"); G = field(SingleQuadParticle.class, "gCol");
B = field(SingleQuadParticle.class, "bCol"); A = field(SingleQuadParticle.class, "alpha"); ROLL = field(SingleQuadParticle.class, "roll");
O_ROLL = field(SingleQuadParticle.class, "oRoll"); SPRITE = field(SingleQuadParticle.class, "sprite");
U0 = SingleQuadParticle.class.getDeclaredMethod("getU0"); U1 = SingleQuadParticle.class.getDeclaredMethod("getU1");
V0 = SingleQuadParticle.class.getDeclaredMethod("getV0"); V1 = SingleQuadParticle.class.getDeclaredMethod("getV1");
LIGHT = Particle.class.getDeclaredMethod("getLightCoords", float.class);
for (var m : new Method[] {U0, U1, V0, V1, LIGHT}) m.setAccessible(true);
var uniquifier = (AtomicLong) field(RandomSupport.class, "SEED_UNIQUIFIER").get(null);
// Initialise SpellParticle first: its static initializer would replace a seeded RANDOM.
Class.forName(SpellParticle.class.getName(), true, SpellParticle.class.getClassLoader());
var spellRandom = field(SpellParticle.class, "RANDOM");
var unsafeObject = unsafe;
var staticBase = u.getMethod("staticFieldBase", Field.class).invoke(unsafeObject, spellRandom);
long staticOffset = (long) u.getMethod("staticFieldOffset", Field.class).invoke(unsafeObject, spellRandom);
var putObject = u.getMethod("putObject", Object.class, long.class, Object.class);
// The real providers, their sprite sets bound to one stand-in sprite per listed texture.
var resources = new ParticleResources();
@SuppressWarnings("unchecked") var sets = (Map<Identifier, Object>) field(ParticleResources.class, "spriteSets").get(resources);
for (var e : sets.entrySet()) {
var stream = Minecraft.class.getResourceAsStream("/assets/minecraft/particles/" + e.getKey().getPath() + ".json");
var sprites = new ArrayList<TextureAtlasSprite>();
if (stream != null) {
try (var reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
for (var t : JsonParser.parseReader(reader).getAsJsonObject().getAsJsonArray("textures"))
sprites.add(sprite(TextureAtlas.LOCATION_PARTICLES, Identifier.parse(t.getAsString()).getPath()));
}
}
if (sprites.isEmpty()) sprites.add(sprite(TextureAtlas.LOCATION_PARTICLES, "missingno"));
var rebind = e.getValue().getClass().getDeclaredMethod("rebind", List.class); rebind.setAccessible(true);
rebind.invoke(e.getValue(), sprites);
}
var providers = resources.getProviders();
// Warm up the classes the providers touch so the clock window stays small.
for (int i = 0; i < 3; i++) RandomSource.create();
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
int n = 0;
for (String line : Files.readAllLines(Path.of(args[0]))) {
var c = JsonParser.parseString(line).getAsJsonObject();
output.write("== " + n++); output.newLine();
var options = options(c);
@SuppressWarnings("unchecked") var provider = (ParticleProvider<ParticleOptions>) providers.get(BuiltInRegistries.PARTICLE_TYPE.getId(options.getType()));
if (provider == null) { output.write("no provider"); output.newLine(); continue; }
long seed = c.get("seed").getAsLong();
RandomSource random = null;
level.floor = c.get("floor").getAsBoolean();
level.events.clear();
var p = c.getAsJsonArray("pos"); var v = c.getAsJsonArray("vel");
Particle particle = null;
long before = 0, t0 = 0, t1 = 0;
for (int attempt = 0; attempt < 4; attempt++) {
level.events.clear();
random = RandomSource.create(seed);
field(Level.class, "random").set(level, RandomSource.create(seed ^ 0x6C6576656CL));
putObject.invoke(unsafeObject, staticBase, staticOffset, RandomSource.create(seed ^ 0x7370656C6CL));
before = uniquifier.get(); t0 = System.nanoTime();
particle = provider.createParticle(options, level, p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble(),
v.get(0).getAsDouble(), v.get(1).getAsDouble(), v.get(2).getAsDouble(), random);
t1 = System.nanoTime();
if (t1 - t0 < 50_000_000L) break;
}
if (particle == null) { output.write("null " + random.nextLong()); output.newLine(); continue; }
long local = recover((LegacyRandomSource) RANDOM.get(particle), before, t0, t1);
output.write("seed " + local + " " + particle.getClass().getSimpleName()); output.newLine();
output.write("next " + random.nextLong() + " " + level.getRandom().nextLong() + " "
+ ((RandomSource) spellRandom.get(null)).nextLong()); output.newLine();
output.write("0 " + state(particle)); output.newLine();
for (var e : level.events) { output.write(e); output.newLine(); }
int ticks = c.get("ticks").getAsInt();
for (int t = 1; t <= ticks && particle.isAlive(); t++) {
level.events.clear();
particle.tick();
output.write(t + " " + state(particle)); output.newLine();
for (var e : level.events) { output.write(e); output.newLine(); }
}
}
}
}
}
@@ -74,7 +74,8 @@ public final class VanillaSceneMotionOracle {
return VanillaBlockLandingOracle.sound(s);
}
static final class Sources extends DamageSources {
DamageSource fall,stalagmite,starve;Sources(){super(null);}
DamageSource fall,stalagmite,starve,freeze;Sources(){super(null);}
@Override public DamageSource freeze(){return freeze;}
@Override public DamageSource starve(){return starve;}
@Override public DamageSource fall(){return fall;}
@Override public DamageSource stalagmite(){return stalagmite;}
@@ -111,9 +112,14 @@ public final class VanillaSceneMotionOracle {
@Override public WorldBorder getWorldBorder(){return border;}
@Override public DamageSources damageSources(){return sources;}
@Override public net.minecraft.util.RandomSource getRandom(){return rng;}
@Override public boolean isRainingAt(BlockPos p){return false;}
@Override public net.minecraft.server.MinecraftServer getServer(){return server;}
@Override public void gameEvent(Holder<GameEvent> event,Vec3 pos,GameEvent.Context context){if(event==GameEvent.HIT_GROUND)actor.events.add("hit "+vectorBits(pos)+" "+Block.getId(context.affectedState()));}
@Override public void gameEvent(Holder<GameEvent> event,BlockPos pos,GameEvent.Context context){actor.events.add("event "+(event==GameEvent.BLOCK_CHANGE?"change":event==GameEvent.BLOCK_DESTROY?"destroy":"unknown")+" "+blockPos(pos)+" "+Block.getId(context.affectedState())+" "+(context.sourceEntity()!=null));}
@Override public <T extends net.minecraft.core.particles.ParticleOptions> int sendParticles(T particle,double x,double y,double z,int count,double dx,double dy,double dz,double xs,double ys,double zs,net.minecraft.network.protocol.game.ClientboundLevelParticlesPacket.RandomizationType type){
if(particle!=net.minecraft.core.particles.ParticleTypes.SNOWFLAKE||count!=1||dx!=0||dy!=0||dz!=0||type!=net.minecraft.network.protocol.game.ClientboundLevelParticlesPacket.RandomizationType.ALTERNATIVE)throw new AssertionError();
actor.events.add("snowflake "+vectorBits(new Vec3(x,y,z))+" "+vectorBits(new Vec3(xs,ys,zs)));return 0;
}
@Override public <T extends net.minecraft.core.particles.ParticleOptions> int sendParticles(T particle,double x,double y,double z,int count,double dx,double dy,double dz,double speed){
var b=(net.minecraft.core.particles.BlockParticleOption)particle;if(dx!=0||dy!=0||dz!=0)throw new AssertionError();
actor.events.add(String.format("particles %d %s %d %016x",Block.getId(b.getState()),vectorBits(new Vec3(x,y,z)),count,Double.doubleToLongBits(speed)));return 0;
@@ -199,16 +205,23 @@ public final class VanillaSceneMotionOracle {
String name=stat==net.minecraft.stats.Stats.DAMAGE_ABSORBED?"absorbed":stat==net.minecraft.stats.Stats.DAMAGE_TAKEN?"taken":stat==net.minecraft.stats.Stats.DAMAGE_RESISTED?"resisted":null;
if(name==null){name=stat.getPath();if(!Set.of("swim_one_cm","walk_under_water_one_cm","walk_on_water_one_cm","climb_one_cm","sprint_one_cm","crouch_one_cm","walk_one_cm","aviate_one_cm","fly_one_cm").contains(name))throw new AssertionError(stat);}events.add("health-stat "+name+" "+value);
}
@Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,DamageSource source,float damage){var sources=((Level)level).sources;events.add(String.format("damage %s %08x",source==sources.fall?"fall":source==sources.stalagmite?"stalagmite":source==sources.starve?"starve":"unknown",Float.floatToIntBits(damage)));return super.hurtServer(level,source,damage);}
@Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,DamageSource source,float damage){var sources=((Level)level).sources;events.add(String.format("damage %s %08x",source==sources.fall?"fall":source==sources.stalagmite?"stalagmite":source==sources.starve?"starve":source==sources.freeze?"freeze":"unknown",Float.floatToIntBits(damage)));return super.hurtServer(level,source,damage);}
@Override public void teleportRelative(double x,double y,double z){setPos(getX()+x,getY()+y,getZ()+z);}
@Override protected void playStepSound(BlockPos p,BlockState state){}
@Override public void gameEvent(Holder<GameEvent> event,Entity source){}
@Override public LivingEntity getControllingPassenger(){return null;}
@Override public double getFluidHeight(net.minecraft.tags.TagKey<net.minecraft.world.level.material.Fluid> tag){return 0;}
@Override public double getFluidJumpThreshold(){return .4;}
@Override public int getTicksFrozen(){return 0;}
@Override public void setTicksFrozen(int value){if(value!=0)throw new AssertionError(value);}
@Override protected void applyEffectsFromBlocks(){}
// Block-inside effects and frozen ticks run only in "snow_tick" operations.
boolean effects;int frozen;Vec3 tickStart;
@Override public int getTicksFrozen(){return frozen;}
@Override public void setTicksFrozen(int value){if(!effects&&value!=0)throw new AssertionError(value);frozen=value;}
@Override protected void applyEffectsFromBlocks(){if(effects)super.applyEffectsFromBlocks();}
// LivingEntity.canFreeze with #freeze_immune_wearables, whose only
// member a scene wears is leather boots (item tags aren't bound here).
@Override public boolean canFreeze(){return !isSpectator()&&!getItemBySlot(net.minecraft.world.entity.EquipmentSlot.FEET).is(net.minecraft.world.item.Items.LEATHER_BOOTS);}
// ServerPlayer.lastKnownClientMovement: this tick's movement.
@Override public Vec3 getKnownMovement(){return tickStart==null?Vec3.ZERO:position().subtract(tickStart);}
@Override protected void applyInput(){if(!preparedInput)super.applyInput();}
void peaceful(){tickRegeneration();}
void clock()throws Exception{sceneLevel.time++;tickCount++;if(cooldown.getInt(this)>0)cooldown.setInt(this,cooldown.getInt(this)-1);if(hurtTime>0)hurtTime--;}
@@ -240,7 +253,7 @@ public final class VanillaSceneMotionOracle {
out.printf("%s %s %s %s %s %s %s %016x %s %s %s %08x %d %08x %d %d %s | %s%n",p.horizontalCollision,p.verticalCollision,p.verticalCollisionBelow,p.minorHorizontalCollision,
p.onGround(),noBlocks.getBoolean(p),pos(support.get(p)),Double.doubleToLongBits(p.fallDistance),pos(last.get(p)),p.needsSync,p.syncPosition,Float.floatToIntBits(storedSpeed.getFloat(p)),delay.getInt(p),Float.floatToIntBits(p.yHeadRot),trigger.getInt(p),grace.getInt(p),impact.get(p)==null?"none":vectorBits((Vec3)impact.get(p)),String.join(";",attributes));
out.println("events "+String.join(" | ",p.events));p.events.clear();
out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25))));
out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25)))+" frozen "+p.frozen+" "+p.isInPowderSnow+" "+p.wasInPowderSnow+" "+vectorBits((Vec3)stuck.get(p)));
out.printf("health %08x %08x %08x %d %d %08x %d %d %s %d %s %s %s %s %s %d%n",
Float.floatToIntBits(p.getHealth()),Float.floatToIntBits(p.getAbsorptionAmount()),Float.floatToIntBits(foodExhaustion.getFloat(p.getFoodData())),
noAction.getInt(p),cooldown.getInt(p),Float.floatToIntBits(lastHurt.getFloat(p)),p.hurtDuration,p.hurtTime,sourceName((DamageSource)lastDamage.get(p)),lastStamp.getLong(p),healthDead.getBoolean(p),p.syncVelocity,
@@ -270,11 +283,11 @@ public final class VanillaSceneMotionOracle {
var trace=new Trace();trace.out=new PrintWriter(OutputStream.nullOutputStream());trace.fail=-1;
var level=(Level)allocate.invoke(unsafe,Level.class);level.chunks=VanillaSceneCollisionOracle.scene(description,trace);level.border=new Border();
level.rng=net.minecraft.util.RandomSource.create(0);level.sources=(Sources)allocate.invoke(unsafe,Sources.class);
level.sources.fall=damageSources.get("minecraft:fall");level.sources.stalagmite=damageSources.get("minecraft:stalagmite");level.sources.starve=damageSources.get("minecraft:starve");
level.sources.fall=damageSources.get("minecraft:fall");level.sources.stalagmite=damageSources.get("minecraft:stalagmite");level.sources.starve=damageSources.get("minecraft:starve");level.sources.freeze=damageSources.get("minecraft:freeze");
level.waypoints=(Waypoints)allocate.invoke(unsafe,Waypoints.class);level.waypoints.level=level;
level.rules=new Rules();level.difficulty=net.minecraft.world.Difficulty.NORMAL;
var server=(VanillaBlockLandingOracle.Server)allocate.invoke(unsafe,VanillaBlockLandingOracle.Server.class);
server.d=new VanillaBlockLandingOracle.Data();server.d.out=new PrintWriter(OutputStream.nullOutputStream());server.d.f=JsonParser.parseString("{\"fail\":-1,\"protected\":false}").getAsJsonObject();level.server=server;
server.d=new VanillaBlockLandingOracle.Data();server.d.out=new PrintWriter(OutputStream.nullOutputStream());server.d.f=JsonParser.parseString("{\"fail\":-1,\"protected\":false}").getAsJsonObject();level.server=server;write(field(net.minecraft.server.MinecraftServer.class,"debugSubscribers"),server,new net.minecraft.util.debug.ServerDebugSubscribers(server));
try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var enriched=new PrintWriter(Files.newBufferedWriter(dir.resolve("inputs-"+args[0]+".txt")));var lines=Files.lines(dir.resolve("inputs.txt"))){
for(var line:(Iterable<String>)lines::iterator){
var row=JsonParser.parseString(line).getAsJsonObject();var p=(Actor)allocate.invoke(unsafe,Actor.class);p.configure(level);p.events=new ArrayList<>();level.actor=p;
@@ -285,6 +298,8 @@ public final class VanillaSceneMotionOracle {
var equipment=new EntityEquipment();write(field(LivingEntity.class,"equipment"),p,equipment);
write(field(Player.class,"inventory"),p,new Inventory(p,equipment));
p.attrs=new TrackedAttributes(VanillaEntityAttributeOracle.supplier(EntityTypes.PLAYER));write(field(LivingEntity.class,"attributes"),p,p.attrs);
write(field(Entity.class,"finalMovementsThisTick"),p,new ArrayList<>());write(field(Entity.class,"visitedBlocks"),p,new it.unimi.dsi.fastutil.longs.LongOpenHashSet());
write(field(Entity.class,"insideEffectCollector"),p,new net.minecraft.world.entity.InsideBlockEffectApplier.StepBasedCollector());
write(history,p,new ArrayDeque<>());write(support,p,Optional.empty());write(last,p,Optional.empty());write(stuck,p,Vec3.ZERO);write(abilities,p,new Abilities());
write(field(ServerPlayer.class,"shoulderEntityLeft"),p,new net.minecraft.nbt.CompoundTag());write(field(ServerPlayer.class,"shoulderEntityRight"),p,new net.minecraft.nbt.CompoundTag());
p.connection=(Connection)allocate.invoke(unsafe,Connection.class);
@@ -334,6 +349,27 @@ public final class VanillaSceneMotionOracle {
case "travel"->p.travel(VanillaSceneCollisionOracle.vector(op.get("value")));
case "tick"->p.movementTick(VanillaSceneCollisionOracle.vector(op.get("value")));
case "player_tick"->p.playerMovementTick(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean());
case "snow_tick"->{
// The clock, Entity.baseTick's powder snow flags and old
// position, then aiStep with its block-inside effects.
p.clock();p.wasInPowderSnow=p.isInPowderSnow;p.isInPowderSnow=false;
p.xOld=p.getX();p.yOld=p.getY();p.zOld=p.getZ();p.tickStart=p.position();
p.effects=true;
try{p.playerMovementTick(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean());}finally{p.effects=false;}
}
case "boots"->{
// Leather boots without data components (item components aren't
// bound here), straight into the equipment: no equip callbacks.
var stack=net.minecraft.world.item.ItemStack.EMPTY;
if(op.get("value").getAsBoolean()){
stack=(net.minecraft.world.item.ItemStack)allocate.invoke(unsafe,net.minecraft.world.item.ItemStack.class);
write(field(net.minecraft.world.item.ItemStack.class,"item"),stack,net.minecraft.world.item.Items.LEATHER_BOOTS.builtInRegistryHolder());
field(net.minecraft.world.item.ItemStack.class,"count").setInt(stack,1);
write(field(net.minecraft.world.item.ItemStack.class,"components"),stack,new net.minecraft.core.component.PatchedDataComponentMap(net.minecraft.core.component.DataComponentMap.EMPTY));
}
((EntityEquipment)field(LivingEntity.class,"equipment").get(p)).set(net.minecraft.world.entity.EquipmentSlot.FEET,stack);
}
case "frozen"->p.frozen=op.get("value").getAsInt();
case "trigger"->trigger.setInt(p,op.get("value").getAsInt());
case "delay"->delay.setInt(p,op.get("value").getAsInt());
case "ack_attributes"->{p.attrs.getAttributesToUpdate().clear();p.attrs.getAttributesToSync().clear();}
@@ -0,0 +1,87 @@
package dev.horizonlab.parity;
import com.mojang.blaze3d.vertex.VertexConsumer;
import java.lang.reflect.Proxy;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import net.minecraft.client.renderer.WeatherEffectRenderer;
import net.minecraft.util.RandomSource;
import net.minecraft.world.phys.Vec3;
/** Build rain and snow column quads with the shipped renderer, without a GPU or a level. */
public final class VanillaWeatherRenderOracle {
public static void main(String[] args) throws Exception {
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
var theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Object renderer = unsafeClass.getMethod("allocateInstance", Class.class)
.invoke(theUnsafe.get(null), WeatherEffectRenderer.class);
// The constructor's column table, built the same way before it reaches Minecraft.getInstance().
float[] sizeX = new float[1024], sizeZ = new float[1024];
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
float deltaX = x - 16, deltaZ = z - 16;
float distance = net.minecraft.util.Mth.length(deltaX, deltaZ);
sizeX[z * 32 + x] = -deltaZ / distance;
sizeZ[z * 32 + x] = deltaX / distance;
}
}
for (String name : new String[]{"columnSizeX", "columnSizeZ"}) {
var field = WeatherEffectRenderer.class.getDeclaredField(name);
field.setAccessible(true);
field.set(renderer, name.endsWith("X") ? sizeX : sizeZ);
}
var rain = WeatherEffectRenderer.class.getDeclaredMethod("createRainColumnInstance",
RandomSource.class, long.class, int.class, int.class, int.class, int.class, int.class, float.class);
var snow = WeatherEffectRenderer.class.getDeclaredMethod("createSnowColumnInstance",
RandomSource.class, long.class, int.class, int.class, int.class, int.class, int.class, float.class);
var prepare = WeatherEffectRenderer.class.getDeclaredMethod("prepareInstances",
VertexConsumer.class, List.class, Vec3.class, float.class, int.class, float.class);
rain.setAccessible(true);
snow.setAccessible(true);
prepare.setAccessible(true);
StringBuilder output = new StringBuilder();
int index = 0;
for (String line : Files.readAllLines(Path.of(args[0]))) {
String[] p = line.split(" ");
int kind = Integer.parseInt(p[0]);
long ticks = Long.parseLong(p[1]);
int x = Integer.parseInt(p[2]), bottom = Integer.parseInt(p[3]), top = Integer.parseInt(p[4]);
int z = Integer.parseInt(p[5]), light = Integer.parseInt(p[6]);
float partial = Float.parseFloat(p[7]);
Vec3 camera = new Vec3(Double.parseDouble(p[8]), Double.parseDouble(p[9]), Double.parseDouble(p[10]));
int radius = Integer.parseInt(p[11]);
float intensity = Float.parseFloat(p[12]);
// extractRenderState: the column random is reseeded per column.
RandomSource random = RandomSource.createThreadLocalInstance(0L);
random.setSeed(x * x * 3121 + x * 45238971 ^ z * z * 418711 + z * 13761);
Object column = (kind == 0 ? rain : snow).invoke(renderer, random, ticks, x, bottom, top, z, light, partial);
var record = (WeatherEffectRenderer.ColumnInstance) column;
output.append(index++).append(' ').append(record.x()).append(' ').append(record.z()).append(' ')
.append(record.bottomY()).append(' ').append(record.topY()).append(' ')
.append(bits(record.uOffset())).append(' ').append(bits(record.vOffset())).append(' ')
.append(record.lightCoords());
StringBuilder vertices = new StringBuilder();
VertexConsumer consumer = (VertexConsumer) Proxy.newProxyInstance(
VertexConsumer.class.getClassLoader(), new Class<?>[]{VertexConsumer.class}, (proxy, method, a) -> {
switch (method.getName()) {
case "addVertex" -> vertices.append(" |").append(bits((Float) a[0])).append(',')
.append(bits((Float) a[1])).append(',').append(bits((Float) a[2]));
case "setUv" -> vertices.append(',').append(bits((Float) a[0])).append(',').append(bits((Float) a[1]));
case "setColor" -> vertices.append(',').append(Integer.toHexString((Integer) a[0]));
case "setLight" -> vertices.append(',').append((Integer) a[0]);
default -> throw new IllegalStateException("unexpected " + method);
}
return proxy;
});
prepare.invoke(renderer, consumer, List.of(column), camera, kind == 0 ? 1.0F : 0.8F, radius, intensity);
output.append(vertices).append('\n');
}
Files.writeString(Path.of(args[1]), output);
}
private static String bits(float value) {
return Float.isNaN(value) ? "nan" : Integer.toHexString(Float.floatToRawIntBits(value));
}
}
+5 -1
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Compare fancy cloud exterior/interior faces and nearest-first mesh traversal with 26.3."""
"""Compare fancy cloud exterior/interior faces, nearest-first mesh traversal and the
cell radius of the Cloud Distance option (independent of the render distance) with 26.3."""
try:
from . import lab, oracle_harness as harness
except ImportError:
@@ -16,6 +17,9 @@ def make_input(build):
for radius in range(11):
for bottom in (-5, -4, 0, 1):
cases.append(f"1 {radius} 0 {bottom} 0\n")
# CloudRenderer.prepare: radius from options.cloudRange (2..128 chunks).
for cloud_range in (2, 3, 4, 7, 8, 12, 32, 64, 127, 128):
cases.append(f"2 {cloud_range} 0 -5 0\n")
inputs = build / "inputs.txt"
inputs.write_text("".join(cases))
return inputs, len(cases)
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Compare vanilla composters with Horizon's: by hand, through hoppers and from droppers.
Every case has a composter at a random level and runs one action over the
headless level of the dispenser harness (`VanillaDispenserOracle` against
`HORIZON_DISPENSE_FIXTURE`):
- `use`: a player (survival or creative) right-clicks the composter holding a
compostable item, another item or nothing (`ComposterBlock.useItemOn`, then
`useWithoutItem`, which empties a full composter);
- `hopper` above: a hopper facing down (or past it) pushes its items into the
composter's input container;
- `hopper` below: a hopper under the composter pulls the bone meal out of its
output container (nothing from the other levels);
- `dispense`: a dropper facing the composter puts one item in from above, or
is refused from the side.
Both sides print block changes, container contents, spawned items, level
events with the sounds the client plays for them, sounds, game events, the
player's statistics and held stack, and the level random afterwards (the
compostable providers draw from it).
"""
import json
import os
import random
try:
from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
except ImportError:
import block_update_harness as h
import lab
import test_dispenser_parity as d
import test_rust_parity as base
OTHERS = ['stick', 'stone', 'bone_meal', 'diamond_sword', 'water_bucket', 'cobblestone', 'egg']
SIDES = ['north', 'south', 'west', 'east']
def stack(rng, items, compostable, others_odds=0.25):
if rng.random() < others_odds:
name = rng.choice(OTHERS)
else:
name = rng.choice(compostable)
top = items['minecraft:' + name].get('minecraft:max_stack_size', 64)
return d.plain(name, min(top, rng.choice([1, 1, 2, 16, 64])))
def composter(states, rng):
level = rng.choice([0, 0, 1, 3, 5, 6, 6, 7, 8, 8])
return states.get('composter', level=str(level))
def cases(facts, items, count, seed):
rng = random.Random(seed)
states = d.States(facts)
compostable = sorted(k.split(':')[1] for k, v in items.items() if 'minecraft:compostable' in v)
modes = ['use', 'use', 'hopper_in', 'hopper_out', 'dispense']
for n in range(count):
mode = modes[n % len(modes)]
case = {**h.environment(rng), 'pos': [0, 0, 0]}
case.pop('raining', None)
case.pop('thundering', None)
cells = []
items_in = []
if mode == 'use':
cells.append([0, 0, 0, composter(states, rng)])
held = '-' if rng.random() < 0.1 else stack(rng, items, compostable)
case['use'] = {'item': held, 'creative': rng.random() < 0.2}
elif mode == 'hopper_in':
facing = 'down' if rng.random() < 0.8 else rng.choice(SIDES)
cells.append([0, 0, 0, states.get('hopper', facing=facing, enabled='true')])
target = {'down': (0, -1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)}[facing]
cells.append([*target, composter(states, rng)])
for slot in rng.sample(range(5), rng.choice([1, 1, 2, 3, 5])):
items_in.append([0, 0, 0, slot, stack(rng, items, compostable, 0.4)])
case['hopper'] = True
elif mode == 'hopper_out':
facing = rng.choice(['down', 'down'] + SIDES)
cells.append([0, 0, 0, states.get('hopper', facing=facing, enabled='true')])
level = 8 if rng.random() < 0.7 else rng.choice([0, 3, 7])
cells.append([0, 1, 0, states.get('composter', level=str(level))])
roll = rng.random()
if roll < 0.3:
# Full of something else: the bone meal can't go in.
for slot in range(5):
items_in.append([0, 0, 0, slot, d.plain('stone', 64)])
elif roll < 0.5:
items_in.append([0, 0, 0, rng.randrange(5), d.plain('bone_meal', rng.choice([1, 63, 64]))])
case['hopper'] = True
else:
facing = 'down' if rng.random() < 0.75 else rng.choice(SIDES + ['up'])
cells.append([0, 0, 0, states.get('dropper', facing=facing, triggered='false')])
dx, dy, dz = d.STEP[facing]
cells.append([dx, dy, dz, composter(states, rng)])
slots = rng.sample(range(9), rng.choice([1, 1, 2, 9]))
for slot in slots:
items_in.append([0, 0, 0, slot, stack(rng, items, compostable, 0.3)])
case['cells'] = cells
case['items'] = items_in
case['mode'] = 'dispense'
case['action'] = mode
yield case
def main():
parser = h.argument_parser(__doc__)
args = parser.parse_args()
if args.count == 40000:
args.count = 3000
lock, jars, libraries = base.verify_artifacts()
facts = h.load_facts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
items = json.loads((resources / 'items.json').read_text())
work = lab.LOCAL / 'composter-parity'
work.mkdir(parents=True, exist_ok=True)
all_cases = list(cases(facts, items, args.count, args.seed))
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
java_root = lab.ROOT / 'mods/horizon/src/test/java'
d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
groups, errors = {}, {}
for case, a, b in zip(all_cases, native, rust):
if a and a[0].startswith('error'):
errors.setdefault(a[0], []).append(case)
continue
if not d.same(a, b):
groups.setdefault(case['action'], []).append((case, a, b))
for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
print(f'oracle error x{len(entries)}: {kind}')
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
print(f'{name}: {len(entries)} differing')
for case, a, b in entries[:args.show]:
print(' case ' + d.describe(case, facts) + (' use=' + json.dumps(case['use']) if 'use' in case else ''))
print(' native ' + ' | '.join(sorted(a)))
print(' rust ' + ' | '.join(sorted(b)))
total = sum(len(v) for v in groups.values())
skipped = sum(len(v) for v in errors.values())
print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors)')
h.finish(total + skipped)
if __name__ == '__main__':
main()
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Compare the survival and container screens' mouse handling with the pinned
client: the real AbstractContainerScreen.mouseClicked/mouseReleased (the slot
id a click targets, -999 outside the window, and the ContainerInput it sends:
PICKUP, QUICK_MOVE from the event's own Shift modifiers, THROW, the quick
craft drag a held stack starts and the drop its release outside makes) and
hasClickedOutside, with AbstractRecipeBookScreen's and RecipeBookComponent's
rule for the recipe book screens."""
import json
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
# imageWidth, imageHeight; the recipe book screens only compare hasClickedOutside.
SCREENS = {'chest': None, 'hopper': (176, 133), 'shulker': (176, 167), 'beacon': (230, 219),
'merchant': (276, 166), 'inventory': (176, 166), 'crafting': (176, 166), 'furnace': (176, 166)}
CLICKING = ('chest', 'hopper', 'shulker', 'beacon')
BOOKS = ('inventory', 'crafting', 'furnace')
def quarter(rng, lo, hi):
return rng.randrange(int(lo * 4), int(hi * 4)) / 4
def point(rng, left, top, width, height):
"""Mostly near the window's edges and the recipe book's area."""
pick = rng.random()
if pick < 0.5:
x = rng.choice([left, left + width, left - 147]) + quarter(rng, -3, 3)
y = quarter(rng, top - 20, top + height + 20)
elif pick < 0.8:
x = quarter(rng, left - 30, left + width + 30)
y = rng.choice([top, top + height]) + quarter(rng, -3, 3)
else:
x = quarter(rng, left - 200, left + width + 60)
y = quarter(rng, top - 40, top + height + 40)
return x, y
def cases(rng):
for _ in range(4000):
kind = rng.choice(list(SCREENS))
width, height = SCREENS[kind] or (176, 114 + 18 * rng.randint(1, 6))
left, top = rng.randrange(0, 300), rng.randrange(0, 120)
sx, sy = rng.randrange(0, width - 16), rng.randrange(0, height - 16)
case = dict(kind=kind, image=[left, top, width, height], slot=[sx, sy], events=[])
if kind in BOOKS:
case['book'] = [rng.random() < 0.7, rng.random() < 0.2]
for _ in range(rng.randrange(4, 24)):
if kind not in CLICKING:
case['events'].append(['point', *point(rng, left, top, width, height)])
continue
on_slot = rng.random() < 0.3
if on_slot:
x = quarter(rng, left + sx - 1, left + sx + 17)
y = quarter(rng, top + sy - 1, top + sy + 17)
else:
while True:
x, y = point(rng, left, top, width, height)
if not (left + sx - 1 <= x < left + sx + 17 and top + sy - 1 <= y < top + sy + 17):
break
case['events'].append([rng.choice(['press', 'release']), x, y, rng.choice([1, 1, 3]),
rng.choice([0, 0, 1, 2, 3]), rng.random() < 0.5, on_slot])
yield case
def make_cases(build):
path = build / 'cases.jsonl'
count = 0
with path.open('w') as out:
for case in cases(random.Random(0x434c4b53)):
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def main():
scope = ('The real AbstractContainerScreen.mouseClicked and mouseReleased of ContainerScreen (one to six rows), '
'HopperScreen, ShulkerBoxScreen and BeaconScreen with one menu slot, press and release of the left and right '
'buttons with the carried stack empty or not and the event Shift modifiers (left, right, both, none), '
'recording every slotClicked (slot id, menu button, ContainerInput); and hasClickedOutside of those screens, '
'MerchantScreen and the recipe book screens (InventoryScreen, CraftingScreen, FurnaceScreen) with the book '
'visible or not and its selected tab hovered or not. Drags (mouseDragged, quickCraftToSlots), double '
'clicks and keyPickItem cloning are not exercised; the menu clicks themselves are menu_click\'s.')
harness.differential(
'rust-container-screen-parity', 'VanillaContainerScreenOracle', 'container_screen_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/container_screen.rs',
lab.ROOT / 'crates/horizon-client/src/menu.rs'])
if __name__ == '__main__':
main()
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Compare the entity predicates of the variant advancements (A Complete
Catalogue, The Whole Pack, Leash all frog variants) with the pinned client: the
real EntityPredicate of each criterion, decoded from the advancement files,
tested on real wolves, cats, frogs, pigs, cows and chickens of every variant
(the variant data components Entity.get reports for minecraft:components)."""
import json
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
ADVANCEMENTS = ('complete_catalogue', 'whole_pack', 'leash_all_frog_variants')
SPECIES = ('wolf', 'cat', 'frog', 'pig', 'cow', 'chicken')
def predicates():
"""Every criterion's entity predicate, plus the components alone and
with the wrong type."""
folder = lab.LOCAL / 'horizon-client/26.3/data/minecraft/advancement/husbandry'
out = []
for name in ADVANCEMENTS:
data = json.loads((folder / f'{name}.json').read_text())
for criterion in data['criteria'].values():
predicate = criterion['conditions']['entity']['predicate']
out.append(predicate)
components = {'minecraft:components': predicate['minecraft:components']}
out.append(components)
out.append(dict(components, **{'minecraft:entity_type': 'minecraft:pig'}))
return out
def variants(species):
folder = lab.LOCAL / f'horizon-client/26.3/data/minecraft/{species}_variant'
return sorted('minecraft:' + p.stem for p in folder.glob('*.json'))
def make_cases(build):
path = build / 'cases.jsonl'
every = predicates()
rng = random.Random(0x56415249)
count = 0
with path.open('w') as out:
for species in SPECIES:
for variant in variants(species):
listed = every + [rng.choice(every) for _ in range(8)]
case = dict(type='minecraft:' + species, variant=variant, predicates=listed)
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def main():
scope = ('The real EntityPredicate of every criterion of complete_catalogue, whole_pack and '
'leash_all_frog_variants (and their minecraft:components alone, or with another entity type), decoded '
'with the registries\' ops, on entities made with EntityType.create(LOAD) given each registered variant '
'of their species through Entity.setComponent. The trigger dispatch around them is not exercised.')
harness.differential(
'rust-entity-components-parity', 'VanillaEntityComponentsOracle', 'entity_components_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/advancements.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs'])
if __name__ == '__main__':
main()
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Compare the fire charge's use sound with the pinned client: the real
FireChargeItem.playSound (lighting a campfire or candle and placing fire both
use it) on level randoms from many seeds, comparing the sound, its volume and
pitch bits, and the level random's next value (how many values it drew)."""
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def make_cases(build):
path = build / 'cases.txt'
rng = random.Random(0x46495245)
seeds = [0, 1, -1, 42, 2**63 - 1, -2**63] + [rng.randrange(-2**63, 2**63) for _ in range(20000)]
path.write_text(''.join(f'{s}\n' for s in seeds))
return path, len(seeds)
def main():
scope = ('The real private FireChargeItem.playSound on a ServerLevel stand-in with a seeded LegacyRandomSource: '
'the sound event, volume, pitch ((nextFloat - nextFloat) * 0.2 + 1) and the random afterwards. '
'FireChargeItem.useOn\'s choice between lighting and placing fire is not exercised.')
harness.differential(
'rust-fire-starter-sound-parity', 'VanillaFireStarterSoundOracle', 'fire_starter_sound_probe', make_cases,
scope, sources=[lab.ROOT / 'crates/horizon-client/src/items.rs'])
if __name__ == '__main__':
main()

Some files were not shown because too many files have changed in this diff Show More