Merge parity-base into parity/platform-maths

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 04:31:39 +02:00
53 changed files with 7701 additions and 1576 deletions
+9 -10
View File
@@ -6,7 +6,7 @@
<a href="https://github.com/ludovic111/horizon/actions/workflows/ci.yml"><img src="https://github.com/ludovic111/horizon/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"></a>
<img src="https://img.shields.io/badge/Minecraft-Java%2026.3-5D9C3F" alt="Minecraft Java 26.3">
<img src="https://img.shields.io/badge/Rust-stable-B7410E?logo=rust&logoColor=white" alt="Rust">
<img src="https://img.shields.io/badge/vanilla%20parity-88%25-F0795A" alt="Vanilla parity 88%">
<img src="https://img.shields.io/badge/vanilla%20parity-89%25-F0795A" alt="Vanilla parity 89%">
<img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-2A2470" alt="Linux, macOS and Windows">
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-3B2F7E" alt="MIT license"></a>
</p>
@@ -22,7 +22,7 @@
A Rust rewrite of Minecraft: Java Edition 26.3 that aims for one-to-one vanilla parity, checked against the game itself with differential tests.
**Status:** in development. The native client is playable on Linux, macOS (Apple Silicon) and Windows; Java parity is 88% (see [Project status](#project-status)).
**Status:** in development. The native client is playable on Linux, macOS (Apple Silicon) and Windows; Java parity is 89% (see [Project status](#project-status)).
> Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft. Horizon contains no Minecraft code, assets or data: you need your own legally obtained copy of Minecraft: Java Edition 26.3.
@@ -111,9 +111,9 @@ The client starts on the title screen. Command-line options (`--world`, `--seed`
## Project status
Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, spawned mob gear enchantments, the resource pack screen, a dedicated server mode, and worlds older than 1.17.
Parity is **not** complete. The table below is the project's own audit of each subsystem. Still missing: the warden's brain and the sculk shrieker summoning it, villager breeding and gossip, the resource pack screen, a dedicated server mode, and worlds older than 1.17.
### Java parity: 88%
### Java parity: 89%
Each subsystem scores 0 (absent), 0.25 (started, not playable), 0.5 (playable,
major vanilla features missing), 0.75 (playable, mostly complete) or 1 (complete
@@ -130,11 +130,11 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and
| Network protocol and multiplayer | 0.75 | Joins vanilla servers and opens worlds to LAN; server.properties, eula.txt and the user lists match vanilla, but there is no dedicated server mode and LAN hosting is not tested against a vanilla client |
| Chunk storage and palettes | 1 | None: client and saves share paletted containers, identical to vanilla over 266 scenarios |
| Section meshing | 1 | None: 112 scenes and over a million quads identical to vanilla |
| Rendering | 0.75 | Entity models, block entity renderers (400 cases, End portals and gateways included) and their animations (256 cases), the HUD overlays (2,200 states), the player list, subtitles and the world border match vanilla; the recipe book's drawing and the banner preview are not compared, and End gateways show no beam in game |
| Rendering | 1 | None: entity models, block entity renderers (407 cases, End portals, gateways and the loom's banner preview included) and their animations (296 cases, End gateway beams included), the HUD overlays (2,200 states), the recipe book (600 states), the player list, subtitles and the world border match vanilla |
| Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included |
| World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla |
| Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.17 to 26.2 upgrade as vanilla's DataFixers do; worlds older than 1.17 are not upgraded |
| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases) and mob AI (71 of 72 scenarios, villager brains included) match; the warden's brain, villager breeding and gossip, and spawned mob gear are missing |
| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules, natural spawning (15,500 cases), raids and patrols (1,900 cases), spawned mobs' gear, enchantments and state (`finalizeSpawn`, 24,000 cases) and mob AI (71 of 72 scenarios, villager brains included) match; the warden's brain and villager breeding and gossip are missing |
| Interaction and inventory | 1 | None: menu clicks match over 8,000 click sequences, the loom and the crafter included; recipe book placement (6,000 cases), its buttons (1,200), the saved book (1,500) and the loom and crafter screens (1,600) match vanilla |
| Menus, HUD and chat | 0.75 | Every command runs as vanilla (758 commands over 39,685 parsed inputs), scoreboards and teams match (81,000 operations), and the player list matches over 844,758 draw calls; the focused chat is not compared and player list heads use default skins |
| Audio | 1 | None: the sound engine, sound events, music, situational music, ambience and subtitles match vanilla |
@@ -154,10 +154,9 @@ from vanilla in places: `mob_ai` (71 of 72 scenarios; a tempted ghastling) and
### Roadmap
1. Finish the warden's brain and the sculk shrieker summoning it, and the tempted ghastling.
2. Villager breeding and gossip, and spawned mob gear enchantments (both started on their branches).
3. A dedicated server mode, and LAN hosting tested with a vanilla client.
4. Save upgrades from before 1.17, and the resource pack screen.
5. Platform-independent float math, so every harness also gives vanilla's results on macOS.
2. A dedicated server mode, and LAN hosting tested with a vanilla client.
3. Save upgrades from before 1.17, and the resource pack screen.
4. Platform-independent float math, so every harness also gives vanilla's results on macOS.
The rewrite is complete when it reaches one-to-one parity and packaged native builds pass the launch checks in [Rust rewrite status](docs/rust-parity.md#completion-criteria-and-playable-builds).
@@ -8,9 +8,10 @@ use horizon_client::{
assets::Assets,
block_entity_anim::{
Bell, BellEntity, BlockEntityAnims, ChestLid, Conduit, ConduitTarget, DIRECTIONS,
PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot, direction_index,
EndGateway, PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot,
direction_index,
},
block_entity_render::BlockEntityRenderer,
block_entity_render::{BlockEntityRenderer, gateway_beam},
blocks::{BlockFacts, Fluid},
items::Items,
};
@@ -188,6 +189,14 @@ fn main() -> Result<()> {
let facing = prop(&block, "facing")
.and_then(direction_index)
.unwrap_or(1);
// End gateways: the saved age, the level's height range and the
// integrated server's copy.
let initial = EndGateway {
age: case["age"].as_i64().unwrap_or(0),
teleport_cooldown: 0,
};
let max_y = int(&case["level"][0]) + int(&case["level"][1]) - 1;
let mut server = initial;
let mut text = String::new();
for step in case["steps"].as_array().into_iter().flatten() {
let time = step["time"].as_i64().unwrap_or(0);
@@ -445,6 +454,36 @@ fn main() -> Result<()> {
f(progress),
style
);
} else if name == "minecraft:end_gateway" {
let client = anims.gateways.entry(pos).or_insert(initial);
if step["enter"].as_bool() == Some(true) && server.enter() {
log.push_str(" blockEvent 1 0");
client.trigger_event(1, 0);
}
if server.portal_tick() {
log.push_str(" blockEvent 1 0");
client.trigger_event(1, 0);
}
if let Some((e0, e1)) = event {
let handled = client.trigger_event(e0, e1);
let _ = write!(log, " event {handled}");
}
client.tick();
let g = *client;
let a = anims.block_anim(pos, time, partial, Default::default());
let b = gateway_beam(a.gateway, partial, max_y, time);
let _ = write!(
text,
"{} {} server {} {} render {} {} {:x} {}",
g.age,
g.teleport_cooldown,
server.age,
server.teleport_cooldown,
b.height,
f(b.scale),
b.color,
f(b.animation_time)
);
} else {
text = format!("unsupported {block}");
}
@@ -13,6 +13,7 @@ use horizon_client::{
},
chunk::{Chunk, Light},
hud::{HudAtlas, Rect},
item_render::{ItemRenderer, gui},
signs::{DYE_TEXT, SignData, SignText},
world::World,
};
@@ -119,6 +120,7 @@ fn main() -> Result<()> {
let renderer = BlockEntityRenderer::load(root, registry)?;
let atlas = HudAtlas::build(root)?;
let banners = Banners::load(root);
let items = ItemRenderer::load(root)?;
let (sprites, names, grid) = fake_sprites(textures)?;
let air = registry.default_state("minecraft:air").ok_or("no air")?;
let mut out = BufWriter::new(fs::File::create(output)?);
@@ -128,6 +130,43 @@ fn main() -> Result<()> {
{
let case: Value = serde_json::from_str(line)?;
let block = case["block"].as_str().unwrap_or_default();
if let Some(loom) = case.get("loom") {
// The loom's result preview, as LoomScreen draws it at (0, 0).
let layers: Vec<(String, String)> = loom["patterns"]
.as_array()
.into_iter()
.flatten()
.map(|p| {
(
banners.banner_texture(p[0].as_str().unwrap_or_default()),
p[1].as_str().unwrap_or_default().to_owned(),
)
})
.collect();
let base = loom["base"].as_str().unwrap_or_default();
let flat = gui::items_flat_lights();
let quads: Vec<Value> =
gui::banner_result_quads(&items, &sprites, 0.0, 0.0, base, &layers)
.iter()
.map(|q| {
let (cu, cv) = ((q.uv[0][0] / 2.0).floor(), (q.uv[0][1] / 2.0).floor());
let texture = names
.get(cu as usize + cv as usize * grid)
.cloned()
.unwrap_or_default();
let v: Vec<Value> = (0..4)
.map(|k| {
let p = q.pos[k];
json!([p.x, p.y, p.z, q.uv[k][0] - cu * 2.0, q.uv[k][1] - cv * 2.0])
})
.collect();
// Full bright (15728880).
json!({"texture": texture, "v": v, "color": gui::lit_color(q, flat), "light": 0xF0F0})
})
.collect();
writeln!(out, "{}", json!({"quads": quads, "texts": []}))?;
continue;
}
if block == "minecraft:beacon" {
// BeaconRenderer: the beam sections from the case, as Horizon's beacon keeps them.
let int = |v: &Value| v.as_i64().unwrap_or(0);
@@ -0,0 +1,531 @@
//! `Mob.finalizeSpawn` for differential tests against vanilla
//! (tools/test_finalize_spawn_parity.py): reads the cases of
//! `VanillaFinalizeSpawnOracle`, runs `mobs::finalize` with the same level
//! random and entity randoms, and prints every entity of the case in the
//! oracle's format.
//!
//! usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN
use horizon_client::{
assets::Assets,
blocks::BlockFacts,
enchant::Enchantments,
items::Items,
mobs::{
Mob, MobTypes, Species,
data::MobData,
finalize::{self, Attr, Ctx, FinalizeLevel, Reason, SpawnData, SpawnRegistries},
gear,
render::{DYE_NAMES, PROFESSIONS, VILLAGER_TYPES},
spawning::LocalDifficulty,
},
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
use std::{collections::HashMap, fmt::Write as _, fs, path::Path, sync::Arc};
struct Level<'a> {
types: &'a MobTypes,
data: &'a MobData,
biome: String,
structure: Option<(String, [i32; 6])>,
phase: usize,
monsters: bool,
peaceful: bool,
time: i64,
halloween: bool,
roof: Option<i32>,
eseed: i64,
/// Every entity of the case in creation order (case chickens first).
created: usize,
/// The level's entities that can carry a zombie: (id, bounds, ridden).
chickens: Vec<(u32, Aabb, bool)>,
rides: Vec<(u32, u32)>,
}
impl FinalizeLevel for Level<'_> {
fn biome(&self, _pos: [i32; 3]) -> String {
self.biome.clone()
}
fn biome_tag(&self, tag: &str, _pos: [i32; 3]) -> bool {
self.data.biome_has(tag, &self.biome)
}
fn structures_with_piece_at(&self, pos: [i32; 3]) -> Vec<String> {
match &self.structure {
Some((id, b))
if pos[0] >= b[0]
&& pos[0] <= b[3]
&& pos[1] >= b[1]
&& pos[1] <= b[4]
&& pos[2] >= b[2]
&& pos[2] <= b[5] =>
{
vec![id.clone()]
}
_ => Vec::new(),
}
}
fn moon_phase(&self, _pos: [i32; 3]) -> usize {
self.phase
}
fn spawning_monsters(&self) -> bool {
self.monsters
}
fn no_collision(&self, bounds: Aabb) -> bool {
// A floor under the spawn point and an optional roof layer.
self.roof.is_none_or(|y| {
let (lo, hi) = (
bounds.min(horizon_core::geometry::Axis::Y),
bounds.max(horizon_core::geometry::Axis::Y),
);
!(lo < f64::from(y) + 1.0 && hi > f64::from(y))
})
}
fn free_chicken(&self, bounds: Aabb) -> Option<u32> {
self.chickens
.iter()
.find(|(_, b, ridden)| !ridden && b.intersects(bounds))
.map(|c| c.0)
}
fn ride_chicken(&mut self, chicken: u32, rider: u32) {
if let Some(c) = self.chickens.iter_mut().find(|c| c.0 == chicken) {
c.2 = true;
}
self.rides.push((chicken, rider));
}
fn game_time(&self) -> i64 {
self.time
}
fn halloween(&self) -> bool {
self.halloween
}
fn create(&mut self, kind: &str, _reason: Reason) -> Option<Mob> {
if self.peaceful && !finalize::allowed_in_peaceful(kind) {
return None;
}
let t = Arc::new(self.types.types.get(kind)?.clone());
let index = self.created;
self.created += 1;
let mut m = Mob::new(index as u32 + 1, t, Vec3::ZERO, 0.0);
m.random = LegacyRandom::new(self.eseed.wrapping_add(index as i64));
Some(m)
}
}
fn hex64(v: f64) -> String {
format!("{:x}", v.to_bits())
}
fn hex32(v: f32) -> String {
format!("{:x}", v.to_bits())
}
const HORSE: [&str; 7] = [
"white",
"creamy",
"chestnut",
"brown",
"black",
"gray",
"dark_brown",
];
const MARKINGS: [&str; 5] = ["none", "white", "white_field", "white_dots", "black_dots"];
const RABBITS: [&str; 6] = ["brown", "white", "black", "white_splotched", "gold", "salt"];
const PARROTS: [&str; 5] = ["red_blue", "blue", "green", "yellow_blue", "gray"];
const AXOLOTLS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"];
const SALMON: [&str; 3] = ["small", "medium", "large"];
const GENES: [&str; 7] = [
"normal",
"lazy",
"worried",
"playful",
"brown",
"weak",
"aggressive",
];
const MEMORIES: [&str; 7] = [
"long_jump_cooldown",
"ram_cooldown",
"attack_target_cooldown",
"hunted_recently",
"dig_cooldown",
"is_emerging",
"home",
];
fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec<String>) {
use Species as S;
let s = m.species();
let named = |reg: &finalize::VariantRegistry, i: u8| {
format!(
"minecraft:{}",
reg.names.get(i as usize).map_or("?", |n| n.as_str())
)
};
let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant));
match s {
S::Pig => {
v.push(var);
v.push(named(&regs.pig_sound, m.extra.sound_variant));
}
S::Cow => {
v.push(var);
v.push(named(&regs.cow_sound, m.extra.sound_variant));
}
S::Mooshroom => v.push(if m.extra.variant == 0 { "red" } else { "brown" }.into()),
S::Chicken => {
v.push(var);
v.push(named(&regs.chicken_sound, m.extra.sound_variant));
v.push(format!("jockey={}", m.extra.jockey));
}
S::Cat => {
v.push(var);
v.push(named(&regs.cat_sound, m.extra.sound_variant));
}
S::Wolf => {
v.push(var);
v.push(named(&regs.wolf_sound, m.extra.sound_variant));
}
S::Frog | S::ZombieNautilus => v.push(var),
S::Sheep => v.push(DYE_NAMES[m.extra.color as usize & 15].into()),
S::Horse => v.push(format!(
"{}/{}",
HORSE[m.extra.variant as usize % 7],
MARKINGS[m.extra.variant2 as usize % 5]
)),
S::Llama | S::TraderLlama => v.push(format!(
"{}/{}",
horizon_client::mobs::llama::VARIANTS[m.extra.variant as usize % 4],
m.extra.variant2
)),
S::SkeletonHorse => v.push(format!("trap={}", m.extra.trap)),
S::Fox => v.push(if m.extra.variant == 1 { "snow" } else { "red" }.into()),
S::Rabbit => v.push(RABBITS[m.extra.variant as usize % 6].into()),
S::Parrot => v.push(PARROTS[m.extra.variant as usize % 5].into()),
S::Axolotl => v.push(AXOLOTLS[m.extra.variant as usize % 5].into()),
S::TropicalFish => {
let p = u32::from(m.extra.variant);
let pattern = if p < 6 { p << 8 } else { 1 | (p - 6) << 8 };
let packed = (pattern & 0xFFFF)
| (u32::from(m.extra.variant2) & 0xFF) << 16
| (u32::from(m.extra.variant3) & 0xFF) << 24;
v.push((packed as i32).to_string());
}
S::Salmon => v.push(SALMON[m.extra.variant as usize % 3].into()),
S::Panda => v.push(format!(
"{}/{}",
GENES[m.extra.variant as usize % 7],
GENES[m.extra.variant2 as usize % 7]
)),
S::Goat => v.push(format!(
"scream={} horns={},{}",
m.extra.screaming, !m.extra.lost_horns[0], !m.extra.lost_horns[1]
)),
S::Slime | S::MagmaCube | S::SulfurCube => v.push(format!("size={}", m.extra.size.max(1))),
S::Villager => v.push(format!(
"minecraft:{}/minecraft:{}/{}",
VILLAGER_TYPES[m.extra.variant as usize % 7],
PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()],
m.extra.variant3.max(1)
)),
S::ZombieVillager => v.push(format!(
"minecraft:{}/{}",
VILLAGER_TYPES[m.extra.variant as usize % 7],
m.extra.variant3.max(1)
)),
S::Phantom => v.push(format!("size={}", m.extra.size)),
S::Turtle => v.push(format!(
"home={}",
m.extra
.home
.map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2]))
)),
S::Dolphin => v.push(format!("air={}", m.air)),
_ => {}
}
if matches!(
s,
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin
) {
v.push(format!("doors={}", m.extra.can_break_doors));
}
if horizon_client::mobs::raider::is_raider(s) {
let st = horizon_client::mobs::raider::state(m);
v.push(format!(
"leader={} patrolling={}",
st.is_some_and(|s| s.patrol_leader),
st.is_some_and(|s| s.patrolling)
));
v.push(format!("raid={}", st.is_some_and(|s| s.can_join_raid)));
}
if s == S::Strider {
v.push(format!("saddled={}", m.extra.saddled));
}
}
fn describe(m: &Mob, all: &[Mob], regs: &SpawnRegistries) -> String {
let mut t = vec![m.kind.id.clone()];
let vehicle = m
.extra
.mount
.and_then(|v| all.iter().position(|o| o.id == v))
.map_or("-".to_owned(), |i| i.to_string());
t.push(format!("veh={vehicle}"));
if finalize::ageable(m.species()) {
t.push(format!("age={}", m.extra.age));
} else {
t.push(format!("baby={}", m.is_baby()));
}
t.push(format!("hp={}", hex32(m.health)));
t.push(format!("lh={}", m.extra.left_handed));
t.push(format!("loot={}", m.can_pick_up_loot()));
t.push(format!("persist={}", m.persistent));
let mut eq = Vec::new();
for (slot, name) in finalize::SLOT_NAMES.iter().enumerate() {
let Some(id) = finalize::item(m, slot) else {
continue;
};
let mut text = id.to_string();
let g = match slot {
0 => Some(gear::MAIN),
1 => Some(gear::OFF),
2 => Some(gear::FEET),
3 => Some(gear::LEGS),
4 => Some(gear::CHEST),
5 => Some(gear::HEAD),
_ => None,
};
if let (Some(g), Some(levels)) = (g, gear::gear(m)) {
let mut list: Vec<String> = levels.slots[g]
.iter()
.map(|(e, l)| format!("{e}={l}"))
.collect();
list.sort();
if !list.is_empty() {
let _ = write!(text, "[{}]", list.join(","));
}
}
if slot == 5 && horizon_client::mobs::raider::is_captain(m) {
text.push_str("*4");
}
eq.push(format!("{name}:{text}"));
}
t.push(format!(
"eq={}",
if eq.is_empty() {
"-".into()
} else {
eq.join(";")
}
));
let drops: Vec<String> = finalize::SLOT_NAMES
.iter()
.enumerate()
.filter_map(|(i, name)| {
let d = finalize::stored_drop_chance(m, i);
(d != 0.085).then(|| format!("{name}:{}", hex32(d)))
})
.collect();
t.push(format!(
"drop={}",
if drops.is_empty() {
"-".into()
} else {
drops.join(";")
}
));
let attrs: Vec<String> = [
Attr::MaxHealth,
Attr::MovementSpeed,
Attr::FollowRange,
Attr::AttackDamage,
Attr::KnockbackResistance,
Attr::SpawnReinforcements,
Attr::JumpStrength,
]
.into_iter()
.filter(|a| finalize::default_value(m, *a).is_some())
.map(|a| format!("{}:{}", a.name(), hex64(finalize::value(m, a))))
.collect();
t.push(format!("a={}", attrs.join(",")));
let mut fx: Vec<String> = m
.extra
.effects
.iter()
.map(|(e, d, a)| format!("{e}:{a}:{d}"))
.collect();
fx.sort();
t.push(format!(
"fx={}",
if fx.is_empty() {
"-".into()
} else {
fx.join(",")
}
));
let mem: Vec<String> = MEMORIES
.iter()
.filter_map(|name| {
let (_, value, ttl) = m.extra.memories.iter().find(|x| x.0 == *name)?;
let text = match *name {
"hunted_recently" => "true".to_owned(),
"dig_cooldown" | "is_emerging" => "INSTANCE".to_owned(),
"home" => m
.extra
.home
.map_or("-".into(), |h| format!("{},{},{}", h[0], h[1], h[2])),
_ => value.to_string(),
};
Some(format!("{name}:{text}:{ttl}"))
})
.collect();
if !mem.is_empty() {
t.push(format!("mem={}", mem.join(",")));
}
let mut v = Vec::new();
variant(m, regs, &mut v);
if !v.is_empty() {
t.push(format!("v={}", v.join(" ").replace(' ', "_")));
}
t.join(" ")
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(
args.get(1)
.ok_or("usage: finalize_spawn_fixture RESOURCES INPUT OUTPUT HALLOWEEN")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let halloween = args.get(4).is_some_and(|h| h == "true");
let assets = Assets::load(root)?;
let facts = BlockFacts::load(root, assets.registry)?;
let mob_data = MobData::load(root, &facts);
let items = Items::tags_only(root)?;
let enchantments = Enchantments::load(root);
let types = MobTypes::load(root)?;
let registries = SpawnRegistries::load(root);
let camel = &types.types["minecraft:camel_husk"];
let data = SpawnData {
registries: &registries,
enchantments: &enchantments,
items: &items,
camel_husk_size: (camel.width as f32, camel.height as f32),
};
let mut out = format!("halloween {halloween}\n");
for line in input.lines().filter(|l| !l.trim().is_empty()) {
let mut c: HashMap<&str, &str> = HashMap::new();
let mut name = "";
for token in line.split_whitespace() {
match token.split_once('=') {
Some((k, v)) => {
c.insert(k, v);
}
None => name = token,
}
}
let get =
|k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() };
let p: Vec<f64> = get("pos", "0,0,0")
.split(',')
.map(|x| x.parse().unwrap_or(0.0))
.collect();
let pos = Vec3::new(p[0], p[1], p[2]);
let block = [
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32,
];
let base = match get("difficulty", "normal").as_str() {
"peaceful" => 0,
"easy" => 1,
"hard" => 3,
_ => 2,
};
let phase: usize = get("phase", "0").parse().unwrap_or(0);
let time: i64 = get("time", "0").parse().unwrap_or(0);
let inhabited: i64 = get("inhabited", "0").parse().unwrap_or(0);
let difficulty = LocalDifficulty::new(
base,
time,
inhabited,
horizon_client::mobs::spawning::MOON_BRIGHTNESS[phase & 7],
);
let mut level = Level {
types: &types,
data: &mob_data,
biome: get("biome", "minecraft:plains"),
structure: c.get("structure").map(|s| {
(
(*s).to_owned(),
[
block[0] - 8,
block[1] - 8,
block[2] - 8,
block[0] + 8,
block[1] + 8,
block[2] + 8,
],
)
}),
phase,
monsters: get("monsters", "1") != "0",
peaceful: base == 0,
time,
halloween,
roof: c
.get("roof")
.and_then(|r| r.parse::<i32>().ok())
.map(|r| block[1] + r),
eseed: get("eseed", "0").parse().unwrap_or(0),
created: 0,
chickens: Vec::new(),
rides: Vec::new(),
};
let mut all: Vec<Mob> = Vec::new();
let chickens: usize = get("chickens", "0").parse().unwrap_or(0);
for i in 0..chickens {
if let Some(mut chicken) = level.create("minecraft:chicken", Reason::Load) {
chicken.position = Vec3::new(pos.x + i as f64, pos.y, pos.z);
level.chickens.push((chicken.id, chicken.bounds(), false));
all.push(chicken);
}
}
let kind = get("type", "minecraft:pig");
let reason = Reason::parse(&get("reason", "NATURAL")).unwrap_or(Reason::Natural);
let pack: usize = get("pack", "1").parse().unwrap_or(1);
let mut random = LegacyRandom::new(get("seed", "0").parse().unwrap_or(0));
let mut group = None;
for _ in 0..pack {
let Some(mut mob) = level.create(&kind, reason) else {
break;
};
mob.position = pos;
mob.previous = pos;
let mut cx = Ctx {
level: &mut level,
random: &mut random,
difficulty,
data: &data,
created: Vec::new(),
};
group = finalize::finalize(&mut cx, &mut mob, reason, group);
let created = std::mem::take(&mut cx.created);
all.push(mob);
all.extend(created);
}
for (chicken, rider) in std::mem::take(&mut level.rides) {
if let Some(c) = all.iter_mut().find(|m| m.id == chicken) {
c.extra.jockey = true;
c.extra.rider = Some(rider);
}
}
all.sort_by_key(|m| m.id);
let mut parts: Vec<String> = all.iter().map(|m| describe(m, &all, &registries)).collect();
for m in &mut all {
parts.push(format!("rng {}", m.random.next_long()));
}
parts.push(format!("next {}", random.next_long()));
let _ = writeln!(out, "{name} {}", parts.join(" | "));
}
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
Ok(())
}
+65 -6
View File
@@ -435,6 +435,13 @@ fn print_heart(
);
}
/// The damage of a mob's direct hit on the player (others count as none).
fn player_damage(e: &MobEvent) -> f32 {
match e {
MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount,
_ => 0.0,
}
}
/// Whether an event hurts the scenario's player (survival, normal difficulty,
/// no armour, made hurtable again every tick by the oracle).
fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
@@ -455,7 +462,9 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
}
}
fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
/// `player_down`: the scenario's player is no valid target (creative, or
/// killed this tick).
fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) {
let _ = write!(out, "{t} {i}");
if m.removed {
// Entity.RemovalReason: the end of the death animation, else a discard.
@@ -495,7 +504,13 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
"\tgoals {}\ttargets {}\ttarget {}",
goals(m, m.ai.goals.running_names()),
goals(m, m.ai.targets.running_names()),
who(m.ai.target)
// Warden.getTarget: the brain's attack target, if still valid.
who(match horizon_client::mobs::warden::brain_target(m) {
Some(Who::Player) if player_down => None,
Some(target) => Some(target),
None if m.species() == Species::Warden => None,
None => m.ai.target,
})
);
let _ = write!(out, "\tnav ");
match &m.ai.nav.path {
@@ -551,6 +566,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
);
let _ = write!(out, "\trng {:x}", m.random.state());
let brain = horizon_client::mobs::villager_brain::describe(m)
.or_else(|| horizon_client::mobs::warden_brain::describe(m))
.or_else(|| horizon_client::mobs::monster_brain::describe(m))
.or_else(|| horizon_client::mobs::animal_brain::describe(m));
if let Some((acts, mem)) = brain {
@@ -762,6 +778,12 @@ fn main() -> horizon_client::Result<()> {
match flag.as_str() {
"persistent" => m.persistent = true,
"noai" => m.no_ai = true,
// Warden.finalizeSpawn's own part.
"digcooldown" | "emerge" => horizon_client::mobs::warden::finalize(
&mut m,
flag == "emerge",
&mut Vec::new(),
),
"inlove" => m.extra.in_love = 600,
"tame" => m.extra.tame = true,
x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(),
@@ -790,13 +812,20 @@ fn main() -> horizon_client::Result<()> {
spec.seed,
);
}
if m.species() == Species::Warden {
// As for villagers: the sensors delayed again, the RunOne seeded.
horizon_client::mobs::warden::init_brain(&mut m, spec.seed);
}
// The same for the sniffer's and the happy ghast's brains.
if horizon_client::mobs::animal_brain::kind_of(&m).is_some() {
horizon_client::mobs::animal_brain::init(&mut m, spec.seed);
}
mobs.push(m);
}
let mut player = s.player.map(|p| {
// Without a player of its own a scenario still has the oracle's,
// 5000 blocks east (Mob.checkDespawn draws for it).
let far = [f64::from(s.origin[0] + 5000), -60.0, f64::from(s.origin[1])];
let mut player = Some(s.player.unwrap_or(far)).map(|p| {
let position = Vec3::new(p[0], p[1], p[2]);
PlayerView {
position,
@@ -826,7 +855,7 @@ fn main() -> horizon_client::Result<()> {
});
let mut scratch = LegacyRandom::new(0);
for (i, m) in mobs.iter().enumerate() {
print(&mut out, 0, i, m);
print(&mut out, 0, i, m, s.creative);
}
// The MobWorld every step sees, over a snapshot of the mobs.
macro_rules! mob_world {
@@ -964,6 +993,26 @@ fn main() -> horizon_client::Result<()> {
&mut born,
s.time,
);
horizon_client::mobs::warden::hear_mob_events(&mut mobs, &events, from, &w);
// Melee hits on other mobs land during the attacker's tick
// (LivingEntity.hurtServer), with the sounds they raise.
let mut k = from;
while k < events.len() {
if let MobEvent::AttackMob {
target,
amount,
source,
} = events[k]
&& let Some(t) = mobs.iter_mut().find(|m| m.id == target)
&& t.damage(amount, source)
{
let raised = std::mem::take(&mut t.outbox);
let n = raised.len();
events.splice(k + 1..k + 1, raised);
k += n;
}
k += 1;
}
// ServerLevel ticks entities one after another: the ones
// after this mob see it as it is now.
if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) {
@@ -1008,8 +1057,13 @@ fn main() -> horizon_client::Result<()> {
_ => {}
}
}
// A hit for the player's whole health kills it until the oracle
// heals it next tick.
let player_killed = events
.iter()
.any(|e| player_hurt(player.as_ref(), e) && player_damage(e) >= 20.0);
for (i, m) in mobs.iter().enumerate() {
print(&mut out, t, i, m);
print(&mut out, t, i, m, s.creative || player_killed);
}
for e in &events {
if let MobEvent::Sound(name, _, volume, pitch) = e {
@@ -1024,9 +1078,14 @@ fn main() -> horizon_client::Result<()> {
} else if player_hurt(player.as_ref(), e) {
// The oracle's survival player, healed and made hurtable every tick,
// takes the damage (LivingEntity.playHurtSound).
let sound = if player_damage(e) >= 20.0 {
"death"
} else {
"hurt"
};
let _ = writeln!(
out,
"{t} sound minecraft:entity.player.hurt 3f800000 3f800000"
"{t} sound minecraft:entity.player.{sound} 3f800000 3f800000"
);
}
}
@@ -0,0 +1,263 @@
//! The recipe book's drawing, for tools/test_recipe_book_render_parity.py:
//! reads one JSON case per line (book type, GUI size, tabs, search box,
//! filter, recipe collections and page, overlay, ghost slots, cycling index,
//! mouse) and writes the calls `horizon_client::recipe_book_screen` makes,
//! in the oracle's JSON form.
//!
//! usage: recipe_book_render_fixture RESOURCES CASES OUTPUT
use horizon_client::{
crafting::Recipes,
hud::{HudAtlas, HudBatch},
items::{ItemStack, Items},
lang,
recipe_book::{Book, BookType, Entry},
recipe_book_screen::{
ButtonView, Call, GhostView, ItemCall, OverlayRecipe, OverlayView, Run, Screen, Search,
TabView, draw, overlay_cells, overlay_origin,
},
};
use serde_json::{Value, json};
use std::{fmt::Write as _, fs, path::Path};
fn runs(r: &[Run]) -> Value {
Value::Array(
r.iter()
.map(|r| json!([r.text, r.color, r.italic]))
.collect(),
)
}
fn round(v: f32) -> f32 {
(v * 1e4).round() / 1e4
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let usage = "usage: recipe_book_render_fixture RESOURCES CASES OUTPUT";
let root = Path::new(args.get(1).ok_or(usage)?);
let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?;
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let book = Book::build(&recipes, &items);
let atlas = HudAtlas::build(root)?;
let root_buf = root.to_path_buf();
lang::set(lang::Language::load(&[&root_buf], lang::DEFAULT));
let translate = |key: &str| lang::get(key);
let text_width = |s: &str| HudBatch::text_width(&atlas, s) as i32;
let mut out = String::new();
for line in cases.lines() {
let case: Value = serde_json::from_str(line)?;
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
let kind = match case["type"].as_str().unwrap_or_default() {
"crafting" => BookType::Crafting,
"furnace" => BookType::Furnace,
"blast_furnace" => BookType::BlastFurnace,
_ => BookType::Smoker,
};
let filtering = case["filtering"].as_bool().unwrap_or(false);
let tab_list = kind.tabs();
let tabs: Vec<TabView> = case["tabs"]
.as_array()
.into_iter()
.flatten()
.map(|t| {
let (a, b) = tab_list[t["tab"].as_u64().unwrap_or(0) as usize].icons();
TabView {
icons: (a.to_owned(), b.map(str::to_owned)),
selected: t["selected"].as_bool().unwrap_or(false),
anim: t["anim"].as_f64().unwrap_or(0.0) as f32,
}
})
.collect();
let s = &case["search"];
let search = Search {
value: s["value"].as_str().unwrap_or_default().to_owned(),
cursor: s["cursor"].as_u64().unwrap_or(0) as usize,
highlight: s["highlight"].as_u64().unwrap_or(0) as usize,
display: s["display"].as_u64().unwrap_or(0) as usize,
focused: s["focused"].as_bool().unwrap_or(false),
blink_ms: s["blink"].as_u64().unwrap_or(0),
};
// Each collection's recipes and craftable flags.
let collections: Vec<Vec<(&Entry, bool)>> = case["collections"]
.as_array()
.into_iter()
.flatten()
.map(|c| {
c["recipes"]
.as_array()
.into_iter()
.flatten()
.filter_map(|r| Some((book.entry(r[0].as_str()?)?, r[1].as_bool()?)))
.collect()
})
.collect();
let page = case["page"].as_u64().unwrap_or(0) as usize;
let pages = collections.len().div_ceil(20);
let anims = case["buttonAnims"].as_array().cloned().unwrap_or_default();
let shown = &collections[(20 * page).min(collections.len())..];
let buttons: Vec<ButtonView> = shown
.iter()
.take(20)
.enumerate()
.map(|(i, c)| ButtonView {
has_craftable: c.iter().any(|e| e.1),
entries: c
.iter()
.filter(|e| e.1 || !filtering)
.map(|e| vec![e.0.result.clone()])
.collect(),
anim: anims.get(i).and_then(Value::as_f64).unwrap_or(0.0) as f32,
})
.collect();
let (xo, yo) = Screen {
book: kind,
width: int(&case["width"]),
height: int(&case["height"]),
narrow: case["narrow"].as_bool().unwrap_or(false),
mouse: (0, 0),
index: 0,
filtering,
search: &search,
tabs: &[],
buttons: &[],
page,
pages,
overlay: None,
ghost: None,
translate: &translate,
text_width: &text_width,
}
.origin();
let overlay = case["overlay"].as_u64().map(|i| {
let i = i as usize;
let c = &shown[i];
let mut recipes: Vec<OverlayRecipe> = c
.iter()
.filter(|e| e.1)
.map(|e| OverlayRecipe {
craftable: true,
cells: overlay_cells(&book, e.0),
})
.collect();
if !filtering {
recipes.extend(c.iter().filter(|e| !e.1).map(|e| OverlayRecipe {
craftable: false,
cells: overlay_cells(&book, e.0),
}));
}
let (x, y) = overlay_origin(
xo + 11 + 25 * (i as i32 % 5),
yo + 31 + 25 * (i as i32 / 5),
recipes.len(),
xo,
yo,
);
OverlayView { x, y, recipes }
});
let ghosts: Vec<GhostView> = case["ghost"]
.as_array()
.into_iter()
.flatten()
.map(|g| GhostView {
x: int(&g["x"]),
y: int(&g["y"]),
result: g["result"].as_bool().unwrap_or(false),
items: g["items"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(|i| ItemStack::new(i, 1))
.collect(),
})
.collect();
let screen = Screen {
book: kind,
width: int(&case["width"]),
height: int(&case["height"]),
narrow: case["narrow"].as_bool().unwrap_or(false),
mouse: (int(&case["mouse"][0]), int(&case["mouse"][1])),
index: case["index"].as_u64().unwrap_or(0) as usize,
filtering,
search: &search,
tabs: &tabs,
buttons: &buttons,
page,
pages,
overlay: overlay.as_ref(),
ghost: case.get("ghost").map(|_| {
(
int(&case["left"]),
int(&case["top"]),
case["big"].as_bool().unwrap_or(false),
ghosts.as_slice(),
)
}),
translate: &translate,
text_width: &text_width,
};
let draws: Vec<Value> = draw(&screen)
.into_iter()
.filter_map(|d| {
let m: Vec<f32> = d.pose.iter().map(|v| round(*v)).collect();
let mut o = match d.call {
Call::Blit {
texture,
x,
y,
w,
h,
u,
v,
tw,
th,
} => json!({"t": "blit", "texture": texture, "x": x, "y": y, "w": w, "h": h,
"u": u, "v": v, "tw": tw, "th": th}),
Call::Sprite { id, x, y, w, h } => {
json!({"t": "sprite", "id": id, "x": x, "y": y, "w": w, "h": h})
}
Call::Fill {
x0,
y0,
x1,
y1,
color,
} => json!({"t": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color}),
Call::Highlight { x0, y0, x1, y1 } => {
json!({"t": "highlight", "x0": x0, "y0": y0, "x1": x1, "y1": y1})
}
Call::Text {
runs: r,
x,
y,
color,
shadow,
} => json!({"t": "text", "runs": runs(&r), "x": x, "y": y, "color": color, "shadow": shadow}),
Call::Item { call, stack, x, y } => {
if stack.count == 0 || &*stack.item == "minecraft:air" {
return None;
}
let t = match call {
ItemCall::Item => "item",
ItemCall::Fake => "fake",
ItemCall::Decorations => "decorations",
};
json!({"t": t, "id": &*stack.item, "count": stack.count, "x": x, "y": y})
}
Call::Tooltip(lines) => {
json!({"t": "tooltip", "lines": lines.iter().map(|l| runs(l)).collect::<Vec<_>>()})
}
Call::ItemTooltip { stack, more } => {
json!({"t": "item_tooltip", "id": &*stack.item, "more": more})
}
Call::Stratum => json!({"t": "stratum"}),
};
o["m"] = json!(m);
Some(o)
})
.collect();
let _ = writeln!(out, "{}", json!({ "draws": draws }));
}
fs::write(args.get(3).ok_or(usage)?, out)?;
Ok(())
}
+66 -3
View File
@@ -725,6 +725,55 @@ impl PotWobble {
}
}
/// `TheEndGatewayBlockEntity` fields the beam reads.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EndGateway {
pub age: i64,
pub teleport_cooldown: i32,
}
impl EndGateway {
/// `beamAnimationTick` (the client ticker).
pub fn tick(&mut self) {
self.age = self.age.wrapping_add(1);
if self.teleport_cooldown > 0 {
self.teleport_cooldown -= 1;
}
}
/// `portalTick` on the server copy: whether it called `triggerCooldown`,
/// whose block event 1 reaches the client copy.
pub fn portal_tick(&mut self) -> bool {
let cooling = self.teleport_cooldown > 0;
self.age = self.age.wrapping_add(1);
if cooling {
self.teleport_cooldown -= 1;
false
} else if self.age % 2400 == 0 {
self.teleport_cooldown = 40;
true
} else {
false
}
}
/// `EndGatewayBlock.entityInside` on the server copy: an entity that can
/// use the portal starts the cooldown unless it is already running.
pub fn enter(&mut self) -> bool {
if self.teleport_cooldown > 0 {
return false;
}
self.teleport_cooldown = 40;
true
}
/// `triggerEvent`: event 1 starts the 40 tick cooldown.
pub fn trigger_event(&mut self, event: i32, _data: i32) -> bool {
if event == 1 {
self.teleport_cooldown = 40;
true
} else {
false
}
}
}
/// The client ticker a block entity runs (`getTicker` on a client level),
/// or [`Ticker::Pot`] for decorated pots, which keep wobble state unticked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -746,6 +795,8 @@ pub enum Ticker {
powered: bool,
},
Pot,
/// `TheEndGatewayBlockEntity.beamAnimationTick`.
Gateway,
}
/// The [`Ticker`] of a block state, by block name and property lookup.
@@ -764,6 +815,7 @@ pub fn ticker(name: &str, prop: impl Fn(&str) -> Option<String>) -> Option<Ticke
"bell" => Ticker::Bell,
"conduit" => Ticker::Conduit,
"decorated_pot" => Ticker::Pot,
"end_gateway" => Ticker::Gateway,
"dragon_head" | "dragon_wall_head" | "piglin_head" | "piglin_wall_head" => Ticker::Skull {
powered: prop("powered").as_deref() == Some("true"),
},
@@ -789,6 +841,9 @@ pub struct BlockEntityAnims {
pub conduits: HashMap<[i32; 3], Conduit>,
pub skulls: HashMap<[i32; 3], Skull>,
pub pots: HashMap<[i32; 3], PotWobble>,
pub gateways: HashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the gateways (`portalTick`).
pub gateway_servers: HashMap<[i32; 3], EndGateway>,
/// The client level's random (conduit particles).
pub random: LegacyRandom,
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
@@ -805,6 +860,8 @@ impl Default for BlockEntityAnims {
conduits: HashMap::new(),
skulls: HashMap::new(),
pots: HashMap::new(),
gateways: HashMap::new(),
gateway_servers: HashMap::new(),
random: LegacyRandom::new(0x6c6576656c),
kinds: Vec::new(),
}
@@ -839,6 +896,8 @@ impl BlockEntityAnims {
self.skulls
.retain(|p, _| is(p, |t| matches!(t, Ticker::Skull { .. })));
self.pots.retain(|p, _| is(p, |t| *t == Ticker::Pot));
self.gateways
.retain(|p, _| is(p, |t| *t == Ticker::Gateway));
}
/// Drops the state of positions whose block entity is gone.
pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) {
@@ -849,6 +908,8 @@ impl BlockEntityAnims {
self.conduits.retain(|p, _| keep(*p));
self.skulls.retain(|p, _| keep(*p));
self.pots.retain(|p, _| keep(*p));
self.gateways.retain(|p, _| keep(*p));
self.gateway_servers.retain(|p, _| keep(*p));
}
/// `getOpenNess(partial)` of the chest or ender chest at `pos`.
pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 {
@@ -867,9 +928,11 @@ impl BlockEntityAnims {
) -> BlockAnim {
let mut anim = BlockAnim {
sherds,
// End gateway ages and cooldowns are not tracked on the client yet:
// gateways render settled (no beam).
gateway: (i64::MAX, 0),
// Gateways not ticked yet render settled (no beam).
gateway: self
.gateways
.get(&pos)
.map_or((i64::MAX, 0), |g| (g.age, g.teleport_cooldown)),
..BlockAnim::default()
};
if let Some(b) = self.books.get(&pos) {
@@ -1292,44 +1292,24 @@ impl BlockEntityRenderer {
}
Kind::EndGateway { state } => {
let anim = (scene.anim)(pos);
let (age, cooldown) = anim.gateway;
// TheEndGatewayRenderer.extractRenderState.
let spawning = age < 200;
if spawning || cooldown > 0 {
let a = scene.partial;
let percent = if spawning {
((age as f32 + a) / 200.0).clamp(0.0, 1.0)
} else {
1.0 - ((cooldown as f32 - a) / 40.0).clamp(0.0, 1.0)
};
let distance = if spawning {
f64::from(scene.max_y)
} else {
50.0
};
let scale = trig::sin(f64::from(percent * PI));
let height = (f64::from(scale) * distance).floor() as i32;
// DyeColor.MAGENTA / PURPLE getTextureDiffuseColor.
let color = if spawning { 0xC7_4EBD } else { 0x89_32B8 };
let time = scene.game_time.rem_euclid(40) as f32 + a;
if height > 0
&& let Some(s) = sprite("entity/end_portal/end_gateway_beam")
{
beam(
base,
BeamShape {
scale,
time,
start: -height,
height: height * 2,
color,
solid_radius: 0.15,
glow_radius: 0.175,
},
s,
out,
);
}
let b = gateway_beam(anim.gateway, scene.partial, scene.max_y, scene.game_time);
if b.height > 0
&& let Some(s) = sprite("entity/end_portal/end_gateway_beam")
{
beam(
base,
BeamShape {
scale: b.scale,
time: b.animation_time,
start: -b.height,
height: b.height * 2,
color: b.color,
solid_radius: 0.15,
glow_radius: 0.175,
},
s,
out,
);
}
// AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace.
let faces: Vec<Direction> = Direction::ALL
@@ -1618,6 +1598,43 @@ impl BeamPart {
}
}
/// `EndGatewayRenderState`'s beam fields (zero when there is no beam).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct GatewayBeam {
pub height: i32,
pub scale: f32,
pub color: u32,
pub animation_time: f32,
}
/// `TheEndGatewayRenderer.extractRenderState` from the block entity's age and
/// teleport cooldown, at `partial`, for a level whose top is `max_y`.
pub fn gateway_beam(
(age, cooldown): (i64, i32),
partial: f32,
max_y: i32,
game_time: i64,
) -> GatewayBeam {
let spawning = age < 200;
if !spawning && cooldown <= 0 {
return GatewayBeam::default();
}
let percent = if spawning {
((age as f32 + partial) / 200.0).clamp(0.0, 1.0)
} else {
1.0 - ((cooldown as f32 - partial) / 40.0).clamp(0.0, 1.0)
};
let distance = if spawning { f64::from(max_y) } else { 50.0 };
let scale = trig::sin(f64::from(percent * PI));
GatewayBeam {
height: (f64::from(scale) * distance).floor() as i32,
scale,
// DyeColor.MAGENTA / PURPLE getTextureDiffuseColor.
color: if spawning { 0xFFC7_4EBD } else { 0xFF89_32B8 },
animation_time: game_time.rem_euclid(40) as f32 + partial,
}
}
/// Entity-shader layers for `rendertype_end_portal`: end portals draw 15
/// layers of `end_portal.png` over `end_sky.png`, End gateways 16.
pub const END_PORTAL_LAYER: u32 = 9;
+18 -9
View File
@@ -24,17 +24,26 @@ const FIREWORK_COLORS: [u32; 16] = [
11_250_603, 2_651_799, 8_073_150, 2_437_522, 5_320_730, 3_887_386, 11_743_532, 1_973_019,
];
/// A set of accepted items (expanded from an item, list or tag).
/// A set of accepted items (expanded from an item, list or tag), and the
/// items in its `HolderSet` order (`Ingredient.display`'s `TagSlotDisplay`).
#[derive(Clone, Debug)]
pub struct Ingredient(pub HashSet<String>);
pub struct Ingredient(pub HashSet<String>, pub Vec<String>);
impl Ingredient {
/// The items of a list, in order.
pub fn of(items: Vec<String>) -> Self {
Self(items.iter().cloned().collect(), items)
}
fn parse(v: &Value, items: &Items) -> Option<Self> {
let mut set = HashSet::new();
let mut list: Vec<String> = Vec::new();
let mut add = |s: &str| {
if let Some(tag) = s.strip_prefix('#') {
set.extend(items.item_tags.get(tag).into_iter().flatten().cloned());
} else {
set.insert(s.to_owned());
let more: Vec<String> = match s.strip_prefix('#') {
Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(),
None => vec![s.to_owned()],
};
for i in more {
if !list.contains(&i) {
list.push(i);
}
}
};
match v {
@@ -50,7 +59,7 @@ impl Ingredient {
}
_ => return None,
}
(!set.is_empty()).then_some(Self(set))
(!list.is_empty()).then(|| Self::of(list))
}
pub fn test(&self, stack: &ItemStack) -> bool {
self.0.contains(&*stack.item)
@@ -1525,7 +1534,7 @@ mod tests {
use crate::banner::BannerLayer;
fn ingredient(items: &[&str]) -> Ingredient {
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
}
fn patterned(item: &str) -> ItemStack {
let mut s = ItemStack::new(item, 1);
+1 -1
View File
@@ -140,7 +140,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (key, value) in [
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))),
("CanPickUpLoot", Tag::Byte(i8::from(m.can_pick_up_loot()))),
("LeftHanded", Tag::Byte(0)),
(
"Brain",
+4
View File
@@ -2930,6 +2930,10 @@ impl Game<'_> {
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
// special renderers included), then the decorations.
self.draw_item_model(batch, stack, x, y);
self.draw_item_decorations(batch, stack, x, y);
}
/// `GuiGraphicsExtractor.itemDecorations`: the count and damage bar.
fn draw_item_decorations(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
let max_damage = self
@@ -5,10 +5,11 @@
//! [`Game::block_anim`] and [`Game::chest_lid`].
use super::Game;
use horizon_client::{
block_entity_anim::{BellEntity, Shulker, ShulkerStatus, Ticker},
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
block_entity_render::BlockAnim,
collisions::{SceneCollisions, no_collision_empty},
particles::{ParticleOptions, ParticleType},
save::number,
};
use horizon_core::geometry::{Aabb, Vec3};
use std::collections::HashMap;
@@ -44,6 +45,14 @@ impl Game<'_> {
.or_default()
.trigger_event(a, b, time, || gathered);
}
Some(Ticker::Gateway) => {
let initial = self.gateway_loaded(pos);
self.be_anims
.gateways
.entry(pos)
.or_insert(initial)
.trigger_event(a, b);
}
Some(Ticker::Pot) => {
self.be_anims
.pots
@@ -276,9 +285,58 @@ impl Game<'_> {
}
}
Ticker::Pot => {}
Ticker::Gateway => {
// The server copy's portalTick runs first; its block event
// reaches the client copy before the client ticks it.
let initial = self.gateway_loaded(pos);
let anims = &mut self.be_anims;
let server = anims.gateway_servers.entry(pos).or_insert(initial);
let triggered = server.portal_tick();
let client = anims.gateways.entry(pos).or_insert(initial);
if triggered {
client.trigger_event(1, 0);
}
client.tick();
}
}
}
}
/// `EndGatewayBlock.entityInside` on the server: whether the gateway at
/// `pos` let the entity in (`triggerCooldown`, with its block event).
pub(super) fn gateway_enter(&mut self, pos: [i32; 3]) -> bool {
let initial = self.gateway_loaded(pos);
let entered = self
.be_anims
.gateway_servers
.entry(pos)
.or_insert(initial)
.enter();
if entered {
self.block_entity_event(pos, 1, 0);
}
entered
}
/// The End gateway at `pos` as its chunk was loaded: `Age` from the saved
/// block entity (`getUpdateTag`), or a new gateway.
fn gateway_loaded(&self, pos: [i32; 3]) -> EndGateway {
let age = self
.world
.chunks
.get(&(pos[0] >> 4, pos[2] >> 4))
.and_then(|c| c.saved.as_deref())
.and_then(|saved| {
saved.block_entities.iter().find(|t| {
[t.get("x"), t.get("y"), t.get("z")]
.map(number)
.eq(&pos.map(|v| Some(i64::from(v))))
})
})
.and_then(|t| number(t.get("Age")));
EndGateway {
age: age.unwrap_or(0),
teleport_cooldown: 0,
}
}
/// The renderer's view of the block entity at `pos`.
pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim {
self.be_anims
+7 -1
View File
@@ -645,7 +645,10 @@ impl Game<'_> {
volume,
spread,
} => {
let r = &mut self.world.random;
// The client's own level random: nothing drawn from the server's.
let mut r = horizon_core::random::LegacyRandom::new(
self.world.game_time.wrapping_mul(341_873_128_712),
);
let pitch = (r.next_float() - r.next_float()) * spread + 1.0;
self.audio
.play(&format!("minecraft:{sound}"), Some(at), volume, pitch)
@@ -653,6 +656,9 @@ impl Game<'_> {
MobEvent::SoundId(name, at, volume, pitch) => {
self.audio.play(&name, Some(at), volume, pitch)
}
// The sculk layer tracks the game's steps itself
// (`entity_motion_events`).
MobEvent::GameEvent { .. } => {}
MobEvent::AttackPlayer(amount, from) => {
self.mob_hits_player(amount, from, "minecraft:mob_attack")
}
+1
View File
@@ -405,6 +405,7 @@ impl Game<'_> {
}
} else if let Some(g) = gateway
&& self.end.gateway_cooldown == 0
&& self.gateway_enter(g)
{
self.enter_gateway(g)?;
}
+20 -49
View File
@@ -44,24 +44,6 @@ const BUTTON: f32 = 14.0;
fn inside(p: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool {
p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h
}
/// A sub-rectangle of a sprite given in texels.
fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect {
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
Rect {
u0: r.u0 + x * du,
v0: r.v0 + y * dv,
u1: r.u0 + (x + w) * du,
v1: r.v0 + (y + h) * dv,
w: w as u32,
h: h as u32,
}
}
/// A dye's tint as a HUD vertex colour.
pub(super) fn dye_color(name: &str) -> u32 {
let c = banner::dye_rgb(name);
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, 255)
}
impl Game<'_> {
/// `LoomScreen.containerChanged`: the error flag, whether the pattern
/// buttons show (only when an input changed), and the scroller reset.
@@ -182,30 +164,30 @@ impl Game<'_> {
l.start_row = l.row_for(l.scroll);
}
}
/// A banner flag's front face (`BannerFlagModel`, 20x40 texels at (1, 1))
/// drawn flat: the cloth, the base colour and every layer.
pub(super) fn draw_flag(
/// `GuiGraphicsExtractor.bannerPattern`: the banner flag model with its
/// layers in a 20x40 picture in picture at `(x, y)`.
fn draw_banner_result(
&self,
batch: &mut HudBatch,
rect: [f32; 4],
x: f32,
y: f32,
base: &str,
layers: &[BannerLayer],
) {
let banners = &self.res.stations.banners;
let mut paint = |name: &str, color: u32| {
if let Some(r) = self.res.atlas.sprites.get(name).copied() {
let uv = sub_rect(r, [1.0, 1.0, 20.0, 40.0]);
batch.rect_uv(rect[0], rect[1], rect[2], rect[3], uv, color);
}
};
paint("entity/banner/banner_base", u32::MAX);
paint("entity/banner/base", dye_color(base));
for layer in layers.iter().take(16) {
paint(
&banners.banner_texture(&layer.pattern),
dye_color(&layer.color),
);
}
let layers: Vec<(String, String)> = layers
.iter()
.map(|l| (banners.banner_texture(&l.pattern), l.color.to_string()))
.collect();
horizon_client::item_render::gui::draw_banner_result(
&self.res.item_renderer,
&self.res.atlas.sprites,
batch,
x,
y,
base,
&layers,
);
}
/// Paints `screen_layout` calls at the menu origin (ox, oy): the container
/// background and the dimmed world are drawn by the caller.
@@ -256,19 +238,8 @@ impl Game<'_> {
layers,
x0,
y0,
x1,
y1,
} => self.draw_flag(
batch,
[
ox + *x0 as f32,
oy + *y0 as f32,
(x1 - x0) as f32,
(y1 - y0) as f32,
],
base,
layers,
),
..
} => self.draw_banner_result(batch, ox + *x0 as f32, oy + *y0 as f32, base, layers),
ScreenDraw::Tooltip { key } => {
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
}
+10
View File
@@ -95,6 +95,16 @@ impl Game<'_> {
extras.fluid_ticks.clear();
}
extras.last_update = time;
// TheEndGatewayBlockEntity saves its Age (the server copy's).
for tag in &mut extras.block_entities {
let pos = [tag.get("x"), tag.get("y"), tag.get("z")]
.map(|v| horizon_client::save::number(v).unwrap_or(0) as i32);
if let Some(g) = self.be_anims.gateway_servers.get(&pos)
&& let Some(age) = tag.get_mut("Age")
{
*age = horizon_world::nbt::Tag::Long(g.age);
}
}
if let Some(t) = self.world.inhabited.get(&(chunk.x, chunk.z)) {
extras
.root
@@ -144,6 +144,7 @@ pub(super) fn player_type(root: &Path) -> Option<Arc<MobType>> {
armor_toughness: 0.0,
knockback_resistance: 0.0,
jump_strength: 0.42,
attributes: Default::default(),
gravity: 0.08,
safe_fall_distance: 3.0,
fall_damage_multiplier: 1.0,
+265 -339
View File
@@ -11,6 +11,11 @@ use horizon_client::{
items::ItemStack,
menu::place::{PostPlace, Stacked},
recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab},
recipe_book_screen::{
self as screen, ButtonView, Call, Drawn, GhostView, ItemCall, OverlayRecipe, OverlayView,
Screen as Layout, Search, TabView,
},
text::{Style, Text},
ui::EditBox,
};
use std::{
@@ -444,9 +449,12 @@ impl Game<'_> {
// ---- geometry ----
/// `RecipeBookComponent.getXOrigin` / `getYOrigin` (`widthTooNarrow`
/// centres the book over the menu).
fn book_origin(&self, batch: &HudBatch) -> (f32, f32) {
let offset = if batch.width < NARROW { 0.0 } else { 86.0 };
(
((batch.width - WIDTH) / 2.0).floor() - 86.0,
((batch.width - WIDTH) / 2.0).floor() - offset,
((batch.height - HEIGHT) / 2.0).floor(),
)
}
@@ -623,25 +631,9 @@ impl Game<'_> {
let mut entries: Vec<(usize, bool)> =
button.entries.iter().copied().filter(|e| e.1).collect();
entries.extend(button.entries.iter().copied().filter(|e| !e.1));
let total = entries.len();
let maxrow = if total <= 16 { 4 } else { 5 };
let rows = total.div_ceil(maxrow);
let (mut x, mut y) = (bx, by);
let (center_x, center_y) = (xo + WIDTH / 2.0, yo + 13.0 + HEIGHT / 2.0);
let right = x + (total.min(maxrow) * 25) as f32;
let max_left = center_x + 50.0;
if right > max_left {
x -= 25.0 * ((right - max_left) / 25.0).floor();
}
let bottom = y + rows as f32 * 25.0;
let max_bottom = center_y + 50.0;
if bottom > max_bottom {
y -= 25.0 * ((bottom - max_bottom) / 25.0).ceil();
}
let max_top = center_y - 100.0;
if y < max_top {
y -= 25.0 * ((y - max_top) / 25.0).ceil();
}
let (x, y) =
screen::overlay_origin(bx as i32, by as i32, entries.len(), xo as i32, yo as i32);
let (x, y) = (x as f32, y as f32);
self.recipe_ui.overlay = Some(Overlay { x, y, entries });
}
@@ -821,359 +813,293 @@ impl Game<'_> {
use winit::keyboard::KeyCode;
self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight)
}
/// `GhostSlots.extractRenderState`, among the container's slots.
fn draw_ghost(&mut self, batch: &mut HudBatch, book_type: BookType) {
if self.recipe_ui.ghost.is_empty() {
return;
}
// Ghosts show only while their slots are empty.
let (ox, oy) = self.inventory_origin(batch);
let step = self.swap_index();
let big_result = book_type != BookType::Crafting || self.craft_size == 3;
let ghosts: Vec<(usize, ItemStack, bool)> = self
let ghosts: Vec<GhostView> = self
.recipe_ui
.ghost
.iter()
.filter(|g| !g.items.is_empty())
.map(|g| (g.slot, g.items[step % g.items.len()].clone(), g.result))
.map(|g| {
let (sx, sy) = self.slot_position(g.slot);
GhostView {
x: sx as i32,
y: sy as i32,
items: g.items.clone(),
result: g.result,
}
})
.collect();
for (slot, stack, result) in ghosts {
let (sx, sy) = self.slot_position(slot);
let (x, y) = (ox + sx, oy + sy);
let atlas = &self.res.atlas;
let red = rgba(255, 0, 0, 0x30);
if result && big_result {
batch.fill(atlas, x - 4.0, y - 4.0, 24.0, 24.0, red);
} else {
batch.fill(atlas, x, y, 16.0, 16.0, red);
}
self.draw_item(batch, &stack, x, y);
batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 0x30));
}
let calls = screen::ghost(self.swap_index(), ox as i32, oy as i32, big_result, &ghosts);
self.paint_book(batch, &calls);
}
/// `RecipeBookComponent.extractRenderState` and `extractTooltip`, laid
/// out by `horizon_client::recipe_book_screen`.
fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) {
let (xo, yo) = self.book_origin(batch);
let cursor = self.cursor;
let atlas_name = "gui/recipe_book";
// Background: the 147x166 page at (1, 1) of the texture.
if let Some(r) = self.res.atlas.sprites.get(atlas_name).copied() {
batch.rect_uv(
xo,
yo,
WIDTH,
HEIGHT,
sub_rect(r, [1.0, 1.0, WIDTH, HEIGHT]),
u32::MAX,
);
}
// Search box.
if let Some(search) = self.recipe_ui.search.as_mut() {
search.x = xo + 25.0;
search.y = yo + 13.0;
search.draw(batch, &self.res.atlas, None);
if search.value.is_empty() && !search.focused {
let hint = self
.res
.stations
.enchantments
.translate("gui.recipebook.search_hint")
.unwrap_or("Search...")
.to_owned();
batch.text(
&self.res.atlas,
&hint,
search.text_x(),
search.text_y(),
rgba(170, 170, 170, 255),
true,
);
}
}
// Tabs.
let tabs = self.recipe_ui.view.tabs.clone();
let current = self
.recipe_ui
.tab
.filter(|t| tabs.contains(t))
.unwrap_or(Tab::Search);
let frame = self.frame_ticks;
for (n, tab) in tabs.iter().enumerate() {
let (x, y) = self.tab_pos(xo, yo, n);
let selected = *tab == current;
let name = if selected { "tab_selected" } else { "tab" };
let sx = if selected { x - 2.0 } else { x };
let start = batch.vertices.len();
batch.sprite(&self.res.atlas, &sprite(name), sx, y);
let (a, b) = tab.icons();
let shift = if selected { -2.0 } else { 0.0 };
match b {
Some(b) => {
self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0);
self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0);
let atlas = &self.res.atlas;
let search = match self.recipe_ui.search.as_mut() {
Some(edit) => {
// The box's place, for clicks and typing.
edit.x = xo + 25.0;
edit.y = yo + 13.0;
let (display, blink_ms) = edit.view_state(atlas);
Search {
value: edit.value.clone(),
cursor: edit.cursor,
highlight: edit.highlight,
display,
focused: edit.focused,
blink_ms,
}
None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0),
}
if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) {
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze);
entry.1 -= frame;
None => Search::default(),
};
let ui = &self.recipe_ui;
let current = ui
.tab
.filter(|t| ui.view.tabs.contains(t))
.unwrap_or(Tab::Search);
let tabs: Vec<TabView> = ui
.view
.tabs
.iter()
.map(|tab| {
let (a, b) = tab.icons();
TabView {
icons: (a.to_owned(), b.map(str::to_owned)),
selected: *tab == current,
anim: ui
.tab_anim
.iter()
.find(|e| e.0 == *tab)
.map_or(0.0, |e| e.1),
}
})
.collect();
let pages = ui.view.buttons.len().div_ceil(20);
let first = ui.page * 20;
let (buttons, overlay) = match ui.book.as_ref() {
Some(book) => {
let buttons: Vec<ButtonView> = ui
.view
.buttons
.iter()
.enumerate()
.skip(first)
.take(20)
.map(|(n, b)| ButtonView {
has_craftable: b.craftable(),
entries: b
.entries
.iter()
.map(|e| vec![book.entries[e.0].result.clone()])
.collect(),
anim: ui
.button_anim
.iter()
.find(|e| e.0 == n)
.map_or(0.0, |e| e.1),
})
.collect();
let overlay = ui.overlay.as_ref().map(|o| OverlayView {
x: o.x as i32,
y: o.y as i32,
recipes: o
.entries
.iter()
.map(|&(i, craftable)| OverlayRecipe {
craftable,
cells: screen::overlay_cells(book, &book.entries[i]),
})
.collect(),
});
(buttons, overlay)
}
None => (Vec::new(), None),
};
let translate = |key: &str| self.translate(key, key);
let text_width = |s: &str| HudBatch::text_width(atlas, s) as i32;
let layout = Layout {
book: book_type,
width: batch.width as i32,
height: batch.height as i32,
narrow: batch.width < NARROW,
mouse: (cursor.0.floor() as i32, cursor.1.floor() as i32),
index: self.swap_index(),
filtering: self.book_filtering(book_type),
search: &search,
tabs: &tabs,
buttons: &buttons,
page: ui.page,
pages,
overlay: overlay.as_ref(),
ghost: None,
translate: &translate,
text_width: &text_width,
};
let calls = screen::draw(&layout);
let tooltip = self.paint_book(batch, &calls);
// The squeeze animations run down with the frames.
let frame = self.frame_ticks;
for e in &mut self.recipe_ui.tab_anim {
e.1 -= frame;
}
for e in &mut self.recipe_ui.button_anim {
e.1 -= frame;
}
self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0);
// Craftable filter.
let filtering = self.book_filtering(book_type);
let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0);
let prefix = if book_type == BookType::Crafting {
""
} else {
"furnace_"
};
let state = if filtering {
"filter_enabled"
} else {
"filter_disabled"
};
let name = format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" });
batch.sprite(&self.res.atlas, &sprite(&name), xo + 110.0, yo + 12.0);
// Recipe buttons.
let buttons = self.recipe_ui.view.buttons.clone();
let pages = buttons.len().div_ceil(20);
let step = self.swap_index();
let first = self.recipe_ui.page * 20;
let mut tooltip: Option<Vec<(String, u32)>> = None;
let overlay_open = self.recipe_ui.overlay.is_some();
for n in 0..20 {
let Some(button) = buttons.get(first + n) else {
break;
};
let (x, y) = Self::button_pos(xo, yo, n);
let anim_start = batch.vertices.len();
let many = button.entries.len() > 1;
let name = match (button.craftable(), many) {
(true, true) => "slot_many_craftable",
(true, false) => "slot_craftable",
(false, true) => "slot_many_uncraftable",
(false, false) => "slot_uncraftable",
};
batch.sprite(&self.res.atlas, &sprite(name), x, y);
let shown = button.entries[step % button.entries.len()].0;
let Some(stack) = self
.recipe_ui
.book
.as_ref()
.map(|b| ItemStack::new(&b.entries[shown].result.item, 1))
else {
continue;
};
let same_result = button.entries.iter().all(|e| {
self.recipe_ui
.book
.as_ref()
.is_some_and(|b| b.entries[e.0].result.item == b.entries[shown].result.item)
});
let mut offset = 4.0;
if many && same_result {
self.draw_item_plain(batch, &stack, x + offset + 1.0, y + offset + 1.0);
offset -= 1.0;
}
self.draw_item_plain(batch, &stack, x + offset, y + offset);
if let Some(entry) = self
.recipe_ui
.button_anim
.iter_mut()
.find(|e| e.0 == first + n)
{
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze);
entry.1 -= self.frame_ticks;
}
if inside(cursor, x, y, 25.0, 25.0) && !overlay_open {
let mut lines = self.stack_tooltip(&stack);
if many {
lines.push((
self.translate("gui.recipebook.moreRecipes", "Right Click for More"),
u32::MAX,
));
}
tooltip = Some(lines);
}
}
self.recipe_ui.button_anim.retain(|e| e.1 > 0.0);
// Page arrows and number.
if pages > 1 {
let page_text = self
.translate("gui.recipebook.page", "%s/%s")
.replacen("%s", &(self.recipe_ui.page + 1).to_string(), 1)
.replacen("%s", &pages.to_string(), 1);
let w = HudBatch::text_width(&self.res.atlas, &page_text);
batch.text(
&self.res.atlas,
&page_text,
xo - (w / 2.0).floor() + 73.0,
yo + 141.0,
u32::MAX,
true,
);
if self.recipe_ui.page + 1 < pages {
let hover = inside(cursor, xo + 93.0, yo + 137.0, 12.0, 17.0);
let name = if hover {
"page_forward_highlighted"
} else {
"page_forward"
};
batch.sprite(&self.res.atlas, &sprite(name), xo + 93.0, yo + 137.0);
if hover {
tooltip = Some(vec![(
self.translate("gui.recipebook.next_page", "Next Page"),
u32::MAX,
)]);
}
}
if self.recipe_ui.page > 0 {
let hover = inside(cursor, xo + 38.0, yo + 137.0, 12.0, 17.0);
let name = if hover {
"page_backward_highlighted"
} else {
"page_backward"
};
batch.sprite(&self.res.atlas, &sprite(name), xo + 38.0, yo + 137.0);
if hover {
tooltip = Some(vec![(
self.translate("gui.recipebook.previous_page", "Previous Page"),
u32::MAX,
)]);
}
}
}
if inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0) {
let key = if !filtering {
"gui.recipebook.toggleRecipes.all"
} else {
match book_type {
BookType::Crafting => "gui.recipebook.toggleRecipes.craftable",
BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable",
BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable",
BookType::Smoker => "gui.recipebook.toggleRecipes.smokable",
}
};
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
}
self.draw_overlay(batch, book_type);
if let Some(lines) = tooltip {
self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1);
}
}
/// An item without count or bars (`GuiGraphics.fakeItem`).
fn draw_item_plain(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
let one = ItemStack {
count: 1,
damage: 0,
..stack.clone()
};
self.draw_item(batch, &one, x, y);
}
fn draw_overlay(&mut self, batch: &mut HudBatch, book_type: BookType) {
let Some(overlay) = self.recipe_ui.overlay.as_ref() else {
return;
};
let (ox, oy, entries) = (overlay.x, overlay.y, overlay.entries.clone());
let maxrow = if entries.len() <= 16 { 4 } else { 5 };
let width = entries.len().min(maxrow) as f32 * 25.0 + 8.0;
let height = entries.len().div_ceil(maxrow) as f32 * 25.0 + 8.0;
horizon_client::ui::nine_slice(
batch,
&self.res.atlas,
&sprite("overlay_recipe"),
ox,
oy,
width,
height,
u32::MAX,
);
let cursor = self.cursor;
let step = self.swap_index();
let (gw, gh) = if book_type == BookType::Crafting {
(3, 3)
} else {
(1, 1)
};
for (n, (index, craftable)) in entries.into_iter().enumerate() {
let x = ox + 4.0 + 25.0 * (n % maxrow) as f32;
let y = oy + 5.0 + 25.0 * (n / maxrow) as f32;
let hover = inside(cursor, x, y, 24.0, 24.0);
let family = if book_type == BookType::Crafting {
"crafting"
} else {
"furnace"
};
let state = if craftable { "" } else { "_disabled" };
let name = format!(
"{family}_overlay{state}{}",
if hover { "_highlighted" } else { "" }
);
batch.sprite(&self.res.atlas, &sprite(&name), x, y);
let Some(entry) = self
.recipe_ui
.book
.as_ref()
.map(|b| b.entries[index].clone())
else {
continue;
};
// The recipe's layout in miniature, ingredients at 3/8 scale.
let mut cells: Vec<(f32, f32, ItemStack)> = Vec::new();
if let Some(book) = self.recipe_ui.book.as_ref() {
let requirements = entry.requirements();
match &entry.display {
Display::Furnace(ingredient) => {
let items = book.items_of(ingredient);
if !items.is_empty() {
let item = &items[step % items.len()];
cells.push((3.0 + 7.0, 3.0 + 7.0, ItemStack::new(item, 1)));
}
}
Display::Shaped { .. } => {
for (ingredient, grid_index) in entry.grid_cells(gw, gh) {
if let Some(i) = ingredient {
let items = book.items_of(requirements[i]);
if !items.is_empty() {
let item = &items[step % items.len()];
cells.push((
3.0 + (grid_index % 3) as f32 * 7.0,
3.0 + (grid_index / 3) as f32 * 7.0,
ItemStack::new(item, 1),
));
}
}
}
}
Display::Shapeless(list) => {
for (i, ingredient) in list.iter().enumerate() {
let items = book.items_of(ingredient);
if !items.is_empty() {
let item = &items[step % items.len()];
cells.push((
3.0 + (i % 3) as f32 * 7.0,
3.0 + (i / 3) as f32 * 7.0,
ItemStack::new(item, 1),
));
}
}
/// Paints recipe book calls; returns the first tooltip set (vanilla keeps
/// the first one a frame asks for).
fn paint_book(&mut self, batch: &mut HudBatch, calls: &[Drawn]) -> Option<Vec<(String, u32)>> {
let mut tooltip: Option<Vec<(String, u32)>> = None;
for d in calls {
let start = batch.vertices.len();
let atlas = &self.res.atlas;
match &d.call {
Call::Blit {
x, y, w, h, u, v, ..
} => {
if let Some(r) = atlas.sprites.get("gui/recipe_book").copied() {
let (w, h) = (*w as f32, *h as f32);
batch.rect_uv(
*x as f32,
*y as f32,
w,
h,
sub_rect(r, [*u, *v, w, h]),
u32::MAX,
);
}
}
Call::Sprite { id, x, y, w, h } => {
let name = format!("gui/sprites/{id}");
let native = atlas
.sprites
.get(&name)
.is_some_and(|r| r.w as i32 == *w && r.h as i32 == *h);
if native {
batch.sprite(atlas, &name, *x as f32, *y as f32);
} else {
horizon_client::ui::nine_slice(
batch,
atlas,
&name,
*x as f32,
*y as f32,
*w as f32,
*h as f32,
u32::MAX,
);
}
}
Call::Fill {
x0,
y0,
x1,
y1,
color,
} => batch.fill(
atlas,
*x0 as f32,
*y0 as f32,
(x1 - x0) as f32,
(y1 - y0) as f32,
argb(*color),
),
Call::Highlight { x0, y0, x1, y1 } => {
let (a, b) = (*x0.min(x1), *x0.max(x1));
batch.fill(
atlas,
a as f32,
*y0 as f32,
(b - a) as f32,
(y1 - y0) as f32,
rgba(0, 0, 255, 128),
);
}
Call::Text {
runs,
x,
y,
color,
shadow,
} => {
let mut x = *x as f32;
for r in runs {
let style = Style {
color: (r.color >= 0).then_some(r.color as u32),
italic: r.italic.then_some(true),
..Style::default()
};
let t = Text::styled(r.text.clone(), style);
batch.text_styled(atlas, &t, x, *y as f32, argb(*color), *shadow);
x += atlas.font.width_text(&t);
}
}
Call::Item { call, stack, x, y } => match call {
ItemCall::Item | ItemCall::Fake => {
self.draw_item_model(batch, stack, *x as f32, *y as f32)
}
ItemCall::Decorations => {
self.draw_item_decorations(batch, stack, *x as f32, *y as f32)
}
},
Call::Tooltip(lines) => {
if tooltip.is_none() {
tooltip = Some(
lines
.iter()
.map(|l| (l.iter().map(|r| r.text.as_str()).collect(), u32::MAX))
.collect(),
);
}
}
Call::ItemTooltip { stack, more } => {
if tooltip.is_none() {
let mut lines = self.stack_tooltip(stack);
if *more {
lines.push((
self.translate(
"gui.recipebook.moreRecipes",
"Right Click for More",
),
u32::MAX,
));
}
tooltip = Some(lines);
}
}
Call::Stratum => {}
}
for (cx, cy, stack) in cells {
// Draw at the origin, then shrink around the cell centre.
let start = batch.vertices.len();
self.draw_item_plain(batch, &stack, 0.0, 0.0);
let (px, py) = (x + 2.0 + cx, y + 2.0 + cy);
if d.pose != screen::IDENTITY {
let m = d.pose;
for v in &mut batch.vertices[start..] {
v.pos = [px + (v.pos[0] - 8.0) * 0.375, py + (v.pos[1] - 8.0) * 0.375];
let [x, y] = v.pos;
v.pos = [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
}
}
}
tooltip
}
}
/// An ARGB colour as a HUD vertex colour.
fn argb(c: i32) -> u32 {
let c = c as u32;
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, (c >> 24) as u8)
}
/// A sub-rectangle of a sprite given in texels.
fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect {
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
+7 -52
View File
@@ -638,54 +638,13 @@ impl Game<'_> {
/// `Warden.VibrationUser`: accept a vibration for the warden at `index`.
fn warden_listen(&mut self, index: usize, event: &'static str, pos: [f64; 3], ctx: &Context) {
let now = self.world.game_time;
let (eye, busy) = {
let m = &self.mobs[index];
let Some(st) = m.extra.warden.as_ref() else {
return;
};
(
[m.position.x, m.position.y + m.kind.eye_height, m.position.z],
st.vibration.current.is_some(),
)
};
if busy {
return;
}
let source_block = block_of(pos);
let eye_block = block_of(eye);
let d = [
i64::from(source_block[0]) - i64::from(eye_block[0]),
i64::from(source_block[1]) - i64::from(eye_block[1]),
i64::from(source_block[2]) - i64::from(eye_block[2]),
];
if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 256 {
return;
}
if !sculk::valid_vibration(sculk::warden_can_listen(event), event, ctx) {
return;
}
if !warden::can_receive_vibration(&self.mobs[index], i64::from(self.mobs[index].age), ctx) {
return;
}
if self.occluded(pos, eye) {
return;
}
let distance = {
let d = [pos[0] - eye[0], pos[1] - eye[1], pos[2] - eye[2]];
(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32
};
if let Some(st) = self.mobs[index].extra.warden.as_mut() {
st.vibration.schedule(
Info {
event,
distance,
pos,
source: ctx.source,
owner: ctx.owner,
},
now,
);
}
let (occludes, world) = (&self.sculk.tables.occludes, &self.world);
warden::listen(&mut self.mobs[index], now, event, pos, ctx, |a, b| {
sculk::is_occluded(a, b, |p| {
let state = world.block(p.x, p.y, p.z);
occludes.get(state.0 as usize).copied().unwrap_or(false)
})
});
}
// ---- ticking ----
@@ -1627,10 +1586,6 @@ impl Game<'_> {
} else {
(move_dist as i32).wrapping_add(1) as f32
};
if warden {
self.audio
.play("minecraft:entity.warden.step", Some(at), 10.0, 1.0);
}
let ctx = self.who_context(Some(who), Some(state));
self.post_game_event("minecraft:step", at, ctx);
} else if in_water {
@@ -130,6 +130,13 @@ fn parse(text: &str) -> Vec<Scenario> {
out
}
/// An entity's own random is unseeded in vanilla, and so are its sensors'
/// first delays and its brain's `RunOne` shuffles: the oracle seeds what
/// appeared, and so does this.
fn seed_fresh(m: &mut Mob, seed: i64) {
m.random = LegacyRandom::new(seed);
horizon_client::mobs::warden::init_brain(m, seed);
}
fn d(v: f64) -> String {
format!("{:x}", v.to_bits())
}
@@ -138,10 +145,12 @@ fn f(v: f32) -> String {
}
/// Sounds the client plays for level events (3006 sculk charge, 3007
/// shriek): vanilla's server never sends them.
/// shriek) and for itself (the warden's heartbeat): vanilla's server never
/// sends them.
const CLIENT_SOUNDS: &[&str] = &[
"minecraft:block.sculk_shrieker.shriek",
"minecraft:block.sculk.charge",
"minecraft:entity.warden.heartbeat",
];
impl Game<'_> {
@@ -469,6 +478,7 @@ impl Game<'_> {
self.world.random = LegacyRandom::new(s.level_seed);
self.audio.capture = Some(Vec::new());
let mut known: HashSet<u32> = self.mobs.iter().map(|m| m.id).collect();
let mut seeded: HashSet<u32> = HashSet::new();
let mut known_items = self.dropped.len();
let mut known_orbs = self.orbs.len();
let mut last: HashMap<[i32; 3], String> = HashMap::new();
@@ -478,7 +488,7 @@ impl Game<'_> {
for t in 0..=s.ticks {
dispense_fixture::start_recording();
if t > 0 {
self.sculk_fixture_tick(t, s, &sources)?;
self.sculk_fixture_tick(t, s, &sources, &known, names.len(), &mut seeded)?;
}
let mut lines: Vec<String> = Vec::new();
for p in &s.watch {
@@ -540,12 +550,11 @@ impl Game<'_> {
for (id, line) in fresh {
known.insert(id);
names.insert(id, format!("n{}", names.len()));
// An entity's own random is unseeded in vanilla: the oracle
// seeds what appeared, and so does this.
let seed = 0x5eed + names.len() as i64;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.random = LegacyRandom::new(seed);
horizon_client::mobs::warden::delay_sensors(m);
if seeded.insert(id)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
seed_fresh(m, seed);
}
lines.push(line);
}
@@ -599,7 +608,15 @@ impl Game<'_> {
}
/// One `ServerLevel.tick` of a scenario.
fn sculk_fixture_tick(&mut self, t: i32, s: &Scenario, sources: &[u32]) -> Result<()> {
fn sculk_fixture_tick(
&mut self,
t: i32,
s: &Scenario,
sources: &[u32],
known: &HashSet<u32>,
named: usize,
seeded: &mut HashSet<u32>,
) -> Result<()> {
self.world.game_time += 1;
// Scheduled block and fluid ticks, then block events.
self.tick_scheduled()?;
@@ -662,6 +679,23 @@ impl Game<'_> {
other => return Err(format!("unknown action {other}").into()),
}
}
// Mobs that appeared during the block ticks (a summoned warden) tick
// in this tick's entity phase: seed them now, as they are seeded
// after the tick.
let mut born: Vec<u32> = self
.mobs
.iter()
.map(|m| m.id)
.filter(|id| !known.contains(id))
.collect();
born.sort_unstable();
for (i, id) in born.into_iter().enumerate() {
if seeded.insert(id)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
seed_fresh(m, 0x5eed + (named + i + 1) as i64);
}
}
// Entities: the player's warden spawn tracker, then the mobs.
self.tick_sculk_entities();
// (ServerChunkCache.tick, natural spawning and its chunk shuffle, is not run.)
+82 -11
View File
@@ -89,7 +89,7 @@ fn clip_triangle(tri: [Point; 3], rect: [f32; 4]) -> Vec<Point> {
}
/// RGBA vertex colour of a lit quad: `minecraft_mix_light` on the tint.
fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 {
pub fn lit_color(q: &ItemQuad, lights: (Vec3, Vec3)) -> u32 {
let light = crate::block_entity_render::diffuse(q.normal, lights);
let [a, r, g, b] = q.color.to_be_bytes();
let c = |v: u8| (f32::from(v) * light) as u8;
@@ -155,6 +155,28 @@ pub fn draw(
} else {
items_flat_lights()
};
let rect = if state.oversized_in_gui {
[
f32::NEG_INFINITY,
f32::NEG_INFINITY,
f32::INFINITY,
f32::INFINITY,
]
} else {
[x, y, x + 16.0, y + 16.0]
};
draw_quads(&quads, lights, batch, rect, time);
}
/// Lights, culls, sorts far to near and clips `quads` (GUI positions) to
/// `rect`.
fn draw_quads(
quads: &[ItemQuad],
lights: (Vec3, Vec3),
batch: &mut HudBatch,
rect: [f32; 4],
time: f32,
) {
// Back-face culling: front faces wind counter-clockwise on screen with y up.
let mut visible: Vec<(f32, usize)> = quads
.iter()
@@ -173,16 +195,6 @@ pub fn draw(
.collect();
// Far to near; the depth buffer of the item atlas, approximated per quad.
visible.sort_by(|a, b| a.0.total_cmp(&b.0));
let rect = if state.oversized_in_gui {
[
f32::NEG_INFINITY,
f32::NEG_INFINITY,
f32::INFINITY,
f32::INFINITY,
]
} else {
[x, y, x + 16.0, y + 16.0]
};
for (_, i) in visible {
let q = &quads[i];
let points: [Point; 4] = std::array::from_fn(|k| Point {
@@ -206,6 +218,65 @@ pub fn draw(
}
}
/// `PictureInPictureRenderer.prepare` for the loom's 20x40 result rectangle
/// at `(x0, y0)` (`translate(w / 2, h)`, `scale(16, 16, -16)`, one texel per
/// GUI pixel), then `GuiBannerResultRenderer.renderToTexture`'s
/// `translate(0, 0.25, 0)`.
pub fn banner_result_pose(x0: f32, y0: f32) -> Mat4 {
Mat4::from_translation(Vec3::new(x0 + 10.0, y0 + 40.0, 0.0))
* Mat4::from_scale(Vec3::new(16.0, 16.0, -16.0))
* Mat4::from_translation(Vec3::new(0.0, 0.25, 0.0))
}
/// The quads of `GuiGraphicsExtractor.bannerPattern` (the loom's result
/// preview) at `(x0, y0)`: base dye and `(texture, dye)` layers.
pub fn banner_result_quads(
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
x0: f32,
y0: f32,
base: &str,
layers: &[(String, String)],
) -> Vec<ItemQuad> {
let mut quads = Vec::new();
super::special::submit_banner_result(
renderer,
banner_result_pose(x0, y0),
base,
layers,
sprites,
&mut quads,
);
// The winding normal flips with the pose's mirrored axis; PoseStack's
// normal matrix only takes the scale's signs, so the lit normal is the
// opposite one.
for q in &mut quads {
q.normal = -q.normal;
}
quads
}
/// Draws the loom's result preview: the picture in picture is lit with
/// `Lighting.Entry.ITEMS_FLAT` and holds only its 20x40 rectangle.
pub fn draw_banner_result(
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
batch: &mut HudBatch,
x0: f32,
y0: f32,
base: &str,
layers: &[(String, String)],
) {
let quads = banner_result_quads(renderer, sprites, x0, y0, base, layers);
draw_quads(
&quads,
items_flat_lights(),
batch,
[x0, y0, x0 + 20.0, y0 + 40.0],
0.0,
);
}
#[cfg(test)]
mod tests {
use super::*;
@@ -379,6 +379,33 @@ fn pot_sides(v: &Value) -> [Option<String>; 4] {
}
}
/// `GuiBannerResultRenderer.renderToTexture` under `pose`: the standing
/// banner flag (`BannerFlagModel.setupAnim(0)`) in the banner base texture,
/// then `BannerRenderer.submitPatterns` (the base colour and up to 16 layers
/// of `(texture, dye)`).
pub(super) fn submit_banner_result(
renderer: &ItemRenderer,
pose: Mat4,
base: &str,
layers: &[(String, String)],
sprites: &HashMap<String, Rect>,
sink: &mut dyn ItemSink,
) {
let Some(flag) = renderer.part("standing_banner_flag") else {
return;
};
let mut part = |texture: &str, color: u32| {
if let Some(r) = sprites.get(texture).copied() {
draw(flag, "root", pose, &flag_pose, r, color, Foil::None, sink);
}
};
part("entity/banner/banner_base", argb(-1));
part("entity/banner/base", dye(base));
for (texture, color) in layers.iter().take(16) {
part(texture, dye(color));
}
}
/// `SpecialModelRenderer.submit`.
#[allow(clippy::too_many_arguments)]
pub(super) fn submit(
+22 -11
View File
@@ -166,6 +166,9 @@ pub struct Items {
/// Block tag name (without '#') -> member block names.
pub block_tags: HashMap<String, HashSet<String>>,
pub item_tags: HashMap<String, HashSet<String>>,
/// Item tags in vanilla's order (`TagLoader`: file order, nested tags in
/// place, first occurrence kept), the order `TagSlotDisplay` resolves.
pub item_tag_order: HashMap<String, Vec<String>>,
loot: HashMap<String, Value>,
/// The `jukebox_song` registry.
pub songs: HashMap<String, Song>,
@@ -216,6 +219,13 @@ fn load_songs(root: &Path) -> HashMap<String, Song> {
songs
}
pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashSet<String>>> {
Ok(load_tag_lists(root, kind)?
.into_iter()
.map(|(k, v)| (k, v.into_iter().collect()))
.collect())
}
/// Every tag's contents in `TagLoader.tryBuildTag` order (a `LinkedHashSet`).
pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result<HashMap<String, Vec<String>>> {
let dir = root.join(format!("data/minecraft/tags/{kind}"));
let mut raw: HashMap<String, Vec<String>> = HashMap::new();
fn walk(dir: &Path, base: &Path, raw: &mut HashMap<String, Vec<String>>) -> Result<()> {
@@ -246,29 +256,24 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashS
if dir.exists() {
walk(&dir, &dir, &mut raw)?;
}
fn resolve(
name: &str,
raw: &HashMap<String, Vec<String>>,
out: &mut HashSet<String>,
depth: u32,
) {
fn resolve(name: &str, raw: &HashMap<String, Vec<String>>, out: &mut Vec<String>, depth: u32) {
if depth > 32 {
return;
}
for v in raw.get(name).into_iter().flatten() {
if let Some(tag) = v.strip_prefix('#') {
resolve(tag, raw, out, depth + 1);
} else {
out.insert(v.clone());
} else if !out.contains(v) {
out.push(v.clone());
}
}
}
Ok(raw
.keys()
.map(|k| {
let mut set = HashSet::new();
resolve(k, &raw, &mut set, 0);
(k.clone(), set)
let mut list = Vec::new();
resolve(k, &raw, &mut list, 0);
(k.clone(), list)
})
.collect())
}
@@ -456,6 +461,7 @@ impl Items {
order,
block_tags: load_tags(root, "block")?,
item_tags: load_tags(root, "item")?,
item_tag_order: load_tag_lists(root, "item")?,
loot,
songs: load_songs(root),
})
@@ -470,6 +476,7 @@ impl Items {
order: Vec::new(),
block_tags: load_tags(root, "block")?,
item_tags: load_tags(root, "item")?,
item_tag_order: load_tag_lists(root, "item")?,
loot: HashMap::new(),
songs: HashMap::new(),
})
@@ -481,6 +488,10 @@ impl Items {
items: HashMap::new(),
order: Vec::new(),
block_tags: HashMap::new(),
item_tag_order: item_tags
.iter()
.map(|(k, v)| (k.clone(), v.iter().cloned().collect()))
.collect(),
item_tags,
loot: HashMap::new(),
songs: HashMap::new(),
+1
View File
@@ -85,6 +85,7 @@ pub mod projectiles;
pub mod raid;
pub mod random_sequences;
pub mod recipe_book;
pub mod recipe_book_screen;
pub mod save;
pub mod scoreboard;
pub mod scoreboard_cmd;
+1 -1
View File
@@ -639,7 +639,7 @@ mod tests {
use super::*;
fn ing(items: &[&str]) -> Ingredient {
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
}
fn have(items: &[(&str, i32)]) -> Stacked {
let mut s = Stacked::default();
+80 -5
View File
@@ -25,6 +25,7 @@ pub mod drops;
pub mod enderman;
pub mod equine;
pub mod farm;
pub mod finalize;
pub mod gear;
pub mod goals;
pub mod golem;
@@ -62,6 +63,7 @@ pub mod vex;
pub mod villager;
pub mod villager_brain;
pub mod warden;
pub mod warden_brain;
pub mod witch;
pub mod wither;
mod world;
@@ -205,6 +207,8 @@ pub struct MobType {
pub armor_toughness: f32,
pub knockback_resistance: f64,
pub jump_strength: f64,
/// Every default attribute value of the type (`entity-types.json`).
pub attributes: Arc<HashMap<String, f64>>,
pub gravity: f64,
pub safe_fall_distance: f64,
pub fall_damage_multiplier: f64,
@@ -238,12 +242,35 @@ impl MobType {
self.layers.get(key)
}
}
/// Each type's default attribute values, parsed exactly (serde_json's
/// default float parsing can miss the nearest double by one ulp).
fn exact_attributes(bytes: &[u8]) -> HashMap<String, HashMap<String, f64>> {
use serde_json::value::RawValue;
type Raw = HashMap<String, Box<RawValue>>;
let Ok(types) = serde_json::from_slice::<Raw>(bytes) else {
return HashMap::new();
};
types
.into_iter()
.filter_map(|(id, t)| {
let t: Raw = serde_json::from_str(t.get()).ok()?;
let attrs: Raw = serde_json::from_str(t.get("attributes")?.get()).ok()?;
let values = attrs
.into_iter()
.filter_map(|(k, v)| v.get().trim().parse::<f64>().ok().map(|v| (k, v)))
.collect();
Some((id, values))
})
.collect()
}
pub struct MobTypes {
pub types: HashMap<String, MobType>,
}
impl MobTypes {
pub fn load(root: &Path) -> crate::Result<Self> {
let types: Value = serde_json::from_slice(&fs::read(root.join("entity-types.json"))?)?;
let bytes = fs::read(root.join("entity-types.json"))?;
let types: Value = serde_json::from_slice(&bytes)?;
let exact = exact_attributes(&bytes);
let models: Value = serde_json::from_slice(&fs::read(root.join("entity-models.json"))?)?;
let item_tags = crate::items::load_tags(root, "item").unwrap_or_default();
sulfur_cube::load_archetype_items(&item_tags);
@@ -268,7 +295,8 @@ impl MobTypes {
let Some(model) = models.get(&model_key) else {
continue;
};
let attr = |k: &str| t["attributes"][format!("minecraft:{k}")].as_f64();
let defaults = exact.get(&id).cloned().unwrap_or_default();
let attr = |k: &str| defaults.get(&format!("minecraft:{k}")).copied();
let mut layers = HashMap::new();
if let Some(all) = models.as_object() {
for prefix in def.layer_prefixes() {
@@ -302,6 +330,7 @@ impl MobTypes {
armor_toughness: attr("armor_toughness").unwrap_or(0.0) as f32,
knockback_resistance: attr("knockback_resistance").unwrap_or(0.0),
jump_strength: attr("jump_strength").unwrap_or(0.42),
attributes: Arc::new(defaults.clone()),
gravity: attr("gravity").unwrap_or(0.08),
safe_fall_distance: attr("safe_fall_distance").unwrap_or(3.0),
fall_damage_multiplier: attr("fall_damage_multiplier").unwrap_or(1.0),
@@ -461,6 +490,9 @@ pub struct Attrs {
pub attack_damage: f32,
pub max_health: f32,
pub follow_range: f64,
pub knockback_resistance: f64,
pub spawn_reinforcements: f64,
pub jump_strength: f64,
}
/// Species-specific persistent state (variants, colours, taming, ageing...).
#[derive(Clone, Debug, Default)]
@@ -561,6 +593,24 @@ pub struct Extra {
/// `Mob.dropChances` by `EquipmentSlot` (`drops::SLOTS` order) when set
/// explicitly; None uses the defaults of `drops::drop_chance`.
pub drop_chances: Option<Box<[f32; 8]>>,
/// `Mob.leftHanded`.
pub left_handed: bool,
/// The sound variant: index in the species' `*_sound_variant` registry.
pub sound_variant: u8,
/// `Zombie.canBreakDoors`.
pub can_break_doors: bool,
/// A goat's `IsScreamingGoat` and the horns it lost (left, right).
pub screaming: bool,
pub lost_horns: [bool; 2],
/// Attribute bases and permanent modifiers set by `finalizeSpawn`.
pub attributes: Option<Box<finalize::Attributes>>,
/// Brain memories `finalizeSpawn` sets: (memory, value, ticks to expiry).
pub memories: Vec<(&'static str, i64, i64)>,
/// A camel's `LAST_POSE_CHANGE_TICK`.
pub pose_change_tick: i64,
/// The school leader a fish follows, and a tropical fish that swims alone.
pub leader: Option<u32>,
pub lone: bool,
/// A breeze's or creaking's brain (`monster_brain`).
pub brain: Option<Box<monster_brain::Brain>>,
}
@@ -668,6 +718,15 @@ pub enum MobEvent {
volume: f32,
spread: f32,
},
/// `Level.gameEvent` from a mob's own movement (`GameEvent.STEP`): the
/// game's sculk layer tracks steps itself, the mob AI probe hears them
/// through the wardens (`warden::listen`).
GameEvent {
event: &'static str,
at: [f64; 3],
source: u32,
state: horizon_world::registry::BlockStateId,
},
AttackPlayer(f32, [f64; 3]),
/// Damage of a given type to the player (guardian lasers, thorns).
DamagePlayer {
@@ -1215,17 +1274,24 @@ impl Mob {
attack_damage: kind.attack_damage,
max_health: kind.max_health,
follow_range: kind.follow_range,
knockback_resistance: kind.knockback_resistance,
spawn_reinforcements: kind
.attributes
.get("minecraft:spawn_reinforcements")
.copied()
.unwrap_or(0.0),
jump_strength: kind.jump_strength,
},
kind,
};
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Allay,
// Dolphin, Fox and Panda constructors.
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Dolphin,
// Fox and Panda constructors (an allay's is false until it holds
// something: it overrides canPickUpLoot).
mob.extra.pick_up_loot = matches!(
mob.species(),
Species::Villager
| Species::Piglin
| Species::PiglinBrute
| Species::Allay
| Species::Dolphin
| Species::Fox
| Species::Panda
@@ -1233,6 +1299,15 @@ impl Mob {
ai::register(&mut mob);
mob
}
/// `Mob.canPickUpLoot`, with the overrides: an allay that holds
/// something off its pickup cooldown, a sulfur cube with no block.
pub fn can_pick_up_loot(&self) -> bool {
match self.species() {
Species::Allay => self.extra.main_hand.is_some() && self.extra.ints[3] <= 0,
Species::SulfurCube => !sulfur_cube::has_body(self),
_ => self.extra.pick_up_loot,
}
}
pub fn bounds(&self) -> Aabb {
let w = f64::from(self.width()) / 2.0;
Aabb::new(
+16 -5
View File
@@ -350,6 +350,7 @@ pub fn tick(
if m.removed {
return false;
}
super::warden::pre_tick(m, w, events);
base_tick(m, w, events);
if m.death_time >= super::creaking::death_limit(m) {
// Creaking.tickDeath: a heart's creaking crumbles away.
@@ -710,6 +711,10 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let _ = m.random.next_int_bound(4);
}
for (who, at) in targets {
// Warden.doPush: touching it angers it, then the push itself.
if m.species() == Species::Warden {
super::warden::do_push(m, w, who, events);
}
// Entity.push(Entity) with `this` the other entity.
let (mut xa, mut za) = (m.position.x - at.x, m.position.z - at.z);
let mut dd = xa.abs().max(za.abs());
@@ -795,6 +800,10 @@ fn server_ai_step(
super::villager_brain::tick(m, w, level_random, events);
let _ = m.random.next_int_bound(100);
}
if m.species() == Species::Warden {
// Warden.customServerAiStep: the brain and its bookkeeping.
super::warden::server_ai_step(m, w, level_random, events);
}
// Sniffer and HappyGhast.customServerAiStep: the brain (a happy ghast's
// only while it is a ghastling), then updateActivity.
if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() {
@@ -828,7 +837,6 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
Species::Enderman => super::enderman::custom_server_ai_step(m, cx),
Species::Blaze => super::nether::blaze_server_ai_step(m, cx),
Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx),
Species::Warden => super::warden::server_ai_step(m, cx),
Species::Wither if m.alive() => super::wither::custom_server_ai_step(m, cx.w, cx.events),
// SpellcasterIllager.customServerAiStep.
Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1,
@@ -895,11 +903,14 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
|| super::nautilus::is_nautilus(m.species()) && m.extra.tame
|| m.species() == Species::SulfurCube
&& (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0);
// removeWhenFarAway: animals, wardens, patrols and raiders, zombie
// villagers being cured and ridden mobs stay.
// removeWhenFarAway: animals, wardens, allays, patrols and raiders,
// zombie villagers being cured and ridden mobs stay; the wither's
// checkDespawn never removes it for distance.
let creature = m.kind.category == "creature";
let removable = !(m.species() == Species::Warden
|| creature && m.kind.flags.animal && !m.extra.jockey
let removable = !(matches!(
m.species(),
Species::Warden | Species::Allay | Species::Wither
) || creature && m.kind.flags.animal && !m.extra.jockey
|| super::raider::keeps_alive(m, d)
|| super::zombie_villager::keeps_alive(m)
|| super::riders::keeps_alive(m));
-1
View File
@@ -27,7 +27,6 @@ pub fn register(m: &mut Mob) {
m.ai.nav.kind = NavKind::Flying;
// FlyingPathNavigation.setRequiredPathLength(48).
m.ai.nav.required_path_length = 48.0;
m.persistent = true;
let g = &mut m.ai.goals;
g.add(0, Panic::new(2.5));
g.add(1, Fetch);
+29 -26
View File
@@ -445,35 +445,38 @@ impl Goal for PufferfishPuff {
}
}
/// finalizeSpawn variants (tropical fish patterns and colours).
/// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour).
pub const COMMON_TROPICAL: [(u8, u8, u8); 22] = [
(7, 1, 7),
(6, 7, 7),
(6, 7, 11),
(11, 0, 7),
(1, 11, 7),
(0, 1, 0),
(5, 6, 3),
(9, 10, 4),
(11, 0, 14),
(5, 0, 4),
(8, 0, 7),
(11, 0, 1),
(3, 9, 6),
(4, 5, 3),
(10, 14, 0),
(2, 7, 14),
(9, 14, 0),
(6, 0, 4),
(0, 14, 0),
(1, 7, 0),
(3, 9, 4),
(6, 4, 4),
];
pub fn finalize(m: &mut Mob) {
if m.species() == Species::TropicalFish {
// TropicalFish.COMMON_VARIANTS: (pattern index, base colour, pattern colour).
const COMMON: [(u8, u8, u8); 22] = [
(7, 1, 7),
(6, 7, 7),
(6, 7, 11),
(11, 0, 7),
(1, 11, 7),
(0, 1, 0),
(5, 6, 3),
(9, 10, 4),
(11, 0, 14),
(5, 0, 4),
(8, 0, 7),
(11, 0, 1),
(3, 9, 6),
(4, 5, 3),
(10, 14, 0),
(2, 7, 14),
(9, 14, 0),
(6, 0, 4),
(0, 14, 0),
(1, 7, 0),
(3, 9, 4),
(6, 4, 4),
];
let (p, b, c) = if m.random.next_float() < 0.9 {
COMMON[m.random.next_int_bound(COMMON.len() as i32).unwrap_or(0) as usize]
COMMON_TROPICAL[m
.random
.next_int_bound(COMMON_TROPICAL.len() as i32)
.unwrap_or(0) as usize]
} else {
(
m.random.next_int_bound(12).unwrap_or(0) as u8,
File diff suppressed because it is too large Load Diff
+5 -3
View File
@@ -346,12 +346,13 @@ impl Mob {
let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water;
(!water && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
}
/// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yRotO)`.
/// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yHeadRotO)`.
pub fn view_vector(&self) -> [f64; 3] {
use horizon_core::geometry::trig::Mth;
let to_rad = std::f32::consts::PI / 180.0;
let x = self.previous_head_pitch * to_rad;
let y = -self.previous_yaw * to_rad;
// LivingEntity.getViewYRot(0): the head's yaw of the last tick.
let y = -self.previous_head_yaw * to_rad;
let (y_cos, y_sin, x_cos, x_sin) = (y.mcos(), y.msin(), x.mcos(), x.msin());
[
f64::from(y_sin * x_cos),
@@ -378,7 +379,8 @@ impl Mob {
fly_height,
xd,
zd,
std::f64::consts::FRAC_PI_2,
// Every caller passes `(float) (Math.PI / 2)`.
f64::from(std::f32::consts::FRAC_PI_2),
)?;
let mut p = m.toward(f64::from(h), d);
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || m.restricted(f64::from(h), p) {
+21 -2
View File
@@ -400,9 +400,18 @@ impl Mob {
let at = [self.position.x, self.position.y, self.position.z];
events.push(MobEvent::Sound(sound, at, volume, pitch));
}
self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32;
// Entity.vibrationAndSoundEffectsFromBlock: the step's game
// event, with the supporting block's state when the effect
// block is another.
events.push(MobEvent::GameEvent {
event: "minecraft:step",
at: [self.position.x, self.position.y, self.position.z],
source: self.id,
state: if legacy == on { legacy_state } else { state },
});
self.ai.steps.next_step = self.next_step();
} else if self.fluids.in_water {
self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32;
self.ai.steps.next_step = self.next_step();
// Entity.waterSwimSound
let v = self.velocity;
let volume = 1.0_f32.min(
@@ -426,6 +435,16 @@ impl Mob {
}
}
}
/// `Entity.nextStep`: the next whole metre walked; a warden's steps come
/// every 0.55.
fn next_step(&self) -> f32 {
let walked = self.ai.steps.move_dist;
if self.kind.species == super::Species::Warden {
walked + 0.55
} else {
(walked as i32).wrapping_add(1) as f32
}
}
/// Entity.isSwimming (mobs never swim in the player sense).
fn fluids_swimming(&self) -> bool {
false
@@ -36,7 +36,7 @@ impl<T> Default for Slot<T> {
}
}
impl<T> Slot<T> {
/// `MemorySlot.tick`.
/// `MemorySlot.tick` (`Brain.forgetOutdatedMemories`).
pub(super) fn tick(&mut self) {
if self.v.is_some() && self.ttl != NEVER {
if self.ttl <= 0 {
@@ -73,6 +73,10 @@ impl<T> Slot<T> {
pub fn present(&self) -> bool {
self.v.is_some()
}
/// The time to live (`i64::MAX`: never expires).
pub fn ttl(&self) -> i64 {
self.ttl
}
}
impl<T: Clone> Slot<T> {
pub fn value(&self) -> Option<T> {
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-1
View File
@@ -28,7 +28,6 @@ pub fn register(m: &mut Mob) {
hovers: false,
};
m.ai.nav.kind = NavKind::Flying;
m.persistent = true;
let g = &mut m.ai.goals;
g.add(0, DoNothing);
g.add(
+4 -5
View File
@@ -405,11 +405,10 @@ impl Book {
pub fn entry(&self, id: &str) -> Option<&Entry> {
self.entries.iter().find(|e| e.id == id)
}
/// `ingredient`'s items in registry order (the cycling order of ghost slots).
/// `ingredient`'s items as its display resolves them (the cycling order
/// of ghost slots and the overlay).
pub fn items_of(&self, ingredient: &Ingredient) -> Vec<String> {
let mut items: Vec<String> = ingredient.0.iter().cloned().collect();
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
items
ingredient.1.clone()
}
/// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a
/// `FullTextSearchTree`): without a colon the text must occur in a
@@ -714,7 +713,7 @@ mod tests {
use super::*;
fn ing(items: &[&str]) -> Ingredient {
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
}
#[test]
fn small_recipes_are_centred_in_the_grid() {
@@ -0,0 +1,734 @@
//! The recipe book's drawing (`RecipeBookComponent.extractRenderState`,
//! `extractTooltip` and `GhostSlots.extractRenderState`) as the list of GUI
//! calls vanilla's widgets make: the background, the search `EditBox`, the
//! `RecipeBookTabButton`s, the craftable filter `CycleButton`, the
//! `RecipeBookPage` with its `RecipeButton`s, page number and arrows, the
//! `OverlayRecipeComponent` and the ghost slots, each with the pose it is
//! drawn under. The game paints them; the render parity harness compares them.
use crate::{
items::ItemStack,
recipe_book::{Book, BookType, Display, Entry},
};
/// A styled run of text: its characters, colour (`-1` for the call's own) and italics.
#[derive(Clone, Debug, PartialEq)]
pub struct Run {
pub text: String,
pub color: i32,
pub italic: bool,
}
impl Run {
pub fn plain(text: impl Into<String>) -> Self {
Run {
text: text.into(),
color: -1,
italic: false,
}
}
}
/// How an item is drawn: `GuiGraphicsExtractor.item`, `fakeItem` or `itemDecorations`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ItemCall {
Item,
Fake,
Decorations,
}
/// One GUI call.
#[derive(Clone, Debug)]
pub enum Call {
/// `blit` of a texture region (the book's background).
Blit {
texture: &'static str,
x: i32,
y: i32,
w: i32,
h: i32,
u: f32,
v: f32,
tw: i32,
th: i32,
},
/// `blitSprite`, the id without its namespace.
Sprite {
id: String,
x: i32,
y: i32,
w: i32,
h: i32,
},
Fill {
x0: i32,
y0: i32,
x1: i32,
y1: i32,
color: i32,
},
/// `textHighlight` (the search box's selection).
Highlight { x0: i32, y0: i32, x1: i32, y1: i32 },
Text {
runs: Vec<Run>,
x: i32,
y: i32,
color: i32,
shadow: bool,
},
Item {
call: ItemCall,
stack: ItemStack,
x: i32,
y: i32,
},
/// A widget's tooltip lines.
Tooltip(Vec<Vec<Run>>),
/// The hovered recipe button's tooltip: its display stack's own tooltip,
/// then "Right Click for More" when it has several recipes.
ItemTooltip { stack: ItemStack, more: bool },
/// `nextStratum`.
Stratum,
}
/// A call and the pose (`Matrix3x2f` m00, m01, m10, m11, m20, m21) it is made under.
#[derive(Clone, Debug)]
pub struct Drawn {
pub call: Call,
pub pose: [f32; 6],
}
pub const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
/// JOML `Matrix3x2f.translate`.
fn translate(m: [f32; 6], x: f32, y: f32) -> [f32; 6] {
[
m[0],
m[1],
m[2],
m[3],
m[0] * x + m[2] * y + m[4],
m[1] * x + m[3] * y + m[5],
]
}
/// JOML `Matrix3x2f.scale`.
fn scale(m: [f32; 6], x: f32, y: f32) -> [f32; 6] {
[m[0] * x, m[1] * x, m[2] * y, m[3] * y, m[4], m[5]]
}
/// The search box (`EditBox` fields).
#[derive(Clone, Debug, Default)]
pub struct Search {
pub value: String,
/// Cursor, selection end and first shown character, in characters.
pub cursor: usize,
pub highlight: usize,
pub display: usize,
pub focused: bool,
/// Milliseconds since the box was focused (`TextCursorUtils.isCursorVisible`).
pub blink_ms: u64,
}
/// A visible tab, in order: its icons, whether selected, its squeeze time left.
#[derive(Clone, Debug)]
pub struct TabView {
pub icons: (String, Option<String>),
pub selected: bool,
pub anim: f32,
}
/// A recipe button: its collection has a craftable recipe; the display
/// stacks of each selected recipe; the squeeze time left.
#[derive(Clone, Debug)]
pub struct ButtonView {
pub has_craftable: bool,
pub entries: Vec<Vec<ItemStack>>,
pub anim: f32,
}
/// A recipe of the overlay: craftable, and its ingredient cells (grid
/// x, y and the stacks the cell cycles through).
#[derive(Clone, Debug)]
pub struct OverlayRecipe {
pub craftable: bool,
pub cells: Vec<(i32, i32, Vec<ItemStack>)>,
}
/// The alternatives overlay of a button, at the corner [`overlay_origin`] gives.
#[derive(Clone, Debug)]
pub struct OverlayView {
pub x: i32,
pub y: i32,
/// Craftable recipes first.
pub recipes: Vec<OverlayRecipe>,
}
/// A ghost slot: its position in the menu, the stacks it cycles through,
/// and whether it is the result slot.
#[derive(Clone, Debug)]
pub struct GhostView {
pub x: i32,
pub y: i32,
pub items: Vec<ItemStack>,
pub result: bool,
}
/// What the recipe book shows.
pub struct Screen<'a> {
pub book: BookType,
/// GUI size and `widthTooNarrow`.
pub width: i32,
pub height: i32,
pub narrow: bool,
pub mouse: (i32, i32),
/// `slotSelectTime.currentIndex()`.
pub index: usize,
pub filtering: bool,
pub search: &'a Search,
pub tabs: &'a [TabView],
/// The current page's buttons.
pub buttons: &'a [ButtonView],
pub page: usize,
pub pages: usize,
pub overlay: Option<&'a OverlayView>,
/// The container's corner, whether its result slot is big, and the ghost slots.
pub ghost: Option<(i32, i32, bool, &'a [GhostView])>,
/// Translations.
pub translate: &'a dyn Fn(&str) -> String,
/// `Font.width`.
pub text_width: &'a dyn Fn(&str) -> i32,
}
impl Screen<'_> {
/// `RecipeBookComponent.getXOrigin` and `getYOrigin`.
pub fn origin(&self) -> (i32, i32) {
let offset = if self.narrow { 0 } else { 86 };
((self.width - 147) / 2 - offset, (self.height - 166) / 2)
}
fn hovered(&self, x: i32, y: i32, w: i32, h: i32) -> bool {
let (mx, my) = self.mouse;
mx >= x && my >= y && mx < x + w && my < y + h
}
/// `Font.plainSubstrByWidth`.
fn substr_by_width<'s>(&self, s: &'s str, max: i32) -> &'s str {
let mut end = 0;
for (i, c) in s.char_indices() {
if (self.text_width)(&s[..i + c.len_utf8()]) > max {
break;
}
end = i + c.len_utf8();
}
&s[..end]
}
}
/// The recipe book's calls, in vanilla's order.
pub fn draw(s: &Screen) -> Vec<Drawn> {
let mut out = Vec::new();
let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose });
let (xo, yo) = s.origin();
put(
Call::Blit {
texture: "textures/gui/recipe_book.png",
x: xo,
y: yo,
w: 147,
h: 166,
u: 1.0,
v: 1.0,
tw: 256,
th: 256,
},
IDENTITY,
);
search_box(s, xo + 25, yo + 13, &mut put);
// updateTabs.
let offset = if s.narrow { 0 } else { 86 };
let tab_x = (s.width - 147) / 2 - offset - 30;
let tab_y = (s.height - 166) / 2 + 3;
for (n, tab) in s.tabs.iter().enumerate() {
let (x, y) = (tab_x, tab_y + 27 * n as i32);
let mut pose = IDENTITY;
if tab.anim > 0.0 {
let squeeze = squeeze(tab.anim);
let (cx, cy) = ((x + 8) as f32, (y + 12) as f32);
pose = translate(scale(translate(pose, cx, cy), 1.0, squeeze), -cx, -cy);
}
let sprite = if tab.selected {
"recipe_book/tab_selected"
} else {
"recipe_book/tab"
};
let left = if tab.selected { -2 } else { 0 };
put(sprite_call(sprite, x + left, y, 35, 27), pose);
let fake = |id: &str, x: i32| Call::Item {
call: ItemCall::Fake,
stack: ItemStack::new(id, 1),
x,
y: y + 5,
};
match &tab.icons.1 {
Some(second) => {
put(fake(&tab.icons.0, x + 3 + left), pose);
put(fake(second, x + 14 + left), pose);
}
None => put(fake(&tab.icons.0, x + 9 + left), pose),
}
}
// The craftable filter.
let (fx, fy) = (xo + 110, yo + 12);
let hover = s.hovered(fx, fy, 26, 16);
let prefix = if s.book == BookType::Crafting {
"recipe_book/"
} else {
"recipe_book/furnace_"
};
let state = if s.filtering {
"filter_enabled"
} else {
"filter_disabled"
};
put(
sprite_call(
&format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" }),
fx,
fy,
26,
16,
),
IDENTITY,
);
if hover {
let key = if !s.filtering {
"gui.recipebook.toggleRecipes.all"
} else {
match s.book {
BookType::Crafting => "gui.recipebook.toggleRecipes.craftable",
BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable",
BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable",
BookType::Smoker => "gui.recipebook.toggleRecipes.smokable",
}
};
put(
Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]),
IDENTITY,
);
}
// RecipeBookPage.extractRenderState.
if s.pages > 1 {
let text = (s.translate)("gui.recipebook.page")
.replacen("%s", &(s.page + 1).to_string(), 1)
.replacen("%s", &s.pages.to_string(), 1);
let w = (s.text_width)(&text);
put(
Call::Text {
runs: vec![Run::plain(text)],
x: xo - w / 2 + 73,
y: yo + 141,
color: -1,
shadow: true,
},
IDENTITY,
);
}
let mut hovered = None;
for (i, b) in s.buttons.iter().enumerate().take(20) {
let (x, y) = (xo + 11 + 25 * (i as i32 % 5), yo + 31 + 25 * (i as i32 / 5));
let many = b.entries.len() > 1;
let sprite = match (b.has_craftable, many) {
(true, true) => "recipe_book/slot_many_craftable",
(true, false) => "recipe_book/slot_craftable",
(false, true) => "recipe_book/slot_many_uncraftable",
(false, false) => "recipe_book/slot_uncraftable",
};
let mut pose = IDENTITY;
if b.anim > 0.0 {
let squeeze = squeeze(b.anim);
let (cx, cy) = ((x + 8) as f32, (y + 12) as f32);
pose = translate(scale(translate(pose, cx, cy), squeeze, squeeze), -cx, -cy);
}
put(sprite_call(sprite, x, y, 25, 25), pose);
let stack = display_stack(&b.entries, s.index);
let mut offset = 4;
if many && same_result_display(&b.entries) {
put(
Call::Item {
call: ItemCall::Item,
stack: stack.clone(),
x: x + offset + 1,
y: y + offset + 1,
},
pose,
);
offset -= 1;
}
put(
Call::Item {
call: ItemCall::Fake,
stack: stack.clone(),
x: x + offset,
y: y + offset,
},
pose,
);
if s.hovered(x, y, 25, 25) {
hovered = Some((stack, many));
}
}
let arrows = [
(
s.pages > 1 && s.page + 1 < s.pages,
xo + 93,
"recipe_book/page_forward",
"gui.recipebook.next_page",
),
(
s.pages > 1 && s.page > 0,
xo + 38,
"recipe_book/page_backward",
"gui.recipebook.previous_page",
),
];
for (visible, x, sprite, key) in arrows {
if !visible {
continue;
}
let hover = s.hovered(x, yo + 137, 12, 17);
let id = if hover {
format!("{sprite}_highlighted")
} else {
sprite.to_owned()
};
put(sprite_call(&id, x, yo + 137, 12, 17), IDENTITY);
if hover {
put(
Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]),
IDENTITY,
);
}
}
put(Call::Stratum, IDENTITY);
if let Some(o) = s.overlay {
overlay(s, o, &mut put);
}
// RecipeBookPage.extractTooltip.
if let Some((stack, more)) = hovered
&& s.overlay.is_none()
{
put(Call::ItemTooltip { stack, more }, IDENTITY);
}
if let Some((left, top, big, ghosts)) = s.ghost {
out.extend(ghost(s.index, left, top, big, ghosts));
}
out
}
/// `GhostSlots.extractRenderState` for a container whose corner is `(left, top)`.
pub fn ghost(index: usize, left: i32, top: i32, big: bool, ghosts: &[GhostView]) -> Vec<Drawn> {
let mut out = Vec::new();
let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose });
let pose = translate(IDENTITY, left as f32, top as f32);
for g in ghosts.iter().filter(|g| !g.items.is_empty()) {
let (x, y) = (g.x, g.y);
if g.result && big {
put(fill(x - 4, y - 4, x + 20, y + 20, 822_018_048), pose);
} else {
put(fill(x, y, x + 16, y + 16, 822_018_048), pose);
}
let stack = g.items[index % g.items.len()].clone();
put(
Call::Item {
call: ItemCall::Fake,
stack: stack.clone(),
x,
y,
},
pose,
);
put(fill(x, y, x + 16, y + 16, 822_083_583), pose);
if g.result {
put(
Call::Item {
call: ItemCall::Decorations,
stack,
x,
y,
},
pose,
);
}
}
out
}
/// `1 + 0.1 sin(t / 15 * PI)`, the squeeze of new recipes' buttons and tabs.
fn squeeze(time: f32) -> f32 {
1.0 + 0.1 * f64::from(time / 15.0 * std::f32::consts::PI).sin() as f32
}
fn sprite_call(id: &str, x: i32, y: i32, w: i32, h: i32) -> Call {
Call::Sprite {
id: id.to_owned(),
x,
y,
w,
h,
}
}
fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: i32) -> Call {
Call::Fill {
x0,
y0,
x1,
y1,
color,
}
}
/// `RecipeButton.getDisplayStack`.
fn display_stack(entries: &[Vec<ItemStack>], index: usize) -> ItemStack {
let n = entries.len().max(1);
let (offset, entry) = (index / n, index % n);
match entries.get(entry) {
Some(items) if !items.is_empty() => items[offset % items.len()].clone(),
_ => ItemStack::new("minecraft:air", 0),
}
}
/// `RecipeButton.allRecipesHaveSameResultDisplay`.
fn same_result_display(entries: &[Vec<ItemStack>]) -> bool {
let mut items = entries.iter().flatten();
let Some(first) = items.next() else {
return true;
};
items.all(|s| first.same_item_same_components(s))
}
/// `EditBox.extractWidgetRenderState` for the recipe book's search box.
fn search_box(s: &Screen, x: i32, y: i32, put: &mut impl FnMut(Call, [f32; 6])) {
let b = s.search;
let (w, h) = (81, 9 + 5);
let sprite = if b.focused {
"widget/text_field_highlighted"
} else {
"widget/text_field"
};
put(sprite_call(sprite, x, y, w, h), IDENTITY);
let (text_x, text_y) = (x + 4, y + (h - 8) / 2);
let color = -1;
let chars: Vec<char> = b.value.chars().collect();
let tail: String = chars[b.display.min(chars.len())..].iter().collect();
let displayed = s.substr_by_width(&tail, w - 8).to_owned();
let shown = displayed.chars().count();
let rel_cursor = b.cursor as i64 - b.display as i64;
let on_screen = rel_cursor >= 0 && rel_cursor <= shown as i64;
let visible = b.focused && (b.blink_ms / 300).is_multiple_of(2) && on_screen;
let mut draw_x = text_x;
let rel_highlight = (b.highlight as i64 - b.display as i64).clamp(0, shown as i64) as usize;
let prefix = |n: usize| displayed.chars().take(n).collect::<String>();
if !displayed.is_empty() {
let half = if on_screen {
prefix(rel_cursor as usize)
} else {
displayed.clone()
};
let width = (s.text_width)(&half);
put(
Call::Text {
runs: runs_of(half),
x: draw_x,
y: text_y,
color,
shadow: true,
},
IDENTITY,
);
draw_x += width + 1;
}
let insert = b.cursor < chars.len() || chars.len() >= 50;
let mut cursor_x = draw_x;
if !on_screen {
cursor_x = if rel_cursor > 0 { text_x + w } else { text_x };
} else if insert {
cursor_x -= 1;
draw_x -= 1;
}
if !displayed.is_empty() && on_screen && (rel_cursor as usize) < shown {
let rest: String = displayed.chars().skip(rel_cursor as usize).collect();
put(
Call::Text {
runs: runs_of(rest),
x: draw_x,
y: text_y,
color,
shadow: true,
},
IDENTITY,
);
}
if displayed.is_empty() && !b.focused {
// SEARCH_HINT: gray, italic.
put(
Call::Text {
runs: vec![Run {
text: (s.translate)("gui.recipebook.search_hint"),
color: 0xAAAAAA,
italic: true,
}],
x: draw_x,
y: text_y,
color,
shadow: true,
},
IDENTITY,
);
}
if rel_highlight as i64 != rel_cursor {
let highlight_x = text_x + (s.text_width)(&prefix(rel_highlight));
put(
Call::Highlight {
x0: cursor_x.min(x + w),
y0: text_y - 1,
x1: (highlight_x - 1).min(x + w),
y1: text_y + 1 + 9,
},
IDENTITY,
);
}
if visible {
if insert {
put(
fill(cursor_x, text_y - 1, cursor_x + 1, text_y + 10, color),
IDENTITY,
);
} else {
put(
Call::Text {
runs: vec![Run::plain("_")],
x: cursor_x,
y: text_y,
color,
shadow: true,
},
IDENTITY,
);
}
}
}
fn runs_of(text: String) -> Vec<Run> {
if text.is_empty() {
Vec::new()
} else {
vec![Run::plain(text)]
}
}
/// `OverlayRecipeComponent.init`'s corner for `total` recipes opened from the
/// button at `(button_x, button_y)` of the book at `(xo, yo)`.
pub fn overlay_origin(button_x: i32, button_y: i32, total: usize, xo: i32, yo: i32) -> (i32, i32) {
let total = total as i32;
let max_row = if total <= 16 { 4 } else { 5 };
let rows = (total as f32 / max_row as f32).ceil() as i32;
let (mut x, mut y) = (button_x, button_y);
let width = 25.0f32;
let (center_x, center_y) = (xo + 147 / 2, yo + 13 + 166 / 2);
let right = (x + total.min(max_row) * 25) as f32;
let max_left = (center_x + 50) as f32;
if right > max_left {
x = (x as f32 - width * ((right - max_left) / width) as i32 as f32) as i32;
}
let bottom = (y + rows * 25) as f32;
let max_bottom = (center_y + 50) as f32;
if bottom > max_bottom {
y = (y as f32 - width * ((bottom - max_bottom) / width).ceil()) as i32;
}
let top = y as f32;
let max_top = (center_y - 100) as f32;
if top < max_top {
y = (y as f32 - width * ((top - max_top) / width).ceil()) as i32;
}
(x, y)
}
/// `OverlayRecipeComponent.extractRenderState`.
fn overlay(s: &Screen, o: &OverlayView, put: &mut impl FnMut(Call, [f32; 6])) {
let total = o.recipes.len() as i32;
let max_row = if total <= 16 { 4 } else { 5 };
let (x, y) = (o.x, o.y);
let columns = total.min(max_row);
let height = (total as f32 / max_row as f32).ceil() as i32;
put(
sprite_call(
"recipe_book/overlay_recipe",
x,
y,
columns * 25 + 8,
height * 25 + 8,
),
IDENTITY,
);
let family = if s.book == BookType::Crafting {
"crafting"
} else {
"furnace"
};
for (i, r) in o.recipes.iter().enumerate() {
let i = i as i32;
let (bx, by) = (x + 4 + 25 * (i % max_row), y + 5 + 25 * (i / max_row));
let hover = s.hovered(bx, by, 24, 24);
let id = format!(
"recipe_book/{family}_overlay{}{}",
if r.craftable { "" } else { "_disabled" },
if hover { "_highlighted" } else { "" }
);
put(sprite_call(&id, bx, by, 24, 24), IDENTITY);
let (gx, gy) = ((bx + 2) as f32, (by + 2) as f32);
for (cx, cy, items) in &r.cells {
let pose = translate(
scale(
translate(IDENTITY, gx + (3 + cx * 7) as f32, gy + (3 + cy * 7) as f32),
0.375,
0.375,
),
-8.0,
-8.0,
);
put(
Call::Item {
call: ItemCall::Item,
stack: items[s.index % items.len()].clone(),
x: 0,
y: 0,
},
pose,
);
}
}
}
/// The ingredient cells a recipe shows in the overlay
/// (`OverlayCraftingRecipeButton` / `OverlaySmeltingRecipeButton.calculateIngredientsPositions`).
pub fn overlay_cells(book: &Book, entry: &Entry) -> Vec<(i32, i32, Vec<ItemStack>)> {
let stacks = |ingredient| -> Vec<ItemStack> {
book.items_of(ingredient)
.iter()
.map(|i| ItemStack::new(i, 1))
.collect()
};
let mut out = Vec::new();
match &entry.display {
Display::Furnace(i) => out.push((1, 1, stacks(i))),
Display::Shaped { .. } => {
let requirements = entry.requirements();
for (ingredient, grid) in entry.grid_cells(3, 3) {
if let Some(i) = ingredient {
out.push((grid as i32 % 3, grid as i32 / 3, stacks(requirements[i])));
}
}
}
Display::Shapeless(list) => {
for (i, ingredient) in list.iter().enumerate() {
out.push((i as i32 % 3, i as i32 / 3, stacks(ingredient)));
}
}
}
out.retain(|c| !c.2.is_empty());
out
}
+1 -1
View File
@@ -53,7 +53,7 @@ pub(crate) fn text(tag: Option<&Tag>) -> Option<String> {
}
}
/// Any numeric tag as i64 (vanilla's `getIntOr` etc. accept every number type).
pub(crate) fn number(tag: Option<&Tag>) -> Option<i64> {
pub fn number(tag: Option<&Tag>) -> Option<i64> {
Some(match tag? {
Tag::Byte(v) => i64::from(*v),
Tag::Short(v) => i64::from(*v),
+10 -7
View File
@@ -10,7 +10,7 @@ use crate::{
};
use horizon_core::random::{LegacyRandom, RandomSource};
use serde_json::Value;
use std::{collections::HashSet, fs, path::Path, sync::Arc};
use std::{fs, path::Path, sync::Arc};
/// Everything the workstation menus read, loaded once with the resources.
pub struct StationData {
@@ -457,7 +457,7 @@ pub struct StationRecipes {
pub trim_materials: Vec<(String, String)>,
}
fn ingredient(v: &Value, items: &Items) -> Ingredient {
let mut set = HashSet::new();
let mut list: Vec<String> = Vec::new();
for s in match v {
Value::String(s) => vec![s.clone()],
Value::Array(a) => a
@@ -466,14 +466,17 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient {
.collect(),
_ => vec![],
} {
match s.strip_prefix('#') {
Some(tag) => set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()),
None => {
set.insert(s);
let more = match s.strip_prefix('#') {
Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(),
None => vec![s],
};
for i in more {
if !list.contains(&i) {
list.push(i);
}
}
}
Ingredient(set)
Ingredient::of(list)
}
impl StationRecipes {
pub fn load(root: &Path, items: &Items) -> Self {
+6
View File
@@ -701,6 +701,12 @@ impl EditBox {
}
true
}
/// The first shown character after scrolling to the cursor, and the
/// milliseconds since the field was focused (the cursor's blink).
pub fn view_state(&mut self, atlas: &HudAtlas) -> (usize, u64) {
self.layout(atlas);
(self.display, self.focused_at.elapsed().as_millis() as u64)
}
/// Draw the field; `format` styles the visible text (command colouring).
pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) {
self.layout(atlas);
+15 -4
View File
@@ -1418,11 +1418,22 @@ vanilla's own classes, and the game uses that code:
`CrafterScreen`'s decorations as draw calls the game paints;
`tools/test_screen_layout_parity.py` runs vanilla's screens on stand-in
menus and compares 1,600 call lists.
- **The book's drawing.** `recipe_book_screen` lays out
`RecipeBookComponent`'s background, search `EditBox`, tab buttons, filter
`CycleButton`, the page of `RecipeButton`s with its number and arrows, the
`OverlayRecipeComponent`, the tooltips and `GhostSlots` as GUI calls with
their poses (squeeze animations, the overlay's 3/8 scale items); the game
paints them. `tools/test_recipe_book_render_parity.py` builds vanilla's
widgets for 600 states (`VanillaRecipeBookScreenOracle`) and compares every
call. Ingredients cycle in their `HolderSet` order (tags in `TagLoader` order).
- **The loom's banner preview.** `item_render::gui::draw_banner_result` draws
`GuiBannerResultRenderer`'s flag model and layers in the 20x40 picture in
picture, lit with `ITEMS_FLAT`; the block entity render harness compares its
quads under the picture-in-picture pose.
Not compared yet: the recipe book's own drawing (tabs, buttons, the overlay
and ghost slots) and its text search, the banner preview's 3D flag (drawn as
the flat front face), furnaces awarding their recipes and experience when
their output is taken, and the limited crafting game rule.
Not compared yet: the recipe book's text search, furnaces awarding their
recipes and experience when their output is taken, and the limited crafting
game rule.
## Player list and world border rendering
@@ -33,13 +33,15 @@ import net.minecraft.world.phys.*;
/**
* Original oracle for the client-ticked animation state of chests and ender
* chests (ChestLidController), enchanting table books, shulker boxes, bells,
* conduits, skulls and decorated pots. Each case builds the real
* conduits, skulls, decorated pots and End gateways. Each case builds the real
* vanilla block entity on a stand-in client level (scripted blocks, entities,
* game time and a seeded LegacyRandomSource), then per step applies the
* scripted block event (triggerEvent), runs the block entity's own client
* ticker (lidAnimateTick, bookAnimationTick with the class's static RANDOM
* reseeded, ShulkerBoxBlockEntity.tick, BellBlockEntity.clientTick,
* ConduitBlockEntity.clientTick, SkullBlockEntity.animation; pots have none)
* ConduitBlockEntity.clientTick, SkullBlockEntity.animation,
* TheEndGatewayBlockEntity.beamAnimationTick after the server copy's portalTick
* on a server-side stand-in; pots have none)
* and runs the real renderer's extractRenderState at the step's partial tick.
* It prints the block entity's fields, the level calls the tick made
* (neighbour updates, entity queries, sounds, particles) and the render state.
@@ -100,6 +102,9 @@ public final class VanillaBlockEntityAnimOracle {
static final class World extends Level {
World() { super(null, null, null, null, false, false, 0L, 0); }
long time;
boolean server;
int minY, height;
BlockEntity serverCopyOf;
Map<BlockPos, BlockState> blocks = new HashMap<>();
List<Mob> mobs = new ArrayList<>();
List<Player> gamers = new ArrayList<>();
@@ -108,7 +113,16 @@ public final class VanillaBlockEntityAnimOracle {
StringBuilder log = new StringBuilder();
@Override public long getGameTime() { return time; }
@Override public boolean isClientSide() { return true; }
@Override public boolean isClientSide() { return !server; }
@Override public int getMinY() { return minY; }
@Override public int getHeight() { return height; }
@Override public void blockEvent(BlockPos p, Block block, int b0, int b1) {
// The integrated server's block event reaching the client copy.
log.append(" blockEvent ").append(b0).append(' ').append(b1);
serverCopyOf.triggerEvent(b0, b1);
}
@Override public void blockEntityChanged(BlockPos p) {}
@Override public void updateNeighbourForOutputSignal(BlockPos p, Block block) {}
@Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p.immutable(), Blocks.AIR.defaultBlockState()); }
@Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); }
@Override public int getBrightness(LightLayer layer, BlockPos p) { return 0; }
@@ -236,6 +250,22 @@ public final class VanillaBlockEntityAnimOracle {
if (c.has("target") && be instanceof ConduitBlockEntity) {
put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world)));
}
World serverWorld = null;
TheEndGatewayBlockEntity serverGateway = null;
if (be instanceof TheEndGatewayBlockEntity g) {
var level = c.getAsJsonArray("level");
world.minY = level.get(0).getAsInt();
world.height = level.get(1).getAsInt();
field(TheEndGatewayBlockEntity.class, "age").setLong(g, c.get("age").getAsLong());
serverWorld = make(World.class);
serverWorld.server = true;
serverWorld.blocks = world.blocks;
serverWorld.log = world.log;
serverWorld.serverCopyOf = g;
serverGateway = (TheEndGatewayBlockEntity) ((EntityBlock) state.getBlock()).newBlockEntity(pos, state);
serverGateway.setLevel(serverWorld);
field(TheEndGatewayBlockEntity.class, "age").setLong(serverGateway, c.get("age").getAsLong());
}
StringBuilder out = new StringBuilder();
for (var stepElement : c.getAsJsonArray("steps")) {
var step = stepElement.getAsJsonObject();
@@ -251,6 +281,14 @@ public final class VanillaBlockEntityAnimOracle {
world.gamers.clear();
for (var e : step.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject()));
}
if (serverGateway != null) {
serverWorld.time = world.time;
// ServerLevel.tick: entities (EndGatewayBlock.entityInside), then block entities.
if (step.has("enter") && !serverGateway.isCoolingDown()) {
TheEndGatewayBlockEntity.triggerCooldown(serverWorld, pos, state, serverGateway);
}
TheEndGatewayBlockEntity.portalTick(serverWorld, pos, state, serverGateway);
}
if (step.has("event")) {
var ev = step.getAsJsonArray("event");
boolean handled = be.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt());
@@ -327,6 +365,15 @@ public final class VanillaBlockEntityAnimOracle {
make(DecoratedPotRenderer.class).extractRenderState(p, r, partial, Vec3.ZERO, null);
fields = p.wobbleStartedAtTick + " " + p.lastWobbleStyle
+ " render " + f(r.wobbleProgress) + " " + r.wobbleStyle;
} else if (be instanceof TheEndGatewayBlockEntity g) {
TheEndGatewayBlockEntity.beamAnimationTick(world, pos, state, g);
var r = make(TheEndGatewayRenderer.class).createRenderState();
make(TheEndGatewayRenderer.class).extractRenderState(g, r, partial, Vec3.ZERO, null);
fields = field(TheEndGatewayBlockEntity.class, "age").getLong(g)
+ " " + field(TheEndGatewayBlockEntity.class, "teleportCooldown").getInt(g)
+ " server " + field(TheEndGatewayBlockEntity.class, "age").getLong(serverGateway)
+ " " + field(TheEndGatewayBlockEntity.class, "teleportCooldown").getInt(serverGateway)
+ " render " + r.height + " " + f(r.scale) + " " + Integer.toHexString(r.color) + " " + f(r.animationTime);
} else {
throw new IllegalArgumentException("no animation for " + be);
}
@@ -11,6 +11,9 @@ import net.minecraft.client.gui.Font;
import net.minecraft.client.model.Model;
import net.minecraft.client.model.geom.EntityModelSet;
import net.minecraft.client.model.geom.LayerDefinitions;
import net.minecraft.client.model.object.banner.BannerFlagModel;
import net.minecraft.client.renderer.Sheets;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.renderer.SubmitNodeCollector;
import net.minecraft.client.renderer.blockentity.*;
import net.minecraft.client.renderer.blockentity.state.*;
@@ -333,17 +336,39 @@ public final class VanillaBlockEntityRenderOracle {
}
be.setLevel(level);
} else if (be instanceof BannerBlockEntity && c.has("patterns")) {
var builder = new net.minecraft.world.level.block.entity.BannerPatternLayers.Builder();
var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN);
for (var e : c.getAsJsonArray("patterns")) {
var p = e.getAsJsonArray();
var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString())));
builder.add(holder, dye(p.get(1).getAsString()));
}
field(BannerBlockEntity.class, "patterns").set(be, builder.build());
field(BannerBlockEntity.class, "patterns").set(be, patterns(c.getAsJsonArray("patterns")));
}
}
/** [[pattern id, dye], ...] as BannerPatternLayers. */
static BannerPatternLayers patterns(JsonArray list) {
var builder = new BannerPatternLayers.Builder();
var registry = ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN);
for (var e : list) {
var p = e.getAsJsonArray();
var holder = registry.getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(p.get(0).getAsString())));
builder.add(holder, dye(p.get(1).getAsString()));
}
return builder.build();
}
/**
* LoomScreen's result preview (GuiGraphicsExtractor.bannerPattern): the
* picture-in-picture pose of PictureInPictureRenderer.prepare for its 20x40
* rectangle at GUI scale 1 (translate(w / 2, h), scale(16, 16, -16)), then
* GuiBannerResultRenderer.renderToTexture without its lighting setup
* (Lighting.Entry.ITEMS_FLAT, applied by the harness).
*/
static void loomResult(JsonObject loom, BannerFlagModel flag, SpriteGetter sprites, SubmitNodeCollector collector) {
var pose = new PoseStack();
pose.translate(20 / 2.0F, 40.0F, 0.0F);
pose.scale(16.0F, 16.0F, -16.0F);
pose.translate(0.0F, 0.25F, 0.0F);
collector.submitModel(flag, 0.0F, pose, 15728880, OverlayTexture.NO_OVERLAY, -1, Sheets.BANNER_BASE, sprites, 0);
BannerRenderer.submitPatterns(sprites, pose, collector, 15728880, OverlayTexture.NO_OVERLAY, flag, 0.0F, true,
dye(loom.get("base").getAsString()), patterns(loom.getAsJsonArray("patterns")));
}
/** Render-state values vanilla reads from the level (absent here). */
static void patch(BlockEntityRenderState rs, BlockState state, JsonObject c) {
if (rs instanceof ChestRenderState chest) {
@@ -381,6 +406,7 @@ public final class VanillaBlockEntityRenderOracle {
var items = new net.minecraft.client.renderer.item.ItemModelResolver(null);
var context = new BlockEntityRendererProvider.Context(null, null, items, null, models, font, sprites, null);
Map<Object, BlockEntityRenderer> renderers = (Map) BlockEntityRenderers.createEntityRenderers(context);
var loomFlag = new BannerFlagModel(models.bakeLayer(net.minecraft.client.model.geom.ModelLayers.STANDING_BANNER_FLAG));
var gson = new Gson();
var out = new StringBuilder();
for (String line : Files.readAllLines(Path.of(args[0]))) {
@@ -389,6 +415,13 @@ public final class VanillaBlockEntityRenderOracle {
var result = new JsonObject();
result.add("case", c);
try {
if (c.has("loom")) {
var submits = new JsonArray();
loomResult(c.getAsJsonObject("loom"), loomFlag, sprites, collector(submits));
result.add("submits", submits);
out.append(gson.toJson(result)).append('\n');
continue;
}
BlockState state = parseState(c.get("block").getAsString());
var p = c.getAsJsonArray("pos");
var pos = new BlockPos(p.get(0).getAsInt(), p.get(1).getAsInt(), p.get(2).getAsInt());
@@ -0,0 +1,527 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.function.Predicate;
import net.minecraft.SharedConstants;
import net.minecraft.core.*;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.TagLoader;
import net.minecraft.util.RandomSource;
import net.minecraft.world.Difficulty;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.ai.Brain;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.ItemEnchantments;
import net.minecraft.world.level.*;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.border.WorldBorder;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.gamerules.GameRules;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.StructurePiece;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
/**
* Original oracle: Mob.finalizeSpawn as vanilla runs it, for every mob type,
* spawn reason, difficulty and local difficulty, on a stand-in ServerLevel
* (one biome, an optional structure piece, a floor and an optional roof,
* chickens standing by, the moon phase).
*
* Each case seeds the level random (what finalizeSpawn reads through
* level.getRandom()) and the entities' own randoms: every entity created
* in the case, the case's mobs and the jockeys finalizeSpawn makes, gets
* a LegacyRandomSource seeded eseed + its creation index, swapped in
* through each EntityType's factory. A pack of mobs is finalized in turn
* with the group data passed along, as NaturalSpawner does, each added to
* the level with its passengers.
*
* The log lists every entity of the case in creation order (equipment and
* enchantments, drop chances, CanPickUpLoot, LeftHanded, persistence, age,
* health, attribute values, effects, the species' variant state and spawn
* memories, its vehicle) and the next draws of the level random and of each
* entity's random, which pin every draw in between.
*/
public final class VanillaFinalizeSpawnOracle {
static Object unsafe;
static Method allocate, putObject, objectFieldOffset;
static Object alloc(Class<?> c) throws Exception { return allocate.invoke(unsafe, c); }
static void put(Object target, Class<?> owner, String field, Object value) throws Exception {
Field f = owner.getDeclaredField(field);
putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value);
}
static Object get(Object target, Class<?> owner, String field) {
try {
Field f = owner.getDeclaredField(field);
f.setAccessible(true);
return f.get(target);
} catch (Exception e) { throw new RuntimeException(e); }
}
static final class Lvl extends ServerLevel {
Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); }
RegistryAccess registries;
net.minecraft.server.MinecraftServer fake;
BlockState floor;
int floorY, roofY;
Holder<Biome> biome;
Difficulty difficulty;
DimensionType dimensionType;
ResourceKey<Level> dimensionKey;
List<Entity> entities = new ArrayList<>();
net.minecraft.world.attribute.EnvironmentAttributeSystem attributes;
BiomeManager biomeManager;
WorldBorder border = new WorldBorder();
GameRules rules;
Structures structures;
RandomSource levelRandom;
long time;
int next = 1;
@Override public net.minecraft.server.MinecraftServer getServer() { return fake; }
@Override public RegistryAccess registryAccess() { return registries; }
@Override public Difficulty getDifficulty() { return difficulty; }
@Override public long getGameTime() { return time; }
@Override public int getNextEntityId() { return next++; }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
@Override public BlockState getBlockState(BlockPos pos) {
if (pos.getY() == floorY) return floor;
if (pos.getY() == roofY) return Blocks.STONE.defaultBlockState();
return Blocks.AIR.defaultBlockState();
}
@Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
@Override public DimensionType dimensionType() { return dimensionType; }
@Override public ResourceKey<Level> dimension() { return dimensionKey; }
@Override public Holder<Biome> getBiome(BlockPos pos) { return biome; }
@Override public BiomeManager getBiomeManager() { return biomeManager; }
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; }
@Override public WorldBorder getWorldBorder() { return border; }
@Override public GameRules getGameRules() { return rules; }
@Override public RandomSource getRandom() { return levelRandom; }
@Override public int getSeaLevel() { return 63; }
net.minecraft.server.ServerScoreboard scoreboard;
@Override public net.minecraft.server.ServerScoreboard getScoreboard() { return scoreboard; }
@Override public net.minecraft.world.level.StructureManager structureManager() { return structures; }
@Override public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return this; }
@Override public boolean isSpawningMonsters() { return rules.get(GameRules.SPAWN_MOBS) && rules.get(GameRules.SPAWN_MONSTERS); }
@Override public void playSeededSound(net.minecraft.world.entity.Entity except, double x, double y, double z, Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {}
@Override public void playSeededSound(net.minecraft.world.entity.Entity except, net.minecraft.world.entity.Entity sourceEntity, Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {}
@Override public void gameEvent(Holder<net.minecraft.world.level.gameevent.GameEvent> gameEvent, Vec3 position, net.minecraft.world.level.gameevent.GameEvent.Context context) {}
@Override public void broadcastEntityEvent(Entity entity, byte event) {}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override public List players() { return List.of(); }
@Override public Iterable<Entity> getAllEntities() { return entities; }
@Override public List<Entity> getEntities(Entity except, AABB bb, Predicate<? super Entity> selector) {
List<Entity> out = new ArrayList<>();
for (Entity e : entities) if (e != except && e.getBoundingBox().intersects(bb) && selector.test(e)) out.add(e);
return out;
}
@Override public <T extends Entity> List<T> getEntities(EntityTypeTest<Entity, T> type, AABB bb, Predicate<? super T> selector) {
List<T> out = new ArrayList<>();
for (Entity e : entities) {
T t = type.tryCast(e);
if (t != null && e.getBoundingBox().intersects(bb) && selector.test(t)) out.add(t);
}
return out;
}
@Override public boolean addFreshEntity(Entity entity) { if (!entities.contains(entity)) entities.add(entity); return true; }
@Override public void addFreshEntityWithPassengers(Entity entity) { entity.getSelfAndPassengers().forEach(this::addFreshEntity); }
@Override public Player getNearestPlayer(double x, double y, double z, double maxDist, boolean filter) { return null; }
}
/** One structure start whose single piece covers a box around the spawn point. */
static final class Structures extends net.minecraft.world.level.StructureManager {
Structures() { super(null, null, null); }
Lvl level;
Structure structure;
StructureStart start;
@Override public List<StructureStart> startsForStructure(int sectionX, int sectionZ, Predicate<Structure> matcher) {
return start != null && matcher.test(structure) ? List.of(start) : List.of();
}
@Override public List<StructureStart> startsForStructure(int sectionX, int sectionZ, Structure s) {
return start != null && s == structure ? List.of(start) : List.of();
}
@Override public RegistryAccess registryAccess() { return level.registries; }
}
static final class Piece extends StructurePiece {
Piece(BoundingBox box) { super(null, 0, box); }
@Override protected void addAdditionalSaveData(net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext context, net.minecraft.nbt.CompoundTag tag) {}
@Override public void postProcess(WorldGenLevel level, net.minecraft.world.level.StructureManager structureManager, net.minecraft.world.level.chunk.ChunkGenerator generator, RandomSource random,
BoundingBox chunkBB, ChunkPos chunkPos, BlockPos referencePos) {}
}
/** Entities created in the current case, and the seed base of their randoms. */
static List<Entity> created = new ArrayList<>();
static long entitySeed;
static boolean seeding;
static int otherIds;
@SuppressWarnings({"unchecked", "rawtypes"})
static void wrapFactories() throws Exception {
Field factory = EntityType.class.getDeclaredField("factory");
long offset = (long) objectFieldOffset.invoke(unsafe, factory);
factory.setAccessible(true);
for (EntityType<?> type : BuiltInRegistries.ENTITY_TYPE) {
EntityType.EntityFactory original = (EntityType.EntityFactory) factory.get(type);
EntityType.EntityFactory wrapped = (t, level) -> {
Entity e = original.create(t, level);
if (e != null && !seeding) e.setId(1000000 + otherIds++);
if (e != null && seeding) {
try {
put(e, Entity.class, "random", RandomSource.create(entitySeed + created.size()));
} catch (Exception ex) { throw new RuntimeException(ex); }
created.add(e);
e.setId(created.size());
}
return e;
};
putObject.invoke(unsafe, type, offset, wrapped);
}
}
static String hex(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
static String hex(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
static String id(Holder<?> h) { return h.unwrapKey().map(k -> k.identifier().toString()).orElse("?"); }
static final EquipmentSlot[] SLOTS = {EquipmentSlot.MAINHAND, EquipmentSlot.OFFHAND, EquipmentSlot.FEET, EquipmentSlot.LEGS,
EquipmentSlot.CHEST, EquipmentSlot.HEAD, EquipmentSlot.BODY, EquipmentSlot.SADDLE};
static String stack(ItemStack s) {
StringBuilder b = new StringBuilder(BuiltInRegistries.ITEM.getKey(s.getItem()).toString());
if (s.getCount() != 1) b.append('x').append(s.getCount());
ItemEnchantments e = s.getOrDefault(DataComponents.ENCHANTMENTS, ItemEnchantments.EMPTY);
if (!e.isEmpty()) {
List<String> list = new ArrayList<>();
for (var entry : e.entrySet()) list.add(id(entry.getKey()) + "=" + entry.getIntValue());
list.sort(null);
b.append('[').append(String.join(",", list)).append(']');
}
// Components besides enchantments (the ominous banner's).
int other = s.getComponentsPatch().forget(t -> t == DataComponents.ENCHANTMENTS).size();
if (other > 0) b.append('*').append(other);
return b.toString();
}
/** Loaded after the bootstrap. */
static final class Lists {
static final List<Map.Entry<String, Holder<Attribute>>> ATTRIBUTES = List.of(
Map.entry("max_health", Attributes.MAX_HEALTH), Map.entry("movement_speed", Attributes.MOVEMENT_SPEED),
Map.entry("follow_range", Attributes.FOLLOW_RANGE), Map.entry("attack_damage", Attributes.ATTACK_DAMAGE),
Map.entry("knockback_resistance", Attributes.KNOCKBACK_RESISTANCE), Map.entry("spawn_reinforcements", Attributes.SPAWN_REINFORCEMENTS_CHANCE),
Map.entry("jump_strength", Attributes.JUMP_STRENGTH));
static final List<Map.Entry<String, MemoryModuleType<?>>> MEMORIES = List.of(
Map.entry("long_jump_cooldown", MemoryModuleType.LONG_JUMP_COOLDOWN_TICKS), Map.entry("ram_cooldown", MemoryModuleType.RAM_COOLDOWN_TICKS),
Map.entry("attack_target_cooldown", MemoryModuleType.ATTACK_TARGET_COOLDOWN), Map.entry("hunted_recently", MemoryModuleType.HUNTED_RECENTLY),
Map.entry("dig_cooldown", MemoryModuleType.DIG_COOLDOWN), Map.entry("is_emerging", MemoryModuleType.IS_EMERGING),
Map.entry("home", MemoryModuleType.HOME));
}
/** The species state finalizeSpawn sets. */
static void variant(Entity e, List<String> v) {
if (e instanceof net.minecraft.world.entity.animal.pig.Pig p) {
v.add(id(p.getVariant()));
v.add(id((Holder<?>) data(p, p.getClass(), "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.cow.Cow c) {
v.add(id(c.getVariant()));
v.add(id((Holder<?>) data(c, net.minecraft.world.entity.animal.cow.Cow.class, "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.cow.MushroomCow m) {
v.add(m.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.chicken.Chicken c) {
v.add(id(c.getVariant()));
v.add(id((Holder<?>) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID")));
v.add("jockey=" + c.isChickenJockey());
} else if (e instanceof net.minecraft.world.entity.animal.feline.Cat c) {
v.add(id(c.getVariant()));
v.add(id((Holder<?>) data(c, c.getClass(), "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.wolf.Wolf w) {
v.add(id((Holder<?>) call(w, net.minecraft.world.entity.animal.wolf.Wolf.class, "getVariant")));
v.add(id((Holder<?>) data(w, w.getClass(), "DATA_SOUND_VARIANT_ID")));
} else if (e instanceof net.minecraft.world.entity.animal.frog.Frog f) {
v.add(id(f.getVariant()));
} else if (e instanceof net.minecraft.world.entity.animal.nautilus.ZombieNautilus n) {
v.add(id(n.getVariant()));
} else if (e instanceof net.minecraft.world.entity.animal.sheep.Sheep s) {
v.add(s.getColor().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.equine.Horse h) {
v.add(h.getVariant().getSerializedName() + "/" + h.getMarkings().name().toLowerCase(Locale.ROOT));
} else if (e instanceof net.minecraft.world.entity.animal.equine.Llama l) {
v.add(l.getVariant().getSerializedName() + "/" + l.getStrength());
} else if (e instanceof net.minecraft.world.entity.animal.equine.SkeletonHorse h) {
v.add("trap=" + h.isTrap());
} else if (e instanceof net.minecraft.world.entity.animal.fox.Fox f) {
v.add(f.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.rabbit.Rabbit r) {
v.add(r.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.parrot.Parrot p) {
v.add(p.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.axolotl.Axolotl a) {
v.add(a.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.fish.TropicalFish f) {
v.add(String.valueOf(call(f, net.minecraft.world.entity.animal.fish.TropicalFish.class, "getPackedVariant")));
} else if (e instanceof net.minecraft.world.entity.animal.fish.Salmon s) {
v.add(s.getVariant().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.panda.Panda p) {
v.add(p.getMainGene().getSerializedName() + "/" + p.getHiddenGene().getSerializedName());
} else if (e instanceof net.minecraft.world.entity.animal.goat.Goat g) {
v.add("scream=" + g.isScreamingGoat() + " horns=" + g.hasLeftHorn() + "," + g.hasRightHorn());
} else if (e instanceof net.minecraft.world.entity.monster.cubemob.AbstractCubeMob s) {
v.add("size=" + s.getSize());
} else if (e instanceof net.minecraft.world.entity.npc.villager.Villager vi) {
v.add(id(vi.getVillagerData().type()) + "/" + id(vi.getVillagerData().profession()) + "/" + vi.getVillagerData().level());
} else if (e instanceof net.minecraft.world.entity.monster.zombie.ZombieVillager z) {
// The profession comes from the constructor's unseeded random.
v.add(id(z.getVillagerData().type()) + "/" + z.getVillagerData().level());
} else if (e instanceof net.minecraft.world.entity.monster.Phantom p) {
v.add("size=" + p.getPhantomSize());
} else if (e instanceof net.minecraft.world.entity.animal.turtle.Turtle t) {
BlockPos h = (BlockPos) get(t, net.minecraft.world.entity.animal.turtle.Turtle.class, "homePos");
v.add("home=" + (h == null ? "-" : h.getX() + "," + h.getY() + "," + h.getZ()));
} else if (e instanceof net.minecraft.world.entity.animal.dolphin.Dolphin d) {
v.add("air=" + d.getAirSupply());
}
if (e instanceof net.minecraft.world.entity.monster.zombie.Zombie z) v.add("doors=" + z.canBreakDoors());
if (e instanceof net.minecraft.world.entity.monster.PatrollingMonster p) v.add("leader=" + p.isPatrolLeader() + " patrolling=" + call(p, net.minecraft.world.entity.monster.PatrollingMonster.class, "isPatrolling"));
if (e instanceof net.minecraft.world.entity.raid.Raider r) v.add("raid=" + r.canJoinRaid());
if (e instanceof net.minecraft.world.entity.monster.Strider s) v.add("saddled=" + s.isSaddled());
}
@SuppressWarnings({"unchecked", "rawtypes"})
static Object data(Entity e, Class<?> owner, String name) {
return e.getEntityData().get((net.minecraft.network.syncher.EntityDataAccessor) fieldValue(owner, name));
}
static Object call(Object target, Class<?> owner, String name) {
try {
Method m = owner.getDeclaredMethod(name);
m.setAccessible(true);
return m.invoke(target);
} catch (Exception ex) { throw new RuntimeException(ex); }
}
static Object fieldValue(Class<?> owner, String name) {
try {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
return f.get(null);
} catch (Exception ex) { throw new RuntimeException(ex); }
}
static String describe(Entity e, List<Entity> all) {
List<String> t = new ArrayList<>();
t.add(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()).toString());
Entity vehicle = e.getVehicle();
t.add("veh=" + (vehicle == null ? "-" : Integer.toString(all.indexOf(vehicle))));
if (e instanceof AgeableMob a) t.add("age=" + a.getAge());
else if (e instanceof LivingEntity l) t.add("baby=" + l.isBaby());
if (e instanceof LivingEntity l) t.add("hp=" + hex(l.getHealth()));
if (e instanceof Mob m) {
t.add("lh=" + m.isLeftHanded());
t.add("loot=" + m.canPickUpLoot());
t.add("persist=" + m.isPersistenceRequired());
List<String> eq = new ArrayList<>();
for (EquipmentSlot s : SLOTS) {
ItemStack st = m.getItemBySlot(s);
if (!st.isEmpty()) eq.add(s.getSerializedName() + ":" + stack(st));
}
t.add("eq=" + (eq.isEmpty() ? "-" : String.join(";", eq)));
List<String> drops = new ArrayList<>();
for (EquipmentSlot s : SLOTS) {
float d = m.getDropChances().byEquipment(s);
if (d != 0.085F) drops.add(s.getSerializedName() + ":" + hex(d));
}
t.add("drop=" + (drops.isEmpty() ? "-" : String.join(";", drops)));
}
if (e instanceof LivingEntity l) {
List<String> attrs = new ArrayList<>();
for (var a : Lists.ATTRIBUTES) {
AttributeInstance inst = l.getAttribute(a.getValue());
if (inst != null) attrs.add(a.getKey() + ":" + hex(inst.getValue()));
}
t.add("a=" + String.join(",", attrs));
List<String> fx = new ArrayList<>();
for (MobEffectInstance i : l.getActiveEffects()) fx.add(id(i.getEffect()) + ":" + i.getAmplifier() + ":" + i.getDuration());
fx.sort(null);
t.add("fx=" + (fx.isEmpty() ? "-" : String.join(",", fx)));
Brain<?> brain = l.getBrain();
List<String> mem = new ArrayList<>();
for (var m : Lists.MEMORIES) {
if (!brain.hasMemoryValue(m.getValue())) continue;
Object value = brain.getMemory(m.getValue()).orElse(null);
String text = value instanceof GlobalPos g ? g.pos().getX() + "," + g.pos().getY() + "," + g.pos().getZ() : String.valueOf(value);
mem.add(m.getKey() + ":" + text + ":" + brain.getTimeUntilExpiry(m.getValue()));
}
if (!mem.isEmpty()) t.add("mem=" + String.join(",", mem));
}
List<String> v = new ArrayList<>();
variant(e, v);
if (!v.isEmpty()) t.add("v=" + String.join(" ", v).replace(' ', '_'));
return String.join(" ", t);
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = unsafeField.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class);
objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class);
var repo = ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
var layers = RegistryLayer.createRegistryAccess();
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
var loaded = net.minecraft.server.ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags();
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
RegistryAccess access = loaded.layers().compositeAccess();
var biomes = access.lookupOrThrow(Registries.BIOME);
var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE);
var blockLookup = access.lookupOrThrow(Registries.BLOCK);
var structureLookup = access.lookupOrThrow(Registries.STRUCTURE);
var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class);
put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class));
Lvl level = (Lvl) alloc(Lvl.class);
level.fake = server;
put(level, ServerLevel.class, "server", server);
level.registries = access;
// Level.playSound draws a sound seed before the (ignored) seeded sound.
put(level, net.minecraft.world.level.Level.class, "soundSeedGenerator", RandomSource.create(0L));
level.entities = new ArrayList<>();
level.scoreboard = new net.minecraft.server.ServerScoreboard(server);
level.border = new WorldBorder();
level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags());
level.biomeManager = new BiomeManager((x, y, z) -> level.biome, 0L) {
@Override public Holder<Biome> getBiome(BlockPos pos) { return level.biome; }
@Override public Holder<Biome> getBiome(int x, int y, int z) { return level.biome; }
};
Structures structures = (Structures) alloc(Structures.class);
structures.level = level;
level.structures = structures;
wrapFactories();
List<String> lines = Files.readAllLines(Path.of(args[0]));
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
w.println("halloween " + net.minecraft.util.SpecialDates.isHalloween());
for (String raw : lines) {
if (raw.isBlank()) continue;
Map<String, String> c = new LinkedHashMap<>();
for (String token : raw.trim().split("\\s+")) {
int eq = token.indexOf('=');
if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1));
}
try {
level.dimensionKey = ResourceKey.create(Registries.DIMENSION, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld")));
level.dimensionType = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, level.dimensionKey.identifier())).value();
level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains"))));
level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal"));
level.time = Long.parseLong(c.getOrDefault("time", "0"));
level.rules.set(GameRules.SPAWN_MONSTERS, !c.getOrDefault("monsters", "1").equals("0"), null);
int phase = Integer.parseInt(c.getOrDefault("phase", "0"));
level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level)
.addConstantLayer(net.minecraft.world.attribute.EnvironmentAttributeMap.builder()
.set(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, MoonPhase.values()[phase]).build())
.build();
String[] p = c.get("pos").split(",");
double x = Double.parseDouble(p[0]), y = Double.parseDouble(p[1]), z = Double.parseDouble(p[2]);
BlockPos block = BlockPos.containing(x, y, z);
level.floorY = block.getY() - 1;
level.floor = net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup, c.getOrDefault("floor", "minecraft:grass_block"), false).blockState();
level.roofY = c.containsKey("roof") ? block.getY() + Integer.parseInt(c.get("roof")) : Integer.MIN_VALUE;
structures.start = null;
if (c.containsKey("structure")) {
structures.structure = structureLookup.getValue(Identifier.parse(c.get("structure")));
BoundingBox box = new BoundingBox(block.getX() - 8, block.getY() - 8, block.getZ() - 8, block.getX() + 8, block.getY() + 8, block.getZ() + 8);
structures.start = new StructureStart(structures.structure, new ChunkPos(block.getX() >> 4, block.getZ() >> 4), 0,
new PiecesContainer(List.of(new Piece(box))));
}
level.entities.clear();
level.levelRandom = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0")));
put(level, Level.class, "random", level.levelRandom);
created = new ArrayList<>();
entitySeed = Long.parseLong(c.getOrDefault("eseed", "0"));
seeding = true;
// Chickens already standing by (zombie jockeys look for one).
int chickens = Integer.parseInt(c.getOrDefault("chickens", "0"));
for (int i = 0; i < chickens; i++) {
Entity chicken = EntityTypes.CHICKEN.create(level, EntitySpawnReason.LOAD);
chicken.setPos(x + i, y, z);
level.entities.add(chicken);
}
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(c.get("type")));
EntitySpawnReason reason = EntitySpawnReason.valueOf(c.getOrDefault("reason", "NATURAL"));
float moon = DimensionType.MOON_BRIGHTNESS_PER_PHASE[phase];
DifficultyInstance difficulty = new DifficultyInstance(level.difficulty, level.time, Long.parseLong(c.getOrDefault("inhabited", "0")), moon);
int pack = Integer.parseInt(c.getOrDefault("pack", "1"));
SpawnGroupData group = null;
for (int i = 0; i < pack; i++) {
Entity e = type.create(level, reason);
if (e == null) break; // monsters do not exist in peaceful
if (!(e instanceof Mob mob)) throw new IllegalStateException("not a mob");
mob.snapTo(x, y, z, 0.0F, 0.0F);
group = mob.finalizeSpawn(level, difficulty, reason, group);
level.addFreshEntityWithPassengers(mob);
}
seeding = false;
List<String> out = new ArrayList<>();
for (Entity e : created) out.add(describe(e, created));
for (Entity e : created) out.add("rng " + e.getRandom().nextLong());
out.add("next " + level.levelRandom.nextLong());
w.println(c.get("name") + " " + String.join(" | ", out));
} catch (Throwable t) {
seeding = false;
Throwable cause = t;
while ((cause instanceof InvocationTargetException || cause instanceof RuntimeException && cause.getCause() != null) && cause.getCause() != null) cause = cause.getCause();
StringBuilder line = new StringBuilder(c.get("name") + " error " + cause);
if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame);
w.println(line);
}
}
}
System.exit(0);
}
}
@@ -558,6 +558,16 @@ public final class VanillaMobAiOracle {
long at = Long.parseLong(v);
afterAdd.add(() -> mob.getBrain().setMemory(MemoryModuleType.LAST_SLEPT, at));
}
// Warden.finalizeSpawn's own part (Mob.finalizeSpawn draws the level random,
// which is not seeded yet): a minute before digging, or climbing out first.
case "digcooldown", "emerge" -> {
mob.getBrain().setMemoryWithExpiry(MemoryModuleType.DIG_COOLDOWN, net.minecraft.util.Unit.INSTANCE, 1200L);
if (kv[0].equals("emerge")) {
mob.setPose(net.minecraft.world.entity.Pose.EMERGING);
mob.getBrain().setMemoryWithExpiry(MemoryModuleType.IS_EMERGING, net.minecraft.util.Unit.INSTANCE,
net.minecraft.world.entity.monster.warden.WardenAi.EMERGE_DURATION);
}
}
case "inlove" -> ((net.minecraft.world.entity.animal.Animal) mob).setInLoveTime(600);
case "tame" -> { if (mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true); }
case "strength" -> method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class)
@@ -0,0 +1,366 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.client.ClientRecipeBook;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.CycleButton;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.client.gui.components.WidgetSprites;
import net.minecraft.client.gui.components.WidgetTooltipHolder;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner;
import net.minecraft.client.gui.screens.recipebook.*;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.util.Util;
import net.minecraft.util.context.ContextMap;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.inventory.tooltip.TooltipComponent;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeManager;
import net.minecraft.world.item.crafting.display.RecipeDisplayEntry;
import net.minecraft.world.item.crafting.display.RecipeDisplayId;
import net.minecraft.world.item.crafting.display.SlotDisplay;
import net.minecraft.world.item.crafting.display.SlotDisplayContext;
import net.minecraft.world.level.Level;
import org.joml.Matrix3x2fStack;
/**
* Original oracle for the recipe book's drawing (RecipeBookComponent.extractRenderState,
* its tooltips and GhostSlots.extractRenderState): the background, the real
* search EditBox, RecipeBookTabButtons, the craftable filter CycleButton, a
* RecipeBookPage of RecipeButtons over real RecipeCollections with its page
* arrows and number, the OverlayRecipeComponent of a button and ghost slots,
* each built as RecipeBookComponent.initVisuals and RecipeBookPage.init build
* them, with the state the case gives (tab and button animations, the cycling
* index, the search box, the mouse). Every GuiGraphicsExtractor call is recorded
* with its pose. The hovered button's tooltip is recorded as its display stack
* (RecipeButton.getTooltipText adds the item's own tooltip, compared elsewhere).
*/
public final class VanillaRecipeBookScreenOracle {
static Object unsafe;
static Method allocate;
@SuppressWarnings("unchecked")
static <T> T alloc(Class<T> type) throws Exception {
return (T) allocate.invoke(unsafe, type);
}
static Field field(Class<?> owner, String name) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
return f;
}
static void put(Object target, Class<?> owner, String name, Object value) throws Exception {
Field f = owner.getDeclaredField(name);
long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
Class<?> t = f.getType();
String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" : t == long.class ? "putLong" : "putObject";
Class<?> param = t.isPrimitive() ? t : Object.class;
unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value);
}
static float round(float v) { return Math.round(v * 1e4f) / 1e4f; }
/** A text's styled runs: [text, rgb or -1, italic]. */
static JsonArray runs(FormattedCharSequence s) {
var out = new JsonArray();
StringBuilder text = new StringBuilder();
int[] style = {Integer.MIN_VALUE, 0};
s.accept((i, st, cp) -> {
int color = st.getColor() == null ? -1 : st.getColor().getValue();
int italic = st.isItalic() ? 1 : 0;
if (text.length() > 0 && (color != style[0] || italic != style[1])) {
var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r);
text.setLength(0);
}
style[0] = color; style[1] = italic;
text.appendCodePoint(cp);
return true;
});
if (text.length() > 0) {
var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r);
}
return out;
}
static String id(ItemStack s) { return s.isEmpty() ? "minecraft:air" : s.getItem().builtInRegistryHolder().key().identifier().toString(); }
/** Records every GuiGraphicsExtractor call with the pose it was made under. */
public static final class Capture extends GuiGraphicsExtractor {
JsonArray draws = new JsonArray();
Matrix3x2fStack stack = new Matrix3x2fStack(16);
private Capture() { super(null, null, 0, 0); }
@Override public Matrix3x2fStack pose() { return stack; }
@Override public void nextStratum() { add("stratum"); }
@Override public void requestCursor(com.mojang.blaze3d.platform.cursor.CursorType type) { }
@Override public boolean containsPointInScissor(int x, int y) { return true; }
JsonObject add(String type) {
var o = new JsonObject();
o.addProperty("t", type);
var m = new JsonArray();
for (float v : new float[] {stack.m00(), stack.m01(), stack.m10(), stack.m11(), stack.m20(), stack.m21()}) m.add(round(v));
o.add("m", m);
draws.add(o);
return o;
}
@Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) {
var o = add("fill");
o.addProperty("x0", Math.min(x0, x1)); o.addProperty("y0", Math.min(y0, y1));
o.addProperty("x1", Math.max(x0, x1)); o.addProperty("y1", Math.max(y0, y1));
o.addProperty("color", color);
}
@Override public void textHighlight(int x0, int y0, int x1, int y1, boolean invert) {
var o = add("highlight");
o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1);
}
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) {
var o = add("sprite");
o.addProperty("id", id.getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
}
@Override public void blit(RenderPipeline p, Identifier texture, int x, int y, float u, float v, int w, int h, int srcW, int srcH, int texW, int texH, int color) {
var o = add("blit");
o.addProperty("texture", texture.getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
o.addProperty("u", u); o.addProperty("v", v); o.addProperty("tw", texW); o.addProperty("th", texH);
}
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
var o = add("text");
o.add("runs", runs(str));
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow);
}
@Override public void text(Font font, String str, int x, int y, int color, boolean shadow) {
if (str != null) text(font, FormattedCharSequence.forward(str, net.minecraft.network.chat.Style.EMPTY), x, y, color, shadow);
}
void item(String kind, ItemStack s, int x, int y) {
if (s.isEmpty()) return;
var o = add(kind);
o.addProperty("id", id(s)); o.addProperty("count", s.getCount());
o.addProperty("x", x); o.addProperty("y", y);
}
@Override public void item(ItemStack s, int x, int y) { item("item", s, x, y); }
@Override public void item(ItemStack s, int x, int y, int seed) { item("item", s, x, y); }
@Override public void fakeItem(ItemStack s, int x, int y) { item("fake", s, x, y); }
@Override public void fakeItem(ItemStack s, int x, int y, int seed) { item("fake", s, x, y); }
@Override public void itemDecorations(Font font, ItemStack s, int x, int y, String count) { item("decorations", s, x, y); }
@Override public void setTooltipForNextFrame(Font font, List<FormattedCharSequence> lines, Optional<TooltipComponent> image,
ClientTooltipPositioner positioner, int x, int y, boolean replace, Identifier style) {
var o = add("tooltip");
var a = new JsonArray();
for (var l : lines) a.add(runs(l));
o.add("lines", a);
}
}
/** The window's text input area, which a focused EditBox moves: not tracked here. */
static final class NoTextInput extends com.mojang.blaze3d.platform.TextInputManager {
NoTextInput() { super(null); }
@Override public void setTextInputArea(int x0, int y0, int x1, int y1) { }
}
static List<RecipeDisplayEntry> displays(RecipeManager recipes, String id) {
List<RecipeDisplayEntry> out = new ArrayList<>();
recipes.listDisplaysForRecipe(ResourceKey.create(Registries.RECIPE, Identifier.parse(id)), out::add);
return out;
}
/** A collection of the given recipes' displays; `craftable` lists the recipes the inventory can craft. */
@SuppressWarnings("unchecked")
static RecipeCollection collection(RecipeManager recipes, JsonObject b) throws Exception {
List<RecipeDisplayEntry> entries = new ArrayList<>();
Set<RecipeDisplayId> craftable = (Set<RecipeDisplayId>) new HashSet<RecipeDisplayId>();
for (var r : b.getAsJsonArray("recipes")) {
var a = r.getAsJsonArray();
for (var e : displays(recipes, a.get(0).getAsString())) {
entries.add(e);
if (a.get(1).getAsBoolean()) craftable.add(e.id());
}
}
var c = new RecipeCollection(entries);
((Set<RecipeDisplayId>) field(RecipeCollection.class, "selected").get(c)).addAll(entries.stream().map(RecipeDisplayEntry::id).toList());
((Set<RecipeDisplayId>) field(RecipeCollection.class, "craftable").get(c)).addAll(craftable);
return c;
}
/** The widget's tooltip shows on this frame when hovered (its delay has passed). */
static void settled(Object widget) throws Exception {
var holder = (WidgetTooltipHolder) field(net.minecraft.client.gui.components.AbstractWidget.class, "tooltip").get(widget);
put(holder, WidgetTooltipHolder.class, "wasDisplayed", true);
put(holder, WidgetTooltipHolder.class, "displayStartTime", Util.getMillis() - 1000L);
}
static JsonArray run(JsonObject c, Minecraft mc, RecipeManager recipes) throws Exception {
var g = alloc(Capture.class);
g.draws = new JsonArray();
g.stack = new Matrix3x2fStack(16);
String type = c.get("type").getAsString();
boolean furnace = !type.equals("crafting");
int width = c.get("width").getAsInt(), height = c.get("height").getAsInt();
int xOffset = c.get("narrow").getAsBoolean() ? 0 : 86;
int xo = (width - 147) / 2 - xOffset, yo = (height - 166) / 2;
int mx = c.getAsJsonArray("mouse").get(0).getAsInt(), my = c.getAsJsonArray("mouse").get(1).getAsInt();
int index = c.get("index").getAsInt();
SlotSelectTime time = () -> index;
boolean filtering = c.get("filtering").getAsBoolean();
// RecipeBookComponent.extractRenderState.
g.blit(RenderPipelines.GUI_TEXTURED, (Identifier) field(RecipeBookComponent.class, "RECIPE_BOOK_LOCATION").get(null), xo, yo, 1.0F, 1.0F, 147, 166, 256, 256);
var s = c.getAsJsonObject("search");
var search = new EditBox(mc.font, xo + 25, yo + 13, 81, 9 + 5, Component.translatable("itemGroup.search"));
search.setMaxLength(50);
search.setVisible(true);
search.setTextColor(-1);
search.setValue(s.get("value").getAsString());
search.setHint((Component) field(RecipeBookComponent.class, "SEARCH_HINT").get(null));
put(search, net.minecraft.client.gui.components.AbstractWidget.class, "focused", s.get("focused").getAsBoolean());
put(search, EditBox.class, "displayPos", s.get("display").getAsInt());
put(search, EditBox.class, "cursorPos", s.get("cursor").getAsInt());
put(search, EditBox.class, "highlightPos", s.get("highlight").getAsInt());
put(search, EditBox.class, "focusedTime", Util.getMillis() - s.get("blink").getAsLong());
search.extractRenderState(g, mx, my, 1.0F);
Class<?> tabOwner = switch (type) {
case "crafting" -> CraftingRecipeBookComponent.class;
case "furnace" -> net.minecraft.client.gui.screens.inventory.FurnaceScreen.class;
case "blast_furnace" -> net.minecraft.client.gui.screens.inventory.BlastFurnaceScreen.class;
default -> net.minecraft.client.gui.screens.inventory.SmokerScreen.class;
};
@SuppressWarnings("unchecked")
var infos = (List<RecipeBookComponent.TabInfo>) field(tabOwner, "TABS").get(null);
// updateTabs: the visible tabs in order.
int n = 0;
for (var t : c.getAsJsonArray("tabs")) {
var tab = t.getAsJsonObject();
var button = new RecipeBookTabButton(0, 0, infos.get(tab.get("tab").getAsInt()), b -> {});
button.setPosition((width - 147) / 2 - xOffset - 30, (height - 166) / 2 + 3 + 27 * n++);
if (tab.get("selected").getAsBoolean()) button.select();
put(button, RecipeBookTabButton.class, "animationTime", tab.get("anim").getAsFloat());
button.extractRenderState(g, mx, my, 1.0F);
}
RecipeBookComponent<?> component = furnace ? alloc(FurnaceRecipeBookComponent.class) : alloc(CraftingRecipeBookComponent.class);
Method name = RecipeBookComponent.class.getDeclaredMethod("getRecipeFilterName");
name.setAccessible(true);
Method sprites = RecipeBookComponent.class.getDeclaredMethod("getFilterButtonTextures");
sprites.setAccessible(true);
if (furnace) put(component, FurnaceRecipeBookComponent.class, "recipeFilterName", Component.translatable(switch (type) {
case "furnace" -> "gui.recipebook.toggleRecipes.smeltable";
case "blast_furnace" -> "gui.recipebook.toggleRecipes.blastable";
default -> "gui.recipebook.toggleRecipes.smokable";
}));
Component filterName = (Component) name.invoke(component);
WidgetSprites filterSprites = (WidgetSprites) sprites.invoke(component);
Component all = (Component) field(RecipeBookComponent.class, "ALL_RECIPES_TOOLTIP").get(null);
var filter = CycleButton.booleanBuilder(filterName, all, filtering)
.withTooltip(f -> f ? Tooltip.create(filterName) : Tooltip.create(all))
.withSprite((b, f) -> filterSprites.get(f, b.isHoveredOrFocused()))
.displayState(CycleButton.DisplayState.HIDE)
.create(xo + 110, yo + 12, 26, 16, CommonComponents.EMPTY, (b, v) -> {});
settled(filter);
filter.extractRenderState(g, mx, my, 1.0F);
// RecipeBookPage.init and updateCollections.
var page = new RecipeBookPage(null, time, furnace);
page.init(mc, xo, yo);
List<RecipeCollection> collections = new ArrayList<>();
for (var b : c.getAsJsonArray("collections")) collections.add(collection(recipes, b.getAsJsonObject()));
put(page, RecipeBookPage.class, "currentPage", c.get("page").getAsInt());
page.updateCollections(collections, false, filtering);
@SuppressWarnings("unchecked")
var buttons = (List<RecipeButton>) field(RecipeBookPage.class, "buttons").get(page);
var anims = c.getAsJsonArray("buttonAnims");
for (int i = 0; i < anims.size(); i++) put(buttons.get(i), RecipeButton.class, "animationTime", anims.get(i).getAsFloat());
for (String arrow : new String[] {"forwardButton", "backButton"}) settled(field(RecipeBookPage.class, arrow).get(page));
var overlay = (OverlayRecipeComponent) field(RecipeBookPage.class, "overlay").get(page);
if (c.has("overlay")) {
// RecipeBookPage.mouseClicked: right click on a button.
var button = buttons.get(c.get("overlay").getAsInt());
ContextMap context = SlotDisplayContext.fromLevel(mc.level);
overlay.init(button.getCollection(), context, filtering, button.getX(), button.getY(), xo + 147 / 2, yo + 13 + 166 / 2, button.getWidth());
}
page.extractRenderState(g, xo, yo, mx, my, 1.0F);
// RecipeBookPage.extractTooltip.
var hovered = (RecipeButton) field(RecipeBookPage.class, "hoveredButton").get(page);
if (hovered != null && !overlay.isVisible()) {
var o = g.add("item_tooltip");
o.addProperty("id", id(hovered.getDisplayStack()));
o.addProperty("more", !hovered.isOnlyOption());
}
// GhostSlots.extractRenderState.
if (c.has("ghost")) {
var ghost = new GhostSlots(time);
ContextMap context = SlotDisplayContext.fromLevel(mc.level);
var container = new SimpleContainer(16);
int i = 0;
for (var e : c.getAsJsonArray("ghost")) {
var gs = e.getAsJsonObject();
var slot = new Slot(container, i++, gs.get("x").getAsInt(), gs.get("y").getAsInt());
List<SlotDisplay> items = new ArrayList<>();
for (var it : gs.getAsJsonArray("items")) items.add(new SlotDisplay.ItemStackSlotDisplay(new net.minecraft.world.item.ItemStackTemplate(net.minecraft.core.registries.BuiltInRegistries.ITEM.getValue(Identifier.parse(it.getAsString())))));
SlotDisplay display = new SlotDisplay.Composite(items);
Method set = GhostSlots.class.getDeclaredMethod(gs.get("result").getAsBoolean() ? "setResult" : "setInput", Slot.class, ContextMap.class, SlotDisplay.class);
set.setAccessible(true);
set.invoke(ghost, slot, context, display);
}
g.pose().pushMatrix();
g.pose().translate(c.get("left").getAsInt(), c.get("top").getAsInt());
ghost.extractRenderState(g, mc, c.get("big").getAsBoolean());
g.pose().popMatrix();
}
return g.draws;
}
public static void main(String[] args) throws Exception {
ParityData.init();
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = unsafeField.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
RecipeManager recipes = new RecipeManager(ParityData.lookup);
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
// A stand-in client: its font, a level for the slot display context, a player's book.
Minecraft mc = alloc(Minecraft.class);
put(mc, Minecraft.class, "font", ParityFont.create(ParityFont.resources()));
var level = alloc(ClientLevel.class);
put(level, Level.class, "registryAccess", ParityData.access);
put(mc, Minecraft.class, "level", level);
var player = alloc(LocalPlayer.class);
put(player, LocalPlayer.class, "recipeBook", new ClientRecipeBook());
put(mc, Minecraft.class, "player", player);
put(mc, Minecraft.class, "lastInputType", net.minecraft.client.InputType.MOUSE);
put(mc, Minecraft.class, "textInputManager", new NoTextInput());
field(Minecraft.class, "instance").set(null, mc);
var gson = new Gson();
var out = new StringBuilder();
for (String line : Files.readAllLines(Path.of(args[0]))) {
if (line.isBlank()) continue;
var c = JsonParser.parseString(line).getAsJsonObject();
var result = new JsonObject();
try {
result.add("draws", run(c, mc, recipes));
} catch (Throwable error) {
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
var sw = new java.io.StringWriter();
cause.printStackTrace(new java.io.PrintWriter(sw));
result.addProperty("error", sw.toString().lines().limit(8).reduce("", (a, b) -> a + b + " | "));
}
out.append(gson.toJson(result)).append('\n');
}
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
}
}
@@ -269,6 +269,32 @@ public final class VanillaSculkOracle {
static Object get(Object o, String name) throws Exception { return field(o.getClass(), name).get(o); }
/**
* A mob's own random, its sensors' first delays and its gates' shuffles (RunOne's ShufflingList)
* are unseeded: seed what appeared, as Horizon does.
*/
static void seedFresh(Mob mob, long seed) throws Exception {
mob.getRandom().setSeed(seed);
@SuppressWarnings("unchecked")
Map<Object, net.minecraft.world.entity.ai.sensing.Sensor<?>> sensors =
(Map<Object, net.minecraft.world.entity.ai.sensing.Sensor<?>>) get(mob.getBrain(), "sensors");
for (var sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
@SuppressWarnings("unchecked")
Map<Integer, Map<?, Set<net.minecraft.world.entity.ai.behavior.BehaviorControl<?>>>> byPriority =
(Map<Integer, Map<?, Set<net.minecraft.world.entity.ai.behavior.BehaviorControl<?>>>>) get(mob.getBrain(), "availableBehaviorsByPriority");
for (var byActivity : byPriority.values())
for (var behaviors : byActivity.values())
for (var behavior : behaviors) seedGate(behavior, seed);
}
static void seedGate(Object behavior, long seed) throws Exception {
if (!(behavior instanceof net.minecraft.world.entity.ai.behavior.GateBehavior<?>)) return;
var list = (net.minecraft.world.entity.ai.behavior.ShufflingList<?>)
field(net.minecraft.world.entity.ai.behavior.GateBehavior.class, "behaviors").get(behavior);
field(net.minecraft.world.entity.ai.behavior.ShufflingList.class, "random").set(list, new LegacyRandomSource(seed));
for (Object child : list) seedGate(child, seed);
}
static long seedOf(Object random) throws Exception {
return ((java.util.concurrent.atomic.AtomicLong) field(LegacyRandomSource.class, "seed").get(random)).get();
}
@@ -538,6 +564,7 @@ public final class VanillaSculkOracle {
Method managerTick = method(manager.getClass(), "tick");
managerTick.invoke(manager);
Set<Entity> known = new HashSet<>();
Set<Entity> seeded = new HashSet<>();
for (Entity e : allEntities(level)) known.add(e);
if (System.getenv("SCULK_TRACE") != null) field(Level.class, "random").set(level, new TracingRandom(0L));
level.getRandom().setSeed(s.levelSeed);
@@ -563,6 +590,13 @@ public final class VanillaSculkOracle {
});
runBlockEvents.invoke(level);
for (Action a : s.actions) if (a.tick == t) act(level, a.words, mobs);
// Mobs that appeared during the block ticks (a summoned warden) tick in this
// tick's entity phase: seed them now, as they are seeded below.
List<Entity> born = new ArrayList<>();
for (Entity e : allEntities(level)) if (!known.contains(e)) born.add(e);
born.sort(Comparator.comparingInt(Entity::getId));
for (int i = 0; i < born.size(); i++)
if (born.get(i) instanceof Mob mob && seeded.add(mob)) seedFresh(mob, 0x5eedL + names.size() + i + 1);
// The player first (it joined first): only its warden spawn tracker.
player.getWardenSpawnTracker().tick();
tickList.forEach(e -> {
@@ -611,13 +645,7 @@ public final class VanillaSculkOracle {
known.add(e);
names.put(e, "n" + names.size());
// An entity's own random is unseeded: seed what appeared, as Horizon does.
if (e instanceof Mob mob) {
mob.getRandom().setSeed(0x5eedL + names.size());
@SuppressWarnings("unchecked")
Map<Object, net.minecraft.world.entity.ai.sensing.Sensor<?>> sensors =
(Map<Object, net.minecraft.world.entity.ai.sensing.Sensor<?>>) get(mob.getBrain(), "sensors");
for (var sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
}
if (e instanceof Mob mob && seeded.add(mob)) seedFresh(mob, 0x5eedL + names.size());
if (e instanceof net.minecraft.world.entity.ExperienceOrb orb) {
// Where an orb flies comes from its own unseeded random: its value only.
lines.add("new minecraft:experience_orb value=" + orb.getValue());
+16 -1
View File
@@ -4,7 +4,7 @@
The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla
block entity (chest, trapped/copper chest and the other half of a double chest,
ender chest, enchanting table, shulker box, bell, conduit, dragon/piglin head,
decorated pot)
decorated pot, End gateway with the integrated server's copy ticking beside it)
on a stand-in client level, then per scripted step applies the block event
(triggerEvent), runs the entity's own client ticker and the renderer's
extractRenderState, printing the fields, the level calls the tick made
@@ -162,6 +162,21 @@ def cases():
step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])]
steps.append(step)
add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps)
# End gateways: the server copy's portalTick (triggerCooldown every 2400
# ticks, entities entering) sends block event 1 to the client copy, whose
# beamAnimationTick and TheEndGatewayRenderer draw the beam; saved ages
# from new to long settled, both level heights.
for i in range(40):
age = rng.choice([0, 0, 150, 2390, 4790, rng.randint(200, 10 ** 6), 2399 + 2400 * rng.randint(1, 50)])
steps = []
for t in times(rng.randint(20, 90), gaps=(1, 1, 1, 2)):
step = {'time': t, 'partial': round(rng.random(), 4)}
if rng.random() < 0.06:
step['enter'] = True
if rng.random() < 0.04:
step['event'] = [rng.choice([1, 2, 0]), rng.choice([0, 3])]
steps.append(step)
add('gateway', 'minecraft:end_gateway', steps, age=age, level=rng.choice([[0, 256], [-64, 384]]))
# Chests and ender chests: open counts from block event 1 (both halves of
# a double chest), other events ignored; the neighbour a double half
# connects to may be its other half or not (wrong block, type, facing).
+21 -5
View File
@@ -72,6 +72,11 @@ def cases():
add(f'minecraft:{color}_wall_banner[facing={f}]',
patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(rng.randint(0, 2))])
add('minecraft:blue_banner[rotation=2]', patterns=[[rng.choice(patterns), rng.choice(DYES)] for _ in range(17)])
# The loom's result preview (GuiBannerResultRenderer in a 20x40 picture in
# picture, lit with Lighting.Entry.ITEMS_FLAT): up to the loom's six layers, and 17.
for n in [0, 1, 2, 3, 6, 6, 17]:
out.append({'block': 'loom_result', 'loom': {'base': rng.choice(DYES),
'patterns': [[rng.choice(patterns), rng.choice(DYES)] for _ in range(n)]}})
for skull in ['skeleton_skull', 'wither_skeleton_skull', 'zombie_head', 'creeper_head', 'dragon_head',
'piglin_head', 'player_head']:
wall = skull.replace('_skull', '_wall_skull').replace('_head', '_wall_head')
@@ -147,15 +152,26 @@ def lights():
return norm([0.2, 1.0, -0.7]), norm([-0.2, 1.0, 0.7])
def items_flat_lights():
"""Lighting.Entry.ITEMS_FLAT: rotationY(-PI/8).rotateX(3PI/4) of the diffuse lights."""
def rotate(v):
a, b = -math.pi / 8, math.pi * 3 / 4
x, y, z = v
y, z = y * math.cos(b) - z * math.sin(b), y * math.sin(b) + z * math.cos(b)
return [x * math.cos(a) + z * math.sin(a), y, -x * math.sin(a) + z * math.cos(a)]
return tuple(rotate(l) for l in lights())
L0, L1 = lights()
FLAT = items_flat_lights()
def mix(normal):
def mix(normal, lit=(L0, L1)):
d = lambda l: max(0.0, sum(a * b for a, b in zip(l, normal)))
return min(1.0, (d(L0) + d(L1)) * 0.6 + 0.4)
return min(1.0, (d(lit[0]) + d(lit[1])) * 0.6 + 0.4)
def vanilla_quads(submits):
def vanilla_quads(submits, lit=(L0, L1)):
quads, other = [], []
for s in submits:
custom = s['type'] == 'submitCustomGeometry'
@@ -167,7 +183,7 @@ def vanilla_quads(submits):
q = verts[i:i + 4]
tint = q[0][3] & 0xFFFFFFFF
# Custom geometry (beacon beams) is unlit; models get the entity shader's mix light.
b = 1.0 if custom else mix(q[0][8:11])
b = 1.0 if custom else mix(q[0][8:11], lit)
ch = lambda shift: int(((tint >> shift) & 255) * b)
quads.append({'texture': s['texture'], 'v': [v[:3] + v[4:6] for v in q],
'rgb': [ch(16), ch(8), ch(0)], 'alpha': tint >> 24, 'light': q[0][7],
@@ -206,7 +222,7 @@ def pair(vq, rq):
def compare_case(v, r, tol):
problems = []
vq, other = vanilla_quads(v['submits'])
vq, other = vanilla_quads(v['submits'], FLAT if 'loom' in v['case'] else (L0, L1))
for s in other:
if s['type'] == 'submitText':
continue
+177
View File
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
"""Compare Mob.finalizeSpawn (spawned mob gear, enchantments and state) with vanilla.
Java (VanillaFinalizeSpawnOracle) creates each case's mobs on a stand-in
ServerLevel and runs vanilla's finalizeSpawn with a seeded level random (what
finalizeSpawn reads through level.getRandom()) and seeded entity randoms; Rust
(finalize_spawn_fixture) runs horizon_client::mobs::finalize on the same case.
Cases cover every mob type, every spawn reason, peaceful to hard, game times,
inhabited times and moon phases (the local difficulty and its special
multiplier), packs sharing group data, biomes (variants, villager types,
sheep colours, rabbit and fox types), structures (black cats), roofs (camel
husk room) and chickens standing by (zombie jockeys).
Each entity created in a case, the mobs and the jockeys finalizeSpawn makes,
is compared: equipment with its enchantments, drop chances, CanPickUpLoot,
LeftHanded, persistence, age, health, attribute values, effects, variants,
the memories finalizeSpawn sets and the vehicle it rides; then the next draw
of every entity random and of the level random, which pins every draw in
between.
"""
import argparse
import json
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
REASONS = ['NATURAL', 'CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'BREEDING', 'MOB_SUMMONED', 'JOCKEY', 'EVENT',
'CONVERSION', 'REINFORCEMENT', 'TRIGGERED', 'BUCKET', 'SPAWN_ITEM_USE', 'COMMAND', 'DISPENSER', 'PATROL',
'TRIAL_SPAWNER', 'LOAD', 'DIMENSION_TRAVEL']
# Mobs whose finalizeSpawn draws, by how often the corpus picks them.
GEARED = ['zombie', 'husk', 'drowned', 'zombie_villager', 'zombified_piglin', 'skeleton', 'stray', 'bogged', 'parched',
'wither_skeleton', 'pillager', 'vindicator', 'piglin', 'piglin_brute', 'vex', 'fox', 'spider', 'illusioner',
'evoker', 'ravager', 'witch']
OTHERS = ['pig', 'cow', 'mooshroom', 'sheep', 'chicken', 'rabbit', 'horse', 'donkey', 'mule', 'llama', 'trader_llama',
'goat', 'panda', 'polar_bear', 'wolf', 'cat', 'ocelot', 'parrot', 'bee', 'turtle', 'armadillo', 'frog',
'axolotl', 'squid', 'glow_squid', 'cod', 'salmon', 'tropical_fish', 'pufferfish', 'dolphin', 'bat', 'villager',
'wandering_trader', 'iron_golem', 'snow_golem', 'creeper', 'cave_spider', 'enderman', 'endermite',
'silverfish', 'slime', 'magma_cube', 'phantom', 'hoglin', 'zoglin', 'ghast', 'blaze', 'strider', 'guardian',
'elder_guardian', 'shulker', 'camel', 'allay', 'breeze', 'sniffer', 'happy_ghast', 'warden', 'creaking',
'camel_husk', 'nautilus', 'zombie_nautilus', 'sulfur_cube', 'zombie_horse', 'skeleton_horse', 'tadpole',
'giant', 'wither']
BIOMES = ['minecraft:plains', 'minecraft:desert', 'minecraft:snowy_plains', 'minecraft:snowy_taiga', 'minecraft:taiga',
'minecraft:jungle', 'minecraft:bamboo_jungle', 'minecraft:swamp', 'minecraft:mangrove_swamp',
'minecraft:savanna', 'minecraft:badlands', 'minecraft:forest', 'minecraft:grove', 'minecraft:old_growth_pine_taiga',
'minecraft:old_growth_spruce_taiga', 'minecraft:sparse_jungle', 'minecraft:windswept_savanna',
'minecraft:mushroom_fields', 'minecraft:river', 'minecraft:frozen_river', 'minecraft:ocean',
'minecraft:warm_ocean', 'minecraft:lukewarm_ocean', 'minecraft:cold_ocean', 'minecraft:frozen_ocean',
'minecraft:ice_spikes', 'minecraft:cherry_grove', 'minecraft:pale_garden', 'minecraft:dripstone_caves',
'minecraft:lush_caves', 'minecraft:deep_dark', 'minecraft:nether_wastes', 'minecraft:crimson_forest',
'minecraft:soul_sand_valley', 'minecraft:the_end', 'minecraft:snowy_slopes', 'minecraft:frozen_peaks',
'minecraft:wooded_badlands', 'minecraft:beach', 'minecraft:snowy_beach', 'minecraft:meadow',
'minecraft:sulfur_caves']
STRUCTURES = ['minecraft:swamp_hut', 'minecraft:village_plains', 'minecraft:pillager_outpost', 'minecraft:fortress',
'minecraft:trial_chambers']
FLOORS = ['minecraft:grass_block', 'minecraft:sand', 'minecraft:stone', 'minecraft:snow_block', 'minecraft:netherrack']
def dimension(biome):
if biome in ('minecraft:nether_wastes', 'minecraft:crimson_forest', 'minecraft:soul_sand_valley'):
return 'minecraft:the_nether'
if biome == 'minecraft:the_end':
return 'minecraft:the_end'
return 'minecraft:overworld'
def corpus():
rng = random.Random(0x46494E414C)
cases = []
for k in range(int(os.environ.get('FINALIZE_SPAWN_CASES', '24000'))):
kind = rng.choice(GEARED) if rng.random() < 0.55 else rng.choice(OTHERS)
reason = rng.choice(['NATURAL'] * 10 + ['CHUNK_GENERATION', 'SPAWNER', 'STRUCTURE', 'COMMAND', 'SPAWN_ITEM_USE',
'TRIAL_SPAWNER', 'PATROL', 'EVENT', 'JOCKEY'] * 2 + REASONS)
biome = rng.choice(BIOMES)
kv = {
'type': f'minecraft:{kind}',
'reason': reason,
'difficulty': rng.choice(['hard', 'hard', 'normal', 'normal', 'easy', 'peaceful']),
'time': rng.choice([0, 0, 50000, 72000, 400000, 800000, 1512000, 3000000, rng.randrange(0, 4000000)]),
'inhabited': rng.choice([0, 0, 0, 100000, 1000000, 3600000, 5000000, rng.randrange(0, 4000000)]),
'phase': rng.randrange(8),
'seed': rng.randrange(-2**63, 2**63),
'eseed': rng.randrange(-2**47, 2**47),
'pack': rng.choice([1, 1, 1, 2, 3, 4, 6]),
'pos': f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.25, 0.0]):.2f},{rng.randrange(-30, 120)},'
f'{rng.randrange(-200, 200) + rng.choice([0.5, 0.75, 0.0]):.2f}',
'biome': biome,
'dim': dimension(biome),
'floor': rng.choice(FLOORS),
}
if rng.random() < 0.15:
kv['structure'] = rng.choice(STRUCTURES)
if rng.random() < 0.2:
kv['roof'] = rng.choice([1, 2, 3])
if rng.random() < 0.15:
kv['chickens'] = rng.choice([1, 2])
if rng.random() < 0.05:
kv['monsters'] = 0
cases.append(f'case/{k} ' + ' '.join(f'{a}={b}' for a, b in kv.items()))
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
parser.add_argument('--java-only', action='store_true', help='run the oracle and stop')
args = parser.parse_args()
build = lab.LOCAL / 'rust-finalize-spawn-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFinalizeSpawnOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/finalize_spawn_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs']
tested = base.source_hashes([s for s in sources if s.exists()])
inputs = build / 'inputs.txt'
cases = corpus()
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
path = build / (name + '.log')
with path.open('w', encoding='utf-8') as log:
try:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
log.flush()
raise SystemExit(f'{name} failed:\n' + path.read_text(errors='replace')[-4000:])
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaFinalizeSpawnOracle', inputs, build / 'server.txt'], 'server')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
if args.java_only:
print(f'{len(vanilla)} oracle lines')
return
halloween = vanilla[0].split()[1]
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'finalize_spawn_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/finalize_spawn_fixture'
run([binary, resources, inputs, build / 'rust.txt', halloween], 'rust')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
if bad or len(vanilla) != len(rust):
report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12])
raise SystemExit(f'{len(bad)} of {len(vanilla)} lines differ (rust {len(rust)} lines):\n{report}')
base.ensure_sources_unchanged([s for s in sources if s.exists()], tested)
entities = sum(line.count(' | ') for line in vanilla) // 2
enchanted = sum(line.count('[minecraft:') for line in vanilla)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'entities': entities, 'enchanted_items': enchanted, 'sources_sha256': tested,
'scope': 'Mob.finalizeSpawn for every mob type and spawn reason: populateDefaultEquipmentSlots, '
'populateDefaultEquipmentEnchantments through the mob_spawn_equipment and pillager_spawn_crossbow '
'providers, drop chances, CanPickUpLoot, LeftHanded, the follow range spawn bonus, babies and '
'group data, jockeys (chicken, spider, strider, zombie horse, camel husk, zombie nautilus), '
'variants and sound variants, zombie attributes, spider effects, patrol leaders, villager types, '
'cube sizes, horse and llama attributes and the memories finalizeSpawn sets, with every draw of the '
'level random and of the entities\' own randoms.'})
print(f'{len(cases):,} finalizeSpawn cases match vanilla ({entities:,} entities, {enchanted:,} enchanted items)')
if __name__ == '__main__':
main()
+12
View File
@@ -77,6 +77,18 @@ def scenarios():
'player 12.5 -60 0.5',
'mob minecraft:villager 0.5 -60 0.5 0 51 persistent',
])
# The warden: idle, sniffing out a player, roaring and fighting (WardenAi).
# Without finalizeSpawn's dig cooldown a warden digs straight back down. warden_player
# and warden_cow stop before the first blow kills the player or the cow (the probe has no dying
# player, nor the attack knockback attribute or a target killed within the attacker's tick).
add('warden_digs', 140, ['mob minecraft:warden 0.5 -60 0.5 0 60'])
add('warden_alone', 400, ['mob minecraft:warden 0.5 -60 0.5 0 61 digcooldown'])
add('warden_player', 565, ['player 5.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 62 digcooldown'])
add('warden_player_far', 600, ['player 14.5 -60 3.5', 'mob minecraft:warden 0.5 -60 0.5 90 63 digcooldown'])
add('warden_creative', 300, ['player 4.5 -60 0.5 creative', 'mob minecraft:warden 0.5 -60 0.5 0 64 digcooldown'])
add('warden_persistent', 400, ['player 7.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 65 persistent digcooldown'])
add('warden_emerging', 300, ['player 6.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 66 emerge'])
add('warden_cow', 176, ['mob minecraft:warden 0.5 -60 0.5 0 67 digcooldown', 'mob minecraft:cow 4.5 -60 0.5 0 68 persistent'])
# Two villagers gossip (TradeWithVillager): what one heard of the player
# passes to the other, weakened, once in 1200 ticks; idle and at the bell.
gossips = ('gossip=player:minor_negative:100 gossip=player:major_positive:15 '
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Compare the recipe book's drawing with the vanilla client's.
Each case opens a book type (the inventory's or a crafting table's crafting
book, the furnace, blast furnace or smoker) at a GUI size, with its visible
tabs (one selected, some in their new-recipe squeeze), the search box (text,
cursor, selection, focus and cursor blink), the craftable filter, a page of
recipe collections (real recipes, some craftable, some buttons squeezing),
the alternatives overlay of one button, ghost slots, the cycling index and
the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's
widgets for that state as RecipeBookComponent.initVisuals and
RecipeBookPage.init do and records every GuiGraphicsExtractor call of their
extractRenderState, the tooltips and GhostSlots.extractRenderState, with its
pose; examples/recipe_book_render_fixture lays out the same state with
horizon_client::recipe_book_screen, which the game paints. The call lists
must agree.
"""
import argparse
import json
import os
import random
import subprocess
import sys
try:
from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base
except ImportError:
import interaction_lab as lib
import test_model_baking_parity as baking
import test_rust_parity as base
TABS = {'crafting': 5, 'furnace': 4, 'blast_furnace': 3, 'smoker': 2}
TYPES = {'crafting': ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless'), 'furnace': ('minecraft:smelting',),
'blast_furnace': ('minecraft:blasting',), 'smoker': ('minecraft:smoking',)}
WORDS = ['', '', 'a', 'stone', 'iron ingot', 'oak', 'zzz', 'red', 'a very long search text that overflows']
def recipes_by_type():
out = {k: [] for k in TYPES}
for path in sorted((lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')):
kind = json.loads(path.read_text()).get('type')
for k, types in TYPES.items():
if kind in types:
out[k].append('minecraft:' + path.stem)
return out
def cases(count, seed):
rng = random.Random(seed)
by_type = recipes_by_type()
items = sorted(i for i in json.loads((lib.RESOURCES / 'items.json').read_text()) if i != 'minecraft:air')
out = []
for n in range(count):
kind = ['crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'][n % 5]
width, height = rng.choice([(427, 240), (480, 270), (640, 360), (320, 240), (378, 260), (854, 480)])
narrow = width < 379
xo = (width - 147) // 2 - (0 if narrow else 86)
yo = (height - 166) // 2
tabs = [0] + sorted(rng.sample(range(1, TABS[kind]), rng.randint(0, TABS[kind] - 1)))
selected = rng.choice(tabs)
tab_list = [{'tab': t, 'selected': t == selected, 'anim': rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)])}
for t in tabs]
total = rng.choice([0, 1, 5, 19, 20, 21, 47, 80])
pages = (total + 19) // 20
page = rng.randrange(pages) if pages else 0
filtering = rng.random() < 0.4
collections = []
for _ in range(total):
group = rng.sample(by_type[kind], rng.choice([1, 1, 1, 2, 3, 6]))
recipes = [[r, rng.random() < 0.4] for r in group]
if filtering and not any(c for _, c in recipes):
recipes[0][1] = True
collections.append({'recipes': recipes})
on_page = max(0, min(20, total - 20 * page))
value = rng.choice(WORDS)
cursor = rng.randint(0, len(value))
highlight = rng.choice([cursor, rng.randint(0, len(value))])
search = {'value': value, 'cursor': cursor, 'highlight': highlight,
'display': rng.choice([0, 0, min(cursor, rng.randint(0, len(value)))]), 'focused': rng.random() < 0.5,
'blink': rng.choice([0, 150, 450, 700])}
targets = [(xo + 11 + 25 * (i % 5) + rng.randint(0, 24), yo + 31 + 25 * (i // 5) + rng.randint(0, 24)) for i in range(on_page)]
targets += [(xo + 115, yo + 20), (xo + 95, yo + 140), (xo + 40, yo + 140), (xo + 30, yo + 18), (xo - 20, yo + 40),
(rng.randint(0, width), rng.randint(0, height))]
case = {'type': kind, 'grid': 2 if rng.random() < 0.5 else 3, 'width': width, 'height': height, 'narrow': narrow,
'mouse': list(rng.choice(targets)), 'index': rng.choice([0, 0, 1, 2, 5, 13, 60]), 'filtering': filtering,
'tabs': tab_list, 'search': search, 'collections': collections, 'page': page,
'buttonAnims': [rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)]) for _ in range(on_page)]}
multi = [i for i in range(on_page) if sum(1 for _, c in collections[20 * page + i]['recipes'] if c or not filtering) > 1]
if multi and rng.random() < 0.4:
case['overlay'] = rng.choice(multi)
if rng.random() < 0.4:
left, top = (width - 176) // 2, (height - 166) // 2
slots = [(124, 35, True)] + [(30 + 18 * (i % 3), 17 + 18 * (i // 3), False) for i in range(9)]
if kind != 'crafting':
slots = [(116, 35, True), (56, 17, False)]
case.update({'left': left, 'top': top, 'big': rng.random() < 0.7,
'ghost': [{'x': x, 'y': y, 'result': r, 'items': rng.sample(items, rng.choice([1, 1, 2, 4]))}
for x, y, r in rng.sample(slots, rng.randint(1, len(slots)))]})
out.append(case)
return out
def same(a, b):
"""Calls agree: every field exactly, poses within float printing."""
if a is None or b is None or set(a) != set(b):
return False
return all(all(abs(x - y) <= 1e-3 for x, y in zip(a[k], b[k])) if k == 'm' else a[k] == b[k] for k in a)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=29)
parser.add_argument('--cases', type=int, default=600)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
work = lib.work_dir('recipe-book-render-parity')
classes = work / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps,
'-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'ParityFont', 'VanillaRecipeBookScreenOracle'))],
capture_output=True, text=True)
if done.returncode:
print(done.stderr[-4000:])
sys.exit('javac failed')
chosen = cases(args.cases, args.seed)
inputs = work / 'cases.jsonl'
inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaRecipeBookScreenOracle',
str(inputs), str(work / 'vanilla.jsonl')], capture_output=True, text=True)
if run.returncode:
print(run.stderr[-4000:])
sys.exit('oracle failed')
lib.cargo_example('horizon-client', 'recipe_book_render_fixture', lib.RESOURCES, inputs, work / 'rust.jsonl')
vanilla = [json.loads(l) for l in (work / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (work / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust) == len(chosen), (len(vanilla), len(rust), len(chosen))
errors, failures, passed = {}, {}, 0
for case, v, r in zip(chosen, vanilla, rust):
if 'error' in v:
errors.setdefault(case['type'], v['error'])
continue
a, b = v['draws'], r['draws']
bad = next((i for i in range(max(len(a), len(b))) if i >= len(a) or i >= len(b) or not same(a[i], b[i])), None)
if bad is None:
passed += 1
else:
failures.setdefault(case['type'], []).append((case, bad, a[bad] if bad < len(a) else None, b[bad] if bad < len(b) else None))
for kind, error in sorted(errors.items()):
print(f'ORACLE ERROR {kind}: {error[:1500]}')
for kind, items in sorted(failures.items()):
print(f'MISMATCH {kind}: {len(items)} cases')
for case, i, x, y in items[:args.limit]:
brief = {k: v for k, v in case.items() if k not in ('collections',)}
print(f' {json.dumps(brief)[:700]}')
print(f' call {i}: vanilla {json.dumps(x)}')
print(f' call {i}: horizon {json.dumps(y)}')
print(f'{passed}/{len(chosen)} cases match')
if errors or failures:
sys.exit(1)
print('recipe book render parity ok')
if __name__ == '__main__':
main()