@@ -1031,19 +1031,22 @@ pub struct ItemModels {
|
||||
}
|
||||
|
||||
impl ItemModels {
|
||||
pub fn components(&self, stack: &StackView) -> Components {
|
||||
let mut out = self
|
||||
.prototypes
|
||||
.get(&stack.item)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
/// The stack's components: its item's defaults with the stack's patch on top. A stack
|
||||
/// with no patch (most stacks a screen draws) borrows the defaults instead of copying them.
|
||||
pub fn components(&self, stack: &StackView) -> std::borrow::Cow<'_, Components> {
|
||||
static NONE: Components = BTreeMap::new();
|
||||
let prototype = self.prototypes.get(&stack.item).unwrap_or(&NONE);
|
||||
if stack.patch.is_empty() {
|
||||
return std::borrow::Cow::Borrowed(prototype);
|
||||
}
|
||||
let mut out = prototype.clone();
|
||||
for (key, value) in &stack.patch {
|
||||
match value {
|
||||
Some(v) => out.insert(key.clone(), v.clone()),
|
||||
None => out.remove(key),
|
||||
};
|
||||
}
|
||||
out
|
||||
std::borrow::Cow::Owned(out)
|
||||
}
|
||||
/// `ItemModelResolver.updateForTopItem`.
|
||||
pub fn resolve(&self, stack: &StackView, ctx: &Context, env: &dyn ItemEnv) -> ResolvedItem {
|
||||
|
||||
@@ -85,6 +85,7 @@ mod sound_engine_fixture;
|
||||
mod sound_event_fixture;
|
||||
mod spawn_rules_fixture;
|
||||
mod sprint_probe;
|
||||
mod squid_client_probe;
|
||||
mod subtitle_fixture;
|
||||
mod tab_list_fixture;
|
||||
mod team_rules_fixture;
|
||||
@@ -109,6 +110,7 @@ probes! {
|
||||
block_transform_fixture,
|
||||
breaking_fixture,
|
||||
camera_probe,
|
||||
squid_client_probe,
|
||||
creative_mining_probe,
|
||||
cushion_placement_probe,
|
||||
cauldron_fixture,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
use horizon_client::{
|
||||
Result,
|
||||
mobs::{Mob, MobTypes, aquatic},
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, BufWriter, Write},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<_> = crate::args().collect();
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
|
||||
let types = MobTypes::load(&root)?;
|
||||
let mut out = BufWriter::new(File::create(&args[2])?);
|
||||
for line in BufReader::new(File::open(&args[1])?).lines() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
let kind = Arc::new(
|
||||
types.types[&format!("minecraft:{}", row["species"].as_str().unwrap())].clone(),
|
||||
);
|
||||
let mut mob = Mob::new(1, kind, Vec3::ZERO, 0.0);
|
||||
mob.fluids.in_water = row["water"].as_bool().unwrap();
|
||||
mob.velocity = Vec3::new(
|
||||
row["x"].as_f64().unwrap(),
|
||||
row["y"].as_f64().unwrap(),
|
||||
row["z"].as_f64().unwrap(),
|
||||
);
|
||||
mob.body_yaw = row["body"].as_f64().unwrap() as f32;
|
||||
for (i, value) in row["v"].as_array().unwrap().iter().enumerate() {
|
||||
mob.anim.v[i] = value.as_f64().unwrap() as f32;
|
||||
}
|
||||
if row["reset"].as_bool().unwrap() {
|
||||
aquatic::squid_cycle_event(&mut mob);
|
||||
}
|
||||
let velocity = mob.velocity;
|
||||
aquatic::squid_client_step(&mut mob);
|
||||
assert_eq!(
|
||||
velocity, mob.velocity,
|
||||
"a remote animation must preserve packet velocity"
|
||||
);
|
||||
write!(out, "{:08x}", mob.body_yaw.to_bits())?;
|
||||
for value in &mob.anim.v[..6] {
|
||||
write!(out, " {:08x}", value.to_bits())?;
|
||||
}
|
||||
writeln!(out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1228,13 +1228,19 @@ pub fn campfire_particles<'a>(
|
||||
if r.next_float() < 0.11 {
|
||||
let count = next_int(r, 2) + 2;
|
||||
for _ in 0..count {
|
||||
make_campfire_smoke(engine, pos, signal);
|
||||
make_campfire_smoke(engine, pos, signal, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `CampfireBlock.makeParticles` (always visible, overriding the limiter).
|
||||
pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: bool) {
|
||||
/// `CampfireBlock.makeParticles` (always visible, overriding the limiter);
|
||||
/// `smoking` adds the plain smoke puff at the logs.
|
||||
pub fn make_campfire_smoke(
|
||||
engine: &mut ParticleEngine,
|
||||
pos: [i32; 3],
|
||||
signal: bool,
|
||||
smoking: bool,
|
||||
) {
|
||||
let r = engine.random();
|
||||
let sign = |r: &mut LegacyRandom| if r.next_boolean() { 1.0 } else { -1.0 };
|
||||
let dx = r.next_double() / 3.0;
|
||||
@@ -1248,6 +1254,17 @@ pub fn make_campfire_smoke(engine: &mut ParticleEngine, pos: [i32; 3], signal: b
|
||||
T::CampfireCosySmoke
|
||||
};
|
||||
engine.create(&ParticleOptions::simple(ty), [x, y, z], [0.0, 0.07, 0.0]);
|
||||
if smoking {
|
||||
let r = engine.random();
|
||||
let dx = r.next_double() / 4.0 * sign(r);
|
||||
let dz = r.next_double() / 4.0 * sign(r);
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5 + dx,
|
||||
f64::from(pos[1]) + 0.4,
|
||||
f64::from(pos[2]) + 0.5 + dz,
|
||||
];
|
||||
engine.create(&ParticleOptions::simple(T::Smoke), at, [0.0, 0.005, 0.0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -28,6 +28,9 @@ pub struct BiomeInfo {
|
||||
pub spawn_costs: HashMap<String, crate::mobs::spawn_selection::SpawnCost>,
|
||||
/// The `gameplay/creature_world_gen_spawn_probability` attribute.
|
||||
pub creature_probability: f32,
|
||||
/// The `gameplay/increased_fire_burnout` attribute (jungles, swamps, peaks,
|
||||
/// mushroom fields).
|
||||
pub increased_fire_burnout: bool,
|
||||
pub name: String,
|
||||
pub temperature: f32,
|
||||
pub downfall: f32,
|
||||
@@ -128,6 +131,9 @@ impl Biomes {
|
||||
attributes["minecraft:gameplay/creature_world_gen_spawn_probability"]
|
||||
.as_f64()
|
||||
.unwrap_or(0.1) as f32,
|
||||
increased_fire_burnout: attributes["minecraft:gameplay/increased_fire_burnout"]
|
||||
.as_bool()
|
||||
.unwrap_or(false),
|
||||
temperature,
|
||||
downfall,
|
||||
precipitation: v["has_precipitation"].as_bool().unwrap_or(true),
|
||||
|
||||
@@ -3,7 +3,12 @@
|
||||
//! (`creative-inventory.json`), a 9x5 scrolling grid and the search tab.
|
||||
use crate::{Result, items::ItemStack, ui::EditBox};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, fs, path::Path};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
path::Path,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Tab {
|
||||
@@ -40,6 +45,17 @@ pub struct Creative {
|
||||
/// The search tab's stacks, in its display order.
|
||||
search_items: Vec<ItemStack>,
|
||||
search_index: Vec<SearchEntry>,
|
||||
/// ItemPickerMenu.items: what the grid shows, filled when the tab or the
|
||||
/// search changes (selectTab, refreshSearchResults), not on every frame.
|
||||
shown: Mutex<Option<Shown>>,
|
||||
}
|
||||
/// The grid's stacks for one tab, search text and language.
|
||||
struct Shown {
|
||||
tab: usize,
|
||||
search: String,
|
||||
/// A display name, so a language change refills the search results.
|
||||
language: String,
|
||||
items: Arc<[ItemStack]>,
|
||||
}
|
||||
/// Display names from the pinned en_us language file.
|
||||
#[derive(Default)]
|
||||
@@ -291,6 +307,7 @@ impl Creative {
|
||||
},
|
||||
search_items,
|
||||
search_index,
|
||||
shown: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
/// Where a stack comes in the creative tabs (the search tab lists them
|
||||
@@ -303,6 +320,22 @@ impl Creative {
|
||||
.position(|s| s.same_item_same_components(stack))
|
||||
.or_else(|| items.iter().position(|s| s.item == stack.item))
|
||||
}
|
||||
/// The tabs without their stacks: what the screen draws of them each frame.
|
||||
pub fn tab_headers(&self) -> Vec<Tab> {
|
||||
self.tabs
|
||||
.iter()
|
||||
.map(|t| Tab {
|
||||
id: t.id.clone(),
|
||||
title: t.title.clone(),
|
||||
icon: t.icon.clone(),
|
||||
items: Vec::new(),
|
||||
top: t.top,
|
||||
column: t.column,
|
||||
search: t.search,
|
||||
inventory: t.inventory,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn tab(&self) -> &Tab {
|
||||
&self.tabs[self.selected.min(self.tabs.len() - 1)]
|
||||
}
|
||||
@@ -384,17 +417,44 @@ impl Creative {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// Items shown by the selected tab (the search tab filters by `search`).
|
||||
pub fn items(&self, names: &Names) -> Vec<ItemStack> {
|
||||
let tab = self.tab();
|
||||
if tab.search {
|
||||
return self
|
||||
.search_results(&self.search.value, names)
|
||||
/// Items shown by the selected tab (the search tab filters by `search`),
|
||||
/// worked out again only when the tab, the search or the language changed.
|
||||
pub fn items(&self, names: &Names) -> Arc<[ItemStack]> {
|
||||
let tab = self.selected.min(self.tabs.len() - 1);
|
||||
let search = if self.tab().search {
|
||||
self.search.value.as_str()
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let language = names.display_get("itemGroup.search").unwrap_or_default();
|
||||
let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(s) = shown.as_ref()
|
||||
&& s.tab == tab
|
||||
&& s.search == search
|
||||
&& s.language == language
|
||||
{
|
||||
return s.items.clone();
|
||||
}
|
||||
let items: Arc<[ItemStack]> = if self.tab().search {
|
||||
self.search_results(search, names)
|
||||
.into_iter()
|
||||
.map(|i| self.search_items[i].clone())
|
||||
.collect();
|
||||
}
|
||||
tab.items.clone()
|
||||
.collect()
|
||||
} else {
|
||||
self.tab().items.as_slice().into()
|
||||
};
|
||||
*shown = Some(Shown {
|
||||
tab,
|
||||
search: search.to_owned(),
|
||||
language,
|
||||
items: items.clone(),
|
||||
});
|
||||
items
|
||||
}
|
||||
/// Drop the shown items, so the next `items` works them out again: a
|
||||
/// reload can rename items without changing the Search label.
|
||||
pub fn forget_items(&self) {
|
||||
*self.shown.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
pub fn rows(&self, names: &Names) -> usize {
|
||||
self.items(names).len().div_ceil(9)
|
||||
|
||||
@@ -166,12 +166,23 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
|
||||
if d >= end { return 1.0; }
|
||||
return (d - start) / (end - start);
|
||||
}
|
||||
// CRUMBLING_UV_BEGIN
|
||||
fn crumbling_uv(uv: vec2<f32>, packed_origin: vec2<f32>, sprite_size: vec2<f32>, dimensions: vec2<u32>) -> vec2<f32> {
|
||||
let size = vec2<f32>(dimensions);
|
||||
// Undo stage_light's 16-bit quantization before adding local texels. Otherwise
|
||||
// different stages can fall on opposite sides of a nearest-sampling boundary.
|
||||
let origin = round(packed_origin * size);
|
||||
let extent = max(round(sprite_size * size), vec2(1.0));
|
||||
let local = min(floor(fract(uv) * extent), extent - vec2(1.0));
|
||||
return (origin + local + vec2(0.5)) / size;
|
||||
}
|
||||
// CRUMBLING_UV_END
|
||||
@fragment fn fs_entity(in: Out, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
|
||||
var uv = in.uv;
|
||||
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
|
||||
if in.overlay == 11u || in.overlay == 12u {
|
||||
// Each crack's stage sprite origin comes in its light bytes (breaking::stage_light).
|
||||
uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw;
|
||||
uv = crumbling_uv(in.uv, in.wrap, globals.crumbling_sprite.zw, textureDimensions(atlas));
|
||||
}
|
||||
var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front);
|
||||
if in.overlay == 9u || in.overlay == 10u {
|
||||
|
||||
@@ -19,6 +19,7 @@ mod books;
|
||||
mod bossbars;
|
||||
mod breezes;
|
||||
mod campfire;
|
||||
mod campfire_douse;
|
||||
mod cartography;
|
||||
mod chat;
|
||||
mod client_ambient;
|
||||
@@ -556,6 +557,11 @@ struct GameLevel<'w> {
|
||||
loot: Option<std::sync::Arc<horizon_world::loot::LootData>>,
|
||||
registry: &'static horizon_world::registry::BlockRegistry,
|
||||
rules: horizon_world::level::GameRules,
|
||||
/// `Difficulty.getId()` (peaceful 0 .. hard 3).
|
||||
difficulty: i32,
|
||||
/// The feet of the players who keep fire spreading around them: the local
|
||||
/// player and the LAN guests in this level, spectators aside.
|
||||
fire_players: Vec<[f64; 3]>,
|
||||
/// Block loot random sequences (`ServerLevel.getRandomSequence`).
|
||||
rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences,
|
||||
pending: &'w mut spill::Pending,
|
||||
@@ -565,6 +571,9 @@ struct GameLevel<'w> {
|
||||
random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections,
|
||||
/// Players with each chest open (a trapped chest's signal).
|
||||
lid_openers: &'w HashMap<(i32, i32, i32), i32>,
|
||||
/// `Level.isClientSide`: a client's copy of the level (a guest of a LAN
|
||||
/// world, a window on its server thread, a dedicated server's client).
|
||||
client_side: bool,
|
||||
}
|
||||
struct PlayerCollision {
|
||||
y: f64,
|
||||
@@ -654,6 +663,9 @@ impl GameLevel<'_> {
|
||||
}
|
||||
}
|
||||
impl LevelAccess for GameLevel<'_> {
|
||||
fn is_client_side(&self) -> bool {
|
||||
self.client_side
|
||||
}
|
||||
fn world_surface(&self, x: i32, z: i32) -> i32 {
|
||||
self.world.world_surface(x, z, |s| self.facts.is_air(s))
|
||||
}
|
||||
@@ -719,6 +731,34 @@ impl LevelAccess for GameLevel<'_> {
|
||||
fn game_rules(&self) -> horizon_world::level::GameRules {
|
||||
self.rules
|
||||
}
|
||||
fn difficulty(&self) -> i32 {
|
||||
self.difficulty
|
||||
}
|
||||
/// `ServerLevel.canSpreadFireAround`: a player (not a spectator) closer
|
||||
/// than the `fire_spread_radius_around_player` rule to the block's corner
|
||||
/// (`ChunkMap.anyPlayerCloseEnoughTo`); -1 spreads everywhere.
|
||||
fn can_spread_fire_around(&self, pos: BlockPos) -> bool {
|
||||
let radius = self.rules.fire_spread_radius_around_player;
|
||||
radius == -1
|
||||
|| self.fire_players.iter().any(|p| {
|
||||
let d = [
|
||||
p[0] - f64::from(pos.x),
|
||||
p[1] - f64::from(pos.y),
|
||||
p[2] - f64::from(pos.z),
|
||||
];
|
||||
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < f64::from(radius) * f64::from(radius)
|
||||
})
|
||||
}
|
||||
fn increased_fire_burnout(&self, pos: BlockPos) -> bool {
|
||||
self.world
|
||||
.chunks
|
||||
.get(&(pos.x >> 4, pos.z >> 4))
|
||||
.is_some_and(|chunk| {
|
||||
self.biomes
|
||||
.get(chunk.biome(pos.x, pos.y, pos.z))
|
||||
.increased_fire_burnout
|
||||
})
|
||||
}
|
||||
fn block_state(&self, pos: BlockPos) -> BlockStateId {
|
||||
self.world.block(pos.x, pos.y, pos.z)
|
||||
}
|
||||
@@ -857,7 +897,16 @@ impl LevelAccess for GameLevel<'_> {
|
||||
fn emit(&mut self, event: LevelEvent) {
|
||||
match event {
|
||||
// Block.dropResources draws its loot and spots right away.
|
||||
LevelEvent::DropResources { pos, state } => self.drop_resources_now(pos, state),
|
||||
// `popResource` only drops server-side (`!level.isClientSide`):
|
||||
// a client's moveBlocks (a piston's block event) skips it.
|
||||
LevelEvent::DropResources { pos, state } if !self.client_side => {
|
||||
self.drop_resources_now(pos, state)
|
||||
}
|
||||
LevelEvent::DropResources { .. } => {}
|
||||
// `ClientLevel.playSeededSound` plays only when the excluded
|
||||
// player is this client's own: the block's `playSound(null, ...)`
|
||||
// (a piston's move, a note) reaches it from the server instead.
|
||||
LevelEvent::Sound { .. } if self.client_side => {}
|
||||
// Block.popResource of the block's own item (tall flowers, flower beds).
|
||||
LevelEvent::BlockEvent {
|
||||
pos,
|
||||
@@ -1270,6 +1319,13 @@ struct Game<'a> {
|
||||
/// Controllers (Horizon's own).
|
||||
pad: pad::Pads,
|
||||
frames: u64,
|
||||
/// `item_level` for one frame, game time, day time and dimension.
|
||||
item_level_cache: std::cell::RefCell<
|
||||
Option<(
|
||||
(u64, i64, i64, &'static str),
|
||||
horizon_assets::item_model::LevelState,
|
||||
)>,
|
||||
>,
|
||||
/// Frames drawn with the player in the world, for `--world-frames`.
|
||||
world_frames: u64,
|
||||
fps: f32,
|
||||
@@ -2462,6 +2518,19 @@ impl Game<'_> {
|
||||
Dim::End => LevelDimension::End,
|
||||
};
|
||||
let rules = self.level_rules();
|
||||
let fire_players: Vec<[f64; 3]> = self
|
||||
.player
|
||||
.iter()
|
||||
.filter(|_| !spectator)
|
||||
.map(|p| [p.position.x, p.position.y, p.position.z])
|
||||
.chain(self.lan.iter().flat_map(|h| {
|
||||
h.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| h.hub.here(g) && !g.spectator())
|
||||
.map(|g| g.position)
|
||||
}))
|
||||
.collect();
|
||||
let blockers = Blockers {
|
||||
mobs: &self.mobs,
|
||||
armor_stands: &self.armor_stands,
|
||||
@@ -2492,12 +2561,15 @@ impl Game<'_> {
|
||||
loot: horizon_client::structure_blocks::loot_data(&self.options.resources),
|
||||
registry: self.pack.assets.registry,
|
||||
rules,
|
||||
difficulty: i32::from(self.ui.difficulty),
|
||||
fire_players,
|
||||
rand_sequences: &mut self.rand_sequences,
|
||||
pending: &mut self.pending,
|
||||
spill: &mut self.spill,
|
||||
tickets: self.tickets.levels(),
|
||||
random_tick_sections: &mut self.random_tick_sections,
|
||||
lid_openers: &self.lid_openers,
|
||||
client_side: self.remote.is_some(),
|
||||
};
|
||||
let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks);
|
||||
self.flush_spill();
|
||||
@@ -2559,14 +2631,15 @@ impl Game<'_> {
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
));
|
||||
}
|
||||
let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| {
|
||||
horizon_client::ticket_levels::Sources {
|
||||
players,
|
||||
forced: self.streaming.forced.iter().copied().collect(),
|
||||
view_distance: self.settings.render_distance.clamp(2, 32),
|
||||
simulation_distance: self.settings.simulation_distance.max(2),
|
||||
}
|
||||
});
|
||||
let sources =
|
||||
(!self.options.execution_role.is_client() || !players.is_empty()).then(|| {
|
||||
horizon_client::ticket_levels::Sources {
|
||||
players,
|
||||
forced: self.streaming.forced.iter().copied().collect(),
|
||||
view_distance: self.settings.render_distance.clamp(2, 32),
|
||||
simulation_distance: self.settings.simulation_distance.max(2),
|
||||
}
|
||||
});
|
||||
self.tickets.update(sources);
|
||||
}
|
||||
/// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are
|
||||
@@ -3561,6 +3634,10 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
if self.use_campfire_douse(hit.pos, held.as_ref())? {
|
||||
self.swing_arm();
|
||||
return Ok(true);
|
||||
}
|
||||
match self.use_respawn_anchor(hit.pos, held.as_ref())? {
|
||||
respawn_anchor::AnchorUse::Charged => {
|
||||
self.swing_arm();
|
||||
@@ -4257,8 +4334,9 @@ impl Game<'_> {
|
||||
if running {
|
||||
self.world.game_time += 1;
|
||||
if self.ui.rules.bool("advance_weather") {
|
||||
self.world.weather.tick(&mut self.world.random);
|
||||
self.world.weather.tick_timers(&mut self.world.random);
|
||||
}
|
||||
self.world.weather.tick_levels();
|
||||
self.tick_weather_effects();
|
||||
}
|
||||
if self.ticks.is_multiple_of(6000) {
|
||||
@@ -8066,6 +8144,7 @@ impl Game<'_> {
|
||||
/// (scaled coordinates, or the End portal's fixed destination).
|
||||
pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result<Vec3> {
|
||||
// Save the departing dimension's changed chunks.
|
||||
self.save.save_forced_chunks(&self.streaming.forced)?;
|
||||
self.streaming.save(&mut self.world, true);
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
|
||||
@@ -9663,8 +9742,9 @@ impl Game<'_> {
|
||||
rain.extend(snow_vertices);
|
||||
rain
|
||||
}
|
||||
/// Player.startSleepInBed: night or thunder, no monsters within 8 blocks;
|
||||
/// the bed becomes the respawn point either way.
|
||||
/// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder,
|
||||
/// and (outside creative) no monsters within 8 blocks; the bed becomes the
|
||||
/// respawn point either way.
|
||||
fn try_sleep(&mut self, pos: [i32; 3]) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
@@ -9679,22 +9759,40 @@ impl Game<'_> {
|
||||
.state(state)
|
||||
.map(|s| s.properties.clone())
|
||||
.unwrap_or_default();
|
||||
let head = if props.get("part").map(String::as_str) == Some("foot") {
|
||||
let d = facing_offset(props.get("facing").map_or("north", String::as_str));
|
||||
[pos[0] + d[0], pos[1], pos[2] + d[2]]
|
||||
// The head and the foot: the block faces from the foot to the head.
|
||||
let d = facing_offset(props.get("facing").map_or("north", String::as_str));
|
||||
let (head, foot) = if props.get("part").map(String::as_str) == Some("foot") {
|
||||
([pos[0] + d[0], pos[1], pos[2] + d[2]], pos)
|
||||
} else {
|
||||
pos
|
||||
(pos, [pos[0] - d[0], pos[1], pos[2] - d[2]])
|
||||
};
|
||||
let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2)
|
||||
+ (p.position.z - f64::from(head[2]) - 0.5).powi(2))
|
||||
.sqrt();
|
||||
if dist > 3.0 {
|
||||
// ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks
|
||||
// sideways and 2 vertically of the head or the foot.
|
||||
let reachable = |bed: [i32; 3]| {
|
||||
(p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0
|
||||
&& (p.position.y - f64::from(bed[1])).abs() <= 2.0
|
||||
&& (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0
|
||||
};
|
||||
if !reachable(head) && !reachable(foot) {
|
||||
self.message = Some((
|
||||
"You may not rest now; the bed is too far away".into(),
|
||||
Instant::now(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
// ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the
|
||||
// blocks above the head and the foot, as `in_wall` reads suffocating.
|
||||
let blocked = [head, foot].iter().any(|bed| {
|
||||
let f = self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(bed[0], bed[1] + 1, bed[2]));
|
||||
f.full_collision && f.solid_render
|
||||
});
|
||||
if blocked {
|
||||
self.message = Some(("This bed is obstructed".into(), Instant::now()));
|
||||
return;
|
||||
}
|
||||
// In reach (bedInRange), day or night: setRespawnPosition(
|
||||
// RespawnConfig(the head, the player's yaw), not forced). It replaces
|
||||
// an anchor or a spawnpoint; respawning checks the bed is still there
|
||||
@@ -9724,13 +9822,15 @@ impl Game<'_> {
|
||||
));
|
||||
return;
|
||||
}
|
||||
let monsters = self.mobs.iter().any(|m| {
|
||||
m.hostile()
|
||||
&& m.alive()
|
||||
&& (m.position.x - p.position.x).abs() < 8.0
|
||||
&& (m.position.y - p.position.y).abs() < 5.0
|
||||
&& (m.position.z - p.position.z).abs() < 8.0
|
||||
});
|
||||
// Creative players skip the monster check (`!this.isCreative()`).
|
||||
let monsters = !self.creative
|
||||
&& self.mobs.iter().any(|m| {
|
||||
m.hostile()
|
||||
&& m.alive()
|
||||
&& (m.position.x - p.position.x).abs() < 8.0
|
||||
&& (m.position.y - p.position.y).abs() < 5.0
|
||||
&& (m.position.z - p.position.z).abs() < 8.0
|
||||
});
|
||||
if monsters {
|
||||
self.message = Some((
|
||||
"You may not rest now; there are monsters nearby".into(),
|
||||
@@ -9780,14 +9880,20 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
// ServerLevel.tick: once enough of the players have slept 100 ticks,
|
||||
// skip to morning, clear the weather and wake everyone.
|
||||
// skip to morning if `advance_time` is on, wake everyone, and
|
||||
// resetWeatherCycle if `advance_weather` is on and it is raining.
|
||||
if self.enough_slept() {
|
||||
let t = self.world.day_time;
|
||||
self.world.day_time = t + 24000 - t.rem_euclid(24000);
|
||||
self.world.weather.raining = false;
|
||||
self.world.weather.thundering = false;
|
||||
self.world.weather.rain_time = 0;
|
||||
self.world.weather.thunder_time = 0;
|
||||
if self.ui.rules.bool("advance_time") {
|
||||
let t = self.world.day_time;
|
||||
self.world.day_time = t + 24000 - t.rem_euclid(24000);
|
||||
}
|
||||
// Level.isRaining: the rain level is above 0.2.
|
||||
if self.ui.rules.bool("advance_weather") && self.world.weather.levels(1.0).0 > 0.2 {
|
||||
self.world.weather.raining = false;
|
||||
self.world.weather.thundering = false;
|
||||
self.world.weather.rain_time = 0;
|
||||
self.world.weather.thunder_time = 0;
|
||||
}
|
||||
if self.sleeping.is_some() {
|
||||
self.wake_up();
|
||||
}
|
||||
@@ -9815,8 +9921,9 @@ impl Game<'_> {
|
||||
fn draw_creative(&mut self, batch: &mut HudBatch) {
|
||||
let (ox, oy) = Self::creative_origin(batch);
|
||||
let selected = self.creative_screen.selected;
|
||||
let tabs = self.creative_screen.tabs.clone();
|
||||
let tab = self.creative_screen.tab().clone();
|
||||
// Only what is drawn of the tabs: their stacks stay where they are.
|
||||
let tabs = self.creative_screen.tab_headers();
|
||||
let tab = tabs[selected.min(tabs.len() - 1)].clone();
|
||||
let tab_sprite = |t: &horizon_client::creative::Tab, on: bool| {
|
||||
format!(
|
||||
"gui/sprites/container/creative_inventory/tab_{}_{}_{}",
|
||||
@@ -10204,6 +10311,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// Save the level in place: its changed chunks, its entities and its raids.
|
||||
fn save_level(&mut self, wait: bool) -> Result<()> {
|
||||
self.save.save_forced_chunks(&self.streaming.forced)?;
|
||||
self.streaming.save(&mut self.world, wait);
|
||||
let keys: Vec<_> = self.world.modified.drain().collect();
|
||||
let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k)));
|
||||
@@ -11594,16 +11702,17 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
self.extras_mouse(button, pressed);
|
||||
self.mod_mouse_key(button, pressed);
|
||||
match self.settings.keys.translate_mouse(button) {
|
||||
Some(Err(b)) => self.play_mouse(b, pressed)?,
|
||||
Some(Ok(k)) if pressed => {
|
||||
self.keys.insert(k);
|
||||
self.key_pressed(k)?;
|
||||
for mapped in self.settings.keys.translate_mouse_all(button) {
|
||||
match mapped {
|
||||
Err(b) => self.play_mouse(b, pressed)?,
|
||||
Ok(k) if pressed => {
|
||||
self.keys.insert(k);
|
||||
self.key_pressed(k)?;
|
||||
}
|
||||
Ok(k) => {
|
||||
self.keys.remove(&k);
|
||||
}
|
||||
}
|
||||
Some(Ok(k)) => {
|
||||
self.keys.remove(&k);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Screen::Inventory | Screen::Creative
|
||||
@@ -11851,18 +11960,24 @@ impl ApplicationHandler for Game<'_> {
|
||||
{
|
||||
self.smooth_camera = !self.smooth_camera;
|
||||
}
|
||||
// Key binds: act as the default key of the bound mapping.
|
||||
let key = match self.settings.keys.translate(key) {
|
||||
Some(Ok(k)) => k,
|
||||
Some(Err(button)) => {
|
||||
if self.screen == Screen::Playing && !event.repeat {
|
||||
self.play_mouse(button, event.state == ElementState::Pressed)?;
|
||||
// Key binds: act as the default key of every mapping bound
|
||||
// to it (KeyMapping.set drives them all).
|
||||
for mapped in self.settings.keys.translate_all(key) {
|
||||
match mapped {
|
||||
Ok(k) => {
|
||||
self.mapped_key(
|
||||
k,
|
||||
event.state == ElementState::Pressed,
|
||||
event.repeat,
|
||||
)?;
|
||||
}
|
||||
Err(button) => {
|
||||
if self.screen == Screen::Playing && !event.repeat {
|
||||
self.play_mouse(button, event.state == ElementState::Pressed)?;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
None => return Ok(()),
|
||||
};
|
||||
self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?;
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
self.observe_fullscreen();
|
||||
@@ -12276,6 +12391,7 @@ impl<'a> Game<'a> {
|
||||
last_input: now,
|
||||
pad: Default::default(),
|
||||
frames: 0,
|
||||
item_level_cache: Default::default(),
|
||||
world_frames: 0,
|
||||
fps: 0.0,
|
||||
fps_frames: 0,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! `CampfireBlock.useItemOn`: an item in `#minecraft:douses_campfires` (the
|
||||
//! shovels) put on a lit campfire puts it out.
|
||||
use super::Game;
|
||||
use horizon_client::{Result, animate_tick::make_campfire_smoke, items::ItemStack};
|
||||
|
||||
impl Game<'_> {
|
||||
/// `CampfireBlock.useItemOn` with `held` in the hand that acts, the block
|
||||
/// at `pos` clicked: true when it doused a lit campfire (SUCCESS).
|
||||
pub(super) fn use_campfire_douse(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
held: Option<&ItemStack>,
|
||||
) -> Result<bool> {
|
||||
let Some(tool) = held.filter(|s| {
|
||||
self.res
|
||||
.items()
|
||||
.item_tags
|
||||
.get("minecraft:douses_campfires")
|
||||
.is_some_and(|members| members.contains(&*s.item))
|
||||
}) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let registry = self.pack.assets.registry;
|
||||
let Some(mut state) = registry
|
||||
.state(self.world.block(pos[0], pos[1], pos[2]))
|
||||
.filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire"))
|
||||
.filter(|s| s.properties.get("lit").map(String::as_str) == Some("true"))
|
||||
.cloned()
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
// Level event 1009 (SOUND_EXTINGUISH_FIRE) goes to every player.
|
||||
self.level_event_at(1009, pos, 0);
|
||||
// CampfireBlock.douse: the acting client's own smoke (twenty puffs),
|
||||
// then the block change game event from the player.
|
||||
if self.lan_acting.is_none() {
|
||||
let signal = state.properties.get("signal_fire").map(String::as_str) == Some("true");
|
||||
for _ in 0..20 {
|
||||
make_campfire_smoke(&mut self.particles, pos, signal, true);
|
||||
}
|
||||
}
|
||||
self.post_block_game_event("minecraft:block_change", pos, self.sculk_actor(), None);
|
||||
state.properties.insert("lit".into(), "false".into());
|
||||
if let Ok(unlit) = registry.resolve(&state) {
|
||||
self.level_set(pos, unlit)?;
|
||||
}
|
||||
let used = tool.clone();
|
||||
self.damage_held(1);
|
||||
// ServerPlayerGameMode.useItemOn: the action was consumed.
|
||||
self.trigger_block("minecraft:item_used_on_block", pos, &used);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
@@ -782,6 +782,7 @@ impl Game<'_> {
|
||||
max_snow_accumulation_height: r.int("max_snow_accumulation_height"),
|
||||
spawn_mobs: r.bool("spawn_mobs"),
|
||||
spawn_monsters: r.bool("spawn_monsters"),
|
||||
fire_spread_radius_around_player: r.int("fire_spread_radius_around_player"),
|
||||
}
|
||||
}
|
||||
/// Apply rules mirrored in other state (natural regeneration, difficulty).
|
||||
|
||||
@@ -1885,11 +1885,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, new)) = horizon_client::save::decode_block_entity(&tag) else {
|
||||
let Some((_, mut new)) = horizon_client::save::decode_block_entity(&tag) else {
|
||||
return false;
|
||||
};
|
||||
let rolled = self.take_loot_table(key, &tag, &mut new);
|
||||
let after = horizon_client::save::encode_block_entity(key, &new, &name);
|
||||
if after == before {
|
||||
if after == before && !rolled {
|
||||
return false;
|
||||
}
|
||||
self.world.block_entities.insert(key, new);
|
||||
@@ -1897,6 +1898,79 @@ impl Game<'_> {
|
||||
let _ = self.world.set(pos[0], pos[1], pos[2], state);
|
||||
true
|
||||
}
|
||||
/// RandomizableContainer.tryLoadLootTable for a tag a command gives a
|
||||
/// container (`setblock`, `data`): an empty container with a `LootTable`
|
||||
/// is rolled now, as a loaded chunk's are (`save::roll_loaded_loot`), and
|
||||
/// the roll is kept with its chunk, so that the container saves, and
|
||||
/// `data get` shows, its table and seed until its items change. A tag
|
||||
/// without one drops what the container had. True when it had a table.
|
||||
pub(super) fn take_loot_table(
|
||||
&mut self,
|
||||
key: (i32, i32, i32),
|
||||
tag: &horizon_world::nbt::Tag,
|
||||
entity: &mut horizon_client::containers::BlockEntity,
|
||||
) -> bool {
|
||||
use horizon_client::{containers::BlockEntity, save, structure_blocks};
|
||||
let table = save::text(tag.get("LootTable"));
|
||||
let rolled = match (table, entity) {
|
||||
(Some(table), BlockEntity::Chest(slots)) if slots.iter().all(Option::is_none) => {
|
||||
let loot = structure_blocks::loot_data(&self.options.resources);
|
||||
let at = Vec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
|
||||
let biome = self.biome_name_at(at).unwrap_or_default();
|
||||
Some(structure_blocks::roll_container(
|
||||
slots,
|
||||
loot.as_deref(),
|
||||
table,
|
||||
structure_blocks::loot_seed(tag),
|
||||
key,
|
||||
&biome,
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let Some(chunk) = self.world.chunks.get_mut(&(key.0 >> 4, key.2 >> 4)) else {
|
||||
return false;
|
||||
};
|
||||
let held = |c: &horizon_client::chunk::Chunk| {
|
||||
c.saved
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.rolled_loot.iter().any(|r| r.pos == key))
|
||||
};
|
||||
if rolled.is_none() && !held(chunk) {
|
||||
return false;
|
||||
}
|
||||
let chunk = std::sync::Arc::make_mut(chunk);
|
||||
let mut extras = chunk
|
||||
.saved
|
||||
.take()
|
||||
.map(std::sync::Arc::unwrap_or_clone)
|
||||
.unwrap_or_default();
|
||||
extras.rolled_loot.retain(|r| r.pos != key);
|
||||
let taken = rolled.is_some();
|
||||
extras.rolled_loot.extend(rolled);
|
||||
chunk.saved = Some(std::sync::Arc::new(extras));
|
||||
taken
|
||||
}
|
||||
/// The loot table and seed a container still holding its roll saves
|
||||
/// (`RolledLoot::restore`), in place of its items.
|
||||
pub(super) fn restore_loot_table(
|
||||
&self,
|
||||
key: (i32, i32, i32),
|
||||
tag: &mut horizon_world::nbt::Tag,
|
||||
) {
|
||||
let horizon_world::nbt::Tag::Compound(map) = tag else {
|
||||
return;
|
||||
};
|
||||
let rolled = self
|
||||
.world
|
||||
.chunks
|
||||
.get(&(key.0 >> 4, key.2 >> 4))
|
||||
.and_then(|c| c.saved.as_ref())
|
||||
.and_then(|s| s.rolled_loot.iter().find(|r| r.pos == key));
|
||||
if let Some(r) = rolled {
|
||||
r.restore(map);
|
||||
}
|
||||
}
|
||||
fn cmd_fill(&mut self, ctx: &Context) -> R<i32> {
|
||||
let a = self.block_pos_arg(ctx, "from")?;
|
||||
let b = self.block_pos_arg(ctx, "to")?;
|
||||
|
||||
@@ -286,6 +286,7 @@ impl Game<'_> {
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
c.remove(&"keepPacked".into());
|
||||
}
|
||||
self.restore_loot_table(key, &mut tag);
|
||||
Ok(tag)
|
||||
}
|
||||
DataRef::Storage(id) => Ok(self.score.storage.get(id)),
|
||||
@@ -296,7 +297,8 @@ impl Game<'_> {
|
||||
DataRef::Entity(t) => self.apply_entity_nbt(*t, tag),
|
||||
DataRef::Block(p) => {
|
||||
let key = (p[0], p[1], p[2]);
|
||||
if let Some((_, new)) = save::decode_block_entity(&tag) {
|
||||
if let Some((_, mut new)) = save::decode_block_entity(&tag) {
|
||||
self.take_loot_table(key, &tag, &mut new);
|
||||
self.world.block_entities.insert(key, new);
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
// Redraw what shows the block entity (signs, banners).
|
||||
|
||||
@@ -841,6 +841,7 @@ impl Game<'_> {
|
||||
pub(super) fn handle_mob_events(&mut self, events: Vec<MobEvent>) -> Result<()> {
|
||||
for e in events {
|
||||
match e {
|
||||
MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at),
|
||||
MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at),
|
||||
MobEvent::Sound(name, at, volume, pitch)
|
||||
| MobEvent::LocalSound(name, at, volume, pitch) => {
|
||||
@@ -1546,7 +1547,10 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
self.hurt_armor(amount);
|
||||
self.thorns(from);
|
||||
// The thorns hurt the entity that caused the hit, if there is one.
|
||||
if let Some(a) = attacker.or(owner) {
|
||||
self.thorns(a);
|
||||
}
|
||||
}
|
||||
if raised {
|
||||
self.after_block(outcome, amount, attacker, projectile);
|
||||
|
||||
@@ -725,6 +725,11 @@ impl Game<'_> {
|
||||
match self.world.block_entities.get_mut(&p) {
|
||||
Some(BlockEntity::Jukebox(j)) => j.record = stack,
|
||||
Some(BlockEntity::Lectern(l)) => l.book = stack,
|
||||
Some(BlockEntity::Campfire(c)) => {
|
||||
if let Some(cell) = c.items.get_mut(slot) {
|
||||
*cell = stack;
|
||||
}
|
||||
}
|
||||
Some(e) => {
|
||||
if let Some(cell) = e.slots_mut().get_mut(slot) {
|
||||
*cell = stack;
|
||||
|
||||
@@ -1687,10 +1687,12 @@ impl Game<'_> {
|
||||
.play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch);
|
||||
}
|
||||
}
|
||||
// checkCrystals: heal 1 every 10 ticks from the nearest crystal within 32.
|
||||
// checkCrystals: heal 1 every 10 ticks from the nearest crystal, found
|
||||
// among those touching the dragon's box grown by 32.
|
||||
let d = self.dragon.as_mut().expect("dragon");
|
||||
if d.nearest_crystal.is_some() && d.ticks % 10 == 0 && d.health < MAX_HEALTH {
|
||||
d.health += 1.0;
|
||||
// LivingEntity.setHealth clamps to the maximum.
|
||||
d.health = (d.health + 1.0).min(MAX_HEALTH);
|
||||
}
|
||||
if d.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
let p = d.position;
|
||||
@@ -3173,16 +3175,24 @@ impl Game<'_> {
|
||||
let _ = self.activate_exit_portal();
|
||||
self.fight.dirty = true;
|
||||
}
|
||||
/// `EnderDragon.checkCrystals`' search: the nearest crystal within 32
|
||||
/// blocks on each axis.
|
||||
/// `EnderDragon.checkCrystals`' search: the nearest crystal whose box
|
||||
/// meets the dragon's box grown by 32.
|
||||
fn nearest_crystal_to(&self, p: Vec3) -> Option<usize> {
|
||||
// The dragon's 16 by 8 box.
|
||||
let reach = Aabb::new(
|
||||
Vec3::new(p.x - 8.0, p.y, p.z - 8.0),
|
||||
Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0),
|
||||
)
|
||||
.inflate(Vec3::new(32.0, 32.0, 32.0));
|
||||
self.crystals
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| {
|
||||
(c.position.x - p.x).abs() <= 32.0
|
||||
&& (c.position.y - p.y).abs() <= 32.0
|
||||
&& (c.position.z - p.z).abs() <= 32.0
|
||||
// An end crystal's 2 by 2 box.
|
||||
reach.intersects(Aabb::new(
|
||||
Vec3::new(c.position.x - 1.0, c.position.y, c.position.z - 1.0),
|
||||
Vec3::new(c.position.x + 1.0, c.position.y + 2.0, c.position.z + 1.0),
|
||||
))
|
||||
})
|
||||
.min_by(|a, b| {
|
||||
let da = (a.1.position.x - p.x).powi(2)
|
||||
|
||||
@@ -255,23 +255,26 @@ impl Game<'_> {
|
||||
let _ = self.wind_burst(feet, radius, knockback, false, false);
|
||||
}
|
||||
}
|
||||
/// Thorns on worn armor when a mob at `from` hits the player.
|
||||
pub(super) fn thorns(&mut self, from: [f64; 3]) {
|
||||
let attacker = self
|
||||
.mobs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, m)| m.alive())
|
||||
.min_by(|a, b| {
|
||||
let d = |m: &horizon_client::mobs::Mob| {
|
||||
(m.position.x - from[0]).powi(2)
|
||||
+ (m.position.y - from[1]).powi(2)
|
||||
+ (m.position.z - from[2]).powi(2)
|
||||
};
|
||||
d(a.1).total_cmp(&d(b.1))
|
||||
})
|
||||
.map(|(i, _)| i);
|
||||
let Some(attacker) = attacker else { return };
|
||||
/// Thorns on worn armor when the mob `attacker` hits the player: the
|
||||
/// `affected: attacker` effect of `Enchantment.doPostAttack` hurts the
|
||||
/// entity that caused the hit.
|
||||
pub(super) fn thorns(&mut self, attacker: u32) {
|
||||
let Some(index) = self.mobs.iter().position(|m| m.id == attacker && m.alive()) else {
|
||||
return;
|
||||
};
|
||||
for damage in self.thorns_damage() {
|
||||
let m = &mut self.mobs[index];
|
||||
m.hurt(damage, None, &mut self.world.random);
|
||||
let center = [m.position.x, m.position.y, m.position.z];
|
||||
self.audio
|
||||
.play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
/// The victim's side of thorns: for each worn piece whose chance comes up,
|
||||
/// the damage to deal the attacker (`DamageEntity` min 1, max 5) and the
|
||||
/// piece's wear (`ChangeItemDamage` 2).
|
||||
pub(super) fn thorns_damage(&mut self) -> Vec<f32> {
|
||||
let mut hits = Vec::new();
|
||||
for slot in 0..4 {
|
||||
let Some(stack) = self.armor[slot].clone() else {
|
||||
continue;
|
||||
@@ -299,15 +302,7 @@ impl Game<'_> {
|
||||
if !ok {
|
||||
continue;
|
||||
}
|
||||
// DamageEntity(min 1, max 5) and ChangeItemDamage(2).
|
||||
let damage = 1.0 + self.world.random.next_float() * 4.0;
|
||||
let center = {
|
||||
let m = &mut self.mobs[attacker];
|
||||
m.hurt(damage, None, &mut self.world.random);
|
||||
[m.position.x, m.position.y, m.position.z]
|
||||
};
|
||||
self.audio
|
||||
.play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0);
|
||||
hits.push(1.0 + self.world.random.next_float() * 4.0);
|
||||
if let Some(s) = self.armor[slot].as_mut() {
|
||||
s.damage += 2;
|
||||
if self
|
||||
@@ -320,6 +315,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
/// `ExperienceOrb.repairPlayerItems`: returns the experience left over.
|
||||
pub(super) fn mending(&mut self, amount: u32) -> u32 {
|
||||
|
||||
@@ -196,13 +196,31 @@ impl Game<'_> {
|
||||
skins: &self.skin_downloads,
|
||||
}
|
||||
}
|
||||
/// The client level as item models read it.
|
||||
/// The client level as item models read it: worked out once a frame (a
|
||||
/// screen of items read the same level, its sky sampled once).
|
||||
pub(super) fn item_level(&self) -> LevelState {
|
||||
let dimension = match self.dim {
|
||||
Dim::Overworld => "minecraft:overworld",
|
||||
Dim::Nether => "minecraft:the_nether",
|
||||
Dim::End => "minecraft:the_end",
|
||||
};
|
||||
let key = (
|
||||
self.frames,
|
||||
self.world.game_time,
|
||||
self.world.day_time,
|
||||
dimension,
|
||||
);
|
||||
let mut cached = self.item_level_cache.borrow_mut();
|
||||
if let Some((at, level)) = cached.as_ref()
|
||||
&& *at == key
|
||||
{
|
||||
return level.clone();
|
||||
}
|
||||
let level = self.level_state_now(dimension);
|
||||
*cached = Some((key, level.clone()));
|
||||
level
|
||||
}
|
||||
fn level_state_now(&self, dimension: &'static str) -> LevelState {
|
||||
let sky = self
|
||||
.dim_environment()
|
||||
.sample(self.world.day_time, None, None);
|
||||
|
||||
@@ -944,6 +944,13 @@ impl Game<'_> {
|
||||
for m in &mut self.mobs {
|
||||
m.needs_sync = false;
|
||||
}
|
||||
// `runBlockEvents`' broadcast precedes the tick's block changes
|
||||
// (`ChunkHolder.broadcastChanges` in `tick_level` below): the
|
||||
// guest re-runs a piston's `triggerEvent` while its level still
|
||||
// has the blocks as they were before the move.
|
||||
for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) {
|
||||
host.hub.block_event(pos, b0, b1, state);
|
||||
}
|
||||
let entities = states.as_slice();
|
||||
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
|
||||
let events = {
|
||||
@@ -1177,17 +1184,29 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
for e in events {
|
||||
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
|
||||
// The acting guest does not predict the egg's teleport
|
||||
// particles, bone meal's growth, or anvil result sounds
|
||||
// (these levelEvent calls name no excluded player).
|
||||
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
|
||||
None
|
||||
} else {
|
||||
self.lan_acting
|
||||
};
|
||||
self.lan_events
|
||||
.push((*id, [pos.x, pos.y, pos.z], *data, except));
|
||||
match e {
|
||||
horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => {
|
||||
// The acting guest does not predict the egg's teleport
|
||||
// particles, bone meal's growth, or anvil result sounds
|
||||
// (these levelEvent calls name no excluded player).
|
||||
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
|
||||
None
|
||||
} else {
|
||||
self.lan_acting
|
||||
};
|
||||
self.lan_events
|
||||
.push((*id, [pos.x, pos.y, pos.z], *data, except));
|
||||
}
|
||||
// `ServerLevel.runBlockEvents` broadcasts a handled block
|
||||
// event (`ClientboundBlockEventPacket`): the guest re-runs
|
||||
// the block's `triggerEvent` — a piston's `moveBlocks` is
|
||||
// what animates the move there. `state` is the block the
|
||||
// event named, read before it ran (the packet's `block`).
|
||||
horizon_world::level::LevelEvent::BlockEntityEvent { pos, state, a, b } => {
|
||||
self.lan_block_events
|
||||
.push(([pos.x, pos.y, pos.z], *a, *b, state.0));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,14 +245,18 @@ impl Game<'_> {
|
||||
if hurt && strength > 0.0 {
|
||||
g.knock_back_player(f64::from(strength), xd, zd);
|
||||
}
|
||||
hurt
|
||||
// The victim's thorns, dealt to the attacker below.
|
||||
let thorns = if hurt { g.thorns_damage() } else { Vec::new() };
|
||||
(hurt, thorns)
|
||||
};
|
||||
let hurt = self.ui.rules.bool("pvp")
|
||||
&& harm
|
||||
&& match victim {
|
||||
let (hurt, thorns) = if self.ui.rules.bool("pvp") && harm {
|
||||
match victim {
|
||||
Victim::Host => land(self),
|
||||
Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false),
|
||||
};
|
||||
Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or_default(),
|
||||
}
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
if hurt && s.crit {
|
||||
let target = match victim {
|
||||
Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)),
|
||||
@@ -272,6 +276,15 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
// `Enchantment.doPostAttack`: thorns hurt the attacking player.
|
||||
for damage in thorns {
|
||||
match s.attacker {
|
||||
None => self.hurt_player_by("minecraft:thorns", damage),
|
||||
Some(conn) => {
|
||||
self.guest_hit_by(host, conn, |g| g.hurt_player_by("minecraft:thorns", damage));
|
||||
}
|
||||
}
|
||||
}
|
||||
let sound = match (hurt, s.crit, s.scale > 0.9) {
|
||||
(false, ..) => "minecraft:entity.player.attack.nodamage",
|
||||
(true, true, _) => "minecraft:entity.player.attack.crit",
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! The game's tick code reads one level: the one in place, held in `Game`'s
|
||||
//! own fields (the world, its streaming and save, block ticks, entities).
|
||||
//! A server (the dedicated server and single player's server thread) keeps
|
||||
//! the other dimensions' levels here and ticks each one that has players by
|
||||
//! swapping it into place (`enter_level`), the way `as_guest` swaps a player
|
||||
//! the other dimensions' levels here and ticks each one with players or forced
|
||||
//! chunks by swapping it into place (`enter_level`), the way `as_guest` swaps a player
|
||||
//! in, so the tick code runs unchanged, one level at a time. The in-frame
|
||||
//! game holds one level, which follows its player (`enter_dimension`).
|
||||
//!
|
||||
@@ -293,8 +293,8 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
/// One server tick (`MinecraftServer.tickServer`): each level with
|
||||
/// players in turn (`tickChildren`), its chunks streamed and loaded and
|
||||
/// its world ticked. The first pass reads the network and runs the
|
||||
/// players or forced chunks in turn (`tickChildren`), its chunks streamed
|
||||
/// and loaded and its world ticked. The first pass reads the network and runs the
|
||||
/// tick's shared parts (the clock, the weather, functions, the autosave);
|
||||
/// the next ones only their level. While `paused`, only the connections
|
||||
/// run.
|
||||
@@ -396,7 +396,7 @@ impl Game<'_> {
|
||||
|
||||
/// The levels this server tick runs, in `MinecraftServer.levels` order
|
||||
/// (the Overworld, the Nether, the End): every level with a player in
|
||||
/// it or a `/pregen` task, or the Overworld while nobody is online.
|
||||
/// it, forced chunks or a `/pregen` task, or the Overworld while idle.
|
||||
pub(super) fn levels_to_tick(&self) -> Vec<Dim> {
|
||||
let guests = self
|
||||
.lan
|
||||
@@ -405,7 +405,17 @@ impl Game<'_> {
|
||||
let mut dims: Vec<Dim> = [Dim::Overworld, Dim::Nether, Dim::End]
|
||||
.into_iter()
|
||||
.filter(|d| {
|
||||
guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d)
|
||||
let forced = if *d == self.dim {
|
||||
!self.streaming.forced.is_empty()
|
||||
} else {
|
||||
self.levels
|
||||
.parked
|
||||
.get(d)
|
||||
.is_some_and(|p| !p.streaming.forced.is_empty())
|
||||
};
|
||||
guests.iter().any(|g| g.dimension == d.id())
|
||||
|| forced
|
||||
|| self.pregen_level() == Some(*d)
|
||||
})
|
||||
.collect();
|
||||
if dims.is_empty() {
|
||||
|
||||
@@ -162,11 +162,9 @@ impl Game<'_> {
|
||||
converted: Vec::new(),
|
||||
});
|
||||
}
|
||||
/// `spawnFire`: fire at the strike point and `extra` random neighbours.
|
||||
/// `spawnFire`: fire at the strike point and `extra` random neighbours,
|
||||
/// wherever `BaseFireBlock.getState` fire can survive.
|
||||
fn bolt_fire(&mut self, at: [f64; 3], extra: i32) {
|
||||
if self.ui.difficulty < 2 {
|
||||
return;
|
||||
}
|
||||
let base = [
|
||||
at[0].floor() as i32,
|
||||
at[1].floor() as i32,
|
||||
@@ -183,18 +181,13 @@ impl Game<'_> {
|
||||
if !self.res.facts().is_air(state) {
|
||||
continue;
|
||||
}
|
||||
// BaseFireBlock.getState: soul fire on soul soil and sand.
|
||||
let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2]));
|
||||
let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") {
|
||||
"minecraft:soul_fire"
|
||||
} else {
|
||||
"minecraft:fire"
|
||||
};
|
||||
// FireBlock.canSurvive: a sturdy floor (flammable neighbours aside).
|
||||
if below.sturdy_full >> 1 & 1 == 0 {
|
||||
continue;
|
||||
}
|
||||
if let Some(fire) = self.pack.assets.registry.default_state(name) {
|
||||
// BaseFireBlock.getState and FireBlock/SoulFireBlock.canSurvive.
|
||||
let at = BlockPos::new(p[0], p[1], p[2]);
|
||||
let fire = self.with_level(|b, level, ticks| {
|
||||
let fire = b.fire_state_for(level, ticks, at);
|
||||
b.can_survive(level, ticks, at, fire).then_some(fire)
|
||||
});
|
||||
if let Some(fire) = fire {
|
||||
let _ = self.level_set(p, fire);
|
||||
}
|
||||
}
|
||||
@@ -219,7 +212,10 @@ impl Game<'_> {
|
||||
pitch,
|
||||
);
|
||||
if !b.visual_only {
|
||||
self.bolt_fire(b.at, 4);
|
||||
// Only Normal and Hard start fires with the strike itself.
|
||||
if self.ui.difficulty >= 2 {
|
||||
self.bolt_fire(b.at, 4);
|
||||
}
|
||||
self.strike_rod(b.at);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,8 +159,10 @@ impl Containers<'_> {
|
||||
});
|
||||
}
|
||||
let entity = self.world.block_entities.get(&pos)?;
|
||||
// A beehive keeps bees, not items: it is no `Container`.
|
||||
if matches!(entity, BlockEntity::Beehive(_)) {
|
||||
// A beehive keeps bees, not items, and a campfire cooks its own: neither
|
||||
// is a `Container` (HopperBlockEntity.getContainerAt), so a dropper drops
|
||||
// in front of them and a hopper leaves them alone.
|
||||
if matches!(entity, BlockEntity::Beehive(_) | BlockEntity::Campfire(_)) {
|
||||
return None;
|
||||
}
|
||||
let kind = match (entity, name) {
|
||||
|
||||
@@ -257,6 +257,7 @@ impl Game<'_> {
|
||||
lang::set(lang::Language::load(&[&root], code));
|
||||
self.refresh_remote_language();
|
||||
self.ui.chat.rescale(&self.gui.atlas);
|
||||
self.creative_screen.forget_items();
|
||||
}
|
||||
/// Settings that Horizon applies beyond render distance, volume and GUI scale.
|
||||
pub(super) fn apply_ui_settings(&mut self) {
|
||||
|
||||
@@ -163,7 +163,7 @@ impl Game<'_> {
|
||||
self.pack.context.biomes.clone(),
|
||||
self.pack.context.light.clone(),
|
||||
)?;
|
||||
// Keep the working GPU resources, but release its exclusive window surface.
|
||||
// Keep the working GPU resources, and hand its window surface over.
|
||||
if let Some(renderer) = &mut self.renderer {
|
||||
renderer.release_surface();
|
||||
}
|
||||
@@ -221,6 +221,8 @@ impl Game<'_> {
|
||||
self.apply_ui_settings();
|
||||
}
|
||||
self.ui.chat.rescale(&self.gui.atlas);
|
||||
// The creative screen survives the reload; item names may not.
|
||||
self.creative_screen.forget_items();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1697,19 +1697,30 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
C::BlockChangedAck(p) => self.end_predictions(p.sequence),
|
||||
// ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids,
|
||||
// shulker boxes, bells) when the block is still the one it names.
|
||||
// Level.blockEvent on the client level: the block's triggerEvent
|
||||
// runs on the client's copy of whatever is at pos (a piston's
|
||||
// moveBlocks builds the moving block entities it animates, a note
|
||||
// block plays); what it doesn't handle reaches the client copy of
|
||||
// the block entity (chest lids, shulker boxes).
|
||||
C::BlockEvent(p) => {
|
||||
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
|
||||
let block = &self.res.facts().get(state).name;
|
||||
let named = self.remote.as_ref().and_then(|r| {
|
||||
r.builtin
|
||||
.get("minecraft:block")?
|
||||
.name(p.block)
|
||||
.map(str::to_owned)
|
||||
let pos = horizon_core::position::BlockPos::new(p.pos[0], p.pos[1], p.pos[2]);
|
||||
let triggered = self.with_level(|b, level, ticks| {
|
||||
b.client_block_event(level, ticks, pos, i32::from(p.b0), i32::from(p.b1))
|
||||
});
|
||||
if named.as_deref() == Some(&**block) {
|
||||
self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1));
|
||||
self.sync_moving_pistons();
|
||||
self.process_level_events()?;
|
||||
if !triggered {
|
||||
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
|
||||
let block = &self.res.facts().get(state).name;
|
||||
let named = self.remote.as_ref().and_then(|r| {
|
||||
r.builtin
|
||||
.get("minecraft:block")?
|
||||
.name(p.block)
|
||||
.map(str::to_owned)
|
||||
});
|
||||
if named.as_deref() == Some(&**block) {
|
||||
self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1));
|
||||
}
|
||||
}
|
||||
}
|
||||
// ClientLevel.levelEvent: LevelEventHandler, as this client's own
|
||||
@@ -2108,6 +2119,11 @@ impl Game<'_> {
|
||||
{
|
||||
horizon_client::mobs::rabbit::hop_event(m);
|
||||
}
|
||||
if p.event == 19
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
|
||||
{
|
||||
horizon_client::mobs::aquatic::squid_cycle_event(m);
|
||||
}
|
||||
// EntityEvent.DEATH: start the death animation.
|
||||
if p.event == 3
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
|
||||
@@ -2982,7 +2998,10 @@ impl Game<'_> {
|
||||
fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) {
|
||||
self.remote_dragon_motion(id, velocity);
|
||||
let v = Vec3::new(velocity[0], velocity[1], velocity[2]);
|
||||
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
|
||||
// Squid.aiStep derives its body pitch and roll from network motion.
|
||||
m.velocity = v;
|
||||
} else if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
|
||||
d.velocity = v;
|
||||
} else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) {
|
||||
f.velocity = v;
|
||||
@@ -3154,8 +3173,14 @@ impl Game<'_> {
|
||||
self.border.tick();
|
||||
self.player_border();
|
||||
self.tick_remote_entities(running);
|
||||
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells.
|
||||
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells,
|
||||
// and the moving pistons a block event's client-side moveBlocks made
|
||||
// (their progress advances between the server's block updates).
|
||||
self.tick_block_entity_anims();
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.client_tick_block_entities(level, ticks);
|
||||
});
|
||||
self.sync_moving_pistons();
|
||||
self.tick_hand();
|
||||
self.tick_particles();
|
||||
self.tick_client_ambient();
|
||||
@@ -3546,6 +3571,8 @@ impl Game<'_> {
|
||||
} else if m.alive() {
|
||||
m.body_rotation_tick();
|
||||
}
|
||||
// Squid.aiStep follows LivingEntity's interpolation and head turn.
|
||||
horizon_client::mobs::aquatic::squid_client_step(m);
|
||||
// WalkAnimationState.update from the horizontal distance moved.
|
||||
let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z);
|
||||
let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0);
|
||||
|
||||
@@ -179,6 +179,7 @@ impl Game<'_> {
|
||||
if keys.is_empty() {
|
||||
self.prune_entity_memory();
|
||||
self.save_raids();
|
||||
self.save.save_forced_chunks(&self.streaming.forced)?;
|
||||
self.save_game_metadata()?;
|
||||
save.stage = Stage::Writes;
|
||||
}
|
||||
|
||||
@@ -265,6 +265,7 @@ pub(super) fn make_streaming(
|
||||
res.threads(),
|
||||
)
|
||||
};
|
||||
streaming.forced = save.load_forced_chunks();
|
||||
streaming.radius = settings.render_distance;
|
||||
streaming.biome_blend = settings.biome_blend;
|
||||
streaming.smooth_lighting = settings.smooth_lighting;
|
||||
|
||||
@@ -32,6 +32,8 @@ fn entity_shader() -> String {
|
||||
crate::overlay::wgsl_constants() + include_str!("entity.wgsl")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod crumbling_tests;
|
||||
mod entity_batch;
|
||||
mod weather;
|
||||
use entity_batch::EntityBatch;
|
||||
@@ -334,6 +336,10 @@ pub struct Renderer {
|
||||
adapter: wgpu::Adapter,
|
||||
/// The window's swapchain; `None` when rendering offscreen (`--offscreen`).
|
||||
surface: Option<wgpu::Surface<'static>>,
|
||||
/// The surface `release_surface` set aside for the renderer that replaces
|
||||
/// this one on the same device: reused, not created again, as a new
|
||||
/// surface for the window can come back lost (Wayland on Mesa).
|
||||
spare_surface: std::sync::Mutex<Option<wgpu::Surface<'static>>>,
|
||||
/// The offscreen colour target, sized like `config`.
|
||||
offscreen: Option<wgpu::Texture>,
|
||||
/// Offscreen submissions still on the GPU: at most two frames run ahead.
|
||||
@@ -1044,7 +1050,15 @@ impl Renderer {
|
||||
surface: if offscreen {
|
||||
None
|
||||
} else {
|
||||
Some(renderer.instance.create_surface(window.clone())?)
|
||||
let spare = renderer
|
||||
.spare_surface
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.take();
|
||||
Some(match spare {
|
||||
Some(surface) => surface,
|
||||
None => renderer.instance.create_surface(window.clone())?,
|
||||
})
|
||||
},
|
||||
instance: renderer.instance.clone(),
|
||||
adapter: renderer.adapter.clone(),
|
||||
@@ -2320,6 +2334,7 @@ impl Renderer {
|
||||
instance,
|
||||
adapter,
|
||||
surface,
|
||||
spare_surface: std::sync::Mutex::new(None),
|
||||
offscreen,
|
||||
in_flight: std::collections::VecDeque::new(),
|
||||
first_frame: if previous.is_none() {
|
||||
@@ -2499,18 +2514,32 @@ impl Renderer {
|
||||
view_formats: &config.view_formats,
|
||||
})
|
||||
}
|
||||
/// Release the window surface before another renderer uses the same window.
|
||||
/// Hand the window surface over to the renderer that replaces this one on
|
||||
/// the same device (it takes `spare_surface`).
|
||||
pub fn release_surface(&mut self) {
|
||||
self.surface = None;
|
||||
*self
|
||||
.spare_surface
|
||||
.get_mut()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = self.surface.take();
|
||||
}
|
||||
/// Reattach a window after surface loss or a failed renderer replacement.
|
||||
pub fn recreate_surface(&mut self) -> Result<()> {
|
||||
if self.offscreen.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
// Wayland allows only one tearing-control object per window surface.
|
||||
self.release_surface();
|
||||
let surface = self.instance.create_surface(self.window.clone())?;
|
||||
// The surface set aside for a replacement that failed, else a new one
|
||||
// (Wayland allows only one tearing-control object per window surface,
|
||||
// so the old one goes first).
|
||||
let spare = self
|
||||
.spare_surface
|
||||
.get_mut()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.take();
|
||||
self.surface = None;
|
||||
let surface = match spare {
|
||||
Some(surface) => surface,
|
||||
None => self.instance.create_surface(self.window.clone())?,
|
||||
};
|
||||
Self::configure(
|
||||
&self.device,
|
||||
&surface,
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// Sample the production WGSL with the production nearest/no-mipmap atlas sampler.
|
||||
#[test]
|
||||
#[ignore = "requires a Vulkan/Metal/DX12 adapter"]
|
||||
fn crack_samples_stay_aligned_between_stages() {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let adapter =
|
||||
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
|
||||
.unwrap();
|
||||
eprintln!("crack sampling adapter: {:?}", adapter.get_info());
|
||||
let (device, queue) =
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap();
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Case {
|
||||
uv: [f32; 2],
|
||||
stage: u32,
|
||||
extent: u32,
|
||||
}
|
||||
let mut cases = Vec::new();
|
||||
let mut expected = Vec::<[u32; 2]>::new();
|
||||
// Include exact texel boundaries, their neighbours, negative projected UVs,
|
||||
// wrapping and the far sprite edge. Origins straddle the packing error's sign change.
|
||||
for extent in [16, 32] {
|
||||
for x in [32, 2080, 4064] {
|
||||
for y in [0, 32] {
|
||||
for i in -32..=32 {
|
||||
for delta in [-0.0001, 0.0, 0.0001] {
|
||||
let uv = [i as f32 / 16.0 + delta, 0.5 - delta];
|
||||
cases.push(Case {
|
||||
uv,
|
||||
stage: crate::breaking::stage_light([
|
||||
x as f32 / 4096.0,
|
||||
y as f32 / 64.0,
|
||||
]),
|
||||
extent,
|
||||
});
|
||||
expected.push(uv.map(|v| {
|
||||
(((v - v.floor()) * extent as f32).floor() as u32).min(extent - 1)
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let math = include_str!("../entity.wgsl")
|
||||
.split("// CRUMBLING_UV_BEGIN")
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.split("// CRUMBLING_UV_END")
|
||||
.next()
|
||||
.unwrap();
|
||||
let source = format!(
|
||||
"{math}\n{}",
|
||||
r#"
|
||||
struct Case { uv: vec2<f32>, stage: u32, extent: u32 }
|
||||
@group(0) @binding(0) var<storage, read> cases: array<Case>;
|
||||
@group(0) @binding(1) var<storage, read_write> results: array<vec4<u32>>;
|
||||
@group(0) @binding(2) var atlas: texture_2d<f32>;
|
||||
@group(0) @binding(3) var atlas_sampler: sampler;
|
||||
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
if id.x >= arrayLength(&cases) { return; }
|
||||
let c = cases[id.x];
|
||||
let origin = vec2(f32(c.stage & 65535u), f32(c.stage >> 16u)) / 65535.0;
|
||||
let dimensions = textureDimensions(atlas);
|
||||
let uv = crumbling_uv(c.uv, origin, vec2(f32(c.extent)) / vec2<f32>(dimensions), dimensions);
|
||||
// Keep the old addressing as a control: the fixture must reproduce its stage jitter.
|
||||
let old_uv = origin + fract(c.uv) * vec2(f32(c.extent)) / vec2<f32>(dimensions);
|
||||
results[id.x] = vec4<u32>(
|
||||
vec2<u32>(round(textureSampleLevel(atlas, atlas_sampler, uv, 0.0).rg * 255.0)),
|
||||
vec2<u32>(round(textureSampleLevel(atlas, atlas_sampler, old_uv, 0.0).rg * 255.0)));
|
||||
}"#
|
||||
);
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Crack sampling regression"),
|
||||
source: wgpu::ShaderSource::Wgsl(source.into()),
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: None,
|
||||
layout: None,
|
||||
module: &shader,
|
||||
entry_point: Some("main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
// Every sprite repeats the same coordinate pattern, so moving a stage's
|
||||
// atlas origin must leave every sampled local texel unchanged.
|
||||
let pixels: Vec<u8> = (0..64)
|
||||
.flat_map(|y| (0..4096).flat_map(move |x| [(x % 32) as u8, (y % 32) as u8, 0, 255]))
|
||||
.collect();
|
||||
let atlas = device.create_texture_with_data(
|
||||
&queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d {
|
||||
width: 4096,
|
||||
height: 64,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
&pixels,
|
||||
);
|
||||
let view = atlas.create_view(&Default::default());
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor::default());
|
||||
let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: None,
|
||||
contents: bytemuck::cast_slice(&cases),
|
||||
usage: wgpu::BufferUsages::STORAGE,
|
||||
});
|
||||
let size = (expected.len() * 16) as u64;
|
||||
let output = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let readback = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: input.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: output.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::TextureView(&view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
},
|
||||
],
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&Default::default());
|
||||
pass.set_pipeline(&pipeline);
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.dispatch_workgroups((cases.len() as u32).div_ceil(64), 1, 1);
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(&output, 0, &readback, 0, size);
|
||||
queue.submit([encoder.finish()]);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap());
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
rx.recv().unwrap().unwrap();
|
||||
let mapped = readback.get_mapped_range(..).unwrap();
|
||||
let actual: &[[u32; 4]] = bytemuck::cast_slice(&mapped);
|
||||
for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
|
||||
assert_eq!(
|
||||
&actual[..2],
|
||||
expected,
|
||||
"case {i}, uv={:?}, stage={}, extent={}",
|
||||
cases[i].uv,
|
||||
cases[i].stage,
|
||||
cases[i].extent
|
||||
);
|
||||
}
|
||||
let old_mismatches = actual
|
||||
.iter()
|
||||
.zip(&expected)
|
||||
.filter(|(a, e)| &a[2..] != e.as_slice())
|
||||
.count();
|
||||
assert!(
|
||||
old_mismatches > 0,
|
||||
"fixture must detect the original sampling bug"
|
||||
);
|
||||
eprintln!(
|
||||
"{} crack texture samples matched; old addressing mismatched {old_mismatches}",
|
||||
cases.len()
|
||||
);
|
||||
}
|
||||
@@ -363,6 +363,9 @@ pub struct ItemRenderer {
|
||||
sprites: FileSprites,
|
||||
baked: Mutex<HashMap<String, Arc<BakedItemModel>>>,
|
||||
extents: Mutex<HashMap<String, Arc<Vec<Vec3>>>>,
|
||||
/// GUI items already drawn: the HUD vertices of a static item at a GUI position
|
||||
/// (`gui::draw`), which are the same every frame it stays there.
|
||||
pub(crate) gui_drawn: Mutex<HashMap<gui::DrawnKey, Arc<[crate::hud::HudVertex]>>>,
|
||||
/// Entity model layers of the special renderers.
|
||||
parts: HashMap<String, ModelPart>,
|
||||
/// `colormap/grass.png` as ARGB.
|
||||
@@ -452,6 +455,7 @@ impl ItemRenderer {
|
||||
},
|
||||
baked: Mutex::default(),
|
||||
extents: Mutex::default(),
|
||||
gui_drawn: Mutex::default(),
|
||||
parts,
|
||||
grass,
|
||||
})
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost};
|
||||
use crate::hud::{HudBatch, Rect};
|
||||
use glam::{EulerRot, Mat4, Vec2, Vec3};
|
||||
use std::{collections::HashMap, f32::consts::PI};
|
||||
use std::{collections::HashMap, f32::consts::PI, sync::Arc};
|
||||
|
||||
mod depth;
|
||||
|
||||
@@ -148,6 +148,95 @@ pub fn draw(
|
||||
if state.is_empty() {
|
||||
return;
|
||||
}
|
||||
// A static item drawn where it was drawn before gives the same vertices:
|
||||
// take them instead of submitting, sorting and clipping its quads again.
|
||||
let key = DrawnKey::of(state, renderer, sprites, x, y);
|
||||
if let Some(key) = &key
|
||||
&& let Some(drawn) = renderer
|
||||
.gui_drawn
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|d| d.get(key).cloned())
|
||||
{
|
||||
batch.vertices.extend_from_slice(&drawn);
|
||||
return;
|
||||
}
|
||||
let start = batch.vertices.len();
|
||||
draw_now(state, renderer, sprites, host, batch, x, y, time);
|
||||
if let Some(key) = key
|
||||
&& let Ok(mut drawn) = renderer.gui_drawn.lock()
|
||||
{
|
||||
// GUI positions and items are few; a long scroll through every tab stays bounded.
|
||||
if drawn.len() >= DRAWN_LIMIT {
|
||||
drawn.clear();
|
||||
}
|
||||
drawn.insert(key, batch.vertices[start..].into());
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries of `ItemRenderer::gui_drawn` before it starts over.
|
||||
const DRAWN_LIMIT: usize = 8192;
|
||||
|
||||
/// What a GUI item's vertices depend on: its layers' baked models (kept for the
|
||||
/// renderer's life, so their addresses name them), tints and transforms, the
|
||||
/// atlas, and the exact position. None for items whose drawing changes with time
|
||||
/// or the host: a glint, or a special model renderer.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct DrawnKey {
|
||||
renderer: usize,
|
||||
sprites: (usize, usize),
|
||||
at: [u32; 2],
|
||||
oversized: bool,
|
||||
layers: Vec<(usize, Vec<i32>, [u32; 16], bool)>,
|
||||
}
|
||||
impl DrawnKey {
|
||||
fn of(
|
||||
state: &ItemRenderState,
|
||||
renderer: &ItemRenderer,
|
||||
sprites: &HashMap<String, Rect>,
|
||||
x: f32,
|
||||
y: f32,
|
||||
) -> Option<Self> {
|
||||
if state.animated {
|
||||
return None;
|
||||
}
|
||||
let layers = state
|
||||
.layers
|
||||
.iter()
|
||||
.map(|layer| match &layer.geometry {
|
||||
super::LayerGeometry::Quads(baked) if layer.foil == super::FoilType::None => {
|
||||
Some((
|
||||
Arc::as_ptr(baked) as usize,
|
||||
layer.tints.clone(),
|
||||
layer.matrix.to_cols_array().map(f32::to_bits),
|
||||
layer.uses_block_light,
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(Self {
|
||||
renderer: std::ptr::from_ref(renderer) as usize,
|
||||
sprites: (std::ptr::from_ref(sprites) as usize, sprites.len()),
|
||||
at: [x.to_bits(), y.to_bits()],
|
||||
oversized: state.oversized_in_gui,
|
||||
layers,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// [`draw`] without the cache.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_now(
|
||||
state: &ItemRenderState,
|
||||
renderer: &ItemRenderer,
|
||||
sprites: &HashMap<String, Rect>,
|
||||
host: &dyn SpecialHost,
|
||||
batch: &mut HudBatch,
|
||||
x: f32,
|
||||
y: f32,
|
||||
time: f32,
|
||||
) {
|
||||
let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0))
|
||||
* Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0));
|
||||
let mut quads: Vec<ItemQuad> = Vec::new();
|
||||
|
||||
@@ -275,6 +275,20 @@ impl Default for KeyBinds {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Each default key once, in order: two mappings that share a default key
|
||||
/// (Advancements and the debug profiler both on L) are one press of it, not
|
||||
/// two (the second would close the screen the first opened). Vanilla clicks
|
||||
/// both mappings, but the profiler one only acts with F3 held.
|
||||
fn distinct<T: PartialEq>(keys: Vec<T>) -> Vec<T> {
|
||||
let mut out = Vec::with_capacity(keys.len());
|
||||
for k in keys {
|
||||
if !out.contains(&k) {
|
||||
out.push(k);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl KeyBinds {
|
||||
pub fn get(&self, name: &str) -> &str {
|
||||
self.keys
|
||||
@@ -320,49 +334,80 @@ impl KeyBinds {
|
||||
}
|
||||
/// The mapping a physical input triggers (first in list order).
|
||||
pub fn mapping_for(&self, key: &str) -> Option<&'static str> {
|
||||
MAPPINGS.iter().map(|m| m.0).find(|n| self.get(n) == key)
|
||||
self.mappings_for(key).next()
|
||||
}
|
||||
/// Every mapping a physical input triggers, in list order: like
|
||||
/// `KeyMapping.set`/`click`, one key drives all the mappings bound to it.
|
||||
pub fn mappings_for<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'static str> + 'a {
|
||||
MAPPINGS
|
||||
.iter()
|
||||
.map(|m| m.0)
|
||||
.filter(move |n| self.get(n) == key)
|
||||
}
|
||||
/// Translate a physical key into the default key of the mapping it is
|
||||
/// bound to, so game code written against vanilla defaults follows the
|
||||
/// player's bindings. `None` means the key now does nothing; mouse
|
||||
/// mappings bound to keys come back as `Err(button)`.
|
||||
/// mappings bound to keys come back as `Err(button)`. The first of
|
||||
/// [`KeyBinds::translate_all`].
|
||||
pub fn translate(&self, key: KeyCode) -> Option<Result<KeyCode, MouseButton>> {
|
||||
self.translate_all(key).into_iter().next()
|
||||
}
|
||||
/// The default keys of every mapping `key` is bound to (empty when it
|
||||
/// now does nothing), so a key bound to two mappings (forward and
|
||||
/// sprint) drives both, as `KeyMapping.set` does.
|
||||
pub fn translate_all(&self, key: KeyCode) -> Vec<Result<KeyCode, MouseButton>> {
|
||||
let Some(name) = key_name(key) else {
|
||||
return Some(Ok(key));
|
||||
return vec![Ok(key)];
|
||||
};
|
||||
if let Some(mapping) = self.mapping_for(name) {
|
||||
let default = Self::default_of(mapping);
|
||||
if let Some(code) = key_code(default) {
|
||||
return Some(Ok(code));
|
||||
}
|
||||
return mouse_button(default).map(Err);
|
||||
let bound: Vec<_> = self
|
||||
.mappings_for(name)
|
||||
.filter_map(|mapping| {
|
||||
let default = Self::default_of(mapping);
|
||||
match key_code(default) {
|
||||
Some(code) => Some(Ok(code)),
|
||||
None => mouse_button(default).map(Err),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !bound.is_empty() {
|
||||
return distinct(bound);
|
||||
}
|
||||
// An unbound key whose default meaning was moved elsewhere is inert.
|
||||
if MAPPINGS
|
||||
.iter()
|
||||
.any(|(n, d, _)| *d == name && !self.is_default(n))
|
||||
{
|
||||
return None;
|
||||
return Vec::new();
|
||||
}
|
||||
Some(Ok(key))
|
||||
vec![Ok(key)]
|
||||
}
|
||||
/// Translate a mouse button the same way (keys bound to mouse buttons).
|
||||
pub fn translate_mouse(&self, button: MouseButton) -> Option<Result<KeyCode, MouseButton>> {
|
||||
self.translate_mouse_all(button).into_iter().next()
|
||||
}
|
||||
/// [`KeyBinds::translate_all`] for a mouse button.
|
||||
pub fn translate_mouse_all(&self, button: MouseButton) -> Vec<Result<KeyCode, MouseButton>> {
|
||||
let name = mouse_name(button);
|
||||
if let Some(mapping) = self.mapping_for(&name) {
|
||||
let default = Self::default_of(mapping);
|
||||
if let Some(b) = mouse_button(default) {
|
||||
return Some(Err(b));
|
||||
}
|
||||
return key_code(default).map(Ok);
|
||||
let bound: Vec<_> = self
|
||||
.mappings_for(&name)
|
||||
.filter_map(|mapping| {
|
||||
let default = Self::default_of(mapping);
|
||||
match mouse_button(default) {
|
||||
Some(b) => Some(Err(b)),
|
||||
None => key_code(default).map(Ok),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !bound.is_empty() {
|
||||
return distinct(bound);
|
||||
}
|
||||
if MAPPINGS
|
||||
.iter()
|
||||
.any(|(n, d, _)| *d == name && !self.is_default(n))
|
||||
{
|
||||
return None;
|
||||
return Vec::new();
|
||||
}
|
||||
Some(Err(button))
|
||||
vec![Err(button)]
|
||||
}
|
||||
/// `AbstractContainerScreen.checkHotbarMouseClicked`: off hand, then hotbar.
|
||||
pub fn container_mouse_key(&self, button: MouseButton, creative: bool) -> Option<KeyCode> {
|
||||
|
||||
@@ -709,6 +709,9 @@ pub struct Extra {
|
||||
/// A copper golem's `openedChestPos`.
|
||||
pub opened_chest: Option<[i32; 3]>,
|
||||
pub point: Option<[f64; 3]>,
|
||||
/// `NEAREST_REPELLENT`: the nearest repelling block a hoglin or piglin
|
||||
/// sensed, looked up every 20 ticks.
|
||||
pub repellent: Option<[i32; 3]>,
|
||||
pub vector: [f64; 3],
|
||||
/// Active status effects: (effect id, ticks left, amplifier).
|
||||
pub effects: Vec<(&'static str, i32, i32)>,
|
||||
@@ -868,6 +871,11 @@ pub struct Mob {
|
||||
/// Events a mob tick asks the game to act on.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum MobEvent {
|
||||
/// Squid.handleEntityEvent(19), resetting the remote tentacle cycle.
|
||||
SquidCycle {
|
||||
mob: u32,
|
||||
at: [f64; 3],
|
||||
},
|
||||
/// Rabbit entity event 1, sent only when a ground jump actually happens.
|
||||
RabbitHop {
|
||||
mob: u32,
|
||||
|
||||
@@ -1242,6 +1242,20 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 {
|
||||
if m.species() == Species::Strider {
|
||||
return super::strider::walk_target_value(m, w, p);
|
||||
}
|
||||
// Hoglin.getWalkTargetValue: nowhere near a repellent, crimson nylium best.
|
||||
if m.species() == Species::Hoglin {
|
||||
let near = m.extra.repellent.is_some_and(|r| {
|
||||
let d = |i: usize| i64::from(r[i] - p[i]);
|
||||
d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < 64
|
||||
});
|
||||
return if near {
|
||||
-1.0
|
||||
} else if w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:crimson_nylium" {
|
||||
10.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
}
|
||||
// Bee.getWalkTargetValue: any air block.
|
||||
if m.species() == Species::Bee {
|
||||
return if w.facts.is_air(w.world.block(p[0], p[1], p[2])) {
|
||||
|
||||
@@ -234,12 +234,40 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
/// Squid.aiStep: tentacle cycle, propulsion and body rotation.
|
||||
fn squid_ai_step(m: &mut Mob) {
|
||||
squid_step(m, false);
|
||||
}
|
||||
|
||||
/// Squid.aiStep also runs on remote entities: animate from packet velocity,
|
||||
/// without running goals or replacing that velocity with the server's movement vector.
|
||||
pub fn squid_client_step(m: &mut Mob) {
|
||||
if matches!(m.species(), Species::Squid | Species::GlowSquid) {
|
||||
m.anim.vo = m.anim.v;
|
||||
squid_step(m, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Squid.handleEntityEvent(19): begin the next server-synchronised tentacle cycle.
|
||||
pub fn squid_cycle_event(m: &mut Mob) {
|
||||
if matches!(m.species(), Species::Squid | Species::GlowSquid) {
|
||||
m.anim.v[TENTACLE_MOVEMENT] = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
fn squid_step(m: &mut Mob, client: bool) {
|
||||
let v = &mut m.anim.v;
|
||||
v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED];
|
||||
if v[TENTACLE_MOVEMENT] > PI * 2.0 {
|
||||
v[TENTACLE_MOVEMENT] -= PI * 2.0;
|
||||
if m.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2;
|
||||
if f64::from(v[TENTACLE_MOVEMENT]) > std::f64::consts::TAU {
|
||||
if client {
|
||||
v[TENTACLE_MOVEMENT] = PI * 2.0;
|
||||
} else {
|
||||
v[TENTACLE_MOVEMENT] -= PI * 2.0;
|
||||
if m.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2;
|
||||
}
|
||||
m.outbox.push(MobEvent::SquidCycle {
|
||||
mob: m.id,
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
});
|
||||
}
|
||||
}
|
||||
let v = &mut m.anim.v;
|
||||
@@ -248,28 +276,39 @@ fn squid_ai_step(m: &mut Mob) {
|
||||
let scale = v[TENTACLE_MOVEMENT] / PI;
|
||||
v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25;
|
||||
if scale > 0.75 {
|
||||
let mv = m.extra.vector;
|
||||
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
|
||||
if !client {
|
||||
let mv = m.extra.vector;
|
||||
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
|
||||
}
|
||||
m.anim.v[ROTATE_SPEED] = 1.0;
|
||||
} else {
|
||||
m.anim.v[ROTATE_SPEED] *= 0.8;
|
||||
}
|
||||
} else {
|
||||
v[TENTACLE_ANGLE] = 0.0;
|
||||
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
|
||||
if !client {
|
||||
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
|
||||
}
|
||||
m.anim.v[ROTATE_SPEED] *= 0.99;
|
||||
}
|
||||
let mv = m.velocity;
|
||||
let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt();
|
||||
m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1;
|
||||
m.body_yaw += (-(horizon_core::geometry::trig::atan2(mv.x, mv.z) as f32) * 57.295776
|
||||
- m.body_yaw)
|
||||
* 0.1;
|
||||
m.yaw = m.body_yaw;
|
||||
let v = &mut m.anim.v;
|
||||
v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5;
|
||||
v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1;
|
||||
v[X_BODY_ROT] += (-(horizon_core::geometry::trig::atan2(horizontal, mv.y) as f32)
|
||||
* 57.295776
|
||||
- v[X_BODY_ROT])
|
||||
* 0.1;
|
||||
} else {
|
||||
v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25;
|
||||
let yd = m.velocity.y - m.kind.gravity;
|
||||
m.velocity = Vec3::new(0.0, yd * 0.98, 0.0);
|
||||
if !client {
|
||||
let yd = m.velocity.y - m.kind.gravity;
|
||||
m.velocity = Vec3::new(0.0, yd * 0.98, 0.0);
|
||||
}
|
||||
let v = &mut m.anim.v;
|
||||
v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::{
|
||||
NearestTarget, Prey, RandomLookAround, Stroll, goal_clone,
|
||||
},
|
||||
};
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
use horizon_core::geometry::{Vec3, trig::Mth};
|
||||
use horizon_core::random::RandomSource;
|
||||
use std::f32::consts::PI;
|
||||
|
||||
@@ -83,12 +83,16 @@ pub fn register_hoglin(m: &mut Mob) {
|
||||
g.add(1, BabyPanic(super::goals::Panic::new(1.25)));
|
||||
g.add(2, MeleeAttack::new(1.0, true));
|
||||
g.add(3, super::goals::Breed::new(1.0));
|
||||
g.add(3, HoglinAvoidRepellent);
|
||||
g.add(4, super::goals::FollowParent::new(1.1));
|
||||
g.add(5, Stroll::avoiding_water(0.4));
|
||||
g.add(6, LookAtPlayer::new(8.0));
|
||||
m.ai.targets.add(1, HurtByTarget::new().alert());
|
||||
m.ai.targets
|
||||
.add(2, NearestTarget::player(true).when(|m, _| !m.is_baby()));
|
||||
// `HoglinAi.findNearestValidAttackTarget`: nothing while pacified.
|
||||
m.ai.targets.add(
|
||||
2,
|
||||
NearestTarget::player(true).when(|m, _| !m.is_baby() && m.extra.ints[0] <= 0),
|
||||
);
|
||||
}
|
||||
pub fn register_zoglin(m: &mut Mob) {
|
||||
let g = &mut m.ai.goals;
|
||||
@@ -108,6 +112,49 @@ pub fn register_zoglin(m: &mut Mob) {
|
||||
.interval(10),
|
||||
);
|
||||
}
|
||||
/// `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, true)` of the hoglin's
|
||||
/// idle activity: closer than 8 blocks to a repellent, walk away from it.
|
||||
#[derive(Clone, Debug)]
|
||||
struct HoglinAvoidRepellent;
|
||||
impl Goal for HoglinAvoidRepellent {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
let Some(r) = m.extra.repellent else {
|
||||
return false;
|
||||
};
|
||||
// Vec3.atBottomCenterOf.
|
||||
let avoid = [
|
||||
f64::from(r[0]) + 0.5,
|
||||
f64::from(r[1]),
|
||||
f64::from(r[2]) + 0.5,
|
||||
];
|
||||
if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 {
|
||||
return false;
|
||||
}
|
||||
for _ in 0..10 {
|
||||
if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) {
|
||||
let at = [
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
];
|
||||
m.ai.pending_path = m.create_path_to(cx.w, at, 0);
|
||||
return m.ai.pending_path.is_some();
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
!m.ai.nav.is_done()
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
let path = m.ai.pending_path.take();
|
||||
m.nav_move_to_path(path, 1.0);
|
||||
}
|
||||
}
|
||||
/// Baby hoglins flee what hurts them; adults stand their ground.
|
||||
#[derive(Clone, Debug)]
|
||||
struct BabyPanic(super::goals::Panic);
|
||||
@@ -165,12 +212,45 @@ impl Goal for GoToWantedItem {
|
||||
m.extra.point = None;
|
||||
}
|
||||
}
|
||||
/// `HoglinSpecificSensor.findNearestRepellent`: the nearest `#hoglin_repellents`
|
||||
/// block within 8 blocks sideways and 4 up or down.
|
||||
fn find_hoglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
|
||||
let tag = w.block_tags.get("minecraft:hoglin_repellents")?;
|
||||
let at = [
|
||||
m.position.x.floor() as i32,
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
w.nearest_block(at, 8, 4, |_, name| tag.contains(name))
|
||||
}
|
||||
/// The hoglin's repellent memories: the sensor (every 20 ticks), the end of
|
||||
/// `PACIFIED` (`ints[0]`), a hit ending it (`HoglinAi.wasHurtBy`, `ints[1]`
|
||||
/// remembers the hit seen) and `BecomePassiveIfMemoryPresent(NEAREST_REPELLENT, 200)`.
|
||||
fn hoglin_repellent(m: &mut Mob, w: &MobWorld) {
|
||||
if m.extra.ints[0] > 0 {
|
||||
m.extra.ints[0] -= 1;
|
||||
}
|
||||
if m.ai.last_hurt_by.is_some() && m.ai.last_hurt_by_time != m.extra.ints[1] {
|
||||
m.extra.ints[1] = m.ai.last_hurt_by_time;
|
||||
m.extra.ints[0] = 0;
|
||||
}
|
||||
if m.age.wrapping_add(m.id).is_multiple_of(20) {
|
||||
m.extra.repellent = find_hoglin_repellent(m, w);
|
||||
}
|
||||
if m.extra.ints[0] <= 0 && m.extra.repellent.is_some() {
|
||||
m.extra.ints[0] = 200;
|
||||
m.ai.target = None;
|
||||
}
|
||||
}
|
||||
/// Per-tick piglin and hoglin state: admiring, anger, zombification and the
|
||||
/// hoglin attack animation. Returns a conversion when it happens.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if m.extra.anim_ticks > 0 {
|
||||
m.extra.anim_ticks -= 1;
|
||||
}
|
||||
if m.species() == Species::Hoglin && m.alive() {
|
||||
hoglin_repellent(m, w);
|
||||
}
|
||||
if m.extra.anger > 0 {
|
||||
m.extra.anger -= 1;
|
||||
if m.extra.anger == 0 && m.ai.target == Some(Who::Player) && !hostile_to_player(m, w) {
|
||||
|
||||
@@ -65,6 +65,35 @@ impl MobWorld<'_> {
|
||||
pub fn has_tag(&self, tag: &str, block: &str) -> bool {
|
||||
self.block_tags.get(tag).is_some_and(|s| s.contains(block))
|
||||
}
|
||||
/// `findBlocksInBoxByManhattanDistance(at, range_xz, range_y).filterState(..).findFirst()`:
|
||||
/// the first block `matches` accepts (given its position and name), going
|
||||
/// out from `at` by Manhattan distance as `BlockPos.withinBoxByManhattanDistance` does.
|
||||
pub fn nearest_block(
|
||||
&self,
|
||||
at: [i32; 3],
|
||||
range_xz: i32,
|
||||
range_y: i32,
|
||||
matches: impl Fn([i32; 3], &str) -> bool,
|
||||
) -> Option<[i32; 3]> {
|
||||
// Visiting order: distance, then x, then y, then +z before -z.
|
||||
let mut best: Option<((i32, i32, i32, bool), [i32; 3])> = None;
|
||||
for dx in -range_xz..=range_xz {
|
||||
for dy in -range_y..=range_y {
|
||||
for dz in -range_xz..=range_xz {
|
||||
let key = (dx.abs() + dy.abs() + dz.abs(), dx, dy, dz < 0);
|
||||
if best.is_some_and(|(k, _)| k <= key) {
|
||||
continue;
|
||||
}
|
||||
let p = [at[0] + dx, at[1] + dy, at[2] + dz];
|
||||
let state = self.world.block(p[0], p[1], p[2]);
|
||||
if !self.facts.is_air(state) && matches(p, &self.facts.get(state).name) {
|
||||
best = Some((key, p));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best.map(|(_, p)| p)
|
||||
}
|
||||
/// Level.clip with COLLIDER shapes (optionally stopping at any fluid): true on a miss.
|
||||
pub fn clear_between(&self, from: Vec3, to: Vec3, fluids_block: bool) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
|
||||
@@ -1083,7 +1083,7 @@ impl MotionWorld<'_, '_, '_> {
|
||||
/// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts
|
||||
/// to inside its movement path: powder snow (`PowderSnowBlock.entityInside`
|
||||
/// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes,
|
||||
/// cactus and lit campfires, and the magma block it stands on
|
||||
/// cactus and lit campfires, and the magma and slime blocks it stands on
|
||||
/// (`stepOn`). Pressure plates, tripwires and rails are the world tick's
|
||||
/// scan.
|
||||
pub fn apply_effects_from_blocks(&mut self) -> Result<()> {
|
||||
@@ -1141,14 +1141,22 @@ impl MotionWorld<'_, '_, '_> {
|
||||
// MagmaBlock's hot floor hurts unless it steps carefully (sneaks).
|
||||
if self.player.ground.on_ground {
|
||||
let on = self.legacy_on_position()?;
|
||||
let magma = self
|
||||
.assets
|
||||
.registry
|
||||
.state(self.block(on))
|
||||
.is_some_and(|s| s.name == "minecraft:magma_block");
|
||||
let under = self.assets.registry.state(self.block(on));
|
||||
let magma = under.is_some_and(|s| s.name == "minecraft:magma_block");
|
||||
let slime = under.is_some_and(|s| s.name == "minecraft:slime_block");
|
||||
if magma && !self.player.shift_key_down {
|
||||
self.environment_hurt("minecraft:hot_floor", 1.0)?;
|
||||
}
|
||||
// SlimeBlock.stepOn: a slow walk on slime drags the horizontal
|
||||
// speed (the client moves its own player, so not the server's copy).
|
||||
if slime && !damage_only && !self.player.shift_key_down {
|
||||
let abs_delta_y = self.player.velocity.y.abs();
|
||||
if abs_delta_y < 0.1 {
|
||||
let scale = 0.4 + abs_delta_y * 0.2;
|
||||
self.player.velocity.x *= scale;
|
||||
self.player.velocity.z *= scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut visited = std::collections::HashSet::new();
|
||||
let mut entered = Vec::new();
|
||||
|
||||
@@ -36,7 +36,7 @@ use horizon_world::{
|
||||
worldgen::terrain::TerrainBlockStates,
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
@@ -1999,6 +1999,9 @@ pub struct SaveDir {
|
||||
/// The dimension's skylight and height, from its folder name.
|
||||
pub shape: LevelShape,
|
||||
}
|
||||
fn is_forced_ticket(ticket: &Tag) -> bool {
|
||||
matches!(ticket.get("type"), Some(Tag::String(t)) if *t == JavaString::from("minecraft:forced"))
|
||||
}
|
||||
impl SaveDir {
|
||||
pub fn new(root: PathBuf) -> Self {
|
||||
let shape = LevelShape::for_dir(&root);
|
||||
@@ -2015,6 +2018,50 @@ impl SaveDir {
|
||||
shape,
|
||||
}
|
||||
}
|
||||
/// 26.3's TicketStorage: persistent tickets live in each dimension's
|
||||
/// data/minecraft/chunk_tickets.dat, with ChunkPos.CODEC's [x, z] int array.
|
||||
pub fn load_forced_chunks(&self) -> HashSet<(i32, i32)> {
|
||||
let Some(data) = read_saved_data(&self.root, "chunk_tickets") else {
|
||||
return HashSet::new();
|
||||
};
|
||||
let Some(Tag::List(tickets)) = data.get("tickets") else {
|
||||
return HashSet::new();
|
||||
};
|
||||
tickets
|
||||
.iter()
|
||||
.filter(|t| is_forced_ticket(t))
|
||||
.filter_map(|t| match t.get("chunk_pos")? {
|
||||
Tag::IntArray(pos) if pos.len() == 2 => Some((pos[0], pos[1])),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn save_forced_chunks(&self, forced: &HashSet<(i32, i32)>) -> Result<()> {
|
||||
if forced.is_empty() && !saved_data_path(&self.root, "chunk_tickets").exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut data = compound_or_empty(read_saved_data(&self.root, "chunk_tickets"));
|
||||
// Preserve persistent tickets Horizon does not simulate.
|
||||
let mut tickets = match data.get("tickets") {
|
||||
Some(Tag::List(tickets)) => tickets
|
||||
.iter()
|
||||
.filter(|t| !is_forced_ticket(t))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut chunks: Vec<_> = forced.iter().copied().collect();
|
||||
chunks.sort_unstable();
|
||||
tickets.extend(chunks.into_iter().map(|(x, z)| {
|
||||
Tag::compound([
|
||||
("type", Tag::String("minecraft:forced".into())),
|
||||
("level", Tag::Int(31)), // ChunkMap.FORCED_TICKET_LEVEL: ENTITY_TICKING.
|
||||
("chunk_pos", Tag::IntArray(vec![x, z])),
|
||||
])
|
||||
}));
|
||||
put(&mut data, "tickets", Tag::List(tickets));
|
||||
write_saved_data(&self.root, "chunk_tickets", data)
|
||||
}
|
||||
fn region_path(&self, folder: &str, rx: i32, rz: i32) -> PathBuf {
|
||||
region_path(&self.root, folder, rx, rz)
|
||||
}
|
||||
@@ -5100,4 +5147,60 @@ mod tests {
|
||||
Some(&5)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_chunks_survive_dimension_restarts_and_removals() {
|
||||
let root = std::env::temp_dir().join(format!("horizon-forced-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let dimensions = [
|
||||
"minecraft:overworld",
|
||||
"minecraft:the_nether",
|
||||
"minecraft:the_end",
|
||||
];
|
||||
for (i, dim) in dimensions.iter().enumerate() {
|
||||
let save = SaveDir::new(dimension_dir(&root, dim));
|
||||
assert!(save.load_forced_chunks().is_empty());
|
||||
let forced = HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)]);
|
||||
save.save_forced_chunks(&forced).unwrap();
|
||||
}
|
||||
for (i, dim) in dimensions.iter().enumerate() {
|
||||
let path = dimension_dir(&root, dim);
|
||||
let save = SaveDir::new(path.clone());
|
||||
let mut forced = save.load_forced_chunks();
|
||||
assert_eq!(
|
||||
forced,
|
||||
HashSet::from([(i as i32, -17), (-23, i as i32), (-1, -1)])
|
||||
);
|
||||
let mut data = read_saved_data(&path, "chunk_tickets").unwrap();
|
||||
let other = Tag::compound([
|
||||
("type", Tag::String("minecraft:portal".into())),
|
||||
("level", Tag::Int(30)),
|
||||
("chunk_pos", Tag::IntArray(vec![7, -8])),
|
||||
("ticks_left", Tag::Long(42)),
|
||||
]);
|
||||
if let Some(Tag::List(tickets)) = data.get_mut("tickets") {
|
||||
assert!(
|
||||
tickets
|
||||
.iter()
|
||||
.all(|t| t.get("level") == Some(&Tag::Int(31)))
|
||||
);
|
||||
tickets.push(other.clone());
|
||||
}
|
||||
write_saved_data(&path, "chunk_tickets", data).unwrap();
|
||||
forced.remove(&(-1, -1));
|
||||
save.save_forced_chunks(&forced).unwrap();
|
||||
drop(save);
|
||||
let reopened = SaveDir::new(path.clone());
|
||||
assert_eq!(reopened.load_forced_chunks(), forced);
|
||||
reopened.save_forced_chunks(&HashSet::new()).unwrap();
|
||||
assert!(SaveDir::new(path.clone()).load_forced_chunks().is_empty());
|
||||
assert_eq!(
|
||||
read_saved_data(&path, "chunk_tickets")
|
||||
.unwrap()
|
||||
.get("tickets"),
|
||||
Some(&Tag::List(vec![other]))
|
||||
);
|
||||
}
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +109,9 @@ pub struct Weather {
|
||||
pub thunder_level: (f32, f32),
|
||||
}
|
||||
impl Weather {
|
||||
pub fn tick(&mut self, random: &mut horizon_core::random::LegacyRandom) {
|
||||
/// The timers of `advanceWeatherCycle`, which run only while
|
||||
/// `advance_weather` is on.
|
||||
pub fn tick_timers(&mut self, random: &mut horizon_core::random::LegacyRandom) {
|
||||
use horizon_core::random::RandomSource;
|
||||
let mut uniform =
|
||||
|min: i32, max: i32| min + random.next_int_bound(max - min + 1).unwrap_or(0);
|
||||
@@ -141,6 +143,10 @@ impl Weather {
|
||||
self.rain_time = uniform(12000, 180000);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The rain and thunder level fade at the end of `advanceWeatherCycle`,
|
||||
/// which runs whatever `advance_weather` says, so `/weather` still shows.
|
||||
pub fn tick_levels(&mut self) {
|
||||
self.thunder_level.0 = self.thunder_level.1;
|
||||
self.thunder_level.1 =
|
||||
(self.thunder_level.1 + if self.thundering { 0.01 } else { -0.01 }).clamp(0.0, 1.0);
|
||||
|
||||
@@ -181,6 +181,8 @@ pub struct GameRules {
|
||||
pub max_snow_accumulation_height: i32,
|
||||
pub spawn_mobs: bool,
|
||||
pub spawn_monsters: bool,
|
||||
/// `fire_spread_radius_around_player`: -1 spreads everywhere.
|
||||
pub fire_spread_radius_around_player: i32,
|
||||
}
|
||||
impl Default for GameRules {
|
||||
fn default() -> Self {
|
||||
@@ -193,6 +195,7 @@ impl Default for GameRules {
|
||||
max_snow_accumulation_height: 1,
|
||||
spawn_mobs: true,
|
||||
spawn_monsters: true,
|
||||
fire_spread_radius_around_player: 128,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -288,6 +291,11 @@ pub enum LevelEvent {
|
||||
|
||||
/// The world as seen by block behaviour. Implemented by the game and tests.
|
||||
pub trait LevelAccess {
|
||||
/// `Level.isClientSide`: this level is a client's copy (false on a
|
||||
/// server, a host or the test harness).
|
||||
fn is_client_side(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// `getBlockState`. Unloaded or out-of-bounds positions read as air.
|
||||
fn block_state(&self, pos: BlockPos) -> BlockStateId;
|
||||
/// Storage write (`LevelChunkSection.setBlockState`). Returns the previous
|
||||
@@ -343,6 +351,11 @@ pub trait LevelAccess {
|
||||
fn can_spread_fire_around(&self, _pos: BlockPos) -> bool {
|
||||
true
|
||||
}
|
||||
/// The `INCREASED_FIRE_BURNOUT` environment attribute at `pos` (a biome
|
||||
/// attribute).
|
||||
fn increased_fire_burnout(&self, _pos: BlockPos) -> bool {
|
||||
false
|
||||
}
|
||||
/// `Level.isUnobstructed(state, pos, context)`: whether the state's
|
||||
/// collision shape at `pos` would intersect an entity.
|
||||
fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool {
|
||||
|
||||
@@ -27,6 +27,9 @@ pub struct MovingPiston {
|
||||
pub progress: f32,
|
||||
pub progress_o: f32,
|
||||
pub last_ticked: i64,
|
||||
/// `PistonMovingBlockEntity.deathTicks`: on a client the entity waits
|
||||
/// five ticks past progress 1.0 before placing the block itself.
|
||||
pub death_ticks: i32,
|
||||
/// Identity of this block entity (a replaced entity is a new ticker).
|
||||
pub id: u64,
|
||||
}
|
||||
@@ -126,11 +129,8 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
self.note_trigger_event(pos, state);
|
||||
true
|
||||
} else if data.is(super::classes::Class::Bell) {
|
||||
// BellBlockEntity.triggerEvent handles event 1; the server
|
||||
// broadcasts handled events to the clients.
|
||||
if a == 1 {
|
||||
self.emit(LevelEvent::BlockEntityEvent { pos, state, a, b });
|
||||
}
|
||||
// BellBlockEntity.triggerEvent handles event 1; the caller
|
||||
// reports handled events (`runBlockEvents` broadcasts them).
|
||||
a == 1
|
||||
} else {
|
||||
false
|
||||
@@ -164,7 +164,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
let Some(piston) = self.moving_piston(pos) else {
|
||||
return;
|
||||
};
|
||||
if piston.progress_o >= 1.0 {
|
||||
// finalTick: `progressO < 1.0 || level.isClientSide` — a client
|
||||
// finishes its copy even at full progress.
|
||||
if piston.progress_o >= 1.0 && !self.level.is_client_side() {
|
||||
return;
|
||||
}
|
||||
self.remove_moving_piston(pos);
|
||||
@@ -189,6 +191,20 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
piston.last_ticked = self.level.game_time();
|
||||
piston.progress_o = piston.progress;
|
||||
if piston.progress_o >= 1.0 {
|
||||
if self.level.is_client_side() && piston.death_ticks < 5 {
|
||||
// The client's copy waits for the server's state before
|
||||
// placing the block itself (deathTicks < 5).
|
||||
piston.death_ticks += 1;
|
||||
if let Some(entry) = self
|
||||
.ticks
|
||||
.moving_pistons
|
||||
.iter_mut()
|
||||
.find(|(p, _)| *p == pos)
|
||||
{
|
||||
entry.1 = piston;
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.remove_moving_piston(pos);
|
||||
if b.is_block(self.state(pos), b.named.moving_piston) {
|
||||
let mut new = self.update_from_neighbour_shapes(piston.moved_state, pos);
|
||||
@@ -241,8 +257,13 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
direction != Direction::Down && self.has_signal(rel(up, direction), direction)
|
||||
})
|
||||
}
|
||||
/// `PistonBaseBlock.checkIfExtend`.
|
||||
/// `PistonBaseBlock.checkIfExtend`, which `neighborChanged`, `onPlace`
|
||||
/// and `setPlacedBy` call only server-side: a client moves its pistons on
|
||||
/// the server's block events alone.
|
||||
pub(crate) fn piston_check_if_extend(&mut self, pos: BlockPos, state: BlockStateId) {
|
||||
if self.level.is_client_side() {
|
||||
return;
|
||||
}
|
||||
let b = self.b;
|
||||
let direction = b.facing(state);
|
||||
let extend = self.piston_neighbor_signal(pos, direction);
|
||||
@@ -527,6 +548,12 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
for pos in to_destroy.iter().rev() {
|
||||
let state = self.state(*pos);
|
||||
self.drop_resources(state, *pos);
|
||||
// The client's copy plays the destroy effect itself (the
|
||||
// server sends no 2001 for piston moves).
|
||||
let fire = b.is_block(state, b.named.fire) || b.is_block(state, b.named.soul_fire);
|
||||
if !fire && self.level.is_client_side() {
|
||||
self.level_event(2001, *pos, state.0 as i32);
|
||||
}
|
||||
self.set_block(*pos, b.air(), 18);
|
||||
self.game_event(*pos, "minecraft:block_destroy");
|
||||
to_update.push(state);
|
||||
@@ -551,6 +578,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
progress: 0.0,
|
||||
progress_o: 0.0,
|
||||
last_ticked: 0,
|
||||
death_ticks: 0,
|
||||
id: 0,
|
||||
},
|
||||
);
|
||||
@@ -576,6 +604,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
progress: 0.0,
|
||||
progress_o: 0.0,
|
||||
last_ticked: 0,
|
||||
death_ticks: 0,
|
||||
id: 0,
|
||||
},
|
||||
);
|
||||
@@ -624,13 +653,17 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
let direction = b.facing(state);
|
||||
let extended_state = b.table.set_bool(state, p.extended, true);
|
||||
let sticky = self.is_sticky_piston(state);
|
||||
let extend = self.piston_neighbor_signal(pos, direction);
|
||||
if extend && (a == 1 || a == 2) {
|
||||
self.set_block(pos, extended_state, 2);
|
||||
return false;
|
||||
}
|
||||
if !extend && a == 0 {
|
||||
return false;
|
||||
// The signal re-check is server-only (`!level.isClientSide`): a
|
||||
// client trusts the event as sent.
|
||||
if !self.level.is_client_side() {
|
||||
let extend = self.piston_neighbor_signal(pos, direction);
|
||||
if extend && (a == 1 || a == 2) {
|
||||
self.set_block(pos, extended_state, 2);
|
||||
return false;
|
||||
}
|
||||
if !extend && a == 0 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if a == 0 {
|
||||
if !self.piston_move_blocks(pos, direction, true, sticky) {
|
||||
@@ -664,6 +697,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
progress: 0.0,
|
||||
progress_o: 0.0,
|
||||
last_ticked: 0,
|
||||
death_ticks: 0,
|
||||
id: 0,
|
||||
},
|
||||
);
|
||||
@@ -748,8 +782,18 @@ impl Behaviours {
|
||||
}
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let state = sim.state(event.pos);
|
||||
if self.block(state) == event.block {
|
||||
sim.trigger_event(state, event.pos, event.param_a, event.param_b);
|
||||
if self.block(state) == event.block
|
||||
&& sim.trigger_event(state, event.pos, event.param_a, event.param_b)
|
||||
{
|
||||
// ServerLevel.runBlockEvents broadcasts a handled event to
|
||||
// the clients (`ClientboundBlockEventPacket`); their copy of
|
||||
// the block re-runs `triggerEvent` (a piston's `moveBlocks`).
|
||||
sim.emit(LevelEvent::BlockEntityEvent {
|
||||
pos: event.pos,
|
||||
state,
|
||||
a: event.param_a,
|
||||
b: event.param_b,
|
||||
});
|
||||
}
|
||||
}
|
||||
for event in reschedule {
|
||||
@@ -779,4 +823,85 @@ impl Behaviours {
|
||||
self.sim(level, ticks).moving_piston_tick(pos);
|
||||
}
|
||||
}
|
||||
/// `ClientLevel.blockEvent`: the client re-runs the block's
|
||||
/// `triggerEvent` on its own level (a piston's `moveBlocks` builds the
|
||||
/// moving block entities it then animates) instead of waiting for the
|
||||
/// server's states. No queue and no ticking-chunk gate: a client runs
|
||||
/// the event where the packet lands.
|
||||
pub fn client_block_event<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
a: i32,
|
||||
b: i32,
|
||||
) -> bool {
|
||||
let triggered = {
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let state = sim.state(pos);
|
||||
let triggered = sim.trigger_event(state, pos, a, b);
|
||||
if triggered {
|
||||
// The client's copy of a handled event reaches the client
|
||||
// copy of the block entity (a bell's ring).
|
||||
sim.emit(LevelEvent::BlockEntityEvent { pos, state, a, b });
|
||||
}
|
||||
triggered
|
||||
};
|
||||
self.client_drain_block_events(level, ticks);
|
||||
triggered
|
||||
}
|
||||
/// `ClientLevel.tickBlockEntities` for moving pistons: the client copy of
|
||||
/// [`Behaviours::tick_block_entities`], without the server's
|
||||
/// ticking-chunk gate (a client ticks every loaded block entity). One
|
||||
/// whose block was replaced is dropped (`TickingBlockEntity.isRemoved`).
|
||||
pub fn client_tick_block_entities<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
) {
|
||||
let tickers: Vec<(BlockPos, u64)> = ticks
|
||||
.moving_pistons
|
||||
.iter()
|
||||
.map(|(p, m)| (*p, m.id))
|
||||
.collect();
|
||||
for (pos, id) in tickers {
|
||||
if !ticks
|
||||
.moving_pistons
|
||||
.iter()
|
||||
.any(|(p, m)| *p == pos && m.id == id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
{
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let state = sim.state(pos);
|
||||
if sim.b.is_block(state, sim.b.named.moving_piston) {
|
||||
sim.moving_piston_tick(pos);
|
||||
} else {
|
||||
sim.remove_moving_piston(pos);
|
||||
}
|
||||
}
|
||||
self.client_drain_block_events(level, ticks);
|
||||
}
|
||||
}
|
||||
/// Block events a client-side `triggerEvent` queued
|
||||
/// (`PistonBaseBlock.checkIfExtend` in a neighbour update): a client
|
||||
/// runs them as they come (`ClientLevel.blockEvent`), not in a tick pass.
|
||||
fn client_drain_block_events<L: LevelAccess + ?Sized>(&self, level: &mut L, ticks: &mut Ticks) {
|
||||
while let Some(event) = ticks.block_events.first().copied() {
|
||||
ticks.block_events.remove(0);
|
||||
let mut sim = self.sim(level, ticks);
|
||||
let state = sim.state(event.pos);
|
||||
if self.block(state) == event.block
|
||||
&& sim.trigger_event(state, event.pos, event.param_a, event.param_b)
|
||||
{
|
||||
sim.emit(LevelEvent::BlockEntityEvent {
|
||||
pos: event.pos,
|
||||
state,
|
||||
a: event.param_a,
|
||||
b: event.param_b,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ pub(crate) struct TestLevel {
|
||||
pub day_time: i64,
|
||||
pub events: Vec<LevelEvent>,
|
||||
pub block_light: HashMap<BlockPos, i32>,
|
||||
/// `Level.isClientSide`.
|
||||
pub client_side: bool,
|
||||
}
|
||||
impl TestLevel {
|
||||
fn new(b: &Behaviours) -> Self {
|
||||
@@ -58,10 +60,14 @@ impl TestLevel {
|
||||
day_time: 0,
|
||||
events: Vec::new(),
|
||||
block_light: HashMap::new(),
|
||||
client_side: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl LevelAccess for TestLevel {
|
||||
fn is_client_side(&self) -> bool {
|
||||
self.client_side
|
||||
}
|
||||
fn block_state(&self, pos: BlockPos) -> BlockStateId {
|
||||
self.blocks.get(&pos).copied().unwrap_or(self.air)
|
||||
}
|
||||
@@ -919,6 +925,100 @@ fn pistons_push_and_sticky_pistons_pull() {
|
||||
assert_eq!(w.get(BlockPos::new(2, 1, 0)), air);
|
||||
}
|
||||
|
||||
/// `ServerLevel.runBlockEvents` reports a handled event for the clients
|
||||
/// (`ClientboundBlockEventPacket`), carrying the block the event named.
|
||||
#[test]
|
||||
fn a_handled_block_event_reaches_the_clients() {
|
||||
let mut w = world!();
|
||||
w.floor(0, 10, "stone");
|
||||
let piston = w.id("piston", &[("facing", "east")]);
|
||||
let block = w.id("redstone_block", &[]);
|
||||
w.set(BlockPos::new(0, 1, 0), piston);
|
||||
w.set(BlockPos::new(-1, 1, 0), block);
|
||||
w.level.events.clear();
|
||||
w.full_tick();
|
||||
assert!(w.level.events.iter().any(|e| matches!(
|
||||
e,
|
||||
LevelEvent::BlockEntityEvent {
|
||||
pos,
|
||||
state,
|
||||
a: 0,
|
||||
..
|
||||
} if *pos == BlockPos::new(0, 1, 0) && *state == piston
|
||||
)));
|
||||
}
|
||||
|
||||
/// `ClientLevel.blockEvent`: the client re-runs `triggerEvent` on its own
|
||||
/// level, which builds the moving block entities a piston's `moveBlocks`
|
||||
/// makes, and ticks them to the placed block.
|
||||
#[test]
|
||||
fn a_client_replays_a_pistons_block_event() {
|
||||
let mut w = world!();
|
||||
w.floor(0, 10, "stone");
|
||||
let piston = w.id("sticky_piston", &[("facing", "east")]);
|
||||
let dirt = w.id("dirt", &[]);
|
||||
let block = w.id("redstone_block", &[]);
|
||||
w.put(BlockPos::new(0, 1, 0), piston);
|
||||
w.put(BlockPos::new(1, 1, 0), dirt);
|
||||
w.put(BlockPos::new(-1, 1, 0), block);
|
||||
w.f.behaviours.client_block_event(
|
||||
&mut w.level,
|
||||
&mut w.ticks,
|
||||
BlockPos::new(0, 1, 0),
|
||||
0,
|
||||
Direction::East as i32,
|
||||
);
|
||||
assert!(
|
||||
w.ticks
|
||||
.moving_pistons
|
||||
.iter()
|
||||
.any(|(p, _)| *p == BlockPos::new(2, 1, 0))
|
||||
);
|
||||
for _ in 0..3 {
|
||||
w.level.time += 1;
|
||||
w.f.behaviours
|
||||
.client_tick_block_entities(&mut w.level, &mut w.ticks);
|
||||
}
|
||||
assert_eq!(w.get(BlockPos::new(2, 1, 0)), dirt);
|
||||
assert_eq!(
|
||||
w.name(BlockPos::new(1, 1, 0)),
|
||||
"piston_head[facing=east,short=false,type=sticky]"
|
||||
);
|
||||
assert!(w.ticks.moving_pistons.is_empty());
|
||||
}
|
||||
|
||||
/// A client's copy of a move doesn't start the pistons the moved block
|
||||
/// powers (`checkIfExtend` is server-only): their own block events come from
|
||||
/// the server.
|
||||
#[test]
|
||||
fn a_client_replay_starts_no_other_piston() {
|
||||
let mut w = world!();
|
||||
w.floor(0, 10, "stone");
|
||||
w.level.client_side = true;
|
||||
let piston = w.id("piston", &[("facing", "east")]);
|
||||
let block = w.id("redstone_block", &[]);
|
||||
let up = w.id("piston", &[("facing", "up")]);
|
||||
w.put(BlockPos::new(0, 1, 0), piston);
|
||||
w.put(BlockPos::new(1, 1, 0), block);
|
||||
w.put(BlockPos::new(2, 2, 0), up);
|
||||
w.f.behaviours.client_block_event(
|
||||
&mut w.level,
|
||||
&mut w.ticks,
|
||||
BlockPos::new(0, 1, 0),
|
||||
0,
|
||||
Direction::East as i32,
|
||||
);
|
||||
for _ in 0..10 {
|
||||
w.level.time += 1;
|
||||
w.f.behaviours
|
||||
.client_tick_block_entities(&mut w.level, &mut w.ticks);
|
||||
}
|
||||
assert_eq!(w.get(BlockPos::new(2, 1, 0)), block);
|
||||
assert_eq!(w.get(BlockPos::new(2, 2, 0)), up);
|
||||
assert!(w.ticks.moving_pistons.is_empty());
|
||||
assert!(w.ticks.block_events.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pistons_pop_fragile_blocks_and_refuse_obsidian() {
|
||||
let mut w = world!();
|
||||
|
||||
@@ -565,9 +565,8 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// FireBlock.tick reads the INCREASED_FIRE_BURNOUT environment attribute
|
||||
// (jungles, swamps, peaks, mushroom fields); Horizon doesn't yet.
|
||||
let burnout = false;
|
||||
// FireBlock.tick: the INCREASED_FIRE_BURNOUT environment attribute.
|
||||
let burnout = self.level.increased_fire_burnout(pos);
|
||||
let extra = if burnout { -50 } else { 0 };
|
||||
for (direction, chance) in [
|
||||
(Direction::East, 300),
|
||||
|
||||
@@ -13,7 +13,7 @@ python3 tools/parity.py --failed # the ones that failed last time
|
||||
python3 tools/parity.py --all # everything, from scratch: the audit (26 minutes on the Mac mini alone)
|
||||
python3 tools/parity.py --fresh food # don't reuse vanilla oracle results
|
||||
python3 tools/parity.py --repeat 3 food # run it three times; the runs must agree
|
||||
python3 tools/parity.py --hosts macmini,thinkpad # with other machines (default: tools/parity_hosts.json's default list, empty)
|
||||
python3 tools/parity.py --hosts macmini,playhorizon # with other machines (default: tools/parity_hosts.json's default list, empty)
|
||||
python3 tools/parity.py --list # what would run
|
||||
python3 tools/parity.py --status # last result of each harness
|
||||
python3 tools/parity.py --changed origin/main # those a branch's changes can affect (CI's parity job)
|
||||
@@ -40,9 +40,9 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder
|
||||
|
||||
### Other machines
|
||||
|
||||
Harnesses can also run on the Mac mini, the ThinkPad and the desktop (`tools/parity_hosts.json` describes them; `desktop` uses its CI runner's environment and vanilla data, and refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/<host><path>`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here.
|
||||
Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/parity_hosts.json` describes them; `desktop` and `playhorizon` use their CI runner's environment and vanilla data, and the desktop refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,playhorizon` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/<host><path>`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8, playhorizon 6. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here.
|
||||
|
||||
Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad helps too, gently: Linux, 2 harnesses at `nice 19`, since it hosts the Claude account pool; it finds ALSA through `~/code/horizon-parity/alsa-dev` like the desktop.
|
||||
Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on.
|
||||
|
||||
### Shards and Rust scopes
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.world.effect.MobEffect;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.animal.squid.Squid;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/** Runs the real Squid.aiStep, with unrelated movement/world services controlled. */
|
||||
public final class VanillaSquidClientOracle {
|
||||
static Field field(Class<?> owner, String name) throws Exception {
|
||||
var f = owner.getDeclaredField(name); f.setAccessible(true); return f;
|
||||
}
|
||||
static final class Shell extends Squid {
|
||||
Level world; boolean water;
|
||||
Shell() { super(EntityTypes.SQUID, null); }
|
||||
@Override public Level level() { return world; }
|
||||
@Override public boolean isAgeLocked() { return true; }
|
||||
@Override public boolean isInWater() { return water; }
|
||||
@Override protected boolean isImmobile() { return true; }
|
||||
@Override protected void applyInput() {}
|
||||
@Override public boolean isEffectiveAi() { return false; }
|
||||
@Override public boolean isFallFlying() { return false; }
|
||||
@Override public boolean hasEffect(Holder<MobEffect> effect) { return false; }
|
||||
@Override public LivingEntity getControllingPassenger() { return null; }
|
||||
@Override public void calculateEntityAnimation(boolean flying) {}
|
||||
@Override protected void pushEntities() {}
|
||||
}
|
||||
static String bits(float value) { return String.format("%08x", Float.floatToIntBits(value)); }
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = field(u, "theUnsafe"); var unsafe = uf.get(null);
|
||||
var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
var world = (ClientLevel) allocate.invoke(unsafe, ClientLevel.class);
|
||||
field(Level.class, "isClientSide").setBoolean(world, true);
|
||||
String[] names = {"tentacleMovement", "tentacleAngle", "xBodyRot", "zBodyRot", "tentacleSpeed", "rotateSpeed"};
|
||||
Field[] values = new Field[names.length];
|
||||
for (int i = 0; i < names.length; i++) values[i] = field(Squid.class, names[i]);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var row = JsonParser.parseString(line).getAsJsonObject();
|
||||
var m = (Shell) allocate.invoke(unsafe, Shell.class);
|
||||
m.world = world; field(Entity.class, "level").set(m, world); m.water = row.get("water").getAsBoolean();
|
||||
field(Entity.class, "type").set(m, EntityTypes.SQUID);
|
||||
field(LivingEntity.class, "equipment").set(m, new EntityEquipment());
|
||||
field(Entity.class, "interpolationHandler").set(m, Proxy.newProxyInstance(
|
||||
InterpolationHandler.class.getClassLoader(), new Class<?>[]{InterpolationHandler.class},
|
||||
(proxy, method, arguments) -> method.getName().equals("hasActiveInterpolation") ? true : null));
|
||||
m.setBoundingBox(new AABB(0, 0, 0, 1, 1, 1));
|
||||
m.setDeltaMovement(new Vec3(row.get("x").getAsDouble(), row.get("y").getAsDouble(), row.get("z").getAsDouble()));
|
||||
m.yBodyRot = row.get("body").getAsFloat();
|
||||
for (int i = 0; i < names.length; i++) values[i].setFloat(m, row.getAsJsonArray("v").get(i).getAsFloat());
|
||||
if (row.get("reset").getAsBoolean()) m.handleEntityEvent((byte)19);
|
||||
m.aiStep();
|
||||
out.print(bits(m.yBodyRot));
|
||||
for (var f : values) out.print(" " + bits(f.getFloat(m)));
|
||||
out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -259,7 +259,11 @@ class OracleReuseTests(unittest.TestCase):
|
||||
self.input, self.output = root / "work" / "in.txt", root / "work" / "out.txt"
|
||||
self.input.parent.mkdir()
|
||||
self.input.write_text("a")
|
||||
python = Path(sys.executable).parent
|
||||
# The shim starts with `#!/usr/bin/env python3`, and a Python's own folder may name it only
|
||||
# python3.13 (Homebrew's): a python3 of its own keeps the PATH below enough.
|
||||
python = root / "python"
|
||||
python.mkdir()
|
||||
(python / "python3").symlink_to(sys.executable)
|
||||
self.env = dict(os.environ, PATH=f"{self.shim}:{self.bin}:{python}", PARITY_SHIM_REAL_PATH=str(self.bin),
|
||||
PARITY_SHIM_CACHE=str(root / "cache"))
|
||||
self.subprocess = subprocess
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Exercise Entity motion delivery through the live multiplayer handler."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("rustc"), "requires Rust")
|
||||
class RemoteMotionTests(unittest.TestCase):
|
||||
def test_mob_velocity_reaches_squid_animation(self):
|
||||
source = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text()
|
||||
start = source.index(" fn remote_motion(")
|
||||
end = source.index(" fn apply_remote_health(", start)
|
||||
fixture = r'''
|
||||
#![allow(dead_code)]
|
||||
use std::collections::HashMap;
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Vec3(f64, f64, f64);
|
||||
impl Vec3 { fn new(x: f64, y: f64, z: f64) -> Self { Self(x,y,z) } }
|
||||
#[derive(Default)]
|
||||
struct Entity { id: u32, velocity: Vec3 }
|
||||
#[derive(Default)]
|
||||
struct Remote { pending_items: HashMap<i32, ((), Vec3)> }
|
||||
#[derive(Default)]
|
||||
struct Creatures { projectiles: Vec<Entity> }
|
||||
#[derive(Default)]
|
||||
struct Potions;
|
||||
impl Potions { fn remote_thrown_motion(&mut self, _id: u32, _v: Vec3) -> bool { false } }
|
||||
#[derive(Default)]
|
||||
struct End;
|
||||
impl End { fn remote_eye_motion(&mut self, _id: u32, _v: [f64; 3]) {} }
|
||||
#[derive(Default)]
|
||||
struct Game {
|
||||
mobs: Vec<Entity>, dropped: Vec<Entity>, falling: Vec<Entity>, tnts: Vec<Entity>,
|
||||
creatures: Creatures, dragon_fireballs: Vec<Entity>, remote: Option<Remote>,
|
||||
potions: Potions, end: End,
|
||||
}
|
||||
impl Game {
|
||||
fn remote_dragon_motion(&mut self, _id: i32, _velocity: [f64; 3]) {}
|
||||
METHOD
|
||||
}
|
||||
fn main() {
|
||||
let mut game = Game::default();
|
||||
game.mobs.push(Entity { id: 42, ..Entity::default() });
|
||||
game.dropped.push(Entity { id: 43, ..Entity::default() });
|
||||
// AddEntity initial motion and subsequent SetEntityMotion share this handler.
|
||||
for motion in [[0.12, -0.04, 0.08], [-0.05, 0.03, 0.2], [0.0; 3]] {
|
||||
game.remote_motion(42, motion);
|
||||
assert_eq!(game.mobs[0].velocity, Vec3::new(motion[0], motion[1], motion[2]));
|
||||
assert_eq!(game.dropped[0].velocity, Vec3::default());
|
||||
}
|
||||
game.remote_motion(43, [0.1, 0.2, 0.3]);
|
||||
assert_eq!(game.dropped[0].velocity, Vec3::new(0.1, 0.2, 0.3));
|
||||
game.remote_motion(999, [1.0; 3]); // Untracked entity is harmless.
|
||||
}
|
||||
'''.replace("METHOD", source[start:end])
|
||||
with tempfile.TemporaryDirectory(prefix="remote-motion-") as directory:
|
||||
path = Path(directory)
|
||||
(path / "main.rs").write_text(fixture)
|
||||
subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")],
|
||||
check=True, capture_output=True, text=True)
|
||||
result = subprocess.run([str(path / "probe")], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
@@ -10,7 +10,9 @@ from tools import test_rust_parity as parity
|
||||
class ParityRunnerTests(unittest.TestCase):
|
||||
def test_report_rejects_sources_changed_during_a_run(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
# Resolved, as source_hashes resolves the sources: macOS's temp folder is a symlink
|
||||
# (/var -> /private/var).
|
||||
root = Path(temp).resolve()
|
||||
source = root / "source.rs"
|
||||
source.write_text("before")
|
||||
with mock.patch.object(parity.lab, "ROOT", root):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# A Horizon CI runner (labels self-hosted, Linux, X64, horizon-game and the host's name) on a Linux machine of the
|
||||
# maintainer's (NixOS: ludodesktop, ludothinkpad; Ubuntu: playhorizon, a partner's server), as a systemd user service
|
||||
# maintainer's (NixOS: ludodesktop; Ubuntu: playhorizon, a partner's server), as a systemd user service
|
||||
# of the account that holds his Minecraft files, like the Mac mini's runners (docs/release-flow.md). Run it on that
|
||||
# machine, as that user:
|
||||
#
|
||||
|
||||
@@ -241,6 +241,12 @@ def world_blocks():
|
||||
cmd('/clone 0 205 0 4 207 4 6 205 6 masked'),
|
||||
cmd('/execute if blocks 0 205 0 4 207 4 6 205 6 all'),
|
||||
cmd('/setblock 3 206 3 minecraft:air'),
|
||||
# A container keeps its loot table and seed until its items change
|
||||
# (RandomizableContainer.tryLoadLootTable / trySaveLootTable).
|
||||
cmd('/setblock 7 206 7 minecraft:chest{LootTable:"minecraft:chests/simple_dungeon",LootTableSeed:42L}'),
|
||||
cmd('/data get block 7 206 7'),
|
||||
cmd('/data get block 7 206 7 LootTableSeed'),
|
||||
cmd('/setblock 7 206 7 minecraft:air'),
|
||||
# A hopper placed into power turns `enabled=false` and keeps its block entity.
|
||||
cmd('/setblock 5 205 5 minecraft:redstone_block'),
|
||||
cmd('/setblock 5 206 5 minecraft:hopper'),
|
||||
|
||||
@@ -7245,5 +7245,58 @@ CHECKS += ['cushions']
|
||||
CHECK_FNS['cushions'] = check_cushions
|
||||
|
||||
|
||||
def check_forced_levels(host, guest, out):
|
||||
"""#1525: forced block/entity ticks outlive the last player and the 300-tick idle timeout.
|
||||
|
||||
Also keep a resident, unforced furnace outside the forced ticket's neighbour ring: scheduling
|
||||
a playerless integrated-server level must not enable the fixtures' tick-everywhere fallback.
|
||||
"""
|
||||
if not SERVER_THREAD:
|
||||
return 'skipped (needs --server-thread)'
|
||||
start = pos_of(guest)
|
||||
results = {}
|
||||
guest('command', command='gamemode creative')
|
||||
try:
|
||||
for dimension in (NETHER, END):
|
||||
into_level(guest, dimension, 8, 100, 8)
|
||||
host('command', command='tick freeze')
|
||||
furnace = ('minecraft:furnace{Items:[{Slot:0b,id:"minecraft:raw_iron",count:1},'
|
||||
'{Slot:1b,id:"minecraft:coal",count:1}],cooking_total_time:200,'
|
||||
'cooking_time_spent:0}')
|
||||
for x in (8, 56):
|
||||
guest('command', command=f'setblock {x} 100 8 {furnace}')
|
||||
server_reply(guest, f'execute if data block {x} 100 8 '
|
||||
'Items[{Slot:0b,id:"minecraft:raw_iron"}] '
|
||||
'run say forced-input-ready', 'forced-input-ready')
|
||||
guest('command', command='forceload add 8 8')
|
||||
guest('command', command='summon minecraft:armor_stand 8.5 104 8.5 {Tags:["forced_tick"]}')
|
||||
guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}')
|
||||
wait_dimension(guest, OVERWORLD, 400)
|
||||
host('command', command='tick step 450')
|
||||
host.wait(500)
|
||||
prefix = f'execute in {dimension} '
|
||||
results[dimension] = server_reply(
|
||||
host, prefix + 'if data block 8 100 8 Items[{Slot:2b,id:"minecraft:iron_ingot"}] '
|
||||
'if data block 56 100 8 {cooking_time_spent:0} '
|
||||
'if data block 56 100 8 Items[{Slot:0b,id:"minecraft:raw_iron"}] '
|
||||
'if data entity @e[tag=forced_tick,limit=1] {Pos:[8.5d,101.0d,8.5d]} run say forced-level-pass',
|
||||
'forced-level-pass')
|
||||
assert dims(host, guest) == (OVERWORLD, OVERWORLD), dims(host, guest)
|
||||
host('command', command=prefix + 'run forceload remove 8 8')
|
||||
host('command', command=prefix + 'run kill @e[tag=forced_tick]')
|
||||
host('command', command='tick unfreeze')
|
||||
finally:
|
||||
host('command', command='tick unfreeze')
|
||||
for dimension in (NETHER, END):
|
||||
host('command', command=f'execute in {dimension} run forceload remove 8 8')
|
||||
guest('command', command=f'execute in {OVERWORLD} run tp @s {start[0]} {start[1]} {start[2]}')
|
||||
guest('command', command='gamemode survival')
|
||||
return results
|
||||
|
||||
|
||||
CHECKS += ['forced-levels']
|
||||
CHECK_FNS['forced-levels'] = check_forced_levels
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
+5
-12
@@ -28,19 +28,12 @@
|
||||
"python": "python3.13",
|
||||
"jobs": 6,
|
||||
"nice": 10,
|
||||
"note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the light Linux checks that used to go to the ThinkPad go here"
|
||||
},
|
||||
"thinkpad": {
|
||||
"ssh": "thinkpad",
|
||||
"root": "code/horizon-parity",
|
||||
"shell": "sh -c",
|
||||
"jobs": 2,
|
||||
"nice": 19,
|
||||
"environment": {
|
||||
"PARITY_BUILD_JOBS": "2"
|
||||
"exclude": {
|
||||
"mob_ai": "the vanilla oracle runs out of its 3 GB heap here (OutOfMemoryError in IO workers; passes on the desktop and the Mac) - 2026-10-26 trial",
|
||||
"lan_integration": "two clients rendered on the CPU (lavapipe): different timing subtests fail on each run (elytra, consume-release, barter, critical-hits) - 2026-10-26 trial",
|
||||
"world_reopen": "failed twice here (no Save and Quit button after reopening; the minecart-count flake), passes on the desktop - 2026-10-26 trial"
|
||||
},
|
||||
"note": "hosts the Claude account pool: two harnesses at most, at the lowest priority",
|
||||
"setup": "export PKG_CONFIG_PATH=$HOME/code/horizon-parity/alsa-dev/lib/pkgconfig"
|
||||
"note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), used by nothing else: 6 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the always-on Linux host since the ThinkPad stopped running harnesses (2026-10-26)"
|
||||
}
|
||||
},
|
||||
"local_only": {
|
||||
|
||||
+2
-4
@@ -46,12 +46,10 @@ from tools import parity, release_train # noqa: E402
|
||||
|
||||
RBUILD = Path.home() / "fleet" / "rbuild"
|
||||
LINE_LIMIT = 500
|
||||
# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad hosts
|
||||
# the Claude account pool: three jobs at most.
|
||||
# What rbuild's login shell needs on each fleet machine before cargo (it adds sccache itself). The ThinkPad no
|
||||
# longer builds (2026-10-26: it keeps the AI pool and a few services; Linux work goes to playhorizon's runner).
|
||||
HOST_SETUP = {
|
||||
"macmini": "source ~/.cargo/env; export PATH=/opt/homebrew/bin:$PATH CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-10}",
|
||||
"thinkpad": 'export CARGO_BUILD_JOBS=3 PKG_CONFIG_PATH="$(ls -d /nix/store/*-alsa-lib-*-dev/lib/pkgconfig | tail -1):'
|
||||
'$(ls -d /nix/store/*-systemd-*-dev/lib/pkgconfig | tail -1)"',
|
||||
"local": "",
|
||||
}
|
||||
# Hosts that hold the vanilla data, and how a run there gets it: CI's own runner scripts on the parity runner's
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check #1527: per-dimension /forceload add/remove across normal restarts.
|
||||
|
||||
Build horizon-client and horizon-ctl with the fast profile first, then run:
|
||||
python3 tools/singleplayer_forced_chunks_audit.py --case force-save
|
||||
Runs both default server-thread and in-frame singleplayer, using scratch homes.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from agent_control_e2e import Cli
|
||||
import lab
|
||||
|
||||
|
||||
DIMENSIONS = ('the_nether', 'the_end', 'overworld')
|
||||
|
||||
|
||||
def query(cli, dimension, expected):
|
||||
since = cli('events')['last']
|
||||
cli('command', command='forceload query')
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
reply = cli('events', since=since)
|
||||
for event in reply['events']:
|
||||
text = event.get('text', '')
|
||||
if event.get('event') != 'chat' or f'minecraft:{dimension}' not in text:
|
||||
continue
|
||||
if expected:
|
||||
if all(f'[{x}, {z}]' in text for x, z in expected):
|
||||
return
|
||||
elif 'No force loaded chunks' in text:
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise AssertionError(f'{dimension}: expected {expected}, got {reply}')
|
||||
|
||||
|
||||
def run(bin_dir, resources, in_frame):
|
||||
with tempfile.TemporaryDirectory(prefix='hz-force-save-') as scratch:
|
||||
work = Path(scratch)
|
||||
previous = None
|
||||
for stage in range(3):
|
||||
# Every process gets fresh homes; copy only this fixture's saved world.
|
||||
env = lab.game_env({k: v for k, v in os.environ.items() if k not in (
|
||||
'HORIZON_HOME', 'HORIZON_LAUNCHER_HOME', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME')})
|
||||
home = Path(env['HORIZON_HOME'])
|
||||
if previous is not None:
|
||||
shutil.copytree(previous, home / 'saves')
|
||||
socket = work / f'{stage}.sock'
|
||||
cli = Cli(bin_dir / 'horizon-ctl', socket, home, env)
|
||||
args = [str(bin_dir / 'horizon-client'), '--resources', str(resources),
|
||||
'--world', 'forced', '--creative', '--seed', '4242', '--offscreen',
|
||||
'--render-distance', '4', '--control', '--control-socket', str(socket)]
|
||||
if in_frame:
|
||||
args.append('--in-frame')
|
||||
with (work / f'{stage}.log').open('w') as log:
|
||||
process = subprocess.Popen(args, cwd=home, env=env, stdout=log, stderr=log)
|
||||
try:
|
||||
deadline = time.monotonic() + 120
|
||||
while not socket.exists():
|
||||
if process.poll() is not None or time.monotonic() > deadline:
|
||||
raise RuntimeError('game did not open its control socket')
|
||||
time.sleep(0.1)
|
||||
cli('wait_ready', seconds=240)
|
||||
for i, dim in enumerate(DIMENSIONS):
|
||||
cli('command', command=f'execute in minecraft:{dim} run tp @s 0 100 0')
|
||||
for _ in range(30):
|
||||
cli('wait', ticks=20)
|
||||
if cli('state').get('dimension') == f'minecraft:{dim}':
|
||||
break
|
||||
else:
|
||||
raise AssertionError(f'did not enter {dim}')
|
||||
cli('wait_ready', seconds=240)
|
||||
expected = [(i - 1, -1)] if stage == 1 else []
|
||||
query(cli, dim, expected)
|
||||
if stage == 0:
|
||||
cli('command', command=f'forceload add {(i - 1) * 16} -1')
|
||||
query(cli, dim, [(i - 1, -1)])
|
||||
elif stage == 1:
|
||||
cli('command', command=f'forceload remove {(i - 1) * 16} -1')
|
||||
query(cli, dim, [])
|
||||
cli('quit')
|
||||
assert process.wait(timeout=120) == 0
|
||||
except Exception:
|
||||
log.flush()
|
||||
print((work / f'{stage}.log').read_text(errors='replace')[-6000:])
|
||||
raise
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=30)
|
||||
previous = home / 'saves'
|
||||
print(f'PASS force-save: {"in-frame" if in_frame else "server-thread"}, three dimensions, add/remove/restart')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--case', choices=['force-save'], default='force-save')
|
||||
parser.add_argument('--bin-dir', type=Path, default=Path(__file__).resolve().parents[1] / 'target/fast')
|
||||
args = parser.parse_args()
|
||||
for in_frame in (False, True):
|
||||
run(args.bin_dir.resolve(), lab.RESOURCES.resolve(), in_frame)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the real Squid.aiStep client branch and cycle event with Rust."""
|
||||
import json
|
||||
import random
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def make_input(build):
|
||||
rng = random.Random(1684)
|
||||
rows = []
|
||||
for species in ('squid', 'glow_squid'):
|
||||
for water in (False, True):
|
||||
for reset in (False, True):
|
||||
for velocity in ((0, 0, 0), (.1, 0, 0), (0, .1, 0),
|
||||
(0, -.1, 0), (0, 0, -.1), (.1, .2, -.3)):
|
||||
for movement in (0, 1, 2.4, 3.14, 4, 6.2, 6.4):
|
||||
rows.append(dict(species=species, water=water, reset=reset,
|
||||
x=velocity[0], y=velocity[1], z=velocity[2],
|
||||
body=rng.uniform(-180, 180),
|
||||
v=[movement, .2, -45, 33, .15, .8]))
|
||||
for _ in range(1000):
|
||||
rows.append(dict(species=rng.choice(('squid', 'glow_squid')), water=True,
|
||||
reset=False, x=rng.uniform(.01, .2), y=rng.uniform(.01, .2),
|
||||
z=rng.uniform(.01, .2), body=rng.uniform(-180, 180),
|
||||
v=[rng.uniform(0, 7), 0, rng.uniform(-90, 90),
|
||||
rng.uniform(0, 180), rng.uniform(.1, .2), rng.random()]))
|
||||
path = build / 'inputs.jsonl'
|
||||
path.write_text(''.join(json.dumps(row) + '\n' for row in rows))
|
||||
return path, len(rows)
|
||||
|
||||
|
||||
def main():
|
||||
harness.differential(
|
||||
'rust-squid-client-parity', 'VanillaSquidClientOracle', 'squid_client_probe',
|
||||
make_input,
|
||||
'Actual Squid.aiStep on a client with controlled inherited movement/world services. '
|
||||
'Checks water/air body rotation and tentacle state, cycle clamping and event 19. '
|
||||
'Glow squid uses the same inherited method; packet dispatch and rendering are separate.',
|
||||
sources=[lab.ROOT / 'crates/horizon-client/src/mobs/aquatic.rs'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user