From f2f3fb6ede37c0431ccead98ee65f54e44e1eb23 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:00:07 +0200 Subject: [PATCH] fix: the ender dragon fight runs on server levels On a dedicated server (and single player's server thread) the End is ticked with no local player, and `tick_fight` returned before spawning the dragon: players in the End found crystals but never a dragon. - The fight finds its players as `EnderDragonFight.updatePlayers` does, every 20 ticks: every player alive within 192 blocks of (0, 128, 0), the host and the network players in the level alike. Scanning the state, the respawn sequence, `createNewDragon` and the crystal count run while it has one; the dragon and crystals tick whenever the End does. - The dragon is tracked to network players (`minecraft:ender_dragon`, its health and `DATA_PHASE` as vanilla pairs them, no attribute instances) and reserves its eight part ids after its own, as `EnderDragon`'s constructor does, so clients can attack the parts; a network player's attack on a part or an end crystal is aimed at it. tools/test_server_dragon_parity.py sends a lone vanilla-codec client to the End of vanilla's dedicated server and of Horizon's: the fight starts and the dragon is tracked with the same spawn data, synched data entries and attributes. VanillaProtocolClient's entity mode answers a scene's teleport with the acceptance alone, as the 26.3 client does. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 618db927d93bbcf7f3669ad0d630377c4646729d) --- crates/horizon-client/src/game/dragon.rs | 134 +++++++++++++--- crates/horizon-client/src/game/lan_actions.rs | 23 ++- .../horizon-client/src/game/lan_entities.rs | 8 + .../parity/VanillaProtocolClient.java | 4 +- tools/test_server_dragon_parity.py | 151 ++++++++++++++++++ 5 files changed, 287 insertions(+), 33 deletions(-) create mode 100644 tools/test_server_dragon_parity.py diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index d2413e45b..db7495ea4 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -37,6 +37,10 @@ pub(super) struct Fight { exit_portal: Option<[i32; 3]>, alive_crystals: i32, crystal_scan: i32, + /// `ticksSinceLastPlayerScan`, and whether the last scan found a player + /// for the fight (`dragonEvent.getPlayers()` is not empty). + player_scan: i32, + players: bool, /// The spikes' crystals have been placed (worldgen does not place entities here). crystals_placed: bool, /// The respawn sequence (`DragonRespawnStage`) and its tick count. @@ -239,6 +243,9 @@ impl Phase { } } pub(super) struct Dragon { + /// `Entity.id` once tracked to guests (0 before); its parts take the + /// eight ids after it (`EnderDragon`'s constructor reserves them). + pub id: u32, pub position: Vec3, pub previous: Vec3, velocity: Vec3, @@ -284,6 +291,7 @@ const ADJACENCY: [u32; 24] = [ impl Dragon { fn new(position: Vec3, yaw: f32, seed: i64) -> Self { Self { + id: 0, position, previous: position, velocity: Vec3::ZERO, @@ -422,6 +430,8 @@ impl Game<'_> { Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), _ => None, }, + // The first tick scans for players. + player_scan: 21, ..Default::default() }; if fight.gateways.is_empty() { @@ -495,45 +505,67 @@ impl Game<'_> { fn arena_loaded(&self) -> bool { (-2..=1).all(|cz| (-2..=1).all(|cx| self.streaming.is_lit(cx, cz))) } - /// `EnderDragonFight.tick` while the player is in the End. + /// `EnderDragonFight.validPlayer`: the players alive within 192 blocks of + /// (0, 128, 0), the host and the guests in the level alike. + fn fight_has_players(&self) -> bool { + let near = + |p: [f64; 3]| p[0].powi(2) + (p[1] - 128.0).powi(2) + p[2].powi(2) <= 192.0 * 192.0; + let host = self.player.as_ref().is_some_and(|p| { + !p.health.dead_or_dying() && near([p.position.x, p.position.y, p.position.z]) + }); + host || self.lan.as_ref().is_some_and(|h| { + h.hub + .guests + .iter() + .any(|g| h.hub.here(g) && g.loaded && !g.dead && near(g.position)) + }) + } + /// `EnderDragonFight.tick` and the fight's entities, while the End is + /// ticked (in place for its player, or on a server with players in it). pub(super) fn tick_fight(&mut self) { if self.dim != Dim::End || self.travelling.is_some() { return; } self.load_fight(); + // updatePlayers, every 20 ticks. + self.fight.player_scan += 1; + if self.fight.player_scan >= 20 { + self.fight.player_scan = 0; + self.fight.players = self.fight_has_players(); + } if !self.arena_loaded() { return; } - if self.fight.needs_scan { - // scanState: a missing exit portal means a fight in progress. - self.fight.previously_killed = self.end_portal_active(); - if !self.fight.previously_killed { - self.fight.killed = false; - } - self.fight.needs_scan = false; - self.fight.dirty = true; - } if !self.fight.crystals_placed { self.place_spike_crystals(); self.fight.crystals_placed = true; self.fight.dirty = true; } - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; - let near = p.x.powi(2) + (p.y - 128.0).powi(2) + p.z.powi(2) <= 192.0 * 192.0; - if !self.fight.killed && near && self.dragon.is_none() { - // createNewDragon: over the podium, holding pattern, a random yaw. - let yaw = self.world.random.next_float() * 360.0; - let seed = self.world.random.next_long(); - self.dragon = Some(Dragon::new(Vec3::new(0.0, 128.0, 0.0), yaw, seed)); - } - if self.fight.respawn.is_some() { - self.tick_respawn(); - } - self.fight.crystal_scan += 1; - if self.fight.crystal_scan >= 100 { - self.count_crystals(); + if self.fight.players { + if self.fight.needs_scan { + // scanState: a missing exit portal means a fight in progress. + self.fight.previously_killed = self.end_portal_active(); + if !self.fight.previously_killed { + self.fight.killed = false; + } + self.fight.needs_scan = false; + self.fight.dirty = true; + } + if self.fight.respawn.is_some() { + self.tick_respawn(); + } + if !self.fight.killed { + if self.dragon.is_none() { + // createNewDragon: over the podium, holding pattern, a random yaw. + let yaw = self.world.random.next_float() * 360.0; + let seed = self.world.random.next_long(); + self.dragon = Some(Dragon::new(Vec3::new(0.0, 128.0, 0.0), yaw, seed)); + } + self.fight.crystal_scan += 1; + if self.fight.crystal_scan >= 100 { + self.count_crystals(); + } + } } self.tick_crystals(); self.tick_dragon(); @@ -665,6 +697,21 @@ impl Game<'_> { } out } + /// The box of the dragon part or end crystal guests know as entity `id` + /// (`EnderDragonPart`s follow the dragon's id). + pub(super) fn tracked_special_box(&self, id: i32) -> Option { + let id = u32::try_from(id).ok().filter(|&id| id != 0)?; + if let Some(d) = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0) + && (d.id + 1..=d.id + 8).contains(&id) + { + return Some(d.part_box((id - d.id - 1) as usize)); + } + let i = self.crystals.iter().position(|c| c.id == id)?; + self.special_targets() + .into_iter() + .find(|(s, _)| *s == CRYSTAL_IDS + i as u32) + .map(|(_, b)| b) + } /// Damage to a special id (from projectiles and melee). pub(super) fn hit_special(&mut self, id: u32, amount: f32, by_player: bool) { if id >= CRYSTAL_IDS { @@ -2355,6 +2402,41 @@ impl Game<'_> { } } } +impl Game<'_> { + /// The dragon as guests track it (`EnderDragon.getAddEntityPacket` and + /// the synched data that differs from the defaults: its health, defined + /// as 1, and `DATA_PHASE`, defined as hovering). Vanilla pairs it with no + /// attribute instances. + pub(super) fn lan_dragon_state(&self) -> Option { + use horizon_protocol::entity_data::{Value, serializer}; + let d = self.dragon.as_ref().filter(|d| d.id != 0)?; + let mut meta = Vec::new(); + let health = d.health.max(0.0); + if health != 1.0 { + meta.push((9, serializer::FLOAT, Value::Float(health))); + } + let phase = d.phase.id(); + if phase != 10 { + meta.push((16, serializer::INT, Value::Int(phase))); + } + Some(horizon_client::lan::entity::EntityState { + id: d.id as i32, + uuid: super::lan::entity_uuid(d.id), + kind: "minecraft:ender_dragon".to_owned(), + position: [d.position.x, d.position.y, d.position.z], + yaw: d.yaw, + pitch: 0.0, + head_yaw: d.yaw, + on_ground: false, + velocity: [d.velocity.x, d.velocity.y, d.velocity.z], + data: 0, + meta, + equipment: Vec::new(), + attributes: Vec::new(), + precise: false, + }) + } +} impl Game<'_> { /// The dragon and fight for `horizon-ctl status`. pub(super) fn dragon_status(&self) -> serde_json::Value { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index af127f42a..ff250dddb 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1082,12 +1082,23 @@ impl Game<'_> { gi: usize, id: i32, ) -> Option<([f64; 3], [f64; 3])> { - let m = self.mobs.iter().find(|m| m.id as i32 == id)?; - let centre = [ - m.position.x, - m.position.y + m.kind.height * 0.5, - m.position.z, - ]; + let centre = match self.mobs.iter().find(|m| m.id as i32 == id) { + Some(m) => [ + m.position.x, + m.position.y + m.kind.height * 0.5, + m.position.z, + ], + // A dragon part or an end crystal (game/dragon.rs). + None => { + let b = self.tracked_special_box(id)?; + let (lo, hi) = (b.min_position(), b.max_position()); + [ + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ] + } + }; let g = &mut host.hub.guests[gi]; let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; let d = [centre[0] - eye[0], centre[1] - eye[1], centre[2] - eye[2]]; diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 020ec6adc..76d1588b3 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -264,6 +264,13 @@ impl Game<'_> { self.tridents.iter_mut().for_each(|t| give(&mut t.id)); self.rockets.iter_mut().for_each(|r| give(&mut r.id)); self.crystals.iter_mut().for_each(|c| give(&mut c.id)); + // EnderDragon: the dragon, then its eight parts. + if let Some(d) = self.dragon.as_mut() + && d.id == 0 + { + d.id = *next + 1; + *next += 9; + } } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -406,6 +413,7 @@ impl Game<'_> { } out.push(e); } + out.extend(self.lan_dragon_state()); } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index e1e7a24c4..9a72ea224 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -523,7 +523,9 @@ public final class VanillaProtocolClient { position.yRot(), position.xRot())); // The 26.3 client answers with the acceptance alone; a second position in the // same tick is an invalid move to vanilla's server once the player is loaded. - if (!respawning) { + // The entity mode's scene may teleport the player (to another level): the + // acceptance alone, as the 26.3 client sends. + if (!respawning && step < ENTITIES) { send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false)); } if (!loaded) { diff --git a/tools/test_server_dragon_parity.py b/tools/test_server_dragon_parity.py new file mode 100644 index 000000000..dc58e851d --- /dev/null +++ b/tools/test_server_dragon_parity.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""The dragon fight on a dedicated server, against vanilla's, seen by a vanilla client. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, with the same server.properties. A vanilla-codec client (VanillaProtocolClient in +its entity mode) joins, and once its chunks are in, the console sends it to the End, over the exit portal. Nobody +else is in the End: the fight must start from that player alone (`EnderDragonFight.tick` finds it among the +level's players, `createNewDragon` spawns the dragon over the podium) and the dragon must be tracked to the client +(`ServerEntity`'s pairing: ClientboundAddEntityPacket, the synched data, the attribute instances). + +The dragon's flight is random (its yaw, its holding-pattern turns), so its position, rotations and motion are +left out; its type, spawn data, which synched data entries it was paired with and sent (and their serializers) +and its attribute instances must match vanilla's exactly. +""" +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-dragon-parity' +PLAYER = 'Tester' +# Over the exit portal, well within 192 blocks of (0, 128, 0) and the dragon's holding pattern. +TO_THE_END = f'execute in minecraft:the_end run tp {PLAYER} 0.5 80 0.5' + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}-client.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), PLAYER, str(out), 'entities'], + cwd=lab.ROOT, stdout=log, stderr=subprocess.STDOUT, text=True) + try: + server.wait_for(rf'<{PLAYER}> summon the entities', timeout=180) + server.console(TO_THE_END) + client.wait(timeout=120) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + lines = out.read_text(encoding='utf-8').splitlines() + (build / f'{label}.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8') + return lines + + +def entities(lines, kind): + return [l for l in lines if l.startswith(f'play-entities entity {kind} ')] + + +def dragon_summary(line): + """What of a tracked dragon does not depend on its random flight: its spawn data, the synched data entries + (id and serializer) it was paired with and sent, and its attribute instances.""" + fields = dict(f.split(' ', 1) for f in line.split(' | ')[1:] if ' ' in f) + data = re.search(r' data (-?\d+) ', fields.get('add', '')) + pairing = sorted(int(e.split('=', 1)[0]) for e in fields.get('pairing', '').split() if '=' in e) + sent = sorted((int(k), v.split(' ', 1)[0]) for k, v in re.findall(r'(\d+)=(\d+ [^,}]*)', fields.get('data', ''))) + return { + 'spawn data': data.group(1) if data else None, + 'paired entries': pairing, + 'entries (id, serializer)': sent, + 'attributes': fields.get('attributes'), + 'equipment': fields.get('equipment'), + 'passengers': fields.get('passengers'), + } + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + # SERVER_DRAGON_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript. + sides = [s for s in os.environ.get('SERVER_DRAGON_SIDES', 'vanilla,horizon').split(',') if s] + if 'horizon' in sides: + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaProtocolClient'] + + world = build / 'generate' / 'world' + if not world.exists() or set(sides) == {'vanilla', 'horizon'}: + world = generate_world(vanilla_server, build) + results = {} + for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: + if label in sides: + results[label] = run_side(label, command, client, build, world) + else: + results[label] = (build / f'{label}.txt').read_text(encoding='utf-8').splitlines() + problems = [] + summaries = {} + for label, lines in results.items(): + errors = [l for l in lines if l.startswith('error')] + problems += [f'{label}: {e}' for e in errors[:5]] + dragons = entities(lines, 'minecraft:ender_dragon') + if not dragons: + problems.append(f'{label}: no dragon was tracked to the player in the End') + continue + summaries[label] = dragon_summary(dragons[0]) + if not problems and summaries['vanilla'] != summaries['horizon']: + problems.append(f'the dragons differ:\n vanilla {summaries["vanilla"]}\n horizon {summaries["horizon"]}') + if problems: + raise AssertionError(f'see {build}/vanilla.txt and horizon.txt:\n' + '\n'.join(problems)) + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + dragon=summaries['horizon'], output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='A lone player sent to the End of a dedicated server: the fight starts from it, the dragon spawns ' + 'and is tracked to its vanilla-codec client (spawn data, synched data entries, attributes).')) + print(f'server dragon: the fight started, dragon tracked as vanilla does ({summaries["horizon"]})') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}')