Merge main into fix/bundle-dump-on-use
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
//! Banner pattern layers (`BannerPatternLayers`) and their NBT form.
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BannerLayer {
|
||||
pub pattern: Arc<str>,
|
||||
pub color: Arc<str>,
|
||||
}
|
||||
impl BannerLayer {
|
||||
pub fn new(pattern: &str, color: &str) -> Self {
|
||||
Self {
|
||||
pattern: Arc::from(pattern),
|
||||
color: Arc::from(color),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `banner_patterns` NBT list of layers.
|
||||
pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag {
|
||||
Tag::List(
|
||||
layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
Tag::compound([
|
||||
("pattern", Tag::String((&*l.pattern).into())),
|
||||
("color", Tag::String((&*l.color).into())),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec<BannerLayer> {
|
||||
let Some(Tag::List(list)) = tag else {
|
||||
return Vec::new();
|
||||
};
|
||||
list.iter()
|
||||
.filter_map(|e| {
|
||||
let text = |k: &str| match e.get(k) {
|
||||
Some(Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
let pattern = text("pattern")?;
|
||||
let color = text("color")?;
|
||||
Some(BannerLayer::new(
|
||||
&if pattern.contains(':') {
|
||||
pattern
|
||||
} else {
|
||||
format!("minecraft:{pattern}")
|
||||
},
|
||||
&color,
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
//! Per-state gameplay facts exported from vanilla's own block-state accessors
|
||||
//! (`gameplay-facts.json`), indexed by registry state ID.
|
||||
mod decode;
|
||||
use crate::Result;
|
||||
use horizon_world::{
|
||||
level::{Behaviours, GameplayStateSource},
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{self, File},
|
||||
io::BufReader,
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RenderShape {
|
||||
Model,
|
||||
Invisible,
|
||||
Animated,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Fluid {
|
||||
None,
|
||||
Water,
|
||||
Lava,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Sounds {
|
||||
pub volume: f32,
|
||||
pub pitch: f32,
|
||||
pub break_sound: Arc<str>,
|
||||
pub step: Arc<str>,
|
||||
pub place: Arc<str>,
|
||||
pub hit: Arc<str>,
|
||||
pub fall: Arc<str>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct StateFacts {
|
||||
pub name: Arc<str>,
|
||||
pub emission: u8,
|
||||
pub dampening: u8,
|
||||
pub skylight_down: bool,
|
||||
pub shape_occlusion: bool,
|
||||
pub can_occlude: bool,
|
||||
pub solid_render: bool,
|
||||
pub hardness: f32,
|
||||
pub requires_tool: bool,
|
||||
pub replaceable: bool,
|
||||
pub random_ticks: bool,
|
||||
pub block_entity: bool,
|
||||
pub render_shape: RenderShape,
|
||||
pub full_collision: bool,
|
||||
pub friction: f32,
|
||||
pub explosion_resistance: f32,
|
||||
pub item: Arc<str>,
|
||||
pub sounds: Sounds,
|
||||
pub fluid: Fluid,
|
||||
/// Fluid amount 1..=8 (8 = source/falling surface), 0 when there is no fluid.
|
||||
pub fluid_level: u8,
|
||||
pub fluid_falling: bool,
|
||||
pub waterlogged: bool,
|
||||
/// `hasOffsetFunction`: the model is jittered per column.
|
||||
pub random_offset: bool,
|
||||
/// Whether the outline, not just the model, follows BlockState.getOffset.
|
||||
pub outline_offset: bool,
|
||||
/// `BlockState.isSolid()` (legacy solidity; fluid surfaces read it).
|
||||
pub legacy_solid: bool,
|
||||
/// `isFaceSturdy(.., SupportType.FULL)` by Direction ordinal.
|
||||
pub sturdy_full: u8,
|
||||
/// The block's class chain (`TransparentBlock`, `LeavesBlock`, ...), most specific first.
|
||||
pub classes: Arc<[Arc<str>]>,
|
||||
/// `getShape` (the outline used for picking) as boxes in block space,
|
||||
/// without the random offset; and its edges as LevelRenderer draws them.
|
||||
pub outline: Arc<[[f64; 6]]>,
|
||||
pub outline_edges: Arc<[[f64; 6]]>,
|
||||
/// `getMapColor(..).id` (0 = NONE).
|
||||
pub map_color: u8,
|
||||
}
|
||||
/// `MapColor.col` by id.
|
||||
pub const MAP_COLORS: [u32; 62] = [
|
||||
0, 8368696, 16247203, 13092807, 16711680, 10526975, 10987431, 31744, 16777215, 10791096,
|
||||
9923917, 7368816, 4210943, 9402184, 16776437, 14188339, 11685080, 6724056, 15066419, 8375321,
|
||||
15892389, 5000268, 10066329, 5013401, 8339378, 3361970, 6704179, 6717235, 10040115, 1644825,
|
||||
16445005, 6085589, 4882687, 55610, 8476209, 7340544, 13742497, 10441252, 9787244, 7367818,
|
||||
12223780, 6780213, 10505550, 3746083, 8874850, 5725276, 8014168, 4996700, 4993571, 5001770,
|
||||
9321518, 2430480, 12398641, 9715553, 6035741, 1474182, 3837580, 5647422, 1356933, 6579300,
|
||||
14200723, 8365974,
|
||||
];
|
||||
/// The 12 edges of the unit cube (outline data predating the export).
|
||||
pub fn cube_edges() -> Vec<[f64; 6]> {
|
||||
let mut edges = Vec::new();
|
||||
for a in 0..3 {
|
||||
for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] {
|
||||
let mut from = [0.0f64; 3];
|
||||
let (b, c) = ((a + 1) % 3, (a + 2) % 3);
|
||||
from[b] = u;
|
||||
from[c] = v;
|
||||
let mut to = from;
|
||||
to[a] = 1.0;
|
||||
edges.push([from[0], from[1], from[2], to[0], to[1], to[2]]);
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
impl StateFacts {
|
||||
pub fn has_class(&self, name: &str) -> bool {
|
||||
self.classes.iter().any(|c| &**c == name)
|
||||
}
|
||||
}
|
||||
/// Compact, owned behaviour inputs retained until the normal behaviour startup stage.
|
||||
/// No borrowed gameplay JSON or process-wide cache survives the fact loader.
|
||||
pub struct GameplayProjection {
|
||||
flags: u16,
|
||||
emission: u64,
|
||||
dampening: u64,
|
||||
hardness: f64,
|
||||
push: Arc<str>,
|
||||
volume: f64,
|
||||
pitch: f64,
|
||||
place: Arc<str>,
|
||||
break_sound: Arc<str>,
|
||||
fall: Arc<str>,
|
||||
}
|
||||
|
||||
impl GameplayProjection {
|
||||
fn from_entry(entry: &decode::Entry<'_>, strings: &mut HashMap<String, Arc<str>>) -> Self {
|
||||
fn intern(strings: &mut HashMap<String, Arc<str>>, value: &str) -> Arc<str> {
|
||||
if let Some(existing) = strings.get(value) {
|
||||
return Arc::clone(existing);
|
||||
}
|
||||
let value_arc: Arc<str> = Arc::from(value);
|
||||
strings.insert(value.to_owned(), Arc::clone(&value_arc));
|
||||
value_arc
|
||||
}
|
||||
const FLAGS: [&str; 11] = [
|
||||
"replaceable",
|
||||
"random_ticks",
|
||||
"solid_render",
|
||||
"liquid",
|
||||
"block_entity",
|
||||
"ignited_by_lava",
|
||||
"can_occlude",
|
||||
"full_collision",
|
||||
"skylight_down",
|
||||
"requires_tool",
|
||||
"shape_occlusion",
|
||||
];
|
||||
Self {
|
||||
flags: FLAGS.iter().enumerate().fold(0, |flags, (i, name)| {
|
||||
flags | ((u16::from(entry.flag(name))) << i)
|
||||
}),
|
||||
emission: entry.unsigned("emission"),
|
||||
dampening: entry.unsigned("dampening"),
|
||||
hardness: entry.number("hardness"),
|
||||
push: intern(strings, entry.text("push")),
|
||||
volume: entry.sound_number("volume"),
|
||||
pitch: entry.sound_number("pitch"),
|
||||
place: intern(strings, entry.sound_id("place")),
|
||||
break_sound: intern(strings, entry.sound_id("break")),
|
||||
fall: intern(strings, entry.sound_id("fall")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GameplayStateSource for GameplayProjection {
|
||||
fn flag(&self, name: &str) -> bool {
|
||||
const FLAGS: [&str; 11] = [
|
||||
"replaceable",
|
||||
"random_ticks",
|
||||
"solid_render",
|
||||
"liquid",
|
||||
"block_entity",
|
||||
"ignited_by_lava",
|
||||
"can_occlude",
|
||||
"full_collision",
|
||||
"skylight_down",
|
||||
"requires_tool",
|
||||
"shape_occlusion",
|
||||
];
|
||||
FLAGS
|
||||
.iter()
|
||||
.position(|field| *field == name)
|
||||
.is_some_and(|index| self.flags & (1 << index) != 0)
|
||||
}
|
||||
fn unsigned(&self, name: &str) -> u64 {
|
||||
match name {
|
||||
"emission" => self.emission,
|
||||
"dampening" => self.dampening,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
fn number(&self, name: &str) -> f64 {
|
||||
if name == "hardness" {
|
||||
self.hardness
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
fn text(&self, name: &str) -> &str {
|
||||
if name == "push" { &self.push } else { "" }
|
||||
}
|
||||
fn sound_number(&self, name: &str) -> f64 {
|
||||
match name {
|
||||
"volume" => self.volume,
|
||||
"pitch" => self.pitch,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
fn sound_id(&self, name: &str) -> &str {
|
||||
match name {
|
||||
"place" => &self.place,
|
||||
"break" => &self.break_sound,
|
||||
"fall" => &self.fall,
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BlockFacts {
|
||||
pub states: Vec<StateFacts>,
|
||||
pub air: BlockStateId,
|
||||
}
|
||||
impl BlockFacts {
|
||||
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
|
||||
let behaviours: Value = serde_json::from_reader(BufReader::new(File::open(
|
||||
root.join("block-behaviours.json"),
|
||||
)?))?;
|
||||
Self::load_with_behaviour_json(root, registry, &behaviours)
|
||||
}
|
||||
|
||||
/// Load both tables from one resource root, sharing each JSON decode.
|
||||
/// No data is cached across calls: changes to prepared packs or mods are read again.
|
||||
pub fn load_pair(root: &Path, registry: &BlockRegistry) -> Result<(Self, Behaviours)> {
|
||||
let behaviours: Value = serde_json::from_reader(BufReader::new(File::open(
|
||||
root.join("block-behaviours.json"),
|
||||
)?))?;
|
||||
Self::load_with_behaviours(root, registry, &behaviours)
|
||||
}
|
||||
|
||||
/// Decode state facts once, retaining only the small owned fields needed later.
|
||||
pub fn load_with_projection(
|
||||
root: &Path,
|
||||
registry: &BlockRegistry,
|
||||
behaviours: &Value,
|
||||
) -> Result<(Self, Vec<GameplayProjection>)> {
|
||||
Self::load_with_callback(root, registry, behaviours, |entries| {
|
||||
let mut strings = HashMap::new();
|
||||
Ok(entries
|
||||
.iter()
|
||||
.map(|entry| GameplayProjection::from_entry(entry, &mut strings))
|
||||
.collect())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn load_with_behaviour_json(
|
||||
root: &Path,
|
||||
registry: &BlockRegistry,
|
||||
behaviours: &Value,
|
||||
) -> Result<Self> {
|
||||
Ok(Self::load_with_callback(root, registry, behaviours, |_| Ok(()))?.0)
|
||||
}
|
||||
|
||||
/// Build both tables from the same behaviour document and gameplay decoder.
|
||||
pub fn load_with_behaviours(
|
||||
root: &Path,
|
||||
registry: &BlockRegistry,
|
||||
behaviours: &Value,
|
||||
) -> Result<(Self, Behaviours)> {
|
||||
Self::load_with_callback(root, registry, behaviours, |entries| {
|
||||
Ok(Behaviours::load_with_gameplay(
|
||||
registry, root, behaviours, entries,
|
||||
)?)
|
||||
})
|
||||
}
|
||||
|
||||
fn load_with_callback<T>(
|
||||
root: &Path,
|
||||
registry: &BlockRegistry,
|
||||
behaviours: &Value,
|
||||
callback: impl FnOnce(&[decode::Entry<'_>]) -> Result<T>,
|
||||
) -> Result<(Self, T)> {
|
||||
let bytes = fs::read(root.join("gameplay-facts.json"))?;
|
||||
serde_json::from_slice::<decode::Validate>(&bytes)?;
|
||||
let raw: decode::Gameplay<'_> = serde_json::from_slice(&bytes)?;
|
||||
let entries = raw
|
||||
.states
|
||||
.0
|
||||
.as_ref()
|
||||
.ok_or("missing gameplay state facts")?;
|
||||
if entries.len() != registry.len() {
|
||||
return Err("gameplay facts do not match the block registry".into());
|
||||
}
|
||||
// Class chains and per-state behaviour flags exported from the actual block objects.
|
||||
let behaviour_states = behaviours["states"]
|
||||
.as_array()
|
||||
.filter(|s| s.len() == registry.len())
|
||||
.ok_or("block behaviour facts do not match the block registry")?;
|
||||
let mut class_names: HashMap<String, Arc<str>> = HashMap::new();
|
||||
let classes: HashMap<&str, Arc<[Arc<str>]>> = behaviours["blocks"]
|
||||
.as_array()
|
||||
.ok_or("missing block behaviour classes")?
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let chain = b["class"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|c| {
|
||||
class_names
|
||||
.entry(c.to_owned())
|
||||
.or_insert_with(|| Arc::from(c))
|
||||
.clone()
|
||||
});
|
||||
Some((b["name"].as_str()?, chain.collect()))
|
||||
})
|
||||
.collect();
|
||||
let mut names: HashMap<String, Arc<str>> = HashMap::new();
|
||||
let mut intern = |s: &str| -> Arc<str> {
|
||||
if let Some(name) = names.get(s) {
|
||||
return name.clone();
|
||||
}
|
||||
let name: Arc<str> = Arc::from(s);
|
||||
names.insert(s.to_owned(), name.clone());
|
||||
name
|
||||
};
|
||||
let mut shapes = decode::Shapes::default();
|
||||
let mut states = Vec::with_capacity(entries.len());
|
||||
for (index, entry) in entries.iter().enumerate() {
|
||||
let id = BlockStateId(index as u32);
|
||||
if entry.id != Some(index as u64) {
|
||||
return Err("gameplay facts are not in registry order".into());
|
||||
}
|
||||
let state = registry.state(id).ok_or("missing registry state")?;
|
||||
let sound = &entry.sound;
|
||||
let prop = |k: &str| state.properties.get(k).map(String::as_str);
|
||||
let (fluid, fluid_level, fluid_falling) = match state.name.as_str() {
|
||||
"minecraft:water" | "minecraft:lava" => {
|
||||
let level: u8 = prop("level").and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
let kind = if state.name == "minecraft:water" {
|
||||
Fluid::Water
|
||||
} else {
|
||||
Fluid::Lava
|
||||
};
|
||||
// LiquidBlock: level 0 is the source; 1..7 flowing; >=8 falling.
|
||||
if level == 0 {
|
||||
(kind, 8, false)
|
||||
} else if level >= 8 {
|
||||
(kind, 8, true)
|
||||
} else {
|
||||
(kind, 8 - level, false)
|
||||
}
|
||||
}
|
||||
"minecraft:bubble_column"
|
||||
| "minecraft:kelp"
|
||||
| "minecraft:kelp_plant"
|
||||
| "minecraft:seagrass"
|
||||
| "minecraft:tall_seagrass" => (Fluid::Water, 8, false),
|
||||
_ if prop("waterlogged") == Some("true") => (Fluid::Water, 8, false),
|
||||
_ => (Fluid::None, 0, false),
|
||||
};
|
||||
let air = matches!(
|
||||
state.name.as_str(),
|
||||
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
|
||||
);
|
||||
let cube = move || {
|
||||
if air {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![[0.0, 0.0, 0.0, 1.0, 1.0, 1.0]]
|
||||
}
|
||||
};
|
||||
let edges = move || if air { Vec::new() } else { cube_edges() };
|
||||
let outline = shapes.intern(entry.outline, cube)?;
|
||||
let outline_edges = shapes.intern(entry.outline_edges, edges)?;
|
||||
// The export holds MapColor.col; ids are positions in MAP_COLORS.
|
||||
let col = entry.map_color.unwrap_or(0) as u32;
|
||||
let map_color = if col == 0 {
|
||||
0
|
||||
} else {
|
||||
MAP_COLORS.iter().position(|c| *c == col).unwrap_or(0) as u8
|
||||
};
|
||||
states.push(StateFacts {
|
||||
map_color,
|
||||
outline,
|
||||
outline_edges,
|
||||
name: intern(&state.name),
|
||||
emission: entry.emission.as_f64().unwrap_or(0.0) as u8,
|
||||
dampening: entry.dampening.as_f64().unwrap_or(0.0) as u8,
|
||||
skylight_down: entry.skylight_down,
|
||||
shape_occlusion: entry.shape_occlusion,
|
||||
can_occlude: entry.can_occlude,
|
||||
solid_render: entry.solid_render,
|
||||
hardness: entry.hardness.as_f64().unwrap_or(0.0) as f32,
|
||||
requires_tool: entry.requires_tool,
|
||||
replaceable: entry.replaceable,
|
||||
random_ticks: entry.random_ticks,
|
||||
block_entity: entry.block_entity,
|
||||
render_shape: match entry.render_shape.as_deref() {
|
||||
Some("INVISIBLE") => RenderShape::Invisible,
|
||||
Some("ENTITYBLOCK_ANIMATED") => RenderShape::Animated,
|
||||
_ => RenderShape::Model,
|
||||
},
|
||||
full_collision: entry.full_collision,
|
||||
friction: entry.friction as f32,
|
||||
explosion_resistance: entry.explosion_resistance as f32,
|
||||
item: intern(entry.item.as_deref().unwrap_or("minecraft:air")),
|
||||
sounds: Sounds {
|
||||
volume: sound.volume as f32,
|
||||
pitch: sound.pitch as f32,
|
||||
break_sound: intern(sound.r#break.id.as_deref().unwrap_or("")),
|
||||
step: intern(sound.step.id.as_deref().unwrap_or("")),
|
||||
place: intern(sound.place.id.as_deref().unwrap_or("")),
|
||||
hit: intern(sound.hit.id.as_deref().unwrap_or("")),
|
||||
fall: intern(sound.fall.id.as_deref().unwrap_or("")),
|
||||
},
|
||||
fluid,
|
||||
fluid_level,
|
||||
fluid_falling,
|
||||
waterlogged: prop("waterlogged") == Some("true"),
|
||||
random_offset: entry.offset,
|
||||
outline_offset: entry.outline_offset.unwrap_or(entry.offset),
|
||||
legacy_solid: behaviour_states[index][1].as_u64().unwrap_or(0) & 1 != 0,
|
||||
sturdy_full: (behaviour_states[index][0].as_u64().unwrap_or(0) & 63) as u8,
|
||||
classes: classes
|
||||
.get(state.name.as_str())
|
||||
.cloned()
|
||||
.ok_or("missing block behaviour class chain")?,
|
||||
});
|
||||
}
|
||||
let extra = callback(entries)?;
|
||||
Ok((
|
||||
Self {
|
||||
states,
|
||||
air: registry
|
||||
.default_state("minecraft:air")
|
||||
.ok_or("missing air")?,
|
||||
},
|
||||
extra,
|
||||
))
|
||||
}
|
||||
pub fn get(&self, id: BlockStateId) -> &StateFacts {
|
||||
&self.states[id.0 as usize]
|
||||
}
|
||||
pub fn is_air(&self, id: BlockStateId) -> bool {
|
||||
matches!(
|
||||
&*self.states[id.0 as usize].name,
|
||||
"minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl GameplayStateSource for decode::Entry<'_> {
|
||||
fn flag(&self, name: &str) -> bool {
|
||||
match name {
|
||||
"replaceable" => self.replaceable,
|
||||
"random_ticks" => self.random_ticks,
|
||||
"solid_render" => self.solid_render,
|
||||
"liquid" => self.liquid,
|
||||
"block_entity" => self.block_entity,
|
||||
"ignited_by_lava" => self.ignited_by_lava,
|
||||
"can_occlude" => self.can_occlude,
|
||||
"full_collision" => self.full_collision,
|
||||
"skylight_down" => self.skylight_down,
|
||||
"requires_tool" => self.requires_tool,
|
||||
"shape_occlusion" => self.shape_occlusion,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn unsigned(&self, name: &str) -> u64 {
|
||||
match name {
|
||||
"emission" => self.emission.as_u64().unwrap_or(0),
|
||||
"dampening" => self.dampening.as_u64().unwrap_or(0),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
fn number(&self, name: &str) -> f64 {
|
||||
match name {
|
||||
"hardness" => self.hardness.as_f64().unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
fn text(&self, name: &str) -> &str {
|
||||
match name {
|
||||
"push" => self.push.as_deref().unwrap_or(""),
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
fn sound_number(&self, name: &str) -> f64 {
|
||||
match name {
|
||||
"volume" => self.sound.volume,
|
||||
"pitch" => self.sound.pitch,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
fn sound_id(&self, name: &str) -> &str {
|
||||
match name {
|
||||
"place" => self.sound.place.id.as_deref().unwrap_or(""),
|
||||
"break" => self.sound.r#break.id.as_deref().unwrap_or(""),
|
||||
"fall" => self.sound.fall.id.as_deref().unwrap_or(""),
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Typed projection of gameplay facts. Scalar conversions deliberately retain Value's
|
||||
//! permissive defaults; maps retain its last-key-wins behavior. Repeated geometry stays
|
||||
//! borrowed until it is interned, rather than allocating a JSON tree for every state.
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{MapAccess, SeqAccess, Visitor},
|
||||
};
|
||||
use serde_json::{Value, value::RawValue};
|
||||
use std::{
|
||||
collections::{HashMap, hash_map::Entry as MapEntry},
|
||||
fmt,
|
||||
hash::{Hash, Hasher},
|
||||
marker::PhantomData,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
// RawValue skips numeric range and depth checks. A non-allocating validation pass
|
||||
// keeps the original Value loader's JSON errors, even in overwritten/unused fields.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Validate;
|
||||
impl<'de> Container<'de> for Validate {}
|
||||
impl<'de> Deserialize<'de> for Validate {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
container(d)
|
||||
}
|
||||
}
|
||||
|
||||
trait Container<'de>: Default {
|
||||
fn map<A: MapAccess<'de>>(mut map: A) -> Result<Self, A::Error> {
|
||||
while map.next_key::<serde::de::IgnoredAny>()?.is_some() {
|
||||
map.next_value::<Validate>()?;
|
||||
}
|
||||
Ok(Self::default())
|
||||
}
|
||||
fn seq<A: SeqAccess<'de>>(mut seq: A) -> Result<Self, A::Error> {
|
||||
while seq.next_element::<Validate>()?.is_some() {}
|
||||
Ok(Self::default())
|
||||
}
|
||||
}
|
||||
struct ContainerVisitor<T>(PhantomData<T>);
|
||||
impl<'de, T: Container<'de>> Visitor<'de> for ContainerVisitor<T> {
|
||||
type Value = T;
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("JSON facts")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
|
||||
T::map(map)
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<T, A::Error> {
|
||||
T::seq(seq)
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, _: &str) -> Result<T, E> {
|
||||
Ok(T::default())
|
||||
}
|
||||
}
|
||||
fn container<'de, D: Deserializer<'de>, T: Container<'de>>(d: D) -> Result<T, D::Error> {
|
||||
d.deserialize_any(ContainerVisitor(PhantomData))
|
||||
}
|
||||
macro_rules! read_field {
|
||||
($map:ident, typed) => {
|
||||
$map.next_value()?
|
||||
};
|
||||
($map:ident, value($convert:expr)) => {
|
||||
($convert)($map.next_value::<Value>()?)
|
||||
};
|
||||
}
|
||||
macro_rules! object {
|
||||
($name:ident<$life:lifetime> { $($field:ident: $ty:ty = $default:expr => $kind:ident $(($convert:expr))?),* $(,)? }) => {
|
||||
pub(super) struct $name<$life> {
|
||||
$(pub $field: $ty,)*
|
||||
marker: PhantomData<&$life ()>,
|
||||
}
|
||||
impl Default for $name<'_> {
|
||||
fn default() -> Self { Self { $($field: $default,)* marker: PhantomData } }
|
||||
}
|
||||
impl<$life> Container<$life> for $name<$life> {
|
||||
fn map<A: MapAccess<$life>>(mut map: A) -> Result<Self, A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[allow(non_camel_case_types)]
|
||||
#[serde(field_identifier)]
|
||||
enum Field { $($field,)* #[serde(other)] Unknown }
|
||||
let mut result = Self::default();
|
||||
while let Some(field) = map.next_key::<Field>()? {
|
||||
match field {
|
||||
$(Field::$field => result.$field = read_field!(map, $kind $(($convert))?),)*
|
||||
Field::Unknown => { map.next_value::<Validate>()?; }
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
impl<$life> Deserialize<$life> for $name<$life> {
|
||||
fn deserialize<D: Deserializer<$life>>(d: D) -> Result<Self, D::Error> { container(d) }
|
||||
}
|
||||
};
|
||||
}
|
||||
fn number(v: Value) -> f64 {
|
||||
v.as_f64().unwrap_or(0.0)
|
||||
}
|
||||
fn flag(v: Value) -> bool {
|
||||
v.as_bool().unwrap_or(false)
|
||||
}
|
||||
fn unsigned(v: Value) -> Option<u64> {
|
||||
v.as_u64()
|
||||
}
|
||||
fn text(v: Value) -> Option<String> {
|
||||
if let Value::String(s) = v {
|
||||
Some(s)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Entries<'a>(pub Option<Vec<Entry<'a>>>);
|
||||
impl<'de> Container<'de> for Entries<'de> {
|
||||
fn seq<A: SeqAccess<'de>>(mut seq: A) -> Result<Self, A::Error> {
|
||||
let mut entries = Vec::new();
|
||||
while let Some(entry) = seq.next_element()? {
|
||||
entries.push(entry);
|
||||
}
|
||||
Ok(Self(Some(entries)))
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for Entries<'de> {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
container(d)
|
||||
}
|
||||
}
|
||||
object!(Gameplay<'a> { states: Entries<'a> = Entries::default() => typed });
|
||||
object!(SoundId<'a> { id: Option<String> = None => value(text) });
|
||||
object!(Sound<'a> {
|
||||
volume: f64 = 1.0 => value(|v: Value| v.as_f64().unwrap_or(1.0)),
|
||||
pitch: f64 = 1.0 => value(|v: Value| v.as_f64().unwrap_or(1.0)),
|
||||
r#break: SoundId<'a> = SoundId::default() => typed,
|
||||
step: SoundId<'a> = SoundId::default() => typed,
|
||||
place: SoundId<'a> = SoundId::default() => typed,
|
||||
hit: SoundId<'a> = SoundId::default() => typed,
|
||||
fall: SoundId<'a> = SoundId::default() => typed,
|
||||
});
|
||||
object!(Entry<'a> {
|
||||
id: Option<u64> = None => value(unsigned),
|
||||
emission: Value = Value::Null => typed,
|
||||
dampening: Value = Value::Null => typed,
|
||||
skylight_down: bool = false => value(flag),
|
||||
shape_occlusion: bool = false => value(flag),
|
||||
can_occlude: bool = false => value(flag),
|
||||
solid_render: bool = false => value(flag),
|
||||
hardness: Value = Value::Null => typed,
|
||||
requires_tool: bool = false => value(flag),
|
||||
replaceable: bool = false => value(flag),
|
||||
random_ticks: bool = false => value(flag),
|
||||
block_entity: bool = false => value(flag),
|
||||
liquid: bool = false => value(flag),
|
||||
ignited_by_lava: bool = false => value(flag),
|
||||
push: Option<String> = None => value(text),
|
||||
render_shape: Option<String> = None => value(text),
|
||||
full_collision: bool = false => value(flag),
|
||||
friction: f64 = 0.0 => value(number),
|
||||
explosion_resistance: f64 = 0.0 => value(number),
|
||||
item: Option<String> = None => value(text),
|
||||
sound: Sound<'a> = Sound::default() => typed,
|
||||
offset: bool = false => value(flag),
|
||||
outline_offset: Option<bool> = None => value(|v: Value| v.as_bool()),
|
||||
map_color: Option<u64> = None => value(unsigned),
|
||||
outline: Option<&'a RawValue> = None => typed,
|
||||
outline_edges: Option<&'a RawValue> = None => typed,
|
||||
});
|
||||
|
||||
// Match Value::to_string identity without serializing: integer/float spelling is
|
||||
// distinct, as is the sign of floating zero. Object keys are already sorted by Value.
|
||||
struct ShapeKey(Value);
|
||||
fn same(a: &Value, b: &Value) -> bool {
|
||||
match (a, b) {
|
||||
(Value::Number(a), Value::Number(b)) => {
|
||||
a == b && a.as_f64().map(f64::to_bits) == b.as_f64().map(f64::to_bits)
|
||||
}
|
||||
(Value::Array(a), Value::Array(b)) => {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| same(a, b))
|
||||
}
|
||||
(Value::Object(a), Value::Object(b)) => {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.zip(b)
|
||||
.all(|((ak, av), (bk, bv))| ak == bk && same(av, bv))
|
||||
}
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
impl PartialEq for ShapeKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
same(&self.0, &other.0)
|
||||
}
|
||||
}
|
||||
impl Eq for ShapeKey {}
|
||||
fn shape_hash<H: Hasher>(v: &Value, h: &mut H) {
|
||||
std::mem::discriminant(v).hash(h);
|
||||
match v {
|
||||
Value::Null => {}
|
||||
Value::Bool(b) => b.hash(h),
|
||||
Value::String(s) => s.hash(h),
|
||||
Value::Number(n) => {
|
||||
n.is_f64().hash(h);
|
||||
n.hash(h);
|
||||
n.as_f64().map(f64::to_bits).hash(h);
|
||||
}
|
||||
Value::Array(a) => {
|
||||
a.len().hash(h);
|
||||
for v in a {
|
||||
shape_hash(v, h);
|
||||
}
|
||||
}
|
||||
Value::Object(o) => {
|
||||
o.len().hash(h);
|
||||
for (k, v) in o {
|
||||
k.hash(h);
|
||||
shape_hash(v, h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Hash for ShapeKey {
|
||||
fn hash<H: Hasher>(&self, h: &mut H) {
|
||||
shape_hash(&self.0, h);
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct Shapes<'a> {
|
||||
raw: HashMap<&'a str, usize>,
|
||||
canonical: HashMap<ShapeKey, usize>,
|
||||
values: Vec<Arc<[[f64; 6]]>>,
|
||||
}
|
||||
impl<'a> Shapes<'a> {
|
||||
pub fn intern(
|
||||
&mut self,
|
||||
raw: Option<&'a RawValue>,
|
||||
fallback: impl FnOnce() -> Vec<[f64; 6]>,
|
||||
) -> crate::Result<Arc<[[f64; 6]]>> {
|
||||
let Some(raw) = raw else {
|
||||
return Ok(fallback().into());
|
||||
};
|
||||
if let Some(&id) = self.raw.get(raw.get()) {
|
||||
return Ok(self.values[id].clone());
|
||||
}
|
||||
let value: Value = serde_json::from_str(raw.get())?;
|
||||
if !value.is_array() {
|
||||
return Ok(fallback().into());
|
||||
}
|
||||
let id = match self.canonical.entry(ShapeKey(value)) {
|
||||
MapEntry::Occupied(entry) => *entry.get(),
|
||||
MapEntry::Vacant(entry) => {
|
||||
let shape = entry
|
||||
.key()
|
||||
.0
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let b = b.as_array()?;
|
||||
Some(std::array::from_fn(|i| {
|
||||
b.get(i).and_then(Value::as_f64).unwrap_or(0.0)
|
||||
}))
|
||||
})
|
||||
.collect::<Arc<[[f64; 6]]>>();
|
||||
let id = self.values.len();
|
||||
self.values.push(shape);
|
||||
entry.insert(id);
|
||||
id
|
||||
}
|
||||
};
|
||||
self.raw.insert(raw.get(), id);
|
||||
Ok(self.values[id].clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "decode_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,137 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shape_identity_and_geometry_match_the_value_loader() -> crate::Result<()> {
|
||||
let inputs = [
|
||||
"[]",
|
||||
"[ ]",
|
||||
"[[0,0,0,1,1,1]]",
|
||||
"[ [0, 0, 0, 1, 1, 1] ]",
|
||||
"[[0.0,0,0,1,1,1]]",
|
||||
"[[0e0,0,0,1,1,1]]",
|
||||
"[[-0.0,0,0,1,1,1]]",
|
||||
"[[0,0,0,1,1,1,7]]",
|
||||
"[[0,0,0,1,1,1,8]]",
|
||||
"[[1,null,\"2\"],true,{}]",
|
||||
"[[1,null,\"\\u0032\"],true,{}]",
|
||||
"[{\"z\":0,\"a\":1}]",
|
||||
"[{\"a\":1,\"z\":0}]",
|
||||
"[[18446744073709551615,-9223372036854775808,1e20]]",
|
||||
"[{\"a\":2,\"a\":1,\"z\":0}]",
|
||||
];
|
||||
let values = inputs
|
||||
.iter()
|
||||
.map(|s| serde_json::from_str::<Value>(s))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// Value equality merges signed zero; the legacy string keys do not.
|
||||
let keys: Vec<_> = values.iter().map(Value::to_string).collect();
|
||||
let mut shapes = Shapes::default();
|
||||
let actual = inputs
|
||||
.iter()
|
||||
.map(|s| {
|
||||
shapes.intern(Some(serde_json::from_str::<&RawValue>(s)?), || {
|
||||
panic!("array fallback")
|
||||
})
|
||||
})
|
||||
.collect::<crate::Result<Vec<_>>>()?;
|
||||
for (i, value) in values.iter().enumerate() {
|
||||
let expected: Vec<[f64; 6]> = value
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let b = b.as_array()?;
|
||||
Some(std::array::from_fn(|i| {
|
||||
b.get(i).and_then(Value::as_f64).unwrap_or(0.0)
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
// Bit comparisons include negative zero.
|
||||
assert_eq!(
|
||||
actual[i]
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|v| v.to_bits())
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|v| v.to_bits())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
for j in 0..values.len() {
|
||||
assert_eq!(
|
||||
Arc::ptr_eq(&actual[i], &actual[j]),
|
||||
keys[i] == keys[j],
|
||||
"{i}, {j}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for input in ["null", "false", "7", "{}", "\"shape\""] {
|
||||
let raw = serde_json::from_str(input)?;
|
||||
let a = shapes.intern(Some(raw), || vec![[7.0; 6]])?;
|
||||
let b = shapes.intern(Some(raw), || vec![[7.0; 6]])?;
|
||||
assert_eq!(&*a, &[[7.0; 6]]);
|
||||
assert!(!Arc::ptr_eq(&a, &b)); // Fallbacks were never interned.
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_fields_keep_defaults_duplicates_and_wrong_type_behavior() -> crate::Result<()> {
|
||||
let input = r#"{"states":[null,[],{"id":0,"id":2,"emission":4.5,"dampening":"15",
|
||||
"hardness":-0.0,"skylight_down":true,"offset":true,"outline_offset":"true",
|
||||
"item":42,"render_shape":false,"sound":{"volume":null,"pitch":2,"break":{"id":"a\u0062"},
|
||||
"step":false,"hit":{"id":2}},"outline":[[0,1]],"unknown":{"nested":true}}]}"#;
|
||||
let parsed: Gameplay<'_> = serde_json::from_str(input)?;
|
||||
let entries = parsed.states.0.unwrap();
|
||||
assert_eq!(entries[0].id, None);
|
||||
assert_eq!(entries[1].id, None);
|
||||
let e = &entries[2];
|
||||
assert_eq!(e.id, Some(2));
|
||||
assert_eq!(e.emission.as_f64(), Some(4.5));
|
||||
assert_eq!(e.dampening.as_f64().unwrap_or(0.0), 0.0);
|
||||
assert_eq!(e.hardness.as_f64().unwrap().to_bits(), (-0.0f64).to_bits());
|
||||
assert!(e.skylight_down && e.outline_offset.unwrap_or(e.offset));
|
||||
assert_eq!(e.item, None);
|
||||
assert_eq!(e.render_shape, None);
|
||||
assert_eq!((e.sound.volume, e.sound.pitch), (1.0, 2.0));
|
||||
assert_eq!(e.sound.r#break.id.as_deref(), Some("ab"));
|
||||
assert_eq!(e.sound.step.id, None);
|
||||
assert_eq!(e.sound.hit.id, None);
|
||||
assert_eq!(e.outline.unwrap().get(), "[[0,1]]");
|
||||
for input in ["null", "[]", "{}", r#"{"states":null}"#, r#"{"states":{}}"#] {
|
||||
let parsed: Gameplay<'_> = serde_json::from_str(input)?;
|
||||
assert!(parsed.states.0.is_none());
|
||||
}
|
||||
for input in [
|
||||
r#"{"states":["#,
|
||||
r#"{"states":[{"id":1e400}]}"#,
|
||||
"{} trailing",
|
||||
r#"{"unknown":1e400}"#,
|
||||
] {
|
||||
let before = serde_json::from_str::<Value>(input).err().unwrap();
|
||||
let after = serde_json::from_str::<Gameplay<'_>>(input).err().unwrap();
|
||||
assert_eq!(before.classify(), after.classify());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_shape_capture_keeps_original_json_errors() {
|
||||
let deep = format!("{}0{}", "[".repeat(130), "]".repeat(130));
|
||||
let inputs = [
|
||||
br#"{"states":[{"outline":[[1e400]],"outline":[]}]}"#.to_vec(),
|
||||
format!("{{\"states\":[{{\"outline\":{deep}}}]}}").into_bytes(),
|
||||
br#"{"states":[{"outline":[[0]]}]} trailing"#.to_vec(),
|
||||
b"{\"states\":[{\"outline\":[[\"\xff\"]]}]}".to_vec(),
|
||||
];
|
||||
for input in inputs {
|
||||
let old = serde_json::from_slice::<Value>(&input).err().unwrap();
|
||||
let new = serde_json::from_slice::<Validate>(&input).err().unwrap();
|
||||
assert_eq!(
|
||||
(old.classify(), old.line(), old.column()),
|
||||
(new.classify(), new.line(), new.column())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
//! `BundleContents.Mutable`: what a bundle takes in and gives back, by
|
||||
//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click
|
||||
//! overrides on it.
|
||||
use crate::item_data::BundleSelected;
|
||||
use crate::items::{ItemStack, Items};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// A bundle weight: vanilla's `Fraction`, exact and kept reduced.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Weight {
|
||||
n: i128,
|
||||
d: i128,
|
||||
}
|
||||
|
||||
fn gcd(a: i128, b: i128) -> i128 {
|
||||
let (mut a, mut b) = (a.abs(), b.abs());
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
a.max(1)
|
||||
}
|
||||
|
||||
impl Weight {
|
||||
const ZERO: Self = Self { n: 0, d: 1 };
|
||||
const ONE: Self = Self { n: 1, d: 1 };
|
||||
|
||||
fn new(n: i128, d: i128) -> Self {
|
||||
let g = gcd(n, d);
|
||||
Self { n: n / g, d: d / g }
|
||||
}
|
||||
|
||||
fn add(self, o: Self) -> Self {
|
||||
Self::new(self.n * o.d + o.n * self.d, self.d * o.d)
|
||||
}
|
||||
|
||||
fn sub(self, o: Self) -> Self {
|
||||
self.add(Self { n: -o.n, d: o.d })
|
||||
}
|
||||
|
||||
fn times(self, count: u32) -> Self {
|
||||
Self::new(self.n * i128::from(count), self.d)
|
||||
}
|
||||
|
||||
/// `this.divideBy(item).intValue()` (truncated), at least 0.
|
||||
fn how_many(self, item: Self) -> u32 {
|
||||
let q = (self.n * item.d) / (self.d * item.n);
|
||||
u32::try_from(q.max(0)).unwrap_or(u32::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sounds of `BundleItem` (`Entity.playSound` at the player): insert
|
||||
/// and remove one at volume 0.8 and pitch `0.8 + random * 0.4`, a failed
|
||||
/// insert at 1, 1; the drop of its contents is played at the player's block
|
||||
/// like remove one.
|
||||
pub const INSERT: &str = "minecraft:item.bundle.insert";
|
||||
pub const INSERT_FAIL: &str = "minecraft:item.bundle.insert_fail";
|
||||
pub const REMOVE_ONE: &str = "minecraft:item.bundle.remove_one";
|
||||
pub const DROP_CONTENTS: &str = "minecraft:item.bundle.drop_contents";
|
||||
|
||||
fn max_stack(items: &Items, stack: &ItemStack) -> u32 {
|
||||
items.get(&stack.item).map_or(64, |i| i.max_stack).max(1)
|
||||
}
|
||||
|
||||
/// The stack's `bundle_contents`, when it has the component.
|
||||
fn contents_of<'a>(items: &Items, stack: &'a ItemStack) -> Option<&'a [ItemStack]> {
|
||||
let inside = stack.data().map_or(&[][..], |d| &d.bundle_contents[..]);
|
||||
let bundle = items.get(&stack.item).is_some_and(|i| i.bundle);
|
||||
(bundle || !inside.is_empty()).then_some(inside)
|
||||
}
|
||||
|
||||
/// `BundleContents.getWeight`: a nested bundle weighs its contents plus
|
||||
/// 1/16, a beehive with bees 1, the rest 1 / max stack size.
|
||||
fn item_weight(items: &Items, stack: &ItemStack) -> Weight {
|
||||
if let Some(inside) = contents_of(items, stack) {
|
||||
return contents_weight(items, inside).add(Weight::new(1, 16));
|
||||
}
|
||||
let bees = stack
|
||||
.data()
|
||||
.and_then(|d| d.other("minecraft:bees"))
|
||||
.is_some_and(|b| matches!(b, Tag::List(l) if !l.is_empty()));
|
||||
if bees {
|
||||
Weight::ONE
|
||||
} else {
|
||||
Weight::new(1, i128::from(max_stack(items, stack)))
|
||||
}
|
||||
}
|
||||
|
||||
fn contents_weight(items: &Items, inside: &[ItemStack]) -> Weight {
|
||||
inside.iter().fold(Weight::ZERO, |w, s| {
|
||||
w.add(item_weight(items, s).times(s.count))
|
||||
})
|
||||
}
|
||||
|
||||
/// `BundleContents.canItemBeInBundle`: shulker boxes don't fit.
|
||||
pub fn can_be_in_bundle(stack: &ItemStack) -> bool {
|
||||
stack.count > 0 && !stack.item.ends_with("shulker_box")
|
||||
}
|
||||
|
||||
/// `BundleContents.Mutable`.
|
||||
pub struct Contents {
|
||||
items: Vec<ItemStack>,
|
||||
weight: Weight,
|
||||
/// `selectedItem`: an index into `items`, -1 for none.
|
||||
selected: i32,
|
||||
}
|
||||
|
||||
impl Contents {
|
||||
/// The bundle's contents; None when the stack is no bundle.
|
||||
pub fn of(items: &Items, stack: &ItemStack) -> Option<Self> {
|
||||
let inside = contents_of(items, stack)?.to_vec();
|
||||
let weight = contents_weight(items, &inside);
|
||||
let selected = stack.data().map_or(-1, |d| d.bundle_selected.0);
|
||||
Some(Self {
|
||||
items: inside,
|
||||
weight,
|
||||
selected,
|
||||
})
|
||||
}
|
||||
|
||||
/// `getMaxAmountToAdd` for `stack`'s kind of item.
|
||||
pub fn room_for(&self, items: &Items, stack: &ItemStack) -> u32 {
|
||||
Weight::ONE
|
||||
.sub(self.weight)
|
||||
.how_many(item_weight(items, stack))
|
||||
}
|
||||
|
||||
/// `tryInsert`: what fits moves to the front, merged with its kind.
|
||||
pub fn try_insert(&mut self, items: &Items, stack: &mut ItemStack) -> u32 {
|
||||
if !can_be_in_bundle(stack) {
|
||||
return 0;
|
||||
}
|
||||
let weight = item_weight(items, stack);
|
||||
let amount = stack
|
||||
.count
|
||||
.min(Weight::ONE.sub(self.weight).how_many(weight));
|
||||
if amount == 0 {
|
||||
return 0;
|
||||
}
|
||||
self.weight = self.weight.add(weight.times(amount));
|
||||
// ItemStack.isStackable: a damaged stack is damageable.
|
||||
let stackable = max_stack(items, stack) > 1 && stack.damage == 0;
|
||||
let same = self
|
||||
.items
|
||||
.iter()
|
||||
.position(|s| stackable && s.same_item_same_components(stack));
|
||||
let added = match same {
|
||||
Some(i) => {
|
||||
let mut merged = self.items.remove(i);
|
||||
merged.count += amount;
|
||||
stack.count -= amount;
|
||||
merged
|
||||
}
|
||||
None => {
|
||||
let mut part = stack.clone();
|
||||
part.count = amount;
|
||||
stack.count -= amount;
|
||||
part
|
||||
}
|
||||
};
|
||||
self.items.insert(0, added);
|
||||
amount
|
||||
}
|
||||
|
||||
/// `removeOne`: the selected stack, else the first; nothing is selected after.
|
||||
pub fn remove_one(&mut self, items: &Items) -> Option<ItemStack> {
|
||||
if self.items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let at =
|
||||
usize::try_from(self.selected).map_or(0, |i| if i < self.items.len() { i } else { 0 });
|
||||
let stack = self.items.remove(at);
|
||||
self.weight = self
|
||||
.weight
|
||||
.sub(item_weight(items, &stack).times(stack.count));
|
||||
self.selected = -1;
|
||||
Some(stack)
|
||||
}
|
||||
|
||||
/// `getSelectedItemIndex`.
|
||||
pub fn selected(&self) -> i32 {
|
||||
self.selected
|
||||
}
|
||||
|
||||
/// The stacks inside, in display order (the first is the next out).
|
||||
pub fn items(&self) -> &[ItemStack] {
|
||||
&self.items
|
||||
}
|
||||
|
||||
/// `getNumberOfItemsToShow`: a full grid shows 11 and a `+N`, so the last
|
||||
/// row keeps its fourth cell for the count.
|
||||
pub fn shown_count(&self) -> usize {
|
||||
let count = self.items.len();
|
||||
let available: usize = if count > 12 { 11 } else { 12 };
|
||||
let on_last_row = count % 4;
|
||||
let empty = if on_last_row == 0 { 0 } else { 4 - on_last_row };
|
||||
count.min(available.saturating_sub(empty))
|
||||
}
|
||||
|
||||
/// The items the tooltip shows, and how many sit beyond them.
|
||||
pub fn shown(&self) -> (&[ItemStack], u32) {
|
||||
let n = self.shown_count();
|
||||
let hidden = self.items[n..].iter().map(|s| s.count).sum();
|
||||
(&self.items[..n], hidden)
|
||||
}
|
||||
|
||||
/// The `Fraction` weight as the float the progress bar reads.
|
||||
pub fn weight_fraction(&self) -> f32 {
|
||||
self.weight.n as f32 / self.weight.d as f32
|
||||
}
|
||||
|
||||
/// `Fraction.ONE`: a full bundle draws the full bar and says so.
|
||||
pub fn is_full(&self) -> bool {
|
||||
self.weight.n >= self.weight.d
|
||||
}
|
||||
|
||||
/// `BundleItem.isBarVisible`, `getBarWidth` and `getBarColor`: the fullness bar
|
||||
/// (width, RGB), blue until the bundle is full, then red.
|
||||
pub fn bar(&self) -> Option<(i32, u32)> {
|
||||
if self.weight.n <= 0 {
|
||||
return None;
|
||||
}
|
||||
let width = (1 + self.weight.n * 12 / self.weight.d).min(13) as i32;
|
||||
let color = if self.is_full() { 0xFF5454 } else { 0x7087FF };
|
||||
Some((width, color))
|
||||
}
|
||||
|
||||
/// `toImmutable`, written back into the bundle's component.
|
||||
pub fn store(self, bundle: &mut ItemStack) {
|
||||
let data = bundle.data_mut();
|
||||
data.bundle_contents = self.items;
|
||||
data.bundle_selected = BundleSelected(self.selected);
|
||||
bundle.tidy();
|
||||
}
|
||||
}
|
||||
|
||||
/// `BundleItem.toggleSelectedItem`: select `index`, or nothing when it is the
|
||||
/// selected one already or outside the contents.
|
||||
pub fn toggle_selected(bundle: &mut ItemStack, index: i32) {
|
||||
let Some(data) = bundle.extra.as_deref_mut() else {
|
||||
return;
|
||||
};
|
||||
let inside = (0..data.bundle_contents.len() as i32).contains(&index);
|
||||
let selected = if data.bundle_selected.0 != index && inside {
|
||||
index
|
||||
} else {
|
||||
-1
|
||||
};
|
||||
data.bundle_selected = BundleSelected(selected);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Weight;
|
||||
|
||||
#[test]
|
||||
fn weights_add_up_exactly() {
|
||||
let w = Weight::new(1, 64)
|
||||
.times(32)
|
||||
.add(Weight::new(1, 16).times(4));
|
||||
assert_eq!(w, Weight::new(3, 4));
|
||||
assert_eq!(Weight::ONE.sub(w).how_many(Weight::new(1, 64)), 16);
|
||||
assert_eq!(Weight::ONE.sub(Weight::ONE).how_many(Weight::ONE), 0);
|
||||
// An over-full bundle (made by a command) has no room.
|
||||
let over = Weight::ONE.sub(Weight::new(5, 4));
|
||||
assert_eq!(over.how_many(Weight::new(1, 64)), 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- the tooltip
|
||||
|
||||
/// `ClientBundleTooltip`'s geometry, relative to the tooltip box's top-left:
|
||||
/// the 96 pixel column of a 4 wide slot grid and the progress bar under it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TooltipLayout {
|
||||
/// The component's own width (96) and height, the text's excluded.
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
/// Each slot's top-left and the stack in it, in drawing order.
|
||||
pub slots: Vec<([f32; 2], ItemStack)>,
|
||||
/// The position in `slots` of the selected item, which is drawn highlighted.
|
||||
pub selected: Option<usize>,
|
||||
/// The `+N` of the items past the grid: its top-left and the count.
|
||||
pub overflow: Option<([f32; 2], u32)>,
|
||||
/// The progress bar's top-left, its fill's width out of 94, and whether
|
||||
/// the weight fills it (the full sprite).
|
||||
pub bar: [f32; 2],
|
||||
pub fill: f32,
|
||||
pub full: bool,
|
||||
/// `item.minecraft.bundle.empty` / `.full`, centred over the bar.
|
||||
pub label: Option<&'static str>,
|
||||
/// An empty bundle's description, wrapped at `width` from here.
|
||||
pub empty_description: Option<[f32; 2]>,
|
||||
}
|
||||
|
||||
/// The tooltip of a bundle's contents (`ClientBundleTooltip`), or None when
|
||||
/// the stack is not a bundle. `x`/`y` are the box's top-left, `box_width` the
|
||||
/// tooltip's width, which the component is centred in.
|
||||
pub fn tooltip_layout(
|
||||
items: &Items,
|
||||
stack: &ItemStack,
|
||||
x: f32,
|
||||
y: f32,
|
||||
box_width: f32,
|
||||
) -> Option<TooltipLayout> {
|
||||
let contents = Contents::of(items, stack)?;
|
||||
let offset = ((box_width - 96.0) / 2.0).floor();
|
||||
if contents.items().is_empty() {
|
||||
// The description takes the top; the bar follows it.
|
||||
let description_height = 9.0 * 2.0;
|
||||
return Some(TooltipLayout {
|
||||
width: 96.0,
|
||||
height: description_height + 13.0 + 8.0,
|
||||
slots: Vec::new(),
|
||||
selected: None,
|
||||
overflow: None,
|
||||
bar: [x + offset, y + description_height + 4.0],
|
||||
fill: 0.0,
|
||||
full: false,
|
||||
label: Some("item.minecraft.bundle.empty"),
|
||||
empty_description: Some([x + offset, y]),
|
||||
});
|
||||
}
|
||||
let (shown, hidden) = contents.shown();
|
||||
// `gridSizeY` counts `slotCount()` (at most twelve), not the slots the
|
||||
// overflow count leaves room for.
|
||||
let rows = contents.items().len().min(12).div_ceil(4).max(1);
|
||||
let grid_height = rows as f32 * 24.0;
|
||||
let x_start = x + offset + 96.0;
|
||||
let y_start = y + grid_height;
|
||||
let mut slots = Vec::with_capacity(shown.len());
|
||||
let mut selected = None;
|
||||
let mut overflow = None;
|
||||
// Rows fill bottom-up and columns right-to-left, as vanilla draws them.
|
||||
let mut slot = 0;
|
||||
for row in 1..=rows {
|
||||
for column in 1..=4 {
|
||||
let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
|
||||
if hidden > 0 && row == 1 && column == 1 {
|
||||
overflow = Some((at, hidden));
|
||||
} else if slot < shown.len() {
|
||||
// `extractSlot`: the cell of slot number n holds item `size - n`.
|
||||
let index = shown.len() - 1 - slot;
|
||||
if usize::try_from(contents.selected()) == Ok(index) {
|
||||
selected = Some(slots.len());
|
||||
}
|
||||
slots.push((at, shown[index].clone()));
|
||||
slot += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let weight = contents.weight_fraction();
|
||||
Some(TooltipLayout {
|
||||
width: 96.0,
|
||||
height: grid_height + 13.0 + 8.0,
|
||||
slots,
|
||||
selected,
|
||||
overflow,
|
||||
bar: [x + offset, y + grid_height + 4.0],
|
||||
// `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
|
||||
fill: (weight * 94.0).trunc().clamp(0.0, 94.0),
|
||||
full: contents.is_full(),
|
||||
label: if contents.is_full() {
|
||||
Some("item.minecraft.bundle.full")
|
||||
} else {
|
||||
None
|
||||
},
|
||||
empty_description: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tooltip_tests {
|
||||
use super::*;
|
||||
|
||||
/// The prepared resources, when they are on this machine: the tooltip
|
||||
/// asks the item registry whether a stack is a bundle.
|
||||
fn items() -> Option<Items> {
|
||||
crate::items::prepared_items()
|
||||
}
|
||||
|
||||
fn bundle_with(counts: &[(&str, u32)]) -> ItemStack {
|
||||
let mut bundle = ItemStack::new("minecraft:bundle", 1);
|
||||
bundle.data_mut().bundle_contents = counts
|
||||
.iter()
|
||||
.map(|(item, n)| ItemStack::new(item, *n))
|
||||
.collect();
|
||||
bundle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_shows_twelve_stacks_and_counts_the_rest() {
|
||||
let Some(items) = items() else { return };
|
||||
let twelve: Vec<(&str, u32)> = (0..12).map(|_| ("minecraft:stone", 1)).collect();
|
||||
let layout = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 96.0).unwrap();
|
||||
assert_eq!(layout.slots.len(), 12);
|
||||
assert_eq!(layout.overflow, None);
|
||||
assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
|
||||
// Rows fill bottom-up and columns right-to-left: the twelfth item is in
|
||||
// the bottom-right cell, the first in the top-left.
|
||||
assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
|
||||
assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
|
||||
assert_eq!(layout.slots[11].0, [0.0, 0.0]);
|
||||
// A wider tooltip centres the 96 pixel column in it.
|
||||
let centred = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 120.0).unwrap();
|
||||
assert_eq!(centred.slots[0].0[0], 12.0 + 96.0 - 24.0);
|
||||
// Thirteen stacks: `getNumberOfItemsToShow` leaves the last row room
|
||||
// for the count, so 8 slots show and `+6` (four stones and two dirt)
|
||||
// takes the first cell.
|
||||
let mut counts = twelve;
|
||||
counts.push(("minecraft:dirt", 2));
|
||||
let layout = tooltip_layout(&items, &bundle_with(&counts), 0.0, 0.0, 96.0).unwrap();
|
||||
assert_eq!(layout.slots.len(), 8);
|
||||
assert_eq!(layout.overflow, Some(([96.0 - 24.0, 48.0], 6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_fills_with_the_weight_and_an_empty_bundle_explains_itself() {
|
||||
let Some(items) = items() else { return };
|
||||
let layout = tooltip_layout(&items, &bundle_with(&[]), 4.0, 8.0, 96.0).unwrap();
|
||||
assert!(layout.slots.is_empty());
|
||||
assert_eq!(layout.fill, 0.0);
|
||||
assert_eq!(layout.label, Some("item.minecraft.bundle.empty"));
|
||||
assert_eq!(layout.empty_description, Some([4.0, 8.0]));
|
||||
assert_eq!(layout.bar, [4.0, 8.0 + 18.0 + 4.0]);
|
||||
// A bundle holding one 64 stack is full: the whole bar, the full label.
|
||||
let layout = tooltip_layout(
|
||||
&items,
|
||||
&bundle_with(&[("minecraft:stone", 64)]),
|
||||
0.0,
|
||||
0.0,
|
||||
96.0,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(layout.full);
|
||||
assert_eq!(layout.fill, 94.0);
|
||||
assert_eq!(layout.label, Some("item.minecraft.bundle.full"));
|
||||
// Something that is not a bundle has no component.
|
||||
let dirt = ItemStack::new("minecraft:dirt", 1);
|
||||
assert!(tooltip_layout(&items, &dirt, 0.0, 0.0, 96.0).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! The namespaces content mods add to a resource root, which loaders read
|
||||
//! besides `minecraft`.
|
||||
use std::{fs, path::Path};
|
||||
|
||||
/// In a root built here: the namespaces the content mods own (their ids and
|
||||
/// listed namespaces), which loaders read besides `minecraft`.
|
||||
pub const MARKER: &str = "horizon-mod-content.json";
|
||||
|
||||
/// The content mods' namespaces in a root built by `mod_content::build`; none in any
|
||||
/// other root, so vanilla's loaders read exactly what they did.
|
||||
pub fn namespaces(root: &Path) -> Vec<String> {
|
||||
fs::read(root.join(MARKER))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The namespaces whose tags loaders read in `root`: `minecraft`, and in a
|
||||
/// root built by `mod_content::build` the convention tags (`c`, shared between mods as
|
||||
/// on NeoForge and Fabric) and the content mods' own.
|
||||
pub fn tag_namespaces(root: &Path) -> Vec<String> {
|
||||
let mods = namespaces(root);
|
||||
let mut out = vec!["minecraft".to_owned()];
|
||||
if !mods.is_empty() {
|
||||
out.push("c".to_owned());
|
||||
out.extend(mods);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//! `Player.getCooldowns()` (`ItemCooldowns`) as the game keeps it: the
|
||||
//! `use_cooldown` component's entries by cooldown group, counted down once a
|
||||
//! tick, and the percent `GuiGraphicsExtractor.itemCooldown` shades a slot
|
||||
//! by. The world crate's `item_cooldowns` models vanilla's hash map and its
|
||||
//! observers for the parity harness; this is the same data with the lookup a
|
||||
//! slot needs, and no observer (vanilla's own player uses the plain class).
|
||||
use crate::items::ItemStack;
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A stack's `minecraft:use_cooldown` component.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct UseCooldown {
|
||||
pub seconds: f32,
|
||||
/// `cooldown_group`: the group the entry is filed under, else the item.
|
||||
pub group: Option<Arc<str>>,
|
||||
}
|
||||
impl UseCooldown {
|
||||
/// `UseCooldown.ticks`: the seconds in ticks, truncated.
|
||||
pub fn ticks(&self) -> i32 {
|
||||
(self.seconds * 20.0) as i32
|
||||
}
|
||||
/// The component as `items.json` holds it.
|
||||
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
|
||||
let seconds = v.get("seconds")?.as_f64()? as f32;
|
||||
Some(Self {
|
||||
seconds,
|
||||
group: v
|
||||
.get("cooldown_group")
|
||||
.and_then(|g| g.as_str())
|
||||
.map(Arc::from),
|
||||
})
|
||||
}
|
||||
/// The component as a stack's saved `components` holds it.
|
||||
pub fn from_tag(t: &Tag) -> Option<Self> {
|
||||
let Tag::Compound(c) = t else {
|
||||
return None;
|
||||
};
|
||||
let text = |k: &str| match c.get(&horizon_world::nbt::JavaString::from(k)) {
|
||||
Some(Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
};
|
||||
let seconds = match c.get(&horizon_world::nbt::JavaString::from("seconds")) {
|
||||
Some(Tag::Float(bits)) => f32::from_bits(*bits),
|
||||
Some(Tag::Double(bits)) => f64::from_bits(*bits) as f32,
|
||||
_ => return None,
|
||||
};
|
||||
Some(Self {
|
||||
seconds,
|
||||
group: text("cooldown_group").map(Arc::from),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The component a stack carries: its own patch first (`ItemStack.get`), then
|
||||
/// the item's default from `items.json` (`ItemInfo::use_cooldown`).
|
||||
pub fn component(stack: &ItemStack, default: Option<&UseCooldown>) -> Option<UseCooldown> {
|
||||
stack
|
||||
.data()
|
||||
.and_then(|d| d.other("minecraft:use_cooldown"))
|
||||
.and_then(UseCooldown::from_tag)
|
||||
.or_else(|| default.cloned())
|
||||
}
|
||||
|
||||
/// `ItemCooldowns.getCooldownGroup`: the component's group, else the item id.
|
||||
pub fn group(stack: &ItemStack, default: Option<&UseCooldown>) -> Arc<str> {
|
||||
component(stack, default)
|
||||
.and_then(|c| c.group)
|
||||
.unwrap_or_else(|| Arc::clone(&stack.item))
|
||||
}
|
||||
|
||||
/// `ItemCooldowns`: start and end ticks by group, and the tick counter.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Cooldowns {
|
||||
tick_count: i32,
|
||||
entries: HashMap<Arc<str>, (i32, i32)>,
|
||||
}
|
||||
impl Cooldowns {
|
||||
/// `getCooldownPercent`: what is left of the entry, from 1 to 0.
|
||||
pub fn percent(&self, group: &str, partial_tick: f32) -> f32 {
|
||||
let Some((start, end)) = self.entries.get(group) else {
|
||||
return 0.0;
|
||||
};
|
||||
let duration = end.wrapping_sub(*start) as f32;
|
||||
let remaining = *end as f32 - (self.tick_count as f32 + partial_tick);
|
||||
(remaining / duration).clamp(0.0, 1.0)
|
||||
}
|
||||
/// `isOnCooldown`: whether the group still has time to run.
|
||||
pub fn is_on_cooldown(&self, group: &str) -> bool {
|
||||
self.percent(group, 0.0) > 0.0
|
||||
}
|
||||
/// `addCooldown`.
|
||||
pub fn add(&mut self, group: Arc<str>, ticks: i32) {
|
||||
self.entries.insert(
|
||||
group,
|
||||
(self.tick_count, self.tick_count.wrapping_add(ticks)),
|
||||
);
|
||||
}
|
||||
/// `ItemCooldowns.tick`: the counter, then every entry that has run out,
|
||||
/// which it hands back (`onCooldownEnded`).
|
||||
pub fn tick(&mut self) -> Vec<Arc<str>> {
|
||||
self.tick_count = self.tick_count.wrapping_add(1);
|
||||
let done: Vec<Arc<str>> = self
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|(_, (_, end))| *end <= self.tick_count)
|
||||
.map(|(group, _)| Arc::clone(group))
|
||||
.collect();
|
||||
self.entries.retain(|_, (_, end)| *end > self.tick_count);
|
||||
done
|
||||
}
|
||||
/// `removeCooldown`.
|
||||
pub fn remove(&mut self, group: &str) {
|
||||
self.entries.remove(group);
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn stack(item: &str) -> ItemStack {
|
||||
ItemStack::new(item, 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_percent_falls_from_one_to_zero_over_the_entry() {
|
||||
let mut c = Cooldowns::default();
|
||||
c.add(Arc::from("minecraft:ender_pearl"), 20);
|
||||
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 1.0);
|
||||
for _ in 0..10 {
|
||||
assert!(c.tick().is_empty());
|
||||
}
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.5);
|
||||
// The partial tick moves it within the tick.
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.5), 0.475);
|
||||
for _ in 0..9 {
|
||||
c.tick();
|
||||
}
|
||||
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
|
||||
// ItemCooldowns.tick drops the entry at its end tick, and says so.
|
||||
assert_eq!(c.tick(), [Arc::<str>::from("minecraft:ender_pearl")]);
|
||||
assert!(!c.is_on_cooldown("minecraft:ender_pearl"));
|
||||
assert!(c.is_empty());
|
||||
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_comes_from_the_stack_then_the_item() {
|
||||
let pearl = stack("minecraft:ender_pearl");
|
||||
let default = UseCooldown::from_json(&json!({"seconds": 1.0})).expect("the component");
|
||||
assert_eq!(&*group(&pearl, Some(&default)), "minecraft:ender_pearl");
|
||||
// A stack's own component overrides the item's, group included.
|
||||
let mut grouped = stack("minecraft:ender_pearl");
|
||||
grouped.data_mut().set_other(
|
||||
"minecraft:use_cooldown",
|
||||
Some(Tag::compound([
|
||||
("seconds", Tag::Float(2.0f32.to_bits())),
|
||||
("cooldown_group", Tag::String("minecraft:pearls".into())),
|
||||
])),
|
||||
);
|
||||
let c = component(&grouped, Some(&default)).expect("the stack's component");
|
||||
assert_eq!(c.ticks(), 40);
|
||||
assert_eq!(&*group(&grouped, Some(&default)), "minecraft:pearls");
|
||||
// An item without the component has no cooldown.
|
||||
assert!(component(&stack("minecraft:dirt"), None).is_none());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,61 @@
|
||||
//! Firework explosions (the `firework_explosion` component and its shapes) and
|
||||
//! the dye colours fireworks use.
|
||||
|
||||
/// FireworkExplosion.Shape.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum FireworkShape {
|
||||
#[default]
|
||||
SmallBall,
|
||||
LargeBall,
|
||||
Star,
|
||||
Creeper,
|
||||
Burst,
|
||||
}
|
||||
impl FireworkShape {
|
||||
pub fn from_name(name: &str) -> Self {
|
||||
match name {
|
||||
"large_ball" => Self::LargeBall,
|
||||
"star" => Self::Star,
|
||||
"creeper" => Self::Creeper,
|
||||
"burst" => Self::Burst,
|
||||
_ => Self::SmallBall,
|
||||
}
|
||||
}
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::SmallBall => "small_ball",
|
||||
Self::LargeBall => "large_ball",
|
||||
Self::Star => "star",
|
||||
Self::Creeper => "creeper",
|
||||
Self::Burst => "burst",
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `DyeColor` names and `getFireworkColor`, by dye id (white to black).
|
||||
pub const DYE_FIREWORK_COLORS: [(&str, u32); 16] = [
|
||||
("white", 0xF0F0F0),
|
||||
("orange", 0xEB8844),
|
||||
("magenta", 0xC354CD),
|
||||
("light_blue", 0x6689D3),
|
||||
("yellow", 0xDECF2A),
|
||||
("lime", 0x41CD34),
|
||||
("pink", 0xD88198),
|
||||
("gray", 0x434343),
|
||||
("light_gray", 0xABABAB),
|
||||
("cyan", 0x287697),
|
||||
("purple", 0x7B2FBE),
|
||||
("blue", 0x253192),
|
||||
("brown", 0x51301A),
|
||||
("green", 0x3B511A),
|
||||
("red", 0xB3312C),
|
||||
("black", 0x1E1B1B),
|
||||
];
|
||||
/// The `firework_explosion` component.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FireworkExplosion {
|
||||
pub shape: FireworkShape,
|
||||
pub colors: Vec<u32>,
|
||||
pub fade: Vec<u32>,
|
||||
pub trail: bool,
|
||||
pub twinkle: bool,
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,62 @@
|
||||
//! Item stacks in NBT (`ItemStack.CODEC`): id, count and components, alone or in
|
||||
//! slot lists.
|
||||
use horizon_client_core::nbt_value::{number, string, text};
|
||||
use horizon_world::nbt::Tag;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn encode_item(stack: &crate::items::ItemStack) -> Vec<(&'static str, Tag)> {
|
||||
let mut entries = vec![
|
||||
("id", string(&stack.item)),
|
||||
("count", Tag::Int(stack.count as i32)),
|
||||
];
|
||||
if let Some(components) = crate::item_data::encode_components(stack) {
|
||||
entries.push(("components", components));
|
||||
}
|
||||
entries
|
||||
}
|
||||
/// ItemStack.CODEC (id, count, components).
|
||||
pub fn item_to_nbt(stack: &crate::items::ItemStack) -> Tag {
|
||||
Tag::compound(encode_item(stack))
|
||||
}
|
||||
pub fn item_from_nbt(tag: &Tag) -> Option<crate::items::ItemStack> {
|
||||
let id = text(tag.get("id"))?;
|
||||
if id == "minecraft:air" {
|
||||
return None;
|
||||
}
|
||||
let count = number(tag.get("count"))
|
||||
.or_else(|| number(tag.get("Count")))
|
||||
.unwrap_or(1)
|
||||
.max(1) as u32;
|
||||
let (damage, extra) = crate::item_data::decode_components(tag.get("components"));
|
||||
Some(crate::items::ItemStack {
|
||||
item: Arc::from(id.as_str()),
|
||||
count,
|
||||
damage,
|
||||
extra,
|
||||
})
|
||||
}
|
||||
pub fn encode_items(slots: &[Option<crate::items::ItemStack>]) -> Tag {
|
||||
Tag::List(
|
||||
slots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| {
|
||||
let mut entries = vec![("Slot", Tag::Byte(i as i8))];
|
||||
entries.extend(encode_item(s.as_ref()?));
|
||||
Some(Tag::compound(entries))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
pub fn decode_items(tag: Option<&Tag>, size: usize) -> Vec<Option<crate::items::ItemStack>> {
|
||||
let mut slots = vec![None; size];
|
||||
if let Some(Tag::List(items)) = tag {
|
||||
for it in items {
|
||||
let slot = number(it.get("Slot")).unwrap_or(0) as u8 as usize;
|
||||
if let Some(cell) = slots.get_mut(slot) {
|
||||
*cell = item_from_nbt(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
slots
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
//! Blocks and items as the client knows them, below gameplay: block facts
|
||||
//! (`blocks`), item stacks and definitions (`items`), their data components
|
||||
//! (`item_data`), enchantments, cooldowns, bundles and item stacks in NBT.
|
||||
//! horizon-client re-exports each module under its old path
|
||||
//! (`horizon_client::items`, ...).
|
||||
#![forbid(unsafe_code)]
|
||||
pub mod banner_layer;
|
||||
pub mod blocks;
|
||||
pub mod bundle;
|
||||
pub mod content_namespaces;
|
||||
pub mod cooldowns;
|
||||
pub mod enchant;
|
||||
pub mod firework;
|
||||
pub mod item_data;
|
||||
pub mod item_nbt;
|
||||
pub mod items;
|
||||
pub mod random_sequences;
|
||||
pub mod use_animation;
|
||||
pub use horizon_client_core::Result;
|
||||
@@ -0,0 +1,173 @@
|
||||
//! `RandomSequences`: the named random streams `/random` draws from.
|
||||
use horizon_core::random::{XoroshiroRandom, mix_stafford13, seed_from_hash};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const GOLDEN_RATIO: u64 = 0x9e37_79b9_7f4a_7c15;
|
||||
const SILVER_RATIO: u64 = 0x6a09_e667_f3bc_c909;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RandomSequences {
|
||||
salt: i32,
|
||||
include_world_seed: bool,
|
||||
include_sequence_id: bool,
|
||||
sequences: BTreeMap<String, XoroshiroRandom>,
|
||||
}
|
||||
impl Default for RandomSequences {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
salt: 0,
|
||||
include_world_seed: true,
|
||||
include_sequence_id: true,
|
||||
sequences: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `RandomSequence.createSequence`.
|
||||
fn create(id: &str, world_seed: i64, salt: i32, world: bool, with_id: bool) -> XoroshiroRandom {
|
||||
let seed = (if world { world_seed } else { 0 }) ^ i64::from(salt);
|
||||
let mut lo = seed as u64 ^ SILVER_RATIO;
|
||||
let mut hi = lo.wrapping_add(GOLDEN_RATIO);
|
||||
if with_id {
|
||||
let [a, b] = seed_from_hash(id);
|
||||
lo ^= a;
|
||||
hi ^= b;
|
||||
}
|
||||
XoroshiroRandom::from_state(mix_stafford13(lo), mix_stafford13(hi))
|
||||
}
|
||||
impl RandomSequences {
|
||||
pub fn get(&mut self, id: &str, world_seed: i64) -> &mut XoroshiroRandom {
|
||||
let (salt, w, i) = (self.salt, self.include_world_seed, self.include_sequence_id);
|
||||
self.sequences
|
||||
.entry(id.to_owned())
|
||||
.or_insert_with(|| create(id, world_seed, salt, w, i))
|
||||
}
|
||||
/// Lends sequence `id` out (created if missing); `give_back` returns it.
|
||||
pub fn lend(&mut self, id: &str, world_seed: i64) -> XoroshiroRandom {
|
||||
self.get(id, world_seed);
|
||||
self.sequences.remove(id).expect("created")
|
||||
}
|
||||
pub fn give_back(&mut self, id: String, random: XoroshiroRandom) {
|
||||
self.sequences.insert(id, random);
|
||||
}
|
||||
/// `RandomSequences.CODEC` (`random_sequences.dat`'s data).
|
||||
pub fn to_nbt(&self) -> horizon_world::nbt::Tag {
|
||||
use horizon_world::nbt::Tag;
|
||||
let sequences = self
|
||||
.sequences
|
||||
.iter()
|
||||
.map(|(id, r)| {
|
||||
let (lo, hi) = r.state_words();
|
||||
(
|
||||
id.as_str(),
|
||||
Tag::compound([("source", Tag::LongArray(vec![lo as i64, hi as i64]))]),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Tag::compound([
|
||||
("salt", Tag::Int(self.salt)),
|
||||
(
|
||||
"include_world_seed",
|
||||
Tag::Byte(i8::from(self.include_world_seed)),
|
||||
),
|
||||
(
|
||||
"include_sequence_id",
|
||||
Tag::Byte(i8::from(self.include_sequence_id)),
|
||||
),
|
||||
("sequences", Tag::compound(sequences)),
|
||||
])
|
||||
}
|
||||
pub fn from_nbt(tag: &horizon_world::nbt::Tag) -> Self {
|
||||
use horizon_world::nbt::Tag;
|
||||
let int = |k: &str| match tag.get(k) {
|
||||
Some(Tag::Int(v)) => Some(*v),
|
||||
Some(Tag::Byte(v)) => Some(i32::from(*v)),
|
||||
_ => None,
|
||||
};
|
||||
let mut out = Self {
|
||||
salt: int("salt").unwrap_or(0),
|
||||
include_world_seed: int("include_world_seed").unwrap_or(1) != 0,
|
||||
include_sequence_id: int("include_sequence_id").unwrap_or(1) != 0,
|
||||
sequences: BTreeMap::new(),
|
||||
};
|
||||
if let Some(Tag::Compound(c)) = tag.get("sequences") {
|
||||
for (id, v) in c {
|
||||
let words = match v.get("source") {
|
||||
Some(Tag::LongArray(a)) if a.len() == 2 => Some((a[0] as u64, a[1] as u64)),
|
||||
Some(Tag::List(l)) if l.len() == 2 => match (&l[0], &l[1]) {
|
||||
(Tag::Long(a), Tag::Long(b)) => Some((*a as u64, *b as u64)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
if let Some((lo, hi)) = words {
|
||||
out.sequences
|
||||
.insert(id.to_string_lossy(), XoroshiroRandom::from_state(lo, hi));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn ids(&self) -> Vec<String> {
|
||||
self.sequences.keys().cloned().collect()
|
||||
}
|
||||
pub fn clear(&mut self) -> usize {
|
||||
let n = self.sequences.len();
|
||||
self.sequences.clear();
|
||||
n
|
||||
}
|
||||
pub fn set_defaults(&mut self, salt: i32, include_world_seed: bool, include_sequence_id: bool) {
|
||||
self.salt = salt;
|
||||
self.include_world_seed = include_world_seed;
|
||||
self.include_sequence_id = include_sequence_id;
|
||||
}
|
||||
pub fn reset(&mut self, id: &str, world_seed: i64) {
|
||||
let (salt, w, i) = (self.salt, self.include_world_seed, self.include_sequence_id);
|
||||
self.sequences
|
||||
.insert(id.to_owned(), create(id, world_seed, salt, w, i));
|
||||
}
|
||||
pub fn reset_with(&mut self, id: &str, world_seed: i64, salt: i32, w: bool, i: bool) {
|
||||
self.sequences
|
||||
.insert(id.to_owned(), create(id, world_seed, salt, w, i));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
#[test]
|
||||
fn sequences_are_deterministic_and_resettable() {
|
||||
let mut a = RandomSequences::default();
|
||||
let first: Vec<i32> = (0..4)
|
||||
.map(|_| a.get("minecraft:x", 42).next_int_bound(100).unwrap())
|
||||
.collect();
|
||||
let mut b = RandomSequences::default();
|
||||
let again: Vec<i32> = (0..4)
|
||||
.map(|_| b.get("minecraft:x", 42).next_int_bound(100).unwrap())
|
||||
.collect();
|
||||
assert_eq!(first, again);
|
||||
// Another id or seed gives another stream.
|
||||
let other = RandomSequences::default()
|
||||
.get("minecraft:y", 42)
|
||||
.next_long();
|
||||
let same = RandomSequences::default()
|
||||
.get("minecraft:x", 42)
|
||||
.next_long();
|
||||
assert_ne!(other, same);
|
||||
// Reset restarts it.
|
||||
a.reset("minecraft:x", 42);
|
||||
assert_eq!(
|
||||
a.get("minecraft:x", 42).next_int_bound(100).unwrap(),
|
||||
first[0]
|
||||
);
|
||||
// Defaults change what new sequences start from.
|
||||
a.set_defaults(7, false, false);
|
||||
a.reset("minecraft:x", 42);
|
||||
let v = a.get("minecraft:x", 1).next_long();
|
||||
let mut c = RandomSequences::default();
|
||||
c.set_defaults(7, false, false);
|
||||
assert_eq!(c.get("minecraft:z", 999).next_long(), v);
|
||||
assert_eq!(a.clear(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! The use animation a `consumable` component names.
|
||||
|
||||
pub fn consumable_animation(v: &serde_json::Value) -> horizon_world::consumable::UseAnimation {
|
||||
use horizon_world::consumable::UseAnimation;
|
||||
match v
|
||||
.get("animation")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("eat")
|
||||
{
|
||||
"eat" => UseAnimation::Eat,
|
||||
"drink" => UseAnimation::Drink,
|
||||
_ => UseAnimation::None,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user