diff --git a/crates/horizon-client/examples/probe/block_entity_render_fixture.rs b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs index a0e3471bc..1db978b77 100644 --- a/crates/horizon-client/examples/probe/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/probe/block_entity_render_fixture.rs @@ -367,6 +367,7 @@ pub fn main() -> Result<()> { lid: &|_| open, sign: &|_| sign.as_ref(), banner: &|_| layers.clone(), + skull: &|_| None, glyph: &|c| atlas.glyph_cell(c), }; let mut verts = Vec::new(); diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index af4168307..a863d6214 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -730,6 +730,10 @@ pub struct Scene<'a> { pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, /// Banner layers at a position: pattern texture and RGB tint, bottom first. pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>, + /// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer` + /// profile → skin): a downloaded `skins/` slot or the profile's + /// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (steve). + pub skull: &'a dyn Fn([i32; 3]) -> Option, /// Font glyph cell (none for blank glyphs such as the space) and advance. pub glyph: &'a dyn Fn(char) -> (Option, f32), } @@ -1277,7 +1281,16 @@ impl BlockEntityRenderer { SkullType::Creeper => ("creeper_head", "entity/creeper/creeper"), SkullType::Dragon => ("dragon_skull", "entity/enderdragon/dragon"), SkullType::Piglin => ("piglin_head", "entity/piglin/piglin"), - SkullType::Player => ("player_head", "entity/player/slim/steve"), + SkullType::Player => ("player_head", "entity/player/wide/steve"), + }; + // SkullBlockRenderer.getRenderType: the profile's skin when it + // resolves, `SKIN_BY_TYPE` (steve) otherwise. + let skin; + let texture = if *kind == SkullType::Player { + skin = (scene.skull)(pos); + skin.as_deref().unwrap_or(texture) + } else { + texture }; let (Some(model), Some(paint)) = (self.models.get(model), paint(texture, 0xFFFFFF, packed)) @@ -1886,6 +1899,7 @@ mod tests { lid: &|_| 0.0, sign: &|_| None, banner: &|_| Vec::new(), + skull: &|_| None, glyph: &|_| (None, 0.0), }; // Compare the cached world path with the original model renderer, diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index de2e1b2e9..7c9da6862 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -79,6 +79,17 @@ pub enum BlockEntity { Beehive(Box), /// `CommandBlockEntity` of the three command blocks (`crate::command_block`). CommandBlock(Box), + /// `SkullBlockEntity` of every skull and head block. + Skull(Skull), +} +/// `SkullBlockEntity`: the player profile the head shows (kept as loaded — +/// `SkullOwner` is a compound, or a string when it names a player only), +/// the note block sound and `custom_name`. +#[derive(Clone, Debug, Default)] +pub struct Skull { + pub profile: Option, + pub note_block_sound: Option, + pub custom_name: Option, } /// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag /// and the ticks left in the crafting animation. @@ -233,6 +244,9 @@ impl BlockEntity { if name.ends_with("_banner") { return Some(Self::Banner(Banner::default())); } + if name.ends_with("_head") || name.ends_with("_skull") { + return Some(Self::Skull(Skull::default())); + } if name == "minecraft:beacon" { return Some(Self::Beacon(Box::new(Beacon { last_check_y: i32::MIN / 2, @@ -278,6 +292,7 @@ impl BlockEntity { Self::Vault(_) => "minecraft:vault", Self::Beehive(_) => "minecraft:beehive", Self::CommandBlock(_) => "minecraft:command_block", + Self::Skull(_) => "minecraft:skull", } } pub fn contents(&self) -> Vec { @@ -293,7 +308,8 @@ impl BlockEntity { | Self::TrialSpawner(_) | Self::Vault(_) | Self::Beehive(_) - | Self::CommandBlock(_) => Vec::new(), + | Self::CommandBlock(_) + | Self::Skull(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), @@ -310,7 +326,8 @@ impl BlockEntity { | Self::Beacon(_) | Self::Lectern(_) | Self::Sculk(_) - | Self::Banner(_) => &[], + | Self::Banner(_) + | Self::Skull(_) => &[], Self::Crafter(c) => &c.items, Self::CreakingHeart(_) | Self::Spawner(_) @@ -330,7 +347,8 @@ impl BlockEntity { | Self::Beacon(_) | Self::Lectern(_) | Self::Sculk(_) - | Self::Banner(_) => &mut [], + | Self::Banner(_) + | Self::Skull(_) => &mut [], Self::Crafter(c) => &mut c.items, Self::CreakingHeart(_) | Self::Spawner(_) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 52d7ce8dd..bfdebe44a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5133,7 +5133,8 @@ impl Game<'_> { | BlockEntity::TrialSpawner(_) | BlockEntity::Vault(_) | BlockEntity::Beehive(_) - | BlockEntity::CommandBlock(_), + | BlockEntity::CommandBlock(_) + | BlockEntity::Skull(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -5392,7 +5393,8 @@ impl Game<'_> { | BlockEntity::TrialSpawner(_) | BlockEntity::Vault(_) | BlockEntity::Beehive(_) - | BlockEntity::CommandBlock(_), + | BlockEntity::CommandBlock(_) + | BlockEntity::Skull(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { @@ -6884,6 +6886,7 @@ impl Game<'_> { _ => None, }, banner: &|p| self.banner_layers_at(p), + skull: &|p| self.skull_skin_at(p), glyph: &|c| self.gui.atlas.glyph_cell(c), }; // Block entities outside the view frustum are skipped (with a diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 619fcd009..136738350 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -8,8 +8,10 @@ use horizon_client::{ block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker}, block_entity_render::BlockAnim, collisions::{SceneCollisions, no_collision_empty}, + containers::BlockEntity, particles::{ParticleOptions, ParticleType}, save::number, + skins, }; use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::nbt::Tag; @@ -392,4 +394,34 @@ impl Game<'_> { pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 { self.be_anims.lid(pos, partial) } + /// `SkullBlockRenderer.getPlayerSkin`: the skin sprite of the `profile` of + /// the player head at `pos`. The skin download is started here; while it + /// is in flight (or when it cannot be got) the profile's uuid picks the + /// `DefaultPlayerSkin` for it, and a profile with no id keeps steve. A + /// head with no profile answers None so `SKIN_BY_TYPE` applies. + pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option { + let key = (pos[0], pos[1], pos[2]); + let profile = match self.world.block_entities.get(&key) { + Some(BlockEntity::Skull(s)) => s.profile.clone(), + _ => None, + } + .or_else(|| self.saved_tag(pos).and_then(|t| t.get("profile").cloned())); + let profile = profile?; + if let Some(url) = skins::profile_skin_url_nbt(&profile) + && let Some(location) = + skins::texture_hash(&url).map(|hash| skins::skin_location(&hash)) + { + self.skin_downloads + .borrow_mut() + .state(skins::Kind::Skin, &url); + if self.gui.atlas.sprites.contains_key(&location) { + return Some(location); + } + } + Some( + skins::profile_uuid_nbt(&profile) + .map(|uuid| horizon_client::tab_list::default_skin(uuid).to_owned()) + .unwrap_or_else(|| "entity/player/wide/steve".to_owned()), + ) + } } diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 6b8b51dde..8d4920b48 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1463,6 +1463,7 @@ impl Game<'_> { lid: &lid, sign: &|_| None, banner: &|_| Vec::new(), + skull: &|_| None, glyph: &|c| self.gui.atlas.glyph_cell(c), }; self.res diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 65b092881..d7dcc6cd8 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -937,6 +937,20 @@ pub fn entity_tag(entity: &BlockEntity) -> Option { match entity { BlockEntity::Sign(sign) => Some(Tag::compound(sign.encode())), BlockEntity::Spawner(s) => Some(s.update_tag()), + // SkullBlockEntity: the profile is the whole reason a head differs. + BlockEntity::Skull(s) => { + let mut entries = Vec::new(); + if let Some(profile) = &s.profile { + entries.push(("profile", profile.clone())); + } + if let Some(sound) = &s.note_block_sound { + entries.push(("note_block_sound", Tag::String(sound.as_str().into()))); + } + if let Some(name) = &s.custom_name { + entries.push(("custom_name", name.clone())); + } + Some(Tag::compound(entries)) + } BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None, _ => None, } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index da5735c17..c59c3c974 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -548,6 +548,17 @@ pub fn encode_block_entity( entries.push(("creaking", uuid_tag(uuid))); } } + BlockEntity::Skull(s) => { + if let Some(profile) = &s.profile { + entries.push(("profile", profile.clone())); + } + if let Some(sound) = &s.note_block_sound { + entries.push(("note_block_sound", string(sound))); + } + if let Some(name) = &s.custom_name { + entries.push(("custom_name", name.clone())); + } + } BlockEntity::Spawner(s) => entries.extend(s.save()), BlockEntity::TrialSpawner(s) => entries.extend(s.save()), BlockEntity::Vault(v) => entries.extend(v.save()), @@ -622,6 +633,19 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain }; return Some((pos, BlockEntity::Beacon(Box::new(beacon)))); } + // A skull's block entity id is not its block's name (every head block). + if id == "minecraft:skull" { + return Some(( + pos, + BlockEntity::Skull(crate::containers::Skull { + profile: tag.get("profile").cloned(), + note_block_sound: text(tag.get("note_block_sound")), + custom_name: tag + .get("custom_name") + .and_then(crate::block_entity_nbt::component), + }), + )); + } // A spawner's block entity id is not its block's name. let block = match id.as_str() { "minecraft:mob_spawner" => "minecraft:spawner", @@ -683,7 +707,8 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) | BlockEntity::Banner(_) - | BlockEntity::CreakingHeart(_) => {} + | BlockEntity::CreakingHeart(_) + | BlockEntity::Skull(_) => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag), BlockEntity::Vault(v) => **v = crate::vault::Vault::load(tag), @@ -3876,6 +3901,47 @@ mod tests { } use super::*; + #[test] + fn skull_block_entity_keeps_its_profile() { + // A placed `player_head` as vanilla saves it: the owning player's + // `profile` survives load, encode and `canonical`. + let saved = horizon_world::nbt::parse_snbt( + r#"{id:"minecraft:skull",x:10,y:64,z:20,profile:{name:"Steve",id:[I;1,2,3,4],properties:[{name:"textures",value:"abc"}]},note_block_sound:"minecraft:entity.player.hurt",custom_name:"Trophy"}"#, + ) + .unwrap() + .0; + let (pos, back) = decode_block_entity(&saved).expect("skull"); + assert_eq!(pos, (10, 64, 20)); + let crate::containers::BlockEntity::Skull(skull) = &back else { + panic!("not a skull"); + }; + assert_eq!(skull.profile, saved.get("profile").cloned()); + assert_eq!( + skull.note_block_sound.as_deref(), + Some("minecraft:entity.player.hurt") + ); + assert_eq!(back.id(), "minecraft:skull"); + let tag = encode_block_entity(pos, &back, "minecraft:player_head"); + assert_eq!( + crate::block_entity_nbt::id(&tag).as_deref(), + Some("minecraft:skull") + ); + assert_eq!(tag.get("profile"), saved.get("profile")); + let (_, again) = decode_block_entity(&tag).expect("skull again"); + let crate::containers::BlockEntity::Skull(again) = again else { + panic!("not a skull"); + }; + assert_eq!(again.profile, skull.profile); + // A profile-less head (skeleton, creeper) round-trips too. + let plain = encode_block_entity( + pos, + &crate::containers::BlockEntity::Skull(crate::containers::Skull::default()), + "minecraft:creeper_head", + ); + let (_, decoded) = decode_block_entity(&plain).expect("plain skull"); + assert!(matches!(decoded, crate::containers::BlockEntity::Skull(_))); + } + #[test] fn uuid_text_round_trips() { let u = [-158327916, 1572358581, -2125825222, -487948715]; diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index 9014032c4..ee6851e00 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -130,6 +130,47 @@ pub fn profile_skin_url(profile: &serde_json::Value) -> Option { unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin } +/// `profile_skin_url` on a block entity's `profile` NBT (`SkullBlockEntity`): +/// the same `properties` list, held as a compound. A name-only profile (a +/// string tag) has no properties and no skin URL. +pub fn profile_skin_url_nbt(profile: &horizon_world::nbt::Tag) -> Option { + let properties = match profile.get("properties")? { + horizon_world::nbt::Tag::List(list) => list, + _ => return None, + }; + let value = properties.iter().find_map(|p| { + let name = nbt_text(p.get("name"))?; + (name == "textures") + .then(|| nbt_text(p.get("value"))) + .flatten() + })?; + unpack(&value, Signature::Unsigned, &TEXTURE_URIS).skin +} + +/// The profile's uuid as u128: `id` as an int array (block entity NBT) or a +/// uuid string (older and component forms). Used for `DefaultPlayerSkin.get` +/// when a head's skin is not downloaded yet. +pub fn profile_uuid_nbt(profile: &horizon_world::nbt::Tag) -> Option { + match profile.get("id")? { + horizon_world::nbt::Tag::IntArray(v) if v.len() == 4 => Some( + v.iter() + .fold(0u128, |a, &w| (a << 32) | u128::from(w as u32)), + ), + horizon_world::nbt::Tag::String(s) => { + let digits: String = s.to_string_lossy().chars().filter(|c| *c != '-').collect(); + u128::from_str_radix(&digits, 16).ok() + } + _ => None, + } +} + +fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option { + match tag { + Some(horizon_world::nbt::Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + } +} + /// `MinecraftProfileTexture.getHash`: the base name of the URL's path. pub fn texture_hash(url: &str) -> Option { let rest = url.split_once("://")?.1; @@ -457,6 +498,42 @@ mod tests { use super::*; + #[test] + fn skull_block_entity_profiles_supply_head_skins() { + let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0="; + let profile = horizon_world::nbt::parse_snbt(&format!( + r#"{{name:"T",id:[I;-158327916,1572358581,-2125825222,-487948715],properties:[{{name:"textures",value:"{value}"}}]}}"# + )) + .unwrap() + .0; + assert_eq!( + super::profile_skin_url_nbt(&profile).as_deref(), + Some("https://textures.minecraft.net/texture/abc123") + ); + assert_eq!( + super::profile_uuid_nbt(&profile), + Some( + [-158327916, 1572358581, -2125825222, -487948715] + .iter() + .fold(0u128, |a, &w: &i32| (a << 32) | u128::from(w as u32)) + ) + ); + // A name-only profile (a string tag) has no properties: no url, no id. + let named = horizon_world::nbt::Tag::String("MHF_Blaze".into()); + assert_eq!(super::profile_skin_url_nbt(&named), None); + assert_eq!(super::profile_uuid_nbt(&named), None); + // A uuid in string form decodes too. + let text_id = horizon_world::nbt::parse_snbt( + r#"{name:"T",id:"e843a1f4-0000-0001-0000-000200000003"}"#, + ) + .unwrap() + .0; + assert_eq!( + super::profile_uuid_nbt(&text_id), + Some(u128::from_str_radix("e843a1f4000000010000000200000003", 16).unwrap()) + ); + } + #[test] fn sha1_and_base64() { let hex: String = sha1(b"abc").iter().map(|b| format!("{b:02x}")).collect();