Fix item-use feedback, ranged poses, arrows and elytra rendering

This commit is contained in:
Cosmic
2026-10-13 22:41:21 -04:00
parent e5c061dba6
commit 5903b5981d
17 changed files with 973 additions and 189 deletions
+240
View File
@@ -8,6 +8,125 @@
//!
//! What those read and do in the world is behind [`HandWorld`].
/// The ranged item state read by the first-person hand renderer.
#[derive(Clone, Copy, Debug)]
pub enum ItemPose {
Swing,
Using,
Eat {
remaining: f32,
duration: f32,
partial: f32,
},
Trident {
ticks_used: f32,
},
Bow {
ticks_used: f32,
},
Crossbow {
ticks_used: Option<f32>,
charge_duration: f32,
charged: bool,
},
}
/// `submitArmWithItem`: the main-hand item pose, before the model transform.
pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -> glam::Mat4 {
use glam::{Mat4, Vec3};
use horizon_core::geometry::trig::Mth;
let invert = if left { -1.0 } else { 1.0 };
let pi = std::f32::consts::PI;
let mut m = Mat4::from_translation(Vec3::new(
invert * 0.56,
-0.52 - inverse_height * 0.6,
-0.72,
));
if let ItemPose::Eat {
remaining,
duration,
partial,
} = pose
{
let time = remaining - partial + 1.0;
let fraction = time / duration;
let mut eat = Mat4::IDENTITY;
if fraction < 0.8 {
eat *=
Mat4::from_translation(Vec3::new(0.0, ((time / 4.0 * pi).mcos() * 0.1).abs(), 0.0));
}
let jiggle = 1.0 - horizon_core::jmath::pow(f64::from(fraction), 27.0) as f32;
eat *= Mat4::from_translation(Vec3::new(jiggle * 0.6 * invert, jiggle * -0.5, 0.0));
eat *= Mat4::from_rotation_y((invert * jiggle * 90.0).to_radians());
eat *= Mat4::from_rotation_x((jiggle * 10.0).to_radians());
eat *= Mat4::from_rotation_z((invert * jiggle * 30.0).to_radians());
return eat * m;
}
if matches!(pose, ItemPose::Using) {
return m;
}
let charging = match pose {
ItemPose::Bow { ticks_used } => {
let power = ticks_used / 20.0;
Some((
ticks_used,
((power * power + power * 2.0) / 3.0).min(1.0),
false,
))
}
ItemPose::Crossbow {
ticks_used: Some(ticks),
charge_duration,
charged: false,
} => Some((ticks, (ticks / charge_duration).min(1.0), true)),
ItemPose::Trident { ticks_used } => Some((ticks_used, (ticks_used / 10.0).min(1.0), false)),
_ => None,
};
if let Some((ticks, power, crossbow)) = charging {
let trident = matches!(pose, ItemPose::Trident { .. });
let (x, y, z, pitch, yaw) = if trident {
(-0.5, 0.7, 0.1, -55.0f32, 35.3f32)
} else if crossbow {
(-0.4785682, -0.094387, 0.05731531, -11.935f32, 65.3f32)
} else {
(-0.2785682, 0.18344387, 0.15731531, -13.935f32, 35.3f32)
};
m *= Mat4::from_translation(Vec3::new(invert * x, y, z));
m *= Mat4::from_rotation_x(pitch.to_radians());
m *= Mat4::from_rotation_y((invert * yaw).to_radians());
m *= Mat4::from_rotation_z((invert * -9.785f32).to_radians());
if power > 0.1 {
let shake = ((ticks - 0.1) * 1.3).msin() * (power - 0.1);
m *= Mat4::from_translation(Vec3::new(0.0, shake * 0.004, 0.0));
}
m *= Mat4::from_translation(Vec3::new(
0.0,
0.0,
power * if trident { 0.2 } else { 0.04 },
));
m *= Mat4::from_scale(Vec3::new(1.0, 1.0, 1.0 + power * 0.2));
m *= Mat4::from_rotation_y((invert * -45.0f32).to_radians());
} else {
let root = attack.sqrt();
m *= Mat4::from_translation(Vec3::new(
invert * -0.4 * (root * pi).msin(),
0.2 * (root * std::f32::consts::TAU).msin(),
-0.2 * (attack * pi).msin(),
));
m *= Mat4::from_rotation_y(
(invert * (45.0 - (attack * attack * pi).msin() * 20.0)).to_radians(),
);
m *= Mat4::from_rotation_z((invert * (root * pi).msin() * -20.0).to_radians());
m *= Mat4::from_rotation_x(((root * pi).msin() * -80.0).to_radians());
m *= Mat4::from_rotation_y((invert * -45.0f32).to_radians());
if matches!(pose, ItemPose::Crossbow { charged: true, .. }) && attack < 0.001 {
m *= Mat4::from_translation(Vec3::new(invert * -0.641864, 0.0, 0.0));
m *= Mat4::from_rotation_y((invert * 10.0f32).to_radians());
}
}
m
}
/// `InteractionHand`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hand {
@@ -599,3 +718,124 @@ mod tests {
assert_eq!(swing_duration(d, None, Some(2)), 12);
}
}
#[cfg(test)]
mod item_pose_tests {
use super::*;
#[test]
fn ranged_draw_uses_native_charge_curves_and_caps() {
for (ticks, stretch) in [
(0.0, 1.0),
(10.0, 1.0 + 0.2 * 1.25 / 3.0),
(20.0, 1.2),
(40.0, 1.2),
] {
let m = item_pose(false, 0.0, 0.0, ItemPose::Bow { ticks_used: ticks });
assert!((m.determinant() - stretch).abs() < 0.000001);
}
for duration in [25.0, 20.0, 15.0, 10.0] {
let m = item_pose(
false,
0.0,
0.0,
ItemPose::Crossbow {
ticks_used: Some(duration),
charge_duration: duration,
charged: false,
},
);
assert!((m.determinant() - 1.2).abs() < 0.000001);
}
}
#[test]
fn left_handed_ranged_poses_mirror_the_right_hand() {
let reflect = glam::Mat4::from_scale(glam::Vec3::new(-1.0, 1.0, 1.0));
for pose in [
ItemPose::Swing,
ItemPose::Bow { ticks_used: 10.0 },
ItemPose::Crossbow {
ticks_used: Some(10.0),
charge_duration: 25.0,
charged: false,
},
ItemPose::Crossbow {
ticks_used: None,
charge_duration: 25.0,
charged: true,
},
] {
let left = item_pose(true, 0.2, 0.0, pose).to_cols_array();
let right = (reflect * item_pose(false, 0.2, 0.0, pose) * reflect).to_cols_array();
for (a, b) in left.into_iter().zip(right) {
assert!((a - b).abs() < 0.000001);
}
}
}
#[test]
fn drawing_bow_has_its_own_pose() {
assert_ne!(
item_pose(false, 0.0, 0.0, ItemPose::Bow { ticks_used: 10.0 }),
item_pose(false, 0.0, 0.0, ItemPose::Swing)
);
}
#[test]
fn charging_crossbow_has_its_own_pose() {
assert_ne!(
item_pose(
false,
0.0,
0.0,
ItemPose::Crossbow {
ticks_used: Some(10.0),
charge_duration: 25.0,
charged: false
}
),
item_pose(false, 0.0, 0.0, ItemPose::Swing)
);
}
#[test]
fn charged_crossbow_is_aimed_while_idle() {
assert_ne!(
item_pose(
false,
0.0,
0.0,
ItemPose::Crossbow {
ticks_used: None,
charge_duration: 25.0,
charged: true
}
),
item_pose(false, 0.0, 0.0, ItemPose::Swing)
);
}
}
#[cfg(test)]
mod continuous_use_tests {
use super::*;
#[test]
fn eating_and_throwing_have_use_poses_not_attack_poses() {
let swing = item_pose(false, 0.0, 0.3, ItemPose::Swing);
assert_ne!(
swing,
item_pose(
false,
0.0,
0.3,
ItemPose::Eat {
remaining: 10.0,
duration: 32.0,
partial: 0.5
}
)
);
assert_ne!(
swing,
item_pose(false, 0.0, 0.3, ItemPose::Trident { ticks_used: 5.0 })
);
assert_ne!(swing, item_pose(false, 0.0, 0.3, ItemPose::Using));
}
}
+145 -94
View File
@@ -792,6 +792,7 @@ struct Game<'a> {
rockets: Vec<fireworks::Rocket>,
creaking: creaking::CreakingState,
trident_model: Option<horizon_client::mobs::Part>,
arrow_model: Option<horizon_client::mobs::Part>,
tnts: Vec<tnt::PrimedTnt>,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
creative_screen: Creative,
@@ -1225,6 +1226,7 @@ impl Game<'_> {
self.inventory[self.selected] = None;
}
self.player_drop(thrown);
self.swing_arm();
}
/// `Player.drop`: the statistics and a thrown item entity in front of the player.
fn player_drop(&mut self, thrown: ItemStack) {
@@ -2066,6 +2068,21 @@ impl Game<'_> {
let Some(info) = self.res.items.get(&stack.item).cloned() else {
return Ok(());
};
if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? {
return Ok(());
}
use horizon_client::first_person::UseResult;
let swings = self.swings_started;
match self.use_tool(&stack)? {
UseResult::Success { swing } => {
if swing && self.swings_started == swings {
self.swing_arm();
}
return Ok(());
}
UseResult::Fail => return Ok(()),
UseResult::Pass => {}
}
if self.use_potion_item(&stack)? || self.throw_item(&stack)? {
return Ok(());
}
@@ -2087,12 +2104,13 @@ impl Game<'_> {
return Ok(());
}
if &*stack.item == "minecraft:bow" {
if self.using.is_none() {
if self.using.is_none() && (self.creative || self.arrow_slot().is_some()) {
self.using = Some((self.selected, 0));
}
return Ok(());
}
if info.food.is_some()
if info.consumable
&& info.food.is_some()
&& let Some(p) = self.player.as_ref()
&& (p.health.food.food < 20 || self.creative)
{
@@ -2102,12 +2120,6 @@ impl Game<'_> {
}
return Ok(());
}
if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? {
return Ok(());
}
if self.use_tool(&stack)? {
return Ok(());
}
if self.place_boat(&stack) {
return Ok(());
}
@@ -6129,8 +6141,9 @@ impl Game<'_> {
}
}
}
/// Item use on blocks for tools, buckets and fire starters; returns true if handled.
fn use_tool(&mut self, stack: &ItemStack) -> Result<bool> {
/// Block tool use: distinguish success, failure and fall-through for hand feedback.
fn use_tool(&mut self, stack: &ItemStack) -> Result<horizon_client::first_person::UseResult> {
use horizon_client::first_person::UseResult;
let item = stack.item.trim_start_matches("minecraft:").to_owned();
let at = |p: [i32; 3]| {
[
@@ -6142,16 +6155,16 @@ impl Game<'_> {
if let Some(hit) = self.pick()
&& self.use_on_cauldron(hit.pos)?
{
return Ok(true);
return Ok(UseResult::Success { swing: true });
}
if item == "bucket" {
let Some(hit) = self.pick_fluid() else {
return Ok(false);
return Ok(UseResult::Pass);
};
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
let f = self.res.facts.get(state).clone();
if f.fluid == Fluid::None || f.fluid_level != 8 || f.fluid_falling {
return Ok(false);
return Ok(UseResult::Pass);
}
let (filled, sound) = match f.fluid {
Fluid::Water => ("minecraft:water_bucket", "minecraft:item.bucket.fill"),
@@ -6177,13 +6190,16 @@ impl Game<'_> {
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
}
}
return Ok(true);
return Ok(UseResult::Success { swing: true });
}
let Some(hit) = self.pick() else {
return Ok(false);
return Ok(UseResult::Pass);
};
let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
if item == "water_bucket" || item == "lava_bucket" {
if let Some((content, sound, mob)) = horizon_client::items::bucket_contents(&stack.item) {
if !self.may_build() {
return Ok(UseResult::Fail);
}
let target = if self.res.facts.get(clicked).replaceable {
hit.pos
} else {
@@ -6193,34 +6209,32 @@ impl Game<'_> {
hit.pos[2] + hit.face[2],
]
};
let existing = self.world.block(target[0], target[1], target[2]);
if !self.res.facts.get(existing).replaceable && !self.res.facts.is_air(existing) {
return Ok(true);
let pos = BlockPos::new(target[0], target[1], target[2]);
let emptied = self
.with_level(|b, level, ticks| b.bucket_empty(level, ticks, pos, content, sound));
self.process_level_events()?;
if !emptied {
return Ok(UseResult::Fail);
}
let fluid = if item == "water_bucket" {
"minecraft:water"
} else {
"minecraft:lava"
};
self.set_state_named(target, fluid, &[])?;
let sound = if item == "water_bucket" {
"minecraft:item.bucket.empty"
} else {
"minecraft:item.bucket.empty_lava"
};
self.audio.play(sound, Some(at(target)), 1.0, 1.0);
if let Some(kind) = mob {
if let Some(id) = self.spawn_mob_at(kind, (target[0], target[1], target[2]), true) {
self.mob_placed(id)?;
}
self.post_block_game_event(
"minecraft:entity_place",
target,
self.sculk_actor(),
None,
);
}
self.trigger_item("minecraft:placed_block", stack);
if !self.creative {
self.inventory[self.selected] = Some(ItemStack {
item: Arc::from("minecraft:bucket"),
count: 1,
damage: 0,
extra: None,
});
self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1));
}
return Ok(true);
return Ok(UseResult::Success { swing: true });
}
if self.use_block_transformer(stack, hit.pos, hit.face)? {
return Ok(true);
return Ok(UseResult::Success { swing: true });
}
if item == "honeycomb" {
let registry = self.res.assets.registry;
@@ -6238,22 +6252,47 @@ impl Game<'_> {
if !self.creative {
self.consume_held();
}
return Ok(true);
return Ok(UseResult::Success { swing: true });
}
}
if item == "flint_and_steel" || item == "fire_charge" {
if !self.may_build() {
return Ok(UseResult::Fail);
}
let name = self.res.facts.get(clicked).name.clone();
if self.can_light(clicked, &name) {
let registry = self.res.assets.registry;
let mut state = registry
.state(clicked)
.cloned()
.ok_or("missing lit block state")?;
state.properties.insert("lit".into(), "true".into());
self.level_set(hit.pos, registry.resolve(&state)?)?;
self.audio.play(
if item == "fire_charge" {
"minecraft:item.firecharge.use"
} else {
"minecraft:item.flintandsteel.use"
},
Some(at(hit.pos)),
1.0,
self.world.random.next_float() * 0.4 + 0.8,
);
if item == "fire_charge" {
self.consume_held();
} else {
self.damage_held(1);
}
return Ok(UseResult::Success { swing: true });
}
let target = [
hit.pos[0] + hit.face[0],
hit.pos[1] + hit.face[1],
hit.pos[2] + hit.face[2],
];
if self
.res
.facts
.is_air(self.world.block(target[0], target[1], target[2]))
{
if self.can_place_used_fire(target) {
if !self.try_light_portal(target)? {
self.set_state_named(target, "minecraft:fire", &[])?;
self.place_used_fire(target)?;
}
let sound = if item == "fire_charge" {
"minecraft:item.firecharge.use"
@@ -6271,36 +6310,11 @@ impl Game<'_> {
} else {
self.damage_held(1);
}
return Ok(true);
return Ok(UseResult::Success { swing: true });
}
return Ok(UseResult::Fail);
}
// Equippable items swap into their armor slot (Equippable.swapWithEquipmentSlot);
// block items aimed at a block are placed instead.
if let Some(slot) = self
.res
.items
.get(&stack.item)
.filter(|i| i.block.is_none())
.and_then(|i| i.equip_slot.clone())
{
let index = match slot.as_str() {
"head" => 0,
"chest" => 1,
"legs" => 2,
"feet" => 3,
_ => return Ok(false),
};
let held = self.inventory[self.selected].take();
self.inventory[self.selected] = self.armor[index].take();
self.armor[index] = held;
if let Some(eye) = self.eye_position() {
self.audio
.play("minecraft:item.armor.equip_generic", Some(eye), 1.0, 1.0);
}
self.apply_equipment();
return Ok(true);
}
Ok(false)
Ok(UseResult::Pass)
}
/// `ExperienceOrb.award`: orbs of the largest sizes; each draws the id
/// `tryMergeToExisting` compares from the level random, then moves with
@@ -6332,6 +6346,21 @@ impl Game<'_> {
on_ground: false,
});
}
fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool {
let pos = BlockPos::new(target[0], target[1], target[2]);
let direction = match ((self.yaw / 90.0 + 0.5).floor() as i32).rem_euclid(4) {
0 => Direction::South,
1 => Direction::West,
2 => Direction::North,
_ => Direction::East,
};
self.with_level(|b, level, ticks| b.fire_can_be_placed_at(level, ticks, pos, direction))
}
fn place_used_fire(&mut self, target: [i32; 3]) -> Result<()> {
let pos = BlockPos::new(target[0], target[1], target[2]);
let state = self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, pos));
self.level_set(target, state)
}
/// DropExperienceBlock / RedStoneOreBlock / SculkBlock experience ranges.
fn block_experience(&mut self, name: &str) -> u32 {
let (min, max) = match name.trim_start_matches("minecraft:") {
@@ -6580,27 +6609,48 @@ impl Game<'_> {
);
}
Some(stack) => {
// 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 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(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));
// `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 using = owner.using_this_item && owner.use_item_remaining_ticks > 0;
let ticks_used =
owner.use_duration as f32 - (owner.use_item_remaining_ticks as f32 - a + 1.0);
use horizon_client::first_person::ItemPose;
let pose = match &*stack.item {
"minecraft:bow" if using => ItemPose::Bow { ticks_used },
"minecraft:crossbow" => {
let charged = stack.data().is_some_and(|d| !d.charged.is_empty());
ItemPose::Crossbow {
ticks_used: (using && !charged).then_some(ticks_used),
charge_duration: owner.crossbow_charge_duration as f32,
charged,
}
}
"minecraft:trident" if using => ItemPose::Trident { ticks_used },
_ if using => {
let components = self
.res
.item_renderer
.models
.components(&horizon_client::item_render::stack_view(&stack));
if components.contains_key("minecraft:consumable") {
ItemPose::Eat {
remaining: owner.use_item_remaining_ticks as f32,
duration: owner.use_duration as f32,
partial: a,
}
} else {
ItemPose::Using
}
}
_ => ItemPose::Swing,
};
let left = self.settings.main_hand_left;
let m = to_world
* horizon_client::first_person::item_pose(left, inverse_height, attack, pose);
let context = if left {
horizon_assets::item_model::DisplayContext::FirstPersonLeftHand
} else {
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,
@@ -8670,6 +8720,7 @@ pub fn run() -> Result<()> {
rockets: Vec::new(),
creaking: Default::default(),
trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"),
arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"),
tnts: Vec::new(),
hoppers: HashMap::new(),
creative_screen: Creative::load(&game_root)?,
@@ -41,6 +41,9 @@ impl ArmorStandAssets {
}
}
}
if let Some(part) = load("minecraft:elytra#main") {
player.insert("elytra", part);
}
let mut equipment = HashMap::new();
if let Ok(entries) = std::fs::read_dir(root.join("assets/minecraft/equipment")) {
for e in entries.flatten() {
@@ -55,7 +58,7 @@ impl ArmorStandAssets {
};
let Ok(v) = v else { continue };
let mut kinds = HashMap::new();
for kind in ["humanoid", "humanoid_leggings"] {
for kind in ["humanoid", "humanoid_leggings", "wings"] {
if let Some(layer) = v["layers"][kind].get(0) {
let tex = layer["texture"]
.as_str()
+1
View File
@@ -77,6 +77,7 @@ impl Game<'_> {
_ => return false,
};
self.open_book(screen);
self.swing_arm();
true
}
fn open_book(&mut self, screen: BookScreen) {
+24 -43
View File
@@ -1327,6 +1327,7 @@ impl Game<'_> {
fn tick_projectiles(&mut self) -> Result<()> {
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
let mut hits = Vec::new();
let mut trails = Vec::new();
let mut deflections: Vec<[f64; 3]> = Vec::new();
{
let mut targets: Vec<(Who, Aabb)> = self
@@ -1362,6 +1363,7 @@ impl Game<'_> {
let w = self.mob_world_base(&[]);
let pw = ProjWorld { w: &w, targets };
projectiles.retain_mut(|p| {
trails.extend(p.arrow_trail(pw.in_water(p.position)));
let (keep, hit) = p.tick(&pw);
let wind = matches!(
p.kind,
@@ -1397,6 +1399,13 @@ impl Game<'_> {
keep
});
}
for (ty, at, velocity) in trails {
self.particles.add(
&horizon_client::particles::ParticleOptions::simple(ty),
at,
velocity,
);
}
for at in deflections {
self.audio
.play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0);
@@ -2345,7 +2354,7 @@ impl Game<'_> {
}
}
self.elder_apparition_geometry(alpha, out);
// Projectiles: arrows as crossed quads, the rest as item billboards.
// Projectiles: the baked vanilla arrow model, the rest as item billboards.
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
let forward = glam::Vec3::new(
-yaw.sin() * pitch.cos(),
@@ -2371,52 +2380,24 @@ impl Game<'_> {
packed = (15 * 16) | ((15 * 16) << 8);
}
if a.is_arrow() {
let Some(model) = self.arrow_model.as_ref() else {
continue;
};
let Some(r) = atlas.sprites.get("entity/projectiles/arrow").copied() else {
continue;
};
let dir = glam::Vec3::new(
a.velocity.x as f32,
a.velocity.y as f32,
a.velocity.z as f32,
)
.normalize_or(glam::Vec3::X);
let dir = if a.stuck {
glam::Vec3::new(
-a.yaw.to_radians().sin() * a.pitch.to_radians().cos(),
a.pitch.to_radians().sin(),
a.yaw.to_radians().cos() * a.pitch.to_radians().cos(),
)
.normalize_or(dir)
} else {
dir
};
let side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08;
let upv = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08;
let (u1, v1) = (
r.u0 + (r.u1 - r.u0) * 0.5,
r.v0 + (r.v1 - r.v0) * (5.0 / 32.0),
let m = glam::Mat4::from_translation(c)
* glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians())
* glam::Mat4::from_rotation_z(a.pitch.to_radians());
horizon_client::mobs::render_model(
model,
m,
&|part| part.pose,
[r.u0, r.v0, r.u1, r.v1],
packed,
0,
out,
);
for off in [side, upv] {
let q = [
c - dir * 0.25 - off,
c + dir * 0.25 - off,
c + dir * 0.25 + off,
c - dir * 0.25 + off,
];
for (v, uv) in q
.iter()
.zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]])
{
out.push(Vertex {
normal: [0; 4],
pos: v.to_array(),
uv,
layer: 0,
color: 0xFFFF_FFFF,
light: packed,
});
}
}
continue;
}
// WindChargeRenderer.
+2 -2
View File
@@ -13,7 +13,7 @@ use horizon_core::{geometry::Vec3, random::RandomSource};
const CROSSBOW: &str = "minecraft:crossbow";
impl Game<'_> {
fn charge_ticks(stack: &ItemStack) -> u32 {
pub(super) fn charge_ticks(stack: &ItemStack) -> u32 {
// crossbow_charge_time: 1.25 s, minus 0.25 s per Quick Charge level.
let seconds = 1.25 - 0.25 * stack.enchantment_level("minecraft:quick_charge") as f32;
(seconds.max(0.0) * 20.0).floor() as u32
@@ -42,7 +42,7 @@ impl Game<'_> {
],
}
}
fn arrow_slot(&self) -> Option<usize> {
pub(super) fn arrow_slot(&self) -> Option<usize> {
self.inventory
.iter()
.position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow"))
+5 -45
View File
@@ -741,7 +741,7 @@ impl Game<'_> {
1.0 + amount
}
/// `EntityType.spawn(.., pos, reason, tryMoveDown, false)` for a mob.
fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option<u32> {
pub(super) fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option<u32> {
let name = if kind.contains(':') {
kind.to_owned()
} else {
@@ -868,7 +868,7 @@ impl Game<'_> {
self.handle_mob_events(events)
}
/// A mob a bucket emptied: `setFromBucket` keeps it, then it calls out.
fn mob_placed(&mut self, id: u32) -> Result<()> {
pub(super) fn mob_placed(&mut self, id: u32) -> Result<()> {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.persistent = true;
}
@@ -1141,48 +1141,8 @@ impl Game<'_> {
) -> Result<Dispensed> {
let item = stack.item.to_string();
let target = offset(pos, facing);
let (content, sound, mob) = match item.as_str() {
"minecraft:lava_bucket" => (
BucketContent::Fluid(FluidKind::Lava),
"minecraft:item.bucket.empty_lava",
None,
),
"minecraft:water_bucket" => (
BucketContent::Fluid(FluidKind::Water),
"minecraft:item.bucket.empty",
None,
),
"minecraft:powder_snow_bucket" => (
BucketContent::Powder,
"minecraft:item.bucket.empty_powder_snow",
None,
),
"minecraft:axolotl_bucket" => (
BucketContent::MobWater,
"minecraft:item.bucket.empty_axolotl",
Some("axolotl"),
),
"minecraft:tadpole_bucket" => (
BucketContent::MobWater,
"minecraft:item.bucket.empty_tadpole",
Some("tadpole"),
),
"minecraft:sulfur_cube_bucket" => (
BucketContent::Nothing,
"minecraft:item.bucket.empty_sulfur_cube",
Some("sulfur_cube"),
),
other => (
BucketContent::MobWater,
"minecraft:item.bucket.empty_fish",
Some(match other {
"minecraft:salmon_bucket" => "salmon",
"minecraft:cod_bucket" => "cod",
"minecraft:pufferfish_bucket" => "pufferfish",
_ => "tropical_fish",
}),
),
};
let (content, sound, mob) =
horizon_client::items::bucket_contents(&item).expect("filled bucket dispatcher");
let target_pos = Self::pos_of(target);
let emptied = self
.with_level(|b, level, ticks| b.bucket_empty(level, ticks, target_pos, content, sound));
@@ -1337,7 +1297,7 @@ impl Game<'_> {
Ok((Some(stack), event))
}
/// `CampfireBlock.canLight || CandleBlock.canLight || CandleCakeBlock.canLight`.
fn can_light(&self, state: BlockStateId, name: &str) -> bool {
pub(super) fn can_light(&self, state: BlockStateId, name: &str) -> bool {
let lit = self.prop(state, "lit");
let waterlogged = self.prop(state, "waterlogged");
let dry_unlit = lit.as_deref() == Some("false") && waterlogged.as_deref() == Some("false");
@@ -102,6 +102,7 @@ impl Game<'_> {
if !self.creative {
self.consume_held();
}
self.swing_arm();
true
}
pub(super) fn tick_rockets(&mut self) {
+1 -1
View File
@@ -222,7 +222,7 @@ impl Game<'_> {
owner.using_this_item = true;
owner.use_duration = duration;
owner.use_item_remaining_ticks = duration - ticks as i32;
owner.crossbow_charge_duration = 25;
owner.crossbow_charge_duration = Self::charge_ticks(stack).max(1) as i32;
}
owner.is_selected =
stack.is_some() && self.inventory.get(self.selected).and_then(Option::as_ref) == stack;
@@ -297,6 +297,14 @@ impl Game<'_> {
}
let crouching = p.pose == Pose::Crouching;
let (position, flying) = (p.position, p.flying || p.fall_flying);
let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity);
let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0);
let charged = self.inventory[self.selected]
.as_ref()
.is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty()));
let charge_duration = self.inventory[self.selected]
.as_ref()
.map_or(25, |s| Self::charge_ticks(s).max(1)) as i32;
let attack = (self.swing.old_animation, self.swing.animation);
let swinging = self.swing.swinging();
let (yaw, pitch) = (self.yaw, self.pitch);
@@ -356,6 +364,14 @@ impl Game<'_> {
m.extra.off_hand = off;
m.extra.crouching = crouching;
m.extra.passenger = riding;
m.velocity = velocity;
m.extra.fall_flying = fall_flying;
m.extra.fall_fly_ticks = fly_ticks;
m.extra.main_hand_left = self.settings.main_hand_left;
m.extra.using_item = using;
m.extra.charged = charged;
m.extra.ints[5] = charge_duration;
m.extra.elytra.tick(fall_flying, crouching, velocity);
m.hurt_time = hurt;
}
/// Whether the player's own model shows in the world view.
@@ -400,6 +416,7 @@ impl Game<'_> {
&self.player_armor_layers(),
out,
);
self.player_elytra_geometry(m, camera, alpha as f32, packed, out);
self.held_item_geometry(m, camera, alpha, packed, true, out);
}
/// `extractEntityInInventoryFollowsMouse`: the player in the box
@@ -454,6 +471,7 @@ impl Game<'_> {
&self.player_armor_layers(),
&mut verts,
);
self.player_elytra_geometry(&m, camera, 1.0, 240 | 240 << 8, &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);
@@ -509,3 +527,54 @@ impl Game<'_> {
}
}
}
impl Game<'_> {
fn player_elytra_geometry(
&self,
m: &Mob,
camera: glam::DVec3,
partial: f32,
light: u32,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
let Some(asset) = self.armor[1]
.as_ref()
.and_then(|s| self.res.items.get(&s.item))
.and_then(|i| i.equip_asset.as_ref())
else {
return;
};
let assets = &self.armor_stand_assets;
let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else {
return;
};
let (Some(model), Some(rect)) = (
assets.player.get("elytra"),
self.res.atlas.sprites.get(texture),
) else {
return;
};
let base = horizon_client::mobs::render::base_transform(m, partial, camera)
* glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.0, 0.125));
let angles = m.extra.elytra.angles(partial);
horizon_client::mobs::render_model(
model,
base,
&|part| {
let mut p = part.pose;
if part.name == "left_wing" || part.name == "right_wing" {
let invert = if part.name == "left_wing" { 1.0 } else { -1.0 };
p[1] = if m.extra.crouching { 3.0 } else { 0.0 };
p[3] = angles[0];
p[4] = invert * angles[1];
p[5] = invert * angles[2];
}
p
},
[rect.u0, rect.v0, rect.u1, rect.v1],
light,
0,
out,
);
}
}
+90
View File
@@ -27,6 +27,7 @@ pub struct ItemInfo {
pub tool: Vec<ToolRule>,
pub tool_default_speed: f32,
pub food: Option<(u32, f32)>,
pub consumable: bool,
pub model: String,
/// Main-hand `attack_damage` / `attack_speed` modifier amounts.
pub attack_damage: f32,
@@ -378,6 +379,7 @@ impl Items {
.as_f64()
.unwrap_or(1.0) as f32,
food,
consumable: c.get("minecraft:consumable").is_some(),
model: c["minecraft:item_model"]
.as_str()
.unwrap_or(name)
@@ -1169,6 +1171,94 @@ impl LootContext<'_> {
}
}
/// `DispensibleContainerItem`: shared contents for hand use and dispensers.
pub fn bucket_contents(
item: &str,
) -> Option<(horizon_world::level::BucketContent, &str, Option<&str>)> {
use horizon_world::{fluid::FluidKind, level::BucketContent as C};
Some(match item {
"minecraft:water_bucket" => (
C::Fluid(FluidKind::Water),
"minecraft:item.bucket.empty",
None,
),
"minecraft:lava_bucket" => (
C::Fluid(FluidKind::Lava),
"minecraft:item.bucket.empty_lava",
None,
),
"minecraft:powder_snow_bucket" => {
(C::Powder, "minecraft:item.bucket.empty_powder_snow", None)
}
"minecraft:cod_bucket" => (C::MobWater, "minecraft:item.bucket.empty_fish", Some("cod")),
"minecraft:salmon_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_fish",
Some("salmon"),
),
"minecraft:pufferfish_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_fish",
Some("pufferfish"),
),
"minecraft:tropical_fish_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_fish",
Some("tropical_fish"),
),
"minecraft:axolotl_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_axolotl",
Some("axolotl"),
),
"minecraft:tadpole_bucket" => (
C::MobWater,
"minecraft:item.bucket.empty_tadpole",
Some("tadpole"),
),
"minecraft:sulfur_cube_bucket" => (
C::Nothing,
"minecraft:item.bucket.empty_sulfur_cube",
Some("sulfur_cube"),
),
_ => return None,
})
}
#[cfg(test)]
mod bucket_use_tests {
use super::*;
#[test]
fn every_filled_bucket_has_the_native_content_and_sound() {
use horizon_world::level::BucketContent as C;
assert_eq!(
bucket_contents("minecraft:powder_snow_bucket"),
Some((C::Powder, "minecraft:item.bucket.empty_powder_snow", None))
);
assert_eq!(
bucket_contents("minecraft:tadpole_bucket"),
Some((
C::MobWater,
"minecraft:item.bucket.empty_tadpole",
Some("tadpole")
))
);
assert_eq!(
bucket_contents("minecraft:sulfur_cube_bucket"),
Some((
C::Nothing,
"minecraft:item.bucket.empty_sulfur_cube",
Some("sulfur_cube")
))
);
for id in ["cod", "salmon", "pufferfish", "tropical_fish", "axolotl"] {
assert!(bucket_contents(&format!("minecraft:{id}_bucket")).is_some());
}
assert!(bucket_contents("minecraft:bucket").is_none());
assert!(bucket_contents("minecraft:milk_bucket").is_none());
}
}
#[cfg(test)]
mod tests {
use super::*;
+63
View File
@@ -660,6 +660,10 @@ pub struct Extra {
pub legs: Option<Arc<str>>,
pub feet: Option<Arc<str>>,
pub using_item: i32,
pub fall_flying: bool,
pub fall_fly_ticks: i32,
pub main_hand_left: bool,
pub elytra: ElytraAnimation,
pub flag: bool,
pub flag2: bool,
/// Species scratch values (the wither's head targets and clocks).
@@ -1885,3 +1889,62 @@ mod lighting_tests {
);
}
}
/// `LivingEntity.elytraAnimationState`: eased wing angles and render interpolation.
#[derive(Clone, Copy, Debug, Default)]
pub struct ElytraAnimation {
pub old: [f32; 3],
pub angles: [f32; 3],
}
impl ElytraAnimation {
pub fn tick(&mut self, flying: bool, crouching: bool, velocity: horizon_core::geometry::Vec3) {
use std::f32::consts::PI;
self.old = self.angles;
let target = if flying {
let length =
(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z)
.sqrt();
let ratio = if velocity.y < 0.0 && length > 0.0 {
1.0 - horizon_core::jmath::pow(-velocity.y / length, 1.5) as f32
} else {
1.0
};
[
PI / 12.0 + (PI / 9.0 - PI / 12.0) * ratio,
0.0,
-PI / 12.0 + (-PI / 2.0 + PI / 12.0) * ratio,
]
} else if crouching {
[PI * 2.0 / 9.0, 0.08726646, -PI / 4.0]
} else {
[PI / 12.0, 0.0, -PI / 12.0]
};
for (angle, target) in self.angles.iter_mut().zip(target) {
*angle += (target - *angle) * 0.3;
}
}
pub fn angles(&self, partial: f32) -> [f32; 3] {
std::array::from_fn(|i| self.old[i] + (self.angles[i] - self.old[i]) * partial)
}
}
#[cfg(test)]
mod elytra_tests {
use super::*;
#[test]
fn wings_ease_between_ground_flight_and_crouch() {
let mut wings = ElytraAnimation::default();
wings.tick(false, false, Vec3::ZERO);
assert!((wings.angles[0] - std::f32::consts::PI / 12.0 * 0.3).abs() < 0.000001);
assert_eq!(wings.angles(0.0), wings.old);
assert_eq!(wings.angles(1.0), wings.angles);
for _ in 0..40 {
wings.tick(true, false, Vec3::new(1.0, 0.0, 0.0));
}
assert!((wings.angles[2] + std::f32::consts::FRAC_PI_2).abs() < 0.00001);
for _ in 0..40 {
wings.tick(false, true, Vec3::ZERO);
}
assert!((wings.angles[1] - 0.08726646).abs() < 0.00001);
}
}
+83 -2
View File
@@ -266,6 +266,8 @@ pub struct Hum {
pub left: ArmPose,
pub crouching: bool,
pub passenger: bool,
pub fall_flying: bool,
pub fly_speed_scale: f32,
/// `Some(aggressive)` for `ZombieModel`-style `animateZombieArms`.
pub zombie: Option<bool>,
/// The main hand holds something (`getMainHandItemStack() != EMPTY`).
@@ -282,6 +284,8 @@ impl Hum {
left,
crouching: false,
passenger: false,
fall_flying: false,
fly_speed_scale: 1.0,
zombie: None,
holding: false,
charge: (0.0, 0.0),
@@ -353,7 +357,10 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`).
pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
head(p, s);
let (pos, sp) = (s.pos, s.speed);
if h.fall_flying {
p.xrot("head", -std::f32::consts::FRAC_PI_4);
}
let (pos, sp) = (s.pos, s.speed / h.fly_speed_scale);
p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5);
p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5);
p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp);
@@ -539,7 +546,38 @@ pub fn setup(
} else {
ArmPose::Empty
};
let mut h = Hum::new(right, ArmPose::Empty);
let pose = if player {
match m.extra.main_hand.as_deref() {
Some("minecraft:bow") if m.extra.using_item > 0 => ArmPose::Bow,
Some("minecraft:crossbow") if m.extra.using_item > 0 && !m.extra.charged => {
ArmPose::CrossbowCharge
}
Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => {
ArmPose::CrossbowHold
}
Some(_) => ArmPose::Item,
None => ArmPose::Empty,
}
} else {
right
};
let off = if player && m.extra.off_hand.is_some() && !pose.two_handed() {
ArmPose::Item
} else {
ArmPose::Empty
};
let mut h = if m.extra.main_hand_left {
Hum::new(off, pose)
} else {
Hum::new(pose, off)
};
h.charge = (m.extra.ints[5] as f32, m.extra.using_item as f32);
h.fall_flying = m.extra.fall_flying;
if h.fall_flying {
let v = m.velocity;
h.fly_speed_scale =
(((v.x * v.x + v.y * v.y + v.z * v.z) as f32 / 0.2).powi(3)).max(1.0);
}
h.crouching = m.extra.crouching;
h.passenger = m.extra.passenger;
humanoid(p, s, &h);
@@ -630,3 +668,46 @@ pub fn setup(
}
}
}
#[cfg(test)]
mod flight_pose_tests {
use super::*;
#[test]
fn flight_slows_limbs_and_sets_the_head_pose() {
let state = State {
pos: 0.0,
speed: 1.0,
age: 0.0,
y_rot: 0.0,
x_rot: 0.0,
swing: 0.0,
baby: false,
partial: 0.0,
};
let make = || Poses {
map: [
"head",
"right_arm",
"left_arm",
"right_leg",
"left_leg",
"body",
]
.into_iter()
.map(|n| (n.to_string(), [0.0; 9]))
.collect(),
dummy: [0.0; 9],
skipped: Default::default(),
hidden: Default::default(),
};
let mut ground = make();
let mut flight = make();
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
humanoid(&mut ground, &state, &h);
h.fall_flying = true;
h.fly_speed_scale = 8.0;
humanoid(&mut flight, &state, &h);
assert_eq!(flight.get("head")[3], -std::f32::consts::FRAC_PI_4);
assert_eq!(flight.get("right_leg")[3], ground.get("right_leg")[3] / 8.0);
}
}
+22
View File
@@ -738,6 +738,28 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
};
let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation;
if m.extra.fall_flying {
let ticks = m.extra.fall_fly_ticks as f32 + alpha;
let scale = (ticks * ticks / 100.0).min(1.0);
let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha;
base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians());
let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha;
let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos());
let v = m.velocity;
let view_scale = (pitch.to_radians()).mcos();
let (look_x, look_z) = (look_x * view_scale, look_z * view_scale);
let view_length = f64::from(look_x * look_x + look_z * look_z);
let speed = v.x * v.x + v.z * v.z;
if speed > f64::from(1.0e-5f32) && view_length > f64::from(1.0e-5f32) {
let dot =
(v.x * f64::from(look_x) + v.z * f64::from(look_z)) / (speed * view_length).sqrt();
let sign = (v.x * f64::from(look_z) - v.z * f64::from(look_x)).signum();
base *= glam::Mat4::from_rotation_y(
(sign * horizon_core::jmath::acos(dot.abs().min(1.0))) as f32,
);
}
}
if m.death_time > 0 && !super::creaking::tearing_down(m) {
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
.sqrt()
+85
View File
@@ -138,6 +138,41 @@ impl Projectile {
bonus: Default::default(),
}
}
/// `AbstractArrow.tick`: critical streaks and submerged bubble trails.
pub fn arrow_trail(
&self,
water: bool,
) -> Vec<(crate::particles::ParticleType, [f64; 3], [f64; 3])> {
use crate::particles::ParticleType;
let mut trail = Vec::new();
if self.stuck || !self.is_arrow() {
return trail;
}
let (p, v) = (self.position, self.velocity);
if water {
let drag = f64::from(0.6f32);
let speed = [v.x * drag, v.y * drag, v.z * drag];
let at = [
p.x - speed[0] * 0.25,
p.y - speed[1] * 0.25,
p.z - speed[2] * 0.25,
];
for _ in 0..4 {
trail.push((ParticleType::Bubble, at, speed));
}
}
if matches!(self.kind, ProjectileKind::Arrow { critical: true, .. }) {
for i in 0..4 {
let t = i as f64 / 4.0;
trail.push((
ParticleType::Crit,
[p.x + v.x * t, p.y + v.y * t, p.z + v.z * t],
[-v.x, -v.y + 0.2, -v.z],
));
}
}
trail
}
pub fn is_arrow(&self) -> bool {
matches!(self.kind, ProjectileKind::Arrow { .. })
}
@@ -760,3 +795,53 @@ mod tests {
assert!((p.velocity.x - 0.19).abs() < 1e-9);
}
}
#[cfg(test)]
mod trail_tests {
use super::*;
use crate::particles::ParticleType;
fn arrow(critical: bool) -> Projectile {
let mut p = Projectile::new(
ProjectileKind::Arrow {
base_damage: 2.0,
critical,
effect: None,
},
Vec3::new(1.0, 2.0, 3.0),
None,
);
p.velocity = Vec3::new(4.0, 2.0, -1.0);
p
}
#[test]
fn critical_arrow_emits_four_native_streak_samples() {
let trail = arrow(true).arrow_trail(false);
assert_eq!(trail.len(), 4);
for (i, (ty, pos, speed)) in trail.iter().enumerate() {
assert_eq!(*ty, ParticleType::Crit);
assert_eq!(
*pos,
[1.0 + i as f64, 2.0 + i as f64 * 0.5, 3.0 - i as f64 * 0.25]
);
assert_eq!(*speed, [-4.0, -1.8, 1.0]);
}
}
#[test]
fn submerged_arrow_emits_four_bubbles_after_water_inertia() {
let trail = arrow(false).arrow_trail(true);
assert_eq!(trail.len(), 4);
let drag = f64::from(0.6f32);
for (ty, pos, speed) in trail {
assert_eq!(ty, ParticleType::Bubble);
assert_eq!(speed, [4.0 * drag, 2.0 * drag, -drag]);
assert_eq!(pos, [1.0 - drag, 2.0 - drag * 0.5, 3.0 + drag * 0.25]);
}
}
#[test]
fn ordinary_and_stuck_arrows_do_not_emit_critical_trails() {
assert!(arrow(false).arrow_trail(false).is_empty());
let mut p = arrow(true);
p.stuck = true;
assert!(p.arrow_trail(true).is_empty());
}
}
+45 -1
View File
@@ -34,7 +34,9 @@ pub struct Sprites {
pub translucent: Vec<bool>,
}
/// Edge length of every sprite array layer.
pub const SPRITE_SIZE: u32 = 16;
// Flow sprites are 32 square: each fluid face samples a 16-texel subregion.
// shortcut: HD frames above 32 are resampled; use variable-resolution storage for HD-pack parity.
pub const SPRITE_SIZE: u32 = 32;
impl Sprites {
pub fn insert(&mut self, root: &Path, name: &str) -> Result<u32> {
if let Some(layer) = self.layers.get(name) {
@@ -140,6 +142,48 @@ impl Sprites {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn native_32_pixel_animation_frames_keep_every_texel() {
let root = std::env::temp_dir().join(format!(
"horizon-sprite-detail-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let directory = root.join("assets/test/textures");
fs::create_dir_all(&directory).unwrap();
let path = directory.join("flow.png");
let mut pixels = Vec::new();
for y in 0..64u8 {
for x in 0..32u8 {
pixels.extend([x, y, 0, 255]);
}
}
let mut encoder = png::Encoder::new(File::create(&path).unwrap(), 32, 64);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.unwrap()
.write_image_data(&pixels)
.unwrap();
fs::write(path.with_extension("png.mcmeta"), r#"{"animation":{}}"#).unwrap();
let mut sprites = Sprites::default();
sprites.insert(&root, "test:flow").unwrap();
let size = sprites.size;
let initial = sprites.pixels.clone();
let animation = sprites.animations[0].clone();
fs::remove_dir_all(root).unwrap();
assert_eq!(
size, 32,
"half a flowing-water frame must retain 16 texels, not 8"
);
assert_eq!(initial, pixels[..32 * 32 * 4]);
assert_eq!(animation.pixels(animation.frame(1)), &pixels[32 * 32 * 4..]);
}
#[test]
fn animation_boundaries_and_repeated_frames_do_not_depend_on_render_rate() {
let animation = SpriteAnimation {
+93
View File
@@ -0,0 +1,93 @@
"""Compile the actual drop and ignition branches with world effects stubbed."""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def block(source, start):
opening = source.index("{", start)
depth, end = 1, opening + 1
while depth:
depth += (source[end] == "{") - (source[end] == "}")
end += 1
return source[start:end]
class ItemActionAnimationTests(unittest.TestCase):
@unittest.skipUnless(shutil.which("rustc"), "rustc is required for action-policy tests")
def test_successful_drop_and_ignition_start_a_swing(self):
source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
drop = block(source, source.index("fn drop_held("))
ignition = block(source, source.index("if self.can_place_used_fire(target)"))
caller_start = source.index(" let swings = self.swings_started;", source.index("fn use_item_as_player("))
caller = source[caller_start:source.index(" if self.use_potion_item", caller_start)]
program = """
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
enum UseResult { Pass, Fail, Success { swing: bool } }
#[derive(Clone)] struct ItemStack { count: u32, item: String }
struct Hit { pos: [i32; 3], face: [i32; 3] }
struct Facts; impl Facts { fn is_air(&self, state:u8)->bool { state == 0 } }
struct Res { facts:Facts }
struct Random; impl Random { fn next_float(&mut self)->f32 { 0.5 } }
struct World { air:bool, path:bool, random:Random }
impl World { fn block(&self,_:i32,_:i32,_:i32)->u8 { if self.air {0} else {1} } }
struct Audio { sounds:u32 } impl Audio { fn play(&mut self,_:&str,_:Option<[f64;3]>,_:f32,_:f32) {self.sounds+=1;} }
struct Game { selected:usize, inventory:[Option<ItemStack>;1], alive:bool, swings:u32, drops:u32, res:Res, world:World, audio:Audio }
impl Game {
DROP
fn ignite(&mut self,item:&str)->Result<()> {
let stack=ItemStack {count:1,item:item.into()};
CALLER
Ok(())
}
fn use_tool(&mut self,stack:&ItemStack)->Result<UseResult> {
let item=stack.item.as_str();
let hit = Hit { pos:[0;3], face:[0,1,0] };
let at = |p:[i32;3]| p.map(f64::from);
let target = [0,1,0];
IGNITION
Ok(UseResult::Fail)
}
fn eye_position(&self)->Option<[f64;3]> { self.alive.then_some([0.0;3]) }
fn player_drop(&mut self,stack:ItemStack) { self.drops += stack.count; }
fn swing_arm(&mut self) { self.swings += 1; }
fn try_light_portal(&mut self,_:[i32;3])->Result<bool> {Ok(false)}
fn may_build(&self)->bool {true}
fn can_place_used_fire(&self,_:[i32;3])->bool {self.world.air&&!self.world.path}
fn place_used_fire(&mut self,_:[i32;3])->Result<()> {Ok(())}
fn consume_held(&mut self) {} fn damage_held(&mut self,_:u32) {}
}
fn game()->Game { Game { selected:0, inventory:[Some(ItemStack { count:4,item:"minecraft:stone".into() })], alive:true, swings:0, drops:0, res:Res {facts:Facts}, world:World {air:true,path:false,random:Random}, audio:Audio {sounds:0} } }
#[test] fn dropping_one_and_all_swings_only_on_success() {
let mut g=game();g.drop_held(false);assert_eq!((g.drops,g.swings),(1,1));
g.drop_held(true);assert_eq!((g.drops,g.swings),(4,2));
g.drop_held(false);assert_eq!(g.swings,2);
let mut g=game();g.alive=false;g.drop_held(false);assert_eq!(g.swings,0);
}
#[test] fn successful_ignition_swings_but_blocked_ignition_does_not() {
for item in ["flint_and_steel","fire_charge"] {
let mut g=game();g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(1,1));
let mut g=game();g.world.air=false;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0));
let mut g=game();g.world.path=true;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0));
}
}
""".replace("DROP", drop).replace("IGNITION", ignition).replace("CALLER", caller)
program = program.replace("self.swings_started", "self.swings")
with tempfile.TemporaryDirectory(prefix="horizon-item-action-") as directory:
path = Path(directory)
(path / "probe.rs").write_text(program)
compiled = subprocess.run(
["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
capture_output=True, text=True, check=False,
)
self.assertEqual(compiled.returncode, 0, compiled.stderr)
tested = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr)
if __name__ == "__main__":
unittest.main()