Dark mode text recoloring with resource packs configs (#2118)

Co-authored-by: Ranzu <[email protected]>
Co-authored-by: Alexdoru <[email protected]>
Co-authored-by: Jason Mitchell <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-30 16:12:54 -07:00
1 parent cbd16b1a76
commit 9cb35c67cd
8 files changed
+911 -6

No files matched your search

@@ -1132,6 +1132,32 @@ public class BatchingFontRenderer {
lightmapPackedLight = -1;
}
public static boolean darkModeRecolorEnabled = false;
public static boolean enterRecolorSection(boolean enable) {
boolean prev = darkModeRecolorEnabled;
darkModeRecolorEnabled = enable;
return prev;
}
public static void exitRecolorSection(boolean prev) {
darkModeRecolorEnabled = prev;
}
// Inside a button section, text drawn in one of the button's own three colors is swapped for button_font's color.
// Button sections can't be nested: only the on/off flag is restored on exit, not the colors.
private static boolean buttonSectionActive = false;
private static int buttonEnabledColor, buttonHoveredColor, buttonDisabledColor;
public static boolean enterButtonSection(int enabledColor, int hoveredColor, int disabledColor) {
boolean prev = buttonSectionActive;
buttonSectionActive = true;
buttonEnabledColor = enabledColor;
buttonHoveredColor = hoveredColor;
buttonDisabledColor = disabledColor;
return prev;
}
public static void exitButtonSection(boolean prev) {
buttonSectionActive = prev;
}
// === Actual text mesh generation
public static boolean charInRange(char what, char fromInclusive, char toInclusive) {
@@ -1215,12 +1241,15 @@ public class BatchingFontRenderer {
private static final double WAVE_TIME_SCALE = 5e-9;
private static final float WAVE_FREQUENCY = 0.5f;
public float drawString(final float anchorX, final float anchorY, final int color, final boolean enableShadow,
public float drawString(final float anchorX, final float anchorY, final int inputColor, final boolean enableShadow,
final boolean unicodeFlag, final CharSequence string, int stringOffset, int stringLength) {
// noinspection SizeReplaceableByIsEmpty
if (string == null || string.length() == 0) {
return anchorX + (enableShadow ? 1.0f : 0.0f);
}
final int color = buttonSectionActive
? DarkModeUtils.recolorButtonText(inputColor, buttonEnabledColor, buttonHoveredColor, buttonDisabledColor)
: inputColor;
final int shadowColor = (color & 0xfcfcfc) >> 2 | color & 0xff000000;
FontProviderMC.get(this.isSGA).charWidth = this.charWidth;
@@ -1314,6 +1343,9 @@ public class BatchingFontRenderer {
curColor = (curColor & 0xFF000000) | (rgb & 0x00FFFFFF);
curShadowColor = (curShadowColor & 0xFF000000) | ((rgb & 0xFCFCFC) >> 2);
charIdx += SECTION_X_PAYLOAD;
if (darkModeRecolorEnabled) {
curShadow = false;
}
}
} else {
final boolean is09 = charInRange(fmtCode, '0', '9');
@@ -1334,6 +1366,9 @@ public class BatchingFontRenderer {
curColor = (curColor & 0xFF000000) | (rgb & 0x00FFFFFF);
final int shadowRgb = this.colorCode[colorIdx + 16];
curShadowColor = (curShadowColor & 0xFF000000) | (shadowRgb & 0x00FFFFFF);
if (darkModeRecolorEnabled) {
curShadow = false;
}
} else if (fmtCode == 'k') {
curRandom = true;
} else if (fmtCode == 'l') {
@@ -1479,6 +1514,15 @@ public class BatchingFontRenderer {
renderY += (float) Math.sin(visibleCharIndex * WAVE_FREQUENCY + time) * AngelicaConfig.waveAmplitude;
}
if (darkModeRecolorEnabled) {
long recolor = DarkModeUtils.computeGuiFontRecolor(curColor);
if (recolor != DarkModeUtils.NO_RECOLOR) {
curColor = DarkModeUtils.unpackColor(recolor);
curShadowColor = (curShadowColor & 0xFF000000) | DarkModeUtils.unpackShadowRgb(recolor);
curShadow = DarkModeUtils.unpackShadow(recolor);
}
}
float renderX = curX;
int glyphColor = curColor;
int glyphShadowColor = curShadowColor;
@@ -1507,7 +1551,7 @@ public class BatchingFontRenderer {
// After the background, so this command covers only what is counted below.
final int idxId = idxWriterIndex;
final boolean drawShadow = enableShadow || curShadow;
final boolean drawShadow = enableShadow || curShadow || (darkModeRecolorEnabled && DarkModeUtils.shadowsGlobal());
if (drawShadow) {
final int effectiveShadowColor = curShadowCustomColor
? ((glyphColor & 0xFF000000) | (curShadowColorOverride & 0x00FFFFFF))
@@ -0,0 +1,316 @@
package com.gtnewhorizons.angelica.client.font;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.ResourcePackRepository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.prupe.mcpatcher.mal.resource.TexturePackChangeHandler;
public class DarkModeUtils {
private static final Logger LOGGER = LogManager.getLogger("DarkModeUtils");
private static final String ROOT_KEY = "dark_mode_utils";
private static final int SUPPORTED_SCHEMA = 1;
private static final String DEBUG_PULSE = "debug_pulse";
private static final double DEBUG_PULSE_TIME_SCALE = 5e-9;
private static final String[] INPUT_STREAM_METHOD_NAMES = { "getInputStreamByName", "func_110591_a" };
private static final Map<Class<?>, Method> INPUT_STREAM_METHOD_CACHE = new HashMap<>();
private static FontRecolorRule guiFontRule = null;
private static ButtonFontRules buttonFontRules = null;
private static boolean shadowsGlobal = false;
static {
TexturePackChangeHandler.register(new TexturePackChangeHandler("Angelica Dark Mode Utils", 1) {
@Override
public void beforeChange() {}
@Override
public void afterChange() {
reload();
}
});
}
private DarkModeUtils() {}
public static void init() { /* see static block */ }
private static void reload() {
FontRecolorRule guiFont = null;
ButtonFontRules buttonFont = null;
boolean shadowsGlobalValue = false;
ResourcePackRepository repository = Minecraft.getMinecraft().getResourcePackRepository();
for (ResourcePackRepository.Entry entry : repository.getRepositoryEntries()) {
IResourcePack pack = entry.getResourcePack();
PackDarkModeRules rules = readPackRules(pack);
if (rules == null) {
continue;
}
if (rules.guiFont() != null) {
guiFont = rules.guiFont();
}
if (rules.buttonFont() != null) {
buttonFont = rules.buttonFont();
}
if (rules.shadowsGlobal() != null) {
shadowsGlobalValue = rules.shadowsGlobal();
}
}
guiFontRule = guiFont;
buttonFontRules = buttonFont;
shadowsGlobal = shadowsGlobalValue;
}
// Mechanism similar to GTNHLib's PackMcmetaReader. Will be refactored into one common implementation if a third use case arises.
private static PackDarkModeRules readPackRules(IResourcePack pack) {
try (InputStream stream = openPackMcmeta(pack)) {
if (stream == null) {
return null;
}
JsonElement rootElement = new JsonParser().parse(new InputStreamReader(stream, StandardCharsets.UTF_8));
if (!rootElement.isJsonObject()) {
return null;
}
JsonObject root = rootElement.getAsJsonObject();
if (!root.has(ROOT_KEY) || !root.get(ROOT_KEY).isJsonObject()) {
return null;
}
JsonObject darkModeUtils = root.getAsJsonObject(ROOT_KEY);
int schema = darkModeUtils.has("schema") ? darkModeUtils.get("schema").getAsInt() : -1;
if (schema != SUPPORTED_SCHEMA) {
LOGGER.warn("Unsupported dark_mode_utils schema {} in pack {}", schema, pack.getPackName());
return null;
}
JsonObject target = darkModeUtils.has("target") && darkModeUtils.get("target").isJsonObject()
? darkModeUtils.getAsJsonObject("target")
: null;
if (target == null) {
return null;
}
FontRecolorRule guiFont = target.has("gui_font") && target.get("gui_font").isJsonObject()
? parseFontRecolorRule(target.getAsJsonObject("gui_font"), pack.getPackName(), "gui_font")
: null;
ButtonFontRules buttonFont = target.has("button_font") && target.get("button_font").isJsonObject()
? parseButtonFontRules(target.getAsJsonObject("button_font"), pack.getPackName())
: null;
Boolean shadowsGlobal = target.has("shadows_global")
? target.get("shadows_global").getAsBoolean()
: null;
return new PackDarkModeRules(guiFont, buttonFont, shadowsGlobal);
} catch (IOException e) {
// pack.mcmeta missing/unreadable
return null;
} catch (RuntimeException e) {
LOGGER.warn("Invalid dark_mode_utils block in pack {}: {}", pack.getPackName(), e.toString());
return null;
}
}
private static ButtonFontRules parseButtonFontRules(JsonObject buttonFont, String packName) {
ButtonColorRule enabled = parseButtonState(buttonFont, "enabled", packName);
ButtonColorRule hovered = parseButtonState(buttonFont, "hovered", packName);
ButtonColorRule disabled = parseButtonState(buttonFont, "disabled", packName);
if (enabled == null && hovered == null && disabled == null) {
return null;
}
return new ButtonFontRules(enabled, hovered, disabled);
}
private static ButtonColorRule parseButtonState(JsonObject buttonFont, String state, String packName) {
if (!buttonFont.has(state) || !buttonFont.get(state).isJsonObject()) {
return null;
}
try {
String outputValue = buttonFont.getAsJsonObject(state).get("output").getAsString().trim();
boolean debugPulse = DEBUG_PULSE.equalsIgnoreCase(outputValue);
return new ButtonColorRule(debugPulse ? 0 : parseHexColor(outputValue), debugPulse);
} catch (RuntimeException e) {
LOGGER.warn("Invalid dark_mode_utils button_font.{} rule in pack {}: {}", state, packName, e.toString());
return null;
}
}
private static FontRecolorRule parseFontRecolorRule(JsonObject obj, String packName, String context) {
try {
JsonObject input = obj.getAsJsonObject("input");
int minimum = parseHexColor(input.get("minimum").getAsString());
int maximum = parseHexColor(input.get("maximum").getAsString());
String outputValue = obj.get("output").getAsString().trim();
boolean debugPulse = DEBUG_PULSE.equalsIgnoreCase(outputValue);
int output = debugPulse ? 0 : parseHexColor(outputValue);
boolean shadow = obj.has("shadow") && obj.get("shadow").getAsBoolean();
return new FontRecolorRule(minimum, maximum, output, debugPulse, shadow);
} catch (RuntimeException e) {
LOGGER.warn("Invalid dark_mode_utils {} rule in pack {}: {}", context, packName, e.toString());
return null;
}
}
private static int parseHexColor(String value) {
return Integer.decode(value.trim()) & 0x00FFFFFF;
}
private static InputStream openPackMcmeta(IResourcePack pack) throws IOException {
Method method = findGetInputStreamByName(pack.getClass());
if (method == null) {
return null;
}
try {
return (InputStream) method.invoke(pack, "pack.mcmeta");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof IOException ioException) {
throw ioException;
}
return null;
} catch (IllegalAccessException e) {
return null;
}
}
private static Method findGetInputStreamByName(Class<?> type) {
if (INPUT_STREAM_METHOD_CACHE.containsKey(type)) {
return INPUT_STREAM_METHOD_CACHE.get(type);
}
Method found = null;
outer: for (Class<?> current = type; current != null; current = current.getSuperclass()) {
for (String name : INPUT_STREAM_METHOD_NAMES) {
try {
found = current.getDeclaredMethod(name, String.class);
found.setAccessible(true);
break outer;
} catch (NoSuchMethodException ignored) {
}
}
}
INPUT_STREAM_METHOD_CACHE.put(type, found);
return found;
}
public static final long NO_RECOLOR = -1L;
public static long computeGuiFontRecolor(int argbColor) {
FontRecolorRule rule = guiFontRule;
if (rule == null) {
return NO_RECOLOR;
}
return rule.tryRecolor(argbColor);
}
public static boolean shadowsGlobal() {
return shadowsGlobal;
}
// layout: newColor (32), shadowRgb (24, no alpha), zeroes (7), shadow (1)
private static long packRecolor(int newColor, int shadowRgb, boolean shadow) {
return ((long) newColor << 32) | ((long) (shadowRgb & 0xFFFFFF) << 8) | (shadow ? 1L : 0L);
}
public static int unpackColor(long packed) {
return (int) (packed >>> 32);
}
public static int unpackShadowRgb(long packed) {
return (int) ((packed >>> 8) & 0xFFFFFF);
}
public static boolean unpackShadow(long packed) {
return (packed & 1L) != 0;
}
/**
* Inside a button section, swaps text drawn in one of the button's own three colors for the matching button_font
* color. Pure white also counts as the enabled color, since it's the most likely override of it. Any other color
* is returned untouched.
*/
public static int recolorButtonText(int argbColor, int enabledColor, int hoveredColor, int disabledColor) {
final ButtonFontRules rules = buttonFontRules;
if (rules == null) {
return argbColor;
}
final int rgb = argbColor & 0x00FFFFFF;
final ButtonColorRule rule;
if (rgb == enabledColor || rgb == 0xFFFFFF) { rule = rules.enabled(); }
else if (rgb == hoveredColor) { rule = rules.hovered(); }
else if (rgb == disabledColor) { rule = rules.disabled(); }
else { return argbColor; }
if (rule == null) {
return argbColor;
}
return (argbColor & 0xFF000000) | (rule.debugPulse() ? computeDebugPulseRgb() : rule.output());
}
private static int computeDebugPulseRgb() {
final float time = HUDCaching.renderingCacheOverride ? 0f
: (float) ((System.nanoTime() & 0xFFFFFFFFFFFFL) * DEBUG_PULSE_TIME_SCALE);
final int animated = (int) (Math.round(0x00007F80 * (Math.sin(2 * time) + 1)) & 0x0000FFFF);
return 0x00FF0000 | animated;
}
private record PackDarkModeRules(FontRecolorRule guiFont, ButtonFontRules buttonFont, Boolean shadowsGlobal) {}
private record ButtonFontRules(ButtonColorRule enabled, ButtonColorRule hovered, ButtonColorRule disabled) {}
private record ButtonColorRule(int output, boolean debugPulse) {}
private static final class FontRecolorRule {
final int minR, minG, minB;
final int maxR, maxG, maxB;
final int output;
final boolean debugPulse;
final boolean shadow;
FontRecolorRule(int minimum, int maximum, int output, boolean debugPulse, boolean shadow) {
this.minR = (minimum >> 16) & 0xFF;
this.minG = (minimum >> 8) & 0xFF;
this.minB = minimum & 0xFF;
this.maxR = (maximum >> 16) & 0xFF;
this.maxG = (maximum >> 8) & 0xFF;
this.maxB = maximum & 0xFF;
this.output = output;
this.debugPulse = debugPulse;
this.shadow = shadow;
}
long tryRecolor(int argbColor) {
final int r = (argbColor >> 16) & 0xFF;
final int g = (argbColor >> 8) & 0xFF;
final int b = argbColor & 0xFF;
final boolean nearBlack = r <= minR && g <= minG && b <= minB;
final boolean nearWhite = r >= maxR && g >= maxG && b >= maxB;
if (!nearBlack && !nearWhite) {
return NO_RECOLOR;
}
final int outputRgb = debugPulse ? computeDebugPulseRgb() : output;
final int newColor = (argbColor & 0xFF000000) | outputRgb;
final int shadowRgb = (outputRgb & 0xFCFCFC) >> 2;
return packRecolor(newColor, shadowRgb, shadow);
}
}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.loading.fml.transformers;
import com.gtnewhorizons.angelica.loading.AngelicaClientTweaker;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.DarkModeFontTransform;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
public class DarkModeFontTransformer implements IClassTransformer {
private final DarkModeFontTransform inner = new DarkModeFontTransform();
@Override
public byte[] transform(String name, String transformedName, byte[] basicClass) {
if (DarkModeFontTransform.classesToTransform.containsKey(transformedName)) {
final ClassReader cr = new ClassReader(basicClass);
final ClassNode cn = new ClassNode();
cr.accept(cn, 0);
if (!inner.transformClassNode(cn, transformedName, AngelicaClientTweaker.isObfEnv())) {
return basicClass;
}
final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cn.accept(cw);
final byte[] bytes = cw.toByteArray();
AngelicaClassDump.dumpClass(transformedName, basicClass, bytes, this);
return bytes;
}
return basicClass;
}
}
@@ -64,9 +64,14 @@ public class AngelicaLateTweaker implements ITweaker {
FMLRelaunchLog.warning("[Angelica] Failed to remove EarlyRedirectorTransformer: %s", e.getMessage());
}
final String transformer = "com.gtnewhorizons.angelica.loading.fml.transformers.AngelicaRedirectorTransformer";
FMLRelaunchLog.finer("Registering transformer %s", transformer);
Launch.classLoader.registerTransformer(transformer);
final String[] transformers = {
"com.gtnewhorizons.angelica.loading.fml.transformers.AngelicaRedirectorTransformer",
"com.gtnewhorizons.angelica.loading.fml.transformers.DarkModeFontTransformer"
};
for (String transformer : transformers) {
FMLRelaunchLog.finer("Registering transformer %s", transformer);
Launch.classLoader.registerTransformer(transformer);
}
return new String[0];
}
}
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.loading.rfb;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBAngelicaRedirector;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBCeleritasBlockTransformer;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBDarkModeFontTransformer;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBIsbrhTessellatorAbuseTransformer;
import com.gtnewhorizons.retrofuturabootstrap.api.PluginContext;
import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap;
@@ -30,7 +31,8 @@ public class AngelicaRfbPlugin implements RfbPlugin {
return new RfbClassTransformer[] {
new RFBAngelicaRedirector(),
new RFBCeleritasBlockTransformer(isObf),
new RFBIsbrhTessellatorAbuseTransformer(isObf)
new RFBIsbrhTessellatorAbuseTransformer(isObf),
new RFBDarkModeFontTransformer(isObf)
};
}
}
@@ -0,0 +1,61 @@
package com.gtnewhorizons.angelica.loading.rfb.transformers;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.DarkModeFontTransform;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader;
import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
import org.intellij.lang.annotations.Pattern;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.jar.Manifest;
public class RFBDarkModeFontTransformer implements RfbClassTransformer {
private final DarkModeFontTransform inner;
private final boolean isObf;
public RFBDarkModeFontTransformer(boolean isObf) {
this.inner = new DarkModeFontTransform();
this.isObf = isObf;
}
@Pattern("[a-z0-9-]+")
@Override
public @NotNull String id() {
return "dark-mode-font";
}
@Override
public @NotNull String @Nullable [] sortAfter() {
return new String[] {"*", "mixin:mixin"};
}
@Override
public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context,
@Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) {
if (!classNode.isPresent()) {
return false;
}
return DarkModeFontTransform.classesToTransform.containsKey(className);
}
@Override
public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context,
@Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) {
final boolean changed = inner.transformClassNode(classNode.getNode(), className, this.isObf);
if (changed) {
classNode.computeFrames();
AngelicaClassDump.dumpRFBClass(className, classNode, this);
}
return changed;
}
@Override
public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context,
@Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) {
transformClassIfNeeded(classLoader, context, manifest, className, classNode);
}
}
@@ -0,0 +1,443 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import com.gtnewhorizons.angelica.client.font.DarkModeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DarkModeFontTransform {
private static final Logger LOGGER = LogManager.getLogger("DarkModeFontTransformer");
private static final String BATCHINGFONTRENDERER = "com/gtnewhorizons/angelica/client/font/BatchingFontRenderer";
public static class MethodInfo {
public final String className;
public final String classNameSlash;
private final String name;
private final String obfName;
public final String desc;
// Accepts an AT entry, examples:
// net.minecraft.client.gui.inventory.GuiContainer func_73863_a(IIF)V # drawScreen
// vswe.stevescarts.Interfaces.GuiNEIKiller drawScreen(IIF)V
public MethodInfo(@NotNull String atEntry) {
int firstSpace = atEntry.indexOf(' ');
int descStart = atEntry.indexOf('(');
int hashIndex = atEntry.indexOf('#');
String className = atEntry.substring(0, firstSpace);
String identifierBeforeDesc = atEntry.substring(firstSpace, descStart).trim();
String name, obfName, desc;
if (hashIndex != -1) {
obfName = identifierBeforeDesc;
desc = atEntry.substring(descStart, hashIndex).trim();
name = atEntry.substring(hashIndex + 1).trim();
} else {
name = identifierBeforeDesc;
desc = atEntry.substring(descStart);
obfName = null;
}
this(className, name, obfName, desc);
}
public MethodInfo(@NotNull String className, @NotNull String name, @Nullable String obfName, @NotNull String desc) {
this.className = className;
this.classNameSlash = className.replace('.', '/');
this.name = name;
this.obfName = obfName;
this.desc = desc;
}
public String getName(boolean isObf) {
if (obfName == null) { return name; }
if (isObf) { return obfName; }
return name;
}
@Override
public String toString() {
return className + "#" + name + desc;
}
}
/**
* Data used to tell the transformer that it should use some calls
* ({@link BatchingFontRenderer#enterRecolorSection(boolean)}, {@link BatchingFontRenderer#exitRecolorSection(boolean)})
* to mark areas where text should be recolored according to the rules in {@link DarkModeUtils}.
* Can either apply to an entire method (placing markers in it) or a specific method call in some method (wrapping the call).
* A button target wraps the same way, but with a button section that also carries the button's three text colors.
*/
public record RecolorTarget(@NotNull MethodInfo method, @Nullable MethodInfo calledMethod, boolean recolorEnabled, @Nullable ButtonColors buttonColors) {
public RecolorTarget(MethodInfo method, MethodInfo calledMethod, boolean recolorEnabled) { this(method, calledMethod, recolorEnabled, null); }
public static RecolorTarget includeMethod(MethodInfo method) { return new RecolorTarget(method, null, true); }
public static RecolorTarget excludeMethod(MethodInfo method) { return new RecolorTarget(method, null, false); }
public static RecolorTarget includeMethodCall(MethodInfo callingMethod, MethodInfo calledMethod) { return new RecolorTarget(callingMethod, calledMethod, true); }
public static RecolorTarget excludeMethodCall(MethodInfo callingMethod, MethodInfo calledMethod) { return new RecolorTarget(callingMethod, calledMethod, false); }
public static RecolorTarget includeButtonMethod(MethodInfo method, int enabledColor, int hoveredColor, int disabledColor) {
return new RecolorTarget(method, null, true, new ButtonColors(enabledColor, hoveredColor, disabledColor));
}
public static RecolorTarget includeButtonMethodCall(MethodInfo callingMethod, MethodInfo calledMethod, int enabledColor, int hoveredColor, int disabledColor) {
return new RecolorTarget(callingMethod, calledMethod, true, new ButtonColors(enabledColor, hoveredColor, disabledColor));
}
public static RecolorTarget includeButtonMethod(MethodInfo method) {
return new RecolorTarget(method, null, true, ButtonColors.VANILLA);
}
public static RecolorTarget includeButtonMethodCall(MethodInfo callingMethod, MethodInfo calledMethod) {
return new RecolorTarget(callingMethod, calledMethod, true, ButtonColors.VANILLA);
}
public boolean targetsCall() { return calledMethod != null; }
}
/** The colors a button draws its text in for each of its three states. VANILLA is what vanilla buttons use. */
public record ButtonColors(int enabled, int hovered, int disabled) {
public static final ButtonColors VANILLA = new ButtonColors(0xE0E0E0, 0xFFFFA0, 0xA0A0A0);
}
// A target method must contain the obf name if it's
// a) a vanilla method
// or b) a modded method belonging to a class that extends (or is) a vanilla class that declares said method (so, an override).
// Notably, "GuiNEIKiller" does not override drawGuiContainerForegroundLayer because it doesn't inherit GuiContainer.
public static final RecolorTarget[] recolorTargets = {
//region Include Methods
// Vanilla methods. Many mods use these; several draw text in the "background" layer...
RecolorTarget.includeMethodCall(
new MethodInfo("net.minecraft.client.gui.inventory.GuiContainer func_73863_a(IIF)V # drawScreen"),
new MethodInfo("net.minecraft.client.gui.inventory.GuiContainer func_146979_b(II)V # drawGuiContainerForegroundLayer")
),
RecolorTarget.includeMethodCall(
new MethodInfo("net.minecraft.client.gui.inventory.GuiContainer func_73863_a(IIF)V # drawScreen"),
new MethodInfo("net.minecraft.client.gui.inventory.GuiContainer func_146976_a(FII)V # drawGuiContainerBackgroundLayer")
),
RecolorTarget.excludeMethod(
new MethodInfo("net.minecraft.client.renderer.entity.RenderItem func_94148_a(Lnet/minecraft/client/gui/FontRenderer;Lnet/minecraft/client/renderer/texture/TextureManager;Lnet/minecraft/item/ItemStack;IILjava/lang/String;)V # renderItemOverlayIntoGUI")
),
// Modded stuff. Some mods copy-paste vanilla code.
// Avaritia Addons
RecolorTarget.includeMethodCall(
new MethodInfo("wanion.avaritiaddons.block.chest.infinity.GuiInfinityChest func_73863_a(IIF)V # drawScreen"),
new MethodInfo("wanion.avaritiaddons.block.chest.infinity.GuiInfinityChest func_146979_b(II)V # drawGuiContainerForegroundLayer")
),
// Better Achievements
RecolorTarget.includeMethodCall(
new MethodInfo("betterachievements.gui.GuiBetterAchievements func_73863_a(IIF)V # drawScreen"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_78276_b(Ljava/lang/String;III)I # drawString")
),
// ModularUI 1
RecolorTarget.includeMethodCall(
new MethodInfo("com.gtnewhorizons.modularui.common.internal.wrapper.ModularGui func_73863_a(IIF)V # drawScreen"),
new MethodInfo("com.gtnewhorizons.modularui.common.internal.wrapper.ModularGui func_146976_a(FII)V # drawGuiContainerBackgroundLayer")
),
// Nutrition
RecolorTarget.includeMethod(
new MethodInfo("ca.wescook.nutrition.gui.GuiLabelNutrition drawLabel(Lnet/minecraft/client/Minecraft;II)V")
),
// Railcraft
RecolorTarget.includeMethodCall(
new MethodInfo("mods.railcraft.client.gui.GuiBasic func_73863_a(IIF)V # drawScreen"),
new MethodInfo("mods.railcraft.client.gui.GuiTools drawCenteredString(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;II)V")
),
RecolorTarget.includeMethodCall(
new MethodInfo("mods.railcraft.client.gui.GuiBasic func_73863_a(IIF)V # drawScreen"),
new MethodInfo("mods.railcraft.client.gui.GuiBasic drawExtras(IIF)V")
),
// Galacticraft
RecolorTarget.includeMethodCall(
new MethodInfo("micdoodle8.mods.galacticraft.core.client.gui.element.GuiElementCheckbox func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_85187_a(Ljava/lang/String;IIIZ)I # drawString")
),
// Steve's Factory Manager
RecolorTarget.includeMethodCall(
new MethodInfo("vswe.stevesfactory.interfaces.GuiBase drawString(Ljava/lang/String;IIFI)V"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_78276_b(Ljava/lang/String;III)I # drawString")
),
// Steve's Carts 2
RecolorTarget.includeMethodCall(
new MethodInfo("vswe.stevescarts.Interfaces.GuiNEIKiller func_73863_a(IIF)V # drawScreen"),
new MethodInfo("vswe.stevescarts.Interfaces.GuiNEIKiller drawGuiContainerForegroundLayer(II)V")
),
// Binnie
RecolorTarget.includeMethodCall(
new MethodInfo("binnie.core.craftgui.minecraft.GuiCraftGUI func_73863_a(IIF)V # drawScreen"),
new MethodInfo("binnie.core.craftgui.minecraft.Window render()V")
),
// Malisis Core (Malisis' Doors)
RecolorTarget.includeMethodCall(
new MethodInfo("net.malisis.core.client.gui.MalisisGui func_73863_a(IIF)V # drawScreen"),
new MethodInfo("net.malisis.core.client.gui.GuiRenderer drawScreen(Lnet/malisis/core/client/gui/component/container/UIContainer;IIF)V")
),
// Nuclear Control
RecolorTarget.includeMethod(
new MethodInfo("shedar.mods.ic2.nuclearcontrol.gui.controls.GuiHowlerAlarmSlider func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
RecolorTarget.includeMethod(
new MethodInfo("shedar.mods.ic2.nuclearcontrol.gui.controls.GuiHowlerAlarmListBox func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
RecolorTarget.includeMethod(
new MethodInfo("shedar.mods.ic2.nuclearcontrol.gui.GuiScreenColor func_73863_a(IIF)V # drawScreen")
),
// Draconic Evolution
RecolorTarget.includeMethodCall(
new MethodInfo("com.brandon3055.draconicevolution.client.gui.GUIFlowGate func_73863_a(IIF)V # drawScreen"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_78276_b(Ljava/lang/String;III)I # drawString")
),
RecolorTarget.includeMethodCall(
new MethodInfo("com.brandon3055.draconicevolution.client.gui.GUIParticleGenerator func_73863_a(IIF)V # drawScreen"),
new MethodInfo("com.brandon3055.draconicevolution.client.gui.GUIParticleGenerator$IProperty drawLabel(Lnet/minecraft/client/gui/FontRenderer;II)V")
),
RecolorTarget.includeMethodCall(
new MethodInfo("com.brandon3055.draconicevolution.client.gui.GUIParticleGenerator func_73863_a(IIF)V # drawScreen"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_78279_b(Ljava/lang/String;IIII)V # drawSplitString")
),
// Logistics Pipes
RecolorTarget.includeMethodCall(
new MethodInfo("logisticspipes.utils.gui.SubGuiScreen func_73863_a(IIF)V # drawScreen"),
new MethodInfo("logisticspipes.utils.gui.SubGuiScreen drawGuiContainerForegroundLayer(II)V")
),
// Minecraft-Backpack-Mod
RecolorTarget.includeMethod(
new MethodInfo("de.eydamos.guiadvanced.form.Label draw(Lnet/minecraft/client/Minecraft;IIF)V")
),
//endregion
//region Exclude Methods
// Applied Energistics 2
RecolorTarget.excludeMethod(
new MethodInfo("appeng.client.render.StackSizeRenderer drawStackSize(IILjava/lang/String;Lnet/minecraft/client/gui/FontRenderer;Lappeng/api/config/TerminalFontSize;)V")
),
// GregTech
RecolorTarget.excludeMethodCall(
new MethodInfo("gregtech.common.render.FluidDisplayStackRenderer renderItem(Lnet/minecraftforge/client/IItemRenderer$ItemRenderType;Lnet/minecraft/item/ItemStack;[Ljava/lang/Object;)V"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_85187_a(Ljava/lang/String;IIIZ)I # drawString")
),
RecolorTarget.excludeMethodCall(
new MethodInfo("gregtech.api.recipe.RecipeMapFrontend drawNEIOverlayText(Ljava/lang/String;Lcodechicken/nei/PositionedStack;IFZLcom/gtnewhorizons/modularui/api/math/Alignment;)V"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_85187_a(Ljava/lang/String;IIIZ)I # drawString")
),
// GT NEI Ore Plugin
RecolorTarget.excludeMethodCall(
new MethodInfo("gtneioreplugin.plugin.renderer.ItemDimensionDisplayRenderer renderItem(Lnet/minecraftforge/client/IItemRenderer$ItemRenderType;Lnet/minecraft/item/ItemStack;[Ljava/lang/Object;)V"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_85187_a(Ljava/lang/String;IIIZ)I # drawString")
),
// NotEnoughItems
RecolorTarget.excludeMethod(
new MethodInfo("codechicken.nei.guihook.GuiContainerManager drawBigStackSize(IILjava/lang/String;F)V")
),
// NEI Custom Diagram
RecolorTarget.excludeMethod(
new MethodInfo("com.github.dcysteine.neicustomdiagram.api.draw.Draw drawStackSize(ILcom/github/dcysteine/neicustomdiagram/api/draw/Point;)V")
),
// BiblioCraft
RecolorTarget.excludeMethodCall(
new MethodInfo("jds.bibliocraft.gui.GuiFancySign func_146976_a(FII)V # drawGuiContainerBackgroundLayer"),
new MethodInfo("jds.bibliocraft.gui.GuiBiblioTextField drawTextBox()V")
),
// Harvestcraft
RecolorTarget.excludeMethodCall(
new MethodInfo("com.pam.harvestcraft.TrapRecipeHandler drawExtras(I)V"),
new MethodInfo("codechicken.lib.gui.GuiDraw drawString(Ljava/lang/String;III)V")
),
// Thaumcraft
RecolorTarget.excludeMethod(
new MethodInfo("thaumcraft.client.gui.GuiResearchTable drawAspects(II)V")
),
// Steve's Carts 2
RecolorTarget.excludeMethod(
new MethodInfo("vswe.stevescarts.Interfaces.GuiBase drawMouseOver(Ljava/lang/String;II)V")
),
//endregion
//region Buttons
// Buttons. The three colors are the button's own: enabled, hovered, disabled.
// Vanilla
RecolorTarget.includeButtonMethodCall(
new MethodInfo("net.minecraft.client.gui.GuiButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton"),
new MethodInfo("net.minecraft.client.gui.GuiButton func_73732_a(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;III)V # drawCenteredString")
),
// CodeChickenCore
RecolorTarget.includeButtonMethod(
new MethodInfo("codechicken.core.gui.GuiCCButton drawText(II)V")
),
// NotEnoughItems
RecolorTarget.includeButtonMethodCall(
new MethodInfo("codechicken.nei.LayoutStyleMinecraft drawButton(Lcodechicken/nei/Button;II)V"),
new MethodInfo("codechicken.lib.gui.GuiDraw drawStringC(Ljava/lang/String;III)V"),
0xE0E0E0, 0xFFFFA0, 0x601010
),
RecolorTarget.includeButtonMethod(
new MethodInfo("codechicken.nei.GuiNEIButton drawContent(Lnet/minecraft/client/Minecraft;IIZ)V")
),
RecolorTarget.includeButtonMethodCall(
new MethodInfo("codechicken.nei.config.OptionButton drawButton(II)V"),
new MethodInfo("codechicken.lib.gui.GuiDraw drawStringC(Ljava/lang/String;IIIII)V")
),
RecolorTarget.includeButtonMethodCall(
new MethodInfo("codechicken.nei.config.DataDumper drawButton(IILcodechicken/lib/vec/Rectangle4i;Ljava/lang/String;)V"),
new MethodInfo("codechicken.lib.gui.GuiDraw drawStringC(Ljava/lang/String;IIIII)V")
),
// Malisis Core (Malisis' Doors)
RecolorTarget.includeButtonMethodCall(
new MethodInfo("net.malisis.core.client.gui.component.interaction.UIButton drawForeground(Lnet/malisis/core/client/gui/GuiRenderer;IIF)V"),
new MethodInfo("net.malisis.core.client.gui.GuiRenderer drawText(Lnet/malisis/core/renderer/font/MalisisFont;Ljava/lang/String;FFFLnet/malisis/core/renderer/font/FontRenderOptions;)V"),
0xFFFFFF, 0xFFFFA0, 0xA0A0A0
),
// MrTJPCore (ProjectRed)
RecolorTarget.includeButtonMethodCall(
new MethodInfo("mrtjp.core.gui.TButtonText$class drawButton(Lmrtjp/core/gui/TButtonText;Z)V"),
new MethodInfo("codechicken.lib.gui.GuiDraw drawStringC(Ljava/lang/String;III)V")
),
// LittleTiles (CreativeCore)
RecolorTarget.includeButtonMethodCall(
new MethodInfo("com.creativemd.creativecore.common.gui.controls.GuiButton drawControl(Lnet/minecraft/client/gui/FontRenderer;)V"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_78261_a(Ljava/lang/String;III)I # drawStringWithShadow")
),
// Logistics Pipes
RecolorTarget.includeButtonMethod(
new MethodInfo("logisticspipes.utils.gui.SmallGuiButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
// Nuclear Control
RecolorTarget.includeButtonMethodCall(
new MethodInfo("shedar.mods.ic2.nuclearcontrol.gui.controls.CompactButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_78276_b(Ljava/lang/String;III)I # drawString"),
0x303030, 0x303030, 0x303030
),
// Forge
RecolorTarget.includeButtonMethod(
new MethodInfo("cpw.mods.fml.client.config.GuiButtonExt func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
RecolorTarget.includeButtonMethod(
new MethodInfo("cpw.mods.fml.client.config.GuiUnicodeGlyphButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
// Tinkers Mechworks
RecolorTarget.includeButtonMethod(
new MethodInfo("tmechworks.client.gui.AdvDrawbridgeButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
// RemoteIO
RecolorTarget.includeButtonMethod(
new MethodInfo("remoteio.client.gui.button.GuiBetterButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
// Railcraft
RecolorTarget.includeButtonMethod(
new MethodInfo("mods.railcraft.client.gui.buttons.GuiBetterButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton"),
0xE0E0E0, 0xFFFFA0, 0x777777
),
RecolorTarget.includeButtonMethod(
new MethodInfo("mods.railcraft.client.gui.buttons.GuiMultiButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
// BuildCraft
RecolorTarget.includeButtonMethod(
new MethodInfo("buildcraft.core.lib.gui.buttons.GuiBetterButton func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton")
),
// Minecraft-Backpack-Mod
RecolorTarget.includeButtonMethodCall(
new MethodInfo("de.eydamos.guiadvanced.form.Button func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton"),
new MethodInfo("de.eydamos.guiadvanced.form.Button func_73732_a(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;III)V # drawCenteredString")
),
//endregion
};
public static final Map<String, List<RecolorTarget>> classesToTransform = new HashMap<>();
static {
for (RecolorTarget target : recolorTargets) {
classesToTransform.computeIfAbsent(target.method.className, _ -> new ArrayList<>()).add(target);
}
}
public boolean transformClassNode(ClassNode cn, String className, boolean isObf) {
boolean changed = false;
List<RecolorTarget> targets = classesToTransform.get(className);
if (targets == null) { return false; }
for (RecolorTarget target : targets) {
for (MethodNode mn : cn.methods) {
if (!mn.name.equals(target.method.getName(isObf))) { continue; }
if (!mn.desc.equals(target.method.desc)) { continue; }
if (target.targetsCall()) {
changed = markRecolorCallScoped(mn, target.calledMethod, isObf, target.recolorEnabled, target.buttonColors) || changed;
} else {
changed = markRecolorMethodScoped(mn, target.method, target.recolorEnabled, target.buttonColors) || changed;
}
}
}
return changed;
}
private static void insertEnterSection(InsnList insnList, AbstractInsnNode before, boolean recolorEnabled, @Nullable ButtonColors buttonColors) {
if (buttonColors == null) {
insnList.insertBefore(before, new InsnNode(recolorEnabled ? Opcodes.ICONST_1 : Opcodes.ICONST_0));
insnList.insertBefore(before, new MethodInsnNode(Opcodes.INVOKESTATIC, BATCHINGFONTRENDERER, "enterRecolorSection", "(Z)Z", false));
} else {
insnList.insertBefore(before, new LdcInsnNode(buttonColors.enabled()));
insnList.insertBefore(before, new LdcInsnNode(buttonColors.hovered()));
insnList.insertBefore(before, new LdcInsnNode(buttonColors.disabled()));
insnList.insertBefore(before, new MethodInsnNode(Opcodes.INVOKESTATIC, BATCHINGFONTRENDERER, "enterButtonSection", "(III)Z", false));
}
}
private static MethodInsnNode exitSectionCall(@Nullable ButtonColors buttonColors) {
return new MethodInsnNode(Opcodes.INVOKESTATIC, BATCHINGFONTRENDERER, buttonColors == null ? "exitRecolorSection" : "exitButtonSection", "(Z)V", false);
}
private boolean markRecolorCallScoped(MethodNode mn, MethodInfo calledMethod, boolean isObf, boolean recolorEnabled, @Nullable ButtonColors buttonColors) {
boolean changed = false;
InsnList insnList = mn.instructions;
for (AbstractInsnNode insn = insnList.getFirst(); insn != null; insn = insn.getNext()) {
if (insn instanceof MethodInsnNode min) {
if (!min.owner.equals(calledMethod.classNameSlash)) { continue; }
if (!min.name.equals(calledMethod.getName(isObf))) { continue; }
if (!min.desc.equals(calledMethod.desc)) { continue; }
int maxLocals = mn.maxLocals;
insertEnterSection(insnList, min, recolorEnabled, buttonColors);
insnList.insertBefore(min, new VarInsnNode(Opcodes.ISTORE, maxLocals));
insnList.insert(min, exitSectionCall(buttonColors));
insnList.insert(min, new VarInsnNode(Opcodes.ILOAD, maxLocals));
LOGGER.info("Added {}-recolor flags at call site of {}", recolorEnabled ? "enable" : "disable", calledMethod.toString());
changed = true;
}
}
return changed;
}
private boolean markRecolorMethodScoped(MethodNode mn, MethodInfo method, boolean recolorEnabled, @Nullable ButtonColors buttonColors) {
InsnList insnList = mn.instructions;
if (insnList.size() == 0) { return false; }
AbstractInsnNode firstInsn = insnList.getFirst();
int maxLocals = mn.maxLocals;
insertEnterSection(insnList, firstInsn, recolorEnabled, buttonColors);
insnList.insertBefore(firstInsn, new VarInsnNode(Opcodes.ISTORE, maxLocals));
for (AbstractInsnNode insn = firstInsn; insn != null; insn = insn.getNext()) {
int opcode = insn.getOpcode();
if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) {
insnList.insertBefore(insn, new VarInsnNode(Opcodes.ILOAD, maxLocals));
insnList.insertBefore(insn, exitSectionCall(buttonColors));
}
}
LOGGER.info("Added {}-recolor flags in {}", recolorEnabled ? "enable" : "disable", method.toString());
return true;
}
}
@@ -37,6 +37,7 @@ import biomesoplenty.api.content.BOPCBlocks;
import com.google.common.base.Objects;
import com.gtnewhorizon.gtnhlib.client.model.loading.ModelRegistry;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager;
import com.gtnewhorizons.angelica.client.font.DarkModeUtils;
import com.gtnewhorizons.angelica.commands.AngelicaCommand;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.common.BlockError;
@@ -154,6 +155,7 @@ public final class ClientProxy extends CommonProxy {
HUDCaching.init();
}
CeleritasSetup.ensureInitialized();
DarkModeUtils.init();
final SodiumGameOptions opts = options();
if (opts.advanced.vsyncMode == null) {
opts.advanced.vsyncMode = FrameRateOptions.defaultMode();