Compare commits

..
20 Commits
Author SHA1 Message Date
LexManos b6e4191997 Add protection against large network channel lists 2026-10-14 19:37:35 -07:00
LexManos d01b4128b0 Fix legacy object holders not being fired in the registry specific codepath
Better optimize the scanning for object holders by unrolling streams.
2026-10-13 10:35:28 -07:00
BonsUnleashedandLexManos 6162ec30bd Store object holder handlers per registry name (#10899)
Co-authored-by: LexManos <[email protected]>
2026-10-12 16:19:07 -07:00
LexManos 96ffdf9ee5 Update SRGUtils and Fix new eclipse compiler issue 2026-10-12 16:19:05 -07:00
Paint_NinjaandMartijn van den Brand 23856b57a9 Fix IForgeBlockStateModel.getModelData not being called correct for #getParticleIcon (#10818) (#10874)
Co-authored-by: Martijn van den Brand <[email protected]>
2026-08-15 00:41:45 -07:00
Meme Man 855bafc581 Update equality check for RegistryObject to include RegistryObject#key. (#10867) 2026-08-04 19:09:43 +01:00
Matt a42ea9bc2c Add DeltaTracker (partialTick) context to PassDefinitions (#10831) (#10851) 2026-07-21 16:09:23 -07:00
Matt a6eea5a004 Toml parsing errors are now visible in the latest log (#10839) 2026-07-09 12:34:25 -07:00
Matt 451c3a1f0a Add support for multiple access transformer configs. 2026-03-23 12:14:09 -07:00
Jonathing a6f68087b4 Migrate the MDK to ForgeGradle 7
Backport of d29524b to 1.21.8
2026-03-18 22:49:16 +00:00
Paint_Ninja ae3985f882 Bump ASM to 9.9.1 and EventBus to 7.0.1 2026-03-17 20:05:22 +00:00
Paint_Ninja 0f6951b560 Skip processing vanilla classes in RuntimeDistCleaner when running on a client
Backport of #10682 to 1.21.8
2026-03-17 19:55:18 +00:00
LexManos 19f6b6c294 Update SecureModules to address ZipPath bug with brackets. Closes #10755 2026-01-20 18:23:14 -08:00
LexManos 9441128b1a Fix Entity patch line numbers 2026-01-15 12:42:59 -08:00
MattandLexManos b9d842a484 Optimize memory allocation for checking entity fluid collisions. Backport of #10745 (#10749)
Co-authored-by: LexManos <[email protected]>
2026-01-15 10:34:47 -08:00
LexManos eb884f4f61 Mark applyServerBinpatches as a dependency of BundleList. Fixes: #10729 2025-12-04 08:52:37 -08:00
LexManos 74d2f1c7c3 Migrate to Github Actions 2025-12-02 14:17:14 -08:00
cech12 e75f0b67fe Fixes shearing leads for custom shears (interacting with entity & leash knot) (#10706) 2025-11-19 17:39:39 -08:00
Matt fae5c92daf Fix ItemStack context in RenderTooltipEvent.Pre (#10655) (#10658) 2025-11-14 07:08:10 -08:00
Paint_Ninja 60110cd916 Fix implicit Bus.BOTH not working in @EventBusSubscriber, add additional validation in strict mode, partial backport of #10676 2025-10-05 15:15:25 +01:00
2138 changed files with 35076 additions and 24415 deletions

No files matched your search

+1 -1
View File
@@ -10,4 +10,4 @@ assignees: ''
<!-- Please note, feature requests that are submitted as GitHub issues here are rarely implemented. --> <!-- Please note, feature requests that are submitted as GitHub issues here are rarely implemented. -->
<!-- If you'd like to see something in Forge, you should be ready to implement it as a PR. --> <!-- If you'd like to see something in Forge, you should be ready to implement it as a PR. -->
<!-- If you're not sure, open a Draft PR or discuss it in the Discord server. --> <!-- If you're not sure, open a Draft PR or discuss it in the Discord server. -->
<!-- Discord: https://discord..minecraftforge.net/ --> <!-- Discord: https://discord.gg/UvedJ9m -->
-1
View File
@@ -11,7 +11,6 @@ assignees: ''
<!-- For support with crashes and issues, please create a post on the forum instead: --> <!-- For support with crashes and issues, please create a post on the forum instead: -->
<!-- https://www.minecraftforge.net/forum/forum/18-support-bug-reports/ --> <!-- https://www.minecraftforge.net/forum/forum/18-support-bug-reports/ -->
<!-- You can also use the discord for support, https://discord.minecraftforge.net/ -->
**Minecraft Version:** {Minecraft version} **Minecraft Version:** {Minecraft version}
+1 -1
View File
@@ -2,7 +2,7 @@ name: Publish
on: on:
push: push:
branches: [ '26.2' ] branches: [ '1.21.8' ]
permissions: permissions:
contents: read contents: read
-1
View File
@@ -46,4 +46,3 @@ src/*/generated/**/.cache/
/*/.gitignore /*/.gitignore
/*/.factorypath /*/.factorypath
/*/.apt_generated/ /*/.apt_generated/
/fmlcore/logs/
+4 -7
View File
@@ -7,10 +7,10 @@ plugins {
id 'net.minecraftforge.gradleutils' version '[2.6.4,2.7)' id 'net.minecraftforge.gradleutils' version '[2.6.4,2.7)'
id 'eclipse' id 'eclipse'
id 'de.undercouch.download' version '5.4.0' id 'de.undercouch.download' version '5.4.0'
id 'net.minecraftforge.gradle.patcher' version '[6.0.51,6.2)' apply false id 'net.minecraftforge.gradle.patcher' version '[6.0.54,6.2)' apply false
id 'net.minecraftforge.gradle.mcp' version '[6.0.51,6.2)' apply false id 'net.minecraftforge.gradle.mcp' version '[6.0.45,6.2)' apply false
id 'net.minecraftforge.gradlejarsigner' version '1.0.4' id 'net.minecraftforge.gradlejarsigner' version '1.0.4'
//id 'org.barfuin.gradle.taskinfo' version '3.0.1' id 'org.barfuin.gradle.taskinfo' version '2.1.0'
} }
Util.init() //Init all our extension methods! Util.init() //Init all our extension methods!
@@ -21,7 +21,7 @@ ext {
} }
changelog { changelog {
from '65.0' from '47.999'
} }
tasks.register('setup') { tasks.register('setup') {
@@ -41,9 +41,6 @@ project(':mcp') {
config MC_VERSION + '-' + MCP_VERSION config MC_VERSION + '-' + MCP_VERSION
pipeline = 'joined' pipeline = 'joined'
} }
repositories {
mavenLocal()
}
} }
if (System.env.TEAMCITY_VERSION) { if (System.env.TEAMCITY_VERSION) {
+1 -2
View File
@@ -6,8 +6,7 @@ repositories {
dependencies { dependencies {
implementation 'org.ow2.asm:asm:9.9.1' implementation 'org.ow2.asm:asm:9.9.1'
implementation 'org.ow2.asm:asm-tree:9.9.1' implementation 'org.ow2.asm:asm-tree:9.9.1'
implementation 'net.minecraftforge:srgutils:0.6.2' implementation 'net.minecraftforge:srgutils:0.6.8'
implementation 'net.minecraftforge:JarJarMetadata:0.3.27'
implementation 'commons-io:commons-io:2.13.0' implementation 'commons-io:commons-io:2.13.0'
implementation 'com.google.code.gson:gson:2.10.1' implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.eclipse.jgit:org.eclipse.jgit:6.7.0.202309050840-r' implementation 'org.eclipse.jgit:org.eclipse.jgit:6.7.0.202309050840-r'
@@ -10,11 +10,13 @@ import java.util.zip.ZipFile
abstract class BundleList extends DefaultTask { abstract class BundleList extends DefaultTask {
@InputFiles abstract ConfigurableFileCollection getConfig() @InputFiles abstract ConfigurableFileCollection getConfig()
@InputFiles abstract ConfigurableFileCollection getConfigExtra()
@InputFile abstract RegularFileProperty getServerBundle() @InputFile abstract RegularFileProperty getServerBundle()
@OutputFile abstract RegularFileProperty getOutput() @OutputFile abstract RegularFileProperty getOutput()
BundleList() { BundleList() {
config.setFrom(project.configurations.installer) config.setFrom(project.configurations.installer)
configExtra.setFrom(project.configurations.installerextra)
output.convention(project.layout.buildDirectory.file("$name/output.list")) output.convention(project.layout.buildDirectory.file("$name/output.list"))
configure { configure {
dependsOn(project.tasks.universalJar) dependsOn(project.tasks.universalJar)
@@ -34,6 +36,13 @@ abstract class BundleList extends DefaultTask {
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path") entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
} }
resolved = project.configurations.installerextra.resolvedConfiguration.resolvedArtifacts
for (def dep : resolved) {
def info = Util.getMavenInfoFromDep(dep)
//println("$dep.file.sha1\t$info.name\t$info.path")
entries.put("$info.art.group:$info.art.name", "$dep.file.sha256\t$info.name\t$info.path")
}
var packed = (AbstractArchiveTask) project.tasks.universalJar var packed = (AbstractArchiveTask) project.tasks.universalJar
var info = Util.getMavenInfoFromTask(packed) var info = Util.getMavenInfoFromTask(packed)
def file = packed.archiveFile.get().asFile def file = packed.archiveFile.get().asFile
@@ -53,10 +62,6 @@ abstract class BundleList extends DefaultTask {
def (group, name, other) = artifact.split(':', 3) def (group, name, other) = artifact.split(':', 3)
//println("Group: $group Name: $name") //println("Group: $group Name: $name")
def key = "$group:$name" def key = "$group:$name"
if (other.indexOf(':') != -1){
key += ':' + other.split(':', 2)[1]
//println("\tKey: $key")
}
if (!entries.containsKey(key)) if (!entries.containsKey(key))
entries.put(key, line) entries.put(key, line)
} }
@@ -1,415 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.forge.tasks;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraftforge.jarjar.metadata.ContainedJarIdentifier;
import net.minecraftforge.jarjar.metadata.ContainedJarMetadata;
import net.minecraftforge.jarjar.metadata.ContainedVersion;
import net.minecraftforge.jarjar.metadata.Metadata;
import net.minecraftforge.jarjar.metadata.MetadataIOHandler;
import net.minecraftforge.jarjar.metadata.json.ArtifactVersionSerializer;
import net.minecraftforge.jarjar.metadata.json.ContainedJarIdentifierSerializer;
import net.minecraftforge.jarjar.metadata.json.ContainedJarMetadataSerializer;
import net.minecraftforge.jarjar.metadata.json.ContainedVersionSerializer;
import net.minecraftforge.jarjar.metadata.json.MetadataSerializer;
import net.minecraftforge.jarjar.metadata.json.VersionRangeSerializer;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ExternalModuleDependency;
import org.gradle.api.artifacts.FileCollectionDependency;
import org.gradle.api.artifacts.MinimalExternalModuleDependency;
import org.gradle.api.artifacts.ModuleDependency;
import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.SetProperty;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.zip.ZipFile;
// TODO SUPER SUPER SUPER UGLY, CLEAN UP IN FORGEDEV 7
@Deprecated(forRemoval = true) // Will be moved to JarJar plugin in ForgeDev 7
public abstract class JarJarMetadataOptions extends DefaultTask {
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(VersionRange.class, new VersionRangeSerializer())
.registerTypeAdapter(ArtifactVersion.class, new ArtifactVersionSerializer())
.registerTypeAdapter(DefaultArtifactVersion.class, new ArtifactVersionSerializer())
.registerTypeAdapter(ContainedJarIdentifier.class, new ContainedJarIdentifierSerializer())
.registerTypeAdapter(ContainedJarMetadata.class, new ContainedJarMetadataSerializer())
.registerTypeAdapter(ContainedVersion.class, new ContainedVersionSerializer())
.registerTypeAdapter(Metadata.class, new MetadataSerializer())
.setPrettyPrinting()
.create();
protected abstract @Input SetProperty<ResolvedDependencyInfoImpl> getResolvedDependencies();
protected abstract @OutputFile RegularFileProperty getMetadataFile();
protected abstract @Inject ProjectLayout getLayout();
// NOTE: I'm not adding a non-provider version. please just use the version catalog entries for now.
public void add(Provider<MinimalExternalModuleDependency> dependency, Action<? super ResolvedDependencyInfo> action) {
this.getResolvedDependencies().add(dependency.map(d -> {
var ret = ResolvedDependencyInfoImpl.from(this.getProject().getConfigurations(), d);
action.execute(ret);
return ret;
}));
}
@Inject
public JarJarMetadataOptions() {
this.getMetadataFile().convention(this.getLayout().getBuildDirectory().file(this.getName() + "/options.json"));
}
@TaskAction
protected void exec() {
record ForgeLocaterOptions(String resource, String layer, String id, List<ContainedJarMetadata> deps, ContainedJarMetadata meta, boolean nested) { }
var resolved = this.getResolvedDependencies().get();
var jars = new ArrayList<ForgeLocaterOptions>(resolved.size());
for (var dependency : resolved) {
var deps = new ArrayList<ContainedJarMetadata>();
try (var zip = new ZipFile(dependency.artifact)) {
var entry = zip.getEntry("META-INF/jarjar/metadata.json");
if (entry != null) {
try (var stream = zip.getInputStream(entry)) {
var meta = MetadataIOHandler.fromStream(stream).orElse(null);
if (meta == null)
throw new IllegalStateException("Corrupt metadata.json in " + dependency.artifact.getAbsolutePath());
for (var dep : meta.jars())
deps.add(new ContainedJarMetadata(dep.identifier(), dep.version(), "", dep.isObfuscated()));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
jars.add(new ForgeLocaterOptions(
dependency.resource,
dependency.layer,
dependency.identifier,
deps,
new ContainedJarMetadata(
new ContainedJarIdentifier(validateGroup(dependency), dependency.module.getName()),
new ContainedVersion(null, parseVersion(dependency)),
Objects.requireNonNull(dependency.path, "Dependency path is unspecified: " + dependency.asString),
false
),
dependency.nested
));
}
try {
record Meta(List<ForgeLocaterOptions> options){}
Files.writeString(
this.getMetadataFile().getAsFile().get().toPath(),
GSON.toJson(new Meta(jars), Meta.class)
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String validateGroup(ResolvedDependencyInfoImpl dependency) {
try {
return Objects.requireNonNull(dependency.module.getGroup());
} catch (NullPointerException e) {
throw new IllegalArgumentException("Module dependency has no group: " + dependency.asString, e);
}
}
private ArtifactVersion parseVersion(ResolvedDependencyInfoImpl resolved) {
try {
return VersionRange.createFromVersionSpec(Objects.requireNonNull(resolved.version)).getRecommendedVersion();
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException("Version is invalid for: " + resolved.asString, e);
} catch (NullPointerException e) {
throw new IllegalArgumentException("Version is unspecified for: " + resolved.asString, e);
}
}
private VersionRange parseVersionRange(ResolvedDependencyInfoImpl dependency) {
if (dependency.hasManuallySpecifiedRange) {
try {
return VersionRange.createFromVersionSpec(dependency.versionRange);
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException("Version is invalid for: " + dependency.asString, e);
}
} else {
try {
return VersionRange.createFromVersionSpec("[%s,)".formatted(Objects.requireNonNull(dependency.versionRange)));
} catch (InvalidVersionSpecificationException e) {
throw new IllegalArgumentException("Version range is invalid for: " + dependency.asString, e);
} catch (NullPointerException e) {
throw new IllegalArgumentException("Version is unspecified for: " + dependency.asString, e);
}
}
}
public interface ResolvedDependencyInfo {
void containedJarMetadata(Action<? super ContainedJarMetadataInfo> action);
void setResource(String resource);
void setLayer(String layer);
void setId(String identifier);
void setNested(boolean nested);
interface ContainedJarMetadataInfo {
void setGroup(String group);
void setName(String name);
void setPath(String version);
}
}
static final class ResolvedDependencyInfoImpl implements ResolvedDependencyInfo, ResolvedDependencyInfo.ContainedJarMetadataInfo, Serializable {
private static final @Serial long serialVersionUID = -7577318115877822993L;
final MinimalModuleVersionIdentifier module;
final String version;
String versionRange;
boolean hasManuallySpecifiedRange;
boolean nested;
final File artifact;
String path;
String resource;
String layer;
String identifier;
final String asString;
public ResolvedDependencyInfoImpl(MinimalModuleVersionIdentifier module, String version, File artifact, String asString) {
this.module = module;
this.version = version;
this.artifact = artifact;
this.asString = asString;
}
@Override
public void containedJarMetadata(Action<? super ContainedJarMetadataInfo> action) {
action.execute(this);
}
@Override
public void setGroup(String group) {
this.module.group = group;
}
@Override
public void setName(String name) {
this.module.name = name;
}
@Override
public void setPath(String path) {
this.path = path;
}
@Override
public void setResource(String resource) {
this.resource = resource;
}
@Override
public void setLayer(String layer) {
this.layer = layer;
}
@Override
public void setId(String identifier) {
this.identifier = identifier;
}
@Override
public void setNested(boolean nested) {
this.nested = nested;
}
static Set<File> getFiles(Set<ResolvedDependencyInfoImpl> resolvedDependencies) {
var ret = new HashSet<File>(resolvedDependencies.size());
for (var dependency : resolvedDependencies) {
ret.add(dependency.artifact);
}
return ret;
}
static ResolvedDependencyInfoImpl from(ConfigurationContainer configurations, Dependency dependency) {
var group = dependency.getGroup();
var name = dependency.getName();
var version = dependency.getVersion();
if (dependency instanceof FileCollectionDependency filesDependency) {
File artifact;
try {
artifact = filesDependency.getFiles().getSingleFile();
} catch (IllegalStateException e) {
// TODO fileCollectionDependencyIsNotSingleFile
throw e;
}
return new ResolvedDependencyInfoImpl(
new MinimalModuleVersionIdentifier(group, name, version),
version,
artifact,
filesDependency.toString()
);
} else if (dependency instanceof ModuleDependency moduleDependency) {
moduleDependency = moduleDependency.copy();
if (moduleDependency instanceof ExternalModuleDependency externalModuleDependency) {
externalModuleDependency.version(v -> v.strictly(version.toString()));
}
var detachedConfiguration = configurations.detachedConfiguration(moduleDependency);
detachedConfiguration.setTransitive(false);
ResolvedDependencyInfoImpl ret = null;
for (var artifact : detachedConfiguration.getResolvedConfiguration().getFirstLevelModuleDependencies().iterator().next().getModuleArtifacts()) {
var fileName = getFileName(artifact);
if (!fileName.endsWith(".jar"))
continue;
if (ret != null)
throw new IllegalArgumentException("Module dependency has too many Jar artifacts: " + moduleDependency);
ret = new ResolvedDependencyInfoImpl(
new MinimalModuleVersionIdentifier(group, name, artifact.getModuleVersion().getId().getVersion()),
version,
artifact.getFile(),
moduleDependency.toString()
);
}
if (ret == null)
throw new IllegalArgumentException("Module dependency has no Jar artifacts: " + moduleDependency);
return ret;
} else {
throw new IllegalArgumentException("Unsupported dependency type: " + dependency.getClass().getName() + " -- " + dependency);
}
}
private static String getFileName(ResolvedArtifact artifact) {
try {
return InvokerHelper.getProperty(artifact.getId(), "fileName").toString();
} catch (Throwable e) {
// NOTE: Why not just use this to begin with?
// ComponentArtifactIdentifier can have a getFileName() method, which doesn't necessarily resolve the file itself.
// This allows us to get the name of the file to be used without asking Gradle to download the file.
// So, if a file is not a JAR file, we can check the name without actually downloading it.
return artifact.getFile().getName();
}
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (ResolvedDependencyInfoImpl) obj;
return Objects.equals(this.module, that.module) &&
Objects.equals(this.version, that.version) &&
Objects.equals(this.versionRange, that.versionRange) &&
Objects.equals(this.artifact, that.artifact);
}
@Override
public int hashCode() {
return Objects.hash(module, version, versionRange, artifact);
}
@Override
public String toString() {
return "ResolvedDependencyInfo[" +
"module=" + module + ", " +
"fixedVersion=" + version + ", " +
"versionRange=" + versionRange + ", " +
"artifact=" + artifact + ']';
}
static final class MinimalModuleVersionIdentifier implements ModuleIdentifier, ModuleVersionIdentifier {
private static final @Serial long serialVersionUID = -955346236759069739L;
private String group;
private String name;
private final String version;
@Inject
public MinimalModuleVersionIdentifier(String group, String name, String version) {
this.group = group;
this.name = name;
this.version = version;
}
@Override
public ModuleIdentifier getModule() {
return this;
}
@Override
public String getGroup() {
return this.group;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getVersion() {
return this.version;
}
@Override
public boolean equals(Object obj) {
return this == obj || obj instanceof MinimalModuleVersionIdentifier o
&& Objects.equals(this.group, o.group)
&& Objects.equals(this.name, o.name)
&& Objects.equals(this.version, o.version);
}
@Override
public int hashCode() {
return Objects.hash(group, name, version);
}
@Override
public String toString() {
return "MinimalModuleVersionIdentifier[" +
"group=" + group + ", " +
"name=" + name + ", " +
"version=" + version + ']';
}
}
}
}
@@ -24,6 +24,7 @@ abstract class LauncherJson extends DefaultTask {
dependsOn(project.tasks.universalJar) dependsOn(project.tasks.universalJar)
input.from(project.tasks.universalJar.archiveFile) input.from(project.tasks.universalJar.archiveFile)
input.from(project.configurations.installer) input.from(project.configurations.installer)
input.from(project.configurations.installerextra)
configure { configure {
def mc = project.rootProject.ext.MC_VERSION def mc = project.rootProject.ext.MC_VERSION
def forge = project.rootProject.ext.FORGE_VERSION def forge = project.rootProject.ext.FORGE_VERSION
@@ -88,6 +89,7 @@ abstract class LauncherJson extends DefaultTask {
] ]
]) ])
json.libraries.addAll(getArtifacts(project.configurations.installerextra).values())
json.libraries.addAll(getArtifacts(project.configurations.installer).values()) json.libraries.addAll(getArtifacts(project.configurations.installer).values())
Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString()) Files.writeString(output.get().asFile.toPath(), new JsonBuilder(json).toPrettyString())
} }
@@ -17,15 +17,17 @@ abstract class CheckATs extends CheckTask {
@InputFile abstract RegularFileProperty getInheritance() @InputFile abstract RegularFileProperty getInheritance()
@InputFiles abstract ConfigurableFileCollection getAts() @InputFiles abstract ConfigurableFileCollection getAts()
@InputFile @Optional abstract RegularFileProperty getMappings()
@Override @Override
void check(Reporter reporter, boolean fix) { void check(Reporter reporter, boolean fix) {
final IMappingFile mappings = mappings.map { RegularFile it -> IMappingFile.load(it.asFile) }.getOrNull()
final inheritance = InheritanceData.parse(this.inheritance.get().asFile) final inheritance = InheritanceData.parse(this.inheritance.get().asFile)
ats.each { ats.each {
final lines = process(it, reporter, inheritance) final lines = process(it, reporter, inheritance)
if (fix) { if (fix) {
it.text = joinBack(lines, inheritance).join('\n') it.text = joinBack(lines, inheritance, mappings).join('\n')
} }
} }
} }
@@ -168,18 +170,45 @@ abstract class CheckATs extends CheckTask {
return lines return lines
} }
private static List<String> joinBack(TreeMap<String, ATParser.Entry> lines, Map<String, InheritanceData> inheritance) { private static List<String> joinBack(TreeMap<String, ATParser.Entry> lines, Map<String, InheritanceData> inheritance, IMappingFile mappings) {
final data = [] as List<String> final data = [] as List<String>
final remapComment = { ATParser.Entry entry ->
if (!mappings || !entry || !entry.desc) return null
final comment = entry.comment?.substring(1)?.trim()
final jsonCls = inheritance.get(entry.cls.replaceAll('\\.', '/'))
final mappingsClass = mappings?.getClass(jsonCls.name)
if (mappingsClass === null) return entry.comment
final idx = entry.desc.indexOf('(')
String mappedName = idx == -1
? mappingsClass.remapField(entry.desc)
: mappingsClass.remapMethod(entry.desc.substring(0, idx), entry.desc.substring(idx))
if (!mappedName) return entry.comment
if (mappedName == '<init>')
mappedName = 'constructor'
if (comment?.startsWith(mappedName))
return '# ' + comment
if (comment && comment.indexOf(' ') !== -1) {
def split = comment.split(' - ').toList()
if (split[0].indexOf(' ') !== -1)
// The first string is more than one word, so append before it
return "# ${mappedName} - ${comment}"
split.remove(0)
return "# ${mappedName} - ${String.join(' - ', split)}"
}
return '# ' + mappedName
}
lines.each { key, value -> lines.each { key, value ->
if (!value.group) { if (!value.group) {
def comment = null //value.comment def comment = remapComment.call(value)
data.add(value.modifier + ' ' + key + (comment ? ' ' + comment : '')) data.add(value.modifier + ' ' + key + (comment ? ' ' + comment : ''))
} else { } else {
data.add(('#group ' + value.modifier + ' ' + key + ' ' + (value.comment ?: '')).trim()) data.add(('#group ' + value.modifier + ' ' + key + ' ' + (value.comment ?: '')).trim())
value.children.each { value.children.each {
final line = value.modifier + ' ' + it final line = value.modifier + ' ' + it
final entry = ATParser.parseEntry(line) final entry = ATParser.parseEntry(line)
final comment = null //entry.comment final comment = remapComment(entry)
data.add(line + (comment ? ' ' + comment : '')) data.add(line + (comment ? ' ' + comment : ''))
} }
data.add('#endgroup') data.add('#endgroup')
@@ -260,7 +289,6 @@ class ATParser {
final String comment = idx === -1 ? null : line.substring(idx) final String comment = idx === -1 ? null : line.substring(idx)
if (idx !== -1) line = line.substring(0, idx - 1) if (idx !== -1) line = line.substring(0, idx - 1)
final data = (line.trim() + ' ').split(' ', -1) final data = (line.trim() + ' ').split(' ', -1)
data[1] = data[1].replaceAll('/', '.') // Convert to Source names, internal names are fine by spec, but not supported by old AST based AT implementations.
new Entry(data[0], data[1], data[2], comment) new Entry(data[0], data[1], data[2], comment)
} }
+146 -56
View File
@@ -88,10 +88,10 @@ ext {
} }
final String MAVEN_PATH = ext.MAVEN_PATH final String MAVEN_PATH = ext.MAVEN_PATH
final String BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.3.0:fatjar' final String BINPATCH_TOOL = 'net.minecraftforge:binarypatcher:1.2.0:fatjar'
final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.5' final String INSTALLER_TOOLS = 'net.minecraftforge:installertools:1.4.3'
final String FART = 'net.minecraftforge:ForgeAutoRenamingTool:1.0.6' final String FART = 'net.minecraftforge:ForgeAutoRenamingTool:1.0.6'
final String S2S_TOOL = 'net.minecraftforge:Srg2Source:8.2.0:fatjar' final String S2S_TOOL = 'net.minecraftforge:Srg2Source:8.1.1:fatjar'
configurations { configurations {
// Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it. // Don't pull all libraries, if we're missing something, add it to the installer list so the installer knows to download it.
@@ -100,6 +100,10 @@ configurations {
extendsFrom(bootstrap) extendsFrom(bootstrap)
transitive = false transitive = false
} }
installerextra {
extendsFrom(bootstrap)
transitive = false
}
api.extendsFrom(installer) api.extendsFrom(installer)
} }
@@ -108,7 +112,6 @@ dependencies {
// And this is only needed because custom file systems are REQUIRED to be on the boot classloader. // And this is only needed because custom file systems are REQUIRED to be on the boot classloader.
// This has ASM/BootStrap/Unsafe all because I haven't gotten around to moving UnionFileSystem out to its own project. // This has ASM/BootStrap/Unsafe all because I haven't gotten around to moving UnionFileSystem out to its own project.
bootstrap(libs.jarjar.fs) // JarInJar file system bootstrap(libs.jarjar.fs) // JarInJar file system
bootstrap(libs.roimfs) // JarInJar File System - FileSystems need to be on boot loader.
bootstrap(libs.bundles.jimfs) // In memory file system used for ForgeDev launches bootstrap(libs.bundles.jimfs) // In memory file system used for ForgeDev launches
bootstrap(libs.securemodules) // Has Union file system in it bootstrap(libs.securemodules) // Has Union file system in it
bootstrap(libs.unsafe) // Needed by securemodules bootstrap(libs.unsafe) // Needed by securemodules
@@ -122,16 +125,15 @@ dependencies {
installer(libs.eventbus) installer(libs.eventbus)
installer(libs.jspecify) // Dep of EventBus installer(libs.jspecify) // Dep of EventBus
installer(libs.forgespi) installer(libs.forgespi)
installer(libs.coremods.api) installer(libs.coremods)
installer(libs.nashorn) // Dep of Coremods
installer(libs.modlauncher) installer(libs.modlauncher)
installer(libs.mergetool.api) installer(libs.mergetool.api)
installer(libs.bundles.night.config) installer(libs.bundles.night.config)
installer(libs.maven.artifact) installer(libs.maven.artifact)
installer(libs.bundles.terminalconsoleappender) installer(libs.bundles.terminalconsoleappender)
installer(libs.mixin) installer(libs.mixin)
installer(libs.mixinextras.forge)
installer(libs.bundles.jarjar) installer(libs.bundles.jarjar)
installer(libs.roimfs)
installer(project(':fmlcore')) installer(project(':fmlcore'))
installer(project(':fmlloader')) installer(project(':fmlloader'))
@@ -141,6 +143,8 @@ dependencies {
installer(project(':mclanguage')) installer(project(':mclanguage'))
installer(project(':forge-transformers')) installer(project(':forge-transformers'))
installerextra("${MCP_ARTIFACT.group}:${MCP_ARTIFACT.name}:${MCP_ARTIFACT.version}:srg2off")
runtimeOnly(libs.bootstrap) runtimeOnly(libs.bootstrap)
runtimeOnly(libs.bootstrap.dev) runtimeOnly(libs.bootstrap.dev)
@@ -150,17 +154,6 @@ dependencies {
tasks.named('extractRangeMap').configure { tasks.named('extractRangeMap').configure {
tool = S2S_TOOL tool = S2S_TOOL
} }
tasks.named('applyRangeMap').configure {
tool = S2S_TOOL
}
tasks.named('applyRangeMapBase').configure {
tool = S2S_TOOL
}
// Disable all tests, we have GameTests not JUnit tests
test {
exclude '**/*'
}
patcher { patcher {
excs.from file("$rootDir/src/main/resources/forge.exc") excs.from file("$rootDir/src/main/resources/forge.exc")
@@ -216,6 +209,7 @@ patcher {
args '--launchTarget', 'forge_dev_data', args '--launchTarget', 'forge_dev_data',
'--mod', 'forge', '--mod', 'forge',
'--all', '--all',
'--validate',
'--output', rootProject.file('src/main/generated/'), '--output', rootProject.file('src/main/generated/'),
'--existing', sourceSets.main.resources.srcDirs[0], '--existing', sourceSets.main.resources.srcDirs[0],
'--assetsDir', downloadAssets.output, '--assetsDir', downloadAssets.output,
@@ -227,6 +221,7 @@ patcher {
args '--launchTarget', 'forge_dev_data', args '--launchTarget', 'forge_dev_data',
'--mod', '.+', '--mod', '.+',
'--all', '--all',
'--validate',
'--output', rootProject.file('src/test/generated/'), '--output', rootProject.file('src/test/generated/'),
'--existing', sourceSets.main.resources.srcDirs[0], '--existing', sourceSets.main.resources.srcDirs[0],
'--existing', sourceSets.test.resources.srcDirs[0], '--existing', sourceSets.test.resources.srcDirs[0],
@@ -269,6 +264,21 @@ afterEvaluate {
userdevJar { userdevJar {
onlyIf = { t -> true } onlyIf = { t -> true }
} }
def patches = project.file('build/genPatchesForUserdev/output/')
patches.mkdirs()
def genPatchesForUserdev = tasks.register('genPatchesForUserdev', GeneratePatches){
base = project(':mcp').setupMCP.output
modified = applyRangeMapBase.output
originalPrefix = genPatches.originalPrefix
modifiedPrefix = genPatches.modifiedPrefix
output = patches
autoHeader true
lineEnding = '\n'
}
bakePatches {
dependsOn = []
input = genPatchesForUserdev.get().output
}
} }
} }
@@ -288,11 +298,6 @@ tasks.userdevConfig.configure {
libraries.add(dep) libraries.add(dep)
} }
// TODO [ForgeDev][UserDev] Split API/Runtime elements in userdev config
// so we don't gotta keep making exceptions for MixinExtras
addCompileDependency(libs.mixinextras.common)
addAnnotationProcessorDependency(libs.mixinextras.common)
inject = '' // We don't have a userdev sourceset anymore. Empty as a gradle workaround... inject = '' // We don't have a userdev sourceset anymore. Empty as a gradle workaround...
runs { runs {
client { client {
@@ -335,7 +340,7 @@ for (def run in patcher.runs + tasks.userdevConfig.runs) {
if (run.parents) continue // We already added this to the parent run config if (run.parents) continue // We already added this to the parent run config
//run.property 'bsl.debug', 'true' //run.property 'bsl.debug', 'true'
run.args '--gameDir', '.' run.args '--gameDir', '.'
run.jvmArgs '-Djava.net.preferIPv6Addresses=system', '-XX:+UseCompactObjectHeaders' run.jvmArgs '-Djava.net.preferIPv6Addresses=system'
run.client run.name.contains('client') run.client run.name.contains('client')
run.main 'net.minecraftforge.bootstrap.ForgeBootstrap' run.main 'net.minecraftforge.bootstrap.ForgeBootstrap'
} }
@@ -408,9 +413,8 @@ tasks.register('extractInheritance', ExtractInheritance) {
} }
} }
tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) { tasks.register("findFinalizeSpawnTargets", BytecodePredicateFinder) {
dependsOn downloadClientRaw jar = createClientOfficial.output
jar = downloadClientRaw.dest output = rootProject.file('src/main/resources/coremods/finalize_spawn_targets.json')
output = rootProject.file('forge-transformers/src/main/resources/coremods/finalize_spawn_targets.json')
predicate = { predicate = {
parent, node, insn -> parent, node, insn ->
return 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it. return 'net/minecraft/world/level/BaseSpawner' != parent.name // Ignore this class as we special case it.
@@ -434,39 +438,62 @@ tasks.register("downloadServerShim", DownloadMavenArtifact) {
artifact = libs.bootstrap.shim.get().toString() artifact = libs.bootstrap.shim.get().toString()
changing = true changing = true
} }
tasks.register('downloadClientMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
ext.output = file('build/client_mappings.tsrg')
tool = INSTALLER_TOOLS + ':fatjar'
args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'client', '--output', output.absolutePath]
outputs.file(output)
}
tasks.register('downloadServerMappings', net.minecraftforge.gradle.common.tasks.JarExec) {
ext.output = file('build/server_mappings.tsrg')
tool = INSTALLER_TOOLS + ':fatjar'
args = ['--task', 'DOWNLOAD_MOJMAPS', '--sanitize', '--version', MC_VERSION, '--side', 'server', '--output', output.absolutePath]
outputs.file(output)
}
tasks.register("createJoinedSRG", DownloadMavenArtifact) { tasks.register("createJoinedSRG", DownloadMavenArtifact) {
artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}" artifact = "net.minecraft:joined:${MC_VERSION}-${MCP_VERSION}:srg"
}
tasks.register("createClientOfficial", RenameJar) {
tool = FART + ':all'
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
mappings = downloadClientMappings.output
dependsOn(downloadClientRaw, downloadClientMappings)
input = downloadClientRaw.dest
output = file("build/createClientOfficial/output.jar")
}
tasks.register("createServerOfficial", RenameJar) {
tool = FART + ':all'
args = ['--input', '{input}', '--output', '{output}', '--names', '{mappings}', '--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse']
mappings = downloadServerMappings.output
dependsOn(downloadServerMappings)
input = extractServer.output
output = file("build/createServerOfficial/output.jar")
} }
tasks.named('genClientBinPatches').configure { tasks.named('genClientBinPatches').configure {
dependsOn(downloadClientRaw)
tool = BINPATCH_TOOL tool = BINPATCH_TOOL
cleanJar = downloadClientRaw.dest cleanJar = createClientOfficial.output
dirtyJar = jar.archiveFile dirtyJar = jar.archiveFile
} }
tasks.named('genServerBinPatches').configure { tasks.named('genServerBinPatches').configure {
dependsOn(extractServer)
tool = BINPATCH_TOOL tool = BINPATCH_TOOL
cleanJar = extractServer.output cleanJar = createServerOfficial.output
dirtyJar = jar.archiveFile dirtyJar = jar.archiveFile
} }
tasks.named('genJoinedBinPatches').configure { tasks.named('genJoinedBinPatches').configure {
tool = BINPATCH_TOOL tool = BINPATCH_TOOL
cleanJar = createJoinedSRG.output cleanJar = createJoinedSRG.output
dirtyJar = jar.archiveFile
} }
tasks.register('applyClientBinPatches', ApplyBinPatches) { tasks.register('applyClientBinPatches', ApplyBinPatches) {
dependsOn downloadClientRaw
tool = BINPATCH_TOOL tool = BINPATCH_TOOL
clean = downloadClientRaw.dest clean = createClientOfficial.output
patch = genClientBinPatches.output patch = genClientBinPatches.output
args.addAll(['--data', '--unpatched', '--store', '--marker', '.forge_patched_minecraft']) args.addAll(['--data', '--unpatched'])
} }
tasks.register('applyServerBinPatches', ApplyBinPatches) { tasks.register('applyServerBinPatches', ApplyBinPatches) {
dependsOn extractServer
tool = BINPATCH_TOOL tool = BINPATCH_TOOL
clean = extractServer.output clean = createServerOfficial.output
patch = genServerBinPatches.output patch = genServerBinPatches.output
args.addAll(['--data', '--unpatched', '--store']) args.addAll(['--data', '--unpatched'])
} }
tasks.register('applyJoinedBinPatches', ApplyBinPatches) { tasks.register('applyJoinedBinPatches', ApplyBinPatches) {
tool = BINPATCH_TOOL tool = BINPATCH_TOOL
@@ -482,7 +509,7 @@ tasks.register('createServerShimConfig') {
doLast { doLast {
var cfg = new CleanProperties() var cfg = new CleanProperties()
cfg['Main-Class'] = 'net.minecraftforge.bootstrap.ForgeBootstrap' cfg['Main-Class'] = 'net.minecraftforge.bootstrap.ForgeBootstrap'
cfg['Java-Version'] = '25' cfg['Java-Version'] = '21'
cfg['Arguments'] = '--launchTarget forge_server' cfg['Arguments'] = '--launchTarget forge_server'
cfg.store(output) cfg.store(output)
} }
@@ -514,9 +541,10 @@ tasks.register('checkAllAndFix') {
} }
CheckTask.registerTask(tasks, 'ATs', CheckATs) { CheckTask.registerTask(tasks, 'ATs', CheckATs) {
dependsOn extractInheritance dependsOn extractInheritance, createSrg2Mcp
ats.from patcher.accessTransformers ats.from patcher.accessTransformers
inheritance = extractInheritance.output inheritance = extractInheritance.output
mappings = createSrg2Mcp.output
} }
CheckTask.registerTask(tasks, 'SAS', CheckSAS) { CheckTask.registerTask(tasks, 'SAS', CheckSAS) {
@@ -603,8 +631,7 @@ tasks.register('launcherJson', LauncherJson).configure {
'--launchTarget', 'forge_client' '--launchTarget', 'forge_client'
], ],
jvm: [ jvm: [
'-Djava.net.preferIPv6Addresses=system', '-Djava.net.preferIPv6Addresses=system'
'-XX:+UseCompactObjectHeaders'
] ]
] ]
] as LinkedHashMap) ] as LinkedHashMap)
@@ -617,9 +644,15 @@ tasks.register('installerJson', InstallerJson) {
dependsOn(launcherJson) dependsOn(launcherJson)
input.from(launcherJson.output) input.from(launcherJson.output)
// Download Official Mappings
dependsOn(downloadClientMappings, downloadServerMappings)
input.from(downloadClientMappings.output, downloadServerMappings.output)
// Get 'base' MC jar, Client is straight download, server is extracted from the bundle // Get 'base' MC jar, Client is straight download, server is extracted from the bundle
dependsOn(downloadClientRaw, extractServer) dependsOn(downloadClientRaw, extractServer)
input.from(downloadClientRaw.dest, extractServer.output) input.from(downloadClientRaw.dest, extractServer.output)
// Rename MC Jar
dependsOn(createClientOfficial, createServerOfficial)
input.from(createClientOfficial.output, createServerOfficial.output)
// Apply Binary patches to vanilla jar // Apply Binary patches to vanilla jar
dependsOn(applyClientBinPatches, applyServerBinPatches) dependsOn(applyClientBinPatches, applyServerBinPatches)
input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar) input.from(applyClientBinPatches.output, applyServerBinPatches.output, genClientBinPatches.toolJar)
@@ -637,6 +670,14 @@ tasks.register('installerJson', InstallerJson) {
minecraft: MC_VERSION, minecraft: MC_VERSION,
serverJarPath: '{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}-bundled.jar', serverJarPath: '{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}-bundled.jar',
data: [ data: [
MOJMAPS: [
client: "[net.minecraft:client:${MC_VERSION}:mappings@tsrg]",
server: "[net.minecraft:server:${MC_VERSION}:mappings@tsrg]"
],
MOJMAPS_SHA: [
client: "'${downloadClientMappings.output.sha1}'",
server: "'${downloadServerMappings.output.sha1}'"
],
MC_UNPACKED: [ MC_UNPACKED: [
client: "[net.minecraft:client:${MC_VERSION}]", client: "[net.minecraft:client:${MC_VERSION}]",
server: "[net.minecraft:server:${MC_VERSION}:unpacked]" server: "[net.minecraft:server:${MC_VERSION}:unpacked]"
@@ -645,6 +686,14 @@ tasks.register('installerJson', InstallerJson) {
client: "'${downloadClientRaw.dest.sha1}'", client: "'${downloadClientRaw.dest.sha1}'",
server: "'${extractServer.output.get().asFile.sha1}'" server: "'${extractServer.output.get().asFile.sha1}'"
], ],
MC_OFF: [
client: "[net.minecraft:client:${MC_VERSION}:official]",
server: "[net.minecraft:server:${MC_VERSION}:official]"
],
MC_OFF_SHA: [
client: "'${createClientOfficial.output.get().asFile.sha1}'",
server: "'${createServerOfficial.output.get().asFile.sha1}'"
],
BINPATCH: [ BINPATCH: [
client: '/data/client.lzma', client: '/data/client.lzma',
server: '/data/server.lzma' server: '/data/server.lzma'
@@ -711,27 +760,52 @@ tasks.register('installerJson', InstallerJson) {
'{MC_UNPACKED}': '{MC_UNPACKED_SHA}' '{MC_UNPACKED}': '{MC_UNPACKED_SHA}'
] ]
], [ ], [
sides: ['server'], jar: INSTALLER_TOOLS,
jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar classpath: INSTALLER_TOOLS_CLASSPATH,
classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]),
args: [ args: [
'--clean', '{MC_UNPACKED}', '--task', 'DOWNLOAD_MOJMAPS',
'--output', '{PATCHED}', '--sanitize',
'--apply', '{BINPATCH}', '--version', MC_VERSION,
'--data', '--unpatched', '--store' '--side', '{SIDE}',
'--output', '{MOJMAPS}'
], ],
outputs: [ outputs: [
'{PATCHED}': '{PATCHED_SHA}' '{MOJMAPS}': '{MOJMAPS_SHA}'
]
], [
sides: ['server'],
jar: FART,
classpath: getClasspath(project, libs, FART),
args: [
'--input', '{MC_UNPACKED}',
'--output', '{MC_OFF}',
'--names', '{MOJMAPS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
],
outputs: [
'{MC_OFF}': '{MC_OFF_SHA}'
] ]
], [ ], [
sides: ['client'], sides: ['client'],
jar: FART,
classpath: getClasspath(project, libs, FART),
args: [
'--input', '{MINECRAFT_JAR}',
'--output', '{MC_OFF}',
'--names', '{MOJMAPS}',
'--ann-fix', '--ids-fix', '--src-fix', '--record-fix', '--strip-sigs', '--reverse'
],
outputs: [
'{MC_OFF}': '{MC_OFF_SHA}'
]
], [
jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar jar: BINPATCH_TOOL.rsplit(':', 1)[0], // remove :fatjar
classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]), classpath: getClasspath(project, libs, BINPATCH_TOOL.rsplit(':', 1)[0]),
args: [ args: [
'--clean', '{MINECRAFT_JAR}', '--clean', '{MC_OFF}',
'--output', '{PATCHED}', '--output', '{PATCHED}',
'--apply', '{BINPATCH}', '--apply', '{BINPATCH}',
'--data', '--unpatched', '--store', '--marker', '.forge_patched_minecraft' '--data', '--unpatched'
], ],
outputs: [ outputs: [
'{PATCHED}': '{PATCHED_SHA}' '{PATCHED}': '{PATCHED_SHA}'
@@ -756,7 +830,12 @@ tasks.register('officialClassesOnly', Zip).configure {
tasks.named('filterJarNew').configure { tasks.named('filterJarNew').configure {
dependsOn('officialClassesOnly') dependsOn('officialClassesOnly')
input = officialClassesOnly.archiveFile input = officialClassesOnly.archiveFile
filterInners = true }
tasks.register('filterJarNewSRG', FilterNewJar).configure {
input = reobfJar.output
srg = filterJarNew.srg
blacklist = filterJarNew.blacklist
} }
tasks.named('universalJar').configure { tasks.named('universalJar').configure {
@@ -793,8 +872,18 @@ tasks.named('universalJar').configure {
jarSigner.sign(it) jarSigner.sign(it)
} }
tasks.register('universalJarSrg', Jar).configure {
from zipTree(filterJarNewSRG.output)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from zipTree(universalJar.archiveFile)
destinationDirectory = file('build/libs')
archiveClassifier = 'universal-srg'
manifest.from(universalJar.manifest)
jarSigner.sign(it)
}
tasks.named('userdevConfig').configure { tasks.named('userdevConfig').configure {
universal = "$project.group:$project.name:$project.version:universal@jar" universal = "$project.group:$project.name:$project.version:universal-srg@jar"
} }
tasks.register('installerJar', InstallerJar) { tasks.register('installerJar', InstallerJar) {
@@ -901,7 +990,7 @@ license {
} }
tasks.register('genAllData') { tasks.register('genAllData') {
dependsOn 'forge_data', 'forge_data_test', 'forge_client_data_test' dependsOn 'forge_data', 'forge_test_data'
} }
if (project.hasProperty('UPDATE_MAPPINGS')) { if (project.hasProperty('UPDATE_MAPPINGS')) {
@@ -995,6 +1084,7 @@ tasks.named('javadoc', Javadoc).configure {
publishing { publishing {
publications.register('mavenJava', MavenPublication).configure { publications.register('mavenJava', MavenPublication).configure {
artifact universalJar artifact universalJar
artifact universalJarSrg
artifact installerJar artifact installerJar
artifact mdkZip artifact mdkZip
artifact userdevJar artifact userdevJar
-4
View File
@@ -38,10 +38,6 @@ tasks.register('generateResources') {
dependsOn('writeManifest') dependsOn('writeManifest')
} }
tasks.named('processResources') {
dependsOn(generateResources)
}
// Make sure out manifests get written before compiling the code, IDEA calls this task if you tell it to use the gradle build. // Make sure out manifests get written before compiling the code, IDEA calls this task if you tell it to use the gradle build.
tasks.withType(JavaCompile).configureEach { tasks.withType(JavaCompile).configureEach {
dependsOn 'generateResources' dependsOn 'generateResources'
+8 -10
View File
@@ -2,8 +2,8 @@
MinecraftForge MinecraftForge
============= =============
[![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=26.1.2-&query=$.promos["26.1.2-latest"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download] [![Stable Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Stable&prefix=1.21.8-&query=$.promos["1.21.8-recommended"]&color=brightgreen&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtc3RhciBmYS13LTE4IiBhcmlhLWhpZGRlbj0idHJ1ZSIgZGF0YS1pY29uPSJzdGFyIiBkYXRhLXByZWZpeD0iZmFzIiBmb2N1c2FibGU9ImZhbHNlIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCA1NzYgNTEyIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMjU5LjMgMTcuOEwxOTQgMTUwLjIgNDcuOSAxNzEuNWMtMjYuMiAzLjgtMzYuNyAzNi4xLTE3LjcgNTQuNmwxMDUuNyAxMDMtMjUgMTQ1LjVjLTQuNSAyNi4zIDIzLjIgNDYgNDYuNCAzMy43TDI4OCA0MzkuNmwxMzAuNyA2OC43YzIzLjIgMTIuMiA1MC45LTcuNCA0Ni40LTMzLjdsLTI1LTE0NS41IDEwNS43LTEwM2MxOS0xOC41IDguNS01MC44LTE3LjctNTQuNkwzODIgMTUwLjIgMzE2LjcgMTcuOGMtMTEuNy0yMy42LTQ1LjYtMjMuOS01Ny40IDB6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K)][Download]
[![Latest Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Latest&prefix=26.2-&query=$.promos["26.2-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo= [![Latest Release](https://img.shields.io/badge/dynamic/json?url=https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json&label=Latest&prefix=1.21.8-&query=$.promos["1.21.8-latest"]&color=blue&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBjbGFzcz0ic3ZnLWlubGluZS0tZmEgZmEtYnVnIGZhLXctMTYiIGFyaWEtaGlkZGVuPSJ0cnVlIiBkYXRhLWljb249ImJ1ZyIgZGF0YS1wcmVmaXg9ImZhcyIgZm9jdXNhYmxlPSJmYWxzZSIgcm9sZT0iaW1nIiB2aWV3Qm94PSIwIDAgNTEyIDUxMiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTUxMS45ODggMjg4LjljLS40NzggMTcuNDMtMTUuMjE3IDMxLjEtMzIuNjUzIDMxLjFINDI0djE2YzAgMjEuODY0LTQuODgyIDQyLjU4NC0xMy42IDYxLjE0NWw2MC4yMjggNjAuMjI4YzEyLjQ5NiAxMi40OTcgMTIuNDk2IDMyLjc1OCAwIDQ1LjI1NS0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDBsLTU0LjczNi01NC43MzZDMzQ1Ljg4NiA0NjcuOTY1IDMxNC4zNTEgNDgwIDI4MCA0ODBWMjM2YzAtNi42MjctNS4zNzMtMTItMTItMTJoLTI0Yy02LjYyNyAwLTEyIDUuMzczLTEyIDEydjI0NGMtMzQuMzUxIDAtNjUuODg2LTEyLjAzNS05MC42MzYtMzIuMTA4bC01NC43MzYgNTQuNzM2Yy0xMi40OTggMTIuNDk3LTMyLjc1OSAxMi40OTYtNDUuMjU2IDAtMTIuNDk2LTEyLjQ5Ny0xMi40OTYtMzIuNzU4IDAtNDUuMjU1bDYwLjIyOC02MC4yMjhDOTIuODgyIDM3OC41ODQgODggMzU3Ljg2NCA4OCAzMzZ2LTE2SDMyLjY2NkMxNS4yMyAzMjAgLjQ5MSAzMDYuMzMuMDEzIDI4OC45LS40ODQgMjcwLjgxNiAxNC4wMjggMjU2IDMyIDI1Nmg1NnYtNTguNzQ1bC00Ni42MjgtNDYuNjI4Yy0xMi40OTYtMTIuNDk3LTEyLjQ5Ni0zMi43NTggMC00NS4yNTUgMTIuNDk4LTEyLjQ5NyAzMi43NTgtMTIuNDk3IDQ1LjI1NiAwTDE0MS4yNTUgMTYwaDIyOS40ODlsNTQuNjI3LTU0LjYyN2MxMi40OTgtMTIuNDk3IDMyLjc1OC0xMi40OTcgNDUuMjU2IDAgMTIuNDk2IDEyLjQ5NyAxMi40OTYgMzIuNzU4IDAgNDUuMjU1TDQyNCAxOTcuMjU1VjI1Nmg1NmMxNy45NzIgMCAzMi40ODQgMTQuODE2IDMxLjk4OCAzMi45ek0yNTcgMGMtNjEuODU2IDAtMTEyIDUwLjE0NC0xMTIgMTEyaDIyNEMzNjkgNTAuMTQ0IDMxOC44NTYgMCAyNTcgMHoiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo=
)][Download] [![Discord](https://img.shields.io/discord/313125603924639766.svg?color=%237289da&label=Discord&logo=discord&logoColor=%237289da)][Discord] [![Support](https://img.shields.io/badge/Patreon-Support-orange.svg?logo=Patreon)][Patreon] )][Download] [![Discord](https://img.shields.io/discord/313125603924639766.svg?color=%237289da&label=Discord&logo=discord&logoColor=%237289da)][Discord] [![Support](https://img.shields.io/badge/Patreon-Support-orange.svg?logo=Patreon)][Patreon]
Forge is a free, open-source modding API all of your favourite mods use! Forge is a free, open-source modding API all of your favourite mods use!
@@ -34,13 +34,12 @@ For support and questions, visit [the Support Forum][Support-Forum] or [the Forg
We require the version of Java that Minecraft requires, which is currently: We require the version of Java that Minecraft requires, which is currently:
| Minecraft | Java | | Minecraft | Java |
|------------------|-------------------| |---------------|-------------------|
| 26.1+ | [25][Adoptium-25] | | 1.20.6+ | [21][Adoptium-21] |
| 1.20.6 - 1.21.11 | [21][Adoptium-21] | | 1.18 - 1.20.4 | [17][Adoptium-17] |
| 1.18 - 1.20.4 | [17][Adoptium-17] | | 1.17.1 | [16][Adoptium-16] |
| 1.17.1 | [16][Adoptium-16] | | 1.16.5- | [8][Adoptium-8] |
| 1.16.5- | [8][Adoptium-8] |
**If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].** **If you are on Windows and have difficulty using Java to launch JAR files, consider using [Jarfix by Johann Löfflmann][Jarfix].**
@@ -81,7 +80,6 @@ YourKit for providing us accesss to their [YourKit Java Profiler] which helps id
[Download]: https://files.minecraftforge.net/ [Download]: https://files.minecraftforge.net/
[Adoptium-25]: https://adoptium.net/temurin/releases/?version=25
[Adoptium-21]: https://adoptium.net/temurin/releases/?version=21 [Adoptium-21]: https://adoptium.net/temurin/releases/?version=21
[Adoptium-17]: https://adoptium.net/temurin/releases/?version=17 [Adoptium-17]: https://adoptium.net/temurin/releases/?version=17
[Adoptium-16]: https://adoptium.net/temurin/releases/?version=16 [Adoptium-16]: https://adoptium.net/temurin/releases/?version=16
@@ -14,14 +14,16 @@ import java.util.List;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
import java.util.function.Supplier; import java.util.function.Supplier;
public class CrashReportCallables { public class CrashReportCallables
{
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final List<ISystemReportExtender> crashCallables = Collections.synchronizedList(new ArrayList<>()); private static final List<ISystemReportExtender> crashCallables = Collections.synchronizedList(new ArrayList<>());
/** /**
* Register a custom {@link ISystemReportExtender} * Register a custom {@link ISystemReportExtender}
*/ */
public static void registerCrashCallable(ISystemReportExtender callable) { public static void registerCrashCallable(ISystemReportExtender callable)
{
crashCallables.add(callable); crashCallables.add(callable);
} }
@@ -31,15 +33,19 @@ public class CrashReportCallables {
* @param headerName The name of the system report entry * @param headerName The name of the system report entry
* @param reportGenerator The report generator to be called when a crash report is built * @param reportGenerator The report generator to be called when a crash report is built
*/ */
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator) { public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator)
registerCrashCallable(new ISystemReportExtender() { {
registerCrashCallable(new ISystemReportExtender()
{
@Override @Override
public String getLabel() { public String getLabel()
{
return headerName; return headerName;
} }
@Override @Override
public String get() { public String get()
{
return reportGenerator.get(); return reportGenerator.get();
} }
}); });
@@ -52,23 +58,31 @@ public class CrashReportCallables {
* @param reportGenerator The report generator to be called when a crash report is built * @param reportGenerator The report generator to be called when a crash report is built
* @param active The supplier of the flag to be checked when a crash report is built * @param active The supplier of the flag to be checked when a crash report is built
*/ */
public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator, BooleanSupplier active) { public static void registerCrashCallable(String headerName, Supplier<String> reportGenerator, BooleanSupplier active)
registerCrashCallable(new ISystemReportExtender() { {
registerCrashCallable(new ISystemReportExtender()
{
@Override @Override
public String getLabel() { public String getLabel()
{
return headerName; return headerName;
} }
@Override @Override
public String get() { public String get()
{
return reportGenerator.get(); return reportGenerator.get();
} }
@Override @Override
public boolean isActive() { public boolean isActive()
try { {
try
{
return active.getAsBoolean(); return active.getAsBoolean();
} catch (Throwable t) { }
catch (Throwable t)
{
LOGGER.warn("CrashCallable '{}' threw an exception while checking the active flag, disabling", headerName, t); LOGGER.warn("CrashCallable '{}' threw an exception while checking the active flag, disabling", headerName, t);
return false; return false;
} }
@@ -76,7 +90,8 @@ public class CrashReportCallables {
}); });
} }
public static List<ISystemReportExtender> allCrashCallables() { public static List<ISystemReportExtender> allCrashCallables()
{
return List.copyOf(crashCallables); return List.copyOf(crashCallables);
} }
} }
@@ -0,0 +1,273 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fml;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.loading.FMLEnvironment;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.function.Supplier;
/**
* Use to execute code conditionally based on sidedness.
* <ul>
* <li>When you want to call something on one side and return a result {@link #safeCallWhenOn(Dist, Supplier)}</li>
* <li>When you want to call one thing on one side, another thing on the other and return a result {@link #safeRunForDist(Supplier, Supplier)}</li>
* <li>When you want to run something on one side {@link #safeRunWhenOn(Dist, Supplier)}</li>
* </ul>
*
* @deprecated Historically, this allowed for safe execution of code on the correct side by exploiting a low-level
* detail in Java 8, but in newer versions a simple if check is enough.
* <br>
* For example:
* <pre>{@code
* if (FMLEnvironment.dist.isClient()) {
* // client code here
* }
* }</pre>
*/
@Deprecated(since = "1.21.5", forRemoval = true)
public final class DistExecutor
{
private static final Logger LOGGER = LogManager.getLogger();
private DistExecutor() {}
/**
* Run the callable in the supplier only on the specified {@link Dist}.
* This method is NOT sided-safe and special care needs to be taken in code using this method that implicit class
* loading is not triggered by the Callable.
*
* This method can cause unexpected ClassNotFound exceptions.
*
* Use {@link #safeCallWhenOn(Dist, Supplier)} where possible.
*
* @param dist The dist to run on
* @param toRun A supplier of the callable to run (Supplier wrapper to ensure classloading only on the appropriate dist)
* @param <T> The return type from the callable
* @return The callable's result
* @deprecated use {@link #safeCallWhenOn(Dist, Supplier)} instead. This remains for advanced use cases.
*/
@Deprecated
public static <T> T callWhenOn(Dist dist, Supplier<Callable<T>> toRun) {
return unsafeCallWhenOn(dist, toRun);
}
public static <T> T unsafeCallWhenOn(Dist dist, Supplier<Callable<T>> toRun) {
if (dist == FMLEnvironment.dist) {
try
{
return toRun.get().call();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
return null;
}
/**
* Call the SafeCallable when on the correct {@link Dist}.
*
* <strong>The lambda supplied here is required to be a method reference to a method defined in
* another class, otherwise an invalid SafeReferent error will be thrown</strong>
* @param dist the dist which this will run on
* @param toRun the SafeCallable to run and return the result from
* @param <T> The type of the SafeCallable
* @return the result of the SafeCallable or null if on the wrong side
*/
public static <T> T safeCallWhenOn(Dist dist, Supplier<SafeCallable<T>> toRun) {
validateSafeReferent(toRun);
return callWhenOn(dist, toRun::get);
}
/**
* Runs the supplied Runnable on the speicified side. Same warnings apply as {@link #callWhenOn(Dist, Supplier)}.
*
* This method can cause unexpected ClassNotFound exceptions.
*
* @see #callWhenOn(Dist, Supplier)
* @param dist Dist to run this code on
* @param toRun The code to run
* @deprecated use {@link #safeRunWhenOn(Dist, Supplier)} where possible. Advanced uses only.
*/
@Deprecated
public static void runWhenOn(Dist dist, Supplier<Runnable> toRun) {
unsafeRunWhenOn(dist, toRun);
}
/**
* Runs the supplied Runnable on the speicified side. Same warnings apply as {@link #unsafeCallWhenOn(Dist, Supplier)}.
*
* This method can cause unexpected ClassNotFoundException problems in common scenarios. Understand the pitfalls of
* the way the class verifier works to load classes before using this.
*
* Use {@link #safeRunWhenOn(Dist, Supplier)} if you can.
*
* @see #unsafeCallWhenOn(Dist, Supplier)
* @param dist Dist to run this code on
* @param toRun The code to run
*/
public static void unsafeRunWhenOn(Dist dist, Supplier<Runnable> toRun) {
if (dist == FMLEnvironment.dist) {
toRun.get().run();
}
}
/**
* Call the supplied SafeRunnable when on the correct Dist.
* @param dist The dist to run on
* @param toRun The code to run
*/
public static void safeRunWhenOn(Dist dist, Supplier<SafeRunnable> toRun) {
validateSafeReferent(toRun);
if (dist == FMLEnvironment.dist) {
toRun.get().run();
}
}
/**
* Executes one of the two suppliers, based on which side is active.
*
* <p>
* Example (replacement for old SidedProxy):<br/>
* {@code Proxy p = DistExecutor.runForDist(()->ClientProxy::new, ()->ServerProxy::new);}
*
* NOTE: the double supplier is required to avoid classloading the secondary target.
*
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
* @param <T> The common type to return
* @return The returned instance
* @deprecated Use {@link #safeRunForDist(Supplier, Supplier)}
*/
@Deprecated
public static <T> T runForDist(Supplier<Supplier<T>> clientTarget, Supplier<Supplier<T>> serverTarget) {
return unsafeRunForDist(clientTarget, serverTarget);
}
/**
* Unsafe version of {@link #safeRunForDist(Supplier, Supplier)}. Use only when you know what you're doing
* and understand why the verifier can cause unexpected ClassNotFoundException crashes even when code is apparently
* not sided. Ensure you test both sides fully to be confident in using this.
*
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
* @param <T> The common type to return
* @return The returned instance
*/
public static <T> T unsafeRunForDist(Supplier<Supplier<T>> clientTarget, Supplier<Supplier<T>> serverTarget) {
switch (FMLEnvironment.dist)
{
case CLIENT:
return clientTarget.get().get();
case DEDICATED_SERVER:
return serverTarget.get().get();
default:
throw new IllegalArgumentException("UNSIDED?");
}
}
/**
* Executes one of the two suppliers, based on which side is active.
*
* <p>
* Example (replacement for old SidedProxy):<br/>
* {@code Proxy p = DistExecutor.safeRunForDist(()->ClientProxy::new, ()->ServerProxy::new);}
*
* NOTE: the double supplier is required to avoid classloading the secondary target.
*
* @param clientTarget The supplier supplier to run when on the {@link Dist#CLIENT}
* @param serverTarget The supplier supplier to run when on the {@link Dist#DEDICATED_SERVER}
* @param <T> The common type to return
* @return The returned instance
*/
public static <T> T safeRunForDist(Supplier<SafeSupplier<T>> clientTarget, Supplier<SafeSupplier<T>> serverTarget) {
validateSafeReferent(clientTarget);
validateSafeReferent(serverTarget);
switch (FMLEnvironment.dist)
{
case CLIENT:
return clientTarget.get().get();
case DEDICATED_SERVER:
return serverTarget.get().get();
default:
throw new IllegalArgumentException("UNSIDED?");
}
}
/**
* A safe referent. This will assert that it is being called via a separated class method reference. This will
* avoid the common pitfalls of {@link #callWhenOn(Dist, Supplier)} above.
*
* SafeReferents assert that they are defined as a separate method outside the scope of the calling class.
*
* <strong>Implementations need to be defined in a separate class to the referring site, with appropriate
* visibility to be accessible at the callsite (generally, avoid private methods).</strong>
*
* <p>
* Valid:<br/>
*
* {@code DistExecutor.safeCallWhenOn(Dist.CLIENT, ()->AnotherClass::clientOnlyMethod);}
*
* <p>
* Invalid:<br/>
*
* {@code DistExecutor.safeCallWhenOn(Dist.CLIENT, ()->()->Minecraft.getInstance().world);}
*/
public interface SafeReferent {}
/**
* SafeCallable version of {@link SafeReferent}.
* @see SafeReferent
* @param <T> The return type of the Callable
*/
public interface SafeCallable<T> extends SafeReferent, Callable<T>, Serializable {}
/**
* SafeSupplier version of {@link SafeReferent}
* @param <T> The return type of the Supplier
*/
public interface SafeSupplier<T> extends SafeReferent, Supplier<T>, Serializable {}
/**
* SafeRunnable version of {@link SafeReferent}
*/
public interface SafeRunnable extends SafeReferent, Runnable, Serializable {}
private static final void validateSafeReferent(Supplier<? extends SafeReferent> safeReferentSupplier) {
if (FMLEnvironment.production) return;
final SafeReferent setter;
try {
setter = safeReferentSupplier.get();
} catch (Exception e) {
// Typically a class cast exception, just return out, expected.
return;
}
for (Class<?> cl = setter.getClass(); cl != null; cl = cl.getSuperclass()) {
try {
Method m = cl.getDeclaredMethod("writeReplace");
m.setAccessible(true);
Object replacement = m.invoke(setter);
if (!(replacement instanceof SerializedLambda))
break;// custom interface implementation
SerializedLambda l = (SerializedLambda) replacement;
if (Objects.equals(l.getCapturingClass(), l.getImplClass())) {
LOGGER.fatal("Detected unsafe referent usage, please view the code at {}",Thread.currentThread().getStackTrace()[3]);
throw new RuntimeException("Unsafe Referent usage found in safe referent method");
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException | InvocationTargetException e) {
break;
}
}
}
}
@@ -6,14 +6,13 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import net.minecraftforge.fml.loading.progress.ProgressMeter; import net.minecraftforge.fml.loading.progress.ProgressMeter;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.IntSupplier; import java.util.function.ToIntFunction;
import java.util.function.Supplier;
/** /**
* A mod loading state. During mod loading, the mod loader transitions between states in a defined sorted list of states, * A mod loading state. During mod loading, the mod loader transitions between states in a defined sorted list of states,
@@ -21,7 +20,6 @@ import java.util.function.Supplier;
* *
* @see IModStateProvider * @see IModStateProvider
*/ */
@NullMarked
public interface IModLoadingState { public interface IModLoadingState {
/** /**
* {@return the name of this state} * {@return the name of this state}
@@ -44,21 +42,19 @@ public interface IModLoadingState {
/** /**
* {@return a function returning a human-friendly message for this state} * {@return a function returning a human-friendly message for this state}
*/ */
Supplier<String> message(); Function<ModList, String> message();
/** /**
* @return a function that computes the size of this transition based on the size of the modlist. * @return a function that computes the size of this transition based on the size of the modlist.
* Used to compute progress. * Used to compute progress.
*/ */
default IntSupplier size() { ToIntFunction<ModList> size();
return ModList::size;
}
/** /**
* {@return an optional runnable, which runs before starting the transition from this state to the next} * {@return an optional runnable, which runs before starting the transition from this state to the next}
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function) * @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
*/ */
@Nullable Runnable inlineRunnable(); Optional<Consumer<ModList>> inlineRunnable();
/** /**
* Builds the transition task for this state with a blank pre-sync and post-sync task. * Builds the transition task for this state with a blank pre-sync and post-sync task.
@@ -69,14 +65,14 @@ public interface IModLoadingState {
* @return a transition task for this state * @return a transition task for this state
* @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function) * @see #buildTransition(Executor, Executor, ProgressMeter, Function, Function)
*/ */
default @Nullable CompletableFuture<Void> buildTransition( default Optional<CompletableFuture<Void>> buildTransition(
final Executor syncExecutor, final Executor syncExecutor,
final Executor parallelExecutor, final Executor parallelExecutor,
final ProgressMeter progressBar final ProgressMeter progressBar
) { ) {
return buildTransition(syncExecutor, parallelExecutor, progressBar, return buildTransition(syncExecutor, parallelExecutor, progressBar,
_ -> CompletableFuture.completedFuture(null), e -> CompletableFuture.completedFuture(null),
_ -> CompletableFuture.completedFuture(null) e -> CompletableFuture.completedFuture(null)
); );
} }
@@ -91,7 +87,7 @@ public interface IModLoadingState {
* @param postSyncTask a function which returns a task to run after event post-dispatch hook * @param postSyncTask a function which returns a task to run after event post-dispatch hook
* @return a transition task for this state * @return a transition task for this state
*/ */
@Nullable CompletableFuture<Void> buildTransition(final Executor syncExecutor, Optional<CompletableFuture<Void>> buildTransition(final Executor syncExecutor,
final Executor parallelExecutor, final Executor parallelExecutor,
final ProgressMeter progressBar, final ProgressMeter progressBar,
final Function<Executor, CompletableFuture<Void>> preSyncTask, final Function<Executor, CompletableFuture<Void>> preSyncTask,
@@ -6,16 +6,21 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.loading.progress.ProgressMeter;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import net.minecraftforge.fml.loading.progress.ProgressMeter;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public interface IModStateTransition { public interface IModStateTransition {
/** Magic value to allow me to optimize the futures list by ignoring the default value without making old methods nullable. */
BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> NULL_HOOK = (e, g) -> CompletableFuture.completedFuture(null);
static IModStateTransition buildNoopTransition() { static IModStateTransition buildNoopTransition() {
return ModStateTransitionHelper.NOOP; return ModStateTransitionHelper.NOOP;
} }
@@ -35,6 +40,15 @@ public interface IModStateTransition {
return ModLoadingStage::nextState; return ModLoadingStage::nextState;
} }
/**
* This used to allow you to fire multiple events during the transition. However, in doing so it would cause issues with the default
* ModContainer's event handlers causing issues such as mod classes being constructed multiple times.
*/
@Deprecated(since = "1.21.3", forRemoval = true)
default Supplier<Stream<EventGenerator<?>>> eventFunctionStream() {
return () -> Stream.ofNullable(eventFunction());
}
@Nullable @Nullable
default <T extends IModBusEvent> EventGenerator<T> eventFunction() { default <T extends IModBusEvent> EventGenerator<T> eventFunction() {
return null; return null;
@@ -43,9 +57,25 @@ public interface IModStateTransition {
ThreadSelector threadSelector(); ThreadSelector threadSelector();
BiFunction<Executor, CompletableFuture<Void>, CompletableFuture<Void>> finalActivityGenerator(); BiFunction<Executor, CompletableFuture<Void>, CompletableFuture<Void>> finalActivityGenerator();
/**
* I think this was meant as a way to do some things for each mod container beforge/after the transition had been sent to the container.
* However, the Future returned by this was never linked to the main transition future in any way. Which means that it was run
* in parallel and couldn't guarantee the state of the ModContainer.
* <p>
* Plus all existing code that I could find returned a completedFuture, so I don't think anyone ever used this.
* <p>
* If I were to add this back it would be a CompletableFuture wrap(ModContainer, CompletableFuture)
* <p>
* Added magic value NULL_HOOK to allow me to optimize the futures list by ignoring the default value without making this method nullable.
*/
@Deprecated(since = "1.21.3", forRemoval = true)
default BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> preDispatchHook() { return NULL_HOOK; }
@Deprecated(since = "1.21.3", forRemoval = true)
default BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> postDispatchHook() { return NULL_HOOK; }
interface EventGenerator<T extends IModBusEvent> extends Function<ModContainer, T> { interface EventGenerator<T extends IModBusEvent> extends Function<ModContainer, T> {
static <FN extends IModBusEvent> EventGenerator<FN> fromFunction(Function<ModContainer, FN> fn) { static <FN extends IModBusEvent> EventGenerator<FN> fromFunction(Function<ModContainer, FN> fn) {
return fn::apply; return fn::apply;
} }
} }
} }
@@ -7,10 +7,12 @@ package net.minecraftforge.fml;
import java.util.function.Supplier; import java.util.function.Supplier;
public interface ISystemReportExtender extends Supplier<String> { public interface ISystemReportExtender extends Supplier<String>
{
String getLabel(); String getLabel();
default boolean isActive() { default boolean isActive()
{
return true; return true;
} }
} }
@@ -5,20 +5,63 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import java.util.Iterator; import java.util.Iterator;
import java.util.Spliterator; import java.util.Spliterator;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.stream.Stream; import java.util.stream.Stream;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
public final class InterModComms { public class InterModComms
public record IMCMessage(String senderModId, String modId, String method, Supplier<?> messageSupplier) {} {
public record IMCMessage(String senderModId, String modId, String method, Supplier<?> messageSupplier) {
private static final ConcurrentHashMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>(); /**
* Deprecated: use {@link #senderModId()}
* @return The modid of the sender. This is supplied by the caller, or by the active mod container context.
* Consider it unreliable.
*/
@Deprecated
public final String getSenderModId() {
return this.senderModId;
}
/**
* Deprecated: use {@link #modId()}
* @return The modid being sent to.
*/
@Deprecated
public final String getModId() {
return this.modId;
}
/**
* Deprecated: use {@link #method()}
* @return The method being sent to.
*/
@Deprecated
public final String getMethod() {
return this.method;
}
/**
* @param <T> The type of the message.
* @return A {@link Supplier} of the message.
* Use {@link #messageSupplier()}
*/
@SuppressWarnings("unchecked")
@Deprecated
public final <T> Supplier<T> getMessageSupplier() {
return (Supplier<T>) this.messageSupplier;
}
}
private static final ConcurrentMap<String, ConcurrentLinkedQueue<IMCMessage>> containerQueues = new ConcurrentHashMap<>();
/** /**
* Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not. * Send IMC to remote. Sender will default to the active modcontainer, or minecraft if not.
@@ -29,9 +72,8 @@ public final class InterModComms {
* @return true if the message was enqueued for sending (the target modid is loaded) * @return true if the message was enqueued for sending (the target modid is loaded)
*/ */
public static boolean sendTo(final String modId, final String method, final Supplier<?> thing) { public static boolean sendTo(final String modId, final String method, final Supplier<?> thing) {
if (!ModList.isLoaded(modId)) return false; if (!ModList.get().isLoaded(modId)) return false;
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>()) containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(ModLoadingContext.get().getActiveContainer().getModId(), modId, method, thing));
.add(new IMCMessage(ModLoadingContext.get().getContainer().getModId(), modId, method, thing));
return true; return true;
} }
@@ -45,9 +87,8 @@ public final class InterModComms {
* @return true if the message was enqueued for sending (the target modid is loaded) * @return true if the message was enqueued for sending (the target modid is loaded)
*/ */
public static boolean sendTo(final String senderModId, final String modId, final String method, final Supplier<?> thing) { public static boolean sendTo(final String senderModId, final String modId, final String method, final Supplier<?> thing) {
if (!ModList.isLoaded(modId)) return false; if (!ModList.get().isLoaded(modId)) return false;
containerQueues.computeIfAbsent(modId, _ -> new ConcurrentLinkedQueue<>()) containerQueues.computeIfAbsent(modId, k->new ConcurrentLinkedQueue<>()).add(new IMCMessage(senderModId, modId, method, thing));
.add(new IMCMessage(senderModId, modId, method, thing));
return true; return true;
} }
@@ -71,7 +112,7 @@ public final class InterModComms {
* @return All messages * @return All messages
*/ */
public static Stream<IMCMessage> getMessages(final String modId) { public static Stream<IMCMessage> getMessages(final String modId) {
return getMessages(modId, _ -> true); return getMessages(modId, s->Boolean.TRUE);
} }
private record QueueFilteringSpliterator( private record QueueFilteringSpliterator(
@@ -95,10 +136,13 @@ public final class InterModComms {
} }
@Override @Override
public boolean tryAdvance(final Consumer<? super IMCMessage> action) { public boolean tryAdvance(final Consumer<? super IMCMessage> action)
{
IMCMessage next; IMCMessage next;
do { do
if (!iterator.hasNext()) { {
if (!iterator.hasNext())
{
return false; return false;
} }
next = this.iterator.next(); next = this.iterator.next();
@@ -113,5 +157,6 @@ public final class InterModComms {
public Spliterator<IMCMessage> trySplit() { public Spliterator<IMCMessage> trySplit() {
return null; return null;
} }
} }
} }
@@ -5,7 +5,6 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.fml.config.IConfigEvent; import net.minecraftforge.fml.config.IConfigEvent;
import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.fml.event.IModBusEvent;
@@ -19,6 +18,7 @@ import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.function.BiPredicate; import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
/** /**
@@ -40,6 +40,11 @@ public abstract class ModContainer {
protected final Map<Class<? extends IExtensionPoint<?>>, Supplier<?>> extensionPoints = new IdentityHashMap<>(); protected final Map<Class<? extends IExtensionPoint<?>>, Supplier<?>> extensionPoints = new IdentityHashMap<>();
protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class); protected final EnumMap<ModConfig.Type, ModConfig> configs = new EnumMap<>(ModConfig.Type.class);
final Set<ModContainer> dependencies = new HashSet<>(); final Set<ModContainer> dependencies = new HashSet<>();
/**
* If you want to handle the event, override {@link #dispatchConfigEvent(IConfigEvent)}
*/
@Deprecated(since = "1.21.3", forRemoval = true)
protected Optional<Consumer<IConfigEvent>> configHandler = Optional.empty();
public ModContainer(IModInfo info) { public ModContainer(IModInfo info) {
this.modId = info.getModId(); this.modId = info.getModId();
@@ -53,7 +58,7 @@ public abstract class ModContainer {
Supplier<IExtensionPoint.DisplayTest> displayTestSupplier = switch (displayTestString) { Supplier<IExtensionPoint.DisplayTest> displayTestSupplier = switch (displayTestString) {
case "MATCH_VERSION" -> // default displaytest checks for version string match case "MATCH_VERSION" -> // default displaytest checks for version string match
() -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(), () -> new IExtensionPoint.DisplayTest(() -> this.modInfo.getVersion().toString(),
(incoming, _) -> Objects.equals(incoming, this.modInfo.getVersion().toString())); (incoming, isNetwork) -> Objects.equals(incoming, this.modInfo.getVersion().toString()));
case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods case "IGNORE_SERVER_VERSION" -> // Ignores any version information coming from the server - use for server only mods
IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION; IExtensionPoint.DisplayTest.IGNORE_SERVER_VERSION;
case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information case "IGNORE_ALL_VERSION" -> // Ignores all information and provides no information
@@ -132,7 +137,12 @@ public abstract class ModContainer {
configs.put(modConfig.getType(), modConfig); configs.put(modConfig.getType(), modConfig);
} }
public void dispatchConfigEvent(IConfigEvent event) {} public void dispatchConfigEvent(IConfigEvent event) {
var handler = configHandler.orElse(null);
if (handler != null) {
handler.accept(event);
}
}
/** /**
* Does this mod match the supplied mod? * Does this mod match the supplied mod?
@@ -147,14 +157,6 @@ public abstract class ModContainer {
*/ */
public abstract Object getMod(); public abstract Object getMod();
/**
* @return the mod bus group for this specific mod, or null if there is none.
* Leave null if you use {@link BusGroup#DEFAULT} for your mod lifecycle events.
*/
public BusGroup getModBusGroup() {
return null;
}
/** /**
* Accept an arbitrary event for processing by the mod. Probably posted to an event bus in the lower level container. * Accept an arbitrary event for processing by the mod. Probably posted to an event bus in the lower level container.
* @param e Event to accept * @param e Event to accept
@@ -5,14 +5,14 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import net.minecraftforge.fml.loading.LoadingModList;
import net.minecraftforge.forgespi.language.IModFileInfo; import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.language.IModInfo; import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.forgespi.language.ModFileScanData; import net.minecraftforge.forgespi.language.ModFileScanData;
import net.minecraftforge.fml.loading.moddiscovery.ModFile; import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo; import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.IModFile;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -30,36 +30,33 @@ import java.util.stream.Stream;
* Master list of all mods - game-side version. This is classloaded in the game scope and * Master list of all mods - game-side version. This is classloaded in the game scope and
* can dispatch game level events as a result. * can dispatch game level events as a result.
*/ */
public final class ModList { public class ModList {
private ModList() {} private static ModList INSTANCE;
private final List<IModFileInfo> modFiles;
private final List<IModInfo> sortedList;
private final Map<String, IModFileInfo> fileById;
private List<ModContainer> mods;
private Map<String, ModContainer> indexedMods;
private List<ModFileScanData> modFileScanData;
private List<ModContainer> sortedContainers;
private static final List<IModFileInfo> MOD_FILES; private ModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) {
private static final List<IModInfo> SORTED_LIST; this.modFiles = modFiles.stream().map(ModFile::getModFileInfo).toList();
private static final Map<String, IModFileInfo> FILE_BY_ID; this.sortedList = sortedList.stream().map(IModInfo.class::cast).toList();
private static List<ModContainer> mods;
private static Map<String, ModContainer> indexedMods;
private static List<ModContainer> sortedContainers;
static {
var loadingModFiles = LoadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList();
var loadingSortedList = LoadingModList.getMods();
var modFileInfos = MOD_FILES = loadingModFiles.stream().map(ModFile::getModFileInfo).toList();
SORTED_LIST = loadingSortedList.stream().map(IModInfo.class::cast).toList();
var byId = new HashMap<String, IModFileInfo>(); var byId = new HashMap<String, IModFileInfo>();
for (var file : modFileInfos) { for (var file : this.modFiles) {
for (var mod : file.getMods()) for (var mod : file.getMods())
byId.put(mod.getModId(), mod.getOwningFile()); byId.put(mod.getModId(), mod.getOwningFile());
} }
FILE_BY_ID = Map.copyOf(byId); this.fileById = Collections.unmodifiableMap(byId);
CrashReportCallables.registerCrashCallable("Mod List", ModList::crashReport); CrashReportCallables.registerCrashCallable("Mod List", this::crashReport);
} }
private static String getModContainerState(String modId) { private String getModContainerState(String modId) {
return getModContainerById(modId).map(ModContainer::getCurrentState).map(Object::toString).orElse("NONE"); return getModContainerById(modId).map(ModContainer::getCurrentState).map(Object::toString).orElse("NONE");
} }
private static String fileToLine(IModFile mf) { private String fileToLine(IModFile mf) {
var mainMod = mf.getModInfos().getFirst(); var mainMod = mf.getModInfos().getFirst();
return String.format(Locale.ENGLISH, "%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(), return String.format(Locale.ENGLISH, "%-50.50s|%-30.30s|%-30.30s|%-20.20s|%-10.10s|Manifest: %s", mf.getFileName(),
mainMod.getDisplayName(), mainMod.getDisplayName(),
@@ -69,92 +66,93 @@ public final class ModList {
((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE")); ((ModFileInfo)mf.getModFileInfo()).getCodeSigningFingerprint().orElse("NOSIGNATURE"));
} }
private static String crashReport() { private String crashReport() {
return "\n" + applyForEachModFile(ModList::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", "")); return "\n"+applyForEachModFile(this::fileToLine).collect(Collectors.joining("\n\t\t", "\t\t", ""));
} }
public static void init() {} public static ModList of(List<ModFile> modFiles, List<ModInfo> sortedList) {
INSTANCE = new ModList(modFiles, sortedList);
public static List<IModFileInfo> getModFiles() { return INSTANCE;
return MOD_FILES;
} }
public static IModFileInfo getModFileById(String modid) { public static ModList get() {
return FILE_BY_ID.get(modid); return INSTANCE;
} }
static void setLoadedMods(final List<ModContainer> modContainers) { public List<IModFileInfo> getModFiles() {
mods = modContainers; return modFiles;
sortedContainers = modContainers.stream().sorted(Comparator.comparingInt(c -> SORTED_LIST.indexOf(c.getModInfo()))).toList();
indexedMods = modContainers.stream().collect(Collectors.toUnmodifiableMap(ModContainer::getModId, Function.identity()));
} }
static void clearLoadedMods() { public IModFileInfo getModFileById(String modid) {
mods = List.of(); return this.fileById.get(modid);
indexedMods = Map.of(); }
sortedContainers = List.of();
void setLoadedMods(final List<ModContainer> modContainers) {
this.mods = modContainers;
this.sortedContainers = modContainers.stream().sorted(Comparator.comparingInt(c -> sortedList.indexOf(c.getModInfo()))).toList();
this.indexedMods = modContainers.stream().collect(Collectors.toMap(ModContainer::getModId, Function.identity()));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> Optional<T> getModObjectById(String modId) { public <T> Optional<T> getModObjectById(String modId) {
return getModContainerById(modId).map(ModContainer::getMod).map(o -> (T) o); return getModContainerById(modId).map(ModContainer::getMod).map(o -> (T) o);
} }
public static Optional<? extends ModContainer> getModContainerById(String modId) { public Optional<? extends ModContainer> getModContainerById(String modId) {
return Optional.ofNullable(indexedMods.get(modId)); return Optional.ofNullable(this.indexedMods.get(modId));
} }
public static Optional<? extends ModContainer> getModContainerByObject(Object obj) { public Optional<? extends ModContainer> getModContainerByObject(Object obj) {
return mods.stream().filter(mc -> mc.getMod() == obj).findFirst(); return mods.stream().filter(mc -> mc.getMod() == obj).findFirst();
} }
public static List<IModInfo> getMods() { public List<IModInfo> getMods() {
return SORTED_LIST; return this.sortedList;
} }
public static boolean isLoaded(String modTarget) { public boolean isLoaded(String modTarget) {
return indexedMods.containsKey(modTarget); return this.indexedMods.containsKey(modTarget);
} }
public static int size() { public int size() {
return mods.size(); return mods.size();
} }
public static List<ModFileScanData> getAllScanData() { public List<ModFileScanData> getAllScanData() {
final class LazyInit { if (modFileScanData == null) {
private LazyInit() {} modFileScanData = this.sortedList.stream().
private static final List<ModFileScanData> MOD_FILE_SCAN_DATA = SORTED_LIST.stream() map(IModInfo::getOwningFile).
.map(IModInfo::getOwningFile) filter(Objects::nonNull).
.filter(Objects::nonNull) map(IModFileInfo::getFile).
.map(IModFileInfo::getFile) distinct().
.distinct() map(IModFile::getScanResult).
.map(IModFile::getScanResult) collect(Collectors.toList());
.toList();
} }
return LazyInit.MOD_FILE_SCAN_DATA; return modFileScanData;
} }
public static void forEachModFile(Consumer<IModFile> fileConsumer) { public void forEachModFile(Consumer<IModFile> fileConsumer) {
MOD_FILES.stream().map(IModFileInfo::getFile).forEach(fileConsumer); modFiles.stream().map(IModFileInfo::getFile).forEach(fileConsumer);
} }
public static <T> Stream<T> applyForEachModFile(Function<IModFile, T> function) { public <T> Stream<T> applyForEachModFile(Function<IModFile, T> function) {
return MOD_FILES.stream().map(IModFileInfo::getFile).map(function); return modFiles.stream().map(IModFileInfo::getFile).map(function);
} }
public static void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) { public void forEachModContainer(BiConsumer<String, ModContainer> modContainerConsumer) {
indexedMods.forEach(modContainerConsumer); indexedMods.forEach(modContainerConsumer);
} }
public static void forEachModInOrder(Consumer<ModContainer> containerConsumer) { public void forEachModInOrder(Consumer<ModContainer> containerConsumer) {
sortedContainers.forEach(containerConsumer); this.sortedContainers.forEach(containerConsumer);
} }
public static List<ModContainer> getLoadedMods() { public List<ModContainer> getLoadedMods() {
return sortedContainers; return this.sortedContainers;
} }
public static <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) { public <T> Stream<T> applyForEachModContainer(Function<ModContainer, T> function) {
return indexedMods.values().stream().map(function); return indexedMods.values().stream().map(function);
} }
} }
@@ -5,11 +5,15 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import net.minecraftforge.eventbus.api.bus.BusGroup; import com.google.common.collect.ImmutableList;
import net.minecraftforge.fml.event.IModBusEvent; import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.loading.*; import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.fml.loading.ImmediateWindowHandler;
import net.minecraftforge.fml.loading.LoadingModList;
import net.minecraftforge.fml.loading.moddiscovery.InvalidModIdentifier; import net.minecraftforge.fml.loading.moddiscovery.InvalidModIdentifier;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo; import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.fml.loading.progress.ProgressMeter; import net.minecraftforge.fml.loading.progress.ProgressMeter;
import net.minecraftforge.fml.loading.progress.StartupNotificationManager; import net.minecraftforge.fml.loading.progress.StartupNotificationManager;
import net.minecraftforge.forgespi.language.IModInfo; import net.minecraftforge.forgespi.language.IModInfo;
@@ -66,76 +70,92 @@ import static net.minecraftforge.fml.Logging.LOADING;
* and completes the mod loading sequence.</dd> * and completes the mod loading sequence.</dd>
* </dl> * </dl>
*/ */
public final class ModLoader { public class ModLoader {
private ModLoader() {}
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private static final ArrayList<ModLoadingException> LOADING_EXCEPTIONS = new ArrayList<>(); private final LoadingModList loadingModList;
private static final ArrayList<ModLoadingWarning> LOADING_WARNINGS = new ArrayList<>();
private static final Consumer<String> STATUS_CONSUMER = StartupNotificationManager.modLoaderConsumer().orElse(_ -> {}); private final List<ModLoadingException> loadingExceptions;
private static final HashSet<IModLoadingState> COMPLETED_STATES = new HashSet<>(); private final Set<IModInfo> erroredModInfos;
private final List<ModLoadingWarning> loadingWarnings;
private final ModStateManager stateManager;
private static boolean loadingStateValid; private static boolean loadingStateValid;
private final Consumer<String> statusConsumer = StartupNotificationManager.modLoaderConsumer().orElse(msg -> {});
private final Set<IModLoadingState> completedStates = new HashSet<>();
private ModList modList;
private ModLoader() {
this.loadingModList = FMLLoader.getLoadingModList();
this.loadingExceptions = this.loadingModList.getErrors().stream()
.flatMap(ModLoadingException::fromEarlyException)
.collect(Collectors.toList());
this.loadingWarnings = this.loadingModList.getBrokenFiles().stream()
.map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName()))
.collect(Collectors.toList());
if (this.loadingExceptions.isEmpty()) {
this.erroredModInfos = Collections.emptySet();
} else {
this.erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
this.erroredModInfos.addAll(this.loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
}
this.loadingModList.getModFiles().stream()
.filter(ModFileInfo::missingLicense)
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(this.erroredModInfos::contains)) //Ignore files where any other mod already encountered an error
.map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
.forEach(this.loadingExceptions::add);
this.stateManager = new ModStateManager();
CrashReportCallables.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
CrashReportCallables.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
CrashReportCallables.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
CrashReportCallables.registerCrashCallable("ModLauncher services", ModLoader::computeModLauncherServiceList);
CrashReportCallables.registerCrashCallable("FML Language Providers", ModLoader::computeLanguageList);
}
private static String computeLanguageList() { private static String computeLanguageList() {
return "\n" + LanguageLoadingProvider return "\n" + FMLLoader.getLanguageLoadingProvider()
.applyForEach(lp -> lp.name() + '@' + lp.getClass().getPackage().getImplementationVersion()) .applyForEach(lp -> lp.name() + "@" + lp.getClass().getPackage().getImplementationVersion())
.collect(Collectors.joining("\n\t\t", "\t\t", "")); .collect(Collectors.joining("\n\t\t", "\t\t", ""));
} }
private static String computeModLauncherServiceList() { private static String computeModLauncherServiceList() {
final List<Map<String, String>> mods = FMLLoader.modLauncherModList(); final List<Map<String, String>> mods = FMLLoader.modLauncherModList();
return "\n" + mods.stream().map(mod -> mod.getOrDefault("file","nofile") + return "\n"+mods.stream().map(mod->mod.getOrDefault("file","nofile")+
' ' + mod.getOrDefault("name", "missing") + " "+mod.getOrDefault("name", "missing")+
' ' + mod.getOrDefault("type","NOTYPE") + " "+mod.getOrDefault("type","NOTYPE")+
' ' + mod.getOrDefault("description", "")). " "+mod.getOrDefault("description", "")).
collect(Collectors.joining("\n\t\t","\t\t","")); collect(Collectors.joining("\n\t\t","\t\t",""));
} }
public static ModLoader get() {
return LazyInit.INSTANCE;
}
private static final class LazyInit {
private static final ModLoader INSTANCE = new ModLoader();
private LazyInit() {}
}
/** /**
* Run on the primary starting thread by ClientModLoader and ServerModLoader * Run on the primary starting thread by ClientModLoader and ServerModLoader
* @param syncExecutor An executor to run tasks on the main thread * @param syncExecutor An executor to run tasks on the main thread
* @param parallelExecutor An executor to run tasks on a parallel loading thread pool * @param parallelExecutor An executor to run tasks on a parallel loading thread pool
* @param periodicTask Optional periodic task to perform on the main thread while other activities run * @param periodicTask Optional periodic task to perform on the main thread while other activities run
*/ */
public static void gatherAndInitializeMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) { public void gatherAndInitializeMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
var loadingExceptions = LoadingModList.getErrors().stream()
.flatMap(ModLoadingException::fromEarlyException)
.toList();
ModLoader.LOADING_EXCEPTIONS.addAll(loadingExceptions);
LOADING_WARNINGS.addAll(LoadingModList.getBrokenFiles().stream()
.map(file -> new ModLoadingWarning(null, ModLoadingStage.VALIDATE, InvalidModIdentifier.identifyJarProblem(file.getFilePath()).orElse("fml.modloading.brokenfile"), file.getFileName()))
.toList());
Set<IModInfo> erroredModInfos;
if (loadingExceptions.isEmpty()) {
erroredModInfos = Collections.emptySet();
} else {
erroredModInfos = Collections.newSetFromMap(new IdentityHashMap<>());
erroredModInfos.addAll(loadingExceptions.stream().map(ModLoadingException::getModInfo).toList());
}
LoadingModList.getModFiles().stream()
.filter(ModFileInfo::missingLicense)
.filter(modFileInfo -> modFileInfo.getMods().stream().noneMatch(erroredModInfos::contains)) //Ignore files where any other mod already encountered an error
.map(modFileInfo -> new ModLoadingException(null, ModLoadingStage.VALIDATE, "fml.modloading.missinglicense", null, modFileInfo.getFile()))
.forEach(LOADING_EXCEPTIONS::add);
CrashReportCallables.registerCrashCallable("ModLauncher", FMLLoader::getLauncherInfo);
CrashReportCallables.registerCrashCallable("ModLauncher launch target", FMLLoader::launcherHandlerName);
CrashReportCallables.registerCrashCallable("ModLauncher naming", FMLLoader::getNaming);
CrashReportCallables.registerCrashCallable("ModLauncher services", ModLoader::computeModLauncherServiceList);
CrashReportCallables.registerCrashCallable("FML Language Providers", ModLoader::computeLanguageList);
ForgeFeature.registerFeature("javaVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.BOTH, System.getProperty("java.version"))); ForgeFeature.registerFeature("javaVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.BOTH, System.getProperty("java.version")));
ForgeFeature.registerFeature("openGLVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.CLIENT, ImmediateWindowHandler.getGLVersion())); ForgeFeature.registerFeature("openGLVersion", ForgeFeature.VersionFeatureTest.forVersionString(IModInfo.DependencySide.CLIENT, ImmediateWindowHandler.getGLVersion()));
loadingStateValid = true; loadingStateValid = true;
FMLLoader.backgroundScanHandler.waitForScanToComplete(periodicTask); FMLLoader.backgroundScanHandler.waitForScanToComplete(periodicTask);
if (!LOADING_EXCEPTIONS.isEmpty()) { final ModList modList = ModList.of(loadingModList.getModFiles().stream().map(ModFileInfo::getFile).toList(),
LOGGER.fatal(CORE, "Error during pre-loading phase", LOADING_EXCEPTIONS.getFirst()); loadingModList.getMods());
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING"); if (!this.loadingExceptions.isEmpty()) {
ModList.clearLoadedMods(); LOGGER.fatal(CORE, "Error during pre-loading phase", loadingExceptions.getFirst());
statusConsumer.accept("ERROR DURING MOD LOADING");
modList.setLoadedMods(Collections.emptyList());
loadingStateValid = false; loadingStateValid = false;
throw new LoadingFailedException(LOADING_EXCEPTIONS); throw new LoadingFailedException(loadingExceptions);
} }
var failedBounds = new ArrayList<ForgeFeature.Bound>(); var failedBounds = new ArrayList<ForgeFeature.Bound>();
for (var mod : LoadingModList.getMods()) { for (var mod : loadingModList.getMods()) {
for (var feature : mod.getForgeFeatures()) { for (var feature : mod.getForgeFeatures()) {
if (!ForgeFeature.testFeature(FMLEnvironment.dist, feature)) if (!ForgeFeature.testFeature(FMLEnvironment.dist, feature))
failedBounds.add(feature); failedBounds.add(feature);
@@ -144,8 +164,8 @@ public final class ModLoader {
if (!failedBounds.isEmpty()) { if (!failedBounds.isEmpty()) {
LOGGER.fatal(CORE, "Failed to validate feature bounds for mods: {}", failedBounds); LOGGER.fatal(CORE, "Failed to validate feature bounds for mods: {}", failedBounds);
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING"); statusConsumer.accept("ERROR DURING MOD LOADING");
ModList.clearLoadedMods(); modList.setLoadedMods(Collections.emptyList());
loadingStateValid = false; loadingStateValid = false;
throw new LoadingFailedException(failedBounds.stream() throw new LoadingFailedException(failedBounds.stream()
.map(fb -> new ModLoadingException(fb.modInfo(), ModLoadingStage.CONSTRUCT, "fml.modloading.feature.missing", null, fb, ForgeFeature.featureValue(fb))) .map(fb -> new ModLoadingException(fb.modInfo(), ModLoadingStage.CONSTRUCT, "fml.modloading.feature.missing", null, fb, ForgeFeature.featureValue(fb)))
@@ -153,18 +173,18 @@ public final class ModLoader {
} }
final var modContainers = new HashMap<String, ModContainer>(); final var modContainers = new HashMap<String, ModContainer>();
for (var file : LoadingModList.getModFiles()) { for (var file : loadingModList.getModFiles()) {
var containers = buildMods(file.getFile()); var containers = this.buildMods(file.getFile());
for (var container : containers) for (var container : containers)
modContainers.put(container.getModId(), container); modContainers.put(container.getModId(), container);
} }
if (!LOADING_EXCEPTIONS.isEmpty()) { if (!loadingExceptions.isEmpty()) {
LOGGER.fatal(CORE, "Failed to initialize mod containers", LOADING_EXCEPTIONS.getFirst()); LOGGER.fatal(CORE, "Failed to initialize mod containers", loadingExceptions.getFirst());
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING"); statusConsumer.accept("ERROR DURING MOD LOADING");
ModList.clearLoadedMods(); modList.setLoadedMods(Collections.emptyList());
loadingStateValid = false; loadingStateValid = false;
throw new LoadingFailedException(LOADING_EXCEPTIONS); throw new LoadingFailedException(loadingExceptions);
} }
// Gather all dependencies, so we can make sure they have finished their transition events before we fire ours // Gather all dependencies, so we can make sure they have finished their transition events before we fire ours
@@ -187,47 +207,36 @@ public final class ModLoader {
} }
} }
ModList.setLoadedMods(modContainers.values().stream().toList()); modList.setLoadedMods(modContainers.values().stream().toList());
var stateList = ModStateManager.getStates(ModLoadingPhase.GATHER); this.modList = modList;
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum()); var stateList = stateManager.getStates(ModLoadingPhase.GATHER);
var progress = StartupMessageManager.addProgressBar("Mod Gather", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(this.modList)).sum());
for (IModLoadingState mls : stateList) { for (IModLoadingState mls : stateList) {
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress); dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
} }
progress.complete(); progress.complete();
} }
public static void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) { public void loadMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
var stateList = ModStateManager.getStates(ModLoadingPhase.LOAD); var stateList = stateManager.getStates(ModLoadingPhase.LOAD);
var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum()); var progress = StartupMessageManager.addProgressBar("Mod Loading", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
for (IModLoadingState mls : stateList) { for (IModLoadingState mls : stateList) {
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress); dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
} }
progress.complete(); progress.complete();
} }
public static void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) { public void finishMods(final ModWorkManager.DrivenExecutor syncExecutor, final Executor parallelExecutor, final Runnable periodicTask) {
var stateList = ModStateManager.getStates(ModLoadingPhase.COMPLETE); var stateList = stateManager.getStates(ModLoadingPhase.COMPLETE);
var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().getAsInt()).sum()); var progress = StartupMessageManager.addProgressBar("Mod Complete", stateList.stream().mapToInt(mls -> mls.size().applyAsInt(modList)).sum());
for (IModLoadingState mls : stateList) { for (IModLoadingState mls : stateList) {
dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress); dispatchAndHandleError(mls, syncExecutor, parallelExecutor, periodicTask, progress);
} }
statusConsumer.accept(String.format("Mod loading complete - %d mods loaded", this.modList.size()));
var modBusGroups = Set.of(
ModList.getLoadedMods().stream()
.map(ModContainer::getModBusGroup)
.filter(Objects::nonNull)
.toArray(BusGroup[]::new)
);
for (var modBusGroup : modBusGroups) {
parallelExecutor.execute(modBusGroup::trim);
}
parallelExecutor.execute(BusGroup.DEFAULT::trim);
STATUS_CONSUMER.accept("Mod loading complete - %d mods loaded".formatted(ModList.size()));
progress.complete(); progress.complete();
} }
private static void dispatchAndHandleError(IModLoadingState state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker, final ProgressMeter progressBar) { private void dispatchAndHandleError(IModLoadingState state, ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor, final Runnable ticker, final ProgressMeter progressBar) {
if (!isLoadingStateValid()) { if (!isLoadingStateValid()) {
LOGGER.error("Cowardly refusing to process mod state change request from {}", state); LOGGER.error("Cowardly refusing to process mod state change request from {}", state);
return; return;
@@ -235,25 +244,25 @@ public final class ModLoader {
progressBar.label(progressBar.name() + " working"); progressBar.label(progressBar.name() + " working");
syncExecutor.drive(ticker); syncExecutor.drive(ticker);
var inlineRunnable = state.inlineRunnable(); var inlineRunnable = state.inlineRunnable().orElse(null);
if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker); if (inlineRunnable != null) handleInlineTransition(inlineRunnable, state, syncExecutor, ticker);
var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar); var transition = state.buildTransition(syncExecutor, parallelExecutor, progressBar).orElse(null);
if (transition != null) waitForTransition(state, syncExecutor, ticker, transition); if (transition != null) waitForTransition(state, syncExecutor, ticker, transition);
COMPLETED_STATES.add(state); completedStates.add(state);
} }
private static void handleInlineTransition(final Runnable transition, final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker) { private void handleInlineTransition(final Consumer<ModList> transition, final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker) {
var pb = StartupMessageManager.addProgressBar("State transition " + state.name() + " running", 0); var pb = StartupMessageManager.addProgressBar("State transition " +state.name()+" running", 0);
syncExecutor.drive(ticker); syncExecutor.drive(ticker);
transition.run(); transition.accept(this.modList);
syncExecutor.drive(ticker); syncExecutor.drive(ticker);
pb.complete(); pb.complete();
syncExecutor.drive(ticker); syncExecutor.drive(ticker);
} }
private static void waitForTransition(final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker, final CompletableFuture<Void> transition) { private void waitForTransition(final IModLoadingState state, final ModWorkManager.DrivenExecutor syncExecutor, final Runnable ticker, final CompletableFuture<Void> transition) {
while (!transition.isDone()) { while (!transition.isDone()) {
syncExecutor.drive(ticker); syncExecutor.drive(ticker);
} }
@@ -267,7 +276,7 @@ public final class ModLoader {
.anyMatch(obj -> !(obj instanceof ModLoadingException)); .anyMatch(obj -> !(obj instanceof ModLoadingException));
if (hasNotModLoadingEx) { if (hasNotModLoadingEx) {
LOGGER.fatal("Encountered non-modloading exceptions!", e); LOGGER.fatal("Encountered non-modloading exceptions!", e);
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING"); statusConsumer.accept("ERROR DURING MOD LOADING");
throw e; throw e;
} }
@@ -276,12 +285,12 @@ public final class ModLoader {
.map(ModLoadingException.class::cast) .map(ModLoadingException.class::cast)
.toList(); .toList();
LOGGER.fatal(LOADING,"Failed to complete lifecycle event {}, {} errors found", state.name(), modLoadingExceptions.size()); LOGGER.fatal(LOADING,"Failed to complete lifecycle event {}, {} errors found", state.name(), modLoadingExceptions.size());
STATUS_CONSUMER.accept("ERROR DURING MOD LOADING"); statusConsumer.accept("ERROR DURING MOD LOADING");
throw new LoadingFailedException(modLoadingExceptions); throw new LoadingFailedException(modLoadingExceptions);
} }
} }
private static List<ModContainer> buildMods(final IModFile modFile) { private List<ModContainer> buildMods(final IModFile modFile) {
final Map<String, IModInfo> modInfoMap = new HashMap<>(); final Map<String, IModInfo> modInfoMap = new HashMap<>();
for (var mod : modFile.getModFileInfo().getMods()) for (var mod : modFile.getModFileInfo().getMods())
modInfoMap.put(mod.getModId(), mod); modInfoMap.put(mod.getModId(), mod);
@@ -311,14 +320,14 @@ public final class ModLoader {
missingMods.removeAll(modIds); missingMods.removeAll(modIds);
LOGGER.fatal(LOADING, "The following mods are missing, but have classes in the jar: {}", missingMods); LOGGER.fatal(LOADING, "The following mods are missing, but have classes in the jar: {}", missingMods);
LOADING_EXCEPTIONS.add(new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingclasses", null, modFile.getFilePath())); loadingExceptions.add(new ModLoadingException(null, ModLoadingStage.CONSTRUCT, "fml.modloading.missingclasses", null, modFile.getFilePath()));
} }
// remove errored mod containers // remove errored mod containers
return containers.stream().filter(mc -> mc.modLoadingStage != ModLoadingStage.ERROR).toList(); return containers.stream().filter(mc -> mc.modLoadingStage != ModLoadingStage.ERROR).toList();
} }
private static ModContainer buildModContainerFromTOML(final IModFile modFile, final Map<String, IModInfo> modInfoMap, private ModContainer buildModContainerFromTOML(final IModFile modFile, final Map<String, IModInfo> modInfoMap,
final String modId, final IModLanguageProvider.IModLanguageLoader languageLoader final String modId, final IModLanguageProvider.IModLanguageLoader languageLoader
) { ) {
try { try {
@@ -330,7 +339,7 @@ public final class ModLoader {
return languageLoader.loadMod(info, modFile.getScanResult(), FMLLoader.getGameLayer()); return languageLoader.loadMod(info, modFile.getScanResult(), FMLLoader.getGameLayer());
} catch (ModLoadingException mle) { } catch (ModLoadingException mle) {
// exceptions are caught and added to the error list for later handling // exceptions are caught and added to the error list for later handling
LOADING_EXCEPTIONS.add(mle); loadingExceptions.add(mle);
// return an errored container instance here, because we tried and failed building a container. // return an errored container instance here, because we tried and failed building a container.
return new ErroredModContainer(); return new ErroredModContainer();
} }
@@ -344,64 +353,66 @@ public final class ModLoader {
return loadingStateValid; return loadingStateValid;
} }
public static boolean hasCompletedState(IModLoadingState state) { public boolean hasCompletedState(final String stateName) {
return COMPLETED_STATES.contains(state); IModLoadingState state = stateManager.findState(stateName);
return completedStates.contains(state);
} }
public static <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) { public <T extends IModBusEvent> void runEventGenerator(Function<ModContainer, T> generator) {
if (!loadingStateValid) { if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event generator to a broken mod state"); LOGGER.error("Cowardly refusing to send event generator to a broken mod state");
return; return;
} }
for (var mod : ModList.getLoadedMods()) for (var mod : ModList.get().getLoadedMods())
mod.acceptEvent(generator.apply(mod)); mod.acceptEvent(generator.apply(mod));
} }
public static <T extends IModBusEvent> void postEvent(T e) { public <T extends IModBusEvent> void postEvent(T e) {
var cls = e.getClass();
if (!loadingStateValid) { if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName()); LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
return; return;
} }
for (var mod : ModList.getLoadedMods()) for (var mod : ModList.get().getLoadedMods())
mod.acceptEvent(e); mod.acceptEvent(e);
} }
public static <T extends IModBusEvent> T postEventWithReturn(T e) { public <T extends IModBusEvent> T postEventWithReturn(T e) {
if (!loadingStateValid) { if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName()); LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
return e; return e;
} }
for (var mod : ModList.getLoadedMods()) for (var mod : ModList.get().getLoadedMods())
mod.acceptEvent(e); mod.acceptEvent(e);
return e; return e;
} }
@SuppressWarnings("removal") @SuppressWarnings("removal")
public static <T extends IModBusEvent> void postEventWrapContainerInModOrder(T event) { public <T extends IModBusEvent> void postEventWrapContainerInModOrder(T event) {
postEventWithWrapInModOrder(event, postEventWithWrapInModOrder(event,
(mc, _) -> ModLoadingContext.get().setActiveContainer(mc), (mc, e) -> ModLoadingContext.get().setActiveContainer(mc),
(_, _) -> ModLoadingContext.get().setActiveContainer(null) (mc, e) -> ModLoadingContext.get().setActiveContainer(null)
); );
} }
public static <T extends IModBusEvent> void postEventWithWrapInModOrder(T e, BiConsumer<ModContainer, T> pre, BiConsumer<ModContainer, T> post) { public <T extends IModBusEvent> void postEventWithWrapInModOrder(T e, BiConsumer<ModContainer, T> pre, BiConsumer<ModContainer, T> post) {
if (!loadingStateValid) { if (!loadingStateValid) {
LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName()); LOGGER.error("Cowardly refusing to send event {} to a broken mod state", e.getClass().getName());
return; return;
} }
for (var mod : ModList.getLoadedMods()) { for (var mod : ModList.get().getLoadedMods()) {
pre.accept(mod, e); pre.accept(mod, e);
mod.acceptEvent(e); mod.acceptEvent(e);
post.accept(mod, e); post.accept(mod, e);
} }
} }
public static List<ModLoadingWarning> getWarnings() { public List<ModLoadingWarning> getWarnings() {
return List.copyOf(LOADING_WARNINGS); return ImmutableList.copyOf(this.loadingWarnings);
} }
public static void addWarning(ModLoadingWarning warning) { public void addWarning(ModLoadingWarning warning) {
LOADING_WARNINGS.add(warning); this.loadingWarnings.add(warning);
} }
private static boolean runningDataGen = false; private static boolean runningDataGen = false;
@@ -19,24 +19,31 @@ public class ModLoadingContext {
private Object languageExtension; private Object languageExtension;
/** /**
* @deprecated Use the context provided by your language loader in your mod's constructor. Example for Java mods: {@snippet : * @deprecated Use the context provided by your language loader in your mod's constructor
* @Mod("examplemod")
* public final class ExampleMod {
* public ExampleMod(FMLJavaModLoadingContext context) {
* // Use context from the param instead of FMLJavaModLoadingContext.get() or ModLoadingContext.get()
* }
* }}
*/ */
@Deprecated(forRemoval = true, since="1.21.1") @Deprecated(forRemoval = true, since="1.21.1")
public static ModLoadingContext get() { public static ModLoadingContext get() {
return context.get(); return context.get();
} }
void setActiveContainer(final ModContainer container) { /**
* @deprecated Going to be moved to ForgeHooks for Internal use.
*/
@Deprecated(forRemoval = true, since="1.21.1")
public void setActiveContainer(final ModContainer container) {
this.activeContainer = container; this.activeContainer = container;
this.languageExtension = container == null ? null : container.contextExtension.get(); this.languageExtension = container == null ? null : container.contextExtension.get();
} }
/**
* Going to be moved to ForgeHooks for Internal use.
* @deprecated Override/Use {@link ModLoadingContext#getContainer()}
*/
@Deprecated(forRemoval = true, since="1.21.1")
public ModContainer getActiveContainer() {
return activeContainer == null ? ModList.get().getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!")) : activeContainer;
}
/** /**
* @deprecated Going to be moved to ForgeHooks for Internal use. * @deprecated Going to be moved to ForgeHooks for Internal use.
*/ */
@@ -45,10 +52,11 @@ public class ModLoadingContext {
return activeContainer == null ? "minecraft" : activeContainer.getNamespace(); return activeContainer == null ? "minecraft" : activeContainer.getNamespace();
} }
/**
* @return {@link ModLoadingContext#getActiveContainer()} by default.
*/
public ModContainer getContainer() { public ModContainer getContainer() {
return activeContainer == null return getActiveContainer();
? ModList.getModContainerById("minecraft").orElseThrow(()->new RuntimeException("Where is minecraft???!"))
: activeContainer;
} }
/** /**
@@ -100,7 +108,8 @@ public class ModLoadingContext {
} }
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) { public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec) {
if (spec.isEmpty()) { if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it. // This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId()); LOGGER.debug("Attempted to register an empty config for type {} on mod {}", type, getContainer().getModId());
return; return;
@@ -110,7 +119,8 @@ public class ModLoadingContext {
} }
public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) { public void registerConfig(ModConfig.Type type, IConfigSpec<?> spec, String fileName) {
if (spec.isEmpty()) { if (spec.isEmpty())
{
// This handles the case where a mod tries to register a config, without any options configured inside it. // This handles the case where a mod tries to register a config, without any options configured inside it.
LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName); LOGGER.debug("Attempted to register an empty config for type {} on mod {} using file name {}", type, getContainer().getModId(), fileName);
return; return;
@@ -119,6 +129,7 @@ public class ModLoadingContext {
getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName)); getContainer().addConfig(new ModConfig(type, spec, getContainer(), fileName));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T extension() { public <T> T extension() {
return (T)languageExtension; return (T)languageExtension;
@@ -6,14 +6,13 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import net.minecraftforge.fml.loading.progress.ProgressMeter; import net.minecraftforge.fml.loading.progress.ProgressMeter;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.IntSupplier; import java.util.function.ToIntFunction;
import java.util.function.Supplier;
/** /**
* Implementation of the {@link IModLoadingState} interface. * Implementation of the {@link IModLoadingState} interface.
@@ -25,26 +24,27 @@ import java.util.function.Supplier;
* @param inlineRunnable an optional runnable, which runs before starting the transition from this state to the next * @param inlineRunnable an optional runnable, which runs before starting the transition from this state to the next
* @param transition optional state transition information * @param transition optional state transition information
*/ */
@NullMarked
public record ModLoadingState( public record ModLoadingState(
String name, String name,
String previous, String previous,
Supplier<String> message, Function<ModList, String> message,
IntSupplier size, ToIntFunction<ModList> size,
ModLoadingPhase phase, ModLoadingPhase phase,
@Nullable Runnable inlineRunnable, Optional<Consumer<ModList>> inlineRunnable,
@Nullable IModStateTransition transition Optional<IModStateTransition> transition
) implements IModLoadingState { ) implements IModLoadingState {
@Override @Override
public @Nullable CompletableFuture<Void> buildTransition( public Optional<CompletableFuture<Void>> buildTransition(
final Executor syncExecutor, final Executor syncExecutor,
final Executor parallelExecutor, final Executor parallelExecutor,
final ProgressMeter progressBar, final ProgressMeter progressBar,
final Function<Executor, CompletableFuture<Void>> preSyncTask, final Function<Executor, CompletableFuture<Void>> preSyncTask,
final Function<Executor, CompletableFuture<Void>> postSyncTask final Function<Executor, CompletableFuture<Void>> postSyncTask
) { ) {
if (transition == null) return null; var transition = this.transition.orElse(null);
return transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask); return transition == null
? Optional.empty()
: Optional.ofNullable(transition.build(name, syncExecutor, parallelExecutor, progressBar, preSyncTask, postSyncTask));
} }
/** /**
@@ -59,7 +59,7 @@ public record ModLoadingState(
*/ */
@Deprecated(since = "1.21.3", forRemoval = true) @Deprecated(since = "1.21.3", forRemoval = true)
public static ModLoadingState empty(final String name, final String previous, final ModLoadingPhase phase) { public static ModLoadingState empty(final String name, final String previous, final ModLoadingPhase phase) {
return new ModLoadingState(name, previous, () -> "", () -> 0, phase, null, null); return of(name, phase).after(previous).empty();
} }
/** /**
@@ -93,7 +93,7 @@ public record ModLoadingState(
*/ */
@Deprecated(since = "1.21.3", forRemoval = true) @Deprecated(since = "1.21.3", forRemoval = true)
public static ModLoadingState withTransition(final String name, final String previous, public static ModLoadingState withTransition(final String name, final String previous,
final Supplier<String> message, final ModLoadingPhase phase, final Function<ModList, String> message, final ModLoadingPhase phase,
final IModStateTransition transition) { final IModStateTransition transition) {
return of(name, phase).after(previous).message(message).withTransition(transition); return of(name, phase).after(previous).message(message).withTransition(transition);
} }
@@ -112,7 +112,7 @@ public record ModLoadingState(
*/ */
@Deprecated(since = "1.21.3", forRemoval = true) @Deprecated(since = "1.21.3", forRemoval = true)
public static ModLoadingState withInline(final String name, final String previous, final ModLoadingPhase phase, public static ModLoadingState withInline(final String name, final String previous, final ModLoadingPhase phase,
final Runnable inline) { final Consumer<ModList> inline) {
return of(name, phase).after(previous).withInline(inline); return of(name, phase).after(previous).withInline(inline);
} }
@@ -120,28 +120,12 @@ public record ModLoadingState(
return new Builder(name, phase); return new Builder(name, phase);
} }
@Override public static class Builder {
public boolean equals(Object o) {
return o instanceof ModLoadingState that
&& this.phase == that.phase
&& this.name.equals(that.name)
&& this.previous.equals(that.previous);
}
@Override
public int hashCode() {
int result = phase.hashCode();
result = 31 * result + name.hashCode();
result = 31 * result + previous.hashCode();
return result;
}
public static final class Builder {
private final String name; private final String name;
private final ModLoadingPhase phase; private final ModLoadingPhase phase;
private String after = ""; private String after;
private @Nullable Supplier<String> message = null; private Function<ModList, String> message = null;
private @Nullable IntSupplier size = null; private ToIntFunction<ModList> size = null;
private Builder(final String name, final ModLoadingPhase phase) { private Builder(final String name, final ModLoadingPhase phase) {
this.name = name; this.name = name;
@@ -154,28 +138,28 @@ public record ModLoadingState(
return this; return this;
} }
public Builder message(final String value) { return message(() -> value); } public Builder message(final String value) { return message(ml -> value); }
public Builder message(final Supplier<String> value) { public Builder message(final Function<ModList, String> value) {
this.message = value; this.message = value;
return this; return this;
} }
public Builder size(final int value) { return size(() -> value); } public Builder size(final int value) { return size(ml -> value); }
public Builder size(final IntSupplier value) { public Builder size(final ToIntFunction<ModList> value) {
this.size = value; this.size = value;
return this; return this;
} }
public ModLoadingState empty() { public ModLoadingState empty() {
return new ModLoadingState(name, after, message != null ? message : () -> "", size != null ? size : () -> 0, phase, null, null); return new ModLoadingState(name, after, message != null ? message : ml -> "", size != null ? size : ml -> 0, phase, Optional.empty(), Optional.empty());
} }
public ModLoadingState withTransition(final IModStateTransition transition) { public ModLoadingState withTransition(final IModStateTransition transition) {
return new ModLoadingState(name, after, message != null ? message : () -> "Processing transition " + name, size != null ? size : ModList::size, phase, null, transition); return new ModLoadingState(name, after, message != null ? message : ml -> "Processing transition " + name, size != null ? size : ModList::size, phase, Optional.empty(), Optional.of(transition));
} }
public ModLoadingState withInline(final Runnable inline) { public ModLoadingState withInline(final Consumer<ModList> inline) {
return new ModLoadingState(name, after, message != null ? message : () -> "Processing work " + name, size != null ? size : () -> 0, phase, inline, null); return new ModLoadingState(name, after, message != null ? message : ml -> "Processing work " + name, size != null ? size : ml -> 0, phase, Optional.of(inline), Optional.empty());
} }
} }
} }
@@ -5,27 +5,41 @@
package net.minecraftforge.fml; package net.minecraftforge.fml;
import com.google.common.collect.Streams;
import net.minecraftforge.forgespi.language.IModInfo; import net.minecraftforge.forgespi.language.IModInfo;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
/** public class ModLoadingWarning {
* @param modInfo Mod info for mod with warning /**
* @param warningStage The stage where this warning was encountered * Mod Info for mod with warning
* @param i18nMessage I18N message to use for display */
* @param context Context for message display private final IModInfo modInfo;
*/ /**
public record ModLoadingWarning(IModInfo modInfo, ModLoadingStage warningStage, String i18nMessage, List<Object> context) { * The stage where this warning was encountered
public ModLoadingWarning(final IModInfo modInfo, final ModLoadingStage warningStage, final String i18nMessage, Object... context) { */
this(modInfo, warningStage, i18nMessage, List.of(context)); private final ModLoadingStage warningStage;
}
public ModLoadingWarning { /**
context = List.copyOf(context); * I18N message to use for display
*/
private final String i18nMessage;
/**
* Context for message display
*/
private final List<Object> context;
public ModLoadingWarning(final IModInfo modInfo, final ModLoadingStage warningStage, final String i18nMessage, Object... context) {
this.modInfo = modInfo;
this.warningStage = warningStage;
this.i18nMessage = i18nMessage;
this.context = Arrays.asList(context);
} }
public String formatToString() { public String formatToString() {
return Bindings.getMessageParser().get().parseMessage(i18nMessage, Stream.concat(Stream.of(modInfo, warningStage), context.stream()).toArray()); return Bindings.getMessageParser().get().parseMessage(i18nMessage, Streams.concat(Stream.of(modInfo, warningStage), context.stream()).toArray());
} }
} }
@@ -15,19 +15,18 @@ import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
public final class ModStateManager { public class ModStateManager {
private ModStateManager() {} private final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
private static final EnumMap<ModLoadingPhase, List<IModLoadingState>> stateMap;
static { public ModStateManager() {
final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class); final var sp = ServiceLoader.load(FMLLoader.getGameLayer(), IModStateProvider.class);
stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, _ -> {}) this.stateMap = ServiceLoaderUtils.streamWithErrorHandling(sp, sce->{})
.map(IModStateProvider::getAllStates) .map(IModStateProvider::getAllStates)
.flatMap(List::stream) .flatMap(List::stream)
.collect(Collectors.groupingBy(IModLoadingState::phase, () -> new EnumMap<>(ModLoadingPhase.class), Collectors.toUnmodifiableList())); .collect(Collectors.groupingBy(IModLoadingState::phase, ()->new EnumMap<>(ModLoadingPhase.class), Collectors.toUnmodifiableList()));
} }
public static List<IModLoadingState> getStates(final ModLoadingPhase phase) { public List<IModLoadingState> getStates(final ModLoadingPhase phase) {
var nodes = stateMap.get(phase); var nodes = stateMap.get(phase);
var lookup = nodes.stream().collect(Collectors.toMap(IModLoadingState::name, Function.identity())); var lookup = nodes.stream().collect(Collectors.toMap(IModLoadingState::name, Function.identity()));
@@ -41,14 +40,12 @@ public final class ModStateManager {
return TopologicalSort.topologicalSort(graph, Comparator.comparingInt(nodes::indexOf)).stream().filter(st->st!=dummy).toList(); return TopologicalSort.topologicalSort(graph, Comparator.comparingInt(nodes::indexOf)).stream().filter(st->st!=dummy).toList();
} }
public static IModLoadingState findState(final String stateName) { public IModLoadingState findState(final String stateName) {
var result = stateMap.values() return stateMap.values()
.stream() .stream()
.flatMap(List::stream) .flatMap(List::stream)
.filter(mls -> mls.name().equals(stateName)) .filter(mls -> mls.name().equals(stateName))
.findFirst() .findFirst()
.orElse(null); .orElseThrow(() -> new IllegalArgumentException("Unknown IModLoadingState: " + stateName));
if (result != null) return result;
else throw new IllegalArgumentException("Unknown IModLoadingState: " + stateName);
} }
} }
@@ -24,7 +24,7 @@ import net.minecraftforge.fml.event.IModBusEvent;
import net.minecraftforge.fml.loading.progress.ProgressMeter; import net.minecraftforge.fml.loading.progress.ProgressMeter;
@ApiStatus.Internal @ApiStatus.Internal
final class ModStateTransitionHelper { class ModStateTransitionHelper {
static final IModStateTransition NOOP = new NoopTransition(); static final IModStateTransition NOOP = new NoopTransition();
record NoopTransition() implements IModStateTransition { record NoopTransition() implements IModStateTransition {
@Override @Override
@@ -62,30 +62,7 @@ final class ModStateTransitionHelper {
} }
} }
/// Same as [#completableFutureFromExceptionList(List)] but specialised for a single future record FutureResult<V>(V value, Throwable exception){}
static <V> CompletionStage<Void> completableFutureFromException(FutureResult<V> t) {
if (t.exception() == null) {
return CompletableFuture.completedFuture(null);
} else {
var exception = t.exception();
CompletableFuture<Void> cf = new CompletableFuture<>();
RuntimeException accumulator = new RuntimeException();
cf.completeExceptionally(accumulator);
if (exception instanceof CompletionException) {
exception = exception.getCause();
}
if (exception.getSuppressed().length != 0) {
for (Throwable throwable : exception.getSuppressed()) {
accumulator.addSuppressed(throwable);
}
} else {
accumulator.addSuppressed(exception);
}
return cf;
}
}
record FutureResult<V>(V value, Throwable exception) {}
static <V> CompletableFuture<List<FutureResult<V>>> gather(Collection<? extends CompletableFuture<? extends V>> futures) { static <V> CompletableFuture<List<FutureResult<V>>> gather(Collection<? extends CompletableFuture<? extends V>> futures) {
var list = new ArrayList<FutureResult<V>>(futures.size()); var list = new ArrayList<FutureResult<V>>(futures.size());
@@ -99,17 +76,25 @@ final class ModStateTransitionHelper {
results[i] = raw.whenComplete((result, exception) -> list.set(i, new FutureResult<>(result, exception))); results[i] = raw.whenComplete((result, exception) -> list.set(i, new FutureResult<>(result, exception)));
} }
return CompletableFuture.allOf(results).handle((_, _)->null).thenApply(_ -> list); return CompletableFuture.allOf(results).handle((r, th)->null).thenApply(res -> list);
} }
private static <T extends IModBusEvent> CompletableFuture<Void> addCompletableFutureTaskForModDispatch( private static <T extends IModBusEvent> void addCompletableFutureTaskForModDispatch(
final IModStateTransition transition,
final Executor executor, final Executor executor,
final List<CompletableFuture<Void>> completableFutures,
final ProgressMeter progressBar, final ProgressMeter progressBar,
final EventGenerator<T> eventGenerator, final EventGenerator<T> eventGenerator,
final BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextState final BiFunction<ModLoadingStage, Throwable, ModLoadingStage> nextState
) { ) {
@SuppressWarnings("removal")
var preDispatchHook = getHook(transition.preDispatchHook(), executor, eventGenerator);
if (preDispatchHook != null)
completableFutures.add(preDispatchHook);
var modFutures = new LinkedHashMap<String, CompletableFuture<Void>>(); var modFutures = new LinkedHashMap<String, CompletableFuture<Void>>();
for (var mod : ModList.getLoadedMods()) { for (var mod : ModList.get().getLoadedMods()) {
CompletableFuture<Void> parent = null; CompletableFuture<Void> parent = null;
if (mod.dependencies.isEmpty()) { if (mod.dependencies.isEmpty()) {
@@ -135,7 +120,7 @@ final class ModStateTransitionHelper {
handler.run(); handler.run();
mod.acceptEvent(eventGenerator.apply(mod)); mod.acceptEvent(eventGenerator.apply(mod));
}, executor) }, executor)
.whenComplete((_, exception) -> { .whenComplete((mc, exception) -> {
mod.modLoadingStage = nextState.apply(mod.modLoadingStage, exception); mod.modLoadingStage = nextState.apply(mod.modLoadingStage, exception);
progressBar.increment(); progressBar.increment();
ModLoadingContext.get().setActiveContainer(null); ModLoadingContext.get().setActiveContainer(null);
@@ -144,7 +129,20 @@ final class ModStateTransitionHelper {
modFutures.put(mod.getModId(), dispatch); modFutures.put(mod.getModId(), dispatch);
} }
return gather(modFutures.values()).thenComposeAsync(ModStateTransitionHelper::completableFutureFromExceptionList, executor); var dispatch = gather(modFutures.values()).thenComposeAsync(ModStateTransitionHelper::completableFutureFromExceptionList, executor);
completableFutures.add(dispatch);
@SuppressWarnings("removal")
var postDispatchHook = getHook(transition.preDispatchHook(), executor, eventGenerator);
if (postDispatchHook != null)
completableFutures.add(postDispatchHook);
}
private static <T extends IModBusEvent> CompletableFuture<Void> getHook(BiFunction<Executor, ? extends EventGenerator<?>, CompletableFuture<Void>> hook, Executor executor, EventGenerator<T> eventGenerator) {
if (hook == null || hook == IModStateTransition.NULL_HOOK) return null;
@SuppressWarnings("unchecked")
var hookTyped = (BiFunction<Executor, EventGenerator<T>, CompletableFuture<Void>>)hook;
return hookTyped.apply(executor, eventGenerator);
} }
static <T extends IModBusEvent> CompletableFuture<Void> build( static <T extends IModBusEvent> CompletableFuture<Void> build(
@@ -156,25 +154,31 @@ final class ModStateTransitionHelper {
final Function<Executor, CompletableFuture<Void>> preSyncTask, final Function<Executor, CompletableFuture<Void>> preSyncTask,
final Function<Executor, CompletableFuture<Void>> postSyncTask final Function<Executor, CompletableFuture<Void>> postSyncTask
) { ) {
CompletableFuture<Void> future; List<CompletableFuture<Void>> futures = new ArrayList<>();
final var executor = transition.threadSelector().apply(syncExecutor, parallelExecutor); final var executor = transition.threadSelector().apply(syncExecutor, parallelExecutor);
final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor); @SuppressWarnings({ "removal", "unchecked" })
CompletableFuture<Void> postEventDispatchCF = preSyncTaskCF var events = transition.eventFunctionStream().get().map(f -> (EventGenerator<T>)f).toList();
.thenRunAsync(() -> progressBar.label(progressBar.name() + ": dispatching " + name), parallelExecutor); for (int x = 0; x < events.size(); x++) {
var gen = events.get(x);
var eventGenerator = transition.eventFunction(); BiFunction<ModLoadingStage, Throwable, ModLoadingStage> state = x == events.size() - 1
if (eventGenerator != null) { ? transition.nextModLoadingStage()
BiFunction<ModLoadingStage, Throwable, ModLoadingStage> state = transition.nextModLoadingStage(); : ModLoadingStage::currentState;
future = addCompletableFutureTaskForModDispatch(executor, progressBar, eventGenerator, state); addCompletableFutureTaskForModDispatch(transition, executor, futures, progressBar, gen, state);
final CompletableFuture<Void> eventDispatchCF = future.handle(FutureResult::new)
.thenCompose(ModStateTransitionHelper::completableFutureFromException);
postEventDispatchCF = postEventDispatchCF.thenComposeAsync(_ -> eventDispatchCF, parallelExecutor);
} }
postEventDispatchCF = postEventDispatchCF.thenRun(() -> postSyncTask.apply(syncExecutor)); final CompletableFuture<Void> preSyncTaskCF = preSyncTask.apply(syncExecutor);
final CompletableFuture<Void> eventDispatchCF = gather(futures).thenCompose(ModStateTransitionHelper::completableFutureFromExceptionList);
final CompletableFuture<Void> postEventDispatchCF = preSyncTaskCF
.thenApplyAsync(n -> {
progressBar.label(progressBar.name() + ": dispatching " + name);
return null;
}, parallelExecutor)
.thenComposeAsync(n -> eventDispatchCF, parallelExecutor)
.thenApply(r -> {
postSyncTask.apply(syncExecutor);
return null;
});
return transition.finalActivityGenerator().apply(syncExecutor, postEventDispatchCF); return transition.finalActivityGenerator().apply(syncExecutor, postEventDispatchCF);
} }
} }
@@ -14,12 +14,25 @@ import java.util.concurrent.locks.LockSupport;
import static net.minecraftforge.fml.Logging.LOADING; import static net.minecraftforge.fml.Logging.LOADING;
public final class ModWorkManager { public class ModWorkManager {
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1); private static final long PARK_TIME = TimeUnit.MILLISECONDS.toNanos(1);
public sealed interface DrivenExecutor extends Executor { public interface DrivenExecutor extends Executor {
void drive(Runnable ticker); boolean selfDriven();
boolean driveOne();
default void drive(Runnable ticker) {
if (!selfDriven()) {
ticker.run();
while (true) {
if (!driveOne()) break;
}
} else {
// park for a bit so other threads can schedule
LockSupport.parkNanos(PARK_TIME);
}
}
} }
private record SyncExecutor(ConcurrentLinkedDeque<Runnable> tasks) implements DrivenExecutor { private record SyncExecutor(ConcurrentLinkedDeque<Runnable> tasks) implements DrivenExecutor {
@@ -27,7 +40,8 @@ public final class ModWorkManager {
this(new ConcurrentLinkedDeque<>()); this(new ConcurrentLinkedDeque<>());
} }
private boolean driveOne() { @Override
public boolean driveOne() {
final Runnable task = tasks.pollFirst(); final Runnable task = tasks.pollFirst();
if (task != null) { if (task != null) {
task.run(); task.run();
@@ -36,29 +50,30 @@ public final class ModWorkManager {
} }
@Override @Override
public void execute(final Runnable command) { public boolean selfDriven() {
tasks.addLast(command); return false;
} }
@Override @Override
public void drive(Runnable ticker) { public void execute(final Runnable command) {
ticker.run(); tasks.addLast(command);
while (true) {
if (!driveOne()) break;
}
} }
} }
private record WrappingExecutor(Executor wrapped) implements DrivenExecutor { private record WrappingExecutor(Executor wrapped) implements DrivenExecutor {
@Override @Override
public void execute(final Runnable command) { public boolean selfDriven() {
wrapped.execute(command); return true;
} }
@Override @Override
public void drive(Runnable ticker) { public boolean driveOne() {
// Park for a bit so other threads can schedule return false;
LockSupport.parkNanos(PARK_TIME); }
@Override
public void execute(final Runnable command) {
wrapped.execute(command);
} }
} }
@@ -43,7 +43,7 @@ public final class OptionalMod<T>
private T getValue() private T getValue()
{ {
if (!searched) { if (!searched) {
this.value = ModList.<T>getModObjectById(this.modId).orElse(null); this.value = ModList.get().<T>getModObjectById(this.modId).orElse(null);
searched = true; searched = true;
} }
return this.value; return this.value;
@@ -9,8 +9,8 @@ import java.util.concurrent.Executor;
import java.util.function.BinaryOperator; import java.util.function.BinaryOperator;
public enum ThreadSelector implements BinaryOperator<Executor> { public enum ThreadSelector implements BinaryOperator<Executor> {
SYNC((sync, _) -> sync), SYNC((sync, parallel) -> sync),
PARALLEL((_, parallel) -> parallel); PARALLEL((sync, parallel) -> parallel);
private final BinaryOperator<Executor> selector; private final BinaryOperator<Executor> selector;
@@ -93,8 +93,8 @@ public class VersionChecker {
return; return;
} }
var mc = ModList.getModContainerById("minecraft"); var mc = ModList.get().getModContainerById("minecraft");
var forge = ModList.getModContainerById("forge"); var forge = ModList.get().getModContainerById("forge");
this.mcVersion = mc.get().getModInfo().getVersion().toString(); this.mcVersion = mc.get().getModInfo().getVersion().toString();
this.agent = "Java-http-client/" + System.getProperty("java.version") this.agent = "Java-http-client/" + System.getProperty("java.version")
@@ -223,7 +223,7 @@ public class VersionChecker {
// Gather a list of mods that have opted in to this update system by providing a URL. // Gather a list of mods that have opted in to this update system by providing a URL.
private static List<IModInfo> gatherMods() { private static List<IModInfo> gatherMods() {
List<IModInfo> ret = new LinkedList<>(); List<IModInfo> ret = new LinkedList<>();
for (IModInfo info : ModList.getMods()) { for (IModInfo info : ModList.get().getMods()) {
if (info.getUpdateURL().isPresent()) if (info.getUpdateURL().isPresent())
ret.add(info); ret.add(info);
} }
@@ -8,7 +8,8 @@ package net.minecraftforge.fml.config;
import com.electronwill.nightconfig.core.CommentedConfig; import com.electronwill.nightconfig.core.CommentedConfig;
import com.electronwill.nightconfig.core.file.CommentedFileConfig; import com.electronwill.nightconfig.core.file.CommentedFileConfig;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.loading.FMLPaths; import net.minecraftforge.fml.loading.FMLPaths;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.Marker; import org.slf4j.Marker;
@@ -18,54 +19,57 @@ import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public final class ConfigTracker { public class ConfigTracker {
private ConfigTracker() {}
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
static final Marker CONFIG = MarkerFactory.getMarker("CONFIG"); static final Marker CONFIG = MarkerFactory.getMarker("CONFIG");
private static final ConcurrentHashMap<String, ModConfig> FILE_MAP = new ConcurrentHashMap<>(); public static final ConfigTracker INSTANCE = new ConfigTracker();
private static final Map<ModConfig.Type, Set<ModConfig>> CONFIG_SETS = Map.of( private final ConcurrentHashMap<String, ModConfig> fileMap;
ModConfig.Type.CLIENT, Collections.synchronizedSet(new LinkedHashSet<>()), private final EnumMap<ModConfig.Type, Set<ModConfig>> configSets;
ModConfig.Type.COMMON, Collections.synchronizedSet(new LinkedHashSet<>()), private final ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> configsByMod;
ModConfig.Type.SERVER, Collections.synchronizedSet(new LinkedHashSet<>())
);
private static final ConcurrentHashMap<String, Map<ModConfig.Type, ModConfig>> CONFIGS_BY_MOD = new ConcurrentHashMap<>();
static void trackConfig(final ModConfig config) { private ConfigTracker() {
if (FILE_MAP.containsKey(config.getFileName())) { this.fileMap = new ConcurrentHashMap<>();
LOGGER.error(CONFIG,"Detected config file conflict {} between {} and {}", config.getFileName(), FILE_MAP.get(config.getFileName()).getModId(), config.getModId()); this.configSets = new EnumMap<>(ModConfig.Type.class);
this.configsByMod = new ConcurrentHashMap<>();
this.configSets.put(ModConfig.Type.CLIENT, Collections.synchronizedSet(new LinkedHashSet<>()));
this.configSets.put(ModConfig.Type.COMMON, Collections.synchronizedSet(new LinkedHashSet<>()));
// this.configSets.put(ModConfig.Type.PLAYER, new ConcurrentSkipListSet<>());
this.configSets.put(ModConfig.Type.SERVER, Collections.synchronizedSet(new LinkedHashSet<>()));
}
void trackConfig(final ModConfig config) {
if (this.fileMap.containsKey(config.getFileName())) {
LOGGER.error(CONFIG,"Detected config file conflict {} between {} and {}", config.getFileName(), this.fileMap.get(config.getFileName()).getModId(), config.getModId());
throw new RuntimeException("Config conflict detected!"); throw new RuntimeException("Config conflict detected!");
} }
FILE_MAP.put(config.getFileName(), config); this.fileMap.put(config.getFileName(), config);
CONFIG_SETS.get(config.getType()).add(config); this.configSets.get(config.getType()).add(config);
CONFIGS_BY_MOD.computeIfAbsent(config.getModId(), _ -> new EnumMap<>(ModConfig.Type.class)).put(config.getType(), config); this.configsByMod.computeIfAbsent(config.getModId(), (k)->new EnumMap<>(ModConfig.Type.class)).put(config.getType(), config);
LOGGER.debug(CONFIG, "Config file {} for {} tracking", config.getFileName(), config.getModId()); LOGGER.debug(CONFIG, "Config file {} for {} tracking", config.getFileName(), config.getModId());
} }
public static void loadConfigs(ModConfig.Type type, Path configBasePath) { public void loadConfigs(ModConfig.Type type, Path configBasePath) {
LOGGER.debug(CONFIG, "Loading configs type {}", type); LOGGER.debug(CONFIG, "Loading configs type {}", type);
for (ModConfig config : CONFIG_SETS.get(type)) { for (ModConfig config : this.configSets.get(type)) {
openConfig(config, configBasePath); openConfig(config, configBasePath);
} }
} }
// TODO: [FML] This is only called for the server (outside of forceUnload) // TODO: [FML] This is only called for the server (outside of forceUnload)
// rethink config implementation for eventual FML rewrite // rethink config implementation for eventual FML rewrite
public static void unloadConfigs(ModConfig.Type type, Path configBasePath) { public void unloadConfigs(ModConfig.Type type, Path configBasePath) {
LOGGER.debug(CONFIG, "Unloading configs type {}", type); LOGGER.debug(CONFIG, "Unloading configs type {}", type);
for (ModConfig config : CONFIG_SETS.get(type)) { for (ModConfig config : this.configSets.get(type)) {
closeConfig(config, configBasePath); closeConfig(config, configBasePath);
} }
ConfigFileTypeHandler.get(type).stopWatcher(); ConfigFileTypeHandler.get(type).stopWatcher();
} }
// If there is a better way to do this, please tell me. Because this is FUCKED // If there is a better way to do this, please tell me. Because this is FUCKED
public static void forceUnload() { public void forceUnload() {
// This is how ModStateProvider handles loading configs. So we're doing the same but with unloadConfigs instead // This is how ModStateProvider handles loading configs. So we're doing the same but with unloadConfigs instead
if (FMLEnvironment.dist.isClient()) DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> this.unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get()));
unloadConfigs(ModConfig.Type.CLIENT, FMLPaths.CONFIGDIR.get()); this.unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
unloadConfigs(ModConfig.Type.COMMON, FMLPaths.CONFIGDIR.get());
// just in case server watcher is still alive somehow... // just in case server watcher is still alive somehow...
ConfigFileTypeHandler.get(ModConfig.Type.SERVER).stopWatcher(); ConfigFileTypeHandler.get(ModConfig.Type.SERVER).stopWatcher();
@@ -92,8 +96,8 @@ public final class ConfigTracker {
} }
} }
public static void loadDefaultServerConfigs() { public void loadDefaultServerConfigs() {
CONFIG_SETS.get(ModConfig.Type.SERVER).forEach(modConfig -> { configSets.get(ModConfig.Type.SERVER).forEach(modConfig -> {
final CommentedConfig commentedConfig = CommentedConfig.inMemory(); final CommentedConfig commentedConfig = CommentedConfig.inMemory();
modConfig.getSpec().correct(commentedConfig); modConfig.getSpec().correct(commentedConfig);
modConfig.setConfigData(commentedConfig); modConfig.setConfigData(commentedConfig);
@@ -101,16 +105,16 @@ public final class ConfigTracker {
}); });
} }
public static String getConfigFileName(String modId, ModConfig.Type type) { public String getConfigFileName(String modId, ModConfig.Type type) {
return Optional.ofNullable(CONFIGS_BY_MOD.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)). return Optional.ofNullable(configsByMod.getOrDefault(modId, Collections.emptyMap()).getOrDefault(type, null)).
map(ModConfig::getFullPath).map(Object::toString).orElse(null); map(ModConfig::getFullPath).map(Object::toString).orElse(null);
} }
public static Map<ModConfig.Type, Set<ModConfig>> configSets() { public Map<ModConfig.Type, Set<ModConfig>> configSets() {
return CONFIG_SETS; return configSets;
} }
public static ConcurrentHashMap<String, ModConfig> fileMap() { public ConcurrentHashMap<String, ModConfig> fileMap() {
return FILE_MAP; return fileMap;
} }
} }
@@ -13,7 +13,6 @@ import java.util.function.Function;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public interface IConfigEvent { public interface IConfigEvent {
// TODO: [FML] Get rid of this indirection somehow
record ConfigConfig(Function<ModConfig, IConfigEvent> loading, Function<ModConfig, IConfigEvent> reloading, @Nullable Function<ModConfig, IConfigEvent> unloading) {} record ConfigConfig(Function<ModConfig, IConfigEvent> loading, Function<ModConfig, IConfigEvent> reloading, @Nullable Function<ModConfig, IConfigEvent> unloading) {}
ConfigConfig CONFIGCONFIG = Bindings.getConfigConfiguration().get(); ConfigConfig CONFIGCONFIG = Bindings.getConfigConfiguration().get();
@@ -13,6 +13,8 @@ import net.minecraftforge.fml.loading.StringUtils;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Locale;
import java.util.concurrent.Callable;
public class ModConfig public class ModConfig
{ {
@@ -29,7 +31,7 @@ public class ModConfig
this.fileName = fileName; this.fileName = fileName;
this.container = container; this.container = container;
this.configHandler = ConfigFileTypeHandler.get(type); this.configHandler = ConfigFileTypeHandler.get(type);
ConfigTracker.trackConfig(this); ConfigTracker.INSTANCE.trackConfig(this);
} }
public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer activeContainer) { public ModConfig(final Type type, final IConfigSpec<?> spec, final ModContainer activeContainer) {
@@ -38,9 +40,8 @@ public class ModConfig
private static String defaultConfigName(Type type, String modId) { private static String defaultConfigName(Type type, String modId) {
// config file name would be "forge-client.toml" and "forge-server.toml" // config file name would be "forge-client.toml" and "forge-server.toml"
return modId + '-' + type.extension() + ".toml"; return String.format(Locale.ROOT, "%s-%s.toml", modId, type.extension());
} }
public Type getType() { public Type getType() {
return type; return type;
} }
@@ -8,22 +8,16 @@ package net.minecraftforge.fml.event;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.InheritableEvent; import net.minecraftforge.eventbus.api.event.InheritableEvent;
import org.jspecify.annotations.NonNull;
/** /**
* Marker interface for mod lifecycle events dispatched on the * Marker interface for events dispatched on the ModLifecycle event bus instead of the primary event bus
* {@linkplain net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext#getModBusGroup() mod BusGroup} instead
* of the {@linkplain BusGroup#DEFAULT default BusGroup}.
*
* @apiNote Each mod gets its own unique mod BusGroup instance, obtained from the mod loading context. Most events
* should go on the default BusGroup.
*/ */
public interface IModBusEvent extends InheritableEvent { public interface IModBusEvent extends InheritableEvent {
/** /**
* @param modEventBusGroup Obtained from {@link net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext#getModBusGroup()} or your language provider's equivalent. * @param modEventBusGroup Obtained from {@link net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext#getModBusGroup()} or your language provider's equivalent.
* @param eventClass The event type you want to get the associated bus for. * @param eventClass The event type you want to get the associated bus for.
*/ */
static <T extends IModBusEvent> @NonNull EventBus<@NonNull T> getBus(@NonNull BusGroup modEventBusGroup, @NonNull Class<T> eventClass) { static <T extends IModBusEvent> EventBus<T> getBus(BusGroup modEventBusGroup, Class<T> eventClass) {
// Do not copy! Temporary solution until the FML rewrite is complete. May throw in future // Do not copy! Temporary solution until the FML rewrite is complete. May throw in future
// without prior notice. // without prior notice.
// //
@@ -7,11 +7,8 @@ package net.minecraftforge.fml.util.thread;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
/** public class EffectiveSide
* Attempts to determine the effect side of the current thread, based on know threads in networking. {
* This is not guaranteed to be correct, and modders should use other methods to determine the logical side when possible.
*/
public class EffectiveSide {
public static LogicalSide get() { public static LogicalSide get() {
final ThreadGroup group = Thread.currentThread().getThreadGroup(); final ThreadGroup group = Thread.currentThread().getThreadGroup();
return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : LogicalSide.CLIENT; return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : LogicalSide.CLIENT;
@@ -7,13 +7,11 @@ package net.minecraftforge.fml.util.thread;
import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.LogicalSide;
public final class SidedThreadGroups { public final class SidedThreadGroups
{
public static final SidedThreadGroup CLIENT = new SidedThreadGroup(LogicalSide.CLIENT); public static final SidedThreadGroup CLIENT = new SidedThreadGroup(LogicalSide.CLIENT);
public static final SidedThreadGroup SERVER = new SidedThreadGroup(LogicalSide.SERVER); public static final SidedThreadGroup SERVER = new SidedThreadGroup(LogicalSide.SERVER);
public static SidedThreadGroup get(boolean client) { private SidedThreadGroups() {
return client ? CLIENT : SERVER;
} }
private SidedThreadGroups() { }
} }
@@ -46,6 +46,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.IntConsumer; import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.stream.Collector; import java.util.stream.Collector;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -68,7 +70,7 @@ import static org.lwjgl.opengl.GL32C.*;
* Based on the prior ClientVisualization, with some personal touches. * Based on the prior ClientVisualization, with some personal touches.
*/ */
public class DisplayWindow implements ImmediateWindowProvider { public class DisplayWindow implements ImmediateWindowProvider {
private static final int[][] GL_VERSIONS = new int[][] {{4,6}, {4,5}, {4,4}, {4,3}, {4,2}, {4,1}, {4,0}, {3,3}}; private static final int[][] GL_VERSIONS = new int[][] {{4,6}, {4,5}, {4,4}, {4,3}, {4,2}, {4,1}, {4,0}, {3,3}, {3,2}};
private static final Logger LOGGER = LoggerFactory.getLogger("EARLYDISPLAY"); private static final Logger LOGGER = LoggerFactory.getLogger("EARLYDISPLAY");
private final AtomicBoolean animationTimerTrigger = new AtomicBoolean(true); private final AtomicBoolean animationTimerTrigger = new AtomicBoolean(true);
@@ -312,18 +314,17 @@ public class DisplayWindow implements ImmediateWindowProvider {
LOGGER.error("ERROR DISPLAY\n"+msgBuilder); LOGGER.error("ERROR DISPLAY\n"+msgBuilder);
// we show the display on a new dedicated thread // we show the display on a new dedicated thread
Executors.newSingleThreadExecutor().submit(()-> { Executors.newSingleThreadExecutor().submit(()-> {
var res = TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", msgBuilder.toString(), "yesno", "error", 0); var res = TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", msgBuilder.toString(), "yesno", "error", false);
if (res != 0) { if (res) {
try { try {
Desktop.getDesktop().browse(URI.create(ERROR_URL)); Desktop.getDesktop().browse(URI.create(ERROR_URL));
} catch (IOException ioe) { } catch (IOException ioe) {
TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", "Sadly, we couldn't open your browser.\nVisit " + ERROR_URL, "ok", "error", 0); TinyFileDialogs.tinyfd_messageBox("Minecraft: Forge", "Sadly, we couldn't open your browser.\nVisit " + ERROR_URL, "ok", "error", false);
} }
} }
System.exit(1); System.exit(1);
}); });
} }
/** /**
* Called to initialize the window when preparing for the Render Thread. * Called to initialize the window when preparing for the Render Thread.
* *
@@ -528,7 +529,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
* *
* @return the Window we own. * @return the Window we own.
*/ */
public long setupMinecraftWindow(final int width, final int height, final String title, final long monitorSupplier, final Supplier<Object> backend) { public long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitorSupplier) {
// wait for the window to actually be initialized // wait for the window to actually be initialized
try { try {
this.initializationFuture.get(30, TimeUnit.SECONDS); this.initializationFuture.get(30, TimeUnit.SECONDS);
@@ -548,11 +549,11 @@ public class DisplayWindow implements ImmediateWindowProvider {
var renderlockticket = false; var renderlockticket = false;
do { do {
try { try {
renderlockticket = renderLock.tryAcquire(100, TimeUnit.MILLISECONDS); renderlockticket = renderLock.tryAcquire(100, TimeUnit.MILLISECONDS);
if (++tries > 9) { if (++tries > 9) {
Thread.dumpStack(); Thread.dumpStack();
crashElegantly("We seem to be having trouble handing off the window, tried for 1 second"); crashElegantly("We seem to be having trouble handing off the window, tried for 1 second");
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.interrupted(); Thread.interrupted();
} }
@@ -562,7 +563,7 @@ public class DisplayWindow implements ImmediateWindowProvider {
glfwMakeContextCurrent(window); glfwMakeContextCurrent(window);
// Set the title to what the game wants // Set the title to what the game wants
glfwSetWindowTitle(window, title); glfwSetWindowTitle(window, title.get());
glfwSwapInterval(0); glfwSwapInterval(0);
// Clean up our hooks // Clean up our hooks
glfwSetFramebufferSizeCallback(window, null).free(); glfwSetFramebufferSizeCallback(window, null).free();
@@ -116,7 +116,7 @@ public class RenderElement {
} }
public static RenderElement forgeVersionOverlay(SimpleFont font, String version) { public static RenderElement forgeVersionOverlay(SimpleFont font, String version) {
return new RenderElement(RenderElement.initializeText(font, (bb, _, ctx)-> return new RenderElement(RenderElement.initializeText(font, (bb, fnt, ctx)->
font.generateVerticesForTexts(ctx.scaledWidth() - font.stringWidth(version) - 10, font.generateVerticesForTexts(ctx.scaledWidth() - font.stringWidth(version) - 10,
ctx.scaledHeight() - font.lineSpacing() + font.descent() - 10, bb, ctx.scaledHeight() - font.lineSpacing() + font.descent() - 10, bb,
new SimpleFont.DisplayText(version, ctx.colourScheme.foreground().packedint(RenderElement.globalAlpha))))); new SimpleFont.DisplayText(version, ctx.colourScheme.foreground().packedint(RenderElement.globalAlpha)))));
@@ -178,11 +178,11 @@ public class RenderElement {
var colour = (alpha << 24) | 0xFFFFFF; var colour = (alpha << 24) | 0xFFFFFF;
Renderer bar; Renderer bar;
if (pm.steps() == 0) { if (pm.steps() == 0) {
bar = progressBar(ctx->new int[] {(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _->colour, frame -> indeterminateBar(frame, cnt == 0)); bar = progressBar(ctx->new int[] {(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, f->colour, frame -> indeterminateBar(frame, cnt == 0));
} else { } else {
bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pm.progress()}); bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y + font.lineSpacing() - font.descent(), BAR_WIDTH * ctx.scale()}, f -> colour, f -> new float[]{0f, pm.progress()});
} }
Renderer label = (bb, ctx, _) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx); Renderer label = (bb, ctx, frame) -> renderText(font, text((ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, pm.label().getText(), colour), bb, ctx);
return bar.then(label); return bar.then(label);
} }
private static float[] indeterminateBar(int frame, boolean isActive) { private static float[] indeterminateBar(int frame, boolean isActive) {
@@ -198,9 +198,9 @@ public class RenderElement {
var y = 10 * context.scale(); var y = 10 * context.scale();
PerformanceInfo pi = context.performance(); PerformanceInfo pi = context.performance();
final int colour = hsvToRGB((1.0f - (float)Math.pow(pi.memory(), 1.5f)) / 3f, 1.0f, 0.5f); final int colour = hsvToRGB((1.0f - (float)Math.pow(pi.memory(), 1.5f)) / 3f, 1.0f, 0.5f);
var bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, BAR_WIDTH * ctx.scale()}, _ -> colour, _ -> new float[]{0f, pi.memory()}); var bar = progressBar(ctx -> new int[]{(ctx.scaledWidth() - BAR_WIDTH * ctx.scale()) / 2, y, BAR_WIDTH * ctx.scale()}, f -> colour, f -> new float[]{0f, pi.memory()});
var width = font.stringWidth(pi.text()); var width = font.stringWidth(pi.text());
Renderer label = (bb, ctx, _) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx); Renderer label = (bb, ctx, frame) -> renderText(font, text(ctx.scaledWidth() / 2 - width / 2, y + 18, pi.text(), context.colourScheme.foreground().packedint(globalAlpha)), bb, ctx);
bar.then(label).accept(buffer, context, frameNumber); bar.then(label).accept(buffer, context, frameNumber);
} }
@@ -250,7 +250,7 @@ public class RenderElement {
} }
private static Renderer initializeText(SimpleFont font, TextGenerator textGenerator) { private static Renderer initializeText(SimpleFont font, TextGenerator textGenerator) {
return (bb, context, _) -> renderText(font, textGenerator, bb, context); return (bb, context, frame) -> renderText(font, textGenerator, bb, context);
} }
private static void renderText(final SimpleFont font, final TextGenerator textGenerator, final SimpleBufferBuilder bb, final DisplayContext context) { private static void renderText(final SimpleFont font, final TextGenerator textGenerator, final SimpleBufferBuilder bb, final DisplayContext context) {
@@ -262,7 +262,7 @@ public class RenderElement {
} }
private static TextGenerator text(int x, int y, String text, int colour) { private static TextGenerator text(int x, int y, String text, int colour) {
return (bb, font, _) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour)); return (bb, font, context) -> font.generateVerticesForTexts(x, y, bb, new SimpleFont.DisplayText(text, colour));
} }
private static Renderer initializeTexture(final String textureFileName, int size, int textureNumber, TextureRenderer positionAndColour) { private static Renderer initializeTexture(final String textureFileName, int size, int textureNumber, TextureRenderer positionAndColour) {
+1 -21
View File
@@ -26,6 +26,7 @@ dependencies {
api(libs.apache.commons) api(libs.apache.commons)
api(libs.bundles.night.config) api(libs.bundles.night.config)
api(libs.modlauncher) api(libs.modlauncher)
api(libs.coremods)
api(libs.mojang.logging) api(libs.mojang.logging)
api(libs.jarjar.selector) api(libs.jarjar.selector)
api(libs.jarjar.meta) api(libs.jarjar.meta)
@@ -35,7 +36,6 @@ dependencies {
implementation(libs.accesstransformers) implementation(libs.accesstransformers)
implementation(libs.terminalconsoleappender) implementation(libs.terminalconsoleappender)
implementation(libs.jimfs) implementation(libs.jimfs)
implementation(libs.roimfs)
// Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated // Needed because we have a custom log4j plugin, and they removed package scanning and require a data file to be generated
implementation(libs.log4j.core) implementation(libs.log4j.core)
@@ -103,31 +103,11 @@ tasks.register('writeForgeVersionJson') {
} }
} }
tasks.register('jarJarOptionsJson', net.minecraftforge.forge.tasks.JarJarMetadataOptions) {
metadataFile = project.file('src/main/resources/jarjar_options.json')
// This is resolved too early by cpw.mods.modlauncher.TransformationServicesHandler.discoverServices(DiscoveryData) But eventually...
//add(libs.mixin, 'org/spongepowered/asm/mixin/Mixin.class')
add(libs.mixinextras.forge) {
containedJarMetadata {
path = ''
}
resource = 'com/llamalad7/mixinextras/platform/forge/MixinExtrasConfigPlugin.class'
layer = 'GAMELIBRARY'
id = 'mixinextras'
nested = true
}
}
tasks.named('generateResources').configure { tasks.named('generateResources').configure {
dependsOn('eclipseJdt') dependsOn('eclipseJdt')
dependsOn('eclipseJdtApt') dependsOn('eclipseJdtApt')
dependsOn('eclipseFactorypath') dependsOn('eclipseFactorypath')
dependsOn('writeForgeVersionJson') dependsOn('writeForgeVersionJson')
dependsOn('jarJarOptionsJson')
}
tasks.named('sourcesJar') {
dependsOn('jarJarOptionsJson')
} }
eclipse { eclipse {
@@ -34,10 +34,11 @@ import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
* }</code> * }</code>
* </pre> * </pre>
*/ */
public final class CapabilityTokenSubclass implements ILaunchPluginService { public class CapabilityTokenSubclass implements ILaunchPluginService {
private static final String FUNC_NAME = "getType"; private static final String FUNC_NAME = "getType";
private static final String FUNC_DESC = "()Ljava/lang/String;"; private static final String FUNC_DESC = "()Ljava/lang/String;";
private static final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; // Don't directly reference this to prevent class loading. private static final String CAP_INJECT = "net/minecraftforge/common/capabilities/CapabilityToken"; //Don't directly reference this to prevent class loading.
@Override @Override
public String name() { public String name() {
@@ -55,11 +56,8 @@ public final class CapabilityTokenSubclass implements ILaunchPluginService {
String internalName = classType.getInternalName(); String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/")) if (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"))
return NAY; return NAY;
if (internalName.startsWith("net/minecraftforge/common/capabilities/"))
return YAY;
return internalName.contains("$") ? YAY : NAY; // Anonymous subclasses only return YAY;
} }
@Override @Override
@@ -72,7 +70,7 @@ public final class CapabilityTokenSubclass implements ILaunchPluginService {
} }
return ComputeFlags.SIMPLE_REWRITE; return ComputeFlags.SIMPLE_REWRITE;
} else if (CAP_INJECT.equals(classNode.superName)) { } else if (CAP_INJECT.equals(classNode.superName)) {
var cls = new Object() { String value = null; }; Holder cls = new Holder();
SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful. SignatureReader reader = new SignatureReader(classNode.signature); // Having a node version of this would probably be useful.
reader.accept(new SignatureVisitor(Opcodes.ASM9) { reader.accept(new SignatureVisitor(Opcodes.ASM9) {
@@ -108,4 +106,8 @@ public final class CapabilityTokenSubclass implements ILaunchPluginService {
return ComputeFlags.NO_REWRITE; return ComputeFlags.NO_REWRITE;
} }
} }
private static final class Holder {
String value;
}
} }
@@ -0,0 +1,131 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fml.common.asm;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
/**
* Removes the final modifier from fields with the @ObjectHolder annotation, prevents the JITer from in lining them so our runtime replacements can work.
* Will also de-finalize all fields in on class level annotations.
*/
public class ObjectHolderDefinalize implements ILaunchPluginService {
// Hardcoded map of vanilla classes that should have object holders for each field of the given registry type.
// IMPORTANT: Updates to this collection must be reflected in ObjectHolderRegistry. Duplicated cuz classloaders, yay!
// Classnames are validated in ObjectHolderRegistry.
private static final Map<String, VanillaObjectHolderData> VANILLA_OBJECT_HOLDERS = Stream.of(
new VanillaObjectHolderData("net.minecraft.world.level.block.Blocks", "block", "net.minecraft.world.level.block.Block"),
new VanillaObjectHolderData("net.minecraft.world.item.Items", "item", "net.minecraft.world.item.Item"),
new VanillaObjectHolderData("net.minecraft.world.item.enchantment.Enchantments", "enchantment", "net.minecraft.world.item.enchantment.Enchantment"),
new VanillaObjectHolderData("net.minecraft.world.effect.MobEffects", "mob_effect", "net.minecraft.world.effect.MobEffect"),
new VanillaObjectHolderData("net.minecraft.core.particles.ParticleTypes", "particle_type", "net.minecraft.core.particles.ParticleType"),
new VanillaObjectHolderData("net.minecraft.sounds.SoundEvents", "sound_event", "net.minecraft.sounds.SoundEvent")
).collect(Collectors.toUnmodifiableMap(VanillaObjectHolderData::holderClass, Function.identity()));
private static final Set<String> VANILLA_OBJECT_HOLDER_CLASSES = VANILLA_OBJECT_HOLDERS.keySet().stream()
.map(it -> it.replace('.', '/'))
.collect(Collectors.toUnmodifiableSet());
private static final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
private static final int PUBLIC_STATIC_FINAL_FLAGS = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
@Override
public String name() {
return "object_holder_definalize";
}
private static final EnumSet<Phase> YAY = EnumSet.of(Phase.AFTER);
private static final EnumSet<Phase> NAY = EnumSet.noneOf(Phase.class);
@Override
public EnumSet<Phase> handlesClass(Type classType, boolean isEmpty) {
if (isEmpty)
return NAY;
// Let's skip processing classes that definitely don't have object holders
String internalName = classType.getInternalName();
// Forge classes that aren't in the debug package (that package is used for tests)
if (internalName.startsWith("net/minecraftforge/") && !internalName.substring(18).contains("debug"))
return NAY;
// Vanilla classes that don't have object holders
if (internalName.startsWith("com/mojang/"))
return NAY;
// ...except specific ones we added to the VANILLA_OBJECT_HOLDERS map
if (internalName.startsWith("net/minecraft/") && !VANILLA_OBJECT_HOLDER_CLASSES.contains(internalName))
return NAY;
return YAY;
}
private static boolean hasHolder(List<AnnotationNode> lst) {
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
}
@SuppressWarnings("unused")
private String getValue(List<AnnotationNode> lst)
{
AnnotationNode ann = lst.stream().filter(n -> n.desc.equals(OBJECT_HOLDER)).findFirst().get();
if (ann.values != null)
{
for (int x = 0; x < ann.values.size() - 1; x += 2) {
if (ann.values.get(x).equals("value")) {
return (String)ann.values.get(x + 1);
}
}
}
return null;
}
@Override
public int processClassWithFlags(final Phase phase, final ClassNode classNode, final Type classType, final String reason)
{
final AtomicBoolean changes = new AtomicBoolean();
//Must be public static finals, and non-array objects
//Fix Annotated Fields before injecting from class level
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL; //Strip final
f.access |= Opcodes.ACC_SYNTHETIC; //Add Synthetic so we can check in runtime. ? Good idea?
changes.compareAndSet(false, prev != f.access);
});
if (VANILLA_OBJECT_HOLDERS.containsKey(classType.getClassName())) //Class level, de-finalize all fields and add @ObjectHolder to them!
{
classNode.fields.stream().filter(f -> ((f.access & PUBLIC_STATIC_FINAL_FLAGS) == PUBLIC_STATIC_FINAL_FLAGS) && f.desc.startsWith("L")).forEach(f ->
{
int prev = f.access;
f.access &= ~Opcodes.ACC_FINAL;
f.access |= Opcodes.ACC_SYNTHETIC;
/*if (!hasHolder(f.visibleAnnotations)) //Add field level annotation, doesn't do anything until after we figure out how ASMDataTable is gatherered
{
if (value == null)
f.visitAnnotation(OBJECT_HOLDER, true);
else
f.visitAnnotation(OBJECT_HOLDER, true).visit("value", value + ":" + f.name.toLowerCase());
}*/
changes.compareAndSet(false, prev != f.access);
});
}
return changes.get() ? ComputeFlags.SIMPLE_REWRITE : ComputeFlags.NO_REWRITE;
}
private record VanillaObjectHolderData(String holderClass, String registryName, String registryType) {}
}
@@ -7,9 +7,11 @@ package net.minecraftforge.fml.common.asm;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.LoadingModList; import net.minecraftforge.fml.loading.LoadingModList;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import org.objectweb.asm.Label; import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type; import org.objectweb.asm.Type;
@@ -49,7 +51,7 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
private static final class LazyInit { private static final class LazyInit {
private LazyInit() {} private LazyInit() {}
private static final boolean ANY_MODS = LoadingModList.getMods().size() > 2; // 2: forge, minecraft private static final boolean ANY_MODS = LoadingModList.get().getMods().size() > 2; // 2: forge, minecraft
} }
@Override @Override
@@ -58,10 +60,10 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
return NAY; return NAY;
String internalName = classType.getInternalName(); String internalName = classType.getInternalName();
if (internalName.startsWith("net/minecraft/client/model") || internalName.startsWith("net/minecraft/world")) if (internalName.startsWith("net/minecraftforge/") || internalName.startsWith("com/mojang/"))
return YAY; return NAY;
return NAY; return YAY;
} }
@Override @Override
@@ -73,6 +75,11 @@ public class RuntimeEnumExtender implements ILaunchPluginService {
if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName())) if (!classNode.interfaces.contains(MARKER_IFACE.getInternalName()))
return ComputeFlags.NO_REWRITE; return ComputeFlags.NO_REWRITE;
if (!classNode.name.startsWith("net/minecraft/")) {
LOGGER.warn("IExtensibleEnum found on non-Minecraft class: {}", classType.getClassName());
LOGGER.warn("This behaviour is deprecated for removal and will have no effect in a future MC release. Please use a record with static final field instances instead.");
}
Type array = Type.getType("[" + classType.getDescriptor()); Type array = Type.getType("[" + classType.getDescriptor());
String arrayDesc = array.getDescriptor(); String arrayDesc = array.getDescriptor();
@@ -109,7 +109,7 @@ public class FMLConfig
} }
if (!configSpec.isCorrect(configData)) { if (!configSpec.isCorrect(configData)) {
LOGGER.warn(CORE, "Configuration file {} is not correct. Correcting", configFile); LOGGER.warn(CORE, "Configuration file {} is not correct. Correcting", configFile);
configSpec.correct(configData, (_, path, incorrectValue, correctedValue) -> configSpec.correct(configData, (action, path, incorrectValue, correctedValue) ->
LOGGER.info(CORE, "Incorrect key {} was corrected from {} to {}", path, incorrectValue, correctedValue)); LOGGER.info(CORE, "Incorrect key {} was corrected from {} to {}", path, incorrectValue, correctedValue));
} }
configData.putAllComments(configComments); configData.putAllComments(configComments);
@@ -20,8 +20,8 @@ public class FMLEnvironment
public static final boolean secureJarsEnabled = FMLLoader.isSecureJarEnabled(); public static final boolean secureJarsEnabled = FMLLoader.isSecureJarEnabled();
static void setupInteropEnvironment(IEnvironment environment) { static void setupInteropEnvironment(IEnvironment environment) {
environment.computePropertyIfAbsent(IEnvironment.Keys.NAMING.get(), _->naming); environment.computePropertyIfAbsent(IEnvironment.Keys.NAMING.get(), v->naming);
environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), _->dist); environment.computePropertyIfAbsent(Environment.Keys.DIST.get(), v->dist);
} }
public static class Keys { public static class Keys {
@@ -16,6 +16,7 @@ import net.minecraftforge.accesstransformer.service.AccessTransformerService;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.loading.targets.CommonLaunchHandler; import net.minecraftforge.fml.loading.targets.CommonLaunchHandler;
import net.minecraftforge.forgespi.Environment; import net.minecraftforge.forgespi.Environment;
import net.minecraftforge.forgespi.coremod.ICoreModProvider;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.nio.file.Path; import java.nio.file.Path;
@@ -30,11 +31,14 @@ import java.util.function.BiFunction;
import static net.minecraftforge.fml.loading.LogMarkers.CORE; import static net.minecraftforge.fml.loading.LogMarkers.CORE;
import static net.minecraftforge.fml.loading.LogMarkers.SCAN; import static net.minecraftforge.fml.loading.LogMarkers.SCAN;
public final class FMLLoader { public class FMLLoader {
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static AccessTransformerService accessTransformer; private static AccessTransformerService accessTransformer;
private static ICoreModProvider coreModProvider;
private static LanguageLoadingProvider languageLoadingProvider;
private static Dist dist; private static Dist dist;
private static String naming; private static String naming;
private static LoadingModList loadingModList;
private static RuntimeDistCleaner runtimeDistCleaner; private static RuntimeDistCleaner runtimeDistCleaner;
private static Path gamePath; private static Path gamePath;
private static final VersionInfo versionInfo = VersionInfo.detect(); private static final VersionInfo versionInfo = VersionInfo.detect();
@@ -53,6 +57,8 @@ public final class FMLLoader {
checkPackage(ITransformationService.class, "4.0", "ModLauncher"); checkPackage(ITransformationService.class, "4.0", "ModLauncher");
accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer"); accessTransformer = getPlugin(env, "accesstransformer", "1.0", "AccessTransformer");
runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner"); runtimeDistCleaner = getPlugin(env, "runtimedistcleaner", "1.0", "RuntimeDistCleaner");
coreModProvider = getSingleService(ICoreModProvider.class, "CoreMod");
LOGGER.debug(CORE, "FML found CoreMod version : {}", JarVersionLookupHandler.getInfo(coreModProvider.getClass()).impl().version().orElse("MISSING"));
checkPackage(Environment.class, "2.0", "ForgeSPI"); checkPackage(Environment.class, "2.0", "ForgeSPI");
try { try {
@@ -90,7 +96,6 @@ public final class FMLLoader {
} }
} }
@SuppressWarnings("unused")
private static <T> T getSingleService(Class<T> clazz, String name) throws IncompatibleEnvironmentException { private static <T> T getSingleService(Class<T> clazz, String name) throws IncompatibleEnvironmentException {
var providers = new ArrayList<T>(); var providers = new ArrayList<T>();
for (var itr = ServiceLoader.load(FMLLoader.class.getModule().getLayer(), clazz).iterator(); itr.hasNext(); ) { for (var itr = ServiceLoader.load(FMLLoader.class.getModule().getLayer(), clazz).iterator(); itr.hasNext(); ) {
@@ -141,19 +146,29 @@ public final class FMLLoader {
} }
public static List<ITransformationService.Resource> beginModScan(final Map<String,?> arguments) { public static List<ITransformationService.Resource> beginModScan(final Map<String,?> arguments) {
LOGGER.debug(SCAN, "Scanning for Mod Locators"); LOGGER.debug(SCAN,"Scanning for Mod Locators");
modValidator = ModDiscoverer.discoverMods(arguments); var modDiscoverer = new ModDiscoverer(arguments);
modValidator = modDiscoverer.discoverMods();
var pluginResources = modValidator.getPluginResources(); var pluginResources = modValidator.getPluginResources();
return List.of(pluginResources); return List.of(pluginResources);
} }
public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) { public static List<ITransformationService.Resource> completeScan(IModuleLayerManager layerManager) {
moduleLayerManager = layerManager; moduleLayerManager = layerManager;
LanguageLoadingProvider.reload(); languageLoadingProvider = new LanguageLoadingProvider();
backgroundScanHandler = modValidator.stage2Validation(); backgroundScanHandler = modValidator.stage2Validation();
loadingModList = backgroundScanHandler.getLoadingModList();
return List.of(modValidator.getModResources()); return List.of(modValidator.getModResources());
} }
public static ICoreModProvider getCoreModProvider() {
return coreModProvider;
}
public static LanguageLoadingProvider getLanguageLoadingProvider() {
return languageLoadingProvider;
}
public static CommonLaunchHandler getLaunchHandler() { public static CommonLaunchHandler getLaunchHandler() {
return commonLaunchHandler; return commonLaunchHandler;
} }
@@ -173,6 +188,10 @@ public final class FMLLoader {
progressWindowTick.run(); progressWindowTick.run();
} }
public static LoadingModList getLoadingModList() {
return loadingModList;
}
public static Path getGamePath() { public static Path getGamePath() {
return gamePath; return gamePath;
} }
@@ -12,6 +12,7 @@ import net.minecraftforge.forgespi.Environment;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@@ -41,7 +42,7 @@ public class FMLServiceProvider implements ITransformationService {
LOGGER.debug(CORE, "Loading configuration"); LOGGER.debug(CORE, "Loading configuration");
FMLConfig.load(); FMLConfig.load();
LOGGER.debug(CORE, "Preparing ModFile"); LOGGER.debug(CORE, "Preparing ModFile");
environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), _->ModFile::new); environment.computePropertyIfAbsent(Environment.Keys.MODFILEFACTORY.get(), k->ModFile::new);
LOGGER.debug(CORE, "Preparing launch handler"); LOGGER.debug(CORE, "Preparing launch handler");
FMLLoader.setupLaunchHandler(environment, arguments); FMLLoader.setupLaunchHandler(environment, arguments);
FMLEnvironment.setupInteropEnvironment(environment); FMLEnvironment.setupInteropEnvironment(environment);
@@ -67,6 +68,7 @@ public class FMLServiceProvider implements ITransformationService {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Override @Override
public @NotNull List<ITransformer> transformers() { public @NotNull List<ITransformer> transformers() {
return List.of(); LOGGER.debug(CORE, "Loading coremod transformers");
return new ArrayList<>(FMLLoader.getCoreModProvider().getCoreModTransformers());
} }
} }
@@ -51,8 +51,8 @@ public class ImmediateWindowHandler {
earlyProgress.label("Bootstrapping Minecraft"); earlyProgress.label("Bootstrapping Minecraft");
} }
public static long setupMinecraftWindow(final int width, final int height, final String title, final long monitor, final Supplier<Object> backend) { public static long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor) {
return provider.setupMinecraftWindow(width, height, title, monitor, backend); return provider.setupMinecraftWindow(width, height, title, monitor);
} }
public static boolean positionWindow(Optional<Object> monitor,IntConsumer widthSetter, IntConsumer heightSetter, IntConsumer xSetter, IntConsumer ySetter) { public static boolean positionWindow(Optional<Object> monitor,IntConsumer widthSetter, IntConsumer heightSetter, IntConsumer xSetter, IntConsumer ySetter) {
@@ -104,9 +104,9 @@ public class ImmediateWindowHandler {
} }
@Override @Override
public long setupMinecraftWindow(final int width, final int height, final String title, final long monitor, final Supplier<Object> backend) { public long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor) {
try { try {
var longsupplier = (LongSupplier)NV_HANDOFF.invoke(null, width, height, title, monitor, backend); var longsupplier = (LongSupplier)NV_HANDOFF.invoke(null, width, height, title, monitor);
return longsupplier.getAsLong(); return longsupplier.getAsLong();
} catch (Throwable e) { } catch (Throwable e) {
throw new IllegalStateException("How did you get here?", e); throw new IllegalStateException("How did you get here?", e);
@@ -8,6 +8,8 @@ package net.minecraftforge.fml.loading;
import java.util.Optional; import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.IntConsumer; import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import java.util.function.Supplier; import java.util.function.Supplier;
/** /**
@@ -64,7 +66,7 @@ public interface ImmediateWindowProvider {
* @param monitor This is the monitor it should appear on. * @param monitor This is the monitor it should appear on.
* @return The window id * @return The window id
*/ */
long setupMinecraftWindow(final int width, final int height, final String title, final long monitor, final Supplier<Object> backend); long setupMinecraftWindow(final IntSupplier width, final IntSupplier height, final Supplier<String> title, final LongSupplier monitor);
/** /**
* This is called after window handoff to allow us to tell Mojang about our window's position. This might give a * This is called after window handoff to allow us to tell Mojang about our window's position. This might give a
@@ -18,6 +18,7 @@ import org.slf4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.ServiceConfigurationError; import java.util.ServiceConfigurationError;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -27,36 +28,43 @@ import java.util.stream.Stream;
import static net.minecraftforge.fml.loading.LogMarkers.CORE; import static net.minecraftforge.fml.loading.LogMarkers.CORE;
import static net.minecraftforge.fml.loading.LogMarkers.LOADING; import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
public final class LanguageLoadingProvider { public class LanguageLoadingProvider {
public static void forEach(Consumer<IModLanguageProvider> consumer) { public void forEach(Consumer<IModLanguageProvider> consumer) {
providers.forEach(consumer); providers.forEach(consumer);
} }
public static <T> Stream<T> applyForEach(Function<IModLanguageProvider, T> function) { public <T> Stream<T> applyForEach(Function<IModLanguageProvider, T> function) {
return providers.stream().map(function); return providers.stream().map(function);
} }
public static void reload() { public void reload() {
loadLanguageProviders(); loadLanguageProviders();
} }
/** This doesn't actually do anything with the argument, so just call reload(). Not sure when cpw broke that. */
@Deprecated(forRemoval = true, since = "1.20.2")
public void addAdditionalLanguages(List<ModFile> modFiles) {
reload();
}
/*==========================================================================* /*==========================================================================*
* INTERNAL * * INTERNAL SHIT *
*==========================================================================*/ *==========================================================================*/
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final ServiceLoader<IModLanguageProvider> serviceLoader; private final ServiceLoader<IModLanguageProvider> serviceLoader;
private static final ArrayList<IModLanguageProvider> providers = new ArrayList<>(); private final List<IModLanguageProvider> providers = new ArrayList<>();
private static final HashMap<String, Wrapper> providersByName = new HashMap<>(); private final Map<String, Wrapper> providersByName = new HashMap<>();
private static final DefaultArtifactVersion IN_DEV = new DefaultArtifactVersion("0.0-dev"); private static final DefaultArtifactVersion IN_DEV = new DefaultArtifactVersion("0.0-dev");
private record Wrapper(ArtifactVersion version, IModLanguageProvider service) {} private record Wrapper(ArtifactVersion version, IModLanguageProvider service) {}
static { LanguageLoadingProvider() {
var sl = Launcher.INSTANCE.environment().findModuleLayerManager().flatMap(lm -> lm.getLayer(Layer.PLUGIN)).orElseThrow(); var sl = Launcher.INSTANCE.environment().findModuleLayerManager().flatMap(lm -> lm.getLayer(Layer.PLUGIN)).orElseThrow();
serviceLoader = ServiceLoader.load(sl, IModLanguageProvider.class); serviceLoader = ServiceLoader.load(sl, IModLanguageProvider.class);
loadLanguageProviders();
} }
private static void loadLanguageProviders() { private void loadLanguageProviders() {
providers.clear(); providers.clear();
providersByName.clear(); providersByName.clear();
@@ -89,7 +97,7 @@ public final class LanguageLoadingProvider {
} }
} }
public static IModLanguageProvider findLanguage(ModFile mod, String language, VersionRange versionRange) { public IModLanguageProvider findLanguage(ModFile mod, String language, VersionRange versionRange) {
var consumer = mod.getFileName(); var consumer = mod.getFileName();
var wrapper = providersByName.get(language); var wrapper = providersByName.get(language);
@@ -5,46 +5,125 @@
package net.minecraftforge.fml.loading; package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo; import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo; import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.IModFile;
import org.jetbrains.annotations.Nullable; import org.slf4j.Logger;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/// Master list of all mods in the loading context /**
public sealed interface LoadingModList permits LoadingModListImpl { * Master list of all mods <em>in the loading context. This class cannot refer outside the
static ModFileInfo getModFileById(String modId) { * loading package</em>
return get().fileById().get(modId); */
public class LoadingModList {
private static final Logger LOGGER = LogUtils.getLogger();
private static LoadingModList INSTANCE;
private final List<ModFileInfo> modFiles;
private final List<ModInfo> sortedList;
private final Map<String, ModFileInfo> fileById;
private final List<EarlyLoadingException> preLoadErrors;
private List<IModFile> brokenFiles;
private LoadingModList(final List<ModFile> modFiles, final List<ModInfo> sortedList) {
this.modFiles = modFiles.stream()
.map(ModFile::getModFileInfo)
.map(ModFileInfo.class::cast)
.toList();
this.sortedList = sortedList.stream()
.map(ModInfo.class::cast)
.toList();
this.fileById = this.modFiles.stream()
.map(ModFileInfo::getMods)
.flatMap(Collection::stream)
.map(ModInfo.class::cast)
.collect(Collectors.toMap(ModInfo::getModId, ModInfo::getOwningFile));
this.preLoadErrors = new ArrayList<>();
} }
static List<ModFileInfo> getModFiles() { public static LoadingModList of(List<ModFile> modFiles, List<ModInfo> sortedList, final EarlyLoadingException earlyLoadingException) {
return get().getModFiles(); INSTANCE = new LoadingModList(modFiles, sortedList);
if (earlyLoadingException != null)
INSTANCE.preLoadErrors.add(earlyLoadingException);
return INSTANCE;
} }
static List<ModInfo> getMods() { public static LoadingModList get() {
return get().getMods(); return INSTANCE;
} }
static @Nullable Path findResource(String className) { public void addCoreMods() {
for (ModFileInfo modFileInfo : get().getModFiles()) { modFiles.stream()
Path resource = modFileInfo.getFile().findResource(className); .map(ModFileInfo::getFile)
.map(ModFile::getCoreMods)
.flatMap(List::stream)
.forEach(FMLLoader.getCoreModProvider()::addCoreMod);
}
public void addAccessTransformers() {
var errors = new ArrayList<EarlyLoadingException.ExceptionData>();
for (ModFileInfo modFile : modFiles) {
ModFile mod = modFile.getFile();
for (Path at : mod.getAccessTransformers()) {
if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new EarlyLoadingException.ExceptionData(message));
LOGGER.error(message);
} else {
FMLLoader.addAccessTransformer(at, mod);
}
}
}
if (!errors.isEmpty()) {
preLoadErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
}
public void addForScanning(BackgroundScanHandler backgroundScanHandler) {
backgroundScanHandler.setLoadingModList(this);
modFiles.stream()
.map(ModFileInfo::getFile)
.forEach(backgroundScanHandler::submitForScanning);
}
public List<ModFileInfo> getModFiles() {
return modFiles;
}
public Path findResource(final String className) {
for (ModFileInfo mf : modFiles) {
final Path resource = mf.getFile().findResource(className);
if (Files.exists(resource)) return resource; if (Files.exists(resource)) return resource;
} }
return null; return null;
} }
static List<EarlyLoadingException> getErrors() { public ModFileInfo getModFileById(String modid) {
return get().getErrors(); return this.fileById.get(modid);
} }
static List<IModFile> getBrokenFiles() { public List<ModInfo> getMods() {
return get().getBrokenFiles(); return this.sortedList;
} }
private static LoadingModListImpl get() { public List<EarlyLoadingException> getErrors() {
return LoadingModListImpl.get(); return preLoadErrors;
}
public void setBrokenFiles(final List<IModFile> brokenFiles) {
this.brokenFiles = brokenFiles;
}
public List<IModFile> getBrokenFiles() {
return this.brokenFiles;
} }
} }
@@ -1,90 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fml.loading;
import net.minecraftforge.fml.loading.EarlyLoadingException.ExceptionData;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.loading.moddiscovery.ModInfo;
import net.minecraftforge.forgespi.locating.IModFile;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
/**
* Master list of all mods <em>in the loading context. This class cannot refer outside the
* loading package</em>
*/
record LoadingModListImpl(
List<ModFileInfo> getModFiles,
List<ModInfo> getMods,
Map<String, ModFileInfo> fileById,
ArrayList<EarlyLoadingException> getErrors,
ArrayList<IModFile> getBrokenFiles
) implements LoadingModList {
private static final Logger LOGGER = LogUtils.getLogger();
private static ModSorter.State temp;
LoadingModListImpl(List<ModFile> modFiles, List<ModInfo> sortedList) {
var modFileInfos = modFiles.stream()
.map(ModFile::getModFileInfo)
.map(ModFileInfo.class::cast)
.toList();
sortedList = sortedList.stream().toList();
var fileById = modFileInfos.stream()
.map(ModFileInfo::getMods)
.flatMap(Collection::stream)
.map(ModInfo.class::cast)
.collect(Collectors.toUnmodifiableMap(ModInfo::getModId, ModInfo::getOwningFile));
this(modFileInfos, sortedList, fileById, new ArrayList<>(), new ArrayList<>());
}
static LoadingModListImpl init(ModSorter.State modSorterState, EarlyLoadingException earlyLoadingException) {
temp = modSorterState;
var instance = get();
if (earlyLoadingException != null)
instance.getErrors.add(earlyLoadingException);
temp = null;
instance.addAccessTransformers();
return instance;
}
static LoadingModListImpl get() {
final class LazyInit {
private LazyInit() {}
private static final LoadingModListImpl INSTANCE
= new LoadingModListImpl(LoadingModListImpl.temp.files(), LoadingModListImpl.temp.mods());
}
return LazyInit.INSTANCE;
}
private void addAccessTransformers() {
var errors = new ArrayList<ExceptionData>();
for (ModFileInfo modFile : getModFiles) {
ModFile mod = modFile.getFile();
for (var at : mod.getAccessTransformers()) {
if (!Files.exists(at)) {
var message = "Invalid mod file: " + modFile.getFile().getFileName() + ". Missing Access Transformer: " + at;
errors.add(new ExceptionData(message));
LOGGER.error(message);
} else
FMLLoader.addAccessTransformer(at, mod);
}
}
if (!errors.isEmpty())
getErrors.add(new EarlyLoadingException("Invalid Access Transformers", null, errors));
}
}
@@ -7,6 +7,7 @@ package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.api.INameMappingService; import cpw.mods.modlauncher.api.INameMappingService;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.io.BufferedReader; import java.io.BufferedReader;
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.loading; package net.minecraftforge.fml.loading;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
/** /**
* Convert a maven coordinate into a Path. * Convert a maven coordinate into a Path.
@@ -7,10 +7,8 @@ package net.minecraftforge.fml.loading;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import cpw.mods.jarhandling.SecureJar; import cpw.mods.jarhandling.SecureJar;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils; import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import cpw.mods.modlauncher.api.NamedPath; import cpw.mods.modlauncher.api.NamedPath;
import cpw.mods.modlauncher.api.TypesafeMap;
import cpw.mods.modlauncher.serviceapi.ITransformerDiscoveryService; import cpw.mods.modlauncher.serviceapi.ITransformerDiscoveryService;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@@ -42,17 +40,6 @@ public class ModDirTransformerDiscoverer implements ITransformerDiscoveryService
@Override @Override
public void earlyInitialization(final String launchTarget, final String[] arguments) { public void earlyInitialization(final String launchTarget, final String[] arguments) {
boolean isMixinEnabledInDev = false;
for (String arg : arguments) {
if (arg.startsWith("-mixin") || arg.startsWith("--mixin")) {
isMixinEnabledInDev = true;
break;
}
}
Launcher.INSTANCE.blackboard().putIfAbsent(
TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "isMixinEnabledInDev", Boolean.class),
isMixinEnabledInDev
);
ImmediateWindowHandler.load(launchTarget, arguments); ImmediateWindowHandler.load(launchTarget, arguments);
} }
@@ -33,10 +33,10 @@ import java.util.stream.Stream;
import static net.minecraftforge.fml.loading.LogMarkers.LOADING; import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
public final class ModSorter { public class ModSorter {
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
record State(List<ModFile> files, List<ModInfo> mods) {} private record State(List<ModFile> files, List<ModInfo> mods) {}
private ModSorter() {} private ModSorter() {}
@@ -46,13 +46,13 @@ public final class ModSorter {
List<ModFile> modFiles; List<ModFile> modFiles;
try { try {
modFiles = UniqueModListBuilder.buildUniqueList(mods).modFiles(); modFiles = new UniqueModListBuilder(mods).buildUniqueList().modFiles();
} catch (EarlyLoadingException e) { } catch (EarlyLoadingException e) {
// We cannot build any list with duped mods. We have to abort immediately and report it // We cannot build any list with duped mods. We have to abort immediately and report it
// Note this will never actually throw an error because the duplicate checks are done in ModDiscovererer before we get to this phase // Note this will never actually throw an error because the duplicate checks are done in ModDiscovererer before we get to this phase
// So all this is really doing is wasting time. // So all this is really doing is wasting time.
// But i'm leaving it here until I rewrite all of cpw's mod loading code because its such a clusterfuck. // But i'm leaving it here until I rewrite all of cpw's mod loading code because its such a clusterfuck.
return LoadingModListImpl.init(systemMods, e); return LoadingModList.of(systemMods.files(), systemMods.mods(), e);
} }
var named = new HashMap<String, ModInfo>(); var named = new HashMap<String, ModInfo>();
@@ -66,15 +66,15 @@ public final class ModSorter {
// if we miss one or the other, we abort now // if we miss one or the other, we abort now
if (!failedList.isEmpty()) { if (!failedList.isEmpty()) {
return LoadingModListImpl.init(systemMods, new EarlyLoadingException("failure to validate mod list", null, failedList)); return LoadingModList.of(systemMods.files(), systemMods.mods(), new EarlyLoadingException("failure to validate mod list", null, failedList));
} else { } else {
// Otherwise, lets try and sort the modlist and proceed // Otherwise, lets try and sort the modlist and proceed
try { try {
var sorted = sort(modFiles, named); var sorted = sort(modFiles, named);
return LoadingModListImpl.init(sorted, null); return LoadingModList.of(sorted.files(), sorted.mods(), null);
} catch (EarlyLoadingException e) { } catch (EarlyLoadingException e) {
// The only exception that can happen here is a cyclic exception, but fall back to system mods so we can display the nice screen. // The only exception that can happen here is a cyclic exception, but fall back to system mods so we can display the nice screen.
return LoadingModListImpl.init(systemMods, e); return LoadingModList.of(systemMods.files(), systemMods.mods(), e);
} }
} }
} }
@@ -33,6 +33,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
private static String DIST; private static String DIST;
private static final String ONLYIN = Type.getDescriptor(OnlyIn.class); private static final String ONLYIN = Type.getDescriptor(OnlyIn.class);
private static final String ONLYINS = Type.getDescriptor(OnlyIns.class); private static final String ONLYINS = Type.getDescriptor(OnlyIns.class);
private static final String MOD = "Lnet/minecraftforge/fml/common/Mod;";
@Override @Override
public String name() { public String name() {
@@ -48,21 +49,14 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
return NAY; return NAY;
String internalName = classType.getInternalName(); String internalName = classType.getInternalName();
// Only apply to MC classes when on a dedicated server in a production environment
if (FMLEnvironment.production)
return FMLEnvironment.dist.isDedicatedServer() && isMinecraftClass(internalName) ? YAY : NAY;
// For dev time it's a bit trickier so that we can throw exceptions when someone uses @OnlyIn in their mod code,
// so that it's more obvious that the behaviour they're expecting won't work in production anymore
if (internalName.startsWith("net/minecraftforge/")) if (internalName.startsWith("net/minecraftforge/"))
return NAY; return NAY;
// No Vanilla classes use @OnlyIn(Dist.SERVER), so we can skip them entirely when we're running on a client // No Vanilla classes use @OnlyIn(Dist.SERVER), so we can skip them entirely when we're running on a client
if (FMLEnvironment.dist.isClient() && isMinecraftClass(internalName)) if (FMLEnvironment.dist.isClient() && (internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/")))
return NAY; return NAY;
return YAY; // mod classes might have @OnlyIn, so parse them in dev to find out and throw if they do return YAY;
} }
@Override @Override
@@ -70,15 +64,16 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
var changed = false; var changed = false;
var annotations = unpack(classNode.visibleAnnotations); var annotations = unpack(classNode.visibleAnnotations);
var isNonMinecraftClass = !isMinecraftClass(classNode.name);
if (remove(annotations, DIST)) { if (remove(annotations, DIST)) {
LOGGER.error(DISTXFORM, "Attempted to load class {} for invalid dist {}", classNode.name, DIST); LOGGER.error(DISTXFORM, "Attempted to load class {} for invalid dist {}", classNode.name, DIST);
throw new RuntimeException("Attempted to load class " + classNode.name + " for invalid dist " + DIST); throw new RuntimeException("Attempted to load class "+ classNode.name + " for invalid dist "+ DIST);
} }
if (isNonMinecraftClass && !annotations.isEmpty()) if (!FMLEnvironment.production && !annotations.isEmpty() && hasModAnnotation(classNode.visibleAnnotations)) {
throw new UnsupportedOperationException("Mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times"); LOGGER.error(DISTXFORM, "Attempted to load class {} with @Mod and @OnlyIn/@OnlyIns annotations", classNode.name);
throw new RuntimeException("Found @OnlyIn on @Mod class "+ classNode.name + " - this is not allowed as it causes crashes. Remove the OnlyIn and consider setting clientSideOnly=true in the root of your mods.toml instead");
}
if (classNode.interfaces != null && !classNode.interfaces.isEmpty()) { if (classNode.interfaces != null && !classNode.interfaces.isEmpty()) {
for (var ann : annotations) { for (var ann : annotations) {
@@ -86,7 +81,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
continue; continue;
if (classNode.interfaces.remove(ann.intf)) { if (classNode.interfaces.remove(ann.intf)) {
LOGGER.debug(DISTXFORM, "Removing Interface: {} implements {}", classNode.name, ann.intf); LOGGER.debug(DISTXFORM,"Removing Interface: {} implements {}", classNode.name, ann.intf);
changed = true; changed = true;
} }
} }
@@ -110,9 +105,6 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
LOGGER.debug(DISTXFORM, "Removing field: {}.{}", classNode.name, field.name); LOGGER.debug(DISTXFORM, "Removing field: {}.{}", classNode.name, field.name);
itr.remove(); itr.remove();
changed = true; changed = true;
if (isNonMinecraftClass)
throw new UnsupportedOperationException("Field " + field.name + " in mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
} }
} }
@@ -124,9 +116,6 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
itr.remove(); itr.remove();
lambdaGatherer.accept(method); lambdaGatherer.accept(method);
changed = true; changed = true;
if (isNonMinecraftClass)
throw new UnsupportedOperationException("Method " + method.name + " in mod class " + classNode.name + " is annotated with @OnlyIn, this is no longer supported as it slowed down startup times");
} }
} }
@@ -153,7 +142,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
return changed ? ComputeFlags.SIMPLE_REWRITE : ComputeFlags.NO_REWRITE; return changed ? ComputeFlags.SIMPLE_REWRITE : ComputeFlags.NO_REWRITE;
} }
private record Target(String side, String intf) { private static record Target(String side, String intf) {
static Target from(final AnnotationNode node) { static Target from(final AnnotationNode node) {
var idx = node.values.indexOf("value"); var idx = node.values.indexOf("value");
var value = (String[])node.values.get(idx + 1); // Enums are stored as [Type, Value] var value = (String[])node.values.get(idx + 1); // Enums are stored as [Type, Value]
@@ -207,8 +196,16 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
return false; return false;
} }
private static boolean isMinecraftClass(final String internalName) { private static boolean hasModAnnotation(final List<AnnotationNode> anns) {
return internalName.startsWith("net/minecraft/") || internalName.startsWith("com/mojang/"); if (anns == null || anns.isEmpty())
return false;
for (var ann : anns) {
if (ann.desc.equals(MOD))
return true;
}
return false;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -220,7 +217,7 @@ public final class RuntimeDistCleaner implements ILaunchPluginService {
}; };
} }
private static final class LambdaGatherer extends MethodVisitor { private static class LambdaGatherer extends MethodVisitor {
private static final Handle META_FACTORY = new Handle(Opcodes.H_INVOKESTATIC, private static final Handle META_FACTORY = new Handle(Opcodes.H_INVOKESTATIC,
"java/lang/invoke/LambdaMetafactory", "metafactory", "java/lang/invoke/LambdaMetafactory", "metafactory",
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
@@ -12,7 +12,6 @@ import java.util.Map;
import org.apache.commons.lang3.text.StrLookup; import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor; import org.apache.commons.lang3.text.StrSubstitutor;
// TODO: [FML] Remove this
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class StringSubstitutor { public class StringSubstitutor {
private static final Map<String, String> GLOBALS = Map.of( private static final Map<String, String> GLOBALS = Map.of(
@@ -26,7 +26,6 @@ public class StringUtils {
return java.util.stream.Stream.of(endings).anyMatch(lowerSearch::endsWith); return java.util.stream.Stream.of(endings).anyMatch(lowerSearch::endsWith);
} }
@SuppressWarnings("deprecation")
public static URL toURL(final String string) { public static URL toURL(final String string) {
if (string == null || string.trim().isEmpty() || string.contains("myurl.me") || string.contains("example.invalid")) if (string == null || string.trim().isEmpty() || string.contains("myurl.me") || string.contains("example.invalid"))
return null; return null;
@@ -17,6 +17,8 @@ import java.util.Collection;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.joining;
@@ -24,12 +26,19 @@ import static net.minecraftforge.fml.loading.LogMarkers.LOADING;
@ApiStatus.Internal @ApiStatus.Internal
@Deprecated(since = "1.21.3", forRemoval = true) // TODO: [FML][Loading] Convert to package private in 1.22 @Deprecated(since = "1.21.3", forRemoval = true) // TODO: [FML][Loading] Convert to package private in 1.22
public final class UniqueModListBuilder { public class UniqueModListBuilder {
private UniqueModListBuilder() {} private final static Logger LOGGER = LogUtils.getLogger();
private static final Logger LOGGER = LogUtils.getLogger(); private final List<ModFile> modFiles;
public UniqueModListBuilder(final List<ModFile> modFiles) {
this.modFiles = modFiles;
}
public UniqueModListData buildUniqueList() {
List<ModFile> uniqueModList;
List<ModFile> uniqueLibListWithVersion;
public static UniqueModListData buildUniqueList(List<ModFile> modFiles) {
// Collect mod files by module name. This will be used for deduping purposes // Collect mod files by module name. This will be used for deduping purposes
final Map<String, List<ModFile>> modFilesByFirstId = modFiles.stream() final Map<String, List<ModFile>> modFilesByFirstId = modFiles.stream()
.filter(mf -> mf.getModFileInfo() != null) .filter(mf -> mf.getModFileInfo() != null)
@@ -40,12 +49,12 @@ public final class UniqueModListBuilder {
.collect(groupingBy(UniqueModListBuilder::getModId)); .collect(groupingBy(UniqueModListBuilder::getModId));
// Select the newest by artifact version sorting of non-unique files thus identified // Select the newest by artifact version sorting of non-unique files thus identified
final List<ModFile> uniqueModList = modFilesByFirstId.entrySet().stream() uniqueModList = modFilesByFirstId.entrySet().stream()
.map(UniqueModListBuilder::selectNewestModInfo) .map(UniqueModListBuilder::selectNewestModInfo)
.toList(); .toList();
// Select the newest by artifact version sorting of non-unique files thus identified // Select the newest by artifact version sorting of non-unique files thus identified
final List<ModFile> uniqueLibListWithVersion = libFilesWithVersionByModuleName.entrySet().stream() uniqueLibListWithVersion = libFilesWithVersionByModuleName.entrySet().stream()
.map(UniqueModListBuilder::selectNewestModInfo) .map(UniqueModListBuilder::selectNewestModInfo)
.toList(); .toList();
@@ -57,10 +66,12 @@ public final class UniqueModListBuilder {
.collect(groupingBy(IModInfo::getModId)); .collect(groupingBy(IModInfo::getModId));
// Transform to the full lib id list // Transform to the full lib id list
final List<List<ModFile>> versionedLibs = uniqueLibListWithVersion.stream() final Map<String, List<ModFile>> versionedLibIds = uniqueLibListWithVersion.stream()
.map(UniqueModListBuilder::getModId) .map(UniqueModListBuilder::getModId)
.map(libFilesWithVersionByModuleName::get) .collect(Collectors.toMap(
.toList(); Function.identity(),
libFilesWithVersionByModuleName::get
));
// Its theoretically possible that some mod has somehow moved an id to a secondary place, thus causing a dupe. // Its theoretically possible that some mod has somehow moved an id to a secondary place, thus causing a dupe.
// We can't handle this // We can't handle this
@@ -73,24 +84,24 @@ public final class UniqueModListBuilder {
)).toList(); )).toList();
if (!dupedModErrors.isEmpty()) { if (!dupedModErrors.isEmpty()) {
LOGGER.error(LOADING, "Found duplicate mods:\n{}", String.join("\n", dupedModErrors)); LOGGER.error(LOADING, "Found duplicate mods:\n{}", dupedModErrors.stream().collect(joining("\n")));
throw new EarlyLoadingException("Duplicate mods found", null, dupedModErrors.stream() throw new EarlyLoadingException("Duplicate mods found", null, dupedModErrors.stream()
.map(EarlyLoadingException.ExceptionData::new) .map(s -> new EarlyLoadingException.ExceptionData(s))
.toList()); .toList());
} }
final List<String> dupedLibErrors = versionedLibs.stream() final List<String> dupedLibErrors = versionedLibIds.values().stream()
.filter(libModFiles -> libModFiles.size() > 1) .filter(modFiles -> modFiles.size() > 1)
.map(mods -> String.format("\tLibrary: '%s' from files: %s", .map(mods -> String.format("\tLibrary: '%s' from files: %s",
getModId(mods.getFirst()), getModId(mods.getFirst()),
mods.stream().map(ModFile::getFileName).collect(joining(", ")) mods.stream().map(ModFile::getFileName).collect(joining(", "))
)).toList(); )).toList();
if (!dupedLibErrors.isEmpty()) { if (!dupedLibErrors.isEmpty()) {
LOGGER.error(LOADING, "Found duplicate plugins or libraries:\n{}", String.join("\n", dupedLibErrors)); LOGGER.error(LOADING, "Found duplicate plugins or libraries:\n{}", dupedLibErrors.stream().collect(joining("\n")));
throw new EarlyLoadingException("Duplicate plugins or libraries found", null, dupedLibErrors.stream() throw new EarlyLoadingException("Duplicate plugins or libraries found", null, dupedLibErrors.stream()
.map(EarlyLoadingException.ExceptionData::new) .map(s -> new EarlyLoadingException.ExceptionData(s))
.toList()); .toList());
} }
@@ -111,26 +122,23 @@ public final class UniqueModListBuilder {
modInfoList.sort(Comparator.comparing(UniqueModListBuilder::getVersion).reversed()); modInfoList.sort(Comparator.comparing(UniqueModListBuilder::getVersion).reversed());
LOGGER.debug("Selected file {} for modid {} with version {}", modInfoList.getFirst().getFileName(), fullList.getKey(), getVersion(modInfoList.getFirst())); LOGGER.debug("Selected file {} for modid {} with version {}", modInfoList.getFirst().getFileName(), fullList.getKey(), getVersion(modInfoList.getFirst()));
} }
return modInfoList.getFirst(); return modInfoList.get(0);
} }
private static ArtifactVersion getVersion(final ModFile mf) { private static ArtifactVersion getVersion(final ModFile mf) {
List<IModInfo> modInfos; if (mf.getModFileInfo() == null || mf.getModInfos() == null || mf.getModInfos().isEmpty()) {
if (mf.getModFileInfo() == null || (modInfos = mf.getModInfos()) == null || modInfos.isEmpty()) {
return mf.getJarVersion(); return mf.getJarVersion();
} }
return modInfos.getFirst().getVersion(); return mf.getModInfos().get(0).getVersion();
} }
private static String getModId(ModFile modFile) { private static String getModId(ModFile modFile) {
var modFileInfo = modFile.getModFileInfo(); if (modFile.getModFileInfo() == null || modFile.getModFileInfo().getMods().isEmpty()) {
List<IModInfo> mods;
if (modFileInfo == null || (mods = modFileInfo.getMods()).isEmpty()) {
return modFile.getSecureJar().name(); return modFile.getSecureJar().name();
} }
return mods.getFirst().getModId(); return modFile.getModFileInfo().getMods().get(0).getModId();
} }
public record UniqueModListData(List<ModFile> modFiles, Map<String, List<ModFile>> modFilesByFirstId) {} public record UniqueModListData(List<ModFile> modFiles, Map<String, List<ModFile>> modFilesByFirstId) {}
@@ -13,6 +13,7 @@ import org.jetbrains.annotations.ApiStatus;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.BiPredicate;
@ApiStatus.Internal // since 1.21.1, will be made non-public in a later MC version @ApiStatus.Internal // since 1.21.1, will be made non-public in a later MC version
public class VersionSupportMatrix { public class VersionSupportMatrix {
@@ -31,6 +32,15 @@ public class VersionSupportMatrix {
} }
} }
/**
* @deprecated Use {@link #testVersionSupportMatrix(VersionRange, String, String)} instead, unwrapping your BiPredicate.
*/
@Deprecated(forRemoval = true, since = "1.21.1")
public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type, BiPredicate<String, VersionRange> standardLookup) {
if (standardLookup.test(lookupId, declaredRange)) return true;
return testVersionSupportMatrix(declaredRange, lookupId, type);
}
public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type) { public static boolean testVersionSupportMatrix(VersionRange declaredRange, String lookupId, String type) {
if (OVERRIDE_VERSIONS.isEmpty()) return false; if (OVERRIDE_VERSIONS.isEmpty()) return false;
List<ArtifactVersion> custom = OVERRIDE_VERSIONS.get(type + "." + lookupId); List<ArtifactVersion> custom = OVERRIDE_VERSIONS.get(type + "." + lookupId);
@@ -54,16 +54,12 @@ public abstract class AbstractModProvider implements IModProvider {
@Nullable @Nullable
protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown, String defaultType) { protected IModLocator.ModFileOrException createMod(Path path, boolean ignoreUnknown, String defaultType) {
var debug = path.toString();
if (debug.equals("/"))
debug = path.toUri().toString();
var mjm = new ModJarMetadata(); var mjm = new ModJarMetadata();
SecureJar sj = null; SecureJar sj = null;
try { try {
sj = SecureJar.from(jar -> loadMetaFromJar(jar, mjm), path); sj = SecureJar.from(jar -> loadMetaFromJar(jar, mjm), path);
} catch (Throwable t) { } catch (Throwable t) {
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Failed to create secure jar for \"" + debug + "\" - " + t.getMessage())); return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Failed to create secure jar for \"" + path + "\" - " + t.getMessage()));
} }
IModFile mod; IModFile mod;
@@ -72,7 +68,7 @@ public abstract class AbstractModProvider implements IModProvider {
type = defaultType; type = defaultType;
if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) { if (sj.moduleDataProvider().findFile(MODS_TOML).isPresent()) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, debug); LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", MODS_TOML, type, path);
mod = new ModFile(sj, this, ModFileParser::modsTomlParser); mod = new ModFile(sj, this, ModFileParser::modsTomlParser);
// ModJarMetadata is only used when loading mods.toml mods as ModJarMetadata // ModJarMetadata is only used when loading mods.toml mods as ModJarMetadata
mjm.setModFile(mod); mjm.setModFile(mod);
@@ -81,17 +77,17 @@ public abstract class AbstractModProvider implements IModProvider {
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("File \"%s\" is not a Forge mod and cannot be loaded. Look for a Forge version of this mod or consider alternative mods.".formatted(mod.getFileName()))); return new IModLocator.ModFileOrException(null, new ModFileLoadingException("File \"%s\" is not a Forge mod and cannot be loaded. Look for a Forge version of this mod or consider alternative mods.".formatted(mod.getFileName())));
} }
} else if (type != null) { } else if (type != null) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, debug); LOGGER.debug(LogMarkers.SCAN, "Found {} mod of type {}: {}", JarFile.MANIFEST_NAME, type, path);
mod = new ModFile(sj, this, this::manifestParser, type); mod = new ModFile(sj, this, this::manifestParser, type);
} else if (ignoreUnknown) { } else if (ignoreUnknown) {
return null; return null;
} else } else
return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + debug)); return new IModLocator.ModFileOrException(null, new ModFileLoadingException("Invalid mod file found " + path));
return new IModLocator.ModFileOrException(mod, null); return new IModLocator.ModFileOrException(mod, null);
} }
protected static JarMetadata loadMetaFromJar(SecureJar jar, ModJarMetadata mjm) { private static JarMetadata loadMetaFromJar(SecureJar jar, ModJarMetadata mjm) {
var info = jar.moduleDataProvider().open(MODULE_INFO).orElse(null); var info = jar.moduleDataProvider().open(MODULE_INFO).orElse(null);
if (info != null) { if (info != null) {
try { try {
@@ -149,12 +145,6 @@ public abstract class AbstractModProvider implements IModProvider {
public <T> Optional<T> getConfigElement(String... key) { public <T> Optional<T> getConfigElement(String... key) {
return Optional.empty(); return Optional.empty();
} }
@Override
public List<? extends IConfigurable> getConfigList(String key) {
return Collections.emptyList();
}
@Override @Override
public List<? extends IConfigurable> getConfigList(String... key) { public List<? extends IConfigurable> getConfigList(String... key) {
return Collections.emptyList(); return Collections.emptyList();
@@ -7,6 +7,7 @@ package net.minecraftforge.fml.loading.moddiscovery;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.ImmediateWindowHandler; import net.minecraftforge.fml.loading.ImmediateWindowHandler;
import net.minecraftforge.fml.loading.LoadingModList;
import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.forgespi.language.ModFileScanData; import net.minecraftforge.forgespi.language.ModFileScanData;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -16,7 +17,8 @@ import java.time.Instant;
import java.util.List; import java.util.List;
import java.util.concurrent.*; import java.util.concurrent.*;
public final class BackgroundScanHandler { public class BackgroundScanHandler
{
private enum ScanStatus { private enum ScanStatus {
NOT_STARTED, NOT_STARTED,
RUNNING, RUNNING,
@@ -31,6 +33,7 @@ public final class BackgroundScanHandler {
private final ExecutorService modContentScanner; private final ExecutorService modContentScanner;
private final List<ModFile> modFiles; private final List<ModFile> modFiles;
private ScanStatus status; private ScanStatus status;
private LoadingModList loadingModList;
public BackgroundScanHandler(final List<ModFile> modFiles) { public BackgroundScanHandler(final List<ModFile> modFiles) {
this.modFiles = modFiles; this.modFiles = modFiles;
@@ -55,7 +58,7 @@ public final class BackgroundScanHandler {
ImmediateWindowHandler.updateProgress("Scanning mod candidates"); ImmediateWindowHandler.updateProgress("Scanning mod candidates");
CompletableFuture<ModFileScanData> future = CompletableFuture.supplyAsync(file::compileContent, modContentScanner) CompletableFuture<ModFileScanData> future = CompletableFuture.supplyAsync(file::compileContent, modContentScanner)
.whenComplete(file::setScanResult); .whenComplete(file::setScanResult);
if (DEBUG) future = future.whenComplete((_, t) -> addCompletedFile(file, t)); if (DEBUG) future = future.whenComplete((r, t) -> addCompletedFile(file, t));
file.setFutureScanResult(future); file.setFutureScanResult(future);
} }
@@ -66,6 +69,16 @@ public final class BackgroundScanHandler {
} }
} }
public void setLoadingModList(LoadingModList loadingModList)
{
this.loadingModList = loadingModList;
}
public LoadingModList getLoadingModList()
{
return loadingModList;
}
public void waitForScanToComplete(final Runnable ticker) { public void waitForScanToComplete(final Runnable ticker) {
boolean timeoutActive = System.getProperty("fml.disableScanTimeout") == null; boolean timeoutActive = System.getProperty("fml.disableScanTimeout") == null;
Instant deadline = Instant.now().plus(Duration.ofMinutes(10)); Instant deadline = Instant.now().plus(Duration.ofMinutes(10));
@@ -45,7 +45,7 @@ public final class ClasspathLocator extends AbstractModProvider implements IModL
// Find 'minecraft' during dev time this is also Forge. So skip it. // Find 'minecraft' during dev time this is also Forge. So skip it.
// Can return null for dedicated server as Minecraft isn't on the classpath // Can return null for dedicated server as Minecraft isn't on the classpath
// On the client it doesn't matter as it's the vanilla jar so wouldnt have mods.toml in it. // On the client it doesn't matter as it's the vanilla jar so wouldnt have mods.toml in it.
var minecraft = getPathFromResource(cl, "net/minecraft/world/item/Item.class"); var minecraft = getPathFromResource(cl, "net/minecraft/obfuscate/DontObfuscate.class");
var claimed = new HashSet<Path>(); var claimed = new HashSet<Path>();
var tomls = getUrls(cl, MODS_TOML); var tomls = getUrls(cl, MODS_TOML);
@@ -74,8 +74,7 @@ public final class ClasspathLocator extends AbstractModProvider implements IModL
var ret = new ArrayList<ModFileOrException>(); var ret = new ArrayList<ModFileOrException>();
for (var path : claimed) { for (var path : claimed) {
// Filter out anything found by the ServiceLoader // Filter out anything found by the ServiceLoader
if (!ModDirTransformerDiscoverer.isServiceProvider(path) if (!ModDirTransformerDiscoverer.isServiceProvider(path))
&& !JarInJarDependencyLocator.isOption(path))
ret.add(createMod(path)); ret.add(createMod(path));
} }
return ret; return ret;
@@ -108,7 +107,7 @@ public final class ClasspathLocator extends AbstractModProvider implements IModL
return Path.of(URI.create(str)); return Path.of(URI.create(str));
} }
static Path getPathFromResource(ClassLoader cl, String resource) { private static Path getPathFromResource(ClassLoader cl, String resource) {
var url = cl.getResource(resource); var url = cl.getResource(resource);
if (url == null) if (url == null)
return null; return null;
@@ -0,0 +1,53 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fml.loading.moddiscovery;
import net.minecraftforge.forgespi.coremod.ICoreModFile;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jetbrains.annotations.ApiStatus;
@ApiStatus.Internal
public final class CoreModFile implements ICoreModFile {
private final Path internalPath;
private final ModFile file;
private final String name;
CoreModFile(final String name, final Path path, final ModFile file) {
this.name = name;
this.internalPath = path;
this.file = file;
}
@Override
public Reader readCoreMod() throws IOException {
return Files.newBufferedReader(this.internalPath);
}
@Override
public Path getPath() {
return this.internalPath;
}
@Override
public Reader getAdditionalFile(final String fileName) throws IOException {
return Files.newBufferedReader(file.findResource(fileName));
}
@Override
public String getOwnerId() {
return this.file.getModInfos().get(0).getModId();
}
@Override
public String toString() {
return "{Name: " + name + ", Owner: " + getOwnerId() + " @ " + getPath() + "}";
}
}
@@ -24,7 +24,7 @@ public enum InvalidModIdentifier {
LITELOADER(filePresent("litemod.json")), LITELOADER(filePresent("litemod.json")),
OPTIFINE(filePresent("optifine/Installer.class")), OPTIFINE(filePresent("optifine/Installer.class")),
BUKKIT(filePresent("plugin.yml")), BUKKIT(filePresent("plugin.yml")),
INVALIDZIP((_,zf) -> zf.isEmpty()); // note: only this one INVALIDZIP check is ran until the todo on this class is fixed INVALIDZIP((f,zf) -> zf.isEmpty()); // note: only this one INVALIDZIP check is ran until the todo on this class is fixed
private final BiPredicate<Path, Optional<ZipFile>> ident; private final BiPredicate<Path, Optional<ZipFile>> ident;
@@ -51,7 +51,7 @@ public enum InvalidModIdentifier {
private static BiPredicate<Path, Optional<ZipFile>> filePresent(String filename) private static BiPredicate<Path, Optional<ZipFile>> filePresent(String filename)
{ {
return (_, zfo) -> zfo.map(zf -> zf.getEntry(filename) != null).orElse(false); return (f, zfo) -> zfo.map(zf -> zf.getEntry(filename) != null).orElse(false);
} }
private static <T> Optional<T> optionalFromException(Supplier_WithExceptions<T, ? extends Exception> supp) private static <T> Optional<T> optionalFromException(Supplier_WithExceptions<T, ? extends Exception> supp)
@@ -5,39 +5,22 @@
package net.minecraftforge.fml.loading.moddiscovery; package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.UnmodifiableConfig; import com.google.common.collect.ImmutableMap;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.TypesafeMap;
import net.minecraftforge.fml.loading.EarlyLoadingException; import net.minecraftforge.fml.loading.EarlyLoadingException;
import net.minecraftforge.fml.loading.EarlyLoadingException.ExceptionData;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.forgespi.language.IModInfo; import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.forgespi.locating.IDependencyLocator; import net.minecraftforge.forgespi.locating.IDependencyLocator;
import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.forgespi.locating.IModFile.Type; import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import net.minecraftforge.jarjar.metadata.ContainedJarIdentifier;
import net.minecraftforge.jarjar.metadata.ContainedJarMetadata;
import net.minecraftforge.jarjar.metadata.ContainedVersion;
import net.minecraftforge.jarjar.metadata.MetadataIOHandler;
import net.minecraftforge.jarjar.selection.JarSelector; import net.minecraftforge.jarjar.selection.JarSelector;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.artifact.versioning.VersionRange;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.module.ModuleDescriptor;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem; import java.nio.file.FileSystem;
import java.nio.file.FileSystems; import java.nio.file.FileSystems;
import java.nio.file.Files; import java.nio.file.Files;
@@ -45,20 +28,14 @@ import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.StringJoiner; import java.util.Optional;
import java.util.TreeMap;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApiStatus.Internal @ApiStatus.Internal
public class JarInJarDependencyLocator extends AbstractModProvider implements IDependencyLocator { public class JarInJarDependencyLocator extends AbstractModProvider implements IDependencyLocator {
private static final String ROIMFS = "roimfs";
private static final String COLOR_CODE = "\u00a7"; private static final String COLOR_CODE = "\u00a7";
private static final String RESET = COLOR_CODE + "r"; private static final String RESET = COLOR_CODE + "r";
private static final String YELLOW = COLOR_CODE + "e"; private static final String YELLOW = COLOR_CODE + "e";
@@ -66,238 +43,32 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
private static final String GREEN = COLOR_CODE + "2"; private static final String GREEN = COLOR_CODE + "2";
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final Marker MARKER = MarkerFactory.getMarker("JAR-JAR"); // LogMarkers.SCAN;
private static final Map<Path, Option> OPTIONS = new HashMap<>();
private static volatile boolean optionsLoaded = false;
private static final Attributes.Name MIXIN_CONFIGS_ATTR = new Attributes.Name("MixinConfigs");
private static final Attributes.Name MIXIN_CONNECTOR_ATTR = new Attributes.Name("MixinConnector");
private static final ContainedJarMetadata MIXIN_EXTRAS_DEPENDENCY = makeMixinExtraDependency();
private static ContainedJarMetadata makeMixinExtraDependency() {
VersionRange range = null;
try {
range = VersionRange.createFromVersionSpec("[0,)");
} catch (InvalidVersionSpecificationException e) {
throw new RuntimeException("Failed to create version range for mixinextras-forge dependency", e);
}
return new ContainedJarMetadata(
new ContainedJarIdentifier("io.github.llamalad7", "mixinextras-forge"),
new ContainedVersion(range, null),
null, false
);
}
@Override @Override
public String name() { public String name() {
return "JarInJar"; return "JarInJar";
} }
private int fsID = 0;
private synchronized int nextId() {
return fsID++;
}
@Override @Override
public List<IModFile> scanMods(Iterable<IModFile> loadedMods) { public List<IModFile> scanMods(Iterable<IModFile> loadedMods) {
var mods = new ArrayList<IModFile>(); final List<IModFile> sources = new ArrayList<>();
loadedMods.forEach(mods::add); loadedMods.forEach(sources::add);
var selector = new Selector(mods); var dependenciesToLoad = JarSelector.detectAndSelect(
sources,
this::loadResourceFromModFile,
this::loadModFileFrom,
this::identifyMod,
this::exception
);
// Add a synthetic Mixin-Extras dependency if we detect anyone using Mixin if (dependenciesToLoad.isEmpty()) {
if (anyMixinsLoaded(mods)) {
if (!selector.isRequired(MIXIN_EXTRAS_DEPENDENCY.identifier()))
selector.addRequirement(MIXIN_EXTRAS_DEPENDENCY);
} else if (selector.entries.size() == mods.size()) {
LOGGER.info("No dependencies to load found. Skipping!"); LOGGER.info("No dependencies to load found. Skipping!");
return Collections.emptyList(); return Collections.emptyList();
} }
loadOptions(); LOGGER.info("Found {} dependencies adding them to mods collection", dependenciesToLoad.size());
return dependenciesToLoad;
// Ideally, the json would be in order so we only have to loop once. But its written this way just in case.
var seen = new HashSet<Option>();
var added = false;
do {
added = false;
for (var entry : OPTIONS.values()) {
if (seen.contains(entry) || !selector.isRequired(entry.meta.identifier()))
continue;
seen.add(entry);
entry.addTo(selector);
if (entry.deps != null && !entry.deps.isEmpty()) {
added = true;
for (var dep : entry.deps)
selector.addRequirement(dep);
}
}
} while (added);
var selected = selector.select();
if (LOGGER.isDebugEnabled()) {
var ids = new TreeMap<String, List<Entry>>();
for (var entry : selector.entries.values()) {
if (entry != FAILED && entry.coord != null)
ids.computeIfAbsent(entry.coord, _ -> new ArrayList<>()).add(entry);
}
for (var entry : ids.entrySet()) {
LOGGER.info(MARKER, "JarJar Candidated for {}", entry.getKey());
Collections.sort(entry.getValue());
for (var option : entry.getValue())
LOGGER.info(MARKER, "\t{}{}", selected.contains(option) ? '*' : ' ', option);
}
}
if (selected.isEmpty()) {
LOGGER.info("No dependencies to load found. Skipping!");
return Collections.emptyList();
}
/* Since Java 11, the JRE decompresses all zip files to memory when getting a ByteChannel for them.
* JarJar only targets Minecraft 1.18+ which is Java17+ Which means we can exploit the fact that
* these are Disjointed file systems, and close all unselected libraries.
*
* https://github.com/openjdk/jdk11u/blob/25a9b9e5594e88c9e1e66f95c7ca45d5a9da8854/src/jdk.zipfs/share/classes/jdk/nio/zipfs/ZipFileSystem.java#L703
*
* Combined with the fact that the JarJarFileSystem has always simply called into FileSystems.newFileSystem for its wrapped targets.
* https://github.com/MinecraftForge/JarJar/blame/b39b2051439c81519d826d38898778bf3081356f/src/main/java/net/minecraftforge/jarjar/nio/pathfs/PathFileSystem.java#L38
*
* This effectively means that JarJar has ALWAYS been a wrapper around in-memory copies of every jar it scans.
*
* It also never closes these FileSystems, which potentially means they are leaked if the GC can't inherently GC them.
*
* Ideally we would extract these contained jars to a temp folder, so that we can use the nice optimizations Java has for ZipFile/JarFile.
* But in order to do that we would need to write the file to a place that could potentially have conflicts.
* To resolve those conflicts we should take a hint out of maven/gradle/minecraft's book and key the filepath based on a hash of the file being extracted.
* However, because that hash is no available in existing metadata we would need to re-calculate it.
*
* To do it in an efficient way we I needed to be able to share the single opened FileSystem with both the SecureJar implementation, and with our recursive search.
* So I use my new ReadOnlyInMemoryFileSystem which is specifically designed to use the same backing array for the JarInJar search as it does with the resulting dependency
* selected SecureJars.
*
* This means that if we wanted to we could rather efficiently calculate a hash for extracting the file. However, it also means that we don't have to extract to file to
* support ZipFileSystem caching properly. So as long as we are okay with not using the JRE's optimized ZipFile implementation, or we want to support legacy JarInJar metadata,
* using this efficient in memory file system is the best option performance wise. Extracting the files during launch without an efficient caching/unique identifier system
* would incur a lot of Disc IO which can be super slow depending on your setup.
*
* So, it is a stated goal of our future re-write to extract files into a cache directory to gain the benefits of JRE optimizations, using a FileSystem much simpler then
* the existing JarInJarFileSystem is good enough.
*/
// Lets close all unselected FileSystems
var wasSelected = new HashSet<>(selected);
for (var entry : selector.entries.values())
entry.cleanup(wasSelected.contains(entry));
LOGGER.info(MARKER, "Found {} dependencies adding them to mods collection", selected.size());
var ret = new ArrayList<IModFile>(selected.size());
// Now lets build the actual mod files
for (var entry : selected) {
try {
var root = entry.getFinalPath();
var mod = createMod(root, false, entry.type.name());
if (mod.ex() != null)
throw fail("Failed to load JarInJar file " + entry, mod.ex());
ret.add(mod.file());
} catch (EarlyLoadingException e) {
throw e;
} catch (Throwable e) {
throw fail("Failed to load JarInJar file " + entry, e);
}
}
return ret;
}
private static Boolean anyMixinsLoaded = null;
private static boolean anyMixinsLoaded(List<IModFile> mods) {
var ret = anyMixinsLoaded;
if (ret != null) return ret;
if (!FMLEnvironment.production
&& Launcher.INSTANCE.blackboard().get(TypesafeMap.Key.getOrCreate(Launcher.INSTANCE.blackboard(), "isMixinEnabledInDev", Boolean.class)).orElse(false)) {
anyMixinsLoaded = true;
return true;
}
for (var mod : mods) {
var attributes = mod.getSecureJar().moduleDataProvider().getManifest().getMainAttributes();
if (attributes.getValue(MIXIN_CONFIGS_ATTR) != null || attributes.getValue(MIXIN_CONNECTOR_ATTR) != null) {
anyMixinsLoaded = true;
return true;
}
}
anyMixinsLoaded = false;
return false;
}
private record Options(List<OptionMetadata> options) {}
private record OptionMetadata(String resource, Type layer, String id, List<ContainedJarMetadata> deps, ContainedJarMetadata meta, boolean nested) {}
private static void loadOptions() {
if (optionsLoaded)
return;
synchronized (OPTIONS) {
if (optionsLoaded)
return;
optionsLoaded = true;
var self = JarInJarDependencyLocator.class;
try (var stream = self.getModule().getResourceAsStream("/jarjar_options.json")) {
if (stream == null) {
LOGGER.error(MARKER, "Failed to find jarjar_options.json");
return;
}
var meta = MetadataIOHandler.getGson().fromJson(new InputStreamReader(stream), Options.class);
//var meta = MetadataIOHandler.fromStream(stream).orElse(null);
if (meta == null) {
LOGGER.error(MARKER, "Corrupted jarjar_options.json");
return;
}
for (var jar : meta.options()) {
Path path = ClasspathLocator.getPathFromResource(self.getClassLoader(), jar.resource());
if (path == null) {
LOGGER.error(MARKER, "Failed to find JarJar option for {}", jar.resource());
continue;
}
LOGGER.debug(MARKER, "Found JarJar Option: {}", path.toAbsolutePath());
if (jar.nested())
OPTIONS.put(path, new NestedOption(jar.id(), path, jar.layer(), jar.meta(), jar.deps()));
else
OPTIONS.put(path, new Option(jar.id(), path, jar.layer(), jar.meta(), jar.deps()));
}
} catch (Throwable e) {
LOGGER.error(MARKER, "Failed to read JarJar Options file", e);
}
}
}
static boolean isOption(Path path) {
loadOptions();
return OPTIONS.containsKey(path);
}
private static EarlyLoadingException fail(String message, @Nullable Throwable cause) {
LOGGER.error(MARKER, message);
return new EarlyLoadingException(message, cause, Collections.emptyList());
} }
@Override @Override
@@ -305,7 +76,89 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
return IModFile.Type.GAMELIBRARY.name(); return IModFile.Type.GAMELIBRARY.name();
} }
protected static String identifyMod(IModFile modFile) { protected Optional<IModFile> loadModFileFrom(IModFile file, Path path) {
try {
final Path pathInModFile = file.findResource(path.toString());
final URI filePathUri = new URI("jij:" + (pathInModFile.toAbsolutePath().toUri().getRawSchemeSpecificPart())).normalize();
final Map<String, ?> outerFsArgs = ImmutableMap.of("packagePath", pathInModFile);
final FileSystem zipFS = FileSystems.newFileSystem(filePathUri, outerFsArgs);
final Path pathInFS = zipFS.getPath("/");
final IModFile.Type parentType = file.getType();
final String modType;
if (parentType == IModFile.Type.LIBRARY || parentType == IModFile.Type.LANGPROVIDER) {
modType = IModFile.Type.LIBRARY.name();
} else {
modType = IModFile.Type.GAMELIBRARY.name();
}
return Optional.of(createMod(pathInFS, false, modType).file());
} catch (Exception e) {
LOGGER.error("Failed to load mod file {} from {}", path, file.getFileName());
final RuntimeException exception = new ModFileLoadingException("Failed to load mod file " + file.getFileName());
exception.initCause(e);
throw exception;
}
}
protected EarlyLoadingException exception(Collection<JarSelector.ResolutionFailureInformation<IModFile>> failedDependencies) {
final List<EarlyLoadingException.ExceptionData> errors = failedDependencies.stream()
.filter(entry -> !entry.sources().isEmpty()) //Should never be the case, but just to be sure
.map(JarInJarDependencyLocator::buildExceptionData)
.toList();
return new EarlyLoadingException(failedDependencies.size() + " Dependency restrictions were not met.", null, errors);
}
@NotNull
private static EarlyLoadingException.ExceptionData buildExceptionData(JarSelector.ResolutionFailureInformation<IModFile> entry) {
return new EarlyLoadingException.ExceptionData(
getErrorTranslationKey(entry),
entry.identifier().group() + ":" + entry.identifier().artifact(),
entry.sources()
.stream()
.flatMap(JarInJarDependencyLocator::getModWithVersionRangeStream)
.map(JarInJarDependencyLocator::formatError)
.collect(Collectors.joining(", "))
);
}
@NotNull
private static String getErrorTranslationKey(JarSelector.ResolutionFailureInformation<IModFile> entry) {
return entry.failureReason() == JarSelector.FailureReason.VERSION_RESOLUTION_FAILED ?
"fml.dependencyloading.conflictingdependencies" :
"fml.dependencyloading.mismatchedcontaineddependencies";
}
@NotNull
private static Stream<ModWithVersionRange> getModWithVersionRangeStream(JarSelector.SourceWithRequestedVersionRange<IModFile> file) {
return file.sources()
.stream()
.map(IModFile::getModFileInfo)
.flatMap(modFileInfo -> modFileInfo.getMods().stream())
.map(modInfo -> new ModWithVersionRange(modInfo, file.requestedVersionRange(), file.includedVersion()));
}
protected Optional<InputStream> loadResourceFromModFile(IModFile modFile, Path path) {
try {
var pathInModFile = modFile.findResource(path.toString());
if (!Files.exists(pathInModFile)) {
LOGGER.debug("Failed to load resource {} from {}, it does not contain dependency information.", path, modFile.getFileName());
return Optional.empty();
}
return Optional.of(Files.newInputStream(pathInModFile));
} catch (Exception e) {
LOGGER.error("Failed to load resource {} from mod {}, cause {}", path, modFile.getFileName(), e);
return Optional.empty();
}
}
@NotNull
private static String formatError(ModWithVersionRange modWithVersionRange){
return YELLOW + modWithVersionRange.modInfo().getModId() + RESET + " - " +
RED + modWithVersionRange.versionRange().toString() + RESET + " - " +
GREEN + modWithVersionRange.artifactVersion().toString() + RESET;
}
protected String identifyMod(IModFile modFile) {
if (modFile.getModFileInfo() != null && !modFile.getModInfos().isEmpty()) if (modFile.getModFileInfo() != null && !modFile.getModInfos().isEmpty())
return modFile.getModInfos().stream().map(IModInfo::getModId).collect(Collectors.joining()); return modFile.getModInfos().stream().map(IModInfo::getModId).collect(Collectors.joining());
@@ -316,377 +169,5 @@ public class JarInJarDependencyLocator extends AbstractModProvider implements ID
return modFile.getFileName(); return modFile.getFileName();
} }
private static final Entry FAILED = new Entry("FAILED ENTRY", Path.of(""), Type.LIBRARY, null); private record ModWithVersionRange(IModInfo modInfo, VersionRange versionRange, ArtifactVersion artifactVersion) {}
private static sealed class Entry implements Comparable<Entry> {
final String id;
final Path path;
final Type type;
final @Nullable String coord;
private Entry(String id, Path path, Type type, @Nullable String coord) {
this.id = id;
this.path = path;
this.type = type;
this.coord = coord;
}
Path getFinalPath() {
return path;
}
void cleanup(boolean selected) {
}
@Override
public String toString() {
if (path.getFileName() == null)
return path.toUri().toString();
return path.getFileName().toString();
}
@Nullable
Path getResource(String path) {
return null;
}
@Override
public int compareTo(Entry o) {
return o.toString().compareTo(toString());
}
}
private static final class ModEntry extends Entry {
private final IModFile mod;
ModEntry(IModFile mod) {
super(identifyMod(mod), mod.getFilePath(), mod.getType(), null);
this.mod = mod;
}
@Override
@Nullable
Path getResource(String path) {
return mod.findResource(path);
}
}
private static sealed class Option extends Entry {
final ContainedJarMetadata meta;
final List<ContainedJarMetadata> deps;
private Option(String id, Path path, Type type, ContainedJarMetadata meta, List<ContainedJarMetadata> deps) {
super(id, path, type, meta.identifier().group() + ':' + meta.identifier().artifact());
this.meta = meta;
this.deps = deps;
}
public void addTo(Selector selector) {
selector.option(this, meta);
}
}
private static final class NestedOption extends Option {
private FileSystem zip;
private Path root;
private NestedOption(String id, Path path, Type type, ContainedJarMetadata meta, List<ContainedJarMetadata> deps) {
super(id, path, type, meta, deps);
}
@Override
public void addTo(Selector selector) {
super.addTo(selector);
selector.add(this);
}
@Override
void cleanup(boolean selected) {
if (this.zip != null) {
try {
zip.close();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to close unselected FileSystem {}", this, e);
}
}
}
@Nullable
Path getResource(String path) {
if (zip == null) {
try {
this.zip = FileSystems.newFileSystem(this.path);
this.root = zip.getRootDirectories().iterator().next();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to open FileSystem for option root {}", this, e);
return null;
}
}
var target = root.resolve(path);
if (Files.exists(target))
return target;
return null;
}
}
private static final class Nested extends Entry {
private final Entry parent;
private final String nestedPath;
private final Path zipPath;
Nested(String id, Path path, Type type, String coords, Entry parent, String nestedPath, Path zipPath) {
super(id, path, type, coords);
this.parent = parent;
this.nestedPath = nestedPath;
this.zipPath = zipPath;
}
/*
* Due to a bug in Mixin, anything that is not on the DefaultFileSystem MUST be a directory.
* Or else it can't resolve resources correctly. So for anything we put on the roimfs we need
* to return the nested zip file system.
*
* This will be an annoying to backport, but we can cross that bridge when we come to it.
*
* See: https://github.com/SpongePowered/Mixin/blob/4053421aa10aaac6127d969028a29c94fe3054f6/src/main/java/org/spongepowered/asm/launch/platform/MainAttributes.java#L102
*/
@Override
public Path getFinalPath() {
return zipPath;
}
@Override
void cleanup(boolean selected) {
if (selected)
return;
LOGGER.info(MARKER, "Closeing unselected FileSystem {}", this);
try {
zipPath.getFileSystem().close();
path.getFileSystem().close();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to close unselected FileSystem {}", this, e);
}
}
@Override
@Nullable
Path getResource(String path) {
return zipPath.resolve(path);
}
@Override
public String toString() {
return parent + "!/" + nestedPath;
}
}
private record Key(Entry parent, String path) {}
private final class Selector extends JarSelector<Entry> {
private final HashMap<Key, Entry> entries = new HashMap<>();
private final HashMap<Entry, HashMap<String, String>> children = new HashMap<>();
private Selector(Iterable<IModFile> mods) {
for (var mod : mods)
this.force(new ModEntry(mod));
}
@Override
public void force(Entry entry) {
super.force(entry);
entries.put(new Key(entry, ""), entry);
}
@Override
public void option(Entry entry, ContainedJarMetadata meta) {
super.option(entry, meta);
entries.put(new Key(entry, ""), entry);
}
@Override
public void add(Entry entry) {
super.add(entry);
entries.put(new Key(entry, ""), entry);
}
@Override
@Nullable
protected InputStream getResource(Entry source, String path) {
try {
Path target = source.getResource(path);
if (target == null || !Files.exists(target)) {
LOGGER.debug(MARKER, "Failed to load resource {} from {}, it does not contain dependency information.", path, source);
return null;
}
// Read the metadata file and store identifiers so we can group them later.
if (JarSelector.CONTAINED_JARS_METADATA_PATH.equals(path)) {
try (var is = Files.newInputStream(target)) {
var meta = MetadataIOHandler.fromStream(is).orElse(null);
if (meta == null)
return Files.newInputStream(target);
var children = new HashMap<String, String>();
for (var child : meta.jars())
children.put(child.path().replace('\\', '/'), child.identifier().group() + ':' + child.identifier().artifact());
this.children.put(source, children);
}
}
return Files.newInputStream(target);
} catch (Exception e) {
LOGGER.error(MARKER, "Failed to load resource {} from {}, cause {}", path, source, e);
return null;
}
}
@Override
protected Entry getNested(Entry source, String path) {
var cleaned = path.replace('\\', '/');
var key = new Key(source, cleaned);
var entry = entries.get(key);
if (entry == null) {
entry = createNested(source, path, cleaned);
if (entry == null)
entry = FAILED;
entries.put(key, entry);
}
return entry == FAILED ? null : entry;
}
private Entry createNested(Entry source, String path, String cleaned) {
var targetPath = source.getResource(path);
if (targetPath == null || !Files.isRegularFile(targetPath))
return null;
Path roimfsPath = null;
Path zipPath = null;
try {
// Lets copy the uncompressed file to memory, and then create a ReadOnlyInMemorryFileSystem for it, this allows us to reference it by URI.
// Which is needed because a lot of things require navigation via URI.
// And ZipFileSystem only caches the FileSystem instance when accessed via URI.
byte[] data = Files.readAllBytes(targetPath);
String filename = targetPath.getFileName().toString();
URI uri = new URI(ROIMFS, "jar-jar-" + nextId() + "/" + filename, null);
var roimfs = FileSystems.newFileSystem(uri, Collections.singletonMap("data", data));
roimfsPath = roimfs.getPath(filename);
var zip = FileSystems.newFileSystem(new URI("jar:" + roimfsPath.toUri()), Collections.emptyMap());
zipPath = zip.getRootDirectories().iterator().next(); // Get first root, which on ZipFileSystem is the only root
} catch (IOException | URISyntaxException e) {
LOGGER.error(MARKER, "Failed to create FileSystem for nested jar {}", source, e);
return null;
}
var mf = new Manifest();
var mfPath = zipPath.resolve(JarFile.MANIFEST_NAME);
if (Files.exists(mfPath)) {
try (var is = Files.newInputStream(mfPath)) {
mf = new Manifest(is);
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to read manifest from {}", source, e);
}
}
IModFile.Type type = null;
String id = null;
var tomlPath = zipPath.resolve(MODS_TOML);
if (Files.exists(tomlPath)) {
var cfg = FileConfig.builder(tomlPath).build();
cfg.load();
cfg.close();
if (cfg.getOrElse("mods", null) instanceof Collection collection) {
@SuppressWarnings("unchecked")
var mods = (Collection<UnmodifiableConfig>)collection;
if (!mods.isEmpty()) {
var first = mods.iterator().next();
var modId = first.getOrElse("modId", null);
if (modId instanceof String str)
id = str;
}
}
var value = mf.getMainAttributes().getValue(ModFile.TYPE);
if (value != null)
type = IModFile.Type.valueOf(value);
else
type = IModFile.Type.MOD;
} else {
var value = mf.getMainAttributes().getValue(ModFile.TYPE);
if (value != null)
type = IModFile.Type.valueOf(value);
else {
// No mods.toml, no entry value, so decide based on the container's type
if (source.type == IModFile.Type.LIBRARY || source.type == IModFile.Type.LANGPROVIDER)
type = IModFile.Type.LIBRARY;
else
type = IModFile.Type.GAMELIBRARY;
}
}
if (id == null) {
var modulePath = zipPath.resolve(MODULE_INFO);
if (Files.exists(modulePath)) {
try (var is = Files.newInputStream(modulePath)) {
var module = ModuleDescriptor.read(is);
id = module.name();
} catch (IOException e) {
LOGGER.error(MARKER, "Failed to read module-info.class from {}", source, e);
}
}
}
if (id == null)
id = mf.getMainAttributes().getValue("Automatic-Module-Name");
if (id == null)
id = Path.of(path).getFileName().toString();
String coords = null;
var child = this.children.get(source);
if (child != null)
coords = child.get(cleaned);
return new Nested(id, roimfsPath, type, coords, source, cleaned, zipPath);
}
@Override
protected String getIdentifier(Entry entry) {
return entry.id;
}
@Override
protected Throwable getFailureException(Collection<ResolutionFailureInformation<Entry>> failures) {
var errors = new ArrayList<ExceptionData>();
for (var failure : failures) {
var message = failure.failureReason() == JarSelector.FailureReason.VERSION_RESOLUTION_FAILED ? "fml.dependencyloading.conflictingdependencies" : "fml.dependencyloading.mismatchedcontaineddependencies";
var joiner = new StringJoiner(", ");
for (var source : failure.sources()) {
String paths = null;
if (source.sources().size() == 0) {
paths = "[No Sources]";
} else if (source.sources().size() == 1) {
var entry = source.sources().iterator().next();
paths = entry.toString();
} else {
var j = new StringJoiner(", ", "[", "]");
for (var entry : source.sources())
j.add(entry.toString());
paths = j.toString();
}
var error = YELLOW + paths + RESET + " - " +
RED + source.requestedVersionRange() + RESET + " - " +
GREEN + source.includedVersion() + RESET;
joiner.add(error);
}
errors.add(new ExceptionData(message, failure.identifier().group() + ":" + failure.identifier().artifact(), joiner.toString()));
}
return new EarlyLoadingException(failures.size() + " Dependency restrictions were not met.", null, errors);
}
}
} }
@@ -14,7 +14,6 @@ import net.minecraftforge.forgespi.locating.IModLocator;
import net.minecraftforge.forgespi.locating.ModFileFactory; import net.minecraftforge.forgespi.locating.ModFileFactory;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.ApiStatus;
@@ -27,7 +26,7 @@ public final class MinecraftLocator extends AbstractModProvider implements IModL
// Minecraft itself. // Minecraft itself.
var meta = new ModJarMetadata(); var meta = new ModJarMetadata();
var mcjar = SecureJar.from(_ -> meta, paths); var mcjar = SecureJar.from(jar -> meta, paths);
var mc = ModFileFactory.FACTORY.build(mcjar, this, MinecraftLocator::buildMinecraftTOML); var mc = ModFileFactory.FACTORY.build(mcjar, this, MinecraftLocator::buildMinecraftTOML);
meta.setModFile(mc); meta.setModFile(mc);
@@ -58,9 +57,4 @@ public final class MinecraftLocator extends AbstractModProvider implements IModL
public String name() { public String name() {
return "minecraft"; return "minecraft";
} }
@Override
public void scanFile(IModFile file, Consumer<Path> pathConsumer) {
// skip annotation scanning for MC itself
}
} }
@@ -19,7 +19,7 @@ import org.objectweb.asm.Type;
import com.google.common.base.MoreObjects; import com.google.common.base.MoreObjects;
@ApiStatus.Internal @ApiStatus.Internal
final class ModAnnotation { class ModAnnotation {
public static ModFileScanData.AnnotationData fromModAnnotation(Type clazz, ModAnnotation annotation) { public static ModFileScanData.AnnotationData fromModAnnotation(Type clazz, ModAnnotation annotation) {
return new ModFileScanData.AnnotationData(annotation.asmType, annotation.type, clazz, annotation.member, annotation.values); return new ModFileScanData.AnnotationData(annotation.asmType, annotation.type, clazz, annotation.member, annotation.values);
} }
@@ -84,7 +84,6 @@ final class ModAnnotation {
} }
public void endArray() { public void endArray() {
arrayList.trimToSize();
values.put(arrayName, arrayList); values.put(arrayName, arrayList);
arrayList = null; arrayList = null;
} }
@@ -22,47 +22,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ApiStatus.Internal @ApiStatus.Internal
final class ModClassVisitor extends ClassVisitor { class ModClassVisitor extends ClassVisitor {
private static final Set<String> ANNOTATION_BLACKLIST;
private static final Type OBJECT_TYPE = Type.getObjectType("java/lang/Object");
private static final Type RECORD_TYPE = Type.getObjectType("java/lang/Record");
static {
var customBlacklist = System.getProperty("forge.annotationScanningBlacklist");
if (customBlacklist != null) {
ANNOTATION_BLACKLIST = Set.of(customBlacklist.split(","));
} else {
ANNOTATION_BLACKLIST = Set.of(
"Ljava/lang/Deprecated;",
"Ljava/lang/FunctionalInterface;",
"Ljava/lang/SafeVarargs;",
"Ljava/lang/annotation/Retention;",
"Ljava/lang/annotation/Target;",
"Ljavax/annotation/Nullable;",
"Lorg/jspecify/nullness/NonNull;",
"Lorg/jspecify/nullness/Nullable;",
"Lorg/jspecify/annotations/NullMarked;",
"Lorg/jspecify/annotations/NullUnmarked;",
"Lorg/jetbrains/annotations/ApiStatus$Internal;",
"Lorg/jetbrains/annotations/Contract;",
"Lorg/jetbrains/annotations/Nullable;",
"Lorg/jetbrains/annotations/NotNull;",
"Lorg/jetbrains/annotations/VisibleForTesting;",
"Lcom/google/common/annotations/VisibleForTesting;",
"Lnet/minecraftforge/api/distmarker/OnlyIn", // should not be used by mods
// @Mod.EventBusSubscriber doesn't use scan data for finding @SubscribeEvent annotated methods
"Lnet/minecraftforge/eventbus/api/listener/SubscribeEvent;"
);
}
}
private Type asmType; private Type asmType;
private Type asmSuperType; private Type asmSuperType;
private Set<Type> interfaces; private Set<Type> interfaces;
@@ -75,17 +35,12 @@ final class ModClassVisitor extends ClassVisitor {
@Override @Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
this.asmType = Type.getObjectType(name); this.asmType = Type.getObjectType(name);
this.asmSuperType = superName != null && !superName.isEmpty() ? switch (superName) { this.asmSuperType = superName != null && !superName.isEmpty() ? Type.getObjectType(superName) : null;
case "java/lang/Object" -> OBJECT_TYPE;
case "java/lang/Record" -> RECORD_TYPE;
default -> Type.getObjectType(superName);
} : null;
this.interfaces = Stream.of(interfaces).map(Type::getObjectType).collect(Collectors.toSet()); this.interfaces = Stream.of(interfaces).map(Type::getObjectType).collect(Collectors.toSet());
} }
@Override @Override
public AnnotationVisitor visitAnnotation(final String annotationName, final boolean runtimeVisible) { public AnnotationVisitor visitAnnotation(final String annotationName, final boolean runtimeVisible) {
if (ANNOTATION_BLACKLIST.contains(annotationName)) return null;
var ann = new ModAnnotation(ElementType.TYPE, Type.getType(annotationName), this.asmType.getClassName()); var ann = new ModAnnotation(ElementType.TYPE, Type.getType(annotationName), this.asmType.getClassName());
annotations.addFirst(ann); annotations.addFirst(ann);
return new ModAnnotationVisitor(ann); return new ModAnnotationVisitor(ann);
@@ -96,7 +51,6 @@ final class ModClassVisitor extends ClassVisitor {
return new FieldVisitor(Opcodes.ASM9) { return new FieldVisitor(Opcodes.ASM9) {
@Override @Override
public AnnotationVisitor visitAnnotation(String annotationName, boolean runtimeVisible) { public AnnotationVisitor visitAnnotation(String annotationName, boolean runtimeVisible) {
if (ANNOTATION_BLACKLIST.contains(annotationName)) return null;
var ann = new ModAnnotation(ElementType.FIELD, Type.getType(annotationName), name); var ann = new ModAnnotation(ElementType.FIELD, Type.getType(annotationName), name);
annotations.addFirst(ann); annotations.addFirst(ann);
return new ModAnnotationVisitor(ann); return new ModAnnotationVisitor(ann);
@@ -109,7 +63,6 @@ final class ModClassVisitor extends ClassVisitor {
return new MethodVisitor(Opcodes.ASM9) { return new MethodVisitor(Opcodes.ASM9) {
@Override @Override
public AnnotationVisitor visitAnnotation(String annotationName, boolean runtimeVisible) { public AnnotationVisitor visitAnnotation(String annotationName, boolean runtimeVisible) {
if (ANNOTATION_BLACKLIST.contains(annotationName)) return null;
ModAnnotation ann = new ModAnnotation(ElementType.METHOD, Type.getType(annotationName), name + desc); ModAnnotation ann = new ModAnnotation(ElementType.METHOD, Type.getType(annotationName), name + desc);
annotations.addFirst(ann); annotations.addFirst(ann);
return new ModAnnotationVisitor(ann); return new ModAnnotationVisitor(ann);
@@ -125,7 +78,7 @@ final class ModClassVisitor extends ClassVisitor {
} }
} }
private final class ModAnnotationVisitor extends AnnotationVisitor { private class ModAnnotationVisitor extends AnnotationVisitor {
private final ModAnnotation annotation; private final ModAnnotation annotation;
private boolean array; private boolean array;
private boolean isSubAnnotation; private boolean isSubAnnotation;
@@ -5,6 +5,7 @@
package net.minecraftforge.fml.loading.moddiscovery; package net.minecraftforge.fml.loading.moddiscovery;
import com.google.common.collect.ImmutableList;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import cpw.mods.modlauncher.Launcher; import cpw.mods.modlauncher.Launcher;
import cpw.mods.modlauncher.api.IModuleLayerManager; import cpw.mods.modlauncher.api.IModuleLayerManager;
@@ -34,37 +35,41 @@ import java.util.ServiceLoader;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ApiStatus.Internal @ApiStatus.Internal
public final class ModDiscoverer { public class ModDiscoverer {
private ModDiscoverer() {}
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private final ServiceLoader<IModLocator> modLocators;
private final ServiceLoader<IDependencyLocator> dependencyLocators;
private final List<IModLocator> modLocatorList;
private final List<IDependencyLocator> dependencyLocatorList;
@SuppressWarnings("removal") public ModDiscoverer(Map<String, ?> arguments) {
public static ModValidator discoverMods(Map<String, ?> arguments) { Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), v->ModsFolderLocator::new);
var env = Launcher.INSTANCE.environment(); Launcher.INSTANCE.environment().computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), v-> StartupNotificationManager.locatorConsumer().orElseGet(()-> s->{}));
env.computePropertyIfAbsent(Environment.Keys.MODDIRECTORYFACTORY.get(), _ -> ModsFolderLocator::new); final var moduleLayerManager = Launcher.INSTANCE.environment().findModuleLayerManager().orElseThrow();
env.computePropertyIfAbsent(Environment.Keys.PROGRESSMESSAGE.get(), _ -> StartupNotificationManager.locatorConsumer().orElse(_ -> {})); modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class);
final var moduleLayerManager = env.findModuleLayerManager().orElseThrow(); dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
ServiceLoader<IModLocator> modLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IModLocator.class); modLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> modLocators, sce->LOGGER.error("Failed to load mod locator list", sce)).collect(Collectors.toList());
ServiceLoader<IDependencyLocator> dependencyLocators = ServiceLoader.load(moduleLayerManager.getLayer(IModuleLayerManager.Layer.SERVICE).orElseThrow(), IDependencyLocator.class);
List<IModLocator> modLocatorList = ServiceLoaderUtils.streamWithErrorHandling(modLocators, sce -> LOGGER.error("Failed to load mod locator list", sce)).toList();
for (IModLocator iModLocator : modLocatorList) { for (IModLocator iModLocator : modLocatorList) {
iModLocator.initArguments(arguments); iModLocator.initArguments(arguments);
} }
List<IDependencyLocator> dependencyLocatorList = ServiceLoaderUtils.streamWithErrorHandling(dependencyLocators, sce -> LOGGER.error("Failed to load dependency locator list", sce)).toList(); dependencyLocatorList = ServiceLoaderUtils.streamServiceLoader(()-> dependencyLocators, sce->LOGGER.error("Failed to load dependency locator list", sce)).collect(Collectors.toList());
for (IDependencyLocator l : dependencyLocatorList) { for (IDependencyLocator l : dependencyLocatorList) {
l.initArguments(arguments); l.initArguments(arguments);
} }
if (LOGGER.isDebugEnabled(LogMarkers.CORE)) { if (LOGGER.isDebugEnabled(LogMarkers.CORE))
{
LOGGER.debug(LogMarkers.CORE, "Found Mod Locators : {}", modLocatorList.stream() LOGGER.debug(LogMarkers.CORE, "Found Mod Locators : {}", modLocatorList.stream()
.map(modLocator -> "(%s:%s)".formatted(modLocator.name(), .map(modLocator -> "(%s:%s)".formatted(modLocator.name(),
modLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(","))); modLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(",")));
LOGGER.debug(LogMarkers.CORE, "Found Dependency Locators : {}", dependencyLocatorList.stream() LOGGER.debug(LogMarkers.CORE, "Found Dependency Locators : {}", dependencyLocatorList.stream()
.map(dependencyLocator -> "(%s:%s)".formatted(dependencyLocator.name(), .map(dependencyLocator -> "(%s:%s)".formatted(dependencyLocator.name(),
dependencyLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(","))); dependencyLocator.getClass().getPackage().getImplementationVersion())).collect(Collectors.joining(",")));
} }
}
@SuppressWarnings("removal")
public ModValidator discoverMods() {
LOGGER.debug(LogMarkers.SCAN,"Scanning for mods and other resources to load. We know {} ways to find mods", modLocatorList.size()); LOGGER.debug(LogMarkers.SCAN,"Scanning for mods and other resources to load. We know {} ways to find mods", modLocatorList.size());
List<ModFile> loadedFiles = new ArrayList<>(); List<ModFile> loadedFiles = new ArrayList<>();
List<EarlyLoadingException.ExceptionData> discoveryErrorData = new ArrayList<>(); List<EarlyLoadingException.ExceptionData> discoveryErrorData = new ArrayList<>();
@@ -112,7 +117,7 @@ public final class ModDiscoverer {
} }
LOGGER.debug(LogMarkers.SCAN, "Locator {} found {} valid mod files", locator, locatedFiles.size()); LOGGER.debug(LogMarkers.SCAN, "Locator {} found {} valid mod files", locator, locatedFiles.size());
handleLocatedFiles(loadedFiles, locatedFiles, locator); handleLocatedFiles(loadedFiles, locatedFiles);
} catch (InvalidModFileException imfe) { } catch (InvalidModFileException imfe) {
// We don't generally expect this exception, since it should come from the candidates stream above and be handled in the Locator, but just in case. // We don't generally expect this exception, since it should come from the candidates stream above and be handled in the Locator, but just in case.
LOGGER.error(LogMarkers.SCAN, "Locator {} found an invalid mod file {}", locator, imfe.getBrokenFile(), imfe); LOGGER.error(LogMarkers.SCAN, "Locator {} found an invalid mod file {}", locator, imfe.getBrokenFile(), imfe);
@@ -126,7 +131,8 @@ public final class ModDiscoverer {
//First processing run of the mod list. Any duplicates will cause resolution failure and dependency loading will be skipped. //First processing run of the mod list. Any duplicates will cause resolution failure and dependency loading will be skipped.
Map<IModFile.Type, List<ModFile>> modFilesMap = new EnumMap<>(IModFile.Type.class); Map<IModFile.Type, List<ModFile>> modFilesMap = new EnumMap<>(IModFile.Type.class);
try { try {
final UniqueModListBuilder.UniqueModListData uniqueModsData = UniqueModListBuilder.buildUniqueList(loadedFiles); final UniqueModListBuilder modsUniqueListBuilder = new UniqueModListBuilder(loadedFiles);
final UniqueModListBuilder.UniqueModListData uniqueModsData = modsUniqueListBuilder.buildUniqueList();
//Grab the temporary results. //Grab the temporary results.
//This allows loading to continue to a base state, in case dependency loading fails. //This allows loading to continue to a base state, in case dependency loading fails.
@@ -146,10 +152,14 @@ public final class ModDiscoverer {
for (IDependencyLocator locator : dependencyLocatorList) { for (IDependencyLocator locator : dependencyLocatorList) {
try { try {
LOGGER.debug(LogMarkers.SCAN,"Trying locator {}", locator); LOGGER.debug(LogMarkers.SCAN,"Trying locator {}", locator);
final List<IModFile> locatedMods = List.copyOf(loadedFiles); final List<IModFile> locatedMods = ImmutableList.copyOf(loadedFiles);
var locatedFiles = locator.scanMods(locatedMods); var locatedFiles = locator.scanMods(locatedMods);
handleLocatedFiles(loadedFiles, locatedFiles, locator); if (locatedFiles.stream().anyMatch(file -> !(file instanceof ModFile))) {
LOGGER.error(LogMarkers.SCAN, "A dependency locator returned a file which is not a ModFile instance!. They will be skipped!");
}
handleLocatedFiles(loadedFiles, locatedFiles);
} }
catch (EarlyLoadingException exception) { catch (EarlyLoadingException exception) {
LOGGER.error(LogMarkers.SCAN, "Failed to load dependencies with locator {}", locator, exception); LOGGER.error(LogMarkers.SCAN, "Failed to load dependencies with locator {}", locator, exception);
@@ -159,7 +169,8 @@ public final class ModDiscoverer {
//Second processing run of the mod list. Any duplicates will cause resolution failure and only the mods list will be loaded. //Second processing run of the mod list. Any duplicates will cause resolution failure and only the mods list will be loaded.
try { try {
final UniqueModListBuilder.UniqueModListData uniqueModsAndDependenciesData = UniqueModListBuilder.buildUniqueList(loadedFiles); final UniqueModListBuilder modsAndDependenciesUniqueListBuilder = new UniqueModListBuilder(loadedFiles);
final UniqueModListBuilder.UniqueModListData uniqueModsAndDependenciesData = modsAndDependenciesUniqueListBuilder.buildUniqueList();
//We now only need the mod files map, not the list. //We now only need the mod files map, not the list.
modFilesMap = uniqueModsAndDependenciesData.modFiles().stream() modFilesMap = uniqueModsAndDependenciesData.modFiles().stream()
@@ -182,14 +193,11 @@ public final class ModDiscoverer {
return validator; return validator;
} }
private static void handleLocatedFiles(final List<ModFile> loadedFiles, final List<IModFile> locatedFiles, final Object locator) { private static void handleLocatedFiles(final List<ModFile> loadedFiles, final List<IModFile> locatedFiles) {
for (IModFile mf : locatedFiles) { var locatedModFiles = locatedFiles.stream().filter(ModFile.class::isInstance).map(ModFile.class::cast).toList();
if (mf instanceof ModFile modFile) { for (IModFile mf : locatedModFiles) {
LOGGER.info(LogMarkers.SCAN, "Found mod file {} of type {} with provider {}", mf.getFileName(), mf.getType(), mf.getProvider()); LOGGER.info(LogMarkers.SCAN, "Found mod file {} of type {} with provider {}", mf.getFileName(), mf.getType(), mf.getProvider());
loadedFiles.add(modFile);
} else {
LOGGER.error(LogMarkers.SCAN, "Skipping mod file {} found by {}, as it was not a ModFile instance!", mf.getFileName(), locator);
}
} }
loadedFiles.addAll(locatedModFiles);
} }
} }
@@ -8,7 +8,7 @@ package net.minecraftforge.fml.loading.moddiscovery;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import cpw.mods.jarhandling.SecureJar; import cpw.mods.jarhandling.SecureJar;
import net.minecraftforge.fml.loading.LanguageLoadingProvider; import net.minecraftforge.fml.loading.FMLLoader;
import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.forgespi.language.IModFileInfo; import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.language.IModInfo; import net.minecraftforge.forgespi.language.IModInfo;
@@ -21,12 +21,13 @@ import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.nio.file.FileSystems;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@@ -47,7 +48,9 @@ public class ModFile implements IModFile {
private final IModFileInfo modFileInfo; private final IModFileInfo modFileInfo;
private ModFileScanData fileModFileScanData; private ModFileScanData fileModFileScanData;
private CompletableFuture<ModFileScanData> futureScanResult; private CompletableFuture<ModFileScanData> futureScanResult;
private List<Path> accessTransformers = List.of(); private List<CoreModFile> coreMods;
private Path accessTransformer;
private List<Path> accessTransformers = Collections.emptyList();
static final Attributes.Name TYPE = new Attributes.Name("FMLModType"); static final Attributes.Name TYPE = new Attributes.Name("FMLModType");
private SecureJar.Status securityStatus; private SecureJar.Status securityStatus;
@@ -90,32 +93,53 @@ public class ModFile implements IModFile {
return modFileInfo.getMods(); return modFileInfo.getMods();
} }
/** @deprecated Use {@link #getAccessTransformers()} instead*/
@Deprecated(forRemoval=true, since="1.21.11")
public Optional<Path> getAccessTransformer() {
return Optional.ofNullable(accessTransformer);
}
public List<Path> getAccessTransformers() { public List<Path> getAccessTransformers() {
return this.accessTransformers; return accessTransformers;
} }
public boolean identifyMods() { public boolean identifyMods() {
if (this.modFileInfo == null) return this.getType() != Type.MOD; if (this.modFileInfo == null) return this.getType() != Type.MOD;
LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFileName(), this.modFileInfo.requiredLanguageLoaders()); LOGGER.debug(LogMarkers.LOADING,"Loading mod file {} with languages {}", this.getFilePath(), this.modFileInfo.requiredLanguageLoaders());
var cfg = this.modFileInfo.getConfig() this.coreMods = ModFileParser.getCoreMods(this);
.<List<String>>getConfigElement("accessTransformers") if (!this.coreMods.isEmpty())
.orElse(null); LOGGER.warn("Mod file {} contains javascript coremods! JS CoreMods are deprecated and will be removed in a future release. Consider using Mixin or ModLauncher transformers.", this.getFileName());
for (var mi : this.coreMods)
LOGGER.debug(LogMarkers.LOADING, "Found coremod {}", mi.getPath());
List<String> cfg;
// Note: Some mods may have invalid tomls copied from other projects.
// Unfortunately we must protect against those landmines.
try {
cfg = this.modFileInfo.getConfig().<List<String>>getConfigElement("accessTransformers").orElse(null);
} catch (Exception e) {
cfg = null;
LOGGER.warn("{} contains an invalid 'accessTransformers' TOML entry. Should be e.g. accessTransformers = [\"META-INF/accesstransformer.cfg\", \"META-INF/extra_at.cfg\"] or accessTransformers = [] for no ATs. Falling back to default.", this.getFileName());
}
if (cfg == null) { if (cfg == null) {
var path = findResource("META-INF", "accesstransformer.cfg"); var path = findResource("META-INF", "accesstransformer.cfg");
if (Files.exists(path)) { if (Files.exists(path)) {
this.accessTransformer = path;
this.accessTransformers = List.of(path); this.accessTransformers = List.of(path);
} }
} else if (!cfg.isEmpty()) { } else if (!cfg.isEmpty()) {
var paths = new ArrayList<Path>(cfg.size()); var paths = new ArrayList<Path>(cfg.size());
for (var path : cfg) for (var path : cfg) {
paths.add(getSecureJar().getPath(path.replace('\\', '/'))); paths.add(getSecureJar().getPath(path.replace("\\","/")));
}
this.accessTransformers = List.copyOf(paths); this.accessTransformers = List.copyOf(paths);
} }
return true; return true;
} }
public List<CoreModFile> getCoreMods() {
return coreMods;
}
/** /**
* Run in an executor thread to harvest the class and annotation list * Run in an executor thread to harvest the class and annotation list
*/ */
@@ -173,37 +197,22 @@ public class ModFile implements IModFile {
public void identifyLanguage() { public void identifyLanguage() {
var lst = new ArrayList<IModLanguageProvider>(this.modFileInfo.requiredLanguageLoaders().size()); var lst = new ArrayList<IModLanguageProvider>(this.modFileInfo.requiredLanguageLoaders().size());
var services = FMLLoader.getLanguageLoadingProvider();
for (var spec : this.modFileInfo.requiredLanguageLoaders()) { for (var spec : this.modFileInfo.requiredLanguageLoaders()) {
var service = LanguageLoadingProvider.findLanguage(this, spec.languageName(), spec.acceptedVersions()); var service = services.findLanguage(this, spec.languageName(), spec.acceptedVersions());
lst.add(service); lst.add(service);
} }
this.loaders = List.copyOf(lst); this.loaders = Collections.unmodifiableList(lst);
} }
@Override @Override
public String toString() { public String toString() {
var path = getFilePath(); return "Mod File: " + Objects.toString(this.jar.getPrimaryPath());
return "Mod File: " + path == null ? "null" : path.toUri().toString();
} }
@Override @Override
public String getFileName() { public String getFileName() {
// This is only used for debugging, so lets try and make it a useful debug return getFilePath().getFileName().toString();
var path = getFilePath();
var filename = path.getFileName();
// ZipFileSystem toString will return the outer file path
var ret = filename == null ? path.getFileSystem().toString() : filename.toString();
// If it's a directory on the default file system, return the full path
if (Files.isDirectory(path) && path.getFileSystem() == FileSystems.getDefault())
ret = path.toAbsolutePath().toString();
// If we are in a FileSystem 'root' like UnionFS, return the full uri
if (ret.isEmpty() || ret.equals("/"))
ret = path.toUri().toString();
return ret;
} }
@Override @Override
@@ -264,7 +264,7 @@ public class ModFileInfo implements IModFileInfo, IConfigurable {
@Override @Override
public String versionString() { public String versionString() {
return getMods().getFirst().getVersion().toString(); return getMods().get(0).getVersion().toString();
} }
@Override @Override
@@ -6,16 +6,25 @@
package net.minecraftforge.fml.loading.moddiscovery; package net.minecraftforge.fml.loading.moddiscovery;
import com.electronwill.nightconfig.core.file.FileConfig; import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.core.io.ParsingException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import net.minecraftforge.fml.loading.LogMarkers; import net.minecraftforge.fml.loading.LogMarkers;
import net.minecraftforge.forgespi.language.IModFileInfo; import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.locating.IModFile; import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.forgespi.locating.ModFileFactory; import net.minecraftforge.forgespi.locating.ModFileFactory;
import net.minecraftforge.forgespi.locating.ModFileLoadingException;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class ModFileParser { public class ModFileParser {
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
@@ -24,6 +33,7 @@ public class ModFileParser {
return parser.build(modFile); return parser.build(modFile);
} }
// Note: Although @Nullable, several other places in FML assume ModFileInfo is not null. Keep this in mind
public static @Nullable IModFileInfo modsTomlParser(final IModFile imodFile) { public static @Nullable IModFileInfo modsTomlParser(final IModFile imodFile) {
ModFile modFile = (ModFile) imodFile; ModFile modFile = (ModFile) imodFile;
LOGGER.debug(LogMarkers.LOADING,"Considering mod file candidate {}", modFile.getFilePath()); LOGGER.debug(LogMarkers.LOADING,"Considering mod file candidate {}", modFile.getFilePath());
@@ -34,9 +44,35 @@ public class ModFileParser {
} }
final FileConfig fileConfig = FileConfig.builder(modsjson).build(); final FileConfig fileConfig = FileConfig.builder(modsjson).build();
fileConfig.load(); try {
fileConfig.close(); fileConfig.load();
final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig); fileConfig.close();
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile); final NightConfigWrapper configWrapper = new NightConfigWrapper(fileConfig);
return new ModFileInfo(modFile, configWrapper, configWrapper::setFile);
} catch (ParsingException e) {
LOGGER.error("Mod candidate {} contains a corrupt or misconfigured toml.", modFile.getFileName());
throw new ModFileLoadingException("Mod candidate " + modFile.getFileName() + " contains a corrupt or misconfigured toml.");
}
}
protected static List<CoreModFile> getCoreMods(final ModFile modFile) {
Map<String,String> coreModPaths;
try {
final Path coremodsjson = modFile.findResource("META-INF", "coremods.json");
if (!Files.exists(coremodsjson)) {
return Collections.emptyList();
}
final Type type = new TypeToken<Map<String, String>>() {}.getType();
final Gson gson = new Gson();
coreModPaths = gson.fromJson(Files.newBufferedReader(coremodsjson), type);
} catch (IOException e) {
LOGGER.debug(LogMarkers.LOADING,"Failed to read coremod list coremods.json", e);
return Collections.emptyList();
}
return coreModPaths.entrySet().stream()
.peek(e-> LOGGER.debug(LogMarkers.LOADING,"Found coremod {} with Javascript path {}", e.getKey(), e.getValue()))
.map(e -> new CoreModFile(e.getKey(), modFile.findResource(e.getValue()),modFile))
.toList();
} }
} }
@@ -31,8 +31,10 @@ public class ModValidator {
private final List<ModFile> candidatePlugins; private final List<ModFile> candidatePlugins;
private final List<ModFile> candidateMods; private final List<ModFile> candidateMods;
private final List<ModFile> gameLibraries; private final List<ModFile> gameLibraries;
private LoadingModList loadingModList;
private final List<IModFile> brokenFiles = new ArrayList<>(); private final List<IModFile> brokenFiles = new ArrayList<>();
private final List<EarlyLoadingException.ExceptionData> discoveryErrorData; private final List<EarlyLoadingException.ExceptionData> discoveryErrorData;
private final List<ModFileLoadingException> modFileLoadingExceptions;
public ModValidator(Map<IModFile.Type, List<ModFile>> modFiles, List<IModFileInfo> brokenFiles, List<EarlyLoadingException.ExceptionData> discoveryErrorData, List<ModFileLoadingException> modFileLoadingExceptions) { public ModValidator(Map<IModFile.Type, List<ModFile>> modFiles, List<IModFileInfo> brokenFiles, List<EarlyLoadingException.ExceptionData> discoveryErrorData, List<ModFileLoadingException> modFileLoadingExceptions) {
this.candidateMods = lst(modFiles.get(IModFile.Type.MOD)); this.candidateMods = lst(modFiles.get(IModFile.Type.MOD));
@@ -42,6 +44,7 @@ public class ModValidator {
this.candidatePlugins.addAll(lst(modFiles.get(IModFile.Type.LIBRARY))); this.candidatePlugins.addAll(lst(modFiles.get(IModFile.Type.LIBRARY)));
this.discoveryErrorData = discoveryErrorData; this.discoveryErrorData = discoveryErrorData;
this.brokenFiles.addAll(brokenFiles.stream().map(IModFileInfo::getFile).toList()); this.brokenFiles.addAll(brokenFiles.stream().map(IModFileInfo::getFile).toList());
this.modFileLoadingExceptions = modFileLoadingExceptions;
} }
public ModValidator(Map<IModFile.Type, List<ModFile>> modFiles, List<IModFileInfo> brokenFiles, List<EarlyLoadingException.ExceptionData> discoveryErrorData) { public ModValidator(Map<IModFile.Type, List<ModFile>> modFiles, List<IModFileInfo> brokenFiles, List<EarlyLoadingException.ExceptionData> discoveryErrorData) {
@@ -49,9 +52,7 @@ public class ModValidator {
} }
private static List<ModFile> lst(List<ModFile> files) { private static List<ModFile> lst(List<ModFile> files) {
if (files == null) return new ArrayList<>(); return files == null ? new ArrayList<>() : new ArrayList<>(files);
if (files instanceof ArrayList) return files;
return new ArrayList<>(files);
} }
public void stage1Validation() { public void stage1Validation() {
@@ -59,7 +60,7 @@ public class ModValidator {
if (LOGGER.isDebugEnabled(LogMarkers.SCAN)) { if (LOGGER.isDebugEnabled(LogMarkers.SCAN)) {
LOGGER.debug(LogMarkers.SCAN, "Found {} mod files with {} mods", candidateMods.size(), candidateMods.stream().mapToInt(mf -> mf.getModInfos().size()).sum()); LOGGER.debug(LogMarkers.SCAN, "Found {} mod files with {} mods", candidateMods.size(), candidateMods.stream().mapToInt(mf -> mf.getModInfos().size()).sum());
} }
ImmediateWindowHandler.updateProgress("Found " + candidateMods.size() + " mod candidates"); ImmediateWindowHandler.updateProgress("Found "+candidateMods.size()+" mod candidates");
} }
@NotNull @NotNull
@@ -86,7 +87,7 @@ public class ModValidator {
// If any detectable error happens during the sorting process {missing deps, duplicates, // If any detectable error happens during the sorting process {missing deps, duplicates,
// This helps prevent coremods/mixins from screwing up us displaying the error screens that the sorting/validation is trying to display. // This helps prevent coremods/mixins from screwing up us displaying the error screens that the sorting/validation is trying to display.
// This won't fix them all as they are still loaded and will still apply but it might help // This won't fix them all as they are still loaded and will still apply but it might help
for (var info : LoadingModList.getModFiles()) for (var info : this.loadingModList.getModFiles())
mods.add(info.getFile().getSecureJar()); mods.add(info.getFile().getSecureJar());
// Add any game libraries, this *may* be duplicates, depending on the state of the sorting. But until I get around to re-writing // Add any game libraries, this *may* be duplicates, depending on the state of the sorting. But until I get around to re-writing
@@ -123,12 +124,12 @@ public class ModValidator {
var allErrors = new ArrayList<>(errors); var allErrors = new ArrayList<>(errors);
allErrors.addAll(this.discoveryErrorData); allErrors.addAll(this.discoveryErrorData);
ModSorter.sort(candidateMods, allErrors); loadingModList = ModSorter.sort(candidateMods, allErrors);
LoadingModList.getBrokenFiles().addAll(brokenFiles); loadingModList.addCoreMods();
var backgroundScanHandler = new BackgroundScanHandler(candidateMods); loadingModList.addAccessTransformers();
LoadingModList.getModFiles().stream() loadingModList.setBrokenFiles(brokenFiles);
.map(ModFileInfo::getFile) BackgroundScanHandler backgroundScanHandler = new BackgroundScanHandler(candidateMods);
.forEach(backgroundScanHandler::submitForScanning); loadingModList.addForScanning(backgroundScanHandler);
return backgroundScanHandler; return backgroundScanHandler;
} }
} }
@@ -56,7 +56,7 @@ public class StartupNotificationManager {
private synchronized static void addMessage(Message.MessageType type, String message, int maxSize) private synchronized static void addMessage(Message.MessageType type, String message, int maxSize)
{ {
EnumMap<Message.MessageType, List<Message>> newMessages = new EnumMap<>(messages); EnumMap<Message.MessageType, List<Message>> newMessages = new EnumMap<>(messages);
newMessages.compute(type, (_, existingList) -> { newMessages.compute(type, (key, existingList) -> {
List<Message> newList = new ArrayList<>(); List<Message> newList = new ArrayList<>();
if (existingList != null) if (existingList != null)
{ {
@@ -141,7 +141,7 @@ abstract class CommonDevLaunchHandler extends CommonLaunchHandler {
protected static Path getForgeOnly(Path forge) { protected static Path getForgeOnly(Path forge) {
var packages = getPackages(); // Pulled out so it is passed to the lambda as value var packages = getPackages(); // Pulled out so it is passed to the lambda as value
// We need to separate out our resources/code so that we can show up as a different data pack. // We need to separate out our resources/code so that we can show up as a different data pack.
var modJar = SecureJar.from((path, _) -> { var modJar = SecureJar.from((path, base) -> {
if (!path.endsWith(".class")) return true; if (!path.endsWith(".class")) return true;
for (var pkg : packages) for (var pkg : packages)
if (path.startsWith(pkg)) return true; if (path.startsWith(pkg)) return true;
@@ -156,6 +156,7 @@ abstract class CommonDevLaunchHandler extends CommonLaunchHandler {
return new String[] { return new String[] {
"net/minecraftforge/", "net/minecraftforge/",
"META-INF/services/", "META-INF/services/",
"META-INF/coremods.json",
"META-INF/mods.toml" "META-INF/mods.toml"
}; };
} }
@@ -112,7 +112,7 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
// We want just the class files from the root of the input paths. So make a new union with a filter. // We want just the class files from the root of the input paths. So make a new union with a filter.
var classes = UnionHelper.newFileSystem( var classes = UnionHelper.newFileSystem(
(name, _) -> { (name, base) -> {
if (name.endsWith("/")) { if (name.endsWith("/")) {
if (name.startsWith("/")) if (name.startsWith("/"))
name = name.substring(1); name = name.substring(1);
@@ -164,7 +164,7 @@ public final class ForgeDevLocator extends AbstractModProvider implements IModLo
if ("value".equals(key)) { if ("value".equals(key)) {
int idx = clsName.lastIndexOf('/'); int idx = clsName.lastIndexOf('/');
var pkg = clsName.substring(0, idx); var pkg = clsName.substring(0, idx);
mods.computeIfAbsent(pkg, _ -> new HashSet<>()).add((String)value); mods.computeIfAbsent(pkg, k -> new HashSet<>()).add((String)value);
idx = pkg.lastIndexOf('/'); idx = pkg.lastIndexOf('/');
while (idx != -1) { while (idx != -1) {
@@ -25,9 +25,7 @@ sealed abstract class ForgeProdLaunchHandler extends CommonLaunchHandler {
@Override @Override
public List<Path> getMinecraftPaths() { public List<Path> getMinecraftPaths() {
// We use a marker because 3rd party launcher don't build their class paths correctly return List.of(getPathFromResource("net/minecraft/client/Minecraft.class"));
// https://github.com/MinecraftForge/MinecraftForge/issues/10797
return List.of(getPathFromResource(".forge_patched_minecraft"));
} }
} }
@@ -1,4 +1,5 @@
net.minecraftforge.fml.loading.log4j.SLF4JFixerLaunchPluginService net.minecraftforge.fml.loading.log4j.SLF4JFixerLaunchPluginService
net.minecraftforge.fml.loading.RuntimeDistCleaner net.minecraftforge.fml.loading.RuntimeDistCleaner
net.minecraftforge.fml.common.asm.RuntimeEnumExtender net.minecraftforge.fml.common.asm.RuntimeEnumExtender
net.minecraftforge.fml.common.asm.ObjectHolderDefinalize
net.minecraftforge.fml.common.asm.CapabilityTokenSubclass net.minecraftforge.fml.common.asm.CapabilityTokenSubclass
@@ -1,35 +0,0 @@
{
"options": [
{
"resource": "com/llamalad7/mixinextras/platform/forge/MixinExtrasConfigPlugin.class",
"layer": "GAMELIBRARY",
"id": "mixinextras",
"deps": [
{
"identifier": {
"group": "com.github.LlamaLad7",
"artifact": "MixinExtras"
},
"version": {
"range": "[0.5.3,)",
"artifactVersion": "0.5.3"
},
"path": "",
"isObfuscated": false
}
],
"meta": {
"identifier": {
"group": "io.github.llamalad7",
"artifact": "mixinextras-forge"
},
"version": {
"artifactVersion": "0.5.3"
},
"path": "",
"isObfuscated": false
},
"nested": true
}
]
}
+1 -1
View File
@@ -19,7 +19,7 @@ dependencies {
implementation(libs.log4j.api) implementation(libs.log4j.api)
implementation(libs.gson) implementation(libs.gson)
implementation(libs.modlauncher) implementation(libs.modlauncher)
implementation(libs.coremods.api) implementation(libs.coremods) // Used for ASMAPI (for now)
testCompileOnly(libs.jetbrains.annotations) testCompileOnly(libs.jetbrains.annotations)
} }
@@ -8,27 +8,16 @@ package net.minecraftforge.forge.transformers;
import cpw.mods.modlauncher.api.ITransformer; import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerVotingContext; import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult; import cpw.mods.modlauncher.api.TransformerVoteResult;
import net.minecraftforge.coremod.api.ASMAPI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
record FieldToMethodTransformer(String className, Map<String, String> fields) implements ITransformer<ClassNode> { record FieldToMethodTransformer(String className, Map<String, String> fields) implements ITransformer<ClassNode> {
private static final Logger LOGGER = LogManager.getLogger();
// TODO [Forge][Transformer] Make this properly data driven or configurable. // TODO [Forge][Transformer] Make this properly data driven or configurable.
// It was hard-coded like this before when using JS CoreMods, though. // It was hard-coded like this before when using JS CoreMods, though.
static final Map<String, Map<String, String>> TARGETS = Map.of( static final Map<String, Map<String, String>> TARGETS = Map.of(
@@ -71,7 +60,7 @@ record FieldToMethodTransformer(String className, Map<String, String> fields) im
@Override @Override
public @NotNull ClassNode transform(ClassNode input, ITransformerVotingContext context) { public @NotNull ClassNode transform(ClassNode input, ITransformerVotingContext context) {
for (var entry : this.fields.entrySet()) { for (var entry : this.fields.entrySet()) {
redirectFieldToMethod(input, entry.getKey(), entry.getValue()); ASMAPI.redirectFieldToMethod(input, entry.getKey(), entry.getValue());
} }
return input; return input;
@@ -86,73 +75,4 @@ record FieldToMethodTransformer(String className, Map<String, String> fields) im
public @NotNull Set<Target> targets() { public @NotNull Set<Target> targets() {
return Set.of(Target.targetClass(this.className)); return Set.of(Target.targetClass(this.className));
} }
private static final @Nullable FieldNode findField(final ClassNode classNode, final String name) {
FieldNode ret = null;
for (var fieldNode : classNode.fields) {
if (name.equals(fieldNode.name)) {
if (ret != null)
throw new IllegalStateException("Found multiple fields with name " + name);
ret = fieldNode;
}
}
return ret;
}
private static final @Nullable MethodNode findMethod(final ClassNode classNode, final String name, final String desc) {
for (var methodNode : classNode.methods) {
if (name.equals(methodNode.name) && desc.equals(methodNode.desc))
return methodNode;
}
return null;
}
/**
* Rewrites accesses to a specific field in the given class to a method-call.
* <p>
* The field specified by fieldName must be private and non-static. The method-call the field-access is redirected
* to does not take any parameters and returns an object of the same type as the field. If no methodName is passed,
* any method matching the described signature will be used as callable method.
*
* @param classNode the class to rewrite the accesses in
* @param fieldName the field accesses should be redirected to
* @param methodName the name of the method to redirect accesses through
* @apiNote This method was written as a special use case for Forge. It is not recommended to use this method
* unless you know what you are doing.
*/
private static void redirectFieldToMethod(final ClassNode classNode, final String fieldName, final String methodName) {
var foundField = findField(classNode, fieldName);
if (foundField == null)
throw new IllegalStateException("No field with name " + fieldName + " found");
if (!Modifier.isPrivate(foundField.access) || Modifier.isStatic(foundField.access))
throw new IllegalStateException("Field " + classNode.name + '.' + fieldName + " is not private and an instance field");
var methodSignature = "()" + foundField.desc;
var foundMethod = findMethod(classNode, methodName, methodSignature);
if (foundMethod == null)
throw new IllegalStateException("Unable to find method " + methodName + methodSignature);
for (MethodNode methodNode : classNode.methods) {
// skip the found getter method
if (methodNode == foundMethod) continue;
// Why is this filtered? UI twas added in the beginning but would it matter?
if (methodSignature.equals(foundMethod)) {
LOGGER.debug("FieldToMethodTransformer " + classNode.name + " skipping " + methodNode.name + methodNode.hashCode());
continue;
}
for (var insn : methodNode.instructions) {
if (insn.getOpcode() != Opcodes.GETFIELD)
continue;
var fieldInsnNode = (FieldInsnNode)insn;
if (fieldName.equals(fieldInsnNode.name)) {
var replace = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classNode.name, foundMethod.name, foundMethod.desc, false);
methodNode.instructions.set(insn, replace);
}
}
}
}
} }
@@ -10,6 +10,7 @@ import cpw.mods.modlauncher.api.ITransformationService;
import cpw.mods.modlauncher.api.ITransformer; import cpw.mods.modlauncher.api.ITransformer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -10,15 +10,14 @@ import com.google.gson.annotations.SerializedName;
import cpw.mods.modlauncher.api.ITransformer; import cpw.mods.modlauncher.api.ITransformer;
import cpw.mods.modlauncher.api.ITransformerVotingContext; import cpw.mods.modlauncher.api.ITransformerVotingContext;
import cpw.mods.modlauncher.api.TransformerVoteResult; import cpw.mods.modlauncher.api.TransformerVoteResult;
import net.minecraftforge.coremod.api.ASMAPI;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;
@@ -37,16 +36,15 @@ record MethodRedirector() implements ITransformer<ClassNode> {
private static final Replacement[] REPLACEMENTS = { private static final Replacement[] REPLACEMENTS = {
new Replacement( new Replacement(
// finalizeSpawn redirection to ForgeEventFactory.onFinalizeSpawn // finalizeSpawn redirection to ForgeEventFactory.onFinalizeSpawn
Opcodes.INVOKEVIRTUAL, ASMAPI.MethodType.VIRTUAL,
"finalizeSpawn", "finalizeSpawn",
"(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;", "(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;",
GSON.fromJson(new InputStreamReader(sneak(() -> MethodRedirector.class.getModule().getResourceAsStream("coremods/finalize_spawn_targets.json"))), Target[].class), GSON.fromJson(new InputStreamReader(sneak(() -> MethodRedirector.class.getModule().getResourceAsStream("coremods/finalize_spawn_targets.json"))), Target[].class),
_ -> new MethodInsnNode( insn -> ASMAPI.buildMethodCall(
Opcodes.INVOKESTATIC, ASMAPI.MethodType.STATIC,
"net/minecraftforge/event/ForgeEventFactory", "net/minecraftforge/event/ForgeEventFactory",
"onFinalizeSpawn", "onFinalizeSpawn",
"(Lnet/minecraft/world/entity/Mob;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;", "(Lnet/minecraft/world/entity/Mob;Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
false
) )
) )
}; };
@@ -60,7 +58,7 @@ record MethodRedirector() implements ITransformer<ClassNode> {
} }
record Replacement( record Replacement(
int opcode, ASMAPI.MethodType type,
String name, String name,
String desc, String desc,
Target[] targets, Target[] targets,
@@ -96,7 +94,7 @@ record MethodRedirector() implements ITransformer<ClassNode> {
var splitPos = methodString.indexOf('('); var splitPos = methodString.indexOf('(');
var methodName = methodString.substring(0, splitPos); var methodName = methodString.substring(0, splitPos);
var methodDesc = methodString.substring(splitPos); var methodDesc = methodString.substring(splitPos);
var method = findMethodNode(clazz, methodName, methodDesc); var method = ASMAPI.findMethodNode(clazz, methodName, methodDesc);
if (method == null) { if (method == null) {
LOGGER.error("Failed to redirect method call for {}! Method {} not found in class {}! This is a Forge bug, and is likely due to a Minecraft update changing something.", replacement.name, methodString, clazz.name); LOGGER.error("Failed to redirect method call for {}! Method {} not found in class {}! This is a Forge bug, and is likely due to a Minecraft update changing something.", replacement.name, methodString, clazz.name);
@@ -109,7 +107,7 @@ record MethodRedirector() implements ITransformer<ClassNode> {
var methodInsn = (MethodInsnNode) insn; var methodInsn = (MethodInsnNode) insn;
var redirection = replacement.factory.apply(methodInsn); var redirection = replacement.factory.apply(methodInsn);
LOGGER.debug("Redirecting method call {}{} to {}{} inside of {}.{}", methodInsn.name, methodInsn.desc, redirection.name, redirection.desc, clazz.name, method.name); LOGGER.debug("Redirecting method call {}{} to {}{} inside of {}.{}", methodInsn.name, methodInsn.desc, redirection.name, redirection.desc, clazz.name, method.name);
method.instructions.set(insn, redirection); ASMAPI.insertInsn(method, methodInsn, redirection, ASMAPI.InsertMode.REMOVE_ORIGINAL);
} }
} }
} }
@@ -117,16 +115,8 @@ record MethodRedirector() implements ITransformer<ClassNode> {
return clazz; return clazz;
} }
private static @Nullable MethodNode findMethodNode(ClassNode clazz, String name, String desc) {
for (var method : clazz.methods) {
if (name.equals(method.name) && desc.equals(method.desc))
return method;
}
return null;
}
private static boolean shouldReplace(AbstractInsnNode insn, Replacement replacement) { private static boolean shouldReplace(AbstractInsnNode insn, Replacement replacement) {
return insn.getOpcode() == replacement.opcode return insn.getOpcode() == replacement.type.toOpcode()
&& replacement.name.equals(((MethodInsnNode) insn).name) && replacement.name.equals(((MethodInsnNode) insn).name)
&& replacement.desc.equals(((MethodInsnNode) insn).desc); && replacement.desc.equals(((MethodInsnNode) insn).desc);
} }
@@ -1,10 +1,4 @@
[ [
{
"class": "net/minecraft/gametest/framework/GameTestEntityBuilder",
"methods": [
"spawn()Lnet/minecraft/world/entity/Entity;"
]
},
{ {
"class": "net/minecraft/server/commands/RaidCommand", "class": "net/minecraft/server/commands/RaidCommand",
"methods": [ "methods": [
@@ -20,7 +14,7 @@
{ {
"class": "net/minecraft/world/entity/EntityType", "class": "net/minecraft/world/entity/EntityType",
"methods": [ "methods": [
"create(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/PostSpawnProcessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/EntitySpawnReason;ZZ)Lnet/minecraft/world/entity/Entity;" "create(Lnet/minecraft/server/level/ServerLevel;Ljava/util/function/Consumer;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/EntitySpawnReason;ZZ)Lnet/minecraft/world/entity/Entity;"
] ]
}, },
{ {
@@ -29,25 +23,31 @@
"trySpawn(Lnet/minecraft/server/level/ServerLevel;)V" "trySpawn(Lnet/minecraft/server/level/ServerLevel;)V"
] ]
}, },
{
"class": "net/minecraft/world/entity/animal/equine/SkeletonTrapGoal",
"methods": [
"createHorse(Lnet/minecraft/world/DifficultyInstance;)Lnet/minecraft/world/entity/animal/equine/AbstractHorse;",
"createSkeleton(Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/animal/equine/AbstractHorse;)Lnet/minecraft/world/entity/monster/skeleton/Skeleton;"
]
},
{
"class": "net/minecraft/world/entity/animal/equine/ZombieHorse",
"methods": [
"finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
]
},
{ {
"class": "net/minecraft/world/entity/animal/frog/Tadpole", "class": "net/minecraft/world/entity/animal/frog/Tadpole",
"methods": [ "methods": [
] ]
}, },
{
"class": "net/minecraft/world/entity/animal/horse/SkeletonTrapGoal",
"methods": [
"createHorse(Lnet/minecraft/world/DifficultyInstance;)Lnet/minecraft/world/entity/animal/horse/AbstractHorse;",
"createSkeleton(Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/animal/horse/AbstractHorse;)Lnet/minecraft/world/entity/monster/Skeleton;"
]
},
{
"class": "net/minecraft/world/entity/monster/Evoker$EvokerSummonSpellGoal",
"methods": [
"performSpellCasting()V"
]
},
{
"class": "net/minecraft/world/entity/monster/Spider",
"methods": [
"finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
]
},
{ {
"class": "net/minecraft/world/entity/monster/Strider", "class": "net/minecraft/world/entity/monster/Strider",
"methods": [ "methods": [
@@ -55,38 +55,14 @@
] ]
}, },
{ {
"class": "net/minecraft/world/entity/monster/illager/Evoker$EvokerSummonSpellGoal", "class": "net/minecraft/world/entity/monster/Zombie",
"methods": [
"performSpellCasting()V"
]
},
{
"class": "net/minecraft/world/entity/monster/spider/Spider",
"methods": [
"finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
]
},
{
"class": "net/minecraft/world/entity/monster/zombie/Drowned",
"methods": [
"finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
]
},
{
"class": "net/minecraft/world/entity/monster/zombie/Husk",
"methods": [
"finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
]
},
{
"class": "net/minecraft/world/entity/monster/zombie/Zombie",
"methods": [ "methods": [
"hurtServer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)Z", "hurtServer(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/damagesource/DamageSource;F)Z",
"finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;" "finalizeSpawn(Lnet/minecraft/world/level/ServerLevelAccessor;Lnet/minecraft/world/DifficultyInstance;Lnet/minecraft/world/entity/EntitySpawnReason;Lnet/minecraft/world/entity/SpawnGroupData;)Lnet/minecraft/world/entity/SpawnGroupData;"
] ]
}, },
{ {
"class": "net/minecraft/world/entity/monster/zombie/ZombieVillager", "class": "net/minecraft/world/entity/monster/ZombieVillager",
"methods": [ "methods": [
] ]
@@ -98,9 +74,9 @@
] ]
}, },
{ {
"class": "net/minecraft/world/entity/npc/villager/Villager", "class": "net/minecraft/world/entity/npc/Villager",
"methods": [ "methods": [
"getBreedOffspring(Lnet/minecraft/server/level/ServerLevel;Lnet/minecraft/world/entity/AgeableMob;)Lnet/minecraft/world/entity/npc/Villager;"
] ]
}, },
{ {
@@ -131,7 +107,7 @@
{ {
"class": "net/minecraft/world/level/levelgen/PhantomSpawner", "class": "net/minecraft/world/level/levelgen/PhantomSpawner",
"methods": [ "methods": [
"tick(Lnet/minecraft/server/level/ServerLevel;Z)V" "tick(Lnet/minecraft/server/level/ServerLevel;ZZ)V"
] ]
}, },
{ {
+5 -5
View File
@@ -4,12 +4,12 @@ org.gradle.jvmargs=-Xmx6G
org.gradle.daemon=false org.gradle.daemon=false
org.gradle.parallel=true org.gradle.parallel=true
JAVA_VERSION=25 JAVA_VERSION=21
MC_VERSION=26.2 MC_VERSION=1.21.8
MC_NEXT_VERSION=26.3 MC_NEXT_VERSION=1.22
MCP_VERSION=20260616.103818 MCP_VERSION=20250717.105350
MAPPING_CHANNEL=official MAPPING_CHANNEL=official
MAPPING_VERSION=26.2 MAPPING_VERSION=1.21.8
# Set to true before the first build of a new MC version, so we don't do compatibility checks # Set to true before the first build of a new MC version, so we don't do compatibility checks
CHECK_COMPATIBILITY=false CHECK_COMPATIBILITY=false
@@ -6,6 +6,7 @@
package net.minecraftforge.fml.javafmlmod; package net.minecraftforge.fml.javafmlmod;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.eventbus.api.bus.BusGroup; import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.CancellableEventBus; import net.minecraftforge.eventbus.api.bus.CancellableEventBus;
import net.minecraftforge.eventbus.api.bus.EventBus; import net.minecraftforge.eventbus.api.bus.EventBus;
@@ -47,10 +48,11 @@ import java.util.stream.Collectors;
* annotations and passes the class instances to the {@link Bus} * annotations and passes the class instances to the {@link Bus}
* defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS} * defined by the annotation. Defaults to {@code MinecraftForge#EVENT_BUS}
*/ */
public final class AutomaticEventSubscriber { public class AutomaticEventSubscriber {
private static final Logger LOGGER = LogManager.getLogger(); private static final Logger LOGGER = LogManager.getLogger();
private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class); private static final Type AUTO_SUBSCRIBER = Type.getType(EventBusSubscriber.class);
private static final Type MOD_TYPE = Type.getType(Mod.class); private static final Type MOD_TYPE = Type.getType(Mod.class);
private static final Type ONLY_IN_TYPE = Type.getType(OnlyIn.class);
private static final List<EnumData> DEFAULT_SIDES = List.of(new EnumData(null, "CLIENT"), new EnumData(null, "DEDICATED_SERVER")); private static final List<EnumData> DEFAULT_SIDES = List.of(new EnumData(null, "CLIENT"), new EnumData(null, "DEDICATED_SERVER"));
private static final EnumData DEFAULT_BUS = new EnumData(null, "BOTH"); private static final EnumData DEFAULT_BUS = new EnumData(null, "BOTH");
@@ -62,11 +64,20 @@ public final class AutomaticEventSubscriber {
.filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType())) .filter(data -> AUTO_SUBSCRIBER.equals(data.annotationType()))
.toList(); .toList();
var onlyIns = FMLEnvironment.production ? Collections.emptySet() : scanData.getAnnotations().stream()
.filter(data -> ONLY_IN_TYPE.equals(data.annotationType()))
.map(data -> data.clazz().getClassName())
.collect(Collectors.toSet());
var modids = scanData.getAnnotations().stream() var modids = scanData.getAnnotations().stream()
.filter(data -> MOD_TYPE.equals(data.annotationType())) .filter(data -> MOD_TYPE.equals(data.annotationType()))
.collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value"))); .collect(Collectors.toMap(a -> a.clazz().getClassName(), a -> (String)a.annotationData().get("value")));
for (var data : targets) { for (var data : targets) {
if (!FMLEnvironment.production && onlyIns.contains(data.clazz().getClassName())) {
throw new RuntimeException("Found @OnlyIn on @EventBusSubscriber class " + data.clazz().getClassName() + " - this is not allowed as it causes crashes. Remove the OnlyIn and set value=Dist.CLIENT in the EventBusSubscriber annotation instead");
}
var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId()); var modId = modids.getOrDefault(data.clazz().getClassName(), mod.getModId());
modId = value(data, "modid", modId); modId = value(data, "modid", modId);
@@ -81,7 +81,7 @@ public class FMLJavaModLanguageProvider implements IModLanguageProvider
.filter(ad -> ad.annotationType().equals(MODANNOTATION)) .filter(ad -> ad.annotationType().equals(MODANNOTATION))
.peek(ad -> LOGGER.debug(SCAN, "Found @Mod class {} with id {}", ad.clazz().getClassName(), ad.annotationData().get("value"))) .peek(ad -> LOGGER.debug(SCAN, "Found @Mod class {} with id {}", ad.clazz().getClassName(), ad.annotationData().get("value")))
.map(ad -> new FMLModTarget(ad.clazz().getClassName(), (String)ad.annotationData().get("value"))) .map(ad -> new FMLModTarget(ad.clazz().getClassName(), (String)ad.annotationData().get("value")))
.collect(Collectors.toMap(FMLModTarget::modId, Function.identity(), (a, _) -> a)); .collect(Collectors.toMap(FMLModTarget::modId, Function.identity(), (a,b)->a));
scanResult.addLanguageLoader(modTargetMap); scanResult.addLanguageLoader(modTargetMap);
}; };
} }
@@ -43,13 +43,12 @@ public class FMLModContainer extends ModContainer {
LOGGER.debug(LOADING,"Creating FMLModContainer instance for {}", className); LOGGER.debug(LOADING,"Creating FMLModContainer instance for {}", className);
this.scanResults = modFileScanResults; this.scanResults = modFileScanResults;
activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod); activityMap.put(ModLoadingStage.CONSTRUCT, this::constructMod);
this.eventBusGroup = BusGroup.create("modBusFor" + info.getModId(), IModBusEvent.class); this.eventBusGroup = BusGroup.create("modBusFor" + info.getModId());
this.contextExtension = () -> context; this.contextExtension = () -> context;
try { try {
var moduleName = info.getOwningFile().moduleName(); var moduleName = info.getOwningFile().moduleName();
var module = gameLayer.findModule(moduleName).orElse(null); var module = gameLayer.findModule(moduleName)
if (module == null) .orElseThrow(() -> new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer));
throw new IllegalStateException("Failed to find " + moduleName + " in " + gameLayer);
openModules(gameLayer, module, info.getOwningFile().getFile().getSecureJar()); openModules(gameLayer, module, info.getOwningFile().getFile().getSecureJar());
@@ -167,7 +166,6 @@ public class FMLModContainer extends ModContainer {
return modInstance; return modInstance;
} }
@Override
public BusGroup getModBusGroup() { public BusGroup getModBusGroup() {
return this.eventBusGroup; return this.eventBusGroup;
} }
@@ -74,7 +74,7 @@ public class LowCodeModLanguageProvider implements IModLanguageProvider
.flatMap(fi->fi.getMods().stream()) .flatMap(fi->fi.getMods().stream())
.map(IModInfo::getModId) .map(IModInfo::getModId)
.map(LowCodeModTarget::new) .map(LowCodeModTarget::new)
.collect(Collectors.toMap(LowCodeModTarget::modId, Function.identity(), (a, _)->a)); .collect(Collectors.toMap(LowCodeModTarget::modId, Function.identity(), (a, b)->a));
scanResult.addLanguageLoader(modTargetMap); scanResult.addLanguageLoader(modTargetMap);
}; };
} }
+5 -3
View File
@@ -6,19 +6,21 @@ plugins {
id 'java' id 'java'
id 'idea' id 'idea'
id 'eclipse' id 'eclipse'
id 'net.minecraftforge.gradle' version '[7.0.17,8)' id 'net.minecraftforge.gradle' version '[7.0.3,8)'
} }
version = '1.0.0' version = '1.0.0'
group = 'com.example.examplemod' group = 'com.example.examplemod'
// Mojang ships Java 25 to end users in 26.1+, so your mod should target Java 25. // Mojang ships Java 21 to end users in 1.20.5+, so your mod should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(25) java.toolchain.languageVersion = JavaLanguageVersion.of(21)
// Include generated resources // Include generated resources
sourceSets.main.resources { srcDir 'src/generated/resources' } sourceSets.main.resources { srcDir 'src/generated/resources' }
minecraft { minecraft {
mappings channel: 'official', version: '@MC_VERSION@'
runs { runs {
configureEach { configureEach {
workingDir = layout.projectDirectory.dir('run') workingDir = layout.projectDirectory.dir('run')
@@ -19,6 +19,12 @@ displayName="Example Mod"
authors="YourNameHere, OtherNameHere" #optional authors="YourNameHere, OtherNameHere" #optional
#displayTest="MATCH_VERSION" #optional, default=MATCH_VERSION when not clientSideOnly, else IGNORE_ALL_VERSION #displayTest="MATCH_VERSION" #optional, default=MATCH_VERSION when not clientSideOnly, else IGNORE_ALL_VERSION
# Access Transformers
# Optional, if not specified Forge will attempt to find the default META-INF/accesstransformer.cfg and silently continue if not found. May default to an empty list in a future MC.
# If you specify AT path strings in this list, Forge will attempt to load each of them and throw errors for any that aren't found.
# Specifying an empty list when your mod has no ATs is recommended to opt-out of the default for slightly better loading performance.
#accessTransformers = []
description='''Example mod description. description='''Example mod description.
Newline characters can be used like this, and rendered on the mods screen properly.''' Newline characters can be used like this, and rendered on the mods screen properly.'''
@@ -1,12 +1,12 @@
--- a/com/mojang/blaze3d/opengl/GlCommandEncoder.java --- a/com/mojang/blaze3d/opengl/GlCommandEncoder.java
+++ b/com/mojang/blaze3d/opengl/GlCommandEncoder.java +++ b/com/mojang/blaze3d/opengl/GlCommandEncoder.java
@@ -201,6 +_,9 @@ @@ -132,6 +_,9 @@
GlStateManager._colorMask(15); GlStateManager._colorMask(true, true, true, true);
GlStateManager._clear(16384); GlStateManager._clear(16384);
GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, 0, 0); GlStateManager._glFramebufferTexture2D(36160, 36064, 3553, 0, 0);
+ // Forge: if using stencil, clear it as well (3553 = GlConst.GL_TEXTURE_2D) + // Forge: if using stencil, clear it as well (3553 = GlConst.GL_TEXTURE_2D)
+ if (colorTexture.isStencilEnabled()) + if (p_394273_.isStencilEnabled())
+ GlStateManager._glFramebufferTexture2D(GlConst.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, GlConst.GL_TEXTURE_2D, 0, 0); + GlStateManager._glFramebufferTexture2D(GlConst.GL_FRAMEBUFFER, org.lwjgl.opengl.GL30.GL_STENCIL_ATTACHMENT, GlConst.GL_TEXTURE_2D, 0, 0);
GlStateManager._glBindFramebuffer(36160, 0); GlStateManager._glBindFramebuffer(36160, 0);
}
} }
@@ -1,35 +0,0 @@
--- a/com/mojang/blaze3d/opengl/GlConst.java
+++ b/com/mojang/blaze3d/opengl/GlConst.java
@@ -239,6 +_,10 @@
}
public static int toGlInternalId(final GpuFormat gpuFormat) {
+ return toGlInternalId(gpuFormat, false);
+ }
+ public static int toGlInternalId(final GpuFormat gpuFormat, final boolean stencil) {
+ if (stencil && gpuFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8;
return switch (gpuFormat) {
case R8_UNORM -> 33321;
case R8_SNORM -> 36756;
@@ -291,6 +_,10 @@
}
public static int toGlExternalId(final GpuFormat gpuFormat) {
+ return toGlExternalId(gpuFormat, false);
+ }
+ public static int toGlExternalId(final GpuFormat gpuFormat, final boolean stencil) {
+ if (stencil && gpuFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL;
return switch (gpuFormat) {
case R8_UNORM, R8_SNORM, R16_UNORM, R16_SNORM, R16_FLOAT, R32_FLOAT -> 6403;
case RG8_UNORM, RG8_SNORM, RG16_UNORM, RG16_SNORM, RG16_FLOAT, RG32_FLOAT -> 33319;
@@ -308,6 +_,10 @@
}
public static int toGlType(final GpuFormat gpuFormat) {
+ return toGlType(gpuFormat, false);
+ }
+ public static int toGlType(final GpuFormat gpuFormat, boolean stencil) {
+ if (stencil && gpuFormat.hasDepthAspect()) return org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
return switch (gpuFormat) {
case R8_UNORM, RG8_UNORM, RGB8_UNORM, RGBA8_UNORM, R8_UINT, RG8_UINT, RGBA8_UINT, S8_UINT, RGB8_UINT -> 5121;
case R8_SNORM, RG8_SNORM, RGB8_SNORM, RGBA8_SNORM, R8_SINT, RG8_SINT, RGBA8_SINT, RGB8_SINT -> 5120;
@@ -1,6 +1,6 @@
--- a/com/mojang/blaze3d/opengl/GlDebug.java --- a/com/mojang/blaze3d/opengl/GlDebug.java
+++ b/com/mojang/blaze3d/opengl/GlDebug.java +++ b/com/mojang/blaze3d/opengl/GlDebug.java
@@ -22,6 +_,14 @@ @@ -23,6 +_,14 @@
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public class GlDebug { public class GlDebug {
@@ -15,30 +15,20 @@
private static final Logger LOGGER = LogUtils.getLogger(); private static final Logger LOGGER = LogUtils.getLogger();
private static final int CIRCULAR_LOG_SIZE = 10; private static final int CIRCULAR_LOG_SIZE = 10;
private final Queue<GlDebug.LogEntry> MESSAGE_BUFFER = EvictingQueue.create(10); private final Queue<GlDebug.LogEntry> MESSAGE_BUFFER = EvictingQueue.create(10);
@@ -83,6 +_,8 @@ @@ -105,6 +_,8 @@
} }
LOGGER.info("OpenGL debug message: {}", entry); LOGGER.info("OpenGL debug message: {}", gldebug$logentry);
+ // TODO: [VEN] Trim the stack trace + // TODO: [VEN] Trim the stack trace
+ if (PRINT_STACKTRACE_ON_ERROR) LOGGER.info("Trace: ", new Throwable("GlDebug")); + if (PRINT_STACKTRACE_ON_ERROR) LOGGER.info("Trace: ", new Throwable("GlDebug"));
} }
public List<String> getLastOpenGlDebugMessages() { public List<String> getLastOpenGlDebugMessages() {
@@ -107,7 +_,7 @@ @@ -121,6 +_,7 @@
GlDebug debug = new GlDebug();
enabledExtensions.add("GL_KHR_debug");
GL33C.glEnable(37600);
- if (debugSynchronousGlLogs) {
+ if (debugSynchronousGlLogs | PRINT_STACKTRACE_ON_ERROR) {
GL33C.glEnable(33346);
}
@@ -121,7 +_,7 @@
} else if (caps.GL_ARB_debug_output && GlDevice.USE_GL_ARB_debug_output) {
GlDebug debug = new GlDebug();
enabledExtensions.add("GL_ARB_debug_output");
- if (debugSynchronousGlLogs) {
+ if (debugSynchronousGlLogs | PRINT_STACKTRACE_ON_ERROR) {
GL33C.glEnable(33346);
}
@Nullable
public static GlDebug enableDebugCallback(int p_394351_, boolean p_393026_, Set<String> p_393339_) {
+ p_393026_ |= PRINT_STACKTRACE_ON_ERROR;
if (p_394351_ <= 0) {
return null;
} else {
@@ -1,50 +1,74 @@
--- a/com/mojang/blaze3d/opengl/GlDevice.java --- a/com/mojang/blaze3d/opengl/GlDevice.java
+++ b/com/mojang/blaze3d/opengl/GlDevice.java +++ b/com/mojang/blaze3d/opengl/GlDevice.java
@@ -150,7 +_,12 @@ @@ -89,8 +_,15 @@
final int depthOrLayers, public GpuTexture createTexture(
final int mipLevels @Nullable Supplier<String> p_397830_, int p_394481_, TextureFormat p_394839_, int p_391831_, int p_395609_, int p_407582_, int p_408928_
) { ) {
- return this.createTexture(this.debugLabels.exists() && label != null ? label.get() : null, usage, format, width, height, depthOrLayers, mipLevels); + return createTexture(p_397830_, p_394481_, p_394839_, p_391831_, p_395609_, p_407582_, p_408928_, false);
+ return this.createTexture(label, usage, format, width, height, depthOrLayers, mipLevels, false);
+ } + }
+ +
+ @Override + @Override
+ public GpuTexture createTexture(final @Nullable Supplier<String> label, @GpuTexture.Usage final int usage, final GpuFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels, final boolean stencil) { + public GpuTexture createTexture(
+ return this.createTexture(this.debugLabels.exists() && label != null ? label.get() : null, usage, format, width, height, depthOrLayers, mipLevels, stencil); + @Nullable Supplier<String> p_397830_, int p_394481_, TextureFormat p_394839_, int p_391831_, int p_395609_, int p_407582_, int p_408928_, boolean stencil
+ ) {
return this.createTexture(
- this.debugLabels.exists() && p_397830_ != null ? p_397830_.get() : null, p_394481_, p_394839_, p_391831_, p_395609_, p_407582_, p_408928_
+ this.debugLabels.exists() && p_397830_ != null ? p_397830_.get() : null, p_394481_, p_394839_, p_391831_, p_395609_, p_407582_, p_408928_, stencil
);
} }
@Override @@ -98,6 +_,15 @@
@@ -163,6 +_,11 @@ public GpuTexture createTexture(
final int depthOrLayers, @Nullable String p_394142_, int p_395535_, TextureFormat p_394951_, int p_393944_, int p_392329_, int p_408015_, int p_406483_
final int mipLevels
) { ) {
+ return this.createTexture(label, usage, format, width, height, depthOrLayers, mipLevels, false); + return createTexture(p_394142_, p_395535_, p_394951_, p_393944_, p_392329_, p_408015_, p_406483_, false);
+ } + }
+ +
+ @Override + @Override
+ public GpuTexture createTexture(@Nullable String label, @GpuTexture.Usage final int usage, final GpuFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels, boolean stencil) { + public GpuTexture createTexture(
GlStateManager.clearGlErrors(); + @Nullable String p_394142_, int p_395535_, TextureFormat p_394951_, int p_393944_, int p_392329_, int p_408015_, int p_406483_, boolean stencil
int id = GlStateManager._genTexture(); + ) {
if (label == null) { + // Forge: stencil rendering is only for depth
@@ -186,9 +_,9 @@ + stencil &= p_394951_.hasDepthAspect();
GlStateManager._texParameter(target, 34892, 0); if (p_406483_ < 1) {
} throw new IllegalArgumentException("mipLevels must be at least 1");
} else if (p_408015_ < 1) {
- int glInternalID = GlConst.toGlInternalId(format); @@ -148,11 +_,14 @@
- int glExternalID = GlConst.toGlExternalId(format); GlStateManager._texImage2D(
- int glType = GlConst.toGlType(format); k,
+ int glInternalID = GlConst.toGlInternalId(format, stencil); l,
+ int glExternalID = GlConst.toGlExternalId(format, stencil); + stencil ? org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8 :
+ int glType = GlConst.toGlType(format, stencil); GlConst.toGlInternalId(p_394951_),
if (glInternalID != 0 && glExternalID != 0 && glType != 0) { p_393944_ >> l,
if (isCubemap) { p_392329_ >> l,
for (int cubeTarget : GlConst.CUBEMAP_TARGETS) { 0,
@@ -211,7 +_,7 @@ + stencil ? org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL :
throw new IllegalStateException("OpenGL error " + error); GlConst.toGlExternalId(p_394951_),
+ stencil ? org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV :
GlConst.toGlType(p_394951_),
null
);
@@ -163,11 +_,14 @@
GlStateManager._texImage2D(
j,
i1,
+ stencil ? org.lwjgl.opengl.GL30.GL_DEPTH32F_STENCIL8 :
GlConst.toGlInternalId(p_394951_),
p_393944_ >> i1,
p_392329_ >> i1,
0,
+ stencil ? org.lwjgl.opengl.GL30.GL_DEPTH_STENCIL :
GlConst.toGlExternalId(p_394951_),
+ stencil ? org.lwjgl.opengl.GL30.GL_FLOAT_32_UNSIGNED_INT_24_8_REV :
GlConst.toGlType(p_394951_),
null
);
@@ -180,7 +_,7 @@
} else if (j1 != 0) {
throw new IllegalStateException("OpenGL error " + j1);
} else {
- GlTexture gltexture = new GlTexture(p_395535_, p_394142_, p_394951_, p_393944_, p_392329_, p_408015_, p_406483_, i);
+ GlTexture gltexture = new GlTexture(p_395535_, p_394142_, p_394951_, p_393944_, p_392329_, p_408015_, p_406483_, i, stencil);
this.debugLabels.applyLabel(gltexture);
return gltexture;
} }
- GlTexture texture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, id, this.frameBufferCache);
+ GlTexture texture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, id, this.frameBufferCache, stencil);
this.debugLabels.applyLabel(texture);
return texture;
} else {
@@ -1,18 +1,18 @@
--- a/com/mojang/blaze3d/opengl/GlStateManager.java --- a/com/mojang/blaze3d/opengl/GlStateManager.java
+++ b/com/mojang/blaze3d/opengl/GlStateManager.java +++ b/com/mojang/blaze3d/opengl/GlStateManager.java
@@ -80,6 +_,11 @@ @@ -89,6 +_,11 @@
} }
} }
+ public static boolean _isBlendEnabled(int index) { + public static boolean _isBlendEnabled() {
+ RenderSystem.assertOnRenderThread(); + RenderSystem.assertOnRenderThread();
+ return BLEND[index].mode.enabled; + return BLEND.mode.enabled;
+ } + }
+ +
public static void _disableBlend(int index) { public static void _disableBlend() {
RenderSystem.assertOnRenderThread(); RenderSystem.assertOnRenderThread();
BLEND[index].mode.disable(); BLEND.mode.disable();
@@ -390,9 +_,17 @@ @@ -404,9 +_,17 @@
} }
} }
@@ -20,13 +20,13 @@
+ public static float lastBrightnessX = 0.0f; + public static float lastBrightnessX = 0.0f;
+ public static float lastBrightnessY = 0.0f; + public static float lastBrightnessY = 0.0f;
+ +
public static void _texParameter(final int target, final int name, final int value) { public static void _texParameter(int p_393876_, int p_397998_, int p_396741_) {
RenderSystem.assertOnRenderThread(); RenderSystem.assertOnRenderThread();
GL33C.glTexParameteri(target, name, value); GL11.glTexParameteri(p_393876_, p_397998_, p_396741_);
+ if (target == GL33C.GL_TEXTURE1) { + if (p_393876_ == GL13.GL_TEXTURE1) {
+ lastBrightnessX = name; + lastBrightnessX = p_397998_;
+ lastBrightnessY = value; + lastBrightnessY = p_396741_;
+ } + }
} }
public static int _getTexLevelParameter(final int target, final int level, final int name) { public static int _getTexLevelParameter(int p_393352_, int p_397204_, int p_396319_) {
@@ -1,30 +1,33 @@
--- a/com/mojang/blaze3d/opengl/GlTexture.java --- a/com/mojang/blaze3d/opengl/GlTexture.java
+++ b/com/mojang/blaze3d/opengl/GlTexture.java +++ b/com/mojang/blaze3d/opengl/GlTexture.java
@@ -27,9 +_,14 @@ @@ -19,8 +_,13 @@
final int id, private int views;
final FrameBufferCache frameBufferCache
) { protected GlTexture(int p_394590_, String p_393950_, TextureFormat p_392837_, int p_391379_, int p_391947_, int p_396659_, int p_408255_, int p_408889_) {
+ this(usage, label, format, width, height, depthOrLayers, mipLevels, id, frameBufferCache, false); + this(p_394590_, p_393950_, p_392837_, p_391379_, p_391947_, p_396659_, p_408255_, p_408889_, false);
+ } + }
+ +
+ protected GlTexture(@GpuTexture.Usage int usage, String label, GpuFormat format, int width, int height, int depthOrLayers, int mipLevels, int id, FrameBufferCache frameBufferCache, boolean stencil) { + protected GlTexture(int p_394590_, String p_393950_, TextureFormat p_392837_, int p_391379_, int p_391947_, int p_396659_, int p_408255_, int p_408889_, boolean stencil) {
super(usage, label, format, width, height, depthOrLayers, mipLevels); super(p_394590_, p_393950_, p_392837_, p_391379_, p_391947_, p_396659_, p_408255_);
this.id = id; this.id = p_408889_;
this.frameBufferCache = frameBufferCache;
+ this.stencilEnabled = stencil; + this.stencilEnabled = stencil;
} }
@Override @Override
@@ -84,5 +_,12 @@ @@ -93,6 +_,16 @@
if (this.closed && this.views == 0) { public void setTextureFilter(FilterMode p_394977_, FilterMode p_397175_, boolean p_393558_) {
this.destroyImmediately(); super.setTextureFilter(p_394977_, p_397175_, p_393558_);
} this.modesDirty = true;
+ } + }
+ +
+
+ /* FORGE START */
+
+ private final boolean stencilEnabled; + private final boolean stencilEnabled;
+ +
+ @Override + @Override
+ public boolean isStencilEnabled() { + public boolean isStencilEnabled() {
+ return this.stencilEnabled; + return this.stencilEnabled;
} }
}
@Override
@@ -1,17 +1,17 @@
--- a/com/mojang/blaze3d/pipeline/RenderTarget.java --- a/com/mojang/blaze3d/pipeline/RenderTarget.java
+++ b/com/mojang/blaze3d/pipeline/RenderTarget.java +++ b/com/mojang/blaze3d/pipeline/RenderTarget.java
@@ -83,7 +_,7 @@ @@ -92,7 +_,7 @@
this.width = width; this.width = p_83951_;
this.height = height; this.height = p_83952_;
if (this.useDepth) { if (this.useDepth) {
- this.depthTexture = device.createTexture(() -> this.label + " / Depth", 15, GpuFormat.D32_FLOAT, width, height, 1, 1); - this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, p_83951_, p_83952_, 1, 1);
+ this.depthTexture = device.createTexture(() -> this.label + " / Depth", 15, GpuFormat.D32_FLOAT, width, height, 1, 1, this.stencilEnabled); + this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, p_83951_, p_83952_, 1, 1, this.stencilEnabled);
this.depthTextureView = device.createTextureView(this.depthTexture); this.depthTextureView = gpudevice.createTextureView(this.depthTexture);
} this.depthTexture.setTextureFilter(FilterMode.NEAREST, false);
this.depthTexture.setAddressMode(AddressMode.CLAMP_TO_EDGE);
@@ -121,5 +_,26 @@ @@ -166,5 +_,26 @@
@Nullable
public @Nullable GpuTextureView getDepthTextureView() { public GpuTextureView getDepthTextureView() {
return this.depthTextureView; return this.depthTextureView;
+ } + }
+ +
@@ -25,7 +25,7 @@
+ public void enableStencil() { + public void enableStencil() {
+ if (stencilEnabled) return; + if (stencilEnabled) return;
+ stencilEnabled = true; + stencilEnabled = true;
+ this.resize(width, height); + this.resize(viewWidth, viewHeight);
+ } + }
+ +
+ /** + /**
Loaded 100 of 2138 files, more files were not shown because too many files have changed in this diff. Show more