Merge origin/main into feat/fox-states

This commit is contained in:
Kacpherek
2026-10-26 23:02:27 +01:00
128 changed files with 8191 additions and 668 deletions
+1
View File
@@ -144,6 +144,7 @@ jobs:
with:
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
# Horizon never downloads the game. These jobs need a self-hosted Linux runner
# (label horizon-game) holding the maintainer's own copy: the official launcher's
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
+41 -60
View File
@@ -13,6 +13,13 @@ on:
description: The commit to check out and test
type: string
required: true
full:
description: >-
The pull request carries the full-parity label (a change every harness reaches, such as a crate split): it
runs on the desktop's runner only, so the Mac mini's runners stay free for the others. While the desktop is
in use the job waits for it.
type: boolean
default: false
permissions:
contents: read
env:
@@ -21,40 +28,53 @@ env:
jobs:
parity:
runs-on: [self-hosted, horizon-game]
timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini
runs-on: ${{ inputs.full && fromJSON('["self-hosted", "horizon-game", "ludodesktop"]') || fromJSON('["self-hosted", "horizon-game"]') }}
# A change to core crates reruns ~350 harnesses: ~60-90 min on the Mac mini, ~35 min on the desktop, longer if
# someone comes back to the desktop meanwhile (the job then goes on with 2 threads).
timeout-minutes: ${{ inputs.full && 300 || 120 }}
steps:
- uses: actions/checkout@v4
with:
# The commit the event names: a fork's later pushes need another run-parity label.
# The commit the event names: a fork's later pushes need another run-parity label. The next step merges
# main into it.
ref: ${{ inputs.head }}
fetch-depth: 0
persist-credentials: false
# Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs.
clean: false
- name: The head merged into main (what merging it would land)
id: merge
env:
BASE_SHA: ${{ inputs.base }}
HEAD_SHA: ${{ inputs.head }}
run: |
# Harness fixes and game fixes that reached main since the branch was made then apply here too: a head
# tested alone failed harnesses already fixed on main (server_knockback before #2114, mob_ai's heap before
# #2270, save_roundtrip before #2212). Selection then compares with this main, so it sees only the pull
# request's own changes. A head that conflicts with main is tested alone.
set -euo pipefail
git merge --abort 2>/dev/null || true
git fetch -q --no-tags origin +refs/heads/main:refs/remotes/origin/main
main=$(git rev-parse origin/main)
if git -c user.name=parity -c user.email=parity@localhost merge -q --no-edit --no-ff "$main" >/dev/null 2>&1; then
echo "base=$main" >> "$GITHUB_OUTPUT"
echo "Tested: head ${HEAD_SHA:0:9} merged into main ${main:0:9}" | tee -a "$GITHUB_STEP_SUMMARY"
else
git merge --abort
echo "base=$BASE_SHA" >> "$GITHUB_OUTPUT"
echo "::warning::head ${HEAD_SHA:0:9} conflicts with main ${main:0:9}: tested alone, without main's fixes"
echo "Tested: head ${HEAD_SHA:0:9} alone (it conflicts with main ${main:0:9})" | tee -a "$GITHUB_STEP_SUMMARY"
fi
- uses: dtolnay/rust-toolchain@stable
- name: Tools from the runner
run: bash tools/ci/runner-env.sh
- name: Vanilla data, and resources prepared by this preparer
env:
BASE_SHA: ${{ inputs.base }}
run: |
# main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on
# the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own.
set -euo pipefail
if git rev-parse --verify -q origin/main >/dev/null \
&& git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then
git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh"
bash "$RUNNER_TEMP/vanilla-data.sh"
else
bash tools/ci/vanilla-data.sh
fi
run: bash tools/ci/vanilla-data.sh
- name: The prepared output is the one the preparer's OUTPUT_VERSION says
env:
BASE_SHA: ${{ inputs.base }}
BASE_SHA: ${{ steps.merge.outputs.base }}
run: |
# The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither
# the tool nor the number, so there is nothing to check.
# A head made before OUTPUT_VERSION (#1947) that conflicts with main has neither the tool nor the number.
if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then
echo "This head's preparer has no OUTPUT_VERSION: nothing to check"
exit 0
@@ -65,47 +85,8 @@ jobs:
- name: The harnesses this change can affect
env:
PARITY_HOSTS: ''
BASE_SHA: ${{ inputs.base }}
run: |
# main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a
# branch made before a better selection landed gets it too; the head's own runner then runs those
# harnesses. A branch that changes the selection itself selects with its own code.
set -euo pipefail
own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner
fork_point=$(git merge-base "$BASE_SHA" HEAD)
if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then
own
exit
fi
had_reach=$(git ls-files tools/parity_reach.py)
git show origin/main:tools/parity.py > tools/parity.py
git show origin/main:tools/parity_reach.py > tools/parity_reach.py
status=0
python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$?
git checkout -- tools/parity.py
if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi
cat .local/parity-selection.txt
if [ "$status" != 0 ]; then
echo "main's selection failed: the head's own selection runs"
own
exit
fi
names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true)
# The summary line says how many would run: a count that doesn't match the names read (a format change)
# must not let the job pass untested.
expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p')
count=$(printf '%s' "$names" | grep -c . || true)
if [ -z "$expected" ] || [ "$expected" != "$count" ]; then
echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs"
own
exit
fi
if [ "$count" = 0 ]; then
echo "Nothing to run."
exit 0
fi
# shellcheck disable=SC2086
python3 tools/parity.py $names --timeout 2400
BASE_SHA: ${{ steps.merge.outputs.base }}
run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v4
+1
View File
@@ -22,3 +22,4 @@ jobs:
with:
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
Generated
+14
View File
@@ -216,6 +216,13 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "beacons"
version = "0.1.0"
dependencies = [
"horizon-mod-sdk",
]
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -2971,6 +2978,13 @@ dependencies = [
"objc2-quartz-core 0.3.2",
]
[[package]]
name = "recipes"
version = "1.0.0"
dependencies = [
"horizon-mod-sdk",
]
[[package]]
name = "redox_syscall"
version = "0.4.1"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "crates/horizon-mod-sdk/examples/beacons", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask", "mods/official/recipes"]
resolver = "2"
[workspace.package]
+9
View File
@@ -266,8 +266,17 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
format!("{} quiet command(s)", lines.len())
}
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
Output::SetBlocks {
dimension, blocks, ..
} => {
format!("set {} block(s) in {dimension}", blocks.len())
}
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
Output::PlaceRecipe { book_id, all } => {
format!("placed recipe {book_id}{}", if all { " (all)" } else { "" })
}
Output::Give { item, count, .. } => format!("gave {count} {item}"),
Output::Shake { strength, seconds } => {
format!("shook the camera: {strength:.2} for {seconds:.1} s")
}
@@ -1057,6 +1057,7 @@ pub fn main() -> horizon_client::Result<()> {
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
effects: Vec::new(),
uuid: PLAYER_UUID,
allies: Default::default(),
remote: false,
@@ -164,6 +164,8 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
.iter()
.filter_map(|e| match e {
MotionEvent::Fall(e) => Some(e.trace()),
// The oracle's player wears no armor; the game applies this one.
MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt { .. }) => None,
MotionEvent::Health(e) => Some(e.trace()),
MotionEvent::Snowflake { position, velocity } => Some(format!(
"snowflake {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}",
+55 -3
View File
@@ -156,7 +156,11 @@ pub struct ArrowState {
/// `pickupItemStack`: what picking the arrow up gives.
pub pickup_item: crate::items::ItemStack,
pub no_physics: bool,
/// `AbstractArrow.getPierceLevel`.
pub pierce: u8,
/// `piercingIgnoreEntityIds`: the entities a piercing arrow has gone
/// through (cleared when it sticks in a block).
pub pierced: Vec<Who>,
/// `Entity.remainingFireTicks`.
pub fire_ticks: i32,
pub fall_distance: f64,
@@ -199,6 +203,7 @@ impl ArrowState {
pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1),
no_physics: false,
pierce: 0,
pierced: Vec::new(),
fire_ticks: 0,
fall_distance: 0.0,
fluids: EntityFluidInteraction::new([WATER, LAVA]),
@@ -362,6 +367,29 @@ fn bounds(at: Vec3) -> Aabb {
Vec3::new(at.x + w, at.y + f64::from(HEIGHT), at.z + w),
)
}
/// The bounding box of an arrow, or a thrown trident, at `at`.
pub fn arrow_bounds(at: Vec3) -> Aabb {
bounds(at)
}
/// The blocks an arrow that moved from `from` to `to` was inside
/// (`Entity.checkInsideBlocks`: the sweep of its box, 16 steps at most), for
/// the blocks that react to it (`entityInside`).
pub fn blocks_inside(from: Vec3, to: Vec3) -> Vec<BlockPos> {
let deflated = bounds(to).deflate(Vec3::new(
f64::from(1.0e-5f32),
f64::from(1.0e-5f32),
f64::from(1.0e-5f32),
));
let mut inside = Vec::new();
let _ = sweep_intersected_blocks(from, to, deflated, 1_000_000, |p, iteration| {
if iteration >= 16 {
return false;
}
inside.push(p);
true
});
inside
}
/// `Projectile.lerpRotation`.
fn lerp_rotation(mut old: f32, new: f32) -> f32 {
while new - old < -180.0 {
@@ -431,10 +459,19 @@ pub fn finish_entity_hit(p: &mut Projectile, scene: &ArrowScene, outcome: Entity
match outcome {
EntityHit::Hurt => {
ticker.hit_sound();
ticker.st.removed = true;
// A piercing arrow flies on (`getPierceLevel() <= 0` discards).
if ticker.st.pierce == 0 {
ticker.st.removed = true;
}
}
EntityHit::Refused => ticker.turn_back(),
EntityHit::Deflected => {}
EntityHit::Deflected => {
// The deflection comes before `onHitEntity` adds the entity to
// `piercingIgnoreEntityIds`.
if ticker.st.pierce > 0 {
ticker.st.pierced.pop();
}
}
}
ticker.finish();
p.stuck = st.in_ground;
@@ -639,7 +676,8 @@ impl Ticker<'_, '_, '_, '_> {
self.st.life = 0;
}
/// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the
/// block (piercing is not modelled).
/// block. A piercing arrow that hits an entity here goes on from it next
/// tick (`finish_entity_hit`); vanilla's loop goes on within the same tick.
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);
@@ -653,6 +691,10 @@ impl Ticker<'_, '_, '_, '_> {
if Some(*who) == self.p.owner && !self.p.left_owner || !b.intersects(area) {
continue;
}
// canHitEntity: not an entity a piercing arrow has gone through.
if self.st.pierced.contains(who) {
continue;
}
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).
@@ -667,6 +709,15 @@ impl Ticker<'_, '_, '_, '_> {
self.p.position = next;
self.apply_effects_from_blocks(from, next);
if let Some((who, at, _)) = best {
// AbstractArrow.onHitEntity: past pierce level + 1 entities the
// arrow is discarded before it hurts the next one.
if self.st.pierce > 0 {
if self.st.pierced.len() > usize::from(self.st.pierce) {
self.st.removed = true;
return Hit::None;
}
self.st.pierced.push(who);
}
return Hit::Entity { who, at };
}
let Some((at, pos, face)) = block else {
@@ -752,6 +803,7 @@ impl Ticker<'_, '_, '_, '_> {
self.st.shake = 7;
self.p.set_critical(false);
self.st.pierce = 0;
self.st.pierced.clear();
}
/// `Projectile.mayInteract`: a mob's arrows need `mob_griefing`.
fn may_interact(&self) -> bool {
@@ -648,6 +648,61 @@ impl Conduit {
}
}
/// What `ConduitBlockEntity.serverTick`'s 40-tick check decided.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ConduitCheck {
/// The shape changed: `CONDUIT_ACTIVATE` (true) or `CONDUIT_DEACTIVATE`.
pub toggled: Option<bool>,
/// The frame blocks counted, while the conduit is active: `applyEffects`
/// and `updateAndAttackTarget` follow (the attack needs 42 or more).
pub frames: Option<usize>,
}
/// `ConduitBlockEntity` (server side): what `serverTick` keeps between ticks.
#[derive(Clone, Debug, Default)]
pub struct ConduitServer {
shape: Conduit,
/// `destroyTarget`: the mob id of the enemy being struck.
pub target: Option<u32>,
next_ambient_sound: i64,
}
impl ConduitServer {
/// The `gameTime % 40` part of `serverTick`: the shape is checked again.
pub fn check(
&mut self,
pos: [i32; 3],
game_time: i64,
is_water: impl Fn([i32; 3]) -> bool,
is_frame: impl Fn([i32; 3]) -> bool,
) -> Option<ConduitCheck> {
if game_time % 40 != 0 {
return None;
}
let active = self.shape.update_shape(pos, &is_water, &is_frame);
let toggled = (active != self.shape.is_active).then_some(active);
self.shape.is_active = active;
Some(ConduitCheck {
toggled,
frames: active.then_some(self.shape.effect_blocks.len()),
})
}
/// The sounds of an active conduit at the end of `serverTick`: whether
/// `CONDUIT_AMBIENT` (every 80 ticks) and `CONDUIT_AMBIENT_SHORT` (every
/// 60 to 99 ticks) play.
pub fn ambient(&mut self, game_time: i64, random: &mut impl RandomSource) -> (bool, bool) {
if !self.shape.is_active {
return (false, false);
}
let short = game_time > self.next_ambient_sound;
if short {
self.next_ambient_sound =
game_time + 60 + i64::from(random.next_int_bound(40).unwrap_or(0));
}
(game_time % 80 == 0, short)
}
}
/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Skull {
@@ -832,6 +887,8 @@ pub struct BlockEntityAnims {
pub gateways: FxHashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the gateways (`portalTick`).
pub gateway_servers: FxHashMap<[i32; 3], EndGateway>,
/// The integrated server's copies of the conduits (`serverTick`).
pub conduit_servers: FxHashMap<[i32; 3], ConduitServer>,
/// The client level's random (conduit particles).
pub random: LegacyRandom,
/// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]).
@@ -854,6 +911,7 @@ impl Default for BlockEntityAnims {
pots: FxHashMap::default(),
gateways: FxHashMap::default(),
gateway_servers: FxHashMap::default(),
conduit_servers: FxHashMap::default(),
random: LegacyRandom::new(0x6c6576656c),
kinds: Vec::new(),
present: Vec::new(),
@@ -909,6 +967,7 @@ impl BlockEntityAnims {
self.pots.retain(|p, _| keep(*p));
self.gateways.retain(|p, _| keep(*p));
self.gateway_servers.retain(|p, _| keep(*p));
self.conduit_servers.retain(|p, _| keep(*p));
}
/// `getOpenNess(partial)` of the chest or ender chest at `pos`.
pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 {
+13 -3
View File
@@ -98,6 +98,9 @@ pub enum BlockEntity {
Campfire(Box<Campfire>),
/// `SkullBlockEntity` of every skull and head block.
Skull(Skull),
/// `DaylightDetectorBlockEntity`: no data, only the ticker
/// (`DaylightDetectorBlock.tickEntity`).
DaylightDetector,
}
/// `CampfireBlockEntity`: four cooking slots, each with its
/// `cookingProgress` and `cookingTime` (the recipe's).
@@ -363,6 +366,9 @@ impl BlockEntity {
if is_skull(name) {
return Some(Self::Skull(Skull::default()));
}
if name == "minecraft:daylight_detector" {
return Some(Self::DaylightDetector);
}
if name == "minecraft:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -412,6 +418,7 @@ impl BlockEntity {
Self::Beehive(_) => "minecraft:beehive",
Self::CommandBlock(_) => "minecraft:command_block",
Self::Skull(_) => "minecraft:skull",
Self::DaylightDetector => "minecraft:daylight_detector",
Self::Campfire(_) => "minecraft:campfire",
}
}
@@ -429,7 +436,8 @@ impl BlockEntity {
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_)
| Self::Skull(_) => Vec::new(),
| Self::Skull(_)
| Self::DaylightDetector => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
@@ -448,7 +456,8 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
| Self::Skull(_) => &[],
| Self::Skull(_)
| Self::DaylightDetector => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
@@ -471,7 +480,8 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_)
| Self::Skull(_) => &mut [],
| Self::Skull(_)
| Self::DaylightDetector => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
+66 -9
View File
@@ -95,6 +95,15 @@ impl ItemEntity {
self.health -= fire_damage as i32;
}
}
// CactusBlock.entityInside: `entity.hurt(cactus, 1.0)`. An item has no
// hurt cooldown, so it loses 1 health every tick it touches a cactus
// (5 health: gone in 5 ticks). Fire resistance does not help;
// `ItemStack.canBeHurtBy` only skips it for a damage_resistant stack.
if crate::motion::environment::cactus_contact(world, registry, self.bounds())
&& !items.resists_cactus(&self.stack)
{
self.health -= 1;
}
ItemEnvironmentTick {
alive: self.health > 0,
lava_hurt,
@@ -385,8 +394,29 @@ pub struct ExperienceOrb {
pub value: u32,
pub age: u32,
pub on_ground: bool,
/// `ExperienceOrb.count`: orbs merged into this one; each pickup gives
/// `value` once and takes one off.
pub count: u32,
/// `Entity.tickCount`, which paces `ExperienceOrb.scanForMerges`.
pub ticks: u32,
}
impl ExperienceOrb {
pub fn bounds(&self) -> Aabb {
let h = 0.25;
Aabb::new(
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
Vec3::new(
self.position.x + h,
self.position.y + 0.5,
self.position.z + h,
),
)
}
/// `ExperienceOrb.canMerge(orb, id, value)` for an orb that is not removed:
/// the same value and ids a multiple of 40 apart.
pub fn can_merge(&self, id: u32, value: u32) -> bool {
self.value == value && (self.id as i32).wrapping_sub(id as i32) % 40 == 0
}
/// ExperienceOrb.getExperienceValue: the largest orb size not above `value`.
pub fn split(value: u32) -> u32 {
[2477, 1237, 617, 307, 149, 73, 37, 17, 7, 3, 1]
@@ -416,7 +446,9 @@ impl ExperienceOrb {
facts: &BlockFacts,
collision: &BlockCollisionRegistry<'_>,
player: Option<[f64; 3]>,
next_float: &mut dyn FnMut() -> f32,
) -> bool {
self.ticks += 1;
self.previous = self.position;
let block = world.block(
self.position.x.floor() as i32,
@@ -432,6 +464,14 @@ impl ExperienceOrb {
} else {
self.velocity.y -= 0.03;
}
if facts.get(block).fluid == Fluid::Lava {
// ExperienceOrb.tick: lava throws the orb back out.
self.velocity = Vec3::new(
f64::from((next_float() - next_float()) * 0.2),
f64::from(0.2f32),
f64::from((next_float() - next_float()) * 0.2),
);
}
if let Some(p) = player {
let d = [
(p[0] - self.position.x) / 8.0,
@@ -449,15 +489,7 @@ impl ExperienceOrb {
);
}
}
let h = 0.25;
let bounds = Aabb::new(
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
Vec3::new(
self.position.x + h,
self.position.y + 0.5,
self.position.z + h,
),
);
let bounds = self.bounds();
let mut scene = SceneCollisions {
world,
binding: collision,
@@ -494,6 +526,31 @@ impl ExperienceOrb {
self.age < 6000
}
}
/// `ExperienceOrb.scanForMerges`, run by each orb on `tickCount % 20 == 1`:
/// it absorbs the orbs that `canMerge` within 0.5 blocks of its box,
/// adding their counts and keeping the smaller age.
pub fn merge_orbs(orbs: &mut Vec<ExperienceOrb>) {
let mut removed = vec![false; orbs.len()];
for i in 0..orbs.len() {
if removed[i] || orbs[i].ticks % 20 != 1 {
continue;
}
let area = orbs[i].bounds().inflate(Vec3::new(0.5, 0.5, 0.5));
for j in 0..orbs.len() {
if j != i
&& !removed[j]
&& orbs[j].can_merge(orbs[i].id, orbs[i].value)
&& orbs[j].bounds().intersects(area)
{
orbs[i].count += orbs[j].count;
orbs[i].age = orbs[i].age.min(orbs[j].age);
removed[j] = true;
}
}
}
let mut removed = removed.into_iter();
orbs.retain(|_| !removed.next().unwrap_or(false));
}
/// Player experience (Player.giveExperiencePoints / getXpNeededForNextLevel).
#[derive(Clone, Copy, Debug, Default)]
pub struct Experience {
+152 -14
View File
@@ -265,6 +265,19 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Tag::Byte(i8::from(m.extra.flag2)),
);
map.insert("TimeInOverworld".into(), Tag::Int(m.extra.counter2));
if id == "minecraft:piglin" {
// InventoryCarrier.writeInventoryToTag.
map.insert(
"Inventory".into(),
Tag::List(
m.extra
.inventory
.iter()
.map(crate::save::item_to_nbt)
.collect(),
),
);
}
}
"minecraft:horse"
| "minecraft:donkey"
@@ -357,6 +370,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:bat" => {
map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag)));
}
"minecraft:turtle" => {
map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag)));
if let Some(home) = m.extra.home {
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
}
}
"minecraft:creaking" => {
// home_pos: the heart it is bound to.
if let Some(home) = m.extra.home {
@@ -482,7 +501,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:zombie" => {
map.insert("IsBaby".into(), Tag::Byte(i8::from(m.is_baby())));
for (key, value) in [
("CanBreakDoors", Tag::Byte(0)),
("DrownedConversionTime", Tag::Int(-1)),
("InWaterTime", Tag::Int(-1)),
] {
@@ -507,6 +525,13 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
_ => {}
}
// Zombie.addAdditionalSaveData: CanBreakDoors.
if crate::mobs::doors::is_zombie(m.species()) {
map.insert(
"CanBreakDoors".into(),
Tag::Byte(i8::from(m.extra.can_break_doors)),
);
}
crate::mobs::raider::write_nbt(m, map);
crate::mobs::riders::write_nbt(m, map);
// LivingEntity equipment: what the mob holds now.
@@ -706,6 +731,16 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
) {
m.extra.flag2 = flag(tag, "IsImmuneToZombification");
m.extra.counter2 = number(tag.get("TimeInOverworld")).unwrap_or(0) as i32;
if m.species() == crate::mobs::Species::Piglin
&& let Some(Tag::List(items)) = tag.get("Inventory")
{
// InventoryCarrier.readInventoryFromTag (eight slots).
m.extra.inventory = items
.iter()
.filter_map(crate::save::item_from_nbt)
.take(8)
.collect();
}
}
if matches!(
m.species(),
@@ -847,6 +882,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
{
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
}
if m.species() == crate::mobs::Species::Turtle {
// Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`.
m.extra.flag = flag(tag, "has_egg");
m.extra.home = Some(match tag.get("home_pos") {
Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]],
_ => [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
],
});
}
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
@@ -925,6 +972,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
if !crate::mobs::finalize::ageable(m.species()) && flag(tag, "IsBaby") {
crate::mobs::finalize::set_baby(&mut m, true);
}
// Zombie.readAdditionalSaveData: setCanBreakDoors.
if crate::mobs::doors::is_zombie(m.species()) {
crate::mobs::doors::set_can_break_doors(&mut m, flag(tag, "CanBreakDoors"));
}
crate::mobs::raider::read_nbt(&mut m, tag);
crate::mobs::riders::read_nbt(&mut m, tag);
// A mob saved mid-death finishes dying; one saved dead is dropped.
@@ -1043,18 +1094,18 @@ pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag {
("Health", Tag::Short(5)),
("Age", Tag::Short(o.age.min(i16::MAX as u32) as i16)),
("Value", Tag::Short(o.value.min(i16::MAX as u32) as i16)),
("Count", Tag::Int(1)),
("Count", Tag::Int(o.count.min(i32::MAX as u32) as i32)),
] {
put(&mut tag, key, value);
}
tag
}
/// One Horizon orb per counted orb (vanilla merges orbs of equal value).
/// One orb with its merged `Count`.
pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
let Some(position) = position(tag) else {
return Vec::new();
};
let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize;
let count = number(tag.get("Count")).unwrap_or(1).max(1) as u32;
let orb = ExperienceOrb {
id: 0,
position,
@@ -1063,8 +1114,10 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
value: number(tag.get("Value")).unwrap_or(1).max(1) as u32,
age: number(tag.get("Age")).unwrap_or(0).max(0) as u32,
on_ground: flag(tag, "OnGround"),
count,
ticks: 0,
};
vec![orb; count]
vec![orb]
}
/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow;
@@ -1913,7 +1966,7 @@ mod tests {
assert_eq!(number(tag.get("Health")), Some(5));
}
#[test]
fn orbs_expand_their_count() {
fn orbs_keep_their_count() {
let o = ExperienceOrb {
id: 0,
position: Vec3::new(1.0, 2.0, 3.0),
@@ -1922,12 +1975,14 @@ mod tests {
value: 7,
age: 3,
on_ground: false,
count: 3,
ticks: 0,
};
let mut tag = orb_to_nbt(&o, [0; 4]);
put(&mut tag, "Count", Tag::Int(3));
let tag = orb_to_nbt(&o, [0; 4]);
let back = orbs_from_nbt(&tag);
assert_eq!(back.len(), 3);
assert_eq!(back.len(), 1);
assert_eq!(back[0].value, 7);
assert_eq!(back[0].count, 3);
}
}
@@ -1992,12 +2047,39 @@ fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) {
}
}
const AXOLOTL_VARIANTS: [&str; 5] = ["lucy", "wild", "gold", "cyan", "blue"];
/// `Salmon.Variant` names, by id.
const SALMON_SIZES: [&str; 3] = ["small", "medium", "large"];
/// `TropicalFish.Pattern` names in enum order: the six small patterns, then
/// the six large ones (the order of `extra.variant`).
const TROPICAL_PATTERNS: [&str; 12] = [
"kob",
"sunstreak",
"snooper",
"dasher",
"brinely",
"spotty",
"flopper",
"stripey",
"glitter",
"blockfish",
"betty",
"clayfish",
];
/// `Bucketable.saveDefaultDataToBucketTag`, with the age an axolotl and a
/// tadpole add (`saveToBucketTag`).
pub fn bucket_data(m: &Mob) -> Tag {
let mut data = Tag::compound([
("Age", Tag::Int(m.extra.age)),
("AgeLocked", Tag::Byte(i8::from(m.extra.age_locked))),
("Health", Tag::Float(m.health.to_bits())),
]);
let mut data = Tag::compound([("Health", Tag::Float(m.health.to_bits()))]);
if matches!(
m.species(),
crate::mobs::Species::Axolotl | crate::mobs::Species::Tadpole
) {
put(&mut data, "Age", Tag::Int(m.extra.age));
put(
&mut data,
"AgeLocked",
Tag::Byte(i8::from(m.extra.age_locked)),
);
}
for (key, on) in [
("NoAI", m.no_ai),
("Silent", m.silent),
@@ -2027,6 +2109,29 @@ pub fn bucket_components(m: &Mob) -> crate::item_data::StackData {
.unwrap_or(&"lucy");
data.set_other("minecraft:axolotl/variant", Some(string(variant)));
}
// Salmon.saveToBucketTag: the size.
if m.species() == crate::mobs::Species::Salmon {
let size = SALMON_SIZES
.get(usize::from(m.extra.variant))
.unwrap_or(&"medium");
data.set_other("minecraft:salmon/size", Some(string(size)));
}
// TropicalFish.saveToBucketTag: the pattern and both colours.
if m.species() == crate::mobs::Species::TropicalFish {
let dye = |i: u8| crate::mobs::render::DYE_NAMES[usize::from(i) & 15];
let pattern = TROPICAL_PATTERNS
.get(usize::from(m.extra.variant))
.unwrap_or(&"kob");
data.set_other("minecraft:tropical_fish/pattern", Some(string(pattern)));
data.set_other(
"minecraft:tropical_fish/base_color",
Some(string(dye(m.extra.variant2))),
);
data.set_other(
"minecraft:tropical_fish/pattern_color",
Some(string(dye(m.extra.variant3))),
);
}
data
}
pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
@@ -2077,6 +2182,39 @@ pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) {
{
m.extra.variant = id as u8;
}
// Salmon.applyImplicitComponents: the size.
if m.species() == crate::mobs::Species::Salmon
&& let Some(name) = text(components.other("minecraft:salmon/size"))
&& let Some(id) = SALMON_SIZES
.iter()
.position(|&v| v == name.trim_start_matches("minecraft:"))
{
m.extra.variant = id as u8;
}
// TropicalFish.applyImplicitComponent: the pattern and both colours.
if m.species() == crate::mobs::Species::TropicalFish {
let name = |key| text(components.other(key));
let dye = |key| {
name(key).and_then(|n| {
crate::mobs::render::DYE_NAMES
.iter()
.position(|&v| v == n.trim_start_matches("minecraft:"))
})
};
if let Some(id) = name("minecraft:tropical_fish/pattern").and_then(|n| {
TROPICAL_PATTERNS
.iter()
.position(|&v| v == n.trim_start_matches("minecraft:"))
}) {
m.extra.variant = id as u8;
}
if let Some(id) = dye("minecraft:tropical_fish/base_color") {
m.extra.variant2 = id as u8;
}
if let Some(id) = dye("minecraft:tropical_fish/pattern_color") {
m.extra.variant3 = id as u8;
}
}
}
#[cfg(test)]
+305 -67
View File
@@ -102,7 +102,12 @@ mod maps;
mod minecarts;
mod mob_blocks;
mod mob_gear;
mod mod_browser;
#[cfg(feature = "mods")]
mod mod_browser_recipes;
mod mod_input;
#[cfg(feature = "mods")]
mod mod_recipes;
mod mod_render;
mod mods;
mod mount_menu;
@@ -186,6 +191,7 @@ mod win;
mod wind;
mod wither;
mod world_loading;
mod zombie_reinforcements;
mod zombie_villagers;
use horizon_client::{
Result,
@@ -537,6 +543,8 @@ struct GameLevel<'w> {
events: &'w mut Vec<LevelEvent>,
dimension: LevelDimension,
darken: i32,
/// The environment of the level's dimension (`SUN_ANGLE`).
environment: &'w Environment,
raining: bool,
thundering: bool,
player_box: Option<([f64; 3], [f64; 3])>,
@@ -545,6 +553,8 @@ struct GameLevel<'w> {
player_collision: Option<PlayerCollision>,
/// Minecart boxes (detector rails).
cart_boxes: Vec<([f64; 3], [f64; 3])>,
/// Arrow and thrown trident boxes (wooden buttons).
arrow_boxes: Vec<([f64; 3], [f64; 3])>,
/// The other entities that keep blocks from being placed into them.
blockers: Blockers<'w>,
biomes: &'w Biomes,
@@ -803,6 +813,11 @@ impl LevelAccess for GameLevel<'_> {
fn sky_darken(&self) -> i32 {
self.darken
}
fn sun_angle(&self, _pos: BlockPos) -> f32 {
self.environment
.sample(self.world.day_time, None, None)
.sun_angle
}
fn is_raining(&self) -> bool {
self.raining
}
@@ -871,8 +886,9 @@ impl LevelAccess for GameLevel<'_> {
fn is_ticking_chunk(&self, chunk: horizon_core::position::ChunkPos) -> bool {
self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z)
}
/// Entities that trigger pressure plates, tripwires and detector rails:
/// the players (the host and the LAN guests, mobs) and the minecarts.
/// Entities that trigger pressure plates, tripwires, detector rails and
/// wooden buttons: the players (the host and the LAN guests, mobs) and
/// the minecarts, and for `EntityQuery::Arrows` the arrows.
fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize {
let hit = |(lo, hi): &([f64; 3], [f64; 3])| {
area.intersects(Aabb::new(
@@ -881,6 +897,7 @@ impl LevelAccess for GameLevel<'_> {
))
};
let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count();
let arrows = || self.arrow_boxes.iter().filter(|b| hit(b)).count();
let players = || {
self.player_box
.iter()
@@ -890,6 +907,7 @@ impl LevelAccess for GameLevel<'_> {
};
match query {
EntityQuery::Minecart => carts(),
EntityQuery::Arrows => arrows(),
EntityQuery::Mobs => players(),
EntityQuery::Everything => players() + carts(),
}
@@ -2225,8 +2243,9 @@ impl Game<'_> {
ticks: 0,
});
}
/// `Block.getDrops`: the block's loot table, drawing from its server random
/// sequence (`LootContext.Builder.create`), else the level random.
/// `Block.getDrops` for a block a player breaks: the block's loot table
/// with the player as `this`, drawing from its server random sequence
/// (`LootContext.Builder.create`), else the level random.
fn block_loot_at(
&mut self,
pos: [i32; 3],
@@ -2240,9 +2259,9 @@ impl Game<'_> {
let random = self.rand_sequences.get(&sequence, self.level.seed);
self.res
.items()
.block_drops_with(registry, state, held, &dynamic, random)
.block_drops_by_player(registry, state, held, &dynamic, random)
}
None => self.res.items().block_drops_with(
None => self.res.items().block_drops_by_player(
registry,
state,
held,
@@ -2286,11 +2305,13 @@ impl Game<'_> {
// Player.drop: the drop statistics.
self.stats.add("dropped", &thrown.item, thrown.count as i32);
self.stats.custom("drop", 1);
self.throw_from_eyes(thrown, eye);
self.throw_from_eyes(thrown, eye, true);
}
/// `Player.createItemStackToDrop`: an item entity thrown from the eyes
/// along the view direction.
fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3]) {
/// along the view direction. `thrown_from_hand` (`drop(stack, true)`, the
/// drop key) names the player as the thrower; `drop(stack, false)`, for
/// what no longer fits in the inventory, does not.
fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3], thrown_from_hand: bool) {
let (yaw, pitch) = (
f64::from(self.yaw).to_radians(),
f64::from(self.pitch).to_radians(),
@@ -2304,7 +2325,7 @@ impl Game<'_> {
yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength,
];
self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40);
if self.lan_acting.is_none() {
if thrown_from_hand && self.lan_acting.is_none() {
let uuid = self.level.ensure_player_uuid();
self.dropped.last_mut().unwrap().thrower = Some(uuid);
}
@@ -2511,6 +2532,18 @@ impl Game<'_> {
)
})
.collect();
let arrow_boxes = self
.creatures
.projectiles
.iter()
.filter(|p| p.arrow.is_some())
.map(|p| p.position)
.chain(self.tridents.iter().map(|t| t.position))
.map(|at| {
let b = horizon_client::arrows::arrow_bounds(at);
(b.min_position().components(), b.max_position().components())
})
.collect();
let guest_boxes = self.lan_block_trigger_boxes();
let dimension = match self.dim {
Dim::Overworld => LevelDimension::Overworld,
@@ -2541,6 +2574,7 @@ impl Game<'_> {
};
let mut level = GameLevel {
cart_boxes,
arrow_boxes,
blockers,
world: &mut self.world,
facts: self.res.facts(),
@@ -2548,6 +2582,11 @@ impl Game<'_> {
events: &mut self.level_events,
dimension,
darken,
environment: match dimension {
LevelDimension::Overworld => self.res.environment(),
LevelDimension::Nether => self.res.nether_environment(),
LevelDimension::End => self.res.end_environment(),
},
raining: rain > 0.2,
thundering: thunder > 0.9,
player_box,
@@ -2674,8 +2713,9 @@ impl Game<'_> {
.copied()
.filter(|&(x, z)| levels.random_ticking(x, z) && ticking_chunk(&self.world, x, z))
.collect();
// Entity.checkInsideBlocks for the plates, tripwires and detector rails
// under the players (the host and the LAN guests) and the minecarts.
// Entity.checkInsideBlocks for the plates, tripwires, detector rails and
// buttons under the players (the host and the LAN guests), the minecarts
// and the arrows.
let mut inside = Vec::new();
let guests = self.lan_block_trigger_boxes();
let boxes = self
@@ -2707,6 +2747,24 @@ impl Game<'_> {
}
}
}
// AbstractArrow.applyEffectsFromBlocks: the blocks every arrow passed
// through this tick (a wooden button is pressed by one inside it), and
// the ones a thrown trident is in.
for p in self
.creatures
.projectiles
.iter()
.filter(|p| p.arrow.is_some())
{
inside.extend(horizon_client::arrows::blocks_inside(
p.previous, p.position,
));
}
for t in &self.tridents {
inside.extend(horizon_client::arrows::blocks_inside(
t.position, t.position,
));
}
// BigDripleafBlock.entityInside also asks whether the player stands on
// the ground and how high its feet are: the leaves its box's feet
// layer is inside (the host and the LAN guests).
@@ -2901,6 +2959,9 @@ impl Game<'_> {
1501 => Some(("minecraft:block.lava.extinguish", 0.5)),
1009 => Some(("minecraft:block.fire.extinguish", 0.5)),
1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)),
// LevelEvent.SOUND_ZOMBIE_WOODEN_DOOR (attack, break).
1019 => Some(("minecraft:entity.zombie.attack_wooden_door", 2.0)),
1021 => Some(("minecraft:entity.zombie.break_wooden_door", 2.0)),
1030 => Some(("minecraft:block.anvil.use", 1.0)),
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
1031 => Some(("minecraft:block.anvil.land", 0.3)),
@@ -2920,9 +2981,14 @@ impl Game<'_> {
1029 | 1030 | 1042 | 1043 | 1044 => {
self.world.random.next_float() * 0.1 + 0.9
}
1019 | 1021 => {
(self.world.random.next_float() - self.world.random.next_float())
* 0.2
+ 1.0
}
_ => 1.0,
};
if matches!(id, 1029 | 1030) {
if matches!(id, 1019 | 1021 | 1029 | 1030) {
// Clients play the anvil sound from its level event;
// capturing it also sends a duplicate sound packet.
self.audio.play_unshared(name, c, volume, pitch);
@@ -3052,6 +3118,11 @@ impl Game<'_> {
kind: "hatch_sniffer",
..
} => self.hatch_sniffer([pos.x, pos.y, pos.z]),
LevelEvent::BlockEvent {
pos,
state,
kind: "hatch_turtles",
} => self.hatch_turtles([pos.x, pos.y, pos.z], state),
LevelEvent::BlockEvent {
pos,
kind: "portal_spawn",
@@ -3089,6 +3160,10 @@ impl Game<'_> {
.name
.clone();
let key = (pos[0], pos[1], pos[2]);
if self.chest_menu_blocked(key, &name) {
// The use still succeeds, but no menu, stat or piglin anger.
return;
}
if &*name == "minecraft:lectern" {
self.open_lectern(pos);
return;
@@ -4435,12 +4510,6 @@ impl Game<'_> {
let events = std::mem::take(&mut player.events);
let spin_hit = player.spin_hit.take();
let glider_wear = std::mem::take(&mut player.glider_wear);
if glider_wear > 0
&& !self.creative
&& let Some(elytra) = self.armor[1].as_mut()
{
elytra.damage += glider_wear;
}
let feet = [player.position.x, player.position.y, player.position.z];
let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z];
self.previous_eye = self.eye;
@@ -4451,9 +4520,36 @@ impl Game<'_> {
};
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
// `LivingEntity.baseTick` (Soul Speed) comes before `aiStep` (the
// glide's wear): both draw from the level random.
if let Some((at, velocity)) = self.tick_soul_speed() {
self.particles.send_particles(
&horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::Soul,
),
at,
velocity,
1.0,
0,
);
if let Some(host) = self.lan.as_ref() {
lan_particles::send_soul_particle(host, at, velocity);
}
}
// `ItemStack.hurtAndBreak` for the glide: Unbreaking can save the wear.
if glider_wear > 0
&& !self.creative
&& let Some(stack) = self.armor[1].clone()
{
let loss = self.durability_loss(&stack, glider_wear);
if let Some(elytra) = self.armor[1].as_mut() {
elytra.damage += loss;
}
}
self.tick_avatar(before, riding);
self.end_spin_attack(spin_hit);
self.record_combat(&events);
self.wear_armor(&events);
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet),
@@ -4626,7 +4722,7 @@ impl Game<'_> {
&& let Some(stack) = self.carried.take()
&& let Some(eye) = self.eye_position()
{
self.throw_from_eyes(stack, eye);
self.throw_from_eyes(stack, eye, false);
}
}
self.tick_world(running)
@@ -4946,7 +5042,7 @@ impl Game<'_> {
self.capture(true);
}
}
fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
fn draw_item(&self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
// special renderers included), then the decorations.
self.draw_item_model(batch, stack, x, y);
@@ -5036,7 +5132,7 @@ impl Game<'_> {
/// `GuiGraphicsExtractor.itemDecorations`: the count (or `count_text`)
/// and damage bar.
fn draw_item_decorations(
&mut self,
&self,
batch: &mut HudBatch,
stack: &ItemStack,
x: f32,
@@ -5163,12 +5259,12 @@ impl Game<'_> {
for d in &draws {
if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d {
let stack = if slot == 40 {
self.offhand.clone()
self.offhand.as_ref()
} else {
self.inventory[slot as usize].clone()
self.inventory[slot as usize].as_ref()
};
if let Some(stack) = stack {
self.draw_item(&mut batch, &stack, x as f32, y as f32);
self.draw_item(&mut batch, stack, x as f32, y as f32);
}
}
}
@@ -5329,6 +5425,7 @@ impl Game<'_> {
Screen::CommandBlock => self.draw_command_block(&mut batch),
Screen::Inventory => {
self.draw_inventory(&mut batch);
self.draw_mod_browser(&mut batch);
}
Screen::Creative => {
self.draw_creative(&mut batch);
@@ -5394,6 +5491,7 @@ impl Game<'_> {
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
) => {}
None => {
@@ -5665,6 +5763,7 @@ impl Game<'_> {
| BlockEntity::Beehive(_)
| BlockEntity::CommandBlock(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
@@ -5719,6 +5818,7 @@ impl Game<'_> {
self.last_inv_click = None;
}
pub(super) fn close_container(&mut self) {
self.mod_browser_closed();
self.reset_inventory_clicks();
self.close_station();
self.mount_closed();
@@ -5732,7 +5832,8 @@ impl Game<'_> {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
// AbstractContainerMenu.dropOrPlaceInInventory: `drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
self.craft_size = 2;
@@ -6445,6 +6546,9 @@ impl Game<'_> {
fn inventory_press(&mut self, right: bool) {
use horizon_client::container_screen::Target;
use horizon_client::menu::Input;
if self.mod_browser_press(right) {
return;
}
if !right && self.sort_press() {
return;
}
@@ -6628,24 +6732,8 @@ impl Game<'_> {
}
/// `hasClickedOutside` of the open screen at the cursor.
fn clicked_outside(&self, batch: &HudBatch) -> bool {
use horizon_client::container_screen::{Book, Image, clicked_outside};
let (ox, oy) = self.inventory_origin(batch);
let (shift, width, height) = if self.screen == Screen::Creative {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
let image = Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height,
};
use horizon_client::container_screen::{Book, clicked_outside};
let image = self.container_image(batch);
let book = self
.recipe_book_area(batch)
.map(|(visible, tab_hovered)| Book {
@@ -6659,6 +6747,26 @@ impl Game<'_> {
book,
)
}
/// The open container screen's window: its place and size.
fn container_image(&self, batch: &HudBatch) -> horizon_client::container_screen::Image {
let (ox, oy) = self.inventory_origin(batch);
let (shift, width, height) = if self.screen == Screen::Creative {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
horizon_client::container_screen::Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height,
}
}
/// A click outside the window (slot id -999): `THROW` does nothing; a
/// `PICKUP` drops the carried stack (left) or one of it (right), thrown
/// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`).
@@ -6819,7 +6927,7 @@ impl Game<'_> {
}
}
fn click_inventory(&mut self, right: bool) {
if self.mount_click(right) {
if self.mod_browser_press(right) || self.mount_click(right) {
return;
}
if self.recipe_book_click(right) {
@@ -7866,6 +7974,9 @@ impl Game<'_> {
if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
self.audio
.play(&format!("minecraft:{s}"), Some(at), volume, pitch);
} else {
// Left for the end of the tick.
self.mobs[index].outbox.push(event);
}
}
self.weapon_hit(index);
@@ -7988,6 +8099,7 @@ impl Game<'_> {
creative: bool,
create: Option<&horizon_client::title::WorldOptions>,
) -> Result<()> {
world_loading::world_data_used();
if self.defer_world_entry(PendingWorldEntry::Local {
folder: folder.to_owned(),
name: name.map(str::to_owned),
@@ -8540,15 +8652,54 @@ impl Game<'_> {
}
self.apply_enchantment_attributes();
}
/// Inventory.hurtArmor: each piece loses max(1, damage / 4) durability.
fn hurt_armor(&mut self, damage: f32) {
/// The armor hits among a tick's motion events (`Player.hurtArmor` from
/// `getDamageAfterArmorAbsorb`), whatever the damage: a mob, an explosion,
/// a cactus, lava, a campfire.
fn wear_armor(&mut self, events: &[MotionEvent]) {
for event in events {
if let MotionEvent::Health(horizon_client::health::HealthEvent::ArmorHurt {
source,
amount,
}) = event
{
self.hurt_armor(*source, *amount);
}
}
}
/// `Player.hurtArmor` -> `LivingEntity.doHurtEquipment`: each worn piece that
/// wears when its wearer is hurt loses max(1, damage / 4) durability, except
/// to a fire source when the piece resists fire (`ItemStack.canBeHurtBy`).
fn hurt_armor(&mut self, source: horizon_world::damage_source::DamageTypeId, damage: f32) {
if damage <= 0.0 {
return;
}
let amount = ((damage / 4.0) as u32).max(1);
let name = self
.motion
.health
.damage
.definition(source)
.map(|d| d.name.clone())
.unwrap_or_default();
let fire = self
.motion
.health
.damage
.in_tag(source, "minecraft:is_fire");
let mut broke = false;
let losses: Vec<u32> = (0..4)
.map(|i| {
self.armor[i]
.clone()
.map_or(amount, |s| self.durability_loss(&s, amount))
.map(|i| match self.armor[i].clone() {
Some(s)
if self
.res
.items()
.get(&s.item)
.is_some_and(|info| info.equip_damage_on_hurt)
&& !(fire && self.res.items().resists_fire(&s, &name)) =>
{
self.durability_loss(&s, amount)
}
_ => 0,
})
.collect();
for (slot, amount) in self.armor.iter_mut().zip(losses) {
@@ -8645,7 +8796,8 @@ impl Game<'_> {
}
fn drop_stack(&mut self, stack: ItemStack) {
if let Some(eye) = self.0.eye_position() {
self.0.spawn_item(stack, eye, [0.0, 0.1, 0.0], 40);
// ItemUtils.createFilledResult: `player.drop(stack, false)`.
self.0.throw_from_eyes(stack, eye, false);
}
}
}
@@ -8883,6 +9035,24 @@ impl Game<'_> {
}
}
}
/// `ItemStack.hurtWithoutBreaking`: Unbreaking applies, but the stack stops at
/// one point of durability left instead of breaking.
fn hurt_held_without_breaking(&mut self, amount: u32) {
if self.creative {
return;
}
let Some(held) = self.held().cloned() else {
return;
};
let amount = self.durability_loss(&held, amount);
let max = self.res.items().get(&held.item).map_or(0, |i| i.max_damage);
if amount == 0 || max == 0 {
return;
}
if let Some(stack) = self.held_mut().as_mut() {
stack.damage = (stack.damage + amount).min(max - 1);
}
}
/// Block tool use: distinguish success, failure and fall-through for hand feedback.
fn use_tool(
&mut self,
@@ -8970,7 +9140,8 @@ impl Game<'_> {
} else if let Some(rest) = self.give(filled)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
// ItemUtils.createFilledResult: `player.drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
return Ok(UseResult::Success { swing: true });
@@ -9120,8 +9291,29 @@ impl Game<'_> {
while value > 0 {
let v = ExperienceOrb::split(value);
value -= v;
let _merge_id = self.world.random.next_int_bound(40);
self.add_orb(at, v);
let merge_id = self.world.random.next_int_bound(40).unwrap_or(0);
self.award_orb(at, v, merge_id);
}
}
/// `ExperienceOrb.tryMergeToExisting`: an orb of the same value within a
/// 1 block box of `at`, whose id is a multiple of 40 from `merge_id`, takes
/// the new one as one more in its count (and restarts its age); otherwise
/// a fresh orb spawns.
fn award_orb(&mut self, at: [f64; 3], value: u32, merge_id: i32) {
let centre = Vec3::new(at[0], at[1], at[2]);
let half = Vec3::new(0.5, 0.5, 0.5);
let area = Aabb::new(centre.subtract(half), centre.add_vector(half));
// A server's orbs are its own; a LAN or server guest only shows them.
let target = self.remote.is_none().then(|| {
self.orbs
.iter_mut()
.find(|o| o.can_merge(merge_id as u32, value) && o.bounds().intersects(area))
});
if let Some(Some(orb)) = target {
orb.count += 1;
orb.age = 0;
} else {
self.add_orb(at, value);
}
}
/// `new ExperienceOrb(level, pos, Vec3.ZERO, value)`: yaw and motion from
@@ -9143,6 +9335,8 @@ impl Game<'_> {
value,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
});
}
fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool {
@@ -9219,18 +9413,31 @@ impl Game<'_> {
}),
);
}
// Player.aiStep: the pickup area is the box inflated by (1, 0.5, 1).
let bounds = player.map(|p| {
let w = f64::from(p.dimensions.width) / 2.0;
(
[p.position.x - w, p.position.y, p.position.z - w],
[
p.position.x + w,
p.position.y + f64::from(p.dimensions.height),
p.position.z + w,
p.position.x - w - 1.0,
p.position.y - 0.5,
p.position.z - w - 1.0,
],
[
p.position.x + w + 1.0,
p.position.y + f64::from(p.dimensions.height) + 0.5,
p.position.z + w + 1.0,
],
)
});
let mut orbs = std::mem::take(&mut self.orbs);
// An orb has no random of its own here: lava draws from one made on
// first use, apart from the level stream.
let mut lava_random = None;
let mut next_float = || {
lava_random
.get_or_insert_with(dispenser::entity_random)
.next_float()
};
orbs.retain_mut(|o| {
let distance = |feet: &[f64; 3]| -> f64 {
(feet[0] - o.position.x).powi(2)
@@ -9242,12 +9449,22 @@ impl Game<'_> {
.filter(|(feet, _)| distance(feet) < 64.0)
.min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0)))
.map(|(_, target)| *target);
o.tick(&self.world, self.res.facts(), self.collision, target)
o.tick(
&self.world,
self.res.facts(),
self.collision,
target,
&mut next_float,
)
});
// ExperienceOrb.scanForMerges runs on the server only.
if self.remote.is_none() {
horizon_client::entities::merge_orbs(&mut orbs);
}
let mut gained = 0;
let mut taken = Vec::new();
if let Some((min, max)) = bounds {
orbs.retain(|o| {
orbs.retain_mut(|o| {
let touching = o.position.x + 0.25 > min[0]
&& o.position.x - 0.25 < max[0]
&& o.position.y + 0.5 > min[1]
@@ -9255,11 +9472,13 @@ impl Game<'_> {
&& o.position.z + 0.25 > min[2]
&& o.position.z - 0.25 < max[2];
if touching && self.xp_delay == 0 {
// ExperienceOrb.playerTouch: one orb every 2 ticks.
// ExperienceOrb.playerTouch: one orb every 2 ticks; a
// merged orb gives its value once per count.
self.xp_delay = 2;
gained += o.value;
taken.push(o.clone());
return false;
o.count -= 1;
return o.count > 0;
}
true
});
@@ -9335,7 +9554,10 @@ impl Game<'_> {
};
// BowItem.shootProjectile: shootFromRotation(power * 3, inaccuracy 1).
let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]);
let (power_bonus, infinity) = self.bow_enchantments();
let ammo = arrow_slot
.and_then(|i| self.stack_in(i).cloned())
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
let (power_bonus, infinity) = self.bow_enchantments(&ammo.item);
let kind = horizon_client::projectiles::ProjectileKind::Arrow {
base_damage: 2.0 + power_bonus,
critical: power >= 1.0,
@@ -9349,9 +9571,6 @@ impl Game<'_> {
// 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.stack_in(i).cloned())
.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,
@@ -11929,6 +12148,14 @@ impl ApplicationHandler for Game<'_> {
// The recipe book's search box takes every key but Escape.
self.recipe_key(&event);
}
WindowEvent::KeyboardInput { event, .. }
if self.mod_browser_typing()
&& event.state == ElementState::Pressed
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
{
// A mod's item panel's search box, as the recipe book's.
self.mod_browser_key(&event);
}
WindowEvent::KeyboardInput { event, .. }
if self.station_typing()
&& event.state == ElementState::Pressed
@@ -12837,6 +13064,17 @@ impl Game<'_> {
if self.rest_loader.is_some() {
return Ok(());
}
let on_world_screens = self.title.as_ref().is_some_and(|title| {
!matches!(
title.mode,
horizon_client::title::Mode::Main | horizon_client::title::Mode::Multiplayer(_)
)
});
world_loading::preload_world_data(
on_world_screens,
&self.options.resources,
self.pack.assets.registry,
);
if std::mem::take(&mut self.pending_pack_reload) {
self.reload_packs();
}
@@ -453,6 +453,11 @@ impl Game<'_> {
}
// ArmorStand.swapItem.
match held {
// A player with infinite materials puts a copy of one on an empty
// slot and keeps the stack.
Some(h) if self.creative && current.is_none() => {
self.armor_stands[i].equipment[slot] = Some(ItemStack { count: 1, ..h });
}
Some(h) if h.count > 1 => {
if current.is_some() {
return true;
@@ -5,10 +5,14 @@
//! [`Game::block_anim`] and [`Game::chest_lid`].
use super::Game;
use horizon_client::{
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
block_entity_anim::{
BellEntity, ConduitServer, ConduitTarget, EndGateway, Shulker, ShulkerStatus, Ticker,
},
block_entity_render::BlockAnim,
collisions::{SceneCollisions, no_collision_empty},
containers::BlockEntity,
effects::EffectInstance,
mobs::{Damage, DamageKind},
particles::{ParticleOptions, ParticleType},
save::number,
skins,
@@ -16,6 +20,7 @@ use horizon_client::{
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
random::RandomSource,
};
use horizon_world::nbt::Tag;
@@ -218,9 +223,12 @@ impl Game<'_> {
/// The client tickers of the loaded animated block entities, once per
/// client tick (`ClientLevel.tickBlockEntities`).
pub(super) fn tick_block_entity_anims(&mut self) {
// A server has no window, but its gateways and conduits still run
// their server tickers; a client of one only animates what it is sent.
if self.remote.is_none() {
self.tick_conduit_servers();
}
let Some(r) = &self.renderer else {
// A server has no window, but its gateways still run their
// server ticker.
if self.remote.is_none() {
self.tick_gateway_servers();
}
@@ -337,6 +345,7 @@ impl Game<'_> {
}
}
Ticker::Conduit => {
let target = self.conduit_target(pos);
let world = &self.world;
let facts = self.res.facts();
let registry = self.pack.assets.registry;
@@ -356,7 +365,7 @@ impl Game<'_> {
time,
is_water,
is_frame,
None,
target,
self.particles.random(),
);
let nautilus = ParticleOptions::simple(ParticleType::Nautilus);
@@ -383,6 +392,248 @@ impl Game<'_> {
}
self.be_anims.present = positions;
}
/// `ConduitBlockEntity.serverTick` of every conduit in the chunks that
/// tick blocks, with or without a renderer. The conduits are looked for
/// when the shape is checked, every 40 ticks (they have no block entity
/// of their own here).
fn tick_conduit_servers(&mut self) {
if self.world.game_time % 40 == 0 {
self.find_conduits();
}
let mut positions: Vec<[i32; 3]> = self.be_anims.conduit_servers.keys().copied().collect();
positions.sort_unstable();
for pos in positions {
self.tick_conduit_server(pos);
}
}
/// Sets `be_anims.conduit_servers` to the conduits in the
/// chunks that tick blocks, keeping the state of those already known.
fn find_conduits(&mut self) {
let levels = self.tickets.levels();
let kinds = &self.be_anims.kinds;
let is_conduit = |id: u32| matches!(kinds.get(id as usize), Some(Some(Ticker::Conduit)));
let mut found = Vec::new();
for (&(cx, cz), chunk) in &self.world.chunks {
if !levels.block_ticking_at(cx * 16, cz * 16) {
continue;
}
for (si, section) in chunk.sections.iter().enumerate() {
if !section.blocks.maybe_has(is_conduit) {
continue;
}
for i in 0..4096 {
if is_conduit(section.get(i)) {
found.push([
cx * 16 + (i & 15) as i32,
horizon_client::chunk::MIN_Y + si as i32 * 16 + (i >> 8) as i32,
cz * 16 + ((i >> 4) & 15) as i32,
]);
}
}
}
}
let mut old = std::mem::take(&mut self.be_anims.conduit_servers);
for pos in found {
let known = old.remove(&pos).unwrap_or_default();
self.be_anims.conduit_servers.insert(pos, known);
}
}
/// `ConduitBlockEntity.serverTick` of the conduit at `pos`, in a chunk
/// that ticks blocks: the shape check every 40 ticks with its sounds, the
/// power for players in range, the hurt for an enemy, then the ambient
/// sounds.
fn tick_conduit_server(&mut self, pos: [i32; 3]) {
let state = self.world.block(pos[0], pos[1], pos[2]).0;
if self.be_anims.ticker(state) != Some(Ticker::Conduit) {
// Broken since the chunks were searched.
self.be_anims.conduit_servers.remove(&pos);
return;
}
if !self.tickets.levels().block_ticking_at(pos[0], pos[2])
|| !self.border.contains(f64::from(pos[0]), f64::from(pos[2]))
{
return;
}
let time = self.world.game_time;
let mut conduit = self
.be_anims
.conduit_servers
.remove(&pos)
.unwrap_or_default();
let check = {
let world = &self.world;
let facts = self.res.facts();
let registry = self.pack.assets.registry;
let frames = self
.res
.items()
.block_tags
.get("minecraft:conduit_effect_block");
// Level.isWaterAt: the fluid at the position is water.
let is_water = |p: [i32; 3]| {
facts.get(world.block(p[0], p[1], p[2])).fluid
== horizon_client::blocks::Fluid::Water
};
let is_frame = |p: [i32; 3]| {
registry
.state(world.block(p[0], p[1], p[2]))
.is_some_and(|s| frames.is_some_and(|f| f.contains(&s.name)))
};
conduit.check(pos, time, is_water, is_frame)
};
let centre = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
if let Some(check) = check {
if let Some(active) = check.toggled {
let sound = if active {
"minecraft:block.conduit.activate"
} else {
"minecraft:block.conduit.deactivate"
};
self.audio.play(sound, Some(centre), 1.0, 1.0);
}
if let Some(frames) = check.frames {
self.conduit_apply_effects(pos, frames);
self.conduit_attack(&mut conduit, pos, frames >= 42);
}
}
let (ambient, short) = conduit.ambient(time, &mut self.world.random);
if ambient {
self.audio
.play("minecraft:block.conduit.ambient", Some(centre), 1.0, 1.0);
}
if short {
self.audio.play(
"minecraft:block.conduit.ambient_short",
Some(centre),
1.0,
1.0,
);
}
self.be_anims.conduit_servers.insert(pos, conduit);
}
/// `ConduitBlockEntity.applyEffects`: conduit power for every player
/// in water or rain within `frames / 7 * 16` blocks.
fn conduit_apply_effects(&mut self, pos: [i32; 3], frames: usize) {
let range = (frames / 7 * 16) as i64;
self.for_each_player(|g| {
let Some(p) = g.player.as_ref().filter(|p| !p.health.dead_or_dying()) else {
return;
};
if g.spectator() {
return;
}
let at = p.position;
let in_water = p.fluids.was_touching_water;
let top = at.y + f64::from(p.dimensions.height);
// BlockPos.closerThan: the squared distance under range squared.
let d = [at.x, at.y, at.z]
.map(|v| v.floor() as i64)
.iter()
.zip(pos)
.map(|(a, b)| (a - i64::from(b)).pow(2))
.sum::<i64>();
if d >= range * range || !(in_water || g.in_rain(at, top)) {
return;
}
let power = EffectInstance {
ambient: true,
..EffectInstance::new("conduit_power", 260, 0)
};
g.potions.effects.add(power);
});
}
/// `Entity.isInRain`: rain at the block position or at the top of the box.
fn in_rain(&mut self, at: Vec3, top: f64) -> bool {
let p = BlockPos::new(
at.x.floor() as i32,
at.y.floor() as i32,
at.z.floor() as i32,
);
let up = BlockPos::new(p.x, top.floor() as i32, p.z);
self.with_level(|b, level, _| b.is_raining_at(level, p) || b.is_raining_at(level, up))
}
/// `ConduitBlockEntity.updateAndAttackTarget`: while the conduit hunts
/// (42 frame blocks) its target stays until it dies or leaves the 8
/// blocks, else a random enemy in water or rain is chosen; the target
/// takes 4 magic damage.
fn conduit_attack(&mut self, conduit: &mut ConduitServer, pos: [i32; 3], hunting: bool) {
conduit.target = match conduit.target {
_ if !hunting => None,
None => self.conduit_new_target(pos),
Some(id) => self
.mobs
.iter()
.find(|m| m.id == id && !m.removed)
.filter(|m| {
let at = [m.position.x, m.position.y, m.position.z].map(|v| v.floor() as i64);
m.alive()
&& at
.iter()
.zip(pos)
.map(|(a, b)| (a - i64::from(b)).pow(2))
.sum::<i64>()
< 64
})
.map(|m| m.id),
};
let Some(m) = conduit
.target
.and_then(|id| self.mobs.iter_mut().find(|m| m.id == id))
else {
return;
};
let at = [m.position.x, m.position.y, m.position.z];
m.damage(4.0, Damage::of(DamageKind::Magic));
self.audio
.play("minecraft:block.conduit.attack.target", Some(at), 1.0, 1.0);
}
/// `ConduitBlockEntity.selectNewTarget`: one of the enemies in water or
/// rain whose box meets the conduit's block inflated by 8.
fn conduit_new_target(&mut self, pos: [i32; 3]) -> Option<u32> {
let [x, y, z] = pos.map(f64::from);
let area = Aabb::new(
Vec3::new(x - 8.0, y - 8.0, z - 8.0),
Vec3::new(x + 9.0, y + 9.0, z + 9.0),
);
let near: Vec<(u32, bool, Vec3, f64)> = self
.mobs
.iter()
.filter(|m| m.hostile() && !m.removed && m.bounds().intersects(area))
.map(|m| {
let top = m.position.y + f64::from(m.height());
(m.id, m.fluids.in_water, m.position, top)
})
.collect();
let candidates: Vec<u32> = near
.into_iter()
.filter(|&(_, in_water, at, top)| in_water || self.in_rain(at, top))
.map(|(id, ..)| id)
.collect();
if candidates.is_empty() {
return None;
}
let pick = self
.world
.random
.next_int_bound(candidates.len() as i32)
.unwrap_or(0);
Some(candidates[pick as usize])
}
/// The conduit's `destroyTarget` as the client draws it.
fn conduit_target(&self, pos: [i32; 3]) -> Option<ConduitTarget> {
let id = self.be_anims.conduit_servers.get(&pos)?.target?;
let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
Some(ConduitTarget {
position: [m.position.x, m.position.y, m.position.z],
eye_y: m.eye_y(),
width: m.width(),
height: m.height(),
})
}
/// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the
/// gateways a server keeps a copy of, in block-ticking chunks
/// (`Level.tickBlockEntities`): the cooldown an entry started runs out,
@@ -10,6 +10,7 @@ use horizon_client::{
block_entities::{Pos, Ticking},
containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS},
};
use horizon_core::position::BlockPos;
use horizon_world::registry::BlockStateId;
impl Game<'_> {
@@ -56,6 +57,7 @@ impl Game<'_> {
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
Some(BlockEntity::Brewing(_)) => self.tick_brewing_stand(pos)?,
Some(BlockEntity::DaylightDetector) => self.tick_daylight_detector(pos),
Some(BlockEntity::Campfire(_)) => self.tick_campfire(pos)?,
_ => {}
}
@@ -94,6 +96,7 @@ impl Game<'_> {
| "minecraft:beehive"
| "minecraft:bee_nest"
| "minecraft:brewing_stand"
| "minecraft:daylight_detector"
// Lit, cookTick; unlit, cooldownTick.
| "minecraft:campfire"
| "minecraft:soul_campfire" => Ticking::Yes,
@@ -117,6 +120,16 @@ impl Game<'_> {
let levels = self.tickets.levels();
move |x, z| levels.block_ticking_at(x, z)
}
/// `DaylightDetectorBlock.tickEntity` of the detector at `pos`.
fn tick_daylight_detector(&mut self, pos: Pos) {
// It updates every 20 game ticks (the behaviour checks this too).
if self.world.game_time % 20 != 0 {
return;
}
let at = BlockPos::new(pos.0, pos.1, pos.2);
self.with_level(|b, level, ticks| b.tick_daylight_detector(level, ticks, at));
let _ = self.process_level_events();
}
/// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and
/// its block's `lit` following it.
fn tick_furnace(&mut self, pos: Pos) -> Result<()> {
+4
View File
@@ -31,6 +31,10 @@ pub(super) struct CombatTracker {
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
/// fire decides whom the blast may hurt.
pub(super) explosion_source: Option<u32>,
/// Charged creepers whose blast just went off and that have not dropped
/// a head yet (`Creeper.droppedSkulls`): they are gone from the mob list,
/// but the mobs they killed still ask for their loot.
pub(super) charged_exploders: Vec<u32>,
/// The player's fall distance before this tick's movement (as of the
/// end of the last one).
fall_before: f64,
@@ -1697,6 +1697,8 @@ impl Game<'_> {
value: 0,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
});
name = Text::translate("entity.minecraft.experience_orb", &[]);
}
@@ -5,6 +5,7 @@
use super::{Game, commands::compute::ComputeContext};
use horizon_client::{
items::ItemStack,
mobs::villager,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{position::BlockPos, random::RandomSource};
@@ -86,6 +87,82 @@ impl Game<'_> {
self.composter_add(pos, &layers);
(stack.count > 0).then_some(stack)
}
/// `WorkAtComposter.compostItems` for the villager at `mob`: a full
/// composter is emptied, then up to 20 wheat or beetroot seeds go in
/// (keeping 10 of each kind) until the composter reaches level 7. Level
/// event 1500 plays once, at the end.
pub(super) fn villager_compost_items(&mut self, mob: usize, pos: [i32; 3]) {
let at = BlockPos::new(pos[0], pos[1], pos[2]);
let Some(mut before) = self.composter_level(pos) else {
return;
};
if before == 8 {
self.with_level(|b, level, ticks| b.composter_extract(level, ticks, at));
let _ = self.process_level_events();
before = 0;
}
let mut remaining = 20;
let mut amounts: Vec<(std::sync::Arc<str>, i32)> = Vec::new();
let slots = villager::ext(&self.mobs[mob]).map_or(0, |e| e.inventory.len());
'slots: for slot in (0..slots).rev() {
if remaining <= 0 {
break;
}
let stack = villager::ext_mut(&mut self.mobs[mob]).inventory[slot].clone();
if !matches!(
&*stack.item,
"minecraft:wheat_seeds" | "minecraft:beetroot_seeds"
) {
continue;
}
let known = amounts.iter().position(|(item, _)| *item == stack.item);
let total = known.map_or(0, |k| amounts[k].1) + stack.count as i32;
match known {
Some(k) => amounts[k].1 = total,
None => amounts.push((stack.item.clone(), total)),
}
let uses = (total - 10).min(remaining).min(stack.count as i32);
if uses <= 0 {
continue;
}
remaining -= uses;
for _ in 0..uses {
self.villager_insert_item(mob, slot, &stack, pos);
if self.composter_level(pos) == Some(7) {
break 'slots;
}
}
}
let after = self.composter_level(pos).unwrap_or(before);
self.with_level(|b, level, ticks| {
b.composter_fill_effects(level, ticks, at, after != before)
});
let _ = self.process_level_events();
}
/// `ComposterBlock.insertItem` with a villager's stack: below level 7 a
/// compostable item is used up and may add a layer.
fn villager_insert_item(&mut self, mob: usize, slot: usize, stack: &ItemStack, pos: [i32; 3]) {
if self.composter_level(pos).is_none_or(|level| level >= 7) {
return;
}
let Some(layers) = self.compostable(stack) else {
return;
};
let context = ComputeContext {
block: Some(pos),
target: None,
};
let layers = self.provider_int(&layers, &context, 0).unwrap_or(0);
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| b.composter_layer(level, ticks, at, layers));
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
let _ = self.process_level_events();
let inventory = &mut villager::ext_mut(&mut self.mobs[mob]).inventory;
inventory[slot].count -= 1;
if inventory[slot].count == 0 {
inventory.remove(slot);
}
}
/// `ComposterBlock.handleFill` (level event 1500) on the client: the
/// fill sound and ten composter particles above the compost.
pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) {
@@ -628,6 +628,9 @@ impl Game<'_> {
// The port, or the game rules' search and number boxes.
Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
Screen::WorldOptions => self.world_options_text(Some(text)),
Screen::Inventory if self.mod_browser_typing() => {
self.mod_browser_text((text != "\\b").then_some(text), text == "\\b")
}
Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false)
}
+243 -34
View File
@@ -193,6 +193,7 @@ impl Game<'_> {
velocity: p.velocity,
yaw: self.yaw,
hero: self.potions.effects.get("hero_of_the_village").is_some(),
effects: self.potions.effects.list.iter().map(|e| e.id).collect(),
uuid: self.level.player_uuid.unwrap_or_default(),
allies: std::sync::Arc::new(self.player_allies()),
remote: false,
@@ -497,6 +498,8 @@ impl Game<'_> {
self.died.insert(m.id);
self.mob_died(&m);
}
// Their victims have been looted: no charged creeper is waiting any more.
self.combat.charged_exploders.clear();
let uuid = self.level.player_uuid;
let mut snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
let mut events = Vec::new();
@@ -779,7 +782,17 @@ impl Game<'_> {
.mobs
.iter()
.find(|o| o.id == id)
.map(|o| drops::loot_entity(o, None)),
.map(|o| drops::loot_entity(o, None))
// A charged creeper's blast kills after the creeper left the list.
.or_else(|| {
self.combat
.charged_exploders
.contains(&id)
.then(|| LootEntity {
powered: true,
..LootEntity::new("minecraft:creeper")
})
}),
None => None,
};
let direct = match d.kind {
@@ -815,12 +828,12 @@ impl Game<'_> {
world_seed: self.level.seed,
};
let (items, skulls) = drops::die(m, &death, &mut self.rand_sequences);
if skulls
&& let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker)
&& let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id)
{
if skulls && let Some(Who::Mob(id)) = m.last_damage.and_then(|(d, _)| d.attacker) {
// Creeper.droppedSkulls: one head per charged explosion.
creeper.extra.charged = false;
self.combat.charged_exploders.retain(|c| *c != id);
if let Some(creeper) = self.mobs.iter_mut().find(|o| o.id == id) {
creeper.extra.charged = false;
}
}
let raider = horizon_client::mobs::raider::is_raider(m.species());
for d in items {
@@ -838,6 +851,47 @@ impl Game<'_> {
}
}
}
/// `LivingEntity.dropFromGiftLootTable`: the gift table from its random
/// sequence with the mob as `this` (a chicken's egg depends on its
/// variant); the loot data of the game's resources decides, and without it
/// the items' table engine (no entity) rolls it.
fn drop_gift_loot(&mut self, mob: u32, table: &'static str, at: [f64; 3]) {
use horizon_client::mobs::drops;
use horizon_world::loot::EntityLootParams;
let loot = horizon_client::structure_blocks::loot_data(&self.options.resources);
let this = self
.mobs
.iter()
.find(|m| m.id == mob)
.map(|m| drops::loot_entity(m, None));
let stacks = match (loot, this) {
(Some(loot), Some(this)) if loot.has_table(table) => {
let params = EntityLootParams {
this,
..EntityLootParams::default()
};
let seed = self.level.seed;
match loot.random_sequence(table) {
Some(id) => {
let random = self.rand_sequences.get(id, seed);
loot.roll_entity(table, random, &params)
.iter()
.filter(|s| !s.is_empty())
.map(from_loot)
.collect()
}
None => Vec::new(),
}
}
_ => self
.res
.items()
.loot_table(table, false, None, &mut self.world.random),
};
for d in stacks {
self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
}
}
pub(super) fn handle_mob_events(&mut self, events: Vec<MobEvent>) -> Result<()> {
for e in events {
match e {
@@ -903,16 +957,24 @@ impl Game<'_> {
owner,
} => self.add_fangs(at, yaw, delay, owner),
MobEvent::Shoot(..) => {}
MobEvent::ExplosionSource { mob, charged } => {
self.combat.explosion_source = Some(mob);
if charged {
self.combat.charged_exploders.push(mob);
}
}
MobEvent::Explode(at, radius) => {
// The exploding mob causes the damage (Creeper.explodeCreeper).
let source_mob = self
.mobs
.iter()
.filter(|m| {
(m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) < 1.0
})
.map(|m| m.id)
.next();
let source_mob = self.combat.explosion_source.or_else(|| {
self.mobs
.iter()
.filter(|m| {
(m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2)
< 1.0
})
.map(|m| m.id)
.next()
});
if let Some(id) = source_mob {
self.note_attacker("minecraft:explosion", id);
}
@@ -943,6 +1005,9 @@ impl Game<'_> {
volume,
pitch,
);
} else {
// Left for the end of the tick.
t.outbox.push(event);
}
}
}
@@ -1045,6 +1110,40 @@ impl Game<'_> {
self.with_level(|b, level, ticks| b.set_door_open(level, ticks, pos, open));
self.process_level_events()?;
}
MobEvent::BreakDoor { pos } => {
// BreakDoorGoal.tick: removeBlock, then level events 1021
// and 2001 with the state that is there now.
let air = self.world.air;
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| b.set_block(level, ticks, at, air, 3));
self.process_level_events()?;
self.level_event_at(1021, pos, 0);
let left = self.world.block(pos[0], pos[1], pos[2]);
self.level_event_at(2001, pos, left.0 as i32);
}
MobEvent::DestroyProgress { mob, pos, progress } => {
self.destroy_block_progress(mob as i32, pos, progress);
// ServerLevel.destroyBlockProgress: every player nearby sees it.
if let Some(host) = self.lan.as_ref() {
host.hub.broadcast_near(
[f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])],
64.0,
&horizon_protocol::packets::play::Clientbound::BlockDestruction(
horizon_protocol::packets::play::BlockDestruction {
id: mob as i32,
pos,
progress: if (0..10).contains(&progress) {
progress as u8
} else {
255
},
},
),
None,
);
}
}
MobEvent::LevelEvent { id, pos, data } => self.level_event_at(id, pos, data),
MobEvent::SetBlockName { pos, name, effect } => {
if effect {
let old = self.world.block(pos[0], pos[1], pos[2]);
@@ -1199,6 +1298,10 @@ impl Game<'_> {
self.process_level_events()?;
}
MobEvent::DigParticles { at } => self.warden_dig_particles(at),
MobEvent::BlockBreakEffect { pos, block } => {
let state = self.world.block(block[0], block[1], block[2]);
self.destroy_particles(pos, state);
}
MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius),
MobEvent::CreakingHurt {
home,
@@ -1209,12 +1312,14 @@ impl Game<'_> {
self.creaking_tear_down(center, spread)
}
MobEvent::CureZombieVillager { mob } => self.cure_zombie_villager(mob),
MobEvent::Reinforcements { mob, target } => self.call_reinforcements(mob, target),
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
MobEvent::VillagerBirth {
parent,
partner,
child,
} => self.villager_birth(parent, partner, child),
MobEvent::WorkAtComposter { mob, pos } => self.villager_work_at_composter(mob, pos),
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
MobEvent::Firework { at, color, flight } => {
self.villager_firework(at, color, flight)
@@ -1235,19 +1340,51 @@ impl Game<'_> {
m.ai.aggressive |= aggressive;
}
}
MobEvent::GiftLoot { table, at } => {
let drops =
self.res
.items()
.loot_table(table, false, None, &mut self.world.random);
for d in drops {
self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
MobEvent::GiftLoot { mob, table, at } => {
// Turtle.ageBoundaryReached: only with mob loot on.
if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops")
{
continue;
}
self.drop_gift_loot(mob, table, at);
}
}
}
Ok(())
}
/// `TurtleEggBlock.randomTick` at the last hatch stage: one baby turtle
/// per egg, a day from grown, with the egg as its home (the sound, the
/// crumbs and the block's removal came from the level).
pub(super) fn hatch_turtles(
&mut self,
pos: [i32; 3],
state: horizon_world::registry::BlockStateId,
) {
let eggs = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("eggs"))
.and_then(|v| v.parse::<i32>().ok())
.unwrap_or(1);
for i in 0..eggs {
let at = [
f64::from(pos[0]) + 0.3 + f64::from(i) * 0.2,
f64::from(pos[1]),
f64::from(pos[2]) + 0.3,
];
if let Some(id) = self.spawn_mob("minecraft:turtle", at, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.extra.age = -24000;
m.extra.home = Some(pos);
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
}
}
}
fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) {
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
@@ -1310,6 +1447,8 @@ impl Game<'_> {
.unwrap_or_else(|| parent.clone());
let mut child = parent.clone();
child.baby = true;
// TurtleBreedGoal.breed triggers it without a child.
let turtle = p.species() == Species::Turtle;
if matches!(
(
p.species(),
@@ -1322,7 +1461,7 @@ impl Game<'_> {
) {
child.kind = "minecraft:mule".into();
}
self.trigger_bred(&parent, &partner_view, Some(&child));
self.trigger_bred(&parent, &partner_view, (!turtle).then_some(&child));
}
if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) {
q.extra.age = 6000;
@@ -1334,6 +1473,19 @@ impl Game<'_> {
self.lay_sniffer_egg(&p);
return;
}
// TurtleBreedGoal.breed: the goal gave the mother her egg; only the
// experience is left, and only with mob loot on.
if p.species() == Species::Turtle {
// One `new ExperienceOrb` of 1 to 7 from the mother's random (not
// split up as `ExperienceOrb.award` does).
if self.ui.rules.bool("mob_drops")
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent)
{
let xp = 1 + m.random.next_int_bound(7).unwrap_or(0) as u32;
self.add_orb([p.position.x, p.position.y, p.position.z], xp);
}
return;
}
let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
// A horse and a donkey have a mule.
@@ -1570,7 +1722,6 @@ impl Game<'_> {
r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]);
}
}
self.hurt_armor(amount);
// The thorns hurt the entity that caused the hit, if there is one.
if let Some(a) = attacker.or(owner) {
self.thorns(a);
@@ -2025,6 +2176,23 @@ impl Game<'_> {
self.creatures.projectiles.push(arrow);
}
}
/// `TargetBlock.onProjectileHit`: a target block takes its power from
/// where the projectile landed and resets after 20 ticks for an arrow, 8
/// for any other projectile. A player's shot counts as a target hit.
fn target_block_hit(&mut self, p: &Projectile, pos: [i32; 3], at: Vec3, face: [i32; 3]) {
let block = BlockPos::new(pos[0], pos[1], pos[2]);
let arrow = p.arrow.is_some();
let location = [at.x, at.y, at.z];
let hit = self.with_level(|b, level, ticks| {
b.target_projectile_hit(level, ticks, block, location, face, arrow)
});
if hit.is_some() {
let _ = self.process_level_events();
if p.owner == Some(Who::Player) {
self.stats.custom("target_hit", 1);
}
}
}
pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
self.combat.projectile_owner = match p.owner {
Some(Who::Mob(id)) => Some(id),
@@ -2034,6 +2202,13 @@ impl Game<'_> {
Hit::Entity { at, .. } | Hit::Block { at, .. } => at,
Hit::None => return Ok(()),
};
// Projectile.onHitBlock: BlockState.onProjectileHit, for every
// projectile (a wind charge out of the world's top has no face).
if let Hit::Block { pos, face, .. } = hit
&& face != [0; 3]
{
self.target_block_hit(p, pos, at, face);
}
if let Hit::Entity {
who: Who::Mob(id),
at,
@@ -2396,12 +2571,14 @@ impl Game<'_> {
// ShulkerBullet.onHitEntity: 4 damage, then levitation for 10 s.
(ProjectileKind::ShulkerBullet { .. }, Hit::Entity { who, .. }) => match who {
Who::Player => {
if !self.creative {
self.mob_hits_player(
// Only a hit that hurt (`wasHurt`) brings the levitation.
if !self.creative
&& self.mob_hits_player(
4.0,
[p.previous.x, p.previous.y, p.previous.z],
"minecraft:mob_projectile",
);
)
{
self.give_player_effect("minecraft:levitation", 200, 0);
}
}
@@ -2410,6 +2587,8 @@ impl Game<'_> {
&& m.damage(4.0, source)
{
m.extra.levitation = 200;
// Shulker.hurtServer: a shulker hit by a bullet.
horizon_client::mobs::shulker::hit_by_bullet(m);
}
}
},
@@ -2491,21 +2670,22 @@ impl Game<'_> {
.as_ref()
.map(|h| h.item.to_string())
.unwrap_or_default();
// Bucketable.bucketMobPickup: a water bucket scoops up a fish, a
// tadpole or an axolotl, with the data its bucket carries.
if item == "minecraft:water_bucket"
&& self.mobs[index].species() == Species::Axolotl
&& self.mobs[index].alive()
&& let Some((bucket, sound)) = bucketable(self.mobs[index].species())
{
let mut filled = ItemStack::new("minecraft:axolotl_bucket", 1);
let mut filled = ItemStack::new(bucket, 1);
filled.extra = Some(Box::new(horizon_client::entity_nbt::bucket_components(
&self.mobs[index],
)));
self.audio.play(
"minecraft:item.bucket.fill_axolotl",
Some(self.mobs[index].center()),
1.0,
1.0,
);
self.audio
.play(sound, Some(self.mobs[index].center()), 1.0, 1.0);
self.trigger_item("minecraft:filled_bucket", &filled);
// Leashable.dropLeash, then discard.
let id = self.mobs[index].id;
self.break_leash(id, true, false);
self.mobs[index].removed = true;
if self.creative {
if let Some(rest) = self.give(filled) {
@@ -2587,6 +2767,7 @@ impl Game<'_> {
let mut handled = true;
let mut drops: Vec<(String, u32)> = Vec::new();
let is_food = m.kind.food.contains(&item);
let baby_turtle = species == Species::Turtle && m.is_baby();
match species {
Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => {
give = Some("minecraft:milk_bucket");
@@ -2876,6 +3057,14 @@ impl Game<'_> {
if !handled {
return Ok(false);
}
// Turtle.ageBoundaryReached: food that finishes a baby's growth.
if baby_turtle && !self.mobs[index].is_baby() {
self.handle_mob_events(vec![MobEvent::GiftLoot {
mob: self.mobs[index].id,
table: "minecraft:gameplay/turtle_grow",
at: feet,
}])?;
}
self.swing_arm();
if let Some(s) = sound {
let pitch =
@@ -3309,6 +3498,26 @@ impl Game<'_> {
}
}
}
/// `Bucketable.getBucketItemStack` and `getPickupSound` of a mob that a water
/// bucket picks up.
fn bucketable(species: Species) -> Option<(&'static str, &'static str)> {
let fish = "minecraft:item.bucket.fill_fish";
Some(match species {
Species::Cod => ("minecraft:cod_bucket", fish),
Species::Salmon => ("minecraft:salmon_bucket", fish),
Species::Pufferfish => ("minecraft:pufferfish_bucket", fish),
Species::TropicalFish => ("minecraft:tropical_fish_bucket", fish),
Species::Tadpole => (
"minecraft:tadpole_bucket",
"minecraft:item.bucket.fill_tadpole",
),
Species::Axolotl => (
"minecraft:axolotl_bucket",
"minecraft:item.bucket.fill_axolotl",
),
_ => return None,
})
}
/// Mob.getBaseExperienceReward
/// The damage type id of a Horizon damage kind.
pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str {
@@ -6,6 +6,7 @@
//! finds the ammo for bows and crossbows.
use super::{Game, shield::OFFHAND_SLOT, view_vector};
use horizon_client::{
enchant::EffectContext,
items::ItemStack,
mobs::Who,
projectiles::{Projectile, ProjectileKind},
@@ -152,6 +153,20 @@ impl Game<'_> {
};
let charged = std::mem::take(&mut bow.data_mut().charged);
bow.tidy();
let weapon = bow.clone();
// AbstractArrow's constructor: `getPiercingCount` of the weapon.
let pierce = self
.res
.stations()
.enchantments
.modify_value(
Some(&weapon),
"minecraft:projectile_piercing",
&EffectContext::default(),
&mut self.world.random,
0.0,
)
.clamp(0.0, 127.0) as u8;
let count = charged.len();
// getShootingPower: a rocket among them slows every shot.
let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) {
@@ -204,6 +219,7 @@ impl Game<'_> {
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(ammo);
a.set_owner(Some(Who::Player));
a.pierce = pierce;
}
arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0);
self.creatures.projectiles.push(arrow);
@@ -1131,14 +1131,18 @@ impl Game<'_> {
let (p, v) = (b.position, b.velocity);
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
// A merged orb prints once per count, as the oracle does: whether orbs
// merge depends on entity ids, which differ from vanilla's.
for o in &self.orbs {
let (p, v) = (o.position, o.velocity);
out.push(line(
"minecraft:experience_orb",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
"",
));
for _ in 0..o.count.max(1) {
out.push(line(
"minecraft:experience_orb",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
"",
));
}
}
for c in &self.carts {
let (p, v) = (c.position, c.velocity);
@@ -3,10 +3,14 @@
//! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power
//! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`),
//! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and
//! the armor attribute effects (respiration, depth strider, ...).
//! the armor attribute effects (respiration, depth strider, ...) and Soul
//! Speed's `location_changed` and `tick` effects.
use super::Game;
use horizon_client::{enchant::EffectContext, items::ItemStack};
use horizon_core::random::RandomSource;
use horizon_client::{
enchant::{EffectContext, Enchantments, level_value},
items::ItemStack,
};
use horizon_core::{position::BlockPos, random::RandomSource};
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
#[derive(Clone, Copy)]
@@ -384,7 +388,9 @@ impl Game<'_> {
}
}
/// Bow enchantments at release: (extra base damage, infinity keeps the arrow).
pub(super) fn bow_enchantments(&mut self) -> (f64, bool) {
/// `ammo` is the item being fired: `Enchantment.itemContext` hands it to the
/// `ammo_use` conditions as the tool, so Infinity only frees plain arrows.
pub(super) fn bow_enchantments(&mut self, ammo: &str) -> (f64, bool) {
let Some(bow) = self.inventory[self.selected].clone() else {
return (0.0, false);
};
@@ -403,7 +409,7 @@ impl Game<'_> {
0.0,
);
let ammo_ctx = EffectContext {
tool: Some("minecraft:arrow"),
tool: Some(ammo),
items: Some(self.res.items()),
..Default::default()
};
@@ -456,6 +462,134 @@ impl Game<'_> {
}
ignite
}
/// Soul Speed (`data/minecraft/enchantment/soul_speed.json`), the parts of
/// `Enchantment.runLocationChangedEffects` and `tick` that file uses. The
/// `location_changed` effects run when the player enters a new block, lands,
/// or its boots change:
/// - the speed and movement efficiency modifiers turn on over a soul speed
/// block (not flying, not riding) and stay on while airborne, then off
/// (`enchantment_active_check`);
/// - the boots lose 1 durability with a 4% chance when on such a block.
///
/// Every fifth tick the player walking on one also gets a soul particle
/// (returned as its position and velocity, for the caller to show or send
/// to the players around) and sometimes a sound. Runs for the window's own
/// player and for each guest on the server (`guest_server_tick`); a remote
/// client leaves it to its server.
pub(super) fn tick_soul_speed(&mut self) -> Option<([f64; 3], [f64; 3])> {
const ID: &str = "minecraft:soul_speed";
let player = self.player.as_mut()?;
if player.client_side {
return None;
}
let level = self.armor[3]
.as_ref()
.map_or(0, |s| s.enchantment_level(ID));
let position = player.position;
let (on_ground, flying) = (player.ground.on_ground, player.flying);
let moved = position.subtract(player.old_position);
let (tick, width) = (player.health.tick_count, player.dimensions.width);
let fx = &mut player.location_effects;
let on_soul = fx.on_soul_speed_block;
let block = BlockPos::containing(position);
let changed_block = fx.block.replace(block) != Some(block);
let landed = std::mem::take(&mut fx.landed);
// Changed boots: `stopLocationBasedEffects`, then the effects run again.
let equipped = std::mem::replace(&mut fx.boots_level, level) != level;
let was_active = fx.applied_level;
let mut active = was_active > 0 && !equipped;
let mut wear = false;
if level > 0 && (changed_block || landed || equipped) {
let riding = self.riding.is_some();
let wanted = !riding && !flying && (on_soul || (active && !on_ground));
active = wanted;
// `random_chance` is the first term of the wear's `all_of`: it
// draws from the level random before the block is looked at.
let roll = self.world.random.next_float() < 0.04;
wear = roll && on_ground && on_soul;
}
fx.applied_level = if active { level } else { 0 };
// `Entity.getKnownMovement` horizontal speed of at least 1.0E-5.
let walking = moved.x * moved.x + moved.z * moved.z >= 1.0e-10;
let tick_effects = level > 0 && !flying && on_ground && walking && on_soul && tick % 5 == 0;
// The attribute effects were applied to the player before: swap them.
if was_active > 0 && (!active || equipped) {
for (attribute, id, _, op) in
soul_speed_modifiers(&self.res.stations().enchantments, was_active)
{
let _ = player.set_modifier(&attribute, &id, 0.0, &op, false);
}
}
if active && (was_active == 0 || equipped) {
for (attribute, id, amount, op) in
soul_speed_modifiers(&self.res.stations().enchantments, level)
{
let _ = player.set_modifier(&attribute, &id, amount, &op, true);
}
}
if wear && !self.creative {
self.wear_boots(1);
}
if level == 0 {
return None;
}
let r = &mut self.world.random;
// `spawn_particles`: in the bounding box, 0.1 above the feet, thrown
// back against the movement (-0.2) and up (0.1).
let particle = tick_effects.then(|| {
let x = position.x + (r.next_double() - 0.5) * f64::from(width);
let z = position.z + (r.next_double() - 0.5) * f64::from(width);
(
[x, position.y + 0.1, z],
[moved.x * -0.2, 0.1, moved.z * -0.2],
)
});
// `play_sound`: its `random_chance` (35%) comes first in its `all_of`,
// so the level random is drawn every tick the boots are worn; volume
// 0.6, pitch 0.6 to 1.0.
if r.next_float() < 0.35 && tick_effects {
let pitch = r.next_float() * 0.4 + 0.6;
self.audio.play(
"minecraft:particle.soul_escape",
Some([position.x, position.y, position.z]),
0.6,
pitch,
);
}
particle
}
/// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`):
/// Unbreaking applies, and they break when worn out.
fn wear_boots(&mut self, amount: u32) {
let Some(stack) = self.armor[3].clone() else {
return;
};
let loss = self.durability_loss(&stack, amount);
let max = self
.res
.items()
.get(&stack.item)
.map_or(0, |info| info.max_damage);
if max == 0 {
return;
}
let Some(boots) = self.armor[3].as_mut() else {
return;
};
boots.damage += loss;
if boots.damage >= max {
self.armor[3] = None;
if let Some(eye) = self.eye_position() {
self.audio.play(
"minecraft:entity.item.break",
Some(eye),
0.8,
0.8 + self.world.random.next_float() * 0.4,
);
}
self.apply_equipment();
}
}
/// Enchantment attribute modifiers of worn armor (respiration, depth strider...).
/// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`),
/// so the same enchantment on two pieces stacks instead of replacing itself.
@@ -479,3 +613,28 @@ impl Game<'_> {
self.potions.enchant_modifiers = wanted;
}
}
/// Soul Speed's `attribute` effects at `level` (attribute, id, amount, operation),
/// the id taking the boots slot like `EnchantmentAttributeEffect.idForSlot`.
fn soul_speed_modifiers(
enchantments: &Enchantments,
level: u32,
) -> Vec<(String, String, f64, String)> {
let Some(e) = enchantments.get("minecraft:soul_speed") else {
return Vec::new();
};
e.effects["minecraft:location_changed"][0]["effect"]["effects"]
.as_array()
.into_iter()
.flatten()
.filter(|a| a["type"] == "minecraft:attribute")
.map(|a| {
(
a["attribute"].as_str().unwrap_or("").to_owned(),
format!("{}/feet", a["id"].as_str().unwrap_or("")),
f64::from(level_value(&a["amount"], level)),
a["operation"].as_str().unwrap_or("add_value").to_owned(),
)
})
.collect()
}
+4 -4
View File
@@ -316,9 +316,6 @@ impl Game<'_> {
);
}
}
if outcome.hurt && !creative {
self.hurt_armor(amount);
}
if raised {
self.after_block(outcome, amount, None, false);
}
@@ -393,9 +390,11 @@ impl Game<'_> {
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
// The exploding mob is the damage source's entity, so victims
// it kills drop its charged-creeper loot (`Creeper.killedEntity`).
let source = horizon_client::mobs::Damage {
kind: horizon_client::mobs::DamageKind::Explosion,
attacker: None,
attacker: exploding.map(horizon_client::mobs::Who::Mob),
from: Some(center),
};
if hurtable && !m.damage(damage(dist, exposure), source) {
@@ -622,6 +621,7 @@ impl Game<'_> {
&mut self.world.random,
Some((&mut self.rand_sequences, self.level.seed)),
decay,
false,
);
for mut stack in drops {
if &*stack.item == "minecraft:air" || stack.count == 0 {
@@ -108,16 +108,10 @@ impl Game<'_> {
} else {
amount
};
let hurt = if let Some(p) = self.player.as_mut()
if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(kind)
{
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false)
} else {
false
};
if hurt {
self.hurt_armor(amount);
let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
}
}
}
+21 -9
View File
@@ -81,16 +81,28 @@ impl Game<'_> {
};
bite(self);
self.each_guest_hit(bite);
// `AbstractIllager.considersEntityAsAlly`: with no teams, the illager
// tag is allied; `Evoker.considersEntityAsAlly` adds a vex whose
// owner is allied (itself or another illager). Teams are not modelled.
let illager = |s: Species| {
matches!(
s,
Species::Evoker | Species::Illusioner | Species::Pillager | Species::Vindicator
)
};
let illagers: Vec<u32> = self
.mobs
.iter()
.filter(|m| illager(m.species()))
.map(|m| m.id)
.collect();
// A missing owner hurts everyone (`currentOwner == null`).
let owner_known = illagers.contains(&f.owner);
for m in &mut self.mobs {
let ally = matches!(
m.species(),
Species::Evoker
| Species::Illusioner
| Species::Vex
| Species::Pillager
| Species::Vindicator
| Species::Witch
);
let ally = owner_known
&& (illager(m.species())
|| m.species() == Species::Vex
&& illagers.contains(&(m.extra.counter2 as u32)));
if m.id != f.owner && !ally && m.alive() && m.bounds().intersects(b) {
m.damage(
6.0,
+2 -8
View File
@@ -372,17 +372,11 @@ impl Game<'_> {
if self.creative || self.spectator() {
return;
}
let hurt = if let Some(p) = self.player.as_mut()
if let Some(p) = self.player.as_mut()
&& !p.health.dead_or_dying()
&& let Some(id) = self.motion.health.damage.id("minecraft:fireworks")
{
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false)
} else {
false
};
if hurt {
self.hurt_armor(amount);
let _ = p.hurt(&self.motion.health, self.world.health_rules, id, amount);
}
}
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
+64 -35
View File
@@ -154,37 +154,54 @@ impl Game<'_> {
let mut damage = 0;
if let State::Hooked(id) = hook.state {
// pullEntity: 0.1 of the way to the owner.
let d = Vec3::new(
owner.x - hook.position.x,
owner.y - hook.position.y,
owner.z - hook.position.z,
);
let pulled = |v: Vec3| Vec3::new(v.x + d.x * 0.1, v.y + d.y * 0.1, v.z + d.z * 0.1);
let mut hooked_item = false;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
let d = Vec3::new(
owner.x - hook.position.x,
owner.y - hook.position.y,
owner.z - hook.position.z,
);
m.velocity = Vec3::new(
m.velocity.x + d.x * 0.1,
m.velocity.y + d.y * 0.1,
m.velocity.z + d.z * 0.1,
);
m.velocity = pulled(m.velocity);
} else if let Some(item) = self.dropped.iter_mut().find(|i| i.id == id) {
item.velocity = pulled(item.velocity);
hooked_item = true;
}
damage = 5;
// `hookedIn instanceof ItemEntity ? 3 : 5`.
damage = if hooked_item { 3 } else { 5 };
} else if hook.nibble > 0 {
let biome = self.biome_name_at(hook.position);
let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources)
else {
return damage;
};
// `withLuck(this.luck + owner.getLuck())`: the rod's Luck of the Sea
// plus the owner's luck attribute (the Luck and Bad Luck effects).
let owner_luck = self
.player
.as_mut()
.and_then(|p| p.attribute("minecraft:luck").ok())
.unwrap_or(0.0) as f32;
let mut random = self.world.random.clone();
let items = loot.roll(
"minecraft:gameplay/fishing",
&mut random,
hook.luck as f32,
hook.luck as f32 + owner_luck,
biome.as_deref(),
Some(hook.open_water),
);
self.world.random = random;
// FishingHook.retrieve: fish_caught for a catch.
self.stats.custom("fish_caught", 1);
for stack in items {
// FishingHook.retrieve: fish_caught for each catch in #minecraft:fishes.
if self
.res
.items()
.item_tags
.get("minecraft:fishes")
.is_some_and(|t| t.contains(stack.item.as_str()))
{
self.stats.custom("fish_caught", 1);
}
let mut item = ItemStack {
item: Arc::from(stack.item.as_str()),
count: stack.count.max(1) as u32,
@@ -457,35 +474,47 @@ impl Game<'_> {
self.hook = Some(h);
return;
}
// checkCollision: hook the first living mob it touches.
// checkCollision: hook the first living mob it touches, or (via
// `canHitEntity`) a dropped item.
let bb = bounds(h.position);
let (lo, hi) = (bb.min_position(), bb.max_position());
if let Some(m) = self.mobs.iter().find(|m| {
let mb = m.bounds();
let (a, z) = (mb.min_position(), mb.max_position());
m.alive()
&& a.x < hi.x
&& lo.x < z.x
&& a.y < hi.y
&& lo.y < z.y
&& a.z < hi.z
&& lo.z < z.z
}) {
h.state = State::Hooked(m.id);
let touches = |b: Aabb| {
let (a, z) = (b.min_position(), b.max_position());
a.x < hi.x && lo.x < z.x && a.y < hi.y && lo.y < z.y && a.z < hi.z && lo.z < z.z
};
let hit = self
.mobs
.iter()
.find(|m| m.alive() && touches(m.bounds()))
.map(|m| m.id)
.or_else(|| {
self.dropped
.iter()
.find(|i| touches(i.bounds()))
.map(|i| i.id)
});
if let Some(id) = hit {
h.state = State::Hooked(id);
h.velocity = Vec3::ZERO;
self.hook = Some(h);
return;
}
}
State::Hooked(id) => {
match self.mobs.iter().find(|m| m.id == id && m.alive()) {
Some(m) => {
h.position = Vec3::new(
m.position.x,
m.position.y + f64::from(m.height()) * 0.8,
m.position.z,
)
}
// updateHookedEntity: ride the hooked mob or item at 0.8 of its height.
let hooked = self
.mobs
.iter()
.find(|m| m.id == id && m.alive())
.map(|m| (m.position, f64::from(m.height())))
.or_else(|| {
self.dropped
.iter()
.find(|i| i.id == id)
.map(|i| (i.position, horizon_client::entities::ItemEntity::WIDTH))
});
match hooked {
Some((at, height)) => h.position = Vec3::new(at.x, at.y + height * 0.8, at.z),
None => h.state = State::Flying,
}
self.hook = Some(h);
+53 -22
View File
@@ -126,28 +126,7 @@ impl Game<'_> {
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
let mut finder = match self.player_spawn {
Some(finder) => finder,
None if self.level.game_mode == 2 => {
// Adventure mode: the suggestion itself.
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
finder.next_candidate();
finder
}
None => {
let mut radius = self.ui.rules.int("respawn_radius").max(0);
let to_border = self
.border
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
.floor() as i32;
if to_border < radius {
radius = to_border;
}
if to_border <= 1 {
radius = 1;
}
PlayerSpawnFinder::new(suggestion, radius, |n| {
entity_random().next_int_bound(n).unwrap_or(0)
})
}
None => self.spawn_finder(suggestion),
};
let found = loop {
let Some(candidate) = finder.next_candidate() else {
@@ -176,6 +155,58 @@ impl Game<'_> {
self.player_spawn = found.is_none().then_some(finder);
Ok(found)
}
/// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut
/// by the world border; the suggestion itself in adventure mode.
fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder {
if self.level.game_mode == 2 {
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
finder.next_candidate();
return finder;
}
let mut radius = self.ui.rules.int("respawn_radius").max(0);
let to_border = self
.border
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
.floor() as i32;
if to_border < radius {
radius = to_border;
}
if to_border <= 1 {
radius = 1;
}
PlayerSpawnFinder::new(suggestion, radius, |n| {
entity_random().next_int_bound(n).unwrap_or(0)
})
}
/// ServerPlayer.adjustSpawnLocation for a server's new player: where
/// PlayerSpawnFinder.findSpawn puts their feet around the world spawn
/// (`spawn`, the feet there), so that players new to a world don't all
/// stand in one spot. Vanilla waits for each candidate's chunk; a server
/// tick can't, so a candidate in a chunk not loaded yet is passed over,
/// and `spawn` stays when the search never reaches a loaded column.
pub(super) fn server_player_spawn(&self, spawn: [f64; 3]) -> [f64; 3] {
let suggestion = spawn.map(|v| v.floor() as i32);
let mut finder = self.spawn_finder(suggestion);
while let Some(candidate) = finder.next_candidate() {
let (x, z) = match candidate {
SpawnCandidate::Column(x, z) => (x, z),
SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
};
if !self.streaming.is_lit(x >> 4, z >> 4) {
continue;
}
let feet = match candidate {
SpawnCandidate::Column(x, z) => level_respawn_pos(&self.spawn_columns(), x, z)
.filter(|&pos| self.player_fits(pos))
.map(bottom_center),
SpawnCandidate::Suggestion => Some(self.fixup_spawn_height(suggestion)),
};
if let Some(feet) = feet {
return [feet.x, feet.y, feet.z];
}
}
spawn
}
/// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the
/// block's bottom centre touches no block or liquid.
fn player_fits(&self, pos: [i32; 3]) -> bool {
+27 -8
View File
@@ -24,11 +24,24 @@ use horizon_protocol::{
};
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
sync::{Arc, Mutex},
};
/// The registries and tags are the same for every world: load them once.
static SYNC: OnceLock<std::result::Result<Arc<SyncData>, String>> = OnceLock::new();
static SYNC: Mutex<Option<std::result::Result<Arc<SyncData>, String>>> = Mutex::new(None);
/// The registries and tags a server sends, loaded from `root` the first time.
pub(super) fn sync_data(root: &std::path::Path) -> std::result::Result<Arc<SyncData>, String> {
let mut sync = SYNC.lock().unwrap_or_else(|e| e.into_inner());
sync.get_or_insert_with(|| SyncData::load(root).map(Arc::new))
.clone()
}
/// Let go of what `sync_data` loaded: for a preload no world used
/// (game/world_loading.rs).
pub(super) fn forget_sync_data() {
*SYNC.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
/// The settings of the open world (WorldOptionsScreen's multiplayer section).
#[derive(Clone, Copy, Debug)]
@@ -574,10 +587,7 @@ impl Game<'_> {
config: HubConfig,
host: Option<u128>,
) -> Result<()> {
let root = self.options.resources.clone();
let sync = SYNC
.get_or_init(|| SyncData::load(&root).map(Arc::new))
.clone()?;
let sync = sync_data(&self.options.resources)?;
let biome_names: Vec<String> = self
.res
.biomes()
@@ -1140,8 +1150,17 @@ impl Game<'_> {
g.game_mode = default_mode;
}
if !known {
g.position = spawn;
g.previous_position = spawn;
// ServerPlayer.adjustSpawnLocation: a player new to the world
// stands where PlayerSpawnFinder puts them, not all on one spot
// (it reads the loaded level, which holds the spawn when it is
// the overworld).
let feet = if self.dim == super::Dim::Overworld {
self.server_player_spawn(spawn)
} else {
spawn
};
g.position = feet;
g.previous_position = feet;
g.health = 20.0;
g.food = 20;
g.dimension = super::Dim::Overworld.id().to_owned();
+22 -3
View File
@@ -2183,6 +2183,7 @@ impl Game<'_> {
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position;
let sneaking = g.sneaking;
let mut soul = None;
let events = self.as_guest(host, conn, |game| {
let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health;
@@ -2252,6 +2253,7 @@ impl Game<'_> {
w.player.shift_key_down = sneaking;
w.player.freeze_immune = freeze_immune;
let _ = w.server_block_damage(start);
let _ = w.update_soul_speed_block();
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
@@ -2279,6 +2281,9 @@ impl Game<'_> {
// LivingEntity.baseTick: outside the world border, then tickEffects.
game.border_damage();
game.tick_mob_effects();
// Soul Speed's effects (LivingEntity.baseTick's location_changed
// and tick effects); its particle goes to the players around.
soul = game.tick_soul_speed();
let Some(player) = game.player.as_mut() else {
return (Vec::new(), None);
};
@@ -2301,11 +2306,15 @@ impl Game<'_> {
let marked = std::mem::take(&mut player.health.sync_velocity);
let velocity = marked.then_some(player.velocity);
game.record_combat(&events);
game.wear_armor(&events);
(events, velocity)
});
let Some((events, marked)) = events else {
return;
};
if let Some((at, velocity)) = soul {
super::lan_particles::send_soul_particle(host, at, velocity);
}
self.as_guest(host, conn, |game| game.tick_player_sculk_events());
for event in events {
match event {
@@ -2394,9 +2403,13 @@ impl Game<'_> {
}
if (next / 10) % 2 == 0
&& !creative
&& let Some(elytra) = game.armor[1].as_mut()
&& let Some(stack) = game.armor[1].clone()
{
elytra.damage += 1;
// `ItemStack.hurtAndBreak`: Unbreaking can save the wear.
let loss = game.durability_loss(&stack, 1);
if let Some(elytra) = game.armor[1].as_mut() {
elytra.damage += loss;
}
}
let ctx = game.player_context(None);
game.post_game_event("minecraft:elytra_glide", at, ctx);
@@ -2659,7 +2672,13 @@ impl Game<'_> {
.random
.next_int_bound(touching.len() as i32)
.unwrap_or(0) as usize;
let orb = self.orbs.remove(touching[pick]);
// A merged orb gives its value once per count and goes at zero.
let orb = self.orbs[touching[pick]].clone();
if orb.count <= 1 {
self.orbs.remove(touching[pick]);
} else {
self.orbs[touching[pick]].count -= 1;
}
play.xp_delay = 2;
host.hub.take_item(orb.id as i32, id, 1, at);
// ClientPacketListener.handleTakeItemEntity's sound, at the orb.
@@ -370,6 +370,7 @@ mod tests {
velocity: Vec3::ZERO,
yaw: 0.0,
hero: false,
effects: Vec::new(),
uuid: [0; 4],
allies: Default::default(),
remote: false,
@@ -24,6 +24,35 @@ fn rgb(c: [f32; 4]) -> [f32; 3] {
[c[0], c[1], c[2]]
}
/// `ServerLevel.sendParticles` of one soul particle moving by `velocity`
/// (Soul Speed's `spawn_particles`): sent to the players within 32 blocks.
pub(super) fn send_soul_particle(host: &super::lan::LanHost, at: [f64; 3], velocity: [f64; 3]) {
let Some(id) = host
.hub
.registry_id("minecraft:particle_type", "minecraft:soul")
else {
return;
};
let packet = C::LevelParticles(play::LevelParticles {
particle: Particle { id, data: None },
override_limiter: false,
always_show: false,
pos: at,
dist: velocity.map(|v| v as f32),
max_speed: [1.0; 3],
count: 0,
randomization: 0,
});
for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
let distance: f64 = (0..3)
.map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
.sum();
if distance < 32.0 * 32.0 {
g.send(&packet);
}
}
}
impl Game<'_> {
/// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point.
/// Keep the local event's rendering; connected players receive one at rest.
+16
View File
@@ -109,6 +109,19 @@ pub(super) struct Levels {
parked: HashMap<Dim, Parked>,
}
impl Levels {
/// The chunks of each level not in place (capability `world` lends
/// them to server mods for a call).
#[cfg_attr(not(feature = "mods"), allow(dead_code))]
pub(super) fn parked_chunks(
&mut self,
) -> impl Iterator<Item = (Dim, &mut horizon_client::chunk_map::ChunkMap)> {
self.parked
.iter_mut()
.map(|(d, p)| (*d, &mut p.world.chunks))
}
}
impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result<Parked> {
@@ -225,6 +238,7 @@ impl Game<'_> {
swap(&mut a.pots, &mut b.pots);
swap(&mut a.gateways, &mut b.gateways);
swap(&mut a.gateway_servers, &mut b.gateway_servers);
swap(&mut a.conduit_servers, &mut b.conduit_servers);
self.raiding.swap_level(&mut p.raiding);
self.sculk.swap_level(&mut p.sculk);
self.creaking.swap_level(&mut p.creaking);
@@ -313,6 +327,8 @@ impl Game<'_> {
};
self.update_dedicated_streaming();
self.update_world();
// What server mods set in this level since its last tick.
self.apply_mod_block_writes();
result = if paused {
self.tick_lan(true);
Ok(())
+62 -2
View File
@@ -74,14 +74,74 @@ impl Game<'_> {
self.spawn_bolt(at, trap);
}
}
/// `findLightningTargetAround`: a living entity under open sky in the
/// column (3 blocks around), else the top of the column.
/// `ServerLevel.findLightningRod`: `PoiManager.findClosest` over the
/// lightning rod points of interest within 128 blocks of `center` whose
/// block is the top (`WORLD_SURFACE`) of its column; the strike lands one
/// above it. Horizon keeps no point-of-interest index, so this scans the
/// loaded chunks the way `/locate poi` does.
fn find_lightning_rod(&self, center: [i32; 3]) -> Option<[i32; 3]> {
const RANGE: i32 = 128;
let facts = self.res.facts();
let mut is_rod: std::collections::HashMap<u32, bool> = std::collections::HashMap::new();
let mut best: Option<(i64, [i32; 3])> = None;
let (cx0, cz0) = ((center[0] - RANGE) >> 4, (center[2] - RANGE) >> 4);
let (cx1, cz1) = ((center[0] + RANGE) >> 4, (center[2] + RANGE) >> 4);
for cx in cx0..=cx1 {
for cz in cz0..=cz1 {
let Some(chunk) = self.world.chunks.get(&(cx, cz)) else {
continue;
};
for (i, section) in chunk.sections.iter().enumerate() {
let mut rod = |state: u32| {
*is_rod.entry(state).or_insert_with(|| {
facts
.get(horizon_world::registry::BlockStateId(state))
.name
.ends_with("lightning_rod")
})
};
if !section.blocks.maybe_has(&mut rod) {
continue;
}
let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32;
for j in 0..4096 {
if !rod(section.get(j)) {
continue;
}
let p = [
cx * 16 + (j & 15) as i32,
base_y + (j >> 8) as i32,
cz * 16 + ((j >> 4) & 15) as i32,
];
let d = [p[0] - center[0], p[1] - center[1], p[2] - center[2]]
.map(|d| i64::from(d) * i64::from(d))
.iter()
.sum::<i64>();
if d > i64::from(RANGE * RANGE) || best.is_some_and(|(b, _)| d >= b) {
continue;
}
let surface = self.world.world_surface(p[0], p[2], |s| facts.is_air(s));
if p[1] == surface - 1 {
best = Some((d, p));
}
}
}
}
}
best.map(|(_, p)| [p[0], p[1] + 1, p[2]])
}
/// `findLightningTargetAround`: the closest lightning rod, else a living
/// entity under open sky in the column (3 blocks around), else the top of
/// the column.
fn lightning_target(&mut self, x: i32, z: i32) -> Option<[i32; 3]> {
if !self.world.loaded(x, z) {
return None;
}
let top =
self.with_level(|b, level, _| b.motion_blocking_top(level, BlockPos::new(x, 0, z)));
if let Some(rod) = self.find_lightning_rod([x, top.y, z]) {
return Some(rod);
}
let sees_sky = |g: &Self, p: [i32; 3]| g.world.light(p[0], p[1], p[2]) >> 4 == 15;
let mut candidates: Vec<[i32; 3]> = self
.mobs
@@ -0,0 +1,485 @@
//! Capability `ui`'s panel beside container screens (WIT `interface
//! browser`, docs/mods.md): the items a recipe viewer mod lists, drawn as
//! the game's own item slots in pages right of the screen's window, with a
//! search box under them. The mod says what the panel holds; the game pages
//! it and tells the mod what the player clicked, typed, and which of the
//! mod's keys went down over an item. With no mod showing a panel, each
//! hook here returns after one check.
use super::Game;
#[cfg(feature = "mods")]
use {
super::Screen,
horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
ui::EditBox,
},
horizon_mods::{BrowserClick, BrowserEvent, BrowserStack},
};
#[cfg(not(feature = "mods"))]
impl Game<'_> {
pub(super) fn draw_mod_browser(&mut self, _batch: &mut horizon_client::hud::HudBatch) {}
pub(super) fn mod_browser_press(&mut self, _right: bool) -> bool {
false
}
pub(super) fn mod_browser_typing(&self) -> bool {
false
}
pub(super) fn mod_browser_key(&mut self, _event: &winit::event::KeyEvent) {}
pub(super) fn mod_browser_text(&mut self, _text: Option<&str>, _backspace: bool) {}
pub(super) fn mod_browser_closed(&mut self) {}
}
/// One slot of the panel, in GUI pixels.
#[cfg(feature = "mods")]
const SLOT: f32 = 18.0;
/// The most columns the panel takes, and the fewest it shows with.
#[cfg(feature = "mods")]
const COLUMNS: (usize, usize) = (12, 2);
/// The gap between the window and the panel, and the screen's edges.
#[cfg(feature = "mods")]
const MARGIN: f32 = 8.0;
/// The panel's state in the game.
#[cfg(feature = "mods")]
#[derive(Default)]
pub(super) struct Browser {
/// The items' owner and version they were made from.
of: Option<(usize, u64)>,
/// The mod's items as stacks; `None` for an item the game doesn't have.
stacks: Vec<Option<ItemStack>>,
page: usize,
search: Option<EditBox>,
/// The search text the mod last heard.
sent: String,
/// `set-recipes`' recipes, shown instead of the items.
pub(super) recipes: Option<super::mod_browser_recipes::Pages>,
}
/// Where the panel's parts are this frame.
#[cfg(feature = "mods")]
pub(super) struct Layout {
/// The panel's whole area, for clicks that hit none of its parts.
pub(super) area: [f32; 4],
/// The grid's top left corner, its columns and rows.
pub(super) grid: (f32, f32),
pub(super) columns: usize,
pub(super) rows: usize,
/// The page arrows' row.
pub(super) arrows_y: f32,
pub(super) search: [f32; 4],
}
#[cfg(feature = "mods")]
impl Layout {
fn per_page(&self) -> usize {
self.columns * self.rows
}
pub(super) fn width(&self) -> f32 {
self.columns as f32 * SLOT
}
fn slot(&self, n: usize) -> (f32, f32) {
(
self.grid.0 + (n % self.columns) as f32 * SLOT,
self.grid.1 + (n / self.columns) as f32 * SLOT,
)
}
/// The page arrows: backward, then forward.
pub(super) fn arrows(&self) -> [(f32, f32); 2] {
[
(self.grid.0, self.arrows_y),
(self.grid.0 + self.width() - 12.0, self.arrows_y),
]
}
}
#[cfg(feature = "mods")]
pub(super) fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool {
p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h
}
#[cfg(feature = "mods")]
impl Game<'_> {
fn browser_batch(&self) -> Option<HudBatch> {
let r = self.renderer.as_ref()?;
Some(HudBatch::new([r.config.width, r.config.height]))
}
/// The mod showing a panel, with its items made into stacks once per
/// `set-items`; none while no mod shows one or no container screen is up.
fn browser_sync(&mut self) -> Option<usize> {
if self.screen != Screen::Inventory || self.title.is_some() {
return None;
}
let Some((owner, version)) = self.mods.mods.browser_items().map(|(o, v, _)| (o, v)) else {
self.mods.browser.of = None;
self.mods.browser.stacks.clear();
return None;
};
if self.mods.browser.of != Some((owner, version)) {
let items = self.res.items();
let stacks = self
.mods
.mods
.browser_items()
.map_or_else(Vec::new, |(_, _, list)| {
list.iter().map(|s| browser_stack(items, s)).collect()
});
self.mods.browser.stacks = stacks;
// The same title again (the mod updating its buttons) keeps the page.
let old = self.mods.browser.recipes.take();
self.mods.browser.recipes = self
.mods
.mods
.browser_recipes(owner)
.map(|shown| super::mod_browser_recipes::Pages::new(items, shown, old));
self.mods.browser.of = Some((owner, version));
}
Some(owner)
}
/// The panel's parts: right of the window, from the top of the screen to
/// the search box at its foot. None when the screen has no room for it.
fn browser_layout(&self, batch: &HudBatch) -> Option<Layout> {
let image = self.container_image(batch);
let left = (image.left + image.width) as f32 + MARGIN;
let right = batch.width - MARGIN;
let columns = (((right - left) / SLOT).floor().max(0.0) as usize).min(COLUMNS.0);
if columns < COLUMNS.1 {
return None;
}
let x = (left + (right - left - columns as f32 * SLOT) / 2.0).floor();
let arrows_y = MARGIN;
let top = arrows_y + 17.0 + 4.0;
let search = [x, batch.height - MARGIN - 16.0, columns as f32 * SLOT, 16.0];
let rows = ((search[1] - 4.0 - top) / SLOT).floor().max(0.0) as usize;
(rows > 0).then_some(Layout {
area: [left, 0.0, right - left, batch.height],
grid: (x, top),
columns,
rows,
arrows_y,
search,
})
}
fn browser_pages(&self, layout: &Layout) -> usize {
self.mods
.browser
.stacks
.len()
.div_ceil(layout.per_page())
.max(1)
}
/// The stack under the pointer on the panel, an item's or a recipe's,
/// as the mod sent it and as a stack.
fn browser_pointed_stack(&self, layout: &Layout) -> Option<(BrowserStack, ItemStack)> {
if self.mods.browser.recipes.is_some() {
if let Some((_, sent, stack)) = self.recipe_tab_hovered(layout) {
return Some((sent, stack));
}
let (_, _, sent, stack) = self.recipe_slot_hovered(layout)?;
return Some((sent, stack));
}
let (index, stack) = self.browser_hovered(layout)?;
let (_, _, items) = self.mods.mods.browser_items()?;
Some((items.get(index)?.clone(), stack))
}
/// The panel's item under the pointer: its index and stack.
fn browser_hovered(&self, layout: &Layout) -> Option<(usize, ItemStack)> {
if self.mods.browser.recipes.is_some() {
return None;
}
let first = self.mods.browser.page * layout.per_page();
(0..layout.per_page()).find_map(|n| {
let (x, y) = layout.slot(n);
if !inside(self.cursor, [x, y, SLOT, SLOT]) {
return None;
}
let stack = self.mods.browser.stacks.get(first + n)?.clone()?;
Some((first + n, stack))
})
}
fn browser_search(&mut self, layout: &Layout) -> &mut EditBox {
let search = self.mods.browser.search.get_or_insert_with(|| {
let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0);
edit.max_length = 50;
edit.focused = false;
edit
});
[search.x, search.y, search.width, search.height] = layout.search;
search
}
/// The items' page arrows and grid.
fn draw_browser_items(&mut self, batch: &mut HudBatch, layout: &Layout) {
let pages = self.browser_pages(layout);
self.mods.browser.page = self.mods.browser.page.min(pages - 1);
let page = self.mods.browser.page;
let cursor = self.cursor;
if pages > 1 {
let labels = [
self.translate("gui.recipebook.previous_page", "Previous Page"),
self.translate("gui.recipebook.next_page", "Next Page"),
];
let shown = [page > 0, page + 1 < pages];
let atlas = &self.gui.atlas;
for (((x, y), name), (label, shown)) in layout
.arrows()
.into_iter()
.zip(["page_backward", "page_forward"])
.zip(labels.iter().zip(shown))
{
if !shown {
continue;
}
let hover = inside(cursor, [x, y, 12.0, 17.0]);
let suffix = if hover { "_highlighted" } else { "" };
batch.sprite(
atlas,
&format!("gui/sprites/recipe_book/{name}{suffix}"),
x,
y,
);
horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true);
}
let text = format!("{}/{pages}", page + 1);
let w = HudBatch::text_width(atlas, &text);
let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor();
batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true);
}
let first = page * layout.per_page();
for n in 0..layout.per_page() {
let Some(stack) = self.mods.browser.stacks.get(first + n) else {
break;
};
let Some(stack) = stack.clone() else {
continue;
};
let (x, y) = layout.slot(n);
self.draw_item(batch, &stack, x + 1.0, y + 1.0);
let rect = [x + 1.0, y + 1.0, 16.0, 16.0];
if inside(cursor, [x, y, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + 1.0,
y + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&name,
rect,
true,
horizon_client::widgets::Kind::Button,
);
}
}
/// Draws the panel over the open container screen, then the carried
/// stack or the tooltip again so they stay on top of it.
pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) {
if self.browser_sync().is_none() {
return;
}
let Some(layout) = self.browser_layout(batch) else {
return;
};
let cursor = self.cursor;
if self.mods.browser.recipes.is_some() {
self.draw_browser_recipes(batch, &layout);
} else {
self.draw_browser_items(batch, &layout);
}
let hint = self.translate("gui.recipebook.search_hint", "Search...");
let search = self.browser_search(&layout);
// The hint shows in an empty box without focus, as the recipe book's.
search.suggestion = (search.value.is_empty() && !search.focused).then_some(hint);
let mut search = search.clone();
search.draw(batch, &self.gui.atlas, None);
self.mods.browser.search = Some(search);
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = self.browser_pointed_stack(&layout) {
let lines = self.stack_tooltip(&stack.1);
self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1);
} else {
self.draw_slot_tooltip(batch);
}
}
/// A mouse press on a container screen: true when the panel took it
/// (its search box, page arrows, items or empty space; a click there
/// never throws the carried stack).
pub(super) fn mod_browser_press(&mut self, right: bool) -> bool {
let Some(owner) = self.browser_sync() else {
return false;
};
let Some(batch) = self.browser_batch() else {
return false;
};
let Some(layout) = self.browser_layout(&batch) else {
return false;
};
let cursor = self.cursor;
let shift = self.has_shift_down();
let atlas = &self.gui.atlas;
let search = self.mods.browser.search.get_or_insert_with(|| {
let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0);
edit.max_length = 50;
edit
});
[search.x, search.y, search.width, search.height] = layout.search;
if inside(cursor, layout.search) {
search.focused = true;
search.click(atlas, cursor.0, shift, false);
search.reset_blink();
return true;
}
search.focused = false;
if self.mods.browser.recipes.is_some() {
return self.browser_recipes_press(&layout, owner, right)
|| inside(cursor, layout.area);
}
let pages = self.browser_pages(&layout);
let page = self.mods.browser.page;
let [back, forward] = layout.arrows();
let step = if pages > 1 && page > 0 && inside(cursor, [back.0, back.1, 12.0, 17.0]) {
Some(page - 1)
} else if pages > 1
&& page + 1 < pages
&& inside(cursor, [forward.0, forward.1, 12.0, 17.0])
{
Some(page + 1)
} else {
None
};
if let Some(to) = step {
self.mods.browser.page = to;
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
return true;
}
if let Some((index, _)) = self.browser_hovered(&layout) {
let event = BrowserEvent::Clicked(BrowserClick {
index: index as u32,
right,
});
self.mods.mods.browser_event(owner, event);
return true;
}
inside(cursor, layout.area)
}
/// Whether keys go to the panel's search box.
pub(super) fn mod_browser_typing(&self) -> bool {
self.screen == Screen::Inventory
&& self.mods.browser.of.is_some()
&& self.mods.browser.search.as_ref().is_some_and(|s| s.focused)
}
/// A key press while the search box has focus.
pub(super) fn mod_browser_key(&mut self, event: &winit::event::KeyEvent) {
use winit::keyboard::PhysicalKey;
let shortcut = self.edit_shortcut(event);
let ctrl = self.has_control_down();
let shift = self.has_shift_down();
let Some(search) = self.mods.browser.search.as_mut() else {
return;
};
if let Some(shortcut) = shortcut {
search.shortcut(shortcut, &mut self.clipboard);
} else {
let handled = match event.physical_key {
PhysicalKey::Code(code) => search.key(code, ctrl, shift),
_ => false,
};
if !handled
&& !ctrl
&& let Some(text) = &event.text
{
let text: String = text.chars().filter(|c| !c.is_control()).collect();
search.insert_text(&text);
}
}
search.reset_blink();
self.browser_searched();
}
/// Text typed (or one backspace) into the search box (`horizon-ctl type`).
pub(super) fn mod_browser_text(&mut self, text: Option<&str>, backspace: bool) {
let Some(search) = self.mods.browser.search.as_mut() else {
return;
};
if backspace {
search.delete_chars(-1);
} else if let Some(text) = text {
search.insert_text(text);
}
self.browser_searched();
}
/// The mod hears the search text when it changed.
fn browser_searched(&mut self) {
let (Some((owner, _)), Some(search)) = (self.mods.browser.of, &self.mods.browser.search)
else {
return;
};
if search.value != self.mods.browser.sent {
let value = search.value.clone();
self.mods.browser.sent.clone_from(&value);
self.mods.browser.page = 0;
self.mods
.mods
.browser_event(owner, BrowserEvent::Search(value));
}
}
/// The container screen closed: the search box lets go of the keys.
pub(super) fn mod_browser_closed(&mut self) {
if let Some(search) = self.mods.browser.search.as_mut() {
search.focused = false;
}
}
/// The item under the pointer on a container screen, for the mods' keys
/// (`browser`'s `key` event): the panel's, else a slot's.
pub(super) fn mod_browser_pointed(&mut self) -> Option<BrowserStack> {
let batch = self.browser_batch()?;
let stack = match self
.browser_sync()
.and_then(|_| self.browser_layout(&batch))
{
// The panel's stacks as the mod sent them.
Some(layout) if inside(self.cursor, layout.area) => {
return Some(self.browser_pointed_stack(&layout)?.0);
}
_ => {
let slot = self.slot_at(&batch, self.cursor.0, self.cursor.1)?;
self.slot_view(slot)?
}
};
Some(BrowserStack {
item: stack.item.to_string(),
count: stack.count,
components: super::mod_recipes::components(&stack),
})
}
}
/// A mod's item as a stack: an item the game has, its components read as
/// `/give` reads them (ones it can't read are left out).
#[cfg(feature = "mods")]
pub(super) fn browser_stack(
items: &horizon_client::items::Items,
s: &BrowserStack,
) -> Option<ItemStack> {
items.get(&s.item)?;
let (damage, extra) = if s.components.is_empty() {
(0, None)
} else {
horizon_client::item_data::command_components(&s.components).map_or((0, None), |tag| {
horizon_client::item_data::decode_components(Some(&tag))
})
};
Some(ItemStack {
item: s.item.as_str().into(),
count: s.count.clamp(1, 99),
damage,
extra,
})
}
@@ -0,0 +1,523 @@
//! `browser.set-recipes` (docs/mods.md): a mod's recipes shown in its item
//! panel's place, laid out by the game with its own slots, arrows and
//! buttons, paged to the panel's height, under a title and a back button.
//! The mod hears clicks on their slots, their action buttons, the back
//! button and page turns.
use super::{
Game,
mod_browser::{Layout, browser_stack, inside},
};
use horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
};
use horizon_mods::{BrowserEvent, BrowserLayout, BrowserSlotClick, BrowserStack, RecipePage};
use std::time::Instant;
const SLOT: f32 = 18.0;
/// The title row's height, and the gap under each recipe.
const TITLE: f32 = 18.0;
/// A tab's step: an 18 px slot and a gap.
const TAB: f32 = 20.0;
const GAP: f32 = 6.0;
/// One recipe as the game draws it.
pub(super) struct Shown {
layout: BrowserLayout,
width: usize,
height: usize,
/// Each slot's stacks (the result last), as the mod sent them and as
/// stacks; a stack the game doesn't have is left out of the cycle.
slots: Vec<Vec<(BrowserStack, ItemStack)>>,
note: String,
action: Option<bool>,
}
/// The recipes a panel shows, and its page.
pub(super) struct Pages {
title: String,
/// The tabs' icons and the selected one.
tabs: Vec<(BrowserStack, Option<ItemStack>)>,
tab: usize,
recipes: Vec<Shown>,
page: usize,
since: Instant,
}
impl Pages {
pub(super) fn new(
items: &horizon_client::items::Items,
shown: &RecipePage,
old: Option<Pages>,
) -> Self {
let (title, list, tab) = (&shown.title, &shown.recipes, shown.tab as usize);
let kept = old.filter(|o| o.title == *title && o.tab == tab);
let cycle = |stacks: &[BrowserStack]| -> Vec<(BrowserStack, ItemStack)> {
stacks
.iter()
.filter_map(|s| Some((s.clone(), browser_stack(items, s)?)))
.collect()
};
let recipes = list
.iter()
.map(|r| {
let mut slots: Vec<_> = r.slots.iter().map(|s| cycle(s)).collect();
slots.push(cycle(&r.results));
Shown {
layout: r.layout,
width: r.width as usize,
height: r.height as usize,
slots,
note: r.note.clone(),
action: r.action,
}
})
.collect();
Self {
title: title.clone(),
tabs: shown
.tabs
.iter()
.map(|t| (t.clone(), browser_stack(items, t)))
.collect(),
tab,
recipes,
page: kept.as_ref().map_or(0, |o| o.page),
since: kept.map_or_else(Instant::now, |o| o.since),
}
}
}
impl Shown {
/// The inputs' block: its size and each input slot's place in it.
fn inputs(&self) -> ((f32, f32), Vec<(f32, f32)>) {
let row = |n: usize| (0..n).map(|i| (i as f32 * SLOT, 0.0)).collect();
match self.layout {
BrowserLayout::Grid => {
let (w, h) = (self.width.max(1), self.height.max(1));
let at = (0..w * h)
.map(|i| ((i % w) as f32 * SLOT, (i / w) as f32 * SLOT))
.collect();
((w as f32 * SLOT, h as f32 * SLOT), at)
}
// The input over the flame.
BrowserLayout::Cooking => ((SLOT, 2.0 * SLOT), vec![(0.0, 0.0)]),
BrowserLayout::Single => ((SLOT, SLOT), row(1)),
BrowserLayout::Smithing => ((3.0 * SLOT, SLOT), row(3)),
BrowserLayout::Brewing => ((2.0 * SLOT, SLOT), row(2)),
}
}
/// The height of its slots, arrow and button, `room` wide.
fn block(&self, room: f32) -> f32 {
let h = self.inputs().0.1;
let (_, _, action) = self.places(room);
match self.action {
Some(_) => h.max(action.1 + 12.0),
None => h,
}
}
fn height(&self, room: f32) -> f32 {
let note = if self.note.is_empty() { 0.0 } else { 11.0 };
self.block(room) + note + GAP
}
/// Every slot's place from the recipe's corner (the result last), the
/// arrow's and the action button's: beside the result, or under it
/// when the panel is `room` wide and that doesn't fit.
fn places(&self, room: f32) -> (Vec<(f32, f32)>, (f32, f32), (f32, f32)) {
let ((w, h), mut at) = self.inputs();
// The mod's slots beyond the layout's are not shown.
at.truncate(self.slots.len() - 1);
let arrow = (w + 4.0, ((h - 16.0) / 2.0).floor());
let result = (w + 32.0, ((h - SLOT) / 2.0).floor());
let action = if result.0 + SLOT + 16.0 <= room {
(result.0 + SLOT + 4.0, ((h - 12.0) / 2.0).floor())
} else {
(result.0 + 3.0, result.1 + SLOT + 2.0)
};
while at.len() < self.slots.len() - 1 {
at.push((f32::NAN, f32::NAN));
}
at.push(result);
(at, arrow, action)
}
}
/// The tabs' places, in rows under the title row.
fn tab_places(pages: &Pages, layout: &Layout) -> Vec<(f32, f32)> {
let per_row = ((layout.width() / TAB).floor() as usize).max(1);
(0..pages.tabs.len())
.map(|i| {
(
layout.grid.0 + (i % per_row) as f32 * TAB,
layout.grid.1 + TITLE + 3.0 + (i / per_row) as f32 * TAB,
)
})
.collect()
}
/// Where the recipes start: under the title row and the tabs.
fn recipes_top(pages: &Pages, layout: &Layout) -> f32 {
let tabs = tab_places(pages, layout);
tabs.last()
.map_or(layout.grid.1 + TITLE, |&(_, y)| y + TAB + 3.0)
}
impl Game<'_> {
/// The first recipe of each page, filling the panel from the tabs to
/// the search box.
fn recipe_pages(pages: &Pages, layout: &Layout) -> Vec<usize> {
let room = layout.search[1] - 4.0 - recipes_top(pages, layout);
let mut starts = vec![0];
let mut used = 0.0;
for (i, r) in pages.recipes.iter().enumerate() {
let h = r.height(layout.width());
if used > 0.0 && used + h > room {
starts.push(i);
used = 0.0;
}
used += h;
}
starts
}
/// The recipes on the open page, each with its corner.
fn recipes_shown(&self, layout: &Layout) -> Vec<(usize, (f32, f32))> {
let Some(pages) = &self.mods.browser.recipes else {
return Vec::new();
};
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let end = starts.get(page + 1).copied().unwrap_or(pages.recipes.len());
let mut y = recipes_top(pages, layout);
(starts[page]..end)
.map(|i| {
let at = (layout.grid.0, y);
y += pages.recipes[i].height(layout.width());
(i, at)
})
.collect()
}
fn back_button(&self, layout: &Layout) -> ([f32; 4], String) {
let label = self.translate("gui.back", "Back");
let w = HudBatch::text_width(&self.gui.atlas, &label) + 8.0;
([layout.grid.0, layout.grid.1, w, 14.0], label)
}
/// What a slot of a shown recipe holds now: its stacks cycle once a second.
fn recipe_slot_now(&self, recipe: usize, slot: usize) -> Option<&(BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
let stacks = pages.recipes.get(recipe)?.slots.get(slot)?;
let n = pages.since.elapsed().as_secs() as usize;
stacks.get(n % stacks.len().max(1))
}
/// The tab under the pointer: its index and icon.
pub(super) fn recipe_tab_hovered(
&self,
layout: &Layout,
) -> Option<(usize, BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
let places = tab_places(pages, layout);
places.iter().enumerate().find_map(|(i, &(x, y))| {
if !inside(self.cursor, [x, y, SLOT, SLOT]) {
return None;
}
let (sent, stack) = pages.tabs.get(i)?;
Some((i, sent.clone(), stack.clone()?))
})
}
/// The recipe slot under the pointer: recipe, slot, and its stack now.
pub(super) fn recipe_slot_hovered(
&self,
layout: &Layout,
) -> Option<(usize, usize, BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
self.recipes_shown(layout)
.into_iter()
.find_map(|(i, (x, y))| {
let (at, _, _) = pages.recipes[i].places(layout.width());
at.iter().enumerate().find_map(|(k, &(sx, sy))| {
if !inside(self.cursor, [x + sx, y + sy, SLOT, SLOT]) {
return None;
}
let (mod_stack, stack) = self.recipe_slot_now(i, k)?.clone();
Some((i, k, mod_stack, stack))
})
})
}
/// Draws the title row, the page's recipes and the page arrows.
pub(super) fn draw_browser_recipes(&mut self, batch: &mut HudBatch, layout: &Layout) {
let Some(pages) = &self.mods.browser.recipes else {
return;
};
let cursor = self.cursor;
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let (title, pages_n) = (pages.title.clone(), starts.len());
let (back, label) = self.back_button(layout);
let atlas = &self.gui.atlas;
let hover = inside(cursor, back);
let sprite = if hover {
"gui/sprites/widget/button_highlighted"
} else {
"gui/sprites/widget/button"
};
horizon_client::ui::nine_slice(
batch,
atlas,
sprite,
back[0],
back[1],
back[2],
back[3],
u32::MAX,
);
batch.text(atlas, &label, back[0] + 4.0, back[1] + 3.0, u32::MAX, true);
horizon_client::widgets::record(&label, back, true);
let room = layout.width() - back[2] - 4.0;
// Cut to the panel with vanilla's ellipsis (CommonComponents.ELLIPSIS).
let shown = if atlas.font.fit(&title, room) >= title.chars().count() {
title
} else {
let fit = atlas.font.fit(&title, room - atlas.font.width("..."));
let kept: String = title.chars().take(fit).collect();
format!("{}...", kept.trim_end())
};
batch.text(
atlas,
&shown,
back[0] + back[2] + 4.0,
back[1] + 3.0,
u32::MAX,
true,
);
self.draw_recipe_tabs(batch, layout);
if pages_n > 1 {
let labels = [
self.translate("gui.recipebook.previous_page", "Previous Page"),
self.translate("gui.recipebook.next_page", "Next Page"),
];
let visible = [page > 0, page + 1 < pages_n];
let atlas = &self.gui.atlas;
for (((x, y), name), (label, visible)) in layout
.arrows()
.into_iter()
.zip(["page_backward", "page_forward"])
.zip(labels.iter().zip(visible))
{
if !visible {
continue;
}
let suffix = if inside(cursor, [x, y, 12.0, 17.0]) {
"_highlighted"
} else {
""
};
batch.sprite(
atlas,
&format!("gui/sprites/recipe_book/{name}{suffix}"),
x,
y,
);
horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true);
}
let text = format!("{}/{pages_n}", page + 1);
let w = HudBatch::text_width(atlas, &text);
let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor();
batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true);
}
for (i, (x, y)) in self.recipes_shown(layout) {
let Some(r) = self.mods.browser.recipes.as_ref().map(|p| &p.recipes[i]) else {
break;
};
let (at, arrow, action) = r.places(layout.width());
let h = r.block(layout.width());
let (cooking, note, button) =
(r.layout == BrowserLayout::Cooking, r.note.clone(), r.action);
let atlas = &self.gui.atlas;
for &(sx, sy) in at.iter().filter(|p| p.0.is_finite()) {
batch.sprite(atlas, "gui/sprites/container/slot", x + sx, y + sy);
}
if cooking {
batch.sprite(
atlas,
"gui/sprites/container/furnace/lit_progress",
x + 2.0,
y + SLOT + 2.0,
);
}
batch.sprite(
atlas,
"gui/sprites/container/furnace/burn_progress",
x + arrow.0,
y + arrow.1,
);
if let Some(enabled) = button {
let rect = [x + action.0, y + action.1, 12.0, 12.0];
let sprite = match (enabled, inside(cursor, rect)) {
(false, _) => "gui/sprites/widget/button_disabled",
(true, true) => "gui/sprites/widget/button_highlighted",
(true, false) => "gui/sprites/widget/button",
};
horizon_client::ui::nine_slice(
batch,
atlas,
sprite,
rect[0],
rect[1],
12.0,
12.0,
u32::MAX,
);
let color = if enabled {
u32::MAX
} else {
rgba(160, 160, 160, 255)
};
batch.text(atlas, "+", rect[0] + 3.0, rect[1] + 2.0, color, true);
horizon_client::widgets::record(&format!("+ {i}"), rect, enabled);
}
if !note.is_empty() {
batch.text(atlas, &note, x, y + h + 2.0, rgba(224, 224, 224, 255), true);
}
for (k, &(sx, sy)) in at.iter().enumerate().filter(|(_, p)| p.0.is_finite()) {
let Some((_, stack)) = self.recipe_slot_now(i, k).cloned() else {
continue;
};
self.draw_item(batch, &stack, x + sx + 1.0, y + sy + 1.0);
if inside(cursor, [x + sx, y + sy, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + sx + 1.0,
y + sy + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&format!("{name} {i}:{k}"),
[x + sx + 1.0, y + sy + 1.0, 16.0, 16.0],
true,
horizon_client::widgets::Kind::Button,
);
}
}
}
/// The tabs, on slots; the selected one framed.
fn draw_recipe_tabs(&mut self, batch: &mut HudBatch, layout: &Layout) {
let Some(pages) = &self.mods.browser.recipes else {
return;
};
let places = tab_places(pages, layout);
let tabs: Vec<Option<ItemStack>> = pages.tabs.iter().map(|t| t.1.clone()).collect();
let selected = pages.tab;
for (i, (&(x, y), stack)) in places.iter().zip(tabs).enumerate() {
let atlas = &self.gui.atlas;
batch.sprite(atlas, "gui/sprites/container/slot", x, y);
let Some(stack) = stack else {
continue;
};
self.draw_item(batch, &stack, x + 1.0, y + 1.0);
// The selected tab: a white frame around its slot.
if i == selected {
let white = rgba(255, 255, 255, 255);
let atlas = &self.gui.atlas;
batch.fill(atlas, x - 1.0, y - 1.0, SLOT + 2.0, 1.0, white);
batch.fill(atlas, x - 1.0, y + SLOT, SLOT + 2.0, 1.0, white);
batch.fill(atlas, x - 1.0, y, 1.0, SLOT, white);
batch.fill(atlas, x + SLOT, y, 1.0, SLOT, white);
}
if inside(self.cursor, [x, y, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + 1.0,
y + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&format!("{name} tab"),
[x + 1.0, y + 1.0, 16.0, 16.0],
true,
horizon_client::widgets::Kind::Tab(i == selected),
);
}
}
/// A press on the recipes: true when it hit one of their parts.
pub(super) fn browser_recipes_press(
&mut self,
layout: &Layout,
owner: usize,
right: bool,
) -> bool {
let Some(pages) = &self.mods.browser.recipes else {
return false;
};
let cursor = self.cursor;
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let [back_arrow, forward] = layout.arrows();
let turn = if page > 0 && inside(cursor, [back_arrow.0, back_arrow.1, 12.0, 17.0]) {
Some(page - 1)
} else if page + 1 < starts.len() && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) {
Some(page + 1)
} else {
None
};
if let Some(to) = turn {
if let Some(p) = self.mods.browser.recipes.as_mut() {
p.page = to;
}
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Page(starts[to] as u32));
return true;
}
if let Some((tab, _, _)) = self.recipe_tab_hovered(layout) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Tab(tab as u32));
return true;
}
if inside(cursor, self.back_button(layout).0) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods.mods.browser_event(owner, BrowserEvent::Back);
return true;
}
if let Some((recipe, slot, stack, _)) = self.recipe_slot_hovered(layout) {
let event = BrowserEvent::SlotClicked(BrowserSlotClick {
recipe: recipe as u32,
slot: slot as u32,
stack,
right,
});
self.mods.mods.browser_event(owner, event);
return true;
}
let action = self.recipes_shown(layout).into_iter().find(|&(i, (x, y))| {
let r = &pages.recipes[i];
let (_, _, (ax, ay)) = r.places(layout.width());
r.action.is_some() && inside(cursor, [x + ax, y + ay, 12.0, 12.0])
});
if let Some((i, _)) = action {
if pages.recipes[i].action == Some(true) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Action(i as u32));
}
return true;
}
false
}
}
@@ -111,6 +111,18 @@ impl Game<'_> {
if repeat || !self.mods.mods.has_keys() {
return;
}
// Over an item on a container screen, the mods' keys are `browser`
// events (a recipe viewer's R and U).
if pressed
&& self.screen == Screen::Inventory
&& self.title.is_none()
&& !self.mod_browser_typing()
&& let Some(name) = horizon_client::keybinds::key_name(key)
&& let Some(stack) = self.mod_browser_pointed()
{
self.mods.mods.browser_key(name, &stack);
return;
}
if pressed && (self.screen != Screen::Playing || self.title.is_some()) {
return;
}
@@ -0,0 +1,274 @@
//! Capability `recipes` (docs/mods.md): every item and recipe the game
//! knows, made once for the mods that read them, and the recipe book's
//! known displays. The recipes are the window's own data: the world's in
//! single player, vanilla's on a server (a client is sent no others), while
//! the known displays follow the server's book as the recipe book does.
use super::Game;
use horizon_client::{
crafting::Ingredient,
items::ItemStack,
recipe_book::{Category, Display},
stations::Smithing,
};
use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes};
use std::{collections::HashMap, sync::Arc};
/// Item id -> its index in [`Recipes::items`].
struct Index(HashMap<Arc<str>, u32>);
impl Index {
fn stack(&self, item: &str, count: u32, components: String) -> Option<RecipeStack> {
Some(RecipeStack {
item: *self.0.get(item)?,
count,
components,
})
}
fn of(&self, s: &ItemStack) -> Option<RecipeStack> {
self.stack(&s.item, s.count, components(s))
}
fn any(&self, i: &Ingredient) -> Vec<RecipeStack> {
i.1.iter()
.filter_map(|id| self.stack(id, 1, String::new()))
.collect()
}
}
/// A stack's components beyond its item's, as vanilla's item syntax writes
/// them (`[minecraft:potion_contents={potion:"minecraft:swiftness"}]`), or "".
pub(super) fn components(s: &ItemStack) -> String {
use horizon_world::nbt::Tag;
let Some(Tag::Compound(entries)) = horizon_client::item_data::encode_components(s) else {
return String::new();
};
let parts: Vec<String> = entries
.iter()
.map(|(k, v)| {
format!(
"{}={}",
k.to_string_lossy(),
horizon_client::snbt::to_snbt(v)
)
})
.collect();
format!("[{}]", parts.join(","))
}
fn recipe(id: String, kind: RecipeKind) -> Recipe {
Recipe {
id,
kind,
category: String::new(),
group: String::new(),
width: 0,
height: 0,
slots: Vec::new(),
results: Vec::new(),
cooking_time: 0,
experience: 0.0,
book_id: -1,
}
}
impl Game<'_> {
/// `recipes.give`: a creative player takes the stack as from the
/// creative inventory; a server hears it as `SetCreativeModeSlot`
/// through the inventory's sync, and refuses it unless creative.
pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) {
let Some(max) = self.res.items().get(item).map(|i| i.max_stack) else {
return;
};
if !self.creative {
return;
}
let (damage, extra) = horizon_client::item_data::command_components(components)
.map_or((0, None), |tag| {
horizon_client::item_data::decode_components(Some(&tag))
});
let _ = self.give(ItemStack {
item: item.into(),
// One stack at most, as the creative inventory hands out.
count: count.min(max),
damage,
extra,
});
}
/// Capability `recipes`'s tables and known displays for this tick's
/// snapshot; nothing while no running mod reads them.
pub(super) fn mod_recipes(&mut self) -> (Option<Arc<Recipes>>, Arc<[i32]>) {
if !self.mods.mods.wants_recipes() {
return (None, Arc::from([]));
}
if self.mods.recipes.is_none() {
self.mods.recipes = Some(Arc::new(self.make_mod_recipes()));
}
let (version, known) = self.recipe_book_displays();
if self.mods.known_recipes.0 != Some(version) {
self.mods.known_recipes = (Some(version), known.into());
}
(self.mods.recipes.clone(), self.mods.known_recipes.1.clone())
}
fn make_mod_recipes(&mut self) -> Recipes {
let names = &self.pack.names;
let items = self.res.items();
let mut tags: HashMap<&str, Vec<String>> = HashMap::new();
for (tag, members) in &items.item_tags {
for m in members {
tags.entry(m).or_default().push(tag.clone());
}
}
let table: Vec<RecipeItem> = items
.registry_order
.iter()
.map(|id| RecipeItem {
id: id.to_string(),
name: names.display_item(id),
tags: tags.remove(&**id).map_or_else(Vec::new, |mut t| {
t.sort();
t
}),
})
.collect();
let index = Index(
items
.registry_order
.iter()
.enumerate()
.map(|(i, id)| (id.clone(), i as u32))
.collect(),
);
let mut out = Vec::new();
let cooking: HashMap<String, (u32, f32)> = self
.res
.recipes()
.cooking
.iter()
.map(|c| (format!("minecraft:{}", c.id), (c.time, c.experience)))
.collect();
for e in self.recipe_book_entries() {
let furnace = |c: Category| match c.name().split('_').next() {
Some("blast") => RecipeKind::Blasting,
Some("smoker") => RecipeKind::Smoking,
_ => RecipeKind::Smelting,
};
let kind = match &e.display {
Display::Shaped { .. } => RecipeKind::CraftingShaped,
Display::Shapeless(_) => RecipeKind::CraftingShapeless,
Display::Furnace(_) => furnace(e.category),
};
let mut r = recipe(e.id.clone(), kind);
r.category = e.category.name().to_owned();
r.group = e.group.clone().unwrap_or_default();
r.book_id = e.display_id;
r.slots = match &e.display {
Display::Shaped {
width,
height,
cells,
} => {
(r.width, r.height) = (*width as u32, *height as u32);
cells
.iter()
.map(|c| c.as_ref().map_or_else(Vec::new, |i| index.any(i)))
.collect()
}
Display::Shapeless(list) => list.iter().map(|i| index.any(i)).collect(),
Display::Furnace(i) => vec![index.any(i)],
};
// Requirements shown as other stacks (an arrow's potions): the
// requirement's index counts the filled slots only.
let filled: Vec<usize> = (0..r.slots.len())
.filter(
|&k| !matches!(&e.display, Display::Shaped { cells, .. } if cells[k].is_none()),
)
.collect();
for (req, stacks) in &e.stacks {
if let Some(&k) = filled.get(*req) {
r.slots[k] = stacks.iter().filter_map(|s| index.of(s)).collect();
}
}
r.results = e.results().iter().filter_map(|s| index.of(s)).collect();
if let Some(&(time, xp)) = cooking.get(&e.id) {
(r.cooking_time, r.experience) = (time, xp);
}
out.push(r);
}
for c in &self.res.recipes().cooking {
if c.kind == "minecraft:campfire_cooking" {
let mut r = recipe(format!("minecraft:{}", c.id), RecipeKind::Campfire);
r.group = c.group.clone();
r.slots = vec![index.any(&c.ingredient)];
r.results = index.of(&c.result).into_iter().collect();
(r.cooking_time, r.experience) = (c.time, c.experience);
out.push(r);
}
}
let stations = self.res.stations();
for s in &stations.recipes.stonecutting {
let mut r = recipe(s.id.clone(), RecipeKind::Stonecutting);
r.slots = vec![index.any(&s.input)];
r.results = index.of(&s.result).into_iter().collect();
out.push(r);
}
for s in &stations.recipes.smithing {
let (id, template, base, addition, results) = match s {
Smithing::Transform {
id,
template,
base,
addition,
result,
} => (
id,
template,
base,
addition,
index.stack(result, 1, String::new()).into_iter().collect(),
),
Smithing::Trim {
id,
template,
base,
addition,
..
} => (id, template, base, addition, index.any(base)),
};
let mut r = recipe(id.clone(), RecipeKind::Smithing);
r.slots = vec![index.any(template), index.any(base), index.any(addition)];
r.results = results;
out.push(r);
}
for b in &stations.brewing.recipes {
let potion = |p: &horizon_client::brewing::PotionIngredient| -> Vec<RecipeStack> {
let mut item_ids: Vec<&String> = p.items.iter().collect();
item_ids.sort();
let mut potions: Vec<&String> = p.potions.iter().flatten().collect();
potions.sort();
item_ids
.into_iter()
.flat_map(|item| {
let one = |c: String| index.stack(item, 1, c);
if potions.is_empty() {
one(String::new()).into_iter().collect::<Vec<_>>()
} else {
potions
.iter()
.filter_map(|p| {
one(format!("[minecraft:potion_contents={{potion:\"{p}\"}}]"))
})
.collect()
}
})
.collect()
};
let mut r = recipe(b.id.clone(), RecipeKind::Brewing);
r.slots = vec![potion(&b.input), potion(&b.reagent)];
r.results = index.of(&b.output).into_iter().collect();
out.push(r);
}
Recipes {
items: table,
recipes: out,
}
}
}
+41 -2
View File
@@ -63,6 +63,14 @@ pub(super) struct ModsState {
/// What players did this tick, for server mods at its end.
#[cfg(feature = "mods")]
pub(super) events: Vec<ModEvent>,
/// A running server mod has capability `world`: its calls get the
/// levels' chunks to read.
#[cfg(feature = "mods")]
pub(super) world: bool,
/// Blocks server mods set, by dimension, made before that level's next
/// tick.
#[cfg(feature = "mods")]
pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>,
/// `command.run` lines for this window's own world, run on the next tick:
/// run at once, their chat lines would reach the mods while their output
/// is still being shown, and a mod answering its own lines would recurse.
@@ -81,6 +89,15 @@ pub(super) struct ModsState {
/// The HUD font's advances for `render.text-width`, made once.
#[cfg(feature = "mods")]
font_widths: std::sync::Arc<[f32]>,
/// Capability `recipes`'s tables, made once a mod reads them.
#[cfg(feature = "mods")]
pub(super) recipes: Option<std::sync::Arc<horizon_mods::Recipes>>,
/// The recipe book's known displays, and the book's version they are of.
#[cfg(feature = "mods")]
pub(super) known_recipes: (Option<u64>, std::sync::Arc<[i32]>),
/// Capability `ui`'s item panel beside container screens.
#[cfg(feature = "mods")]
pub(super) browser: super::mod_browser::Browser,
/// Extras that are official mods now, being installed.
#[cfg(feature = "mods")]
pub(super) moved: super::moved_extras::MovedState,
@@ -293,6 +310,8 @@ impl Game<'_> {
self.mods.mods.set_bindings(|id| chosen.keys_of(id));
// Entries were replaced wholesale: a screen's owner index is stale.
self.mods.screen = None;
// Content mods may have changed the items: remade on the next read.
self.mods.recipes = None;
self.list_mods();
self.sync_mod_commands();
self.show_mod_output();
@@ -309,6 +328,7 @@ impl Game<'_> {
/// The Mods page's rows, from what loaded.
fn list_mods(&mut self) {
self.mods.server = self.mods.mods.runs_server();
self.mods.world = self.mods.mods.wants_world();
let dev = &self.mods.dev;
self.settings.mods.installed = self
.mods
@@ -440,6 +460,7 @@ impl Game<'_> {
.map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1))
.collect();
}
let (recipes, known_recipes) = self.mod_recipes();
Snapshot {
player,
clock,
@@ -451,6 +472,10 @@ impl Game<'_> {
font_widths: self.mods.font_widths.clone(),
players,
view_hit: self.mod_view_hit(),
recipes,
known_recipes,
placing: self.mod_recipe_screen(),
creative: self.creative,
}
}
/// The first block along the player's view within
@@ -673,8 +698,10 @@ impl Game<'_> {
}
Text::literal(line).with_color(text::RED)
}
server
@ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => {
server @ (Output::Tell { .. }
| Output::Broadcast { .. }
| Output::Reply { .. }
| Output::SetBlocks { .. }) => {
self.route_server_output(host.as_deref_mut(), server);
continue;
}
@@ -686,6 +713,18 @@ impl Game<'_> {
self.mods.shake.add(strength, seconds);
continue;
}
Output::PlaceRecipe { book_id, all } => {
self.mod_place_recipe(book_id, all);
continue;
}
Output::Give {
item,
count,
components,
} => {
self.mod_give(&item, count, &components);
continue;
}
Output::CloseScreen { owner } => {
if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) {
self.close_mod_screen(false);
+1 -1
View File
@@ -91,7 +91,7 @@ impl Game<'_> {
})
}
/// `isEyeInFluid(WATER)`: the eye inside the water of its block column.
fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool {
pub(super) fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool {
let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32);
let f = self.res.facts().get(self.world.block(bx, by, bz));
if f.fluid != Fluid::Water {
@@ -155,6 +155,8 @@ mod tests {
value: 1,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
}))
}
+192 -33
View File
@@ -4,18 +4,172 @@
use super::Game;
use horizon_client::{
items::ItemStack,
mobs::{Species, Who, piglin::ADMIRE},
mobs::{
Mob, Species, Who,
finalize::{
SLOT_NAMES, set_drop_chance, set_item, set_slot_enchantments, slot_enchantments,
stored_drop_chance,
},
piglin::{ADMIRE, ATE_RECENTLY},
},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
impl Game<'_> {
fn piglin_loved(&self, item: &str) -> bool {
fn item_in_tag(&self, tag: &str, item: &str) -> bool {
self.res
.items()
.item_tags
.get("minecraft:piglin_loved")
.get(tag)
.is_some_and(|t| t.contains(item))
}
fn piglin_loved(&self, item: &str) -> bool {
self.item_in_tag("minecraft:piglin_loved", item)
}
/// `PiglinAi.isLovedItem` or a preferred weapon (`Piglin.canReplaceCurrentItem`).
fn piglin_wanted(&self, item: &str) -> bool {
self.piglin_loved(item) || self.item_in_tag("minecraft:piglin_preferred_weapons", item)
}
/// The `SLOT_NAMES` index `getEquipmentSlotForItem` picks: armour goes
/// to its slot, anything else to the main hand.
fn piglin_slot(&self, item: &str) -> usize {
let slot = self
.res
.items()
.get(item)
.and_then(|i| i.equip_slot.as_deref())
.filter(|s| matches!(*s, "head" | "chest" | "legs" | "feet"))
.unwrap_or("mainhand");
SLOT_NAMES.iter().position(|n| *n == slot).unwrap_or(0)
}
/// `Piglin.canReplaceCurrentItem`: an empty slot takes anything, a wanted
/// item replaces an unwanted one and never the other way round. Vanilla's
/// armour and weapon comparison for two equal-interest items is left out
/// (the piglin keeps what it has).
fn piglin_can_replace(&self, m: &Mob, item: &str, slot: usize) -> bool {
let Some(current) = horizon_client::mobs::finalize::item(m, slot) else {
return true;
};
self.piglin_wanted(item) && !self.piglin_wanted(&current)
}
/// `SimpleContainer.canAddItem` on the piglin's eight slots.
fn piglin_can_add(&self, m: &Mob, stack: &ItemStack) -> bool {
m.extra.inventory.len() < 8
|| m.extra.inventory.iter().any(|s| {
s.same_item_same_components(stack) && s.count < self.piglin_max_stack(&s.item)
})
}
fn piglin_max_stack(&self, item: &str) -> u32 {
self.res.items().get(item).map_or(64, |i| i.max_stack)
}
/// `PiglinAi.wantsToPickup` (an adult that is not hurt-shy), without
/// the baby rule, which babies skip entirely here.
fn piglin_wants(&self, m: &Mob, stack: &ItemStack) -> bool {
let item = &*stack.item;
if self.item_in_tag("minecraft:piglin_repellents", item) {
return false;
}
let holds_loved = m
.extra
.off_hand
.as_deref()
.is_some_and(|o| self.piglin_loved(o));
if item == "minecraft:gold_ingot" {
return !holds_loved;
}
let space = self.piglin_can_add(m, stack);
if item == "minecraft:gold_nugget" {
space
} else if self.item_in_tag("minecraft:piglin_food", item) {
m.extra.ints[0] <= 0 && space
} else if !self.piglin_loved(item) {
self.piglin_can_replace(m, item, self.piglin_slot(item))
} else {
!holds_loved && space
}
}
/// `Mob.equipItemIfPossible` for a piglin: put it in its slot when that
/// slot takes it (an armour piece that cannot replace what is worn goes
/// to an empty main hand), dropping what it replaces by drop chance.
fn piglin_equip(&mut self, index: usize, stack: &ItemStack) -> bool {
let item = &*stack.item;
let mut slot = self.piglin_slot(item);
let m = &self.mobs[index];
let mut replace = self.piglin_can_replace(m, item, slot);
if slot > 1 && !replace {
slot = 0;
replace = m.extra.main_hand.is_none();
}
if !replace {
return false;
}
let m = &mut self.mobs[index];
let old = horizon_client::mobs::finalize::item(m, slot);
let chance = stored_drop_chance(m, slot);
let drop_old = old.is_some() && (m.random.next_float() - 0.1).max(0.0) < chance;
let old_enchantments = slot_enchantments(m, slot);
set_item(m, slot, item);
// The piglin keeps what the stack carried (Protection IV stays on).
set_slot_enchantments(m, slot, stack.enchantments().to_vec());
// setItemSlotAndDropWhenKilled, then persistenceRequired.
set_drop_chance(m, slot, 2.0);
m.persistent = true;
let at = [m.position.x, m.position.y, m.position.z];
if let (true, Some(old)) = (drop_old, old) {
let mut dropped = ItemStack::new(&old, 1);
dropped.set_crafting_enchantments(old_enchantments);
self.spawn_item(dropped, at, super::dispenser::new_item_motion(), 10);
}
true
}
/// `PiglinAi.putInInventory`: what does not fit is thrown at a random
/// spot nearby.
fn piglin_stash(&mut self, index: usize, mut stack: ItemStack) {
let max = self.piglin_max_stack(&stack.item);
let m = &mut self.mobs[index];
for s in &mut m.extra.inventory {
if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max {
let n = (max - s.count).min(stack.count);
s.count += n;
stack.count -= n;
}
}
while stack.count > 0 && m.extra.inventory.len() < 8 {
let n = stack.count.min(max);
m.extra.inventory.push(ItemStack {
count: n,
..stack.clone()
});
stack.count -= n;
}
if stack.count == 0 {
return;
}
let from = [m.position.x, m.position.y + 1.3, m.position.z];
let r = &mut self.world.random;
let to = [
from[0] + f64::from(r.next_float() * 8.0 - 4.0),
from[1],
from[2] + f64::from(r.next_float() * 8.0 - 4.0),
];
self.piglin_throw(from, to, stack);
}
/// `PiglinAi.stopHoldingOffHandItem` for something that is not
/// bartering currency: wear it if it can, else keep it in the inventory.
fn piglin_keep(&mut self, index: usize, stack: ItemStack) {
// Nuggets keep their whole stack in the inventory (a hand slot here
// holds one item id only).
if &*stack.item == "minecraft:gold_nugget" || !self.piglin_equip(index, &stack) {
self.piglin_stash(index, stack);
}
}
/// `BehaviorUtils.throwItem`: toss a stack from a point toward another.
fn piglin_throw(&mut self, from: [f64; 3], to: [f64; 3], stack: ItemStack) {
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6);
let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3];
self.spawn_item(stack, from, v, 40);
}
/// `PiglinAi.isWearingSafeArmor`.
pub(super) fn wearing_gold(&self) -> bool {
let tag = self
@@ -28,15 +182,13 @@ impl Game<'_> {
.flatten()
.any(|s| tag.is_some_and(|t| t.contains(&*s.item)))
}
/// Piglins notice gold on the ground within 9 blocks, walk to it and
/// take it (`GoToWantedItem`, `Piglin.pickUpItem`).
/// Piglins notice wanted items on the ground within 9 blocks (`PiglinAi.wantsToPickup`:
/// gold and other loved items, nuggets, food, gear), walk to them and
/// take them (`GoToWantedItem`, `Piglin.pickUpItem`).
pub(super) fn piglin_pickups(&mut self) {
if !self.ui.rules.bool("mob_griefing") {
return;
}
// Whether each item is piglin-loved, kept until an item is added or
// removed (added ones are pushed at the end under a new id).
let mut loved: (Option<(usize, Option<u32>)>, Vec<bool>) = (None, Vec::new());
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Piglin
@@ -44,27 +196,17 @@ impl Game<'_> {
|| m.is_baby()
|| m.extra.using_item > 0
|| m.extra.egg_time > 0
|| m.extra.off_hand.is_some()
{
continue;
}
let pos = m.position;
let key = (self.dropped.len(), self.dropped.last().map(|e| e.id));
if loved.0 != Some(key) {
loved.0 = Some(key);
loved.1 = self
.dropped
.iter()
.map(|e| self.piglin_loved(&e.stack.item))
.collect();
}
let best = self
.dropped
.iter()
.enumerate()
.filter(|&(j, _)| loved.1[j])
.map(|(j, e)| (j, e.position.distance_squared(pos)))
.filter(|(_, d)| *d <= 81.0)
.filter(|&(j, _)| self.piglin_wants(m, &self.dropped[j].stack))
.min_by(|a, b| a.1.total_cmp(&b.1));
let Some((j, _)) = best else {
self.mobs[i].extra.point = None;
@@ -79,24 +221,38 @@ impl Game<'_> {
continue;
}
// Nuggets come whole, anything else one at a time.
let item = e.stack.item.clone();
let (taken_item, id) = (e.clone(), self.mobs[i].id);
let item = e.stack.item.clone();
self.add_pickup(
super::pickups::Taken::Item(Box::new(taken_item)),
super::pickups::Collector::Mob(id),
);
let taken = if &*item == "minecraft:gold_nugget" {
self.dropped.remove(j).stack.count
let stack = if &*item == "minecraft:gold_nugget" {
self.dropped.remove(j).stack
} else {
let e = &mut self.dropped[j];
e.stack.count -= 1;
let one = ItemStack {
count: 1,
..e.stack.clone()
};
if e.stack.count == 0 {
self.dropped.remove(j);
}
1
one
};
let _ = taken;
self.start_admiring(i, item);
if self.piglin_loved(&item) {
self.start_admiring(i, item);
} else if self.item_in_tag("minecraft:piglin_food", &item)
&& self.mobs[i].extra.ints[0] <= 0
{
// PiglinAi.eat: the food is gone and it will not eat for a while.
self.mobs[i].extra.ints[0] = ATE_RECENTLY;
self.mobs[i].nav_stop();
} else {
self.mobs[i].nav_stop();
self.piglin_keep(i, stack);
}
}
}
fn start_admiring(&mut self, index: usize, item: std::sync::Arc<str>) {
@@ -109,14 +265,15 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.piglin.admiring_item", Some(at), 1.0, 1.0);
}
/// `PiglinAi.mobInteract`: hand a piglin something it loves.
/// `PiglinAi.mobInteract`: hand a piglin a gold ingot (only piglin
/// currency is accepted from the hand; other loved items are passed over).
pub(super) fn give_piglin(&mut self, index: usize, item: &str) -> bool {
let m = &self.mobs[index];
if m.species() != Species::Piglin
|| m.is_baby()
|| m.extra.using_item > 0
|| m.extra.egg_time > 0
|| !self.piglin_loved(item)
|| item != "minecraft:gold_ingot"
{
return false;
}
@@ -124,7 +281,8 @@ impl Game<'_> {
true
}
/// `PiglinAi.stopHoldingOffHandItem` after admiring: gold ingots buy a
/// roll of the bartering table, thrown toward the player.
/// roll of the bartering table, thrown toward the player; any other loved
/// item it picked up is kept (worn if it can be, else stored).
pub(super) fn finish_admiring(&mut self, mob: u32) {
let Some(i) = self.mobs.iter().position(|m| m.id == mob) else {
return;
@@ -132,9 +290,13 @@ impl Game<'_> {
let Some(item) = self.mobs[i].extra.off_hand.take() else {
return;
};
if &*item != "minecraft:gold_ingot" {
self.piglin_keep(i, ItemStack::new(&item, 1));
return;
}
let m = &self.mobs[i];
let from = [m.position.x, m.position.y + 1.3, m.position.z];
let items = if &*item == "minecraft:gold_ingot" && !m.is_baby() {
let items = if !m.is_baby() {
self.res.items().loot_table(
"minecraft:gameplay/piglin_bartering",
false,
@@ -176,10 +338,7 @@ impl Game<'_> {
from[2] + f64::from(r.next_float() * 8.0 - 4.0),
]
});
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt().max(1e-6);
let v = [d[0] / len * 0.3, d[1] / len * 0.3 + 0.1, d[2] / len * 0.3];
self.spawn_item(stack, from, v, 40);
self.piglin_throw(from, to, stack);
}
}
/// `PiglinAi.angerNearbyPiglins`.
+22 -1
View File
@@ -276,7 +276,8 @@ impl Game<'_> {
} else if let Some(rest) = self.give(filled)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40);
// `player.drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
/// Drinking a potion while right-click is held; true when handled.
@@ -400,8 +401,28 @@ impl Game<'_> {
for action in actions {
self.apply_effect_action(action);
}
self.turtle_helmet_tick();
self.apply_effect_status();
}
/// `Player.tick` -> `turtleHelmetTick`: with a turtle helmet on the head
/// and the eyes out of the water, Water Breathing for 200 ticks (no
/// particles, an icon).
fn turtle_helmet_tick(&mut self) {
let Some(p) = self.player.as_ref() else {
return;
};
let eye_y = p.position.y + f64::from(p.dimensions.eye_height);
if !p.health.dead_or_dying()
&& self.armor[0]
.as_ref()
.is_some_and(|s| &*s.item == "minecraft:turtle_helmet")
&& !self.eye_in_water(p.position.x, eye_y, p.position.z)
{
let mut effect = EffectInstance::new("water_breathing", 200, 0);
effect.visible = false;
self.potions.effects.add(effect);
}
}
/// A client's own effects (`LivingEntity.tickEffects` on the client,
/// `MobEffectInstance.tickClient`): they count down, and the server
/// removes them. Their modifiers and flags move the predicted player.
+2
View File
@@ -796,6 +796,8 @@ impl Game<'_> {
let s = m.extra.raider.get_or_insert_with(Box::default);
s.rider = has_rider;
s.in_village = in_village;
// Vindicator.customServerAiStep: `ServerLevel.isRaided`.
s.raided = species == Species::Vindicator && raids.nearby(block).is_some();
if s.raid_id.is_some_and(|id| raids.get(id).is_none()) {
s.raid_id = None;
s.ticks_outside_raid = 0;
@@ -338,6 +338,25 @@ impl Game<'_> {
ui.client_known = Some(known.clone());
ui.client_version += 1;
}
/// Every entry of the book, in its order (capability `recipes`).
#[cfg(feature = "mods")]
pub(super) fn recipe_book_entries(&mut self) -> Vec<Entry> {
self.ensure_book();
self.recipe_ui
.book
.as_ref()
.map_or_else(Vec::new, |b| b.entries.clone())
}
/// The display ids the player's book holds, and a number that changes
/// whenever they do (capability `recipes`).
#[cfg(feature = "mods")]
pub(super) fn recipe_book_displays(&mut self) -> (u64, Vec<i32>) {
self.sync_client_book();
(
self.recipe_ui.client_version,
self.recipe_ui.client.displays(),
)
}
fn ensure_book(&mut self) {
if self.recipe_ui.book.is_none() {
let mut book = Book::build(self.res.recipes(), self.res.items());
@@ -826,6 +845,34 @@ impl Game<'_> {
self.recipe_ui.ghost.clear();
self.place_recipe(book_type, entry_index, use_max);
}
/// Whether the open screen takes `recipes.place`: a crafting grid's
/// book (the inventory's or a crafting table's).
#[cfg(feature = "mods")]
pub(super) fn mod_recipe_screen(&self) -> bool {
self.screen == Screen::Inventory
&& self.active_book() == Some(BookType::Crafting)
&& !self.spectator()
}
/// `recipes.place`: the book's click on the recipe with this display
/// id, refused as `handlePlaceRecipe` refuses it (no crafting screen,
/// not in the player's book; an impossible one in `place_recipe`).
#[cfg(feature = "mods")]
pub(super) fn mod_place_recipe(&mut self, display_id: i32, all: bool) {
if !self.mod_recipe_screen() || !self.recipe_ui.client.displays().contains(&display_id) {
return;
}
self.ensure_book();
let Some(index) = self
.recipe_ui
.book
.as_ref()
.and_then(|b| b.entries.iter().position(|e| e.display_id == display_id))
else {
return;
};
self.recipe_ui.ghost.clear();
self.place_recipe(BookType::Crafting, index, all);
}
/// `ServerboundPlaceRecipePacket`: the server places the recipe
/// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost
/// recipe when the items are missing.
+9 -8
View File
@@ -1283,6 +1283,8 @@ impl Game<'_> {
value: 1,
age: 0,
on_ground: false,
count: 1,
ticks: 0,
});
}
if let Some(t) = mob_type {
@@ -2064,7 +2066,10 @@ impl Game<'_> {
{
self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector);
}
self.remove_entity(p.item);
// An orb stays: the server may still hold merged ones in it.
if !orb {
self.remove_entity(p.item);
}
}
// ClientPacketListener.handleSetEntityMotion: knockback on this player.
C::SetEntityMotion(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => {
@@ -4055,15 +4060,11 @@ impl Game<'_> {
world_border: false,
sequence: seq,
}));
let target = [
hit.pos[0] + hit.face[0],
hit.pos[1] + hit.face[1],
hit.pos[2] + hit.face[2],
];
let ticks = self.ticks;
// Only a predicted placement (predict_place) marks a cell whose
// resend plays a place sound: an empty hand or a non-block item
// places nothing (BlockItem.place is where the sound comes from).
if let Some(r) = self.remote.as_mut() {
r.use_target = Some(hit.pos);
r.placing = Some((target, ticks));
}
if reacts {
self.predict_use(&changes, seq);
@@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[
impl Game<'_> {
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
fn parse_state(&self, text: &str) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let registry = &self.pack.assets.registry;
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
parse_state(self.pack.assets.registry, text)
}
pub(super) fn render_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
let int = |i: usize| -> Result<i32> {
@@ -137,3 +111,36 @@ impl Game<'_> {
}
}
}
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
pub(super) fn parse_state(
registry: &horizon_world::registry::BlockRegistry,
text: &str,
) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
}
+151 -3
View File
@@ -47,19 +47,72 @@ impl Game<'_> {
) -> bool {
false
}
pub(super) fn apply_mod_block_writes(&mut self) {}
}
#[cfg(feature = "mods")]
mod run {
use super::{Game, LanHost, ModEvent, Who};
use horizon_client::chunk_map::ChunkMap;
use horizon_client::{
command::args::GameMode as Mode,
lan::data::component_nbt,
text::{self, Text},
};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView};
use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::registry::BlockStateId;
use horizon_world::registry::{BlockRegistry, BlockStateId};
/// Blocks queued for levels that don't tick (another dimension, in-frame)
/// are kept up to this many; the oldest go first.
const MAX_QUEUED_WRITES: usize = 1 << 16;
/// Capability `world`'s view during a call: the levels' chunks, moved out
/// of the game for the call and back after it (no copy).
struct LentWorld {
registry: &'static BlockRegistry,
biomes: std::sync::Arc<horizon_client::biome::Biomes>,
dims: Vec<(&'static str, ChunkMap)>,
}
impl WorldView for LentWorld {
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(state_string(self.registry, chunk.block(x & 15, y, z & 15)))
}
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(self.biomes.get(chunk.biome(x, y, z)).name.clone())
}
fn has_dimension(&self, dimension: &str) -> bool {
matches!(
dimension,
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
)
}
fn check_state(&self, state: &str) -> Result<(), String> {
crate::game::render_control::parse_state(self.registry, state)
.map(drop)
.map_err(|e| format!("{state}: {e}"))
}
}
/// `minecraft:oak_log[axis=y]`.
fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String {
let Some(s) = registry.state(state) else {
return "minecraft:air".into();
};
if s.properties.is_empty() {
return s.name.clone();
}
let props: Vec<String> = s
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}[{}]", s.name, props.join(","))
}
/// `UUID.toString()`.
fn uuid_string(u: u128) -> String {
@@ -144,6 +197,7 @@ mod run {
let players = self.server_players(None);
let snapshot = self.mod_snapshot_with(players.clone());
self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let before = std::mem::take(&mut self.mods.players);
for p in before
.iter()
@@ -197,8 +251,80 @@ mod run {
}
}
self.mods.mods.server_tick(self.ticks);
self.return_world();
self.mods.players = players;
self.show_mod_output();
self.apply_mod_block_writes();
}
/// Lends the levels' chunks to capability `world` for the calls up to
/// [`Game::return_world`], when a running server mod has it.
fn lend_world(&mut self) {
if !self.mods.world {
return;
}
let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))];
for (dim, chunks) in self.levels.parked_chunks() {
dims.push((dim.id(), std::mem::take(chunks)));
}
let registry = self.pack.assets.registry;
let biomes = self.res.biomes().clone();
self.mods.mods.lend_world(Box::new(LentWorld {
registry,
biomes,
dims,
}));
}
/// Puts back the chunks [`Game::lend_world`] lent.
fn return_world(&mut self) {
let Some(view) = self.mods.mods.take_world() else {
return;
};
let view: Box<dyn std::any::Any> = view;
let Ok(lent) = view.downcast::<LentWorld>() else {
return;
};
let mut dims = lent.dims;
if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) {
self.world.chunks = dims.swap_remove(i).1;
}
for (dim, chunks) in self.levels.parked_chunks() {
if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) {
*chunks = dims.swap_remove(i).1;
}
}
}
/// Makes the blocks server mods set in the level in place, in order,
/// as `/setblock` does. Those of other dimensions wait for their level.
pub(in crate::game) fn apply_mod_block_writes(&mut self) {
if self.mods.block_writes.is_empty() {
return;
}
let dim = self.dim.id();
let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes)
.into_iter()
.partition(|(d, _)| d == dim);
self.mods.block_writes = later;
let registry = self.pack.assets.registry;
for (_, b) in now {
let state = match crate::game::render_control::parse_state(registry, &b.state) {
Ok(state) => state,
Err(e) => {
log::warn!("Horizon: a server mod set {}: {e}", b.state);
continue;
}
};
if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) {
log::debug!(
"Horizon: a server mod's block at {} {} {}: {e:?}",
b.x,
b.y,
b.z
);
}
}
}
/// A player broke (or placed) `state` at `pos`: the player acting now.
@@ -240,8 +366,11 @@ mod run {
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let owned = self.mods.mods.server_command(&me, line);
self.return_world();
self.show_mod_output();
self.apply_mod_block_writes();
owned
}
@@ -266,10 +395,14 @@ mod run {
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
if !self.mods.mods.server_command(&me, line) {
self.lend_world();
let owned = self.mods.mods.server_command(&me, line);
self.return_world();
if !owned {
return false;
}
self.route_mod_output(Some(host));
self.apply_mod_block_writes();
true
}
@@ -349,6 +482,21 @@ mod run {
self.tell_server_player(host.as_deref_mut(), &p.id, line);
}
}
Output::SetBlocks {
name,
dimension,
blocks,
} => {
let queued = &mut self.mods.block_writes;
queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b)));
if queued.len() > MAX_QUEUED_WRITES {
let over = queued.len() - MAX_QUEUED_WRITES;
queued.drain(..over);
log::warn!(
"Horizon: mod {name} set more blocks than wait for their level: {over} dropped"
);
}
}
_ => {}
}
}
+6 -6
View File
@@ -171,8 +171,8 @@ pub(super) struct Spawn {
pub(super) struct Spill {
pub(super) spawns: Vec<Spawn>,
/// Experience orbs (`ExperienceOrb.award`): where and how much, each
/// having drawn its merge id from the level random.
pub(super) orbs: Vec<([f64; 3], u32)>,
/// and the merge id it drew from the level random.
pub(super) orbs: Vec<([f64; 3], u32, i32)>,
/// Block entities the behaviour removed, for the game's own follow-ups
/// (open screens, playing songs).
pub(super) removed: Vec<([i32; 3], BlockEntity)>,
@@ -342,8 +342,8 @@ impl GameLevel<'_> {
while amount > 0 {
let value = removal::orb_value(amount);
amount -= value;
let _merge_id = self.world.random.next_int_bound(40);
self.spill.orbs.push((at, value));
let merge_id = self.world.random.next_int_bound(40).unwrap_or(0);
self.spill.orbs.push((at, value, merge_id));
}
}
/// `BlockEntity.preRemoveSideEffects` and `removeBlockEntity` for the block
@@ -583,8 +583,8 @@ impl Game<'_> {
let motion = s.motion.unwrap_or_else(new_item_motion);
self.spawn_item(s.stack, s.pos, motion, s.delay);
}
for (at, value) in spill.orbs {
self.add_orb(at, value);
for (at, value, merge_id) in spill.orbs {
self.award_orb(at, value, merge_id);
}
for (pos, entity) in spill.removed {
let key = (pos[0], pos[1], pos[2]);
+2 -1
View File
@@ -713,7 +713,8 @@ impl Game<'_> {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
{
self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
// Inventory.placeItemBackInInventory: `player.drop(stack, false)`.
self.throw_from_eyes(rest, eye, false);
}
}
/// `Player.giveExperienceLevels`.
+49
View File
@@ -33,6 +33,55 @@ impl Game<'_> {
self.container = Some(key);
self.ender_open = Some(key);
}
/// The block above `key` is a redstone conductor.
fn conductor_above(&self, key: (i32, i32, i32)) -> bool {
let above = self.world.block(key.0, key.1 + 1, key.2);
self.res.behaviours().facts(above).flags
& horizon_world::level::data::state_flags::CONDUCTOR
!= 0
}
/// `ChestBlock.isChestBlockedAt`: a redstone conductor above the chest or
/// a cat sitting on it.
fn chest_blocked_at(&self, key: (i32, i32, i32)) -> bool {
if self.conductor_above(key) {
return true;
}
// isCatSittingOnChest: a cat whose box meets the block above.
let area = horizon_core::geometry::Aabb::new(
horizon_core::geometry::Vec3::new(
f64::from(key.0),
f64::from(key.1 + 1),
f64::from(key.2),
),
horizon_core::geometry::Vec3::new(
f64::from(key.0 + 1),
f64::from(key.1 + 2),
f64::from(key.2 + 1),
),
);
self.mobs.iter().any(|m| {
m.species() == horizon_client::mobs::Species::Cat
&& m.alive()
&& horizon_client::mobs::tame::cat_sitting(m)
&& m.bounds().intersects(area)
})
}
/// `ChestBlock.getMenuProvider` (`combine(.., false)`) and
/// `EnderChestBlock.useWithoutItem`: a blocked chest, or a double chest
/// with either half blocked, opens no menu.
pub(super) fn chest_menu_blocked(&self, key: (i32, i32, i32), name: &str) -> bool {
match name {
"minecraft:chest" | "minecraft:trapped_chest" => {
self.chest_blocked_at(key)
|| self
.chest_partner(key)
.is_some_and(|(other, _)| self.chest_blocked_at(other))
}
// The ender chest only looks at the block above (no cat check).
"minecraft:ender_chest" => self.conductor_above(key),
_ => false,
}
}
/// Closing it copies the items back and leaves no block-entity contents.
pub(super) fn close_ender_chest(&mut self) {
let Some(key) = self.ender_open.take() else {
+87 -11
View File
@@ -1,7 +1,8 @@
//! Tridents: `TridentItem.releaseUsing` (throw after 10 ticks, or Riptide in
//! water or rain) and `ThrownTrident` (arrow flight with 0.99 water inertia,
//! 8 damage plus Impaling, the reversed bounce off a hit, sticking, Loyalty's
//! return to the owner, pickup) with `ThrownTridentRenderer`.
//! return to the owner, pickup) with `ThrownTridentRenderer`, and Channeling's
//! lightning on a hit (`channeling.json`).
use super::{Game, view_vector};
use horizon_client::{
collisions::SceneCollisions,
@@ -10,7 +11,8 @@ use horizon_client::{
mobs::{Damage, DamageKind, Who, anim::Poses},
};
use horizon_core::{
geometry::{Aabb, Vec3},
geometry::{Aabb, Vec3, traverse_blocks},
position::BlockPos,
random::RandomSource,
};
@@ -154,6 +156,69 @@ impl Game<'_> {
p.auto_spin_attack_dmg = 0.0;
}
}
/// The `summon_entity` and `play_sound` effects of `channeling.json`: in a
/// thunderstorm (`weather_check`) a spot that sees the sky (`can_see_sky`)
/// gets a lightning bolt and the thunder sound.
fn channel_lightning(&mut self, at: [f64; 3]) {
// Level.isThundering: the thunder level, in dimensions with weather.
if self.dim != super::Dim::Overworld || self.world.weather.levels(1.0).1 <= 0.9 {
return;
}
// BlockAndLightGetter.canSeeSky: full sky light.
let (x, y, z) = (
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
);
if self.world.light(x, y, z) >> 4 != 15 {
return;
}
self.spawn_bolt(at, false);
self.audio
.play("minecraft:item.trident.thunder", Some(at), 5.0, 1.0);
}
/// `minecraft:hit_block` of Channeling (`AbstractArrow.hitBlockEnchantmentEffects`):
/// the block the trident's path first hits, if it is a lightning rod, with
/// the hit location clamped into the block (`BlockPos.clampLocationWithin`).
fn channel_rod_hit(&mut self, from: Vec3, velocity: Vec3) {
let to = Vec3::new(
from.x + velocity.x,
from.y + velocity.y,
from.z + velocity.z,
);
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
// ClipContext.Block.COLLIDER with Fluid.NONE.
let hit = traverse_blocks(from, to, 1024, |p: BlockPos| {
let state = self.world.block(p.x, p.y, p.z);
if self.res.facts().is_air(state) {
return None;
}
let shape = self
.collision
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
.ok()?;
shape.clip(from, to, p)
});
let Some(hit) = hit.ok().flatten() else {
return;
};
let state = self.world.block(hit.block.x, hit.block.y, hit.block.z);
if !self.res.facts().get(state).name.ends_with("lightning_rod") {
return;
}
let edge = f64::from(1.0e-5f32);
let clamp =
|v: f64, origin: i32| v.clamp(f64::from(origin) + edge, f64::from(origin) + 1.0 - edge);
self.channel_lightning([
clamp(hit.location.x, hit.block.x),
clamp(hit.location.y, hit.block.y),
clamp(hit.location.z, hit.block.z),
]);
}
/// `TridentItem.releaseUsing`.
pub(super) fn release_trident(&mut self, ticks: u32) {
if ticks < 10 {
@@ -171,10 +236,11 @@ impl Game<'_> {
.as_ref()
.map(|p| [p.position.x, p.position.y, p.position.z]);
if riptide > 0 {
if !self.in_water_or_rain() {
// `isInWaterOrRain() && !isPassenger()`.
if !self.in_water_or_rain() || self.riding.is_some() {
return;
}
self.damage_held(1);
self.hurt_held_without_breaking(1);
// trident_spin_attack_strength: 1.5 + 0.75 per level above the first.
let strength = 1.5 + 0.75 * (riptide as f32 - 1.0);
let d = view_vector(self.yaw, self.pitch);
@@ -195,12 +261,8 @@ impl Game<'_> {
self.audio.play(&sound, at, 1.0, 1.0);
return;
}
// hurtWithoutBreaking, then the thrown copy.
if !self.creative
&& let Some(s) = self.held_mut().as_mut()
{
s.damage += 1;
}
// hurtWithoutBreaking (Unbreaking applies), then the thrown copy.
self.hurt_held_without_breaking(1);
let thrown = self.held().cloned().unwrap_or(stack);
if !self.creative {
*self.held_mut() = None;
@@ -311,9 +373,10 @@ impl Game<'_> {
});
let damage = 8.0 + if aquatic { 2.5 * impaling } else { 0.0 };
t.dealt_damage = true;
let mut hurt_at = None;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
let from = Some([t.position.x, t.position.y, t.position.z]);
m.damage(
let hurt = m.damage(
damage,
Damage {
kind: DamageKind::Arrow,
@@ -321,6 +384,15 @@ impl Game<'_> {
from,
},
);
if hurt {
hurt_at = Some([m.position.x, m.position.y, m.position.z]);
}
}
// `minecraft:post_attack` of Channeling, on the victim.
if let Some(at) = hurt_at
&& t.stack.enchantment_level("minecraft:channeling") > 0
{
self.channel_lightning(at);
}
self.audio.play(
"minecraft:item.trident.hit",
@@ -341,6 +413,7 @@ impl Game<'_> {
subject: None,
};
if let Ok(moved) = scene.resolve(bounds(t.position), t.velocity, 0.0, false) {
let (from, flight) = (t.position, t.velocity);
let blocked = (moved.x - t.velocity.x).abs() > 1e-7
|| (moved.y - t.velocity.y).abs() > 1e-7
|| (moved.z - t.velocity.z).abs() > 1e-7;
@@ -350,6 +423,9 @@ impl Game<'_> {
t.position.z + moved.z,
);
if blocked {
if t.stack.enchantment_level("minecraft:channeling") > 0 {
self.channel_rod_hit(from, flight);
}
t.in_ground = true;
t.velocity = Vec3::ZERO;
self.audio.play(
@@ -21,6 +21,38 @@ impl Game<'_> {
fn item_max_stack(&self, item: &str) -> u32 {
self.res.items().get(item).map_or(64, |i| i.max_stack)
}
/// `WorkAtComposter.useWorkstation`: at a composter the farmer makes
/// bread, then composts seeds.
pub(super) fn villager_work_at_composter(&mut self, id: u32, pos: [i32; 3]) {
let Some(i) = self.villager_index(id) else {
return;
};
if self.composter_level(pos).is_none() {
return;
}
self.villager_make_bread(i);
self.villager_compost_items(i, pos);
}
/// `WorkAtComposter.makeBread`: up to three loaves from nine wheat while
/// the villager holds at most 36 bread; what does not fit drops.
fn villager_make_bread(&mut self, i: usize) {
let max_stack = self.item_max_stack("minecraft:bread");
let e = villager::ext_mut(&mut self.mobs[i]);
if e.count_item("minecraft:bread") > 36 {
return;
}
let loaves = (e.count_item("minecraft:wheat") / 3).min(3);
if loaves == 0 {
return;
}
e.remove_item("minecraft:wheat", loaves * 3);
let left = e.add_item(ItemStack::new("minecraft:bread", loaves), max_stack);
if let Some(rest) = left {
// spawnAtLocation(level, stack, 0.5F)
let p = self.mobs[i].position;
self.spawn_item(rest, [p.x, p.y + 0.5, p.z], [0.0, 0.2, 0.0], 10);
}
}
/// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward
/// a point.
fn villager_throw(&mut self, from: Vec3, eye: f64, to: Vec3, stack: ItemStack) {
@@ -46,6 +46,10 @@ impl WorldRequest {
options: &Options,
settings: &Settings,
) -> Result<PreparedWorld> {
// Before any chunk is read: a loaded container with a loot table is rolled as its chunk
// is decoded (`save::roll_loaded_loot`), and the spawn chunks are read while the world
// opens. Every world opens here: in-frame, on the server thread, on a dedicated server.
horizon_client::structure_blocks::loot_data(&options.resources);
let Self {
save_root,
folder,
@@ -192,6 +196,82 @@ impl WorldLoader {
}
}
/// How long the preloaded world data outlives the world screens: a player
/// who goes back to the title or to Multiplayer and opens no world for this
/// long gets the memory back.
const PRELOAD_KEPT: std::time::Duration = std::time::Duration::from_secs(60);
enum Preload {
Idle,
/// Read, or being read, on the "World data preload" thread. `left`: when
/// the player last left the world screens.
Started {
thread: std::thread::JoinHandle<()>,
left: Option<std::time::Instant>,
},
/// A world opened: the data is the world's now, and stays.
Used,
}
static PRELOAD: std::sync::Mutex<Preload> = std::sync::Mutex::new(Preload::Idle);
/// Each frame of the title: read what every world opening loads and keeps
/// for the rest of the process (the worldgen bundle, the loot tables and the
/// registries the server sends) on a helper thread while the player is on the
/// world screens (`on_world_screens`: Singleplayer, Create World and their
/// dialogs), so it overlaps the time spent choosing a world. A world opened
/// meanwhile waits for the part being read instead of reading it again. Not
/// at the title screen itself: many players only go to Multiplayer, and
/// small machines need the memory. Dropped after `PRELOAD_KEPT` away from
/// the world screens without a world opening.
pub(super) fn preload_world_data(
on_world_screens: bool,
resources: &std::path::Path,
registry: &'static horizon_world::registry::BlockRegistry,
) {
let mut preload = PRELOAD.lock().unwrap_or_else(|e| e.into_inner());
match &mut *preload {
Preload::Used => {}
Preload::Idle if on_world_screens => {
let resources = resources.to_owned();
let spawned = std::thread::Builder::new()
.name("World data preload".into())
.spawn(move || {
horizon_threads::behind_server();
// Errors are left for the world opening to report.
let _ = horizon_client::vanillagen::shared_data(
&resources.join("worldgen"),
registry,
);
let _ = horizon_client::structure_blocks::loot_data(&resources);
let _ = super::lan::sync_data(&resources);
});
match spawned {
Ok(thread) => *preload = Preload::Started { thread, left: None },
Err(e) => log::warn!("Horizon: world data preload: {e}"),
}
}
Preload::Idle => {}
Preload::Started { left, .. } if on_world_screens => *left = None,
Preload::Started { thread, left } => {
let left = *left.get_or_insert_with(std::time::Instant::now);
if left.elapsed() >= PRELOAD_KEPT && thread.is_finished() {
horizon_client::vanillagen::forget_shared_data();
horizon_client::structure_blocks::forget_loot_data();
super::lan::forget_sync_data();
horizon_threads::release_free_memory();
*preload = Preload::Idle;
log::info!("Horizon: preloaded world data dropped, no world opened");
}
}
}
}
/// A world opens: what `preload_world_data` read is the world's from now on.
pub(super) fn world_data_used() {
*PRELOAD.lock().unwrap_or_else(|e| e.into_inner()) = Preload::Used;
}
pub(super) fn make_streaming(
res: &Resources,
pack: &PackResources,
@@ -0,0 +1,134 @@
//! `Zombie.hurtServer`'s reinforcements: a hurt zombie on Hard may call
//! another of its kind from 7 to 40 blocks away to fight its target.
use super::Game;
use horizon_client::mobs::{
MobType, Species, Who,
finalize::{self, Attr, Op},
spawn_rules::{self, Reason},
spawn_selection::{self, NaturalLevel},
spawner::SpawnerLevel,
};
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::food::Difficulty;
/// `Zombie.REINFORCEMENT_ATTEMPTS`.
const ATTEMPTS: usize = 50;
/// `Zombie.REINFORCEMENT_RANGE_MIN` and `REINFORCEMENT_RANGE_MAX`.
const RANGE_MIN: i32 = 7;
const RANGE_MAX: i32 = 40;
/// One axis of the offset: `Mth.nextInt(random, 7, 40) * Mth.nextInt(random, -1, 1)`.
fn offset(random: &mut LegacyRandom) -> i32 {
let distance = random
.next_int_between_inclusive(RANGE_MIN, RANGE_MAX)
.unwrap_or(RANGE_MIN);
distance * random.next_int_between_inclusive(-1, 1).unwrap_or(0)
}
impl Game<'_> {
/// `Zombie.hurtServer` after the hit: on Hard, with the zombie's chance
/// and monsters spawning, a copy of it appears out of sight and takes
/// `target`; both then call less often.
pub(super) fn call_reinforcements(&mut self, caller: u32, target: Who) {
let Some(index) = self.mobs.iter().position(|m| m.id == caller) else {
return;
};
if self.world.health_rules.difficulty != Difficulty::Hard {
return;
}
let zombie = &mut self.mobs[index];
if f64::from(zombie.random.next_float()) >= zombie.attrs.spawn_reinforcements {
return;
}
// ServerLevel.isSpawningMonsters.
if !self.ui.rules.bool("spawn_mobs") || !self.ui.rules.bool("spawn_monsters") {
return;
}
let kind = zombie.kind.clone();
let from = [
zombie.position.x.floor() as i32,
zombie.position.y.floor() as i32,
zombie.position.z.floor() as i32,
];
let mut own = std::mem::replace(&mut zombie.random, LegacyRandom::new(0));
let mut rules = std::mem::replace(&mut self.world.random, LegacyRandom::new(0));
let spot = self.reinforcement_spot(&kind, from, &mut own, &mut rules);
self.mobs[index].random = own;
self.world.random = rules;
let Some(spot) = spot else {
return;
};
let Some(id) = self.spawn_mob(&kind.id, spot.map(f64::from), false) else {
return;
};
if let Some(reinforcement) = self.mobs.iter_mut().find(|m| m.id == id) {
reinforcement.ai.target = Some(target);
// ZOMBIE_REINFORCEMENT_CALLEE_CHARGE.
finalize::add_modifier(
reinforcement,
Attr::SpawnReinforcements,
"minecraft:reinforcement_callee_charge",
-f64::from(0.05f32),
Op::AddValue,
);
}
// The caller's charge grows by 0.05 each time it calls.
let caller = &mut self.mobs[index];
let charged = finalize::modifier_amount(
caller,
Attr::SpawnReinforcements,
"minecraft:reinforcement_caller_charge",
)
.unwrap_or(0.0);
finalize::add_modifier(
caller,
Attr::SpawnReinforcements,
"minecraft:reinforcement_caller_charge",
charged - 0.05,
Op::AddValue,
);
}
/// The block `Zombie.hurtServer` puts the reinforcement at: the first of
/// 50 random offsets with a valid spawn surface, no alive player within
/// 7 blocks, and room for the zombie standing on the block's corner.
fn reinforcement_spot(
&self,
kind: &MobType,
from: [i32; 3],
own: &mut LegacyRandom,
rules: &mut LegacyRandom,
) -> Option<[i32; 3]> {
let level = self.natural_level();
let (width, height) = (kind.width as f32, kind.height as f32);
for _ in 0..ATTEMPTS {
let [x, y, z] = from.map(|v| v + offset(own));
if !spawn_rules::is_spawn_position_ok(kind.species, &level, x, y, z)
|| !spawn_rules::check_spawn_rules(
kind.species,
&level,
Reason::Reinforcement,
rules,
x,
y,
z,
)
{
continue;
}
// setPos(x, y, z): the box is centred on the block's corner.
let bounds =
spawn_selection::spawn_box(f64::from(x), f64::from(y), f64::from(z), width, height);
// Drowned.canSpawnInLiquids.
let wet_ok = kind.species == Species::Drowned
|| !spawn_selection::contains_any_liquid(&level, bounds);
if !level.alive_player_near(f64::from(x), f64::from(y), f64::from(z), 7.0)
&& level.unobstructed(bounds)
&& level.no_collision(bounds)
&& wet_ok
{
return Some([x, y, z]);
}
}
None
}
}
+14 -2
View File
@@ -111,6 +111,12 @@ pub enum HealthEvent {
amount: f32,
},
Phase(&'static str),
/// `Player.hurtArmor`: a hit that doesn't bypass armor wears the worn
/// pieces (`LivingEntity.getDamageAfterArmorAbsorb`); the game applies it.
ArmorHurt {
source: DamageTypeId,
amount: f32,
},
/// `ServerLevel.broadcastDamageEvent`: the client's
/// `LivingEntity.handleDamageEvent` plays the source's hurt sound.
DamageBroadcast {
@@ -139,6 +145,7 @@ impl HealthEvent {
format!("record-damage {:08x}", amount.to_bits())
}
Self::Phase(name) => name.into(),
Self::ArmorHurt { amount, .. } => format!("hurt-armor {:08x}", amount.to_bits()),
Self::DamageBroadcast { .. } => "broadcast-damage".into(),
Self::Criterion { .. } => "hurt-criterion".into(),
}
@@ -534,9 +541,14 @@ impl ServerDamageEnvironment<Attributes> for Environment<'_> {
fn bypasses(&mut self, kind: Bypass) -> io::Result<bool> {
Ok(self.source.bypasses(kind))
}
fn hurt_armor(&mut self, _: &mut Attributes, _: f32) -> io::Result<()> {
fn hurt_armor(&mut self, _: &mut Attributes, damage: f32) -> io::Result<()> {
// The worn armor lives in the game, which wears it from this event.
self.event(HealthEvent::ArmorHurt {
source: self.source.type_id(),
amount: damage,
});
Ok(())
} // empty equipment
}
fn has_resistance(&mut self) -> io::Result<bool> {
Ok(self.status.resistance.is_some())
}
+78 -3
View File
@@ -113,6 +113,9 @@ pub struct ItemInfo {
pub swappable: bool,
/// `equippable.dispensable` (dispensers may put it on an entity).
pub equip_dispensable: bool,
/// `equippable.damage_on_hurt`: the item wears when its wearer is hurt
/// (false for the elytra).
pub equip_damage_on_hurt: bool,
/// `equippable.allowed_entities` resolved to entity type ids; None allows all.
pub equip_allowed: Option<HashSet<String>>,
pub equip_sound: Option<String>,
@@ -400,6 +403,36 @@ impl Items {
self.get(&stack.item).is_some_and(|i| i.fire_resistant)
}
/// `ItemStack.canBeHurtBy` for the cactus damage type: a `damage_resistant`
/// component naming `minecraft:cactus`, or a damage type tag that holds it.
/// (`#minecraft:is_fire`, as on netherite gear, does not.)
pub fn resists_cactus(&self, stack: &ItemStack) -> bool {
const CACTUS_TAGS: [&str; 5] = [
"#minecraft:bypasses_shield",
"#minecraft:no_knockback",
"#minecraft:panic_environmental_causes",
"#minecraft:panic_causes",
"#minecraft:sulfur_cube_with_block_immune_to",
];
let Some((_, v)) = stack.data().and_then(|data| {
data.other
.iter()
.find(|(key, _)| key == "minecraft:damage_resistant")
}) else {
return false;
};
match v.get("types") {
Some(horizon_world::nbt::Tag::String(id)) => id
.to_string()
.is_ok_and(|id| id == "minecraft:cactus" || CACTUS_TAGS.contains(&id.as_str())),
Some(horizon_world::nbt::Tag::List(ids)) => ids.iter().any(|t| {
matches!(t, horizon_world::nbt::Tag::String(id)
if id.to_string().is_ok_and(|id| id == "minecraft:cactus"))
}),
_ => false,
}
}
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new();
for (i, s) in facts.states.iter().enumerate() {
@@ -596,6 +629,9 @@ impl Items {
equip_dispensable: c["minecraft:equippable"]["dispensable"]
.as_bool()
.unwrap_or(true),
equip_damage_on_hurt: c["minecraft:equippable"]["damage_on_hurt"]
.as_bool()
.unwrap_or(true),
equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] {
Value::String(spec) => Some(entity_spec(&entity_tags, spec)),
Value::Array(list) => Some(
@@ -834,6 +870,7 @@ impl Items {
held: None,
killed_by_player: false,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -898,10 +935,26 @@ impl Items {
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
) -> Vec<ItemStack> {
self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None)
self.block_drops_exploded(
registry, state, held, dynamic, random, sequences, None, false,
)
}
/// `block_drops_with` for a block a player breaks (`Block.playerDestroy`):
/// the player is the loot context's `this` entity, so snow and chorus
/// flower tables see an entity.
pub fn block_drops_by_player(
&self,
registry: &BlockRegistry,
state: BlockStateId,
held: Option<&ItemStack>,
dynamic: &[ItemStack],
random: &mut impl RandomSource,
) -> Vec<ItemStack> {
self.block_drops_exploded(registry, state, held, dynamic, random, None, None, true)
}
/// `block_drops_full` for a block an explosion destroys: `explosion`
/// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`).
/// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`);
/// `breaker` is whether an entity (the player) broke the block.
#[allow(clippy::too_many_arguments)]
pub fn block_drops_exploded(
&self,
@@ -912,8 +965,10 @@ impl Items {
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
explosion: Option<f32>,
breaker: bool,
) -> Vec<ItemStack> {
let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion);
let drops =
self.block_drops_raw(registry, state, held, random, sequences, explosion, breaker);
if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) {
return drops;
}
@@ -928,6 +983,7 @@ impl Items {
})
.collect()
}
#[allow(clippy::too_many_arguments)]
fn block_drops_raw(
&self,
registry: &BlockRegistry,
@@ -936,6 +992,7 @@ impl Items {
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
explosion_radius: Option<f32>,
breaker: bool,
) -> Vec<ItemStack> {
let Some(block) = registry.state(state) else {
return vec![];
@@ -969,6 +1026,7 @@ impl Items {
held,
killed_by_player: false,
explosion_radius,
this_entity: breaker,
};
return ctx.evaluate(table, random);
}
@@ -979,6 +1037,7 @@ impl Items {
held,
killed_by_player: false,
explosion_radius,
this_entity: breaker,
};
ctx.evaluate(table, random)
}
@@ -1002,6 +1061,7 @@ impl Items {
held,
killed_by_player,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -1034,6 +1094,7 @@ impl Items {
held: None,
killed_by_player: false,
explosion_radius: None,
this_entity: false,
};
match table.get("random_sequence").and_then(Value::as_str) {
Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)),
@@ -1059,6 +1120,7 @@ impl Items {
held,
killed_by_player,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -1081,6 +1143,7 @@ impl Items {
held,
killed_by_player,
explosion_radius: None,
this_entity: false,
};
ctx.evaluate(table, random)
}
@@ -1122,6 +1185,8 @@ struct LootContext<'a> {
killed_by_player: bool,
/// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops.
explosion_radius: Option<f32>,
/// `LootContextParams.THIS_ENTITY` is set (a player broke the block).
this_entity: bool,
}
impl LootContext<'_> {
/// Level of an enchantment on the tool / killer's weapon.
@@ -1282,6 +1347,15 @@ impl LootContext<'_> {
};
random.next_float() < chance
}
// `this` with no checks (snow, chorus flower) holds when an entity
// broke the block (LootItemEntityPropertyCondition needs the entity).
"minecraft:entity_properties"
if self.this_entity
&& c["entity"].as_str() == Some("this")
&& c["predicate"].as_object().is_none_or(|p| p.is_empty()) =>
{
true
}
// Entity flags, equipment and damage-source predicates: none hold
// for an unenchanted player kill without fire or lightning.
"minecraft:entity_properties" | "minecraft:damage_source_properties" => false,
@@ -1667,6 +1741,7 @@ mod tests {
held,
killed_by_player: block.is_empty(),
explosion_radius: None,
this_entity: false,
}
}
+76 -2
View File
@@ -25,6 +25,7 @@ pub mod creaking;
pub mod creaking_heart;
pub mod cube;
pub mod data;
pub mod doors;
pub mod drops;
pub mod enderman;
pub mod equine;
@@ -69,6 +70,7 @@ pub mod tame;
pub mod trader;
pub mod transport_items;
pub mod trial_spawner;
pub mod turtle;
pub mod undead;
pub mod vex;
pub mod villager;
@@ -666,6 +668,8 @@ pub struct Extra {
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
pub items: Vec<Option<crate::items::ItemStack>>,
/// `Piglin.inventory` (`SimpleContainer(8)`): what it picked up and kept.
pub inventory: Vec<crate::items::ItemStack>,
pub tame: bool,
pub sitting: bool,
/// The owner's UUID (tamed animals).
@@ -974,6 +978,14 @@ pub enum MobEvent {
owner: u32,
},
Shoot([f64; 3], [f64; 3]),
/// The mob the `Explode` right after this comes from
/// (`ServerExplosion.source`), and whether it is a charged creeper: the
/// exploding creeper is already out of the mob list when the game applies
/// the blast, so its victims' loot cannot look it up.
ExplosionSource {
mob: u32,
charged: bool,
},
Explode([f64; 3], f32),
/// Melee or ranged damage to another mob.
AttackMob {
@@ -1010,6 +1022,24 @@ pub enum MobEvent {
pos: [i32; 3],
open: bool,
},
/// `BreakDoorGoal.tick` at its end: the door is removed (`removeBlock`),
/// then level events 1021 and 2001 with the state that is left there.
BreakDoor {
pos: [i32; 3],
},
/// `Level.destroyBlockProgress` for a mob's crack on a block (`-1`
/// clears it).
DestroyProgress {
mob: u32,
pos: [i32; 3],
progress: i32,
},
/// `Level.levelEvent`: the game plays and sends the event.
LevelEvent {
id: i32,
pos: [i32; 3],
data: i32,
},
/// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock).
BreakBlock {
pos: [i32; 3],
@@ -1107,6 +1137,13 @@ pub enum MobEvent {
partner: u32,
child: Option<([i32; 3], Option<u8>)>,
},
/// `WorkAtComposter.useWorkstation`: a farmer at its composter makes
/// bread and composts seeds (the game applies it to the villager's
/// inventory and the block).
WorkAtComposter {
mob: u32,
pos: [i32; 3],
},
/// A villager asks whether enough neighbours want an iron golem.
GolemCheck {
mob: u32,
@@ -1135,8 +1172,10 @@ pub enum MobEvent {
target: Who,
aggressive: bool,
},
/// Drop the loot of a gift table (chicken eggs, armadillo scutes).
/// Drop the loot of a gift table (chicken eggs, sniffer seeds) with the
/// mob as `this` (`LivingEntity.dropFromGiftLootTable`).
GiftLoot {
mob: u32,
table: &'static str,
at: [f64; 3],
},
@@ -1167,6 +1206,18 @@ pub enum MobEvent {
DigParticles {
at: [f64; 3],
},
/// `Zombie.hurtServer`: a zombie hurt with a target in sight (its own,
/// else the attacker) may call a reinforcement against it on Hard.
Reinforcements {
mob: u32,
target: Who,
},
/// `LevelEvent.PARTICLES_DESTROY_BLOCK` (2001) at `pos` for the block at
/// `block`: a turtle's digging.
BlockBreakEffect {
pos: [i32; 3],
block: [i32; 3],
},
/// `Warden.applyDarknessAround`: darkness for survival players nearby.
Darkness {
at: [f64; 3],
@@ -1263,6 +1314,14 @@ pub struct Seen {
pub sitting: bool,
/// `Entity.isVehicle` or `isPassenger`.
pub ridden: bool,
/// The active effects, without namespace (`slowness`, `poison`...).
pub effects: Vec<&'static str>,
}
impl Seen {
/// `LivingEntity.hasEffect`, by id without namespace.
pub fn has_effect(&self, effect: &str) -> bool {
self.effects.contains(&effect)
}
}
impl Mob {
pub fn burning_time(&self) -> f64 {
@@ -1337,6 +1396,12 @@ impl Mob {
],
sitting: m.extra.sitting,
ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(),
effects: m
.extra
.effects
.iter()
.map(|e| e.0.trim_start_matches("minecraft:"))
.collect(),
}
}
/// `EntityType.getCategory`'s name.
@@ -1481,6 +1546,8 @@ pub struct PlayerView {
pub yaw: f32,
/// The Hero of the Village effect.
pub hero: bool,
/// The active effects, without namespace (`slowness`, `poison`...).
pub effects: Vec<&'static str>,
/// The player's UUID (villagers' gossip is keyed by it).
pub uuid: [i32; 4],
/// The mobs on the player's team (`isAlliedTo`): combat targeting
@@ -1490,6 +1557,12 @@ pub struct PlayerView {
/// (`EntitySelector.pushableBy` on the client).
pub remote: bool,
}
impl PlayerView {
/// `LivingEntity.hasEffect`, by id without namespace.
pub fn has_effect(&self, effect: &str) -> bool {
self.effects.contains(&effect)
}
}
#[derive(Clone)]
pub struct MobWorld<'a> {
pub world: &'a World,
@@ -1865,7 +1938,8 @@ impl Mob {
/// Movement speed attribute bonus (baby zombies, sprinting modifiers).
/// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level).
pub fn movement_speed(&self) -> f64 {
let mut v = strider::movement_speed(self, self.attrs.speed) * self.speed_bonus();
let mut v = strider::movement_speed(self, witch::speed(self, self.attrs.speed))
* self.speed_bonus();
for (e, _, amp) in &self.extra.effects {
match *e {
"minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1),
+26 -3
View File
@@ -184,6 +184,9 @@ pub fn register(m: &mut Mob) {
if m.species() == Species::Rabbit {
super::rabbit::register(m);
}
if m.species() == Species::Turtle {
super::turtle::register(m);
}
}
Family::Inert => {}
Family::Witch => super::witch::register(m),
@@ -716,6 +719,14 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
// setAge at the age boundary: refreshDimensions.
if m.extra.age >= 0 {
m.fudge_position_after_size_change(w, bw, bh);
// Turtle.ageBoundaryReached: a grown turtle drops a scute.
if m.species() == Species::Turtle {
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/turtle_grow",
at: [m.position.x, m.position.y, m.position.z],
});
}
}
} else if m.extra.age > 0 {
m.extra.age -= 1;
@@ -750,7 +761,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) && m.extra.head.is_none() {
m.ignite_for_ticks(160);
}
species_ai_step(m, w, events);
species_ai_step(m, w, level_random, events);
}
impl Mob {
/// LivingEntity.isPushable (and the push it takes from `Entity.push(Entity)`):
@@ -948,6 +959,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
| Species::Parched
| Species::WitherSkeleton
| Species::ZombifiedPiglin => undead::custom_server_ai_step(m, cx),
Species::Vindicator => super::illager::vindicator_server_ai_step(m),
Species::Enderman => super::enderman::custom_server_ai_step(m, cx),
Species::Blaze => super::nether::blaze_server_ai_step(m, cx),
Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx),
@@ -959,7 +971,12 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
_ => {}
}
}
fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
fn species_ai_step(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) {
if family(m.species()) == Family::Aquatic {
aquatic::ai_step(m, w, events);
}
@@ -992,7 +1009,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
Species::Shulker => {
super::shulker::tick(m, w, events);
super::shulker::ai_step(m, w, events);
super::shulker::ai_step(m, w, level_random, events);
}
Species::SnowGolem => super::golem::snow_ai_step(m, w, events),
Species::CopperGolem => super::copper_golem::ai_step(m, w, events),
@@ -1004,6 +1021,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events),
Species::Chicken => farm::chicken_ai_step(m, w, events),
Species::Fox => super::fox::ai_step(m, w, events),
Species::Turtle => super::turtle::ai_step(m, w, events),
Species::Sheep if m.extra.anim_ticks > 0 => {
m.extra.anim_ticks -= 1;
}
@@ -1329,6 +1347,11 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) {
Species::Warden => super::warden::hurt(m, source),
Species::Wolf => super::tame::after_hurt(m, source),
Species::Nautilus | Species::ZombieNautilus => super::nautilus::after_hurt(m, source),
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin => super::undead::after_hurt(m, source),
// NeutralMob: an iron golem hit by the player stays angry a while.
// PiglinAi.wasHurtBy: drop what is being admired, no admiring for
// a while after a player's hit, and anger.
+2 -2
View File
@@ -969,8 +969,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
s,
&Turtle {
on_land: !m.fluids.in_water && m.on_ground,
laying_egg: false,
has_egg: false,
laying_egg: m.extra.flag2,
has_egg: m.extra.flag,
},
),
Species::Strider => strider(p, s, m.rider.is_some()),
+252
View File
@@ -0,0 +1,252 @@
//! Doors a mob gets through on its own: `DoorInteractGoal` with its two
//! users, `BreakDoorGoal` (zombies that can break doors, vindicators in a
//! raid) and `OpenDoorGoal` (`AbstractIllager.RaiderOpenDoorGoal`).
use super::{
Mob, MobEvent, MobWorld, Species,
goals::{Cx, Goal, MOVE, goal_clone, reduced},
nav::NavKind,
raider,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
/// `DefaultDoorBreakTime`: `BreakDoorGoal.getDoorBreakTime` is
/// `max(240, doorBreakTime)`, and the vindicator's 6 is below it.
const DOOR_BREAK_TIME: i32 = 240;
/// `GoalUtils.hasGroundPathNavigation`: ground, wall-climbing and
/// amphibious navigations walk.
pub fn can_navigate_ground(m: &Mob) -> bool {
matches!(
m.ai.nav.kind,
NavKind::Ground | NavKind::WallClimber | NavKind::Amphibious
)
}
/// `Zombie.setCanBreakDoors`: only a mob that walks can break doors, and
/// then its navigation opens them.
pub fn set_can_break_doors(m: &mut Mob, can_break: bool) {
let can_break = can_break && can_navigate_ground(m);
m.extra.can_break_doors = can_break;
m.ai.nav.can_open_doors = can_break;
}
/// The species that extend `Zombie` (`CanBreakDoors` is theirs to save).
pub fn is_zombie(s: Species) -> bool {
matches!(
s,
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin
)
}
/// `DoorBlock.isWoodenDoor`: a door a hand opens, which is any but iron.
fn wooden_door(w: &MobWorld, p: [i32; 3]) -> bool {
let name = w.block_name(p[0], p[1], p[2]);
name.ends_with("_door") && name != "minecraft:iron_door"
}
/// `DoorInteractGoal`'s door: where it is and whether one is there.
#[derive(Clone, Debug, Default)]
struct Interact {
door: [i32; 3],
has_door: bool,
}
impl Interact {
/// `DoorInteractGoal.canUse`: the mob bumped into something and a
/// wooden door is on its path within 1.5 blocks, or at its own head.
fn can_use(&mut self, m: &Mob, w: &MobWorld) -> bool {
if !can_navigate_ground(m) || !m.horizontal_collision {
return false;
}
let Some(path) = m.ai.nav.path.as_ref().filter(|p| !p.is_done()) else {
return false;
};
for node in path
.nodes
.iter()
.take((path.next + 2).min(path.nodes.len()))
{
self.door = [node.x, node.y + 1, node.z];
let dx = m.position.x - f64::from(node.x);
let dz = m.position.z - f64::from(node.z);
if dx * dx + dz * dz <= 2.25 {
self.has_door = wooden_door(w, self.door);
if self.has_door {
return true;
}
}
}
let at = m.position;
self.door = [
at.x.floor() as i32,
at.y.floor() as i32 + 1,
at.z.floor() as i32,
];
self.has_door = wooden_door(w, self.door);
self.has_door
}
/// `DoorInteractGoal.isOpen`: the door is still there and open.
fn is_open(&mut self, w: &MobWorld) -> bool {
if !self.has_door {
return false;
}
let d = self.door;
if !w.block_name(d[0], d[1], d[2]).ends_with("_door") {
self.has_door = false;
return false;
}
w.prop(d[0], d[1], d[2], "open") == Some("true")
}
/// `DoorInteractGoal.setOpen`.
fn set_open(&self, cx: &mut Cx, open: bool) {
let d = self.door;
if self.has_door && cx.w.block_name(d[0], d[1], d[2]).ends_with("_door") {
cx.events.push(MobEvent::SetDoorOpen { pos: d, open });
}
}
}
/// `BlockPos.closerToCenterThan`.
fn closer_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool {
Vec3::new(
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
)
.distance_squared(at)
< distance * distance
}
/// `BreakDoorGoal`: crack the door in the way for 240 ticks, then remove it.
/// A zombie does it on hard only; `Vindicator.VindicatorBreakDoorGoal` on
/// normal and hard, in a raid, and holds the mob's movement.
#[derive(Clone, Debug)]
pub struct BreakDoor {
interact: Interact,
vindicator: bool,
break_time: i32,
last_break_progress: i32,
}
impl BreakDoor {
/// `Zombie.breakDoorGoal`, added when the zombie can break doors.
pub fn zombie() -> Self {
Self::new(false)
}
/// `Vindicator.VindicatorBreakDoorGoal`.
pub fn vindicator() -> Self {
Self::new(true)
}
fn new(vindicator: bool) -> Self {
Self {
interact: Interact::default(),
vindicator,
break_time: 0,
last_break_progress: -1,
}
}
/// `DOOR_BREAKING_PREDICATE`.
fn valid_difficulty(&self, w: &MobWorld) -> bool {
if self.vindicator {
w.difficulty.normal || w.difficulty.hard
} else {
w.difficulty.hard
}
}
/// `BreakDoorGoal.canUse` after `DoorInteractGoal.canUse`.
fn can_break(&mut self, m: &Mob, w: &MobWorld) -> bool {
self.interact.can_use(m, w)
&& w.mob_griefing
&& self.valid_difficulty(w)
&& !self.interact.is_open(w)
}
}
impl Goal for BreakDoor {
goal_clone!();
fn flags(&self) -> u8 {
if self.vindicator { MOVE } else { 0 }
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if self.vindicator {
return raider::has_active_raid(m)
&& m.random.next_int_bound(reduced(10)).unwrap_or(1) == 0
&& self.can_break(m, cx.w);
}
m.extra.can_break_doors && self.can_break(m, cx.w)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
(!self.vindicator || raider::has_active_raid(m))
&& self.break_time <= DOOR_BREAK_TIME
&& !self.interact.is_open(cx.w)
&& closer_to_center(self.interact.door, m.position, 2.0)
&& self.valid_difficulty(cx.w)
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
self.break_time = 0;
if self.vindicator {
m.ai.no_action_time = 0;
}
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
cx.events.push(MobEvent::DestroyProgress {
mob: m.id,
pos: self.interact.door,
progress: -1,
});
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let door = self.interact.door;
if m.random.next_int_bound(20).unwrap_or(1) == 0 {
cx.events.push(MobEvent::LevelEvent {
id: 1019,
pos: door,
data: 0,
});
if !m.ai.swinging {
m.swing();
}
}
self.break_time += 1;
let progress = (self.break_time as f32 / DOOR_BREAK_TIME as f32 * 10.0) as i32;
if progress != self.last_break_progress {
cx.events.push(MobEvent::DestroyProgress {
mob: m.id,
pos: door,
progress,
});
self.last_break_progress = progress;
}
if self.break_time == DOOR_BREAK_TIME && self.valid_difficulty(cx.w) {
cx.events.push(MobEvent::BreakDoor { pos: door });
}
}
}
/// `AbstractIllager.RaiderOpenDoorGoal` (`OpenDoorGoal` that does not wait
/// to close): open the door in the way during a raid. It never continues, so
/// it closes the door again as soon as it stops.
#[derive(Clone, Debug, Default)]
pub struct RaiderOpenDoor {
interact: Interact,
}
impl Goal for RaiderOpenDoor {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.interact.can_use(m, cx.w) && raider::has_active_raid(m)
}
fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool {
false
}
fn start(&mut self, _m: &mut Mob, cx: &mut Cx) {
self.interact.set_open(cx, true);
}
fn stop(&mut self, _m: &mut Mob, cx: &mut Cx) {
self.interact.set_open(cx, false);
}
}
+11
View File
@@ -351,6 +351,9 @@ pub fn loot_entity(m: &Mob, vehicle: Option<LootEntity>) -> LootEntity {
.to_owned(),
);
}
if s == S::Chicken {
e.chicken_variant = super::finalize::variant_component(m).map(|(_, id)| id);
}
e.powered = s == S::Creeper && m.extra.charged;
e.equipment = SLOTS
.iter()
@@ -456,6 +459,14 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec<Drop
out.push(Drop::Item(loot_stack("minecraft:nether_star", 1)));
}
}
// Piglin.dropCustomDeathLoot: everything in its inventory.
if s == Species::Piglin {
for stack in m.extra.inventory.drain(..) {
let mut item = loot_stack(&stack.item, stack.count as i32);
item.damage = stack.damage as i32;
out.push(Drop::Item(item));
}
}
// dropEquipment: AbstractHorse's inventory, then a chested horse's chest.
if equine::is_equine(s) {
for stack in m.extra.items.iter().flatten() {
+1
View File
@@ -80,6 +80,7 @@ pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::Sound("entity.chicken.egg", at, 1.0, pitch));
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/chicken_lay",
at,
});
+72 -56
View File
@@ -590,6 +590,14 @@ pub fn has_modifier(m: &Mob, a: Attr, id: &str) -> bool {
.as_ref()
.is_some_and(|s| s.modifiers.iter().any(|x| x.attr == a && x.id == id))
}
/// The amount of a permanent modifier, if the mob has it.
pub fn modifier_amount(m: &Mob, a: Attr, id: &str) -> Option<f64> {
m.extra
.attributes
.as_ref()
.and_then(|s| s.modifiers.iter().find(|x| x.attr == a && x.id == id))
.map(|x| x.amount)
}
/// `addOrReplacePermanentModifier`.
pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op) {
let s = m.extra.attributes.get_or_insert_with(Box::default);
@@ -605,6 +613,59 @@ pub fn add_modifier(m: &mut Mob, a: Attr, id: &'static str, amount: f64, op: Op)
}
refresh(m, a);
}
/// `Zombie.handleAttributes`, from the zombie's own random.
pub fn zombie_attributes(m: &mut Mob, special: f32, reason: Reason) {
let r = &mut m.random;
let reinforcements = if m.kind.species == Species::ZombifiedPiglin {
0.0
} else {
r.next_double() * f64::from(0.1f32)
};
let knockback = r.next_double() * f64::from(0.05f32);
let follow = r.next_double() * 1.5 * f64::from(special);
let leader = r.next_float() < special * 0.05;
let leader_rolls = leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0));
set_base(m, Attr::SpawnReinforcements, reinforcements);
add_modifier(
m,
Attr::KnockbackResistance,
"minecraft:random_spawn_bonus",
knockback,
Op::AddValue,
);
if follow > 1.0 {
add_modifier(
m,
Attr::FollowRange,
"minecraft:zombie_random_spawn_bonus",
follow,
Op::AddMultipliedTotal,
);
}
if let Some((reinforce, health)) = leader_rolls {
add_modifier(
m,
Attr::SpawnReinforcements,
"minecraft:leader_zombie_bonus",
reinforce,
Op::AddValue,
);
add_modifier(
m,
Attr::MaxHealth,
"minecraft:leader_zombie_bonus",
health,
Op::AddMultipliedTotal,
);
if !matches!(
reason,
Reason::Conversion | Reason::Load | Reason::DimensionTravel
) {
m.health = max_health(m);
}
super::doors::set_can_break_doors(m, true);
}
}
pub fn max_health(m: &Mob) -> f32 {
value(m, Attr::MaxHealth) as f32
}
@@ -829,6 +890,14 @@ pub fn set_item(m: &mut Mob, slot: usize, id: &str) {
}
gear::set(m, gear_slot(slot), Vec::new());
}
/// The enchantments on what `m` has in `slot`.
pub fn slot_enchantments(m: &Mob, slot: usize) -> gear::Levels {
gear::gear(m).map_or_else(Vec::new, |g| g.slots[gear_slot(slot)].clone())
}
/// Replace the enchantments of what `m` has in `slot` (after `set_item`).
pub fn set_slot_enchantments(m: &mut Mob, slot: usize, levels: gear::Levels) {
gear::set(m, gear_slot(slot), levels);
}
/// `Mob.setDropChance`.
pub fn set_drop_chance(m: &mut Mob, slot: usize, chance: f32) {
let c = m
@@ -1144,70 +1213,17 @@ impl<L: FinalizeLevel + ?Sized, R: RandomSource> Ctx<'_, L, R> {
}
}
}
m.extra.can_break_doors = self.float() < special * 0.1;
let can_break_doors = self.float() < special * 0.1;
super::doors::set_can_break_doors(m, can_break_doors);
if reason != Reason::Conversion {
self.populate(m);
self.enchant(m);
}
}
self.halloween(m);
self.zombie_attributes(m, special, reason);
zombie_attributes(m, special, reason);
g
}
/// `Zombie.handleAttributes`, from the zombie's own random.
fn zombie_attributes(&mut self, m: &mut Mob, special: f32, reason: Reason) {
let r = &mut m.random;
let reinforcements = if m.kind.species == Species::ZombifiedPiglin {
0.0
} else {
r.next_double() * f64::from(0.1f32)
};
let knockback = r.next_double() * f64::from(0.05f32);
let follow = r.next_double() * 1.5 * f64::from(special);
let leader = r.next_float() < special * 0.05;
let leader_rolls =
leader.then(|| (r.next_double() * 0.25 + 0.5, r.next_double() * 3.0 + 1.0));
set_base(m, Attr::SpawnReinforcements, reinforcements);
add_modifier(
m,
Attr::KnockbackResistance,
"minecraft:random_spawn_bonus",
knockback,
Op::AddValue,
);
if follow > 1.0 {
add_modifier(
m,
Attr::FollowRange,
"minecraft:zombie_random_spawn_bonus",
follow,
Op::AddMultipliedTotal,
);
}
if let Some((reinforce, health)) = leader_rolls {
add_modifier(
m,
Attr::SpawnReinforcements,
"minecraft:leader_zombie_bonus",
reinforce,
Op::AddValue,
);
add_modifier(
m,
Attr::MaxHealth,
"minecraft:leader_zombie_bonus",
health,
Op::AddMultipliedTotal,
);
if !matches!(
reason,
Reason::Conversion | Reason::Load | Reason::DimensionTravel
) {
m.health = max_health(m);
}
m.extra.can_break_doors = true;
}
}
fn husk(&mut self, m: &mut Mob, g: Option<Group>, reason: Reason) -> Option<Group> {
let mut g = self.zombie(m, g, reason);
if reason != Reason::Conversion {
+37
View File
@@ -1210,6 +1210,9 @@ pub struct NearestTarget {
pub interval: i32,
/// Extra condition on the attacker, checked after the random interval.
pub when: Option<fn(&Mob, &MobWorld) -> bool>,
/// Mobs closer than this squared distance are not picked
/// (`GuardianAttackSelector`: `distanceToSqr > 9`).
pub beyond_sqr: Option<f64>,
/// A condition checked before anything else, by subclasses overriding
/// `canUse` (SpiderTargetGoal: only in the dark).
pub gate: Option<fn(&Mob, &MobWorld) -> bool>,
@@ -1242,6 +1245,7 @@ impl NearestTarget {
must_reach: false,
interval: reduced(10),
when: None,
beyond_sqr: None,
gate: None,
label: None,
found: None,
@@ -1274,6 +1278,10 @@ impl NearestTarget {
self.when = Some(f);
self
}
pub fn beyond(mut self, distance_sqr: f64) -> Self {
self.beyond_sqr = Some(distance_sqr);
self
}
pub fn gate(mut self, f: fn(&Mob, &MobWorld) -> bool) -> Self {
self.gate = Some(f);
self
@@ -1284,9 +1292,25 @@ impl NearestTarget {
self
}
}
/// `AbstractIllager.canAttack`: a baby `AbstractVillager` is never attacked.
fn illager_spares(attacker: Species, target: &Seen) -> bool {
matches!(
attacker,
Species::Pillager | Species::Vindicator | Species::Evoker | Species::Illusioner
) && target.baby
&& matches!(target.species, Species::Villager | Species::WanderingTrader)
}
/// TargetGoal.canContinueToUse
pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(who) = m.ai.target else { return false };
if let Who::Mob(id) = who
&& cx
.w
.seen(id)
.is_some_and(|s| illager_spares(m.species(), s))
{
return false;
}
let Some(t) = cx.w.target_info(who) else {
return false;
};
@@ -1345,10 +1369,12 @@ impl Goal for NearestTarget {
prey => {
let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z);
let id = m.id;
let attacker = m.species();
let candidates: Vec<(u32, Vec3)> =
cx.w.nearby(pos, range, move |s| {
s.id != id
&& !s.playing_dead
&& !illager_spares(attacker, s)
&& match prey {
Prey::Species(list) => list.contains(&s.species),
Prey::Filter(f) => f(s),
@@ -1361,6 +1387,9 @@ impl Goal for NearestTarget {
if m.distance_sqr(cpos) > range * range {
continue;
}
if self.beyond_sqr.is_some_and(|d| m.distance_sqr(cpos) <= d) {
continue;
}
if !m.sees(cx.w, Who::Mob(cid)) {
continue;
}
@@ -1779,6 +1808,10 @@ impl Goal for Breed {
if tamable && (!m.extra.tame || m.extra.sitting) {
return false;
}
// TurtleBreedGoal.canUse: not while carrying an egg.
if species == Species::Turtle && super::turtle::has_egg(m) {
return false;
}
let id = m.id;
// Horses and donkeys breed together (AbstractHorse.canParent: tame).
// Sniffer.canMate: calm states only.
@@ -1857,6 +1890,10 @@ impl Goal for Breed {
});
m.extra.in_love = 0;
m.extra.age = 6000;
// TurtleBreedGoal.breed: the mother carries an egg, not a baby.
if m.species() == Species::Turtle {
m.extra.flag = true;
}
cx.events.push(MobEvent::Breed {
parent: m.id,
partner: p.id,
+6 -3
View File
@@ -61,7 +61,8 @@ pub fn register(m: &mut Mob) {
NearestTarget::species(
&[Species::Squid, Species::GlowSquid, Species::Axolotl],
true,
),
)
.beyond(9.0),
);
}
/// `GuardianAttackGoal`.
@@ -120,9 +121,11 @@ impl Goal for GuardianAttack {
1.0,
));
} else if self.attack_time >= attack_duration(m) {
// Indirect magic (1, +2 for the elder; NORMAL difficulty), then
// Indirect magic (1, +2 on Hard, +2 for the elder), then
// doHurtTarget.
let magic = if is_elder(m) { 3.0 } else { 1.0 };
let magic = 1.0
+ if cx.w.difficulty.hard { 2.0 } else { 0.0 }
+ if is_elder(m) { 2.0 } else { 0.0 };
let from = [m.position.x, m.position.y, m.position.z];
match who {
Who::Player => cx.events.push(MobEvent::DamagePlayer {
@@ -177,6 +177,10 @@ pub fn creeper_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
if m.swell >= 30 {
m.swell = 30;
let radius = if m.extra.charged { 6.0 } else { 3.0 };
events.push(MobEvent::ExplosionSource {
mob: m.id,
charged: m.extra.charged,
});
events.push(MobEvent::Explode(
[m.position.x, m.position.y, m.position.z],
radius,
+15 -4
View File
@@ -72,6 +72,8 @@ pub fn register_vindicator(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, avoid_creaking(1.0, 1.2));
g.add(2, super::doors::BreakDoor::vindicator());
g.add(3, super::doors::RaiderOpenDoor::default());
g.add(4, super::raider::HoldGroundAttack::new(10.0));
g.add(5, MeleeAttack::new(1.0, false));
g.add(8, Stroll::new(0.6));
@@ -86,6 +88,13 @@ pub fn register_vindicator(m: &mut Mob) {
.when(|m, _| m.custom_name.as_deref() == Some("Johnny")),
);
}
/// `Vindicator.customServerAiStep`: its navigation opens doors while a raid
/// is at its position.
pub fn vindicator_server_ai_step(m: &mut Mob) {
if super::doors::can_navigate_ground(m) {
m.ai.nav.can_open_doors = super::raider::state(m).is_some_and(|s| s.raided);
}
}
// Evoker state: `counter` spellCastingTickCount, `variant2` the spell
// being cast (0 none, 1 vexes, 2 fangs, 3 wololo), `counter2` the wololo
// sheep's id.
@@ -179,8 +188,8 @@ impl Goal for UseSpell {
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let age = i64::from(m.age);
if self.spell == Spell::Wololo {
// EvokerWololoSpellGoal.canUse: a blue sheep within 16 (4 up or
// down), no target, griefing on.
// EvokerWololoSpellGoal.canUse: a blue sheep within the box
// (16 sideways, 4 up or down) and `range(16)`, no target, griefing on.
if m.ai.target.is_some() || m.extra.counter > 0 || age < self.next || !cx.w.mob_griefing
{
return false;
@@ -196,6 +205,7 @@ impl Goal for UseSpell {
&& (s.position.x - p.x).abs() <= 16.0
&& (s.position.y - p.y).abs() <= 4.0
&& (s.position.z - p.z).abs() <= 16.0
&& s.position.distance_squared(p) <= 16.0 * 16.0
})
.map(|s| s.id)
.collect();
@@ -210,7 +220,8 @@ impl Goal for UseSpell {
return false;
}
if self.spell == Spell::Vexes {
// EvokerSummonSpellGoal: fewer vexes nearby than a roll of 1..8.
// EvokerSummonSpellGoal: fewer vexes within `range(16)` than a
// roll of 1..8.
let p = m.position;
let vexes =
cx.w.others
@@ -218,7 +229,7 @@ impl Goal for UseSpell {
.filter(|s| {
s.species == Species::Vex
&& s.alive
&& s.position.distance_squared(p) <= 16.0 * 16.0 * 3.0
&& s.position.distance_squared(p) <= 16.0 * 16.0
})
.count() as i32;
return m.random.next_int_bound(8).unwrap_or(0) + 1 > vexes;
+75
View File
@@ -15,6 +15,9 @@ use std::f32::consts::PI;
/// `PiglinAi.ADMIRE_DURATION`.
pub const ADMIRE: i32 = 119;
/// `PiglinAi.eat`: the `ATE_RECENTLY` memory lasts 200 ticks (kept in
/// `extra.ints[0]` of a piglin).
pub const ATE_RECENTLY: i32 = 200;
/// `AbstractPiglin.CONVERSION_TIME` (and the hoglin's).
const CONVERSION: i32 = 300;
@@ -45,6 +48,7 @@ pub fn register_piglin(m: &mut Mob) {
g.add(3, super::illager::crossbow_goal(1.0, 8.0));
}
g.add(3, MeleeAttack::new(1.0, true));
g.add(4, PiglinAvoidRepellent);
g.add(4, GoToWantedItem);
g.add(5, Stroll::avoiding_water(0.6));
g.add(6, LookAtPlayer::new(8.0));
@@ -176,6 +180,54 @@ impl Goal for BabyPanic {
self.0.stop(m, cx)
}
}
/// `PiglinAi.avoidRepellent`: `SetWalkTargetAwayFrom.pos(NEAREST_REPELLENT, 1.0, 8, false)`
/// of the idle activity. Closer than 8 blocks to a repellent and not walking
/// anywhere, walk away from it.
#[derive(Clone, Debug)]
struct PiglinAvoidRepellent;
impl Goal for PiglinAvoidRepellent {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(r) = m.extra.repellent else {
return false;
};
// The idle activity: not fighting or admiring, and no walk target yet.
if m.ai.target.is_some() || m.extra.using_item > 0 || !m.ai.nav.is_done() {
return false;
}
// Vec3.atBottomCenterOf.
let avoid = [
f64::from(r[0]) + 0.5,
f64::from(r[1]),
f64::from(r[2]) + 0.5,
];
if m.distance_sqr(Vec3::new(avoid[0], avoid[1], avoid[2])) >= 64.0 {
return false;
}
for _ in 0..10 {
if let Some(p) = m.land_random_pos_away(cx.w, 16, 7, avoid) {
let at = [
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32,
];
m.ai.pending_path = m.create_path_to(cx.w, at, 0);
return m.ai.pending_path.is_some();
}
}
false
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
!m.ai.nav.is_done()
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
let path = m.ai.pending_path.take();
m.nav_move_to_path(path, 1.0);
}
}
/// Admiring a gold item held in the off hand: stand and look at it.
#[derive(Clone, Debug)]
struct Admire;
@@ -257,6 +309,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.ai.target = None;
}
}
if m.species() == Species::Piglin && m.extra.ints[0] > 0 {
m.extra.ints[0] -= 1;
}
// Admiring disabled after being hit by a player.
if m.extra.egg_time > 0 {
m.extra.egg_time -= 1;
@@ -299,6 +354,26 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
} else {
m.extra.counter2 = 0;
}
// PiglinSpecificSensor (every 20 ticks): the nearest repelling block.
if m.species() == Species::Piglin && m.alive() && m.age.wrapping_add(m.id).is_multiple_of(20) {
m.extra.repellent = find_piglin_repellent(m, w);
}
}
/// `PiglinSpecificSensor.findNearestRepellent`: the nearest `#piglin_repellents`
/// block within 8 blocks sideways and 4 up or down; a soul campfire only
/// counts while lit.
fn find_piglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
let tag = w.block_tags.get("minecraft:piglin_repellents")?;
let at = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
w.nearest_block(at, 8, 4, |p, name| {
tag.contains(name)
&& (name != "minecraft:soul_campfire"
|| w.prop(p[0], p[1], p[2], "lit") == Some("true"))
})
}
/// `HoglinBase.hurtAndThrowTarget`.
pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
+3
View File
@@ -30,6 +30,9 @@ pub struct State {
pub celebrating: bool,
/// The raid is active (`hasActiveRaid`); set by the game every tick.
pub active_raid: bool,
/// A raid is active within 96 blocks (`ServerLevel.isRaided`); set by
/// the game every tick for vindicators.
pub raided: bool,
/// The raid is won or lost (`Raid.isOver`), lost (`isLoss`).
pub raid_over: bool,
pub raid_loss: bool,
+54 -4
View File
@@ -3,7 +3,7 @@
//! their face is lost or when badly hurt, and shrugging off arrows while
//! closed.
use super::{
Damage, DamageKind, Mob, MobEvent, MobWorld, Who,
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{
Cx, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround,
@@ -14,7 +14,7 @@ use crate::projectiles::{Projectile, ProjectileWorld, STEPS};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
random::{LegacyRandom, RandomSource},
};
use std::f32::consts::PI;
@@ -164,12 +164,62 @@ pub fn after_hurt(m: &mut Mob) {
m.extra.flag = true;
}
}
/// The deferred teleport of `after_hurt`.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
/// `Shulker.hurtServer` after a shulker bullet's damage: unless the
/// low-health teleport was drawn instead (`else if`), `hitByShulkerBullet`
/// runs on the next tick. Whether the shell is open is read here, at hurt
/// time, so a goal opening it before that tick cannot change the outcome.
pub fn hit_by_bullet(m: &mut Mob) {
if m.species() == Species::Shulker && !m.extra.flag && m.extra.counter != 0 {
m.extra.flag2 = true;
}
}
/// The deferred teleport of `after_hurt` and `hitByShulkerBullet`.
pub fn ai_step(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) {
if m.extra.flag {
m.extra.flag = false;
teleport(m, w, events);
}
if m.extra.flag2 {
m.extra.flag2 = false;
hit_by_shulker_bullet(m, w, level_random, events);
}
}
/// `Shulker.hitByShulkerBullet` (only queued by an open shulker): it
/// teleports, and leaves a new one of its colour behind unless shulkers
/// crowd the place (one in five fewer chances for every other shulker
/// within 8 blocks).
fn hit_by_shulker_bullet(
m: &mut Mob,
w: &MobWorld,
level_random: &mut LegacyRandom,
events: &mut Vec<MobEvent>,
) {
let old_position = m.position;
let old_box = m.bounds();
if !teleport(m, w, events) {
return;
}
let area = old_box.inflate(Vec3::new(8.0, 8.0, 8.0));
// The shulker itself stands within reach of its old box, so it counts.
let others = w
.others_near(area)
.filter(|s| {
s.alive && s.species == Species::Shulker && s.id != m.id && s.bounds.intersects(area)
})
.count();
let failure_chance = others as f32 / 5.0;
// The level's random, not the shulker's.
if level_random.next_float() < failure_chance {
return;
}
let mut baby = Mob::new(0, m.kind.clone(), old_position, 0.0);
baby.extra.color = m.extra.color;
events.push(MobEvent::Spawn(Box::new(baby)));
}
/// A ProjectileWorld over the mob world, for aiming a new bullet.
struct Probe<'a, 'w> {
@@ -94,6 +94,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
if current == DIGGING && now(m) == m.extra.ints[3] {
let h = head_block(m);
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/sniffer_digging",
at: [f64::from(h[0]), f64::from(h[1]), f64::from(h[2])],
});
@@ -35,6 +35,8 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b
#[derive(Clone, Copy, Debug)]
pub struct LocalDifficulty {
pub effective: f32,
/// The world difficulty is normal.
pub normal: bool,
/// The world difficulty is hard.
pub hard: bool,
}
@@ -45,9 +47,11 @@ impl LocalDifficulty {
/// the overworld clock, the chunk's inhabited time and the moon.
pub fn new(base: u8, total: i64, inhabited: i64, moon: f32) -> Self {
let hard = base == 3;
let normal = base == 2;
if base == 0 {
return Self {
effective: 0.0,
normal,
hard,
};
}
@@ -60,6 +64,7 @@ impl LocalDifficulty {
}
Self {
effective: f32::from(base) * (0.75 + global + local),
normal,
hard,
}
}
@@ -148,6 +153,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index,
S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random),
S::Mooshroom => m.extra.variant = 0,
// Turtle.finalizeSpawn: home is where it spawned.
S::Turtle => {
m.extra.home = Some([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
])
}
S::Frog => m.extra.variant = biome.frog,
S::Wolf => m.extra.variant = biome.wolf,
S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon),
@@ -158,6 +171,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
if m.random.next_float() < 0.05 {
m.extra.age = i32::MIN / 2;
}
// setCanBreakDoors(nextFloat() < special * 0.1), before the gear.
let can_break_doors = m.random.next_float() < difficulty.special() * 0.1;
super::doors::set_can_break_doors(m, can_break_doors);
if m.species() != S::Drowned {
populate_armor(m, difficulty);
}
@@ -191,6 +207,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
// ZombifiedPiglin.populateDefaultEquipmentSlots: a golden sword, or
// one time in 20 a golden spear.
S::ZombifiedPiglin => {
// Zombie.finalizeSpawn's setCanBreakDoors.
let can_break_doors = m.random.next_float() < difficulty.special() * 0.1;
super::doors::set_can_break_doors(m, can_break_doors);
let spear = m.random.next_int_bound(20).unwrap_or(1) == 0;
m.extra.main_hand = Some(
if spear {
@@ -264,6 +283,18 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Slime | S::MagmaCube => super::cube::finalize(m),
_ => {}
}
// Zombie.finalizeSpawn ends with handleAttributes: the reinforcement
// chance (and a leader's bonus) that `Zombie.hurtServer` reads.
if matches!(
m.species(),
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager | S::ZombifiedPiglin
) {
super::finalize::zombie_attributes(
m,
difficulty.special(),
super::finalize::Reason::Natural,
);
}
}
/// VillagerType.byBiome
pub fn villager_type(b: &BiomeFacts) -> u8 {
+209
View File
@@ -0,0 +1,209 @@
//! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her
//! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand
//! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`,
//! `extra.counter` `layEggCounter` and `extra.home` `homePos`.
use super::{
Mob, MobEvent, MobWorld,
goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced},
};
use horizon_core::random::RandomSource;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(1, Breed::new(1.0));
g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1)));
g.add(4, GoHome::default());
}
/// `Turtle.hasEgg`.
pub fn has_egg(m: &Mob) -> bool {
m.extra.flag
}
/// `Turtle.setLayingEgg`.
fn set_laying_egg(m: &mut Mob, on: bool) {
m.extra.counter = i32::from(on);
m.extra.flag2 = on;
}
/// `homePos.closerToCenterThan(position, distance)`. Spawning, hatching and
/// loading all set a home; one made any other way is at home where it stands.
fn close_to_home(m: &Mob, distance: f64) -> bool {
let home = m.extra.home.unwrap_or([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]);
let d = [
f64::from(home[0]) + 0.5 - m.position.x,
f64::from(home[1]) + 0.5 - m.position.y,
f64::from(home[2]) + 0.5 - m.position.z,
];
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < distance * distance
}
fn block_of(m: &Mob) -> [i32; 3] {
[
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]
}
/// `TurtleEggBlock.isSand`.
fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool {
w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2]))
}
/// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 {
let at = block_of(m);
let below = [at[0], at[1] - 1, at[2]];
if is_sand(w, below) {
events.push(MobEvent::BlockBreakEffect {
pos: at,
block: below,
});
}
}
}
/// `Turtle.TurtleLayEggGoal`: a mother with an egg within 9 blocks of home
/// walks to sand with air above, digs for 200 ticks and lays it.
#[derive(Clone, Debug)]
struct LayEgg(MoveToBlock);
impl LayEgg {
/// `isValidTarget`: sand with air above it.
fn valid(w: &MobWorld, p: [i32; 3]) -> bool {
w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) && is_sand(w, p)
}
}
impl Goal for LayEgg {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn name(&self) -> &'static str {
"TurtleLayEggGoal"
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !(has_egg(m) && close_to_home(m, 9.0)) {
return false;
}
// MoveToBlockGoal.canUse.
if self.0.next_start > 0 {
self.0.next_start -= 1;
return false;
}
self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
self.0.find_nearest(m, cx.w, Self::valid)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_continue(cx.w, Self::valid) && has_egg(m) && close_to_home(m, 9.0)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.start(m, cx.w);
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.tick(m, cx.w);
if m.fluids.in_water || !self.0.reached {
return;
}
if m.extra.counter < 1 {
set_laying_egg(m, true);
} else if m.extra.counter > 200 {
let at = [m.position.x, m.position.y, m.position.z];
let pitch = 0.9 + m.random.next_float() * 0.2;
cx.events
.push(MobEvent::Sound("entity.turtle.lay_egg", at, 0.3, pitch));
// Blocks.TURTLE_EGG with EGGS = nextInt(4) + 1 above the sand.
let eggs = m.random.next_int_bound(4).unwrap_or(0) + 1;
let registry = cx.w.registry;
let state = registry
.default_state("minecraft:turtle_egg")
.and_then(|d| registry.state(d).cloned())
.and_then(|mut s| {
s.properties.insert("eggs".into(), eggs.to_string());
registry.resolve(&s).ok()
});
let b = self.0.block;
if let Some(state) = state {
cx.events.push(MobEvent::SetBlock {
pos: [b[0], b[1] + 1, b[2]],
state,
});
}
m.extra.flag = false;
set_laying_egg(m, false);
m.extra.in_love = 600;
}
if m.extra.flag2 {
m.extra.counter += 1;
}
}
}
/// `Turtle.TurtleGoHomeGoal`: a mother with an egg heads home; any adult
/// that strayed 64 blocks away does now and then.
#[derive(Clone, Debug, Default)]
struct GoHome {
stuck: bool,
close_to_home_try_ticks: i32,
}
impl Goal for GoHome {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn name(&self) -> &'static str {
"TurtleGoHomeGoal"
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
if m.is_baby() {
false
} else if has_egg(m) {
true
} else {
m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0)
}
}
fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) {
self.stuck = false;
self.close_to_home_try_ticks = 0;
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
!close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600)
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let home = m.extra.home.unwrap_or(block_of(m));
let close = close_to_home(m, 16.0);
if close {
self.close_to_home_try_ticks += 1;
}
if !m.ai.nav.is_done() {
return;
}
let to = [
f64::from(home[0]) + 0.5,
f64::from(home[1]),
f64::from(home[2]) + 0.5,
];
let mut next = m
.default_random_pos_towards(cx.w, 16, 3, to, std::f64::consts::PI / 10.0)
.or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2));
if let Some(at) = next
&& !close
&& cx.w.block_name(
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
) != "minecraft:water"
{
next = m.default_random_pos_towards(cx.w, 16, 5, to, std::f64::consts::FRAC_PI_2);
}
match next {
Some(at) => {
m.nav_move_to(cx.w, at, 1.0);
}
None => self.stuck = true,
}
}
}
+15 -1
View File
@@ -1,7 +1,8 @@
//! Zombies (zombie, husk, drowned, zombie villager) and skeletons (skeleton,
//! stray, bogged, wither skeleton): goals, bow attacks, water conversion.
use super::{
Mob, MobEvent, Species, Who,
Damage, Mob, MobEvent, Species, Who,
doors::BreakDoor,
goals::{
Avoid, AvoidEntity, Cx, FleeSun, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack,
NearestTarget, RandomLookAround, RestrictSun, Stroll, goal_clone,
@@ -10,11 +11,22 @@ use super::{
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::{geometry::Vec3, random::RandomSource};
/// `Zombie.hurtServer`, once the hit landed: a zombie with a target (its own,
/// else a living attacker) asks the game to try calling a reinforcement; the
/// difficulty, chance and spawn tests are the game's (`call_reinforcements`).
pub fn after_hurt(m: &mut Mob, source: &Damage) {
if let Some(target) = m.ai.target.or(source.attacker) {
m.outbox
.push(MobEvent::Reinforcements { mob: m.id, target });
}
}
pub fn register(m: &mut Mob) {
use Species as S;
match m.species() {
S::Zombie | S::Husk | S::ZombieVillager => {
let g = &mut m.ai.goals;
g.add(1, BreakDoor::zombie());
g.add(4, AttackTurtleEgg::default());
g.add(8, LookAtPlayer::new(8.0));
g.add(8, RandomLookAround::default());
@@ -42,6 +54,7 @@ pub fn register(m: &mut Mob) {
S::ZombifiedPiglin => {
// ZombifiedPiglin.addBehaviourGoals: neutral until provoked.
let g = &mut m.ai.goals;
g.add(1, BreakDoor::zombie());
g.add(8, LookAtPlayer::new(8.0));
g.add(8, RandomLookAround::default());
g.add(2, MeleeAttack::new(1.0, false).zombie());
@@ -58,6 +71,7 @@ pub fn register(m: &mut Mob) {
S::Drowned => {
// Zombie.registerGoals, then Drowned.addBehaviourGoals.
let g = &mut m.ai.goals;
g.add(1, BreakDoor::zombie());
g.add(4, AttackTurtleEgg::default());
g.add(8, LookAtPlayer::new(8.0));
g.add(8, RandomLookAround::default());
+2 -1
View File
@@ -29,6 +29,7 @@ pub fn register(m: &mut Mob) {
g.add(8, RandomMove);
g.add(9, LookAtPlayer::new(3.0).probability(1.0));
g.add(10, LookAtPlayer::mobs(8.0));
// `HurtByTargetGoal(this, Raider.class)`: raiders are ignored, vexes are not.
let mut hurt = HurtByTarget::new().alert();
hurt.ignore = vec![
Species::Pillager,
@@ -36,7 +37,7 @@ pub fn register(m: &mut Mob) {
Species::Evoker,
Species::Illusioner,
Species::Witch,
Species::Vex,
Species::Ravager,
];
m.ai.targets.add(1, hurt);
m.ai.targets.add(2, CopyOwnerTarget);
+18 -24
View File
@@ -448,6 +448,24 @@ impl Ext {
}
(stack.count > 0).then_some(stack)
}
/// `SimpleContainer.removeItemType`: take up to `count` of the item from
/// the first stacks that hold it.
pub fn remove_item(&mut self, item: &str, mut count: u32) {
let mut slot = 0;
while slot < self.inventory.len() && count > 0 {
let s = &mut self.inventory[slot];
if &*s.item == item {
let n = s.count.min(count);
s.count -= n;
count -= n;
if s.count == 0 {
self.inventory.remove(slot);
continue;
}
}
slot += 1;
}
}
pub fn count_item(&self, item: &str) -> u32 {
self.inventory
.iter()
@@ -754,30 +772,6 @@ pub fn finalize_summoned_golem(m: &mut Mob, random: &mut impl RandomSource) {
}
m.extra.left_handed = random.next_float() < 0.05;
}
/// `PoiManager.take(HOME, ..., 48)`: the nearest bed head not `claimed`
/// (`free_head`: a bed head that is not occupied).
pub fn take_vacant_bed(
claimed: &[[i32; 3]],
from: [i32; 3],
mut free_head: impl FnMut(i32, i32, i32) -> bool,
) -> Option<[i32; 3]> {
let mut best: Option<(i32, [i32; 3])> = None;
for y in from[1] - 8..=from[1] + 8 {
for z in from[2] - 48..=from[2] + 48 {
for x in from[0] - 48..=from[0] + 48 {
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if d <= 48 * 48
&& best.is_none_or(|(b, _)| d < b)
&& free_head(x, y, z)
&& !claimed.contains(&[x, y, z])
{
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
/// `Villager.canBreed`: enough food, awake and an adult.
pub fn can_breed(m: &Mob) -> bool {
m.species() == Species::Villager
@@ -1242,6 +1242,8 @@ enum B {
WorkAtPoi {
t: Timed,
last_check: i64,
/// `WorkAtComposter` (a farmer's package) rather than `WorkAtPoi`.
composter: bool,
},
StrollAroundPoi {
running: bool,
@@ -1635,7 +1637,11 @@ impl B {
*birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
true
}
B::WorkAtPoi { t, last_check } => {
B::WorkAtPoi {
t,
last_check,
composter,
} => {
let mm = mem(m);
let Some(site) = mm.job_site.value() else {
return false;
@@ -1656,6 +1662,13 @@ impl B {
mm.last_worked_at_poi.set(now);
mm.look_target.set(Tracker::Block(site));
play_work_sound(m, cx);
// WorkAtComposter.useWorkstation, before the restock.
if *composter {
cx.events.push(MobEvent::WorkAtComposter {
mob: m.id,
pos: site,
});
}
restock_if_due(m, cx.w);
true
}
@@ -3396,8 +3409,10 @@ fn breeding_possible(m: &mut Mob, w: &MobWorld) -> bool {
&& super::villager::can_breed(m)
&& w.seen(id).is_some_and(|s| s.in_love)
}
/// `VillagerMakeLove.takeVacantBed`: a bed head no villager has claimed.
fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
/// `VillagerMakeLove.takeVacantBed`: `PoiManager.take(HOME, ..., 48)` over a
/// sphere of 48 blocks, the nearest bed head no villager has claimed that the
/// villager can walk to (`canReach`: a path that gets there).
fn take_bed_for_child(m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> {
let claimed: Vec<[i32; 3]> = w
.others
.iter()
@@ -3405,10 +3420,20 @@ fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
.filter_map(|s| s.bed)
.chain(m.extra.bed)
.collect();
let p = m.position;
let from = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
super::villager::take_vacant_bed(&claimed, from, |x, y, z| {
w.prop(x, y, z, "part") == Some("head") && w.prop(x, y, z, "occupied") != Some("true")
let from = block_of(m.position);
let mut beds: Vec<[i32; 3]> = homes_in_range(m, w, 48)
.into_iter()
.filter(|p| {
w.prop(p[0], p[1], p[2], "part") == Some("head")
&& w.prop(p[0], p[1], p[2], "occupied") != Some("true")
&& !claimed.contains(p)
})
.collect();
// Nearest first; equally near beds stay in scan order.
beds.sort_by_key(|p| dist_sqr(*p, from));
beds.into_iter().find(|&p| {
m.create_path_to(w, p, Poi::Home.valid_range())
.is_some_and(|path| path.reached)
})
}
/// `BehaviorUtils.lockGazeAndWalkToEachOther`: this villager's half, and
@@ -3775,6 +3800,7 @@ fn packages(baby: bool, seed: i64, farmer: bool) -> Vec<Entry> {
B::WorkAtPoi {
t: timed(60, 60),
last_check: 0,
composter: farmer,
},
7,
),
+17 -3
View File
@@ -193,6 +193,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
}
Who::Player => false,
};
// `target.hasEffect`: a target that already has the effect gets the next one.
let has = |effect: &str| match who {
Who::Player => cx.w.player.as_ref().is_some_and(|p| p.has_effect(effect)),
Who::Mob(id) => cx.w.seen(id).is_some_and(|s| s.has_effect(effect)),
};
let (effect, ticks, amplifier) = if heals {
m.ai.target = None;
if health <= 4.0 {
@@ -200,11 +205,11 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
} else {
("minecraft:regeneration", 900, 0)
}
} else if dist >= 8.0 {
} else if dist >= 8.0 && !has("slowness") {
("minecraft:slowness", 1800, 0)
} else if health >= 8.0 {
} else if health >= 8.0 && !has("poison") {
("minecraft:poison", 900, 0)
} else if dist <= 3.0 && m.random.next_float() < 0.25 {
} else if dist <= 3.0 && !has("weakness") && m.random.next_float() < 0.25 {
("minecraft:weakness", 1800, 0)
} else {
("minecraft:instant_damage", 1, 0)
@@ -236,6 +241,15 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
pitch,
));
}
/// The movement speed of a witch with `SPEED_MODIFIER_DRINKING` (-0.25,
/// `ADD_VALUE`) while it drinks: it stands still for the 32 ticks.
pub fn speed(m: &Mob, base: f64) -> f64 {
if m.species() == Species::Witch && m.extra.flag {
(base - 0.25).max(0.0)
} else {
base
}
}
/// Witch.aiStep before `super.aiStep()`: the healing cooldown, then drink
/// water breathing, fire resistance, healing or swiftness.
pub fn ai_step(m: &mut Mob, cx_events: &mut Vec<MobEvent>, target_far: bool) {
+123 -6
View File
@@ -50,6 +50,10 @@ pub struct MotionResources {
pub attributes: Arc<Catalog>,
pub blocks: BoundMovementProperties,
pub climbable: BTreeSet<String>,
/// `BlockTags.CAN_GLIDE_THROUGH`: climbable blocks a gliding player passes.
pub glide_through: BTreeSet<String>,
/// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for.
pub soul_speed_blocks: BTreeSet<String>,
pub fall_reset: BTreeSet<String>,
pub landing: BlockLandingRegistry,
pub health: crate::health::HealthResources,
@@ -108,11 +112,30 @@ impl MotionResources {
suppresses_bounce: tag("minecraft:suppresses_bounce")?,
})?,
climbable: tag("minecraft:climbable")?,
glide_through: tag("minecraft:can_glide_through")?,
soul_speed_blocks: tag("minecraft:soul_speed_blocks")?,
fall_reset: tag("minecraft:fall_damage_resetting")?,
})
}
}
/// What the `location_changed` enchantment effects (Soul Speed) need to know
/// between ticks.
#[derive(Clone, Debug, Default)]
pub struct LocationEffects {
/// `MovementAffectedByPredicate`: the block under the player
/// (`getBlockPosBelowThatAffectsMyMovement`) is in `#minecraft:soul_speed_blocks`.
pub on_soul_speed_block: bool,
/// `LivingEntity.lastPos`: the block the player was in last tick.
pub block: Option<BlockPos>,
/// A landing ran `onChangedBlock` (`LivingEntity.checkFallDamage`).
pub landed: bool,
/// The Soul Speed level of the boots seen last tick (0: none).
pub boots_level: u32,
/// The Soul Speed level whose attribute modifiers are on the player (0: none).
pub applied_level: u32,
}
/// Ordered requests and phase records for world/audio/network consumers. Landing
/// hurt dispatch updates stored health synchronously before these are drained.
#[derive(Clone, Copy, Debug)]
@@ -255,6 +278,8 @@ pub struct PlayerMotion {
pub glide_ending: bool,
/// Glider durability to take this tick (updateFallFlying).
pub glider_wear: u32,
/// Soul Speed's `location_changed` bookkeeping.
pub location_effects: LocationEffects,
/// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's
/// spin. The damage stays until the game has dealt the hit.
pub auto_spin_attack_ticks: i32,
@@ -308,6 +333,9 @@ pub struct PlayerMotion {
/// it travels on the server: `isLocalInstanceAuthoritative` is false, so
/// its moves check no fall damage.
pub server_copy: bool,
/// The span of `events` a wall hit on the server's copy pushed (sound and
/// damage): `server_travel` keeps them while it drops the simulated moves.
pub wall_hit_events: Option<std::ops::Range<usize>>,
/// A client's copy of its own player (`Level.isClientSide`): only the
/// server hurts it (`Entity.hurt` does nothing on a client) and ticks its
/// food (`ServerPlayer.tick`). Its hurt animation comes from the server.
@@ -443,6 +471,7 @@ impl PlayerMotion {
fall_fly_ticks: 0,
glide_ending: false,
glider_wear: 0,
location_effects: LocationEffects::default(),
auto_spin_attack_ticks: 0,
auto_spin_attack_dmg: 0.0,
spin_targets: Vec::new(),
@@ -477,6 +506,7 @@ impl PlayerMotion {
freeze_immune: false,
old_position: position,
server_copy: false,
wall_hit_events: None,
client_side: false,
block_effects: true,
powder_snow_entered: Vec::new(),
@@ -765,6 +795,10 @@ impl MotionWorld<'_, '_, '_> {
.state(self.block(p))
.ok_or("missing scene state")?
.name;
// A gliding player passes through vines (`CAN_GLIDE_THROUGH`).
if self.player.fall_flying && self.resources.glide_through.contains(name) {
return Ok(false);
}
let climbable = self.resources.climbable.contains(name);
if climbable {
self.player.last_climbable = Some(p);
@@ -834,9 +868,17 @@ impl MotionWorld<'_, '_, '_> {
let can_glide = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& self.player.status.levitation.is_none()
&& !self.player.fluids.was_touching_water
&& !self.player.is_in_lava();
if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide {
// LocalPlayer.aiStep: `!onClimbable()` before tryToStartFallFlying.
if jumping
&& !toggled
&& !was_jumping
&& !self.climbable()?
&& !self.player.fall_flying
&& can_glide
{
self.player.fall_flying = true;
}
// LivingEntity.tick fallFlyTicks, then updateFallFlying.
@@ -848,8 +890,11 @@ impl MotionWorld<'_, '_, '_> {
self.player.fall_distance = 1.0;
}
self.player.fall_fly_ticks += 1;
// canGlide alone: water and lava don't end a glide.
let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying;
// canGlide alone: water and lava don't end a glide, levitation does.
let still = self.player.glider
&& !self.player.ground.on_ground
&& !self.player.flying
&& self.player.status.levitation.is_none();
if !still {
self.player.glide_ending = true;
} else if (self.player.fall_fly_ticks + 1) % 10 == 0
@@ -984,6 +1029,7 @@ impl MotionWorld<'_, '_, '_> {
)
});
self.player.try_add_frost(on_air)?;
self.update_soul_speed_block()?;
if self.player.health.tick_count % 40 == 0
&& self.player.is_fully_frozen()
&& self.player.can_freeze()
@@ -996,6 +1042,22 @@ impl MotionWorld<'_, '_, '_> {
}
Ok(())
}
/// Refresh whether the player stands on a soul speed block, for the
/// `location_changed` enchantment effects (a server's player too, whose
/// client does the walking).
pub fn update_soul_speed_block(&mut self) -> Result<()> {
self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?;
Ok(())
}
/// `MovementAffectedByPredicate` for `#minecraft:soul_speed_blocks`.
fn on_soul_speed_block(&mut self) -> Result<bool> {
let on = self.support(movement_support::MOVEMENT_SUPPORT_OFFSET)?;
Ok(self
.assets
.registry
.state(self.block(on))
.is_some_and(|s| self.resources.soul_speed_blocks.contains(&s.name)))
}
/// Player.travel: swim steering, then LivingEntity.travel (fluids first,
/// then gliding, then air), keeping 0.6 of the vertical speed while flying.
fn player_travel(&mut self, input: Vec3) -> Result<()> {
@@ -1021,7 +1083,14 @@ impl MotionWorld<'_, '_, '_> {
{
horizon_world::living_fluid::travel_in_fluid(self, input)?;
} else if self.player.fall_flying {
self.travel_fall_flying()?;
// LivingEntity.travelFallFlying: on a climbable the glide ends and
// the player moves like in the air.
if self.climbable()? {
self.travel_in_air(input)?;
self.player.fall_flying = false;
} else {
self.travel_fall_flying()?;
}
} else {
self.travel_in_air(input)?;
}
@@ -1048,7 +1117,14 @@ impl MotionWorld<'_, '_, '_> {
p.server_copy = false;
(p.position, p.ground, p.collision) = (position, ground, collision);
(p.history, p.fall_distance, p.steps) = (history, fall_distance, steps);
// The wall hit is the server's own: its sound and damage events stay.
let kept: Vec<_> = p
.wall_hit_events
.take()
.map(|span| p.events.drain(span).collect())
.unwrap_or_default();
p.events.truncate(events);
p.events.extend(kept);
travelled
}
/// `LivingEntity.checkAutoSpinAttack`: the first living entity in the
@@ -1536,7 +1612,7 @@ impl MotionWorld<'_, '_, '_> {
let lean = pitch;
let look_h = (look.x * look.x + look.z * look.z).sqrt();
let move_h = (v.x * v.x + v.z * v.z).sqrt();
let gravity = 0.08;
let gravity = living_motion::effective_gravity(self)?;
let lift = f64::from(lean.cos()).powi(2);
let mut m = Vec3::new(v.x, v.y + gravity * (-1.0 + lift * 0.75), v.z);
if m.y < 0.0 && look_h > 0.0 {
@@ -1564,7 +1640,44 @@ impl MotionWorld<'_, '_, '_> {
}
self.player.velocity = Vec3::new(m.x * 0.99, m.y * 0.98, m.z * 0.99);
let movement = self.player.velocity;
self.move_self(movement)
self.move_self(movement)?;
// LivingEntity.handleFallFlyingCollisions: only the server hurts.
if !self.player.client_side && self.player.collision.horizontal {
let new_h = {
let v = self.player.velocity;
(v.x * v.x + v.z * v.z).sqrt()
};
let dmg = ((move_h - new_h) * 10.0 - 3.0) as f32;
if dmg > 0.0 {
let first = self.player.events.len();
// getFallDamageSound((int) dmg)
let sound = if dmg as i32 > 4 {
crate::landing::SceneSound::BigFall
} else {
crate::landing::SceneSound::SmallFall
};
self.player
.events
.push(MotionEvent::Fall(crate::landing::FallEvent::Sound {
sound,
position: None,
volume: 1.0,
pitch: 1.0,
}));
let id = self
.resources
.health
.damage
.id("minecraft:fly_into_wall")
.ok_or("missing fly_into_wall damage type")?;
let rules = self.scene.health_rules;
self.player.hurt(&self.resources.health, rules, id, dmg)?;
if self.player.server_copy {
self.player.wall_hit_events = Some(first..self.player.events.len());
}
}
}
Ok(())
}
/// `LocalPlayer.move`: the move, then `updateAutoJump` with the float
/// horizontal displacement.
@@ -1842,6 +1955,10 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
if self.player.status.slow_falling || self.player.status.levitation.is_some() {
self.player.fall_distance = 0.0;
}
// LivingEntity.checkFallDamage: a landing runs onChangedBlock.
if grounded && self.player.fall_distance > 0.0 {
self.player.location_effects.landed = true;
}
if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0
{
self.player.events.push(MotionEvent::SmashLanding {
@@ -161,6 +161,29 @@ pub(crate) fn fire_contact(
}
damage
}
/// `CactusBlock.entityInside`: the box (deflated by `1.0E-5`, as in
/// `Entity.checkInsideBlocks`) touches a cactus; its inside shape is the
/// whole block.
pub(crate) fn cactus_contact(
world: &World,
registry: &horizon_world::registry::BlockRegistry,
bounds: Aabb,
) -> bool {
let b = bounds.deflate(Vec3::new(1e-5, 1e-5, 1e-5));
for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 {
for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 {
for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 {
if registry
.state(world.block(x, y, z))
.is_some_and(|s| s.name == "minecraft:cactus")
{
return true;
}
}
}
}
false
}
impl LivingFluidWorld for MotionWorld<'_, '_, '_> {
fn in_water(&mut self) -> Result<bool> {
Ok(self.player.fluids.was_touching_water)
+6 -5
View File
@@ -186,12 +186,13 @@ impl Projectile {
self
}
/// The shooter's bow enchantments; Flame spawns the arrow burning for 100
/// seconds (`projectile_spawned` ignite).
/// seconds (`projectile_spawned` ignite), Piercing sets its pierce level.
pub fn set_bonus(&mut self, bonus: crate::mobs::gear::ArrowBonus) {
if bonus.flame
&& let Some(a) = self.arrow.as_mut()
{
a.ignite_for_seconds(100.0);
if let Some(a) = self.arrow.as_mut() {
if bonus.flame {
a.ignite_for_seconds(100.0);
}
a.pierce = bonus.pierce.min(127) as u8;
}
self.bonus = bonus;
}
+3 -1
View File
@@ -648,6 +648,7 @@ pub fn encode_block_entity(
BlockEntity::Vault(v) => entries.extend(v.save()),
BlockEntity::Beehive(h) => entries.extend(h.to_nbt()),
BlockEntity::CommandBlock(c) => entries.extend(c.save()),
BlockEntity::DaylightDetector => {}
}
Tag::compound(entries)
}
@@ -845,7 +846,8 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_)
| BlockEntity::Skull(_) => {}
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector => {}
BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag),
BlockEntity::TrialSpawner(s) => **s = crate::mobs::trial_spawner::TrialSpawner::load(tag),
BlockEntity::Vault(v) => **v = crate::vault::Vault::load(tag),
+3
View File
@@ -448,6 +448,7 @@ pub fn grindstone_experience(
#[derive(Clone, Debug)]
pub enum Smithing {
Transform {
id: String,
template: Ingredient,
base: Ingredient,
addition: Ingredient,
@@ -527,6 +528,7 @@ impl StationRecipes {
);
match v["type"].as_str().unwrap_or("") {
"minecraft:smithing_transform" => smithing.push(Smithing::Transform {
id,
template: ingredient(&v["template"], items),
base: ingredient(&v["base"], items),
addition: ingredient(&v["addition"], items),
@@ -630,6 +632,7 @@ impl StationRecipes {
base: b,
addition: a,
result,
..
} => {
if t.test(template) && b.test(base) && a.test(addition) {
// SmithingTransformRecipe: transmute the base keeping its components.
+113 -9
View File
@@ -175,6 +175,11 @@ pub enum Done {
}
struct Queued {
priority: i64,
/// The column the job is for and what it adds to the column's distance
/// (`Streaming::submit`): the priority is computed again from them when
/// the centre moves (`Streaming::requeue`). None for saves, which go first.
at: Option<(i32, i32)>,
bias: i64,
order: u64,
job: Job,
}
@@ -222,6 +227,9 @@ pub struct Streaming {
/// radius it was last ranked for.
decoration_order: DecorationOrder,
order_area: Option<((i32, i32), i32)>,
/// What the queued jobs' priorities were computed from (`requeue`): the
/// centre, the loading screen, the band, and the extra areas.
queue_basis: (((i32, i32), bool, Option<Band>), Vec<((i32, i32), i32)>),
finishing: FxHashSet<(i32, i32)>,
decorates: bool,
lighting: FxHashMap<(i32, i32), u64>,
@@ -544,6 +552,7 @@ impl Streaming {
saving: 0,
decoration_order: DecorationOrder::default(),
order_area: None,
queue_basis: Default::default(),
finishing: Default::default(),
decorates: generator.decorates(),
lighting: Default::default(),
@@ -648,15 +657,39 @@ impl Streaming {
world.dirty_sections.take_column(x, z);
world.chunks.remove(&(x, z))
}
fn submit(&mut self, priority: i64, job: Job) {
/// Queue a job for the column `at`, nearest first: its distance (`distance`)
/// times four plus `bias`, which orders a column's jobs. A job without a
/// column (a save) goes ahead of every other.
fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) {
self.order += 1;
let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias);
self.shared.queue.lock().unwrap().push(Queued {
priority,
at,
bias,
order: self.order,
job,
});
self.shared.ready.notify_one();
}
/// Rank the queued jobs again when what their priorities were computed
/// from changed: the centre, the extra areas, the band, or the loading
/// screen (ring order, `Ranges::rings`, whose values are far above the
/// distances used after it). Vanilla's chunk task queue follows the
/// current ticket levels in the same way. Without it, generation queued
/// while the loading screen was up waited behind every job queued after
/// it, and with it the decoration of the chunks around the player: at
/// render distance 32 nothing was decorated until every proto chunk had
/// been generated.
fn requeue(&mut self) {
let basis = (self.center, self.loading, self.band);
if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra {
return;
}
self.queue_basis = (basis, self.extra.clone());
let mut queue = self.shared.queue.lock().unwrap();
rank_again(&mut queue, |x, z| self.distance(x, z));
}
fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) {
self.generation_scan.exhausted = false;
self.decorating -= 1;
@@ -686,7 +719,7 @@ impl Streaming {
self.saving += 1;
// Ahead of every other job: a column generated again meanwhile
// would not find them saved.
self.submit(i64::MIN, Job::Save(protos));
self.submit(None, 0, Job::Save(protos));
}
}
fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) {
@@ -829,6 +862,7 @@ impl Streaming {
return (uploads, Vec::new());
}
ExtraCover::refresh(&mut self.cover, &self.extra);
self.requeue();
self.relight_edits(world);
let deferred = std::mem::take(&mut self.deferred);
let received = std::iter::from_fn(|| self.results.try_recv().ok());
@@ -984,7 +1018,7 @@ impl Streaming {
.expect("present proto");
self.finishing.insert((x, z));
self.written.remove(&(x, z));
self.submit(self.distance(x, z) * 4, Job::Finish(proto));
self.submit(Some((x, z)), 0, Job::Finish(proto));
}
}
// Decorate chunks whose 3x3 proto neighbourhood is available, in
@@ -1052,7 +1086,7 @@ impl Streaming {
w.0 = self.decoration_order.rank_or_append(w.2, w.3);
}
wanted.sort_unstable();
for (_, d, x, z) in wanted {
for (_, _, x, z) in wanted {
if self.decorating >= workers * 2 {
break;
}
@@ -1091,7 +1125,7 @@ impl Streaming {
Err(_) => continue,
};
self.decorating += 1;
self.submit(d * 4 + 1, Job::Decorate(x, z, region));
self.submit(Some((x, z)), 1, Job::Decorate(x, z, region));
}
}
self.schedule_generation(world, workers);
@@ -1111,7 +1145,8 @@ impl Streaming {
self.light_snapshots
.insert((x, z), self.light_edit_sequence);
self.submit(
self.distance(x, z) * 4 + 1,
Some((x, z)),
1,
Job::Light(x, z, region, self.sequence, self.sky_light),
);
}
@@ -1183,7 +1218,8 @@ impl Streaming {
self.sequence += 1;
self.meshing.insert((x, sy, z), self.sequence);
self.submit(
self.distance(x, z) * 4 + if first { 2 } else { 0 },
Some((x, z)),
if first { 2 } else { 0 },
Job::Mesh(
x,
sy,
@@ -1222,9 +1258,9 @@ impl Streaming {
loading: self.loading,
};
if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) {
for (d, x, z) in wanted {
for (_, x, z) in wanted {
self.generating.insert((x, z));
self.submit(d * 4, Job::Generate(x, z));
self.submit(Some((x, z)), 0, Job::Generate(x, z));
}
}
}
@@ -1738,10 +1774,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator<Item = i32> {
})
})
}
/// The queued jobs' priorities computed again from each one's column
/// `distance` (`Streaming::submit`).
fn rank_again(queue: &mut BinaryHeap<Queued>, distance: impl Fn(i32, i32) -> i64) {
if queue.is_empty() {
return;
}
let mut jobs = std::mem::take(queue).into_vec();
for job in &mut jobs {
if let Some((x, z)) = job.at {
job.priority = distance(x, z) * 4 + job.bias;
}
}
*queue = BinaryHeap::from(jobs);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queued_jobs_follow_the_centre_and_the_loading_screen() {
let forced = HashSet::new();
let ranges = |center| Ranges {
center,
radius: 32,
extra: &[],
forced: &forced,
cover: None,
band: None,
};
let generate = |x, z, priority, order| Queued {
priority,
at: Some((x, z)),
bias: 0,
order,
job: Job::Generate(x, z),
};
let loading = ranges((0, 0));
let queued = || {
BinaryHeap::from(vec![
// Queued while the loading screen was up: ring order.
generate(3, 1, loading.priority(3, 1, true) * 4, 1),
// Queued after it closed: plain distances, far below any ring past the first.
generate(20, 0, loading.priority(20, 0, false) * 4, 2),
Queued {
priority: i64::MIN,
at: None,
bias: 0,
order: 3,
job: Job::Save(Vec::new()),
},
])
};
let pops = |mut queue: BinaryHeap<Queued>| {
std::iter::from_fn(move || queue.pop())
.map(|q| q.at)
.collect::<Vec<_>>()
};
assert_eq!(
pops(queued()),
[None, Some((20, 0)), Some((3, 1))],
"the stale order"
);
let mut queue = queued();
rank_again(&mut queue, |x, z| loading.priority(x, z, false));
assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]);
// The player moved: the job near the new centre goes first.
let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]);
let moved = ranges((19, 0));
rank_again(&mut queue, |x, z| moved.priority(x, z, false));
assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0)));
}
#[test]
fn view_distance_is_vanillas_shape() {
// ChunkTrackingView.isInViewDistance at render distance 12: a column
+15 -4
View File
@@ -9,7 +9,7 @@ use horizon_world::{
};
use std::{
path::Path,
sync::{Arc, OnceLock},
sync::{Arc, Mutex},
};
/// The `custom_data` key holding an exploration map's search until the game
@@ -114,11 +114,13 @@ pub fn has_pending_map(item: &ItemStack) -> bool {
})
}
static LOOT: OnceLock<Option<Arc<LootData>>> = OnceLock::new();
/// None until `loot_data` runs; `Some(None)` when the tables failed to load.
static LOOT: Mutex<Option<Option<Arc<LootData>>>> = Mutex::new(None);
/// Loot data of the resource root, loaded once per process.
pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
LOOT.get_or_init(|| match LootData::load(root) {
let mut loot = LOOT.lock().unwrap_or_else(|e| e.into_inner());
loot.get_or_insert_with(|| match LootData::load(root) {
Ok(data) => Some(Arc::new(data)),
Err(e) => {
log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}");
@@ -130,7 +132,16 @@ pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
/// The loot data `loot_data` loaded, if it ran.
pub fn loaded_loot_data() -> Option<Arc<LootData>> {
LOOT.get().cloned().flatten()
LOOT.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.flatten()
}
/// Let go of the loot data: for a preload no world used
/// (game/world_loading.rs). The next `loot_data` loads it again.
pub fn forget_loot_data() {
*LOOT.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
/// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table`
+11 -3
View File
@@ -333,15 +333,23 @@ impl VanillaTerrain {
u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX)
}
}
static SHARED_DATA: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> =
std::sync::Mutex::new(Vec::new());
/// Let go of the bundles `shared_data` loaded: for a preload no world used
/// (game/world_loading.rs). A generator that holds one keeps it.
pub fn forget_shared_data() {
SHARED_DATA
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
/// The worldgen bundle at `dir`, loaded once and shared by every generator
/// and by live feature placement (sapling growth, bone meal).
pub fn shared_data(
dir: &Path,
registry: &'static BlockRegistry,
) -> crate::Result<Arc<GeneratorData>> {
static CACHE: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> =
std::sync::Mutex::new(Vec::new());
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
let mut cache = SHARED_DATA.lock().unwrap_or_else(|e| e.into_inner());
if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) {
return Ok(data.clone());
}
@@ -0,0 +1,16 @@
[package]
name = "beacons"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish = false
description = "Example Horizon server mod: /beacon lights a pillar beside you, /ground says what you stand on"
[lib]
crate-type = ["cdylib"]
[dependencies]
horizon-mod-sdk = { path = "../.." }
[lints]
workspace = true
@@ -0,0 +1,8 @@
id = "beacons"
name = "Beacons"
version = "0.1.0"
description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome."
authors = ["Horizon"]
api = "0.3"
side = "server"
capabilities = ["players", "world"]
@@ -0,0 +1,87 @@
//! Example Horizon server mod (`docs/mods.md`, "Server mods") with
//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east
//! of the player, `/ground` reads the block under their feet and the biome.
use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world};
/// How tall `/beacon` builds.
const HEIGHT: i32 = 4;
struct Beacons;
/// The block the player stands in: their feet, floored.
fn feet(player: &Player) -> (i32, i32, i32) {
(
player.x.floor() as i32,
player.y.floor() as i32,
player.z.floor() as i32,
)
}
/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up.
fn pillar(player: &Player) -> Vec<BlockChange> {
let (x, y, z) = feet(player);
(0..HEIGHT)
.map(|dy| BlockChange {
x: x + 2,
y: y + dy,
z,
state: "minecraft:glowstone".into(),
})
.collect()
}
impl ServerMod for Beacons {
fn init() -> Result<(Self, Registration), String> {
Ok((
Beacons,
Registration::new().command("beacon").command("ground"),
))
}
fn command(
&mut self,
player: &Player,
name: &str,
_args: &str,
) -> Result<Option<String>, String> {
let (x, y, z) = feet(player);
if name == "beacon" {
world::set_blocks(&player.dimension, &pillar(player))?;
players::broadcast(&format!(
"{} lit a beacon at {} {y} {z}",
player.name,
x + 2
));
return Ok(None);
}
let below = world::get_block(&player.dimension, x, y - 1, z)
.ok_or("The ground under you isn't loaded")?;
let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default();
Ok(Some(format!("You are standing on {below} in {biome}")))
}
}
horizon_mod_sdk::export_server_mod!(Beacons);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pillar_stands_two_blocks_east() {
let p = Player {
id: String::new(),
name: "Alex".into(),
x: -0.5,
y: 64.0,
z: 3.2,
dimension: "minecraft:overworld".into(),
game_mode: horizon_mod_sdk::server::GameMode::Survival,
health: 20.0,
};
let blocks = pillar(&p);
assert_eq!(blocks.len(), HEIGHT as usize);
assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3));
assert_eq!(blocks[3].y, 67);
}
}
@@ -0,0 +1,22 @@
# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east.
[[step]]
join = "Alex"
blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:grass_block[snowy=false]" }]
command = "ground"
expect.feedback = "You are standing on minecraft:grass_block[snowy=false] in minecraft:plains"
[[step]]
command = "beacon"
expect.broadcast = ["Alex lit a beacon at 2 64 0"]
expect.blocks = [
{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" },
{ x = 2, y = 67, z = 0, state = "minecraft:glowstone" },
{ x = 2, y = 68, z = 0, state = "minecraft:air" },
]
# Anywhere the script set nothing is air.
[[step]]
player = { x = 10.5, z = 10.5 }
command = "ground"
expect.feedback = "You are standing on minecraft:air in minecraft:plains"
+4 -1
View File
@@ -39,7 +39,9 @@ wit_bindgen::generate!({
pub use exports::horizon::mods::events::{Guest as __Guest, Registration};
pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest;
pub use horizon::mods::{chat, command, game, hud, input, log, render, storage, ui};
pub use horizon::mods::{
browser, chat, command, game, hud, input, log, recipes, render, storage, ui,
};
/// The game's calls into a mod. Only the hooks [`Registration`] asks for
/// are called; the others may stay as their defaults.
@@ -194,6 +196,7 @@ pub mod server {
pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration};
pub use horizon::mods::players::{self, GameMode, Player};
pub use horizon::mods::world::{self, BlockChange};
/// The server's calls into a mod. Only the hooks [`Registration`] asks
/// for are called; the others may stay as their defaults.
+211
View File
@@ -439,6 +439,181 @@ interface events {
chat: func(text: string);
}
/// Capability `recipes` (experimental): the recipes and items the game
/// knows, for recipe viewers. In single player and on Horizon's servers
/// they are the world's; on any other server they are vanilla 26.3's (a
/// client is sent no others), while `known` follows that server's book.
interface recipes {
/// An item of `items`, by its index there, with a count and the
/// components it has beyond the item's own, in vanilla's item syntax
/// (`[potion_contents={potion:"minecraft:swiftness"}]`), or "".
record stack {
item: u32,
count: u32,
components: string,
}
/// The station a recipe is made at.
enum kind {
crafting-shaped,
crafting-shapeless,
smelting,
blasting,
smoking,
campfire,
stonecutting,
smithing,
brewing,
}
record recipe {
/// `minecraft:oak_planks`.
id: string,
kind: kind,
/// The recipe book's tab (`crafting_building_blocks`,
/// `furnace_food`), or "".
category: string,
/// Recipes the book shows on one button share a group, or "".
group: string,
/// A shaped recipe's grid: `slots` holds its cells row by row.
/// 0 for the other kinds.
width: u32,
height: u32,
/// Each slot's stacks, any one of which fits; an empty list is an
/// empty cell. Cooking and stonecutting: the input. Smithing: the
/// template, the base, the addition. Brewing: the bottle, the
/// reagent.
slots: list<list<stack>>,
/// What it makes; several when that varies (a trim on any armour).
results: list<stack>,
/// Cooking: game ticks and experience; 0 for the other kinds.
cooking-time: u32,
experience: f32,
/// The recipe book's id for it (one per way the book shows it), as
/// `known` lists them; -1 for the kinds the book doesn't show
/// (campfire, stonecutting, smithing, brewing).
book-id: s32,
}
record item {
/// `minecraft:diamond`, `<mod>:<path>`.
id: string,
/// In the player's language.
name: string,
/// Its item tags, without the `#`.
tags: list<string>,
}
/// Every item, in the registry's order: `stack.item` indexes this list.
items: func() -> list<item>;
/// Every recipe: the book's in its order, then campfire, stonecutting,
/// smithing and brewing. They don't change while a world is open.
all: func() -> list<recipe>;
/// The `book-id`s of the recipes the player's recipe book holds now.
known: func() -> list<s32>;
/// Places a recipe in the open screen's grid as a click in the recipe
/// book does (`ServerboundPlaceRecipePacket`): the inventory's grid or
/// a crafting table. `all` places as many as the items allow, as with
/// Shift. Refused while no such screen is open, for a recipe the
/// player's book doesn't hold and for one that can't be placed; one
/// missing items shows as a ghost in the grid, as in the book.
place: func(book-id: s32, all: bool) -> result<_, string>;
/// Creative mode only: gives the player the stack, as taking it from
/// the creative inventory does (`ServerboundSetCreativeModeSlot`): the
/// selected slot first, then the hotbar, then the inventory. The count
/// is cut to one stack of the item (64, 16 or 1).
give: func(stack: stack) -> result<_, string>;
}
/// Capability `ui` (experimental): a recipe viewer's panel beside the
/// game's inventory and container screens (not the creative inventory), on
/// the right of the screen. The game draws it with its own widgets and
/// slots, pages it and keeps its search box; the mod says what it holds.
/// The first loaded mod with a panel shows.
interface browser {
/// An item to show: its id, a count (1 draws none) and its components
/// beyond the item's own, in vanilla's item syntax, or "".
record stack {
item: string,
count: u32,
components: string,
}
/// A click on an item of the panel, by its index in `set-items`'s list.
record click {
index: u32,
right: bool,
}
/// A key the mod registered (`input.register-key`) went down while the
/// pointer was on an item: a slot of the screen's, or the panel's.
record item-key {
key: string,
stack: stack,
}
/// A click on a slot of a recipe the panel shows (`set-recipes`).
record slot-click {
/// The recipe's index in `set-recipes`'s list and the slot's in
/// it; the results come after the slots.
recipe: u32,
slot: u32,
/// The stack the slot showed at that moment.
stack: stack,
right: bool,
}
variant event {
clicked(click),
/// The search box's text, each time the player changes it.
search(string),
key(item-key),
slot-clicked(slot-click),
/// The action button of the recipe at this index in
/// `set-recipes`'s list.
action(u32),
/// The player turned the recipes' page (`set-recipes`): the index
/// of the first recipe now shown.
page(u32),
/// The back button of `set-recipes`.
back,
/// The player picked the tab at this index of `set-recipes`' tabs.
tab(u32),
}
/// How the game lays out a recipe of `set-recipes`.
enum layout {
/// A crafting grid of `width` x `height` slots, an arrow and the
/// result.
grid,
/// One input over a flame, an arrow and the result (furnaces,
/// smokers, campfires).
cooking,
/// One input, an arrow and the result (the stonecutter).
single,
/// Template, base and addition, an arrow and the result.
smithing,
/// A potion and an ingredient, an arrow and the result.
brewing,
}
/// A recipe to show. Each slot, and the result, cycles through its
/// stacks, one a second; an empty slot shows nothing.
record recipe-view {
layout: layout,
/// The grid's size (`grid` only), at most 3 x 3.
width: u32,
height: u32,
slots: list<list<stack>>,
results: list<stack>,
/// A short line under the recipe (a cooking time), or "".
note: string,
/// The action button beside it: none, enabled, or shown greyed.
action: option<bool>,
}
/// The panel's items, at most 8192 (an empty list hides the panel).
set-items: func(items: list<stack>);
/// Shows these recipes in the panel instead of its items, as many as
/// fit a page, under `title` and a back button, with a row of `tabs`
/// (each an icon; `tab` is the selected one) between them; an empty
/// list of recipes shows the items again. At most 256 recipes and 16
/// tabs.
set-recipes: func(title: string, tabs: list<stack>, tab: u32, recipes: list<recipe-view>);
/// What the player did on the panel since the last poll, at most 256
/// kept.
poll: func() -> list<event>;
}
/// Capability `players`, server mods only (manifest `api = "0.3"`,
/// experimental): the players on the server, and messages to them.
interface players {
@@ -472,6 +647,33 @@ interface players {
broadcast: func(text: string);
}
/// Capability `world`, server mods only (manifest `api = "0.3"`,
/// experimental): the blocks of the server's loaded chunks, and changes to
/// them through the server's own block updates.
interface %world {
record block-change {
x: s32,
y: s32,
z: s32,
/// `minecraft:oak_log[axis=y]`; properties left out take the block's
/// defaults, `minecraft:stone` alone is the default state.
state: string,
}
/// The block state at a position in a dimension (`minecraft:overworld`,
/// ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the
/// server has no chunk loaded there.
get-block: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
/// The biome at a position (`minecraft:plains`, ...), as the server
/// stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded.
get-biome: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
/// Sets blocks as `/setblock` does: the old block entity removed,
/// neighbours and shapes updated, light, and every player told. Every
/// state is checked now (an error queues nothing); the changes are made
/// in order after this call returns, before that dimension's next tick;
/// one in a chunk not loaded then is skipped. At most 4096 per call.
set-blocks: func(dimension: string, blocks: list<block-change>) -> result<_, string>;
}
/// What the server calls in a server mod (manifest `api = "0.3"`,
/// experimental). Only the hooks `init` asks for are ever called. The player
/// in each event is as the server saw them when it happened.
@@ -534,6 +736,7 @@ world horizon-server-mod {
import log;
import storage;
import players;
import %world;
export server-events;
}
@@ -545,6 +748,8 @@ world horizon-ui-mod {
import ui;
import render;
import input;
import recipes;
import browser;
export ui-events;
}
@@ -559,3 +764,9 @@ world render-host {
import render;
import input;
}
/// The game's side of capability `recipes` (imports only).
world recipes-host {
import recipes;
import browser;
}
+13 -2
View File
@@ -7,13 +7,13 @@
//! version's level so the launcher can tell before it installs.
/// The newest level this Horizon serves.
pub const LEVEL: u32 = 3;
pub const LEVEL: u32 = 6;
/// Every function the game offers mods, as `interface.function`, with its
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
/// function takes the next level and raises [`LEVEL`] (the `api_reference`
/// test fails until it is listed here).
pub const FUNCTIONS: [(&str, u32); 34] = [
pub const FUNCTIONS: [(&str, u32); 45] = [
("log.write", 0),
("game.get-player", 0),
("game.get-clock", 0),
@@ -48,6 +48,17 @@ pub const FUNCTIONS: [(&str, u32); 34] = [
("players.broadcast", 1),
("game.raycast", 2),
("command.run-quiet", 3),
("world.get-block", 4),
("world.get-biome", 4),
("world.set-blocks", 4),
("recipes.items", 5),
("recipes.all", 5),
("recipes.known", 5),
("browser.set-items", 6),
("browser.poll", 6),
("browser.set-recipes", 6),
("recipes.place", 6),
("recipes.give", 6),
];
/// What the game's program carries so the launcher can read its level
+26 -3
View File
@@ -97,9 +97,15 @@ pub enum Capability {
Input,
/// The players on the server and messages to them (server mods).
Players,
/// Blocks in the server's loaded chunks, and changes to them (server
/// mods; client mods later, where the game runs the world).
World,
/// The recipes and items the game knows, for recipe viewers
/// (interface `recipes`).
Recipes,
}
impl Capability {
pub const ALL: [Capability; 10] = [
pub const ALL: [Capability; 12] = [
Capability::GameRead,
Capability::Chat,
Capability::Hud,
@@ -110,10 +116,15 @@ impl Capability {
Capability::Render,
Capability::Input,
Capability::Players,
Capability::World,
Capability::Recipes,
];
/// Whether a server mod may have it: the others act on a local player.
pub fn on_server(self) -> bool {
matches!(self, Capability::Storage | Capability::Players)
matches!(
self,
Capability::Storage | Capability::Players | Capability::World
)
}
/// The WIT interface it grants, in `horizon:mods`.
pub fn interface(self) -> &'static str {
@@ -128,6 +139,8 @@ impl Capability {
Capability::Render => "render",
Capability::Input => "input",
Capability::Players => "players",
Capability::World => "world",
Capability::Recipes => "recipes",
}
}
/// May change in any release: a mod uses it only with
@@ -135,7 +148,7 @@ impl Capability {
pub fn is_experimental(self) -> bool {
matches!(
self,
Capability::Ui | Capability::Render | Capability::Input
Capability::Ui | Capability::Render | Capability::Input | Capability::Recipes
)
}
/// What the player reads before turning the mod on: "May <this>".
@@ -153,6 +166,10 @@ impl Capability {
"see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys"
}
Capability::Players => "see who is on the server and message them",
Capability::World => "read and change the world's blocks",
Capability::Recipes => {
"read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items"
}
}
}
/// The capability a component import needs, `Ok(None)` for one every
@@ -167,6 +184,10 @@ impl Capability {
if interface == "log" {
return Ok(None);
}
// A recipe viewer's panel is part of capability `ui`.
if interface == "browser" {
return Ok(Some(Capability::Ui));
}
Capability::ALL
.into_iter()
.filter(|c| *c != Capability::Registries)
@@ -188,6 +209,8 @@ impl fmt::Display for Capability {
Capability::Render => "render",
Capability::Input => "input",
Capability::Players => "players",
Capability::World => "world",
Capability::Recipes => "recipes",
};
f.write_str(name)
}
+361 -4
View File
@@ -1,12 +1,13 @@
//! Loading and calling mods with wasmtime's component model.
use crate::manifest::{Manifest, Package, Side};
use server_bindings::{
HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration,
horizon::mods::players,
HorizonServerMod,
exports::horizon::mods::server_events::Registration as ServerRegistration,
horizon::mods::{players, world as mod_world},
};
use std::{
path::{Path, PathBuf},
sync::Arc,
sync::{Arc, Mutex},
time::{Duration, Instant, SystemTime},
};
use wasmtime::{
@@ -25,6 +26,7 @@ mod server_bindings {
wasmtime::component::bindgen!({
path: "../horizon-mod-sdk/wit",
world: "horizon-server-mod",
additional_derives: [PartialEq],
with: {
"horizon:mods/log": super::bindings::horizon::mods::log,
"horizon:mods/storage": super::bindings::horizon::mods::storage,
@@ -52,6 +54,7 @@ use bindings::{
pub use server_bindings::{
exports::horizon::mods::server_events::BlockPos,
horizon::mods::players::{GameMode, Player as ServerPlayer},
horizon::mods::world::BlockChange,
};
type ClientEvents = bindings::exports::horizon::mods::events::Guest;
type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest;
@@ -78,6 +81,24 @@ pub use render_bindings::horizon::mods::render::{
Zoom as ModZoom,
};
use render_bindings::{RenderHost, horizon::mods::render};
/// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items.
mod recipes_bindings {
wasmtime::component::bindgen!({
path: "../horizon-mod-sdk/wit",
world: "recipes-host",
});
}
/// Capability `ui`'s recipe viewer panel (WIT `interface browser`).
pub use recipes_bindings::horizon::mods::browser::{
Click as BrowserClick, Event as BrowserEvent, ItemKey as BrowserItemKey,
Layout as BrowserLayout, RecipeView as BrowserRecipe, SlotClick as BrowserSlotClick,
Stack as BrowserStack,
};
/// What capability `recipes` reads (WIT `interface recipes`).
pub use recipes_bindings::horizon::mods::recipes::{
Item as RecipeItem, Kind as RecipeKind, Recipe, Stack as RecipeStack,
};
use recipes_bindings::{RecipesHost, horizon::mods::browser, horizon::mods::recipes};
/// A mod's linear memory cap.
const MEMORY: usize = 64 << 20;
@@ -87,6 +108,8 @@ const FUEL_INIT: u64 = 2_000_000_000;
const FUEL_TICK: u64 = 50_000_000;
const FUEL_FRAME: u64 = 10_000_000;
const FUEL_EVENT: u64 = 100_000_000;
/// Blocks a mod may set per `world.set-blocks` call.
pub const BLOCKS_PER_CALL: usize = 4096;
/// Chat lines a mod may show per call, HUD lines and their length.
const CHAT_PER_CALL: usize = 8;
/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's
@@ -133,6 +156,23 @@ pub struct Snapshot {
/// its distance from the eye, for `game.raycast`; the game works it out
/// only while a mod calls it ([`Mods::wants_raycast`]).
pub view_hit: Option<(f32, Hit)>,
/// Every item and recipe, for capability `recipes`; the game makes them
/// once, and only while a mod reads them ([`Mods::wants_recipes`]).
pub recipes: Option<Arc<Recipes>>,
/// The `book-id`s of the recipes the player's book holds.
pub known_recipes: Arc<[i32]>,
/// The open screen takes recipes (`recipes.place`).
pub placing: bool,
/// The player is in creative mode (`recipes.give`).
pub creative: bool,
}
/// Capability `recipes`'s tables: `items` in the registry's order, which
/// each [`RecipeStack::item`] indexes.
#[derive(Clone, Debug, Default)]
pub struct Recipes {
pub items: Vec<RecipeItem>,
pub recipes: Vec<Recipe>,
}
/// Which mods a game starts: the window's game the client mods, the game
@@ -182,6 +222,13 @@ pub enum Output {
text: String,
error: bool,
},
/// `world.set-blocks`: changes to make in `dimension`, in order, each
/// state checked by the [`WorldView`] lent for the call.
SetBlocks {
name: String,
dimension: String,
blocks: Vec<BlockChange>,
},
/// `ui.open-screen`: the mod's entry in `entries()`; what it shows is
/// [`Mods::screen`].
OpenScreen { owner: usize },
@@ -189,8 +236,34 @@ pub enum Output {
CloseScreen { owner: usize },
/// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10).
Shake { strength: f32, seconds: f32 },
/// `recipes.place`: the recipe book's click on this display id, all of
/// it when `all`.
PlaceRecipe { book_id: i32, all: bool },
/// `recipes.give`: a stack for a creative player.
Give {
item: String,
count: u32,
components: String,
},
}
/// The game's world as capability `world` reads it during a call: the
/// game lends one with [`Mods::lend_world`] and takes it back after.
pub trait WorldView: std::any::Any + Send {
/// The block state at a position, `minecraft:oak_log[axis=y]`; `None`
/// where no chunk of that dimension is loaded.
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
/// The biome at a position, `minecraft:plains`; `None` as for blocks.
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
/// Whether `dimension` is one the server has.
fn has_dimension(&self, dimension: &str) -> bool;
/// `Err` (why) for a state string that names no block state.
fn check_state(&self, state: &str) -> Result<(), String>;
}
/// The view lent for the current calls, shared by every mod's store.
type WorldSlot = Arc<Mutex<Option<Box<dyn WorldView>>>>;
/// A mod's text panel, drawn every frame until it changes.
#[derive(Clone, Debug)]
pub struct Panel {
@@ -241,6 +314,8 @@ struct Running {
hooks: Hooks,
/// It imports `game.raycast`.
raycasts: bool,
/// It imports capability `recipes`.
reads_recipes: bool,
}
/// A running mod's exports and the hooks its `init` asked for.
@@ -282,6 +357,46 @@ struct UiState {
close: bool,
}
/// Capability `ui`'s panel beside container screens (`browser`).
#[derive(Default)]
struct BrowserState {
items: Vec<BrowserStack>,
/// Which `set-items` or `set-recipes` call the panel is from, unique
/// across mods and reloads, so the game converts them once.
version: u64,
/// `set-recipes`' title and recipes, shown instead of the items.
recipes: Option<RecipePage>,
events: std::collections::VecDeque<BrowserEvent>,
}
/// What `browser.set-recipes` shows: a title, tabs (`tab` the selected
/// one) and the recipes.
#[derive(Clone, Debug)]
pub struct RecipePage {
pub title: String,
pub tabs: Vec<BrowserStack>,
pub tab: u32,
pub recipes: Vec<BrowserRecipe>,
}
static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// Items a panel may hold, and events kept for `browser.poll`.
const BROWSER_ITEMS: usize = 8192;
/// `recipes.place` and `give` calls a hook call may make.
const RECIPE_ACTIONS: usize = 36;
/// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles.
const BROWSER_RECIPES: usize = 256;
const RECIPE_SLOTS: usize = 9;
const RECIPE_TABS: usize = 16;
const SLOT_STACKS: usize = 64;
const BROWSER_EVENTS: usize = 256;
impl BrowserState {
fn push(&mut self, event: BrowserEvent) {
if self.events.len() == BROWSER_EVENTS {
self.events.pop_front();
}
self.events.push_back(event);
}
}
struct State {
name: String,
id: String,
@@ -298,6 +413,7 @@ struct State {
/// Capability `render`'s minimap, when the mod shows one.
minimap: Option<ModMinimap>,
input: InputState,
browser: BrowserState,
/// Capability `storage`'s folder; made on first `set`.
data_dir: PathBuf,
/// Bytes `storage::set` may still write before this hook call ends
@@ -306,6 +422,7 @@ struct State {
/// needs its own budget.
storage_budget: u64,
limits: StoreLimits,
world: WorldSlot,
}
/// The installed mods and the engine running them. `Mods::default()` is
@@ -316,9 +433,33 @@ pub struct Mods {
entries: Vec<Entry>,
snapshot: Arc<Snapshot>,
out: Vec<Output>,
world: WorldSlot,
}
impl Mods {
/// Whether a running mod may use capability `world`: only then is a
/// view worth lending.
pub fn wants_world(&self) -> bool {
self.entries.iter().any(|e| {
e.status == Status::Running
&& e.manifest
.as_ref()
.is_some_and(|m| m.capabilities.contains(&crate::Capability::World))
})
}
/// Lends the game's world to capability `world` for the calls until
/// [`Mods::take_world`]; with none lent, `get-block` finds nothing and
/// `set-blocks` checks only its count.
pub fn lend_world(&mut self, view: Box<dyn WorldView>) {
if let Ok(mut slot) = self.world.lock() {
*slot = Some(view);
}
}
/// The view [`Mods::lend_world`] lent, back to the game.
pub fn take_world(&mut self) -> Option<Box<dyn WorldView>> {
self.world.lock().ok()?.take()
}
/// Reads every mod at `paths` and starts those `enabled` says are on,
/// client and server mods alike. A command that `reserved` (vanilla's
/// commands) or an earlier mod already uses is refused.
@@ -388,10 +529,14 @@ impl Mods {
.map_err(|e| e.to_string())?;
players::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
mod_world::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
UiHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
RenderHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
RecipesHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
self.engine = Some((engine, linker));
}
Ok(self.engine.as_ref().expect("made above"))
@@ -429,6 +574,7 @@ impl Mods {
.flat_map(|r| r.hooks.commands().iter().cloned())
.collect();
let snapshot = self.snapshot.clone();
let world = self.world.clone();
let (engine, linker) = self.engine()?;
let component =
Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?;
@@ -461,12 +607,14 @@ impl Mods {
zoom: None,
minimap: None,
input: InputState::default(),
browser: BrowserState::default(),
data_dir,
storage_budget: STORAGE_WRITE_BUDGET,
limits: StoreLimitsBuilder::new()
.memory_size(MEMORY)
.instances(16)
.build(),
world,
};
let mut store = Store::new(engine, state);
store.limiter(|s| &mut s.limits);
@@ -509,6 +657,7 @@ impl Mods {
ui,
hooks,
raycasts: functions.iter().any(|f| f == "game.raycast"),
reads_recipes: functions.iter().any(|f| f.starts_with("recipes.")),
}))
}
@@ -769,6 +918,58 @@ impl Mods {
.iter()
.any(|e| e.run.as_ref().is_some_and(|r| r.raycasts))
}
/// The panel beside container screens (`browser.set-items`): the first
/// running mod with items or recipes, its index, the panel's version and
/// the items.
pub fn browser_items(&self) -> Option<(usize, u64, &[BrowserStack])> {
self.entries.iter().enumerate().find_map(|(i, e)| {
let b = &e.run.as_ref()?.store.data().browser;
(!b.items.is_empty() || b.recipes.is_some()).then_some((
i,
b.version,
b.items.as_slice(),
))
})
}
/// What mod `owner`'s panel shows instead of its items
/// (`browser.set-recipes`).
pub fn browser_recipes(&self, owner: usize) -> Option<&RecipePage> {
let b = &self.entries.get(owner)?.run.as_ref()?.store.data().browser;
b.recipes.as_ref()
}
/// The player did `event` on mod `owner`'s panel.
pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) {
if let Some(run) = self.entries.get_mut(owner).and_then(|e| e.run.as_mut()) {
run.store.data_mut().browser.push(event);
}
}
/// The key `key` went down with the pointer on `stack` in a container
/// screen: each mod with a key on it hears its own name for it.
pub fn browser_key(&mut self, key: &str, stack: &BrowserStack) {
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
let data = run.store.data_mut();
let names: Vec<String> = data
.input
.keys
.iter()
.filter(|k| k.key == key)
.map(|k| k.name.clone())
.collect();
for key in names {
data.browser.push(BrowserEvent::Key(BrowserItemKey {
key,
stack: stack.clone(),
}));
}
}
}
/// Some running mod reads capability `recipes`: the snapshot needs
/// [`Snapshot::recipes`] and [`Snapshot::known_recipes`].
pub fn wants_recipes(&self) -> bool {
self.entries
.iter()
.any(|e| e.run.as_ref().is_some_and(|r| r.reads_recipes))
}
/// Some running mod has a `frame` hook: the game refreshes the snapshot
/// every frame for it.
pub fn wants_frames(&self) -> bool {
@@ -1064,7 +1265,10 @@ fn reason(e: &wasmtime::Error) -> String {
}
fn clip(text: String) -> String {
match text.char_indices().nth(LINE_CHARS) {
clip_to(text, LINE_CHARS)
}
fn clip_to(text: String, chars: usize) -> String {
match text.char_indices().nth(chars) {
Some((at, _)) => text[..at].to_string(),
None => text,
}
@@ -1125,6 +1329,125 @@ impl game::Host for State {
(*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone())
}
}
impl browser::Host for State {
fn set_items(&mut self, items: Vec<BrowserStack>) {
self.browser.items = items
.into_iter()
.take(BROWSER_ITEMS)
.map(|s| BrowserStack {
item: clip(s.item),
components: clip_to(s.components, 4096),
..s
})
.collect();
self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
fn set_recipes(
&mut self,
title: String,
tabs: Vec<BrowserStack>,
tab: u32,
recipes: Vec<BrowserRecipe>,
) {
let stack = |s: BrowserStack| BrowserStack {
item: clip(s.item),
components: clip_to(s.components, 4096),
..s
};
let cycle = |list: Vec<BrowserStack>| -> Vec<BrowserStack> {
list.into_iter().take(SLOT_STACKS).map(stack).collect()
};
self.browser.recipes = (!recipes.is_empty()).then(|| {
let recipes = recipes
.into_iter()
.take(BROWSER_RECIPES)
.map(|r| BrowserRecipe {
width: r.width.clamp(1, 3),
height: r.height.clamp(1, 3),
slots: r.slots.into_iter().take(RECIPE_SLOTS).map(cycle).collect(),
results: cycle(r.results),
note: clip(r.note),
..r
})
.collect();
RecipePage {
title: clip(title),
tabs: tabs.into_iter().take(RECIPE_TABS).map(stack).collect(),
tab,
recipes,
}
});
self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
fn poll(&mut self) -> Vec<BrowserEvent> {
self.browser.events.drain(..).collect()
}
}
impl recipes::Host for State {
fn items(&mut self) -> Vec<RecipeItem> {
self.snapshot
.recipes
.as_ref()
.map_or_else(Vec::new, |r| r.items.clone())
}
fn all(&mut self) -> Vec<Recipe> {
self.snapshot
.recipes
.as_ref()
.map_or_else(Vec::new, |r| r.recipes.clone())
}
fn known(&mut self) -> Vec<i32> {
self.snapshot.known_recipes.to_vec()
}
fn place(&mut self, book_id: i32, all: bool) -> Result<(), String> {
self.recipe_action()?;
if !self.snapshot.placing {
return Err("no screen that takes recipes is open".into());
}
if !self.snapshot.known_recipes.contains(&book_id) {
return Err(format!(
"recipe {book_id} is not in the player's recipe book"
));
}
self.out.push(Output::PlaceRecipe { book_id, all });
Ok(())
}
fn give(&mut self, stack: RecipeStack) -> Result<(), String> {
self.recipe_action()?;
if !self.snapshot.creative {
return Err("only in creative mode".into());
}
let item = self
.snapshot
.recipes
.as_ref()
.and_then(|r| r.items.get(stack.item as usize))
.ok_or_else(|| format!("no item {}", stack.item))?
.id
.clone();
self.out.push(Output::Give {
item,
count: stack.count.clamp(1, 99),
components: clip_to(stack.components, 4096),
});
Ok(())
}
}
impl State {
/// `recipes.place` and `give` take at most [`RECIPE_ACTIONS`] a call.
fn recipe_action(&self) -> Result<(), String> {
let done = self
.out
.iter()
.filter(|o| matches!(o, Output::PlaceRecipe { .. } | Output::Give { .. }))
.count();
if done < RECIPE_ACTIONS {
Ok(())
} else {
Err(format!("at most {RECIPE_ACTIONS} places and gives a call"))
}
}
}
impl State {
/// Queues a chat line unless the call already sent [`CHAT_PER_CALL`].
fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool {
@@ -1153,6 +1476,40 @@ impl chat::Host for State {
});
}
}
impl mod_world::Host for State {
fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
let view = self.world.lock().ok()?;
view.as_ref()?.block(&dimension, x, y, z)
}
fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
let view = self.world.lock().ok()?;
view.as_ref()?.biome(&dimension, x, y, z)
}
fn set_blocks(&mut self, dimension: String, blocks: Vec<BlockChange>) -> Result<(), String> {
if blocks.len() > BLOCKS_PER_CALL {
return Err(format!(
"{} blocks: at most {BLOCKS_PER_CALL} per call",
blocks.len()
));
}
if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) {
if !view.has_dimension(&dimension) {
return Err(format!("no dimension {dimension}"));
}
for b in &blocks {
view.check_state(&b.state)?;
}
}
if !blocks.is_empty() {
self.out.push(Output::SetBlocks {
name: self.name.clone(),
dimension,
blocks,
});
}
Ok(())
}
}
impl players::Host for State {
fn online(&mut self) -> Vec<ServerPlayer> {
self.snapshot.players.clone()
+89 -3
View File
@@ -29,6 +29,54 @@ pub struct TestGame {
/// Every name that joined, for their id.
names: Vec<String>,
tick: u64,
/// Capability `world`'s Overworld: the blocks a script set or the mod
/// changed; every other block, and the other dimensions, are air. Every
/// biome is the dimension's plainest: plains, nether wastes, the end.
pub world: std::collections::BTreeMap<(i32, i32, i32), String>,
}
/// The world a script's mod reads: [`TestGame::world`], copied for a step.
struct ScriptWorld(std::collections::BTreeMap<(i32, i32, i32), String>);
impl crate::WorldView for ScriptWorld {
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let here = (dimension == "minecraft:overworld")
.then(|| self.0.get(&(x, y, z)).cloned())
.flatten();
Some(here.unwrap_or_else(|| "minecraft:air".into()))
}
fn biome(&self, dimension: &str, _x: i32, _y: i32, _z: i32) -> Option<String> {
let biome = match dimension {
"minecraft:overworld" => "minecraft:plains",
"minecraft:the_nether" => "minecraft:nether_wastes",
"minecraft:the_end" => "minecraft:the_end",
_ => return None,
};
Some(biome.into())
}
fn has_dimension(&self, dimension: &str) -> bool {
matches!(
dimension,
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
)
}
fn check_state(&self, state: &str) -> Result<(), String> {
// No registry here: the shape only (the game checks the names).
let name = state.split('[').next().unwrap_or_default();
let plain = |t: &str| {
!t.is_empty()
&& t.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-/".contains(&b))
};
let ok = match name.split_once(':') {
Some((ns, path)) => plain(ns) && plain(path),
None => plain(name),
};
let closed = !state.contains('[') || state.ends_with(']');
(ok && closed)
.then_some(())
.ok_or_else(|| format!("{state} is not a block state"))
}
}
/// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing
@@ -71,6 +119,7 @@ impl TestGame {
players: Vec::new(),
names: Vec::new(),
tick: 0,
world: Default::default(),
};
copy_mod(hmod, &copy)?;
game.start()?;
@@ -312,9 +361,10 @@ pub struct ClockSet {
}
/// One step. Its parts happen in this order: `reload`, `title-screen`,
/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`,
/// `place`, `leave`; then `expect` is checked against what the mod showed
/// during the step. For a server mod, `player`, `chat`, `command`, `break`
/// `blocks`, `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`,
/// `break`, `place`, `leave`; then the blocks the mod set are made, and
/// `expect` is checked against what the mod showed and changed during the
/// step. For a server mod, `player`, `chat`, `command`, `break`
/// and `place` are the doing of the player named by `as`, or of the first
/// player on.
#[derive(Debug, Default, Deserialize)]
@@ -341,6 +391,10 @@ pub struct Step {
#[serde(rename = "break")]
broken: Option<BlockSet>,
place: Option<BlockSet>,
/// Blocks of the Overworld before the rest of the step (capability
/// `world`); every other block is air.
#[serde(default)]
blocks: Vec<BlockSet>,
#[serde(default)]
expect: Expect,
}
@@ -363,6 +417,9 @@ pub struct Expect {
/// The panel's lines (`[]`: no panel) and its corner.
panel: Option<Vec<String>>,
corner: Option<String>,
/// Blocks of the Overworld after the step, the mod's changes made
/// (capability `world`).
blocks: Option<Vec<BlockSet>>,
/// The mod is turned off during this step, for a reason holding this text.
/// Without it, a mod that stops fails the test.
stopped: Option<String>,
@@ -467,6 +524,11 @@ impl Step {
game.player = None;
game.clock = None;
}
for b in &self.blocks {
game.world.insert((b.x, b.y, b.z), b.state.clone());
}
game.mods
.lend_world(Box::new(ScriptWorld(game.world.clone())));
if let Some(name) = &self.join {
game.join(name);
}
@@ -531,7 +593,19 @@ impl Step {
{
return Err(format!("{name} is not on the server"));
}
game.mods.take_world();
let out = game.drain();
for o in &out {
if let Output::SetBlocks {
dimension, blocks, ..
} = o
&& dimension == "minecraft:overworld"
{
for b in blocks {
game.world.insert((b.x, b.y, b.z), b.state.clone());
}
}
}
let stopped = out.iter().find_map(|o| match o {
Output::Stopped { reason, .. } => Some(reason.as_str()),
_ => None,
@@ -615,6 +689,18 @@ impl Step {
.unwrap_or_default();
same("panel", want, &got)?;
}
if let Some(want) = &e.blocks {
for b in want {
let got = game.world.get(&(b.x, b.y, b.z));
let got = got.map_or("minecraft:air", String::as_str);
if got != b.state {
return Err(format!(
"block at {} {} {}: expected {}, got {got}",
b.x, b.y, b.z, b.state
));
}
}
}
if let Some(want) = &e.corner {
let got = game.panel().map(|p| corner_name(p.corner).to_string());
same("corner", &Some(want.clone()), &got)?;

Some files were not shown because too many files have changed in this diff Show More