Feat: Add cross-version TTF font rendering

- Port stb_truetype rasterizer and bake TTF glyph atlases\n- Add FontRenderer/Render2D API with section colors, shadows and CJK fallback\n- Add 1.8.9 GL11 backend and 26.2 GuiRenderState backend\n- Hook GuiIngame/GuiIngameForge and Gui#extractRenderState for per-frame 2D\n- Bundle Proxima, Noto and Poppins fonts\n- Add render/font documentation
This commit is contained in:
xiaozhou233 committed 2026-11-05 20:31:32 +08:00
1 parent 6c19985e52
commit c3dab97779
54 files changed
+6545 -7

No files matched your search

+5
View File
@@ -24,6 +24,11 @@ dependencies {
// 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.
@@ -3,6 +3,8 @@ 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.render.FontDebugOverlay;
import cn.xiaozhou233.orangex.render.Render2DManager;
import cn.xiaozhou233.orangex.runtime.RuntimeDetector;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import cn.xiaozhou233.orangex.wrapper.MinecraftFactory;
@@ -23,6 +25,8 @@ public class OrangeX {
.build();
@Getter
private RuntimeInfo runtimeInfo;
@Getter
private Render2DManager render2DManager;
public OrangeX() {
System.out.println("OrangeX <init> start!");
@@ -39,8 +43,13 @@ public class OrangeX {
Minecraft minecraft = MinecraftFactory.create(runtimeInfo, MappingManager.getResolver());
System.out.println(minecraft.getMinecraft());
// DELETE THIS ON RELEASE:
eventBus.register(this);
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();
}
@@ -48,9 +57,4 @@ public class OrangeX {
public void stop() {
System.out.println("OrangeX stop!");
}
@Subscribe()
public void onTick(EventTickPre event) {
System.out.println("PRE 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,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;
}
}
@@ -16,6 +16,7 @@ public final class HookManager {
private HookManager() {
register(new TickHook());
register(new Render2DHook());
}
public void register(ClassHook hook) {
@@ -0,0 +1,105 @@
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;
/**
* 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;
}
}
@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 not obfuscated.
methodName = "renderGameOverlay";
methodDescriptor = "(F)V";
} 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);");
System.out.println("[OrangeX] Render2DHook injected: "
+ ctClass.getName() + "#" + methodName + methodDescriptor);
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);");
System.out.println("[OrangeX] Render2DHook injected: "
+ ctClass.getName() + "#" + target.getTargetName()
+ target.getTargetDescriptor());
break;
}
default:
break;
}
}
}
@@ -0,0 +1,40 @@
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 {
private static boolean logged;
@Subscribe(threadMode = ThreadMode.POSTING)
public void onRender2D(EventRender2D event) {
Render2D render2D = event.getRender2D();
if (!logged) {
logged = true;
System.out.println("[OrangeX] Render2D event: "
+ render2D.getWidth() + "x" + render2D.getHeight()
+ " scale=" + render2D.getGuiScale());
}
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,59 @@
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;
private boolean hookLogged;
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();
boolean hasSubscribers = eventBus.hasSubscriberForEvent(EventRender2D.class);
if (!hookLogged) {
hookLogged = true;
System.out.println("[OrangeX] Render2D hook fired; subscribers="
+ hasSubscribers + ", context="
+ (platformContext == null ? "null" : platformContext.getClass().getName()));
}
if (!hasSubscribers) {
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,28 @@
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);
/**
* 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,162 @@
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));
long start = System.currentTimeMillis();
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);
System.out.println("[OrangeX] Baked " + family.name().toLowerCase()
+ (bold ? "-bold" : "") + " " + rasterHeight + "px ("
+ atlas.getGlyphs().size() + " glyphs, "
+ (System.currentTimeMillis() - start) + " ms)");
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
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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();
}
}
@@ -0,0 +1,6 @@
package cn.xiaozhou233.orangex.render.font.stb;
public class StbTrueTypeGlyphPackNode {
public int z;
}
@@ -0,0 +1,8 @@
package cn.xiaozhou233.orangex.render.font.stb;
public class StbTrueTypeKerningEntry {
public int y;
public int q;
public int o;
}
@@ -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;
}
@@ -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;
}
@@ -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]);
}
}
}
@@ -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;
}
@@ -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);
}
@@ -0,0 +1,94 @@
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;
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);
int glError = GL11.glGetError();
System.out.println("[OrangeX] Font texture uploaded: id=" + textureId
+ " size=" + atlas.getWidth() + "x" + atlas.getHeight()
+ " glError=" + glError);
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);
}
@Override
public String getName() {
return "1.8.9/GL11";
}
}
@@ -0,0 +1,35 @@
package cn.xiaozhou233.orangex.render.internal.v1_8_9;
import cn.xiaozhou233.orangex.render.internal.FontTexture;
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() {
org.lwjgl.opengl.GL11.glDeleteTextures(textureId);
}
}
@@ -0,0 +1,142 @@
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.BufferUtils;
import org.lwjgl.opengl.GL11;
import java.nio.FloatBuffer;
/**
* Immediate-mode glyph drawer for the legacy (1.8.9) OpenGL pipeline.
*/
final class V1_8_9GlyphDrawer implements GlyphDrawer {
private int boundTexture = -1;
private static boolean firstDrawLogged;
private boolean initialized;
private boolean previousBlend;
private boolean previousTexture2D;
private boolean previousAlphaTest;
private boolean previousDepthTest;
private boolean previousCullFace;
private boolean previousLighting;
private boolean previousScissorTest;
private boolean previousFog;
private int previousTexture;
private int previousTextureEnvMode;
private int previousActiveTexture;
private final FloatBuffer previousColor = BufferUtils.createFloatBuffer(16);
@Override
public void drawGlyph(FontTexture texture, Glyph glyph,
double penX, double baseline, double scale, int argb) {
if (!(texture instanceof V1_8_9FontTexture)) {
return;
}
initialize();
int textureId = ((V1_8_9FontTexture) texture).getTextureId();
if (textureId != boundTexture) {
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
boundTexture = textureId;
}
if (!firstDrawLogged) {
firstDrawLogged = true;
System.out.println("[OrangeX] Font first glyph draw: tex=" + textureId
+ " penX=" + penX + " baseline=" + baseline
+ " scale=" + scale + " glError=" + GL11.glGetError());
}
float red = ((argb >> 16) & 0xFF) / 255.0f;
float green = ((argb >> 8) & 0xFF) / 255.0f;
float blue = (argb & 0xFF) / 255.0f;
float alpha = ((argb >>> 24) & 0xFF) / 255.0f;
GL11.glColor4f(red, green, blue, alpha);
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 flush() {
if (!initialized) {
return;
}
GL11.glBindTexture(GL11.GL_TEXTURE_2D, previousTexture);
GL11.glColor4f(previousColor.get(0), previousColor.get(1),
previousColor.get(2), previousColor.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_SCISSOR_TEST, previousScissorTest);
setEnabled(GL11.GL_FOG, previousFog);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE, previousTextureEnvMode);
org.lwjgl.opengl.GL13.glActiveTexture(previousActiveTexture);
initialized = false;
boundTexture = -1;
}
private void initialize() {
if (initialized) {
return;
}
initialized = true;
previousTexture = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
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);
previousScissorTest = GL11.glIsEnabled(GL11.GL_SCISSOR_TEST);
previousFog = GL11.glIsEnabled(GL11.GL_FOG);
previousTextureEnvMode = GL11.glGetTexEnvi(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE);
previousActiveTexture = GL11.glGetInteger(org.lwjgl.opengl.GL13.GL_ACTIVE_TEXTURE);
org.lwjgl.opengl.GL13.glActiveTexture(org.lwjgl.opengl.GL13.GL_TEXTURE0);
previousColor.clear();
GL11.glGetFloat(GL11.GL_CURRENT_COLOR, previousColor);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(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_SCISSOR_TEST);
GL11.glDisable(GL11.GL_FOG);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);
}
private static void setEnabled(int capability, boolean enabled) {
if (enabled) {
GL11.glEnable(capability);
} else {
GL11.glDisable(capability);
}
}
}
@@ -0,0 +1,106 @@
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 java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* 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 final FontManager fonts;
private final double guiScale;
private final V1_8_9GlyphDrawer drawer = new V1_8_9GlyphDrawer();
private final int width;
private final int height;
V1_8_9Render2D(FontManager fonts, RuntimeInfo runtimeInfo,
MappingResolver resolver, Object minecraft) {
this.fonts = fonts;
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 flush() {
drawer.flush();
}
}
@@ -0,0 +1,90 @@
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;
import java.lang.reflect.Constructor;
import java.nio.ByteBuffer;
import java.util.function.Supplier;
/**
* 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;
public V26_2FontBackend(RuntimeInfo runtimeInfo) {
this.loader = runtimeInfo.getMinecraftClassLoader();
}
@Override
public FontTexture createTexture(FontAtlas atlas) {
try {
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];
}
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 dynamicTexture = dynamicTextureConstructor.newInstance(
new Supplier<String>() {
@Override
public String get() {
return "OrangeX font atlas";
}
},
image);
Object textureView = dynamicTextureClass.getMethod("getTextureView")
.invoke(dynamicTexture);
Object sampler = dynamicTextureClass.getMethod("getSampler")
.invoke(dynamicTexture);
System.out.println("[OrangeX] 26.2 font texture created: "
+ width + "x" + height);
return new V26_2FontTexture(dynamicTexture, textureView, sampler,
width, height);
} catch (Throwable throwable) {
throw new IllegalStateException("Cannot upload the 26.2 font atlas",
throwable);
}
}
@Override
public Render2D createRender2D(FontManager fonts, Object platformContext) {
return new V26_2Render2D(fonts, platformContext, loader);
}
@Override
public String getName() {
return "26.2/GuiRenderState";
}
}
@@ -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);
}
}
}
@@ -0,0 +1,59 @@
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 static boolean firstDrawLogged;
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);
if (!firstDrawLogged) {
firstDrawLogged = true;
System.out.println("[OrangeX] 26.2 first glyph blit: "
+ x0 + "," + y0 + " -> " + x1 + "," + y1
+ " tex=" + fontTexture.getTextureView());
}
} catch (Throwable throwable) {
throw new IllegalStateException("Failed to submit a GUI glyph", throwable);
}
}
}
@@ -0,0 +1,138 @@
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 static boolean contextLogged;
private final FontManager fonts;
private final V26_2GlyphDrawer drawer;
private final int width;
private final int height;
private final double guiScale;
V26_2Render2D(FontManager fonts, Object gui, ClassLoader loader) {
this.fonts = fonts;
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));
if (!contextLogged) {
contextLogged = true;
System.out.println("[OrangeX] 26.2 Render2D: "
+ width + "x" + height + " scale=" + guiScale);
}
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.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 flush() {
// Everything was submitted to the GuiRenderState; nothing to restore.
}
}
+31
View File
@@ -0,0 +1,31 @@
# 渲染相关文档
本目录记录客户端字体、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 接入、调试参数与限制 |
## 快速导航
- 字体资源与语言选择 → 主文档 §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` 为源码根,涉及的文件路径均相对于该目录。
文中结论来自静态源码阅读,运行时行为仍需结合实际客户端验证。
+194
View File
@@ -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 正常、其他版本没反应”。
```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
[OrangeX] Baked proxima 20px (191 glyphs, 33 ms)
[OrangeX] Baked noto 28px (... glyphs, ... ms)
```
## 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`。
+642
View File
@@ -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()`