Merge parity/assets into parity-base

# Conflicts:
#	crates/horizon-client/src/game.rs
This commit is contained in:
Ludovic Marie
2026-10-11 14:09:10 +02:00
20 changed files with 2817 additions and 1253 deletions
+464
View File
@@ -0,0 +1,464 @@
//! Atlas sprite sources (`SpriteSourceList`): the `atlases/*.json`
//! definitions listing which sprites an atlas holds. `directory`, `single`,
//! `filter`, `unstitch` and `paletted_permutations` sources run in order
//! against the resource tree; a later source replaces an earlier sprite of
//! the same id and a filter removes the matching ones.
use crate::packs::pattern::Pattern;
use horizon_assets::palette::apply_palette;
use serde_json::Value;
use std::{
collections::BTreeMap,
fs,
path::{Path, PathBuf},
};
/// One region of an `unstitch` source, in units of the divisors.
#[derive(Clone, Debug, PartialEq)]
pub struct Region {
pub sprite: String,
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
#[derive(Clone, Debug)]
pub enum SpriteSource {
Directory {
source: String,
prefix: String,
},
Single {
resource: String,
sprite: Option<String>,
},
Filter {
namespace: Option<Pattern>,
path: Option<Pattern>,
},
Unstitch {
resource: String,
regions: Vec<Region>,
divisor_x: f64,
divisor_y: f64,
},
PalettedPermutations {
textures: Vec<String>,
palette_key: String,
permutations: BTreeMap<String, String>,
separator: String,
},
}
/// Where a listed sprite's pixels come from.
#[derive(Clone, Debug, PartialEq)]
pub enum SpriteOrigin {
/// A whole texture (`textures/<path>.png`), by texture identifier.
File(String),
/// `Unstitcher.RegionInstance`: part of a texture.
Region {
texture: String,
region: Region,
divisor_x: f64,
divisor_y: f64,
},
/// `PalettedSpriteSupplier`: a texture with its colours remapped.
Paletted {
texture: String,
palette_key: String,
palette: String,
},
}
/// `Identifier.parse` default namespace.
pub fn qualified(id: &str) -> String {
if id.contains(':') {
id.to_owned()
} else {
format!("minecraft:{id}")
}
}
fn string(v: &Value, key: &str) -> Option<String> {
v.get(key)?.as_str().map(str::to_owned)
}
fn number(v: &Value, key: &str, default: f64) -> Option<f64> {
match v.get(key) {
None => Some(default),
Some(n) => n.as_f64(),
}
}
/// `SpriteSources.FILE_CODEC`: the `sources` list of an atlas definition.
/// A malformed source fails the whole file, as the codec does.
pub fn decode(text: &str) -> Option<Vec<SpriteSource>> {
let json: Value = serde_json::from_str(text).ok()?;
json.get("sources")?
.as_array()?
.iter()
.map(decode_source)
.collect()
}
fn decode_source(s: &Value) -> Option<SpriteSource> {
Some(match qualified(s.get("type")?.as_str()?).as_str() {
"minecraft:directory" => SpriteSource::Directory {
source: string(s, "source")?,
prefix: string(s, "prefix")?,
},
"minecraft:single" => SpriteSource::Single {
resource: qualified(&string(s, "resource")?),
sprite: match s.get("sprite") {
None => None,
Some(v) => Some(qualified(v.as_str()?)),
},
},
"minecraft:filter" => {
let p = s.get("pattern")?;
let pattern = |key: &str| -> Option<Option<Pattern>> {
match p.get(key) {
None => Some(None),
Some(v) => Pattern::new(v.as_str()?).map(Some),
}
};
SpriteSource::Filter {
namespace: pattern("namespace")?,
path: pattern("path")?,
}
}
"minecraft:unstitch" => {
let regions = s
.get("regions")?
.as_array()?
.iter()
.map(|r| {
Some(Region {
sprite: qualified(&string(r, "sprite")?),
x: r.get("x")?.as_f64()?,
y: r.get("y")?.as_f64()?,
width: r.get("width")?.as_f64()?,
height: r.get("height")?.as_f64()?,
})
})
.collect::<Option<Vec<_>>>()?;
if regions.is_empty() {
return None;
}
SpriteSource::Unstitch {
resource: qualified(&string(s, "resource")?),
regions,
divisor_x: number(s, "divisor_x", 1.0)?,
divisor_y: number(s, "divisor_y", 1.0)?,
}
}
"minecraft:paletted_permutations" => SpriteSource::PalettedPermutations {
textures: s
.get("textures")?
.as_array()?
.iter()
.map(|t| t.as_str().map(qualified))
.collect::<Option<_>>()?,
palette_key: qualified(&string(s, "palette_key")?),
permutations: s
.get("permutations")?
.as_object()?
.iter()
.map(|(k, v)| Some((k.clone(), qualified(v.as_str()?))))
.collect::<Option<_>>()?,
separator: match s.get("separator") {
None => "_".to_owned(),
Some(v) => v.as_str()?.to_owned(),
},
},
_ => return None,
})
}
/// The texture files of a resource tree: `namespace:path` for every
/// `assets/<namespace>/textures/<path>.png`.
pub fn list_textures(root: &Path) -> Vec<String> {
let mut out = Vec::new();
let Ok(namespaces) = fs::read_dir(root.join("assets")) else {
return out;
};
for ns in namespaces.flatten() {
let namespace = ns.file_name().to_string_lossy().into_owned();
let base = ns.path().join("textures");
let mut stack = vec![base.clone()];
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
stack.push(p);
} else if p.extension().is_some_and(|x| x == "png")
&& let Ok(rel) = p.strip_prefix(&base)
{
let rel = rel.with_extension("").to_string_lossy().replace('\\', "/");
out.push(format!("{namespace}:{rel}"));
}
}
}
}
out.sort();
out
}
/// The file of a texture identifier.
pub fn texture_path(root: &Path, texture: &str, directory: &str) -> PathBuf {
let (namespace, path) = texture.split_once(':').unwrap_or(("minecraft", texture));
root.join(format!("assets/{namespace}/{directory}/{path}.png"))
}
/// `SpriteSourceList.list`: every sprite id of the atlas and its origin.
/// `textures` are the available texture identifiers ([`list_textures`]).
pub fn list(sources: &[SpriteSource], textures: &[String]) -> BTreeMap<String, SpriteOrigin> {
let mut out = BTreeMap::new();
let exists = |t: &str| textures.binary_search_by(|x| x.as_str().cmp(t)).is_ok();
for source in sources {
match source {
SpriteSource::Directory { source, prefix } => {
// FileToIdConverter("textures/" + source, ".png").
let dir = format!("{source}/");
for t in textures {
let (namespace, path) = t.split_once(':').unwrap_or(("minecraft", t));
if let Some(rest) = path.strip_prefix(&dir) {
out.insert(
format!("{namespace}:{prefix}{rest}"),
SpriteOrigin::File(t.clone()),
);
}
}
}
SpriteSource::Single { resource, sprite } => {
if exists(resource) {
out.insert(
sprite.clone().unwrap_or_else(|| resource.clone()),
SpriteOrigin::File(resource.clone()),
);
}
}
SpriteSource::Filter { namespace, path } => {
out.retain(|id: &String, _| {
let (ns, p) = id.split_once(':').unwrap_or(("minecraft", id));
!(namespace.as_ref().is_none_or(|m| m.is_match(ns))
&& path.as_ref().is_none_or(|m| m.is_match(p)))
});
}
SpriteSource::Unstitch {
resource,
regions,
divisor_x,
divisor_y,
} => {
if exists(resource) {
for region in regions {
out.insert(
region.sprite.clone(),
SpriteOrigin::Region {
texture: resource.clone(),
region: region.clone(),
divisor_x: *divisor_x,
divisor_y: *divisor_y,
},
);
}
}
}
SpriteSource::PalettedPermutations {
textures: bases,
palette_key,
permutations,
separator,
} => {
for base in bases {
if !exists(base) {
continue;
}
for (suffix, palette) in permutations {
out.insert(
format!("{base}{separator}{suffix}"),
SpriteOrigin::Paletted {
texture: base.clone(),
palette_key: palette_key.clone(),
palette: palette.clone(),
},
);
}
}
}
}
}
out
}
/// An RGBA image.
pub type Image = (u32, u32, Vec<u8>);
fn argb(rgba: &[u8]) -> Vec<u32> {
rgba.as_chunks::<4>()
.0
.iter()
.map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]]))
.collect()
}
/// The pixels of a generated sprite (`Region` or `Paletted`); `None` for a
/// plain file, which loads as itself.
pub fn generate(
origin: &SpriteOrigin,
load: &dyn Fn(&str, &str) -> Option<Image>,
) -> Option<Image> {
match origin {
SpriteOrigin::File(_) => None,
SpriteOrigin::Region {
texture,
region,
divisor_x,
divisor_y,
} => {
let (w, h, pixels) = load(texture, "textures")?;
let x_scale = f64::from(w) / divisor_x;
let y_scale = f64::from(h) / divisor_y;
let x = (region.x * x_scale).floor() as i64;
let y = (region.y * y_scale).floor() as i64;
let width = (region.width * x_scale).floor() as i64;
let height = (region.height * y_scale).floor() as i64;
if width <= 0 || height <= 0 {
return None;
}
let mut out = vec![0u8; (width * height * 4) as usize];
for row in 0..height {
for col in 0..width {
let (sx, sy) = (x + col, y + row);
if sx < 0 || sy < 0 || sx >= i64::from(w) || sy >= i64::from(h) {
continue;
}
let s = ((sy * i64::from(w) + sx) * 4) as usize;
let d = ((row * width + col) * 4) as usize;
out[d..d + 4].copy_from_slice(&pixels[s..s + 4]);
}
}
Some((width as u32, height as u32, out))
}
SpriteOrigin::Paletted {
texture,
palette_key,
palette,
} => {
let (w, h, pixels) = load(texture, "textures")?;
let (_, _, key) = load(palette_key, "textures/palettes")?;
let (_, _, target) = load(palette, "textures/palettes")?;
let mut mapped = argb(&pixels);
apply_palette(&mut mapped, &argb(&key), &argb(&target))?;
let out = mapped
.iter()
.flat_map(|p| {
let [a, r, g, b] = p.to_be_bytes();
[r, g, b, a]
})
.collect();
Some((w, h, out))
}
}
}
/// Every atlas definition of a resource tree (`atlases/*.json` in every
/// namespace), by atlas id.
pub fn atlases(root: &Path) -> BTreeMap<String, Vec<SpriteSource>> {
let mut out = BTreeMap::new();
let Ok(namespaces) = fs::read_dir(root.join("assets")) else {
return out;
};
for ns in namespaces.flatten() {
let namespace = ns.file_name().to_string_lossy().into_owned();
let Ok(files) = fs::read_dir(ns.path().join("atlases")) else {
continue;
};
for f in files.flatten() {
let path = f.path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let name = path.file_stem().unwrap_or_default().to_string_lossy();
if let Some(sources) = fs::read_to_string(&path).ok().and_then(|t| decode(&t)) {
out.insert(format!("{namespace}:{name}"), sources);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn textures() -> Vec<String> {
let mut t: Vec<String> = [
"minecraft:item/apple",
"minecraft:item/stick",
"minecraft:trims/items/boots_trim",
"minecraft:block/stone",
"minecraft:entity/sheet",
]
.iter()
.map(|s| s.to_string())
.collect();
t.sort();
t
}
#[test]
fn sources_run_in_order() {
let sources = decode(
r#"{"sources":[
{"type":"directory","source":"item","prefix":"item/"},
{"type":"minecraft:single","resource":"block/stone","sprite":"item/stone"},
{"type":"filter","pattern":{"path":"stick"}},
{"type":"unstitch","resource":"entity/sheet","divisor_x":2,"regions":[{"sprite":"a","x":1,"y":0,"width":1,"height":1}]},
{"type":"paletted_permutations","textures":["trims/items/boots_trim"],"palette_key":"trims/color_palettes/trim_palette","permutations":{"quartz":"trims/color_palettes/quartz"}}
]}"#,
)
.unwrap();
let listed = list(&sources, &textures());
let ids: Vec<&str> = listed.keys().map(String::as_str).collect();
assert_eq!(
ids,
[
"minecraft:a",
"minecraft:item/apple",
"minecraft:item/stone",
"minecraft:trims/items/boots_trim_quartz"
]
);
assert_eq!(
listed["minecraft:item/stone"],
SpriteOrigin::File("minecraft:block/stone".into())
);
}
#[test]
fn malformed_sources_fail_the_file() {
assert!(decode(r#"{"sources":[{"type":"directory","source":"item"}]}"#).is_none());
assert!(
decode(r#"{"sources":[{"type":"unstitch","resource":"x","regions":[]}]}"#).is_none()
);
assert!(decode(r#"{"sources":[{"type":"horizon"}]}"#).is_none());
}
#[test]
fn unstitch_cuts_by_divisor() {
let pixels: Vec<u8> = (0..16u8).flat_map(|i| [i, i, i, 255]).collect();
let load = |_: &str, _: &str| Some((4u32, 4u32, pixels.clone()));
let origin = SpriteOrigin::Region {
texture: "t".into(),
region: Region {
sprite: "s".into(),
x: 1.0,
y: 1.0,
width: 1.0,
height: 1.0,
},
divisor_x: 2.0,
divisor_y: 2.0,
};
let (w, h, out) = generate(&origin, &load).unwrap();
assert_eq!((w, h), (2, 2));
assert_eq!(out[0], 10);
assert_eq!(out[4], 11);
assert_eq!(out[8], 14);
}
}
+40 -570
View File
@@ -34,6 +34,7 @@ mod game_mode;
mod ghasts;
mod golems;
mod growth;
mod item_draw;
mod jukebox;
mod lan;
mod lan_actions;
@@ -290,16 +291,6 @@ enum Screen {
/// WorldOptionsScreen (game/lan_screen.rs).
WorldOptions,
}
#[derive(Clone)]
enum Icon {
Flat(String),
Cube {
top: String,
left: String,
right: String,
tint: u32,
},
}
struct Mining {
pos: [i32; 3],
progress: f32,
@@ -493,7 +484,6 @@ pub struct Resources {
biomes: Arc<Biomes>,
environment: Environment,
atlas: HudAtlas,
icons: HashMap<String, Option<Icon>>,
layer_names: HashMap<u32, String>,
mob_types: HashMap<String, Arc<MobType>>,
mob_data: horizon_client::mobs::MobData,
@@ -514,8 +504,8 @@ pub struct Resources {
threads: usize,
player_arm: Option<horizon_client::mobs::Part>,
player_type: Option<Arc<horizon_client::mobs::MobType>>,
/// firstperson_righthand display transforms per item: (rotation, translation, scale).
displays: HashMap<String, Option<([f32; 3], [f32; 3], [f32; 3])>>,
/// Item definitions, baked item models and special renderers.
item_renderer: Arc<horizon_client::item_render::ItemRenderer>,
/// Enchantments, workstation recipes and brewing (game/stations.rs).
stations: horizon_client::stations::StationData,
}
@@ -985,37 +975,6 @@ impl Game<'_> {
}
Some(stack)
}
/// The block's particle texture (approximated by its first model face) and tint.
/// The `particle` texture of a block's first blockstate model (for models without faces).
fn model_particle(&self, block: &str) -> Option<String> {
let root = &self.options.resources;
let read = |path: String| -> Option<serde_json::Value> {
serde_json::from_slice(&std::fs::read(root.join(path)).ok()?).ok()
};
let states = read(format!("assets/minecraft/blockstates/{block}.json"))?;
let mut model = states["variants"]
.as_object()?
.values()
.next()
.and_then(|v| v["model"].as_str().or_else(|| v[0]["model"].as_str()))?
.to_owned();
for _ in 0..8 {
let m = read(format!(
"assets/minecraft/models/{}.json",
model.trim_start_matches("minecraft:")
))?;
if let Some(p) = m["textures"]["particle"].as_str() {
let p = if let Some(alias) = p.strip_prefix('#') {
m["textures"][alias].as_str()?
} else {
p
};
return Some(p.trim_start_matches("minecraft:").to_owned());
}
model = m["parent"].as_str()?.to_owned();
}
None
}
fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> {
let models = self
.res
@@ -2156,7 +2115,15 @@ impl Game<'_> {
0.5 + 0.5 * self.world.random.next_int_bound(2).unwrap_or(0) as f32,
pitch,
);
if let Some(Icon::Flat(sprite)) = self.icon(&stack.item) {
// `ItemParticleOption`: the particle material of a random layer of
// the stack resolved for the ground (`BreakingItemParticle`).
let state = self.resolve_item(
&stack,
horizon_assets::item_model::DisplayContext::Ground,
None,
0,
);
if let Some(sprite) = state.pick_particle(&mut self.world.random) {
let (yaw, pitch) = (
f64::from(self.yaw).to_radians(),
f64::from(self.pitch).to_radians(),
@@ -2826,231 +2793,11 @@ impl Game<'_> {
}
window.set_cursor_visible(!self.captured);
}
fn icon(&mut self, item: &str) -> Option<Icon> {
if let Some(icon) = self.res.icons.get(item) {
return icon.clone();
}
let icon = self.resolve_icon(item);
self.res.icons.insert(item.to_owned(), icon.clone());
icon
}
fn resolve_icon(&self, item: &str) -> Option<Icon> {
let root = &self.options.resources;
let name = item.trim_start_matches("minecraft:");
let info = self.res.items.get(item);
let model_name = info.map_or(name.to_owned(), |i| {
i.model.trim_start_matches("minecraft:").to_owned()
});
let def: serde_json::Value = serde_json::from_slice(
&std::fs::read(root.join(format!("assets/minecraft/items/{model_name}.json"))).ok()?,
)
.ok()?;
// Find the first plain model reference in the item model definition.
fn first_model(v: &serde_json::Value) -> Option<String> {
match v {
serde_json::Value::Object(o) => {
if o.get("type").and_then(|t| t.as_str()) == Some("minecraft:model") {
return o.get("model").and_then(|m| m.as_str()).map(str::to_owned);
}
// A display_context select: the inventory shows the `gui` case.
if o.get("property").and_then(|t| t.as_str())
== Some("minecraft:display_context")
&& let Some(case) =
o.get("cases").and_then(|c| c.as_array()).and_then(|cases| {
cases.iter().find(|c| match &c["when"] {
serde_json::Value::String(w) => w == "gui",
serde_json::Value::Array(ws) => ws.iter().any(|w| w == "gui"),
_ => false,
})
})
{
return first_model(&case["model"]);
}
for key in [
"model", "fallback", "on_false", "on_true", "cases", "entries", "tints",
] {
if let Some(m) = o.get(key).and_then(first_model) {
return Some(m);
}
}
o.values().find_map(first_model)
}
serde_json::Value::Array(a) => a.iter().find_map(first_model),
_ => None,
}
}
let Some(model) = first_model(&def["model"]) else {
// Special item models (chests, beds, banners...): show the block's particle texture.
let block = self
.res
.assets
.registry
.default_state(item)
.or_else(|| info.and_then(|i| i.block))?;
let (sprite, tint) = self
.particle_sprite(block)
.or_else(|| self.model_particle(name).map(|s| (s, 0xFFFFFF)))?;
return Some(Icon::Cube {
top: sprite.clone(),
left: sprite.clone(),
right: sprite,
tint,
});
};
let path = model.trim_start_matches("minecraft:").to_owned();
let mut current = path.clone();
let mut textures = serde_json::Map::new();
for _ in 0..16 {
let text =
std::fs::read(root.join(format!("assets/minecraft/models/{current}.json"))).ok()?;
let m: serde_json::Value = serde_json::from_slice(&text).ok()?;
if let Some(t) = m["textures"].as_object() {
for (k, v) in t {
textures.entry(k.clone()).or_insert(v.clone());
}
}
match m["parent"].as_str() {
Some(p)
if p.ends_with("item/generated")
|| p.ends_with("item/handheld")
|| p.contains("handheld") =>
{
let layer = textures.get("layer0")?.as_str()?;
return Some(Icon::Flat(
layer.trim_start_matches("minecraft:").to_owned(),
));
}
Some(p) => current = p.trim_start_matches("minecraft:").to_owned(),
None => break,
}
}
if path.starts_with("block/") {
let block = self
.res
.assets
.registry
.default_state(&format!("minecraft:{name}"))
.or_else(|| info.and_then(|i| i.block))?;
let models = self
.res
.assets
.model_catalog
.collect(block, horizon_core::position::BlockPos::new(0, 0, 0))
.ok()?;
let mut faces: HashMap<usize, (u32, i32)> = HashMap::new();
for (_, m) in &models {
for f in &m.faces {
faces
.entry(f.quad.facing as usize)
.or_insert((f.layer, f.quad.tint_index));
}
}
use horizon_assets::model::Direction as D;
let get = |d: D| {
faces
.get(&(d as usize))
.and_then(|(l, _)| self.res.layer_names.get(l))
.cloned()
};
let top = get(D::Up)?;
let tinted = faces.get(&(D::Up as usize)).is_some_and(|(_, t)| *t >= 0);
let tint = if tinted {
if name.contains("leaves") || name == "vine" {
0x48B518
} else {
0x91BD59
}
} else {
0xFFFFFF
};
return Some(Icon::Cube {
left: get(D::South).unwrap_or(top.clone()),
right: get(D::East).unwrap_or(top.clone()),
top,
tint,
});
}
textures
.get("layer0")
.or_else(|| textures.get("all"))
.or_else(|| textures.get("texture"))
.and_then(|t| t.as_str())
.map(|t| Icon::Flat(t.trim_start_matches("minecraft:").to_owned()))
}
fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
// Special-model items: the shield and banners draw their own 3D icon.
let banner = if &*stack.item == "minecraft:shield" {
let passes = shield::shield_passes(&self.res.stations.banners, stack);
shield::draw_shield_icon(batch, &self.res.atlas, x, y, &passes);
true
} else {
self.draw_banner_icon(batch, stack, x, y)
};
let icon = if banner { None } else { self.icon(&stack.item) };
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
// special renderers included), then the decorations.
self.draw_item_model(batch, stack, x, y);
let atlas = &self.res.atlas;
match icon {
None if banner => {}
Some(Icon::Flat(name)) => batch.sprite_scaled(atlas, &name, x, y, 16.0, 16.0, u32::MAX),
Some(Icon::Cube {
top,
left,
right,
tint,
}) => {
let color = |b: f32| {
let c = |s: u32| (((tint >> s) & 255) as f32 * b) as u8;
rgba(c(16), c(8), c(0), 255)
};
let (cx, top_y) = (x + 8.0, y + 1.0);
let quad = |batch: &mut HudBatch, name: &str, p: [[f32; 2]; 4], c: u32| {
if let Some(r) = atlas.sprites.get(name).copied() {
batch.quad(
p,
[[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]],
c,
);
}
};
let (w, h) = (7.0, 3.6);
quad(
batch,
&top,
[
[cx, top_y],
[cx + w, top_y + h],
[cx, top_y + 2.0 * h],
[cx - w, top_y + h],
],
color(1.0),
);
let side = 8.0;
quad(
batch,
&left,
[
[cx - w, top_y + h],
[cx, top_y + 2.0 * h],
[cx, top_y + 2.0 * h + side],
[cx - w, top_y + h + side],
],
color(0.8),
);
quad(
batch,
&right,
[
[cx, top_y + 2.0 * h],
[cx + w, top_y + h],
[cx + w, top_y + h + side],
[cx, top_y + 2.0 * h + side],
],
color(0.6),
);
}
None => batch.fill(atlas, x + 2.0, y + 2.0, 12.0, 12.0, rgba(200, 0, 200, 255)),
}
self.draw_potion_layers(batch, stack, x, y);
self.draw_glint(batch, stack, x, y);
if stack.count > 1 {
let text = stack.count.to_string();
let w = HudBatch::text_width(atlas, &text);
@@ -4209,147 +3956,8 @@ impl Game<'_> {
/// ItemEntityRenderer: items bob and spin; blocks render as small cubes.
fn entity_geometry(&mut self, camera: glam::DVec3, alpha: f64) -> Vec<Vertex> {
let mut out = Vec::new();
let items = self.dropped.clone();
for item in &items {
let p = item.previous;
let q = item.position;
let pos = glam::DVec3::new(
p.x + (q.x - p.x) * alpha,
p.y + (q.y - p.y) * alpha,
p.z + (q.z - p.z) * alpha,
) - camera;
if pos.length_squared() > 64.0 * 64.0 {
continue;
}
let age = item.age as f32 + alpha as f32;
let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1;
let spin = age / 20.0 + item.bob_offset;
let light = self.world.light(
q.x.floor() as i32,
(q.y + 0.1).floor() as i32,
q.z.floor() as i32,
);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let center = pos.as_vec3() + glam::Vec3::new(0.0, bob + 0.125, 0.0);
let rot = glam::Mat3::from_rotation_y(spin);
let icon = self.icon(&item.stack.item);
let atlas = &self.res.atlas;
let mut quad = |corners: [glam::Vec3; 4], name: &str, shade: f32, tint: u32| {
let Some(r) = atlas.sprites.get(name).copied() else {
return;
};
let uv = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]];
let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32;
let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16);
for (corner, uv) in corners.iter().zip(uv) {
let v = center + rot * *corner;
out.push(Vertex {
pos: v.to_array(),
uv,
layer: 0,
color,
light: packed,
});
}
};
let copies = match item.stack.count {
0..=1 => 1,
2..=16 => 2,
17..=32 => 3,
_ => 4,
};
for k in 0..copies {
let o = glam::Vec3::new(k as f32 * 0.03, k as f32 * 0.03, k as f32 * 0.05);
match &icon {
Some(Icon::Cube {
top,
left,
right,
tint,
}) => {
let h = 0.125;
let v = |x: f32, y: f32, z: f32| glam::Vec3::new(x * h, y * h, z * h) + o;
quad(
[
v(-1., 1., 1.),
v(1., 1., 1.),
v(1., 1., -1.),
v(-1., 1., -1.),
],
top,
1.0,
*tint,
);
quad(
[
v(-1., -1., -1.),
v(1., -1., -1.),
v(1., -1., 1.),
v(-1., -1., 1.),
],
top,
0.5,
*tint,
);
quad(
[
v(-1., -1., 1.),
v(1., -1., 1.),
v(1., 1., 1.),
v(-1., 1., 1.),
],
left,
0.8,
0xFFFFFF,
);
quad(
[
v(1., -1., -1.),
v(-1., -1., -1.),
v(-1., 1., -1.),
v(1., 1., -1.),
],
left,
0.8,
0xFFFFFF,
);
quad(
[
v(1., -1., 1.),
v(1., -1., -1.),
v(1., 1., -1.),
v(1., 1., 1.),
],
right,
0.6,
0xFFFFFF,
);
quad(
[
v(-1., -1., -1.),
v(-1., -1., 1.),
v(-1., 1., 1.),
v(-1., 1., -1.),
],
right,
0.6,
0xFFFFFF,
);
}
Some(Icon::Flat(name)) => {
let h = 0.25;
let v = |x: f32, y: f32| glam::Vec3::new(x * h, y * h + 0.125, 0.0) + o;
quad(
[v(-1., -1.), v(1., -1.), v(1., 1.), v(-1., 1.)],
name,
1.0,
0xFFFFFF,
);
}
None => {}
}
}
}
// `ItemEntityRenderer`.
self.dropped_item_geometry(camera, alpha, &mut out);
// Mobs and their projectiles.
self.mob_geometry(camera, alpha, &mut out);
self.player_model_geometry(camera, alpha, &mut out);
@@ -6501,67 +6109,6 @@ impl Game<'_> {
self.hand_item = held;
}
}
fn display_transform(&mut self, item: &str) -> Option<([f32; 3], [f32; 3], [f32; 3])> {
if let Some(d) = self.res.displays.get(item) {
return *d;
}
let root = &self.options.resources;
let name = item.trim_start_matches("minecraft:");
let model_name = self.res.items.get(item).map_or(name.to_owned(), |i| {
i.model.trim_start_matches("minecraft:").to_owned()
});
let mut found = None;
let def: Option<serde_json::Value> =
std::fs::read(root.join(format!("assets/minecraft/items/{model_name}.json")))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok());
let mut current = def.and_then(|d| {
fn first(v: &serde_json::Value) -> Option<String> {
match v {
serde_json::Value::Object(o) => {
if o.get("type").and_then(|t| t.as_str()) == Some("minecraft:model") {
return o.get("model").and_then(|m| m.as_str()).map(str::to_owned);
}
o.values().find_map(first)
}
serde_json::Value::Array(a) => a.iter().find_map(first),
_ => None,
}
}
first(&d["model"])
});
if item.ends_with("_banner") {
// The banner item model is a special renderer over this base model.
current = Some("minecraft:item/template_banner".to_owned());
}
for _ in 0..16 {
let Some(m) = current.take() else { break };
let path = m.trim_start_matches("minecraft:").to_owned();
let Some(model) =
std::fs::read(root.join(format!("assets/minecraft/models/{path}.json")))
.ok()
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
else {
break;
};
let d = &model["display"]["firstperson_righthand"];
if d.is_object() {
let v = |k: &str, default: f32| -> [f32; 3] {
let a = d[k].as_array();
std::array::from_fn(|i| {
a.and_then(|a| a.get(i))
.and_then(|x| x.as_f64())
.map_or(default, |x| x as f32)
})
};
found = Some((v("rotation", 0.0), v("translation", 0.0), v("scale", 1.0)));
break;
}
current = model["parent"].as_str().map(str::to_owned);
}
self.res.displays.insert(item.to_owned(), found);
found
}
/// FirstPersonHandsAndItemsRenderer: the right arm or held item in view
/// space, converted to camera-relative world space.
fn hand_geometry(&mut self, alpha: f64) -> Vec<Vertex> {
@@ -6657,115 +6204,39 @@ impl Game<'_> {
);
}
Some(stack) => {
let display = self
.display_transform(&stack.item)
.unwrap_or(([0.0; 3], [0.0; 3], [1.0; 3]));
let icon = self.icon(&stack.item);
// applyItemArmTransform + swingArm (applyItemArmAttackTransform)
let x = -0.4 * (sqrt_attack * std::f32::consts::PI).sin();
let y = 0.2 * (sqrt_attack * std::f32::consts::TAU).sin();
let z = -0.2 * (attack * std::f32::consts::PI).sin();
let y_swing_rot = (attack * attack * std::f32::consts::PI).sin();
let xz_swing_rot = (sqrt_attack * std::f32::consts::PI).sin();
let (rot, trans, scale) = display;
let m = to_world
* glam::Mat4::from_translation(glam::Vec3::new(0.56, -0.52 + inverse_height * -0.6, -0.72))
* glam::Mat4::from_translation(glam::Vec3::new(
0.56,
-0.52 + inverse_height * -0.6,
-0.72,
))
* glam::Mat4::from_translation(glam::Vec3::new(x, y, z))
* glam::Mat4::from_rotation_y(deg(45.0 + y_swing_rot * -20.0))
* glam::Mat4::from_rotation_z(deg(xz_swing_rot * -20.0))
* glam::Mat4::from_rotation_x(deg(xz_swing_rot * -80.0))
* glam::Mat4::from_rotation_y(deg(-45.0))
// ItemTransform.apply: translation is in sixteenths, rotation XYZ, then scale.
* glam::Mat4::from_translation(glam::Vec3::from(trans) / 16.0)
* glam::Mat4::from_quat(glam::Quat::from_euler(glam::EulerRot::XYZ, deg(rot[0]), deg(rot[1]), deg(rot[2])))
* glam::Mat4::from_scale(glam::Vec3::from(scale))
* glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
if self.held_banner_geometry(m, &stack, packed, &mut out) {
return out;
}
let atlas = &self.res.atlas;
let quad = |corners: [glam::Vec3; 4],
name: &str,
shade: f32,
tint: u32,
out: &mut Vec<Vertex>| {
let Some(r) = atlas.sprites.get(name).copied() else {
return;
};
let uv = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]];
let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32;
let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16);
for (p, uv) in corners.iter().zip(uv) {
out.push(Vertex {
pos: m.transform_point3(*p).to_array(),
uv,
layer: 0,
color,
light: packed,
});
}
};
let v = glam::Vec3::new;
match icon {
Some(Icon::Cube {
top,
left,
right,
tint,
}) => {
quad(
[v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)],
&top,
1.0,
tint,
&mut out,
);
quad(
[v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)],
&left,
0.8,
0xFFFFFF,
&mut out,
);
quad(
[v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)],
&left,
0.8,
0xFFFFFF,
&mut out,
);
quad(
[v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)],
&right,
0.6,
0xFFFFFF,
&mut out,
);
quad(
[v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)],
&right,
0.6,
0xFFFFFF,
&mut out,
);
}
Some(Icon::Flat(name)) => {
// Generated item models are a sprite on the z = 8/16 plane.
quad(
[
v(0., 0., 0.5),
v(1., 0., 0.5),
v(1., 1., 0.5),
v(0., 1., 0.5),
],
&name,
1.0,
0xFFFFFF,
&mut out,
);
}
None => {}
}
* glam::Mat4::from_rotation_y(deg(-45.0));
// `ItemInHandRenderer.renderItem`: the player as owner, seeded by
// its id plus the display context ordinal.
let owner = self.player_owner(Some(&stack));
let context = horizon_assets::item_model::DisplayContext::FirstPersonRightHand;
let state = self.resolve_item(&stack, context, Some(&owner), 4);
let light = self.world.light(
eye[0].floor() as i32,
eye[1].floor() as i32,
eye[2].floor() as i32,
);
self.submit_item_world(
&state,
m,
horizon_client::block_entity_render::vertex_light(light),
&mut out,
);
}
}
out
@@ -8374,7 +7845,7 @@ pub fn run() -> Result<()> {
biomes,
environment,
atlas,
icons: HashMap::new(),
item_renderer: Arc::new(horizon_client::item_render::ItemRenderer::load(&root)?),
layer_names,
providers: Providers::load(&root),
block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load(
@@ -8412,7 +7883,6 @@ pub fn run() -> Result<()> {
player_type: perspective::player_type(&root),
player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main")
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
displays: HashMap::new(),
};
let inventory = vec![None; 36];
let now = Instant::now();
@@ -415,6 +415,8 @@ impl Game<'_> {
pose[5] = deg(rot[2]);
}
}
// Item layers pose from the hidden arms too (`visible` only skips drawing).
let posed = poses.clone();
let mut hide = |name: &str| {
if poses.has(name) {
let pose = poses.get(name);
@@ -446,6 +448,7 @@ impl Game<'_> {
0,
out,
);
self.armor_stand_items(a, model, base, &posed, packed, out);
// HumanoidArmorLayer: head, chest, legs, feet.
for (slot, layer) in [
(5usize, "helmet"),
@@ -562,3 +565,120 @@ impl Game<'_> {
true
}
}
impl Game<'_> {
/// `ItemInHandLayer` and `CustomHeadLayer` of an armour stand: the hand
/// items in the third-person contexts, and a non-armour head item on the
/// head (`translateToHead`: down a quarter, turned, 0.625 scale).
fn armor_stand_items(
&self,
a: &ArmorStand,
model: &Part,
base: glam::Mat4,
poses: &Poses,
light: u32,
out: &mut Vec<Vertex>,
) {
use horizon_assets::item_model::DisplayContext;
use horizon_client::mobs::render::part_matrix;
let owner = super::item_draw::owner_at(
[a.position.x, a.position.y, a.position.z],
a.yaw,
"minecraft:armor_stand",
);
// `useBabyOffset`: small stands use the baby hand offsets.
let (ox, oy, oz) = if a.small {
(0.0, 1.0, -4.5)
} else {
(1.0, 2.0, -10.0)
};
for (slot, left, context) in [
(0usize, false, DisplayContext::ThirdPersonRightHand),
(1, true, DisplayContext::ThirdPersonLeftHand),
] {
let Some(stack) = &a.equipment[slot] else {
continue;
};
let arm = if left { "left_arm" } else { "right_arm" };
let Some(hand) = part_matrix(model, base, poses, arm, 0.0) else {
continue;
};
let pose = hand
* glam::Mat4::from_rotation_x((-90.0f32).to_radians())
* glam::Mat4::from_rotation_y(std::f32::consts::PI)
* glam::Mat4::from_translation(glam::Vec3::new(
if left { -ox } else { ox } / 16.0,
oy / 16.0,
oz / 16.0,
));
let seed = a.id as i32 + if left { 1 } else { 2 };
let state = self.resolve_item(stack, context, Some(&owner), seed);
self.submit_item_world(&state, pose, light, out);
}
// `CustomHeadLayer`: a worn skull draws the skull model.
if let Some(stack) = &a.equipment[5]
&& let Some(kind) = skull_kind(&stack.item)
&& let Some(head) = part_matrix(model, base, poses, "head", 0.0)
{
let pose = head * glam::Mat4::from_scale(glam::Vec3::splat(1.1875));
let special = horizon_assets::item_model::SpecialModel {
kind: if kind == "player" {
horizon_assets::item_model::SpecialKind::PlayerHead
} else {
horizon_assets::item_model::SpecialKind::Head {
kind: kind.to_owned(),
texture: None,
animation: 0.0,
}
},
};
let mut sink = horizon_client::item_render::WorldSink {
out,
light,
lights: Some(horizon_client::block_entity_render::diffuse_lights(
self.dim == super::Dim::Nether,
)),
};
self.res.item_renderer.submit_special(
&special,
&serde_json::Value::Null,
false,
pose,
&self.res.atlas.sprites,
&self.item_host(),
&mut sink,
);
return;
}
// A head item that is not worn armour.
if let Some(stack) = &a.equipment[5]
&& self
.res
.items
.get(&stack.item)
.is_none_or(|i| i.equip_asset.is_none())
&& let Some(head) = part_matrix(model, base, poses, "head", 0.0)
{
let pose = head
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0))
* glam::Mat4::from_rotation_y(std::f32::consts::PI)
* glam::Mat4::from_scale(glam::Vec3::new(0.625, -0.625, -0.625));
// `updateForLiving`: seeded by the entity id plus HEAD's ordinal.
let state =
self.resolve_item(stack, DisplayContext::Head, Some(&owner), a.id as i32 + 5);
self.submit_item_world(&state, pose, light, out);
}
}
}
/// `AbstractSkullBlock.getType` of a skull item.
fn skull_kind(item: &str) -> Option<&'static str> {
Some(match item {
"minecraft:skeleton_skull" => "skeleton",
"minecraft:wither_skeleton_skull" => "wither_skeleton",
"minecraft:zombie_head" => "zombie",
"minecraft:creeper_head" => "creeper",
"minecraft:dragon_head" => "dragon",
"minecraft:piglin_head" => "piglin",
"minecraft:player_head" => "player",
_ => return None,
})
}
-159
View File
@@ -2,14 +2,10 @@
//! banner item to the block when placed and back to the dropped item when
//! broken (`copy_components` in the banner loot tables).
use super::Game;
use glam::{EulerRot, Mat4, Quat, Vec3};
use horizon_client::{
banner::{self, BannerLayer},
block_entity_render::{Paint, draw_part},
containers::{Banner, BlockEntity},
hud::{HudBatch, rgba},
items::ItemStack,
mesher::Vertex,
};
impl Game<'_> {
@@ -34,161 +30,6 @@ impl Game<'_> {
b.name = stack.custom_name().map(str::to_owned);
}
}
/// A banner in a slot: `item/template_banner`'s `gui` transform on the
/// banner model (pole, bar and flag with every layer), flat-lit and
/// depth-sorted. False when the stack is not a banner.
pub(super) fn draw_banner_icon(
&self,
batch: &mut HudBatch,
stack: &ItemStack,
x: f32,
y: f32,
) -> bool {
let Some(base) = banner::banner_color(&stack.item) else {
return false;
};
let Some((main, flag)) = self.res.block_entity_render.banner_models() else {
return true;
};
let banners = &self.res.stations.banners;
let sprites = &self.res.atlas.sprites;
// display.gui, then the item's special transformation (a banner is
// modelled upside down and 2/3 size around the block centre).
let m = Mat4::from_translation(Vec3::new(0.0, -3.25 / 16.0, 0.0))
* Mat4::from_quat(Quat::from_euler(
EulerRot::XYZ,
30f32.to_radians(),
20f32.to_radians(),
0.0,
))
* Mat4::from_scale(Vec3::splat(0.5325))
* Mat4::from_translation(Vec3::new(0.0, -0.5, 0.0))
* Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0));
let wave = |name: &str, p: &mut [f32; 9]| {
if name == "flag" {
p[3] = (-0.0125 + 0.01) * std::f32::consts::PI;
}
};
let none = |_: &str, _: &mut [f32; 9]| {};
let mut passes: Vec<(&str, u32, bool, String)> = vec![
("entity/banner/banner_base", 0xFFFFFF, true, String::new()),
(
"entity/banner/base",
banner::dye_rgb(base),
false,
String::new(),
),
];
for layer in banner::layers(stack).iter().take(16) {
passes.push((
"",
banner::dye_rgb(&layer.color),
false,
banners.banner_texture(&layer.pattern),
));
}
// (depth, pass, screen corners, uv, colour)
let mut faces: Vec<(f32, usize, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new();
for (index, (fixed, tint, with_pole, dynamic)) in passes.iter().enumerate() {
let name = if fixed.is_empty() {
dynamic.as_str()
} else {
fixed
};
let Some(sprite) = sprites.get(name).copied() else {
continue;
};
let paint = Paint {
sprite,
tint: 0xFFFFFF,
light: 0,
lights: (Vec3::ZERO, Vec3::ZERO),
};
let mut verts: Vec<Vertex> = Vec::new();
if *with_pole {
draw_part(main, "root", m, &none, paint, &mut verts);
}
draw_part(flag, "root", m, &wave, paint, &mut verts);
for quad in verts.as_chunks::<4>().0 {
let p = |i: usize| Vec3::from(quad[i].pos);
let normal = (p(1) - p(0)).cross(p(2) - p(0)).normalize_or_zero();
// Faces turned away from the viewer are culled.
if normal.z <= 0.0 {
continue;
}
let depth = (0..4).map(|i| p(i).z).sum::<f32>() / 4.0;
let shade = (0.6 + 0.4 * normal.z).min(1.0);
let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8;
faces.push((
depth,
index,
std::array::from_fn(|i| {
[
x + 8.0 + quad[i].pos[0] * 16.0,
y + 8.0 - quad[i].pos[1] * 16.0,
]
}),
std::array::from_fn(|i| quad[i].uv),
rgba(c(16), c(8), c(0), 255),
));
}
}
faces.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
for (_, _, corners, uv, color) in faces {
batch.quad(corners, uv, color);
}
true
}
/// A banner in the first-person hand: the standing banner model under the
/// item's `firstperson_righthand` transform (`m`) and its special
/// transformation. False when the stack is not a banner.
pub(super) fn held_banner_geometry(
&self,
m: Mat4,
stack: &ItemStack,
packed: u32,
out: &mut Vec<Vertex>,
) -> bool {
let Some(base) = banner::banner_color(&stack.item) else {
return false;
};
let Some((main, flag)) = self.res.block_entity_render.banner_models() else {
return true;
};
let m = m
* Mat4::from_translation(Vec3::new(0.5, 0.0, 0.5))
* Mat4::from_scale(Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0));
let wave = |name: &str, p: &mut [f32; 9]| {
if name == "flag" {
p[3] = (-0.0125 + 0.01) * std::f32::consts::PI;
}
};
let none = |_: &str, _: &mut [f32; 9]| {};
let lights = horizon_client::block_entity_render::diffuse_lights(false);
let sprites = &self.res.atlas.sprites;
let paint = |name: &str, tint: u32| {
sprites.get(name).map(|&sprite| Paint {
sprite,
tint,
light: packed,
lights,
})
};
if let Some(p) = paint("entity/banner/banner_base", 0xFFFFFF) {
draw_part(main, "root", m, &none, p, out);
draw_part(flag, "root", m, &wave, p, out);
}
if let Some(p) = paint("entity/banner/base", banner::dye_rgb(base)) {
draw_part(flag, "root", m, &wave, p, out);
}
for layer in banner::layers(stack).iter().take(16) {
let texture = self.res.stations.banners.banner_texture(&layer.pattern);
if let Some(p) = paint(&texture, banner::dye_rgb(&layer.color)) {
draw_part(flag, "root", m, &wave, p, out);
}
}
true
}
/// The layers a banner dropped at `pos` carries.
pub(super) fn attach_banner_layers(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
if !stack.item.ends_with("_banner") {
@@ -718,7 +718,6 @@ impl Game<'_> {
self.mobs.append(&mut mobs);
self.sync_riders();
self.tick_skeleton_traps();
self.cache_mob_icons();
self.tick_apparition();
self.villager_reputation_tick();
self.villager_pickups();
+25 -88
View File
@@ -2,7 +2,7 @@
//! `ItemFrame.survives`, `interact` (put an item in, then rotate it),
//! `hurtServer` (take the item out, then break the frame) and
//! `ItemFrameRenderer` (the frame model and the item at a 45 degree step).
use super::{Game, Hit, Icon, view_vector};
use super::{Game, Hit, view_vector};
use horizon_assets::{bake::bake_model, model::CuboidModel, resolve::ModelLibrary};
use horizon_client::{entities::ItemFrame, items::ItemStack, mesher::Vertex};
use horizon_core::{
@@ -300,17 +300,10 @@ impl Game<'_> {
}
/// ItemFrameRenderer: the frame model, then the item half size on its face.
pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let icons: Vec<Option<Icon>> = (0..self.item_frames.len())
.map(|i| {
self.item_frames[i]
.item
.clone()
.and_then(|s| self.icon(&s.item))
})
.collect();
let sprites = &self.res.atlas.sprites;
let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new();
for (f, icon) in self.item_frames.iter().zip(icons) {
let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new();
for f in &self.item_frames {
let map = f.item.as_ref().and_then(super::maps::map_id);
let s = f.step();
// Pose: to the block centre, then X/Y rotation by facing.
@@ -391,89 +384,33 @@ impl Game<'_> {
maps.push((id, m.as_mat4(), item_light));
continue;
}
let Some(icon) = icon else { continue };
// GlowItemFrame items render full bright.
let item_light = if f.glow { 240 | 240 << 8 } else { packed };
let Some(stack) = f.item.clone() else {
continue;
};
// `GlowItemFrame` items render full bright (15728880).
let item_light = if f.glow { 0xFF } else { light };
let depth = if f.invisible { 0.5 } else { 0.4375 };
let m = pose
* glam::DMat4::from_translation(glam::DVec3::new(0.0, 0.0, depth))
* glam::DMat4::from_rotation_z((f64::from(f.rotation) * 45.0).to_radians())
* glam::DMat4::from_scale(glam::DVec3::splat(0.5));
let full = |r: &horizon_client::hud::Rect| {
[[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]
};
match icon {
// A flat item faces out of the frame (towards -z here).
Icon::Flat(sprite) => {
if let Some(r) = sprites.get(&sprite) {
let z = -0.03125;
quad(
&m,
[
[0.5, -0.5, z],
[-0.5, -0.5, z],
[-0.5, 0.5, z],
[0.5, 0.5, z],
],
full(r),
item_light,
);
}
}
Icon::Cube {
top, left, right, ..
} => {
let h = 0.25;
let face = |name: &str| sprites.get(name).copied();
if let (Some(t), Some(l), Some(r)) = (face(&top), face(&left), face(&right)) {
let c = |x: f64, y: f64, z: f64| [x * h, y * h, z * h - h];
quad(
&m,
[
c(-1., 1., -1.),
c(1., 1., -1.),
c(1., 1., 1.),
c(-1., 1., 1.),
],
full(&t),
item_light,
);
quad(
&m,
[
c(1., -1., -1.),
c(-1., -1., -1.),
c(-1., 1., -1.),
c(1., 1., -1.),
],
full(&l),
item_light,
);
quad(
&m,
[
c(-1., -1., -1.),
c(-1., -1., 1.),
c(-1., 1., 1.),
c(-1., 1., -1.),
],
full(&r),
item_light,
);
quad(
&m,
[
c(1., -1., 1.),
c(1., -1., -1.),
c(1., 1., -1.),
c(1., 1., 1.),
],
full(&r),
item_light,
);
}
}
}
items.push((stack, f.id, m.as_mat4(), item_light));
}
// `extractRenderState`: FIXED, seeded by the frame entity.
for (stack, id, m, light) in items {
let owner = super::item_draw::owner_at([0.0; 3], 0.0, "minecraft:item_frame");
let state = self.resolve_item(
&stack,
horizon_assets::item_model::DisplayContext::Fixed,
Some(&owner),
id as i32,
);
self.submit_item_world(
&state,
m,
horizon_client::block_entity_render::vertex_light(light),
out,
);
}
for (id, m, light) in maps {
self.map_vertices(id, m, light, out);
+373
View File
@@ -0,0 +1,373 @@
//! Items drawn through the resolved item model pipeline
//! (`horizon_client::item_render`): GUI icons (`GuiGraphics.renderItem`),
//! dropped items (`ItemEntityRenderer`) and items posed in the world (hands,
//! frames, armour stands). This binds the resolver's host services
//! (`ItemEnv`) and the special renderers' registries to the game.
use super::{Dim, Game};
use horizon_assets::item_model::{
Components, DisplayContext, GlobalPos, ItemEnv, LevelState, OwnerState, StackView,
};
use horizon_client::{
block_entity_render::{diffuse_lights, vertex_light},
hud::HudBatch,
item_render::{self, ItemRenderState, SpecialHost, WorldSink},
items::ItemStack,
mesher::Vertex,
};
use serde_json::Value;
use winit::keyboard::KeyCode;
/// The game's answers to what the resolver cannot read from the stack.
pub(super) struct Env<'a, 'g> {
game: &'a Game<'g>,
}
impl ItemEnv for Env<'_, '_> {
fn potion_effect_color(&self, contents: &Value) -> Option<i32> {
// `PotionContents.getColorOr`: the effect mix when any effect is visible.
let id = contents["potion"].as_str();
let effects = id
.and_then(horizon_client::brewing::potion)
.is_some_and(|p| !p.effects.is_empty());
effects.then(|| (0xFF00_0000 | horizon_client::brewing::potion_color(id)) as i32)
}
fn grass_color(&self, temperature: f64, downfall: f64) -> i32 {
self.game
.res
.item_renderer
.grass_color(temperature, downfall)
}
fn bundle_fullness(&self, _stack: &StackView, components: &Components) -> f32 {
// `BundleContents.weight`: count / max stack size, summed.
let Some(items) = components
.get("minecraft:bundle_contents")
.and_then(Value::as_array)
else {
return 0.0;
};
let prototypes = &self.game.res.item_renderer.models.prototypes;
let mut total = 0.0f64;
for item in items {
let id = item["id"].as_str().unwrap_or("");
let count = item["count"].as_i64().unwrap_or(1) as f64;
let max = prototypes
.get(id)
.and_then(|c| c.get("minecraft:max_stack_size"))
.and_then(Value::as_i64)
.unwrap_or(1) as f64;
total += count / max;
}
total as f32
}
fn has_shift_down(&self) -> bool {
self.game.keys.contains(&KeyCode::ShiftLeft)
|| self.game.keys.contains(&KeyCode::ShiftRight)
}
fn local_time(&self, pattern: &str, _locale: &str, _time_zone: Option<&str>) -> String {
local_time(pattern)
}
fn random_float(&self) -> f32 {
let nanos = self.game.started.elapsed().subsec_nanos();
(nanos % 1_000_000) as f32 / 1_000_000.0
}
}
/// The days since 1970-01-01 as a civil (year, month, day) date.
fn civil(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(yoe + era * 400 + i64::from(m <= 2), m, d)
}
/// `DateTimeFormatter.ofPattern(pattern).format(now)` for the month, day,
/// year and time letters item models use (UTC: no time zone database).
pub(super) fn local_time(pattern: &str) -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64);
let (y, mo, d) = civil(secs.div_euclid(86_400));
let s = secs.rem_euclid(86_400);
let (h, mi, se) = (s / 3600, s / 60 % 60, s % 60);
let mut out = String::new();
let chars: Vec<char> = pattern.chars().collect();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
let mut n = 1;
while i + n < chars.len() && chars[i + n] == c {
n += 1;
}
let num = |v: i64| format!("{v:0n$}");
match c {
'M' => out += &num(i64::from(mo)),
'd' => out += &num(i64::from(d)),
'y' | 'u' => out += &if n == 2 { num(y % 100) } else { num(y) },
'H' => out += &num(h),
'm' => out += &num(mi),
's' => out += &num(se),
'\'' => {
// Quoted literal text.
let end = chars[i + 1..].iter().position(|&x| x == '\'');
if let Some(e) = end {
out.extend(&chars[i + 1..i + 1 + e]);
i += e + 2;
continue;
}
n = 1;
}
other => out.extend(std::iter::repeat_n(other, n)),
}
i += n;
}
out
}
/// Banner and shield pattern textures from the banner pattern registry.
pub(super) struct Host<'a> {
banners: &'a horizon_client::banner::Banners,
}
impl SpecialHost for Host<'_> {
fn banner_texture(&self, pattern: &str) -> Option<String> {
self.banners
.pattern(pattern)
.map(|_| self.banners.banner_texture(pattern))
}
fn shield_texture(&self, pattern: &str) -> Option<String> {
self.banners
.pattern(pattern)
.map(|_| self.banners.shield_texture(pattern))
}
}
/// `ItemOwner` of an entity holding or showing an item.
pub(super) fn owner_at(position: [f64; 3], yaw: f32, entity_type: &str) -> OwnerState {
OwnerState {
position,
visual_rotation_y_degrees: yaw,
entity_type: entity_type.to_owned(),
..Default::default()
}
}
/// `UseDuration` of a stack: 72000 for drawn items, the consume time for food.
fn use_duration(components: &Components) -> i32 {
if let Some(c) = components.get("minecraft:consumable") {
let seconds = c["consume_seconds"].as_f64().unwrap_or(1.6);
return (seconds * 20.0) as i32;
}
let item_model = components
.get("minecraft:item_model")
.and_then(Value::as_str)
.unwrap_or("");
match item_model {
"minecraft:bow"
| "minecraft:crossbow"
| "minecraft:trident"
| "minecraft:spyglass"
| "minecraft:goat_horn"
| "minecraft:brush" => 72_000,
_ => 0,
}
}
impl Game<'_> {
pub(super) fn item_env(&self) -> Env<'_, '_> {
Env { game: self }
}
pub(super) fn item_host(&self) -> Host<'_> {
Host {
banners: &self.res.stations.banners,
}
}
/// The client level as item models read it.
pub(super) fn item_level(&self) -> LevelState {
let dimension = match self.dim {
Dim::Overworld => "minecraft:overworld",
Dim::Nether => "minecraft:the_nether",
Dim::End => "minecraft:the_end",
};
let sky = self
.dim_environment()
.sample(self.world.day_time, None, None);
LevelState {
dimension: dimension.to_owned(),
game_time: self.world.game_time,
sun_angle: sky.sun_angle,
moon_phase: (self.world.day_time.div_euclid(24_000)).rem_euclid(8) as i32,
respawn: self.spawn.map(|s| GlobalPos {
dimension: "minecraft:overworld".to_owned(),
pos: [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32],
}),
runs_normally: true,
}
}
/// The local player as `ItemOwner`; `stack` is the stack drawn, to tell
/// whether it is the one in use.
pub(super) fn player_owner(&self, stack: Option<&ItemStack>) -> OwnerState {
let position = self
.player
.as_ref()
.map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]);
let mut owner = owner_at(position, self.yaw, "minecraft:player");
owner.main_arm_left = self.settings.main_hand_left;
owner.is_local_player = true;
owner.is_view_entity = true;
if let (Some((slot, ticks)), Some(stack)) = (self.using, stack)
&& self.inventory.get(slot).and_then(Option::as_ref) == Some(stack)
{
let view = item_render::stack_view(stack);
let duration = use_duration(&self.res.item_renderer.models.components(&view));
owner.using_this_item = true;
owner.use_duration = duration;
owner.use_item_remaining_ticks = duration - ticks as i32;
owner.crossbow_charge_duration = 25;
}
owner.is_selected =
stack.is_some() && self.inventory.get(self.selected).and_then(Option::as_ref) == stack;
owner.is_carried = owner.is_selected;
owner
}
/// `ItemModelResolver.updateForTopItem`.
pub(super) fn resolve_item(
&self,
stack: &ItemStack,
display: DisplayContext,
owner: Option<&OwnerState>,
seed: i32,
) -> ItemRenderState {
let level = self.item_level();
self.res.item_renderer.resolve(
&item_render::stack_view(stack),
display,
owner,
Some(&level),
seed,
&self.item_env(),
)
}
/// `GuiGraphics.renderItem(player, level, stack, x, y, 0)`.
pub(super) fn draw_item_model(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
let owner = self.player_owner(Some(stack));
let state = self.resolve_item(stack, DisplayContext::Gui, Some(&owner), 0);
item_render::gui::draw(
&state,
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.item_host(),
batch,
x,
y,
self.started.elapsed().as_secs_f32(),
);
}
/// Submit a resolved item under `pose` (camera-relative) at `light`
/// (packed lightmap coordinates).
pub(super) fn submit_item_world(
&self,
state: &ItemRenderState,
pose: glam::Mat4,
light: u32,
out: &mut Vec<Vertex>,
) {
let mut sink = WorldSink {
out,
light,
lights: Some(diffuse_lights(self.dim == Dim::Nether)),
};
state.submit(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
);
}
/// [`Self::submit_item_world`] without the level's diffuse shading.
pub(super) fn submit_item_unlit(
&self,
state: &ItemRenderState,
pose: glam::Mat4,
light: u32,
out: &mut Vec<Vertex>,
) {
let mut sink = WorldSink {
out,
light,
lights: None,
};
state.submit(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
);
}
/// `ItemEntityRenderer.submit` for every dropped item.
pub(super) fn dropped_item_geometry(
&self,
camera: glam::DVec3,
alpha: f64,
out: &mut Vec<Vertex>,
) {
for item in &self.dropped {
let (p, q) = (item.previous, item.position);
let pos = glam::DVec3::new(
p.x + (q.x - p.x) * alpha,
p.y + (q.y - p.y) * alpha,
p.z + (q.z - p.z) * alpha,
) - camera;
if pos.length_squared() > 64.0 * 64.0 {
continue;
}
// `extractItemGroupRenderState`: GROUND, seeded by the entity id.
let owner = owner_at([q.x, q.y, q.z], 0.0, "minecraft:item");
let state = self.resolve_item(
&item.stack,
DisplayContext::Ground,
Some(&owner),
item.id as i32,
);
if state.is_empty() {
continue;
}
let age = item.age as f32 + alpha as f32;
let (lo, _) = state.bounding_box();
let min_offset_y = -lo.y + 0.0625;
let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1;
let spin = item_render::item_spin(age, item.bob_offset);
let pose = glam::Mat4::from_translation(pos.as_vec3())
* glam::Mat4::from_translation(glam::Vec3::new(0.0, bob + min_offset_y, 0.0))
* glam::Mat4::from_rotation_y(spin);
let packed = self.world.light(
q.x.floor() as i32,
(q.y + 0.1).floor() as i32,
q.z.floor() as i32,
);
let seed = i64::from(self.res.item_renderer.item_id(&item.stack.item))
+ i64::from(item.stack.damage);
for copy in item_render::cluster_poses(
&state,
pose,
item_render::rendered_amount(item.stack.count),
seed,
) {
self.submit_item_world(&state, copy, vertex_light(packed), out);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn civil_dates_follow_the_gregorian_calendar() {
assert_eq!(civil(0), (1970, 1, 1));
assert_eq!(civil(19_716), (2023, 12, 25));
assert_eq!(civil(11_016), (2000, 2, 29));
}
}
+70 -51
View File
@@ -1,8 +1,9 @@
//! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the
//! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like
//! dropped block items.
use super::{Game, Icon};
use super::Game;
use horizon_client::{
items::ItemStack,
mesher::Vertex,
mobs::{Mob, Species, render},
};
@@ -176,22 +177,6 @@ impl Game<'_> {
render::draw(flag, m, &flag_poses, r, color, light, 0, out);
}
}
/// Resolve the icons of the items mobs hold, so drawing can look them up.
pub(super) fn cache_mob_icons(&mut self) {
let items: Vec<String> = self
.mobs
.iter()
.filter(|m| m.extra.main_hand.is_some() || m.extra.off_hand.is_some())
.flat_map(|m| [m.extra.main_hand.clone(), m.extra.off_hand.clone()])
.flatten()
.map(|i| i.to_string())
.collect();
for item in items {
if !self.res.icons.contains_key(&item) {
let _ = self.icon(&item);
}
}
}
fn push_cube(
&self,
t: glam::Mat4,
@@ -232,40 +217,7 @@ impl Game<'_> {
) {
let overlay = u32::from(mob.hurt_time > 0);
self.captain_banner_geometry(mob, camera, alpha, light, out);
for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
let Some(item) = item else { continue };
let Some(Icon::Cube {
top,
left: z,
right: x,
tint,
}) = self.res.icons.get(&**item).cloned().flatten()
else {
continue;
};
let Some(t) =
render::held_block_transform(mob, alpha as f32, camera, &self.res.mob_data, left)
else {
continue;
};
let slot = if left {
horizon_client::mobs::gear::OFF
} else {
horizon_client::mobs::gear::MAIN
};
let glint = horizon_client::mobs::gear::enchanted(mob, slot);
let overlay = if glint { 7 } else { overlay };
self.push_cube(
t,
&Cube {
sprites: [&top, &z, &x],
tint,
},
light,
overlay,
out,
);
}
self.held_item_geometry(mob, camera, alpha, light, true, out);
if mob.species() == Species::Enderman
&& let Some(state) = mob.extra.carried
&& let Some((sprite, tint)) = self.particle_sprite(state)
@@ -292,4 +244,71 @@ impl Game<'_> {
);
}
}
/// `ItemInHandLayer`: both hands through the item model pipeline; `lit`
/// applies the level's diffuse lighting (off for GUI previews, which
/// light the projected quads themselves).
pub(super) fn held_item_geometry(
&self,
mob: &Mob,
camera: glam::DVec3,
alpha: f64,
light: u32,
lit: bool,
out: &mut Vec<Vertex>,
) {
let overlay = u32::from(mob.hurt_time > 0);
for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
let Some(item) = item else { continue };
let Some(t) =
render::held_item_transform(mob, alpha as f32, camera, &self.res.mob_data, left)
else {
continue;
};
let slot = if left {
horizon_client::mobs::gear::OFF
} else {
horizon_client::mobs::gear::MAIN
};
let mut stack = ItemStack::new(item, 1);
if horizon_client::mobs::gear::enchanted(mob, slot) {
// The gear's enchantments are not tracked, only that it has some.
stack.enchant("minecraft:unbreaking", 1);
}
if &**item == "minecraft:crossbow" && mob.extra.flag2 {
stack.data_mut().charged = vec![ItemStack::new("minecraft:arrow", 1)];
}
let mut owner = super::item_draw::owner_at(
[mob.position.x, mob.position.y, mob.position.z],
mob.body_yaw,
&mob.kind.id,
);
if !left && mob.extra.using_item > 0 {
owner.using_this_item = true;
owner.use_duration = 72_000;
owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item;
owner.crossbow_charge_duration = 25;
}
let context = if left {
horizon_assets::item_model::DisplayContext::ThirdPersonLeftHand
} else {
horizon_assets::item_model::DisplayContext::ThirdPersonRightHand
};
// `updateForLiving`: seeded by the entity id plus the context ordinal.
let seed = mob.id as i32 + if left { 1 } else { 2 };
let state = self.resolve_item(&stack, context, Some(&owner), seed);
let start = out.len();
if lit {
self.submit_item_world(&state, t, light, out);
} else {
self.submit_item_unlit(&state, t, light, out);
}
if overlay != 0 {
for v in &mut out[start..] {
if v.layer == 0 {
v.layer = overlay;
}
}
}
}
}
}
+4 -2
View File
@@ -123,8 +123,10 @@ impl Game<'_> {
);
}
self.res.atlas = atlas;
self.res.icons.clear();
self.res.displays.clear();
match horizon_client::item_render::ItemRenderer::load(&root) {
Ok(r) => self.res.item_renderer = std::sync::Arc::new(r),
Err(e) => eprintln!("Horizon: item model reload failed: {e}"),
}
} else {
eprintln!(
"Horizon: resource pack atlas size changed; restart to apply GUI textures"
@@ -395,6 +395,7 @@ impl Game<'_> {
&self.player_armor_layers(),
out,
);
self.held_item_geometry(m, camera, alpha, packed, true, out);
}
/// `extractEntityInInventoryFollowsMouse`: the player in the box
/// `[x0, x1) x [y0, y1)`, `size` pixels per block, turned toward the
@@ -448,6 +449,7 @@ impl Game<'_> {
&self.player_armor_layers(),
&mut verts,
);
self.held_item_geometry(&m, camera, 1.0, 240 | 240 << 8, false, &mut verts);
let height = if m.extra.crouching { 1.5 } else { 1.8 };
// PictureInPictureRenderer: the box centre, (size, size, -size);
// then the translation and Rz(pi) * Rx(y_angle * 20 degrees).
-129
View File
@@ -244,132 +244,3 @@ impl Game<'_> {
}
}
}
/// The shield in a slot: `ShieldSpecialRenderer`'s plate and handle boxes
/// under item/shield's `gui` display transform, flat-lit and depth-sorted.
pub(super) fn draw_shield_icon(
batch: &mut horizon_client::hud::HudBatch,
atlas: &horizon_client::hud::HudAtlas,
x: f32,
y: f32,
passes: &[(String, u32)],
) {
// display.gui: rotation [15, -25, -5], translation [2, 3, 0], scale 0.65.
let (sx, cx) = 15f32.to_radians().sin_cos();
let (sy, cy) = (-25f32).to_radians().sin_cos();
let (sz, cz) = (-5f32).to_radians().sin_cos();
// Quaternionf.rotationXYZ: Rx * Ry * Rz.
let rotate = |[x, y, z]: [f32; 3]| {
let (x, y) = (x * cz - y * sz, x * sz + y * cz);
let (x, z) = (x * cy + z * sy, -x * sy + z * cy);
let (y, z) = (y * cx - z * sx, y * sx + z * cx);
[x, y, z]
};
// Model pixels -> slot pixels: S(1,-1,-1), T(-0.5), S(0.65), R, T, and
// the GUI's (16, -16, 16) around the slot centre.
let place = |[px, py, pz]: [f32; 3]| {
let q = [px / 16.0 - 0.5, -py / 16.0 - 0.5, -pz / 16.0 - 0.5].map(|v| v * 0.65);
let [qx, qy, qz] = rotate(q);
[
x + 8.0 + (qx + 2.0 / 16.0) * 16.0,
y + 8.0 - (qy + 3.0 / 16.0) * 16.0,
qz,
]
};
// ShieldModel: plate texOffs(0, 0) box(-6, -11, -2, 12, 22, 1) and
// handle texOffs(26, 0) box(-1, -3, -1, 2, 6, 6).
let mut faces: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], f32)> = Vec::new();
for (tu, tv, from, size) in [
(0.0, 0.0, [-6.0, -11.0, -2.0], [12.0, 22.0, 1.0]),
(26.0, 0.0, [-1.0, -3.0, -1.0], [2.0, 6.0, 6.0]),
] {
let [w, h, d] = size;
let (x0, y0, z0) = (from[0], from[1], from[2]);
let (x1, y1, z1) = (x0 + w, y0 + h, z0 + d);
let t0 = [x0, y0, z0];
let t1 = [x1, y0, z0];
let t2 = [x1, y1, z0];
let t3 = [x0, y1, z0];
let l0 = [x0, y0, z1];
let l1 = [x1, y0, z1];
let l2 = [x1, y1, z1];
let l3 = [x0, y1, z1];
let (u0, u1, u2) = (tu, tu + d, tu + d + w);
let (u22, u3, u4) = (tu + d + w + w, tu + d + w + d, tu + d + w + d + w);
let (v0, v1, v2) = (tv, tv + d, tv + d + h);
// ModelPart.Cube's polygons: (vertices, u0, v0, u1, v1, normal).
for (verts, a, b, c, e, n) in [
([l1, l0, t0, t1], u1, v0, u2, v1, [0.0, -1.0, 0.0]),
([t2, t3, l3, l2], u2, v1, u22, v0, [0.0, 1.0, 0.0]),
([t0, l0, l3, t3], u0, v1, u1, v2, [-1.0, 0.0, 0.0]),
([t1, t0, t3, t2], u1, v1, u2, v2, [0.0, 0.0, -1.0]),
([l1, t1, t2, l2], u2, v1, u3, v2, [1.0, 0.0, 0.0]),
([l0, l1, l2, l3], u3, v1, u4, v2, [0.0, 0.0, 1.0]),
] {
let normal = rotate([n[0], -n[1], -n[2]]);
if normal[2] <= 0.0 {
continue;
}
let p = verts.map(place);
let depth = p.iter().map(|q| q[2]).sum::<f32>() / 4.0;
let texels = [[c, b], [a, b], [a, e], [c, e]];
// Flat item lighting: faces toward the viewer are brightest.
let shade = (0.6 + 0.4 * normal[2]).min(1.0);
faces.push((depth, p.map(|q| [q[0], q[1]]), texels, shade));
}
}
// Every pass redraws the same boxes; equal depths keep the pass order.
let mut quads = Vec::new();
for (index, (name, tint)) in passes.iter().enumerate() {
let Some(r) = atlas.sprites.get(name).copied() else {
continue;
};
for (depth, p, texels, shade) in &faces {
let uv = texels.map(|[u, v]| {
[
r.u0 + (r.u1 - r.u0) * u / 64.0,
r.v0 + (r.v1 - r.v0) * v / 64.0,
]
});
let c = |s: u32| (((tint >> s) & 255) as f32 * shade) as u8;
quads.push((
*depth,
index,
*p,
uv,
horizon_client::hud::rgba(c(16), c(8), c(0), 255),
));
}
}
quads.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
for (_, _, p, uv, color) in quads {
batch.quad(p, uv, color);
}
}
/// The textures a shield draws: the plain or patterned base, then the
/// banner layers (`ShieldSpecialRenderer.submit`).
pub(super) fn shield_passes(
banners: &horizon_client::banner::Banners,
stack: &ItemStack,
) -> Vec<(String, u32)> {
let data = stack.data();
let layers = data.map_or(&[][..], |d| &d.banner_patterns[..]);
let base = data.and_then(|d| d.base_color.as_deref());
if layers.is_empty() && base.is_none() {
return vec![("entity/shield/shield_base_nopattern".into(), 0xFFFFFF)];
}
let mut passes = vec![
("entity/shield/shield_base".into(), 0xFFFFFF),
(
"entity/shield/base".into(),
horizon_client::banner::dye_rgb(base.unwrap_or("white")),
),
];
for layer in layers.iter().take(16) {
passes.push((
banners.shield_texture(&layer.pattern),
horizon_client::banner::dye_rgb(&layer.color),
));
}
passes
}
@@ -1991,100 +1991,6 @@ impl Game<'_> {
self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1);
}
}
/// Potion items: `layer0` tinted with the potion colour under the bottle
/// (`minecraft:potion` item tint source).
pub(super) fn draw_potion_layers(
&self,
batch: &mut HudBatch,
stack: &ItemStack,
x: f32,
y: f32,
) {
let (overlay, base) = match &*stack.item {
"minecraft:potion" => ("item/potion_overlay", "item/potion"),
"minecraft:splash_potion" => ("item/potion_overlay", "item/splash_potion"),
"minecraft:lingering_potion" => ("item/potion_overlay", "item/lingering_potion"),
"minecraft:tipped_arrow" => ("item/tipped_arrow_head", "item/tipped_arrow_base"),
_ => return,
};
let c = brewing::potion_color(stack.potion());
let atlas = &self.res.atlas;
batch.sprite_scaled(
atlas,
overlay,
x,
y,
16.0,
16.0,
rgba(
(c >> 16 & 255) as u8,
(c >> 8 & 255) as u8,
(c & 255) as u8,
255,
),
);
batch.sprite_scaled(atlas, base, x, y, 16.0, 16.0, u32::MAX);
}
/// The enchantment glint over an item icon: a shimmering purple tint.
pub(super) fn draw_glint(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
if !self.res.stations.enchantments.has_glint(stack) {
return;
}
// ItemRenderer glint: the enchanted_glint texture scrolls diagonally over the
// item's shape. Approximated with a grid of item-texture quads whose vertex
// colours carry a purple base tint plus a moving bright band.
let t = self.started.elapsed().as_secs_f32();
let glint = |gx: f32, gy: f32| -> u32 {
let d = ((gx + gy) / 32.0 - t * 0.35).rem_euclid(1.0);
let band = (1.0 - (d - 0.5).abs() * 6.0).max(0.0);
let a = 45.0 + 110.0 * band;
rgba(
(170.0 + 70.0 * band) as u8,
(90.0 + 110.0 * band) as u8,
255,
a as u8,
)
};
match self.res.icons.get(&*stack.item).cloned().flatten() {
Some(super::Icon::Flat(name)) => {
let Some(r) = self.res.atlas.sprites.get(&name).copied() else {
return;
};
const N: usize = 4;
let cell = 16.0 / N as f32;
let (du, dv) = ((r.u1 - r.u0) / N as f32, (r.v1 - r.v0) / N as f32);
for row in 0..N {
for col in 0..N {
let (x0, y0) = (col as f32 * cell, row as f32 * cell);
let (u0, v0) = (r.u0 + du * col as f32, r.v0 + dv * row as f32);
let corners = [
(x0, y0, u0, v0),
(x0 + cell, y0, u0 + du, v0),
(x0 + cell, y0 + cell, u0 + du, v0 + dv),
(x0, y0 + cell, u0, v0 + dv),
];
for i in [0usize, 1, 2, 0, 2, 3] {
let (cx, cy, u, v) = corners[i];
batch.vertices.push(horizon_client::hud::HudVertex {
pos: [x + cx, y + cy],
uv: [u + 2.0, v],
color: glint(cx, cy),
});
}
}
}
}
Some(super::Icon::Cube { .. }) => batch.fill(
&self.res.atlas,
x + 1.0,
y + 1.0,
14.0,
14.0,
glint(8.0, 8.0) & 0x7FFF_FFFF,
),
None => {}
}
}
// ---------------------------------------------------------------- brewing stand
+53
View File
@@ -62,6 +62,58 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
}
}
}
/// A packed atlas image: sprite name, size and RGBA pixels.
type PackedImage = (String, u32, u32, Vec<u8>);
/// Sprites the atlas definitions (`atlases/*.json`) add beyond the texture
/// files already packed: generated ones (`paletted_permutations` such as the
/// armour trim sprites, `unstitch` regions) and files listed under another id.
fn atlas_sprites(root: &Path, packed: &[PackedImage]) -> Vec<PackedImage> {
use crate::atlas_sources::{self, SpriteOrigin};
let have: std::collections::HashSet<&str> = packed.iter().map(|i| i.0.as_str()).collect();
let textures = atlas_sources::list_textures(root);
let load = |texture: &str, directory: &str| {
decode(&atlas_sources::texture_path(root, texture, directory)).ok()
};
let mut out: Vec<PackedImage> = Vec::new();
let mut added = std::collections::HashSet::new();
for (atlas, sources) in atlas_sources::atlases(root) {
// The other atlases' renamed files (GUI sprites, particles...) are
// looked up by their texture paths here.
let item_models = atlas == "minecraft:blocks" || atlas == "minecraft:items";
for (id, origin) in atlas_sources::list(&sources, &textures) {
if !item_models && matches!(origin, SpriteOrigin::File(_)) {
continue;
}
let name = id.strip_prefix("minecraft:").unwrap_or(&id).to_owned();
if have.contains(name.as_str()) || added.contains(&name) {
continue;
}
let image = match &origin {
SpriteOrigin::File(texture) => {
let path = texture.strip_prefix("minecraft:").unwrap_or(texture);
// Packed under its own name already: only a renamed file is new.
if path == name {
continue;
}
load(texture, "textures").map(|(w, h, p)| {
// Animated strips keep their first frame, like the packed files.
if h > w && (path.starts_with("block/") || path.starts_with("item/")) {
(w, w, p[..(w * w * 4) as usize].to_vec())
} else {
(w, h, p)
}
})
}
generated => atlas_sources::generate(generated, &load),
};
if let Some((w, h, pixels)) = image {
added.insert(name.clone());
out.push((name, w, h, pixels));
}
}
}
out
}
impl HudAtlas {
/// A font glyph's atlas cell (8x8 GUI pixels) and advance.
pub fn glyph(&self, ch: char) -> Option<(Rect, f32)> {
@@ -136,6 +188,7 @@ impl HudAtlas {
.flat_map(|h| h.join().unwrap_or_default())
.collect()
});
images.extend(atlas_sprites(root, &images));
images.push(("horizon/white".into(), 4, 4, vec![255; 64]));
// Map textures (game/maps.rs) are written into these slots at run time.
for i in 0..MAP_SLOTS {
+815
View File
@@ -0,0 +1,815 @@
//! Item rendering through the resolved item model pipeline: the
//! `ItemModelResolver` of `horizon-assets` fills an [`ItemRenderState`]
//! (`ItemStackRenderState`: layers of baked quads or special renderers, each
//! with its display transform, local transform, tints and foil), and
//! [`ItemRenderState::submit`] turns it into the quads `ItemFeatureRenderer`
//! and the special model renderers submit, in pose space. A sink then draws
//! them: [`gui`] into the HUD batch with the GUI item lighting, [`WorldSink`]
//! into entity vertices with the level's lighting.
pub mod gui;
mod special;
use crate::{
block_entity_render::{ModelPart, diffuse},
hud::Rect,
mesher::Vertex,
};
use glam::{Mat3, Mat4, Vec3};
use horizon_assets::{
animation::AnimationMetadata,
item_bake::{BakedItemModel, SpriteLookup, SpriteMask, bake_item_model},
item_model::{
ClientItem, Components, Context, DisplayContext, FoilType, ItemEnv, ItemModels,
LayerContent, LevelState, OwnerState, SpecialModel, StackView,
},
model::{CuboidModel, Direction},
palette::PalettedPermutations,
resolve::{MISSING_MODEL, ModelLibrary},
};
use horizon_world::nbt::Tag;
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
/// One quad as submitted for drawing: pose-space corners, atlas UVs, the
/// transformed unit normal, ARGB colour (tint, `-1` white) and its glint.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ItemQuad {
pub pos: [Vec3; 4],
pub uv: [[f32; 2]; 4],
pub normal: Vec3,
pub color: u32,
pub foil: Foil,
/// `MaterialInfo.lightEmission` (block light floor).
pub light_emission: u8,
}
/// Which glint render type a quad uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Foil {
None,
/// `GLINT_TEXTURING` over the sprite's UVs (`itemGlintRenderType`,
/// `entitySolidGlint`).
Standard,
/// `itemGlintSpecialRenderType`: compasses and clocks, a sheeted decal.
Special,
}
/// Where submitted quads go.
pub trait ItemSink {
fn quad(&mut self, quad: ItemQuad);
}
impl ItemSink for Vec<ItemQuad> {
fn quad(&mut self, quad: ItemQuad) {
self.push(quad);
}
}
/// Data special renderers read from the game (registries, skins).
pub trait SpecialHost {
/// The banner atlas texture of a banner pattern (`entity/banner/<asset>`).
fn banner_texture(&self, pattern: &str) -> Option<String>;
/// The shield atlas texture of a banner pattern (`entity/shield/<asset>`).
fn shield_texture(&self, pattern: &str) -> Option<String>;
/// The skin texture of a `minecraft:profile` component, if loaded.
fn player_skin(&self, _profile: &Value) -> Option<String> {
None
}
}
/// A host with no registries: patterns and skins fall back to defaults.
pub struct NoHost;
impl SpecialHost for NoHost {
fn banner_texture(&self, _: &str) -> Option<String> {
None
}
fn shield_texture(&self, _: &str) -> Option<String> {
None
}
}
/// The geometry of one layer.
#[derive(Clone, Debug)]
pub enum LayerGeometry {
Quads(Arc<BakedItemModel>),
Special {
model: SpecialModel,
argument: Value,
},
}
/// `ItemStackRenderState.LayerRenderState`.
#[derive(Clone, Debug)]
pub struct LayerRender {
pub geometry: LayerGeometry,
pub tints: Vec<i32>,
pub foil: FoilType,
/// `applyTransform`: the display transform, then the local transform.
pub matrix: Mat4,
/// `particleMaterial` (atlas sprite name).
pub particle: String,
pub uses_block_light: bool,
/// Untransformed extents (quad corners or the special model's parts).
pub extents: Arc<Vec<Vec3>>,
}
/// `ItemStackRenderState`.
#[derive(Clone, Debug)]
pub struct ItemRenderState {
pub display: DisplayContext,
pub layers: Vec<LayerRender>,
pub oversized_in_gui: bool,
pub animated: bool,
}
impl ItemRenderState {
pub fn is_empty(&self) -> bool {
self.layers.is_empty()
}
/// `pickParticleMaterial`: a random layer's particle sprite.
pub fn pick_particle(
&self,
random: &mut impl horizon_core::random::RandomSource,
) -> Option<String> {
if self.layers.is_empty() {
return None;
}
let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize;
self.layers.get(i).map(|l| l.particle.clone())
}
/// `usesBlockLight` of the first layer (GUI lighting choice).
pub fn uses_block_light(&self) -> bool {
self.layers.first().is_some_and(|l| l.uses_block_light)
}
/// `getModelBoundingBox`: the transformed extents of every layer, as
/// (min, max); a zero box at the origin when there are none.
pub fn bounding_box(&self) -> (Vec3, Vec3) {
let mut lo = Vec3::splat(f32::INFINITY);
let mut hi = Vec3::splat(f32::NEG_INFINITY);
for layer in &self.layers {
for p in layer.extents.iter() {
let q = layer.matrix.transform_point3(*p);
lo = lo.min(q);
hi = hi.max(q);
}
}
if lo.x > hi.x {
(Vec3::ZERO, Vec3::ZERO)
} else {
(lo, hi)
}
}
/// `ItemStackRenderState.submit` under `pose`.
pub fn submit(
&self,
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
host: &dyn SpecialHost,
pose: Mat4,
sink: &mut dyn ItemSink,
) {
for layer in &self.layers {
let m = pose * layer.matrix;
match &layer.geometry {
LayerGeometry::Quads(baked) => {
submit_quads(baked, layer, self.display, m, sprites, sink);
}
LayerGeometry::Special { model, argument } => special::submit(
renderer,
model,
argument,
layer.foil != FoilType::None,
m,
sprites,
host,
sink,
),
}
}
}
}
/// The atlas name of a sprite identifier (`minecraft:item/apple` -> `item/apple`).
pub fn sprite_name(sprite: &str) -> &str {
sprite.strip_prefix("minecraft:").unwrap_or(sprite)
}
/// `Direction.getUnitVec3f`.
pub fn direction_vector(d: Direction) -> Vec3 {
match d {
Direction::Down => Vec3::NEG_Y,
Direction::Up => Vec3::Y,
Direction::North => Vec3::NEG_Z,
Direction::South => Vec3::Z,
Direction::West => Vec3::NEG_X,
Direction::East => Vec3::X,
}
}
/// `PoseStack.Pose.transformNormal`: the normal matrix, renormalized.
pub fn transform_normal(m: Mat4, n: Vec3) -> Vec3 {
let normal = Mat3::from_mat4(m).inverse().transpose();
(normal * n).normalize_or_zero()
}
/// An `ARGB` int as the `u32` colour of an [`ItemQuad`].
pub fn argb(color: i32) -> u32 {
color as u32
}
/// `ItemFeatureRenderer.prepareMainSubmit` for one cuboid layer.
fn submit_quads(
baked: &BakedItemModel,
layer: &LayerRender,
display: DisplayContext,
m: Mat4,
sprites: &HashMap<String, Rect>,
sink: &mut dyn ItemSink,
) {
let foil = match layer.foil {
FoilType::None => Foil::None,
FoilType::Standard => Foil::Standard,
FoilType::Special => Foil::Special,
};
let _ = display;
for q in &baked.quads {
let Some(r) = sprites
.get(sprite_name(&q.material.sprite))
.or_else(|| sprites.get("misc/missingno"))
.or_else(|| sprites.get("horizon/missingno"))
.copied()
else {
continue;
};
// `getLayerColorSafe`: an untinted quad, or a tint index past the
// tints, draws white.
let color = if q.tint_index >= 0 {
layer
.tints
.get(q.tint_index as usize)
.copied()
.unwrap_or(-1)
} else {
-1
};
let pos = q.positions.map(|p| m.transform_point3(Vec3::from(p)));
let uv =
q.uv.map(|[u, v]| [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v]);
sink.quad(ItemQuad {
pos,
uv,
normal: transform_normal(m, direction_vector(q.facing)),
color: argb(color),
foil,
light_emission: q.light_emission,
});
}
}
// ---------------------------------------------------------------------------
// Sprites for baking
// ---------------------------------------------------------------------------
/// The alpha masks of item and block sprites, read from the texture files
/// (every unique animation frame) and the items atlas's palette sprites.
struct FileSprites {
root: PathBuf,
permutations: Vec<PalettedPermutations>,
cache: Mutex<HashMap<String, Option<SpriteMask>>>,
}
impl SpriteLookup for FileSprites {
fn mask(&self, sprite: &str) -> Option<SpriteMask> {
if let Ok(cache) = self.cache.lock()
&& let Some(hit) = cache.get(sprite)
{
return hit.clone();
}
let mask = self.load(sprite);
if let Ok(mut cache) = self.cache.lock() {
cache.insert(sprite.to_owned(), mask.clone());
}
mask
}
}
fn argb_pixels(rgba: &[u8]) -> Vec<u32> {
rgba.as_chunks::<4>()
.0
.iter()
.map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]]))
.collect()
}
impl FileSprites {
fn png(&self, sprite: &str, directory: &str) -> PathBuf {
crate::atlas_sources::texture_path(&self.root, sprite, directory)
}
fn image(&self, sprite: &str, directory: &str) -> Option<(usize, usize, Vec<u32>)> {
let (w, h, rgba) = crate::hud::decode(&self.png(sprite, directory)).ok()?;
Some((w as usize, h as usize, argb_pixels(&rgba)))
}
fn load(&self, sprite: &str) -> Option<SpriteMask> {
let png = self.png(sprite, "textures");
let (iw, ih, argb) = match self.image(sprite, "textures") {
Some(image) => image,
None => {
let p = self.permutations.iter().find_map(|s| s.find(sprite))?;
let (w, h, mut pixels) = self.image(p.base, "textures")?;
let (_, _, key) = self.image(p.palette_key, "textures/palettes")?;
let (_, _, target) = self.image(p.palette, "textures/palettes")?;
horizon_assets::palette::apply_palette(&mut pixels, &key, &target)?;
(w, h, pixels)
}
};
let alpha: Vec<u8> = argb.iter().map(|p| (p >> 24) as u8).collect();
let animation = fs::read_to_string(png.with_extension("png.mcmeta"))
.ok()
.and_then(|m| serde_json::from_str::<Value>(&m).ok())
.and_then(|m| m.get("animation").map(Value::to_string))
.and_then(|a| AnimationMetadata::from_json(&a).ok());
let (w, h) = match &animation {
Some(a) => {
let [w, h] = a.frame_size(iw as i32, ih as i32);
(w as usize, h as usize)
}
None => (iw, ih),
};
if w == 0 || h == 0 {
return None;
}
let columns = iw / w;
let total = columns * (ih / h);
let clip = animation.and_then(|a| a.clip(total as u32).ok().flatten());
let frames: Vec<usize> = match clip {
Some(clip) => {
let mut unique = Vec::new();
for (index, _) in clip.sequence() {
if !unique.contains(&(*index as usize)) {
unique.push(*index as usize);
}
}
unique
}
None => vec![0],
};
let frames = frames
.into_iter()
.map(|f| {
let (fx, fy) = (f % columns * w, f / columns * h);
(0..h)
.flat_map(|y| (0..w).map(move |x| (x, y)))
.map(|(x, y)| alpha[(fy + y) * iw + fx + x] == 0)
.collect()
})
.collect();
Some(SpriteMask {
width: w,
height: h,
frames,
})
}
}
// ---------------------------------------------------------------------------
// The renderer
// ---------------------------------------------------------------------------
/// The baked item models and everything resolution needs.
pub struct ItemRenderer {
pub models: ItemModels,
library: ModelLibrary,
sprites: FileSprites,
baked: Mutex<HashMap<String, Arc<BakedItemModel>>>,
extents: Mutex<HashMap<String, Arc<Vec<Vec3>>>>,
/// Entity model layers of the special renderers.
parts: HashMap<String, ModelPart>,
/// `colormap/grass.png` as ARGB.
grass: Vec<i32>,
/// `minecraft:item` registry ids (`Item.getId`).
item_ids: HashMap<String, i32>,
}
/// Every `models/**.json` of a namespace directory, by identifier.
fn load_models(root: &Path) -> BTreeMap<String, CuboidModel> {
let mut out = BTreeMap::new();
let Ok(namespaces) = fs::read_dir(root.join("assets")) else {
return out;
};
for ns in namespaces.flatten() {
let namespace = ns.file_name().to_string_lossy().into_owned();
let base = ns.path().join("models");
let mut stack = vec![base.clone()];
while let Some(dir) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for e in entries.flatten() {
let path = e.path();
if path.is_dir() {
stack.push(path);
} else if path.extension().is_some_and(|x| x == "json")
&& let Ok(rel) = path.strip_prefix(&base)
&& let Ok(text) = fs::read_to_string(&path)
&& let Ok(model) = CuboidModel::from_json(&text)
{
let rel = rel.with_extension("").to_string_lossy().replace('\\', "/");
out.insert(format!("{namespace}:{rel}"), model);
}
}
}
}
out
}
/// Every `items/*.json` client item definition, by identifier.
fn load_definitions(root: &Path) -> BTreeMap<String, ClientItem> {
let mut out = BTreeMap::new();
let Ok(namespaces) = fs::read_dir(root.join("assets")) else {
return out;
};
for ns in namespaces.flatten() {
let namespace = ns.file_name().to_string_lossy().into_owned();
let Ok(files) = fs::read_dir(ns.path().join("items")) else {
continue;
};
for f in files.flatten() {
let path = f.path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let name = path.file_stem().unwrap_or_default().to_string_lossy();
if let Some(item) = fs::read_to_string(&path)
.ok()
.and_then(|t| ClientItem::from_json(&t).ok())
{
out.insert(format!("{namespace}:{name}"), item);
}
}
}
out
}
impl ItemRenderer {
/// Load item definitions, item prototypes (`items.json`), every model,
/// the special renderers' entity models and the grass colormap.
pub fn load(root: &Path) -> crate::Result<Self> {
let prototypes: BTreeMap<String, Components> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let models = ItemModels {
definitions: load_definitions(root),
prototypes,
};
let library = ModelLibrary::with_item_generator(load_models(root))
.map_err(|e| format!("item models: {e:?}"))?;
let permutations = PalettedPermutations::from_atlas(
&fs::read_to_string(root.join("assets/minecraft/atlases/items.json"))
.unwrap_or_default(),
);
let parts = special::load_parts(root);
let grass = crate::hud::decode(&root.join("assets/minecraft/textures/colormap/grass.png"))
.map(|(_, _, rgba)| argb_pixels(&rgba).into_iter().map(|p| p as i32).collect())
.unwrap_or_default();
let item_ids = horizon_protocol::registry::Builtin::find(root)
.and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok())
.and_then(|b| {
let ids = b.get("minecraft:item")?;
let mut out = HashMap::new();
for i in 0.. {
let Some(name) = ids.name(i) else { break };
out.insert(name.to_owned(), i);
}
Some(out)
})
.unwrap_or_default();
Ok(Self {
item_ids,
models,
library,
sprites: FileSprites {
root: root.to_path_buf(),
permutations,
cache: Mutex::default(),
},
baked: Mutex::default(),
extents: Mutex::default(),
parts,
grass,
})
}
/// `ModelBakery` item baking, cached per model.
pub fn bake(&self, model: &str) -> Arc<BakedItemModel> {
if let Ok(cache) = self.baked.lock()
&& let Some(hit) = cache.get(model)
{
return hit.clone();
}
let baked = bake_item_model(&self.library, &self.sprites, model)
.or_else(|_| bake_item_model(&self.library, &self.sprites, MISSING_MODEL))
.map(Arc::new)
.unwrap_or_else(|_| {
Arc::new(BakedItemModel {
quads: Vec::new(),
uses_block_light: false,
particle: horizon_assets::model::Material {
sprite: horizon_assets::item_bake::MISSING_SPRITE.to_owned(),
force_translucent: false,
},
transforms: Default::default(),
})
});
if let Ok(mut cache) = self.baked.lock() {
cache.insert(model.to_owned(), baked.clone());
}
baked
}
/// `CuboidItemModelWrapper.computeExtents`: the distinct quad corners.
fn quad_extents(&self, model: &str, baked: &BakedItemModel) -> Arc<Vec<Vec3>> {
if let Ok(cache) = self.extents.lock()
&& let Some(hit) = cache.get(model)
{
return hit.clone();
}
let mut out: Vec<Vec3> = Vec::new();
for q in &baked.quads {
for p in q.positions {
let p = Vec3::from(p);
if !out.contains(&p) {
out.push(p);
}
}
}
let out = Arc::new(out);
if let Ok(mut cache) = self.extents.lock() {
cache.insert(model.to_owned(), out.clone());
}
out
}
fn special_extents(&self, model: &SpecialModel) -> Arc<Vec<Vec3>> {
let key = model.to_json().to_string();
if let Ok(cache) = self.extents.lock()
&& let Some(hit) = cache.get(&key)
{
return hit.clone();
}
let out = Arc::new(special::extents(self, model));
if let Ok(mut cache) = self.extents.lock() {
cache.insert(key, out.clone());
}
out
}
/// `ItemModelResolver.updateForTopItem`.
pub fn resolve(
&self,
stack: &StackView,
display: DisplayContext,
owner: Option<&OwnerState>,
level: Option<&LevelState>,
seed: i32,
env: &dyn ItemEnv,
) -> ItemRenderState {
let ctx = Context {
display,
owner,
level,
seed,
};
let resolved = self.models.resolve(stack, &ctx, env);
let mut animated = false;
let layers = resolved
.layers
.into_iter()
.map(|layer| {
let (geometry, baked, extents) = match layer.content {
LayerContent::Model { model } => {
let baked = self.bake(&model);
let extents = self.quad_extents(&model, &baked);
(LayerGeometry::Quads(baked.clone()), baked, extents)
}
LayerContent::Missing => {
let baked = self.bake(MISSING_MODEL);
let extents = self.quad_extents(MISSING_MODEL, &baked);
(LayerGeometry::Quads(baked.clone()), baked, extents)
}
LayerContent::Special {
base,
model,
argument,
} => {
let baked = self.bake(&base);
let extents = self.special_extents(&model);
(LayerGeometry::Special { model, argument }, baked, extents)
}
};
if layer.foil != FoilType::None {
animated = true;
}
LayerRender {
geometry,
tints: layer.tints,
foil: layer.foil,
matrix: glam_matrix(&baked.layer_matrix(display, &layer.transform)),
uses_block_light: baked.uses_block_light,
particle: sprite_name(&baked.particle.sprite).to_owned(),
extents,
}
})
.collect();
ItemRenderState {
display,
layers,
oversized_in_gui: resolved.oversized_in_gui,
animated,
}
}
/// `GrassColor.get` over the loaded colormap.
pub fn grass_color(&self, temperature: f64, downfall: f64) -> i32 {
let rain = downfall * temperature;
let x = ((1.0 - temperature) * 255.0) as i64;
let y = ((1.0 - rain) * 255.0) as i64;
let index = (y << 8 | x) as usize;
self.grass.get(index).copied().unwrap_or(-65281)
}
/// Submit a special model renderer directly (worn skulls of
/// `CustomHeadLayer`, which draw the skull model, not the item).
#[allow(clippy::too_many_arguments)]
pub fn submit_special(
&self,
model: &SpecialModel,
argument: &Value,
has_foil: bool,
pose: Mat4,
sprites: &HashMap<String, Rect>,
host: &dyn SpecialHost,
sink: &mut dyn ItemSink,
) {
special::submit(self, model, argument, has_foil, pose, sprites, host, sink);
}
/// `Item.getId` (0 when the registry report is missing).
pub fn item_id(&self, item: &str) -> i32 {
self.item_ids.get(item).copied().unwrap_or(0)
}
pub(crate) fn part(&self, key: &str) -> Option<&ModelPart> {
self.parts.get(key)
}
}
/// A `horizon-assets` (row-major, JOML-exact) matrix as glam's.
pub fn glam_matrix(m: &horizon_assets::math::Mat4) -> Mat4 {
Mat4::from_cols_array_2d(&m.rows()).transpose()
}
// ---------------------------------------------------------------------------
// Stacks
// ---------------------------------------------------------------------------
/// An NBT value as the JSON its component codec reads.
pub fn tag_json(tag: &Tag) -> Value {
match tag {
Tag::End => Value::Null,
Tag::Byte(v) => Value::from(*v),
Tag::Short(v) => Value::from(*v),
Tag::Int(v) => Value::from(*v),
Tag::Long(v) => Value::from(*v),
Tag::Float(bits) => serde_json::Number::from_f64(f64::from(f32::from_bits(*bits)))
.map_or(Value::Null, Value::Number),
Tag::Double(bits) => {
serde_json::Number::from_f64(f64::from_bits(*bits)).map_or(Value::Null, Value::Number)
}
Tag::ByteArray(a) => Value::Array(a.iter().map(|b| Value::from(*b as i8)).collect()),
Tag::String(s) => Value::String(s.to_string_lossy()),
Tag::List(l) => Value::Array(l.iter().map(tag_json).collect()),
Tag::Compound(c) => Value::Object(
c.iter()
.map(|(k, v)| (k.to_string_lossy(), tag_json(v)))
.collect(),
),
Tag::IntArray(a) => Value::Array(a.iter().map(|v| Value::from(*v)).collect()),
Tag::LongArray(a) => Value::Array(a.iter().map(|v| Value::from(*v)).collect()),
}
}
/// The resolver's view of a client stack: its item, count and component patch.
pub fn stack_view(stack: &crate::items::ItemStack) -> StackView {
let mut view = StackView::new(&stack.item, stack.count as i32);
if let Some(Tag::Compound(c)) = crate::item_data::components_tag(stack.damage, stack.data()) {
for (k, v) in &c {
let key = k.to_string_lossy();
match key.strip_prefix('!') {
Some(removed) => view.patch.insert(removed.to_owned(), None),
None => view.patch.insert(key, Some(tag_json(v))),
};
}
}
view
}
// ---------------------------------------------------------------------------
// World drawing
// ---------------------------------------------------------------------------
/// Entity vertices for submitted quads: the `item`/`entity` shader's
/// `minecraft_mix_light` with the level's diffuse lights on the vertex
/// colour, the packed lightmap coordinates (raised by light emission) and
/// overlay 7 for the glint.
pub struct WorldSink<'a> {
pub out: &'a mut Vec<Vertex>,
/// Packed light (`block_entity_render::vertex_light`).
pub light: u32,
/// The level's diffuse lights; `None` leaves the colour unshaded.
pub lights: Option<(Vec3, Vec3)>,
}
impl ItemSink for WorldSink<'_> {
fn quad(&mut self, q: ItemQuad) {
let brightness = self.lights.map_or(1.0, |l| diffuse(q.normal, l));
let [a, r, g, b] = q.color.to_be_bytes();
let c = |v: u8| (f32::from(v) * brightness) as u32;
let color = u32::from(a) << 24 | c(b) << 16 | c(g) << 8 | c(r);
// `LightCoordsUtil.lightCoordsWithEmission`: block light at least the emission.
let emission = u32::from(q.light_emission) * 16;
let light = if (self.light >> 8 & 0xFF) < emission {
(self.light & 0xFF) | emission << 8
} else {
self.light
};
let overlay = if q.foil == Foil::None { 0 } else { 7 };
for (p, uv) in q.pos.iter().zip(q.uv) {
self.out.push(Vertex {
pos: p.to_array(),
uv,
layer: overlay,
color,
light,
});
}
}
}
/// `ItemEntity.getSpin`.
pub fn item_spin(age_in_ticks: f32, bob_offset: f32) -> f32 {
age_in_ticks / 20.0 + bob_offset
}
/// `ItemClusterRenderState.getRenderedAmount`.
pub fn rendered_amount(count: u32) -> u32 {
match count {
0..=1 => 1,
2..=16 => 2,
17..=32 => 3,
33..=48 => 4,
_ => 5,
}
}
/// `ItemEntityRenderer.submitMultipleFromCount`: the poses of each copy of
/// a stack (`seed` is `ItemClusterRenderState.getSeedForItemStack`).
pub fn cluster_poses(state: &ItemRenderState, pose: Mat4, amount: u32, seed: i64) -> Vec<Mat4> {
use horizon_core::random::{LegacyRandom, RandomSource};
let mut out = Vec::new();
if amount == 0 {
return out;
}
let mut random = LegacyRandom::new(seed);
let (lo, hi) = state.bounding_box();
let depth = hi.z - lo.z;
let mut next = || random.next_float() * 2.0 - 1.0;
if depth > 0.0625 {
out.push(pose);
for _ in 1..amount {
let (x, y, z) = (next() * 0.15, next() * 0.15, next() * 0.15);
out.push(pose * Mat4::from_translation(Vec3::new(x, y, z)));
}
} else {
let offset = depth * 1.5;
let mut p = pose
* Mat4::from_translation(Vec3::new(0.0, 0.0, -(offset * (amount - 1) as f32 / 2.0)));
out.push(p);
p *= Mat4::from_translation(Vec3::new(0.0, 0.0, offset));
for _ in 1..amount {
let (x, y) = (next() * 0.15 * 0.5, next() * 0.15 * 0.5);
out.push(p * Mat4::from_translation(Vec3::new(x, y, 0.0)));
p *= Mat4::from_translation(Vec3::new(0.0, 0.0, offset));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rendered_amounts_follow_the_count_bands() {
let bands: Vec<u32> = [0, 1, 2, 16, 17, 32, 33, 48, 49, 64]
.iter()
.map(|c| rendered_amount(*c))
.collect();
assert_eq!(bands, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]);
}
#[test]
fn nbt_components_read_as_json() {
let tag = Tag::compound([
("a", Tag::Int(3)),
("b", Tag::List(vec![Tag::String("x".into())])),
("c", Tag::Float(1.5f32.to_bits())),
]);
assert_eq!(
tag_json(&tag),
serde_json::json!({"a": 3, "b": ["x"], "c": 1.5})
);
}
#[test]
fn normals_follow_the_inverse_transpose() {
let m = Mat4::from_scale(Vec3::new(2.0, 1.0, 1.0));
assert_eq!(transform_normal(m, Vec3::X), Vec3::X);
let r = Mat4::from_rotation_y(std::f32::consts::FRAC_PI_2);
assert!((transform_normal(r, Vec3::Z) - Vec3::X).length() < 1e-6);
}
}
@@ -0,0 +1,245 @@
//! `GuiGraphics.renderItem` drawn into the HUD batch: the item's layers are
//! submitted under the GUI item pose (`translate(x + 8, y + 8)`,
//! `scale(16, -16, 16)`), lit with `Lighting.Entry.ITEMS_3D` or `ITEMS_FLAT`
//! (`minecraft_mix_light` on the transformed normals), back faces culled,
//! drawn far to near, and clipped to the item's 16x16 slot unless the model
//! is oversized in the GUI (`GuiItemAtlas` draws each item into a scissored
//! 16x16 slot; oversized items get a picture-in-picture of their bounds).
use super::{Foil, ItemQuad, ItemRenderState, ItemRenderer, SpecialHost};
use crate::hud::{HudBatch, Rect};
use glam::{EulerRot, Mat4, Vec2, Vec3};
use std::{collections::HashMap, f32::consts::PI};
/// `Lighting.DIFFUSE_LIGHT_0` and `DIFFUSE_LIGHT_1`.
fn diffuse_lights() -> (Vec3, Vec3) {
(
Vec3::new(0.2, 1.0, -0.7).normalize(),
Vec3::new(-0.2, 1.0, 0.7).normalize(),
)
}
/// `Lighting.Entry.ITEMS_FLAT`: `rotationY(-PI/8).rotateX(3PI/4)`.
pub fn items_flat_lights() -> (Vec3, Vec3) {
let m = Mat4::from_rotation_y(-PI / 8.0) * Mat4::from_rotation_x(PI * 3.0 / 4.0);
let (a, b) = diffuse_lights();
(m.transform_vector3(a), m.transform_vector3(b))
}
/// JOML `rotateYXZ(y, x, z)`.
fn rotate_yxz(y: f32, x: f32, z: f32) -> Mat4 {
Mat4::from_euler(EulerRot::YXZ, y, x, z)
}
/// `Lighting.Entry.ITEMS_3D`.
pub fn items_3d_lights() -> (Vec3, Vec3) {
let m = Mat4::from_scale(Vec3::new(1.0, -1.0, 1.0))
* rotate_yxz(1.082_104_1, 3.237_585_8, 0.0)
* rotate_yxz(-PI / 8.0, PI * 3.0 / 4.0, 0.0);
let (a, b) = diffuse_lights();
(m.transform_vector3(a), m.transform_vector3(b))
}
/// A GUI-space vertex: position, atlas UV.
#[derive(Clone, Copy, Debug)]
struct Point {
p: Vec2,
uv: [f32; 2],
}
fn lerp(a: Point, b: Point, t: f32) -> Point {
Point {
p: a.p + (b.p - a.p) * t,
uv: [
a.uv[0] + (b.uv[0] - a.uv[0]) * t,
a.uv[1] + (b.uv[1] - a.uv[1]) * t,
],
}
}
/// Sutherland-Hodgman against one half plane `dot(p, n) <= limit`.
fn clip_edge(poly: &[Point], axis: usize, limit: f32, keep_below: bool) -> Vec<Point> {
let inside = |p: &Point| {
let v = p.p[axis];
if keep_below { v <= limit } else { v >= limit }
};
let mut out = Vec::with_capacity(poly.len() + 2);
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
let (ia, ib) = (inside(&a), inside(&b));
if ia {
out.push(a);
}
if ia != ib {
let t = (limit - a.p[axis]) / (b.p[axis] - a.p[axis]);
out.push(lerp(a, b, t));
}
}
out
}
/// A triangle clipped to `[x0, x1] x [y0, y1]`, as a fan.
fn clip_triangle(tri: [Point; 3], rect: [f32; 4]) -> Vec<Point> {
let mut poly = tri.to_vec();
for (axis, limit, below) in [
(0, rect[0], false),
(0, rect[2], true),
(1, rect[1], false),
(1, rect[3], true),
] {
if poly.is_empty() {
break;
}
poly = clip_edge(&poly, axis, limit, below);
}
poly
}
/// RGBA vertex colour of a lit quad: `minecraft_mix_light` on the tint.
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;
crate::hud::rgba(c(r), c(g), c(b), a)
}
/// The glint's moving sheen at a GUI position (a stand-in for the
/// `GLINT_TEXTURING`-scrolled `enchanted_glint_item` texture added on top).
fn glint_color(p: Vec2, time: f32) -> u32 {
let d = ((p.x + p.y) / 32.0 - time * 0.35).rem_euclid(1.0);
let band = (1.0 - (d - 0.5).abs() * 6.0).max(0.0);
crate::hud::rgba(
(170.0 + 70.0 * band) as u8,
(90.0 + 110.0 * band) as u8,
255,
(45.0 + 110.0 * band) as u8,
)
}
fn emit(batch: &mut HudBatch, fan: &[Point], color: impl Fn(Vec2) -> u32, glint: bool) {
let shift = if glint { 2.0 } else { 0.0 };
for i in 1..fan.len().saturating_sub(1) {
let (a, b, c) = (fan[0], fan[i], fan[i + 1]);
let corners = [a, b, c, c];
// `HudBatch.quad` draws (0, 1, 2) and (0, 2, 3): the second is empty.
batch.quad(
corners.map(|v| v.p.to_array()),
corners.map(|v| [v.uv[0] + shift, v.uv[1]]),
color(a.p),
);
if glint {
// Per-vertex colours are flat per quad in the HUD batch: use the
// fan centre for the sheen.
let n = batch.vertices.len();
for v in &mut batch.vertices[n - 6..] {
v.color = color(Vec2::from(v.pos));
}
}
}
}
/// Submit, light, cull, sort and clip one item's quads into `batch` at GUI
/// position `(x, y)`.
#[allow(clippy::too_many_arguments)]
pub fn draw(
state: &ItemRenderState,
renderer: &ItemRenderer,
sprites: &HashMap<String, Rect>,
host: &dyn SpecialHost,
batch: &mut HudBatch,
x: f32,
y: f32,
time: f32,
) {
if state.is_empty() {
return;
}
let pose = Mat4::from_translation(Vec3::new(x + 8.0, y + 8.0, 0.0))
* Mat4::from_scale(Vec3::new(16.0, -16.0, 16.0));
let mut quads: Vec<ItemQuad> = Vec::new();
state.submit(renderer, sprites, host, pose, &mut quads);
let lights = if state.uses_block_light() {
items_3d_lights()
} else {
items_flat_lights()
};
// Back-face culling: front faces wind counter-clockwise on screen with y up.
let mut visible: Vec<(f32, usize)> = quads
.iter()
.enumerate()
.filter(|(_, q)| {
let p = q.pos.map(|v| Vec2::new(v.x, -v.y));
let area: f32 = (0..4)
.map(|i| {
let (a, b) = (p[i], p[(i + 1) % 4]);
a.x * b.y - b.x * a.y
})
.sum();
area > 0.0
})
.map(|(i, q)| (q.pos.iter().map(|v| v.z).sum::<f32>() / 4.0, i))
.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 {
p: Vec2::new(q.pos[k].x, q.pos[k].y),
uv: q.uv[k],
});
let color = lit_color(q, lights);
for tri in [
[points[0], points[1], points[2]],
[points[0], points[2], points[3]],
] {
let fan = clip_triangle(tri, rect);
if fan.len() < 3 {
continue;
}
emit(batch, &fan, |_| color, false);
if q.foil != Foil::None {
emit(batch, &fan, |p| glint_color(p, time), true);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flat_lights_match_joml() {
// new Matrix4f().rotationY(-PI/8).rotateX(3PI/4).transformDirection(L0).
let (l0, _) = items_flat_lights();
let l = Vec3::new(0.2, 1.0, -0.7).normalize();
let (s, c) = ((3.0 * PI / 4.0).sin(), (3.0 * PI / 4.0).cos());
let rx = Vec3::new(l.x, c * l.y - s * l.z, s * l.y + c * l.z);
let (s, c) = ((-PI / 8.0).sin(), (-PI / 8.0).cos());
let ry = Vec3::new(c * rx.x + s * rx.z, rx.y, -s * rx.x + c * rx.z);
assert!((l0 - ry).length() < 1e-6);
}
#[test]
fn triangles_clip_to_the_slot() {
let p = |x: f32, y: f32| Point {
p: Vec2::new(x, y),
uv: [x, y],
};
let fan = clip_triangle(
[p(-4.0, 0.0), p(8.0, 0.0), p(8.0, 8.0)],
[0.0, 0.0, 16.0, 16.0],
);
assert!(fan.iter().all(|v| v.p.x >= 0.0));
// UVs follow the cut affinely.
assert!(fan.iter().all(|v| (v.uv[0] - v.p.x).abs() < 1e-6));
assert!(
clip_triangle(
[p(20.0, 0.0), p(30.0, 0.0), p(30.0, 5.0)],
[0.0, 0.0, 16.0, 16.0]
)
.is_empty()
);
}
}
@@ -0,0 +1,597 @@
//! `SpecialModelRenderer`s: items drawn with entity models (chests, shulker
//! boxes, banners, heads, shields, tridents, decorated pots, conduits, bells,
//! books and copper golem statues). Each submits its model at the layer pose
//! as vanilla's `submit` does (no block-entity placement transform) and
//! reports `getExtents` over the same posed parts.
use super::{Foil, ItemQuad, ItemRenderer, ItemSink, SpecialHost, argb};
use crate::{block_entity_render::ModelPart, hud::Rect};
use glam::{Mat4, Quat, Vec3};
use horizon_assets::item_model::{SpecialKind, SpecialModel};
use serde_json::Value;
use std::{collections::HashMap, f32::consts::PI, path::Path};
/// Entity model layers the special renderers bake (`ModelLayers`).
const LAYERS: [(&str, &str); 22] = [
("chest", "minecraft:chest#main"),
("double_chest_left", "minecraft:double_chest_left#main"),
("double_chest_right", "minecraft:double_chest_right#main"),
("shulker_box", "minecraft:shulker_box#main"),
("standing_banner", "minecraft:standing_banner#main"),
("standing_banner_flag", "minecraft:standing_banner#flag"),
("wall_banner", "minecraft:wall_banner#main"),
("wall_banner_flag", "minecraft:wall_banner#flag"),
("skeleton", "minecraft:skeleton_skull#main"),
("wither_skeleton", "minecraft:wither_skeleton_skull#main"),
("zombie", "minecraft:zombie_head#main"),
("creeper", "minecraft:creeper_head#main"),
("dragon", "minecraft:dragon_skull#main"),
("piglin", "minecraft:piglin_head#main"),
("player", "minecraft:player_head#main"),
("bell", "minecraft:bell#main"),
("book", "minecraft:book#main"),
("conduit_shell", "minecraft:conduit#shell"),
("decorated_pot_base", "minecraft:decorated_pot_base#main"),
("decorated_pot_sides", "minecraft:decorated_pot_sides#main"),
("shield", "minecraft:shield#main"),
("trident", "minecraft:trident#main"),
];
const COPPER_GOLEM_LAYERS: [(&str, &str); 4] = [
("copper_golem", "minecraft:copper_golem#main"),
(
"copper_golem_running",
"minecraft:copper_golem_running#main",
),
(
"copper_golem_sitting",
"minecraft:copper_golem_sitting#main",
),
("copper_golem_star", "minecraft:copper_golem_star#main"),
];
pub(super) fn load_parts(root: &Path) -> HashMap<String, ModelPart> {
let Ok(all) = std::fs::read(root.join("entity-models.json"))
.map_err(|_| ())
.and_then(|b| serde_json::from_slice::<Value>(&b).map_err(|_| ()))
else {
return HashMap::new();
};
LAYERS
.iter()
.chain(COPPER_GOLEM_LAYERS.iter())
.filter_map(|(key, layer)| {
all.get(*layer)
.map(|v| ((*key).to_owned(), ModelPart::parse(v)))
})
.collect()
}
/// A pose override for a named part (`setupAnim`).
type Adjust<'a> = &'a dyn Fn(&str, &mut [f32; 9]);
fn none(_: &str, _: &mut [f32; 9]) {}
/// `ModelPart.translateAndRotate`.
fn part_matrix(parent: Mat4, p: &[f32; 9]) -> Mat4 {
parent
* Mat4::from_translation(Vec3::new(p[0], p[1], p[2]) / 16.0)
* Mat4::from_quat(Quat::from_euler(glam::EulerRot::ZYX, p[5], p[4], p[3]))
* Mat4::from_scale(Vec3::new(p[6], p[7], p[8]))
}
/// `ModelPart.render` of `part` (named `name`) as item quads.
#[allow(clippy::too_many_arguments)]
fn draw(
part: &ModelPart,
name: &str,
parent: Mat4,
adjust: Adjust,
sprite: Rect,
color: u32,
foil: Foil,
sink: &mut dyn ItemSink,
) {
let mut p = part.pose;
adjust(name, &mut p);
let m = part_matrix(parent, &p);
for poly in &part.polygons {
let pos = poly.map(|v| m.transform_point3(Vec3::new(v[0], v[1], v[2]) / 16.0));
let normal = (pos[1] - pos[0]).cross(pos[2] - pos[0]).normalize_or_zero();
let normal = if normal == Vec3::ZERO {
(pos[2] - pos[1])
.cross(pos[3] - pos[1])
.normalize_or(Vec3::Y)
} else {
normal
};
sink.quad(ItemQuad {
pos,
uv: poly.map(|v| {
[
sprite.u0 + (sprite.u1 - sprite.u0) * v[3],
sprite.v0 + (sprite.v1 - sprite.v0) * v[4],
]
}),
normal,
color,
foil,
light_emission: 0,
});
}
for (child_name, child) in &part.children {
draw(child, child_name, m, adjust, sprite, color, foil, sink);
}
}
/// `ModelPart.getExtentsForGui` from an identity pose.
fn extents_of(part: &ModelPart, name: &str, parent: Mat4, adjust: Adjust, out: &mut Vec<Vec3>) {
if part.polygons.is_empty() && part.children.is_empty() {
return;
}
let mut p = part.pose;
adjust(name, &mut p);
let m = part_matrix(parent, &p);
for poly in &part.polygons {
for v in poly {
let q = m.transform_point3(Vec3::new(v[0], v[1], v[2]) / 16.0);
if !out.contains(&q) {
out.push(q);
}
}
}
for (child_name, child) in &part.children {
extents_of(child, child_name, m, adjust, out);
}
}
fn child<'a>(part: &'a ModelPart, name: &str) -> Option<&'a ModelPart> {
part.child(name)
}
/// A texture identifier relative to `textures/` (`minecraft:entity/x` or a
/// full `minecraft:textures/entity/x.png`) as its atlas sprite name.
fn texture_sprite(id: &str) -> String {
let path = id.strip_prefix("minecraft:").unwrap_or(id);
let path = path.strip_prefix("textures/").unwrap_or(path);
path.strip_suffix(".png").unwrap_or(path).to_owned()
}
fn mapped(directory: &str, id: &str) -> String {
format!(
"entity/{directory}/{}",
id.strip_prefix("minecraft:").unwrap_or(id)
)
}
/// `DyeColor.getTextureDiffuseColor` as ARGB.
fn dye(name: &str) -> u32 {
0xFF00_0000 | crate::banner::dye_rgb(name)
}
/// The chest model of a chest type, with `ChestModel.setupAnim(openness)`.
fn chest_model(chest_type: &str) -> &'static str {
match chest_type {
"left" => "double_chest_left",
"right" => "double_chest_right",
_ => "chest",
}
}
fn skull_layer(kind: &str) -> &'static str {
match kind {
"skeleton" => "skeleton",
"wither_skeleton" => "wither_skeleton",
"zombie" => "zombie",
"creeper" => "creeper",
"dragon" => "dragon",
"piglin" => "piglin",
_ => "player",
}
}
/// `SkullBlockRenderer.SKIN_BY_TYPE`.
fn skull_texture(kind: &str) -> &'static str {
match kind {
"skeleton" => "entity/skeleton/skeleton",
"wither_skeleton" => "entity/skeleton/wither_skeleton",
"zombie" => "entity/zombie/zombie",
"creeper" => "entity/creeper/creeper",
"dragon" => "entity/enderdragon/dragon",
"piglin" => "entity/piglin/piglin",
_ => "entity/player/wide/steve",
}
}
/// `SkullModelBase.setupAnim` for a head at `animation` (yRot = xRot = 0).
fn skull_pose(kind: &str, animation: f32) -> impl Fn(&str, &mut [f32; 9]) + '_ {
move |name: &str, p: &mut [f32; 9]| match (kind, name) {
(_, "head") => {
p[3] = 0.0;
p[4] = 0.0;
}
("dragon", "jaw") => p[3] = (((animation * PI * 0.2) as f64).sin() as f32 + 1.0) * 0.2,
("piglin", "left_ear") => {
p[5] = -((((animation * PI * 0.2 * 1.2) as f64).cos() + 2.5) as f32) * 0.2;
}
("piglin", "right_ear") => {
p[5] = ((((animation * PI * 0.2) as f64).cos() + 2.5) as f32) * 0.2;
}
_ => {}
}
}
fn shulker_pose(progress: f32) -> impl Fn(&str, &mut [f32; 9]) {
move |name: &str, p: &mut [f32; 9]| {
if name == "lid" {
p[0] = 0.0;
p[1] = 24.0 - progress * 0.5 * 16.0;
p[2] = 0.0;
p[4] = 270.0 * progress * (PI / 180.0);
}
}
}
fn chest_pose(open: f32) -> impl Fn(&str, &mut [f32; 9]) {
move |name: &str, p: &mut [f32; 9]| {
if name == "lid" || name == "lock" {
p[3] = -(open * (PI / 2.0));
}
}
}
/// `BannerFlagModel.setupAnim(0)`.
fn flag_pose(name: &str, p: &mut [f32; 9]) {
if name == "flag" {
p[3] = (-0.0125 + 0.01 * (2.0 * PI * 0.0f32).cos()) * PI;
}
}
/// `BookModel.setupAnim`.
fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; 9]) {
move |name: &str, p: &mut [f32; 9]| match name {
"left_lid" => p[4] = PI + openness,
"right_lid" => p[4] = -openness,
"left_pages" => {
p[4] = openness;
p[0] = openness.sin();
}
"right_pages" => {
p[4] = -openness;
p[0] = openness.sin();
}
"flip_page1" => {
p[4] = openness - openness * 2.0 * flip1;
p[0] = openness.sin();
}
"flip_page2" => {
p[4] = openness - openness * 2.0 * flip2;
p[0] = openness.sin();
}
_ => {}
}
}
/// `CopperGolemStatueModel.setupAnim`.
fn statue_pose(name: &str, p: &mut [f32; 9]) {
if name == "root" {
p[1] = 0.0;
p[5] = PI;
}
}
fn statue_layer(pose: &str) -> &'static str {
match pose {
"running" => "copper_golem_running",
"sitting" => "copper_golem_sitting",
"star" => "copper_golem_star",
_ => "copper_golem",
}
}
/// `SpecialModelRenderer.getExtents`.
pub(super) fn extents(renderer: &ItemRenderer, model: &SpecialModel) -> Vec<Vec3> {
let mut out = Vec::new();
let id = Mat4::IDENTITY;
let mut add = |key: &str, adjust: Adjust| {
if let Some(part) = renderer.part(key) {
extents_of(part, "root", id, adjust, &mut out);
}
};
match &model.kind {
SpecialKind::Bell => add("bell", &none),
SpecialKind::Banner { .. } => {
// `BannerRenderer.getExtents`: the standing models only.
add("standing_banner", &none);
add("standing_banner_flag", &flag_pose);
}
SpecialKind::Book {
open_angle,
page1,
page2,
} => add(
"book",
&book_pose(open_angle * (PI / 180.0), *page1, *page2),
),
SpecialKind::Conduit => add("conduit_shell", &none),
SpecialKind::Chest {
openness,
chest_type,
..
} => add(chest_model(chest_type), &chest_pose(*openness)),
SpecialKind::CopperGolemStatue { pose, .. } => add(statue_layer(pose), &statue_pose),
SpecialKind::DecoratedPot => {
if let Some(base) = renderer.part("decorated_pot_base") {
// `neck`, `top` and `bottom` are posed from an identity stack.
for name in ["neck", "top", "bottom"] {
if let Some(part) = child(base, name) {
extents_of(part, name, id, &none, &mut out);
}
}
}
}
SpecialKind::EndCube { .. } => {}
SpecialKind::Head {
kind, animation, ..
} => add(skull_layer(kind), &skull_pose(kind, *animation)),
SpecialKind::PlayerHead => add("player", &none),
SpecialKind::ShulkerBox { openness, .. } => add("shulker_box", &shulker_pose(*openness)),
SpecialKind::Shield => add("shield", &none),
SpecialKind::Trident => add("trident", &none),
}
out
}
/// Banner pattern layers of a `minecraft:banner_patterns` value: the
/// pattern identifier (or inline asset) and the dye.
fn pattern_layers(v: &Value) -> Vec<(String, String)> {
v.as_array()
.into_iter()
.flatten()
.filter_map(|layer| {
let pattern = match &layer["pattern"] {
Value::String(s) => s.clone(),
Value::Object(o) => format!("#asset:{}", o.get("asset_id")?.as_str()?),
_ => return None,
};
let color = layer["color"].as_str()?.to_owned();
Some((pattern, color))
})
.collect()
}
fn pattern_texture(host: &dyn SpecialHost, banner: bool, pattern: &str) -> Option<String> {
if let Some(asset) = pattern.strip_prefix("#asset:") {
let path = asset.strip_prefix("minecraft:").unwrap_or(asset);
return Some(format!(
"entity/{}/{path}",
if banner { "banner" } else { "shield" }
));
}
if banner {
host.banner_texture(pattern)
} else {
host.shield_texture(pattern)
}
}
/// `DecoratedPotPatterns.getPatternFromItem` for one side's sherd item.
fn pot_side(item: Option<&str>) -> String {
let item = item.map(|i| i.strip_prefix("minecraft:").unwrap_or(i));
match item.and_then(|i| i.strip_suffix("_pottery_sherd")) {
Some(name) => format!("entity/decorated_pot/{name}_pottery_pattern"),
None => "entity/decorated_pot/decorated_pot_side".to_owned(),
}
}
/// `PotDecorations` as [back, left, right, front] item ids, from the list
/// codec or a keyed object.
fn pot_sides(v: &Value) -> [Option<String>; 4] {
let id = |s: &Value| match s {
Value::String(s) => Some(s.clone()),
Value::Object(o) => o.get("id").and_then(Value::as_str).map(str::to_owned),
_ => None,
};
match v {
Value::Array(a) => std::array::from_fn(|i| a.get(i).and_then(id)),
Value::Object(o) => ["back", "left", "right", "front"].map(|k| o.get(k).and_then(id)),
_ => Default::default(),
}
}
/// `SpecialModelRenderer.submit`.
#[allow(clippy::too_many_arguments)]
pub(super) fn submit(
renderer: &ItemRenderer,
model: &SpecialModel,
argument: &Value,
has_foil: bool,
pose: Mat4,
sprites: &HashMap<String, Rect>,
host: &dyn SpecialHost,
sink: &mut dyn ItemSink,
) {
let white = argb(-1);
let mut part = |key: &str, adjust: Adjust, texture: &str, color: u32, foil: Foil| {
if let (Some(p), Some(r)) = (renderer.part(key), sprites.get(texture).copied()) {
draw(p, "root", pose, adjust, r, color, foil, sink);
}
};
match &model.kind {
SpecialKind::Bell => part("bell", &none, "entity/bell/bell_body", white, Foil::None),
SpecialKind::Book {
open_angle,
page1,
page2,
} => part(
"book",
&book_pose(open_angle * (PI / 180.0), *page1, *page2),
"entity/enchantment/enchanting_table_book",
white,
Foil::None,
),
SpecialKind::Conduit => {
part(
"conduit_shell",
&none,
"entity/conduit/base",
white,
Foil::None,
);
}
SpecialKind::Chest {
texture,
openness,
chest_type,
} => part(
chest_model(chest_type),
&chest_pose(*openness),
&mapped("chest", texture),
white,
Foil::None,
),
SpecialKind::ShulkerBox { texture, openness } => part(
"shulker_box",
&shulker_pose(*openness),
&mapped("shulker", texture),
white,
Foil::None,
),
SpecialKind::CopperGolemStatue { texture, pose: p } => part(
statue_layer(p),
&statue_pose,
&texture_sprite(texture),
white,
Foil::None,
),
SpecialKind::Head {
kind,
texture,
animation,
} => {
let skin = texture
.as_deref()
.map(|t| format!("entity/{}", t.strip_prefix("minecraft:").unwrap_or(t)))
.unwrap_or_else(|| skull_texture(kind).to_owned());
part(
skull_layer(kind),
&skull_pose(kind, *animation),
&skin,
white,
Foil::None,
);
}
SpecialKind::PlayerHead => {
let skin = (!argument.is_null())
.then(|| host.player_skin(argument))
.flatten()
.unwrap_or_else(|| "entity/player/wide/steve".to_owned());
part("player", &none, &skin, white, Foil::None);
}
SpecialKind::Trident => {
let foil = if has_foil { Foil::Standard } else { Foil::None };
part("trident", &none, "entity/trident/trident", white, foil);
}
SpecialKind::Banner { color, wall } => {
let (main, flag) = if *wall {
("wall_banner", "wall_banner_flag")
} else {
("standing_banner", "standing_banner_flag")
};
part(main, &none, "entity/banner/banner_base", white, Foil::None);
part(
flag,
&flag_pose,
"entity/banner/banner_base",
white,
Foil::None,
);
// `submitPatterns`: the base layer in the banner's colour, then up to 16 layers.
part(
flag,
&flag_pose,
"entity/banner/base",
dye(color),
Foil::None,
);
for (pattern, color) in pattern_layers(argument).into_iter().take(16) {
if let Some(t) = pattern_texture(host, true, &pattern) {
part(flag, &flag_pose, &t, dye(&color), Foil::None);
}
}
}
SpecialKind::Shield => {
let patterns = pattern_layers(&argument["minecraft:banner_patterns"]);
let base_color = argument["minecraft:base_color"].as_str();
let has_patterns = !patterns.is_empty() || base_color.is_some();
let base = if has_patterns {
"entity/shield/shield_base"
} else {
"entity/shield/shield_base_nopattern"
};
let foil = if has_foil && !has_patterns {
Foil::Standard
} else {
Foil::None
};
part("shield", &none, base, white, foil);
if has_patterns {
part(
"shield",
&none,
"entity/shield/base",
dye(base_color.unwrap_or("white")),
Foil::None,
);
for (pattern, color) in patterns.into_iter().take(16) {
if let Some(t) = pattern_texture(host, false, &pattern) {
part("shield", &none, &t, dye(&color), Foil::None);
}
}
if has_foil {
// `patternedShieldGlint`: the glint alone over the model.
part("shield", &none, base, white, Foil::Standard);
}
}
}
SpecialKind::DecoratedPot => {
let sides = pot_sides(argument);
if let Some(base) = renderer.part("decorated_pot_base")
&& let Some(r) = sprites
.get("entity/decorated_pot/decorated_pot_base")
.copied()
{
for name in ["neck", "top", "bottom"] {
if let Some(p) = child(base, name) {
draw(p, name, pose, &none, r, white, Foil::None, sink);
}
}
}
if let Some(side_parts) = renderer.part("decorated_pot_sides") {
for (i, name) in ["back", "left", "right", "front"].into_iter().enumerate() {
let texture = pot_side(sides[i].as_deref());
if let (Some(p), Some(r)) = (child(side_parts, name), sprites.get(&texture)) {
draw(p, name, pose, &none, *r, white, Foil::None, sink);
}
}
}
}
// `EndCubeSpecialRenderer` draws the end portal/gateway effect; no
// bundled item uses it.
SpecialKind::EndCube { .. } => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pot_sides_read_both_shapes() {
let list = serde_json::json!(["minecraft:brick", "minecraft:angler_pottery_sherd"]);
let sides = pot_sides(&list);
assert_eq!(
pot_side(sides[0].as_deref()),
"entity/decorated_pot/decorated_pot_side"
);
assert_eq!(
pot_side(sides[1].as_deref()),
"entity/decorated_pot/angler_pottery_pattern"
);
assert_eq!(
pot_side(sides[3].as_deref()),
"entity/decorated_pot/decorated_pot_side"
);
}
#[test]
fn texture_ids_map_to_sprites() {
assert_eq!(
texture_sprite("minecraft:textures/entity/copper_golem/copper_golem.png"),
"entity/copper_golem/copper_golem"
);
assert_eq!(
mapped("chest", "minecraft:christmas"),
"entity/chest/christmas"
);
}
}
+2
View File
@@ -5,6 +5,7 @@ pub mod advancements;
pub mod ambience;
pub mod animate_tick;
pub mod assets;
pub mod atlas_sources;
pub mod attribute_updates;
pub mod audio;
pub mod auto_jump;
@@ -47,6 +48,7 @@ pub mod hud_layout;
pub mod hunger;
pub mod input;
pub mod item_data;
pub mod item_render;
pub mod items;
pub mod java_text;
pub mod key_names;
+1
View File
@@ -101,6 +101,7 @@ impl AnimState {
pub fn end_tick(&mut self, _swinging: bool) {}
}
/// Part poses for one draw, keyed by part name.
#[derive(Clone)]
pub struct Poses {
map: HashMap<String, [f32; 9]>,
dummy: [f32; 9],
+5 -158
View File
@@ -915,7 +915,6 @@ fn render_visible(
for (part, uv, color) in extra {
draw(part, base, &poses, *uv, *color, light, overlay, out);
}
held_items(m, &model, base, &poses, atlas, light, out);
let mut all_layers = layers(m);
// WardenRenderer: the translucent emissive layers fade with the animations.
if m.species() == Species::Warden {
@@ -1013,57 +1012,6 @@ pub fn part_matrix(
.iter()
.find_map(|c| part_matrix(c, m, poses, name, x_offset))
}
/// ItemModel thirdperson_righthand display transform by item model parent.
fn item_display(item: &str) -> ([f32; 3], [f32; 3], [f32; 3]) {
let name = item.trim_start_matches("minecraft:");
if name == "bow" {
([-80.0, 260.0, -40.0], [-1.0, -2.0, 2.5], [0.9; 3])
} else if name == "crossbow" {
([-90.0, 0.0, -60.0], [2.0, 0.1, -3.0], [0.9; 3])
} else if name == "fishing_rod"
|| name == "carrot_on_a_stick"
|| name == "warped_fungus_on_a_stick"
{
([0.0, 90.0, 55.0], [0.0, 4.0, 2.5], [0.85; 3])
} else if [
"_sword",
"_axe",
"_pickaxe",
"_shovel",
"_hoe",
"trident",
"mace",
"stick",
"bone",
"blaze_rod",
]
.iter()
.any(|t| name.ends_with(t))
{
([0.0, -90.0, 55.0], [0.0, 4.0, 0.5], [0.85; 3])
} else {
([0.0, 0.0, 0.0], [0.0, 3.0, 1.0], [0.55; 3])
}
}
/// The sprite drawn for a held item (bow pull frames while charging).
fn item_sprite(m: &Mob, item: &str) -> String {
let name = item.trim_start_matches("minecraft:");
if name == "bow" && m.extra.using_item > 0 {
let pull = m.extra.using_item as f32 * 0.05;
let frame = if pull >= 0.9 {
2
} else if pull >= 0.65 {
1
} else {
0
};
return format!("item/bow_pulling_{frame}");
}
if name == "crossbow" && m.extra.flag2 {
return "item/crossbow_arrow".into();
}
format!("item/{name}")
}
/// The hand of a mob in model space, up to the item's own transform
/// (`ItemInHandLayer.submitArmWithItem`).
fn hand_base(
@@ -1122,10 +1070,10 @@ pub fn part_transform(
anim::setup(m, &s, &mut poses, &data.animations);
part_matrix(&model, base, &poses, part, 0.0)
}
/// Where a mob holds a block item (`block/block` thirdperson display: turned
/// 75 and 45 degrees, at 0.375 scale), as the hand transform for `left`, or
/// `None` when the mob shows no held items.
pub fn held_block_transform(
/// The pose a mob's held item is submitted under (`ItemInHandLayer`:
/// `translateToHand`, then the hand offset; the item model adds its own
/// display transform), or `None` when the mob shows no held items.
pub fn held_item_transform(
m: &Mob,
alpha: f32,
camera: glam::DVec3,
@@ -1145,106 +1093,5 @@ pub fn held_block_transform(
.unwrap_or_else(|| m.kind.model.clone());
let mut poses = Poses::new(&model);
anim::setup(m, &s, &mut poses, &data.animations);
let mut t = hand_base(m, &model, base, &poses, left)?;
let ry = if left { -45.0f32 } else { 45.0 };
t *= glam::Mat4::from_translation(glam::Vec3::new(0.0, 2.5, 0.0) / 16.0);
t *= glam::Mat4::from_quat(glam::Quat::from_euler(
glam::EulerRot::XYZ,
75.0f32.to_radians(),
ry.to_radians(),
0.0,
));
t *= glam::Mat4::from_scale(glam::Vec3::splat(0.375));
t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
Some(t)
}
/// ItemInHandLayer: items in the mob's hands.
fn held_items(
m: &Mob,
model: &Part,
base: glam::Mat4,
poses: &Poses,
atlas: Atlas,
light: u32,
out: &mut Vec<Vertex>,
) {
if !super::illager::shows_item(m) {
return;
}
for (item, left) in [(&m.extra.main_hand, false), (&m.extra.off_hand, true)] {
let Some(item) = item else { continue };
let Some(mut t) = hand_base(m, model, base, poses, left) else {
continue;
};
let Some(uv) = atlas(&item_sprite(m, item)) else {
continue;
};
// ItemTransform.apply (mirrored for the left hand).
let (rot, tr, sc) = item_display(item);
let (ry, rz, tx) = if left {
(-rot[1], -rot[2], -tr[0])
} else {
(rot[1], rot[2], tr[0])
};
t *= glam::Mat4::from_translation(glam::Vec3::new(tx, tr[1], tr[2]) / 16.0);
t *= glam::Mat4::from_quat(glam::Quat::from_euler(
glam::EulerRot::XYZ,
rot[0].to_radians(),
ry.to_radians(),
rz.to_radians(),
));
t *= glam::Mat4::from_scale(glam::Vec3::from(sc));
t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
let glint = super::gear::enchanted(
m,
if left {
super::gear::OFF
} else {
super::gear::MAIN
},
);
draw_item_plane_with(t, uv, light, if glint { 7 } else { 0 }, out);
}
}
/// A generated item model: the sprite on two faces 1/16 apart.
pub fn draw_item_plane(t: glam::Mat4, uv: [f32; 4], light: u32, out: &mut Vec<Vertex>) {
draw_item_plane_with(t, uv, light, 0, out);
}
/// `draw_item_plane` with an entity shader overlay (7: enchantment glint).
pub fn draw_item_plane_with(
t: glam::Mat4,
uv: [f32; 4],
light: u32,
overlay: u32,
out: &mut Vec<Vertex>,
) {
let (u0, v0, u1, v1) = (uv[0], uv[1], uv[2], uv[3]);
let south = 8.5 / 16.0;
let north = 7.5 / 16.0;
let quads = [
[
([0.0, 0.0, south], [u0, v1]),
([1.0, 0.0, south], [u1, v1]),
([1.0, 1.0, south], [u1, v0]),
([0.0, 1.0, south], [u0, v0]),
],
[
([1.0, 0.0, north], [u1, v1]),
([0.0, 0.0, north], [u0, v1]),
([0.0, 1.0, north], [u0, v0]),
([1.0, 1.0, north], [u1, v0]),
],
];
for q in quads {
for (p, uv) in q {
let pos = t.transform_point3(glam::Vec3::from(p));
out.push(Vertex {
pos: pos.to_array(),
uv,
layer: overlay,
color: 0xFFFF_FFFF,
light,
});
}
}
hand_base(m, &model, base, &poses, left)
}
+1 -1
View File
@@ -3,7 +3,7 @@
//! and High Contrast packs, `pack.mcmeta` metadata and format compatibility,
//! and an overlay resource root that layers the enabled packs over the
//! vanilla resources (later packs win), so every loader sees one tree.
mod pattern;
pub mod pattern;
use crate::{text::Text, zip::Zip};
use pattern::Pattern;
use std::{