Refactor: Make runtime detection extensible and Java 8 compatible

Split the runtime package into small, single-purpose pieces so new loaders and Minecraft versions can be added by registration instead of editing control flow.

- Add LoaderProbe registry for mod loader detection

- Add VersionSignatureRegistry/VersionSignature and move structural version signatures out of VersionDetector

- Add VersionIdSource list for Forge/NeoForge metadata readers

- Extract ModernVersionDetector and CandidateClassLoaders

- Replace MinecraftVersion's mutable static id with RuntimeInfo.versionId

- Target Java 8 with source/target 1.8 and --release 8 on JDK 9+

- Add docs/adding-minecraft-versions.md
This commit is contained in:
xiaozhou233 committed 2026-11-04 01:04:50 +08:00
1 parent 789303c665
commit 8b9dbce0f7
25 files changed
+1039 -512

No files matched your search

@@ -1,76 +0,0 @@
package cn.xiaozhou233.orangex.runtime;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class MinecraftProbe {
private final String minecraftClass;
private final String minecraftGetter;
private final String minecraftInstanceField;
private final String[] minecraftAnchors;
public MinecraftProbe(String minecraftClass, String minecraftGetter, String minecraftInstanceField, String... minecraftAnchors) {
this.minecraftClass = minecraftClass;
this.minecraftGetter = minecraftGetter;
this.minecraftInstanceField = minecraftInstanceField;
this.minecraftAnchors = minecraftAnchors;
}
/**
* Probes the given loader. The game class and every anchor must be defined by
* the same class loader, otherwise classes inherited from a parent loader can
* produce false positives.
*/
public boolean probe(ClassLoader loader) {
// Class Check
Class<?> mcClass = ClassProbe.find(loader, minecraftClass);
if (mcClass == null) {
return false;
}
ClassLoader definingLoader = mcClass.getClassLoader();
if (definingLoader == null) {
return false;
}
// Anchor Check
for (String anchor : minecraftAnchors) {
if (anchor == null || anchor.isEmpty()) {
continue;
}
Class<?> anchorClass = ClassProbe.find(definingLoader, anchor);
if (anchorClass == null || anchorClass.getClassLoader() != definingLoader) {
return false;
}
}
return matchesStructure(mcClass);
}
private boolean matchesStructure(Class<?> mcClass) {
try {
// Method(Getter) Check
if (minecraftGetter != null && !minecraftGetter.isEmpty()) {
Method getter = mcClass.getDeclaredMethod(minecraftGetter);
boolean getterOk = Modifier.isStatic(getter.getModifiers())
&& getter.getReturnType() == mcClass;
if (!getterOk) {
return false;
}
}
// Instance Field Check (Tips: Some version of minecraft does not have this field)
if (minecraftInstanceField == null || minecraftInstanceField.isEmpty()) {
return true;
}
Field instance = mcClass.getDeclaredField(minecraftInstanceField);
return Modifier.isStatic(instance.getModifiers())
&& instance.getType() == mcClass;
} catch (ReflectiveOperationException | SecurityException | LinkageError e) {
return false;
}
}
}
@@ -6,12 +6,29 @@ import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import cn.xiaozhou233.orangex.runtime.version.VersionDetector;
/**
* Entry point for Minecraft runtime detection.
*
* <p>Each step has a single owner, so the pipeline stays easy to extend:</p>
* <ol>
* <li>{@link GameClassLoaderResolver} - find the game class loader.</li>
* <li>{@link LoaderDetector} - identify the mod loader.</li>
* <li>{@link VersionDetector} - resolve the Minecraft version.</li>
* </ol>
*/
public final class RuntimeDetector {
public static RuntimeInfo detect() {
ClassLoader classLoader = GameClassLoaderResolver.resolve();
LoaderType loaderType = LoaderDetector.detect(classLoader);
MinecraftVersion version = VersionDetector.detect(classLoader, loaderType);
return new RuntimeInfo(classLoader, loaderType, version);
int versionId = VersionDetector.detectId(classLoader, loaderType);
return new RuntimeInfo(
classLoader,
loaderType,
MinecraftVersion.fromId(versionId),
versionId
);
}
public static void debug(RuntimeInfo runtime) {
@@ -25,11 +42,25 @@ public final class RuntimeDetector {
ClassLoader loader = runtime.getMinecraftClassLoader();
MinecraftVersion version = runtime.getMinecraftVersion();
int protocol = MinecraftVersion.getCurrentProtocolVersion();
System.out.println("Minecraft ClassLoader: " + loader);
System.out.println("Context ClassLoader (current thread): " + Thread.currentThread().getContextClassLoader());
if (loader != null) {
System.out.println("Context ClassLoader (current thread): "
+ Thread.currentThread().getContextClassLoader());
printHierarchy(loader);
System.out.println("Loader Type: "
+ (runtime.getLoaderType() == null ? "UNKNOWN" : runtime.getLoaderType().name()));
System.out.println("Minecraft Version: "
+ (version == null ? "UNKNOWN" : version.name())
+ " (version id " + runtime.getVersionId() + ")");
System.out.println("========================================");
}
private static void printHierarchy(ClassLoader loader) {
if (loader == null) {
return;
}
StringBuilder hierarchy = new StringBuilder(loader.getClass().getName());
ClassLoader parent = loader.getParent();
while (parent != null) {
@@ -38,9 +69,7 @@ public final class RuntimeDetector {
}
System.out.println("ClassLoader Hierarchy: " + hierarchy);
}
System.out.println("Loader Type: " + (runtime.getLoaderType() == null ? "UNKNOWN" : runtime.getLoaderType().name()));
System.out.println("Minecraft Version: " + (version == null ? "UNKNOWN" : version.name())
+ " (version id " + protocol + ")");
System.out.println("========================================");
private RuntimeDetector() {
}
}
@@ -5,10 +5,24 @@ import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
/**
* Immutable result of runtime detection.
*/
@Getter
public class RuntimeInfo {
@AllArgsConstructor
public final class RuntimeInfo {
private final ClassLoader minecraftClassLoader;
private final LoaderType loaderType;
private final MinecraftVersion minecraftVersion;
/**
* OrangeX internal version id. Kept even when {@link #minecraftVersion} is
* unknown, so diagnostics can still show what was detected.
*/
private final int versionId;
public boolean isKnown() {
return !minecraftVersion.isUnknown();
}
}
@@ -0,0 +1,38 @@
package cn.xiaozhou233.orangex.runtime.classloader;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Collects every class loader that may define Minecraft classes.
*
* <p>The primary loader is tried first, so detection stays deterministic when
* several loaders can see the same classes.</p>
*/
public final class CandidateClassLoaders {
public static Set<ClassLoader> of(ClassLoader primary) {
Set<ClassLoader> loaders = new LinkedHashSet<>();
add(loaders, primary);
add(loaders, Thread.currentThread().getContextClassLoader());
add(loaders, CandidateClassLoaders.class.getClassLoader());
try {
add(loaders, ClassLoader.getSystemClassLoader());
} catch (SecurityException ignored) {
// Security manager may forbid system loader lookup.
}
return loaders;
}
private static void add(Set<ClassLoader> loaders, ClassLoader loader) {
if (loader != null) {
loaders.add(loader);
}
}
private CandidateClassLoaders() {
}
}
@@ -1,6 +1,6 @@
package cn.xiaozhou233.orangex.runtime.classloader;
import cn.xiaozhou233.orangex.runtime.ClassProbe;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
public final class GameClassLoaderResolver {
@@ -0,0 +1,27 @@
package cn.xiaozhou233.orangex.runtime.loader;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
/**
* Matches a loader when at least one of its marker classes is present.
*/
public final class ClassPresenceLoaderProbe implements LoaderProbe {
private final LoaderType type;
private final String[] markers;
public ClassPresenceLoaderProbe(LoaderType type, String... markers) {
this.type = type;
this.markers = markers.clone();
}
@Override
public LoaderType type() {
return type;
}
@Override
public boolean matches(ClassLoader loader) {
return ClassProbe.exists(loader, markers);
}
}
@@ -1,69 +1,50 @@
package cn.xiaozhou233.orangex.runtime.loader;
import cn.xiaozhou233.orangex.runtime.ClassProbe;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Identifies the mod loader by running an ordered list of {@link LoaderProbe}s.
*
* <p>To support a new mod loader, add a probe to {@link #PROBES} and a matching
* value to {@link LoaderType}.</p>
*/
public final class LoaderDetector {
/**
* Order matters:
* <ol>
* <li>NeoForge before Forge, because NeoForge is a Forge fork.</li>
* <li>MCP before VANILLA, because MCP is a deobfuscated environment.</li>
* </ol>
*/
private static final List<LoaderProbe> PROBES = Collections.unmodifiableList(Arrays.<LoaderProbe>asList(
new ClassPresenceLoaderProbe(LoaderType.NEOFORGE,
"net.neoforged.fml.ModList",
"net.neoforged.fml.loading.FMLLoader"),
new ClassPresenceLoaderProbe(LoaderType.FORGE,
"net.minecraftforge.fml.common.Loader",
"net.minecraftforge.fml.loading.FMLLoader"),
new ClassPresenceLoaderProbe(LoaderType.FABRIC,
"net.fabricmc.loader.api.FabricLoader"),
new McpLoaderProbe()
));
public static LoaderType detect(ClassLoader loader) {
if (loader == null) {
return LoaderType.UNKNOWN;
}
// NeoForge has higher priority because it is a Forge fork
if (isNeoForge(loader)) {
return LoaderType.NEOFORGE;
for (LoaderProbe probe : PROBES) {
if (probe.matches(loader)) {
return probe.type();
}
}
// Forge
if (isForge(loader)) {
return LoaderType.FORGE;
}
// Fabric
if (isFabric(loader)) {
return LoaderType.FABRIC;
}
// MCP: Minecraft deobfuscated (development) environment
// Has real class names (net.minecraft.client.Minecraft) but no mod loader
if (isMCP(loader)) {
return LoaderType.MCP;
}
// No mod loader found, obfuscated vanilla
return LoaderType.VANILLA;
}
private static boolean isNeoForge(ClassLoader loader) {
return ClassProbe.exists(loader,
"net.neoforged.fml.ModList",
"net.neoforged.fml.loading.FMLLoader");
}
private static boolean isForge(ClassLoader loader) {
return ClassProbe.exists(loader,
"net.minecraftforge.fml.common.Loader")
||
ClassProbe.exists(loader,
"net.minecraftforge.fml.loading.FMLLoader");
}
private static boolean isFabric(ClassLoader loader) {
return ClassProbe.exists(loader,
"net.fabricmc.loader.api.FabricLoader");
}
private static boolean isMCP(ClassLoader loader) {
try {
Class<?> mcClass = Class.forName("net.minecraft.client.Minecraft", false, loader);
mcClass.getDeclaredMethod("getMinecraft");
return true;
} catch (Throwable t) {
return false;
private LoaderDetector() {
}
}
}
@@ -0,0 +1,11 @@
package cn.xiaozhou233.orangex.runtime.loader;
/**
* One way to recognize a mod loader. Probes are checked in registration order.
*/
public interface LoaderProbe {
LoaderType type();
boolean matches(ClassLoader loader);
}
@@ -0,0 +1,30 @@
package cn.xiaozhou233.orangex.runtime.loader;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
/**
* MCP is a deobfuscated development environment: it exposes real class names
* but no mod loader.
*/
public final class McpLoaderProbe implements LoaderProbe {
@Override
public LoaderType type() {
return LoaderType.MCP;
}
@Override
public boolean matches(ClassLoader loader) {
Class<?> minecraftClass = ClassProbe.find(loader, "net.minecraft.client.Minecraft");
if (minecraftClass == null) {
return false;
}
try {
minecraftClass.getDeclaredMethod("getMinecraft");
return true;
} catch (Throwable ignored) {
return false;
}
}
}
@@ -0,0 +1,24 @@
/**
* Minecraft runtime detection.
*
* <p>Detection flows in a fixed order:</p>
* <ol>
* <li>{@link cn.xiaozhou233.orangex.runtime.classloader.GameClassLoaderResolver}
* finds the game class loader.</li>
* <li>{@link cn.xiaozhou233.orangex.runtime.loader.LoaderDetector}
* identifies the mod loader.</li>
* <li>{@link cn.xiaozhou233.orangex.runtime.version.VersionDetector}
* resolves the internal version id: loader metadata, then 26.x
* {@code version.json}, then structural signatures.</li>
* </ol>
*
* <p>Extending detection:</p>
* <ul>
* <li>New mod loader: add a {@code LoaderProbe} to {@code LoaderDetector}.</li>
* <li>New Minecraft version: add a {@code VersionSignature} to
* {@code VersionSignatureRegistry} (and an enum value if needed).</li>
* <li>New loader version metadata: add a {@code VersionIdSource} to
* {@code VersionIdSources}.</li>
* </ul>
*/
package cn.xiaozhou233.orangex.runtime;
@@ -1,40 +1,41 @@
package cn.xiaozhou233.orangex.runtime;
package cn.xiaozhou233.orangex.runtime.probe;
/**
* Small reflection helper for checking whether classes are visible to a loader.
*
* <p>Accepts both binary names ({@code net.minecraft.client.Minecraft}) and
* internal names ({@code net/minecraft/client/Minecraft}).</p>
*/
public final class ClassProbe {
public class ClassProbe {
public static boolean exists(ClassLoader loader, String... names) {
return find(loader, names) != null;
}
public static Class<?> find(ClassLoader loader, String... names) {
if (loader == null)
return null;
if (names == null)
if (loader == null || names == null) {
return null;
}
for (String name : names) {
// Check for empty names
if (name == null || name.isEmpty()) {
continue;
}
String binaryName = toBinaryName(name);
// Check for class existence
try {
return Class.forName(binaryName, false, loader);
return Class.forName(toBinaryName(name), false, loader);
} catch (Throwable ignored) {
// Missing classes are expected while probing.
}
}
return null;
}
/**
* Accepts both binary names ({@code net.minecraft.client.Minecraft}) and
* internal names ({@code net/minecraft/client/Minecraft}).
*/
private static String toBinaryName(String name) {
return name.indexOf('/') >= 0 ? name.replace('/', '.') : name;
}
private ClassProbe() {
}
}
@@ -0,0 +1,77 @@
package cn.xiaozhou233.orangex.runtime.probe;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Matches a {@link MinecraftSignature} against a class loader.
*/
public final class MinecraftProbe {
private final MinecraftSignature signature;
public MinecraftProbe(MinecraftSignature signature) {
this.signature = signature;
}
/**
* The game class and every anchor must be defined by the same class loader,
* otherwise classes inherited from a parent loader can produce false
* positives.
*/
public boolean matches(ClassLoader loader) {
Class<?> minecraftClass = ClassProbe.find(loader, signature.minecraftClass());
if (minecraftClass == null) {
return false;
}
ClassLoader definingLoader = minecraftClass.getClassLoader();
if (definingLoader == null) {
return false;
}
for (String anchor : signature.anchors()) {
Class<?> anchorClass = ClassProbe.find(definingLoader, anchor);
if (anchorClass == null || anchorClass.getClassLoader() != definingLoader) {
return false;
}
}
return matchesStructure(minecraftClass);
}
private boolean matchesStructure(Class<?> minecraftClass) {
try {
if (!matchesGetter(minecraftClass)) {
return false;
}
return matchesInstanceField(minecraftClass);
} catch (ReflectiveOperationException | SecurityException | LinkageError e) {
return false;
}
}
private boolean matchesGetter(Class<?> minecraftClass) throws NoSuchMethodException {
String getterName = signature.instanceGetter();
if (getterName == null || getterName.isEmpty()) {
return true;
}
Method getter = minecraftClass.getDeclaredMethod(getterName);
return Modifier.isStatic(getter.getModifiers())
&& getter.getReturnType() == minecraftClass;
}
private boolean matchesInstanceField(Class<?> minecraftClass) throws NoSuchFieldException {
String fieldName = signature.instanceField();
if (fieldName == null || fieldName.isEmpty()) {
// Some Minecraft versions do not expose a singleton field.
return true;
}
Field instance = minecraftClass.getDeclaredField(fieldName);
return Modifier.isStatic(instance.getModifiers())
&& instance.getType() == minecraftClass;
}
}
@@ -0,0 +1,65 @@
package cn.xiaozhou233.orangex.runtime.probe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Declarative description of the Minecraft entry class for one mapping set.
*
* <p>A version is recognized by locating {@link #minecraftClass()} and checking
* that its singleton getter/field and a set of anchor classes all belong to the
* same class loader. A signature therefore proves both the version and the
* class loader that owns the game classes.</p>
*/
public final class MinecraftSignature {
private final String minecraftClass;
private final String instanceGetter;
private final String instanceField;
private final List<String> anchors;
/**
* @param minecraftClass game entry class, binary or internal name
* @param instanceGetter static getter returning the singleton, or {@code null}
* @param instanceField static singleton field, or {@code null}
* @param anchors classes that must be defined by the same loader
*/
public MinecraftSignature(String minecraftClass,
String instanceGetter,
String instanceField,
List<String> anchors) {
this.minecraftClass = minecraftClass;
this.instanceGetter = instanceGetter;
this.instanceField = instanceField;
this.anchors = Collections.unmodifiableList(new ArrayList<String>(anchors));
}
public static MinecraftSignature of(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return new MinecraftSignature(
minecraftClass,
instanceGetter,
instanceField,
Arrays.asList(anchors));
}
public String minecraftClass() {
return minecraftClass;
}
public String instanceGetter() {
return instanceGetter;
}
public String instanceField() {
return instanceField;
}
public List<String> anchors() {
return anchors;
}
}
@@ -1,45 +0,0 @@
package cn.xiaozhou233.orangex.runtime.utils;
public class ForgeUtils {
public static int parseForgeVersion(Object value) {
if (value == null) {
return -1;
}
String text = String.valueOf(value).trim();
int start = 0;
while (start < text.length() && !Character.isDigit(text.charAt(start))) {
++start;
}
int end = start;
while (end < text.length() && Character.isDigit(text.charAt(end))) {
++end;
}
if (start == end) {
return -1;
}
try {
int parsed = Integer.parseInt(text.substring(start, end));
if (parsed == 62) {
return 100;
}
if (parsed == 65) {
return 110;
}
return isKnownVersionId(parsed) ? parsed : -1;
}
catch (NumberFormatException ignored) {
return -1;
}
}
private static boolean isKnownVersionId(int version) {
switch (version) {
case 13: case 15: case 23: case 28: case 35: case 36: case 37:
case 47: case 50: case 51: case 52: case 54: case 55: case 56: case 60: case 61:
case 100: case 110:
return true;
default:
return false;
}
}
}
@@ -1,5 +1,6 @@
package cn.xiaozhou233.orangex.runtime.utils;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@@ -8,57 +9,69 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class MinecraftUtils {
public static int matchesVersionMetadata(Class<?> minecraftClass) {
try (InputStream stream = minecraftClass.getResourceAsStream(
"/version.json")) {
/**
* Reads metadata bundled with the running Minecraft client.
*/
public final class MinecraftUtils {
/**
* Reads {@code /version.json} and maps the 26.x version family to an
* internal version id.
*
* @return the internal id, or {@link MinecraftVersion#UNKNOWN_ID} when the
* metadata is missing or does not describe a 26.x client
*/
public static int readModernVersionId(Class<?> minecraftClass) {
try (InputStream stream = minecraftClass.getResourceAsStream("/version.json")) {
if (stream == null) {
return 0;
return MinecraftVersion.UNKNOWN_ID;
}
JsonElement element = JsonParser.parseReader(new InputStreamReader(
stream, StandardCharsets.UTF_8));
if (!element.isJsonObject()) {
return 0;
return MinecraftVersion.UNKNOWN_ID;
}
JsonObject version = element.getAsJsonObject();
int javaVersion = getInteger(version, "java_version");
if (javaVersion != Integer.MIN_VALUE && javaVersion < 25) {
return 0;
return MinecraftVersion.UNKNOWN_ID;
}
String id = getString(version, "id");
String name = getString(version, "name");
if (id != null && id.equals(name)) {
boolean is261Family = id.startsWith("26.1")
&& (id.length() == 4 || id.charAt(4) == '.');
boolean is262Family = id.startsWith("26.2")
&& (id.length() == 4 || id.charAt(4) == '.');
if (is261Family) {
return 100;
if (id == null || !id.equals(name)) {
return MinecraftVersion.UNKNOWN_ID;
}
if (is262Family) {
return 110;
if (isFamily(id, "26.1")) {
return MinecraftVersion.V26_1.getId();
}
if (isFamily(id, "26.2")) {
return MinecraftVersion.V26_2.getId();
}
return MinecraftVersion.UNKNOWN_ID;
} catch (Exception | LinkageError ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
return 0;
}
catch (Exception ignored) {
return 0;
}
catch (LinkageError ignored) {
return 0;
}
private static boolean isFamily(String id, String family) {
return id.startsWith(family)
&& (id.length() == family.length() || id.charAt(family.length()) == '.');
}
private static String getString(JsonObject object, String name) {
JsonElement value = object.get(name);
return value != null && value.isJsonPrimitive()
? value.getAsString() : null;
return value != null && value.isJsonPrimitive() ? value.getAsString() : null;
}
private static int getInteger(JsonObject object, String name) {
JsonElement value = object.get(name);
return value != null && value.isJsonPrimitive()
? value.getAsInt() : Integer.MIN_VALUE;
return value != null && value.isJsonPrimitive() ? value.getAsInt() : Integer.MIN_VALUE;
}
private MinecraftUtils() {
}
}
@@ -0,0 +1,52 @@
package cn.xiaozhou233.orangex.runtime.version;
/**
* Parses Forge/NeoForge version strings into OrangeX internal version ids.
*
* <p>Some Forge lines use ids that differ from Minecraft's own numbering, so a
* couple of values are remapped explicitly. Any other value is accepted only
* when it matches a known {@link MinecraftVersion}.</p>
*/
public final class ForgeVersionParser {
private static final int NOT_FOUND = -1;
public static int parse(Object value) {
if (value == null) {
return NOT_FOUND;
}
String text = String.valueOf(value).trim();
int start = 0;
while (start < text.length() && !Character.isDigit(text.charAt(start))) {
start++;
}
int end = start;
while (end < text.length() && Character.isDigit(text.charAt(end))) {
end++;
}
if (start == end) {
return NOT_FOUND;
}
try {
int parsed = Integer.parseInt(text.substring(start, end));
if (parsed == 62) {
return MinecraftVersion.V26_1.getId();
}
if (parsed == 65) {
return MinecraftVersion.V26_2.getId();
}
return MinecraftVersion.fromId(parsed).isUnknown() ? NOT_FOUND : parsed;
} catch (NumberFormatException ignored) {
return NOT_FOUND;
}
}
private ForgeVersionParser() {
}
}
@@ -1,12 +1,16 @@
package cn.xiaozhou233.orangex.runtime.version;
import lombok.Getter;
import lombok.Setter;
/**
* Minecraft versions supported by OrangeX.
*
* <p>The numbers are OrangeX's internal version ids, <strong>not</strong>
* Minecraft network protocol numbers (for example, 1.8.9 is id 15 here, while
* its network protocol is 47).</p>
*/
@Getter
public enum MinecraftVersion {
// Note: the numbers below are OrangeX's internal version ids, NOT the
// Minecraft network protocol numbers (e.g. 1.8.9 is id 15 here, but its
// network protocol is 47).
V1_7_10(13),
V1_8_9(15),
V1_12_2(23),
@@ -27,43 +31,21 @@ public enum MinecraftVersion {
V26_2(110),
UNKNOWN(0);
@Setter
@Getter
public static int currentProtocolVersion;
@Getter
private final int protocolVersion;
public static final int UNKNOWN_ID = 0;
MinecraftVersion(int protocolVersion) {
this.protocolVersion = protocolVersion;
private final int id;
MinecraftVersion(int id) {
this.id = id;
}
public boolean is(int current) {
return current == this.protocolVersion;
public boolean isUnknown() {
return this == UNKNOWN;
}
public boolean isNot(int current) {
return current != this.protocolVersion;
}
public boolean greaterThan(int current) {
return current > this.protocolVersion;
}
public boolean greaterThanOrEqual(int current) {
return current >= this.protocolVersion;
}
public boolean lessThan(int current) {
return current < this.protocolVersion;
}
public boolean lessThanOrEqual(int current) {
return current <= this.protocolVersion;
}
public static MinecraftVersion fromProtocolId(int protocolId) {
public static MinecraftVersion fromId(int id) {
for (MinecraftVersion version : values()) {
if (version.protocolVersion == protocolId) {
if (version.id == id) {
return version;
}
}
@@ -0,0 +1,75 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.classloader.CandidateClassLoaders;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftProbe;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftSignature;
import cn.xiaozhou233.orangex.runtime.utils.MinecraftUtils;
/**
* Detects the 26.x line from class structure plus the bundled
* {@code version.json} metadata.
*
* <p>This runs before structural signatures: once a 26.x client is confirmed,
* older NeoForge signatures must not be considered (they share class names).</p>
*/
public final class ModernVersionDetector {
private static final String MINECRAFT_CLASS = "net/minecraft/client/Minecraft";
private static final MinecraftProbe MINECRAFT_PROBE = new MinecraftProbe(
MinecraftSignature.of(MINECRAFT_CLASS, "getInstance", "instance"));
public static int detect(ClassLoader primaryLoader) {
for (ClassLoader loader : CandidateClassLoaders.of(primaryLoader)) {
int versionId = detectIn(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
}
return MinecraftVersion.UNKNOWN_ID;
}
private static int detectIn(ClassLoader loader) {
Class<?> minecraftClass = resolveClass(loader, MINECRAFT_CLASS);
if (minecraftClass == null) {
return MinecraftVersion.UNKNOWN_ID;
}
ClassLoader definingLoader = minecraftClass.getClassLoader();
if (definingLoader == null || !MINECRAFT_PROBE.matches(loader)) {
return MinecraftVersion.UNKNOWN_ID;
}
if (!hasExpectedHierarchy(definingLoader)) {
return MinecraftVersion.UNKNOWN_ID;
}
return MinecraftUtils.readModernVersionId(minecraftClass);
}
private static boolean hasExpectedHierarchy(ClassLoader loader) {
Class<?> clientLevel = resolveClass(loader, "net/minecraft/client/multiplayer/ClientLevel");
Class<?> localPlayer = resolveClass(loader, "net/minecraft/client/player/LocalPlayer");
Class<?> abstractClientPlayer = resolveClass(loader, "net/minecraft/client/player/AbstractClientPlayer");
Class<?> level = resolveClass(loader, "net/minecraft/world/level/Level");
return clientLevel != null
&& localPlayer != null
&& abstractClientPlayer != null
&& level != null
&& clientLevel.getSuperclass() == level
&& localPlayer.getSuperclass() == abstractClientPlayer;
}
private static Class<?> resolveClass(ClassLoader loader, String internalName) {
try {
return Class.forName(internalName.replace('/', '.'), false, loader);
} catch (ClassNotFoundException | LinkageError | SecurityException e) {
return null;
}
}
private ModernVersionDetector() {
}
}
@@ -1,262 +1,31 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.ClassProbe;
import cn.xiaozhou233.orangex.runtime.MinecraftProbe;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.utils.ForgeUtils;
import cn.xiaozhou233.orangex.runtime.utils.MinecraftUtils;
import cn.xiaozhou233.orangex.runtime.utils.ReflectUtils;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Resolves the internal Minecraft version id.
*
* <p>Detection order, from most to least reliable:</p>
* <ol>
* <li>Loader-provided Forge/NeoForge metadata.</li>
* <li>The 26.x {@code version.json} family.</li>
* <li>Structural class signatures.</li>
* </ol>
*/
public final class VersionDetector {
public static MinecraftVersion detect(ClassLoader loader, LoaderType loaderType) {
int protocol = detectProtocol(loader, loaderType);
MinecraftVersion.setCurrentProtocolVersion(protocol);
return MinecraftVersion.fromProtocolId(protocol);
public static int detectId(ClassLoader loader, LoaderType loaderType) {
int versionId = VersionIdSources.resolve(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
private static int detectProtocol(ClassLoader loader, LoaderType loaderType) {
Throwable lastFailure = null;
// Layer 1: Forge minorVersion (legacy Forge)
try {
Object minorVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.common.ForgeVersion", "minorVersion");
if (minorVersion instanceof Number) {
return ((Number) minorVersion).intValue();
}
lastFailure = new IllegalStateException("ForgeVersion.minorVersion is not numeric");
} catch (Throwable t) {
lastFailure = t;
versionId = ModernVersionDetector.detect(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
// Layer 2: FMLLoader.forgeVersion (modern Forge/NeoForge)
try {
Object forgeVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.fml.loading.FMLLoader", "forgeVersion");
int parsed = ForgeUtils.parseForgeVersion(forgeVersion);
if (parsed >= 0) {
return parsed;
}
lastFailure = new IllegalStateException("FMLLoader.forgeVersion not supported: " + forgeVersion);
} catch (Throwable t) {
lastFailure = t;
}
// Layer 3: ForgeVersion.forgeVersion (newer Forge)
try {
Object forgeVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.common.ForgeVersion", "forgeVersion");
int parsed = ForgeUtils.parseForgeVersion(forgeVersion);
if (parsed >= 0) {
return parsed;
}
lastFailure = new IllegalStateException("ForgeVersion.forgeVersion not supported: " + forgeVersion);
} catch (Throwable t) {
lastFailure = t;
}
// Layer 4: FMLLoader.versionInfo().forgeVersion() (newest Forge)
try {
Class<?> fmlLoader = ReflectUtils.loadClass(loader,
"net.minecraftforge.fml.loading.FMLLoader");
Object versionInfo = fmlLoader.getMethod("versionInfo").invoke(null);
Object forgeVersion = versionInfo.getClass().getMethod("forgeVersion").invoke(versionInfo);
int parsed = ForgeUtils.parseForgeVersion(forgeVersion);
if (parsed >= 0) {
return parsed;
}
lastFailure = new IllegalStateException("FMLLoader.versionInfo().forgeVersion() not supported: " + forgeVersion);
} catch (Throwable t) {
lastFailure = t;
}
// Layer 5: Fabric/NeoForge marker detection (reuse the loader detection result)
boolean isNeoForge = loaderType == LoaderType.NEOFORGE
|| (loaderType == LoaderType.UNKNOWN && ClassProbe.exists(loader,
"net.neoforged.fml.ModList",
"net.neoforged.fml.loading.FMLLoader"));
boolean isFabric = loaderType == LoaderType.FABRIC
|| (loaderType == LoaderType.UNKNOWN && ClassProbe.exists(loader,
"net.fabricmc.loader.api.FabricLoader"));
// Layer 6: Structural detection via obfuscated/mojmap class probing
int structuralVersion = detectByStructuralProbe(loader, isNeoForge, isFabric);
if (structuralVersion != 0) {
return structuralVersion;
}
// Layer 7: version.json detection for 26.x
int modernVersion = detectModernVersion(loader);
if (modernVersion != 0) {
return modernVersion;
}
if (lastFailure != null) {
System.out.println("[VersionDetector] Forge/Fabric version detection failed, falling back to structural probe");
}
return 0;
}
private static int detectByStructuralProbe(ClassLoader loader, boolean isNeoForge, boolean isFabric) {
Set<ClassLoader> loaders = candidateLoaders(loader);
boolean vanilla189 = probe(loaders, new MinecraftProbe("ave", "A", "S", "bew", "adm"));
boolean vanilla1122 = probe(loaders, new MinecraftProbe("bib", "z", "R", "bud", "amu"));
boolean vanilla1165 = probe(loaders, new MinecraftProbe("djz", "C", "F", "dwt", "dzm", "dzj", "brx"));
boolean vanilla1201 = probe(loaders, new MinecraftProbe("enn", "N", "F", "few", "fiy", "fiv", "cmm"));
boolean vanilla1206 = probe(loaders, new MinecraftProbe("ffh", "Q", "E", "fxx", "gcs", "gcp", "dca"));
boolean vanilla1211 = probe(loaders, new MinecraftProbe("fgo", "Q", "E", "fzf", "geb", "gdy", "dcw"));
boolean vanilla12111 = probe(loaders, new MinecraftProbe("gfj", "V", "A", "hif", "hnh", "hne", "dwo"));
boolean vanilla262 = isVanilla262Present(loaders);
boolean fabric262 = vanilla262 && isFabric;
boolean excludesModern = vanilla262 || fabric262;
boolean neoForge1201 = isNeoForge && probe(loaders, new MinecraftProbe(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer",
"net/minecraft/client/player/AbstractClientPlayer",
"net/minecraft/world/level/Level"))
&& !excludesModern && !vanilla12111;
boolean neoForge1211 = isNeoForge && probe(loaders, new MinecraftProbe(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer",
"net/minecraft/client/player/AbstractClientPlayer",
"net/minecraft/world/level/Level",
"net/minecraft/world/item/component/ItemContainerContents"))
&& !excludesModern && !vanilla12111;
boolean fabric12111 = isFabric && probe(loaders, new MinecraftProbe(
"net/minecraft/class_310", "method_1551", "field_1700",
"net/minecraft/class_638", "net/minecraft/class_746",
"net/minecraft/class_742", "net/minecraft/class_1937",
"com/mojang/blaze3d/buffers/GpuBuffer",
"com/mojang/blaze3d/systems/CommandEncoder"));
// MCP (deobfuscated) detection - only 1.8.9
boolean mcp = probe(loaders, new MinecraftProbe(
"net.minecraft.client.Minecraft", "getMinecraft", "theMinecraft",
"net.minecraft.client.entity.EntityPlayerSP",
"net.minecraft.client.gui.GuiIngame",
"net.minecraft.client.renderer.EntityRenderer",
"net.minecraft.client.network.NetHandlerPlayClient"));
int matchingVersions = (vanilla189 ? 1 : 0)
+ (vanilla1122 ? 1 : 0)
+ (vanilla1165 ? 1 : 0)
+ (vanilla1201 || neoForge1201 ? 1 : 0)
+ (vanilla1211 || neoForge1211 ? 1 : 0)
+ (vanilla1206 ? 1 : 0)
+ (vanilla12111 || fabric12111 ? 1 : 0)
+ (vanilla262 || fabric262 ? 1 : 0)
+ (mcp ? 1 : 0);
if (matchingVersions == 1) {
if (vanilla189) return 15;
if (vanilla1122) return 23;
if (vanilla1165) return 36;
if (vanilla1201 || neoForge1201) return 47;
if (vanilla1211 || neoForge1211) return 52;
if (vanilla1206) return 50;
if (vanilla12111 || fabric12111) return 61;
if (vanilla262) {
int modernProtocol = getModernProtocol(loaders);
return modernProtocol != 0 ? modernProtocol : 110;
}
if (mcp) return 15;
}
return 0;
}
private static boolean probe(Set<ClassLoader> loaders, MinecraftProbe minecraftProbe) {
for (ClassLoader loader : loaders) {
if (minecraftProbe.probe(loader)) {
return true;
}
}
return false;
}
private static boolean isVanilla262Present(Set<ClassLoader> loaders) {
return getModernProtocol(loaders) != 0;
}
private static int getModernProtocol(Set<ClassLoader> loaders) {
for (ClassLoader loader : loaders) {
Class<?> mcClass = resolveClass("net/minecraft/client/Minecraft", loader);
if (mcClass == null) continue;
ClassLoader definingLoader = mcClass.getClassLoader();
if (definingLoader == null) continue;
if (!new MinecraftProbe("net/minecraft/client/Minecraft", "getInstance", "instance").probe(loader)) {
continue;
}
Class<?> clientLevel = resolveClass("net/minecraft/client/multiplayer/ClientLevel", definingLoader);
Class<?> localPlayer = resolveClass("net/minecraft/client/player/LocalPlayer", definingLoader);
Class<?> abstractPlayer = resolveClass("net/minecraft/client/player/AbstractClientPlayer", definingLoader);
Class<?> level = resolveClass("net/minecraft/world/level/Level", definingLoader);
if (clientLevel == null || localPlayer == null
|| abstractPlayer == null || level == null
|| clientLevel.getSuperclass() != level
|| localPlayer.getSuperclass() != abstractPlayer) {
continue;
}
int protocol = MinecraftUtils.matchesVersionMetadata(mcClass);
if (protocol != 0) {
return protocol;
}
}
return 0;
}
private static int detectModernVersion(ClassLoader loader) {
Set<ClassLoader> loaders = candidateLoaders(loader);
return getModernProtocol(loaders);
}
private static Class<?> resolveClass(String internalName, ClassLoader loader) {
String binaryName = internalName.replace('/', '.');
try {
return Class.forName(binaryName, false, loader);
} catch (ClassNotFoundException | LinkageError | SecurityException e) {
return null;
}
}
private static Set<ClassLoader> candidateLoaders(ClassLoader primary) {
Set<ClassLoader> loaders = new LinkedHashSet<>();
if (primary != null) {
loaders.add(primary);
}
ClassLoader context = Thread.currentThread().getContextClassLoader();
if (context != null) {
loaders.add(context);
}
ClassLoader self = VersionDetector.class.getClassLoader();
if (self != null) {
loaders.add(self);
}
try {
ClassLoader system = ClassLoader.getSystemClassLoader();
if (system != null) {
loaders.add(system);
}
} catch (SecurityException ignored) {
}
return loaders;
return VersionSignatureRegistry.detect(loader, loaderType).getId();
}
private VersionDetector() {
@@ -0,0 +1,17 @@
package cn.xiaozhou233.orangex.runtime.version;
/**
* Reads an internal Minecraft version id from loader-provided metadata.
*
* <p>Sources are intentionally small and independent so new loader versions can
* be supported by adding one entry to {@link VersionIdSources}.</p>
*/
@FunctionalInterface
public interface VersionIdSource {
/**
* @return an internal version id, or {@link MinecraftVersion#UNKNOWN_ID}
* when this source has no answer
*/
int resolve(ClassLoader loader);
}
@@ -0,0 +1,99 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.utils.ReflectUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Ordered readers for Forge/NeoForge version metadata.
*
* <p>The first source that returns a known id wins. Every source is fail-safe:
* missing classes, fields or methods simply fall through to the next one.</p>
*/
public final class VersionIdSources {
private static final List<VersionIdSource> SOURCES =
Collections.unmodifiableList(Arrays.<VersionIdSource>asList(
VersionIdSources::legacyForgeMinorVersion,
VersionIdSources::fmlLoaderForgeVersion,
VersionIdSources::forgeVersionField,
VersionIdSources::fmlVersionInfoForgeVersion
));
public static int resolve(ClassLoader loader) {
for (VersionIdSource source : SOURCES) {
int versionId = source.resolve(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
}
return MinecraftVersion.UNKNOWN_ID;
}
/**
* Legacy Forge already exposes an internal-style version id.
*/
private static int legacyForgeMinorVersion(ClassLoader loader) {
try {
Object minorVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.common.ForgeVersion", "minorVersion");
if (minorVersion instanceof Number) {
return ((Number) minorVersion).intValue();
}
return MinecraftVersion.UNKNOWN_ID;
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
/**
* Modern Forge / NeoForge: {@code FMLLoader.forgeVersion}.
*/
private static int fmlLoaderForgeVersion(ClassLoader loader) {
try {
Object forgeVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.fml.loading.FMLLoader", "forgeVersion");
return parse(forgeVersion);
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
/**
* Newer Forge: {@code ForgeVersion.forgeVersion}.
*/
private static int forgeVersionField(ClassLoader loader) {
try {
Object forgeVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.common.ForgeVersion", "forgeVersion");
return parse(forgeVersion);
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
/**
* Newest Forge: {@code FMLLoader.versionInfo().forgeVersion()}.
*/
private static int fmlVersionInfoForgeVersion(ClassLoader loader) {
try {
Class<?> fmlLoader = ReflectUtils.loadClass(loader,
"net.minecraftforge.fml.loading.FMLLoader");
Object versionInfo = fmlLoader.getMethod("versionInfo").invoke(null);
Object forgeVersion = versionInfo.getClass().getMethod("forgeVersion").invoke(versionInfo);
return parse(forgeVersion);
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
private static int parse(Object forgeVersion) {
int parsed = ForgeVersionParser.parse(forgeVersion);
return parsed >= 0 ? parsed : MinecraftVersion.UNKNOWN_ID;
}
private VersionIdSources() {
}
}
@@ -0,0 +1,55 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftProbe;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftSignature;
/**
* One recognizable form of a Minecraft version.
*
* <p>A version can have several signatures (for example vanilla obfuscated
* names, Fabric intermediary names and NeoForge Mojang mappings). Matching is
* intentionally conservative: the registry only accepts a version when exactly
* one version matches, so overlapping class names cannot produce a guess.</p>
*/
public final class VersionSignature {
private final MinecraftVersion version;
private final LoaderType requiredLoader;
private final MinecraftProbe probe;
public VersionSignature(MinecraftVersion version,
LoaderType requiredLoader,
MinecraftSignature signature) {
this.version = version;
this.requiredLoader = requiredLoader;
this.probe = new MinecraftProbe(signature);
}
/**
* A signature that is valid for any mod loader.
*/
public static VersionSignature anyLoader(MinecraftVersion version,
MinecraftSignature signature) {
return new VersionSignature(version, null, signature);
}
/**
* A signature that only applies to one mod loader (for example NeoForge or
* Fabric mapping sets).
*/
public static VersionSignature forLoader(LoaderType loader,
MinecraftVersion version,
MinecraftSignature signature) {
return new VersionSignature(version, loader, signature);
}
public MinecraftVersion version() {
return version;
}
public boolean matches(ClassLoader loader, LoaderType loaderType) {
return (requiredLoader == null || requiredLoader == loaderType)
&& probe.matches(loader);
}
}
@@ -0,0 +1,117 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.classloader.CandidateClassLoaders;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftSignature;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static cn.xiaozhou233.orangex.runtime.loader.LoaderType.FABRIC;
import static cn.xiaozhou233.orangex.runtime.loader.LoaderType.NEOFORGE;
import static cn.xiaozhou233.orangex.runtime.version.MinecraftVersion.*;
/**
* Registry of structural version signatures.
*
* <p><strong>To add a Minecraft version:</strong> add the enum value to
* {@link MinecraftVersion} and one signature below. For a brand-new version
* family (for example a new version.json scheme), also update
* {@link ModernVersionDetector}.</p>
*
* <p>Matching is conservative: if two different versions match, the result is
* {@link MinecraftVersion#UNKNOWN}. This prevents overlapping mapping sets
* (such as adjacent NeoForge versions) from silently resolving to the wrong
* version.</p>
*/
public final class VersionSignatureRegistry {
private static final List<VersionSignature> SIGNATURES =
Collections.unmodifiableList(Arrays.<VersionSignature>asList(
// Vanilla, obfuscated client classes
VersionSignature.anyLoader(V1_8_9, obf("ave", "A", "S", "bew", "adm")),
VersionSignature.anyLoader(V1_12_2, obf("bib", "z", "R", "bud", "amu")),
VersionSignature.anyLoader(V1_16_5_ACTUAL, obf("djz", "C", "F", "dwt", "dzm", "dzj", "brx")),
VersionSignature.anyLoader(V1_20_1, obf("enn", "N", "F", "few", "fiy", "fiv", "cmm")),
VersionSignature.anyLoader(V1_20_6, obf("ffh", "Q", "E", "fxx", "gcs", "gcp", "dca")),
VersionSignature.anyLoader(V1_21_1, obf("fgo", "Q", "E", "fzf", "geb", "gdy", "dcw")),
VersionSignature.anyLoader(V1_21_11, obf("gfj", "V", "A", "hif", "hnh", "hne", "dwo")),
// MCP development environment (real 1.8.9 names, no mod loader)
VersionSignature.anyLoader(V1_8_9, mojang(
"net.minecraft.client.Minecraft", "getMinecraft", "theMinecraft",
"net.minecraft.client.entity.EntityPlayerSP",
"net.minecraft.client.gui.GuiIngame",
"net.minecraft.client.renderer.EntityRenderer",
"net.minecraft.client.network.NetHandlerPlayClient")),
// NeoForge uses Mojang mappings
VersionSignature.forLoader(NEOFORGE, V1_20_1, mojang(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer",
"net/minecraft/client/player/AbstractClientPlayer",
"net/minecraft/world/level/Level")),
VersionSignature.forLoader(NEOFORGE, V1_21_1, mojang(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer",
"net/minecraft/client/player/AbstractClientPlayer",
"net/minecraft/world/level/Level",
"net/minecraft/world/item/component/ItemContainerContents")),
// Fabric uses intermediary names
VersionSignature.forLoader(FABRIC, V1_21_11, intermediary(
"net/minecraft/class_310", "method_1551", "field_1700",
"net/minecraft/class_638", "net/minecraft/class_746",
"net/minecraft/class_742", "net/minecraft/class_1937",
"com/mojang/blaze3d/buffers/GpuBuffer",
"com/mojang/blaze3d/systems/CommandEncoder"))
));
public static MinecraftVersion detect(ClassLoader primaryLoader, LoaderType loaderType) {
MinecraftVersion match = null;
for (ClassLoader loader : CandidateClassLoaders.of(primaryLoader)) {
for (VersionSignature signature : SIGNATURES) {
if (!signature.matches(loader, loaderType)) {
continue;
}
if (match == null) {
match = signature.version();
} else if (match != signature.version()) {
// Two different versions match: refuse to guess.
return MinecraftVersion.UNKNOWN;
}
}
}
return match == null ? MinecraftVersion.UNKNOWN : match;
}
private static MinecraftSignature obf(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return MinecraftSignature.of(minecraftClass, instanceGetter, instanceField, anchors);
}
private static MinecraftSignature mojang(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return MinecraftSignature.of(minecraftClass, instanceGetter, instanceField, anchors);
}
private static MinecraftSignature intermediary(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return MinecraftSignature.of(minecraftClass, instanceGetter, instanceField, anchors);
}
private VersionSignatureRegistry() {
}
}
+15
View File
@@ -51,6 +51,21 @@ tasks.register('packageAll') {
}
subprojects {
plugins.withId('java') {
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
if (JavaVersion.current().isJava9Compatible()) {
// Fail fast if a post-Java-8 API is used.
options.release = 8
}
}
}
tasks.matching { it.name == 'shadowJar' }.configureEach {
mustRunAfter rootProject.tasks.named('cleanOut')
}
+157
View File
@@ -0,0 +1,157 @@
# 添加 Minecraft 版本支持
本文说明如何为 OrangeX 增加一个新的 Minecraft 版本。大多数版本只需要两步:注册内部版本 ID、注册结构签名。
## 检测流程
`cn.xiaozhou233.orangex.runtime` 按以下顺序检测版本,前一步成功就返回:
1. **加载器元数据** — `VersionIdSources` 读取 Forge/NeoForge 暴露的版本号。
2. **26.x 版本族** — `ModernVersionDetector` 读取客户端自带的 `version.json`。
3. **结构签名** — `VersionSignatureRegistry` 通过类名、单例 getter/field 和锚点类识别版本。
因此,普通版本只需要修改结构签名;只有新的版本族或新的加载器版本号规则才需要动前两步。
## 1. 添加内部版本 ID
在 `runtime/version/MinecraftVersion.java` 中添加枚举值:
```java
V1_21_10(60),
```
注意:
- 这里的数字是 **OrangeX 内部版本 ID**,不是 Minecraft 网络协议号。
- ID 一旦发布就不要再修改或复用,否则会破坏已有的版本判断和存档/配置兼容性。
- `ForgeVersionParser` 会用这个枚举校验 Forge 版本号,所以新版本 ID 也会自动生效。
## 2. 添加结构签名
在 `runtime/version/VersionSignatureRegistry.java` 的 `SIGNATURES` 列表中注册签名。
### 2.1 Vanilla(混淆类名)
```java
VersionSignature.anyLoader(V1_21_10, obf(
"obfuscatedMinecraftClass", "getterName", "instanceField",
"anchorClass1", "anchorClass2", "anchorClass3")),
```
### 2.2 MCP / 开发环境(真实类名)
```java
VersionSignature.anyLoader(V1_8_9, mojang(
"net.minecraft.client.Minecraft", "getMinecraft", "theMinecraft",
"net.minecraft.client.entity.EntityPlayerSP")),
```
### 2.3 Fabric(intermediary 类名)
```java
VersionSignature.forLoader(FABRIC, V1_21_11, intermediary(
"net/minecraft/class_310", "method_1551", "field_1700",
"net/minecraft/class_638", "net/minecraft/class_746")),
```
### 2.4 NeoForge(Mojang 映射)
```java
VersionSignature.forLoader(NEOFORGE, V1_21_1, mojang(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer")),
```
### 参数说明
| 参数 | 说明 |
|---|---|
| `minecraftClass` | Minecraft 主类。支持 `a.b.C` 和 `a/b/C` 两种写法。 |
| `instanceGetter` | 返回单例的静态方法名;没有就传 `null`。 |
| `instanceField` | 保存单例的静态字段名;没有就传 `null`。 |
| `anchors` | 锚点类。必须和 Minecraft 主类由**同一个 ClassLoader** 定义。 |
### 锚点选择规则
- 选目标版本**独有**的类,优先选该版本新增内容对应的类。
- 锚点必须存在于运行时,不能只存在于开发环境。
- 不要选父 ClassLoader 提供的类,否则 `MinecraftProbe` 会判定不匹配。
- 签名之间不能重叠:**如果两个不同版本同时匹配,检测结果会变成 `UNKNOWN`**,这是有意的防误判策略。
## 3. 新版本族(`version.json`)
如果新版本使用 `id == name` 的版本族命名(例如 26.x),并且没有稳定的混淆类名可探测:
1. 在 `MinecraftVersion` 中添加对应 ID。
2. 在 `utils/MinecraftUtils.java` 的 `readModernVersionId` 中识别新的版本族前缀:
```java
if (isFamily(id, "26.3")) {
return MinecraftVersion.V26_3.getId();
}
```
3. 如有需要,在 `ModernVersionDetector` 中补充该类版本族的类结构检查。
## 4. 新的 Forge 版本号规则
如果 Forge/NeoForge 提供了新的版本信息来源:
1. 在 `VersionIdSources` 中添加一个 `VersionIdSource`,并加入 `SOURCES` 列表。
2. 如果版本号字符串有新的映射规则,修改 `ForgeVersionParser.parse`。
来源方法必须保持 fail-safe:找不到类、字段或方法时返回 `MinecraftVersion.UNKNOWN_ID`,让后续来源继续尝试。
## 5. 验证
构建:
```bash
./gradlew :OrangeX:shadowJar
```
启动带 OrangeX 的客户端,检查日志:
```text
Loader Type: FORGE
Minecraft Version: V1_21_10 (version id 60)
```
也可以直接调用:
```java
RuntimeInfo info = RuntimeDetector.detect();
RuntimeDetector.debug(info);
```
排查建议:
| 现象 | 可能原因 |
|---|---|
| `UNKNOWN (version id 0)` | 签名没匹配上:锚点类名错误、类不存在,或 ClassLoader 不一致。 |
| 检测成旧版本 | 旧版本签名也匹配了目标版本:给新版本签名增加独有锚点,避免重叠。 |
| 检测成新版本但实际是旧版本 | 锚点在旧版本中已经存在:换一个真正新增的锚点。 |
| Fabric/NeoForge 下不匹配 | 缺少对应的 `forLoader(...)` 签名,或 `LoaderType` 判断错误。 |
建议分别验证 Vanilla、Fabric、NeoForge 三种环境,并确认检测结果唯一。
## 6. Checklist
- [ ] `MinecraftVersion` 中的内部 ID 唯一。
- [ ] 至少注册了一条结构签名。
- [ ] 锚点类与 Minecraft 主类由同一个 ClassLoader 定义。
- [ ] 目标版本与相邻版本的签名不会同时匹配。
- [ ] Fabric/NeoForge 使用了正确的 `forLoader(...)`。
- [ ] 新版本族已更新 `MinecraftUtils` / `ModernVersionDetector`。
- [ ] 已在真实客户端中验证 `Loader Type` 和 `Minecraft Version` 输出。
## 附:添加新的 Mod 加载器
版本检测之外,加载器识别也使用注册表:
1. 在 `loader/LoaderType.java` 中添加枚举值。
2. 在 `loader/LoaderDetector.java` 的 `PROBES` 中注册 `LoaderProbe`:
- 如果只需检查 marker 类,使用 `ClassPresenceLoaderProbe`。
- 如果需要结构判断,实现 `LoaderProbe`。
3. 如果新加载器需要专属版本签名,在 `VersionSignatureRegistry` 中使用 `VersionSignature.forLoader(...)`。