mirror of
https://github.com/xiaozhou233/OrangeX-Client.git
synced 2026-12-05 13:05:52 +08:00
Compare commits
7
Commits
40ca99f853
...
715cb0755f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
715cb0755f | ||
|
|
b9ac9d5a92 | ||
|
|
b909a01fe0 | ||
|
|
867949967e | ||
|
|
c8fa1a4c64 | ||
|
|
c3dab97779 | ||
|
|
6c19985e52 |
No files matched your search
@@ -49,6 +49,9 @@ public class Loader {
|
|||||||
orangexFile = new File(OrangeXPath + "/OrangeX.jar");
|
orangexFile = new File(OrangeXPath + "/OrangeX.jar");
|
||||||
}
|
}
|
||||||
System.out.println("OrangeX Injection: " + orangexFile.getAbsolutePath());
|
System.out.println("OrangeX Injection: " + orangexFile.getAbsolutePath());
|
||||||
|
// javassist's ClassPool cannot always discover this jar through the
|
||||||
|
// game ClassLoader, so expose the path to OrangeX explicitly.
|
||||||
|
System.setProperty("orangex.jar", orangexFile.getAbsolutePath());
|
||||||
addToGameClassLoader(orangexFile, minecraftClassLoader);
|
addToGameClassLoader(orangexFile, minecraftClassLoader);
|
||||||
|
|
||||||
// Start OrangeX
|
// Start OrangeX
|
||||||
|
|||||||
@@ -17,6 +17,21 @@ dependencies {
|
|||||||
|
|
||||||
// Source: https://mvnrepository.com/artifact/com.google.code.gson/gson
|
// Source: https://mvnrepository.com/artifact/com.google.code.gson/gson
|
||||||
implementation 'com.google.code.gson:gson:2.15.0'
|
implementation 'com.google.code.gson:gson:2.15.0'
|
||||||
|
|
||||||
|
// Source: https://mvnrepository.com/artifact/org.javassist/javassist
|
||||||
|
implementation 'org.javassist:javassist:3.33.0-GA'
|
||||||
|
|
||||||
|
// Source: https://mvnrepository.com/artifact/org.greenrobot/eventbus
|
||||||
|
implementation 'org.greenrobot:eventbus:3.2.0'
|
||||||
|
|
||||||
|
// Legacy OpenGL entry points for the 1.8.9 font backend. This is compile
|
||||||
|
// only: the 1.8.9 runtime provides its own LWJGL 2, and the 26.2 backend
|
||||||
|
// never loads these classes.
|
||||||
|
compileOnly files('../Minecraft1.8.8/runtime/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar')
|
||||||
|
|
||||||
|
// JuiceAgent is provided at runtime by the agent (see JuiceAgentBridge).
|
||||||
|
// Do NOT bundle it: Fabric's KnotClassLoader would load a second copy of
|
||||||
|
// the API whose native methods are not registered.
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('shadowJar') {
|
tasks.named('shadowJar') {
|
||||||
@@ -26,4 +41,9 @@ tasks.named('shadowJar') {
|
|||||||
|
|
||||||
shadowJar {
|
shadowJar {
|
||||||
relocate 'com.google.gson', 'cn.xiaozhou233.orangex.shaded.gson'
|
relocate 'com.google.gson', 'cn.xiaozhou233.orangex.shaded.gson'
|
||||||
|
// Javassist must live in OrangeX's own namespace: Forge's
|
||||||
|
// LaunchClassLoader delegates the "javassist." package to its parent,
|
||||||
|
// which cannot see the injected jar.
|
||||||
|
relocate 'javassist', 'cn.xiaozhou233.orangex.shaded.javassist'
|
||||||
|
relocate 'org.greenrobot.eventbus', 'cn.xiaozhou233.orangex.shaded.eventbus'
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,32 @@
|
|||||||
package cn.xiaozhou233.orangex;
|
package cn.xiaozhou233.orangex;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
|
||||||
|
import cn.xiaozhou233.orangex.hook.HookManager;
|
||||||
import cn.xiaozhou233.orangex.mapping.MappingManager;
|
import cn.xiaozhou233.orangex.mapping.MappingManager;
|
||||||
|
import cn.xiaozhou233.orangex.render.FontDebugOverlay;
|
||||||
|
import cn.xiaozhou233.orangex.render.Render2DManager;
|
||||||
import cn.xiaozhou233.orangex.runtime.RuntimeDetector;
|
import cn.xiaozhou233.orangex.runtime.RuntimeDetector;
|
||||||
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
|
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
|
||||||
import cn.xiaozhou233.orangex.wrapper.MinecraftFactory;
|
import cn.xiaozhou233.orangex.wrapper.MinecraftFactory;
|
||||||
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
|
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
import org.greenrobot.eventbus.EventBus;
|
||||||
|
import org.greenrobot.eventbus.Subscribe;
|
||||||
|
|
||||||
public class OrangeX {
|
public class OrangeX {
|
||||||
@Getter
|
@Getter
|
||||||
private static final OrangeX instance = new OrangeX();
|
private static final OrangeX instance = new OrangeX();
|
||||||
|
@Getter
|
||||||
|
private final EventBus eventBus = EventBus.builder()
|
||||||
|
.logNoSubscriberMessages(false)
|
||||||
|
.logSubscriberExceptions(false)
|
||||||
|
.sendNoSubscriberEvent(false)
|
||||||
|
.sendSubscriberExceptionEvent(false)
|
||||||
|
.build();
|
||||||
@Getter
|
@Getter
|
||||||
private RuntimeInfo runtimeInfo;
|
private RuntimeInfo runtimeInfo;
|
||||||
|
@Getter
|
||||||
|
private Render2DManager render2DManager;
|
||||||
|
|
||||||
public OrangeX() {
|
public OrangeX() {
|
||||||
System.out.println("OrangeX <init> start!");
|
System.out.println("OrangeX <init> start!");
|
||||||
@@ -28,6 +42,16 @@ public class OrangeX {
|
|||||||
|
|
||||||
Minecraft minecraft = MinecraftFactory.create(runtimeInfo, MappingManager.getResolver());
|
Minecraft minecraft = MinecraftFactory.create(runtimeInfo, MappingManager.getResolver());
|
||||||
System.out.println(minecraft.getMinecraft());
|
System.out.println(minecraft.getMinecraft());
|
||||||
|
|
||||||
|
render2DManager = new Render2DManager(
|
||||||
|
runtimeInfo, MappingManager.getResolver(), minecraft.getMinecraft());
|
||||||
|
System.out.println("[OrangeX] Font backend: " + render2DManager.getBackendName());
|
||||||
|
|
||||||
|
if (Boolean.getBoolean("orangex.debugFont")) {
|
||||||
|
eventBus.register(new FontDebugOverlay());
|
||||||
|
}
|
||||||
|
|
||||||
|
HookManager.getINSTANCE().applyAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package cn.xiaozhou233.orangex.event;
|
||||||
|
|
||||||
|
public interface Event {
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package cn.xiaozhou233.orangex.event.facade;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.OrangeX;
|
||||||
|
import cn.xiaozhou233.orangex.render.Render2DManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entry point used by injected code. Always refer to this class by its simple
|
||||||
|
* name inside Javassist snippets (see docs/hooks.md).
|
||||||
|
*/
|
||||||
|
public final class Render2DEvents {
|
||||||
|
|
||||||
|
private static boolean failureLogged;
|
||||||
|
|
||||||
|
public static void fire(Object platformContext) {
|
||||||
|
try {
|
||||||
|
Render2DManager manager = OrangeX.getInstance().getRender2DManager();
|
||||||
|
if (manager != null) {
|
||||||
|
manager.fire(platformContext);
|
||||||
|
}
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
if (!failureLogged) {
|
||||||
|
failureLogged = true;
|
||||||
|
System.err.println("[OrangeX] Render2D callback failed");
|
||||||
|
throwable.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Render2DEvents() {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package cn.xiaozhou233.orangex.event.facade;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.OrangeX;
|
||||||
|
import cn.xiaozhou233.orangex.event.impl.EventTickPost;
|
||||||
|
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
|
||||||
|
import org.greenrobot.eventbus.EventBus;
|
||||||
|
|
||||||
|
public class TickEvents {
|
||||||
|
private static final EventBus BUS = OrangeX.getInstance().getEventBus();
|
||||||
|
|
||||||
|
public static void firePre() {
|
||||||
|
BUS.post(new EventTickPre());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void firePost() {
|
||||||
|
BUS.post(new EventTickPost());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package cn.xiaozhou233.orangex.event.impl;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fired once per frame while the game collects its GUI. Listeners can queue
|
||||||
|
* text through {@link #getRender2D()}.
|
||||||
|
*/
|
||||||
|
public class EventRender2D {
|
||||||
|
|
||||||
|
private final Render2D render2D;
|
||||||
|
|
||||||
|
public EventRender2D(Render2D render2D) {
|
||||||
|
this.render2D = render2D;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Render2D getRender2D() {
|
||||||
|
return render2D;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package cn.xiaozhou233.orangex.event.impl;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.event.Event;
|
||||||
|
|
||||||
|
public class EventTickPost implements Event {
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package cn.xiaozhou233.orangex.event.impl;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.event.Event;
|
||||||
|
|
||||||
|
public class EventTickPre implements Event {
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import javassist.ClassPool;
|
||||||
|
import javassist.CtClass;
|
||||||
|
import javassist.LoaderClassPath;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
|
||||||
|
public abstract class ClassHook {
|
||||||
|
|
||||||
|
protected abstract String getTargetClass();
|
||||||
|
|
||||||
|
protected abstract void transform(CtClass ctClass) throws Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fully qualified names of classes referenced by the injected code.
|
||||||
|
* Their packages are imported so the injected source can use simple names.
|
||||||
|
*/
|
||||||
|
protected String[] getInjectedClassNames() {
|
||||||
|
return new String[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
public final byte[] transform(ClassLoader loader, byte[] classBytes)
|
||||||
|
throws Exception {
|
||||||
|
|
||||||
|
ClassPool pool = ClassPool.getDefault();
|
||||||
|
pool.appendClassPath(new LoaderClassPath(loader));
|
||||||
|
ClassPoolUtils.prepare(pool, getInjectedClassNames());
|
||||||
|
|
||||||
|
CtClass ctClass = pool.makeClass(
|
||||||
|
new ByteArrayInputStream(classBytes),
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
transform(ctClass);
|
||||||
|
return ctClass.toBytecode();
|
||||||
|
} finally {
|
||||||
|
ctClass.detach();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import javassist.ClassClassPath;
|
||||||
|
import javassist.ClassPool;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Javassist setup shared by all hooks.
|
||||||
|
*/
|
||||||
|
public final class ClassPoolUtils {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set by the Loader before OrangeX loads: the jar that was injected into
|
||||||
|
* the game class loader.
|
||||||
|
*/
|
||||||
|
private static final String ORANGEX_JAR_PROPERTY = "orangex.jar";
|
||||||
|
|
||||||
|
private static final Set<String> importedPackages = new HashSet<String>();
|
||||||
|
|
||||||
|
private static boolean classPathAdded;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepares {@code pool} for compiling injected code.
|
||||||
|
*
|
||||||
|
* <p>Solves two problems:</p>
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>{@link ClassPool#getDefault()} only knows the JVM class path. The
|
||||||
|
* OrangeX jar is injected into the game class loader at runtime, so it
|
||||||
|
* must be added explicitly, otherwise javassist cannot find OrangeX
|
||||||
|
* classes.</li>
|
||||||
|
* <li>Vanilla 1.8.8 contains an obfuscated class in the default package
|
||||||
|
* named {@code cn}, which collides with the first segment of our
|
||||||
|
* package. Javassist resolves qualified names from left to right, finds
|
||||||
|
* that class instead of the package, and fails with the misleading
|
||||||
|
* {@code no such class: cn$xiaozhou233...}. Importing the packages lets
|
||||||
|
* injected code use simple class names and avoids the collision.</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* @param classNames fully qualified names of the classes referenced by the
|
||||||
|
* injected code; their packages are imported
|
||||||
|
*/
|
||||||
|
public static synchronized void prepare(ClassPool pool, String... classNames) {
|
||||||
|
importPackages(pool, classNames);
|
||||||
|
|
||||||
|
if (classPathAdded) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
classPathAdded = true;
|
||||||
|
|
||||||
|
File jar = orangeXJar();
|
||||||
|
if (jar == null) {
|
||||||
|
System.out.println("[OrangeX] WARNING: OrangeX.jar not found for javassist; "
|
||||||
|
+ "injected classes may fail to compile");
|
||||||
|
pool.insertClassPath(new ClassClassPath(ClassPoolUtils.class));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
pool.insertClassPath(jar.getAbsolutePath());
|
||||||
|
System.out.println("[OrangeX] javassist classpath: " + jar.getAbsolutePath());
|
||||||
|
} catch (Throwable t) {
|
||||||
|
System.out.println("[OrangeX] Failed to add javassist classpath: "
|
||||||
|
+ jar.getAbsolutePath() + " (" + t + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void importPackages(ClassPool pool, String[] classNames) {
|
||||||
|
for (String className : classNames) {
|
||||||
|
int dot = className.lastIndexOf('.');
|
||||||
|
if (dot <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String packageName = className.substring(0, dot);
|
||||||
|
if (importedPackages.add(packageName)) {
|
||||||
|
pool.importPackage(packageName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static File orangeXJar() {
|
||||||
|
String path = System.getProperty(ORANGEX_JAR_PROPERTY);
|
||||||
|
if (path == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
File jar = new File(path);
|
||||||
|
return jar.isFile() ? jar : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClassPoolUtils() {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.OrangeX;
|
||||||
|
import cn.xiaozhou233.orangex.hook.impl.*;
|
||||||
|
import lombok.Getter;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class HookManager {
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
private static final HookManager INSTANCE = new HookManager();
|
||||||
|
|
||||||
|
private final List<ClassHook> hooks = new ArrayList<ClassHook>();
|
||||||
|
|
||||||
|
private HookManager() {
|
||||||
|
register(new TickHook());
|
||||||
|
register(new Render2DHook());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void register(ClassHook hook) {
|
||||||
|
hooks.add(hook);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void applyAll() {
|
||||||
|
ClassLoader loader = OrangeX.getInstance().getRuntimeInfo().getMinecraftClassLoader();
|
||||||
|
|
||||||
|
for (ClassHook hook : hooks) {
|
||||||
|
String className = hook.getTargetClass();
|
||||||
|
if (className == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
byte[] classBytes = JuiceAgentBridge.getClassBytesByName(
|
||||||
|
className.replace(".", "/"));
|
||||||
|
if (classBytes == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] bytes = hook.transform(loader, classBytes);
|
||||||
|
JuiceAgentBridge.retransformClassByName(className, bytes);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
System.err.println("[OrangeX] Failed to apply hook: " + className);
|
||||||
|
t.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reflective access to the JuiceAgent API.
|
||||||
|
*
|
||||||
|
* <p>The agent registers its native methods on the API class loaded by the
|
||||||
|
* system class loader. On Fabric, OrangeX itself is loaded by Knot, so a
|
||||||
|
* direct reference could resolve to a second copy of {@code JuiceAgent} that
|
||||||
|
* has no native implementation and throws {@link UnsatisfiedLinkError}.
|
||||||
|
* Looking the class up through the system class loader always reaches the
|
||||||
|
* registered copy.</p>
|
||||||
|
*/
|
||||||
|
final class JuiceAgentBridge {
|
||||||
|
|
||||||
|
private static final String API_CLASS = "cn.xiaozhou233.juiceagent.api.JuiceAgent";
|
||||||
|
|
||||||
|
private static Method getClassBytesByName;
|
||||||
|
private static Method retransformClassByName;
|
||||||
|
|
||||||
|
static byte[] getClassBytesByName(String className) {
|
||||||
|
init();
|
||||||
|
|
||||||
|
try {
|
||||||
|
return (byte[]) getClassBytesByName.invoke(null, className);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"JuiceAgent.getClassBytesByName failed: " + className, t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void retransformClassByName(String className, byte[] bytes) {
|
||||||
|
init();
|
||||||
|
|
||||||
|
try {
|
||||||
|
retransformClassByName.invoke(null, className, bytes, bytes.length);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"JuiceAgent.retransformClassByName failed: " + className, t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static synchronized void init() {
|
||||||
|
if (getClassBytesByName != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Class<?> api = Class.forName(API_CLASS, true, ClassLoader.getSystemClassLoader());
|
||||||
|
getClassBytesByName = api.getMethod("getClassBytesByName", String.class);
|
||||||
|
retransformClassByName = api.getMethod(
|
||||||
|
"retransformClassByName", String.class, byte[].class, int.class);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
throw new IllegalStateException("JuiceAgent API is not available", t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private JuiceAgentBridge() {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
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.loader.LoaderType;
|
||||||
|
import javassist.CtClass;
|
||||||
|
import javassist.CtMethod;
|
||||||
|
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fires {@link cn.xiaozhou233.orangex.event.impl.EventRender2D} once per frame.
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>1.8.9: tail of {@code GuiIngame#renderGameOverlay(float)}.</li>
|
||||||
|
* <li>26.2: tail of {@code Gui#extractRenderState(DeltaTracker, boolean,
|
||||||
|
* boolean)}. The {@code Gui} instance is passed to the facade so the
|
||||||
|
* font backend can reach its {@code GuiRenderState}.</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public final class Render2DHook extends ClassHook {
|
||||||
|
|
||||||
|
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.Render2DEvents"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getTargetClass() {
|
||||||
|
switch (runtimeInfo.getMinecraftVersion()) {
|
||||||
|
case V1_8_9:
|
||||||
|
if (runtimeInfo.getLoaderType() == LoaderType.FORGE
|
||||||
|
&& classPresent("net.minecraftforge.client.GuiIngameForge")) {
|
||||||
|
// Forge replaces the HUD renderer with its own subclass.
|
||||||
|
return "net.minecraftforge.client.GuiIngameForge";
|
||||||
|
}
|
||||||
|
return resolver.mapClass("net/minecraft/client/gui/GuiIngame")
|
||||||
|
.getTargetName().replace("/", ".");
|
||||||
|
case V26_2:
|
||||||
|
return "net.minecraft.client.gui.Gui";
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean classPresent(String className) {
|
||||||
|
try {
|
||||||
|
Class.forName(className, false, Render2DHook.class.getClassLoader());
|
||||||
|
return true;
|
||||||
|
} catch (Throwable ignored) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the HUD entry point in a Forge class whose member names depend on
|
||||||
|
* the remapping stage (Notch {@code a}, SRG {@code func_175180_a}, MCP
|
||||||
|
* {@code renderGameOverlay}).
|
||||||
|
*/
|
||||||
|
private static CtMethod findFloatOverlayMethod(CtClass ctClass) {
|
||||||
|
CtMethod fallback = null;
|
||||||
|
for (CtMethod method : ctClass.getDeclaredMethods()) {
|
||||||
|
if (!"(F)V".equals(method.getSignature())
|
||||||
|
|| Modifier.isStatic(method.getModifiers())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String name = method.getName();
|
||||||
|
if ("renderGameOverlay".equals(name)
|
||||||
|
|| "func_175180_a".equals(name)
|
||||||
|
|| "a".equals(name)) {
|
||||||
|
return method;
|
||||||
|
}
|
||||||
|
if (fallback == null) {
|
||||||
|
fallback = method;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void transform(CtClass ctClass) throws Exception {
|
||||||
|
switch (runtimeInfo.getMinecraftVersion()) {
|
||||||
|
case V1_8_9: {
|
||||||
|
String methodName;
|
||||||
|
String methodDescriptor;
|
||||||
|
if (runtimeInfo.getLoaderType() == LoaderType.FORGE
|
||||||
|
&& classPresent("net.minecraftforge.client.GuiIngameForge")) {
|
||||||
|
// Forge's GuiIngameForge is remapped to SRG names at
|
||||||
|
// runtime (func_175180_a), but the universal jar contains
|
||||||
|
// the Notch name (a). Locate the override by its descriptor
|
||||||
|
// instead of hardcoding any of them.
|
||||||
|
CtMethod method = findFloatOverlayMethod(ctClass);
|
||||||
|
if (method == null) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"No (F)V HUD method found in " + ctClass.getName());
|
||||||
|
}
|
||||||
|
method.insertAfter("Render2DEvents.fire(null);");
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
MappingMethod target = resolver.mapMethod(
|
||||||
|
"net/minecraft/client/gui/GuiIngame",
|
||||||
|
"renderGameOverlay",
|
||||||
|
"(F)V");
|
||||||
|
methodName = target.getTargetName();
|
||||||
|
methodDescriptor = target.getTargetDescriptor();
|
||||||
|
}
|
||||||
|
CtMethod method = ctClass.getMethod(methodName, methodDescriptor);
|
||||||
|
method.insertAfter("Render2DEvents.fire(null);");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case V26_2: {
|
||||||
|
MappingMethod target = resolver.mapMethod(
|
||||||
|
"net/minecraft/client/gui/Gui",
|
||||||
|
"extractRenderState",
|
||||||
|
"(Lnet/minecraft/client/DeltaTracker;ZZ)V");
|
||||||
|
CtMethod method = ctClass.getMethod(
|
||||||
|
target.getTargetName(), target.getTargetDescriptor());
|
||||||
|
method.insertAfter("Render2DEvents.fire($0);");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
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 javassist.CtClass;
|
||||||
|
import javassist.CtMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fires {@code EventTickPre}/{@code EventTickPost} around
|
||||||
|
* {@code Minecraft#runTick}. The descriptor differs per version.
|
||||||
|
*/
|
||||||
|
public final class TickHook extends ClassHook {
|
||||||
|
|
||||||
|
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.TickEvents"};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected String getTargetClass() {
|
||||||
|
switch (runtimeInfo.getMinecraftVersion()) {
|
||||||
|
case V1_8_9:
|
||||||
|
return resolver.mapClass("net/minecraft/client/Minecraft").getTargetName().replace("/", ".");
|
||||||
|
case V26_2:
|
||||||
|
return "net.minecraft.client.Minecraft";
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void transform(CtClass ctClass) throws Exception {
|
||||||
|
String methodName = null;
|
||||||
|
String methodDesc = null;
|
||||||
|
|
||||||
|
switch (runtimeInfo.getMinecraftVersion()) {
|
||||||
|
case V1_8_9: {
|
||||||
|
MappingMethod runTick = resolver.mapMethod(
|
||||||
|
"net/minecraft/client/Minecraft", "runTick", "()V");
|
||||||
|
methodName = runTick.getTargetName();
|
||||||
|
methodDesc = runTick.getTargetDescriptor();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// 26.2 is not obfuscated: runTick(Z)V, private.
|
||||||
|
case V26_2: {
|
||||||
|
MappingMethod runTick = resolver.mapMethod(
|
||||||
|
"net/minecraft/client/Minecraft", "runTick", "(Z)V");
|
||||||
|
methodName = runTick.getTargetName();
|
||||||
|
methodDesc = runTick.getTargetDescriptor();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (methodName == null || methodDesc == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
CtMethod method = ctClass.getMethod(methodName, methodDesc);
|
||||||
|
|
||||||
|
// Simple names: the package is imported by ClassPoolUtils.
|
||||||
|
// Fully qualified "cn.*" names collide with the vanilla "cn" class.
|
||||||
|
method.insertBefore("TickEvents.firePre();");
|
||||||
|
method.insertAfter("TickEvents.firePost();");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
import org.greenrobot.eventbus.Subscribe;
|
||||||
|
import org.greenrobot.eventbus.ThreadMode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optional debug overlay. Enable with {@code -Dorangex.debugFont=true}.
|
||||||
|
*/
|
||||||
|
public final class FontDebugOverlay {
|
||||||
|
|
||||||
|
@Subscribe(threadMode = ThreadMode.POSTING)
|
||||||
|
public void onRender2D(EventRender2D event) {
|
||||||
|
Render2D render2D = event.getRender2D();
|
||||||
|
|
||||||
|
render2D.fillRoundedRect(4, 4, 250, 120, 8,
|
||||||
|
1.0, 0xD0141414, 0xFF303030);
|
||||||
|
render2D.fillGradient(10, 112, 238, 6,
|
||||||
|
0xFF55FFFF, 0xFF55FF55);
|
||||||
|
render2D.drawLine(10, 124, 248, 124, 1.0, 0x80FFFFFF);
|
||||||
|
|
||||||
|
FontRenderer title = render2D.getFont(14.0f, true);
|
||||||
|
FontRenderer body = render2D.getFont(10.0f, false);
|
||||||
|
|
||||||
|
title.drawStringWithShadow("OrangeX", 8, 8, 0xFFFFFFFF);
|
||||||
|
body.drawString("Font backend: " + render2D.getClass().getSimpleName(),
|
||||||
|
8, 26, 0xFF55FFFF);
|
||||||
|
body.drawString("ASCII 0123456789", 8, 40, 0xFFAAAAAA);
|
||||||
|
body.drawString("中文测试:钻石剑 / 迅捷", 8, 54, 0xFFFFAA00);
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.OrangeX;
|
||||||
|
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingResolver;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontManager;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontBackend;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontBackendFactory;
|
||||||
|
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
|
||||||
|
import org.greenrobot.eventbus.EventBus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Owns the font cache and turns one platform render callback into an
|
||||||
|
* {@link EventRender2D}.
|
||||||
|
*/
|
||||||
|
public final class Render2DManager {
|
||||||
|
|
||||||
|
private final FontBackend backend;
|
||||||
|
private final FontManager fonts;
|
||||||
|
|
||||||
|
public Render2DManager(RuntimeInfo runtimeInfo,
|
||||||
|
MappingResolver mappingResolver,
|
||||||
|
Object minecraft) {
|
||||||
|
this.backend = FontBackendFactory.create(
|
||||||
|
runtimeInfo, mappingResolver, minecraft);
|
||||||
|
this.fonts = new FontManager(backend);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void fire(Object platformContext) {
|
||||||
|
EventBus eventBus = OrangeX.getInstance().getEventBus();
|
||||||
|
if (!eventBus.hasSubscriberForEvent(EventRender2D.class)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Render2D context = backend.createRender2D(fonts, platformContext);
|
||||||
|
try {
|
||||||
|
eventBus.post(new EventRender2D(context));
|
||||||
|
} finally {
|
||||||
|
context.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBackendName() {
|
||||||
|
return backend.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
public FontManager getFonts() {
|
||||||
|
return fonts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.api;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A font face bound to the current 2D render pass.
|
||||||
|
*
|
||||||
|
* <p>Instances are created by {@link Render2D#getFont(float)} and must only be
|
||||||
|
* used during the frame that produced the {@code Render2D} instance.</p>
|
||||||
|
*/
|
||||||
|
public interface FontRenderer {
|
||||||
|
|
||||||
|
void drawString(String text, double x, double y, int argb);
|
||||||
|
|
||||||
|
void drawStringWithShadow(String text, double x, double y, int argb);
|
||||||
|
|
||||||
|
void drawCenteredString(String text, double centerX, double y, int argb);
|
||||||
|
|
||||||
|
void drawCenteredStringWithShadow(String text, double centerX, double y, int argb);
|
||||||
|
|
||||||
|
double getStringWidth(String text);
|
||||||
|
|
||||||
|
double getStringHeight();
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.api;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The 2D drawing context for one frame.
|
||||||
|
*
|
||||||
|
* <p>Feature code receives this object through
|
||||||
|
* {@code cn.xiaozhou233.orangex.event.impl.EventRender2D}. Coordinates and
|
||||||
|
* sizes are expressed in Minecraft GUI pixels (the same space used by the
|
||||||
|
* vanilla HUD after {@code ScaledResolution}).</p>
|
||||||
|
*/
|
||||||
|
public interface Render2D {
|
||||||
|
|
||||||
|
int getWidth();
|
||||||
|
|
||||||
|
int getHeight();
|
||||||
|
|
||||||
|
double getGuiScale();
|
||||||
|
|
||||||
|
FontRenderer getFont(float size);
|
||||||
|
|
||||||
|
FontRenderer getFont(float size, boolean bold);
|
||||||
|
|
||||||
|
void fillRect(double x, double y, double width, double height, int argb);
|
||||||
|
|
||||||
|
void fillGradient(double x, double y, double width, double height,
|
||||||
|
int topArgb, int bottomArgb);
|
||||||
|
|
||||||
|
void drawRect(double x, double y, double width, double height,
|
||||||
|
double thickness, int argb);
|
||||||
|
|
||||||
|
void fillRoundedRect(double x, double y, double width, double height,
|
||||||
|
double radius, int argb);
|
||||||
|
|
||||||
|
void fillRoundedRect(double x, double y, double width, double height,
|
||||||
|
double radius, double borderWidth,
|
||||||
|
int argb, int borderArgb);
|
||||||
|
|
||||||
|
void drawLine(double x1, double y1, double x2, double y2,
|
||||||
|
double thickness, int argb);
|
||||||
|
|
||||||
|
void enableScissor(double x, double y, double width, double height);
|
||||||
|
|
||||||
|
void disableScissor();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Framework-internal: restores any state the backend changed for this
|
||||||
|
* frame. Feature code should not call it.
|
||||||
|
*/
|
||||||
|
void flush();
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A baked font atlas.
|
||||||
|
*
|
||||||
|
* <p>{@link #getPixels()} contains one 8-bit coverage value per texel. The
|
||||||
|
* backends decide how to upload that data (alpha-only on legacy OpenGL, RGBA
|
||||||
|
* on modern Minecraft).</p>
|
||||||
|
*/
|
||||||
|
public final class FontAtlas {
|
||||||
|
|
||||||
|
private final int width;
|
||||||
|
private final int height;
|
||||||
|
private byte[] pixels;
|
||||||
|
private final Map<Integer, Glyph> glyphs;
|
||||||
|
|
||||||
|
/** Distance from the top of a line to the baseline, in atlas pixels. */
|
||||||
|
private final float ascent;
|
||||||
|
/** Recommended line height, in atlas pixels. */
|
||||||
|
private final float lineHeight;
|
||||||
|
|
||||||
|
private final Glyph[] ascii = new Glyph[128];
|
||||||
|
|
||||||
|
public FontAtlas(int width, int height, byte[] pixels,
|
||||||
|
Map<Integer, Glyph> glyphs,
|
||||||
|
float ascent, float lineHeight) {
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
this.pixels = pixels;
|
||||||
|
this.glyphs = Collections.unmodifiableMap(new HashMap<Integer, Glyph>(glyphs));
|
||||||
|
this.ascent = ascent;
|
||||||
|
this.lineHeight = lineHeight;
|
||||||
|
|
||||||
|
for (Map.Entry<Integer, Glyph> entry : glyphs.entrySet()) {
|
||||||
|
int codePoint = entry.getKey();
|
||||||
|
if (codePoint >= 0 && codePoint < ascii.length) {
|
||||||
|
ascii[codePoint] = entry.getValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getHeight() {
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getPixels() {
|
||||||
|
if (pixels == null) {
|
||||||
|
throw new IllegalStateException("Atlas pixels have already been released");
|
||||||
|
}
|
||||||
|
return pixels;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drops the CPU-side coverage bitmap after the texture has been uploaded.
|
||||||
|
*/
|
||||||
|
public void releasePixels() {
|
||||||
|
this.pixels = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getAscent() {
|
||||||
|
return ascent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getLineHeight() {
|
||||||
|
return lineHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Glyph getGlyph(int codePoint) {
|
||||||
|
if (codePoint >= 0 && codePoint < ascii.length) {
|
||||||
|
Glyph glyph = ascii[codePoint];
|
||||||
|
if (glyph != null) {
|
||||||
|
return glyph;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return glyphs.get(codePoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Glyph getFallbackGlyph() {
|
||||||
|
Glyph space = getGlyph(' ');
|
||||||
|
if (space != null) {
|
||||||
|
return space;
|
||||||
|
}
|
||||||
|
return getGlyph('?');
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Integer, Glyph> getGlyphs() {
|
||||||
|
return glyphs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A baked atlas plus its GPU texture and the scale needed to draw it at the
|
||||||
|
* requested logical size.
|
||||||
|
*/
|
||||||
|
public final class FontFace {
|
||||||
|
|
||||||
|
private final FontFamily family;
|
||||||
|
private final FontAtlas atlas;
|
||||||
|
private final FontTexture texture;
|
||||||
|
private final float logicalSize;
|
||||||
|
private final float drawScale;
|
||||||
|
|
||||||
|
public FontFace(FontFamily family, FontAtlas atlas, FontTexture texture,
|
||||||
|
float logicalSize, float drawScale) {
|
||||||
|
this.family = family;
|
||||||
|
this.atlas = atlas;
|
||||||
|
this.texture = texture;
|
||||||
|
this.logicalSize = logicalSize;
|
||||||
|
this.drawScale = drawScale;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FontFamily getFamily() {
|
||||||
|
return family;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FontAtlas getAtlas() {
|
||||||
|
return atlas;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FontTexture getTexture() {
|
||||||
|
return texture;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getLogicalSize() {
|
||||||
|
return logicalSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getDrawScale() {
|
||||||
|
return drawScale;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Glyph getGlyph(int codePoint) {
|
||||||
|
return atlas.getGlyph(codePoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Glyph getFallbackGlyph() {
|
||||||
|
return atlas.getFallbackGlyph();
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getAscent() {
|
||||||
|
return atlas.getAscent();
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getLineHeight() {
|
||||||
|
return atlas.getLineHeight();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bundled font families.
|
||||||
|
*/
|
||||||
|
public enum FontFamily {
|
||||||
|
|
||||||
|
PROXIMA("assets/orangex/font/proxima.ttf", "assets/orangex/font/proximabd.ttf", false),
|
||||||
|
NOTO("assets/orangex/font/noto.ttf", "assets/orangex/font/noto.ttf", true),
|
||||||
|
POPPINS("assets/orangex/font/poppins_rg.ttf", "assets/orangex/font/poppins_rg.ttf", false);
|
||||||
|
|
||||||
|
private final String regularResource;
|
||||||
|
private final String boldResource;
|
||||||
|
private final boolean cjkCapable;
|
||||||
|
|
||||||
|
FontFamily(String regularResource, String boldResource, boolean cjkCapable) {
|
||||||
|
this.regularResource = regularResource;
|
||||||
|
this.boldResource = boldResource;
|
||||||
|
this.cjkCapable = cjkCapable;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRegularResource() {
|
||||||
|
return regularResource;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBoldResource() {
|
||||||
|
return boldResource;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getResource(boolean bold) {
|
||||||
|
return bold ? boldResource : regularResource;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCjkCapable() {
|
||||||
|
return cjkCapable;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontBackend;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates and caches {@link FontFace} instances.
|
||||||
|
*
|
||||||
|
* <p>One face exists per (family, bold, logical size, GUI scale) tuple. The
|
||||||
|
* atlas is rasterised at {@code size * guiScale} pixels so text stays crisp on
|
||||||
|
* high GUI scales, while {@link FontFace#getDrawScale()} converts atlas pixels
|
||||||
|
* back to GUI pixels.</p>
|
||||||
|
*/
|
||||||
|
public final class FontManager {
|
||||||
|
|
||||||
|
private static final int MAX_RASTER_HEIGHT = 64;
|
||||||
|
private static final int MAX_CJK_RASTER_HEIGHT = 36;
|
||||||
|
|
||||||
|
private final FontBackend backend;
|
||||||
|
private final Map<Key, FontFace> faces = new HashMap<Key, FontFace>();
|
||||||
|
private final Map<String, byte[]> fontData = new HashMap<String, byte[]>();
|
||||||
|
|
||||||
|
public FontManager(FontBackend backend) {
|
||||||
|
this.backend = backend;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized FontFace getFace(FontFamily family, float logicalSize,
|
||||||
|
boolean bold, double guiScale) {
|
||||||
|
if (family == null) {
|
||||||
|
family = FontFamily.PROXIMA;
|
||||||
|
}
|
||||||
|
if (logicalSize <= 0.0f) {
|
||||||
|
throw new IllegalArgumentException("logicalSize must be positive");
|
||||||
|
}
|
||||||
|
|
||||||
|
int rasterHeight = (int) Math.round(logicalSize * Math.max(1.0, guiScale));
|
||||||
|
int maxRasterHeight = family.isCjkCapable()
|
||||||
|
? MAX_CJK_RASTER_HEIGHT
|
||||||
|
: MAX_RASTER_HEIGHT;
|
||||||
|
if (rasterHeight < 1) {
|
||||||
|
rasterHeight = 1;
|
||||||
|
} else if (rasterHeight > maxRasterHeight) {
|
||||||
|
rasterHeight = maxRasterHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
Key key = new Key(family, bold, rasterHeight, logicalSize);
|
||||||
|
FontFace cached = faces.get(key);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] data = loadFont(family.getResource(bold));
|
||||||
|
FontAtlas atlas = StbFontBaker.bake(
|
||||||
|
data,
|
||||||
|
rasterHeight,
|
||||||
|
family.isCjkCapable(),
|
||||||
|
!"false".equalsIgnoreCase(
|
||||||
|
System.getProperty("orangex.font.fullGbk", "true"))
|
||||||
|
);
|
||||||
|
FontTexture texture = backend.createTexture(atlas);
|
||||||
|
atlas.releasePixels();
|
||||||
|
float drawScale = logicalSize / (float) rasterHeight;
|
||||||
|
FontFace face = new FontFace(family, atlas, texture, logicalSize, drawScale);
|
||||||
|
faces.put(key, face);
|
||||||
|
return face;
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] loadFont(String resource) {
|
||||||
|
byte[] cached = fontData.get(resource);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
InputStream stream = FontManager.class.getClassLoader()
|
||||||
|
.getResourceAsStream(resource);
|
||||||
|
if (stream == null) {
|
||||||
|
throw new IllegalStateException("Missing font resource: " + resource);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
ByteArrayOutputStream output = new ByteArrayOutputStream(64 * 1024);
|
||||||
|
byte[] buffer = new byte[8192];
|
||||||
|
int read;
|
||||||
|
while ((read = stream.read(buffer)) != -1) {
|
||||||
|
output.write(buffer, 0, read);
|
||||||
|
}
|
||||||
|
byte[] data = output.toByteArray();
|
||||||
|
fontData.put(resource, data);
|
||||||
|
return data;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalStateException("Cannot read font resource: " + resource, e);
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
stream.close();
|
||||||
|
} catch (IOException ignored) {
|
||||||
|
// Ignore close failures for a classpath resource.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getBackendName() {
|
||||||
|
return backend.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clear() {
|
||||||
|
for (FontFace face : faces.values()) {
|
||||||
|
face.getTexture().close();
|
||||||
|
}
|
||||||
|
faces.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Key {
|
||||||
|
private final FontFamily family;
|
||||||
|
private final boolean bold;
|
||||||
|
private final int rasterHeight;
|
||||||
|
private final float logicalSize;
|
||||||
|
|
||||||
|
private Key(FontFamily family, boolean bold, int rasterHeight,
|
||||||
|
float logicalSize) {
|
||||||
|
this.family = family;
|
||||||
|
this.bold = bold;
|
||||||
|
this.rasterHeight = rasterHeight;
|
||||||
|
this.logicalSize = logicalSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object other) {
|
||||||
|
if (this == other) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!(other instanceof Key)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Key key = (Key) other;
|
||||||
|
return bold == key.bold
|
||||||
|
&& rasterHeight == key.rasterHeight
|
||||||
|
&& Float.compare(logicalSize, key.logicalSize) == 0
|
||||||
|
&& family == key.family;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = family.hashCode();
|
||||||
|
result = 31 * result + (bold ? 1 : 0);
|
||||||
|
result = 31 * result + rasterHeight;
|
||||||
|
result = 31 * result + Float.floatToIntBits(logicalSize);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One glyph inside a {@link FontAtlas}.
|
||||||
|
*
|
||||||
|
* <p>All offsets are expressed in atlas pixels relative to the pen position on
|
||||||
|
* the baseline. UVs are normalised to {@code [0, 1]}.</p>
|
||||||
|
*/
|
||||||
|
public final class Glyph {
|
||||||
|
|
||||||
|
private final float x0;
|
||||||
|
private final float y0;
|
||||||
|
private final float x1;
|
||||||
|
private final float y1;
|
||||||
|
|
||||||
|
private final float u0;
|
||||||
|
private final float v0;
|
||||||
|
private final float u1;
|
||||||
|
private final float v1;
|
||||||
|
|
||||||
|
private final float advance;
|
||||||
|
|
||||||
|
public Glyph(float x0, float y0, float x1, float y1,
|
||||||
|
float u0, float v0, float u1, float v1,
|
||||||
|
float advance) {
|
||||||
|
this.x0 = x0;
|
||||||
|
this.y0 = y0;
|
||||||
|
this.x1 = x1;
|
||||||
|
this.y1 = y1;
|
||||||
|
this.u0 = u0;
|
||||||
|
this.v0 = v0;
|
||||||
|
this.u1 = u1;
|
||||||
|
this.v1 = v1;
|
||||||
|
this.advance = advance;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getX0() {
|
||||||
|
return x0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getY0() {
|
||||||
|
return y0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getX1() {
|
||||||
|
return x1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getY1() {
|
||||||
|
return y1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getU0() {
|
||||||
|
return u0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getV0() {
|
||||||
|
return v0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getU1() {
|
||||||
|
return u1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getV1() {
|
||||||
|
return v1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getAdvance() {
|
||||||
|
return advance;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isBlank() {
|
||||||
|
return x0 == x1 || y0 == y1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbRasterizer;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypeFontInfo;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypePackContext;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypePackRange;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypePackedChar;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bakes a TrueType/OpenType font into a {@link FontAtlas}.
|
||||||
|
*
|
||||||
|
* <p>This is a thin adapter around the ported stb_truetype code in
|
||||||
|
* {@code render.font.stb}. The original Vape renderer used a single range and
|
||||||
|
* one fixed 4096x4096 sheet; here the character set is split into a Latin range
|
||||||
|
* and an optional CJK range so oversampling/atlas pressure can be controlled
|
||||||
|
* separately.</p>
|
||||||
|
*/
|
||||||
|
public final class StbFontBaker {
|
||||||
|
|
||||||
|
private static final int DEFAULT_ATLAS_SIZE = 4096;
|
||||||
|
private static final int LATIN_OVERSAMPLE = 2;
|
||||||
|
private static final int CJK_OVERSAMPLE = 1;
|
||||||
|
|
||||||
|
private StbFontBaker() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static FontAtlas bake(byte[] fontData, int pixelHeight,
|
||||||
|
boolean includeCjk, boolean fullGbk) {
|
||||||
|
if (fontData == null || fontData.length == 0) {
|
||||||
|
throw new IllegalArgumentException("fontData is empty");
|
||||||
|
}
|
||||||
|
if (pixelHeight < 1) {
|
||||||
|
throw new IllegalArgumentException("pixelHeight must be positive");
|
||||||
|
}
|
||||||
|
|
||||||
|
StbTrueTypeFontInfo info = new StbTrueTypeFontInfo();
|
||||||
|
if (StbRasterizer.z(info, fontData, 0) == 0) {
|
||||||
|
throw new IllegalArgumentException("Not a valid TrueType/OpenType font");
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] ascent = new int[1];
|
||||||
|
int[] descent = new int[1];
|
||||||
|
int[] lineGap = new int[1];
|
||||||
|
StbRasterizer.x(info, ascent, descent, lineGap);
|
||||||
|
|
||||||
|
float fontScale = StbRasterizer.V(info, pixelHeight);
|
||||||
|
float ascentPx = ascent[0] * fontScale;
|
||||||
|
float lineHeightPx = (ascent[0] - descent[0] + lineGap[0]) * fontScale;
|
||||||
|
|
||||||
|
int atlasSize = atlasSize();
|
||||||
|
byte[] pixels = new byte[atlasSize * atlasSize];
|
||||||
|
|
||||||
|
StbTrueTypePackContext packContext = new StbTrueTypePackContext();
|
||||||
|
if (StbRasterizer.C(packContext, pixels, atlasSize, atlasSize, 0, 1) == 0) {
|
||||||
|
throw new IllegalStateException("Unable to initialise the stb pack context");
|
||||||
|
}
|
||||||
|
StbRasterizer.n(packContext, LATIN_OVERSAMPLE, LATIN_OVERSAMPLE);
|
||||||
|
|
||||||
|
int[] latin = latinCodepoints();
|
||||||
|
StbTrueTypePackRange latinRange = createRange(latin, pixelHeight, LATIN_OVERSAMPLE);
|
||||||
|
StbTrueTypePackRange[] ranges;
|
||||||
|
|
||||||
|
int[] cjk = null;
|
||||||
|
StbTrueTypePackRange cjkRange = null;
|
||||||
|
if (includeCjk) {
|
||||||
|
cjk = cjkCodepoints(fullGbk);
|
||||||
|
if (cjk.length > 0) {
|
||||||
|
cjkRange = createRange(cjk, pixelHeight, CJK_OVERSAMPLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cjkRange != null) {
|
||||||
|
ranges = new StbTrueTypePackRange[]{latinRange, cjkRange};
|
||||||
|
} else {
|
||||||
|
ranges = new StbTrueTypePackRange[]{latinRange};
|
||||||
|
}
|
||||||
|
|
||||||
|
int packed = StbRasterizer.c(packContext, fontData, 0, ranges, ranges.length);
|
||||||
|
StbRasterizer.S(packContext);
|
||||||
|
|
||||||
|
Map<Integer, Glyph> glyphs = new HashMap<Integer, Glyph>();
|
||||||
|
collectGlyphs(glyphs, latinRange, latin, atlasSize, packed != 0);
|
||||||
|
if (cjkRange != null) {
|
||||||
|
collectGlyphs(glyphs, cjkRange, cjk, atlasSize, packed != 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Missing glyph: '?' or space. The renderer falls back to it for
|
||||||
|
// unsupported code points.
|
||||||
|
if (!glyphs.containsKey((int) '?')) {
|
||||||
|
Glyph space = glyphs.get((int) ' ');
|
||||||
|
if (space != null) {
|
||||||
|
glyphs.put((int) '?', space);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new FontAtlas(atlasSize, atlasSize, pixels, glyphs,
|
||||||
|
ascentPx, lineHeightPx);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int atlasSize() {
|
||||||
|
int configured = Integer.getInteger("orangex.font.atlasSize", DEFAULT_ATLAS_SIZE);
|
||||||
|
if (configured < 512) {
|
||||||
|
configured = 512;
|
||||||
|
} else if (configured > 8192) {
|
||||||
|
configured = 8192;
|
||||||
|
}
|
||||||
|
return configured;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static StbTrueTypePackRange createRange(int[] codepoints, int pixelHeight,
|
||||||
|
int oversample) {
|
||||||
|
StbTrueTypePackedChar[] packedChars = new StbTrueTypePackedChar[codepoints.length];
|
||||||
|
for (int i = 0; i < packedChars.length; i++) {
|
||||||
|
packedChars[i] = new StbTrueTypePackedChar();
|
||||||
|
}
|
||||||
|
|
||||||
|
StbTrueTypePackRange range = new StbTrueTypePackRange();
|
||||||
|
range.E = pixelHeight;
|
||||||
|
range.R = 0;
|
||||||
|
range.N = codepoints;
|
||||||
|
range.b = codepoints.length;
|
||||||
|
range.M = packedChars;
|
||||||
|
range.i = (byte) oversample;
|
||||||
|
range.y = (byte) oversample;
|
||||||
|
return range;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void collectGlyphs(Map<Integer, Glyph> out,
|
||||||
|
StbTrueTypePackRange range,
|
||||||
|
int[] codepoints,
|
||||||
|
int atlasSize,
|
||||||
|
boolean packedOk) {
|
||||||
|
float inverse = 1.0f / (float) atlasSize;
|
||||||
|
for (int i = 0; i < codepoints.length; i++) {
|
||||||
|
StbTrueTypePackedChar packedChar = range.M[i];
|
||||||
|
if (packedChar.A == 0.0f && packedChar.q == 0 && packedChar.p == 0) {
|
||||||
|
// Glyph did not fit or has no advance; keep spaces (A > 0).
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.put(codepoints[i], new Glyph(
|
||||||
|
packedChar.s,
|
||||||
|
packedChar.G,
|
||||||
|
packedChar.t,
|
||||||
|
packedChar.R,
|
||||||
|
packedChar.b * inverse,
|
||||||
|
packedChar.k * inverse,
|
||||||
|
packedChar.q * inverse,
|
||||||
|
packedChar.p * inverse,
|
||||||
|
packedChar.A
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if (!packedOk) {
|
||||||
|
System.out.println("[OrangeX] Font pack reported overflow (atlas "
|
||||||
|
+ atlasSize + "x" + atlasSize + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] latinCodepoints() {
|
||||||
|
Set<Integer> codepoints = new LinkedHashSet<Integer>();
|
||||||
|
for (int c = 32; c <= 126; c++) {
|
||||||
|
codepoints.add(c);
|
||||||
|
}
|
||||||
|
for (int c = 160; c <= 255; c++) {
|
||||||
|
codepoints.add(c);
|
||||||
|
}
|
||||||
|
return toArray(codepoints);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes GBK double-byte ranges. Level 1 (common simplified Chinese) is
|
||||||
|
* used by default; {@code fullGbk} widens it to the whole GBK range that
|
||||||
|
* Vape covered.
|
||||||
|
*/
|
||||||
|
private static int[] cjkCodepoints(boolean fullGbk) {
|
||||||
|
Set<Integer> codepoints = new LinkedHashSet<Integer>();
|
||||||
|
int highStart = fullGbk ? 0xA1 : 0xB0;
|
||||||
|
int highEnd = fullGbk ? 0xF7 : 0xD7;
|
||||||
|
Charset gbk;
|
||||||
|
try {
|
||||||
|
gbk = Charset.forName("GBK");
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
return new int[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int high = highStart; high <= highEnd; high++) {
|
||||||
|
for (int low = 0xA1; low <= 0xFE; low++) {
|
||||||
|
String decoded = new String(
|
||||||
|
new byte[]{(byte) high, (byte) low}, gbk);
|
||||||
|
if (decoded.length() != 1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
char c = decoded.charAt(0);
|
||||||
|
if (c >= '\u4e00' && c <= '\u9fff') {
|
||||||
|
codepoints.add((int) c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return toArray(codepoints);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] toArray(Set<Integer> values) {
|
||||||
|
int[] result = new int[values.size()];
|
||||||
|
int index = 0;
|
||||||
|
for (Integer value : values) {
|
||||||
|
result[index++] = value;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.GlyphDrawer;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Draws UTF-16 text with a primary face and an optional CJK fallback face.
|
||||||
|
*
|
||||||
|
* <p>Supported formatting: Minecraft {@code §} colour codes ({@code 0-9},
|
||||||
|
* {@code a-f}, {@code r}). Shadow text is drawn as MC does: a dimmed copy
|
||||||
|
* offset by one GUI pixel.</p>
|
||||||
|
*/
|
||||||
|
public final class TrueTypeFontRenderer implements FontRenderer {
|
||||||
|
|
||||||
|
private static final int[] COLORS = new int[]{
|
||||||
|
0xFF000000, 0xFF0000AA, 0xFF00AA00, 0xFF00AAAA,
|
||||||
|
0xFFAA0000, 0xFFAA00AA, 0xFFFFAA00, 0xFFAAAAAA,
|
||||||
|
0xFF555555, 0xFF5555FF, 0xFF55FF55, 0xFF55FFFF,
|
||||||
|
0xFFFF5555, 0xFFFF55FF, 0xFFFFFF55, 0xFFFFFFFF
|
||||||
|
};
|
||||||
|
|
||||||
|
private final FontManager manager;
|
||||||
|
private final FontFace primary;
|
||||||
|
private final GlyphDrawer drawer;
|
||||||
|
private final boolean bold;
|
||||||
|
private final double guiScale;
|
||||||
|
|
||||||
|
private final Map<String, Double> widthCache = new HashMap<String, Double>();
|
||||||
|
private FontFace fallback;
|
||||||
|
|
||||||
|
public TrueTypeFontRenderer(FontManager manager, FontFace primary,
|
||||||
|
boolean bold, double guiScale,
|
||||||
|
GlyphDrawer drawer) {
|
||||||
|
this.manager = manager;
|
||||||
|
this.primary = primary;
|
||||||
|
this.bold = bold;
|
||||||
|
this.guiScale = guiScale;
|
||||||
|
this.drawer = drawer;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawString(String text, double x, double y, int argb) {
|
||||||
|
draw(text, x, y, argb, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawStringWithShadow(String text, double x, double y, int argb) {
|
||||||
|
draw(text, x, y, argb, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawCenteredString(String text, double centerX, double y, int argb) {
|
||||||
|
drawString(text, centerX - getUncachedWidth(text) / 2.0, y, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawCenteredStringWithShadow(String text, double centerX,
|
||||||
|
double y, int argb) {
|
||||||
|
drawStringWithShadow(text, centerX - getUncachedWidth(text) / 2.0, y, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getStringWidth(String text) {
|
||||||
|
if (text == null || text.isEmpty()) {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
Double cached = widthCache.get(text);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
double width = getUncachedWidth(text);
|
||||||
|
if (widthCache.size() > 4096) {
|
||||||
|
widthCache.clear();
|
||||||
|
}
|
||||||
|
widthCache.put(text, width);
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getStringHeight() {
|
||||||
|
float height = primary.getLineHeight() * primary.getDrawScale();
|
||||||
|
return height > 0.0f ? height : primary.getLogicalSize();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void draw(String text, double x, double y, int argb, boolean shadow) {
|
||||||
|
if (text == null || text.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int color = normalizeAlpha(argb);
|
||||||
|
if (shadow) {
|
||||||
|
drawPass(text, x + 1.0, y + 1.0, color, true);
|
||||||
|
}
|
||||||
|
drawPass(text, x, y, color, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void drawPass(String text, double x, double y,
|
||||||
|
int baseColor, boolean shadow) {
|
||||||
|
int color = baseColor;
|
||||||
|
double penX = x;
|
||||||
|
|
||||||
|
for (int i = 0; i < text.length(); ) {
|
||||||
|
char ch = text.charAt(i);
|
||||||
|
|
||||||
|
if (ch == '\u00a7' && i + 1 < text.length()) {
|
||||||
|
char code = text.charAt(i + 1);
|
||||||
|
color = colorFor(code, baseColor);
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
int codePoint;
|
||||||
|
if (Character.isHighSurrogate(ch) && i + 1 < text.length()) {
|
||||||
|
codePoint = Character.toCodePoint(ch, text.charAt(i + 1));
|
||||||
|
i += 2;
|
||||||
|
} else {
|
||||||
|
codePoint = ch;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
ResolvedGlyph resolved = resolve(codePoint);
|
||||||
|
if (resolved == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
float scale = resolved.face.getDrawScale();
|
||||||
|
double baseline = y + resolved.face.getAscent() * scale;
|
||||||
|
int drawColor = shadow ? shadowColor(color) : color;
|
||||||
|
|
||||||
|
if (!resolved.glyph.isBlank()) {
|
||||||
|
drawer.drawGlyph(resolved.face.getTexture(), resolved.glyph,
|
||||||
|
penX, baseline, scale, drawColor);
|
||||||
|
}
|
||||||
|
penX += resolved.glyph.getAdvance() * scale;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private double getUncachedWidth(String text) {
|
||||||
|
double width = 0.0;
|
||||||
|
for (int i = 0; i < text.length(); ) {
|
||||||
|
char ch = text.charAt(i);
|
||||||
|
|
||||||
|
if (ch == '\u00a7' && i + 1 < text.length()) {
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
int codePoint;
|
||||||
|
if (Character.isHighSurrogate(ch) && i + 1 < text.length()) {
|
||||||
|
codePoint = Character.toCodePoint(ch, text.charAt(i + 1));
|
||||||
|
i += 2;
|
||||||
|
} else {
|
||||||
|
codePoint = ch;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
ResolvedGlyph resolved = resolve(codePoint);
|
||||||
|
if (resolved == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
width += resolved.glyph.getAdvance() * resolved.face.getDrawScale();
|
||||||
|
}
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ResolvedGlyph resolve(int codePoint) {
|
||||||
|
Glyph glyph = primary.getGlyph(codePoint);
|
||||||
|
if (glyph != null) {
|
||||||
|
return new ResolvedGlyph(primary, glyph);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ASCII/Latin faces do not contain CJK. Lazy-load Noto only when a
|
||||||
|
// missing code point is actually encountered.
|
||||||
|
if (!primary.getFamily().isCjkCapable()) {
|
||||||
|
if (fallback == null) {
|
||||||
|
fallback = manager.getFace(FontFamily.NOTO,
|
||||||
|
primary.getLogicalSize(), bold, guiScale);
|
||||||
|
}
|
||||||
|
glyph = fallback.getGlyph(codePoint);
|
||||||
|
if (glyph != null) {
|
||||||
|
return new ResolvedGlyph(fallback, glyph);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
glyph = primary.getFallbackGlyph();
|
||||||
|
return glyph != null ? new ResolvedGlyph(primary, glyph) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int normalizeAlpha(int argb) {
|
||||||
|
if ((argb >>> 24) == 0) {
|
||||||
|
return 0xFF000000 | (argb & 0x00FFFFFF);
|
||||||
|
}
|
||||||
|
return argb;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int colorFor(char code, int baseColor) {
|
||||||
|
if (code == 'r' || code == 'R') {
|
||||||
|
return baseColor;
|
||||||
|
}
|
||||||
|
if (code >= '0' && code <= '9') {
|
||||||
|
return applyAlpha(COLORS[code - '0'], baseColor);
|
||||||
|
}
|
||||||
|
if (code >= 'a' && code <= 'f') {
|
||||||
|
return applyAlpha(COLORS[10 + code - 'a'], baseColor);
|
||||||
|
}
|
||||||
|
if (code >= 'A' && code <= 'F') {
|
||||||
|
return applyAlpha(COLORS[10 + code - 'A'], baseColor);
|
||||||
|
}
|
||||||
|
return baseColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int applyAlpha(int rgb, int baseColor) {
|
||||||
|
return (baseColor & 0xFF000000) | (rgb & 0x00FFFFFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int shadowColor(int color) {
|
||||||
|
int alpha = color & 0xFF000000;
|
||||||
|
int red = (color >> 16) & 0xFF;
|
||||||
|
int green = (color >> 8) & 0xFF;
|
||||||
|
int blue = color & 0xFF;
|
||||||
|
return alpha
|
||||||
|
| ((red / 4) << 16)
|
||||||
|
| ((green / 4) << 8)
|
||||||
|
| (blue / 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class ResolvedGlyph {
|
||||||
|
private final FontFace face;
|
||||||
|
private final Glyph glyph;
|
||||||
|
|
||||||
|
private ResolvedGlyph(FontFace face, Glyph glyph) {
|
||||||
|
this.face = face;
|
||||||
|
this.glyph = glyph;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/*
|
||||||
|
* Recovered from the sample class that collided with Javassist's
|
||||||
|
* javassist.bytecode.analysis.Frame.
|
||||||
|
*/
|
||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
/** A lightweight cursor over a byte-array slice used by the STB parser. */
|
||||||
|
public final class StbByteBufferView {
|
||||||
|
public byte[] f;
|
||||||
|
public int y;
|
||||||
|
public int C;
|
||||||
|
public int h;
|
||||||
|
|
||||||
|
public StbByteBufferView() {
|
||||||
|
this(null, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
public StbByteBufferView(byte[] data, int offset, int length) {
|
||||||
|
this.f = data;
|
||||||
|
this.C = offset;
|
||||||
|
this.h = 0;
|
||||||
|
this.y = length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public StbByteBufferView k() {
|
||||||
|
StbByteBufferView copy = new StbByteBufferView();
|
||||||
|
copy.f = this.f;
|
||||||
|
copy.C = this.C;
|
||||||
|
copy.h = this.h;
|
||||||
|
copy.y = this.y;
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeActiveEdge {
|
||||||
|
public float j;
|
||||||
|
public float e;
|
||||||
|
public float N;
|
||||||
|
public float m;
|
||||||
|
public StbTrueTypeActiveEdge l;
|
||||||
|
public float T;
|
||||||
|
public float L;
|
||||||
|
}
|
||||||
|
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeAlignedQuad {
|
||||||
|
public float K;
|
||||||
|
public float G;
|
||||||
|
public float C;
|
||||||
|
public float x;
|
||||||
|
public float v;
|
||||||
|
public float M;
|
||||||
|
public float O;
|
||||||
|
public float S;
|
||||||
|
}
|
||||||
|
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeBakedChar {
|
||||||
|
public int V;
|
||||||
|
public float k;
|
||||||
|
public float l;
|
||||||
|
public int D;
|
||||||
|
public float B;
|
||||||
|
public int U;
|
||||||
|
public int Q;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeBitmap {
|
||||||
|
public byte[] E;
|
||||||
|
public int c;
|
||||||
|
public int K;
|
||||||
|
public int h;
|
||||||
|
public int A;
|
||||||
|
}
|
||||||
|
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypeVertex;
|
||||||
|
|
||||||
|
public class StbTrueTypeCharStringContext {
|
||||||
|
public int Z;
|
||||||
|
public int c;
|
||||||
|
public int q;
|
||||||
|
public float p;
|
||||||
|
public int v;
|
||||||
|
public float o;
|
||||||
|
public float s;
|
||||||
|
public float C;
|
||||||
|
public int J;
|
||||||
|
public int y;
|
||||||
|
public int f;
|
||||||
|
public StbTrueTypeVertex[] V;
|
||||||
|
|
||||||
|
public StbTrueTypeCharStringContext(int n) {
|
||||||
|
this.J = n;
|
||||||
|
this.v = 0;
|
||||||
|
this.s = 0.0f;
|
||||||
|
this.p = 0.0f;
|
||||||
|
this.C = 0.0f;
|
||||||
|
this.o = 0.0f;
|
||||||
|
this.y = 0;
|
||||||
|
this.c = 0;
|
||||||
|
this.Z = 0;
|
||||||
|
this.f = 0;
|
||||||
|
this.V = null;
|
||||||
|
this.q = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeEdge {
|
||||||
|
public float u;
|
||||||
|
public float d;
|
||||||
|
public int W;
|
||||||
|
public float X;
|
||||||
|
public float i;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeFontInfo {
|
||||||
|
public int h;
|
||||||
|
public int G;
|
||||||
|
public StbByteBufferView H;
|
||||||
|
public int Y;
|
||||||
|
public int L;
|
||||||
|
public int Q;
|
||||||
|
public int U;
|
||||||
|
public StbByteBufferView g = new StbByteBufferView();
|
||||||
|
public int c;
|
||||||
|
public StbByteBufferView j;
|
||||||
|
public byte[] S;
|
||||||
|
public StbByteBufferView z = new StbByteBufferView();
|
||||||
|
public StbByteBufferView J;
|
||||||
|
public int d;
|
||||||
|
public int T;
|
||||||
|
public int w;
|
||||||
|
public StbByteBufferView N;
|
||||||
|
public int v;
|
||||||
|
public int p;
|
||||||
|
|
||||||
|
public StbTrueTypeFontInfo() {
|
||||||
|
this.j = new StbByteBufferView();
|
||||||
|
this.J = new StbByteBufferView();
|
||||||
|
this.H = new StbByteBufferView();
|
||||||
|
this.N = new StbByteBufferView();
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeGlyphPackNode {
|
||||||
|
public int z;
|
||||||
|
}
|
||||||
|
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeKerningEntry {
|
||||||
|
public int y;
|
||||||
|
public int q;
|
||||||
|
public int o;
|
||||||
|
}
|
||||||
|
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypePackAtlasState {
|
||||||
|
public int F;
|
||||||
|
public int a;
|
||||||
|
public int n;
|
||||||
|
public int f;
|
||||||
|
public int t;
|
||||||
|
}
|
||||||
|
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypeGlyphPackNode;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypePackAtlasState;
|
||||||
|
|
||||||
|
public class StbTrueTypePackContext {
|
||||||
|
public int d;
|
||||||
|
public StbTrueTypeGlyphPackNode[] j;
|
||||||
|
public int m;
|
||||||
|
public int h;
|
||||||
|
public int G;
|
||||||
|
public int b;
|
||||||
|
public StbTrueTypePackAtlasState J;
|
||||||
|
public int c;
|
||||||
|
public int w;
|
||||||
|
public byte[] X;
|
||||||
|
}
|
||||||
|
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.font.stb.StbTrueTypePackedChar;
|
||||||
|
|
||||||
|
public class StbTrueTypePackRange {
|
||||||
|
public int y;
|
||||||
|
public int R;
|
||||||
|
public int[] N;
|
||||||
|
public StbTrueTypePackedChar[] M;
|
||||||
|
public int i;
|
||||||
|
public float E;
|
||||||
|
private static String[] j;
|
||||||
|
public int b;
|
||||||
|
|
||||||
|
public static void t(String[] stringArray) {
|
||||||
|
j = stringArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String[] x() {
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
static {
|
||||||
|
if (StbTrueTypePackRange.x() != null) {
|
||||||
|
StbTrueTypePackRange.t(new String[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypePackRectangle {
|
||||||
|
public int e;
|
||||||
|
public int J;
|
||||||
|
public int P;
|
||||||
|
public int M;
|
||||||
|
public int N;
|
||||||
|
public int q;
|
||||||
|
}
|
||||||
|
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypePackedChar {
|
||||||
|
public int p;
|
||||||
|
public int q;
|
||||||
|
public float R;
|
||||||
|
public int k;
|
||||||
|
public float A;
|
||||||
|
public int b;
|
||||||
|
public float G;
|
||||||
|
public float t;
|
||||||
|
public float s;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypePoint {
|
||||||
|
public float E;
|
||||||
|
public float M;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font.stb;
|
||||||
|
|
||||||
|
public class StbTrueTypeVertex {
|
||||||
|
public short h;
|
||||||
|
public int O;
|
||||||
|
public short H;
|
||||||
|
public short a;
|
||||||
|
public short D;
|
||||||
|
public short s;
|
||||||
|
public int v;
|
||||||
|
public short f;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontAtlas;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Version-specific GPU operations for the font renderer.
|
||||||
|
*/
|
||||||
|
public interface FontBackend {
|
||||||
|
|
||||||
|
FontTexture createTexture(FontAtlas atlas);
|
||||||
|
|
||||||
|
Render2D createRender2D(FontManager fonts, Object platformContext);
|
||||||
|
|
||||||
|
String getName();
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingResolver;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.v1_8_9.V1_8_9FontBackend;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.v26_2.V26_2FontBackend;
|
||||||
|
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Selects the font backend for the detected Minecraft version.
|
||||||
|
*/
|
||||||
|
public final class FontBackendFactory {
|
||||||
|
|
||||||
|
public static FontBackend create(RuntimeInfo runtimeInfo,
|
||||||
|
MappingResolver mappingResolver,
|
||||||
|
Object minecraft) {
|
||||||
|
switch (runtimeInfo.getMinecraftVersion()) {
|
||||||
|
case V1_8_9:
|
||||||
|
return new V1_8_9FontBackend(runtimeInfo, mappingResolver, minecraft);
|
||||||
|
case V26_2:
|
||||||
|
return new V26_2FontBackend(runtimeInfo);
|
||||||
|
default:
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"No font backend for " + runtimeInfo.getMinecraftVersion());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private FontBackendFactory() {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opaque GPU texture owned by one {@link cn.xiaozhou233.orangex.render.font.FontAtlas}.
|
||||||
|
* The concrete type depends on the Minecraft version.
|
||||||
|
*/
|
||||||
|
public interface FontTexture {
|
||||||
|
|
||||||
|
int getWidth();
|
||||||
|
|
||||||
|
int getHeight();
|
||||||
|
|
||||||
|
void close();
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.font.Glyph;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Draws one glyph for the current frame. A drawer is created per frame because
|
||||||
|
* modern Minecraft renders the GUI through a deferred render-state object.
|
||||||
|
*/
|
||||||
|
public interface GlyphDrawer {
|
||||||
|
|
||||||
|
void drawGlyph(FontTexture texture, Glyph glyph,
|
||||||
|
double x, double y, double scale, int argb);
|
||||||
|
}
|
||||||
+91
@@ -0,0 +1,91 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v1_8_9;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingResolver;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontAtlas;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontManager;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontBackend;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
|
||||||
|
import org.lwjgl.BufferUtils;
|
||||||
|
import org.lwjgl.opengl.GL11;
|
||||||
|
import org.lwjgl.opengl.GL12;
|
||||||
|
import org.lwjgl.opengl.GL13;
|
||||||
|
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Legacy OpenGL backend used by Minecraft 1.8.9.
|
||||||
|
*
|
||||||
|
* <p>The atlas is uploaded as {@code GL_ALPHA}; the fixed-function pipeline
|
||||||
|
* modulates the current colour with the glyph coverage, which is exactly what
|
||||||
|
* the old Minecraft font renderer does.</p>
|
||||||
|
*/
|
||||||
|
public final class V1_8_9FontBackend implements FontBackend {
|
||||||
|
|
||||||
|
private final RuntimeInfo runtimeInfo;
|
||||||
|
private final MappingResolver resolver;
|
||||||
|
private final Object minecraft;
|
||||||
|
private final V1_8_9RenderState state = new V1_8_9RenderState();
|
||||||
|
private final V1_8_9GlyphDrawer drawer = new V1_8_9GlyphDrawer(state);
|
||||||
|
|
||||||
|
public V1_8_9FontBackend(RuntimeInfo runtimeInfo,
|
||||||
|
MappingResolver resolver,
|
||||||
|
Object minecraft) {
|
||||||
|
this.runtimeInfo = runtimeInfo;
|
||||||
|
this.resolver = resolver;
|
||||||
|
this.minecraft = minecraft;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FontTexture createTexture(FontAtlas atlas) {
|
||||||
|
int previousTexture = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
|
||||||
|
int previousAlignment = GL11.glGetInteger(GL11.GL_UNPACK_ALIGNMENT);
|
||||||
|
int previousActiveTexture = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE);
|
||||||
|
GL13.glActiveTexture(GL13.GL_TEXTURE0);
|
||||||
|
int textureId = GL11.glGenTextures();
|
||||||
|
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
|
||||||
|
|
||||||
|
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
|
||||||
|
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
|
||||||
|
GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
|
||||||
|
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
|
||||||
|
GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
|
||||||
|
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
|
||||||
|
GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
|
||||||
|
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
|
||||||
|
GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
|
||||||
|
|
||||||
|
ByteBuffer buffer = BufferUtils.createByteBuffer(
|
||||||
|
atlas.getWidth() * atlas.getHeight() * 4);
|
||||||
|
byte[] coverage = atlas.getPixels();
|
||||||
|
for (int i = 0; i < coverage.length; i++) {
|
||||||
|
// RGBA is the most compatible fixed-function format: white RGB
|
||||||
|
// keeps the vertex colour, alpha carries the glyph coverage.
|
||||||
|
buffer.put((byte) 0xFF);
|
||||||
|
buffer.put((byte) 0xFF);
|
||||||
|
buffer.put((byte) 0xFF);
|
||||||
|
buffer.put(coverage[i]);
|
||||||
|
}
|
||||||
|
buffer.flip();
|
||||||
|
|
||||||
|
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA,
|
||||||
|
atlas.getWidth(), atlas.getHeight(), 0,
|
||||||
|
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
|
||||||
|
|
||||||
|
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, previousAlignment);
|
||||||
|
GL11.glBindTexture(GL11.GL_TEXTURE_2D, previousTexture);
|
||||||
|
GL13.glActiveTexture(previousActiveTexture);
|
||||||
|
return new V1_8_9FontTexture(textureId, atlas.getWidth(), atlas.getHeight());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Render2D createRender2D(FontManager fonts, Object platformContext) {
|
||||||
|
return new V1_8_9Render2D(fonts, runtimeInfo, resolver, minecraft, drawer, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getName() {
|
||||||
|
return "1.8.9/GL11";
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v1_8_9;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
import org.lwjgl.opengl.GL11;
|
||||||
|
|
||||||
|
public final class V1_8_9FontTexture implements FontTexture {
|
||||||
|
|
||||||
|
private final int textureId;
|
||||||
|
private final int width;
|
||||||
|
private final int height;
|
||||||
|
|
||||||
|
V1_8_9FontTexture(int textureId, int width, int height) {
|
||||||
|
this.textureId = textureId;
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getTextureId() {
|
||||||
|
return textureId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getHeight() {
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
GL11.glDeleteTextures(textureId);
|
||||||
|
}
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v1_8_9;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.font.Glyph;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.GlyphDrawer;
|
||||||
|
import org.lwjgl.opengl.GL11;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Immediate-mode glyph drawer for the legacy (1.8.9) OpenGL pipeline.
|
||||||
|
*/
|
||||||
|
final class V1_8_9GlyphDrawer implements GlyphDrawer {
|
||||||
|
|
||||||
|
private final V1_8_9RenderState state;
|
||||||
|
private int boundTexture = -1;
|
||||||
|
|
||||||
|
V1_8_9GlyphDrawer(V1_8_9RenderState state) {
|
||||||
|
this.state = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawGlyph(FontTexture texture, Glyph glyph,
|
||||||
|
double penX, double baseline, double scale, int argb) {
|
||||||
|
if (!(texture instanceof V1_8_9FontTexture)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.begin();
|
||||||
|
state.enableTexture();
|
||||||
|
|
||||||
|
int textureId = ((V1_8_9FontTexture) texture).getTextureId();
|
||||||
|
if (textureId != boundTexture) {
|
||||||
|
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
|
||||||
|
boundTexture = textureId;
|
||||||
|
}
|
||||||
|
state.setColor(argb);
|
||||||
|
|
||||||
|
double left = penX + glyph.getX0() * scale;
|
||||||
|
double right = penX + glyph.getX1() * scale;
|
||||||
|
double top = baseline + glyph.getY0() * scale;
|
||||||
|
double bottom = baseline + glyph.getY1() * scale;
|
||||||
|
|
||||||
|
GL11.glBegin(GL11.GL_QUADS);
|
||||||
|
GL11.glTexCoord2f(glyph.getU0(), glyph.getV0());
|
||||||
|
GL11.glVertex2d(left, top);
|
||||||
|
GL11.glTexCoord2f(glyph.getU0(), glyph.getV1());
|
||||||
|
GL11.glVertex2d(left, bottom);
|
||||||
|
GL11.glTexCoord2f(glyph.getU1(), glyph.getV1());
|
||||||
|
GL11.glVertex2d(right, bottom);
|
||||||
|
GL11.glTexCoord2f(glyph.getU1(), glyph.getV0());
|
||||||
|
GL11.glVertex2d(right, top);
|
||||||
|
GL11.glEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
boundTexture = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
+316
@@ -0,0 +1,316 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v1_8_9;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingClass;
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingMethod;
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingResolver;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontFace;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontFamily;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontManager;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.TrueTypeFontRenderer;
|
||||||
|
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
|
||||||
|
import org.lwjgl.BufferUtils;
|
||||||
|
import org.lwjgl.opengl.GL11;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.nio.IntBuffer;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 1.8.9 2D context. Coordinates are the vanilla {@code ScaledResolution}
|
||||||
|
* pixels, which matches the ortho set up by {@code GuiIngame#renderGameOverlay}.
|
||||||
|
*/
|
||||||
|
final class V1_8_9Render2D implements Render2D {
|
||||||
|
|
||||||
|
private static final String SCALED_RESOLUTION =
|
||||||
|
"net/minecraft/client/gui/ScaledResolution";
|
||||||
|
private static final int ARC_SEGMENTS = 8;
|
||||||
|
|
||||||
|
private final FontManager fonts;
|
||||||
|
private final double guiScale;
|
||||||
|
private final V1_8_9GlyphDrawer drawer;
|
||||||
|
private final V1_8_9RenderState state;
|
||||||
|
private final int width;
|
||||||
|
private final int height;
|
||||||
|
private final List<int[]> scissorStack = new ArrayList<int[]>();
|
||||||
|
private final IntBuffer scissorBuffer = BufferUtils.createIntBuffer(16);
|
||||||
|
|
||||||
|
V1_8_9Render2D(FontManager fonts, RuntimeInfo runtimeInfo,
|
||||||
|
MappingResolver resolver, Object minecraft,
|
||||||
|
V1_8_9GlyphDrawer drawer, V1_8_9RenderState state) {
|
||||||
|
this.fonts = fonts;
|
||||||
|
this.drawer = drawer;
|
||||||
|
this.state = state;
|
||||||
|
|
||||||
|
int resolvedWidth = 854;
|
||||||
|
int resolvedHeight = 480;
|
||||||
|
int resolvedScale = 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
MappingClass mappingClass = resolver.mapClass(SCALED_RESOLUTION);
|
||||||
|
Class<?> scaledClass = Class.forName(
|
||||||
|
mappingClass.getTargetName().replace('/', '.'),
|
||||||
|
false, runtimeInfo.getMinecraftClassLoader());
|
||||||
|
Constructor<?> constructor = scaledClass.getDeclaredConstructor(
|
||||||
|
minecraft.getClass());
|
||||||
|
constructor.setAccessible(true);
|
||||||
|
Object scaled = constructor.newInstance(minecraft);
|
||||||
|
|
||||||
|
Method widthMethod = method(scaledClass, resolver, "getScaledWidth", "()I");
|
||||||
|
Method heightMethod = method(scaledClass, resolver, "getScaledHeight", "()I");
|
||||||
|
Method scaleMethod = method(scaledClass, resolver, "getScaleFactor", "()I");
|
||||||
|
|
||||||
|
resolvedWidth = (Integer) widthMethod.invoke(scaled);
|
||||||
|
resolvedHeight = (Integer) heightMethod.invoke(scaled);
|
||||||
|
resolvedScale = (Integer) scaleMethod.invoke(scaled);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
System.err.println("[OrangeX] Failed to resolve ScaledResolution for 1.8.9: "
|
||||||
|
+ throwable);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.width = resolvedWidth;
|
||||||
|
this.height = resolvedHeight;
|
||||||
|
this.guiScale = Math.max(1, resolvedScale);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Method method(Class<?> owner, MappingResolver resolver,
|
||||||
|
String name, String descriptor) throws Exception {
|
||||||
|
MappingMethod mapping = resolver.mapMethod(
|
||||||
|
SCALED_RESOLUTION, name, descriptor);
|
||||||
|
Method method = owner.getDeclaredMethod(mapping.getTargetName());
|
||||||
|
method.setAccessible(true);
|
||||||
|
return method;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getHeight() {
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getGuiScale() {
|
||||||
|
return guiScale;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FontRenderer getFont(float size) {
|
||||||
|
return getFont(size, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FontRenderer getFont(float size, boolean bold) {
|
||||||
|
FontFace face = fonts.getFace(FontFamily.PROXIMA, size, bold, guiScale);
|
||||||
|
return new TrueTypeFontRenderer(fonts, face, bold, guiScale, drawer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillRect(double x, double y, double width, double height, int argb) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.begin();
|
||||||
|
state.disableTexture();
|
||||||
|
state.setColor(argb);
|
||||||
|
GL11.glBegin(GL11.GL_QUADS);
|
||||||
|
GL11.glVertex2d(x, y);
|
||||||
|
GL11.glVertex2d(x + width, y);
|
||||||
|
GL11.glVertex2d(x + width, y + height);
|
||||||
|
GL11.glVertex2d(x, y + height);
|
||||||
|
GL11.glEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillGradient(double x, double y, double width, double height,
|
||||||
|
int topArgb, int bottomArgb) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.begin();
|
||||||
|
state.disableTexture();
|
||||||
|
GL11.glShadeModel(GL11.GL_SMOOTH);
|
||||||
|
GL11.glBegin(GL11.GL_QUADS);
|
||||||
|
|
||||||
|
state.setColor(topArgb);
|
||||||
|
GL11.glVertex2d(x, y);
|
||||||
|
GL11.glVertex2d(x + width, y);
|
||||||
|
state.setColor(bottomArgb);
|
||||||
|
GL11.glVertex2d(x + width, y + height);
|
||||||
|
GL11.glVertex2d(x, y + height);
|
||||||
|
GL11.glEnd();
|
||||||
|
GL11.glShadeModel(GL11.GL_FLAT);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawRect(double x, double y, double width, double height,
|
||||||
|
double thickness, int argb) {
|
||||||
|
if (thickness <= 0.0 || width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fillRect(x, y, width, thickness, argb);
|
||||||
|
fillRect(x, y + height - thickness, width, thickness, argb);
|
||||||
|
fillRect(x, y + thickness, thickness, height - thickness * 2.0, argb);
|
||||||
|
fillRect(x + width - thickness, y + thickness,
|
||||||
|
thickness, height - thickness * 2.0, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillRoundedRect(double x, double y, double width, double height,
|
||||||
|
double radius, int argb) {
|
||||||
|
fillRoundedRectInternal(x, y, width, height, radius, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillRoundedRect(double x, double y, double width, double height,
|
||||||
|
double radius, double borderWidth,
|
||||||
|
int argb, int borderArgb) {
|
||||||
|
if (borderWidth <= 0.0) {
|
||||||
|
fillRoundedRectInternal(x, y, width, height, radius, argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fillRoundedRectInternal(x, y, width, height, radius, borderArgb);
|
||||||
|
double inner = Math.max(0.0, borderWidth);
|
||||||
|
double innerWidth = width - inner * 2.0;
|
||||||
|
double innerHeight = height - inner * 2.0;
|
||||||
|
if (innerWidth > 0.0 && innerHeight > 0.0) {
|
||||||
|
fillRoundedRectInternal(x + inner, y + inner,
|
||||||
|
innerWidth, innerHeight,
|
||||||
|
Math.max(0.0, radius - inner), argb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fillRoundedRectInternal(double x, double y, double width,
|
||||||
|
double height, double radius, int argb) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
double r = Math.min(radius, Math.min(width, height) / 2.0);
|
||||||
|
if (r <= 0.0) {
|
||||||
|
fillRect(x, y, width, height, argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<double[]> points = roundedRectPerimeter(x, y, width, height, r);
|
||||||
|
if (points.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
state.begin();
|
||||||
|
state.disableTexture();
|
||||||
|
state.setColor(argb);
|
||||||
|
GL11.glBegin(GL11.GL_TRIANGLE_FAN);
|
||||||
|
GL11.glVertex2d(x + width / 2.0, y + height / 2.0);
|
||||||
|
for (double[] point : points) {
|
||||||
|
GL11.glVertex2d(point[0], point[1]);
|
||||||
|
}
|
||||||
|
double[] first = points.get(0);
|
||||||
|
GL11.glVertex2d(first[0], first[1]);
|
||||||
|
GL11.glEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawLine(double x1, double y1, double x2, double y2,
|
||||||
|
double thickness, int argb) {
|
||||||
|
if (thickness <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
double dx = x2 - x1;
|
||||||
|
double dy = y2 - y1;
|
||||||
|
if (Math.abs(dy) < 0.01) {
|
||||||
|
fillRect(Math.min(x1, x2), y1 - thickness / 2.0,
|
||||||
|
Math.abs(dx), thickness, argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Math.abs(dx) < 0.01) {
|
||||||
|
fillRect(x1 - thickness / 2.0, Math.min(y1, y2),
|
||||||
|
thickness, Math.abs(dy), argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.begin();
|
||||||
|
state.disableTexture();
|
||||||
|
state.setColor(argb);
|
||||||
|
GL11.glLineWidth((float) thickness);
|
||||||
|
GL11.glBegin(GL11.GL_LINES);
|
||||||
|
GL11.glVertex2d(x1, y1);
|
||||||
|
GL11.glVertex2d(x2, y2);
|
||||||
|
GL11.glEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enableScissor(double x, double y, double width, double height) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.begin();
|
||||||
|
|
||||||
|
scissorBuffer.clear();
|
||||||
|
GL11.glGetInteger(GL11.GL_SCISSOR_BOX, scissorBuffer);
|
||||||
|
scissorStack.add(new int[]{
|
||||||
|
scissorBuffer.get(0), scissorBuffer.get(1),
|
||||||
|
scissorBuffer.get(2), scissorBuffer.get(3)
|
||||||
|
});
|
||||||
|
|
||||||
|
int scale = (int) Math.round(guiScale);
|
||||||
|
int sx = (int) Math.round(x * scale);
|
||||||
|
int sy = (int) Math.round((this.height - y - height) * scale);
|
||||||
|
int sw = (int) Math.round(width * scale);
|
||||||
|
int sh = (int) Math.round(height * scale);
|
||||||
|
|
||||||
|
GL11.glEnable(GL11.GL_SCISSOR_TEST);
|
||||||
|
GL11.glScissor(sx, sy, Math.max(0, sw), Math.max(0, sh));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void disableScissor() {
|
||||||
|
if (scissorStack.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int[] box = scissorStack.remove(scissorStack.size() - 1);
|
||||||
|
if (scissorStack.isEmpty()) {
|
||||||
|
GL11.glDisable(GL11.GL_SCISSOR_TEST);
|
||||||
|
} else {
|
||||||
|
GL11.glScissor(box[0], box[1], box[2], box[3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<double[]> roundedRectPerimeter(double x, double y,
|
||||||
|
double width, double height,
|
||||||
|
double radius) {
|
||||||
|
List<double[]> points = new ArrayList<double[]>();
|
||||||
|
double right = x + width;
|
||||||
|
double bottom = y + height;
|
||||||
|
|
||||||
|
addArc(points, x + radius, y + radius, radius, 180.0, 270.0);
|
||||||
|
addArc(points, right - radius, y + radius, radius, 270.0, 360.0);
|
||||||
|
addArc(points, right - radius, bottom - radius, radius, 0.0, 90.0);
|
||||||
|
addArc(points, x + radius, bottom - radius, radius, 90.0, 180.0);
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addArc(List<double[]> points, double centerX,
|
||||||
|
double centerY, double radius,
|
||||||
|
double startDegrees, double endDegrees) {
|
||||||
|
for (int i = 0; i <= ARC_SEGMENTS; i++) {
|
||||||
|
double angle = Math.toRadians(startDegrees
|
||||||
|
+ (endDegrees - startDegrees) * i / ARC_SEGMENTS);
|
||||||
|
points.add(new double[]{
|
||||||
|
centerX + Math.cos(angle) * radius,
|
||||||
|
centerY + Math.sin(angle) * radius
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void flush() {
|
||||||
|
state.end();
|
||||||
|
drawer.reset();
|
||||||
|
scissorStack.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
+137
@@ -0,0 +1,137 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v1_8_9;
|
||||||
|
|
||||||
|
import org.lwjgl.BufferUtils;
|
||||||
|
import org.lwjgl.opengl.GL11;
|
||||||
|
import org.lwjgl.opengl.GL13;
|
||||||
|
|
||||||
|
import java.nio.FloatBuffer;
|
||||||
|
import java.nio.IntBuffer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared fixed-function state for one 2D frame.
|
||||||
|
*
|
||||||
|
* <p>Shapes and glyphs both use this object so that interleaved draw calls do
|
||||||
|
* not save/restore each other's GL state. {@link #begin()} is idempotent and
|
||||||
|
* {@link #end()} restores the state that existed before the first draw.</p>
|
||||||
|
*/
|
||||||
|
final class V1_8_9RenderState {
|
||||||
|
|
||||||
|
private final FloatBuffer colorBuffer = BufferUtils.createFloatBuffer(16);
|
||||||
|
private final IntBuffer scissorBuffer = BufferUtils.createIntBuffer(16);
|
||||||
|
|
||||||
|
private boolean active;
|
||||||
|
private boolean previousBlend;
|
||||||
|
private boolean previousTexture2D;
|
||||||
|
private boolean previousAlphaTest;
|
||||||
|
private boolean previousDepthTest;
|
||||||
|
private boolean previousCullFace;
|
||||||
|
private boolean previousLighting;
|
||||||
|
private boolean previousFog;
|
||||||
|
private boolean previousScissorTest;
|
||||||
|
private int previousTexture;
|
||||||
|
private int previousTextureEnvMode;
|
||||||
|
private int previousActiveTexture;
|
||||||
|
private int previousShadeModel;
|
||||||
|
private float previousLineWidth;
|
||||||
|
private int previousScissorX;
|
||||||
|
private int previousScissorY;
|
||||||
|
private int previousScissorWidth;
|
||||||
|
private int previousScissorHeight;
|
||||||
|
|
||||||
|
void begin() {
|
||||||
|
if (active) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
active = true;
|
||||||
|
|
||||||
|
previousBlend = GL11.glIsEnabled(GL11.GL_BLEND);
|
||||||
|
previousTexture2D = GL11.glIsEnabled(GL11.GL_TEXTURE_2D);
|
||||||
|
previousAlphaTest = GL11.glIsEnabled(GL11.GL_ALPHA_TEST);
|
||||||
|
previousDepthTest = GL11.glIsEnabled(GL11.GL_DEPTH_TEST);
|
||||||
|
previousCullFace = GL11.glIsEnabled(GL11.GL_CULL_FACE);
|
||||||
|
previousLighting = GL11.glIsEnabled(GL11.GL_LIGHTING);
|
||||||
|
previousFog = GL11.glIsEnabled(GL11.GL_FOG);
|
||||||
|
previousScissorTest = GL11.glIsEnabled(GL11.GL_SCISSOR_TEST);
|
||||||
|
previousTextureEnvMode = GL11.glGetTexEnvi(
|
||||||
|
GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE);
|
||||||
|
previousShadeModel = GL11.glGetInteger(GL11.GL_SHADE_MODEL);
|
||||||
|
previousLineWidth = GL11.glGetFloat(GL11.GL_LINE_WIDTH);
|
||||||
|
previousActiveTexture = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE);
|
||||||
|
|
||||||
|
GL13.glActiveTexture(GL13.GL_TEXTURE0);
|
||||||
|
previousTexture = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
|
||||||
|
|
||||||
|
scissorBuffer.clear();
|
||||||
|
GL11.glGetInteger(GL11.GL_SCISSOR_BOX, scissorBuffer);
|
||||||
|
previousScissorX = scissorBuffer.get(0);
|
||||||
|
previousScissorY = scissorBuffer.get(1);
|
||||||
|
previousScissorWidth = scissorBuffer.get(2);
|
||||||
|
previousScissorHeight = scissorBuffer.get(3);
|
||||||
|
|
||||||
|
colorBuffer.clear();
|
||||||
|
GL11.glGetFloat(GL11.GL_CURRENT_COLOR, colorBuffer);
|
||||||
|
|
||||||
|
GL11.glEnable(GL11.GL_BLEND);
|
||||||
|
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
|
||||||
|
GL11.glDisable(GL11.GL_TEXTURE_2D);
|
||||||
|
GL11.glDisable(GL11.GL_ALPHA_TEST);
|
||||||
|
GL11.glDisable(GL11.GL_DEPTH_TEST);
|
||||||
|
GL11.glDisable(GL11.GL_CULL_FACE);
|
||||||
|
GL11.glDisable(GL11.GL_LIGHTING);
|
||||||
|
GL11.glDisable(GL11.GL_FOG);
|
||||||
|
GL11.glDisable(GL11.GL_SCISSOR_TEST);
|
||||||
|
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
|
||||||
|
GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
void end() {
|
||||||
|
if (!active) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
active = false;
|
||||||
|
|
||||||
|
GL11.glBindTexture(GL11.GL_TEXTURE_2D, previousTexture);
|
||||||
|
GL11.glColor4f(colorBuffer.get(0), colorBuffer.get(1),
|
||||||
|
colorBuffer.get(2), colorBuffer.get(3));
|
||||||
|
setEnabled(GL11.GL_BLEND, previousBlend);
|
||||||
|
setEnabled(GL11.GL_TEXTURE_2D, previousTexture2D);
|
||||||
|
setEnabled(GL11.GL_ALPHA_TEST, previousAlphaTest);
|
||||||
|
setEnabled(GL11.GL_DEPTH_TEST, previousDepthTest);
|
||||||
|
setEnabled(GL11.GL_CULL_FACE, previousCullFace);
|
||||||
|
setEnabled(GL11.GL_LIGHTING, previousLighting);
|
||||||
|
setEnabled(GL11.GL_FOG, previousFog);
|
||||||
|
setEnabled(GL11.GL_SCISSOR_TEST, previousScissorTest);
|
||||||
|
GL11.glScissor(previousScissorX, previousScissorY,
|
||||||
|
previousScissorWidth, previousScissorHeight);
|
||||||
|
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
|
||||||
|
GL11.GL_TEXTURE_ENV_MODE, previousTextureEnvMode);
|
||||||
|
GL11.glShadeModel(previousShadeModel);
|
||||||
|
GL11.glLineWidth(previousLineWidth);
|
||||||
|
GL13.glActiveTexture(previousActiveTexture);
|
||||||
|
}
|
||||||
|
|
||||||
|
void enableTexture() {
|
||||||
|
GL11.glEnable(GL11.GL_TEXTURE_2D);
|
||||||
|
}
|
||||||
|
|
||||||
|
void disableTexture() {
|
||||||
|
GL11.glDisable(GL11.GL_TEXTURE_2D);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setColor(int argb) {
|
||||||
|
GL11.glColor4f(
|
||||||
|
((argb >> 16) & 0xFF) / 255.0f,
|
||||||
|
((argb >> 8) & 0xFF) / 255.0f,
|
||||||
|
(argb & 0xFF) / 255.0f,
|
||||||
|
((argb >>> 24) & 0xFF) / 255.0f
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void setEnabled(int capability, boolean enabled) {
|
||||||
|
if (enabled) {
|
||||||
|
GL11.glEnable(capability);
|
||||||
|
} else {
|
||||||
|
GL11.glDisable(capability);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v26_2;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontAtlas;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontManager;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontBackend;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 26.x backend.
|
||||||
|
*
|
||||||
|
* <p>The atlas is expanded to RGBA (white RGB + coverage alpha) and wrapped in
|
||||||
|
* a {@code DynamicTexture}. Glyph drawing is deferred through
|
||||||
|
* {@code GuiRenderState}, so no raw OpenGL calls are made here.</p>
|
||||||
|
*/
|
||||||
|
public final class V26_2FontBackend implements FontBackend {
|
||||||
|
|
||||||
|
private final ClassLoader loader;
|
||||||
|
private final V26_2ShapeCache shapes;
|
||||||
|
|
||||||
|
public V26_2FontBackend(RuntimeInfo runtimeInfo) {
|
||||||
|
this.loader = runtimeInfo.getMinecraftClassLoader();
|
||||||
|
this.shapes = new V26_2ShapeCache(loader);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FontTexture createTexture(FontAtlas atlas) {
|
||||||
|
int width = atlas.getWidth();
|
||||||
|
int height = atlas.getHeight();
|
||||||
|
byte[] coverage = atlas.getPixels();
|
||||||
|
|
||||||
|
byte[] rgba = new byte[coverage.length * 4];
|
||||||
|
for (int i = 0, j = 0; i < coverage.length; i++, j += 4) {
|
||||||
|
rgba[j] = (byte) 0xFF;
|
||||||
|
rgba[j + 1] = (byte) 0xFF;
|
||||||
|
rgba[j + 2] = (byte) 0xFF;
|
||||||
|
rgba[j + 3] = coverage[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
V26_2GpuTexture texture = V26_2TextureHelper.create(
|
||||||
|
loader, width, height, rgba);
|
||||||
|
return new V26_2FontTexture(texture.texture, texture.textureView,
|
||||||
|
texture.sampler, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Render2D createRender2D(FontManager fonts, Object platformContext) {
|
||||||
|
return new V26_2Render2D(fonts, platformContext, loader, shapes);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getName() {
|
||||||
|
return "26.2/GuiRenderState";
|
||||||
|
}
|
||||||
|
}
|
||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v26_2;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps a 26.x {@code DynamicTexture}. All fields are kept as {@link Object}
|
||||||
|
* because OrangeX is compiled against Java 8 without Mojang/LWJGL3 on the
|
||||||
|
* compile classpath.
|
||||||
|
*/
|
||||||
|
public final class V26_2FontTexture implements FontTexture {
|
||||||
|
|
||||||
|
private final Object texture;
|
||||||
|
private final Object textureView;
|
||||||
|
private final Object sampler;
|
||||||
|
private final int width;
|
||||||
|
private final int height;
|
||||||
|
|
||||||
|
V26_2FontTexture(Object texture, Object textureView, Object sampler,
|
||||||
|
int width, int height) {
|
||||||
|
this.texture = texture;
|
||||||
|
this.textureView = textureView;
|
||||||
|
this.sampler = sampler;
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object getTexture() {
|
||||||
|
return texture;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object getTextureView() {
|
||||||
|
return textureView;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object getSampler() {
|
||||||
|
return sampler;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getHeight() {
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
try {
|
||||||
|
texture.getClass().getMethod("close").invoke(texture);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
System.err.println("[OrangeX] Failed to close a 26.2 font texture: "
|
||||||
|
+ throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v26_2;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.font.Glyph;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.GlyphDrawer;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds one deferred blit per glyph to the 26.x {@code GuiRenderState}.
|
||||||
|
*/
|
||||||
|
final class V26_2GlyphDrawer implements GlyphDrawer {
|
||||||
|
|
||||||
|
private final Object extractor;
|
||||||
|
private final Method innerBlit;
|
||||||
|
private final Object guiPipeline;
|
||||||
|
|
||||||
|
V26_2GlyphDrawer(Object extractor, Method innerBlit, Object guiPipeline) {
|
||||||
|
this.extractor = extractor;
|
||||||
|
this.innerBlit = innerBlit;
|
||||||
|
this.guiPipeline = guiPipeline;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawGlyph(FontTexture texture, Glyph glyph,
|
||||||
|
double penX, double baseline, double scale, int argb) {
|
||||||
|
if (!(texture instanceof V26_2FontTexture)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int x0 = (int) Math.round(penX + glyph.getX0() * scale);
|
||||||
|
int y0 = (int) Math.round(baseline + glyph.getY0() * scale);
|
||||||
|
int x1 = (int) Math.round(penX + glyph.getX1() * scale);
|
||||||
|
int y1 = (int) Math.round(baseline + glyph.getY1() * scale);
|
||||||
|
if (x1 <= x0 || y1 <= y0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
V26_2FontTexture fontTexture = (V26_2FontTexture) texture;
|
||||||
|
try {
|
||||||
|
innerBlit.invoke(extractor, guiPipeline,
|
||||||
|
fontTexture.getTextureView(), fontTexture.getSampler(),
|
||||||
|
x0, y0, x1, y1,
|
||||||
|
glyph.getU0(), glyph.getU1(),
|
||||||
|
glyph.getV0(), glyph.getV1(),
|
||||||
|
argb);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException("Failed to submit a GUI glyph", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v26_2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reflective holder for a 26.x GPU texture and its sampler.
|
||||||
|
*/
|
||||||
|
final class V26_2GpuTexture {
|
||||||
|
|
||||||
|
final Object texture;
|
||||||
|
final Object textureView;
|
||||||
|
final Object sampler;
|
||||||
|
final int width;
|
||||||
|
final int height;
|
||||||
|
|
||||||
|
V26_2GpuTexture(Object texture, Object textureView, Object sampler,
|
||||||
|
int width, int height) {
|
||||||
|
this.texture = texture;
|
||||||
|
this.textureView = textureView;
|
||||||
|
this.sampler = sampler;
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
}
|
||||||
|
}
|
||||||
+331
@@ -0,0 +1,331 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v26_2;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.Render2D;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontFace;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontFamily;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.FontManager;
|
||||||
|
import cn.xiaozhou233.orangex.render.font.TrueTypeFontRenderer;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 26.x 2D context.
|
||||||
|
*
|
||||||
|
* <p>26.x no longer exposes {@code GuiGraphics}; the GUI is collected into a
|
||||||
|
* {@code GuiRenderState} by {@code Gui#extractRenderState}. The render hook
|
||||||
|
* passes that {@code Gui} instance in, and this class creates a private
|
||||||
|
* {@code GuiGraphicsExtractor} over the same render state to queue glyph
|
||||||
|
* blits.</p>
|
||||||
|
*/
|
||||||
|
final class V26_2Render2D implements Render2D {
|
||||||
|
|
||||||
|
private final FontManager fonts;
|
||||||
|
private final V26_2GlyphDrawer drawer;
|
||||||
|
private final Object extractor;
|
||||||
|
private final Method innerBlit;
|
||||||
|
private final Object guiPipeline;
|
||||||
|
private final Method fillMethod;
|
||||||
|
private final Method fillGradientMethod;
|
||||||
|
private final Method enableScissorMethod;
|
||||||
|
private final Method disableScissorMethod;
|
||||||
|
private final V26_2ShapeCache shapes;
|
||||||
|
private final int width;
|
||||||
|
private final int height;
|
||||||
|
private final double guiScale;
|
||||||
|
|
||||||
|
V26_2Render2D(FontManager fonts, Object gui, ClassLoader loader,
|
||||||
|
V26_2ShapeCache shapes) {
|
||||||
|
this.fonts = fonts;
|
||||||
|
this.shapes = shapes;
|
||||||
|
|
||||||
|
try {
|
||||||
|
Field minecraftField = field(gui.getClass(), "minecraft");
|
||||||
|
Object minecraft = minecraftField.get(gui);
|
||||||
|
|
||||||
|
Field renderStateField = field(gui.getClass(), "guiRenderState");
|
||||||
|
Object guiRenderState = renderStateField.get(gui);
|
||||||
|
|
||||||
|
Class<?> renderStateClass = Class.forName(
|
||||||
|
"net.minecraft.client.renderer.state.gui.GuiRenderState",
|
||||||
|
false, loader);
|
||||||
|
Class<?> extractorClass = Class.forName(
|
||||||
|
"net.minecraft.client.gui.GuiGraphicsExtractor",
|
||||||
|
false, loader);
|
||||||
|
|
||||||
|
Constructor<?> extractorConstructor = extractorClass.getDeclaredConstructor(
|
||||||
|
minecraft.getClass(), renderStateClass, int.class, int.class);
|
||||||
|
extractorConstructor.setAccessible(true);
|
||||||
|
Object extractor = extractorConstructor.newInstance(
|
||||||
|
minecraft, guiRenderState, 0, 0);
|
||||||
|
|
||||||
|
Object window = minecraft.getClass().getMethod("getWindow").invoke(minecraft);
|
||||||
|
this.width = (Integer) window.getClass().getMethod("getGuiScaledWidth")
|
||||||
|
.invoke(window);
|
||||||
|
this.height = (Integer) window.getClass().getMethod("getGuiScaledHeight")
|
||||||
|
.invoke(window);
|
||||||
|
this.guiScale = Math.max(1, (Integer) window.getClass()
|
||||||
|
.getMethod("getGuiScale").invoke(window));
|
||||||
|
|
||||||
|
Class<?> pipelineClass = Class.forName(
|
||||||
|
"com.mojang.blaze3d.pipeline.RenderPipeline", false, loader);
|
||||||
|
Class<?> textureViewClass = Class.forName(
|
||||||
|
"com.mojang.blaze3d.textures.GpuTextureView", false, loader);
|
||||||
|
Class<?> samplerClass = Class.forName(
|
||||||
|
"com.mojang.blaze3d.textures.GpuSampler", false, loader);
|
||||||
|
|
||||||
|
Object guiPipeline = Class.forName(
|
||||||
|
"net.minecraft.client.renderer.RenderPipelines", false, loader)
|
||||||
|
.getField("GUI_TEXTURED").get(null);
|
||||||
|
|
||||||
|
Method innerBlit = extractorClass.getDeclaredMethod("innerBlit",
|
||||||
|
pipelineClass, textureViewClass, samplerClass,
|
||||||
|
int.class, int.class, int.class, int.class,
|
||||||
|
float.class, float.class, float.class, float.class,
|
||||||
|
int.class);
|
||||||
|
innerBlit.setAccessible(true);
|
||||||
|
|
||||||
|
this.extractor = extractor;
|
||||||
|
this.innerBlit = innerBlit;
|
||||||
|
this.guiPipeline = guiPipeline;
|
||||||
|
this.fillMethod = extractorClass.getMethod("fill",
|
||||||
|
int.class, int.class, int.class, int.class, int.class);
|
||||||
|
this.fillGradientMethod = extractorClass.getMethod("fillGradient",
|
||||||
|
int.class, int.class, int.class, int.class,
|
||||||
|
int.class, int.class);
|
||||||
|
this.enableScissorMethod = extractorClass.getMethod("enableScissor",
|
||||||
|
int.class, int.class, int.class, int.class);
|
||||||
|
this.disableScissorMethod = extractorClass.getMethod("disableScissor");
|
||||||
|
this.drawer = new V26_2GlyphDrawer(extractor, innerBlit, guiPipeline);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException(
|
||||||
|
"Cannot initialise the 26.2 GUI font context", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Field field(Class<?> owner, String name) throws Exception {
|
||||||
|
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 NoSuchFieldException(name + " on " + owner.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getHeight() {
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getGuiScale() {
|
||||||
|
return guiScale;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FontRenderer getFont(float size) {
|
||||||
|
return getFont(size, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public FontRenderer getFont(float size, boolean bold) {
|
||||||
|
FontFace face = fonts.getFace(FontFamily.PROXIMA, size, bold, guiScale);
|
||||||
|
return new TrueTypeFontRenderer(fonts, face, bold, guiScale, drawer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillRect(double x, double y, double width, double height, int argb) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int x0 = (int) Math.round(x);
|
||||||
|
int y0 = (int) Math.round(y);
|
||||||
|
int x1 = (int) Math.round(x + width);
|
||||||
|
int y1 = (int) Math.round(y + height);
|
||||||
|
invokeFill(x0, y0, x1, y1, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillGradient(double x, double y, double width, double height,
|
||||||
|
int topArgb, int bottomArgb) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
fillGradientMethod.invoke(extractor,
|
||||||
|
(int) Math.round(x), (int) Math.round(y),
|
||||||
|
(int) Math.round(x + width), (int) Math.round(y + height),
|
||||||
|
topArgb, bottomArgb);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException("Failed to draw a GUI gradient", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawRect(double x, double y, double width, double height,
|
||||||
|
double thickness, int argb) {
|
||||||
|
if (thickness <= 0.0 || width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fillRect(x, y, width, thickness, argb);
|
||||||
|
fillRect(x, y + height - thickness, width, thickness, argb);
|
||||||
|
fillRect(x, y + thickness, thickness, height - thickness * 2.0, argb);
|
||||||
|
fillRect(x + width - thickness, y + thickness,
|
||||||
|
thickness, height - thickness * 2.0, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillRoundedRect(double x, double y, double width, double height,
|
||||||
|
double radius, int argb) {
|
||||||
|
fillRoundedRectInternal(x, y, width, height, radius, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void fillRoundedRect(double x, double y, double width, double height,
|
||||||
|
double radius, double borderWidth,
|
||||||
|
int argb, int borderArgb) {
|
||||||
|
if (borderWidth <= 0.0) {
|
||||||
|
fillRoundedRectInternal(x, y, width, height, radius, argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fillRoundedRectInternal(x, y, width, height, radius, borderArgb);
|
||||||
|
double inset = Math.max(0.0, borderWidth);
|
||||||
|
double innerWidth = width - inset * 2.0;
|
||||||
|
double innerHeight = height - inset * 2.0;
|
||||||
|
if (innerWidth > 0.0 && innerHeight > 0.0) {
|
||||||
|
fillRoundedRectInternal(x + inset, y + inset,
|
||||||
|
innerWidth, innerHeight,
|
||||||
|
Math.max(0.0, radius - inset), argb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fillRoundedRectInternal(double x, double y, double width,
|
||||||
|
double height, double radius, int argb) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
double clamped = Math.min(radius, Math.min(width, height) / 2.0);
|
||||||
|
if (clamped <= 0.5) {
|
||||||
|
fillRect(x, y, width, height, argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int x0 = (int) Math.round(x);
|
||||||
|
int y0 = (int) Math.round(y);
|
||||||
|
int x1 = (int) Math.round(x + width);
|
||||||
|
int y1 = (int) Math.round(y + height);
|
||||||
|
int corner = Math.max(1, (int) Math.round(clamped));
|
||||||
|
corner = Math.min(corner, Math.min((x1 - x0) / 2, (y1 - y0) / 2));
|
||||||
|
if (corner <= 0) {
|
||||||
|
fillRect(x, y, width, height, argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Straight strips.
|
||||||
|
invokeFill(x0 + corner, y0, x1 - corner, y0 + corner, argb);
|
||||||
|
invokeFill(x0 + corner, y1 - corner, x1 - corner, y1, argb);
|
||||||
|
invokeFill(x0 + corner, y0 + corner, x1 - corner, y1 - corner, argb);
|
||||||
|
invokeFill(x0, y0 + corner, x0 + corner, y1 - corner, argb);
|
||||||
|
invokeFill(x1 - corner, y0 + corner, x1, y1 - corner, argb);
|
||||||
|
|
||||||
|
int radiusPixels = Math.max(2, (int) Math.round(clamped * guiScale));
|
||||||
|
V26_2GpuTexture texture = shapes.corner(radiusPixels);
|
||||||
|
|
||||||
|
// Antialiased quarter-circle corners. Flipping U/V mirrors the same
|
||||||
|
// texture for the other three corners.
|
||||||
|
invokeBlit(texture, x0, y0, x0 + corner, y0 + corner,
|
||||||
|
0.0f, 0.0f, 1.0f, 1.0f, argb);
|
||||||
|
invokeBlit(texture, x1 - corner, y0, x1, y0 + corner,
|
||||||
|
1.0f, 0.0f, 0.0f, 1.0f, argb);
|
||||||
|
invokeBlit(texture, x0, y1 - corner, x0 + corner, y1,
|
||||||
|
0.0f, 1.0f, 1.0f, 0.0f, argb);
|
||||||
|
invokeBlit(texture, x1 - corner, y1 - corner, x1, y1,
|
||||||
|
1.0f, 1.0f, 0.0f, 0.0f, argb);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void drawLine(double x1, double y1, double x2, double y2,
|
||||||
|
double thickness, int argb) {
|
||||||
|
if (thickness <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
double dx = x2 - x1;
|
||||||
|
double dy = y2 - y1;
|
||||||
|
if (Math.abs(dy) < 0.01) {
|
||||||
|
fillRect(Math.min(x1, x2), y1 - thickness / 2.0,
|
||||||
|
Math.abs(dx), thickness, argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Math.abs(dx) < 0.01) {
|
||||||
|
fillRect(x1 - thickness / 2.0, Math.min(y1, y2),
|
||||||
|
thickness, Math.abs(dy), argb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int steps = (int) Math.ceil(Math.max(Math.abs(dx), Math.abs(dy)));
|
||||||
|
for (int i = 0; i <= steps; i++) {
|
||||||
|
double t = steps == 0 ? 0.0 : (double) i / (double) steps;
|
||||||
|
fillRect(x1 + dx * t - thickness / 2.0,
|
||||||
|
y1 + dy * t - thickness / 2.0,
|
||||||
|
thickness, thickness, argb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enableScissor(double x, double y, double width, double height) {
|
||||||
|
if (width <= 0.0 || height <= 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
enableScissorMethod.invoke(extractor,
|
||||||
|
(int) Math.round(x), (int) Math.round(y),
|
||||||
|
(int) Math.round(x + width), (int) Math.round(y + height));
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException("Failed to enable a GUI scissor", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void disableScissor() {
|
||||||
|
try {
|
||||||
|
disableScissorMethod.invoke(extractor);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException("Failed to disable a GUI scissor", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void invokeFill(int x0, int y0, int x1, int y1, int argb) {
|
||||||
|
try {
|
||||||
|
fillMethod.invoke(extractor, x0, y0, x1, y1, argb);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException("Failed to draw a GUI rectangle", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void invokeBlit(V26_2GpuTexture texture, int x0, int y0, int x1, int y1,
|
||||||
|
float u0, float v0, float u1, float v1, int argb) {
|
||||||
|
try {
|
||||||
|
innerBlit.invoke(extractor, guiPipeline,
|
||||||
|
texture.textureView, texture.sampler,
|
||||||
|
x0, y0, x1, y1, u0, u1, v0, v1, argb);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException("Failed to draw a GUI corner", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void flush() {
|
||||||
|
// Everything was submitted to the GuiRenderState; nothing to restore.
|
||||||
|
}
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v26_2;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Caches white quarter-circle corner textures used to assemble rounded
|
||||||
|
* rectangles through the 26.x GUI blit pipeline.
|
||||||
|
*/
|
||||||
|
final class V26_2ShapeCache {
|
||||||
|
|
||||||
|
private final ClassLoader loader;
|
||||||
|
private final Map<Integer, V26_2GpuTexture> corners =
|
||||||
|
new HashMap<Integer, V26_2GpuTexture>();
|
||||||
|
|
||||||
|
V26_2ShapeCache(ClassLoader loader) {
|
||||||
|
this.loader = loader;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized V26_2GpuTexture corner(int radiusPixels) {
|
||||||
|
int radius = Math.max(2, radiusPixels);
|
||||||
|
V26_2GpuTexture cached = corners.get(radius);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
int size = radius;
|
||||||
|
byte[] rgba = new byte[size * size * 4];
|
||||||
|
for (int y = 0; y < size; y++) {
|
||||||
|
for (int x = 0; x < size; x++) {
|
||||||
|
double dx = radius - (x + 0.5);
|
||||||
|
double dy = radius - (y + 0.5);
|
||||||
|
double distance = Math.sqrt(dx * dx + dy * dy);
|
||||||
|
float coverage = (float) clamp(radius - distance + 0.5, 0.0, 1.0);
|
||||||
|
|
||||||
|
int offset = (y * size + x) * 4;
|
||||||
|
rgba[offset] = (byte) 0xFF;
|
||||||
|
rgba[offset + 1] = (byte) 0xFF;
|
||||||
|
rgba[offset + 2] = (byte) 0xFF;
|
||||||
|
rgba[offset + 3] = (byte) Math.round(coverage * 255.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
V26_2GpuTexture texture = V26_2TextureHelper.create(
|
||||||
|
loader, size, size, rgba);
|
||||||
|
corners.put(radius, texture);
|
||||||
|
return texture;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double clamp(double value, double min, double max) {
|
||||||
|
return Math.max(min, Math.min(max, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.internal.v26_2;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a {@code DynamicTexture} from an RGBA byte array without linking
|
||||||
|
* against Mojang's classes.
|
||||||
|
*/
|
||||||
|
final class V26_2TextureHelper {
|
||||||
|
|
||||||
|
static V26_2GpuTexture create(ClassLoader loader, int width, int height,
|
||||||
|
byte[] rgba) {
|
||||||
|
try {
|
||||||
|
Class<?> nativeImageClass = Class.forName(
|
||||||
|
"com.mojang.blaze3d.platform.NativeImage", false, loader);
|
||||||
|
Constructor<?> nativeImageConstructor = nativeImageClass
|
||||||
|
.getDeclaredConstructor(int.class, int.class, boolean.class);
|
||||||
|
Object image = nativeImageConstructor.newInstance(width, height, false);
|
||||||
|
|
||||||
|
ByteBuffer buffer = (ByteBuffer) nativeImageClass
|
||||||
|
.getMethod("getPixelBytes").invoke(image);
|
||||||
|
buffer.put(rgba);
|
||||||
|
|
||||||
|
Class<?> dynamicTextureClass = Class.forName(
|
||||||
|
"net.minecraft.client.renderer.texture.DynamicTexture", false, loader);
|
||||||
|
Constructor<?> dynamicTextureConstructor = dynamicTextureClass
|
||||||
|
.getDeclaredConstructor(Supplier.class, nativeImageClass);
|
||||||
|
Object texture = dynamicTextureConstructor.newInstance(
|
||||||
|
new Supplier<String>() {
|
||||||
|
@Override
|
||||||
|
public String get() {
|
||||||
|
return "OrangeX texture";
|
||||||
|
}
|
||||||
|
},
|
||||||
|
image);
|
||||||
|
|
||||||
|
Object textureView = dynamicTextureClass.getMethod("getTextureView")
|
||||||
|
.invoke(texture);
|
||||||
|
Object sampler = dynamicTextureClass.getMethod("getSampler")
|
||||||
|
.invoke(texture);
|
||||||
|
return new V26_2GpuTexture(texture, textureView, sampler, width, height);
|
||||||
|
} catch (Throwable throwable) {
|
||||||
|
throw new IllegalStateException("Cannot create a 26.2 texture", throwable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private V26_2TextureHelper() {
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,431 @@
|
|||||||
|
# 示例:Hook onTick
|
||||||
|
|
||||||
|
本文用一个最小示例演示 **“把事件调用注入到 Minecraft tick 方法”** 的完整流程,包括:
|
||||||
|
|
||||||
|
- hook 和 EventBus 分别负责什么;
|
||||||
|
- 用自研事件跑通注入;
|
||||||
|
- 改用 greenrobot EventBus;
|
||||||
|
- hook 没触发时怎么排查。
|
||||||
|
|
||||||
|
> 仅为示例,省略了版本差异、异常隔离、线程安全、监听器快路径等生产细节。
|
||||||
|
> 项目里的实际实现(HookManager / ClassHook / ClassPoolUtils)见 [hooks.md](hooks.md)。
|
||||||
|
|
||||||
|
## 1. 先理解“触发”
|
||||||
|
|
||||||
|
EventBus 只负责分发,它不会自己产生事件。真正让事件发生的,是你在游戏方法里插入的那行 `post`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Minecraft.runTick() ← 游戏每 tick 自己调用
|
||||||
|
│
|
||||||
|
├── TickEvents.firePre() ← 你插进去的一行
|
||||||
|
│ └── EventBus.post(new TickEvent(true))
|
||||||
|
│ └── 回调 @Subscribe onTick(...)
|
||||||
|
│
|
||||||
|
├── 原来的 runTick 方法体
|
||||||
|
│
|
||||||
|
└── TickEvents.firePost()
|
||||||
|
```
|
||||||
|
|
||||||
|
可以这样理解:
|
||||||
|
|
||||||
|
- **EventBus** = 广播站,负责把事件发给监听器。
|
||||||
|
- **hook / 注入** = 在游戏代码里装一个按钮,游戏走到那里就按下按钮。
|
||||||
|
- 没有注入,就没有 `post`;没有 `post`,EventBus 就没有东西可分发。
|
||||||
|
|
||||||
|
所以完整链路永远是:
|
||||||
|
|
||||||
|
```text
|
||||||
|
字节码注入 → 游戏调用被改写的方法 → post → EventBus 分发 → 监听器
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. 方案 A:最小自研事件
|
||||||
|
|
||||||
|
### 2.1 事件
|
||||||
|
|
||||||
|
```java
|
||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
|
||||||
|
public final class TickEvent {
|
||||||
|
|
||||||
|
public interface Listener {
|
||||||
|
void onTick(TickEvent event);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final List<Listener> LISTENERS = new CopyOnWriteArrayList<>();
|
||||||
|
|
||||||
|
private final boolean pre;
|
||||||
|
|
||||||
|
private TickEvent(boolean pre) {
|
||||||
|
this.pre = pre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPre() {
|
||||||
|
return pre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void register(Listener listener) {
|
||||||
|
LISTENERS.add(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void firePre() {
|
||||||
|
fire(new TickEvent(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void firePost() {
|
||||||
|
fire(new TickEvent(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void fire(TickEvent event) {
|
||||||
|
for (Listener listener : LISTENERS) {
|
||||||
|
try {
|
||||||
|
listener.onTick(event);
|
||||||
|
} catch (Throwable ignored) {
|
||||||
|
// 示例:真实实现应记录日志
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 注入器(Javassist)
|
||||||
|
|
||||||
|
把 `runTick()` 改写成:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public void runTick() {
|
||||||
|
TickEvent.firePre();
|
||||||
|
// ... 原方法体 ...
|
||||||
|
TickEvent.firePost();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```java
|
||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingClass;
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingManager;
|
||||||
|
import cn.xiaozhou233.orangex.mapping.MappingMethod;
|
||||||
|
import javassist.ClassPool;
|
||||||
|
import javassist.CtClass;
|
||||||
|
import javassist.CtMethod;
|
||||||
|
import javassist.LoaderClassPath;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
|
||||||
|
public final class TickHook {
|
||||||
|
|
||||||
|
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
|
||||||
|
private static final String RUN_TICK = "runTick";
|
||||||
|
private static final String RUN_TICK_DESC = "()V";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return 改写后的字节码;返回 null 表示不处理这个类
|
||||||
|
*/
|
||||||
|
public static byte[] transform(ClassLoader loader, String className, byte[] classBytes) {
|
||||||
|
if (className == null || !MINECRAFT.replace('.', '/').equals(className)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 用 MappingResolver 拿到当前运行时的真实类名/方法名,
|
||||||
|
// 不要硬编码混淆名。
|
||||||
|
MappingClass mc = MappingManager.getResolver().mapClass(MINECRAFT);
|
||||||
|
MappingMethod runTick = mc.getMethod(RUN_TICK, RUN_TICK_DESC);
|
||||||
|
if (runTick == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
ClassPool pool = ClassPool.getDefault();
|
||||||
|
pool.appendClassPath(new LoaderClassPath(loader));
|
||||||
|
|
||||||
|
CtClass cc = pool.makeClass(new ByteArrayInputStream(classBytes), false);
|
||||||
|
CtMethod method = cc.getMethod(
|
||||||
|
runTick.getTargetName(),
|
||||||
|
runTick.getTargetDescriptor()
|
||||||
|
);
|
||||||
|
|
||||||
|
// 不要写全限定名,原因见 3.7
|
||||||
|
pool.importPackage("cn.xiaozhou233.orangex.hook");
|
||||||
|
method.insertBefore("TickEvent.firePre();");
|
||||||
|
method.insertAfter("TickEvent.firePost();");
|
||||||
|
|
||||||
|
byte[] result = cc.toBytecode();
|
||||||
|
cc.detach(); // 避免 ClassPool 一直持有这个类
|
||||||
|
return result;
|
||||||
|
} catch (Throwable t) {
|
||||||
|
t.printStackTrace();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 注册到类加载流程
|
||||||
|
|
||||||
|
```java
|
||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import java.lang.instrument.ClassFileTransformer;
|
||||||
|
import java.lang.instrument.Instrumentation;
|
||||||
|
import java.security.ProtectionDomain;
|
||||||
|
|
||||||
|
public final class TickTransformer implements ClassFileTransformer {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] transform(ClassLoader loader,
|
||||||
|
String className,
|
||||||
|
Class<?> classBeingRedefined,
|
||||||
|
ProtectionDomain protectionDomain,
|
||||||
|
byte[] classfileBuffer) {
|
||||||
|
return TickHook.transform(loader, className, classfileBuffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void install(Instrumentation instrumentation) {
|
||||||
|
// true = 允许 retransform 已经加载过的类
|
||||||
|
instrumentation.addTransformer(new TickTransformer(), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> 工程里 `Instrumentation` 由 JuiceAgent/Loader 提供,这里只展示挂载点。
|
||||||
|
> 如果目标类已经加载,还需要 `instrumentation.retransformClasses(minecraftClass);`。
|
||||||
|
|
||||||
|
### 2.4 使用
|
||||||
|
|
||||||
|
```java
|
||||||
|
TickEvent.register(event -> {
|
||||||
|
if (event.isPre()) {
|
||||||
|
System.out.println("tick 开始");
|
||||||
|
} else {
|
||||||
|
System.out.println("tick 结束");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. 方案 B:greenrobot EventBus
|
||||||
|
|
||||||
|
EventBus 只替换“分发”这一层,注入部分不变。
|
||||||
|
|
||||||
|
### 3.1 依赖
|
||||||
|
|
||||||
|
```gradle
|
||||||
|
dependencies {
|
||||||
|
implementation 'org.greenrobot:eventbus:3.3.1'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
和 gson、javassist 一样做 relocate,避免和游戏/其他 Mod 冲突:
|
||||||
|
|
||||||
|
```gradle
|
||||||
|
shadowJar {
|
||||||
|
relocate 'com.google.gson', 'cn.xiaozhou233.orangex.shaded.gson'
|
||||||
|
relocate 'org.javassist', 'cn.xiaozhou233.orangex.shaded.javassist'
|
||||||
|
relocate 'org.greenrobot.eventbus', 'cn.xiaozhou233.orangex.shaded.eventbus'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 事件
|
||||||
|
|
||||||
|
```java
|
||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
public final class TickEvent {
|
||||||
|
|
||||||
|
private final boolean pre;
|
||||||
|
|
||||||
|
public TickEvent(boolean pre) {
|
||||||
|
this.pre = pre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPre() {
|
||||||
|
return pre;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 监听器
|
||||||
|
|
||||||
|
```java
|
||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import org.greenrobot.eventbus.Subscribe;
|
||||||
|
import org.greenrobot.eventbus.ThreadMode;
|
||||||
|
|
||||||
|
public final class TickListener {
|
||||||
|
|
||||||
|
@Subscribe(threadMode = ThreadMode.POSTING)
|
||||||
|
public void onTick(TickEvent event) {
|
||||||
|
if (event.isPre()) {
|
||||||
|
System.out.println("pre tick");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.4 门面类
|
||||||
|
|
||||||
|
注入代码只认这个门面,不直接引用 EventBus:
|
||||||
|
|
||||||
|
```java
|
||||||
|
package cn.xiaozhou233.orangex.hook;
|
||||||
|
|
||||||
|
import org.greenrobot.eventbus.EventBus;
|
||||||
|
|
||||||
|
public final class TickEvents {
|
||||||
|
|
||||||
|
private static final EventBus BUS = EventBus.getDefault();
|
||||||
|
|
||||||
|
public static void register(Object listener) {
|
||||||
|
BUS.register(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void unregister(Object listener) {
|
||||||
|
BUS.unregister(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void firePre() {
|
||||||
|
BUS.post(new TickEvent(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void firePost() {
|
||||||
|
BUS.post(new TickEvent(false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
这样做的原因:
|
||||||
|
|
||||||
|
- 以后改库或做 relocate,字节码字符串不用跟着改。
|
||||||
|
- 门面里可以统一加 `hasListeners` 判断、线程判断、异常处理。
|
||||||
|
|
||||||
|
### 3.5 注入
|
||||||
|
|
||||||
|
和方案 A 完全一样,只是把调用目标换成 `TickEvents`:
|
||||||
|
|
||||||
|
```java
|
||||||
|
pool.importPackage("cn.xiaozhou233.orangex.hook");
|
||||||
|
method.insertBefore("TickEvents.firePre();");
|
||||||
|
method.insertAfter ("TickEvents.firePost();");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.7 不要写全限定名(1.8.8 的 `cn` 类)
|
||||||
|
|
||||||
|
Vanilla 1.8.8 的客户端 jar 里有一个默认包下的混淆类 `cn`(`1.8.8.jar!/cn.class`)。
|
||||||
|
Javassist 从左往右解析限定名,写:
|
||||||
|
|
||||||
|
```java
|
||||||
|
method.insertBefore("cn.xiaozhou233.orangex.hook.TickEvents.firePre();");
|
||||||
|
```
|
||||||
|
|
||||||
|
会先找到 `cn` 类,再把 `xiaozhou233...` 当成它的字段/内部类,最后报出误导性的:
|
||||||
|
|
||||||
|
```text
|
||||||
|
no such class: cn$xiaozhou233.orangex.hook.TickEvents
|
||||||
|
```
|
||||||
|
|
||||||
|
这不是 classpath 问题。正确做法是 `pool.importPackage(...)` 后只写简单类名,就像上面两段示例那样。
|
||||||
|
项目里的 `ClassHook#getInjectedClassNames()` 就是为此存在的,详见 [hooks.md](hooks.md)。
|
||||||
|
|
||||||
|
### 3.6 注册
|
||||||
|
|
||||||
|
```java
|
||||||
|
TickEvents.register(new TickListener());
|
||||||
|
```
|
||||||
|
|
||||||
|
到此触发链完整:
|
||||||
|
|
||||||
|
```text
|
||||||
|
runTick() → TickEvents.firePre()
|
||||||
|
→ EventBus.post(TickEvent)
|
||||||
|
→ TickListener.onTick()
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. hook 没生效的三个必要条件
|
||||||
|
|
||||||
|
| 条件 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 类必须被重新加载/重定义 | 如果 `Minecraft` 已经加载,只加 transformer 不会生效,必须 `retransformClasses` 或 `RedefineClasses`。 |
|
||||||
|
| 类名/方法名必须正确 | 运行时的名字可能是混淆名,必须通过 `MappingResolver` 拿,不能写死 `runTick`。 |
|
||||||
|
| 注入类必须对 game ClassLoader 可见 | OrangeX 的 jar 必须加到游戏 ClassLoader,否则 `TickEvents` 会 `NoClassDefFoundError`。 |
|
||||||
|
|
||||||
|
三种都满足,`firePre()` 才会被执行。
|
||||||
|
|
||||||
|
## 5. 排查
|
||||||
|
|
||||||
|
先在 `firePre()` 里加一行日志:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public static void firePre() {
|
||||||
|
System.out.println("[OrangeX] tick hook hit");
|
||||||
|
BUS.post(new TickEvent(true));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 现象 | 原因 |
|
||||||
|
|---|---|
|
||||||
|
| `no such class: cn$xiaozhou233...` | 注入代码写了全限定名,撞上 1.8.8 的 `cn` 类,见 3.7 |
|
||||||
|
| 日志不打印 | 注入没生效:transformer 没挂上 / 没 retransform / 类名方法名不对 |
|
||||||
|
| 日志打印但 `@Subscribe` 不执行 | 没注册 / 注册和 post 不是同一个 `EventBus` 实例 / 事件类型不匹配 / 方法不是 public |
|
||||||
|
| 执行了但不在游戏线程 | 用了 `ThreadMode.ASYNC` 等非 POSTING 模式 |
|
||||||
|
| `NoClassDefFoundError` | 库没进 game ClassLoader,或没有 shade |
|
||||||
|
|
||||||
|
记住:**日志不打印属于注入问题,日志打印了才算 EventBus 问题**,不要一上来就怀疑库。
|
||||||
|
|
||||||
|
## 6. 另一种触发方式:平台事件桥
|
||||||
|
|
||||||
|
如果只是先把流程跑通,可以暂时用 Forge/Fabric 自带的事件,桥接进 EventBus,不改字节码。
|
||||||
|
|
||||||
|
Forge 1.8.9:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@SubscribeEvent
|
||||||
|
public void onClientTick(TickEvent.ClientTickEvent event) {
|
||||||
|
if (event.phase == TickEvent.Phase.START) {
|
||||||
|
TickEvents.firePre();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Fabric:
|
||||||
|
|
||||||
|
```java
|
||||||
|
ClientTickEvents.START_CLIENT_TICK.register(client -> TickEvents.firePre());
|
||||||
|
```
|
||||||
|
|
||||||
|
注意:
|
||||||
|
|
||||||
|
- Forge 的 `@SubscribeEvent` 和 greenrobot 的 `@Subscribe` 名字很像,注意 import,必要时写全限定名。
|
||||||
|
- Vanilla 环境没有这类事件。
|
||||||
|
- 不同加载器写法不同,OrangeX 需要为每个加载器单独处理。
|
||||||
|
|
||||||
|
所以平台事件桥适合早期验证,长期方案还是字节码注入。
|
||||||
|
|
||||||
|
## 7. greenrobot 在 Minecraft 里的注意点
|
||||||
|
|
||||||
|
1. **只用 `ThreadMode.POSTING`**
|
||||||
|
非 Android 环境不要用 `MAIN` / `MAIN_ORDERED` / `ASYNC`,否则可能投递到错误线程,读游戏状态时会崩。
|
||||||
|
|
||||||
|
2. **父类也会收到事件**
|
||||||
|
greenrobot 会把事件派发给父类型的 `@Subscribe` 方法。有 `TickEvent` 和 `PreTickEvent extends TickEvent` 时,注册 `onTick(TickEvent)` 会同时收到两者。
|
||||||
|
|
||||||
|
3. **统一使用一个实例**
|
||||||
|
注册和 `post` 必须是同一个 `EventBus`。建议像 `TickEvents` 一样用一个静态持有者。
|
||||||
|
|
||||||
|
4. **`@Subscribe` 方法保持 public**
|
||||||
|
减少反射和兼容性问题。
|
||||||
|
|
||||||
|
5. **退出时反注册**
|
||||||
|
持有可卸载类的监听器要 `TickEvents.unregister(listener)`。
|
||||||
|
|
||||||
|
## 8. 简化点
|
||||||
|
|
||||||
|
| 简化 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 只处理 `Minecraft.runTick()` | 不同版本入口可能不同,需要按版本选择映射。 |
|
||||||
|
| 没有取消语义 | 真实事件通常带 `cancel`,并在注入代码里 `if (event.fire()) return;`。 |
|
||||||
|
| 没有 `hasListeners()` 快路径 | 可以在注入前判断监听器数量,避免空事件对象分配。 |
|
||||||
|
| 没有处理异常与重入 | 监听器异常、递归触发都需要额外保护。 |
|
||||||
|
| 直接使用 Javassist 字符串注入 | 需要精确指令时改用 ASM(`MethodVisitor`)更可控。 |
|
||||||
+276
@@ -0,0 +1,276 @@
|
|||||||
|
# Hook 系统
|
||||||
|
|
||||||
|
本文说明 OrangeX 的字节码 Hook 架构、如何新增一个 Hook,以及向 Minecraft 方法里注入 Javassist 代码时必须注意的坑。
|
||||||
|
|
||||||
|
> 只讲当前实现,不讨论历史方案。最小示例见 [hook-on-tick-example.md](hook-on-tick-example.md)。
|
||||||
|
|
||||||
|
## 1. 执行流程
|
||||||
|
|
||||||
|
```text
|
||||||
|
游戏启动
|
||||||
|
└── Loader 把 OrangeX.jar 加入游戏 ClassLoader,反射调用 OrangeX.start()
|
||||||
|
├── RuntimeDetector.detect() 运行时 / 版本 / ClassLoader
|
||||||
|
├── MappingManager.init() 混淆名映射
|
||||||
|
├── eventBus.register(...) 注册事件监听器
|
||||||
|
└── HookManager.applyAll()
|
||||||
|
└── 对每个 ClassHook:
|
||||||
|
├── hook.getTargetClass() 目标类(点分名)
|
||||||
|
├── JuiceAgent.getClassBytesByName(...) 读取原始字节码
|
||||||
|
├── hook.transform(loader, bytes)
|
||||||
|
│ ├── ClassPoolUtils.prepare(...) 准备 Javassist 环境
|
||||||
|
│ ├── transform(ctClass) 插入调用
|
||||||
|
│ └── ctClass.toBytecode() 生成新字节码
|
||||||
|
└── JuiceAgent.retransformClassByName(...) 写回 JVM
|
||||||
|
```
|
||||||
|
|
||||||
|
注入只发生在类重转换阶段。之后每次执行被改写的方法,都会经过注入进去的调用,把事件 post 到 `EventBus`。
|
||||||
|
|
||||||
|
## 2. 核心类
|
||||||
|
|
||||||
|
| 类 | 位置 | 职责 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `HookManager` | `hook/HookManager` | 注册所有 Hook,遍历、读取字节码、触发重转换 |
|
||||||
|
| `ClassHook` | `hook/ClassHook` | Hook 基类:目标类、注入逻辑、注入代码引用的类 |
|
||||||
|
| `ClassPoolUtils` | `hook/ClassPoolUtils` | 准备 Javassist `ClassPool`(导入包、加入 OrangeX.jar) |
|
||||||
|
| `JuiceAgentBridge` | `hook/JuiceAgentBridge` | 通过 system ClassLoader 反射调用 JuiceAgent API(Fabric 必需) |
|
||||||
|
| `TickHook` | `hook/impl/TickHook` | 在 `Minecraft.runTick()` 前后插入事件调用 |
|
||||||
|
| `TickEvents` | `event/facade/TickEvents` | 注入代码唯一引用的门面,负责 post 事件 |
|
||||||
|
| `EventTickPre` / `EventTickPost` | `event/impl/*` | 事件对象 |
|
||||||
|
|
||||||
|
## 3. 新增一个 Hook
|
||||||
|
|
||||||
|
### 3.1 继承 `ClassHook`
|
||||||
|
|
||||||
|
```java
|
||||||
|
public final class TickHook extends ClassHook {
|
||||||
|
|
||||||
|
private static final RuntimeInfo runtimeInfo = OrangeX.getInstance().getRuntimeInfo();
|
||||||
|
private static final MappingResolver resolver = MappingManager.getResolver();
|
||||||
|
|
||||||
|
/** 注入代码里引用到的类,用于 import 包。 */
|
||||||
|
@Override
|
||||||
|
protected String[] getInjectedClassNames() {
|
||||||
|
return new String[]{"cn.xiaozhou233.orangex.event.facade.TickEvents"};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 目标类,点分名;返回 null 表示当前版本不支持。 */
|
||||||
|
@Override
|
||||||
|
protected String getTargetClass() {
|
||||||
|
switch (runtimeInfo.getMinecraftVersion()) {
|
||||||
|
case V1_8_9:
|
||||||
|
return resolver.mapClass("net/minecraft/client/Minecraft")
|
||||||
|
.getTargetName().replace("/", ".");
|
||||||
|
case V26_2:
|
||||||
|
return "net.minecraft.client.Minecraft";
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void transform(CtClass ctClass) throws Exception {
|
||||||
|
String methodName = null;
|
||||||
|
String methodDesc = null;
|
||||||
|
|
||||||
|
// 只在这里做“版本 → 方法名/描述符”的映射,下面注入逻辑共用。
|
||||||
|
// 新增版本时只需要补一个 case。
|
||||||
|
switch (runtimeInfo.getMinecraftVersion()) {
|
||||||
|
case V1_8_9: {
|
||||||
|
MappingMethod runTick = resolver.mapMethod(
|
||||||
|
"net/minecraft/client/Minecraft", "runTick", "()V");
|
||||||
|
methodName = runTick.getTargetName();
|
||||||
|
methodDesc = runTick.getTargetDescriptor();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// 26.2 无混淆:runTick(Z)V,private
|
||||||
|
case V26_2: {
|
||||||
|
MappingMethod runTick = resolver.mapMethod(
|
||||||
|
"net/minecraft/client/Minecraft", "runTick", "(Z)V");
|
||||||
|
methodName = runTick.getTargetName();
|
||||||
|
methodDesc = runTick.getTargetDescriptor();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (methodName == null || methodDesc == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
CtMethod method = ctClass.getMethod(methodName, methodDesc);
|
||||||
|
|
||||||
|
// 必须使用简单类名,原因见 4.1。
|
||||||
|
method.insertBefore("TickEvents.firePre();");
|
||||||
|
method.insertAfter("TickEvents.firePost();");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 注册
|
||||||
|
|
||||||
|
在 `HookManager` 构造器里注册:
|
||||||
|
|
||||||
|
```java
|
||||||
|
private HookManager() {
|
||||||
|
register(new TickHook());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
构造函数里只做注册,不要在此时访问尚未初始化的运行时信息。
|
||||||
|
|
||||||
|
### 3.3 使用映射,不要硬编码
|
||||||
|
|
||||||
|
运行时的类名/方法名可能是混淆名,统一通过 `MappingResolver` 获取:
|
||||||
|
|
||||||
|
```java
|
||||||
|
MappingClass mc = resolver.mapClass("net/minecraft/client/Minecraft");
|
||||||
|
MappingMethod m = resolver.mapMethod("net/minecraft/client/Minecraft", "runTick", "()V");
|
||||||
|
```
|
||||||
|
|
||||||
|
各版本的命名来源:
|
||||||
|
|
||||||
|
| 版本 | 解析器 | 运行时名字 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1.8.9 MCP | `MCPMappingResolver` | MCP 名(`runTick`) |
|
||||||
|
| 1.8.9 Vanilla/Forge | `SrgMappingResolver` | 混淆名(`s` 等) |
|
||||||
|
| 26.2 | `IdentityFallbackMappingResolver` | Mojang 名(`net.minecraft.client.Minecraft#runTick(Z)V`,private) |
|
||||||
|
|
||||||
|
26.2 本身没有混淆,identity 解析器会把 `net/minecraft/client/Minecraft` 和 `runTick()V` 原样返回。只要目标类/方法相同,一个 Hook 就可以同时覆盖多个版本(`TickHook` 的 `V1_8_9` 和 `V26_2` 共用同一段注入逻辑)。
|
||||||
|
|
||||||
|
`ClassHook` 的基类逻辑会负责剩下的步骤:读取字节码 → 注入 → `toBytecode()` → 交给 `JuiceAgent` 重转换。
|
||||||
|
|
||||||
|
## 4. 注入代码的硬性规则
|
||||||
|
|
||||||
|
### 4.1 不要写全限定名(1.8.8 的 `cn` 类)
|
||||||
|
|
||||||
|
Vanilla 1.8.8 的客户端 jar 里有一个**默认包**下的混淆类 `cn`(`1.8.8.jar!/cn.class`)。
|
||||||
|
|
||||||
|
Javassist 解析限定名是从左往右的,写:
|
||||||
|
|
||||||
|
```java
|
||||||
|
method.insertBefore("cn.xiaozhou233.orangex.event.facade.TickEvents.firePre();");
|
||||||
|
```
|
||||||
|
|
||||||
|
会把 `cn` 解析成那个类,然后把后面的 `xiaozhou233...` 当成字段/内部类,最终报出极具误导性的错误:
|
||||||
|
|
||||||
|
```text
|
||||||
|
no such class: cn$xiaozhou233.orangex.event.facade.TickEvents
|
||||||
|
```
|
||||||
|
|
||||||
|
这**不是** classpath 问题,加多少类路径都没用。正确做法是让 `ClassPoolUtils` 导入包,注入代码里只写简单类名:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Override
|
||||||
|
protected String[] getInjectedClassNames() {
|
||||||
|
return new String[]{"cn.xiaozhou233.orangex.event.facade.TickEvents"};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注入时:
|
||||||
|
method.insertBefore("TickEvents.firePre();");
|
||||||
|
```
|
||||||
|
|
||||||
|
`getInjectedClassNames()` 返回的类所在的包会被 `pool.importPackage(...)` 导入,Javassist 会通过 `searchImports` 找到 `TickEvents`,不再触发 `cn` 冲突。
|
||||||
|
|
||||||
|
### 4.2 被引用的类必须对 Javassist 可见
|
||||||
|
|
||||||
|
`ClassPool.getDefault()` 只认识 JVM 启动时的 classpath,而 OrangeX.jar 是运行时注入的。`Loader` 会设置系统属性:
|
||||||
|
|
||||||
|
```java
|
||||||
|
System.setProperty("orangex.jar", orangexFile.getAbsolutePath());
|
||||||
|
```
|
||||||
|
|
||||||
|
`ClassPoolUtils.prepare(...)` 读取该属性,把 jar 加到 `ClassPool` 的 classpath。因此:
|
||||||
|
|
||||||
|
- 新增 Hook 时,凡是注入代码引用到的类,都要放进 `getInjectedClassNames()`;
|
||||||
|
- 不要绕过 `ClassHook.transform()` 自己创建 `ClassPool`,否则会缺少这些准备。
|
||||||
|
|
||||||
|
### 4.3 `ClassPool` 是单例
|
||||||
|
|
||||||
|
`ClassPool.getDefault()` 返回全局单例,`ClassPoolUtils` 只会往里面加一次路径/导入项。不要在每个 Hook 里重复 `insertClassPath`,否则路径会无限增长。
|
||||||
|
|
||||||
|
`ClassHook.transform()` 在最后会 `ctClass.detach()`,避免 `ClassPool` 长期持有一个不可回收的 `CtClass`。
|
||||||
|
|
||||||
|
### 4.4 异常不要外泄
|
||||||
|
|
||||||
|
`HookManager` 对每个 Hook 单独 `try/catch(Throwable)`:某个 Hook 失败只打印堆栈,不影响其他 Hook,也不阻断游戏启动。
|
||||||
|
|
||||||
|
### 4.5 Fabric:不要直接引用 JuiceAgent API
|
||||||
|
|
||||||
|
JuiceAgent 的 native 方法只注册在 **system ClassLoader** 加载的那份 API 类上。Fabric 的 `KnotClassLoader` 会优先从自己的 code source 加载类,如果 `OrangeX.jar` 里 shade 了 `cn.xiaozhou233.juiceagent.api.*`,Knot 就会加载第二份 `JuiceAgent`,调用时直接抛:
|
||||||
|
|
||||||
|
```text
|
||||||
|
java.lang.UnsatisfiedLinkError: 'byte[] cn.xiaozhou233.juiceagent.api.JuiceAgent.getClassBytesByName(java.lang.String)'
|
||||||
|
```
|
||||||
|
|
||||||
|
因此:
|
||||||
|
|
||||||
|
- `OrangeX.jar` **不要** shade JuiceAgent API;
|
||||||
|
- 需要调用 `getClassBytesByName` / `retransformClassByName` 时,统一走 `JuiceAgentBridge`,它用 `Class.forName(..., ClassLoader.getSystemClassLoader())` 拿到已注册 native 的那份类;
|
||||||
|
- 不要在 OrangeX 里 `import cn.xiaozhou233.juiceagent.api.JuiceAgent`。
|
||||||
|
|
||||||
|
`Loader` 运行在 system ClassLoader 下,不受这个限制。
|
||||||
|
|
||||||
|
## 5. 事件总线
|
||||||
|
|
||||||
|
底层是 greenrobot EventBus,但注入代码只认门面 `TickEvents`:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public class TickEvents {
|
||||||
|
private static final EventBus BUS = OrangeX.getInstance().getEventBus();
|
||||||
|
|
||||||
|
public static void firePre() {
|
||||||
|
BUS.post(new EventTickPre());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void firePost() {
|
||||||
|
BUS.post(new EventTickPost());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
监听器:
|
||||||
|
|
||||||
|
```java
|
||||||
|
OrangeX.getInstance().getEventBus().register(new Object() {
|
||||||
|
@Subscribe(threadMode = ThreadMode.POSTING)
|
||||||
|
public void onTick(EventTickPre event) {
|
||||||
|
// 游戏主线程
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
约定:
|
||||||
|
|
||||||
|
- 只用 `ThreadMode.POSTING`,非 Android 环境不要用 `MAIN` / `ASYNC`;
|
||||||
|
- 注册和 post 必须是同一个 `EventBus` 实例(统一从 `OrangeX.getInstance().getEventBus()` 获取);
|
||||||
|
- 监听器需要卸载时调用 `eventBus.unregister(listener)`。
|
||||||
|
|
||||||
|
## 6. 排查
|
||||||
|
|
||||||
|
| 现象 | 原因 |
|
||||||
|
| --- | --- |
|
||||||
|
| `no such class: cn$xiaozhou233...` | 注入代码写了全限定名,撞上 1.8.8 的 `cn` 类。改成 `getInjectedClassNames` + 简单类名 |
|
||||||
|
| `no such class: TickEvents` | `getInjectedClassNames()` 没声明该类,或 OrangeX.jar 没加入 `ClassPool` |
|
||||||
|
| `CannotCompileException`,`getMethod` 抛 `NotFoundException` | 版本不对/方法名或描述符错误,检查 `MappingResolver` |
|
||||||
|
| 日志有 `[OrangeX] javassist classpath: ...` 但无事件打印 | 注入成功但没触发:确认目标方法真的每帧调用(1.8.x `runTick()V`,26.2 `runTick(Z)V`) |
|
||||||
|
| 事件 post 了但 `@Subscribe` 不执行 | 没注册 / 不是同一个 `EventBus` / 方法不是 `public` |
|
||||||
|
| `UnsatisfiedLinkError: JuiceAgent.getClassBytesByName` | Fabric 下加载了第二份 API;不要把 API shade 进 OrangeX.jar,走 `JuiceAgentBridge` |
|
||||||
|
| `NoClassDefFoundError` | OrangeX.jar 不在游戏 ClassLoader;检查 Loader 的注入路径 |
|
||||||
|
| 某个 Hook 失败,其他 Hook 正常 | 预期行为,`HookManager` 会隔离异常 |
|
||||||
|
|
||||||
|
## 7. 相关文件
|
||||||
|
|
||||||
|
```text
|
||||||
|
OrangeX/src/main/java/cn/xiaozhou233/orangex/
|
||||||
|
├── hook/
|
||||||
|
│ ├── HookManager.java
|
||||||
|
│ ├── ClassHook.java
|
||||||
|
│ ├── ClassPoolUtils.java
|
||||||
|
│ ├── JuiceAgentBridge.java
|
||||||
|
│ └── impl/TickHook.java
|
||||||
|
└── event/
|
||||||
|
├── Event.java
|
||||||
|
├── facade/TickEvents.java
|
||||||
|
└── impl/EventTickPre.java, EventTickPost.java
|
||||||
|
```
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# 渲染相关文档
|
||||||
|
|
||||||
|
本目录记录客户端字体、GUI 与跨版本渲染实现的分析与设计参考。
|
||||||
|
|
||||||
|
## 文档索引
|
||||||
|
|
||||||
|
| 文档 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| [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 绘制层:矩形、渐变、圆角、描边、直线、裁剪及两版本实现 |
|
||||||
|
|
||||||
|
## 快速导航
|
||||||
|
|
||||||
|
- 字体资源与语言选择 → 主文档 §2.1
|
||||||
|
- stb_truetype 字形图集 → 主文档 §2.2
|
||||||
|
- Buffered / Legacy 字体渲染器 → 主文档 §2.3
|
||||||
|
- Minecraft 原生 `FontSet` 字体桥 → 主文档 §2.4
|
||||||
|
- § 颜色码、阴影、宽度缓存、GUI Scale → 主文档 §2.5
|
||||||
|
- 中文覆盖与构建期校验 → 主文档 §2.6
|
||||||
|
- ClickGUI 生命周期与输入 → 主文档 §3.1
|
||||||
|
- 坐标系统与缩放 → 主文档 §3.2
|
||||||
|
- 组件树与布局 → 主文档 §3.3
|
||||||
|
- `GuiRenderPrimitives` 双后端 → 主文档 §3.4
|
||||||
|
- Universal Shader 批次渲染 → 主文档 §3.5
|
||||||
|
- 1.21.6+ / 26.x 兼容 → 主文档 §3.7
|
||||||
|
- 版本矩阵 → 主文档 §4
|
||||||
|
|
||||||
|
## 阅读前提
|
||||||
|
|
||||||
|
主文档以 `E:\Vape-v4.21` 为源码根,涉及的文件路径均相对于该目录。
|
||||||
|
文中结论来自静态源码阅读,运行时行为仍需结合实际客户端验证。
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
# 字体移植(Vape 4.21 → OrangeX)
|
||||||
|
|
||||||
|
本文说明从 `E:\Vape-v4.21` 移植过来的 TTF 字体子系统,以及它在 1.8.9 / 26.2 两个版本上的接入方式。
|
||||||
|
|
||||||
|
> 设计目标:字体光栅化、排版、缓存全部与 Minecraft 版本无关;只有“把图集交给 GPU”和“每帧从哪拿绘制上下文”是版本相关的。
|
||||||
|
|
||||||
|
## 1. 目录结构
|
||||||
|
|
||||||
|
```text
|
||||||
|
OrangeX/src/main/java/cn/xiaozhou233/orangex/
|
||||||
|
├── render/
|
||||||
|
│ ├── api/
|
||||||
|
│ │ ├── FontRenderer.java # 业务代码使用的字体接口
|
||||||
|
│ │ └── Render2D.java # 每帧 2D 上下文
|
||||||
|
│ ├── font/
|
||||||
|
│ │ ├── FontFamily.java # 内置字体族
|
||||||
|
│ │ ├── FontManager.java # 按 (family,size,bold,scale) 缓存
|
||||||
|
│ │ ├── FontFace.java # 图集 + 纹理 + drawScale
|
||||||
|
│ │ ├── FontAtlas.java # 烘焙结果
|
||||||
|
│ │ ├── Glyph.java # 单字形度量 / UV
|
||||||
|
│ │ ├── StbFontBaker.java # stb 打包适配
|
||||||
|
│ │ ├── TrueTypeFontRenderer.java # 排版、§ 颜色、阴影、CJK 回退
|
||||||
|
│ │ └── stb/ # 移植的 stb_truetype
|
||||||
|
│ ├── internal/
|
||||||
|
│ │ ├── FontBackend.java # 版本相关 GPU 操作
|
||||||
|
│ │ ├── FontTexture.java
|
||||||
|
│ │ ├── GlyphDrawer.java
|
||||||
|
│ │ ├── FontBackendFactory.java
|
||||||
|
│ │ ├── v1_8_9/ # GL11 立即模式
|
||||||
|
│ │ └── v26_2/ # GuiRenderState 延迟绘制
|
||||||
|
│ ├── Render2DManager.java
|
||||||
|
│ └── FontDebugOverlay.java
|
||||||
|
├── event/
|
||||||
|
│ ├── facade/Render2DEvents.java # 注入代码唯一引用
|
||||||
|
│ └── impl/EventRender2D.java
|
||||||
|
└── hook/impl/Render2DHook.java # 每帧 2D 回调
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. 使用方式
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Subscribe(threadMode = ThreadMode.POSTING)
|
||||||
|
public void onRender2D(EventRender2D event) {
|
||||||
|
Render2D render2D = event.getRender2D();
|
||||||
|
|
||||||
|
FontRenderer title = render2D.getFont(14.0f, true);
|
||||||
|
FontRenderer body = render2D.getFont(10.0f, false);
|
||||||
|
|
||||||
|
title.drawStringWithShadow("OrangeX", 8, 8, 0xFFFFFFFF);
|
||||||
|
body.drawString("中文测试:钻石剑", 8, 30, 0xFFFFAA00);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
约定:
|
||||||
|
|
||||||
|
- 坐标和字号都是 **Minecraft GUI 像素**(`ScaledResolution` / `getGuiScaledWidth` 空间)。
|
||||||
|
- `FontRenderer` 只在当前帧有效,不要缓存到字段里跨帧使用。
|
||||||
|
- `getFont(size, bold)` 返回的对象可以在一帧内重复使用。
|
||||||
|
- 英文默认使用 Proxima;遇到 CJK 字符时自动懒加载 Noto 回退。
|
||||||
|
|
||||||
|
## 3. 光栅化流程
|
||||||
|
|
||||||
|
1. `StbFontBaker` 用 stb_truetype 读取 TTF 的 hhea/ascent/descent。
|
||||||
|
2. 字符集:
|
||||||
|
- ASCII `32..126`
|
||||||
|
- Latin-1 `160..255`
|
||||||
|
- Noto 额外解码 GBK 双字节区间(默认全 GBK,`noto.ttf` 子集实际约 6900 个汉字)
|
||||||
|
3. 在 `4096 × 4096` 的 8 位覆盖度位图上打包:
|
||||||
|
- Latin 使用 `2×2` oversampling
|
||||||
|
- CJK 使用 `1×1` oversampling
|
||||||
|
4. 每个字形记录 `x0/y0/x1/y1`(相对基线)、`u0/v0/u1/v1`、`advance`。
|
||||||
|
5. 纹理上传:
|
||||||
|
- 1.8.9:`GL_ALPHA` + 固定管线 `GL_MODULATE`
|
||||||
|
- 26.2:扩展为 RGBA(白色 RGB + 覆盖度 alpha),包装成 `DynamicTexture`
|
||||||
|
|
||||||
|
字号策略:
|
||||||
|
|
||||||
|
```text
|
||||||
|
rasterHeight = round(logicalSize * guiScale)
|
||||||
|
drawScale = logicalSize / rasterHeight
|
||||||
|
```
|
||||||
|
|
||||||
|
因此 GUI Scale 只提高烘焙分辨率,不改变逻辑排版宽度。为避免 4096 图集溢出:
|
||||||
|
|
||||||
|
| 字体 | 最大 rasterHeight |
|
||||||
|
| --- | --- |
|
||||||
|
| 非 CJK(Proxima/Poppins) | 64 |
|
||||||
|
| CJK(Noto) | 36 |
|
||||||
|
|
||||||
|
## 4. 版本接入
|
||||||
|
|
||||||
|
### 4.1 1.8.9
|
||||||
|
|
||||||
|
- Hook:`GuiIngame#renderGameOverlay(F)V` 的末尾。
|
||||||
|
- Forge:改为 `net.minecraftforge.client.GuiIngameForge#renderGameOverlay(F)V`。
|
||||||
|
- `V1_8_9Render2D` 通过 `MappingResolver` 反射 `ScaledResolution`,拿到 `scaledWidth/scaledHeight/scaleFactor`。
|
||||||
|
- `V1_8_9GlyphDrawer` 使用 `GL11` 立即模式绘制四边形;首次绘制时保存并在 `flush()` 中恢复:
|
||||||
|
- 纹理绑定 / 激活纹理单元
|
||||||
|
- `GL_BLEND` / `GL_TEXTURE_2D` / `GL_ALPHA_TEST` / `GL_DEPTH_TEST`
|
||||||
|
- `GL_CULL_FACE` / `GL_LIGHTING` / `GL_FOG` / `GL_SCISSOR_TEST`
|
||||||
|
- `GL_TEXTURE_ENV_MODE`
|
||||||
|
- 当前 `glColor`
|
||||||
|
- 图集使用 `GL_RGBA`(白色 RGB + 覆盖度 alpha),避免 `GL_ALPHA` 在固定管线中 RGB 为 0 导致文字发黑。
|
||||||
|
|
||||||
|
> 坑:LWJGL2 的 `glGetFloat(GL_CURRENT_COLOR, buffer)` 有
|
||||||
|
> `BufferChecks` 限制,缓冲区至少要有 **16** 个元素;只分配 4 个会在首个字形
|
||||||
|
> 抛出 `IllegalArgumentException`,表现为“字体烘焙成功但屏幕无反应”。
|
||||||
|
|
||||||
|
### 4.2 26.2
|
||||||
|
|
||||||
|
- Hook:`net.minecraft.client.gui.Gui#extractRenderState(DeltaTracker, boolean, boolean)` 的末尾。
|
||||||
|
- 把 `Gui` 实例传给 `Render2DEvents`。
|
||||||
|
- `V26_2Render2D` 反射:
|
||||||
|
- `Gui.minecraft`
|
||||||
|
- `Gui.guiRenderState`
|
||||||
|
- 构造 `GuiGraphicsExtractor`
|
||||||
|
- `Window#getGuiScale/getGuiScaledWidth/getGuiScaledHeight`
|
||||||
|
- 每个字形调用 `GuiGraphicsExtractor#innerBlit(...)`,把 `BlitRenderState` 加入 `GuiRenderState`,由 `GuiRenderer` 统一排序、合批、绘制。
|
||||||
|
- 不直接调用任何 OpenGL。
|
||||||
|
|
||||||
|
## 5. 调试
|
||||||
|
|
||||||
|
构建:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./gradlew :OrangeX:shadowJar
|
||||||
|
# 或完整注入包
|
||||||
|
./gradlew packageAll
|
||||||
|
```
|
||||||
|
|
||||||
|
> 部署注意:MCP 开发环境通常直接读取
|
||||||
|
> `E:\OrangeX-Client\out\tmp\OrangeX.jar`,而 Vanilla/Forge/NeoForge/Fabric
|
||||||
|
> 启动器会读取 `%USERPROFILE%\.orangex\OrangeX.jar`。改完代码后必须把新
|
||||||
|
> jar 同步过去,否则会出现“MCP 正常、其他版本没反应”。
|
||||||
|
|
||||||
|
调试 Overlay 默认关闭;需要时加:
|
||||||
|
|
||||||
|
```text
|
||||||
|
-Dorangex.debugFont=true
|
||||||
|
```
|
||||||
|
|
||||||
|
会在屏幕左上角绘制:
|
||||||
|
|
||||||
|
```text
|
||||||
|
OrangeX
|
||||||
|
Font backend: V1_8_9Render2D / V26_2Render2D
|
||||||
|
ASCII 0123456789
|
||||||
|
中文测试:钻石剑 / 迅捷
|
||||||
|
```
|
||||||
|
|
||||||
|
其他属性:
|
||||||
|
|
||||||
|
| 属性 | 默认 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `-Dorangex.font.fullGbk` | `true` | `false` 时只烘焙 GB2312 一级汉字(约 3755 个) |
|
||||||
|
| `-Dorangex.font.atlasSize` | `4096` | 图集边长,允许 `512..8192`。26.2 使用 RGBA 纹理,8192 约占用 256 MB 显存 |
|
||||||
|
|
||||||
|
启动日志会输出:
|
||||||
|
|
||||||
|
```text
|
||||||
|
[OrangeX] Font backend: 1.8.9/GL11
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. 添加新版本
|
||||||
|
|
||||||
|
1. 在 `render/internal/vX_Y_Z/` 新建:
|
||||||
|
- `VX_Y_ZFontBackend implements FontBackend`
|
||||||
|
- `VX_Y_ZFontTexture implements FontTexture`
|
||||||
|
- `VX_Y_ZRender2D implements Render2D`
|
||||||
|
- `VX_Y_ZGlyphDrawer implements GlyphDrawer`
|
||||||
|
2. 在 `FontBackendFactory` 的 `switch` 中注册。
|
||||||
|
3. 在 `Render2DHook` 的 `getTargetClass/transform` 中增加该版本的每帧 2D 入口。
|
||||||
|
4. 如果该版本使用新的 GUI 渲染架构,只需要改 `Render2D`/`GlyphDrawer`,字体光栅化与排版代码不用动。
|
||||||
|
|
||||||
|
## 7. 当前限制
|
||||||
|
|
||||||
|
- 没有移植 Vape 的 `StbSmoothFontRenderer`(直接读游戏 `FontSet`),因此没有“MC 原版字体”选项。
|
||||||
|
- 没有多页图集;CJK 在超大字号下会被限制到 36px 烘焙高度。
|
||||||
|
- 只支持 `§0-9/a-f/r`,没有 italic / underline / obfuscated。
|
||||||
|
- 粗体只对内置了 bold 文件的字体生效(Proxima);Noto 使用同一文件。
|
||||||
|
- `FontManager` 目前不会在 GUI Scale 变化时主动释放旧纹理,需要时可调用 `clear()`。
|
||||||
|
- 26.2 使用 RGBA 图集,4096² 单张约 67 MB 显存;不同字号会各自持有一张。若要做大量字号,建议后续改成 R8 + 自定义画字管线或做字号分桶。
|
||||||
|
|
||||||
|
## 8. 已验证环境
|
||||||
|
|
||||||
|
| 环境 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 1.8.9 MCP | 正常渲染 |
|
||||||
|
| 1.8.9 Vanilla(`avo#a(F)V`) | 正常渲染 |
|
||||||
|
| 1.8.9 Forge(`GuiIngameForge`) | 走同一注入逻辑,待实机验证 |
|
||||||
|
| 26.2 Vanilla(`Gui#extractRenderState`) | 正常渲染 |
|
||||||
|
|
||||||
|
在真实 LWJGL2 窗口上下文中的离屏冒烟测试也通过:绘制字母 `A` 得到
|
||||||
|
`nonBlack=160, max=255, glError=0`。
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
# GUI 2D 渲染
|
||||||
|
|
||||||
|
本文说明 OrangeX 的基础 2D GUI 绘制层。它建立在字体移植的 `Render2D` 上下文之上,供后续 ClickGUI / HUD / 面板组件直接使用。
|
||||||
|
|
||||||
|
## 1. API
|
||||||
|
|
||||||
|
`cn.xiaozhou233.orangex.render.api.Render2D`:
|
||||||
|
|
||||||
|
| 方法 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `fillRect(x, y, w, h, argb)` | 实心矩形 |
|
||||||
|
| `fillGradient(x, y, w, h, top, bottom)` | 垂直渐变矩形 |
|
||||||
|
| `drawRect(x, y, w, h, thickness, argb)` | 矩形描边 |
|
||||||
|
| `fillRoundedRect(x, y, w, h, radius, argb)` | 实心圆角矩形 |
|
||||||
|
| `fillRoundedRect(x, y, w, h, radius, borderWidth, fill, border)` | 带边框圆角矩形 |
|
||||||
|
| `drawLine(x1, y1, x2, y2, thickness, argb)` | 直线 |
|
||||||
|
| `enableScissor(x, y, w, h)` | 开启裁剪 |
|
||||||
|
| `disableScissor()` | 关闭当前裁剪 |
|
||||||
|
| `getFont(size[, bold])` | 获取字体 |
|
||||||
|
| `getWidth()` / `getHeight()` / `getGuiScale()` | 当前 GUI 尺寸 |
|
||||||
|
|
||||||
|
颜色统一使用 **ARGB int**,例如:
|
||||||
|
|
||||||
|
```java
|
||||||
|
0xFFFFFFFF // 不透明白
|
||||||
|
0xCC101010 // 80% 黑
|
||||||
|
0xFF55FFFF // 青色
|
||||||
|
```
|
||||||
|
|
||||||
|
坐标是 Minecraft GUI 像素(`ScaledResolution` / `getGuiScaledWidth` 空间)。
|
||||||
|
|
||||||
|
## 2. 示例
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Subscribe(threadMode = ThreadMode.POSTING)
|
||||||
|
public void onRender2D(EventRender2D event) {
|
||||||
|
Render2D g = event.getRender2D();
|
||||||
|
|
||||||
|
g.fillRoundedRect(10, 10, 220, 120, 8,
|
||||||
|
1.0, 0xCC151515, 0xFF353535);
|
||||||
|
|
||||||
|
g.fillGradient(18, 100, 204, 6,
|
||||||
|
0xFF55FFFF, 0xFF55FF55);
|
||||||
|
|
||||||
|
g.drawLine(18, 112, 222, 112, 1.0, 0x80FFFFFF);
|
||||||
|
|
||||||
|
FontRenderer font = g.getFont(10.0f);
|
||||||
|
font.drawString("OrangeX", 18, 18, 0xFFFFFFFF);
|
||||||
|
|
||||||
|
g.enableScissor(18, 40, 120, 18);
|
||||||
|
font.drawString("只在裁剪区域内显示的一段文字", 18, 40, 0xFFAAAAAA);
|
||||||
|
g.disableScissor();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
带边框圆角面板的常见写法:
|
||||||
|
|
||||||
|
```java
|
||||||
|
g.fillRoundedRect(x, y, width, height, 6.0,
|
||||||
|
1.0, 0xCC181818, 0xFF3A3A3A);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. 版本实现
|
||||||
|
|
||||||
|
### 3.1 1.8.9
|
||||||
|
|
||||||
|
`V1_8_9Render2D` 使用固定管线立即模式:
|
||||||
|
|
||||||
|
- 矩形 / 描边 / 渐变:`GL_QUADS`,渐变使用 `GL_SMOOTH`
|
||||||
|
- 圆角矩形:按圆角半径生成外轮廓采样点,`GL_TRIANGLE_FAN` 填充
|
||||||
|
- 边框:先画外层圆角矩形(边框色),再画内层圆角矩形(填充色)
|
||||||
|
- 裁剪:`GL_SCISSOR_TEST` + `glScissor`,坐标按 GUI Scale 转成 framebuffer 像素
|
||||||
|
- 直线:水平/垂直用矩形,斜线用 `GL_LINES`
|
||||||
|
|
||||||
|
所有 GL 状态由 `V1_8_9RenderState` 统一保存/恢复:
|
||||||
|
|
||||||
|
- blend / texture / alpha test / depth / cull / lighting / fog / scissor
|
||||||
|
- texture binding / active texture / texture env
|
||||||
|
- shade model / line width / current color
|
||||||
|
|
||||||
|
`Render2D.flush()` 在一帧结束时统一恢复,形状和字体可以任意交错绘制。
|
||||||
|
|
||||||
|
### 3.2 26.2
|
||||||
|
|
||||||
|
`V26_2Render2D` 不直接调用 OpenGL,而是把绘制提交给 `GuiRenderState`:
|
||||||
|
|
||||||
|
- 矩形:`GuiGraphicsExtractor#fill`
|
||||||
|
- 渐变:`GuiGraphicsExtractor#fillGradient`
|
||||||
|
- 裁剪:`GuiGraphicsExtractor#enableScissor/disableScissor`
|
||||||
|
- 圆角矩形:
|
||||||
|
- 直边用 `fill` 拼出 5 个矩形区域
|
||||||
|
- 4 个圆角使用缓存的白色四分之一圆纹理,通过 `innerBlit` 翻转 UV 绘制
|
||||||
|
- 纹理按 `radius * guiScale` 生成,保证一个纹素对应一个物理像素
|
||||||
|
- 边框:外层圆角矩形 + 内层圆角矩形
|
||||||
|
|
||||||
|
圆角纹理由 `V26_2ShapeCache` 缓存,按半径像素复用,不会每帧创建。
|
||||||
|
|
||||||
|
## 4. 裁剪
|
||||||
|
|
||||||
|
裁剪支持嵌套:
|
||||||
|
|
||||||
|
```java
|
||||||
|
g.enableScissor(0, 0, 200, 100);
|
||||||
|
g.enableScissor(20, 20, 100, 50);
|
||||||
|
// ...
|
||||||
|
g.disableScissor(); // 回到第一层
|
||||||
|
g.disableScissor(); // 关闭
|
||||||
|
```
|
||||||
|
|
||||||
|
- 1.8.9 在 `V1_8_9Render2D` 内维护 scissor 栈
|
||||||
|
- 26.2 交给 `GuiGraphicsExtractor` 的 scissor 栈
|
||||||
|
|
||||||
|
## 5. 当前限制
|
||||||
|
|
||||||
|
- 没有旋转、缩放矩阵 API(坐标就是 GUI 像素)
|
||||||
|
- 26.2 的斜线用 1px 方块近似,复杂斜线建议用贴图
|
||||||
|
- 圆角矩形在 26.2 依赖生成的角纹理,半径种类很多时会增加纹理数量
|
||||||
|
- 还没有图片/纹理绘制 API,下一步可以补 `drawTexture` / `drawImage`
|
||||||
|
- 还没有组件树、布局和输入系统
|
||||||
|
|
||||||
|
## 6. 下一步
|
||||||
|
|
||||||
|
建议顺序:
|
||||||
|
|
||||||
|
1. `Texture` / `drawTexture` 图片绘制
|
||||||
|
2. `Component` / `Frame` 组件树与布局
|
||||||
|
3. 鼠标/键盘输入与 ClickGUI 打开逻辑
|
||||||
|
4. 主题、动画和滚动容器
|
||||||
@@ -0,0 +1,642 @@
|
|||||||
|
# Vape 4.21 字体与 GUI 渲染(含跨版本)
|
||||||
|
|
||||||
|
> 分析对象:`E:\Vape-v4.21`(Vape 4.21 恢复工程)。
|
||||||
|
> 本文所有相对路径均以该目录为根,例如 `src/main/java/gg/vape/ui/font/FontManager.java`。
|
||||||
|
> 结论来自源码静态阅读,未做运行时验证。
|
||||||
|
|
||||||
|
## 0. 一句话总结
|
||||||
|
|
||||||
|
Vape **不依赖某个 Minecraft 版本的 `FontRenderer` / `Screen` 实现**:
|
||||||
|
|
||||||
|
- 字体:内嵌 TTF,用移植版 stb_truetype 烘成字形图集,再用自建 shader 画四边形;1.21.10+ 额外提供“直接读取游戏 `FontSet`”的桥。
|
||||||
|
- GUI:不是 `GuiScreen`,而是每帧在 HUD / PostRender 阶段画的自绘 Overlay,输入由原生层回调。
|
||||||
|
- 跨版本:`ForgeVersion` 版本谓词 + `MappedClasses`/`Mapping*` 名字映射 + `GuiRenderPrimitives` 双渲染后端(立即模式 / 自建批次)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 分层架构
|
||||||
|
|
||||||
|
```text
|
||||||
|
注入 DLL → Java payload
|
||||||
|
│
|
||||||
|
├─ Runtime.NativeBridge / wrapper.impl.ForgeVersion 版本探测
|
||||||
|
├─ mapping.MappedClasses / Mapper / Mapping* 运行时类与成员解析
|
||||||
|
├─ wrapper.impl.* 对 MC 的薄封装
|
||||||
|
├─ utils.render.GuiRenderPrimitives 绘制门面(双后端)
|
||||||
|
└─ ui.font / ui.click 字体、组件、布局
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.1 版本探测
|
||||||
|
|
||||||
|
入口:`src/main/java/gg/vape/runtime/NativeBridge.java` 的 `gmv()`。
|
||||||
|
|
||||||
|
1. 优先读 Forge / NeoForge 的版本号:
|
||||||
|
- `net.minecraftforge.common.ForgeVersion.minorVersion`
|
||||||
|
- `net.minecraftforge.fml.loading.FMLLoader.forgeVersion`
|
||||||
|
- `FMLLoader.versionInfo().forgeVersion()`
|
||||||
|
2. 失败则调用 `detectVanillaMappingVersion()`,用锚点类逐个探测:
|
||||||
|
- `Vanilla1710Mappings` / `Vanilla189Mappings` / `Badlion189Mappings`
|
||||||
|
- `Vanilla1122Mappings` / `Vanilla1165Mappings`
|
||||||
|
- `Vanilla1201Mappings` / `Vanilla1206Mappings` / `Vanilla1211Mappings` / `Vanilla12111Mappings`
|
||||||
|
- `NeoForge1201Mappings` / `NeoForge1211Mappings`
|
||||||
|
- `Vanilla262Mappings` / `Fabric262Mappings`
|
||||||
|
3. 结果写入 `ForgeVersion.gameVersion`,对应枚举协议号:
|
||||||
|
|
||||||
|
```text
|
||||||
|
13 1.7.10
|
||||||
|
15 1.8.9
|
||||||
|
23 1.12.2
|
||||||
|
35 1.16.4
|
||||||
|
36 1.16.5
|
||||||
|
37 1.17
|
||||||
|
47 1.20.1
|
||||||
|
50 1.20.6
|
||||||
|
51 1.21.0
|
||||||
|
52 1.21.1
|
||||||
|
54 1.21.4
|
||||||
|
55 1.21.5
|
||||||
|
56 1.21.6
|
||||||
|
60 1.21.10
|
||||||
|
61 1.21.11
|
||||||
|
100 26.1
|
||||||
|
110 26.2
|
||||||
|
```
|
||||||
|
|
||||||
|
之后全代码通过 `ForgeVersion.MC_1_20_1.d()` 这类“大于等于”谓词分支:
|
||||||
|
|
||||||
|
- `d()` = `>=`
|
||||||
|
- `v()` = `>`
|
||||||
|
- `L()` = `<=`
|
||||||
|
- `Y()` = `<`
|
||||||
|
- `B()` = `!=`
|
||||||
|
|
||||||
|
### 1.2 跨版本名字映射
|
||||||
|
|
||||||
|
#### 类名
|
||||||
|
|
||||||
|
`src/main/java/gg/vape/mapping/MappedClasses.java` 里大量静态 `Class` 字段由 `src/main/java/gg/vape/mapping/runtime/` 下的表初始化:
|
||||||
|
|
||||||
|
| 表 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `ClassNameRemapTableV23/V35V36/V37/V50/V51/V54/V55/V56/V60/V61/V100/V110` | 各版本“源码类名 → 运行时类名” |
|
||||||
|
| `MemberNameRemapTableV*` | MCP/mojmap/SRG → 混淆成员名 |
|
||||||
|
| `NeoForgeClassMap` / `NeoForgeFieldMap` / `NeoForgeObfMap` | NeoForge / 纯原版 1.20.1、1.21.1 的特殊转换 |
|
||||||
|
| `VanillaSrgMappings` / `NeoForge*Mappings` / `Fabric*Mappings` | classpath 探测 + `joined.srg` 解析 |
|
||||||
|
|
||||||
|
`MappedClasses` 还区分运行时形态:
|
||||||
|
|
||||||
|
- `Vape.INSTANCE.isForgeAbsent()`:纯原版 / Fabric / NeoForge 无 Forge remap
|
||||||
|
- `Vape.INSTANCE.isForgeRemapActive()`:Forge 的 SRG remap 路径
|
||||||
|
- `Vape.INSTANCE.isVanillaMinecraftPresent()`:纯原版
|
||||||
|
|
||||||
|
#### 成员访问
|
||||||
|
|
||||||
|
`src/main/java/gg/vape/mapping/Mapping.java` + `MappingMethod` / `MappingField`:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 声明式注册(MFontRenderer 片段)
|
||||||
|
this.P = this.Y("drawInBatch", true, Void.TYPE,
|
||||||
|
String.class, Float.TYPE, Float.TYPE, Integer.TYPE, Boolean.TYPE,
|
||||||
|
MappedClasses.ZA, MappedClasses.ZK, MappedClasses.Y8,
|
||||||
|
Integer.TYPE, Integer.TYPE);
|
||||||
|
```
|
||||||
|
|
||||||
|
运行时解析链:
|
||||||
|
|
||||||
|
```text
|
||||||
|
MappingMethod.invoke*
|
||||||
|
├─ generatedInvoker (GeneratedAccessorFactory 生成的字节码访问器)
|
||||||
|
├─ reflectedMethod (Forge remap 未激活时直接反射)
|
||||||
|
└─ NativeMappedMemberInvoker
|
||||||
|
└─ Reflections
|
||||||
|
└─ MappingRegistry.matches()
|
||||||
|
├─ resources/mappings/forgeXXXX/methods.csv
|
||||||
|
├─ resources/mappings/forgeXXXX/fields.csv
|
||||||
|
└─ Vanilla*Mappings 的 SRG 表兜底
|
||||||
|
```
|
||||||
|
|
||||||
|
所以同一份 Java 代码可以匹配:
|
||||||
|
|
||||||
|
- 1.8.9 的 `func_78276_b`
|
||||||
|
- 1.16.5 的 SRG 名
|
||||||
|
- 1.17+ 的 `m_xxxxx_`
|
||||||
|
- 1.20.1+ 的 mojmap 名
|
||||||
|
- 26.x 的 mojmap 名
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 字体系统
|
||||||
|
|
||||||
|
### 2.1 字体资源与语言选择
|
||||||
|
|
||||||
|
`src/main/java/gg/vape/ui/font/FontManager.java`:
|
||||||
|
|
||||||
|
| `FontFamily` | 资源 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `PROXIMA`(默认) | `resources/proxima.ttf`、`proximabd.ttf` | `FontManager.e()` 读入 |
|
||||||
|
| `NOTO`(中文) | `resources/noto.ttf` | 约 1.1 MB 的子集字体 |
|
||||||
|
| `POPPINS` | `resources/poppins_rg.ttf` | |
|
||||||
|
| `ARIAL` | 系统 `arial.ttf` / `arialbd.ttf` | 扫描 `%LOCALAPPDATA%\Microsoft\Windows\Fonts` 与 `%SystemRoot%\Fonts` |
|
||||||
|
| `MINECRAFT` | 游戏自身 `FontSet` | 见 2.4 |
|
||||||
|
|
||||||
|
语言选择在 `src/main/java/gg/vape/ui/font/FontSelector.java`:
|
||||||
|
|
||||||
|
- English → `IdentityFontOption`(Proxima,不翻译)
|
||||||
|
- Chinese → `NotoFontOption`(`FontFamily.NOTO`,`noto.ttf`)
|
||||||
|
- Spanish / French / Portuguese → `FontOptionVariant*`(Proxima + 翻译表)
|
||||||
|
|
||||||
|
翻译表为 `resources/{english,chinese,french,spanish,portuguese}.properties.txt`,由 `FontOption` 用 `Properties` 载入。`FontOption.s(String)` 做整串查表,未命中返回原文。
|
||||||
|
|
||||||
|
### 2.2 字形光栅化:移植版 stb_truetype
|
||||||
|
|
||||||
|
`src/main/java/gg/vape/ui/font/stb/` 是一份完整的 stb_truetype Java 移植:
|
||||||
|
|
||||||
|
- `StbTrueTypeFontInfo`
|
||||||
|
- `StbTrueTypePackContext` / `StbTrueTypePackRange` / `StbTrueTypePackedChar`
|
||||||
|
- `StbTrueTypeGlyphPackNode` / `StbTrueTypeBakeContext`(在 `SmoothFontRasterState` 内)
|
||||||
|
- `StbGlyphCache`(MC 字体桥专用,见 2.4)
|
||||||
|
|
||||||
|
核心入口在 `src/main/java/gg/vape/ui/font/SmoothFontRasterState.java`(约 3400 行)。
|
||||||
|
|
||||||
|
`BufferedSmoothFontRenderer.w(byte[], int, String)` 的流程:
|
||||||
|
|
||||||
|
1. **收集字符集**
|
||||||
|
- ASCII `32..126`
|
||||||
|
- Latin-1 `160..255`
|
||||||
|
- `chinese.properties.txt` 中出现的所有字符
|
||||||
|
- 额外用 GBK 双字节区间(`0xA1..0xF7` × `0xA1..0xFE`)解出全部 CJK 汉字,保证游戏内中文物品/实体名不空白
|
||||||
|
2. **初始化字体**
|
||||||
|
- `SmoothFontRasterState.z(info, bytes, 0)`
|
||||||
|
- 取全局 ascent/descent,计算 `f5 = size * (0.6 / aspect)`
|
||||||
|
3. **打包图集**
|
||||||
|
- `4096 × 4096` 单通道位图
|
||||||
|
- `stbtt_PackBegin/PackFontRange`
|
||||||
|
- 得到每个字的 `x0,y0,x1,y1,xadvance` 与 UV
|
||||||
|
- 存入 `Map<Integer, SmoothFontGlyph>`
|
||||||
|
4. **创建 GL 纹理**
|
||||||
|
```java
|
||||||
|
GlImageTexture.create(4096, 4096, buffer, GL_RED /*6403*/,
|
||||||
|
GL_LINEAR /*9729*/, GL_REPEAT /*10497*/);
|
||||||
|
```
|
||||||
|
通过 `RenderThreadTaskQueue.enqueue(...)` 回到渲染线程执行。
|
||||||
|
|
||||||
|
> 注意:**每个字号、每个字体族都各自持有一张 4096² 图集**。
|
||||||
|
> 默认还会烘入全部 GBK 汉字,单张 R8 约 16 MB,加 mipmap 约 22 MB,多字号叠加后显存开销明显。
|
||||||
|
|
||||||
|
### 2.3 两个字体渲染器实现
|
||||||
|
|
||||||
|
`FontManager` 的缓存值是抽象类 `SmoothFontRenderer`,具体类型由后端决定:
|
||||||
|
|
||||||
|
```java
|
||||||
|
GuiRenderPrimitives.d()
|
||||||
|
? new BufferedSmoothFontRenderer(...)
|
||||||
|
: new LegacySmoothFontRenderer(...);
|
||||||
|
```
|
||||||
|
|
||||||
|
| 实现 | 版本 | 绘制方式 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `BufferedSmoothFontRenderer` | 1.16.5+ | 每字 4 顶点 → `RenderBatchBuilder` → universal shader |
|
||||||
|
| `LegacySmoothFontRenderer` | 1.7.10 / 1.8.9 / 1.12.2 | `glBegin(GL_QUADS)` 立即模式 + 独立 GLSL |
|
||||||
|
|
||||||
|
`BufferedSmoothFontRenderer` 的字体 shader 在 `resources/shader/universal_frag.frag`(`shaderMode = 11`):
|
||||||
|
|
||||||
|
```glsl
|
||||||
|
void fontShader() {
|
||||||
|
float alpha = texture(imgTexture, f_TexCoords).x;
|
||||||
|
alpha = max(0.0, alpha + 0.25 * (1.0 - alpha));
|
||||||
|
float smoothenAlpha = smoothstep(0.2, 0.8, alpha);
|
||||||
|
alpha = mix(alpha, 0.0, 1.0 - smoothenAlpha);
|
||||||
|
FragColor = vec4(f_VertexColor.rgb, alpha * f_VertexColor.a);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
“先加 0.25 再 smoothstep”是为了让小字号不发虚。
|
||||||
|
|
||||||
|
`LegacySmoothFontRenderer` 同样用 stb 建图集,但绘制走:
|
||||||
|
|
||||||
|
```java
|
||||||
|
GL11.glBegin(GL_QUADS);
|
||||||
|
GL11.glTexCoord2f(...);
|
||||||
|
GL11.glVertex2d(...);
|
||||||
|
GL11.glEnd();
|
||||||
|
```
|
||||||
|
|
||||||
|
并用 `glPushMatrix/glScalef` 做缩放;必要时回退 `Minecraft.getFontRenderer()` 画字。
|
||||||
|
|
||||||
|
### 2.4 Minecraft 原生字体桥:`StbSmoothFontRenderer`
|
||||||
|
|
||||||
|
当用户选择 `FontFamily.MINECRAFT` 时,`FontManager.x(int)` 返回 `StbSmoothFontRenderer`。它不读 TTF,而是读取游戏自己的字体:
|
||||||
|
|
||||||
|
1. `Minecraft.q()` 取 MC 的 `FontManager`
|
||||||
|
2. `h()` 取默认 `FontSet`
|
||||||
|
3. `StbGlyphCache` 对每个 code point 调 `FontSet.getGlyphInfo(char)`,取出:
|
||||||
|
- 纹理 id
|
||||||
|
- UV(`u0/v0/u1/v1`)
|
||||||
|
- advance
|
||||||
|
- ascent / descent
|
||||||
|
- glyph 尺寸
|
||||||
|
4. 缓存为 `StbGlyphCacheEntry`
|
||||||
|
5. 绘制时:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 彩色位图字体
|
||||||
|
BufferedGuiRenderPrimitives.drawMinecraftColorFontGlyph(...);
|
||||||
|
// R8 强度字体
|
||||||
|
BufferedGuiRenderPrimitives.drawMinecraftIntensityFontGlyph(...);
|
||||||
|
```
|
||||||
|
|
||||||
|
对应 universal shader 的两个分支:
|
||||||
|
|
||||||
|
| shaderMode | 函数 | 适用纹理 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 16 | `minecraftFontColorShader()` | RGBA8 彩色位图字体 |
|
||||||
|
| 17 | `minecraftFontIntensityShader()` | R8 强度字体(`.r` 当 alpha) |
|
||||||
|
|
||||||
|
纹理格式通过 `glGetTexLevelParameteri(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT)` 探测:
|
||||||
|
|
||||||
|
```java
|
||||||
|
bl2 = n3 != GL_R8; // 33321
|
||||||
|
```
|
||||||
|
|
||||||
|
桥不可用时回退到 wrapper 的 `Minecraft.getFontRenderer()`:
|
||||||
|
|
||||||
|
- `StbGlyphCache.l()` 明确要求 **1.21.10+**
|
||||||
|
- `StbSmoothFontRenderer.y(...)` 用 `MatrixStack.S(f,f,f)` 后调 `FontRenderer.E/V`
|
||||||
|
- 1.21.6+ 走 `RenderItemTextBridge`(新的 `Font.drawInBatch` 签名)
|
||||||
|
- 26.2 对空格单独处理(`StbGlyphCache.H(char)` 调 `getStringWidth(" ")`)
|
||||||
|
|
||||||
|
### 2.5 文本排版细节
|
||||||
|
|
||||||
|
`src/main/java/gg/vape/ui/font/SmoothFontRenderer.java` 统一了 API:
|
||||||
|
|
||||||
|
| 方法 | 含义 |
|
||||||
|
| --- | --- |
|
||||||
|
| `g/O` | 普通绘制;`O(..., boolean shadow)` |
|
||||||
|
| `v/I` | 带阴影;`I()` 先剥掉 `§` |
|
||||||
|
| `d/R/N/Y` | 宽度 / 高度测量 |
|
||||||
|
| `t/T` | 双色(渐变)文本 |
|
||||||
|
| `f` | 清空字符串/宽度缓存 |
|
||||||
|
|
||||||
|
具体行为:
|
||||||
|
|
||||||
|
- **§ 颜色码**
|
||||||
|
- 逐字符解析 `§x`
|
||||||
|
- `o(char, float[3])` 是 16 色表
|
||||||
|
- `§r` 恢复基础色
|
||||||
|
- **阴影**
|
||||||
|
- Buffered 非 Stb:`Integer.MIN_VALUE`(ARGB `0x80000000`,半透明黑)偏移 `+0.5,+0.5` 画一遍
|
||||||
|
- Stb:颜色乘 `0.25`,偏移 `+1,+1` 画一遍
|
||||||
|
- **宽度缓存**
|
||||||
|
- `SmoothFontRendererWidthCache`:`LinkedHashMap`,最多 5120 项
|
||||||
|
- 剥离 `§` 后的字符串也有缓存
|
||||||
|
- **字号 / GUI Scale 关系**
|
||||||
|
|
||||||
|
```java
|
||||||
|
n = (int)(16 * size * guiScaleFactor); // 烘焙字号
|
||||||
|
advance *= 0.6f / guiScaleFactor; // 逻辑宽度
|
||||||
|
```
|
||||||
|
|
||||||
|
即:**GUI Scale 只提高字形烘焙分辨率(超采样),不改变逻辑排版宽度**;实际屏幕尺寸由外层矩阵的 `2 * guiScale` 放大。
|
||||||
|
|
||||||
|
- **截断 / 自适应**
|
||||||
|
- `TextLabelFitScaleCache`:从最大字号往下降,直到宽度放得下
|
||||||
|
- `TruncatedTextComponent` / `FadingTruncatedTextComponent`
|
||||||
|
- `MarqueeTextRendererComponent`:跑马灯
|
||||||
|
- **翻译时机**
|
||||||
|
- `BufferedSmoothFontRenderer.b()` / `StbSmoothFontRenderer.Z()` 在绘制和测宽前都会执行:
|
||||||
|
|
||||||
|
```java
|
||||||
|
string = Vape.INSTANCE.getFontSelector().W().s(string);
|
||||||
|
```
|
||||||
|
|
||||||
|
- 因此翻译后的文本宽度也正确。
|
||||||
|
- **限制**
|
||||||
|
- 按 UTF-16 `char` 遍历,不处理代理对(emoji / 扩展 B 区汉字)
|
||||||
|
- CJK 覆盖到 GBK 范围为止
|
||||||
|
|
||||||
|
### 2.6 中文覆盖的构建期校验
|
||||||
|
|
||||||
|
`build.gradle` 注册了 `verifyFontCoverage`:
|
||||||
|
|
||||||
|
- 用 `tools/FontCoverageCheck.java` 直接解析 `noto.ttf` 的 cmap(format 0/4/6/12)
|
||||||
|
- 对照 `chinese.properties.txt` 中出现的每个字符
|
||||||
|
- 有缺字则构建失败
|
||||||
|
|
||||||
|
所以中文翻译新增字符时,必须同步裁剪或替换 `noto.ttf`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. GUI 系统
|
||||||
|
|
||||||
|
### 3.1 生命周期:不是一个 Minecraft `Screen`
|
||||||
|
|
||||||
|
Vape 的 ClickGUI 不继承 `GuiScreen`,而是画在游戏画面上的自绘 Overlay:
|
||||||
|
|
||||||
|
```text
|
||||||
|
HUD 打开(inputEnabled = true)
|
||||||
|
└─ 游戏 HUD 钩子 EventRender2D.create()
|
||||||
|
├─ GuiRenderPrimitives.o(displayWidth, displayHeight)
|
||||||
|
├─ ClientSettings.renderHudOverlay()/renderHudFrames()
|
||||||
|
├─ EventRender2D.fire()
|
||||||
|
└─ GuiRenderPrimitives.L(...)
|
||||||
|
|
||||||
|
ClickGUI 打开(inputEnabled = false)
|
||||||
|
└─ EventPostRenderTick.fire()
|
||||||
|
└─ GuiScreenNativeCallbackBridge.drawScreen(null, 0, 0, 0.0f)
|
||||||
|
└─ ClientSettings.renderGui()
|
||||||
|
└─ RenderBatchManager.flushGuiBatches(...)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 输入不走 MC 的 `mouseClicked`:
|
||||||
|
- 原生层回调 `GuiScreenNativeCallbackBridge.mouseClicked / handleMouseInput`
|
||||||
|
- 再进入 `InputEventDispatcher` / `MouseInputState`
|
||||||
|
- 打开 / 关闭:`ClientSettings.toggle()`
|
||||||
|
- `Minecraft.R()` 释放鼠标
|
||||||
|
- `gameSettings.P(false)`
|
||||||
|
- `inputEnabled = false`
|
||||||
|
- 26.x 专门注入:
|
||||||
|
- `GuiRendererRenderTickMappingTask` 在 `GuiRenderer.render()` 前后插:
|
||||||
|
- `EventRender2DHudCallback` → 只画 HUD(在游戏 HUD 下)
|
||||||
|
- `EventRender2DGuiCallback` → 画通知和 ClickGUI(在游戏 HUD 上)
|
||||||
|
|
||||||
|
这样做最大的好处:**完全绕开各版本 `Screen` / `GuiScreen` / `AbstractGui` 的 API 差异**。
|
||||||
|
|
||||||
|
### 3.2 坐标系与缩放
|
||||||
|
|
||||||
|
每帧开始:
|
||||||
|
|
||||||
|
```java
|
||||||
|
GuiRenderPrimitives.o(displayWidth, displayHeight);
|
||||||
|
// legacy: NativeBridge.rs(0, w, h) → glOrtho(0, w, h, 0, 1000, 3000)
|
||||||
|
// 然后 backend.scale(2, 2, 2)
|
||||||
|
|
||||||
|
OpenGlBackendHolder.backend.scale(guiScale, guiScale, guiScale);
|
||||||
|
```
|
||||||
|
|
||||||
|
- `Minecraft.J()/h()` 返回 **framebuffer 物理像素**
|
||||||
|
- 正交投影覆盖 `0..framebufferWidth`
|
||||||
|
- 先固定 `scale(2,2,2)`,再乘 Vape 自己的 GUI Scale:
|
||||||
|
- `0.5 / 0.8 / 1.0 / 1.2 / 1.5`
|
||||||
|
- Auto 按高度选:`>= 2000 → 1.5`,`>= 1000 → 1.2`,否则 `1.0`
|
||||||
|
- 因此 **1 个 UI 逻辑单位 ≈ `2 * guiScale` 物理像素**
|
||||||
|
- Scissor 按同一比例换算:
|
||||||
|
|
||||||
|
```java
|
||||||
|
double d5 = 2.0 * Vape.INSTANCE.getClientSettings().getGuiScaleFactor();
|
||||||
|
```
|
||||||
|
|
||||||
|
- 字体烘焙尺寸同样乘 `guiScale`,但逻辑宽度除回去,保证改 GUI Scale 时布局不跳、只是更清晰
|
||||||
|
|
||||||
|
### 3.3 组件树与布局
|
||||||
|
|
||||||
|
核心目录 `src/main/java/gg/vape/ui/click/`:
|
||||||
|
|
||||||
|
| 类 / 目录 | 职责 |
|
||||||
|
| --- | --- |
|
||||||
|
| `GuiComponent` | 位置/尺寸、可见性、父子关系、鼠标/键盘监听、Tooltip、绑定 `Value` |
|
||||||
|
| `FrameComponent extends GuiComponent` | 可滚动 Frame 的基类 |
|
||||||
|
| `Frame` | 可拖动/可缩放的窗口 |
|
||||||
|
| `FrameStackManager` / `ClickGuiFrameManager` | 窗口栈、置顶、Popup |
|
||||||
|
| `PopupFrame` / `AnchoredPopupFrame` / `DimmedCenteredPopupFrame` | 弹窗 |
|
||||||
|
| `layout/ComponentLayout` | 布局约束与排版 |
|
||||||
|
| `layout/WrappingFlowLayout` / `BottomUpFlowLayout` | 流式布局 |
|
||||||
|
| `module.none.ClientSettings` | 每帧调度、GUI Scale、Frame 注册 |
|
||||||
|
|
||||||
|
`FrameComponent` 的两个核心方法:
|
||||||
|
|
||||||
|
- `c()`:**渲染**
|
||||||
|
- 背景 / 圆角 / 阴影
|
||||||
|
- 滚动条
|
||||||
|
- `scissor` 裁剪
|
||||||
|
- 递归子组件 `child.c()`
|
||||||
|
- `J()`:**更新 / 交互**
|
||||||
|
- hover
|
||||||
|
- 点击、滚动
|
||||||
|
- tooltip
|
||||||
|
- 递归子组件
|
||||||
|
|
||||||
|
文本组件最终都落到:
|
||||||
|
|
||||||
|
```java
|
||||||
|
SmoothFontRenderer fr = getFontRenderer(scale);
|
||||||
|
// 或 getAlternateFontRenderer(scale) (bold)
|
||||||
|
|
||||||
|
fr.d(text, x, y, color); // 无阴影
|
||||||
|
fr.v(text, x, y, color); // 有阴影
|
||||||
|
```
|
||||||
|
|
||||||
|
`GuiComponent.getFontRenderer(double scale)`:
|
||||||
|
|
||||||
|
```java
|
||||||
|
return this.fontOption != null
|
||||||
|
? this.fontOption.k((float) scale, false)
|
||||||
|
: Vape.INSTANCE.getFontManager().Y(scale);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.4 绘制门面:`GuiRenderPrimitives` + 双后端
|
||||||
|
|
||||||
|
`src/main/java/gg/vape/utils/render/GuiRenderPrimitives.java` 是所有 UI 绘制的统一入口。每个方法内部都做同一个判断:
|
||||||
|
|
||||||
|
```java
|
||||||
|
if (GuiRenderPrimitives.d()) { // 1.16.5+
|
||||||
|
// BufferedGuiRenderPrimitives / RenderBatchBuilder
|
||||||
|
} else {
|
||||||
|
// GL11 立即模式 + 自带 GLSL
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`d()` 的实现:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public static boolean d() {
|
||||||
|
return ForgeVersion.MC_1_16_5.d();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
后端由 `OpenGlBackendHolder` 选择:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public static OpenGlBackend backend = GuiRenderPrimitives.d()
|
||||||
|
? new BufferedOpenGlBackend()
|
||||||
|
: new LegacyOpenGlBackend();
|
||||||
|
```
|
||||||
|
|
||||||
|
| 后端 | 矩阵 | 顶点 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `LegacyOpenGlBackend` | `glPushMatrix/glTranslatef/glScalef` | `glBegin/glVertex` |
|
||||||
|
| `BufferedOpenGlBackend` | 软件 `RenderMatrixStack` | 只记录 capability,不直接画 |
|
||||||
|
|
||||||
|
### 3.5 现代路径:自建批次 + Universal Shader
|
||||||
|
|
||||||
|
这是跨版本 GUI 的核心设计。
|
||||||
|
|
||||||
|
1. **每个绘制调用产出一个 `RenderBatchBuilder`**
|
||||||
|
- `addSolidRect` / `addRoundedRect` / `addCircle` / `addFontGlyph`
|
||||||
|
- `addTexturedRect` / `addBlurPass` / `addCompositeRoundedRect` …
|
||||||
|
2. **固定 15 个顶点属性**(与 `universal_vert.vert` 的 `layout(location=0..14)` 对应)
|
||||||
|
|
||||||
|
```text
|
||||||
|
shaderMode, position, uv, color,
|
||||||
|
inner, feather, center, middleAngle, sweepAngle,
|
||||||
|
screenDimensions, origin, innerRect, radius3, spread, corners
|
||||||
|
```
|
||||||
|
|
||||||
|
`shaderMode` 就是“这个顶点走哪段片元逻辑”的编号。
|
||||||
|
|
||||||
|
3. **`RenderBatchManager.queueGuiBatch(builder)`**
|
||||||
|
- 按纹理、拓扑、模型矩阵、GL capability、scissor 是否相同尝试合并
|
||||||
|
- 每个 batch 最多合并 4500 个 builder
|
||||||
|
4. **`flushGuiBatches()`**
|
||||||
|
- 保存并接管 GL 状态(VAO / VBO / program / texture / framebuffer)
|
||||||
|
- `RenderBatchBuffer.stageBatch()` → 上传顶点/索引
|
||||||
|
- `glDrawElements`
|
||||||
|
- 恢复状态
|
||||||
|
5. **Universal Shader**
|
||||||
|
- `resources/shader/universal_vert.vert`
|
||||||
|
- `resources/shader/universal_frag.frag`
|
||||||
|
|
||||||
|
顶点着色器:
|
||||||
|
|
||||||
|
```glsl
|
||||||
|
gl_Position = u_Projection * u_View * u_Model * vec4(aPos, 1.0);
|
||||||
|
```
|
||||||
|
|
||||||
|
片元着色器按 `shaderMode` 分发:
|
||||||
|
|
||||||
|
| mode | 功能 |
|
||||||
|
| --- | --- |
|
||||||
|
| 0 | `arcStroke` |
|
||||||
|
| 1 | `blur` |
|
||||||
|
| 2 / 3 | 圆 / 圆环描边 |
|
||||||
|
| 4 | 纹理圆 |
|
||||||
|
| 5 / 6 | 圆角矩形 / 圆角描边 |
|
||||||
|
| 7 | 圆角纹理矩形 |
|
||||||
|
| 8 | 阴影 |
|
||||||
|
| 9 | 纯色 |
|
||||||
|
| 10 | 纹理 |
|
||||||
|
| 11 | 自定义字体 |
|
||||||
|
| 12 | 反向圆角 |
|
||||||
|
| 13 / 14 | 胶囊 / 渐变 |
|
||||||
|
| 16 / 17 | MC 彩色字体 / MC 强度字体 |
|
||||||
|
|
||||||
|
所有圆角、描边、圆、弧、模糊、字体、阴影、渐变都在一个 shader 里完成。
|
||||||
|
**GL 侧只依赖最基础的 VAO / VBO / 纹理 / 混合**,与 MC 的 `RenderType` / `BufferBuilder` / `VertexConsumer` API 解耦,因此 1.17 / 1.20 / 1.21.6 / 26.x 的渲染管线重写基本影响不到它。
|
||||||
|
|
||||||
|
### 3.6 旧版路径:立即模式 + 独立 shader
|
||||||
|
|
||||||
|
1.8.9 / 1.12.2 等版本:
|
||||||
|
|
||||||
|
- `NativeBridge.rs()` 用 `glOrtho` 设置 2D 投影
|
||||||
|
- `GL11.glBegin/glVertex/glTexCoord/glColor` 立即模式
|
||||||
|
- 圆角 / 圆 / 阴影等用 `src/main/java/gg/vape/utils/render/shader/*ShaderProgram` 单独编译的 GLSL
|
||||||
|
- 如 `LegacyFontShaderProgram`:`#version 430 compatibility` + `gl_ModelViewProjectionMatrix`
|
||||||
|
- 每个绘制函数显式 `glPushMatrix/glPopMatrix`、`glEnable/glDisable`
|
||||||
|
- `GlStateManager` 包装层负责不同版本的混合、纹理、alpha test 状态
|
||||||
|
|
||||||
|
### 3.7 1.21.6+ / 26.x 的特殊处理
|
||||||
|
|
||||||
|
- **1.21.6+**
|
||||||
|
- MC 的 `Font.drawInBatch` 改成新签名(`Matrix4f` / `MultiBufferSource` / `DisplayMode`)
|
||||||
|
- `MFontRenderer` 针对 `MC_26_1` 与 `MC_26_2` 分别注册不同的 `drawInBatch` / `text` / `drawString` 映射
|
||||||
|
- **1.21.10+**
|
||||||
|
- `Minecraft.getMainRenderTarget()` 可取主 RT
|
||||||
|
- `RenderBatchManager.refreshTargetFramebuffer()` 会解析颜色/深度纹理,并包一个自己的 FBO,保证 GUI 画到参与最终合成的目标上
|
||||||
|
- **26.2**
|
||||||
|
- `GuiRenderer.render()` 前/后分别插 HUD / GUI 回调
|
||||||
|
- 通知从 HUD pass 移到 GUI pass:
|
||||||
|
|
||||||
|
```java
|
||||||
|
if (!ForgeVersion.MC_26_2.d()) {
|
||||||
|
notificationManager.renderNotifications();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- 字体桥对空格、纹理格式、`FontSet` 初始化都有专门分支
|
||||||
|
|
||||||
|
### 3.8 模糊、物品与实体预览
|
||||||
|
|
||||||
|
- **背景模糊**
|
||||||
|
- 旧版:`ShaderGroupRenderStateManager` 使用 MC 自己的 post-processing `ShaderGroup`
|
||||||
|
- 1.16.5+:`BlurRegionRenderer` + `RenderBatchBuilder.addBlurPass()`,走 universal shader 的 `blur()`
|
||||||
|
- **物品图标**
|
||||||
|
- `ItemIconRenderer` / `ItemStackRenderUtils`
|
||||||
|
- 1.21.6+ 用 `RenderItemTextBridge` / `Matrix4fHandle`
|
||||||
|
- **实体预览**
|
||||||
|
- `EntityModelFramebufferRenderer`
|
||||||
|
- `Post117EntityModelFramebufferRenderer`
|
||||||
|
- 按版本选择“直接画”或“渲染到 FBO 再当纹理贴”
|
||||||
|
- **纹理图集**
|
||||||
|
- `TextureAtlasRegistry` / `TextureAtlas` / `TextureAtlasRegion`
|
||||||
|
- `ImageRenderer` 负责 PNG 解码与图集区域查找
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 跨版本路径一览
|
||||||
|
|
||||||
|
| 版本 | GUI 后端 | 字体渲染 | 备注 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 1.7.10 | Legacy | `LegacySmoothFontRenderer` + MC 字体回退 | `glOrtho` + 立即模式 |
|
||||||
|
| 1.8.9(含 Badlion) | Legacy | 同上 | Badlion 有独立按键队列 / 渲染回调 |
|
||||||
|
| 1.12.2 | Legacy | 同上 | |
|
||||||
|
| 1.16.5 | **Buffered** | `BufferedSmoothFontRenderer` | 第一批切到自建 VAO/VBO + shader |
|
||||||
|
| 1.17–1.20.5 | Buffered | Buffered | `drawInBatch(MatrixStack...)` 系 |
|
||||||
|
| 1.20.6–1.21.5 | Buffered | Buffered / MC 字体桥 | `drawInBatch(Matrix4f, MultiBufferSource, DisplayMode...)` |
|
||||||
|
| 1.21.6–1.21.11 | Buffered | Buffered / MC 字体桥 | 新 RenderPass / GPU 管线,Vape 仍用自建 shader |
|
||||||
|
| 26.1 / 26.2 | Buffered | Buffered / MC 字体桥 | `GuiRenderer.render` 前后双回调;自建 FBO 包装主 RT |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 关键结论与坑
|
||||||
|
|
||||||
|
1. **字体不是“用 MC 的 FontRenderer 改个 TTF”**
|
||||||
|
- 内嵌 stb_truetype 把 TTF 烘成图集
|
||||||
|
- 自建 shader 画四边形
|
||||||
|
- 中文完整覆盖 GBK 汉字
|
||||||
|
- 构建期还有 cmap 覆盖校验
|
||||||
|
|
||||||
|
2. **GUI 不是 `GuiScreen`**
|
||||||
|
- 每帧在 HUD / PostRender 阶段画自绘 Overlay
|
||||||
|
- 输入靠原生回调
|
||||||
|
- 天然规避各版本 `Screen` API 差异
|
||||||
|
|
||||||
|
3. **跨版本的核心是“两条渲染路径 + 一套映射层”**
|
||||||
|
- 1.16.5+:自建批次 + universal shader(GL 基础 API)
|
||||||
|
- 旧版:立即模式 + 独立 shader + `glOrtho`
|
||||||
|
- 所有 MC 类/字段/方法通过 `MappedClasses` / `MappingMethod` / `Reflections` 按版本解析
|
||||||
|
|
||||||
|
4. **缩放策略**
|
||||||
|
- 逻辑坐标固定
|
||||||
|
- `size * guiScale` 只影响烘焙分辨率
|
||||||
|
- 屏幕尺寸由 `2 * guiScale` 统一缩放决定
|
||||||
|
- scissor 同步换算
|
||||||
|
|
||||||
|
5. **主要代价 / 坑**
|
||||||
|
- 每个字号一张 4096² R8 图集(含全 GBK),显存占用高
|
||||||
|
- 系统字体依赖 Windows 路径(Arial / Bahnschrift)
|
||||||
|
- `StbSmoothFontRenderer` 的 MC 字体桥只有 1.21.10+ 可用,低版本回退 MC 原版字体
|
||||||
|
- UTF-16 `char` 遍历不支持代理对(emoji / 扩展汉字)
|
||||||
|
- 旧版 shader 依赖 `#version 430 compatibility`,对驱动/上下文有隐含要求
|
||||||
|
- 1.21.6+ / 26.x 的 framebuffer 与 GUI pass 需要单独的兼容处理
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 建议阅读顺序
|
||||||
|
|
||||||
|
如果要继续修改字体或 GUI,建议从这几个入口按顺序看:
|
||||||
|
|
||||||
|
1. `src/main/java/gg/vape/ui/font/FontManager.java`
|
||||||
|
- 字体选择、字号缓存、GUI Scale 参与方式
|
||||||
|
2. `src/main/java/gg/vape/ui/font/BufferedSmoothFontRenderer.java`
|
||||||
|
- TTF → 字形图集 → 顶点
|
||||||
|
3. `src/main/java/gg/vape/ui/font/StbSmoothFontRenderer.java`
|
||||||
|
- MC 原生 `FontSet` 桥
|
||||||
|
4. `src/main/java/gg/vape/utils/render/RenderBatchBuilder.java`
|
||||||
|
- 图形/字体的顶点语义
|
||||||
|
5. `src/main/resources/resources/shader/universal_frag.frag`
|
||||||
|
- 所有 shaderMode 的实际像素逻辑
|
||||||
|
6. `src/main/java/gg/vape/utils/render/GuiRenderPrimitives.java`
|
||||||
|
- 双后端分界与所有绘制原语
|
||||||
|
7. `src/main/java/gg/vape/module/none/ClientSettings.java` 的 `renderGui()` / `renderHudFrames()`
|
||||||
|
- 每帧顺序、缩放、Frame 调度
|
||||||
|
8. `src/main/java/gg/vape/ui/click/frame/FrameComponent.java`
|
||||||
|
- 组件树渲染 `c()` 与交互 `J()`
|
||||||
Reference in new issue
Block a user