From 7924769ab1f642cc79aa08adc7434a24e2809a8f Mon Sep 17 00:00:00 2001 From: Death Fuel <108496936+DeathFuel@users.noreply.github.com> Date: Sat, 4 Oct 2025 20:20:38 +0200 Subject: [PATCH] Custom/Smooth Font (#1017) --- README.MD | 4 +- dependencies.gradle | 16 +- .../client/font/BatchingFontRenderer.java | 318 +++++++--------- .../angelica/client/font/FontProvider.java | 20 + .../client/font/FontProviderCustom.java | 302 +++++++++++++++ .../angelica/client/font/FontProviderMC.java | 106 ++++++ .../client/font/FontProviderUnicode.java | 93 +++++ .../angelica/client/font/FontStrategist.java | 90 +++++ .../angelica/client/gui/FontConfigScreen.java | 359 ++++++++++++++++++ .../angelica/client/gui/SliderClone.java | 114 ++++++ .../angelica/config/AngelicaConfig.java | 5 - .../angelica/config/AngelicaGuiConfig.java | 8 +- .../angelica/config/FontConfig.java | 58 +++ .../angelica/loading/AngelicaTweaker.java | 2 + .../gtnewhorizons/angelica/mixins/Mixins.java | 1 + .../mixins/interfaces/ResourceAccessor.java | 7 + .../gui/ReeseSodiumVideoOptionsScreen.java | 21 +- .../client/gui/frame/tab/TabFrame.java | 3 +- .../resources/assets/angelica/lang/en_US.lang | 25 ++ .../assets/angelica/shaders/fontFilter.fsh | 65 ++++ .../assets/angelica/shaders/fontFilter.vsh | 12 + .../fontrenderer/MixinFontRenderer.java | 40 +- .../fontrenderer/MixinMCResourceAccessor.java | 19 + 23 files changed, 1493 insertions(+), 195 deletions(-) create mode 100644 src/main/java/com/gtnewhorizons/angelica/client/font/FontProvider.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderCustom.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderMC.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderUnicode.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/client/font/FontStrategist.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/client/gui/FontConfigScreen.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/config/FontConfig.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ResourceAccessor.java create mode 100644 src/main/resources/assets/angelica/shaders/fontFilter.fsh create mode 100644 src/main/resources/assets/angelica/shaders/fontFilter.vsh create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinMCResourceAccessor.java diff --git a/README.MD b/README.MD index c0f71e7e7..43f3c7f1c 100644 --- a/README.MD +++ b/README.MD @@ -7,7 +7,7 @@ * It's a cute angle -mitchej123 * It's the angel that pulls you out of OptiFine's hell -Roadhog360 -## **Beta Quality - Here there be Dragons** +## **Beta Quality - Here there be Dragons** * Shaders - Beta * Complementary & BSL mostly function, but have some bugs * Sildurs, Seus, and any other shader probably doesn't work @@ -27,7 +27,6 @@ # Known Incompatibilities * FalseTweaks - Not currently planned (Looking for volunteers) [Might work if you effectively disable most of the mod] -* SmoothFont - Not currently planned (Looking for volunteers) * RPLE - Not currently planned (Looking for volunteers) * LiteLoader - Install [LiteloaderLoader](https://github.com/Midnight145/LiteloaderLoader) @@ -42,6 +41,7 @@ * [Hodgepodge 2.4.3 and below](https://github.com/GTNewHorizons/Hodgepodge/releases) - Use 0.4.5 or above * CodeChicken[Core](https://github.com/GTNewHorizons/CodeChickenCore/releases)/[Lib](https://github.com/GTNewHorizons/CodeChickenLib/releases) <1.2.0 - Threading issues, use 1.3.0+ * Neodymium - Untested, but unlikely to be compatible. (Chunk Meshing is definitely incompatible, other features might work depending on config) +* SmoothFont - Equivalent functionality added # Credits * ShadersMod diff --git a/dependencies.gradle b/dependencies.gradle index 121987e05..4a6cd2cb8 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -49,7 +49,7 @@ configurations { } dependencies { - compileOnly("com.github.GTNewHorizons:Hodgepodge:2.6.97") + compileOnly("com.github.GTNewHorizons:Hodgepodge:2.6.107") compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.0.7") { transitive = false } @@ -61,7 +61,7 @@ dependencies { // Iris Shaders compileOnly('org.jetbrains:annotations:26.0.2') - api("com.github.GTNewHorizons:GTNHLib:0.6.39:dev") + api("com.github.GTNewHorizons:GTNHLib:0.6.40:dev") shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0 shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-4.g6b42bca") { exclude module: "antlr4" // we only want to shadow the runtime module @@ -70,18 +70,18 @@ dependencies { compileOnly "org.apache.ant:ant:1.8.2" // Because who doesn't want NEI - devOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.7.72-GTNH:dev') + devOnlyNonPublishable('com.github.GTNewHorizons:NotEnoughItems:2.7.90-GTNH:dev') devOnlyNonPublishable('com.github.GTNewHorizons:CodeChickenCore:1.4.7:dev') // Notfine Deps compileOnly("thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev") - devOnlyNonPublishable("com.github.GTNewHorizons:Baubles-Expanded:2.1.9-GTNH:dev") - compileOnly("com.github.GTNewHorizons:twilightforest:2.7.9:dev") { transitive = false } + devOnlyNonPublishable("com.github.GTNewHorizons:Baubles-Expanded:2.1.15-GTNH:dev") + compileOnly("com.github.GTNewHorizons:twilightforest:2.7.13:dev") { transitive = false } compileOnly(rfg.deobf('curse.maven:witchery-69673:2234410')) - compileOnly("com.github.GTNewHorizons:TinkersConstruct:1.13.48-GTNH:dev") { transitive = false } - compileOnly("com.github.GTNewHorizons:Natura:2.8.8:dev") + compileOnly("com.github.GTNewHorizons:TinkersConstruct:1.13.54-GTNH:dev") { transitive = false } + compileOnly("com.github.GTNewHorizons:Natura:2.8.9:dev") - compileOnly("com.github.GTNewHorizons:ThaumicHorizons:1.7.6:dev") + compileOnly("com.github.GTNewHorizons:ThaumicHorizons:1.7.8:dev") compileOnly("com.github.GTNewHorizons:Battlegear2:1.4.3:dev") { transitive = false } diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java index 418a6fee5..504b7f7eb 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java @@ -1,27 +1,29 @@ package com.gtnewhorizons.angelica.client.font; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; - +import com.google.common.collect.ImmutableSet; +import com.gtnewhorizons.angelica.config.FontConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor; -import com.gtnewhorizons.angelica.config.AngelicaConfig; -import it.unimi.dsi.fastutil.chars.Char2ShortOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import jss.util.RandomXoshiro256StarStar; -import net.minecraft.client.Minecraft; +import net.coderbot.iris.gl.program.Program; +import net.coderbot.iris.gl.program.ProgramBuilder; import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.ScaledResolution; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; +import org.apache.commons.io.IOUtils; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; -import java.util.Arrays; +import java.nio.charset.StandardCharsets; import java.util.Comparator; import java.util.Objects; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; + /** * A batching replacement for {@code FontRenderer} * @@ -31,8 +33,6 @@ public class BatchingFontRenderer { /** The underlying FontRenderer object that's being accelerated */ protected FontRenderer underlying; - /** Cached locations for each unicode page atlas */ - private final ResourceLocation[] unicodePageLocations; /** Array of width of all the characters in default.png */ protected int[] charWidth = new int[256]; /** Array of the start/end column (in upper/lower nibble) for every glyph in the /font directory. */ @@ -44,39 +44,37 @@ public class BatchingFontRenderer { private int[] colorCode; /** Location of the primary font atlas to bind. */ protected final ResourceLocation locationFontTexture; - private final RandomXoshiro256StarStar fontRandom = new RandomXoshiro256StarStar(); - /** The full list of characters present in the default Minecraft font, excluding the Unicode font */ - @SuppressWarnings("UnnecessaryUnicodeEscape") - private static final String MCFONT_CHARS = "\u00c0\u00c1\u00c2\u00c8\u00ca\u00cb\u00cd\u00d3\u00d4\u00d5\u00da\u00df\u00e3\u00f5\u011f\u0130\u0131\u0152\u0153\u015e\u015f\u0174\u0175\u017e\u0207\u0000\u0000\u0000\u0000\u0000\u0000\u0000 !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00f8\u00a3\u00d8\u00d7\u0192\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u00ae\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580\u03b1\u03b2\u0393\u03c0\u03a3\u03c3\u03bc\u03c4\u03a6\u0398\u03a9\u03b4\u221e\u2205\u2208\u2229\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0\u0000"; + private final int AAMode; + private final int AAStrength; + private final int texBoundAttrLocation; + private final int fontShaderId; - private static final short[] MCFONT_ASCII_LUT = new short[512]; - private static final Char2ShortOpenHashMap MCFONT_UNI_LUT = new Char2ShortOpenHashMap(); + private final boolean isSGA; - static { - Arrays.fill(MCFONT_ASCII_LUT, (short) -1); - for (short i = 0; i < MCFONT_CHARS.length(); i++) { - char ch = MCFONT_CHARS.charAt(i); - if (ch < MCFONT_ASCII_LUT.length) { - MCFONT_ASCII_LUT[ch] = i; - } else { - MCFONT_UNI_LUT.put(ch, i); + private static class FontAAShader { + + private static Program fontShader = null; + public static Program getProgram() { + if (fontShader == null) { + String vsh, fsh; + try { + fsh = new String(IOUtils.toByteArray(Objects.requireNonNull(FontAAShader.class.getResourceAsStream("/assets/angelica/shaders/fontFilter.fsh"))), StandardCharsets.UTF_8); + vsh = new String(IOUtils.toByteArray(Objects.requireNonNull(FontAAShader.class.getResourceAsStream("/assets/angelica/shaders/fontFilter.vsh"))), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new RuntimeException(e); + } + + ProgramBuilder builder = ProgramBuilder.begin("fontFilter", vsh, null, fsh, ImmutableSet.of(0)); + fontShader = builder.build(); } + return fontShader; } } - public static int lookupMcFontPosition(char ch) { - if (ch < MCFONT_ASCII_LUT.length) { - return MCFONT_ASCII_LUT[ch]; - } else { - return MCFONT_UNI_LUT.getOrDefault(ch, (short) -1); - } - } - - public BatchingFontRenderer(FontRenderer underlying, ResourceLocation[] unicodePageLocations, int[] charWidth, - byte[] glyphWidth, int[] colorCode, ResourceLocation locationFontTexture) { + public BatchingFontRenderer(FontRenderer underlying, int[] charWidth, byte[] glyphWidth, + int[] colorCode, ResourceLocation locationFontTexture) { this.underlying = underlying; - this.unicodePageLocations = unicodePageLocations; this.charWidth = charWidth; this.glyphWidth = glyphWidth; this.colorCode = colorCode; @@ -85,6 +83,18 @@ public class BatchingFontRenderer { for (int i = 0; i < 64; i++) { batchCommandPool.add(new FontDrawCmd()); } + + this.isSGA = Objects.equals(this.locationFontTexture.getResourcePath(), "textures/font/ascii_sga.png"); + + FontProviderMC.get(this.isSGA).charWidth = this.charWidth; + FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture; + FontProviderUnicode.get().glyphWidth = this.glyphWidth; + + //noinspection deprecation + fontShaderId = FontAAShader.getProgram().getProgramId(); + AAMode = GL20.glGetUniformLocation(fontShaderId, "aaMode"); + AAStrength = GL20.glGetUniformLocation(fontShaderId, "strength"); + texBoundAttrLocation = GL20.glGetAttribLocation(fontShaderId, "texBounds"); } // === Batched rendering @@ -100,17 +110,19 @@ public class BatchingFontRenderer { private ByteBuffer batchVtxColors = memAlloc(INITIAL_BATCH_SIZE * 4); private FloatBuffer batchVtxTexCoords = memAllocFloat(INITIAL_BATCH_SIZE * 2); private IntBuffer batchIndices = memAllocInt(INITIAL_BATCH_SIZE / 2 * 3); + private FloatBuffer batchVtxTexBounds = memAllocFloat(INITIAL_BATCH_SIZE * 4); private final ObjectArrayList batchCommands = ObjectArrayList.wrap(new FontDrawCmd[64], 0); private final ObjectArrayList batchCommandPool = ObjectArrayList.wrap(new FontDrawCmd[64], 0); /** */ - private void pushVtx(float x, float y, int rgba, float u, float v) { + private void pushVtx(float x, float y, int rgba, float u, float v, float uMin, float uMax, float vMin, float vMax) { final int oldCap = batchVtxPositions.capacity() / 2; if (vtxWriterIndex >= oldCap) { final int newCap = oldCap * 2; batchVtxPositions = memRealloc(batchVtxPositions, newCap * 2); batchVtxColors = memRealloc(batchVtxColors, newCap * 4); batchVtxTexCoords = memRealloc(batchVtxTexCoords, newCap * 2); + batchVtxTexBounds = memRealloc(batchVtxTexBounds, newCap * 4); final int oldIdxCap = batchIndices.capacity(); final int newIdxCap = oldIdxCap * 2; batchIndices = memRealloc(batchIndices, newIdxCap); @@ -127,15 +139,19 @@ public class BatchingFontRenderer { batchVtxColors.put(idx4 + 3, (byte) ((rgba >> 24) & 0xFF)); batchVtxTexCoords.put(idx2, u); batchVtxTexCoords.put(idx2 + 1, v); + batchVtxTexBounds.put(idx4, uMin); + batchVtxTexBounds.put(idx4 + 1, uMax); + batchVtxTexBounds.put(idx4 + 2, vMin); + batchVtxTexBounds.put(idx4 + 3, vMax); vtxWriterIndex++; } private void pushUntexRect(float x, float y, float w, float h, int rgba) { final int vtxId = vtxWriterIndex; - pushVtx(x, y, rgba, 0, 0); - pushVtx(x, y + h, rgba, 0, 0); - pushVtx(x + w, y, rgba, 0, 0); - pushVtx(x + w, y + h, rgba, 0, 0); + pushVtx(x, y, rgba, 0, 0, 0, 0, 0, 0); + pushVtx(x, y + h, rgba, 0, 0, 0, 0, 0, 0); + pushVtx(x + w, y, rgba, 0, 0, 0, 0, 0, 0); + pushVtx(x + w, y + h, rgba, 0, 0, 0, 0, 0, 0); pushQuadIdx(vtxId); } @@ -242,6 +258,8 @@ public class BatchingFontRenderer { } } + int fontAAModeLast = -1; + int fontAAStrengthLast = -1; private void flushBatch() { // Sort&Draw batchCommands.sort(FontDrawCmd.DRAW_ORDER_COMPARATOR); @@ -257,6 +275,19 @@ public class BatchingFontRenderer { GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); GLStateManager.glShadeModel(GL11.GL_FLAT); + if (FontConfig.fontAAMode != 0) { + GL20.glVertexAttribPointer(texBoundAttrLocation, 4, false, 0, batchVtxTexBounds); + GL20.glEnableVertexAttribArray(texBoundAttrLocation); + GL20.glUseProgram(fontShaderId); + if (FontConfig.fontAAMode != fontAAModeLast) { + fontAAModeLast = FontConfig.fontAAMode; + GL20.glUniform1i(AAMode, FontConfig.fontAAMode); + } + if (FontConfig.fontAAStrength != fontAAStrengthLast) { + fontAAStrengthLast = FontConfig.fontAAStrength; + GL20.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f); + } + } GL11.glTexCoordPointer(2, 0, batchVtxTexCoords); GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); GL11.glColorPointer(4, GL11.GL_UNSIGNED_BYTE, 0, batchVtxColors); @@ -285,20 +316,11 @@ public class BatchingFontRenderer { batchIndices.limit(cmd.startVtx + cmd.idxCount); batchIndices.position(cmd.startVtx); - Minecraft mc = Minecraft.getMinecraft(); - int scaleFactor = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight).getScaleFactor(); - boolean shouldApplyFilter = cmd.isUnicode && scaleFactor % 2 != 0; - - if (shouldApplyFilter) { - GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); - GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); - } GL11.glDrawElements(GL11.GL_TRIANGLES, batchIndices); - - if (shouldApplyFilter) { - GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); - } + } + if (FontConfig.fontAAMode != 0) { + GL20.glUseProgram(0); + GL20.glDisableVertexAttribArray(texBoundAttrLocation); } GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); @@ -327,17 +349,24 @@ public class BatchingFontRenderer { return (what >= fromInclusive) && (what <= toInclusive); } - private ResourceLocation getUnicodePageLocation(int page) { - final ResourceLocation lookup = unicodePageLocations[page]; - if (lookup == null) { - final ResourceLocation rl = new ResourceLocation(String.format( - "textures/font/unicode_page_%02x.png", - page)); - unicodePageLocations[page] = rl; - return rl; - } else { - return lookup; - } + public float getGlyphScaleX() { + return this.isSGA ? 1 : (float) (FontConfig.glyphScale * Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1); + } + + public float getGlyphScaleY() { + return this.isSGA ? 1 : (float) (FontConfig.glyphScale / Math.pow(2, FontConfig.glyphAspect)) * (FontStrategist.customFontInUse ? 1.5f : 1); + } + + public float getGlyphSpacing() { + return (this.isSGA ? 1 : FontConfig.glyphSpacing); + } + + public float getWhitespaceScale() { + return (this.isSGA ? 1 : FontConfig.whitespaceScale); + } + + public float getShadowOffset() { + return (this.isSGA ? 1 : FontConfig.fontShadowOffset); } private static final char FORMATTING_CHAR = 167; // § @@ -350,6 +379,9 @@ public class BatchingFontRenderer { } final int shadowColor = (color & 0xfcfcfc) >> 2 | color & 0xff000000; + FontProviderMC.get(this.isSGA).charWidth = this.charWidth; + FontProviderMC.get(this.isSGA).locationFontTexture = this.locationFontTexture; + this.beginBatch(); float curX = anchorX; try { @@ -369,10 +401,14 @@ public class BatchingFontRenderer { boolean curStrikethrough = false; boolean curUnderline = false; - final float underlineY = anchorY + underlying.FONT_HEIGHT - 1.0f; + final float glyphScaleY = getGlyphScaleY(); + final float heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY / 2); + final float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY; + + final float underlineY = heightNorth + (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY; float underlineStartX = 0.0f; float underlineEndX = 0.0f; - final float strikethroughY = anchorY + (float) (underlying.FONT_HEIGHT / 2) - 1.0F; + final float strikethroughY = heightNorth + ((float) (underlying.FONT_HEIGHT / 2) - 1.0f) * glyphScaleY; float strikethroughStartX = 0.0f; float strikethroughEndX = 0.0f; @@ -384,7 +420,7 @@ public class BatchingFontRenderer { if (curUnderline && underlineStartX != underlineEndX) { final int ulIdx = idxWriterIndex; - pushUntexRect(underlineStartX, underlineY, underlineEndX - underlineStartX, 1.0f, curColor); + pushUntexRect(underlineStartX, underlineY, underlineEndX - underlineStartX, glyphScaleY, curColor); pushDrawCmd(ulIdx, 6, null, false); underlineStartX = underlineEndX; } @@ -394,7 +430,7 @@ public class BatchingFontRenderer { strikethroughStartX, strikethroughY, strikethroughEndX - strikethroughStartX, - 1.0f, + glyphScaleY, curColor); pushDrawCmd(ulIdx, 6, null, false); strikethroughStartX = strikethroughEndX; @@ -441,67 +477,27 @@ public class BatchingFontRenderer { continue; } - int lutIndex = lookupMcFontPosition(chr); - if (curRandom && lutIndex != -1) { - int randomReplacementIndex; - do { - randomReplacementIndex = fontRandom.nextInt(this.charWidth.length); - } while (this.charWidth[lutIndex] != this.charWidth[randomReplacementIndex]); - - lutIndex = randomReplacementIndex; - chr = MCFONT_CHARS.charAt(lutIndex); + if (curRandom) { + chr = FontProviderMC.get(this.isSGA).getRandomReplacement(chr); } + FontProvider fontProvider = FontStrategist.getFontProvider(chr, this.isSGA, FontConfig.enableCustomFont, unicodeFlag); + // Check ASCII space, NBSP, NNBSP if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') { - curX += 4; + curX += 4 * this.getWhitespaceScale(); continue; } - final float uStart; - final float vStart; - final float xAdvance; - final float glyphW; - final float uSz; - final float vSz; + final float uStart = fontProvider.getUStart(chr); + final float vStart = fontProvider.getVStart(chr); + final float xAdvance = fontProvider.getXAdvance(chr) * getGlyphScaleX(); + final float glyphW = fontProvider.getGlyphW(chr) * getGlyphScaleX(); + final float uSz = fontProvider.getUSize(chr); + final float vSz = fontProvider.getVSize(chr); final float itOff = curItalic ? 1.0F : 0.0F; // italic offset - final float shadowOffset; - final ResourceLocation texture; - - if (lutIndex == -1 || unicodeFlag) { - if (glyphWidth[chr] == 0) { - continue; - } - // Draw unicode char - shadowOffset = AngelicaConfig.shadowOffsetFontUC; - final int uniPage = chr / 256; - texture = getUnicodePageLocation(uniPage); - final int startColumn = this.glyphWidth[chr] >>> 4; - final int endColumn = this.glyphWidth[chr] & 15; - final float startColumnF = (float) startColumn; - final float endColumnF = (float) (endColumn + 1); - uStart = ((float) (chr % 16 * 16) + startColumnF + 0.21f) / 256.0f; - vStart = ((float) ((chr & 255) / 16 * 16) + 0.21f) / 256.0f; - final float chrWidth = endColumnF - startColumnF - 0.02F; - glyphW = chrWidth / 2.0f + 1.0f; - xAdvance = (endColumnF - startColumnF) / 2.0F + 1.0F; - uSz = (chrWidth - 0.42f) / 256.0f; - vSz = (16.0f - 0.42f) / 256.0f; - - } else { - // Draw "ASCII" char - shadowOffset = 1.0F; - uStart = ((lutIndex % 16) * 8) / 128.0F; - vStart = (float) ((lutIndex / 16) * 8) / 128.0F; - xAdvance = this.charWidth[lutIndex]; - if (xAdvance == 0) { - continue; - } - glyphW = xAdvance - 0.01F; - uSz = (glyphW - 1.0F) / 128.0F; - vSz = 7.99F / 128.0F; - texture = locationFontTexture; - } + final float shadowOffset = fontProvider.getShadowOffset(); + final ResourceLocation texture = fontProvider.getTexture(chr); final int vtxId = vtxWriterIndex; final int idxId = idxWriterIndex; @@ -509,80 +505,49 @@ public class BatchingFontRenderer { int vtxCount = 0; if (enableShadow) { - pushVtx(curX + itOff + shadowOffset, anchorY + shadowOffset, curShadowColor, uStart, vStart); - pushVtx( - curX - itOff + shadowOffset, - anchorY + 7.99F + shadowOffset, - curShadowColor, - uStart, - vStart + vSz); - pushVtx(curX + glyphW - 1.0F + itOff + shadowOffset, - anchorY + shadowOffset, - curShadowColor, - uStart + uSz, - vStart); - pushVtx(curX + glyphW - 1.0F - itOff + shadowOffset, - anchorY + 7.99F + shadowOffset, - curShadowColor, - uStart + uSz, - vStart + vSz); + pushVtx(curX + itOff + shadowOffset, heightNorth + shadowOffset, curShadowColor, uStart, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX - itOff + shadowOffset, heightNorth + heightSouth + shadowOffset, curShadowColor, uStart, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX + glyphW - 1.0F + itOff + shadowOffset, heightNorth + shadowOffset, curShadowColor, uStart + uSz, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX + glyphW - 1.0F - itOff + shadowOffset, heightNorth + heightSouth + shadowOffset, curShadowColor, uStart + uSz, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); pushQuadIdx(vtxId + vtxCount); vtxCount += 4; if (curBold) { final float shadowOffset2 = 2.0f * shadowOffset; - pushVtx(curX + itOff + shadowOffset2, anchorY + shadowOffset, curShadowColor, uStart, vStart); - pushVtx( - curX - itOff + shadowOffset2, - anchorY + 7.99F + shadowOffset, - curShadowColor, - uStart, - vStart + vSz); - pushVtx( - curX + glyphW - 1.0F + itOff + shadowOffset2, - anchorY + shadowOffset, - curShadowColor, - uStart + uSz, - vStart); - pushVtx(curX + glyphW - 1.0F - itOff + shadowOffset2, - anchorY + 7.99F + shadowOffset, - curShadowColor, - uStart + uSz, - vStart + vSz); + pushVtx(curX + itOff + shadowOffset2, heightNorth + shadowOffset, curShadowColor, uStart, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX - itOff + shadowOffset2, heightNorth + heightSouth + shadowOffset, curShadowColor, uStart, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX + glyphW - 1.0F + itOff + shadowOffset2, heightNorth + shadowOffset, curShadowColor, uStart + uSz, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX + glyphW - 1.0F - itOff + shadowOffset2, heightNorth + heightSouth + shadowOffset, curShadowColor, uStart + uSz, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); pushQuadIdx(vtxId + vtxCount); vtxCount += 4; } } - pushVtx(curX + itOff, anchorY, curColor, uStart, vStart); - pushVtx(curX - itOff, anchorY + 7.99F, curColor, uStart, vStart + vSz); - pushVtx(curX + glyphW - 1.0F + itOff, anchorY, curColor, uStart + uSz, vStart); - pushVtx(curX + glyphW - 1.0F - itOff, anchorY + 7.99F, curColor, uStart + uSz, vStart + vSz); + pushVtx(curX + itOff, heightNorth, curColor, uStart, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX - itOff, heightNorth + heightSouth, curColor, uStart, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX + glyphW - 1.0F + itOff, heightNorth, curColor, uStart + uSz, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(curX + glyphW - 1.0F - itOff, heightNorth + heightSouth, curColor, uStart + uSz, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); pushQuadIdx(vtxId + vtxCount); vtxCount += 4; if (curBold) { - pushVtx(shadowOffset + curX + itOff, anchorY, curColor, uStart, vStart); - pushVtx(shadowOffset + curX - itOff, anchorY + 7.99F, curColor, uStart, vStart + vSz); - pushVtx(shadowOffset + curX + glyphW - 1.0F + itOff, anchorY, curColor, uStart + uSz, vStart); - pushVtx(shadowOffset + curX + glyphW - 1.0F - itOff, - anchorY + 7.99F, - curColor, - uStart + uSz, - vStart + vSz); + pushVtx(shadowOffset + curX + itOff, heightNorth, curColor, uStart, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(shadowOffset + curX - itOff, heightNorth + heightSouth, curColor, uStart, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(shadowOffset + curX + glyphW - 1.0F + itOff, heightNorth, curColor, uStart + uSz, vStart, uStart, uStart + uSz, vStart, vStart + vSz); + pushVtx(shadowOffset + curX + glyphW - 1.0F - itOff, heightNorth + heightSouth, curColor, uStart + uSz, vStart + vSz, uStart, uStart + uSz, vStart, vStart + vSz); pushQuadIdx(vtxId + vtxCount); vtxCount += 4; } pushDrawCmd(idxId, vtxCount / 2 * 3, texture, chr > 255); - curX += xAdvance + (curBold ? shadowOffset : 0.0f); + curX += (xAdvance + (curBold ? shadowOffset : 0.0f)) + getGlyphSpacing(); underlineEndX = curX; strikethroughEndX = curX; } if (curUnderline && underlineStartX != underlineEndX) { final int ulIdx = idxWriterIndex; - pushUntexRect(underlineStartX, underlineY, underlineEndX - underlineStartX, 1.0f, curColor); + pushUntexRect(underlineStartX, underlineY, underlineEndX - underlineStartX, glyphScaleY, curColor); pushDrawCmd(ulIdx, 6, null, false); } if (curStrikethrough && strikethroughStartX != strikethroughEndX) { @@ -591,7 +556,7 @@ public class BatchingFontRenderer { strikethroughStartX, strikethroughY, strikethroughEndX - strikethroughStartX, - 1.0f, + glyphScaleY, curColor); pushDrawCmd(ulIdx, 6, null, false); } @@ -602,4 +567,15 @@ public class BatchingFontRenderer { return curX + (enableShadow ? 1.0f : 0.0f); } + public float getCharWidthFine(char chr) { + if (chr == FORMATTING_CHAR) { return -1; } + + if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') { + return 4 * this.getWhitespaceScale(); + } + + FontProvider fp = FontStrategist.getFontProvider(chr, isSGA, FontConfig.enableCustomFont, underlying.getUnicodeFlag()); + + return fp.getXAdvance(chr) * this.getGlyphScaleX(); + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/FontProvider.java b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProvider.java new file mode 100644 index 000000000..3896777d9 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProvider.java @@ -0,0 +1,20 @@ +package com.gtnewhorizons.angelica.client.font; + +import net.minecraft.util.ResourceLocation; + +public interface FontProvider { + + /** + * For use with §k. Should fetch a character of the same width as provided. + */ + char getRandomReplacement(char chr); + boolean isGlyphAvailable(char chr); + float getUStart(char chr); + float getVStart(char chr); + float getXAdvance(char chr); + float getGlyphW(char chr); + float getUSize(char chr); + float getVSize(char chr); + float getShadowOffset(); + ResourceLocation getTexture(char chr); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderCustom.java b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderCustom.java new file mode 100644 index 000000000..9f7deae0b --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderCustom.java @@ -0,0 +1,302 @@ +package com.gtnewhorizons.angelica.client.font; + +import com.gtnewhorizon.gtnhlib.config.ConfigurationManager; +import com.gtnewhorizons.angelica.config.FontConfig; +import lombok.Setter; +import lombok.Value; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.ITextureObject; +import net.minecraft.client.renderer.texture.TextureManager; +import net.minecraft.client.renderer.texture.TextureUtil; +import net.minecraft.util.ResourceLocation; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import javax.imageio.ImageIO; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.GraphicsEnvironment; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Map; +import java.util.Objects; + +public final class FontProviderCustom implements FontProvider { + + public static final Logger LOGGER = LogManager.getLogger("Angelica"); + public static final String FONT_DIR = "fonts/custom/"; + static final int ATLAS_SIZE = 128; + static final int ATLAS_COUNT = 512; + private final byte id; // 0 - primary font, 1 - fallback font + private FontAtlas[] fontAtlases = new FontAtlas[ATLAS_COUNT]; + private float currentFontQuality = FontConfig.customFontQuality; + @Setter + private Font font; + + private FontProviderCustom(byte id) { + this.id = id; + Font[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + if (availableFonts.length == 0) { + LOGGER.fatal("There seem to be no fonts available on this system! Disabling custom font and throwing an exception in an attempt to restore the session."); + FontConfig.enableCustomFont = false; + ConfigurationManager.save(FontConfig.class); + throw new RuntimeException(); + } + String myFontName = switch (this.id) { + case 0 -> FontConfig.customFontNamePrimary; + case 1 -> FontConfig.customFontNameFallback; + default -> null; + }; + if (Objects.equals(myFontName, "(none)")) { + font = null; + return; + } + int fontPos = -1; + for (int i = 0; i < availableFonts.length; i++) { + if (Objects.equals(myFontName, availableFonts[i].getFontName())) { + fontPos = i; + break; + } + } + if (fontPos == -1) { + LOGGER.info("Could not find previously set font \"{}\". ", myFontName); + font = null; + return; + } + font = availableFonts[fontPos].deriveFont(currentFontQuality); + } + private static class InstLoader { + static final FontProviderCustom instance0 = new FontProviderCustom((byte)0); + static final FontProviderCustom instance1 = new FontProviderCustom((byte)1); + } + public static FontProviderCustom getPrimary() { return InstLoader.instance0; } + public static FontProviderCustom getFallback() { return InstLoader.instance1; } + + public void reloadFont(int fontID) { + currentFontQuality = FontConfig.customFontQuality; + GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); + font = ge.getAllFonts()[fontID].deriveFont(currentFontQuality); + + File[] files = new File(getFontDir()).listFiles(); + if (files != null) { + for (File f : files) { + if (!Files.isSymbolicLink(f.toPath())) { + f.delete(); + } + } + } + + TextureManager tm = Minecraft.getMinecraft().getTextureManager(); + Map mapTextureObjects = tm.mapTextureObjects; + for (int i = 0; i < ATLAS_COUNT; i++) { + ResourceLocation key = new ResourceLocation(getAtlasResourceName(i)); + if (mapTextureObjects.containsKey(key)) { + ITextureObject obj = (ITextureObject) mapTextureObjects.get(key); + TextureUtil.deleteTexture(obj.getGlTextureId()); + mapTextureObjects.remove(key); + } + } + + fontAtlases = new FontAtlas[ATLAS_COUNT]; + } + + private String getFontDir() { + return FONT_DIR + "f" + this.id + "/"; + } + + private String getAtlasFilename(int atlasId) { + return "f" + this.id + "p" + atlasId; + } + + String getAtlasResourceName(int atlasId) { + return "minecraft:angelica_c" + getAtlasFilename(atlasId); + } + + String getAtlasFullPath(int atlasId) { + return getFontDir() + getAtlasFilename(atlasId) + ".png"; + } + + @Value + private class GlyphData { + float uStart; + float vStart; + float xAdvance; + float glyphW; + float uSz; + float vSz; + } + + private class FontAtlas { + + GlyphData[] glyphData = new GlyphData[ATLAS_SIZE]; + private ResourceLocation texture; + private final int id; + + FontAtlas(int id) { + this.id = id; + } + + void construct(Font font) { + float separator = currentFontQuality / 3f; + + BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); + Graphics2D g2d = image.createGraphics(); + g2d.setFont(font); + FontMetrics fm = g2d.getFontMetrics(); + g2d.dispose(); + int width = 0; + int actualChars = 0; + for (int i = 0; i < ATLAS_SIZE; i++) { + final char ch = (char)(i + ATLAS_SIZE * this.id); + if (font.canDisplay(ch)) { + width += (int) (separator + fm.charWidth(ch)); + actualChars++; + } + } + if (actualChars == 0) { + return; + } + final int atlasTilesX = (int) Math.ceil(Math.sqrt(actualChars) * 1.5f); + final int atlasTilesY = (int) Math.ceil((double) actualChars / atlasTilesX); + LOGGER.info("constructing custom font atlas (ID {}) of nominal size {} chars, actual: {}, {} rows by {} columns", + this.id, ATLAS_SIZE, actualChars, atlasTilesX, atlasTilesY); + width = 0; + actualChars = 0; + int maxRowWidth = 0; + for (int i = 0; i < ATLAS_SIZE; i++) { + if (actualChars % atlasTilesX == 0) { + maxRowWidth = Math.max(maxRowWidth, width); + width = 0; + } + final char ch = (char)(i + ATLAS_SIZE * this.id); + if (font.canDisplay(ch)) { + width += (int) (separator + fm.charWidth(ch)); + actualChars++; + } + } + maxRowWidth = Math.max(maxRowWidth, width); + + final int lineHeight = fm.getHeight(); + final float desc = fm.getDescent(); + + final int imageWidth = (int) (maxRowWidth + separator); + final int imageHeight = (int) ((separator + lineHeight) * atlasTilesY + separator); + + image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB); + g2d = image.createGraphics(); + g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); + g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); + g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + g2d.setFont(font); + fm = g2d.getFontMetrics(); + + int tileX = 0, tileY = 0; // position in atlas tiles + int imgX = (int) separator; // position in pixels + + for (int i = 0; i < ATLAS_SIZE; i++) { + final char ch = (char)(i + ATLAS_SIZE * this.id); + if (!font.canDisplay(ch)) { continue; } + + if (tileX >= atlasTilesX) { + tileX = 0; + imgX = (int) separator; + tileY++; + } + + final int charWidth = fm.charWidth(ch); + final float charAspectRatio = (float) charWidth / lineHeight; + final float inset = currentFontQuality / 16; + g2d.drawString(Character.toString(ch), imgX, (lineHeight + separator) * (tileY + 1) - desc); + final float uStart = (float) (imgX - inset * charAspectRatio) / imageWidth; + final float vStart = ((lineHeight + separator) * (tileY + 1) - lineHeight - inset) / imageHeight; + final float xAdvance = charAspectRatio * 8 * charWidth / (charWidth + 2 * inset * charAspectRatio); + final float glyphW = charAspectRatio * 8 + 1; + final float uSz = (float) (charWidth + 2 * inset * charAspectRatio) / imageWidth; + final float vSz = (float) (lineHeight + 2 * inset) / imageHeight; + glyphData[i] = new GlyphData(uStart, vStart, xAdvance, glyphW, uSz, vSz); + imgX += (int) (charWidth + separator); + tileX++; + } + g2d.dispose(); + try { + LOGGER.info("writing custom font atlas texture ({}x{} px) to {}", imageWidth, imageHeight, getAtlasFullPath(this.id)); + Files.createDirectories(Paths.get(getFontDir())); + ImageIO.write(image, "png", new File(getAtlasFullPath(this.id))); + } catch (IOException e) { + e.printStackTrace(); + } + this.texture = new ResourceLocation(getAtlasResourceName(this.id)); + } + } + + private FontAtlas getAtlas(char chr) { + int id = chr / ATLAS_SIZE; + FontAtlas fa = fontAtlases[id]; + if (fa == null) { + fa = new FontAtlas(id); + fa.construct(font); + } + fontAtlases[id] = fa; + return fa; + } + + @Override + public boolean isGlyphAvailable(char chr) { + if (font == null) { return false; } + return (getAtlas(chr).glyphData[chr % ATLAS_SIZE] != null); + } + + @Override + public char getRandomReplacement(char chr) { + return chr; + } + + @Override + public float getUStart(char chr) { + return getAtlas(chr).glyphData[chr % ATLAS_SIZE].uStart; + } + + @Override + public float getVStart(char chr) { + return getAtlas(chr).glyphData[chr % ATLAS_SIZE].vStart; + } + + @Override + public float getXAdvance(char chr) { + return getAtlas(chr).glyphData[chr % ATLAS_SIZE].xAdvance; + } + + @Override + public float getGlyphW(char chr) { + return getAtlas(chr).glyphData[chr % ATLAS_SIZE].glyphW; + } + + @Override + public float getUSize(char chr) { + return getAtlas(chr).glyphData[chr % ATLAS_SIZE].uSz; + } + + @Override + public float getVSize(char chr) { + return getAtlas(chr).glyphData[chr % ATLAS_SIZE].vSz; + } + + @Override + public float getShadowOffset() { + return FontConfig.fontShadowOffset; + } + + @Override + public ResourceLocation getTexture(char chr) { + return getAtlas(chr).texture; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderMC.java b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderMC.java new file mode 100644 index 000000000..714f0c5aa --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderMC.java @@ -0,0 +1,106 @@ +package com.gtnewhorizons.angelica.client.font; + +import com.gtnewhorizons.angelica.config.FontConfig; +import it.unimi.dsi.fastutil.chars.Char2ShortOpenHashMap; +import jss.util.RandomXoshiro256StarStar; +import net.minecraft.util.ResourceLocation; + +public final class FontProviderMC implements FontProvider { + + /** + * The full list of characters present in the default Minecraft font, excluding the Unicode font + */ + @SuppressWarnings("UnnecessaryUnicodeEscape") + private static final String MCFONT_CHARS = "\u00c0\u00c1\u00c2\u00c8\u00ca\u00cb\u00cd\u00d3\u00d4\u00d5\u00da\u00df\u00e3\u00f5\u011f\u0130\u0131\u0152\u0153\u015e\u015f\u0174\u0175\u017e\u0207\u0000\u0000\u0000\u0000\u0000\u0000\u0000 !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00f8\u00a3\u00d8\u00d7\u0192\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u00ae\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580\u03b1\u03b2\u0393\u03c0\u03a3\u03c3\u03bc\u03c4\u03a6\u0398\u03a9\u03b4\u221e\u2205\u2208\u2229\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0\u0000"; + + private FontProviderMC() {} + private static class InstLoader { + static final FontProviderMC instance = new FontProviderMC(); + static final FontProviderMC instanceSGA = new FontProviderMC(); + } + public static FontProviderMC get(boolean isSGA) { + return (isSGA ? InstLoader.instanceSGA : InstLoader.instance); + } + + private static final Char2ShortOpenHashMap MCFONT_ASCII_MAP = new Char2ShortOpenHashMap(); + ResourceLocation locationFontTexture = null; + private final RandomXoshiro256StarStar fontRandom = new RandomXoshiro256StarStar(); + public int[] charWidth; + + static { + for (short i = 0; i < MCFONT_CHARS.length(); i++) { + MCFONT_ASCII_MAP.put(MCFONT_CHARS.charAt(i), i); + } + } + + public int lookupMcFontPosition(char ch) { + if (isGlyphAvailable(ch)) { + return MCFONT_ASCII_MAP.get(ch); + } + return -1; + } + + @Override + public boolean isGlyphAvailable(char chr) { + return MCFONT_ASCII_MAP.containsKey(chr); + } + + public char getRandomReplacement(char chr){ + int lutIndex = lookupMcFontPosition(chr); + if (lutIndex != -1) { + int randomReplacementIndex; + do { + randomReplacementIndex = fontRandom.nextInt(this.charWidth.length); + } while (this.charWidth[lutIndex] != this.charWidth[randomReplacementIndex]); + + lutIndex = randomReplacementIndex; + return MCFONT_CHARS.charAt(lutIndex); + } + return chr; + } + + @Override + public float getUStart(char chr) { + int lutIndex = lookupMcFontPosition(chr); + return ((lutIndex % 16) * 8) / 128.0F; + } + + @Override + public float getVStart(char chr) { + int lutIndex = lookupMcFontPosition(chr); + return (float) ((lutIndex / 16) * 8) / 128.0F; + } + + @Override + public float getXAdvance(char chr) { + int lutIndex = lookupMcFontPosition(chr); + return charWidth[lutIndex]; + } + + @Override + public float getGlyphW(char chr) { + int lutIndex = lookupMcFontPosition(chr); + return charWidth[lutIndex] - 0.01F; + } + + @Override + public float getUSize(char chr) { + int lutIndex = lookupMcFontPosition(chr); + return (charWidth[lutIndex] - 1.01F) / 128.0F; + } + + @Override + public float getVSize(char chr) { + return 7.99F / 128.0F; + } + + @Override + public float getShadowOffset() { + return FontConfig.fontShadowOffset; + } + + @Override + public ResourceLocation getTexture(char chr) { + return locationFontTexture; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderUnicode.java b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderUnicode.java new file mode 100644 index 000000000..9a662d4d4 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/FontProviderUnicode.java @@ -0,0 +1,93 @@ +package com.gtnewhorizons.angelica.client.font; + +import com.gtnewhorizons.angelica.config.FontConfig; +import net.minecraft.util.ResourceLocation; + +public final class FontProviderUnicode implements FontProvider { + + private FontProviderUnicode() {} + private static class InstLoader { static final FontProviderUnicode instance = new FontProviderUnicode(); } + public static FontProviderUnicode get() { return FontProviderUnicode.InstLoader.instance; } + + private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256]; + public byte[] glyphWidth; + + private ResourceLocation getUnicodePageLocation(int page) { + final ResourceLocation lookup = unicodePageLocations[page]; + if (lookup == null) { + final ResourceLocation rl = new ResourceLocation(String.format( + "textures/font/unicode_page_%02x.png", + page)); + unicodePageLocations[page] = rl; + return rl; + } else { + return lookup; + } + } + + @Override + public boolean isGlyphAvailable(char chr) { + return true; + } + + @Override + public char getRandomReplacement(char chr) { + return chr; + } + + @Override + public float getUStart(char chr) { + final float startColumnF = (float)(this.glyphWidth[chr] >>> 4); + return ((float) (chr % 16 * 16) + startColumnF + 0.21f) / 256.0f; + } + + @Override + public float getVStart(char chr) { + return ((float) ((chr & 255) / 16 * 16) + 0.21f) / 256.0f; + } + + @Override + public float getXAdvance(char chr) { + final int startColumn = this.glyphWidth[chr] >>> 4; + final int endColumn = this.glyphWidth[chr] & 15; + final float startColumnF = (float) startColumn; + final float endColumnF = (float) (endColumn + 1); + return (endColumnF - startColumnF) / 2.0F + 1.0F; + } + + @Override + public float getGlyphW(char chr) { + final int startColumn = this.glyphWidth[chr] >>> 4; + final int endColumn = this.glyphWidth[chr] & 15; + final float startColumnF = (float) startColumn; + final float endColumnF = (float) (endColumn + 1); + final float chrWidth = endColumnF - startColumnF - 0.02F; + return chrWidth / 2.0f + 1.0f; + } + + @Override + public float getUSize(char chr) { + final int startColumn = this.glyphWidth[chr] >>> 4; + final int endColumn = this.glyphWidth[chr] & 15; + final float startColumnF = (float) startColumn; + final float endColumnF = (float) (endColumn + 1); + final float chrWidth = endColumnF - startColumnF - 0.02F; + return (chrWidth - 0.42f) / 256.0f; + } + + @Override + public float getVSize(char chr) { + return (16.0f - 0.42f) / 256.0f; + } + + @Override + public float getShadowOffset() { + return FontConfig.fontShadowOffset; + } + + @Override + public ResourceLocation getTexture(char chr) { + final int uniPage = chr / 256; + return getUnicodePageLocation(uniPage); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/FontStrategist.java b/src/main/java/com/gtnewhorizons/angelica/client/font/FontStrategist.java new file mode 100644 index 000000000..8e5453b06 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/FontStrategist.java @@ -0,0 +1,90 @@ +package com.gtnewhorizons.angelica.client.font; + +import com.gtnewhorizons.angelica.config.FontConfig; +import com.gtnewhorizons.angelica.mixins.interfaces.ResourceAccessor; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.DefaultResourcePack; + +import java.awt.Font; +import java.awt.GraphicsEnvironment; +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +public class FontStrategist { + + static { + HashMap packMap = new HashMap<>(); + for (int i = 0; i < FontProviderCustom.ATLAS_COUNT; i++) { + packMap.put(FontProviderCustom.getPrimary().getAtlasResourceName(i), new File(FontProviderCustom.getPrimary().getAtlasFullPath(i))); + packMap.put(FontProviderCustom.getFallback().getAtlasResourceName(i), new File(FontProviderCustom.getFallback().getAtlasFullPath(i))); + } + + DefaultResourcePack fontResourcePack = new DefaultResourcePack(packMap); + List defaultResourcePacks = ((ResourceAccessor) Minecraft.getMinecraft()).angelica$getDefaultResourcePacks(); + defaultResourcePacks.add(fontResourcePack); + Minecraft.getMinecraft().refreshResources(); + + Font[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + boolean primaryFontFound = false; + boolean fallbackFontFound = false; + for (Font availableFont : availableFonts) { + if (Objects.equals(FontConfig.customFontNamePrimary, availableFont.getFontName())) { + primaryFontFound = true; + break; + } + if (Objects.equals(FontConfig.customFontNameFallback, availableFont.getFontName())) { + fallbackFontFound = true; + break; + } + } + customFontInUse = (FontConfig.enableCustomFont && (primaryFontFound || fallbackFontFound)); + } + + public static boolean customFontInUse; + + /** + Lets you get a FontProvider per char while respecting font priority and fallbacks, the unicode flag, whether or not + SGA is on, if a font can even display a character in the first place, etc. + */ + public static FontProvider getFontProvider(char chr, boolean isSGA, boolean customFontEnabled, boolean forceUnicode) { + if (isSGA && FontProviderMC.get(true).isGlyphAvailable(chr)) { + return FontProviderMC.get(true); + } + if (customFontEnabled) { + FontProvider fp; + fp = FontProviderCustom.getPrimary(); + if (fp.isGlyphAvailable(chr)) { return fp; } + fp = FontProviderCustom.getFallback(); + if (fp.isGlyphAvailable(chr)) { return fp; } + return FontProviderUnicode.get(); + } else { + if (!forceUnicode && FontProviderMC.get(false).isGlyphAvailable(chr)) { + return FontProviderMC.get(false); + } else { + return FontProviderUnicode.get(); + } + } + } + + public static void reloadCustomFontProviders() { + Font[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + FontProviderCustom.getPrimary().setFont(null); + FontProviderCustom.getFallback().setFont(null); + boolean primaryFontFound = false; + boolean fallbackFontFound = false; + for (int i = 0; i < availableFonts.length; i++) { + if (Objects.equals(FontConfig.customFontNamePrimary, availableFonts[i].getFontName())) { + FontProviderCustom.getPrimary().reloadFont(i); + primaryFontFound = true; + } + if (Objects.equals(FontConfig.customFontNameFallback, availableFonts[i].getFontName())) { + FontProviderCustom.getFallback().reloadFont(i); + fallbackFontFound = true; + } + if (primaryFontFound && fallbackFontFound) { break; } + } + customFontInUse = (FontConfig.enableCustomFont && (primaryFontFound || fallbackFontFound)); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/gui/FontConfigScreen.java b/src/main/java/com/gtnewhorizons/angelica/client/gui/FontConfigScreen.java new file mode 100644 index 000000000..effbfbf95 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/gui/FontConfigScreen.java @@ -0,0 +1,359 @@ +package com.gtnewhorizons.angelica.client.gui; + +import com.gtnewhorizon.gtnhlib.config.ConfigException; +import com.gtnewhorizon.gtnhlib.config.ConfigurationManager; +import com.gtnewhorizons.angelica.client.font.FontStrategist; +import com.gtnewhorizons.angelica.config.FontConfig; +import net.coderbot.iris.gui.element.widget.IrisButton; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiSlot; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.resources.I18n; +import org.lwjgl.input.Keyboard; + +import java.awt.Font; +import java.awt.GraphicsEnvironment; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class FontConfigScreen extends GuiScreen { + + private final GuiScreen parent; + private final String title; + private final String searchPrompt; + private final Font[] availableFonts; + private String currentPrimaryFontName; + private String currentFallbackFontName; + private FontList fontList; + private int selectedPrimaryFontListPos = -1; + private int selectedFallbackFontListPos = -1; + private ArrayList displayedFonts; + private GuiTextField searchBox; + + public FontConfigScreen(GuiScreen parent) { + this.title = I18n.format("options.angelica.fontconfig.title"); + this.searchPrompt = I18n.format("options.angelica.fontconfig.searchprompt"); + this.parent = parent; + this.currentPrimaryFontName = FontConfig.customFontNamePrimary; + this.currentFallbackFontName = FontConfig.customFontNameFallback; + this.availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + this.displayedFonts = new ArrayList<>(Arrays.asList(availableFonts)); + for (int i = 0; i < availableFonts.length; i++) { + if (Objects.equals(this.currentPrimaryFontName, availableFonts[i].getFontName())) { + selectedPrimaryFontListPos = i; + } + if (Objects.equals(this.currentFallbackFontName, availableFonts[i].getFontName())) { + selectedFallbackFontListPos = i; + } + } + } + + SliderClone.Option optFontQuality = new SliderClone.Option(6, 72, 6); + SliderClone.Option optShadowOffset = new SliderClone.Option(0, 2, 0.05f); + SliderClone.Option optGlyphAspect = new SliderClone.Option(-1, 1, 0.05f); + SliderClone.Option optGlyphScale = new SliderClone.Option(0.1f, 3, 0.05f); + SliderClone.Option optWhitespaceScale = new SliderClone.Option(0.1f, 3, 0.05f); + SliderClone.Option optGlyphSpacing = new SliderClone.Option(-2f, 2f, 0.05f); + SliderClone.Option optFontAAMode = new SliderClone.Option(0, 2, 1); + SliderClone.Option optFontAAStrength = new SliderClone.Option(1, 24, 1); + + public void initGui() { + Keyboard.enableRepeatEvents(true); + searchBox = new GuiTextField(this.fontRendererObj, this.width / 2 - 120, 24, 240, 20); + searchBox.setMaxStringLength(64); + fontList = new FontList(); + initButtons(); + } + + private void initButtons() { + this.buttonList.add(new IrisButton(this.width / 2 - 81 - 165, this.height - 20 - 7, 162, 20, + FontConfig.enableCustomFont ? I18n.format("options.angelica.fontconfig.disable_custom_font") : + I18n.format("options.angelica.fontconfig.enable_custom_font"), this::toggleCustomFont)); + this.buttonList.add(new IrisButton(this.width / 2 - 80, this.height - 20 - 7, 160, 20, + I18n.format("options.angelica.fontconfig.reset_values"), this::resetValues)); + this.buttonList.add(new IrisButton(this.width / 2 - 81 + 165, this.height - 20 - 7, 162, 20, + I18n.format("gui.done"), button -> this.onClose())); + + // might refactor later, feeling too lazy at the moment + this.buttonList.add(new SliderClone( this.width / 2 - 60 - 186, this.height - 40 - 11, 120, 20, + optFontQuality, FontConfig.customFontQuality, this::setFontQuality, + value -> I18n.format("options.angelica.fontconfig.font_quality", String.format("%2.0f", value)), + "options.angelica.fontconfig.font_quality.tooltip")); + this.buttonList.add(new SliderClone( this.width / 2 - 60 - 186, this.height - 60 - 15, 120, 20, + optShadowOffset, FontConfig.fontShadowOffset, value -> FontConfig.fontShadowOffset = value, + value -> I18n.format("options.angelica.fontconfig.shadow_offset", String.format("x%3.2f", value)), + "options.angelica.fontconfig.shadow_offset.tooltip")); + this.buttonList.add(new SliderClone( this.width / 2 - 60 - 62, this.height - 40 - 11, 120, 20, + optGlyphAspect, FontConfig.glyphAspect, value -> FontConfig.glyphAspect = value, + value -> I18n.format("options.angelica.fontconfig.glyph_aspect", String.format("%3.2f", value)), + "options.angelica.fontconfig.glyph_aspect.tooltip")); + this.buttonList.add(new SliderClone( this.width / 2 - 60 - 62, this.height - 60 - 15, 120, 20, + optGlyphScale, FontConfig.glyphScale, value -> FontConfig.glyphScale = value, + value -> I18n.format("options.angelica.fontconfig.glyph_scale", String.format("x%3.2f", value)), + "options.angelica.fontconfig.glyph_scale.tooltip")); + this.buttonList.add(new SliderClone( this.width / 2 - 60 + 62, this.height - 40 - 11, 120, 20, + optWhitespaceScale, FontConfig.whitespaceScale, value -> FontConfig.whitespaceScale = value, + value -> I18n.format("options.angelica.fontconfig.whitespace_scale", String.format("x%3.2f", value)), + "options.angelica.fontconfig.whitespace_scale.tooltip")); + this.buttonList.add(new SliderClone( this.width / 2 - 60 + 62, this.height - 60 - 15, 120, 20, + optGlyphSpacing, FontConfig.glyphSpacing, value -> FontConfig.glyphSpacing = value, + value -> I18n.format("options.angelica.fontconfig.glyph_spacing", String.format("%3.2f", value)), + "options.angelica.fontconfig.glyph_spacing.tooltip")); + this.buttonList.add(new SliderClone( this.width / 2 - 60 + 186, this.height - 40 - 11, 120, 20, + optFontAAStrength, FontConfig.fontAAStrength, value -> FontConfig.fontAAStrength = value.intValue(), + value -> I18n.format("options.angelica.fontconfig.font_aa_strength", String.format("%.0f", value)), + "options.angelica.fontconfig.font_aa_strength.tooltip")); + this.buttonList.add(new SliderClone( this.width / 2 - 60 + 186, this.height - 60 - 15, 120, 20, + optFontAAMode, FontConfig.fontAAMode, value -> FontConfig.fontAAMode = value.intValue(), + this::fontAAModeFormat, + "options.angelica.fontconfig.aamode.tooltip")); + } + + private void onClose() { + applyChanges(true); + this.mc.displayGuiScreen(parent); + } + + private void applyChanges(boolean finalApply) { + int pos; + pos = selectedPrimaryFontListPos; + if (pos >= 0 && pos < displayedFonts.size()) { + FontConfig.customFontNamePrimary = displayedFonts.get(pos).getFontName(); + } + pos = selectedFallbackFontListPos; + if (pos >= 0 && pos < displayedFonts.size()) { + FontConfig.customFontNameFallback = displayedFonts.get(pos).getFontName(); + } + + FontStrategist.reloadCustomFontProviders(); + + if (finalApply) { + ConfigurationManager.save(FontConfig.class); + } + } + + private void resetValues(IrisButton button) { + try { + ConfigurationManager.getConfigElements(FontConfig.class).forEach(elem -> elem.set(elem.getDefault())); + } catch (ConfigException e) { + throw new RuntimeException(e); + } + selectedPrimaryFontListPos = -1; + selectedFallbackFontListPos = -1; + FontStrategist.customFontInUse = false; + super.buttonList.clear(); + this.initButtons(); + } + + private void toggleCustomFont(IrisButton button) { + FontConfig.enableCustomFont = !FontConfig.enableCustomFont; + applyChanges(false); + button.displayString = FontConfig.enableCustomFont ? + I18n.format("options.angelica.fontconfig.disable_custom_font") : + I18n.format("options.angelica.fontconfig.enable_custom_font"); + } + + private int qualityLast = FontConfig.customFontQuality; + + private void setFontQuality(float quality) { + FontConfig.customFontQuality = (int) quality; + if (qualityLast != (int) quality) { + applyChanges(false); + } + qualityLast = (int) quality; + } + + private String fontAAModeFormat(float AAmode) { + return switch ((int) AAmode) { + case 2 -> I18n.format("options.angelica.fontconfig.aamode.aa_16x"); + case 1 -> I18n.format("options.angelica.fontconfig.aamode.aa_4x"); + default -> I18n.format("options.angelica.fontconfig.aamode.aa_none"); + }; + } + + private float lastMouseX = 0; + private float lastMouseY = 0; + private long lastStillTime = 0; + @Override + public void drawScreen(int mouseX, int mouseY, float delta) { + super.drawDefaultBackground(); + fontList.drawScreen(mouseX, mouseY, delta); + searchBox.drawTextBox(); + // I bet you thought this was drawn inside the search box, not on top of it. + if (!this.searchBox.isFocused() && this.searchBox.getText().isEmpty()) { + this.drawCenteredString(this.fontRendererObj, this.searchPrompt, + this.searchBox.xPosition + this.fontRendererObj.getStringWidth(this.searchPrompt) / 2 + 4, + this.searchBox.yPosition + this.searchBox.height / 2 - 4, 0xFFFFFF); + } + drawCenteredString(this.fontRendererObj, this.title, (int) (this.width * 0.5), 8, 0xFFFFFF); + drawCenteredString(this.fontRendererObj, I18n.format("options.angelica.fontconfig.currentfonts", + FontConfig.customFontNamePrimary, FontConfig.customFontNameFallback), (int) (this.width * 0.5), this.height - 92, 0xFFFFFF); + super.drawScreen(mouseX, mouseY, delta); + + for (GuiButton guiButton : buttonList) { + if (!(guiButton instanceof SliderClone slider)) { continue; } + final int top = slider.yPosition; + final int bot = slider.yPosition + slider.height; + final int left = slider.xPosition; + final int right = slider.xPosition + slider.width; + if (mouseY < top || mouseY >= bot || mouseX < left || mouseX >= right) { continue; } + if (mouseX == lastMouseX && mouseY == lastMouseY) { + if (lastStillTime == 0) { + lastStillTime = System.currentTimeMillis(); + } + if (lastStillTime + 500L < System.currentTimeMillis()) { + displayTooltip(mouseX, mouseY, slider.tooltipKey); + } + } else { + lastStillTime = 0; + } + break; + } + lastMouseX = mouseX; + lastMouseY = mouseY; + } + + private void displayTooltip(int x, int y, String langKey) { + List lines = this.fontRendererObj.listFormattedStringToWidth(I18n.format(langKey), this.width / 2); + this.drawHoveringText(lines, x, y, this.fontRendererObj); + } + + @Override + protected void actionPerformed(GuiButton guiButton) { + if (guiButton.enabled) { + if (guiButton instanceof IrisButton irisButton) { + irisButton.onPress(); + } + } + } + + @Override + protected void keyTyped(char typedChar, int keyCode) { + if (this.searchBox.isFocused()) { + if (keyCode == Keyboard.KEY_ESCAPE) { + this.searchBox.setFocused(false); + } + this.searchBox.textboxKeyTyped(typedChar, keyCode); + this.displayedFonts = filterFonts(this.searchBox.getText().toLowerCase()); + } + if (keyCode == Keyboard.KEY_ESCAPE) { + this.onClose(); + } + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { + super.mouseClicked(mouseX, mouseY, mouseButton); + this.searchBox.mouseClicked(mouseX, mouseY, mouseButton); + this.fontList.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + public void updateScreen() { + this.searchBox.updateCursorCounter(); + } + + // this could be more efficient, but it's good enough as is + private ArrayList filterFonts(String search) { + ArrayList results; + if (search == null || search.isEmpty()) { + results = new ArrayList<>(Arrays.asList(availableFonts)); + } else { + results = Arrays.stream(availableFonts).filter((font -> font.getFontName().toLowerCase().contains(search))).collect(Collectors.toCollection(ArrayList::new)); + } + + selectedPrimaryFontListPos = -1; + selectedFallbackFontListPos = -1; + for (int i = 0; i < results.size(); i++) { + if (Objects.equals(currentPrimaryFontName, results.get(i).getFontName())) { + selectedPrimaryFontListPos = i; + } + if (Objects.equals(currentFallbackFontName, results.get(i).getFontName())) { + selectedFallbackFontListPos = i; + } + } + return results; + } + + class FontList extends GuiSlot { + + public FontList() { + super(FontConfigScreen.this.mc, FontConfigScreen.this.width, FontConfigScreen.this.height, 52, FontConfigScreen.this.height - 100, 18); + } + + private void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (mouseY < this.top || mouseY > this.bottom) { return; } + + int listLeftBound = this.width / 2 - this.getListWidth() / 2; + int listRightBound = this.width / 2 + this.getListWidth() / 2; + if (mouseX < listLeftBound || mouseX > listRightBound) { return; } + + int mousePosInList = mouseY - this.top - this.headerPadding + (int)this.amountScrolled - 4; + int slotIndex = mousePosInList / this.slotHeight; + if (slotIndex < 0 || slotIndex >= this.getSize()) { return; } + + if (mouseButton == 0) { + onElemClicked(slotIndex, false); + } else if (mouseButton == 1) { + onElemClicked(slotIndex, true); + } + } + + protected void onElemClicked(int index, boolean rightClick) { + if (!rightClick) { + selectedPrimaryFontListPos = index; + currentPrimaryFontName = displayedFonts.get(index).getFontName(); + } else { + selectedFallbackFontListPos = index; + currentFallbackFontName = displayedFonts.get(index).getFontName(); + } + applyChanges(false); + } + + protected boolean isSelected(int index) { + return (index == selectedPrimaryFontListPos || index == selectedFallbackFontListPos); + } + + protected int getSize() { + return displayedFonts.size(); + } + + @Override + protected int getContentHeight() { + return this.getSize() * 18; + } + + @Override + protected int getScrollBarX() { + return this.width * 11 / 12 - 5; + } + + @Override + public int getListWidth() { + return this.width * 2 / 3; + } + + // see onElemClicked for the proper version that supports right-clicking + protected void elementClicked(int index, boolean doubleClicked, int mouseX, int mouseY) {} + + protected void drawBackground() { + drawDefaultBackground(); + } + + protected void drawSlot(int index, int x, int y, int p_148126_4_, Tessellator tessellator, int p_148126_6_, int p_148126_7_) { + int color = 0xffffff; + if (index == selectedPrimaryFontListPos) { + color &= 0xffff55; + } + if (index == selectedFallbackFontListPos) { + color &= 0x55ffff; + } + drawCenteredString(fontRendererObj, displayedFonts.get(index).getFontName(), this.width / 2, y + 1, color); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java b/src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java new file mode 100644 index 000000000..d94d815b1 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java @@ -0,0 +1,114 @@ +package com.gtnewhorizons.angelica.client.gui; + +import lombok.AllArgsConstructor; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import org.lwjgl.opengl.GL11; + +import java.util.function.Consumer; +import java.util.function.Function; + +public class SliderClone extends GuiButton { + + private final Function displayStringFormatter; + private final Consumer valueSetter; + private final Option option; + private float sliderPercentage; + public final String tooltipKey; + public boolean mouseDragging; + + @AllArgsConstructor + public static class Option { + float min; + float max; + float step; + + float denormalize(float alpha) { + float lerp = min * (1 - alpha) + max * alpha; + return Math.round(lerp / step) * step; + } + float normalize(float value) { + return (value - min) / (max - min); + } + } + + public SliderClone(int x, int y, int width, int height, Option option, float initialValue, + Consumer setter, Function formatter, String tooltipKey) { + super(0, x, y, width, height, ""); + this.option = option; + this.sliderPercentage = option.normalize(initialValue); + this.displayString = formatter.apply(initialValue); + this.valueSetter = setter; + this.displayStringFormatter = formatter; + this.tooltipKey = tooltipKey; + } + + /** + * Returns 0 if the button is disabled, 1 if the mouse is NOT hovering over this button and 2 if it IS hovering over + * this button. + */ + public int getHoverState(boolean mouseOver) { + return 0; + } + + /** + * Fired when the mouse button is dragged. Equivalent of MouseListener.mouseDragged(MouseEvent e). + */ + protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { + if (this.visible) { + if (this.mouseDragging) { + this.sliderPercentage = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); + + if (this.sliderPercentage < 0.0F) { + this.sliderPercentage = 0.0F; + } + + if (this.sliderPercentage > 1.0F) { + this.sliderPercentage = 1.0F; + } + + float f = this.option.denormalize(this.sliderPercentage); + valueSetter.accept(f); + this.sliderPercentage = this.option.normalize(f); + this.displayString = displayStringFormatter.apply(f); + } + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(this.xPosition + (int)(this.sliderPercentage * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); + this.drawTexturedModalRect(this.xPosition + (int)(this.sliderPercentage * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); + } + } + + /** + * Returns true if the mouse has been pressed on this control. Equivalent of MouseListener.mousePressed(MouseEvent e). + */ + public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { + if (super.mousePressed(mc, mouseX, mouseY)) { + this.sliderPercentage = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); + + if (this.sliderPercentage < 0.0F) { + this.sliderPercentage = 0.0F; + } + + if (this.sliderPercentage > 1.0F) { + this.sliderPercentage = 1.0F; + } + + float f = this.option.denormalize(this.sliderPercentage); + valueSetter.accept(f); + this.sliderPercentage = this.option.normalize(f); + this.displayString = displayStringFormatter.apply(f); + this.mouseDragging = true; + return true; + } else { + return false; + } + } + + /** + * Fired when the mouse button is released. Equivalent of MouseListener.mouseReleased(MouseEvent e). + */ + public void mouseReleased(int mouseX, int mouseY) { + this.mouseDragging = false; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java index 7e288a4ca..fb4cfc940 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java @@ -87,11 +87,6 @@ public class AngelicaConfig { @Config.RequiresMcRestart public static boolean enableFontRenderer; - @Config.Comment("OffSet fonts shadows draw") - @Config.DefaultFloat(0.5F) - @Config.RangeFloat(min = 0.5F, max = 1F) - public static float shadowOffsetFontUC; - @Config.Comment("Enable Dynamic Lights") @Config.DefaultBoolean(true) @Config.RequiresMcRestart diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaGuiConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaGuiConfig.java index 1bb7a7ec7..670e618d2 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaGuiConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaGuiConfig.java @@ -6,6 +6,12 @@ import net.minecraft.client.gui.GuiScreen; public class AngelicaGuiConfig extends SimpleGuiConfig { public AngelicaGuiConfig(GuiScreen parent) throws ConfigException { - super(parent, AngelicaConfig.class, "angelica", "Angelica"); + super(parent, + "angelica", + "Angelica", + true, + AngelicaConfig.class, + FontConfig.class + ); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/config/FontConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/FontConfig.java new file mode 100644 index 000000000..798b79a4d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/config/FontConfig.java @@ -0,0 +1,58 @@ +package com.gtnewhorizons.angelica.config; + +import com.gtnewhorizon.gtnhlib.config.Config; + +@Config(modid = "angelica", category = "customfont") +public class FontConfig { + @Config.Comment("Whether or not to use custom fonts when drawing text.") + @Config.DefaultBoolean(false) + public static boolean enableCustomFont; + + @Config.Comment("Name of the primary custom font. Best not to set it from here.") + @Config.DefaultString("(none)") + public static String customFontNamePrimary; + + @Config.Comment("Name of the fallback custom font. Best not to set it from here.") + @Config.DefaultString("(none)") + public static String customFontNameFallback; + + @Config.Comment("The quality at which custom fonts are rendered, making them less pixelated but increasing memory usage.") + @Config.DefaultInt(30) + @Config.RangeInt(min = 6, max = 72) + public static int customFontQuality; + + @Config.Comment("Controls the distance at which the font's shadow is drawn.") + @Config.DefaultFloat(1F) + @Config.RangeFloat(min = 0F, max = 2F) + public static float fontShadowOffset; + + @Config.Comment("Influences the aspect ratio of each glyph.") + @Config.DefaultFloat(0F) + @Config.RangeFloat(min = -1F, max = 1F) + public static float glyphAspect; + + @Config.Comment("Scale of each glyph, whitespace excluded.") + @Config.DefaultFloat(1F) + @Config.RangeFloat(min = 0.1F, max = 3F) + public static float glyphScale; + + @Config.Comment("Whitespace scale.") + @Config.DefaultFloat(1F) + @Config.RangeFloat(min = 0.1F, max = 3F) + public static float whitespaceScale; + + @Config.Comment("Adds extra spacing between glyphs.") + @Config.DefaultFloat(0F) + @Config.RangeFloat(min = -2F, max = 2F) + public static float glyphSpacing; + + @Config.Comment("Controls font antialiasing. 0 = none, 1 = 4x MSAA, 2 = 16x MSAA.") + @Config.DefaultInt(2) + @Config.RangeInt(min = 0, max = 2) + public static int fontAAMode; + + @Config.Comment("Affects font antialiasing sample spacing. Higher values increase blur.") + @Config.DefaultInt(5) + @Config.RangeInt(min = 1, max = 24) + public static int fontAAStrength; +} diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaTweaker.java b/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaTweaker.java index a35b1843a..e0f76e3d8 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaTweaker.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaTweaker.java @@ -7,6 +7,7 @@ import com.gtnewhorizon.gtnhmixins.builders.IMixins; import com.gtnewhorizon.gtnhmixins.builders.ITransformers; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.CompatConfig; +import com.gtnewhorizons.angelica.config.FontConfig; import com.gtnewhorizons.angelica.mixins.Mixins; import com.gtnewhorizons.angelica.loading.fml.compat.CompatHandlers; import cpw.mods.fml.relauncher.FMLLaunchHandler; @@ -57,6 +58,7 @@ public class AngelicaTweaker implements IFMLLoadingPlugin, IEarlyMixinLoader { // Angelica Config ConfigurationManager.registerConfig(AngelicaConfig.class); ConfigurationManager.registerConfig(CompatConfig.class); + ConfigurationManager.registerConfig(FontConfig.class); MCPatcherForgeConfig.registerConfig(); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index b13c47d90..e84f2430c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -54,6 +54,7 @@ public enum Mixins implements IMixins { .addClientMixins( "angelica.fontrenderer.MixinGuiIngameForge" , "angelica.fontrenderer.MixinFontRenderer" + , "angelica.fontrenderer.MixinMCResourceAccessor" ) ), diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ResourceAccessor.java b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ResourceAccessor.java new file mode 100644 index 000000000..e439a3373 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/interfaces/ResourceAccessor.java @@ -0,0 +1,7 @@ +package com.gtnewhorizons.angelica.mixins.interfaces; + +import java.util.List; + +public interface ResourceAccessor { + List angelica$getDefaultResourcePacks(); +} diff --git a/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/ReeseSodiumVideoOptionsScreen.java b/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/ReeseSodiumVideoOptionsScreen.java index 6c2d88529..f9c21e657 100644 --- a/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/ReeseSodiumVideoOptionsScreen.java +++ b/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/ReeseSodiumVideoOptionsScreen.java @@ -1,5 +1,6 @@ package me.flashyreese.mods.reeses_sodium_options.client.gui; +import com.gtnewhorizons.angelica.client.gui.FontConfigScreen; import com.gtnewhorizons.angelica.compat.mojang.Element; import com.gtnewhorizons.angelica.config.AngelicaConfig; import jss.notfine.gui.GuiCustomMenu; @@ -96,25 +97,35 @@ public class ReeseSodiumVideoOptionsScreen extends SodiumOptionsGUI { this.applyButton = new FlatButtonWidget(applyButtonDim, "Apply", this::applyChanges); this.closeButton = new FlatButtonWidget(closeButtonDim, "Close", this::onClose); - Dim2i searchTextFieldDim = new Dim2i(tabFrameDim.getOriginX(), tabFrameDim.getOriginY() - 26, tabFrameDim.getWidth(), 20); basicFrameBuilder = this.parentBasicFrameBuilder(basicFrameDim, tabFrameDim); - if(AngelicaConfig.enableIris) { + int cumulativeXShift = 0; + + if (AngelicaConfig.enableIris) { //int size = this.client.textRenderer.getWidth(new TranslatableText(IrisApi.getInstance().getMainScreenLanguageKey())); final String irisText = I18n.format(IrisApi.getInstance().getMainScreenLanguageKey()); final int size = this.mc.fontRenderer.getStringWidth(irisText); final Dim2i shaderPackButtonDim = new Dim2i(tabFrameDim.getLimitX() - size - 10, tabFrameDim.getOriginY() - 26, 10 + size, 20); + cumulativeXShift += size + 12; - searchTextFieldDim = new Dim2i(tabFrameDim.getOriginX(), tabFrameDim.getOriginY() - 26, tabFrameDim.getWidth() - (tabFrameDim.getLimitX() - shaderPackButtonDim.getOriginX()) - 2, 20); - - //FlatButtonWidget shaderPackButton = new FlatButtonWidget(shaderPackButtonDim, new TranslatableText(IrisApi.getInstance().getMainScreenLanguageKey()), () -> this.client.setScreen((Screen) IrisApi.getInstance().openMainIrisScreenObj(this))); final FlatButtonWidget shaderPackButton = new FlatButtonWidget(shaderPackButtonDim, irisText, () -> mc.displayGuiScreen(new ShaderPackScreen(this))); basicFrameBuilder.addChild(dim -> shaderPackButton); } + if (AngelicaConfig.enableFontRenderer) { + final String fontConfigText = I18n.format("options.angelica.fontconfig"); + final int size = this.mc.fontRenderer.getStringWidth(fontConfigText); + final Dim2i fontConfigButtonDim = new Dim2i(tabFrameDim.getLimitX() - size - 12 - cumulativeXShift, tabFrameDim.getOriginY() - 26, 12 + size, 20); + cumulativeXShift += size + 14; + + final FlatButtonWidget fontConfigButton = new FlatButtonWidget(fontConfigButtonDim, fontConfigText, () -> mc.displayGuiScreen(new FontConfigScreen(this))); + basicFrameBuilder.addChild(dim -> fontConfigButton); + } + + Dim2i searchTextFieldDim = new Dim2i(tabFrameDim.getOriginX(), tabFrameDim.getOriginY() - 26, tabFrameDim.getWidth() - cumulativeXShift, 20); this.searchTextField = new SearchTextFieldComponent(searchTextFieldDim, this.pages, tabFrameSelectedTab, tabFrameScrollBarOffset, optionPageScrollBarOffset, tabFrameDim.getHeight(), this, lastSearch, lastSearchIndex); diff --git a/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/frame/tab/TabFrame.java b/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/frame/tab/TabFrame.java index e3b70d2ae..7866de6df 100644 --- a/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/frame/tab/TabFrame.java +++ b/src/main/java/me/flashyreese/mods/reeses_sodium_options/client/gui/frame/tab/TabFrame.java @@ -47,7 +47,8 @@ public class TabFrame extends AbstractFrame { this.tabSectionSelectedTab = tabSectionSelectedTab; if (this.tabSectionSelectedTab.get() != null) { - this.selectedTab = this.tabs.stream().filter(tab -> tab.getTitle().equals(this.tabSectionSelectedTab.get())).findAny().get(); + Optional> possibleLastTab = this.tabs.stream().filter(tab -> tab.getTitle().equals(this.tabSectionSelectedTab.get())).findAny(); + possibleLastTab.ifPresent(tab -> this.selectedTab = tab); } this.buildFrame(); diff --git a/src/main/resources/assets/angelica/lang/en_US.lang b/src/main/resources/assets/angelica/lang/en_US.lang index 7a62ae2d7..9749ea6b6 100644 --- a/src/main/resources/assets/angelica/lang/en_US.lang +++ b/src/main/resources/assets/angelica/lang/en_US.lang @@ -135,6 +135,31 @@ options.dynamic_lights=Dynamic Lights options.dynamic_lights.tooltip=Enables dynamic lights. Modes: OFF - off, FASTEST - 500ms delay, FAST - 250ms delay, FANCY - 50ms delay, REALTIME - no delay. options.dynamic_lights_shader_force=Dynamic Lights - Forced With Shaders options.dynamic_lights_shader_force.tooltip=Enabled - Dynamic Lights are shown even when a shader is active, Disabled - Dynamic Lights are disabled when a shader is active. +options.angelica.fontconfig=Font Configuration... +options.angelica.fontconfig.title=Font Configuration +options.angelica.fontconfig.currentfonts=Primary font: §e%s§r Fallback font: §b%s +options.angelica.fontconfig.searchprompt=§7§oSearch fonts... +options.angelica.fontconfig.disable_custom_font=Disable Custom Font +options.angelica.fontconfig.enable_custom_font=Enable Custom Font +options.angelica.fontconfig.reset_values=Reset Values +options.angelica.fontconfig.font_quality=Custom Font Quality: %s +options.angelica.fontconfig.shadow_offset=Shadow Offset: %s +options.angelica.fontconfig.glyph_scale=Glyph Scale: %s +options.angelica.fontconfig.glyph_aspect=Glyph Aspect: %s +options.angelica.fontconfig.whitespace_scale=Whitespace Size: %s +options.angelica.fontconfig.glyph_spacing=Glyph Spacing: %s +options.angelica.fontconfig.font_aa_strength=Font AA Strength: %s +options.angelica.fontconfig.aamode.aa_none=Font AA: OFF +options.angelica.fontconfig.aamode.aa_4x=Font AA: 4x MSAA +options.angelica.fontconfig.aamode.aa_16x=Font AA: 16x MSAA +options.angelica.fontconfig.font_quality.tooltip=The quality at which custom fonts are rendered, making them less pixelated at the expense of some performance and memory. +options.angelica.fontconfig.shadow_offset.tooltip=The distance at which the fonts' shadows are drawn. Also affects the way §lbold§r text is drawn; turn this down if you see double text. +options.angelica.fontconfig.glyph_scale.tooltip=The scale of each individual glyph. Extreme values might make your game unplayable. +options.angelica.fontconfig.glyph_aspect.tooltip=The aspect ratio of each individual glyph. +options.angelica.fontconfig.whitespace_scale.tooltip=The scaling factor of blank characters like spaces. +options.angelica.fontconfig.glyph_spacing.tooltip=The spacing between each individual glyph. +options.angelica.fontconfig.font_aa_strength.tooltip=The spacing of samples used in font antialiasing. High values may cause fonts to look blurry, low values may cause aliasing. See what works best with your settings. +options.angelica.fontconfig.aamode.tooltip=The font antialiasing mode. Can significantly improve the appearance and readability of text that's being scaled or viewed at oblique angles, at the expense of some performance. options.angelica.droppedItemLimit=Dropped Item Render Limit options.angelica.droppedItemLimit.tooltip=The maximum number of dropped items that will be rendered. Lower values can improve performance. options.angelica.mobSpawnerRenderDistance=Mob spawner render distance diff --git a/src/main/resources/assets/angelica/shaders/fontFilter.fsh b/src/main/resources/assets/angelica/shaders/fontFilter.fsh new file mode 100644 index 000000000..a04ef05d5 --- /dev/null +++ b/src/main/resources/assets/angelica/shaders/fontFilter.fsh @@ -0,0 +1,65 @@ +#version 120 + +uniform sampler2D sampler; +uniform int aaMode; +uniform float strength; + +varying vec4 color; +varying vec4 tB; + +/* +Hacky MSAA and anisotropic filtering. Cursed beyond belief. There _may_ have been simpler means of +achieving the produced effects, but this appears to work without noticeable performance losses. +*/ + +float totalWt; + +float txSample(vec2 uv, float du, float dv, float factorU, float factorV) { + float distSquared = sqrt(du * du + dv * dv); + float weight = exp(-distSquared / 6); + totalWt += weight; + float finalU = uv.x + factorU * du; + float finalV = uv.y + factorV * dv; + if (finalU < tB.x || finalU > tB.y || finalV < tB.z || finalV > tB.w) { + return 0; + } + return weight * texture2D(sampler, vec2(finalU, finalV)).a; +} + +void main() { + vec2 texCoords = gl_TexCoord[0].st; + vec4 col = color; + if (texCoords.s != 0 || texCoords.t != 0) { + float res = 0; + float fu = strength * fwidth(texCoords.x); + float fv = strength * fwidth(texCoords.y); + totalWt = 0; + if (aaMode == 1) { + res += txSample(texCoords, 2, 6, fu, fv); + res += txSample(texCoords, 6, -2, fu, fv); + res += txSample(texCoords, -2, -6, fu, fv); + res += txSample(texCoords, -6, 2, fu, fv); + } else { + res += txSample(texCoords, 1, 1, fu, fv); + res += txSample(texCoords, -1, -3, fu, fv); + res += txSample(texCoords, -3, 2, fu, fv); + res += txSample(texCoords, 4, -1, fu, fv); + res += txSample(texCoords, -5, -2, fu, fv); + res += txSample(texCoords, 2, 5, fu, fv); + res += txSample(texCoords, 5, 3, fu, fv); + res += txSample(texCoords, 3, -5, fu, fv); + res += txSample(texCoords, -2, 6, fu, fv); + res += txSample(texCoords, 0, -7, fu, fv); + res += txSample(texCoords, -4, -6, fu, fv); + res += txSample(texCoords, -6, 4, fu, fv); + res += txSample(texCoords, -8, 0, fu, fv); + res += txSample(texCoords, 7, -4, fu, fv); + res += txSample(texCoords, 6, 7, fu, fv); + res += txSample(texCoords, -7, -8, fu, fv); + } + res /= totalWt; + col.a = res; + } + + gl_FragColor = col; +} diff --git a/src/main/resources/assets/angelica/shaders/fontFilter.vsh b/src/main/resources/assets/angelica/shaders/fontFilter.vsh new file mode 100644 index 000000000..09b0a9ff2 --- /dev/null +++ b/src/main/resources/assets/angelica/shaders/fontFilter.vsh @@ -0,0 +1,12 @@ +#version 120 + +attribute vec4 texBounds; +varying vec4 tB; +varying vec4 color; + +void main() { + gl_Position = ftransform(); + gl_TexCoord[0] = gl_MultiTexCoord0; + color = gl_Color; + tB = texBounds; +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java index fdb2c7457..3e1fc718a 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.fontrenderer; +import com.gtnewhorizon.gtnhlib.util.font.IFontParameters; import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.FontRendererAccessor; @@ -26,7 +27,7 @@ import java.util.Random; * @author eigenraven */ @Mixin(FontRenderer.class) -public abstract class MixinFontRenderer implements FontRendererAccessor { +public abstract class MixinFontRenderer implements FontRendererAccessor, IFontParameters { @Shadow private boolean randomStyle; @@ -119,7 +120,7 @@ public abstract class MixinFontRenderer implements FontRendererAccessor { @Inject(method = "", at = @At("TAIL")) private void angelica$injectBatcher(GameSettings settings, ResourceLocation fontLocation, TextureManager texManager, boolean unicodeMode, CallbackInfo ci) { - angelica$batcher = new BatchingFontRenderer((FontRenderer) (Object) this, unicodePageLocations, this.charWidth, this.glyphWidth, this.colorCode, this.locationFontTexture); + angelica$batcher = new BatchingFontRenderer((FontRenderer) (Object) this, this.charWidth, this.glyphWidth, this.colorCode, this.locationFontTexture); } @Unique @@ -191,4 +192,39 @@ public abstract class MixinFontRenderer implements FontRendererAccessor { private int angelica$maxCharWidth(int original) { return Integer.MAX_VALUE; } + + @Inject(method = "getCharWidth", at = @At("HEAD"), cancellable = true) + public void getCharWidth(char c, CallbackInfoReturnable cir) { + cir.setReturnValue((int) angelica$getBatcher().getCharWidthFine(c)); + } + + @Override + public float getGlyphScaleX() { + return angelica$getBatcher().getGlyphScaleX(); + } + + @Override + public float getGlyphScaleY() { + return angelica$getBatcher().getGlyphScaleY(); + } + + @Override + public float getGlyphSpacing() { + return angelica$getBatcher().getGlyphSpacing(); + } + + @Override + public float getWhitespaceScale() { + return angelica$getBatcher().getWhitespaceScale(); + } + + @Override + public float getShadowOffset() { + return angelica$getBatcher().getShadowOffset(); + } + + @Override + public float getCharWidthFine(char chr) { + return angelica$getBatcher().getCharWidthFine(chr); + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinMCResourceAccessor.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinMCResourceAccessor.java new file mode 100644 index 000000000..3bfb77936 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinMCResourceAccessor.java @@ -0,0 +1,19 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.fontrenderer; + +import com.gtnewhorizons.angelica.mixins.interfaces.ResourceAccessor; +import net.minecraft.client.Minecraft; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; + +import java.util.List; + +@Mixin(Minecraft.class) +public class MixinMCResourceAccessor implements ResourceAccessor { + @Shadow + private List defaultResourcePacks; + + @Override + public List angelica$getDefaultResourcePacks() { + return defaultResourcePacks; + } +}