fix: prevent spectators from dropping hotbar items
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
//! Selected-slot drop state for the vanilla key-handler parity harness.
|
||||
use horizon_client::command::args::GameMode;
|
||||
use horizon_client::items::{ItemStack, take_held_drop};
|
||||
|
||||
fn main() {
|
||||
for mode in [
|
||||
GameMode::Survival,
|
||||
GameMode::Creative,
|
||||
GameMode::Adventure,
|
||||
GameMode::Spectator,
|
||||
] {
|
||||
for all in [false, true] {
|
||||
for _selected in [0, 8] {
|
||||
for count in [0, 1, 4, 64] {
|
||||
let mut slot = Some(ItemStack::new("minecraft:stone", count));
|
||||
let mut dropped = 0;
|
||||
for _ in 0..2 {
|
||||
if let Some(stack) =
|
||||
take_held_drop(&mut slot, all, mode == GameMode::Spectator)
|
||||
{
|
||||
dropped += stack.count;
|
||||
}
|
||||
println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1857,9 +1857,12 @@ impl Game<'_> {
|
||||
if self.eye_position().is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(thrown) =
|
||||
horizon_client::items::take_held_drop(&mut self.inventory[self.selected], all)
|
||||
else {
|
||||
let spectator = self.spectator();
|
||||
let Some(thrown) = horizon_client::items::take_held_drop(
|
||||
&mut self.inventory[self.selected],
|
||||
all,
|
||||
spectator,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.player_drop(thrown);
|
||||
|
||||
@@ -1705,7 +1705,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_held_drop(slot: &mut Option<ItemStack>, all: bool) -> Option<ItemStack> {
|
||||
/// Minecraft.handleKeybinds: spectators cannot drop from the selected slot.
|
||||
pub fn take_held_drop(
|
||||
slot: &mut Option<ItemStack>,
|
||||
all: bool,
|
||||
spectator: bool,
|
||||
) -> Option<ItemStack> {
|
||||
if spectator {
|
||||
return None;
|
||||
}
|
||||
let stack = slot.as_mut()?;
|
||||
if stack.count == 0 {
|
||||
return None;
|
||||
@@ -1727,10 +1735,23 @@ mod held_drop_tests {
|
||||
#[test]
|
||||
fn one_all_and_empty_drop() {
|
||||
let mut slot = Some(ItemStack::new("minecraft:stone", 4));
|
||||
assert_eq!(take_held_drop(&mut slot, false).unwrap().count, 1);
|
||||
assert_eq!(take_held_drop(&mut slot, false, false).unwrap().count, 1);
|
||||
assert_eq!(slot.as_ref().unwrap().count, 3);
|
||||
assert_eq!(take_held_drop(&mut slot, true).unwrap().count, 3);
|
||||
assert_eq!(take_held_drop(&mut slot, true, false).unwrap().count, 3);
|
||||
assert!(slot.is_none());
|
||||
assert!(take_held_drop(&mut slot, false).is_none());
|
||||
assert!(take_held_drop(&mut slot, false, false).is_none());
|
||||
}
|
||||
#[test]
|
||||
fn spectator_keeps_selected_stack_for_single_and_whole_stack_drops() {
|
||||
for all in [false, true] {
|
||||
let mut slot = Some(ItemStack::new("minecraft:stone", 4));
|
||||
assert!(take_held_drop(&mut slot, all, true).is_none());
|
||||
assert_eq!(slot.as_ref().unwrap().count, 4);
|
||||
// Leaving spectator allows dropping the same selected stack again.
|
||||
assert_eq!(
|
||||
take_held_drop(&mut slot, all, false).unwrap().count,
|
||||
if all { 4 } else { 1 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.io.PrintWriter;
|
||||
import net.minecraft.client.*;
|
||||
import net.minecraft.client.gui.Gui;
|
||||
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.world.entity.player.*;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.level.GameType;
|
||||
|
||||
/** Runs the real key handler through its drop loop; stops before item-use handling. */
|
||||
public final class VanillaHeldDropOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f;
|
||||
}
|
||||
static <T> T make(Class<T> type) throws Exception {
|
||||
return type.cast(allocate.invoke(unsafe, type));
|
||||
}
|
||||
static final class Done extends RuntimeException {}
|
||||
static final class Client extends Minecraft {
|
||||
boolean all;
|
||||
Client() { super(null); }
|
||||
@Override public boolean hasControlDown() { return all; }
|
||||
}
|
||||
static final class Interface extends Gui {
|
||||
Interface() { super(null, null, null); }
|
||||
@Override public void handleKeybinds() {}
|
||||
}
|
||||
static final class Key extends KeyMapping {
|
||||
int clicks;
|
||||
Key() { super("", 0, null); }
|
||||
@Override public boolean consumeClick() { return clicks-- > 0; }
|
||||
@Override public boolean isDown() { return false; }
|
||||
}
|
||||
static final class Actor extends LocalPlayer {
|
||||
GameType mode;
|
||||
Actor() { super(null, null, null, null, null, null, false, null, null); }
|
||||
@Override public GameType gameMode() { return mode; }
|
||||
@Override public boolean isUsingItem() { throw new Done(); }
|
||||
}
|
||||
static final class Controller extends MultiPlayerGameMode {
|
||||
int dropped;
|
||||
Controller() { super(null, null); }
|
||||
// Controlled dispatch boundary: no networking, swings, statistics or item entities.
|
||||
@Override public void dropItem(LocalPlayer player, boolean all) {
|
||||
dropped += player.getInventory().removeFromSelected(all).getCount();
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
Items.AIR.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY);
|
||||
Items.STONE.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY);
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
unsafe = field(u, "theUnsafe").get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
var handler = Minecraft.class.getDeclaredMethod("handleKeybinds");
|
||||
handler.setAccessible(true);
|
||||
var client = make(Client.class);
|
||||
var options = make(Options.class);
|
||||
for (var f : Options.class.getDeclaredFields()) {
|
||||
if (f.getType() == KeyMapping.class && !Modifier.isStatic(f.getModifiers())) {
|
||||
f.setAccessible(true);
|
||||
f.set(options, make(Key.class));
|
||||
}
|
||||
}
|
||||
var hotbar = new KeyMapping[9];
|
||||
for (int i = 0; i < 9; i++) hotbar[i] = make(Key.class);
|
||||
field(Options.class, "keyHotbarSlots").set(options, hotbar);
|
||||
field(Minecraft.class, "options").set(client, options);
|
||||
field(Minecraft.class, "gui").set(client, make(Interface.class));
|
||||
var actor = make(Actor.class);
|
||||
var inventory = new Inventory(actor, new PlayerEquipment(actor));
|
||||
field(Player.class, "inventory").set(actor, inventory);
|
||||
field(Minecraft.class, "player").set(client, actor);
|
||||
var controller = make(Controller.class);
|
||||
field(Minecraft.class, "gameMode").set(client, controller);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) {
|
||||
for (var mode : GameType.values()) for (boolean all : new boolean[]{false, true}) {
|
||||
for (int selected : new int[]{0, 8}) for (int count : new int[]{0, 1, 4, 64}) {
|
||||
actor.mode = mode;
|
||||
client.all = all;
|
||||
inventory.clearContent();
|
||||
inventory.setSelectedSlot(selected);
|
||||
inventory.setItem(selected, new ItemStack(Items.STONE, count));
|
||||
controller.dropped = 0;
|
||||
// Two consecutive key presses also cover an emptied stack and repeated spectator drops.
|
||||
for (int press = 0; press < 2; press++) {
|
||||
((Key) options.keyDrop).clicks = 1;
|
||||
try {
|
||||
handler.invoke(client);
|
||||
throw new AssertionError("did not reach item-use boundary");
|
||||
} catch (InvocationTargetException e) {
|
||||
if (!(e.getCause() instanceof Done)) throw e;
|
||||
}
|
||||
out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare selected-slot drops with Minecraft.handleKeybinds in all four game modes.
|
||||
|
||||
The oracle invokes the unmodified native key handler, consuming real drop-key
|
||||
clicks. Its controlled dropItem callback removes from the real player Inventory;
|
||||
other keys are idle and execution stops at the following item-use boundary.
|
||||
Checks Q/Ctrl+Q, slots 0/8, empty/single/partial/full stacks and repeated drops.
|
||||
Packet delivery, item entities, swing animation and statistics are outside scope.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'held-drop-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
# Minecraft's key handler also links client-only libraries.
|
||||
_, game_dir = lab.config()
|
||||
libraries += sorted((game_dir / 'libraries/client').rglob('*.jar'))
|
||||
classpath = os.pathsep.join(map(str, [jars['client'], *libraries]))
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java'
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none',
|
||||
'-cp', classpath, '-d', str(classes), str(oracle)], check=True)
|
||||
subprocess.run(['java', '-Xmx512M', '-cp', str(classes) + os.pathsep + classpath,
|
||||
'dev.horizonlab.parity.VanillaHeldDropOracle', str(build / 'vanilla.txt')], check=True)
|
||||
with (build / 'rust.txt').open('w') as out:
|
||||
subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example',
|
||||
'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True)
|
||||
matched = base.compare(build / 'vanilla.txt', build / 'rust.txt')
|
||||
print(f'Held drop parity passed: {matched} selected-stack/drop-count snapshots match vanilla')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user