fix(game): finish every consumable as vanilla's Consumable.onConsume
Follow-up to #773 (consume effects on food): - ApplyStatusEffectsConsumeEffect always draws its float and skips the effects when the draw is >= probability (#773 skipped the draw at 1.0 and applied on <=). - on_consume_effects run for every consumable, not only food: milk can be drunk (clear_all_effects, then the bucket), honey removes poison and leaves its glass bottle, stews their bowl (UseRemainder). - The consumable's own timing, sound, animation and particles (consume_seconds, sound, has_consume_particles) through horizon-world's Consumable.emit, in vanilla's draw order; FoodProperties.onConsume's sound and burp; the used statistic; the eat or drink game event after the effects. - teleport_randomly (chorus fruit) through horizon-world's verified TeleportConsume port, with LivingEntity.randomTeleport for the player (border clamp, entities_can_teleport_to ground, collision and liquid checks), the teleport game event and sound, level event 2017's directional particles and entity event 46's portal particles. - tools/agent_control_e2e.py: a consume scenario (golden apple at full hunger, milk, honey, chorus fruit). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -24,6 +24,7 @@ mod command_blocks;
|
||||
mod command_harness;
|
||||
mod commands;
|
||||
mod composter;
|
||||
mod consume;
|
||||
mod control;
|
||||
mod copper_golems;
|
||||
mod creaking;
|
||||
@@ -1203,6 +1204,21 @@ impl Dim {
|
||||
_ => Self::Overworld,
|
||||
}
|
||||
}
|
||||
/// `Level.getMinY`: the dimension type's minimum y.
|
||||
fn min_y(self) -> i32 {
|
||||
match self {
|
||||
Self::Overworld => MIN_Y,
|
||||
Self::Nether | Self::End => 0,
|
||||
}
|
||||
}
|
||||
/// `DimensionType.logicalHeight`.
|
||||
fn logical_height(self) -> i32 {
|
||||
match self {
|
||||
Self::Overworld => HEIGHT,
|
||||
Self::Nether => 128,
|
||||
Self::End => 256,
|
||||
}
|
||||
}
|
||||
/// `Level.getMaxY`: the dimension type's minimum y plus height, less one.
|
||||
fn max_y(self) -> i32 {
|
||||
match self {
|
||||
@@ -1977,6 +1993,11 @@ impl Game<'_> {
|
||||
pos,
|
||||
data,
|
||||
} => self.dragon_egg_particles([pos.x, pos.y, pos.z], data),
|
||||
LevelEvent::LevelEvent {
|
||||
id: 2017,
|
||||
pos,
|
||||
data,
|
||||
} => self.consume_teleport_particles([pos.x, pos.y, pos.z], data),
|
||||
LevelEvent::LevelEvent {
|
||||
id: 2013,
|
||||
pos,
|
||||
@@ -2756,15 +2777,15 @@ impl Game<'_> {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
/// `Consumable.startConsuming` for held food the player can eat
|
||||
/// (`Player.canEat`): the right click is held for `consume_seconds`.
|
||||
/// `Consumable.startConsuming` for a held consumable: food needs
|
||||
/// `Player.canEat` (`Consumable.canConsume`), anything else is always
|
||||
/// consumed. The right click is held for `consume_seconds`.
|
||||
fn start_eating(&mut self, info: &horizon_client::items::ItemInfo) -> bool {
|
||||
if !info.consumable
|
||||
|| info.food.is_none()
|
||||
|| !self
|
||||
.player
|
||||
.as_ref()
|
||||
.is_some_and(|p| info.can_always_eat || p.health.food.food < 20 || self.creative)
|
||||
if info.consumable.is_none()
|
||||
|| (info.food.is_some()
|
||||
&& !self.player.as_ref().is_some_and(|p| {
|
||||
info.can_always_eat || p.health.food.food < 20 || self.creative
|
||||
}))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -2773,18 +2794,17 @@ impl Game<'_> {
|
||||
}
|
||||
true
|
||||
}
|
||||
fn apply_consume_effect(
|
||||
&mut self,
|
||||
effect: &horizon_client::items::ConsumeEffect,
|
||||
eye: [f64; 3],
|
||||
) {
|
||||
fn apply_consume_effect(&mut self, effect: &horizon_client::items::ConsumeEffect) {
|
||||
use horizon_client::items::ConsumeEffect;
|
||||
match effect {
|
||||
ConsumeEffect::ApplyEffects {
|
||||
effects,
|
||||
probability,
|
||||
} => {
|
||||
if *probability >= 1.0 || self.world.random.next_float() <= *probability {
|
||||
// ApplyStatusEffectsConsumeEffect.apply: the user's random
|
||||
// (the level's stands in, as for every player draw) is drawn
|
||||
// even at probability 1.
|
||||
if self.world.random.next_float() < *probability {
|
||||
for eff in effects {
|
||||
if let Some(def) = horizon_client::brewing::effect(&eff.id) {
|
||||
if def.instant {
|
||||
@@ -2817,9 +2837,14 @@ impl Game<'_> {
|
||||
}
|
||||
self.apply_effect_status();
|
||||
}
|
||||
ConsumeEffect::TeleportRandomly => {}
|
||||
ConsumeEffect::TeleportRandomly(teleport) => self.teleport_randomly(teleport),
|
||||
ConsumeEffect::PlaySound(sound) => {
|
||||
self.audio.play(sound, Some(eye), 1.0, 1.0);
|
||||
// PlaySoundConsumeEffect: at the user's block position.
|
||||
let at = self.player.as_ref().map(|p| {
|
||||
let b = horizon_core::position::BlockPos::containing(p.position);
|
||||
[b.x, b.y, b.z].map(|v| f64::from(v) + 0.5)
|
||||
});
|
||||
self.audio.play(sound, at, 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2901,49 +2926,21 @@ impl Game<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let duration = 32;
|
||||
// Consumable.shouldEmitParticlesAndSounds(useItemRemainingTicks), with
|
||||
// the remaining ticks before this tick counts down: every 4 ticks once
|
||||
// more than 21.875% of the time has passed (none on the last tick).
|
||||
let Some(consumable) = info.consumable.as_ref() else {
|
||||
self.using = None;
|
||||
return;
|
||||
};
|
||||
// ItemStack.onUseTick: Consumable.shouldEmitParticlesAndSounds with
|
||||
// the remaining ticks before this tick counts them down.
|
||||
let duration = consumable.ticks().max(0) as u32;
|
||||
let remaining = duration - ticks.min(duration);
|
||||
let ticks = ticks + 1;
|
||||
let eye = self.eye_position().unwrap_or_default();
|
||||
if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 {
|
||||
let pitch =
|
||||
(self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0;
|
||||
self.audio.play(
|
||||
"minecraft:entity.generic.eat",
|
||||
Some(eye),
|
||||
0.5 + 0.5 * self.world.random.next_int_bound(2).unwrap_or(0) as f32,
|
||||
pitch,
|
||||
);
|
||||
self.eat_particles(&stack, 5);
|
||||
if consumable.should_emit(remaining as i32) {
|
||||
self.emit_consume(consumable, &stack, 5);
|
||||
}
|
||||
if ticks >= duration {
|
||||
self.using = None;
|
||||
// Consumable.onConsume: emitParticlesAndSounds(..., 16).
|
||||
self.eat_particles(&stack, 16);
|
||||
// Consumable.onConsume.
|
||||
self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player);
|
||||
if let Some((nutrition, saturation)) = info.food {
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
// FoodData.eat(nutrition, saturation)
|
||||
let food = &mut p.health.food;
|
||||
food.food = (food.food + nutrition as i32).clamp(0, 20);
|
||||
food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32);
|
||||
}
|
||||
self.audio.play(
|
||||
"minecraft:entity.player.burp",
|
||||
Some(eye),
|
||||
0.5,
|
||||
self.world.random.next_float() * 0.1 + 0.9,
|
||||
);
|
||||
for effect in &info.consume_effects {
|
||||
self.apply_consume_effect(effect, eye);
|
||||
}
|
||||
self.trigger_item("minecraft:consume_item", &stack);
|
||||
self.consume_held();
|
||||
}
|
||||
self.finish_consuming(&info, consumable, &stack);
|
||||
} else {
|
||||
self.using = Some((slot, ticks));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Finishing a consumable (`Consumable.onConsume` and the use remainder),
|
||||
//! its particles and sounds, and `TeleportRandomlyConsumeEffect` (chorus
|
||||
//! fruit) for the local player. The level random stands in for the player's
|
||||
//! own, as for every other player draw.
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::{
|
||||
items::{ConsumeEffect, ItemInfo, ItemStack},
|
||||
mobs::Who,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Vec3, position::BlockPos, random::LegacyRandom, random::RandomSource,
|
||||
};
|
||||
use horizon_world::{
|
||||
consumable::{Consumable, EmissionWorld, UseAnimation},
|
||||
teleport_consume::{TeleportConsume, TeleportConsumeWorld},
|
||||
};
|
||||
use std::convert::Infallible;
|
||||
|
||||
type ItemConsumable = Consumable<String, ConsumeEffect>;
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`.
|
||||
pub(super) fn emit_consume(
|
||||
&mut self,
|
||||
consumable: &ItemConsumable,
|
||||
stack: &ItemStack,
|
||||
count: i32,
|
||||
) {
|
||||
let Ok(()) = consumable.emit(&mut Emitter(self), (), stack.clone(), count);
|
||||
}
|
||||
/// `LivingEntity.completeUsingItem` for a consumable: `Consumable.onConsume`,
|
||||
/// then `ItemStack.applyAfterUseComponentSideEffects`' use remainder.
|
||||
pub(super) fn finish_consuming(
|
||||
&mut self,
|
||||
info: &ItemInfo,
|
||||
consumable: &ItemConsumable,
|
||||
stack: &ItemStack,
|
||||
) {
|
||||
self.emit_consume(consumable, stack, 16);
|
||||
// ServerPlayer: the used statistic and the consume_item trigger.
|
||||
self.stats.add("used", &stack.item, 1);
|
||||
self.trigger_item("minecraft:consume_item", stack);
|
||||
// FoodProperties.onConsume, the player's one ConsumableListener.
|
||||
if let Some((nutrition, saturation)) = info.food {
|
||||
let at = self.feet();
|
||||
let pitch = self.world.random.triangle_float(1.0, 0.4);
|
||||
self.audio.play(&consumable.sound, at, 1.0, pitch);
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
// FoodData.eat(nutrition, saturation)
|
||||
let food = &mut p.health.food;
|
||||
food.food = (food.food + nutrition as i32).clamp(0, 20);
|
||||
food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32);
|
||||
}
|
||||
// Mth.randomBetween(random, 0.9, 1.0)
|
||||
let pitch = self.world.random.next_float() * (1.0f32 - 0.9f32) + 0.9;
|
||||
self.audio
|
||||
.play("minecraft:entity.player.burp", self.feet(), 0.5, pitch);
|
||||
}
|
||||
for effect in &consumable.effects {
|
||||
self.apply_consume_effect(effect);
|
||||
}
|
||||
let event = if consumable.animation == UseAnimation::Drink {
|
||||
"minecraft:drink"
|
||||
} else {
|
||||
"minecraft:eat"
|
||||
};
|
||||
self.post_entity_event(event, Who::Player);
|
||||
// ItemStack.consume, then UseRemainder.convertIntoRemainder: nothing
|
||||
// with infinite materials, the hand when emptied, else the inventory
|
||||
// (ServerPlayer.handleExtraItemsCreatedOnUse) or a drop.
|
||||
self.consume_held();
|
||||
if let Some(remainder) = &info.use_remainder
|
||||
&& !self.creative
|
||||
{
|
||||
let remainder = ItemStack::new(remainder, 1);
|
||||
if self.held().is_none() {
|
||||
*self.held_mut() = Some(remainder);
|
||||
} else if let Some(rest) = self.give(remainder) {
|
||||
self.player_drop(rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn feet(&self) -> Option<[f64; 3]> {
|
||||
self.player
|
||||
.as_ref()
|
||||
.map(|p| [p.position.x, p.position.y, p.position.z])
|
||||
}
|
||||
/// `TeleportRandomlyConsumeEffect.apply` for the local player.
|
||||
pub(super) fn teleport_randomly(&mut self, teleport: &TeleportConsume) {
|
||||
if self.player.is_none() {
|
||||
return;
|
||||
}
|
||||
let dim = self.dim;
|
||||
let Ok(_) = teleport.apply(&mut Teleporter(self), dim);
|
||||
}
|
||||
/// `LivingEntity.randomTeleport(x, y, z, true, avoid)`: down to the first
|
||||
/// block entities can teleport onto, inside the border, in a loaded chunk.
|
||||
fn random_teleport(&mut self, target: Vec3, avoid: &str) -> bool {
|
||||
let [min_x, min_z, max_x, max_z] = self.border.bounds();
|
||||
// WorldBorder.clampVec3ToBound (Mth.clamp, 1.0E-5F inside the far edge).
|
||||
let clamp = |v: f64, low: f64, high: f64| if v < low { low } else { v.min(high) };
|
||||
let x = clamp(target.x, min_x, max_x - f64::from(1.0e-5_f32));
|
||||
let z = clamp(target.z, min_z, max_z - f64::from(1.0e-5_f32));
|
||||
let mut y = target.y;
|
||||
let mut pos = BlockPos::containing(Vec3::new(x, y, z));
|
||||
if !self.world.loaded(pos.x, pos.z) {
|
||||
return false;
|
||||
}
|
||||
while pos.y > self.dim.min_y() {
|
||||
pos.y -= 1;
|
||||
let state = self.world.block(pos.x, pos.y, pos.z);
|
||||
if self.state_in_tag("minecraft:entities_can_teleport_to", state) {
|
||||
return self.check_position_and_teleport(Vec3::new(x, y, z), state, avoid);
|
||||
}
|
||||
y -= 1.0;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `LivingEntity.checkPositionAndTeleport`, then `ServerPlayer.teleportTo`
|
||||
/// (the motion and rotation kept) and entity event 46.
|
||||
fn check_position_and_teleport(
|
||||
&mut self,
|
||||
at: Vec3,
|
||||
ground: horizon_world::registry::BlockStateId,
|
||||
avoid: &str,
|
||||
) -> bool {
|
||||
if self.state_in_tag(avoid, ground) {
|
||||
return false;
|
||||
}
|
||||
let entities = self.happy_ghast_player_collisions();
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
let bounds = player.dimensions.bounds(at);
|
||||
let free = horizon_client::motion::MotionWorld {
|
||||
entities: &entities,
|
||||
player,
|
||||
scene: &mut self.world,
|
||||
assets: &self.pack.assets,
|
||||
collision_binding: self.collision,
|
||||
resources: self.motion,
|
||||
}
|
||||
.no_player_collision(bounds)
|
||||
.unwrap_or(false);
|
||||
// LevelReader.containsAnyLiquid and findBlocksIn: the blocks from the
|
||||
// box's minimum corner to the one holding its maximum corner.
|
||||
let (lo, hi) = (
|
||||
BlockPos::containing(bounds.min_position()),
|
||||
BlockPos::containing(bounds.max_position()),
|
||||
);
|
||||
let blocks = (lo.x..=hi.x)
|
||||
.flat_map(|x| (lo.y..=hi.y).flat_map(move |y| (lo.z..=hi.z).map(move |z| (x, y, z))));
|
||||
let states: Vec<_> = blocks.map(|(x, y, z)| self.world.block(x, y, z)).collect();
|
||||
let liquid = states
|
||||
.iter()
|
||||
.any(|&s| self.res.facts.get(s).fluid != horizon_client::blocks::Fluid::None);
|
||||
if !free || liquid || states.iter().any(|&s| self.state_in_tag(avoid, s)) {
|
||||
return false;
|
||||
}
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
p.position = at;
|
||||
}
|
||||
// The position packet moves the old position along (absolute xyz).
|
||||
self.previous_position = at;
|
||||
self.portal_particles();
|
||||
true
|
||||
}
|
||||
fn state_in_tag(&self, tag: &str, state: horizon_world::registry::BlockStateId) -> bool {
|
||||
let name = &self.res.facts.get(state).name;
|
||||
self.res
|
||||
.items
|
||||
.block_tags
|
||||
.get(tag)
|
||||
.is_some_and(|s| s.contains(&**name))
|
||||
}
|
||||
/// `LivingEntity.handleEntityEvent(46)`: 128 portal particles from the old
|
||||
/// to the new position, from the client player's random (the particle
|
||||
/// engine's here).
|
||||
fn portal_particles(&mut self) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let (from, to) = (self.previous_position, p.position);
|
||||
let (width, height) = (
|
||||
f64::from(p.dimensions.width),
|
||||
f64::from(p.dimensions.height),
|
||||
);
|
||||
let options = ParticleOptions::simple(ParticleType::Portal);
|
||||
for i in 0..128 {
|
||||
let d = f64::from(i) / 127.0;
|
||||
let r = self.particles.random();
|
||||
let v = [0; 3].map(|_| f64::from((r.next_float() - 0.5) * 0.2));
|
||||
let x = from.x + d * (to.x - from.x) + (r.next_double() - 0.5) * width * 2.0;
|
||||
let y = from.y + d * (to.y - from.y) + r.next_double() * height;
|
||||
let z = from.z + d * (to.z - from.z) + (r.next_double() - 0.5) * width * 2.0;
|
||||
self.particles.add(&options, [x, y, z], v);
|
||||
}
|
||||
}
|
||||
/// `LivingEntity.stopRiding`.
|
||||
pub(super) fn stop_riding(&mut self) {
|
||||
let Some(id) = self.riding else {
|
||||
return;
|
||||
};
|
||||
if let Some(i) = self.boats.iter().position(|b| b.id == id) {
|
||||
self.dismount(i);
|
||||
} else if let Some(i) = self.carts.iter().position(|c| c.id == id) {
|
||||
self.dismount_cart(i);
|
||||
} else {
|
||||
self.dismount_mount();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Consumable.emitParticlesAndSounds` against the local player.
|
||||
struct Emitter<'a, 'g>(&'a mut Game<'g>);
|
||||
impl EmissionWorld for Emitter<'_, '_> {
|
||||
type Error = Infallible;
|
||||
type Stack = ItemStack;
|
||||
type Sound = String;
|
||||
type Random = ();
|
||||
type Source = LegacyRandom;
|
||||
fn random_source(&mut self, (): ()) -> &mut LegacyRandom {
|
||||
&mut self.0.world.random
|
||||
}
|
||||
/// `LivingEntity.spawnItemParticles`.
|
||||
fn spawn_item_particles(&mut self, stack: ItemStack, count: i32) -> Result<(), Infallible> {
|
||||
self.0.eat_particles(&stack, count.max(0) as u32);
|
||||
Ok(())
|
||||
}
|
||||
fn overrides_consume_sound(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn consume_sound(&mut self, _: ItemStack) -> Result<String, Infallible> {
|
||||
unreachable!("players play the consumable's own sound")
|
||||
}
|
||||
/// `Entity.playSound`: at the player's position.
|
||||
fn play_sound(&mut self, sound: String, volume: f32, pitch: f32) -> Result<(), Infallible> {
|
||||
let at = self.0.feet();
|
||||
self.0.audio.play(&sound, at, volume, pitch);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The local player as `TeleportRandomlyConsumeEffect`'s user.
|
||||
struct Teleporter<'a, 'g>(&'a mut Game<'g>);
|
||||
impl Teleporter<'_, '_> {
|
||||
fn at(&self) -> Vec3 {
|
||||
self.0.player.as_ref().map_or(Vec3::ZERO, |p| p.position)
|
||||
}
|
||||
}
|
||||
impl TeleportConsumeWorld for Teleporter<'_, '_> {
|
||||
type Error = Infallible;
|
||||
type Level = Dim;
|
||||
type Random = ();
|
||||
type Source = LegacyRandom;
|
||||
fn position_field(&self) -> Vec3 {
|
||||
self.at()
|
||||
}
|
||||
fn get_random(&mut self) -> Result<(), Infallible> {
|
||||
Ok(())
|
||||
}
|
||||
fn random_source(&mut self, (): ()) -> &mut LegacyRandom {
|
||||
&mut self.0.world.random
|
||||
}
|
||||
fn min_y(&mut self, level: Dim) -> Result<i32, Infallible> {
|
||||
Ok(level.min_y())
|
||||
}
|
||||
fn logical_height(&mut self, level: Dim) -> Result<i32, Infallible> {
|
||||
Ok(level.logical_height())
|
||||
}
|
||||
fn is_passenger(&mut self) -> Result<bool, Infallible> {
|
||||
Ok(self.0.riding.is_some())
|
||||
}
|
||||
fn stop_riding(&mut self) -> Result<(), Infallible> {
|
||||
self.0.stop_riding();
|
||||
Ok(())
|
||||
}
|
||||
fn position(&mut self) -> Result<Vec3, Infallible> {
|
||||
Ok(self.at())
|
||||
}
|
||||
fn random_teleport(&mut self, target: Vec3) -> Result<bool, Infallible> {
|
||||
Ok(self
|
||||
.0
|
||||
.random_teleport(target, "minecraft:consumable_does_not_teleport_to"))
|
||||
}
|
||||
fn teleport_event(&mut self, _: Dim, old: Vec3) -> Result<(), Infallible> {
|
||||
let ctx = self.0.who_context(Some(Who::Player), None);
|
||||
self.0
|
||||
.post_game_event("minecraft:teleport", [old.x, old.y, old.z], ctx);
|
||||
Ok(())
|
||||
}
|
||||
fn is_fox(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn teleport_sound(&mut self, _: Dim, at: Vec3, _: bool) -> Result<(), Infallible> {
|
||||
self.0.audio.play(
|
||||
"minecraft:item.chorus_fruit.teleport",
|
||||
Some([at.x, at.y, at.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn block_position(&mut self) -> Result<BlockPos, Infallible> {
|
||||
Ok(BlockPos::containing(self.at()))
|
||||
}
|
||||
fn directional_particles(
|
||||
&mut self,
|
||||
_: Dim,
|
||||
origin: BlockPos,
|
||||
offset: i32,
|
||||
) -> Result<(), Infallible> {
|
||||
self.0
|
||||
.level_event_at(2017, [origin.x, origin.y, origin.z], offset);
|
||||
Ok(())
|
||||
}
|
||||
fn reset_fall_distance(&mut self) -> Result<(), Infallible> {
|
||||
if let Some(p) = self.0.player.as_mut() {
|
||||
p.fall_distance = 0.0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn reset_impulse(&mut self) -> Result<(), Infallible> {
|
||||
if let Some(p) = self.0.player.as_mut() {
|
||||
p.impulse.reset();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Level events whose client handler (`LevelEventHandler`) spawns particles
|
||||
//! on a block: dragon egg teleportation (2015), electric sparks (3002),
|
||||
//! waxing (3003), wax off (3004) and scraping (3005).
|
||||
//! on a block: dragon egg teleportation (2015), a consumable's teleport
|
||||
//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and
|
||||
//! scraping (3005).
|
||||
use super::Game;
|
||||
use horizon_client::particles::{self, ParticleOptions, ParticleType};
|
||||
use horizon_core::position::BlockPos;
|
||||
@@ -9,7 +10,12 @@ use horizon_world::level::LevelEvent;
|
||||
impl Game<'_> {
|
||||
pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) {
|
||||
self.particles
|
||||
.block_teleportation(pos, data, self.settings.particles);
|
||||
.block_teleportation(pos, data, [16, 8, 16], self.settings.particles);
|
||||
}
|
||||
/// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles.
|
||||
pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) {
|
||||
self.particles
|
||||
.block_teleportation(pos, data, [127, 127, 127], self.settings.particles);
|
||||
}
|
||||
/// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client
|
||||
/// level's random.
|
||||
|
||||
@@ -1204,6 +1204,9 @@ impl Game<'_> {
|
||||
C::LevelEvent(p) if p.kind == 2015 => {
|
||||
self.dragon_egg_particles(p.pos, p.data);
|
||||
}
|
||||
C::LevelEvent(p) if p.kind == 2017 => {
|
||||
self.consume_teleport_particles(p.pos, p.data);
|
||||
}
|
||||
C::LevelEvent(p) if p.kind == 2001 => {
|
||||
// LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block.
|
||||
let state = BlockStateId(p.data.max(0) as u32);
|
||||
@@ -2901,7 +2904,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `LivingEntity.updatingUsingItem` for food on a server client: the
|
||||
/// `LivingEntity.updatingUsingItem` for a consumable on a server client: the
|
||||
/// eating animation and its crumbs. The server eats it and sends the
|
||||
/// stack, the hunger and the sounds.
|
||||
fn remote_tick_using(&mut self) {
|
||||
@@ -2909,11 +2912,11 @@ impl Game<'_> {
|
||||
return;
|
||||
};
|
||||
let stack = self.stack_in(slot).cloned();
|
||||
let food = stack
|
||||
let consumable = stack
|
||||
.as_ref()
|
||||
.and_then(|s| self.res.items.get(&s.item))
|
||||
.is_some_and(|i| i.consumable && i.food.is_some());
|
||||
let (Some(stack), true) = (stack, food) else {
|
||||
.and_then(|i| i.consumable.clone());
|
||||
let (Some(stack), Some(consumable)) = (stack, consumable) else {
|
||||
self.using = None;
|
||||
return;
|
||||
};
|
||||
@@ -2922,14 +2925,16 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
// Consumable.shouldEmitParticlesAndSounds, as in tick_used_item.
|
||||
let duration = 32;
|
||||
let duration = consumable.ticks().max(0) as u32;
|
||||
let remaining = duration - ticks.min(duration);
|
||||
if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 {
|
||||
if consumable.particles && consumable.should_emit(remaining as i32) {
|
||||
self.eat_particles(&stack, 5);
|
||||
}
|
||||
if ticks + 1 >= duration {
|
||||
self.using = None;
|
||||
self.eat_particles(&stack, 16);
|
||||
if consumable.particles {
|
||||
self.eat_particles(&stack, 16);
|
||||
}
|
||||
} else {
|
||||
self.using = Some((slot, ticks + 1));
|
||||
}
|
||||
|
||||
@@ -54,7 +54,8 @@ pub enum ConsumeEffect {
|
||||
},
|
||||
ClearAllEffects,
|
||||
RemoveEffects(Vec<String>),
|
||||
TeleportRandomly,
|
||||
/// `TeleportRandomlyConsumeEffect`.
|
||||
TeleportRandomly(horizon_world::teleport_consume::TeleportConsume),
|
||||
PlaySound(String),
|
||||
}
|
||||
|
||||
@@ -69,8 +70,10 @@ pub struct ItemInfo {
|
||||
pub tool_default_speed: f32,
|
||||
pub food: Option<(u32, f32)>,
|
||||
pub can_always_eat: bool,
|
||||
pub consumable: bool,
|
||||
pub consume_effects: Vec<ConsumeEffect>,
|
||||
/// `consumable`: its timing, sound, particles and `on_consume_effects`.
|
||||
pub consumable: Option<horizon_world::consumable::Consumable<String, ConsumeEffect>>,
|
||||
/// `use_remainder`: what a finished use leaves (`UseRemainder`).
|
||||
pub use_remainder: Option<String>,
|
||||
pub model: String,
|
||||
/// Main-hand `attack_damage` / `attack_speed` modifier amounts.
|
||||
pub attack_damage: f32,
|
||||
@@ -504,7 +507,18 @@ impl Items {
|
||||
consume_effects.push(ConsumeEffect::RemoveEffects(targets));
|
||||
}
|
||||
Some("minecraft:teleport_randomly") => {
|
||||
consume_effects.push(ConsumeEffect::TeleportRandomly);
|
||||
consume_effects.push(ConsumeEffect::TeleportRandomly(
|
||||
horizon_world::teleport_consume::TeleportConsume {
|
||||
diameter: effect
|
||||
.get("diameter")
|
||||
.and_then(Value::as_f64)
|
||||
.map_or(16.0, |d| d as f32),
|
||||
directional_particles: effect
|
||||
.get("directional_particles")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true),
|
||||
},
|
||||
));
|
||||
}
|
||||
Some("minecraft:play_sound") => {
|
||||
if let Some(sound) = effect.get("sound").and_then(|s| s.as_str()) {
|
||||
@@ -530,8 +544,22 @@ impl Items {
|
||||
.unwrap_or(1.0) as f32,
|
||||
food,
|
||||
can_always_eat,
|
||||
consumable: c.get("minecraft:consumable").is_some(),
|
||||
consume_effects,
|
||||
// Consumable.CODEC's defaults.
|
||||
consumable: c.get("minecraft:consumable").map(|cons| {
|
||||
horizon_world::consumable::Consumable {
|
||||
seconds: cons["consume_seconds"].as_f64().map_or(1.6, |s| s as f32),
|
||||
animation: crate::first_person::consumable_animation(cons),
|
||||
sound: cons["sound"]
|
||||
.as_str()
|
||||
.unwrap_or("minecraft:entity.generic.eat")
|
||||
.to_owned(),
|
||||
particles: cons["has_consume_particles"].as_bool().unwrap_or(true),
|
||||
effects: std::mem::take(&mut consume_effects),
|
||||
}
|
||||
}),
|
||||
use_remainder: c["minecraft:use_remainder"]["id"]
|
||||
.as_str()
|
||||
.map(str::to_owned),
|
||||
model: c["minecraft:item_model"]
|
||||
.as_str()
|
||||
.unwrap_or(name)
|
||||
@@ -1607,18 +1635,63 @@ mod tests {
|
||||
let apple = items.get("minecraft:golden_apple").expect("golden apple");
|
||||
assert!(apple.can_always_eat);
|
||||
assert!(apple.food.is_some());
|
||||
assert!(!apple.consume_effects.is_empty());
|
||||
assert!(!apple.consumable.as_ref().unwrap().effects.is_empty());
|
||||
|
||||
let enchanted = items
|
||||
.get("minecraft:enchanted_golden_apple")
|
||||
.expect("enchanted golden apple");
|
||||
assert!(enchanted.can_always_eat);
|
||||
assert!(enchanted.food.is_some());
|
||||
assert!(!enchanted.consume_effects.is_empty());
|
||||
assert!(!enchanted.consumable.as_ref().unwrap().effects.is_empty());
|
||||
|
||||
let beef = items.get("minecraft:cooked_beef").expect("cooked beef");
|
||||
assert!(!beef.can_always_eat);
|
||||
assert!(beef.food.is_some());
|
||||
|
||||
// Consumables without food, their style and their remainders.
|
||||
use horizon_world::consumable::UseAnimation;
|
||||
let milk = items.get("minecraft:milk_bucket").expect("milk bucket");
|
||||
let drink = milk.consumable.as_ref().unwrap();
|
||||
assert!(milk.food.is_none());
|
||||
assert_eq!(drink.effects, [ConsumeEffect::ClearAllEffects]);
|
||||
assert_eq!((drink.ticks(), drink.animation), (32, UseAnimation::Drink));
|
||||
assert_eq!(drink.sound, "minecraft:entity.generic.drink");
|
||||
assert!(!drink.particles);
|
||||
assert_eq!(milk.use_remainder.as_deref(), Some("minecraft:bucket"));
|
||||
let honey = items.get("minecraft:honey_bottle").expect("honey bottle");
|
||||
let sip = honey.consumable.as_ref().unwrap();
|
||||
assert_eq!(sip.ticks(), 40);
|
||||
assert_eq!(sip.sound, "minecraft:item.honey_bottle.drink");
|
||||
assert_eq!(
|
||||
sip.effects,
|
||||
[ConsumeEffect::RemoveEffects(vec![
|
||||
"minecraft:poison".into()
|
||||
])]
|
||||
);
|
||||
assert_eq!(
|
||||
honey.use_remainder.as_deref(),
|
||||
Some("minecraft:glass_bottle")
|
||||
);
|
||||
let kelp = items.get("minecraft:dried_kelp").unwrap();
|
||||
let bite = kelp.consumable.as_ref().unwrap();
|
||||
assert_eq!((bite.ticks(), bite.animation), (16, UseAnimation::Eat));
|
||||
assert_eq!(bite.sound, "minecraft:entity.generic.eat");
|
||||
assert!(bite.particles && kelp.use_remainder.is_none());
|
||||
let chorus = items.get("minecraft:chorus_fruit").unwrap();
|
||||
assert_eq!(
|
||||
chorus.consumable.as_ref().unwrap().effects,
|
||||
[ConsumeEffect::TeleportRandomly(
|
||||
horizon_world::teleport_consume::TeleportConsume {
|
||||
diameter: 16.0,
|
||||
directional_particles: true,
|
||||
}
|
||||
)]
|
||||
);
|
||||
let chicken = items.get("minecraft:chicken").unwrap();
|
||||
assert!(matches!(
|
||||
chicken.consumable.as_ref().unwrap().effects[..],
|
||||
[ConsumeEffect::ApplyEffects { probability, .. }] if probability == 0.3
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -639,7 +639,8 @@ impl MotionWorld<'_, '_, '_> {
|
||||
entities: self.entities,
|
||||
}
|
||||
}
|
||||
pub(crate) fn no_player_collision(&mut self, bounds: Aabb) -> Result<bool> {
|
||||
/// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes.
|
||||
pub fn no_player_collision(&mut self, bounds: Aabb) -> Result<bool> {
|
||||
let context = self.context();
|
||||
Ok(world_movement::no_world_collision(
|
||||
&mut self.movement_collisions(),
|
||||
|
||||
@@ -1264,12 +1264,21 @@ impl ParticleEngine {
|
||||
}
|
||||
self.create(options, p, v);
|
||||
}
|
||||
/// `LevelEventHandler.singleBlockTeleportationParticles` (event 2015).
|
||||
pub fn block_teleportation(&mut self, from: [i32; 3], data: i32, particle_level: u8) {
|
||||
/// `LevelEventHandler.singleBlockTeleportationParticles` towards
|
||||
/// `BlockUtil.unpackDifferenceInPosition(from, data, radius)`: the dragon
|
||||
/// egg's event 2015 packs offsets within (16, 8, 16), a consumable's
|
||||
/// teleport (2017) within (127, 127, 127).
|
||||
pub fn block_teleportation(
|
||||
&mut self,
|
||||
from: [i32; 3],
|
||||
data: i32,
|
||||
radius: [i32; 3],
|
||||
particle_level: u8,
|
||||
) {
|
||||
let to = [
|
||||
from[0].wrapping_add(((data >> 16) & 255) - 16),
|
||||
from[1].wrapping_add(((data >> 8) & 255) - 8),
|
||||
from[2].wrapping_add((data & 255) - 16),
|
||||
from[0].wrapping_add(((data >> 16) & 255) - radius[0]),
|
||||
from[1].wrapping_add(((data >> 8) & 255) - radius[1]),
|
||||
from[2].wrapping_add((data & 255) - radius[2]),
|
||||
]
|
||||
.map(f64::from);
|
||||
let from = from.map(f64::from);
|
||||
@@ -3798,7 +3807,7 @@ mod tests {
|
||||
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new());
|
||||
engine.seed_randoms(0, 0, 0);
|
||||
// Destination offset (-15, 7, 15); the unused top byte is ignored.
|
||||
engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, 0);
|
||||
engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0);
|
||||
assert_eq!(engine.pending.len(), 128);
|
||||
assert!(engine.pending.iter().all(|p| p.ty == ParticleType::Portal));
|
||||
let first = &engine.pending[0];
|
||||
@@ -3818,6 +3827,25 @@ mod tests {
|
||||
assert!(engine.sounds.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consume_teleport_unpacks_offsets_within_127() {
|
||||
let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new());
|
||||
engine.seed_randoms(0, 0, 0);
|
||||
// TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition
|
||||
// of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4).
|
||||
let data = (-7 + 127) << 16 | (-3 + 127) << 8 | (9 + 127);
|
||||
engine.block_teleportation([4, 12, -5], data, [127, 127, 127], 0);
|
||||
assert_eq!(engine.pending.len(), 128);
|
||||
for p in &engine.pending {
|
||||
let [x, y, z] = p.position;
|
||||
assert!((-3.0..5.0).contains(&x), "{x}");
|
||||
assert!((8.5..12.5).contains(&y), "{y}");
|
||||
assert!((-5.0..5.0).contains(&z), "{z}");
|
||||
}
|
||||
// The same draws as the egg's: only the unpacking differs.
|
||||
assert_eq!(engine.level_random.state(), 99_413_408_083_437);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn egg_teleport_options_roll_before_distance_rejection() {
|
||||
for (option, count, state) in [
|
||||
@@ -3831,7 +3859,7 @@ mod tests {
|
||||
if distant {
|
||||
engine.camera = [1000.0; 3];
|
||||
}
|
||||
engine.block_teleportation([4, 12, -5], 0x010f1f, option);
|
||||
engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16], option);
|
||||
assert_eq!(engine.pending.len(), if distant { 0 } else { count });
|
||||
assert_eq!(engine.level_random.state(), state);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ runs through the CLI (one horizon-ctl process per command) and through `horizon-
|
||||
small JSON-RPC client, and saves a screenshot of each run. The ui scenario drives the menus by
|
||||
widget id instead: the title screen, the options (a slider set by id) and the inventory's slots;
|
||||
the options scenario reads and sets options.txt values by key; the events scenario waits for
|
||||
states (wait-for) and reads the event log.
|
||||
states (wait-for) and reads the event log; the consume scenario eats and drinks consumables (a
|
||||
golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport.
|
||||
|
||||
python3 tools/agent_control_e2e.py # both modes
|
||||
python3 tools/agent_control_e2e.py --mode mcp # one of them
|
||||
@@ -378,7 +379,52 @@ def events_scenario(d, out):
|
||||
return {'events': len(events)}
|
||||
|
||||
|
||||
SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario}
|
||||
def consume_scenario(d, out):
|
||||
# Consumables finish as vanilla's Consumable.onConsume: always-edible food at full hunger with its
|
||||
# effects, milk and honey (no food or drink sounds) with their effects and use remainders, and
|
||||
# chorus fruit's random teleport.
|
||||
d('click', id='singleplayer')
|
||||
if 'game' not in widgets(d):
|
||||
d('click', id='create-new-world')
|
||||
d('type', field='name', replace=True, text='Consume')
|
||||
d('click', id='create-new-world')
|
||||
d('wait_for', condition='loaded', timeout=400)
|
||||
|
||||
def consume(item, seconds):
|
||||
d('command', command='clear @s')
|
||||
d('give', item=item, count=1)
|
||||
d('use_item', hold=seconds)
|
||||
d('wait', ticks=5)
|
||||
state = d('state')
|
||||
return state, {e['id'] for e in state['player']['effects']}
|
||||
|
||||
def held(state):
|
||||
return state['held'] and state['held']['item']
|
||||
|
||||
state, effects = consume('golden_apple', 2.2)
|
||||
assert state['player']['food'] == 20 and {'regeneration', 'absorption'} <= effects, effects
|
||||
assert held(state) is None, state['held']
|
||||
d('command', command='effect give @s minecraft:speed 60')
|
||||
state, effects = consume('milk_bucket', 2.2)
|
||||
assert effects == set(), effects
|
||||
assert held(state) == 'minecraft:bucket', state['held']
|
||||
d('command', command='effect give @s minecraft:poison 60')
|
||||
d('command', command='effect give @s minecraft:speed 60')
|
||||
state, effects = consume('honey_bottle', 2.6)
|
||||
assert effects == {'speed'}, effects
|
||||
assert held(state) == 'minecraft:glass_bottle', state['held']
|
||||
before = d('state')['player']['position']
|
||||
state, _ = consume('chorus_fruit', 2.2)
|
||||
after = state['player']['position']
|
||||
moved = [b - a for a, b in zip(before, after)]
|
||||
assert held(state) is None, state['held']
|
||||
assert moved != [0, 0, 0] and abs(moved[0]) <= 8 and abs(moved[2]) <= 8, moved
|
||||
d('screenshot', path=str(out / f'consume-{d.name}.png'))
|
||||
return {'teleported': [round(m, 2) for m in moved]}
|
||||
|
||||
|
||||
SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario,
|
||||
'consume': consume_scenario}
|
||||
|
||||
|
||||
def run(mode, ctl, out, resources, which='survival'):
|
||||
|
||||
Reference in New Issue
Block a user