diff --git a/.idea/gradle.xml b/.idea/gradle.xml
index acbe309..9f08263 100644
--- a/.idea/gradle.xml
+++ b/.idea/gradle.xml
@@ -11,6 +11,7 @@
+
diff --git a/.idea/runConfigurations/_1_8_8__Start_Client.xml b/.idea/runConfigurations/_1_8_8__Start_Client.xml
index ac4e569..8a1e00e 100644
--- a/.idea/runConfigurations/_1_8_8__Start_Client.xml
+++ b/.idea/runConfigurations/_1_8_8__Start_Client.xml
@@ -4,7 +4,7 @@
Every vanilla screen goes through these methods, so each callback first
+ * checks whether the instance is the empty input screen created by OrangeX. {@link #isInWorld()} mirrors the game's own "should render level" flag.
+ * 1.8.9 only runs the HUD hook while a world is loaded, but modern versions
+ * also extract the GUI on the title screen, so listeners must not assume that
+ * receiving this event means the player is in game.
{@code ClassLoader#defineClass} is protected and cannot be called + * through reflection on modern JDKs; the native agent invokes it through + * JNI instead.
+ */ + public static Class> defineClass(ClassLoader loader, byte[] bytes) { + init(); + + try { + return (Class>) defineClass.invoke(null, loader, bytes); + } catch (Throwable t) { + throw new IllegalStateException("JuiceAgent.defineClass failed", t); + } + } + private static synchronized void init() { if (getClassBytesByName != null) { return; @@ -51,6 +69,8 @@ final class JuiceAgentBridge { getClassBytesByName = api.getMethod("getClassBytesByName", String.class); retransformClassByName = api.getMethod( "retransformClassByName", String.class, byte[].class, int.class); + defineClass = api.getMethod( + "defineClass", ClassLoader.class, byte[].class); } catch (Throwable t) { throw new IllegalStateException("JuiceAgent API is not available", t); } diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/GuiInputHook.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/GuiInputHook.java new file mode 100644 index 0000000..70dc47d --- /dev/null +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/GuiInputHook.java @@ -0,0 +1,98 @@ +package cn.xiaozhou233.orangex.hook.impl; + +import cn.xiaozhou233.orangex.OrangeX; +import cn.xiaozhou233.orangex.hook.ClassHook; +import cn.xiaozhou233.orangex.mapping.MappingManager; +import cn.xiaozhou233.orangex.mapping.MappingMethod; +import cn.xiaozhou233.orangex.mapping.MappingResolver; +import cn.xiaozhou233.orangex.runtime.RuntimeInfo; +import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion; +import javassist.CtClass; +import javassist.CtMethod; + +/** + * Forwards 1.8.9 {@code GuiScreen} input to the OrangeX empty input screen. + * + *1.8.9 has no {@code mouseMoved} callback, so the cursor position is + * sampled from {@code drawScreen(int, int, float)} every frame. Clicks are + * taken from the screen's normal mouse pipeline.
+ * + *26.2 does not need this hook: its input screen overrides the + * {@code Screen} callbacks directly.
+ */ +public final class GuiInputHook extends ClassHook { + + private static final String GUI_SCREEN = "net/minecraft/client/gui/GuiScreen"; + + private static final RuntimeInfo runtimeInfo = + OrangeX.getInstance().getRuntimeInfo(); + private static final MappingResolver resolver = MappingManager.getResolver(); + + @Override + protected String[] getInjectedClassNames() { + return new String[]{ + "cn.xiaozhou233.orangex.event.facade.InputEvents", + "cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input" + }; + } + + @Override + protected String getTargetClass() { + switch (runtimeInfo.getMinecraftVersion()) { + case V1_8_9: + return resolver.mapClass(GUI_SCREEN) + .getTargetName().replace("/", "."); + default: + return null; + } + } + + @Override + protected void transform(CtClass ctClass) throws Exception { + if (runtimeInfo.getMinecraftVersion() != MinecraftVersion.V1_8_9) { + return; + } + + injectBefore(ctClass, "drawScreen", "(IIF)V", + "InputEvents.onDrawScreen($0, $1, $2);"); + + injectBefore(ctClass, "mouseClicked", "(III)V", + "if (InputEvents.onMouseClicked($0, $1, $2, $3)) return;"); + + injectBefore(ctClass, "mouseReleased", "(III)V", + "if (InputEvents.onMouseReleased($0, $1, $2, $3)) return;"); + + injectBefore(ctClass, "mouseClickMove", "(IIIJ)V", + "InputEvents.onMouseDragged($0, $1, $2, $3);"); + + // Close with M while the empty screen is open. Repeat events are + // ignored so holding the key does not bounce the screen. + injectBefore(ctClass, "keyTyped", "(CI)V", + "if ($2 == V1_8_9Input.TOGGLE_KEY" + + " && !V1_8_9Input.isRepeatEvent()" + + " && InputEvents.onKeyTyped($0, $2)) return;"); + + // The empty screen is an overlay: it must not pause singleplayer. + injectAfter(ctClass, "doesGuiPauseGame", "()Z", + "if (InputEvents.isOurInputScreen($0)) { $_ = false; }"); + } + + private void injectBefore(CtClass ctClass, String name, + String descriptor, String code) throws Exception { + CtMethod method = find(ctClass, name, descriptor); + method.insertBefore(code); + } + + private void injectAfter(CtClass ctClass, String name, + String descriptor, String code) throws Exception { + CtMethod method = find(ctClass, name, descriptor); + method.insertAfter(code); + } + + private CtMethod find(CtClass ctClass, String name, String descriptor) + throws Exception { + MappingMethod mapping = resolver.mapMethod(GUI_SCREEN, name, descriptor); + return ctClass.getMethod( + mapping.getTargetName(), mapping.getTargetDescriptor()); + } +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/KeyPressHook.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/KeyPressHook.java new file mode 100644 index 0000000..9af6f4b --- /dev/null +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/KeyPressHook.java @@ -0,0 +1,65 @@ +package cn.xiaozhou233.orangex.hook.impl; + +import cn.xiaozhou233.orangex.OrangeX; +import cn.xiaozhou233.orangex.hook.ClassHook; +import cn.xiaozhou233.orangex.mapping.MappingManager; +import cn.xiaozhou233.orangex.mapping.MappingMethod; +import cn.xiaozhou233.orangex.mapping.MappingResolver; +import cn.xiaozhou233.orangex.runtime.RuntimeInfo; +import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion; +import javassist.CtClass; +import javassist.CtMethod; + +/** + * 1.8.9 key-press hook. + * + *{@code KeyBinding#onTick(int)} is called for every key press while no + * screen is open. Using it for the GUI toggle avoids missing a short tap + * between two 20 Hz client ticks.
+ */ +public final class KeyPressHook extends ClassHook { + + private static final String KEY_BINDING = + "net/minecraft/client/settings/KeyBinding"; + + private static final RuntimeInfo runtimeInfo = + OrangeX.getInstance().getRuntimeInfo(); + private static final MappingResolver resolver = MappingManager.getResolver(); + + @Override + protected String[] getInjectedClassNames() { + return new String[]{ + "cn.xiaozhou233.orangex.event.facade.InputEvents", + "cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input" + }; + } + + @Override + protected String getTargetClass() { + switch (runtimeInfo.getMinecraftVersion()) { + case V1_8_9: + return resolver.mapClass(KEY_BINDING) + .getTargetName().replace("/", "."); + default: + return null; + } + } + + @Override + protected void transform(CtClass ctClass) throws Exception { + if (runtimeInfo.getMinecraftVersion() != MinecraftVersion.V1_8_9) { + return; + } + + MappingMethod mapping = resolver.mapMethod( + KEY_BINDING, "onTick", "(I)V"); + CtMethod method = ctClass.getMethod( + mapping.getTargetName(), mapping.getTargetDescriptor()); + // Static method: $1 is the key code. Ignore auto-repeat so holding + // M does not toggle repeatedly. + method.insertBefore( + "if ($1 == V1_8_9Input.TOGGLE_KEY" + + " && !V1_8_9Input.isRepeatEvent())" + + " { InputEvents.onKeyPressed($1); }"); + } +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/Render2DHook.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/Render2DHook.java index 4f8578e..682bec9 100644 --- a/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/Render2DHook.java +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/hook/impl/Render2DHook.java @@ -16,10 +16,14 @@ import java.lang.reflect.Modifier; * Fires {@link cn.xiaozhou233.orangex.event.impl.EventRender2D} once per frame. * *While the empty screen is open the game stops sending mouse and keyboard + * input to the player. The screen itself forwards cursor and button events + * here, and feature code can poll this class from {@code EventRender2D} to + * draw hover effects, cursors, ClickGUI panels, etc.
+ * + *Coordinates are Minecraft GUI pixels (the same space as + * {@code Render2D}).
+ */ +public final class ClientInput { + + /** + * GUI toggle key. The actual key code is version-specific and is handled + * by {@code VersionInput}; this is only for documentation. + */ + public static final String TOGGLE_KEY_NAME = "M"; + + private static volatile boolean open; + private static volatile double mouseX; + private static volatile double mouseY; + private static volatile boolean leftDown; + private static volatile boolean rightDown; + private static volatile boolean middleDown; + + private static boolean toggleWasDown; + private static boolean started; + private static boolean pendingOpen; + private static boolean pendingClose; + + private ClientInput() { + } + + /** + * Called once per client tick by {@link InputController}. + */ + public static void tick(Minecraft minecraft) { + if (!started) { + started = true; + System.out.println("[OrangeX] Input controller active"); + } + + boolean screenOpen = minecraft.isInputScreenOpen(); + + if (open && !screenOpen) { + reset(); + } else if (!open && screenOpen) { + onScreenOpened(minecraft.getGuiMouseX(), minecraft.getGuiMouseY()); + } + + boolean down = minecraft.isToggleKeyDown(); + + if (minecraft.isToggleEventDriven()) { + // 1.8.9 opens from KeyBinding#onTick (pendingOpen). Closing is + // polled here and applied at the end of the tick so the same key + // event is not also delivered to the freshly opened screen. + if (open && down && !toggleWasDown) { + pendingClose = true; + } + } else if (down && !toggleWasDown) { + // 26.2: no injected Screen subclass key handling, so opening / + // closing here cannot bounce. + if (open) { + minecraft.closeInputScreen(); + } else if (minecraft.isInWorld() && !minecraft.isScreenOpen()) { + minecraft.openInputScreen(); + } + } + + toggleWasDown = down; + } + + /** + * Applies a queued 1.8.9 toggle after the tick's keyboard/mouse handling. + */ + public static void applyPending(Minecraft minecraft) { + if (pendingOpen) { + pendingOpen = false; + if (!open && minecraft.isInWorld() && !minecraft.isScreenOpen()) { + minecraft.openInputScreen(); + // The key event that opened the screen is still held down. + toggleWasDown = true; + } + } + + if (pendingClose) { + pendingClose = false; + if (open) { + minecraft.closeInputScreen(); + toggleWasDown = true; + } + } + } + + public static void requestOpen() { + pendingOpen = true; + } + + public static void requestClose() { + pendingClose = true; + } + + public static void onMouseMove(double x, double y) { + mouseX = x; + mouseY = y; + } + + /** + * Marks the GUI as open immediately, without waiting for the next tick. + */ + public static void onScreenOpened(double x, double y) { + open = true; + mouseX = x; + mouseY = y; + toggleWasDown = true; + System.out.println("[OrangeX] Input screen opened"); + } + + public static void onMouseButton(double x, double y, int button, boolean pressed) { + mouseX = x; + mouseY = y; + + switch (button) { + case 0: + leftDown = pressed; + break; + case 1: + rightDown = pressed; + break; + case 2: + middleDown = pressed; + break; + default: + break; + } + } + + public static void reset() { + if (open) { + System.out.println("[OrangeX] Input screen closed"); + } + open = false; + leftDown = false; + rightDown = false; + middleDown = false; + } + + public static boolean isOpen() { + return open; + } + + public static double getMouseX() { + return mouseX; + } + + public static double getMouseY() { + return mouseY; + } + + public static boolean isLeftDown() { + return leftDown; + } + + public static boolean isRightDown() { + return rightDown; + } + + public static boolean isMiddleDown() { + return middleDown; + } +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/InputController.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/InputController.java new file mode 100644 index 0000000..c6a2304 --- /dev/null +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/InputController.java @@ -0,0 +1,46 @@ +package cn.xiaozhou233.orangex.input; + +import cn.xiaozhou233.orangex.event.impl.EventTickPost; +import cn.xiaozhou233.orangex.event.impl.EventTickPre; +import cn.xiaozhou233.orangex.wrapper.api.Minecraft; +import org.greenrobot.eventbus.Subscribe; +import org.greenrobot.eventbus.ThreadMode; + +/** + * Drives {@link ClientInput} from the game tick. + */ +public final class InputController { + + private final Minecraft minecraft; + private boolean failureLogged; + + public InputController(Minecraft minecraft) { + this.minecraft = minecraft; + } + + @Subscribe(threadMode = ThreadMode.POSTING) + public void onTick(EventTickPre event) { + try { + ClientInput.tick(minecraft); + } catch (Throwable throwable) { + logFailure(throwable); + } + } + + @Subscribe(threadMode = ThreadMode.POSTING) + public void onTickPost(EventTickPost event) { + try { + ClientInput.applyPending(minecraft); + } catch (Throwable throwable) { + logFailure(throwable); + } + } + + private void logFailure(Throwable throwable) { + if (!failureLogged) { + failureLogged = true; + System.err.println("[OrangeX] Input tick failed"); + throwable.printStackTrace(); + } + } +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/internal/VersionInput.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/internal/VersionInput.java new file mode 100644 index 0000000..88ed5fd --- /dev/null +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/internal/VersionInput.java @@ -0,0 +1,54 @@ +package cn.xiaozhou233.orangex.input.internal; + +/** + * Version-specific implementation of the input screen and the cursor helpers. + * + *Implementations live in version packages and may reference that + * version's classes directly. They are loaded lazily through + * {@link cn.xiaozhou233.orangex.wrapper.api.Minecraft} so that a 1.8.9 runtime + * never loads 26.2 classes and vice versa.
+ */ +public interface VersionInput { + + boolean isInWorld(); + + /** + * {@code true} when our own empty screen is the current Minecraft screen. + */ + boolean isInputScreenOpen(); + + /** + * {@code true} when any Minecraft screen is open, including vanilla ones. + */ + boolean isScreenOpen(); + + /** + * Identity check used by injected 1.8.9 code, which runs for every + * {@code GuiScreen} instance. + */ + boolean isInputScreenInstance(Object screen); + + /** + * Opens the empty screen. On both versions this releases the mouse and + * stops keyboard / mouse input from reaching the player. + */ + void openInputScreen(); + + void closeInputScreen(); + + /** + * M: {@code Keyboard.KEY_M} on 1.8.9, GLFW 77 on 26.2. + */ + boolean isToggleKeyDown(); + + /** + * {@code true} when opening/closing is driven by injected key events + * instead of polling {@link #isToggleKeyDown()} once per tick. 1.8.9 uses + * this so a very short key tap is not missed between ticks. + */ + boolean isToggleEventDriven(); + + double getGuiMouseX(); + + double getGuiMouseY(); +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/internal/v1_8_9/V1_8_9Input.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/internal/v1_8_9/V1_8_9Input.java new file mode 100644 index 0000000..6e5cd59 --- /dev/null +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/internal/v1_8_9/V1_8_9Input.java @@ -0,0 +1,315 @@ +package cn.xiaozhou233.orangex.input.internal.v1_8_9; + +import cn.xiaozhou233.orangex.hook.JuiceAgentBridge; +import cn.xiaozhou233.orangex.input.ClientInput; +import cn.xiaozhou233.orangex.input.internal.VersionInput; +import cn.xiaozhou233.orangex.mapping.MappingClass; +import cn.xiaozhou233.orangex.mapping.MappingField; +import cn.xiaozhou233.orangex.mapping.MappingMethod; +import cn.xiaozhou233.orangex.mapping.MappingResolver; +import cn.xiaozhou233.orangex.runtime.RuntimeInfo; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.LoaderClassPath; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.Display; + +import java.io.ByteArrayInputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * 1.8.9 input screen. + * + *{@code GuiScreen} is abstract in 1.8.9, so a concrete empty subclass is + * generated at runtime and defined into the game class loader. Opening it via + * {@code Minecraft#displayGuiScreen} calls {@code setIngameNotInFocus()}, + * which ungrabs the cursor, and while {@code currentScreen != null} the + * player's mouse and keyboard input is not processed.
+ * + *This class imports LWJGL 2 directly and is therefore loaded only on + * 1.8.9 through a reflective factory in the wrapper.
+ */ +public final class V1_8_9Input implements VersionInput { + + /** LWJGL 2 {@code Keyboard.KEY_M}. */ + public static final int TOGGLE_KEY = Keyboard.KEY_M; + + private static final String MINECRAFT_CLASS = "net/minecraft/client/Minecraft"; + private static final String GUI_SCREEN_CLASS = "net/minecraft/client/gui/GuiScreen"; + private static final String GENERATED_SCREEN = + "cn.xiaozhou233.orangex.input.internal.v1_8_9.GeneratedInputScreen"; + + private final Object minecraft; + private final ClassLoader loader; + + private final Class> guiScreenClass; + private final Field currentScreenField; + private final Field worldField; + private final Field screenWidthField; + private final Field screenHeightField; + private final Method displayGuiScreen; + + private Object shellScreen; + private Class> inputScreenClass; + + public V1_8_9Input(RuntimeInfo runtimeInfo, + MappingResolver resolver, + Object minecraft) { + this.minecraft = minecraft; + + MappingClass minecraftMapping = resolver.mapClass(MINECRAFT_CLASS); + MappingClass guiScreenMapping = resolver.mapClass(GUI_SCREEN_CLASS); + + ClassLoader loader = runtimeInfo.getMinecraftClassLoader(); + this.loader = loader; + Class> minecraftClass = loadClass( + minecraftMapping.getTargetName(), loader); + + this.guiScreenClass = loadClass( + guiScreenMapping.getTargetName(), loader); + this.currentScreenField = findField( + minecraftClass, + minecraftMapping.getField("currentScreen").getTargetName()); + this.worldField = findField( + minecraftClass, + minecraftMapping.getField("theWorld").getTargetName()); + + this.screenWidthField = findField( + guiScreenClass, + guiScreenMapping.getField("width").getTargetName()); + this.screenHeightField = findField( + guiScreenClass, + guiScreenMapping.getField("height").getTargetName()); + + MappingMethod displayMapping = resolver.mapMethod( + MINECRAFT_CLASS, + "displayGuiScreen", + "(Lnet/minecraft/client/gui/GuiScreen;)V"); + this.displayGuiScreen = findDisplayGuiScreen( + minecraftClass, displayMapping.getTargetName()); + } + + private static Class> loadClass(String internalName, ClassLoader loader) { + try { + return Class.forName( + internalName.replace('/', '.'), false, loader); + } catch (ClassNotFoundException e) { + throw new IllegalStateException( + "Cannot load " + internalName, e); + } + } + + private static Field findField(Class> owner, String name) { + for (Class> current = owner; current != null; current = current.getSuperclass()) { + try { + Field field = current.getDeclaredField(name); + field.setAccessible(true); + return field; + } catch (NoSuchFieldException ignored) { + // Continue with the superclass. + } + } + throw new IllegalStateException( + "Cannot find field '" + name + "' on " + owner.getName()); + } + + private Method findDisplayGuiScreen(Class> minecraftClass, String name) { + for (Method method : minecraftClass.getDeclaredMethods()) { + if (!method.getName().equals(name) + || method.getParameterTypes().length != 1 + || Modifier.isStatic(method.getModifiers())) { + continue; + } + if (method.getParameterTypes()[0].isAssignableFrom(guiScreenClass)) { + method.setAccessible(true); + return method; + } + } + try { + Method method = minecraftClass.getDeclaredMethod(name, guiScreenClass); + method.setAccessible(true); + return method; + } catch (NoSuchMethodException e) { + throw new IllegalStateException( + "Cannot find displayGuiScreen on " + minecraftClass.getName(), e); + } + } + + @Override + public boolean isInWorld() { + try { + return worldField.get(minecraft) != null; + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot read the world field", e); + } + } + + @Override + public boolean isInputScreenOpen() { + if (shellScreen == null) { + return false; + } + try { + return currentScreenField.get(minecraft) == shellScreen; + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot read the current screen", e); + } + } + + @Override + public boolean isScreenOpen() { + try { + return currentScreenField.get(minecraft) != null; + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot read the current screen", e); + } + } + + @Override + public boolean isInputScreenInstance(Object screen) { + return shellScreen != null && shellScreen == screen; + } + + @Override + public void openInputScreen() { + if (isInputScreenOpen()) { + return; + } + try { + Object screen = inputScreenClass().getDeclaredConstructor().newInstance(); + shellScreen = screen; + displayGuiScreen.invoke(minecraft, screen); + ClientInput.onScreenOpened(getGuiMouseX(), getGuiMouseY()); + } catch (ReflectiveOperationException e) { + shellScreen = null; + throw new IllegalStateException("Cannot open the 1.8.9 input screen", e); + } + } + + /** + * {@code GuiScreen} is abstract in 1.8.9, so generate a concrete empty + * subclass at runtime and define it into the game class loader. Doing it + * with bytecode avoids hardcoding obfuscated class names. + */ + private synchronized Class> inputScreenClass() { + if (inputScreenClass != null) { + return inputScreenClass; + } + + try { + ClassPool pool = new ClassPool(true); + pool.appendClassPath(new LoaderClassPath(loader)); + + CtClass base; + try { + base = pool.get(guiScreenClass.getName()); + } catch (Throwable notFound) { + // Some launch environments hide transformed class resources; + // fall back to the bytes the agent can read for the loaded class. + byte[] baseBytes = JuiceAgentBridge.getClassBytesByName( + guiScreenClass.getName().replace('.', '/')); + if (baseBytes == null) { + throw new IllegalStateException( + "Cannot load " + guiScreenClass.getName(), notFound); + } + base = pool.makeClass(new ByteArrayInputStream(baseBytes)); + } + + CtClass generated = pool.makeClass(GENERATED_SCREEN); + generated.setModifiers(Modifier.PUBLIC); + generated.setSuperclass(base); + + CtConstructor constructor = new CtConstructor(new CtClass[0], generated); + constructor.setModifiers(Modifier.PUBLIC); + constructor.setBody("super();"); + generated.addConstructor(constructor); + + byte[] bytes; + try { + bytes = generated.toBytecode(); + } finally { + generated.detach(); + base.detach(); + } + + Class> defined = JuiceAgentBridge.defineClass(loader, bytes); + if (defined == null) { + throw new IllegalStateException( + "JuiceAgent.defineClass returned null"); + } + inputScreenClass = defined; + return inputScreenClass; + } catch (Throwable throwable) { + throw new IllegalStateException( + "Cannot generate the 1.8.9 input screen", throwable); + } + } + + @Override + public void closeInputScreen() { + if (!isInputScreenOpen()) { + shellScreen = null; + ClientInput.reset(); + return; + } + try { + displayGuiScreen.invoke(minecraft, new Object[]{null}); + shellScreen = null; + ClientInput.reset(); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException("Cannot close the 1.8.9 input screen", e); + } + } + + @Override + public boolean isToggleKeyDown() { + return Keyboard.isKeyDown(TOGGLE_KEY); + } + + @Override + public boolean isToggleEventDriven() { + return true; + } + + /** + * Used by injected {@code GuiScreen}/{@code KeyBinding} code to ignore + * LWJGL auto-repeat events. + */ + public static boolean isRepeatEvent() { + return Keyboard.isRepeatEvent(); + } + + @Override + public double getGuiMouseX() { + Object screen = shellScreen; + if (screen == null) { + return 0.0; + } + try { + int width = screenWidthField.getInt(screen); + return (double) Mouse.getX() * (double) width / (double) Display.getWidth(); + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot read the GUI width", e); + } + } + + @Override + public double getGuiMouseY() { + Object screen = shellScreen; + if (screen == null) { + return 0.0; + } + try { + int height = screenHeightField.getInt(screen); + return (double) height + - (double) Mouse.getY() * (double) height / (double) Display.getHeight() + - 1.0; + } catch (IllegalAccessException e) { + throw new IllegalStateException("Cannot read the GUI height", e); + } + } +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/v26_2/V26_2Input.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/v26_2/V26_2Input.java new file mode 100644 index 0000000..ace3ed1 --- /dev/null +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/v26_2/V26_2Input.java @@ -0,0 +1,90 @@ +package cn.xiaozhou233.orangex.input.v26_2; + +import cn.xiaozhou233.orangex.input.ClientInput; +import cn.xiaozhou233.orangex.input.internal.VersionInput; +import cn.xiaozhou233.orangex.runtime.RuntimeInfo; +import com.mojang.blaze3d.platform.InputConstants; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Screen; + +/** + * 26.2 input implementation. + * + *Loaded reflectively only on 26.2; the wrapper keeps 1.8.9 runtimes free + * of these references.
+ */ +public final class V26_2Input implements VersionInput { + + /** GLFW_KEY_M. */ + private static final int TOGGLE_KEY = 77; + + private final Minecraft minecraft; + + private Screen shellScreen; + + public V26_2Input(RuntimeInfo runtimeInfo, Object minecraft) { + this.minecraft = (Minecraft) minecraft; + } + + @Override + public boolean isInWorld() { + return minecraft.level != null; + } + + @Override + public boolean isInputScreenOpen() { + return shellScreen != null && minecraft.gui.screen() == shellScreen; + } + + @Override + public boolean isScreenOpen() { + return minecraft.gui.screen() != null; + } + + @Override + public boolean isInputScreenInstance(Object screen) { + return shellScreen != null && shellScreen == screen; + } + + @Override + public void openInputScreen() { + if (isInputScreenOpen()) { + return; + } + shellScreen = new V26_2InputScreen(); + minecraft.gui.setScreen(shellScreen); + ClientInput.onScreenOpened(getGuiMouseX(), getGuiMouseY()); + } + + @Override + public void closeInputScreen() { + if (!isInputScreenOpen()) { + shellScreen = null; + ClientInput.reset(); + return; + } + minecraft.gui.setScreen(null); + shellScreen = null; + ClientInput.reset(); + } + + @Override + public boolean isToggleKeyDown() { + return InputConstants.isKeyDown(minecraft.getWindow(), TOGGLE_KEY); + } + + @Override + public boolean isToggleEventDriven() { + return false; + } + + @Override + public double getGuiMouseX() { + return minecraft.mouseHandler.getScaledXPos(minecraft.getWindow()); + } + + @Override + public double getGuiMouseY() { + return minecraft.mouseHandler.getScaledYPos(minecraft.getWindow()); + } +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/v26_2/V26_2InputScreen.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/v26_2/V26_2InputScreen.java new file mode 100644 index 0000000..1086c41 --- /dev/null +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/input/v26_2/V26_2InputScreen.java @@ -0,0 +1,69 @@ +package cn.xiaozhou233.orangex.input.v26_2; + +import cn.xiaozhou233.orangex.input.ClientInput; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; + +/** + * Empty input screen for 26.2. + * + *The client GUI is still rendered by the HUD hook; this screen only exists + * to move the game into its "screen open" state. Doing so makes + * {@code Gui#setScreen} release the mouse and clear key mappings, and routes + * mouse events to this instance instead of the player.
+ */ +public final class V26_2InputScreen extends Screen { + + public V26_2InputScreen() { + super(Component.empty()); + } + + @Override + public void extractBackground(GuiGraphicsExtractor graphics, + int mouseX, int mouseY, float partialTick) { + // No blur, panorama, menu texture or dim layer. + } + + @Override + public void extractRenderState(GuiGraphicsExtractor graphics, + int mouseX, int mouseY, float partialTick) { + // Drawn by the HUD hook instead. + } + + @Override + public boolean isPauseScreen() { + return false; + } + + @Override + public void mouseMoved(double x, double y) { + ClientInput.onMouseMove(x, y); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + ClientInput.onMouseButton(event.x(), event.y(), event.button(), true); + return true; + } + + @Override + public boolean mouseReleased(MouseButtonEvent event) { + ClientInput.onMouseButton(event.x(), event.y(), event.button(), false); + return true; + } + + @Override + public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) { + ClientInput.onMouseMove(event.x(), event.y()); + return true; + } + + @Override + public boolean mouseScrolled(double x, double y, + double scrollX, double scrollY) { + ClientInput.onMouseMove(x, y); + return true; + } +} diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/FontDebugOverlay.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/FontDebugOverlay.java index af59068..8d50332 100644 --- a/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/FontDebugOverlay.java +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/FontDebugOverlay.java @@ -1,6 +1,7 @@ package cn.xiaozhou233.orangex.render; import cn.xiaozhou233.orangex.event.impl.EventRender2D; +import cn.xiaozhou233.orangex.input.ClientInput; import cn.xiaozhou233.orangex.render.api.FontRenderer; import cn.xiaozhou233.orangex.render.api.Render2D; import org.greenrobot.eventbus.Subscribe; @@ -29,11 +30,23 @@ public final class FontDebugOverlay { 8, 26, 0xFF55FFFF); body.drawString("ASCII 0123456789", 8, 40, 0xFFAAAAAA); body.drawString("中文测试:钻石剑 / 迅捷", 8, 54, 0xFFFFAA00); + body.drawString("Input: " + (ClientInput.isOpen() ? "OPEN" : "closed") + + " mouse " + (int) ClientInput.getMouseX() + + ", " + (int) ClientInput.getMouseY(), + 8, 68, 0xFF55FF55); + body.drawString("M: toggle input screen", 8, 82, 0xFF888888); // Large high-contrast marker: if this is invisible too, the problem is // GL state/coordinates rather than the glyph atlas. FontRenderer marker = render2D.getFont(28.0f, true); marker.drawCenteredString("TEST", render2D.getWidth() / 2.0, render2D.getHeight() / 2.0 - 24.0, 0xFFFF3030); + + if (ClientInput.isOpen()) { + double mouseX = ClientInput.getMouseX(); + double mouseY = ClientInput.getMouseY(); + render2D.drawLine(mouseX - 7, mouseY, mouseX + 7, mouseY, 1.0, 0xFFFF4040); + render2D.drawLine(mouseX, mouseY - 7, mouseX, mouseY + 7, 1.0, 0xFFFF4040); + } } } diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/Render2DManager.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/Render2DManager.java index e1a9189..bbd0452 100644 --- a/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/Render2DManager.java +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/render/Render2DManager.java @@ -19,6 +19,14 @@ public final class Render2DManager { private final FontBackend backend; private final FontManager fonts; + /** + * Whether the overlay is drawn on screens that are not backed by a loaded + * level (title screen, world selection, ...). 1.8.9 never renders the HUD + * there, and this defaults to the same behaviour on every version. + * Enable with {@code -Dorangex.renderInMenus=true}. + */ + private volatile boolean renderInMenus = Boolean.getBoolean("orangex.renderInMenus"); + public Render2DManager(RuntimeInfo runtimeInfo, MappingResolver mappingResolver, Object minecraft) { @@ -28,6 +36,19 @@ public final class Render2DManager { } public void fire(Object platformContext) { + fire(platformContext, true); + } + + /** + * @param inWorld {@code true} when a level is loaded (the game's own + * "should render level" flag). When {@code false} the + * event is dropped unless {@link #isRenderInMenus()} is on. + */ + public void fire(Object platformContext, boolean inWorld) { + if (!inWorld && !renderInMenus) { + return; + } + EventBus eventBus = OrangeX.getInstance().getEventBus(); if (!eventBus.hasSubscriberForEvent(EventRender2D.class)) { return; @@ -35,12 +56,20 @@ public final class Render2DManager { Render2D context = backend.createRender2D(fonts, platformContext); try { - eventBus.post(new EventRender2D(context)); + eventBus.post(new EventRender2D(context, inWorld)); } finally { context.flush(); } } + public boolean isRenderInMenus() { + return renderInMenus; + } + + public void setRenderInMenus(boolean renderInMenus) { + this.renderInMenus = renderInMenus; + } + public String getBackendName() { return backend.getName(); } diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/api/Minecraft.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/api/Minecraft.java index 9f4bb2c..8156925 100644 --- a/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/api/Minecraft.java +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/api/Minecraft.java @@ -3,8 +3,8 @@ package cn.xiaozhou233.orangex.wrapper.api; /** * Cross-version view of {@code net.minecraft.client.Minecraft}. * - *Only the native client instance is exposed for now. More operations will be - * added incrementally as they are needed.
+ *Only the native client instance and the input-screen helpers are exposed + * for now. More operations will be added incrementally as they are needed.
*/ public interface Minecraft { @@ -15,4 +15,58 @@ public interface Minecraft { * handling belongs to the implementation. */ Object getMinecraft(); + + /** + * {@code true} while a level is loaded (the title screen returns + * {@code false}). + */ + boolean isInWorld(); + + /** + * {@code true} when the OrangeX empty input screen is the current screen. + */ + boolean isInputScreenOpen(); + + /** + * {@code true} when any Minecraft screen is open, including vanilla ones. + */ + boolean isScreenOpen(); + + /** + * Identity check for injected code: returns {@code true} only for the + * screen instance created by {@link #openInputScreen()}. + */ + boolean isInputScreenInstance(Object screen); + + /** + * Opens an empty screen. This releases the cursor and stops mouse and + * keyboard input from reaching the player. + */ + void openInputScreen(); + + /** + * Closes the input screen and gives mouse capture back to the game. + */ + void closeInputScreen(); + + /** + * {@code true} while the GUI toggle key (M) is held. + */ + boolean isToggleKeyDown(); + + /** + * {@code true} when the toggle is driven by key events (1.8.9) rather + * than per-tick polling (26.2). + */ + boolean isToggleEventDriven(); + + /** + * Current cursor X in Minecraft GUI pixels. + */ + double getGuiMouseX(); + + /** + * Current cursor Y in Minecraft GUI pixels. + */ + double getGuiMouseY(); } diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v1_8_9/V1_8_9Minecraft.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v1_8_9/V1_8_9Minecraft.java index 42f5751..33df64f 100644 --- a/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v1_8_9/V1_8_9Minecraft.java +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v1_8_9/V1_8_9Minecraft.java @@ -1,5 +1,6 @@ package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9; +import cn.xiaozhou233.orangex.input.internal.VersionInput; import cn.xiaozhou233.orangex.mapping.MappingClass; import cn.xiaozhou233.orangex.mapping.MappingField; import cn.xiaozhou233.orangex.mapping.MappingResolver; @@ -22,12 +23,15 @@ public final class V1_8_9Minecraft implements Minecraft { private static final String INSTANCE_FIELD = "theMinecraft"; private final RuntimeInfo runtimeInfo; + private final MappingResolver mappingResolver; private final MappingClass mappingMinecraft; private Object instance; + private VersionInput input; public V1_8_9Minecraft(RuntimeInfo runtimeInfo, MappingResolver mappingResolver) { this.runtimeInfo = runtimeInfo; + this.mappingResolver = mappingResolver; this.mappingMinecraft = mappingResolver.mapClass(MINECRAFT_CLASS); } @@ -39,6 +43,80 @@ public final class V1_8_9Minecraft implements Minecraft { return instance; } + /** + * Loads the version-specific input implementation on first use. The class + * name is kept as a string so a 26.2 runtime never resolves LWJGL 2. + */ + private synchronized VersionInput input() { + if (input == null) { + try { + Class> bridge = Class.forName( + "cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input", + true, + V1_8_9Minecraft.class.getClassLoader()); + input = (VersionInput) bridge.getConstructor( + RuntimeInfo.class, + MappingResolver.class, + Object.class) + .newInstance(runtimeInfo, mappingResolver, getMinecraft()); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException( + "Cannot create the 1.8.9 input bridge", e); + } + } + return input; + } + + @Override + public boolean isInWorld() { + return input().isInWorld(); + } + + @Override + public boolean isInputScreenOpen() { + return input().isInputScreenOpen(); + } + + @Override + public boolean isScreenOpen() { + return input().isScreenOpen(); + } + + @Override + public boolean isInputScreenInstance(Object screen) { + return input().isInputScreenInstance(screen); + } + + @Override + public void openInputScreen() { + input().openInputScreen(); + } + + @Override + public void closeInputScreen() { + input().closeInputScreen(); + } + + @Override + public boolean isToggleKeyDown() { + return input().isToggleKeyDown(); + } + + @Override + public boolean isToggleEventDriven() { + return input().isToggleEventDriven(); + } + + @Override + public double getGuiMouseX() { + return input().getGuiMouseX(); + } + + @Override + public double getGuiMouseY() { + return input().getGuiMouseY(); + } + private Object resolveInstance() { MappingField mappingField = mappingMinecraft.getField(INSTANCE_FIELD); if (mappingField == null) { diff --git a/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v26_2/V26_2Minecraft.java b/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v26_2/V26_2Minecraft.java index 048eca6..ca75123 100644 --- a/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v26_2/V26_2Minecraft.java +++ b/OrangeX/src/main/java/cn/xiaozhou233/orangex/wrapper/internal/v26_2/V26_2Minecraft.java @@ -1,5 +1,6 @@ package cn.xiaozhou233.orangex.wrapper.internal.v26_2; +import cn.xiaozhou233.orangex.input.internal.VersionInput; import cn.xiaozhou233.orangex.mapping.MappingClass; import cn.xiaozhou233.orangex.mapping.MappingField; import cn.xiaozhou233.orangex.mapping.MappingResolver; @@ -25,6 +26,7 @@ public final class V26_2Minecraft implements Minecraft { private final MappingClass mappingMinecraft; private Object instance; + private VersionInput input; public V26_2Minecraft(RuntimeInfo runtimeInfo, MappingResolver mappingResolver) { @@ -40,6 +42,79 @@ public final class V26_2Minecraft implements Minecraft { return instance; } + /** + * Loads the version-specific input implementation on first use. Keeping + * the 26.2 class behind a string keeps 1.8.9 runtimes clean. + */ + private synchronized VersionInput input() { + if (input == null) { + try { + Class> bridge = Class.forName( + "cn.xiaozhou233.orangex.input.v26_2.V26_2Input", + true, + V26_2Minecraft.class.getClassLoader()); + input = (VersionInput) bridge.getConstructor( + RuntimeInfo.class, + Object.class) + .newInstance(runtimeInfo, getMinecraft()); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException( + "Cannot create the 26.2 input bridge", e); + } + } + return input; + } + + @Override + public boolean isInWorld() { + return input().isInWorld(); + } + + @Override + public boolean isInputScreenOpen() { + return input().isInputScreenOpen(); + } + + @Override + public boolean isScreenOpen() { + return input().isScreenOpen(); + } + + @Override + public boolean isInputScreenInstance(Object screen) { + return input().isInputScreenInstance(screen); + } + + @Override + public void openInputScreen() { + input().openInputScreen(); + } + + @Override + public void closeInputScreen() { + input().closeInputScreen(); + } + + @Override + public boolean isToggleKeyDown() { + return input().isToggleKeyDown(); + } + + @Override + public boolean isToggleEventDriven() { + return input().isToggleEventDriven(); + } + + @Override + public double getGuiMouseX() { + return input().getGuiMouseX(); + } + + @Override + public double getGuiMouseY() { + return input().getGuiMouseY(); + } + private Object resolveInstance() { MappingField mappingField = mappingMinecraft.getField(INSTANCE_FIELD); if (mappingField == null) { diff --git a/docs/render/README.md b/docs/render/README.md index 68d7eb9..de30a3e 100644 --- a/docs/render/README.md +++ b/docs/render/README.md @@ -9,6 +9,7 @@ | [vape-font-gui-rendering.md](vape-font-gui-rendering.md) | Vape 4.21 的字体光栅化、文本排版、GUI 组件树、双渲染后端与 1.7.10–26.2 跨版本路径分析 | | [font-port.md](font-port.md) | OrangeX 的字体移植实现:TTF 烘焙、Render2D API、1.8.9 / 26.2 接入、调试参数与限制 | | [gui-rendering.md](gui-rendering.md) | 2D GUI 绘制层:矩形、渐变、圆角、描边、直线、裁剪及两版本实现 | +| [world-gating-and-input.md](world-gating-and-input.md) | 世界内渲染判定、1.8.9 / 26.2 鼠标捕获差异,以及已落地的空 GUI / 输入层实现 | ## 快速导航 @@ -25,6 +26,7 @@ - Universal Shader 批次渲染 → 主文档 §3.5 - 1.21.6+ / 26.x 兼容 → 主文档 §3.7 - 版本矩阵 → 主文档 §4 +- 世界内渲染判定与鼠标输入 → [world-gating-and-input.md](world-gating-and-input.md) ## 阅读前提 diff --git a/docs/render/world-gating-and-input.md b/docs/render/world-gating-and-input.md new file mode 100644 index 0000000..00f1960 --- /dev/null +++ b/docs/render/world-gating-and-input.md @@ -0,0 +1,418 @@ +# 世界内渲染与鼠标输入 + +本文记录两件事: + +1. 为什么 1.8.9 的字体 / GUI 只在进入世界后绘制,而 26.2 在主界面也会绘制,以及 OrangeX 现在如何统一。 +2. 客户端 GUI 打开时,如何让鼠标在 GUI 上移动,而不是继续控制游戏视角。 + +> 状态:第 1 部分和第 2 部分的空 GUI / 鼠标输入已落地。M 键打开或关闭输入界面。 + +--- + +## 1. 世界内渲染 + +### 1.1 两个版本的差异 + +| 版本 | Hook 点 | 调用时机 | +| --- | --- | --- | +| 1.8.9 | `GuiIngame#renderGameOverlay(float)` | `EntityRenderer#updateCameraAndRender` 中,只有 `theWorld != null` 才会调用 | +| 26.2 | `Gui#extractRenderState(DeltaTracker, boolean, boolean)` | 每帧都调用,主界面 / 选世界 / 加载界面同样会执行 | + +26.2 的第二个参数就是“当前是否渲染世界”: + +```java +// GameRenderer#extract +boolean readyForLevelRendering = + resourcesLoaded && advanceGameTime && minecraft.level != null; +minecraft.gui.extractRenderState(deltaTracker, readyForLevelRendering, resourcesLoaded); +``` + +所以 26.2 并不是渲染层出了问题,而是 Hook 拿到的回调本身不区分“菜单”和“世界”。 + +### 1.2 OrangeX 的处理 + +26.2 的注入代码把 `shouldRenderLevel` 一起传给门面: + +```java +// Render2DHook,26.2 分支 +// $0 = this, $1 = DeltaTracker, $2 = shouldRenderLevel +method.insertAfter("Render2DEvents.fire($0, $2);"); +``` + +> 注意:Javassist 的 `$0` 是 `this`,`$1` 才是第一个参数。26.2 的 `shouldRenderLevel` 是第二个参数,因此是 `$2`。 + +1.8.9 的 HUD 方法本来就只在世界内执行,显式传 `true`: + +```java +method.insertAfter("Render2DEvents.fire(null, true);"); +``` + +事件链: + +```text +注入代码 + └─ Render2DEvents.fire(context, inWorld) + └─ Render2DManager.fire(context, inWorld) + ├─ inWorld == false 且未开启菜单渲染 → 直接 return + └─ post EventRender2D(context, inWorld) +``` + +相关文件: + +```text +OrangeX/src/main/java/cn/xiaozhou233/orangex/ +├── hook/impl/Render2DHook.java +├── event/facade/Render2DEvents.java +├── event/impl/EventRender2D.java +└── render/Render2DManager.java +``` + +### 1.3 监听器侧 + +`EventRender2D` 新增了: + +```java +public boolean isInWorld(); +``` + +默认情况下主界面不会收到事件;如果以后需要让某个功能在菜单里也绘制,可以临时打开: + +```java +OrangeX.getInstance().getRender2DManager().setRenderInMenus(true); +``` + +或启动参数: + +```text +-Dorangex.renderInMenus=true +``` + +打开后事件仍然会带 `inWorld=false`,监听器可以自行区分。 + +--- + +## 2. 鼠标输入 + +渲染和输入是两套独立机制。字体 / GUI 画出来不代表鼠标就能用,真正决定鼠标行为的是游戏的鼠标捕获状态: + +- 1.8.9:`Minecraft#inGameHasFocus` + `MouseHelper` +- 26.2:`MouseHandler#mouseGrabbed` + +只要还在捕获状态,鼠标移动就会转视角。 + +### 2.1 为什么“只放开鼠标”不够 + +#### 1.8.9 + +`Minecraft#setIngameNotInFocus()` 会调用 `mouseHelper.ungrabMouseCursor()`,鼠标可以出来。但 `runTick()` 里还有: + +```java +if (this.currentScreen == null) { + if (!this.inGameHasFocus && Mouse.getEventButtonState()) { + this.setIngameFocus(); // 下一次点击重新捕获 + } +} +``` + +而且 `currentScreen == null` 时,鼠标事件仍会走 `KeyBinding.setKeyBindState(...)` / `KeyBinding.onTick(...)`,攻击、使用物品等逻辑依然会触发。 + +#### 26.2 + +`MouseHandler#releaseMouse()` 只是修改 `mouseGrabbed` 并恢复 GLFW 光标: + +```java +public void releaseMouse() { + if (this.mouseGrabbed) { + this.mouseGrabbed = false; + ... + InputConstants.grabOrReleaseMouse(this.minecraft.getWindow(), 212993, this.xpos, this.ypos); + } +} +``` + +但 `MouseHandler#onButton()` 中: + +```java +if (this.minecraft.gui.screen() == null) { + if (!this.mouseGrabbed && pressed) { + this.grabMouse(); // 下一次点击重新捕获 + } +} +``` + +`grabMouse()` 内部还会调用 `minecraft.gui.setScreen(null)`。 + +结论:**单纯 ungrab / releaseMouse 不能作为“打开 GUI”的实现**。 + +### 2.2 推荐方案:用一个只负责输入的 Screen + +Screen 会同时完成: + +- 释放鼠标捕获 +- `KeyMapping.releaseAll()`,WASD / 攻击 / 物品栏不再控制游戏 +- 把 `mouseMoved` / `mouseClicked` / `mouseScrolled` / `keyPressed` 路由给 GUI +- 关闭时自动重新捕获鼠标 + +因此推荐“HUD 继续负责绘制,Screen 只负责输入”的组合,而不是把 HUD 直接改造成 Screen。 + +#### 1.8.9 + +`GuiScreen` 是**抽象类**(1.8.8 / 1.8.9 都是),不能直接 `new`。实际实现是运行时用 Javassist 生成一个空的 concret 子类,再通过 `JuiceAgent#defineClass` 定义到游戏 ClassLoader: + +```text +GuiScreen(抽象) + └─ GeneratedInputScreen(运行时生成,public 无参构造 → super()) +``` + +生成后用 `MappingResolver` 解析出的 `displayGuiScreen` 打开: + +```java +Object screen = inputScreenClass.getDeclaredConstructor().newInstance(); +mcClass.getMethod(displayGuiScreenName, guiScreenClass).invoke(mc, screen); +``` + +`displayGuiScreen(screen)` 内部会 `setIngameNotInFocus()`;`displayGuiScreen(null)` 内部会 `setIngameFocus()`。 + +需要 Hook `GuiScreen` 接收输入,并且只处理自己的空壳实例: + +```text +GuiScreen#drawScreen(int mouseX, int mouseY, float partialTicks) // 每帧鼠标坐标 +GuiScreen#mouseClicked(int mouseX, int mouseY, int mouseButton) +GuiScreen#mouseReleased(int mouseX, int mouseY, int state) +GuiScreen#mouseClickMove(int mouseX, int mouseY, int button, long time) +GuiScreen#keyTyped(char typedChar, int keyCode) // ESC 默认关闭界面 +``` + +这里拿到的坐标已经是 GUI 缩放后的坐标,可以直接给 `Render2D` 使用。 + +两点注意: + +- 原版 `GuiScreen#drawScreen()` 默认只画 `buttonList` / `labelList`,空壳不会覆盖 HUD。 +- `GuiScreen#doesGuiPauseGame()` 默认返回 `true`,单人会暂停;`GuiInputHook` 会只对生成的空壳返回 `false`。 + +#### 26.2 + +`Screen` 是抽象类,实际实现是 `V26_2InputScreen`(输入状态记录在 `ClientInput`): + +```java +public final class V26_2InputScreen extends Screen { + + public V26_2InputScreen() { + super(Component.empty()); + } + + // 不要原版的模糊 / 菜单背景 + @Override + public void extractBackground(GuiGraphicsExtractor g, int mouseX, int mouseY, float a) { + } + + // 不想暂停世界就返回 false + @Override + public boolean isPauseScreen() { + return false; + } + + // GUI 仍由 HUD Hook 绘制,这里留空 + @Override + public void extractRenderState(GuiGraphicsExtractor g, int mouseX, int mouseY, float a) { + } + + @Override + public void mouseMoved(double x, double y) { + ClientInput.onMouseMove(x, y); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + ClientInput.onMouseButton(event.x(), event.y(), event.button(), true); + return true; + } + + @Override + public boolean mouseReleased(MouseButtonEvent event) { + ClientInput.onMouseButton(event.x(), event.y(), event.button(), false); + return true; + } + + @Override + public boolean mouseScrolled(double x, double y, double scrollX, double scrollY) { + ClientInput.onMouseMove(x, y); + return true; + } +} +``` + +ESC 不需要自己处理:`Screen#keyPressed` 默认会调用 `onClose()`,进而 `gui.setScreen(null)`,`ClientInput` 在下一个 tick 检测到界面关闭后自动重置状态。 + +打开 / 关闭(`V26_2Input` 内部): + +```java +minecraft.gui.setScreen(new V26_2InputScreen()); // releaseMouse + releaseAll + init +minecraft.gui.setScreen(null); // grabMouse +``` + +26.2 的 `mouseMoved(x, y)`、`MouseButtonEvent.x()/y()` 已经是 `MouseHandler#getScaledXPos()` 换算后的 GUI 坐标,不要再乘 `guiScale`。 + +绘制顺序方面,26.2 的 `Gui#extractRenderState` 会先提取 Screen,再走到 OrangeX 的 Hook 尾部,所以 HUD Hook 里的内容会盖在 Screen 之上;1.8.9 则是 HUD 先画、空壳 Screen 后画,只要空壳不画背景就不会遮挡。 + +#### 26.2 的编译依赖 + +`libraries/Minecraft26.2.jar` 是 Java 25 字节码(class version 69),而当前 Gradle 使用 JDK 17,不能直接作为 `compileOnly` 依赖。因此 OrangeX 增加了一个只参与编译的 stub 模块: + +```text +Minecraft262Stubs/ +└── src/main/java/ + ├── com/mojang/blaze3d/platform/{Window,InputConstants}.java + └── net/minecraft/ + ├── client/{Minecraft,MouseHandler}.java + ├── client/gui/{Gui,GuiGraphicsExtractor}.java + ├── client/gui/screens/Screen.java + ├── client/input/MouseButtonEvent.java + ├── client/multiplayer/ClientLevel.java + └── network/chat/{Component,MutableComponent}.java +``` + +`OrangeX/build.gradle` 使用 `compileOnly project(':Minecraft262Stubs')`。stub **不会打进 OrangeX.jar**,运行时仍然加载游戏提供的真正 26.2 类。stub 里的字段类型必须和真实类一致,否则会生成错误的字段描述符(例如 `Minecraft#level` 必须是 `ClientLevel` 而不是 `Object`)。 + +### 2.3 当前实现 + +```text +OrangeX/src/main/java/cn/xiaozhou233/orangex/ +├── input/ +│ ├── ClientInput.java 跨版本输入状态:开/关、鼠标坐标、按键状态 +│ ├── InputController.java 在 EventTickPre 中驱动 ClientInput +│ ├── internal/ +│ │ ├── VersionInput.java 版本输入接口 +│ │ └── v1_8_9/V1_8_9Input.java 1.8.9:运行时生成 GuiScreen 子类 + LWJGL 2 +│ └── v26_2/ +│ ├── V26_2Input.java 26.2:gui.setScreen + InputConstants +│ └── V26_2InputScreen.java 26.2 空 Screen +├── event/facade/InputEvents.java 1.8.9 注入代码的门面 +└── hook/impl/ + ├── GuiInputHook.java 1.8.9 GuiScreen 输入 / 关闭 Hook + └── KeyPressHook.java 1.8.9 KeyBinding.onTick 打开 Hook +``` + +行为: + +- M 键在**世界内**打开空 GUI;再次按下关闭。 +- 1.8.9 的开关走事件而不是 tick 轮询: + - 打开:`KeyBinding#onTick(int)` → `InputEvents.onKeyPressed` → `ClientInput.requestOpen()` + - 关闭:`GuiScreen#keyTyped(char, int)` → `InputEvents.onKeyTyped` → `ClientInput.requestClose()` + - 两者都只在 tick 末尾(`EventTickPost` → `ClientInput.applyPending`)真正执行。 + - 原因:如果在键盘循环里直接打开 Screen,同一个 M 事件会立刻被 `currentScreen.handleKeyboardInput()` 再处理一次,导致刚打开就关闭。 + - 自动重复事件通过 `V1_8_9Input.isRepeatEvent()` 过滤,按住 M 不会反复开关。 +- 26.2 仍然每 tick 用 `InputConstants.isKeyDown(window, 77)` 轮询 M。 +- 打开时: + - 1.8.9:运行时生成 `GuiScreen` 具体子类,再 `Minecraft#displayGuiScreen(...)`;`doesGuiPauseGame()` 对自己的空壳返回 `false`。 + - 26.2:`Gui#setScreen(new V26_2InputScreen())`,`isPauseScreen()` 返回 `false`。 +- 打开后鼠标由系统光标接管,`GuiScreen#drawScreen` / `Screen#mouseMoved` 持续把 GUI 坐标写入 `ClientInput`。 +- `ClientInput` 可供 `EventRender2D` 读取: + +```java +if (ClientInput.isOpen()) { + double x = ClientInput.getMouseX(); + double y = ClientInput.getMouseY(); + boolean left = ClientInput.isLeftDown(); +} +``` + +`FontDebugOverlay` 现在会显示 `Input: OPEN/closed` 和鼠标坐标,并在 GUI 打开时画一个红色十字光标。 + +### 2.4 备选方案:不经过 Screen 的 Overlay + +如果完全不想引入 Screen,也可以参考 Vape 的纯 Overlay 思路,但需要自己补齐所有输入拦截: + +26.2: + +```text +mouseHandler.releaseMouse() +Hook MouseHandler#grabMouse() GUI 打开时直接 return +Hook MouseHandler#onButton(...) GUI 打开时转发点击并 return +Hook MouseHandler#onScroll(...) GUI 打开时转发滚轮并 return +Hook KeyboardHandler#keyPress(...) GUI 打开时转发键盘并 return +``` + +鼠标坐标: + +```java +double x = mouseHandler.getScaledXPos(minecraft.getWindow()); +double y = mouseHandler.getScaledYPos(minecraft.getWindow()); +``` + +1.8.9: + +```text +mc.setIngameNotInFocus() +Hook Minecraft#setIngameFocus() GUI 打开时直接 return +处理 runTick() 中 currentScreen == null 的鼠标按键 / KeyBinding 路径 +``` + +鼠标坐标: + +```java +int x = Mouse.getX() * scaledWidth / mc.displayWidth; +int y = scaledHeight - Mouse.getY() * scaledHeight / mc.displayHeight - 1; +``` + +这条路的优点是绕开 Screen API;缺点是键盘、点击、滚轮的拦截全部要自己维护,ClickGUI 场景下不如 Screen 方案稳。 + +--- + +## 3. 常见坑 + +| 现象 | 原因 | +| --- | --- | +| 26.2 主界面也绘制 HUD | `Gui#extractRenderState` 每帧执行,需要看 `shouldRenderLevel` | +| 注入后 `shouldRenderLevel` 取错 | Javassist `$0` 是 `this`,第二个参数是 `$2` | +| 放开鼠标后点一下又转视角 | 1.8.9 `runTick` 会 `setIngameFocus`;26.2 `onButton` 会 `grabMouse` | +| 26.2 `grabMouse` 把界面关掉 | `MouseHandler#grabMouse` 内部会 `gui.setScreen(null)` | +| 点击坐标偏移 | Screen 回调坐标已经过 GUI Scale,不要再乘一次 | +| 1.8.9 注入报 `no such class: cn$...` | 注入代码写了全限定 `cn.*`,应使用简单类名 + `getInjectedClassNames()` | +| 空 GUI 打开后玩家还能动 | 1.8.9 / 26.2 都必须真正打开 Screen;只 ungrab 不够 | +| 1.8.9 空 GUI 导致单人暂停 | 已 Hook `GuiScreen#doesGuiPauseGame`,对自己的空壳返回 false | +| 1.8.9 短按 M 没反应 | 已改为 `KeyBinding#onTick` 事件路径;可用 `-Dorangex.debugInput=true` 查看按键日志 | +| 聊天 / 背包界面里按 M 被劫持 | 打开前检查 `isScreenOpen()`,任何原版 Screen 存在时都不响应 | + +--- + +## 4. 相关文件 + +```text +OrangeX/src/main/java/cn/xiaozhou233/orangex/ +├── hook/ +│ ├── HookManager.java +│ └── impl/ +│ ├── TickHook.java +│ ├── Render2DHook.java +│ ├── GuiInputHook.java +│ └── KeyPressHook.java +├── input/ +│ ├── ClientInput.java +│ ├── InputController.java +│ ├── internal/ +│ │ ├── VersionInput.java +│ │ └── v1_8_9/V1_8_9Input.java +│ └── v26_2/ +│ ├── V26_2Input.java +│ └── V26_2InputScreen.java +├── event/ +│ ├── facade/ +│ │ ├── TickEvents.java +│ │ ├── Render2DEvents.java +│ │ └── InputEvents.java +│ └── impl/ +│ ├── EventTickPre.java +│ ├── EventTickPost.java +│ └── EventRender2D.java +├── render/ +│ ├── Render2DManager.java +│ └── FontDebugOverlay.java +└── wrapper/ + ├── api/Minecraft.java + └── internal/ + ├── v1_8_9/V1_8_9Minecraft.java + └── v26_2/V26_2Minecraft.java + +Minecraft262Stubs/src/main/java/ 26.2 compileOnly stubs(不打包) +``` diff --git a/libraries/.gitignore b/libraries/.gitignore new file mode 100644 index 0000000..f11855f --- /dev/null +++ b/libraries/.gitignore @@ -0,0 +1 @@ +Minecraft26.2.jar diff --git a/libraries/Minecraft26.2.jar.download.url.txt b/libraries/Minecraft26.2.jar.download.url.txt new file mode 100644 index 0000000..4465112 --- /dev/null +++ b/libraries/Minecraft26.2.jar.download.url.txt @@ -0,0 +1 @@ +https://piston-data.mojang.com/v1/objects/2dc72797acbc1b63fc16a11c4ac393605f453754/client.jar \ No newline at end of file diff --git a/libraries/lwjgl-2.9.4-nightly-20150209.jar b/libraries/lwjgl-2.9.4-nightly-20150209.jar new file mode 100644 index 0000000..b576428 Binary files /dev/null and b/libraries/lwjgl-2.9.4-nightly-20150209.jar differ diff --git a/settings.gradle b/settings.gradle index 863ddd6..a6e1f33 100644 --- a/settings.gradle +++ b/settings.gradle @@ -3,3 +3,4 @@ include 'Loader' include 'OrangeX' include 'Injector' include 'Minecraft1.8.8' +include 'Minecraft262Stubs'