Arrows can be picked up (#119)
Players could never pick up arrows: arrows had no pickup rule and no item, nothing checked a player touching them, and arrows from saves were loaded into a separate list that never ticked. Arrows now carry AbstractArrow's pickup rule and pickupItemStack. The player's bow and crossbow give them the drawn ammo (ProjectileWeaponItem .useAmmo: creative, Infinity and multishot's extra arrows draw intangible ammo, so those arrows are CREATIVE_ONLY), setOwner(player) turns DISALLOWED into ALLOWED, dispensers make them ALLOWED, mobs' stay DISALLOWED. Each tick the player touches the arrows in its box grown by (1, 0.5, 1) (Player.aiStep): a stuck arrow that has stopped shaking goes into the inventory (ALLOWED), or just goes for a creative player (CREATIVE_ONLY, or ALLOWED with a full inventory), with the item pickup sound at the arrow. Saved arrows load as live arrows (life, shake, inGround, inBlockState, pickup, item, fire) and live arrows are saved, so stuck arrows survive a reload and despawn on time; the legacy never-ticked arrow list is gone, and /kill, /tp and /data reach the live arrows. The arrow harness adds who shot the arrow, intangible ammo and dispensers' ALLOWED, then touches in flight, while shaking and when stuck by survival and creative players with empty, partly and fully filled inventories, against the real setOwner and playerTouch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,10 +3,14 @@
|
||||
#![forbid(unsafe_code)]
|
||||
use horizon_client::{
|
||||
Result,
|
||||
arrows::{self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction},
|
||||
arrows::{
|
||||
self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, Pickup, Touch,
|
||||
},
|
||||
assets::Assets,
|
||||
blocks::BlockFacts,
|
||||
collisions,
|
||||
items::ItemStack,
|
||||
mobs::Who,
|
||||
motion::{LAVA, MotionResources, WATER},
|
||||
projectiles::{Projectile, ProjectileKind},
|
||||
world::World,
|
||||
@@ -80,8 +84,14 @@ fn main() -> Result<()> {
|
||||
.with_arrow_random(LegacyRandom::new(seed(&f["seed"])));
|
||||
arrow.velocity = vector(&f["velocity"]);
|
||||
arrow.arrow.as_mut().unwrap().no_physics = f["no_physics"].as_bool().unwrap();
|
||||
// ProjectileWeaponItem.useAmmo's stack, intangible when no ammo was used.
|
||||
arrow.arrow.as_mut().unwrap().set_item(&arrows::drawn_ammo(
|
||||
&ItemStack::new("minecraft:arrow", 1),
|
||||
f["intangible"].as_bool().unwrap(),
|
||||
));
|
||||
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" => {
|
||||
if !arrow.arrow.as_ref().unwrap().removed {
|
||||
@@ -218,6 +228,35 @@ fn main() -> Result<()> {
|
||||
u32::from_str_radix(op["value"].as_str().unwrap(), 16).unwrap(),
|
||||
)),
|
||||
"level_seed" => level_random.set_seed(seed(&op["value"])),
|
||||
"owner" => arrow
|
||||
.arrow
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.set_owner(match op["value"].as_str() {
|
||||
Some("player") => Some(Who::Player),
|
||||
Some("mob") => Some(Who::Mob(1)),
|
||||
_ => None,
|
||||
}),
|
||||
"pickup" => {
|
||||
arrow.arrow.as_mut().unwrap().pickup =
|
||||
Pickup::from_byte(op["value"].as_i64().unwrap())
|
||||
}
|
||||
// The game's touch: the inventory takes the arrow unless full,
|
||||
// and a creative player takes it anyway.
|
||||
"touch" => {
|
||||
let creative = op["creative"].as_bool().unwrap();
|
||||
let full = op["inventory"] == "full";
|
||||
let a = arrow.arrow.as_mut().unwrap();
|
||||
let (taken, arrows) = match a.player_touch(creative) {
|
||||
Touch::Ignore => (false, 0),
|
||||
Touch::Take => (true, 0),
|
||||
Touch::Give(_) => (!full || creative, u32::from(!full)),
|
||||
};
|
||||
if taken {
|
||||
a.removed = true;
|
||||
}
|
||||
touched = format!("{taken} {arrows}");
|
||||
}
|
||||
other => return Err(format!("unknown operation {other}").into()),
|
||||
}
|
||||
let a = arrow.arrow.as_ref().unwrap();
|
||||
@@ -244,6 +283,13 @@ fn main() -> Result<()> {
|
||||
a.fall_distance.to_bits()
|
||||
)?;
|
||||
writeln!(out, "events {}", events.join(" | "))?;
|
||||
let a = arrow.arrow.as_ref().unwrap();
|
||||
let intangible = a
|
||||
.pickup_item
|
||||
.data()
|
||||
.and_then(|d| d.other(arrows::INTANGIBLE))
|
||||
.is_some();
|
||||
writeln!(out, "pickup {} {intangible} {touched}", a.pickup.byte())?;
|
||||
}
|
||||
writeln!(out, "end")?;
|
||||
}
|
||||
|
||||
@@ -43,6 +43,47 @@ pub enum Pickup {
|
||||
Allowed,
|
||||
CreativeOnly,
|
||||
}
|
||||
impl Pickup {
|
||||
/// The saved `pickup` byte (`LEGACY_CODEC`: the ordinal, out of range is
|
||||
/// DISALLOWED).
|
||||
pub fn from_byte(b: i64) -> Self {
|
||||
match b {
|
||||
1 => Self::Allowed,
|
||||
2 => Self::CreativeOnly,
|
||||
_ => Self::Disallowed,
|
||||
}
|
||||
}
|
||||
pub fn byte(self) -> i8 {
|
||||
self as i8
|
||||
}
|
||||
}
|
||||
/// `DataComponents.INTANGIBLE_PROJECTILE`.
|
||||
pub const INTANGIBLE: &str = "minecraft:intangible_projectile";
|
||||
/// `ProjectileWeaponItem.useAmmo`'s drawn stack: one of the ammo, marked
|
||||
/// intangible when no ammo was used (creative, Infinity, multishot extras).
|
||||
pub fn drawn_ammo(ammo: &crate::items::ItemStack, intangible: bool) -> crate::items::ItemStack {
|
||||
let mut drawn = crate::items::ItemStack {
|
||||
count: 1,
|
||||
..ammo.clone()
|
||||
};
|
||||
if intangible {
|
||||
drawn.data_mut().set_other(
|
||||
INTANGIBLE,
|
||||
Some(horizon_world::nbt::Tag::Compound(Default::default())),
|
||||
);
|
||||
}
|
||||
drawn
|
||||
}
|
||||
/// What `AbstractArrow.playerTouch` does for a player touching the arrow.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Touch {
|
||||
/// Not stuck yet, still shaking, or not the player's to take.
|
||||
Ignore,
|
||||
/// ALLOWED: taken if the inventory takes this stack whole.
|
||||
Give(crate::items::ItemStack),
|
||||
/// CREATIVE_ONLY in creative: taken without an item.
|
||||
Take,
|
||||
}
|
||||
/// What an arrow's tick asks the game to play or show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ArrowEvent {
|
||||
@@ -108,6 +149,8 @@ pub struct ArrowState {
|
||||
/// The block it stuck in (`lastState`).
|
||||
pub last_state: Option<BlockStateId>,
|
||||
pub pickup: Pickup,
|
||||
/// `pickupItemStack`: what picking the arrow up gives.
|
||||
pub pickup_item: crate::items::ItemStack,
|
||||
pub no_physics: bool,
|
||||
pub pierce: u8,
|
||||
/// `Entity.remainingFireTicks`.
|
||||
@@ -149,6 +192,7 @@ impl ArrowState {
|
||||
shake: 0,
|
||||
last_state: None,
|
||||
pickup: Pickup::Disallowed,
|
||||
pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1),
|
||||
no_physics: false,
|
||||
pierce: 0,
|
||||
fire_ticks: 0,
|
||||
@@ -163,6 +207,36 @@ impl ArrowState {
|
||||
events: Vec::new(),
|
||||
}
|
||||
}
|
||||
/// The `AbstractArrow` constructor's `pickupItemStack`: the drawn ammo
|
||||
/// (one item). Ammo drawn without being used up (`INTANGIBLE_PROJECTILE`)
|
||||
/// makes the arrow CREATIVE_ONLY; vanilla takes the component off the
|
||||
/// stack it was given, not its copy, so the item keeps it.
|
||||
pub fn set_item(&mut self, item: &crate::items::ItemStack) {
|
||||
self.pickup_item = item.clone();
|
||||
if item.data().and_then(|d| d.other(INTANGIBLE)).is_some() {
|
||||
self.pickup = Pickup::CreativeOnly;
|
||||
}
|
||||
}
|
||||
/// `AbstractArrow.setOwner`: a player's arrows may be picked up.
|
||||
pub fn set_owner(&mut self, owner: Option<Who>) {
|
||||
if owner == Some(Who::Player) && self.pickup == Pickup::Disallowed {
|
||||
self.pickup = Pickup::Allowed;
|
||||
}
|
||||
}
|
||||
/// `AbstractArrow.playerTouch` and `tryPickup` (`creative`:
|
||||
/// `Player.hasInfiniteMaterials`). Like vanilla it does not look at
|
||||
/// removal: players only touch arrows still in the world.
|
||||
pub fn player_touch(&self, creative: bool) -> Touch {
|
||||
if !(self.in_ground || self.no_physics) || self.shake > 0 {
|
||||
return Touch::Ignore;
|
||||
}
|
||||
match self.pickup {
|
||||
Pickup::Disallowed => Touch::Ignore,
|
||||
Pickup::Allowed => Touch::Give(self.pickup_item.clone()),
|
||||
Pickup::CreativeOnly if creative => Touch::Take,
|
||||
Pickup::CreativeOnly => Touch::Ignore,
|
||||
}
|
||||
}
|
||||
/// `Entity.isOnFire` (arrows are not fire immune).
|
||||
pub fn on_fire(&self) -> bool {
|
||||
self.fire_ticks > 0
|
||||
|
||||
@@ -110,80 +110,6 @@ impl ItemEntity {
|
||||
self.age < 6000 && self.position.y > -128.0
|
||||
}
|
||||
}
|
||||
/// Arrows (`AbstractArrow.tick`): 0.99 drag, 0.05 gravity, sticking in blocks.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Arrow {
|
||||
/// Shot by the player (hits mobs) rather than a mob (hits the player).
|
||||
pub from_player: bool,
|
||||
pub critical: bool,
|
||||
pub position: Vec3,
|
||||
pub previous: Vec3,
|
||||
pub velocity: Vec3,
|
||||
pub stuck: bool,
|
||||
pub age: u32,
|
||||
pub base_damage: f64,
|
||||
}
|
||||
pub enum ArrowHit {
|
||||
None,
|
||||
Player(f32),
|
||||
}
|
||||
impl Arrow {
|
||||
pub fn tick(
|
||||
&mut self,
|
||||
world: &World,
|
||||
facts: &BlockFacts,
|
||||
player: Option<Aabb>,
|
||||
) -> (bool, ArrowHit) {
|
||||
self.previous = self.position;
|
||||
self.age += 1;
|
||||
if self.stuck {
|
||||
return (self.age < 1200, ArrowHit::None);
|
||||
}
|
||||
let steps = 4;
|
||||
for _ in 0..steps {
|
||||
let next = Vec3::new(
|
||||
self.position.x + self.velocity.x / f64::from(steps),
|
||||
self.position.y + self.velocity.y / f64::from(steps),
|
||||
self.position.z + self.velocity.z / f64::from(steps),
|
||||
);
|
||||
if let Some(b) = player {
|
||||
let (min, max) = (b.min_position(), b.max_position());
|
||||
if next.x >= min.x
|
||||
&& next.x <= max.x
|
||||
&& next.y >= min.y
|
||||
&& next.y <= max.y
|
||||
&& next.z >= min.z
|
||||
&& next.z <= max.z
|
||||
{
|
||||
let speed = (self.velocity.x.powi(2)
|
||||
+ self.velocity.y.powi(2)
|
||||
+ self.velocity.z.powi(2))
|
||||
.sqrt();
|
||||
// AbstractArrow.onHitEntity: ceil(speed * baseDamage).
|
||||
let damage = (speed * self.base_damage).ceil().max(0.0) as f32;
|
||||
return (false, ArrowHit::Player(damage));
|
||||
}
|
||||
}
|
||||
let block = world.block(
|
||||
next.x.floor() as i32,
|
||||
next.y.floor() as i32,
|
||||
next.z.floor() as i32,
|
||||
);
|
||||
if facts.get(block).full_collision {
|
||||
self.stuck = true;
|
||||
self.age = 0;
|
||||
return (true, ArrowHit::None);
|
||||
}
|
||||
self.position = next;
|
||||
}
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * 0.99,
|
||||
self.velocity.y * 0.99 - 0.05,
|
||||
self.velocity.z * 0.99,
|
||||
);
|
||||
(self.position.y > -128.0 && self.age < 1200, ArrowHit::None)
|
||||
}
|
||||
}
|
||||
/// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ExperienceOrb {
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
//! Horizon does not model (variants, attributes, equipment, custom names)
|
||||
//! survive a Horizon save.
|
||||
use crate::{
|
||||
entities::{ArmorStand, Arrow, ExperienceOrb, ItemEntity, ItemFrame, Painting},
|
||||
mobs::{Mob, MobType},
|
||||
arrows::Pickup,
|
||||
entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting},
|
||||
mobs::{Mob, MobType, Who},
|
||||
projectiles::{Projectile, ProjectileKind},
|
||||
save::{
|
||||
doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text,
|
||||
uuid_from_tag,
|
||||
@@ -907,68 +909,102 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
|
||||
vec![orb; count]
|
||||
}
|
||||
|
||||
/// `AbstractArrow`: damage, crit, inGround, life, pickup, item.
|
||||
pub fn arrow_to_nbt(a: &Arrow, uuid: [i32; 4], owner: Option<[i32; 4]>) -> Tag {
|
||||
let v = a.velocity;
|
||||
let horizontal = (v.x * v.x + v.z * v.z).sqrt();
|
||||
let rotation = [
|
||||
(v.x.atan2(v.z).to_degrees()) as f32,
|
||||
(v.y.atan2(horizontal).to_degrees()) as f32,
|
||||
];
|
||||
/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow;
|
||||
/// `in_block` is its `inBlockState`, `raw` the compound it was loaded with.
|
||||
pub fn arrow_to_nbt(
|
||||
p: &Projectile,
|
||||
uuid: [i32; 4],
|
||||
owner: Option<[i32; 4]>,
|
||||
in_block: Option<Tag>,
|
||||
raw: Option<&Tag>,
|
||||
) -> Option<Tag> {
|
||||
let a = p.arrow.as_deref()?;
|
||||
let ProjectileKind::Arrow {
|
||||
base_damage,
|
||||
critical,
|
||||
..
|
||||
} = p.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let base = Base {
|
||||
id: "minecraft:arrow",
|
||||
uuid,
|
||||
position: a.position,
|
||||
motion: a.velocity,
|
||||
rotation,
|
||||
position: p.position,
|
||||
motion: p.velocity,
|
||||
rotation: [p.yaw, p.pitch],
|
||||
on_ground: false,
|
||||
fall_distance: 0.0,
|
||||
fall_distance: a.fall_distance,
|
||||
};
|
||||
let mut tag = base.tag(None);
|
||||
let mut tag = base.tag(raw);
|
||||
for (key, value) in [
|
||||
("damage", Tag::Double(a.base_damage.to_bits())),
|
||||
("crit", Tag::Byte(i8::from(a.critical))),
|
||||
("inGround", Tag::Byte(i8::from(a.stuck))),
|
||||
(
|
||||
"life",
|
||||
Tag::Short(if a.stuck { a.age.min(1200) as i16 } else { 0 }),
|
||||
),
|
||||
// Pickup: allowed for the player's arrows, disallowed for mobs'.
|
||||
("pickup", Tag::Byte(i8::from(a.from_player))),
|
||||
("shake", Tag::Byte(0)),
|
||||
("PierceLevel", Tag::Byte(0)),
|
||||
("HasBeenShot", Tag::Byte(1)),
|
||||
("SoundEvent", string("minecraft:entity.arrow.hit")),
|
||||
(
|
||||
"item",
|
||||
Tag::compound([("id", string("minecraft:arrow")), ("count", Tag::Int(1))]),
|
||||
),
|
||||
("Fire", Tag::Short(a.fire_ticks as i16)),
|
||||
("life", Tag::Short(a.life as i16)),
|
||||
("shake", Tag::Byte(a.shake as i8)),
|
||||
("inGround", Tag::Byte(i8::from(a.in_ground))),
|
||||
("pickup", Tag::Byte(a.pickup.byte())),
|
||||
("damage", Tag::Double(base_damage.to_bits())),
|
||||
("crit", Tag::Byte(i8::from(critical))),
|
||||
("PierceLevel", Tag::Byte(a.pierce as i8)),
|
||||
("HasBeenShot", Tag::Byte(i8::from(a.has_been_shot))),
|
||||
("item", item_to_nbt(&a.pickup_item)),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
if let Tag::Compound(map) = &mut tag {
|
||||
map.entry("SoundEvent".into())
|
||||
.or_insert_with(|| string("minecraft:entity.arrow.hit"));
|
||||
// Projectile: LeftOwner only when set; Owner as the UUID.
|
||||
map.remove(&"LeftOwner".into());
|
||||
map.remove(&"inBlockState".into());
|
||||
}
|
||||
if p.left_owner {
|
||||
put(&mut tag, "LeftOwner", Tag::Byte(1));
|
||||
}
|
||||
if let Some(state) = in_block {
|
||||
put(&mut tag, "inBlockState", state);
|
||||
}
|
||||
if let Some(owner) = owner {
|
||||
put(&mut tag, "Owner", Tag::IntArray(owner.to_vec()));
|
||||
}
|
||||
tag
|
||||
Some(tag)
|
||||
}
|
||||
pub fn arrow_from_nbt(tag: &Tag, player: Option<[i32; 4]>) -> Option<Arrow> {
|
||||
/// A saved arrow as a live one (`readAdditionalSaveData`), with its
|
||||
/// `inBlockState` compound for the caller to resolve. `effect` is the tipped
|
||||
/// arrow's lasting effect from its item.
|
||||
pub fn arrow_from_nbt(
|
||||
tag: &Tag,
|
||||
player: Option<[i32; 4]>,
|
||||
effect: impl FnOnce(&crate::items::ItemStack) -> Option<(&'static str, i32)>,
|
||||
) -> Option<(Projectile, Option<Tag>)> {
|
||||
let position = position(tag)?;
|
||||
let stuck = flag(tag, "inGround");
|
||||
Some(Arrow {
|
||||
from_player: player.is_some() && uuid_from_tag(tag.get("Owner")) == player
|
||||
|| number(tag.get("pickup")) == Some(1),
|
||||
critical: flag(tag, "crit"),
|
||||
position,
|
||||
previous: position,
|
||||
velocity: motion(tag),
|
||||
stuck,
|
||||
age: if stuck {
|
||||
number(tag.get("life")).unwrap_or(0).max(0) as u32
|
||||
} else {
|
||||
0
|
||||
},
|
||||
let owner = uuid_from_tag(tag.get("Owner"));
|
||||
let from_player = player.is_some() && owner == player;
|
||||
let item = tag
|
||||
.get("item")
|
||||
.and_then(item_from_nbt)
|
||||
.unwrap_or_else(|| crate::items::ItemStack::new("minecraft:arrow", 1));
|
||||
let kind = ProjectileKind::Arrow {
|
||||
base_damage: float(tag.get("damage")).unwrap_or(2.0),
|
||||
})
|
||||
critical: flag(tag, "crit"),
|
||||
effect: effect(&item),
|
||||
};
|
||||
let mut p = Projectile::new(kind, position, from_player.then_some(Who::Player));
|
||||
p.velocity = motion(tag);
|
||||
[p.yaw, p.pitch] = rotation(tag);
|
||||
p.left_owner = flag(tag, "LeftOwner");
|
||||
let a = p.arrow.as_mut()?;
|
||||
a.life = number(tag.get("life")).unwrap_or(0) as i16 as i32;
|
||||
a.shake = (number(tag.get("shake")).unwrap_or(0) as i8 as u8).into();
|
||||
a.in_ground = flag(tag, "inGround");
|
||||
a.pickup = Pickup::from_byte(number(tag.get("pickup")).unwrap_or(0));
|
||||
a.pierce = number(tag.get("PierceLevel")).unwrap_or(0) as u8;
|
||||
a.has_been_shot = flag(tag, "HasBeenShot");
|
||||
a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i16 as i32;
|
||||
a.fall_distance = float(tag.get("fall_distance")).unwrap_or(0.0);
|
||||
a.pickup_item = item;
|
||||
p.stuck = a.in_ground;
|
||||
Some((p, tag.get("inBlockState").cloned()))
|
||||
}
|
||||
|
||||
/// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities.
|
||||
|
||||
@@ -130,7 +130,7 @@ use horizon_client::{
|
||||
containers::{BlockEntity, Providers},
|
||||
crafting::Recipes,
|
||||
creative::{Creative, Names},
|
||||
entities::{Arrow, Experience, ExperienceOrb, ItemEntity},
|
||||
entities::{Experience, ExperienceOrb, ItemEntity},
|
||||
environment::Environment,
|
||||
gfx::{Frame, Renderer},
|
||||
hud::{HudAtlas, HudBatch, rgba},
|
||||
@@ -732,7 +732,6 @@ struct Game<'a> {
|
||||
/// A new player's spawn search, while its candidates' chunks load.
|
||||
player_spawn: Option<horizon_client::world_spawn::PlayerSpawnFinder>,
|
||||
mobs: Vec<Mob>,
|
||||
arrows: Vec<Arrow>,
|
||||
creatures: creatures::Creatures,
|
||||
sculk: sculk::SculkState,
|
||||
raiding: raids::Raiding,
|
||||
@@ -3063,6 +3062,7 @@ impl Game<'_> {
|
||||
if running {
|
||||
horizon_client::spans::time("entity_portals", || self.handle_entity_portals());
|
||||
horizon_client::spans::time("tick_items", || self.tick_items());
|
||||
horizon_client::spans::time("touch_arrows", || self.touch_arrows());
|
||||
}
|
||||
horizon_client::spans::time("spawn_loaded_entities", || self.spawn_loaded_entities());
|
||||
if running {
|
||||
@@ -4784,56 +4784,6 @@ impl Game<'_> {
|
||||
self.guest_model_geometry(camera, alpha, &mut out);
|
||||
self.fangs_geometry(camera, alpha, &mut out);
|
||||
self.name_tag_geometry(camera, alpha, &mut out);
|
||||
// Arrows: two crossed quads along the flight direction.
|
||||
if let Some(r) = self
|
||||
.res
|
||||
.atlas
|
||||
.sprites
|
||||
.get("entity/projectiles/arrow")
|
||||
.copied()
|
||||
{
|
||||
for a in &self.arrows {
|
||||
let p = glam::DVec3::new(
|
||||
a.previous.x + (a.position.x - a.previous.x) * alpha,
|
||||
a.previous.y + (a.position.y - a.previous.y) * alpha,
|
||||
a.previous.z + (a.position.z - a.previous.z) * alpha,
|
||||
) - camera;
|
||||
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 side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08;
|
||||
let up = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08;
|
||||
let c = p.as_vec3();
|
||||
let (u1, v1) = (
|
||||
r.u0 + (r.u1 - r.u0) * 0.5,
|
||||
r.v0 + (r.v1 - r.v0) * (5.0 / 32.0),
|
||||
);
|
||||
for off in [side, up] {
|
||||
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: 240 | 240 << 8,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Entity shadows (EntityRenderer.extractShadow).
|
||||
if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() {
|
||||
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
|
||||
@@ -5759,7 +5709,7 @@ impl Game<'_> {
|
||||
self.mobs.clear();
|
||||
self.creatures.reset_trader();
|
||||
self.portals = Default::default();
|
||||
self.arrows.clear();
|
||||
self.creatures.projectiles.clear();
|
||||
self.dropped.clear();
|
||||
self.particles.clear();
|
||||
self.orbs.clear();
|
||||
@@ -5910,7 +5860,7 @@ impl Game<'_> {
|
||||
self.falling.clear();
|
||||
self.tnts.clear();
|
||||
self.mobs.clear();
|
||||
self.arrows.clear();
|
||||
self.creatures.projectiles.clear();
|
||||
self.dropped.clear();
|
||||
self.particles.clear();
|
||||
self.orbs.clear();
|
||||
@@ -6060,7 +6010,7 @@ impl Game<'_> {
|
||||
self.world = World::new(self.res.facts.air, 0);
|
||||
self.player = None;
|
||||
self.mobs.clear();
|
||||
self.arrows.clear();
|
||||
self.creatures.projectiles.clear();
|
||||
self.dropped.clear();
|
||||
self.particles.clear();
|
||||
self.screen = Screen::Playing;
|
||||
@@ -6830,6 +6780,19 @@ impl Game<'_> {
|
||||
p,
|
||||
Some(horizon_client::mobs::Who::Player),
|
||||
);
|
||||
// ProjectileWeaponItem.useAmmo: creative and Infinity draw without
|
||||
// using the ammo, so the arrow is CREATIVE_ONLY; else setOwner(player)
|
||||
// lets it be picked up.
|
||||
let ammo = arrow_slot
|
||||
.and_then(|i| self.inventory[i].clone())
|
||||
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
|
||||
if let Some(a) = arrow.arrow.as_mut() {
|
||||
a.set_item(&horizon_client::arrows::drawn_ammo(
|
||||
&ammo,
|
||||
self.creative || infinity,
|
||||
));
|
||||
a.set_owner(Some(horizon_client::mobs::Who::Player));
|
||||
}
|
||||
// Flame: the arrow is spawned burning (EnchantmentHelper.onProjectileSpawned).
|
||||
if let Some(seconds) = self.bow_projectile_ignite()
|
||||
&& let Some(a) = arrow.arrow.as_mut()
|
||||
@@ -9119,7 +9082,6 @@ pub fn run() -> Result<()> {
|
||||
spawn_spiral: Default::default(),
|
||||
player_spawn: None,
|
||||
mobs: Vec::new(),
|
||||
arrows: Vec::new(),
|
||||
creatures: Default::default(),
|
||||
sculk: Default::default(),
|
||||
raiding: Default::default(),
|
||||
|
||||
@@ -228,7 +228,8 @@ impl Game<'_> {
|
||||
.get(i)
|
||||
.map(|o| [o.position.x, o.position.y, o.position.z]),
|
||||
Target::Arrow(i) => self
|
||||
.arrows
|
||||
.creatures
|
||||
.projectiles
|
||||
.get(i)
|
||||
.map(|a| [a.position.x, a.position.y, a.position.z]),
|
||||
Target::Stand(id) => self
|
||||
@@ -392,7 +393,14 @@ impl Game<'_> {
|
||||
);
|
||||
candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
|
||||
candidates.extend((0..self.orbs.len()).map(Target::Orb));
|
||||
candidates.extend((0..self.arrows.len()).map(Target::Arrow));
|
||||
candidates.extend(
|
||||
self.creatures
|
||||
.projectiles
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, p)| p.arrow.is_some())
|
||||
.map(|(i, _)| Target::Arrow(i)),
|
||||
);
|
||||
candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
|
||||
candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
|
||||
candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
|
||||
@@ -960,7 +968,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Target::Arrow(i) => {
|
||||
if let Some(a) = self.arrows.get_mut(i) {
|
||||
if let Some(a) = self.creatures.projectiles.get_mut(i) {
|
||||
a.position = v;
|
||||
a.previous = v;
|
||||
}
|
||||
@@ -1294,8 +1302,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Target::Arrow(i) => {
|
||||
if i < self.arrows.len() {
|
||||
self.arrows[i].age = u32::MAX / 2;
|
||||
if let Some(a) = self
|
||||
.creatures
|
||||
.projectiles
|
||||
.get_mut(i)
|
||||
.and_then(|p| p.arrow.as_mut())
|
||||
{
|
||||
a.removed = true;
|
||||
}
|
||||
}
|
||||
Target::Stand(id) => self.armor_stands.retain(|a| a.id != id),
|
||||
@@ -1325,7 +1338,9 @@ impl Game<'_> {
|
||||
self.kill_target(t);
|
||||
}
|
||||
self.orbs.retain(|o| o.age < u32::MAX / 2);
|
||||
self.arrows.retain(|a| a.age < u32::MAX / 2);
|
||||
self.creatures
|
||||
.projectiles
|
||||
.retain(|p| !p.arrow.as_ref().is_some_and(|a| a.removed));
|
||||
let message = if targets.len() == 1 {
|
||||
Text::translate("commands.kill.success.single", &[names[0].clone()])
|
||||
} else {
|
||||
|
||||
@@ -109,9 +109,18 @@ impl Game<'_> {
|
||||
}
|
||||
Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()),
|
||||
Target::Arrow(i) => {
|
||||
let a = self.arrows.get(i)?;
|
||||
let owner = if a.from_player { player_uuid } else { None };
|
||||
entity_nbt::arrow_to_nbt(a, random_uuid(), owner)
|
||||
let p = self.creatures.projectiles.get(i)?;
|
||||
let owner = if p.owner == Some(horizon_client::mobs::Who::Player) {
|
||||
player_uuid
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let in_block = p
|
||||
.arrow
|
||||
.as_ref()
|
||||
.and_then(|a| a.last_state)
|
||||
.map(|s| self.state_to_nbt(s));
|
||||
entity_nbt::arrow_to_nbt(p, random_uuid(), owner, in_block, None)?
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1408,6 +1408,63 @@ impl Game<'_> {
|
||||
let _ = player.hurt(&self.motion.health, self.world.health_rules, id, amount);
|
||||
}
|
||||
}
|
||||
/// `Player.aiStep` touching arrows in its box grown by (1, 0.5, 1):
|
||||
/// `AbstractArrow.playerTouch`, then `Player.take`'s pickup sound at the
|
||||
/// arrow (`ClientPacketListener.handleTakeItemEntity`).
|
||||
pub(super) fn touch_arrows(&mut self) {
|
||||
use horizon_client::arrows::Touch;
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
if p.health.dead_or_dying() || self.spectator() {
|
||||
return;
|
||||
}
|
||||
let w = f64::from(p.dimensions.width) / 2.0;
|
||||
let reach = Aabb::new(
|
||||
Vec3::new(p.position.x - w, p.position.y, p.position.z - w),
|
||||
Vec3::new(
|
||||
p.position.x + w,
|
||||
p.position.y + f64::from(p.dimensions.height),
|
||||
p.position.z + w,
|
||||
),
|
||||
)
|
||||
.inflate(Vec3::new(1.0, 0.5, 1.0));
|
||||
// Player.hasInfiniteMaterials.
|
||||
let creative = self.creative;
|
||||
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
|
||||
projectiles.retain(|shot| {
|
||||
let Some(a) = shot.arrow.as_ref().filter(|a| !a.removed) else {
|
||||
return true;
|
||||
};
|
||||
let at = shot.position;
|
||||
let bounds = Aabb::new(
|
||||
Vec3::new(at.x - 0.25, at.y, at.z - 0.25),
|
||||
Vec3::new(at.x + 0.25, at.y + 0.5, at.z + 0.25),
|
||||
);
|
||||
if !bounds.intersects(reach) {
|
||||
return true;
|
||||
}
|
||||
let taken = match a.player_touch(creative) {
|
||||
Touch::Ignore => false,
|
||||
Touch::Take => true,
|
||||
// Inventory.add: a creative player takes what does not fit.
|
||||
Touch::Give(stack) => self.give(stack).is_none() || creative,
|
||||
};
|
||||
if taken {
|
||||
let r = &mut self.world.random;
|
||||
let pitch = (r.next_float() - r.next_float()) * 1.4 + 2.0;
|
||||
self.audio.play(
|
||||
"minecraft:entity.item.pickup",
|
||||
Some([at.x, at.y, at.z]),
|
||||
0.2,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
!taken
|
||||
});
|
||||
self.creatures.projectiles = projectiles;
|
||||
}
|
||||
|
||||
fn tick_projectiles(&mut self) -> Result<()> {
|
||||
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
|
||||
let mut hits = Vec::new();
|
||||
|
||||
@@ -88,8 +88,12 @@ impl Game<'_> {
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let slot_ammo = self.arrow_slot();
|
||||
let ammo = slot_ammo
|
||||
.and_then(|i| self.inventory[i].clone())
|
||||
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
|
||||
if !self.creative {
|
||||
let Some(i) = self.arrow_slot() else { return };
|
||||
let Some(i) = slot_ammo else { return };
|
||||
if let Some(s) = self.inventory[i].as_mut() {
|
||||
s.count -= 1;
|
||||
if s.count == 0 {
|
||||
@@ -97,8 +101,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// useAmmo: the extra multishot arrows and creative's are intangible.
|
||||
let drawn = (0..shots)
|
||||
.map(|i| horizon_client::arrows::drawn_ammo(&ammo, self.creative || i > 0))
|
||||
.collect();
|
||||
if let Some(bow) = self.inventory[slot].as_mut() {
|
||||
bow.data_mut().charged = vec![ItemStack::new("minecraft:arrow", 1); shots];
|
||||
bow.data_mut().charged = drawn;
|
||||
}
|
||||
let pitch = 1.0 / (self.world.random.next_float() * 0.5 + 1.0) + 0.2;
|
||||
self.audio.play(sounds[2], at, 1.0, pitch);
|
||||
@@ -119,7 +127,7 @@ impl Game<'_> {
|
||||
let spread = if count > 1 { 10.0 } else { 0.0 };
|
||||
let view = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
|
||||
let up = glam::DVec3::from_array(view_vector(self.yaw, self.pitch - 90.0));
|
||||
for (index, _) in charged.iter().enumerate() {
|
||||
for (index, ammo) in charged.iter().enumerate() {
|
||||
let angle = if count > 1 {
|
||||
-spread + 2.0 * spread * index as f64 / (count - 1) as f64
|
||||
} else {
|
||||
@@ -142,6 +150,10 @@ impl Game<'_> {
|
||||
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
|
||||
Some(Who::Player),
|
||||
);
|
||||
if let Some(a) = arrow.arrow.as_mut() {
|
||||
a.set_item(ammo);
|
||||
a.set_owner(Some(Who::Player));
|
||||
}
|
||||
arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0);
|
||||
self.creatures.projectiles.push(arrow);
|
||||
self.player_projectile_shot();
|
||||
|
||||
@@ -967,18 +967,7 @@ impl Game<'_> {
|
||||
"minecraft:tipped_arrow" => ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: false,
|
||||
effect: stack
|
||||
.potion()
|
||||
.and_then(horizon_client::brewing::potion)
|
||||
.and_then(|def| {
|
||||
def.effects
|
||||
.iter()
|
||||
.find(|(id, _, _)| {
|
||||
!horizon_client::brewing::effect(id)
|
||||
.is_some_and(|e| e.instant)
|
||||
})
|
||||
.map(|(id, duration, _)| (*id, (duration / 8).max(1)))
|
||||
}),
|
||||
effect: tipped_effect(&stack),
|
||||
},
|
||||
"minecraft:fire_charge" | "minecraft:wind_charge" => {
|
||||
// asProjectile aims with the level's random first; the
|
||||
@@ -1001,6 +990,12 @@ impl Game<'_> {
|
||||
_ => ProjectileKind::Snowball,
|
||||
};
|
||||
let mut shot = Projectile::new(kind, at, None);
|
||||
// ArrowItem/SpectralArrowItem.asProjectile: dispensed arrows
|
||||
// may be picked up.
|
||||
if let Some(a) = shot.arrow.as_mut() {
|
||||
a.set_item(&one);
|
||||
a.pickup = horizon_client::arrows::Pickup::Allowed;
|
||||
}
|
||||
shot.shoot(&mut own, dir, power, uncertainty);
|
||||
self.creatures.projectiles.push(shot);
|
||||
}
|
||||
@@ -2135,3 +2130,16 @@ impl Game<'_> {
|
||||
))
|
||||
}
|
||||
}
|
||||
/// A tipped arrow's lasting effect at an eighth of the potion's duration
|
||||
/// (`Arrow.doPostHurtEffects`).
|
||||
pub(super) fn tipped_effect(stack: &ItemStack) -> Option<(&'static str, i32)> {
|
||||
stack
|
||||
.potion()
|
||||
.and_then(horizon_client::brewing::potion)
|
||||
.and_then(|def| {
|
||||
def.effects
|
||||
.iter()
|
||||
.find(|(id, _, _)| !horizon_client::brewing::effect(id).is_some_and(|e| e.instant))
|
||||
.map(|(id, duration, _)| (*id, (duration / 8).max(1)))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use horizon_client::{
|
||||
Result,
|
||||
chunk::Chunk,
|
||||
entity_nbt,
|
||||
mobs::Who,
|
||||
save::{ChunkExtras, random_uuid},
|
||||
};
|
||||
use horizon_core::{geometry::Vec3, position::ChunkPos, random::RandomSource, ticks::ChunkTicks};
|
||||
@@ -186,8 +187,15 @@ impl Game<'_> {
|
||||
}
|
||||
"minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)),
|
||||
"minecraft:arrow" => {
|
||||
if let Some(a) = entity_nbt::arrow_from_nbt(&tag, player_uuid) {
|
||||
self.arrows.push(a);
|
||||
if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt(
|
||||
&tag,
|
||||
player_uuid,
|
||||
super::dispenser::tipped_effect,
|
||||
) {
|
||||
if let Some(a) = p.arrow.as_mut() {
|
||||
a.last_state = in_block.and_then(|t| self.state_from_nbt(&t));
|
||||
}
|
||||
self.creatures.projectiles.push(p);
|
||||
}
|
||||
}
|
||||
"minecraft:falling_block" => {
|
||||
@@ -517,7 +525,7 @@ impl Game<'_> {
|
||||
.id(&state)
|
||||
.or_else(|| registry.default_state(&state.name))
|
||||
}
|
||||
fn state_to_nbt(&self, state: BlockStateId) -> Tag {
|
||||
pub(in crate::game) fn state_to_nbt(&self, state: BlockStateId) -> Tag {
|
||||
let registry = self.res.assets.registry;
|
||||
match registry.state(state) {
|
||||
Some(s) if registry.default_state(&s.name) == Some(state) => {
|
||||
@@ -579,14 +587,23 @@ impl Game<'_> {
|
||||
.push(with_raw(entity_nbt::orb_to_nbt(o, uuid), raw.as_ref()));
|
||||
}
|
||||
}
|
||||
for a in &self.arrows {
|
||||
if keys.contains(&chunk_of(a.position)) {
|
||||
let owner = if a.from_player { player_uuid } else { None };
|
||||
let (uuid, raw) = anon(&self.persist, "minecraft:arrow", a.position);
|
||||
out.entry(chunk_of(a.position)).or_default().push(with_raw(
|
||||
entity_nbt::arrow_to_nbt(a, uuid, owner),
|
||||
raw.as_ref(),
|
||||
));
|
||||
for p in &self.creatures.projectiles {
|
||||
if !keys.contains(&chunk_of(p.position)) {
|
||||
continue;
|
||||
}
|
||||
let owner = if p.owner == Some(Who::Player) {
|
||||
player_uuid
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (uuid, raw) = anon(&self.persist, "minecraft:arrow", p.position);
|
||||
let in_block = p
|
||||
.arrow
|
||||
.as_ref()
|
||||
.and_then(|a| a.last_state)
|
||||
.map(|s| self.state_to_nbt(s));
|
||||
if let Some(tag) = entity_nbt::arrow_to_nbt(p, uuid, owner, in_block, raw.as_ref()) {
|
||||
out.entry(chunk_of(p.position)).or_default().push(tag);
|
||||
}
|
||||
}
|
||||
for f in &self.falling {
|
||||
@@ -796,7 +813,9 @@ impl Game<'_> {
|
||||
keep
|
||||
});
|
||||
self.orbs.retain(|o| !gone(o.position));
|
||||
self.arrows.retain(|a| !gone(a.position));
|
||||
self.creatures
|
||||
.projectiles
|
||||
.retain(|p| p.arrow.is_none() || !gone(p.position));
|
||||
self.falling.retain(|f| !gone(f.position));
|
||||
self.persist
|
||||
.anon
|
||||
|
||||
@@ -182,7 +182,7 @@ impl Game<'_> {
|
||||
self.player = None;
|
||||
self.spawn = None;
|
||||
self.mobs.clear();
|
||||
self.arrows.clear();
|
||||
self.creatures.projectiles.clear();
|
||||
self.dropped.clear();
|
||||
self.particles.clear();
|
||||
self.orbs.clear();
|
||||
|
||||
@@ -346,11 +346,6 @@ impl Game<'_> {
|
||||
push(p.position, &mut p.velocity, self);
|
||||
}
|
||||
self.creatures.projectiles = projectiles;
|
||||
let mut arrows = std::mem::take(&mut self.arrows);
|
||||
for a in arrows.iter_mut().filter(|a| !a.stuck) {
|
||||
push(a.position, &mut a.velocity, self);
|
||||
}
|
||||
self.arrows = arrows;
|
||||
let mut tnts = std::mem::take(&mut self.tnts);
|
||||
for t in &mut tnts {
|
||||
push(t.position, &mut t.velocity, self);
|
||||
|
||||
@@ -26,7 +26,9 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
|
||||
* and bubbles, fluid currents and splashes, bubble columns, sticking in blocks,
|
||||
* falling out when the block goes, and despawning. Burning arrows: lava and fire along
|
||||
* the path, water putting them out, and the blocks they light (TNT, campfires,
|
||||
* candles). No entities to hit, no rain, no owner; sounds, particles and game events are recorded in order. */
|
||||
* 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. */
|
||||
public final class VanillaArrowOracle {
|
||||
static final class Border extends WorldBorder {
|
||||
@Override public boolean isInsideCloseToBorder(Entity e,AABB b){return false;}
|
||||
@@ -96,6 +98,23 @@ public final class VanillaArrowOracle {
|
||||
events.add("sent "+particle(p)+" "+bits(new Vec3(x,y,z))+" "+bits(new Vec3(dx,dy,dz))+String.format(" %016x",Double.doubleToLongBits(speed)));return 0;
|
||||
}
|
||||
}
|
||||
/** A player for `setOwner` and `playerTouch`: a real inventory and abilities,
|
||||
* and `take` (the pickup packet) recorded. */
|
||||
static final class Toucher extends net.minecraft.server.level.ServerPlayer{
|
||||
boolean took;
|
||||
Toucher(){super(null,null,null,null);}
|
||||
@Override public void take(Entity entity,int count){took=true;}
|
||||
}
|
||||
static Toucher toucher(Object unsafe,Method allocate,boolean creative,String inventory)throws Exception{
|
||||
var player=(Toucher)allocate.invoke(unsafe,Toucher.class);
|
||||
var abilities=new net.minecraft.world.entity.player.Abilities();abilities.instabuild=creative;
|
||||
field(net.minecraft.world.entity.player.Player.class,"abilities").set(player,abilities);
|
||||
var items=new net.minecraft.world.entity.player.Inventory(player,new EntityEquipment());
|
||||
field(net.minecraft.world.entity.player.Player.class,"inventory").set(player,items);
|
||||
int filled=switch(inventory){case "full"->36;case "partial"->35;default->0;};
|
||||
for(int i=0;i<filled;i++)items.setItem(i,new ItemStack(Items.STONE));
|
||||
return player;
|
||||
}
|
||||
static Field field(Class<?> c,String n)throws Exception{var f=c.getDeclaredField(n);f.setAccessible(true);return f;}
|
||||
static long seed(JsonElement v){return Long.parseLong(v.getAsString());}
|
||||
public static void main(String[] args)throws Exception{
|
||||
@@ -107,6 +126,7 @@ public final class VanillaArrowOracle {
|
||||
net.minecraft.tags.FluidTags.LAVA,List.<Holder<net.minecraft.world.level.material.Fluid>>of(net.minecraft.world.level.material.Fluids.FLOWING_LAVA.builtInRegistryHolder(),net.minecraft.world.level.material.Fluids.LAVA.builtInRegistryHolder())))).apply();
|
||||
// The arrow's pickup stack: an arrow item without data components.
|
||||
Items.ARROW.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY);
|
||||
Items.STONE.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY);
|
||||
var u=Class.forName("sun.misc.Unsafe");var f=u.getDeclaredField("theUnsafe");f.setAccessible(true);var unsafe=f.get(null);var allocate=u.getMethod("allocateInstance",Class.class);
|
||||
var description=JsonParser.parseString(Files.readString(dir.resolve("scene.json"))).getAsJsonObject();
|
||||
var trace=new Trace();trace.out=new PrintWriter(OutputStream.nullOutputStream());trace.fail=-1;
|
||||
@@ -125,10 +145,14 @@ public final class VanillaArrowOracle {
|
||||
try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var lines=Files.lines(dir.resolve("inputs.txt"))){
|
||||
for(var line:(Iterable<String>)lines::iterator){
|
||||
var row=JsonParser.parseString(line).getAsJsonObject();
|
||||
var a=new Arrow(level,0,0,0,new ItemStack(Items.ARROW),null);
|
||||
// ProjectileWeaponItem.useAmmo's stack: intangible when no ammo was used.
|
||||
var ammo=new ItemStack(Items.ARROW);
|
||||
if(row.get("intangible").getAsBoolean())ammo.set(net.minecraft.core.component.DataComponents.INTANGIBLE_PROJECTILE,net.minecraft.util.Unit.INSTANCE);
|
||||
var a=new Arrow(level,0,0,0,ammo,null);
|
||||
random.set(a,net.minecraft.util.RandomSource.create(seed(row.get("seed"))));
|
||||
a.setPos(VanillaSceneCollisionOracle.vector(row.get("position")));a.setDeltaMovement(VanillaSceneCollisionOracle.vector(row.get("velocity")));
|
||||
a.setCritArrow(row.get("crit").getAsBoolean());a.setNoPhysics(row.get("no_physics").getAsBoolean());
|
||||
String touched="-";
|
||||
for(var value:row.getAsJsonArray("ops")){
|
||||
var op=value.getAsJsonObject();
|
||||
switch(op.get("mode").getAsString()){
|
||||
@@ -143,6 +167,23 @@ public final class VanillaArrowOracle {
|
||||
// Flame's projectile_spawned ignite.
|
||||
case "ignite"->a.igniteForSeconds(Float.intBitsToFloat(Integer.parseUnsignedInt(op.get("value").getAsString(),16)));
|
||||
case "level_seed"->level.rng.setSeed(seed(op.get("value")));
|
||||
// setOwner(owner) for the pickup rule, then no owner for the flight.
|
||||
case "owner"->{
|
||||
Entity owner=switch(op.get("value").getAsString()){
|
||||
case "player"->toucher(unsafe,allocate,false,"empty");
|
||||
case "mob"->(Entity)allocate.invoke(unsafe,net.minecraft.world.entity.monster.zombie.Zombie.class);
|
||||
default->null;
|
||||
};
|
||||
a.setOwner(owner);a.setOwner((Entity)null);
|
||||
}
|
||||
// ArrowItem.asProjectile (dispensers) sets pickup directly.
|
||||
case "pickup"->a.pickup=AbstractArrow.Pickup.byOrdinal(op.get("value").getAsInt());
|
||||
case "touch"->{
|
||||
var player=toucher(unsafe,allocate,op.get("creative").getAsBoolean(),op.get("inventory").getAsString());
|
||||
a.playerTouch(player);
|
||||
int arrows=0;for(int i=0;i<36;i++)if(player.getInventory().getItem(i).getItem()==Items.ARROW)arrows+=player.getInventory().getItem(i).getCount();
|
||||
touched=player.took+" "+arrows;
|
||||
}
|
||||
default->throw new AssertionError(op);
|
||||
}
|
||||
var state=(BlockState)lastState.get(a);
|
||||
@@ -150,6 +191,7 @@ public final class VanillaArrowOracle {
|
||||
inGround.invoke(a),inGroundTime.getInt(a),life.getInt(a),a.shakeTime,state==null?"none":Block.getId(state),a.getRemainingFireTicks(),touching.getBoolean(a),eyes.getBoolean(a),first.getBoolean(a),
|
||||
Double.doubleToLongBits(a.getFluidHeight(net.minecraft.tags.FluidTags.WATER)),Double.doubleToLongBits(a.getFluidHeight(net.minecraft.tags.FluidTags.LAVA)),a.isRemoved(),a.isCritArrow(),Double.doubleToLongBits(a.fallDistance));
|
||||
out.println("events "+String.join(" | ",level.events));level.events.clear();
|
||||
out.printf("pickup %d %s %s%n",a.pickup.ordinal(),a.getPickupItemStackOrigin().has(net.minecraft.core.component.DataComponents.INTANGIBLE_PROJECTILE),touched);touched="-";
|
||||
}
|
||||
out.println("end");
|
||||
}
|
||||
|
||||
@@ -7,14 +7,19 @@ scene (`VanillaArrowOracle`, client and server jars); Horizon's
|
||||
operation prints the arrow's position, motion, rotation, ground state, life,
|
||||
shake, stuck block, fire ticks, water flags, fluid heights, removal, crit flag
|
||||
and fall distance by exact bits, then its sounds, particles and game events in
|
||||
order. Cases: flights in the air with and without crits or physics, into and
|
||||
order, then its pickup rule, whether its item is intangible and what a player
|
||||
touching it took. Cases: flights in the air with and without crits or physics, into and
|
||||
through water (inertia, bubbles, splashes, currents of flowing water, eyes),
|
||||
kelp, seagrass and waterlogged blocks, bubble columns with and without drag
|
||||
and with air or water above, sticking in full and partial blocks, falling out
|
||||
when the block goes, starting inside a block, and despawning after 1200 ticks;
|
||||
burning arrows: lava and fire blocks lighting them, water putting them out,
|
||||
Flame (ignited at spawn), and TNT, campfires, candles and candle cakes hit by
|
||||
burning and non-burning arrows. No entities, owner or rain.
|
||||
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.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
@@ -42,9 +47,9 @@ def corpus():
|
||||
return [op('block', name='minecraft:' + name, position=list(p), **({'properties': properties} if properties else {})) for p in positions]
|
||||
def restore(positions):
|
||||
return [op('block', name='minecraft:air', position=list(p)) for p in positions]
|
||||
def arrow(position, velocity, ops, crit=False, no_physics=False):
|
||||
def arrow(position, velocity, ops, crit=False, no_physics=False, intangible=False):
|
||||
return dict(seed=str(rng.randrange(-1 << 63, 1 << 63)), position=vec(position), velocity=vec(velocity),
|
||||
crit=crit, no_physics=no_physics, ops=[op('level_seed', str(rng.randrange(1 << 48)))] + ops)
|
||||
crit=crit, no_physics=no_physics, intangible=intangible, ops=[op('level_seed', str(rng.randrange(1 << 48)))] + ops)
|
||||
ticks = lambda n: [op('tick') for _ in range(n)]
|
||||
def aim(speed, yaw, pitch):
|
||||
import math
|
||||
@@ -153,6 +158,28 @@ def corpus():
|
||||
start = (25.5 - v[0] * 3, 9.3 - v[1] * 3, 25.5 - v[2] * 3)
|
||||
ops = ([ignite(rng.choice([1.0, 8.5, 100.0]))] if burning else []) + place(name, target, properties) + ticks(30) + restore(target)
|
||||
yield arrow(start, v, ops)
|
||||
# Pickup: who shot it (setOwner), intangible ammo, dispensers' ALLOWED,
|
||||
# then touches in flight, while shaking and once stuck.
|
||||
def touch(creative, inventory):
|
||||
return op('touch', creative=creative, inventory=inventory)
|
||||
sources = [(None, False, None), ('player', False, None), ('mob', False, None), ('player', True, None),
|
||||
(None, True, None), (None, False, 1), ('mob', False, 2), ('player', False, 2), ('none', False, 0)]
|
||||
for owner, intangible, pickup in sources:
|
||||
for creative in [False, True]:
|
||||
for inventory in ['empty', 'partial', 'full']:
|
||||
start = (rng.uniform(18, 30), rng.uniform(5.5, 7), rng.uniform(4, 30))
|
||||
v = aim(rng.choice([.3, .8, 1.5]), rng.uniform(-180, 180), rng.uniform(30, 89))
|
||||
ops = ([op('owner', owner)] if owner else []) + ([op('pickup', pickup)] if pickup is not None else [])
|
||||
ops += [touch(creative, inventory)] + ticks(1)
|
||||
# Until it sticks, touching every tick (shake 7 counts down).
|
||||
ops += [o for _ in range(14) for o in (op('tick'), touch(creative, inventory))]
|
||||
ops += ticks(3) + [touch(creative, inventory), touch(not creative, inventory)] + ticks(2)
|
||||
yield arrow(start, v, ops, crit=rng.random() < .3, intangible=intangible)
|
||||
# Without physics: touched in flight.
|
||||
for owner in [None, 'player']:
|
||||
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)
|
||||
# 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))
|
||||
@@ -185,7 +212,7 @@ def main():
|
||||
'-d', classes, oracle, *helpers], 'compile-java')
|
||||
fixtures = list(corpus())
|
||||
operations = sum(len(f['ops']) for f in fixtures)
|
||||
expected = 2 * operations + len(fixtures)
|
||||
expected = 3 * operations + len(fixtures)
|
||||
(build / 'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures))
|
||||
input_hash = lab.digest(build / 'inputs.txt', 'sha256')
|
||||
run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'arrow_probe'], 'compile-rust')
|
||||
@@ -206,7 +233,7 @@ def main():
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
if resource_hash != client.resource_fingerprint(resources) or input_hash != lab.digest(build / 'inputs.txt', 'sha256'):
|
||||
raise AssertionError('Arrow inputs changed during verification')
|
||||
lab.write_json(report, {'schema': 1, 'minecraft': lock['minecraft']['version'], 'manifest_sha1': lock['minecraft']['manifest_sha1'],
|
||||
lab.write_json(report, {'schema': 2, 'minecraft': lock['minecraft']['version'], 'manifest_sha1': lock['minecraft']['manifest_sha1'],
|
||||
'platform': platform.platform(), 'rustc': subprocess.check_output(['rustc', '--version'], text=True).strip(),
|
||||
'java': subprocess.check_output(['java', '--version'], text=True).splitlines()[0], 'fixtures': len(fixtures),
|
||||
'operations': operations, 'sources_sha256': tested, 'resources': resource_hash, 'input_sha256': input_hash,
|
||||
|
||||
Reference in New Issue
Block a user