Merge pull request #311 from ludovic111/fix/shield-deflects-arrows

Shields turn arrows back, as vanilla does
This commit is contained in:
Ludovic Marie
2026-10-15 12:32:06 +02:00
committed by GitHub
5 changed files with 319 additions and 101 deletions
+56 -5
View File
@@ -4,7 +4,8 @@
use horizon_client::{
Result,
arrows::{
self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, Pickup, Touch,
self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, EntityHit, Pickup,
Touch,
},
assets::Assets,
blocks::BlockFacts,
@@ -12,11 +13,11 @@ use horizon_client::{
items::ItemStack,
mobs::Who,
motion::{LAVA, MotionResources, WATER},
projectiles::{Projectile, ProjectileKind},
projectiles::{Hit, Projectile, ProjectileKind},
world::World,
};
use horizon_core::{
geometry::Vec3,
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
use serde_json::Value;
@@ -89,11 +90,16 @@ fn main() -> Result<()> {
&ItemStack::new("minecraft:arrow", 1),
f["intangible"].as_bool().unwrap(),
));
// The entity in the way: its box and whether it takes the damage.
let mut target: Option<(Aabb, bool)> = None;
for op in f["ops"].as_array().unwrap() {
let mut events = Vec::new();
let mut touched = "-".to_string();
match op["mode"].as_str().unwrap() {
"tick" => {
// The game's part of an entity hit: the damage it deals
// (recorded after the tick's own events).
let mut hurt = None;
if !arrow.arrow.as_ref().unwrap().removed {
let no_rain = |_| false;
let view = ArrowScene {
@@ -106,9 +112,35 @@ fn main() -> Result<()> {
mob_griefing: true,
tnt_explodes: true,
};
arrows::tick(&mut arrow, &view, &[]);
let targets: Vec<_> = target.iter().map(|t| (Who::Mob(2), t.0)).collect();
let (_, hit) = arrows::tick(&mut arrow, &view, &targets);
if let (Hit::Entity { .. }, Some((_, takes))) = (hit, target) {
let mut st = arrow.arrow.take().unwrap();
let damage = arrow.arrow_damage(&mut st.random);
hurt = Some((st.events.len(), damage));
arrow.arrow = Some(st);
let outcome = if takes {
EntityHit::Hurt
} else {
EntityHit::Refused
};
arrows::finish_entity_hit(&mut arrow, &view, outcome);
}
}
for event in arrow.arrow.as_mut().unwrap().events.drain(..) {
let a = arrow.arrow.as_mut().unwrap();
let (drop_at, dropped) = (arrow.position, a.pickup_item.count);
let raised = std::mem::take(&mut a.events);
let count = raised.len();
for (i, event) in raised.into_iter().map(Some).chain([None]).enumerate() {
if let Some((at, damage)) = hurt
&& at == i
{
events.push(format!("hurt {:08x}", damage.to_bits()));
}
let Some(event) = event else {
debug_assert_eq!(i, count);
break;
};
match event {
ArrowEvent::Particle {
kind,
@@ -191,9 +223,28 @@ fn main() -> Result<()> {
},
ArrowEvent::SplashEvent => events.push("splash-event".into()),
ArrowEvent::ShootEvent => events.push("shoot-event".into()),
ArrowEvent::Drop => events.push(format!(
"drop {} {dropped}",
bits(Vec3::new(
drop_at.x,
drop_at.y + f64::from(0.1f32),
drop_at.z
))
)),
}
}
}
"target" => {
// EntityDimensions.scalable(0.6, 1.8).makeBoundingBox.
let at = vector(&op["position"]);
let w = f64::from(0.6f32) / 2.0;
let h = f64::from(1.8f32);
let b = Aabb::new(
Vec3::new(at.x - w, at.y, at.z - w),
Vec3::new(at.x + w, at.y + h, at.z + w),
);
target = Some((b, op["takes"].as_bool().unwrap()));
}
"block" => {
let p = &op["position"];
let mut state = assets
+111 -18
View File
@@ -1,8 +1,9 @@
//! `AbstractArrow.tick` for arrows, tipped and spectral arrows: the flight with
//! its water inertia and bubbles, the base tick's fluids (currents, splash),
//! bubble columns and water along the path, sticking in blocks, falling out
//! when the block goes, and despawning. Entity hits and their effects stay
//! with the game (`projectile_hit`).
//! when the block goes, and despawning. The tick stops at an entity it hits:
//! the game hurts the entity (`projectile_hit`), then `finish_entity_hit`
//! spends the arrow or turns it back and ends the tick.
use crate::{
blocks::BlockFacts,
collisions::SceneCollisions,
@@ -113,6 +114,9 @@ pub enum ArrowEvent {
/// The SPLASH and PROJECTILE_SHOOT game events.
SplashEvent,
ShootEvent,
/// `spawnAtLocation(pickupItem, 0.1)`: a turned-back arrow too slow to fly
/// on drops what picking it up gives.
Drop,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArrowParticle {
@@ -124,7 +128,7 @@ pub enum ArrowParticle {
pub enum ArrowSound {
/// `entity.generic.splash` (an arrow's splash and high-speed splash).
Splash,
/// The arrow's hit-ground sound (`entity.arrow.hit`).
/// The arrow's `soundEvent` (`entity.arrow.hit`), for blocks and entities.
HitGround,
/// `entity.generic.extinguish_fire`.
Extinguish,
@@ -382,14 +386,17 @@ fn signum(v: f64) -> f64 {
v
}
}
/// One arrow tick: whether to keep it and what it hit.
/// One arrow tick: whether to keep it and what it hit. An arrow that hit an
/// entity stops there and is not kept: the game hands it to
/// `finish_entity_hit` once it has hurt the entity.
pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) -> (bool, Hit) {
let Some(mut st) = p.arrow.take() else {
return (false, Hit::None);
};
// Entity.setOldPosAndRot: the renderer interpolates from here, in flight
// and stuck alike.
// and stuck alike; ServerLevel.tickNonPassenger counts the tick.
p.previous = p.position;
p.age += 1;
let hit = Ticker {
p,
st: &mut st,
@@ -397,10 +404,44 @@ pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) ->
}
.tick(targets);
p.stuck = st.in_ground;
let keep = !st.removed;
let keep = !st.removed && !matches!(hit, Hit::Entity { .. });
p.arrow = Some(st);
(keep, hit)
}
/// What became of the entity an arrow hit (`AbstractArrow.onHitEntity`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntityHit {
/// `hurtOrSimulate` succeeded: the arrow is spent, with its hit sound.
Hurt,
/// It failed (a raised shield, invulnerability): the arrow turns back.
Refused,
/// The entity turned it first (`Entity.deflection`: breezes).
Deflected,
}
/// The rest of the tick of an arrow that hit an entity: whether to keep it.
pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: EntityHit) -> bool {
let Some(mut st) = p.arrow.take() else {
return false;
};
let mut ticker = Ticker {
p,
st: &mut st,
scene,
};
match outcome {
EntityHit::Hurt => {
ticker.hit_sound();
ticker.st.removed = true;
}
EntityHit::Refused => ticker.turn_back(),
EntityHit::Deflected => {}
}
ticker.finish();
p.stuck = st.in_ground;
let keep = !st.removed;
p.arrow = Some(st);
keep
}
struct Ticker<'p, 's, 'a, 'r> {
p: &'p mut Projectile,
st: &'s mut ArrowState,
@@ -517,10 +558,20 @@ impl Ticker<'_, '_, '_, '_> {
);
if physics {
hit = self.step_move_and_hit(original, end, targets);
if matches!(hit, Hit::Entity { .. }) {
return hit;
}
} else {
self.p.position = end;
self.apply_effects_from_blocks(original, end);
}
self.finish();
hit
}
/// The end of a tick in flight: drag and gravity, then `Projectile.tick`
/// and `Entity.baseTick`'s fluid and fire phases.
fn finish(&mut self) {
let physics = !self.st.no_physics;
if !self.st.was_touching_water {
self.p.velocity = self.p.velocity.scale(f64::from(0.99f32));
}
@@ -547,7 +598,6 @@ impl Ticker<'_, '_, '_, '_> {
self.st.removed = true;
}
self.st.first_tick = false;
hit
}
/// `getDeltaMovement().add(0, y, 0)`: the zeros added to x and z also
/// turn a negative zero positive.
@@ -589,16 +639,23 @@ impl Ticker<'_, '_, '_, '_> {
self.st.life = 0;
}
/// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the
/// block (not piercing: the game removes an arrow that hits an entity).
/// block (piercing is not modelled).
fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit {
let block = self.scene.clip(from, to);
let end = block.map_or(to, |b| b.0);
// findHitEntities: ProjectileUtil.computeMargin and the search box.
let margin = f64::from(((self.p.age as i32 - 2) as f32 / 20.0).clamp(0.0, 0.3));
let area = bounds(from)
.expand_towards(self.p.velocity)
.inflate(Vec3::new(1.0, 1.0, 1.0));
let mut best: Option<(Who, Vec3, f64)> = None;
for (who, b) in targets {
if Some(*who) == self.p.owner && !self.p.left_owner {
if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) {
continue;
}
if let Some(at) = b.inflate(Vec3::new(0.3, 0.3, 0.3)).clip(from, end) {
if let Some(at) = self.entity_hit(b, from, end, margin) {
// Sorted by the distance to the entity's position (the
// stable sort keeps the first of equals).
let c = b.center();
let d = from.distance_squared(Vec3::new(c.x, b.min_position().y, c.z));
if best.is_none_or(|bb| d < bb.2) {
@@ -610,8 +667,6 @@ impl Ticker<'_, '_, '_, '_> {
self.p.position = next;
self.apply_effects_from_blocks(from, next);
if let Some((who, at, _)) = best {
// The game hurts it; the arrow is spent (piercing is not modelled).
self.st.removed = true;
return Hit::Entity { who, at };
}
let Some((at, pos, face)) = block else {
@@ -631,6 +686,49 @@ impl Ticker<'_, '_, '_, '_> {
face,
}
}
/// `ProjectileUtil.getManyEntityHitResult` for one entity box: where the
/// path enters it, else where it enters the box grown by `margin`, if a
/// line from there towards the centre (stopped by blocks) reaches the box.
fn entity_hit(&self, b: &Aabb, from: Vec3, to: Vec3, margin: f64) -> Option<Vec3> {
if let Some(at) = b.clip(from, to) {
return Some(at);
}
if margin <= 0.0 {
return None;
}
let outside = b
.inflate(Vec3::new(margin, margin, margin))
.clip(from, to)?;
let centre = b.center();
let towards = self.scene.clip(outside, centre).map_or(centre, |h| h.0);
b.clip(outside, towards).map(|_| outside)
}
/// `playSound(soundEvent, 1, 1.2 / (random * 0.2 + 0.9))`.
fn hit_sound(&mut self) {
let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9);
self.st.events.push(ArrowEvent::Sound {
sound: ArrowSound::HitGround,
volume: 1.0,
pitch,
});
}
/// `onHitEntity` when the entity took no damage: `deflect(REVERSE, 0.2)`,
/// a half turn give or take ten degrees at a tenth of the speed; one
/// left almost still drops its pickup (ALLOWED) and is discarded.
fn turn_back(&mut self) {
let power = 0.2;
let rotation = 170.0 + self.st.random.next_float() * 20.0;
let v = self.p.velocity;
let k = -power * 0.5;
self.p.velocity = Vec3::new(v.x * k, v.y * k, v.z * k);
self.p.yaw += rotation;
if self.p.velocity.length_squared() < 1.0e-7 {
if self.st.pickup == Pickup::Allowed {
self.st.events.push(ArrowEvent::Drop);
}
self.st.removed = true;
}
}
/// `AbstractArrow.onHitBlock`: back off the face by 0.05 along each axis
/// it moved on, stop, and stick.
fn on_hit_block(&mut self, pos: BlockPos, state: BlockStateId) {
@@ -649,12 +747,7 @@ impl Ticker<'_, '_, '_, '_> {
self.p.position.z - signum(v.z) * offset,
);
self.p.velocity = Vec3::ZERO;
let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9);
self.st.events.push(ArrowEvent::Sound {
sound: ArrowSound::HitGround,
volume: 1.0,
pitch,
});
self.hit_sound();
self.st.in_ground = true;
self.st.shake = 7;
self.p.set_critical(false);
+91 -73
View File
@@ -5,6 +5,7 @@
use super::{Dim, Game, view_vector};
use horizon_client::{
Result,
arrows::EntityHit,
blocks::Fluid,
collisions::SceneCollisions,
items::ItemStack,
@@ -25,14 +26,16 @@ use horizon_core::{
use std::sync::Arc;
/// The world impact sound after successful arrow damage, including self-shots.
fn arrow_impact_sound(
random: &mut impl RandomSource,
hurt: bool,
) -> Option<(&'static str, f32, f32)> {
hurt.then(|| {
let pitch = 1.2 / (random.next_float() * 0.2 + 0.9);
("minecraft:entity.arrow.hit", 1.0, pitch)
})
/// `AbstractArrow.onHitEntity`'s damage: the crit bonus comes from the
/// arrow's own random.
fn arrow_damage(arrow: &mut Projectile, fallback: &mut impl RandomSource) -> f32 {
let mut state = arrow.arrow.take();
let damage = match state.as_mut() {
Some(a) => arrow.arrow_damage(&mut a.random),
None => arrow.arrow_damage(fallback),
};
arrow.arrow = state;
damage
}
/// Mob-system state owned by the game.
@@ -1528,20 +1531,8 @@ impl Game<'_> {
self.world.random.next_float()
};
let w = self.mob_world_base(&[]);
// Level.isRainingAt: raining, open to the sky (the biome's
// precipitation is not checked here).
let (raining, world) = (w.raining, w.world);
let rain = move |p: BlockPos| raining && world.light(p.x, p.y, p.z) >> 4 == 15;
let scene = horizon_client::arrows::ArrowScene {
world: w.world,
registry: w.registry,
facts: w.facts,
collision: w.collision,
fluids: &self.motion.fluids,
raining: &rain,
mob_griefing: self.ui.rules.bool("mob_griefing"),
tnt_explodes: self.ui.rules.bool("tnt_explodes"),
};
let rain = self.arrow_rain();
let scene = self.arrow_scene(&rain);
// Arrows also hit minecarts (VehicleEntity is pickable).
let mut arrow_targets = targets.clone();
arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds())));
@@ -1568,8 +1559,10 @@ impl Game<'_> {
&& breezes.contains(&id)
{
super::wind::reverse(p, jitter);
if let Some(a) = p.arrow.as_mut() {
a.removed = false;
if p.arrow.is_some() {
horizon_client::arrows::finish_entity_hit(p, &scene, EntityHit::Deflected);
let a = p.arrow.as_mut().expect("an arrow");
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
}
deflections.push([at.x, at.y, at.z]);
return true;
@@ -1680,7 +1673,53 @@ impl Game<'_> {
ArrowEvent::SplashEvent => {
self.projectile_event("minecraft:splash", None, [at.x, at.y, at.z]);
}
ArrowEvent::ShootEvent => {}
// finish_arrow_hit drops the pickup, which it holds.
ArrowEvent::ShootEvent | ArrowEvent::Drop => {}
}
}
/// `Level.isRainingAt` for arrows: raining, open to the sky (the biome's
/// precipitation is not checked here).
fn arrow_rain(&self) -> impl Fn(BlockPos) -> bool + '_ {
let raining = self.world.weather.levels(1.0).0 > 0.2;
move |p: BlockPos| raining && self.world.light(p.x, p.y, p.z) >> 4 == 15
}
/// The level as arrows see it.
fn arrow_scene<'s>(
&'s self,
rain: &'s dyn Fn(BlockPos) -> bool,
) -> horizon_client::arrows::ArrowScene<'s, 's> {
horizon_client::arrows::ArrowScene {
world: &self.world,
registry: self.res.assets.registry,
facts: &self.res.facts,
collision: self.collision,
fluids: &self.motion.fluids,
raining: rain,
mob_griefing: self.ui.rules.bool("mob_griefing"),
tnt_explodes: self.ui.rules.bool("tnt_explodes"),
}
}
/// The rest of the tick of an arrow that hit an entity
/// (`arrows::finish_entity_hit`): its sounds and drop, and back among the
/// projectiles if it flies on.
fn finish_arrow_hit(&mut self, mut arrow: Projectile, outcome: EntityHit) {
let keep = {
let rain = self.arrow_rain();
horizon_client::arrows::finish_entity_hit(&mut arrow, &self.arrow_scene(&rain), outcome)
};
let Some(a) = arrow.arrow.as_mut() else {
return;
};
let (events, item) = (std::mem::take(&mut a.events), a.pickup_item.clone());
for event in events {
if event == horizon_client::arrows::ArrowEvent::Drop {
self.spawn_at_location(arrow.position, f64::from(0.1f32), item.clone());
} else {
self.arrow_event(arrow.position, event);
}
}
if keep {
self.creatures.projectiles.push(arrow);
}
}
fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
@@ -1720,14 +1759,12 @@ impl Game<'_> {
&& let Some(i) = self.carts.iter().position(|c| c.id == id)
{
// AbstractArrow.onHitEntity on a minecart.
let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage;
let mut arrow = p.clone();
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire());
let creative = p.owner == Some(Who::Player) && self.creative;
self.arrow_hits_cart(i, amount, p.velocity, burning, creative);
if let Some((sound, volume, pitch)) = arrow_impact_sound(&mut self.world.random, true) {
self.audio
.play(sound, Some([at.x, at.y, at.z]), volume, pitch);
}
self.finish_arrow_hit(arrow, EntityHit::Hurt);
return Ok(());
}
let atp = [at.x, at.y, at.z];
@@ -1747,16 +1784,9 @@ impl Game<'_> {
};
match (&p.kind, hit) {
(ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => {
let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage;
// Punch pushes along the flight, Flame burns for five seconds.
let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt();
if p.bonus.punch > 0 && flight > 1e-6 {
let k = f64::from(p.bonus.punch) * 0.6 / flight;
self.handle_mob_events(vec![MobEvent::Push {
target: who,
velocity: [p.velocity.x * k, 0.1, p.velocity.z * k],
}])?;
}
let mut arrow = p.clone();
let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage;
let player_fire = self.player.as_ref().map(|pl| pl.fire_ticks);
// AbstractArrow.onHitEntity: a burning arrow sets its target alight.
if p.arrow.as_ref().is_some_and(|a| a.on_fire()) {
self.handle_mob_events(vec![MobEvent::Ignite {
@@ -1788,10 +1818,27 @@ impl Game<'_> {
hurt
}
};
if let Some((sound, volume, pitch)) =
arrow_impact_sound(&mut self.world.random, hurt)
{
self.audio.play(sound, Some(atp), volume, pitch);
// doKnockback: Punch pushes along the flight.
let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt();
if hurt && p.bonus.punch > 0 && flight > 1e-6 {
let k = f64::from(p.bonus.punch) * 0.6 / flight;
self.handle_mob_events(vec![MobEvent::Push {
target: who,
velocity: [p.velocity.x * k, 0.1, p.velocity.z * k],
}])?;
}
match (hurt, who) {
(true, _) => self.finish_arrow_hit(arrow, EntityHit::Hurt),
// What the player took no damage from (a raised shield)
// keeps its fire as it was and turns the arrow back.
(false, Who::Player) => {
if let (Some(pl), Some(ticks)) = (self.player.as_mut(), player_fire) {
pl.set_remaining_fire_ticks(ticks);
}
self.finish_arrow_hit(arrow, EntityHit::Refused);
}
// Mobs' refusals don't follow hurtServer yet: the arrow is gone.
(false, Who::Mob(_)) => {}
}
}
// AbstractArrow.onHitBlock plays its sound itself (ArrowEvent).
@@ -2945,32 +2992,3 @@ impl Game<'_> {
let _ = self.spawn_mob("minecraft:zombified_piglin", at, false);
}
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_core::random::LegacyRandom;
#[test]
fn arrow_impact_uses_world_sound_volume_and_seeded_pitch() {
let mut random = LegacyRandom::new(0);
assert_eq!(
arrow_impact_sound(&mut random, true),
Some((
"minecraft:entity.arrow.hit",
1.0,
f32::from_bits(0x3f92d167)
))
);
let mut expected = LegacyRandom::new(0);
expected.next_float();
assert_eq!(random.next_float(), expected.next_float());
}
#[test]
fn rejected_arrow_damage_is_silent_without_drawing_pitch() {
let mut random = LegacyRandom::new(0);
assert_eq!(arrow_impact_sound(&mut random, false), None);
assert_eq!(random.next_float(), LegacyRandom::new(0).next_float());
}
}
@@ -28,7 +28,9 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
* the path, water putting them out, and the blocks they light (TNT, campfires,
* candles). Pickup: the INTANGIBLE_PROJECTILE ammo the constructor sees, `setOwner`, and
* `playerTouch` by a player (creative or not, with room in the inventory or not).
* No entities to hit, no rain; sounds, particles and game events are recorded in order. */
* Entities: a box in the way that takes the arrow's damage or refuses it (`onHitEntity`'s
* REVERSE deflection). No rain; sounds, particles, game events, the damage dealt and
* dropped pickups are recorded in order. */
public final class VanillaArrowOracle {
static final class Border extends WorldBorder {
@Override public boolean isInsideCloseToBorder(Entity e,AABB b){return false;}
@@ -50,6 +52,22 @@ public final class VanillaArrowOracle {
@Override public net.minecraft.world.damagesource.DamageSource lava(){return any;}
@Override public net.minecraft.world.damagesource.DamageSource inFire(){return any;}
@Override public net.minecraft.world.damagesource.DamageSource onFire(){return any;}
@Override public net.minecraft.world.damagesource.DamageSource arrow(AbstractArrow arrow,Entity owner){return any;}
}
/** The entity in the way (allocated without a constructor): a box at a position that
* takes the arrow's damage or refuses it (a raised shield), recording what it was dealt. */
static final class Target extends Entity {
boolean takes;List<String> events;
Target(){super(null,null);}
@Override protected void defineSynchedData(net.minecraft.network.syncher.SynchedEntityData.Builder entityData){}
@Override protected void readAdditionalSaveData(net.minecraft.world.level.storage.ValueInput input){}
@Override protected void addAdditionalSaveData(net.minecraft.world.level.storage.ValueOutput output){}
@Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,net.minecraft.world.damagesource.DamageSource source,float damage){
events.add(String.format("hurt %08x",Float.floatToIntBits(damage)));return takes;
}
@Override public boolean isPickable(){return true;}
// Untagged: neither DEFLECTS_PROJECTILES nor REDIRECTABLE_PROJECTILE.
@Override public boolean is(net.minecraft.tags.TagKey<EntityType<?>> tag){return false;}
}
static final class Level extends net.minecraft.server.level.ServerLevel {
Map<Long,Chunk> chunks;WorldBorder border;net.minecraft.util.RandomSource rng;List<String> events;net.minecraft.server.MinecraftServer server;
@@ -64,13 +82,16 @@ public final class VanillaArrowOracle {
@Override public BlockState getBlockState(BlockPos p){var c=chunks.get(key(p.getX()>>4,p.getZ()>>4));return c==null?Blocks.AIR.defaultBlockState():c.getBlockState(p);}
@Override public FluidState getFluidState(BlockPos p){return getBlockState(p).getFluidState();}
@Override public List<VoxelShape> getEntityCollisions(Entity e,AABB b){return List.of();}
@Override public List<Entity> getEntities(Entity e,AABB b,java.util.function.Predicate<? super Entity> p){return List.of();}
Target target;
@Override public List<Entity> getEntities(Entity e,AABB b,java.util.function.Predicate<? super Entity> p){
return target!=null&&target.getBoundingBox().intersects(b)&&p.test(target)?List.of(target):List.of();
}
@Override public WorldBorder getWorldBorder(){return border;}
@Override public net.minecraft.util.RandomSource getRandom(){return rng;}
@Override public boolean isRainingAt(BlockPos p){return false;}
@Override public net.minecraft.server.MinecraftServer getServer(){return server;}
@Override public void gameEvent(Holder<GameEvent> event,Vec3 pos,GameEvent.Context context){
if(event==GameEvent.PROJECTILE_SHOOT)events.add("shoot-event");else if(event==GameEvent.SPLASH)events.add("splash-event");else throw new AssertionError(event);
if(event==GameEvent.PROJECTILE_SHOOT)events.add("shoot-event");else if(event==GameEvent.SPLASH)events.add("splash-event");else if(event!=GameEvent.PROJECTILE_LAND)throw new AssertionError(event);
}
// Projectile.onHit's PROJECTILE_LAND: the game posts it from the hit it is handed.
@Override public void gameEvent(Holder<GameEvent> event,BlockPos pos,GameEvent.Context context){
@@ -84,6 +105,8 @@ public final class VanillaArrowOracle {
chunks.get(key(p.getX()>>4,p.getZ()>>4)).write(p,Block.getId(state));events.add("write "+p.getX()+","+p.getY()+","+p.getZ()+" "+Block.getId(state)+" "+flags);return true;
}
@Override public boolean addFreshEntity(Entity e){
// spawnAtLocation's item (its motion comes from the item's own unseeded random).
if(e instanceof net.minecraft.world.entity.item.ItemEntity item){events.add("drop "+bits(item.position())+" "+item.getItem().getCount());return true;}
if(!(e instanceof net.minecraft.world.entity.item.PrimedTnt tnt))throw new AssertionError(e);
events.add("spawn tnt "+bits(tnt.position())+" "+tnt.getFuse());return true;
}
@@ -154,7 +177,7 @@ public final class VanillaArrowOracle {
// The client's recreateFromPacket snaps a spawned arrow, old position included.
a.setOldPosAndRot();
a.setCritArrow(row.get("crit").getAsBoolean());a.setNoPhysics(row.get("no_physics").getAsBoolean());
String touched="-";
String touched="-";level.target=null;
for(var value:row.getAsJsonArray("ops")){
var op=value.getAsJsonObject();
switch(op.get("mode").getAsString()){
@@ -178,6 +201,14 @@ public final class VanillaArrowOracle {
};
a.setOwner(owner);a.setOwner((Entity)null);
}
// A player-sized box standing at the position.
case "target"->{
var t=(Target)allocate.invoke(unsafe,Target.class);t.takes=op.get("takes").getAsBoolean();t.events=level.events;
var at=VanillaSceneCollisionOracle.vector(op.get("position"));
field(Entity.class,"level").set(t,level);field(Entity.class,"position").set(t,at);
field(Entity.class,"bb").set(t,EntityDimensions.scalable(0.6F,1.8F).makeBoundingBox(at));
level.target=t;
}
// ArrowItem.asProjectile (dispensers) sets pickup directly.
case "pickup"->a.pickup=AbstractArrow.Pickup.byOrdinal(op.get("value").getAsInt());
case "touch"->{
+26 -1
View File
@@ -20,9 +20,14 @@ burning and non-burning arrows; pickup: arrows from no one, a player or a mob,
from intangible ammo (creative, Infinity, multishot extras) or a dispenser,
touched in flight, while shaking and when stuck, by survival and creative
players with empty, partly and fully filled inventories, and without physics.
No entities to hit, no rain.
Entities: a player-sized box in the way that takes the arrow's damage (the
arrow is spent with its hit sound) or refuses it (a raised shield: the arrow
turns back, and drops its pickup when left almost still), struck squarely or
grazed within ProjectileUtil's margin, crits drawing from the arrow's random.
No rain.
"""
import json
import math
import os
from pathlib import Path
import platform
@@ -181,6 +186,26 @@ def corpus():
for creative in [False, True]:
ops = ([op('owner', owner)] if owner else []) + [o for _ in range(4) for o in (op('tick'), touch(creative, 'empty'))]
yield arrow((rng.uniform(18, 30), 6, rng.uniform(4, 30)), aim(.4, rng.uniform(-180, 180), 0), ops, no_physics=True)
# An entity in the way (a player-sized box on the floor) that takes or
# refuses the damage: squarely, grazing within the margin (older arrows),
# missing, and slow enough to drop on the spot.
def target(x, z, takes):
return op('target', position=vec((x, 4, z)), takes=takes)
for takes in [True, False]:
for _ in range(24):
tx, tz = rng.uniform(21, 27), rng.uniform(21, 27)
yaw, distance = rng.uniform(-180, 180), rng.uniform(1.5, 9)
start = (tx + math.sin(math.radians(yaw)) * distance, rng.uniform(4.2, 7.5), tz - math.cos(math.radians(yaw)) * distance)
aim_at = (tx + rng.uniform(-.75, .75), rng.uniform(4, 6.2), tz + rng.uniform(-.75, .75))
d = [aim_at[i] - start[i] for i in range(3)]
speed = rng.choice([.4, 1.1, 2.2, 3]) / math.sqrt(sum(c * c for c in d))
yield arrow(start, [c * speed for c in d], [target(tx, tz, takes)] + ticks(45), crit=rng.random() < .5)
for pickup in [0, 1]:
for speed in [.002, .03, .2]:
# Struck in the first tick; the slowest, turned back at a
# tenth of its speed, is left almost still and stops.
ops = [op('pickup', pickup), target(25.5, 25.5, takes)] + ticks(6)
yield arrow((25.199, 4.5, 25.5), (speed, 0, 0), ops)
# Despawning 1200 ticks after sticking in the floor.
for _ in range(2):
yield arrow((rng.uniform(18, 30), 6, rng.uniform(4, 30)), (0, -1, 0), ticks(1215))